Skip to main content

fuel_dispatch/
dispatch.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Capability-driven dispatch tables. Phase 7.5 A5.
3//!
4//! `CapabilityRegistry` collects [`BackendCapabilities`] from each
5//! registered backend; `TransferMatrix` encodes the cheapest path
6//! between every pair of registered devices.
7//!
8//! Together they let DAG construction (Phase B) answer two
9//! questions:
10//!
11//! 1. **Which backend should handle `(op, dtype)`?** — query
12//!    [`CapabilityRegistry::find_backends`] / [`crate::dispatch::CapabilityRegistry::find_backend_for`]
13//!    to get the set of registered backends that support the pair.
14//! 2. **How does data move between two devices?** — query
15//!    [`TransferMatrix::path`] for the chosen path; falls back to
16//!    `HostStaging` if no direct path exists.
17//!
18//! The registry is process-wide (typically initialized once at
19//! application startup via `OnceLock`) but exposed here as a value
20//! so tests and alternative dispatch policies can construct their
21//! own. The canonical process-wide instance lives below
22//! ([`global_registry`] / [`global_bindings`]).
23
24use std::collections::HashMap;
25use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
26use std::sync::{Arc, Mutex, OnceLock, RwLock};
27
28use fuel_ir::backend::{BackendCapabilities, SubstrateClass, TransferPath};
29use fuel_ir::dispatch::OpKind;
30use fuel_ir::probe::BackendId;
31use fuel_ir::{DType, DeviceLocation, Error, Layout, Result};
32
33#[cfg(feature = "cuda")]
34use crate::kernel::KernelCaps;
35use crate::kernel::{KernelBindingTable, MatmulM, OpParams};
36use fuel_memory::{BackendStorage, Storage};
37
38/// Collection of backend capabilities, queried during DAG
39/// construction to pick which backend handles each op.
40#[derive(Debug, Default)]
41pub struct CapabilityRegistry {
42    backends: Vec<BackendCapabilities>,
43}
44
45impl CapabilityRegistry {
46    /// Construct an empty registry. Add backends with `register`.
47    pub fn new() -> Self {
48        Self {
49            backends: Vec::new(),
50        }
51    }
52
53    /// Register a backend's capabilities. Order of registration is
54    /// preserved; lookup methods return registrations in their
55    /// original order so callers can encode preference (CPU
56    /// fallback last; GPU first).
57    pub fn register(&mut self, caps: BackendCapabilities) {
58        self.backends.push(caps);
59    }
60
61    /// All registered backends.
62    pub fn backends(&self) -> &[BackendCapabilities] {
63        &self.backends
64    }
65
66    /// Backends supporting `(op, dtype)`, in registration order.
67    pub fn find_backends(&self, op: OpKind, dtype: DType) -> Vec<&BackendCapabilities> {
68        self.backends
69            .iter()
70            .filter(|caps| caps.op_dtype_support.contains(&(op, dtype)))
71            .collect()
72    }
73
74    /// Pick the first registered backend that supports
75    /// `(op, dtype)`. Returns
76    /// [`Error::NoBackendForOp`](fuel_ir::Error::NoBackendForOp)
77    /// with diagnostic data if none does. Production-correct: never
78    /// panics, always surfaces the gap as a typed error.
79    ///
80    /// "First" follows the order of `register` calls. Convention:
81    /// register GPU before CPU so GPU wins ties; the universal CPU
82    /// fallback gets picked iff no GPU registered for `(op, dtype)`.
83    pub fn find_backend_for(&self, op: OpKind, dtype: DType) -> Result<&BackendCapabilities> {
84        for caps in &self.backends {
85            if caps.op_dtype_support.contains(&(op, dtype)) {
86                return Ok(caps);
87            }
88        }
89        // Capability-level lookups still operate on a single output
90        // dtype (binding-table multi-dtype keys are an execution-time
91        // concern). Wrap the single dtype in a 1-vec for the error so
92        // both error sites share one variant shape.
93        Err(Error::NoBackendForOp {
94            op,
95            dtypes: vec![dtype],
96            available_backends: self.backends.iter().map(|c| c.backend_id).collect(),
97            supported_combinations: self
98                .backends
99                .iter()
100                .flat_map(|c| {
101                    c.op_dtype_support
102                        .iter()
103                        .map(|&(o, d)| (c.backend_id, o, vec![d]))
104                })
105                .collect(),
106        }
107        .bt())
108    }
109
110    /// Build a [`TransferMatrix`] from the registered backends'
111    /// advertised transfer paths. Each backend contributes its
112    /// outbound paths; the matrix consolidates them into a
113    /// `(src, dst) -> TransferPath` lookup.
114    pub fn build_transfer_matrix(&self) -> TransferMatrix {
115        let mut entries = HashMap::new();
116        for caps in &self.backends {
117            for (dst, path) in &caps.transfer_paths {
118                entries.insert((caps.device_location, *dst), *path);
119            }
120        }
121        TransferMatrix { entries }
122    }
123}
124
125/// Lookup table mapping `(source_device, dest_device)` pairs to the
126/// cheapest available [`TransferPath`]. Built once at registration
127/// time from each backend's advertised outbound paths; consulted
128/// every time the DAG inserts an `Op::Move` / `Op::Copy`.
129#[derive(Debug, Default)]
130pub struct TransferMatrix {
131    entries: HashMap<(DeviceLocation, DeviceLocation), TransferPath>,
132}
133
134impl TransferMatrix {
135    /// Look up the registered path between two devices. Returns
136    /// `None` if no direct path was advertised; the caller can
137    /// fall back to host-staging via the universal `HostStaging`
138    /// path.
139    pub fn path(&self, src: DeviceLocation, dst: DeviceLocation) -> Option<TransferPath> {
140        if src == dst {
141            return Some(TransferPath::SameDevice);
142        }
143        self.entries.get(&(src, dst)).copied()
144    }
145
146    /// Same as [`Self::path`] but always returns a path: falls back to
147    /// `TransferPath::HostStaging` (the universal fallback) when no
148    /// direct advertised path exists. CPU is reachable from every
149    /// backend through host-staging, so this never returns an error
150    /// for practical use cases — though see
151    /// [`Error::UnsupportedTransfer`](fuel_ir::Error::UnsupportedTransfer)
152    /// for the case when a backend can't even host-stage.
153    pub fn path_or_staging(&self, src: DeviceLocation, dst: DeviceLocation) -> TransferPath {
154        self.path(src, dst).unwrap_or(TransferPath::HostStaging)
155    }
156
157    /// All entries in the matrix.
158    pub fn entries(
159        &self,
160    ) -> impl Iterator<Item = (&(DeviceLocation, DeviceLocation), &TransferPath)> {
161        self.entries.iter()
162    }
163}
164
165/// Resolve which backend should handle `(op, dtype)` given the
166/// registry of available backends. Returns the chosen `BackendId`
167/// or [`Error::NoBackendForOp`] with diagnostic data on miss.
168///
169/// The chosen backend is the first registered backend that
170/// supports `(op, dtype)`. Convention: register GPU before CPU so
171/// GPU wins ties; the universal CPU fallback is picked iff no GPU
172/// registered.
173///
174/// Phase 7.5 B3 — used by op-builder methods to populate
175/// `Graph::target_backends` at DAG construction time. After the
176/// full migration, every Node has a target_backend set this way.
177pub fn resolve_target_backend(
178    registry: &CapabilityRegistry,
179    op: OpKind,
180    dtype: DType,
181) -> Result<BackendId> {
182    registry
183        .find_backend_for(op, dtype)
184        .map(|caps| caps.backend_id)
185}
186
187/// Residency-aware variant of [`resolve_target_backend`]. Prefers
188/// backends that have at least one input already resident on their
189/// device, breaking ties only on the residency axis (within the
190/// "supports (op, dtype)" set). Falls back to registration order
191/// when no candidate has local input residency.
192///
193/// `input_locations` is the list of input tensors' current
194/// `DeviceLocation`s; pass an empty slice for ops that take no
195/// inputs (constants / factories).
196///
197/// Phase 7.5 B3 — used when the dispatcher should avoid transfers
198/// when possible. A simpler dispatch policy is to call
199/// [`resolve_target_backend`] directly and let Router auto-insert
200/// transfers; the residency-aware version saves transfers when
201/// the choice is otherwise free.
202pub fn resolve_target_backend_residency_aware(
203    registry: &CapabilityRegistry,
204    op: OpKind,
205    dtype: DType,
206    input_locations: &[DeviceLocation],
207) -> Result<BackendId> {
208    let candidates = registry.find_backends(op, dtype);
209    if candidates.is_empty() {
210        // Reuse find_backend_for to construct the canonical error.
211        return registry.find_backend_for(op, dtype).map(|c| c.backend_id);
212    }
213    // Pick a candidate whose device matches at least one input
214    // location.
215    for caps in &candidates {
216        if input_locations.contains(&caps.device_location) {
217            return Ok(caps.backend_id);
218        }
219    }
220    // No residency match — fall back to first candidate
221    // (registration order).
222    Ok(candidates[0].backend_id)
223}
224
225// =============================================================================
226// Phase 7.5 B5 — CPU dispatch wrappers + registration
227// =============================================================================
228
229/// Helper: extract `&CpuStorageBytes` from `&Storage`. Returns
230/// Err if the variant isn't `BackendStorage::Cpu`.
231pub fn cpu_input(s: &Storage) -> Result<&fuel_cpu_backend::CpuStorageBytes> {
232    match &s.inner {
233        BackendStorage::Cpu(c) => Ok(c),
234        #[allow(unreachable_patterns)]
235        _ => Err(Error::Msg("cpu kernel wrapper called with non-CPU input".to_string()).bt()),
236    }
237}
238
239/// Helper: extract `&mut CpuStorageBytes` from `&mut Storage`. `pub`
240/// (along with [`cpu_input`], [`read_storage`], [`write_storage`]) so
241/// external backend crates (fuel-mkl-cpu-backend, fuel-aocl-cpu-backend)
242/// can build their own binding-table wrappers without reimplementing
243/// the lock + dtype-match shape.
244pub fn cpu_output(s: &mut Storage) -> Result<&mut fuel_cpu_backend::CpuStorageBytes> {
245    match &mut s.inner {
246        BackendStorage::Cpu(c) => Ok(c),
247        #[allow(unreachable_patterns)]
248        _ => Err(Error::Msg("cpu kernel wrapper called with non-CPU output".to_string()).bt()),
249    }
250}
251
252/// Acquire a poisoned-lock-aware read guard. Lock poisoning is a
253/// programming bug (a previous writer panicked while holding the
254/// lock); production code surfaces it as a typed error rather than
255/// re-panicking through `unwrap`.
256pub fn read_storage(arc: &Arc<RwLock<Storage>>) -> Result<std::sync::RwLockReadGuard<'_, Storage>> {
257    arc.read()
258        .map_err(|_| Error::Msg("kernel wrapper: storage RwLock poisoned (read)".to_string()).bt())
259}
260
261pub fn write_storage(
262    arc: &Arc<RwLock<Storage>>,
263) -> Result<std::sync::RwLockWriteGuard<'_, Storage>> {
264    arc.write()
265        .map_err(|_| Error::Msg("kernel wrapper: storage RwLock poisoned (write)".to_string()).bt())
266}
267
268/// Build a `(2 inputs, 1 output)` CPU dispatch wrapper that calls a
269/// typed binary kernel. The expanded function matches the
270/// [`KernelRef`] signature and is suitable for direct registration
271/// in the binding table.
272macro_rules! cpu_binary_wrapper {
273    ($wrapper:ident, $kernel:path, $op_name:literal) => {
274        // pub(crate) so the FKC vertical-slice test (fkc::register) can name
275        // the real production wrapper and assert an imported binding IS it.
276        pub(crate) fn $wrapper(
277            inputs: &[Arc<RwLock<Storage>>],
278            outputs: &mut [Arc<RwLock<Storage>>],
279            _layouts: &[Layout],
280            _params: &OpParams,
281        ) -> Result<()> {
282            if inputs.len() != 2 {
283                return Err(Error::Msg(format!(
284                    "{} wrapper expects 2 inputs, got {}",
285                    $op_name,
286                    inputs.len(),
287                ))
288                .bt());
289            }
290            if outputs.len() != 1 {
291                return Err(Error::Msg(format!(
292                    "{} wrapper expects 1 output, got {}",
293                    $op_name,
294                    outputs.len(),
295                ))
296                .bt());
297            }
298            let lhs_guard = read_storage(&inputs[0])?;
299            let rhs_guard = read_storage(&inputs[1])?;
300            let mut out_guard = write_storage(&outputs[0])?;
301            let lhs_cpu = cpu_input(&lhs_guard)?;
302            let rhs_cpu = cpu_input(&rhs_guard)?;
303            let out_cpu = cpu_output(&mut out_guard)?;
304            $kernel(lhs_cpu, rhs_cpu, out_cpu)
305        }
306    };
307}
308
309/// Build a `(1 input, 1 output)` CPU dispatch wrapper that calls a
310/// typed unary kernel.
311macro_rules! cpu_unary_wrapper {
312    ($wrapper:ident, $kernel:path, $op_name:literal) => {
313        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the real
314        // production wrapper for the elementwise-unary contract's entry points.
315        pub(crate) fn $wrapper(
316            inputs: &[Arc<RwLock<Storage>>],
317            outputs: &mut [Arc<RwLock<Storage>>],
318            _layouts: &[Layout],
319            _params: &OpParams,
320        ) -> Result<()> {
321            if inputs.len() != 1 {
322                return Err(Error::Msg(format!(
323                    "{} wrapper expects 1 input, got {}",
324                    $op_name,
325                    inputs.len(),
326                ))
327                .bt());
328            }
329            if outputs.len() != 1 {
330                return Err(Error::Msg(format!(
331                    "{} wrapper expects 1 output, got {}",
332                    $op_name,
333                    outputs.len(),
334                ))
335                .bt());
336            }
337            let in_guard = read_storage(&inputs[0])?;
338            let mut out_guard = write_storage(&outputs[0])?;
339            let in_cpu = cpu_input(&in_guard)?;
340            let out_cpu = cpu_output(&mut out_guard)?;
341            $kernel(in_cpu, out_cpu)
342        }
343    };
344}
345
346cpu_binary_wrapper!(
347    add_elementwise_f32_cpu_wrapper,
348    fuel_cpu_backend::byte_kernels::add_f32,
349    "add_elementwise"
350);
351cpu_binary_wrapper!(
352    sub_elementwise_f32_cpu_wrapper,
353    fuel_cpu_backend::byte_kernels::sub_f32,
354    "sub_elementwise"
355);
356cpu_binary_wrapper!(
357    mul_elementwise_f32_cpu_wrapper,
358    fuel_cpu_backend::byte_kernels::mul_f32,
359    "mul_elementwise"
360);
361cpu_binary_wrapper!(
362    div_elementwise_f32_cpu_wrapper,
363    fuel_cpu_backend::byte_kernels::div_f32,
364    "div_elementwise"
365);
366
367cpu_unary_wrapper!(
368    relu_elementwise_f32_cpu_wrapper,
369    fuel_cpu_backend::byte_kernels::relu_f32,
370    "relu_elementwise"
371);
372cpu_unary_wrapper!(
373    neg_elementwise_f32_cpu_wrapper,
374    fuel_cpu_backend::byte_kernels::neg_f32,
375    "neg_elementwise"
376);
377cpu_unary_wrapper!(
378    sqr_elementwise_f32_cpu_wrapper,
379    fuel_cpu_backend::byte_kernels::sqr_f32,
380    "sqr_elementwise"
381);
382cpu_unary_wrapper!(
383    sqrt_elementwise_f32_cpu_wrapper,
384    fuel_cpu_backend::byte_kernels::sqrt_f32,
385    "sqrt_elementwise"
386);
387cpu_unary_wrapper!(
388    recip_elementwise_f32_cpu_wrapper,
389    fuel_cpu_backend::byte_kernels::recip_f32,
390    "recip_elementwise"
391);
392cpu_unary_wrapper!(
393    abs_elementwise_f32_cpu_wrapper,
394    fuel_cpu_backend::byte_kernels::abs_f32,
395    "abs_elementwise"
396);
397cpu_unary_wrapper!(
398    tanh_elementwise_f32_cpu_wrapper,
399    fuel_cpu_backend::byte_kernels::tanh_f32,
400    "tanh_elementwise"
401);
402cpu_unary_wrapper!(
403    exp_elementwise_f32_cpu_wrapper,
404    fuel_cpu_backend::byte_kernels::exp_f32,
405    "exp_elementwise"
406);
407cpu_unary_wrapper!(
408    log_elementwise_f32_cpu_wrapper,
409    fuel_cpu_backend::byte_kernels::log_f32,
410    "log_elementwise"
411);
412cpu_unary_wrapper!(
413    sin_elementwise_f32_cpu_wrapper,
414    fuel_cpu_backend::byte_kernels::sin_f32,
415    "sin_elementwise"
416);
417cpu_unary_wrapper!(
418    cos_elementwise_f32_cpu_wrapper,
419    fuel_cpu_backend::byte_kernels::cos_f32,
420    "cos_elementwise"
421);
422cpu_unary_wrapper!(
423    sigmoid_elementwise_f32_cpu_wrapper,
424    fuel_cpu_backend::byte_kernels::sigmoid_f32,
425    "sigmoid_elementwise"
426);
427cpu_unary_wrapper!(
428    silu_elementwise_f32_cpu_wrapper,
429    fuel_cpu_backend::byte_kernels::silu_f32,
430    "silu_elementwise"
431);
432cpu_unary_wrapper!(
433    gelu_elementwise_f32_cpu_wrapper,
434    fuel_cpu_backend::byte_kernels::gelu_f32,
435    "gelu_elementwise"
436);
437cpu_unary_wrapper!(
438    step_elementwise_f32_cpu_wrapper,
439    fuel_cpu_backend::byte_kernels::step_f32,
440    "step_elementwise"
441);
442
443// f64 elementwise wrappers — same wrapper macros, different
444// underlying kernels. The dispatch wrappers themselves are
445// dtype-agnostic (they just call the typed kernel); the
446// (op, dtype, backend) registration in `register_cpu_kernels`
447// is what selects the right one at lookup time.
448cpu_binary_wrapper!(
449    add_elementwise_f64_cpu_wrapper,
450    fuel_cpu_backend::byte_kernels::add_f64,
451    "add_elementwise"
452);
453cpu_binary_wrapper!(
454    sub_elementwise_f64_cpu_wrapper,
455    fuel_cpu_backend::byte_kernels::sub_f64,
456    "sub_elementwise"
457);
458cpu_binary_wrapper!(
459    mul_elementwise_f64_cpu_wrapper,
460    fuel_cpu_backend::byte_kernels::mul_f64,
461    "mul_elementwise"
462);
463cpu_binary_wrapper!(
464    div_elementwise_f64_cpu_wrapper,
465    fuel_cpu_backend::byte_kernels::div_f64,
466    "div_elementwise"
467);
468
469cpu_unary_wrapper!(
470    relu_elementwise_f64_cpu_wrapper,
471    fuel_cpu_backend::byte_kernels::relu_f64,
472    "relu_elementwise"
473);
474cpu_unary_wrapper!(
475    neg_elementwise_f64_cpu_wrapper,
476    fuel_cpu_backend::byte_kernels::neg_f64,
477    "neg_elementwise"
478);
479cpu_unary_wrapper!(
480    sqr_elementwise_f64_cpu_wrapper,
481    fuel_cpu_backend::byte_kernels::sqr_f64,
482    "sqr_elementwise"
483);
484cpu_unary_wrapper!(
485    sqrt_elementwise_f64_cpu_wrapper,
486    fuel_cpu_backend::byte_kernels::sqrt_f64,
487    "sqrt_elementwise"
488);
489cpu_unary_wrapper!(
490    recip_elementwise_f64_cpu_wrapper,
491    fuel_cpu_backend::byte_kernels::recip_f64,
492    "recip_elementwise"
493);
494cpu_unary_wrapper!(
495    abs_elementwise_f64_cpu_wrapper,
496    fuel_cpu_backend::byte_kernels::abs_f64,
497    "abs_elementwise"
498);
499cpu_unary_wrapper!(
500    tanh_elementwise_f64_cpu_wrapper,
501    fuel_cpu_backend::byte_kernels::tanh_f64,
502    "tanh_elementwise"
503);
504cpu_unary_wrapper!(
505    exp_elementwise_f64_cpu_wrapper,
506    fuel_cpu_backend::byte_kernels::exp_f64,
507    "exp_elementwise"
508);
509cpu_unary_wrapper!(
510    log_elementwise_f64_cpu_wrapper,
511    fuel_cpu_backend::byte_kernels::log_f64,
512    "log_elementwise"
513);
514cpu_unary_wrapper!(
515    sin_elementwise_f64_cpu_wrapper,
516    fuel_cpu_backend::byte_kernels::sin_f64,
517    "sin_elementwise"
518);
519cpu_unary_wrapper!(
520    cos_elementwise_f64_cpu_wrapper,
521    fuel_cpu_backend::byte_kernels::cos_f64,
522    "cos_elementwise"
523);
524cpu_unary_wrapper!(
525    sigmoid_elementwise_f64_cpu_wrapper,
526    fuel_cpu_backend::byte_kernels::sigmoid_f64,
527    "sigmoid_elementwise"
528);
529cpu_unary_wrapper!(
530    silu_elementwise_f64_cpu_wrapper,
531    fuel_cpu_backend::byte_kernels::silu_f64,
532    "silu_elementwise"
533);
534cpu_unary_wrapper!(
535    gelu_elementwise_f64_cpu_wrapper,
536    fuel_cpu_backend::byte_kernels::gelu_f64,
537    "gelu_elementwise"
538);
539cpu_unary_wrapper!(
540    step_elementwise_f64_cpu_wrapper,
541    fuel_cpu_backend::byte_kernels::step_f64,
542    "step_elementwise"
543);
544
545cpu_binary_wrapper!(
546    maximum_elementwise_f32_cpu_wrapper,
547    fuel_cpu_backend::byte_kernels::maximum_f32,
548    "maximum_elementwise"
549);
550cpu_binary_wrapper!(
551    minimum_elementwise_f32_cpu_wrapper,
552    fuel_cpu_backend::byte_kernels::minimum_f32,
553    "minimum_elementwise"
554);
555cpu_binary_wrapper!(
556    maximum_elementwise_f64_cpu_wrapper,
557    fuel_cpu_backend::byte_kernels::maximum_f64,
558    "maximum_elementwise"
559);
560cpu_binary_wrapper!(
561    minimum_elementwise_f64_cpu_wrapper,
562    fuel_cpu_backend::byte_kernels::minimum_f64,
563    "minimum_elementwise"
564);
565
566// bf16 elementwise wrappers (via-f32 round-trip kernels).
567cpu_binary_wrapper!(
568    add_elementwise_bf16_cpu_wrapper,
569    fuel_cpu_backend::byte_kernels::add_bf16,
570    "add_elementwise"
571);
572cpu_binary_wrapper!(
573    sub_elementwise_bf16_cpu_wrapper,
574    fuel_cpu_backend::byte_kernels::sub_bf16,
575    "sub_elementwise"
576);
577cpu_binary_wrapper!(
578    mul_elementwise_bf16_cpu_wrapper,
579    fuel_cpu_backend::byte_kernels::mul_bf16,
580    "mul_elementwise"
581);
582cpu_binary_wrapper!(
583    div_elementwise_bf16_cpu_wrapper,
584    fuel_cpu_backend::byte_kernels::div_bf16,
585    "div_elementwise"
586);
587cpu_binary_wrapper!(
588    maximum_elementwise_bf16_cpu_wrapper,
589    fuel_cpu_backend::byte_kernels::maximum_bf16,
590    "maximum_elementwise"
591);
592cpu_binary_wrapper!(
593    minimum_elementwise_bf16_cpu_wrapper,
594    fuel_cpu_backend::byte_kernels::minimum_bf16,
595    "minimum_elementwise"
596);
597
598cpu_unary_wrapper!(
599    relu_elementwise_bf16_cpu_wrapper,
600    fuel_cpu_backend::byte_kernels::relu_bf16,
601    "relu_elementwise"
602);
603cpu_unary_wrapper!(
604    neg_elementwise_bf16_cpu_wrapper,
605    fuel_cpu_backend::byte_kernels::neg_bf16,
606    "neg_elementwise"
607);
608cpu_unary_wrapper!(
609    sqr_elementwise_bf16_cpu_wrapper,
610    fuel_cpu_backend::byte_kernels::sqr_bf16,
611    "sqr_elementwise"
612);
613cpu_unary_wrapper!(
614    sqrt_elementwise_bf16_cpu_wrapper,
615    fuel_cpu_backend::byte_kernels::sqrt_bf16,
616    "sqrt_elementwise"
617);
618cpu_unary_wrapper!(
619    recip_elementwise_bf16_cpu_wrapper,
620    fuel_cpu_backend::byte_kernels::recip_bf16,
621    "recip_elementwise"
622);
623cpu_unary_wrapper!(
624    abs_elementwise_bf16_cpu_wrapper,
625    fuel_cpu_backend::byte_kernels::abs_bf16,
626    "abs_elementwise"
627);
628cpu_unary_wrapper!(
629    tanh_elementwise_bf16_cpu_wrapper,
630    fuel_cpu_backend::byte_kernels::tanh_bf16,
631    "tanh_elementwise"
632);
633cpu_unary_wrapper!(
634    exp_elementwise_bf16_cpu_wrapper,
635    fuel_cpu_backend::byte_kernels::exp_bf16,
636    "exp_elementwise"
637);
638cpu_unary_wrapper!(
639    log_elementwise_bf16_cpu_wrapper,
640    fuel_cpu_backend::byte_kernels::log_bf16,
641    "log_elementwise"
642);
643cpu_unary_wrapper!(
644    sin_elementwise_bf16_cpu_wrapper,
645    fuel_cpu_backend::byte_kernels::sin_bf16,
646    "sin_elementwise"
647);
648cpu_unary_wrapper!(
649    cos_elementwise_bf16_cpu_wrapper,
650    fuel_cpu_backend::byte_kernels::cos_bf16,
651    "cos_elementwise"
652);
653cpu_unary_wrapper!(
654    sigmoid_elementwise_bf16_cpu_wrapper,
655    fuel_cpu_backend::byte_kernels::sigmoid_bf16,
656    "sigmoid_elementwise"
657);
658cpu_unary_wrapper!(
659    silu_elementwise_bf16_cpu_wrapper,
660    fuel_cpu_backend::byte_kernels::silu_bf16,
661    "silu_elementwise"
662);
663cpu_unary_wrapper!(
664    gelu_elementwise_bf16_cpu_wrapper,
665    fuel_cpu_backend::byte_kernels::gelu_bf16,
666    "gelu_elementwise"
667);
668cpu_unary_wrapper!(
669    step_elementwise_bf16_cpu_wrapper,
670    fuel_cpu_backend::byte_kernels::step_bf16,
671    "step_elementwise"
672);
673
674// f16 elementwise wrappers — direct mirrors of bf16.
675cpu_binary_wrapper!(
676    add_elementwise_f16_cpu_wrapper,
677    fuel_cpu_backend::byte_kernels::add_f16,
678    "add_elementwise"
679);
680cpu_binary_wrapper!(
681    sub_elementwise_f16_cpu_wrapper,
682    fuel_cpu_backend::byte_kernels::sub_f16,
683    "sub_elementwise"
684);
685cpu_binary_wrapper!(
686    mul_elementwise_f16_cpu_wrapper,
687    fuel_cpu_backend::byte_kernels::mul_f16,
688    "mul_elementwise"
689);
690cpu_binary_wrapper!(
691    div_elementwise_f16_cpu_wrapper,
692    fuel_cpu_backend::byte_kernels::div_f16,
693    "div_elementwise"
694);
695cpu_binary_wrapper!(
696    maximum_elementwise_f16_cpu_wrapper,
697    fuel_cpu_backend::byte_kernels::maximum_f16,
698    "maximum_elementwise"
699);
700cpu_binary_wrapper!(
701    minimum_elementwise_f16_cpu_wrapper,
702    fuel_cpu_backend::byte_kernels::minimum_f16,
703    "minimum_elementwise"
704);
705
706cpu_unary_wrapper!(
707    relu_elementwise_f16_cpu_wrapper,
708    fuel_cpu_backend::byte_kernels::relu_f16,
709    "relu_elementwise"
710);
711cpu_unary_wrapper!(
712    neg_elementwise_f16_cpu_wrapper,
713    fuel_cpu_backend::byte_kernels::neg_f16,
714    "neg_elementwise"
715);
716cpu_unary_wrapper!(
717    sqr_elementwise_f16_cpu_wrapper,
718    fuel_cpu_backend::byte_kernels::sqr_f16,
719    "sqr_elementwise"
720);
721cpu_unary_wrapper!(
722    sqrt_elementwise_f16_cpu_wrapper,
723    fuel_cpu_backend::byte_kernels::sqrt_f16,
724    "sqrt_elementwise"
725);
726cpu_unary_wrapper!(
727    recip_elementwise_f16_cpu_wrapper,
728    fuel_cpu_backend::byte_kernels::recip_f16,
729    "recip_elementwise"
730);
731cpu_unary_wrapper!(
732    abs_elementwise_f16_cpu_wrapper,
733    fuel_cpu_backend::byte_kernels::abs_f16,
734    "abs_elementwise"
735);
736cpu_unary_wrapper!(
737    tanh_elementwise_f16_cpu_wrapper,
738    fuel_cpu_backend::byte_kernels::tanh_f16,
739    "tanh_elementwise"
740);
741cpu_unary_wrapper!(
742    exp_elementwise_f16_cpu_wrapper,
743    fuel_cpu_backend::byte_kernels::exp_f16,
744    "exp_elementwise"
745);
746cpu_unary_wrapper!(
747    log_elementwise_f16_cpu_wrapper,
748    fuel_cpu_backend::byte_kernels::log_f16,
749    "log_elementwise"
750);
751cpu_unary_wrapper!(
752    sin_elementwise_f16_cpu_wrapper,
753    fuel_cpu_backend::byte_kernels::sin_f16,
754    "sin_elementwise"
755);
756cpu_unary_wrapper!(
757    cos_elementwise_f16_cpu_wrapper,
758    fuel_cpu_backend::byte_kernels::cos_f16,
759    "cos_elementwise"
760);
761cpu_unary_wrapper!(
762    sigmoid_elementwise_f16_cpu_wrapper,
763    fuel_cpu_backend::byte_kernels::sigmoid_f16,
764    "sigmoid_elementwise"
765);
766cpu_unary_wrapper!(
767    silu_elementwise_f16_cpu_wrapper,
768    fuel_cpu_backend::byte_kernels::silu_f16,
769    "silu_elementwise"
770);
771cpu_unary_wrapper!(
772    gelu_elementwise_f16_cpu_wrapper,
773    fuel_cpu_backend::byte_kernels::gelu_f16,
774    "gelu_elementwise"
775);
776cpu_unary_wrapper!(
777    step_elementwise_f16_cpu_wrapper,
778    fuel_cpu_backend::byte_kernels::step_f16,
779    "step_elementwise"
780);
781
782// Comparison family — typed input, U8 output. The wrapper signature
783// is identical to a regular binary wrapper (3 byte buffers); only the
784// kernel internally casts inputs to `&[T]` and output to `&mut [u8]`.
785// Binding-table key is `[T, T, U8]` so the executor allocates a U8-
786// sized output buffer (1 byte per element) instead of T-sized.
787cpu_binary_wrapper!(
788    eq_elementwise_f32_cpu_wrapper,
789    fuel_cpu_backend::byte_kernels::eq_f32_u8,
790    "eq_elementwise"
791);
792cpu_binary_wrapper!(
793    eq_elementwise_f64_cpu_wrapper,
794    fuel_cpu_backend::byte_kernels::eq_f64_u8,
795    "eq_elementwise"
796);
797cpu_binary_wrapper!(
798    eq_elementwise_bf16_cpu_wrapper,
799    fuel_cpu_backend::byte_kernels::eq_bf16_u8,
800    "eq_elementwise"
801);
802cpu_binary_wrapper!(
803    eq_elementwise_f16_cpu_wrapper,
804    fuel_cpu_backend::byte_kernels::eq_f16_u8,
805    "eq_elementwise"
806);
807
808cpu_binary_wrapper!(
809    ne_elementwise_f32_cpu_wrapper,
810    fuel_cpu_backend::byte_kernels::ne_f32_u8,
811    "ne_elementwise"
812);
813cpu_binary_wrapper!(
814    ne_elementwise_f64_cpu_wrapper,
815    fuel_cpu_backend::byte_kernels::ne_f64_u8,
816    "ne_elementwise"
817);
818cpu_binary_wrapper!(
819    ne_elementwise_bf16_cpu_wrapper,
820    fuel_cpu_backend::byte_kernels::ne_bf16_u8,
821    "ne_elementwise"
822);
823cpu_binary_wrapper!(
824    ne_elementwise_f16_cpu_wrapper,
825    fuel_cpu_backend::byte_kernels::ne_f16_u8,
826    "ne_elementwise"
827);
828
829cpu_binary_wrapper!(
830    lt_elementwise_f32_cpu_wrapper,
831    fuel_cpu_backend::byte_kernels::lt_f32_u8,
832    "lt_elementwise"
833);
834cpu_binary_wrapper!(
835    lt_elementwise_f64_cpu_wrapper,
836    fuel_cpu_backend::byte_kernels::lt_f64_u8,
837    "lt_elementwise"
838);
839cpu_binary_wrapper!(
840    lt_elementwise_bf16_cpu_wrapper,
841    fuel_cpu_backend::byte_kernels::lt_bf16_u8,
842    "lt_elementwise"
843);
844cpu_binary_wrapper!(
845    lt_elementwise_f16_cpu_wrapper,
846    fuel_cpu_backend::byte_kernels::lt_f16_u8,
847    "lt_elementwise"
848);
849
850cpu_binary_wrapper!(
851    le_elementwise_f32_cpu_wrapper,
852    fuel_cpu_backend::byte_kernels::le_f32_u8,
853    "le_elementwise"
854);
855cpu_binary_wrapper!(
856    le_elementwise_f64_cpu_wrapper,
857    fuel_cpu_backend::byte_kernels::le_f64_u8,
858    "le_elementwise"
859);
860cpu_binary_wrapper!(
861    le_elementwise_bf16_cpu_wrapper,
862    fuel_cpu_backend::byte_kernels::le_bf16_u8,
863    "le_elementwise"
864);
865cpu_binary_wrapper!(
866    le_elementwise_f16_cpu_wrapper,
867    fuel_cpu_backend::byte_kernels::le_f16_u8,
868    "le_elementwise"
869);
870
871cpu_binary_wrapper!(
872    gt_elementwise_f32_cpu_wrapper,
873    fuel_cpu_backend::byte_kernels::gt_f32_u8,
874    "gt_elementwise"
875);
876cpu_binary_wrapper!(
877    gt_elementwise_f64_cpu_wrapper,
878    fuel_cpu_backend::byte_kernels::gt_f64_u8,
879    "gt_elementwise"
880);
881cpu_binary_wrapper!(
882    gt_elementwise_bf16_cpu_wrapper,
883    fuel_cpu_backend::byte_kernels::gt_bf16_u8,
884    "gt_elementwise"
885);
886cpu_binary_wrapper!(
887    gt_elementwise_f16_cpu_wrapper,
888    fuel_cpu_backend::byte_kernels::gt_f16_u8,
889    "gt_elementwise"
890);
891
892cpu_binary_wrapper!(
893    ge_elementwise_f32_cpu_wrapper,
894    fuel_cpu_backend::byte_kernels::ge_f32_u8,
895    "ge_elementwise"
896);
897cpu_binary_wrapper!(
898    ge_elementwise_f64_cpu_wrapper,
899    fuel_cpu_backend::byte_kernels::ge_f64_u8,
900    "ge_elementwise"
901);
902cpu_binary_wrapper!(
903    ge_elementwise_bf16_cpu_wrapper,
904    fuel_cpu_backend::byte_kernels::ge_bf16_u8,
905    "ge_elementwise"
906);
907cpu_binary_wrapper!(
908    ge_elementwise_f16_cpu_wrapper,
909    fuel_cpu_backend::byte_kernels::ge_f16_u8,
910    "ge_elementwise"
911);
912
913/// Build a `(3 inputs, 1 output)` CPU dispatch wrapper for the
914/// ternary [`Op::Where`] family. Inputs are `(cond, a, b)` byte
915/// buffers; output is the typed `T` result. The wrapper signature
916/// matches [`KernelRef`]; the kernel itself does the typed casts
917/// internally.
918macro_rules! cpu_where_wrapper {
919    ($wrapper:ident, $kernel:path, $op_name:literal) => {
920        // pub(crate) so the FKC link table (fkc::cpu_link) can name the real
921        // production wrapper as `crate::dispatch::where_<dt>_cpu_wrapper`.
922        pub(crate) fn $wrapper(
923            inputs: &[Arc<RwLock<Storage>>],
924            outputs: &mut [Arc<RwLock<Storage>>],
925            _layouts: &[Layout],
926            _params: &OpParams,
927        ) -> Result<()> {
928            if inputs.len() != 3 {
929                return Err(Error::Msg(format!(
930                    "{} wrapper expects 3 inputs (cond, a, b), got {}",
931                    $op_name,
932                    inputs.len(),
933                ))
934                .bt());
935            }
936            if outputs.len() != 1 {
937                return Err(Error::Msg(format!(
938                    "{} wrapper expects 1 output, got {}",
939                    $op_name,
940                    outputs.len(),
941                ))
942                .bt());
943            }
944            let cond_guard = read_storage(&inputs[0])?;
945            // GAP-168(c): the cond mask is Bool. This is the RUNTIME arm of the
946            // same rule the graph builder and the Tensor wrapper enforce —
947            // three layers, and each had to be flipped separately. Bool and U8
948            // are byte-identical, so this check is the only thing keeping a U8
949            // buffer from being consumed here as if it were a mask.
950            if cond_guard.dtype != DType::Bool {
951                return Err(Error::Msg(format!(
952                    "{}: cond must be Bool, got {:?} (GAP-168(c))",
953                    $op_name, cond_guard.dtype,
954                ))
955                .bt());
956            }
957            let a_guard = read_storage(&inputs[1])?;
958            let b_guard = read_storage(&inputs[2])?;
959            let mut out_guard = write_storage(&outputs[0])?;
960            let cond_cpu = cpu_input(&cond_guard)?;
961            let a_cpu = cpu_input(&a_guard)?;
962            let b_cpu = cpu_input(&b_guard)?;
963            let out_cpu = cpu_output(&mut out_guard)?;
964            $kernel(cond_cpu, a_cpu, b_cpu, out_cpu)
965        }
966    };
967}
968
969cpu_where_wrapper!(
970    where_f32_cpu_wrapper,
971    fuel_cpu_backend::byte_kernels::where_f32,
972    "where"
973);
974cpu_where_wrapper!(
975    where_f64_cpu_wrapper,
976    fuel_cpu_backend::byte_kernels::where_f64,
977    "where"
978);
979cpu_where_wrapper!(
980    where_bf16_cpu_wrapper,
981    fuel_cpu_backend::byte_kernels::where_bf16,
982    "where"
983);
984cpu_where_wrapper!(
985    where_f16_cpu_wrapper,
986    fuel_cpu_backend::byte_kernels::where_f16,
987    "where"
988);
989
990// Rounding family (Floor / Ceil / Round) — same-dtype unary; standard
991// `cpu_unary_wrapper!`.
992cpu_unary_wrapper!(
993    floor_elementwise_f32_cpu_wrapper,
994    fuel_cpu_backend::byte_kernels::floor_f32,
995    "floor_elementwise"
996);
997cpu_unary_wrapper!(
998    floor_elementwise_f64_cpu_wrapper,
999    fuel_cpu_backend::byte_kernels::floor_f64,
1000    "floor_elementwise"
1001);
1002cpu_unary_wrapper!(
1003    floor_elementwise_bf16_cpu_wrapper,
1004    fuel_cpu_backend::byte_kernels::floor_bf16,
1005    "floor_elementwise"
1006);
1007cpu_unary_wrapper!(
1008    floor_elementwise_f16_cpu_wrapper,
1009    fuel_cpu_backend::byte_kernels::floor_f16,
1010    "floor_elementwise"
1011);
1012
1013cpu_unary_wrapper!(
1014    ceil_elementwise_f32_cpu_wrapper,
1015    fuel_cpu_backend::byte_kernels::ceil_f32,
1016    "ceil_elementwise"
1017);
1018cpu_unary_wrapper!(
1019    ceil_elementwise_f64_cpu_wrapper,
1020    fuel_cpu_backend::byte_kernels::ceil_f64,
1021    "ceil_elementwise"
1022);
1023cpu_unary_wrapper!(
1024    ceil_elementwise_bf16_cpu_wrapper,
1025    fuel_cpu_backend::byte_kernels::ceil_bf16,
1026    "ceil_elementwise"
1027);
1028cpu_unary_wrapper!(
1029    ceil_elementwise_f16_cpu_wrapper,
1030    fuel_cpu_backend::byte_kernels::ceil_f16,
1031    "ceil_elementwise"
1032);
1033
1034cpu_unary_wrapper!(
1035    round_elementwise_f32_cpu_wrapper,
1036    fuel_cpu_backend::byte_kernels::round_f32,
1037    "round_elementwise"
1038);
1039cpu_unary_wrapper!(
1040    round_elementwise_f64_cpu_wrapper,
1041    fuel_cpu_backend::byte_kernels::round_f64,
1042    "round_elementwise"
1043);
1044cpu_unary_wrapper!(
1045    round_elementwise_bf16_cpu_wrapper,
1046    fuel_cpu_backend::byte_kernels::round_bf16,
1047    "round_elementwise"
1048);
1049cpu_unary_wrapper!(
1050    round_elementwise_f16_cpu_wrapper,
1051    fuel_cpu_backend::byte_kernels::round_f16,
1052    "round_elementwise"
1053);
1054
1055cpu_unary_wrapper!(
1056    sign_elementwise_f32_cpu_wrapper,
1057    fuel_cpu_backend::byte_kernels::sign_f32,
1058    "sign_elementwise"
1059);
1060cpu_unary_wrapper!(
1061    sign_elementwise_f64_cpu_wrapper,
1062    fuel_cpu_backend::byte_kernels::sign_f64,
1063    "sign_elementwise"
1064);
1065cpu_unary_wrapper!(
1066    sign_elementwise_bf16_cpu_wrapper,
1067    fuel_cpu_backend::byte_kernels::sign_bf16,
1068    "sign_elementwise"
1069);
1070cpu_unary_wrapper!(
1071    sign_elementwise_f16_cpu_wrapper,
1072    fuel_cpu_backend::byte_kernels::sign_f16,
1073    "sign_elementwise"
1074);
1075
1076cpu_unary_wrapper!(
1077    erf_elementwise_f32_cpu_wrapper,
1078    fuel_cpu_backend::byte_kernels::erf_f32,
1079    "erf_elementwise"
1080);
1081cpu_unary_wrapper!(
1082    erf_elementwise_f64_cpu_wrapper,
1083    fuel_cpu_backend::byte_kernels::erf_f64,
1084    "erf_elementwise"
1085);
1086cpu_unary_wrapper!(
1087    erf_elementwise_bf16_cpu_wrapper,
1088    fuel_cpu_backend::byte_kernels::erf_bf16,
1089    "erf_elementwise"
1090);
1091cpu_unary_wrapper!(
1092    erf_elementwise_f16_cpu_wrapper,
1093    fuel_cpu_backend::byte_kernels::erf_f16,
1094    "erf_elementwise"
1095);
1096
1097cpu_unary_wrapper!(
1098    gelu_erf_elementwise_f32_cpu_wrapper,
1099    fuel_cpu_backend::byte_kernels::gelu_erf_f32,
1100    "gelu_erf_elementwise"
1101);
1102cpu_unary_wrapper!(
1103    gelu_erf_elementwise_f64_cpu_wrapper,
1104    fuel_cpu_backend::byte_kernels::gelu_erf_f64,
1105    "gelu_erf_elementwise"
1106);
1107cpu_unary_wrapper!(
1108    gelu_erf_elementwise_bf16_cpu_wrapper,
1109    fuel_cpu_backend::byte_kernels::gelu_erf_bf16,
1110    "gelu_erf_elementwise"
1111);
1112cpu_unary_wrapper!(
1113    gelu_erf_elementwise_f16_cpu_wrapper,
1114    fuel_cpu_backend::byte_kernels::gelu_erf_f16,
1115    "gelu_erf_elementwise"
1116);
1117
1118cpu_binary_wrapper!(
1119    pow_elementwise_f32_cpu_wrapper,
1120    fuel_cpu_backend::byte_kernels::pow_f32,
1121    "pow_elementwise"
1122);
1123cpu_binary_wrapper!(
1124    pow_elementwise_f64_cpu_wrapper,
1125    fuel_cpu_backend::byte_kernels::pow_f64,
1126    "pow_elementwise"
1127);
1128cpu_binary_wrapper!(
1129    pow_elementwise_bf16_cpu_wrapper,
1130    fuel_cpu_backend::byte_kernels::pow_bf16,
1131    "pow_elementwise"
1132);
1133cpu_binary_wrapper!(
1134    pow_elementwise_f16_cpu_wrapper,
1135    fuel_cpu_backend::byte_kernels::pow_f16,
1136    "pow_elementwise"
1137);
1138
1139cpu_unary_wrapper!(
1140    rsqrt_elementwise_f32_cpu_wrapper,
1141    fuel_cpu_backend::byte_kernels::rsqrt_f32,
1142    "rsqrt_elementwise"
1143);
1144cpu_unary_wrapper!(
1145    rsqrt_elementwise_f64_cpu_wrapper,
1146    fuel_cpu_backend::byte_kernels::rsqrt_f64,
1147    "rsqrt_elementwise"
1148);
1149cpu_unary_wrapper!(
1150    rsqrt_elementwise_bf16_cpu_wrapper,
1151    fuel_cpu_backend::byte_kernels::rsqrt_bf16,
1152    "rsqrt_elementwise"
1153);
1154cpu_unary_wrapper!(
1155    rsqrt_elementwise_f16_cpu_wrapper,
1156    fuel_cpu_backend::byte_kernels::rsqrt_f16,
1157    "rsqrt_elementwise"
1158);
1159
1160cpu_binary_wrapper!(
1161    rem_elementwise_f32_cpu_wrapper,
1162    fuel_cpu_backend::byte_kernels::rem_f32,
1163    "rem_elementwise"
1164);
1165cpu_binary_wrapper!(
1166    rem_elementwise_f64_cpu_wrapper,
1167    fuel_cpu_backend::byte_kernels::rem_f64,
1168    "rem_elementwise"
1169);
1170cpu_binary_wrapper!(
1171    rem_elementwise_bf16_cpu_wrapper,
1172    fuel_cpu_backend::byte_kernels::rem_bf16,
1173    "rem_elementwise"
1174);
1175cpu_binary_wrapper!(
1176    rem_elementwise_f16_cpu_wrapper,
1177    fuel_cpu_backend::byte_kernels::rem_f16,
1178    "rem_elementwise"
1179);
1180
1181/// Dispatch wrapper for `(Flip, *, Cpu)`. Dtype-agnostic at the byte
1182/// level — `dtype_size` flows from the output Storage. Geometry
1183/// (`outer_count`, `dim_size`, `inner_count`) is precomputed by
1184/// `op_to_op_params` from the input shape + flip dim.
1185pub(crate) fn flip_cpu_wrapper(
1186    inputs: &[Arc<RwLock<Storage>>],
1187    outputs: &mut [Arc<RwLock<Storage>>],
1188    _layouts: &[Layout],
1189    params: &OpParams,
1190) -> Result<()> {
1191    if inputs.len() != 1 || outputs.len() != 1 {
1192        return Err(Error::Msg(format!(
1193            "flip wrapper expects 1 input + 1 output, got {} + {}",
1194            inputs.len(),
1195            outputs.len(),
1196        ))
1197        .bt());
1198    }
1199    let (outer, dim_size, inner) = match params {
1200        OpParams::Flip {
1201            outer_count,
1202            dim_size,
1203            inner_count,
1204            ..
1205        } => (*outer_count, *dim_size, *inner_count),
1206        other => {
1207            return Err(Error::Msg(format!(
1208                "flip wrapper expects OpParams::Flip, got {other:?}",
1209            ))
1210            .bt());
1211        }
1212    };
1213    let in_guard = read_storage(&inputs[0])?;
1214    let mut out_guard = write_storage(&outputs[0])?;
1215    let dtype_size = out_guard.dtype.size_in_bytes();
1216    let in_cpu = cpu_input(&in_guard)?;
1217    let out_cpu = cpu_output(&mut out_guard)?;
1218    fuel_cpu_backend::byte_kernels::flip_cpu(in_cpu, out_cpu, outer, dim_size, inner, dtype_size)
1219}
1220
1221/// Build a `(1 input, 1 output)` CPU dispatch wrapper for the
1222/// per-dtype CumSum kernels. The kernel name is bound at macro
1223/// invocation; geometry comes from `OpParams::CumSum`.
1224macro_rules! cpu_cumsum_wrapper {
1225    ($wrapper:ident, $kernel:path, $op_name:literal) => {
1226        pub(crate) fn $wrapper(
1227            inputs: &[Arc<RwLock<Storage>>],
1228            outputs: &mut [Arc<RwLock<Storage>>],
1229            _layouts: &[Layout],
1230            params: &OpParams,
1231        ) -> Result<()> {
1232            if inputs.len() != 1 || outputs.len() != 1 {
1233                return Err(Error::Msg(format!(
1234                    "{} wrapper expects 1 input + 1 output, got {} + {}",
1235                    $op_name,
1236                    inputs.len(),
1237                    outputs.len(),
1238                ))
1239                .bt());
1240            }
1241            let (outer, dim_size, inner) = match params {
1242                OpParams::CumSum {
1243                    outer_count,
1244                    dim_size,
1245                    inner_count,
1246                    ..
1247                } => (*outer_count, *dim_size, *inner_count),
1248                other => {
1249                    return Err(Error::Msg(format!(
1250                        "{} wrapper expects OpParams::CumSum, got {other:?}",
1251                        $op_name,
1252                    ))
1253                    .bt())
1254                }
1255            };
1256            let in_guard = read_storage(&inputs[0])?;
1257            let mut out_guard = write_storage(&outputs[0])?;
1258            let in_cpu = cpu_input(&in_guard)?;
1259            let out_cpu = cpu_output(&mut out_guard)?;
1260            $kernel(in_cpu, out_cpu, outer, dim_size, inner)
1261        }
1262    };
1263}
1264
1265cpu_cumsum_wrapper!(
1266    cumsum_f32_cpu_wrapper,
1267    fuel_cpu_backend::byte_kernels::cumsum_f32,
1268    "cumsum_f32"
1269);
1270cpu_cumsum_wrapper!(
1271    cumsum_f64_cpu_wrapper,
1272    fuel_cpu_backend::byte_kernels::cumsum_f64,
1273    "cumsum_f64"
1274);
1275cpu_cumsum_wrapper!(
1276    cumsum_bf16_cpu_wrapper,
1277    fuel_cpu_backend::byte_kernels::cumsum_bf16,
1278    "cumsum_bf16"
1279);
1280cpu_cumsum_wrapper!(
1281    cumsum_f16_cpu_wrapper,
1282    fuel_cpu_backend::byte_kernels::cumsum_f16,
1283    "cumsum_f16"
1284);
1285
1286/// Triu / Tril share one byte-level kernel; the wrapper picks
1287/// keep_upper from the OpKind at dispatch time. Dtype-agnostic.
1288fn triu_cpu_wrapper(
1289    inputs: &[Arc<RwLock<Storage>>],
1290    outputs: &mut [Arc<RwLock<Storage>>],
1291    _layouts: &[Layout],
1292    params: &OpParams,
1293) -> Result<()> {
1294    triangular_wrapper_inner(
1295        inputs,
1296        outputs,
1297        params,
1298        /*keep_upper*/ true,
1299        "triu_cpu_wrapper",
1300    )
1301}
1302
1303fn tril_cpu_wrapper(
1304    inputs: &[Arc<RwLock<Storage>>],
1305    outputs: &mut [Arc<RwLock<Storage>>],
1306    _layouts: &[Layout],
1307    params: &OpParams,
1308) -> Result<()> {
1309    triangular_wrapper_inner(
1310        inputs,
1311        outputs,
1312        params,
1313        /*keep_upper*/ false,
1314        "tril_cpu_wrapper",
1315    )
1316}
1317
1318fn triangular_wrapper_inner(
1319    inputs: &[Arc<RwLock<Storage>>],
1320    outputs: &mut [Arc<RwLock<Storage>>],
1321    params: &OpParams,
1322    keep_upper: bool,
1323    op_name: &str,
1324) -> Result<()> {
1325    if inputs.len() != 1 || outputs.len() != 1 {
1326        return Err(Error::Msg(format!(
1327            "{op_name}: expects 1 input + 1 output, got {} + {}",
1328            inputs.len(),
1329            outputs.len(),
1330        ))
1331        .bt());
1332    }
1333    let (batch, rows, cols, diag) = match params {
1334        OpParams::Triangular {
1335            batch_count,
1336            rows,
1337            cols,
1338            diagonal,
1339        } => (*batch_count, *rows, *cols, *diagonal),
1340        other => {
1341            return Err(Error::Msg(format!(
1342                "{op_name}: expects OpParams::Triangular, got {other:?}",
1343            ))
1344            .bt());
1345        }
1346    };
1347    let in_guard = read_storage(&inputs[0])?;
1348    let mut out_guard = write_storage(&outputs[0])?;
1349    let dtype_size = out_guard.dtype.size_in_bytes();
1350    let in_cpu = cpu_input(&in_guard)?;
1351    let out_cpu = cpu_output(&mut out_guard)?;
1352    fuel_cpu_backend::byte_kernels::triangular_cpu(
1353        in_cpu, out_cpu, batch, rows, cols, diag, keep_upper, dtype_size,
1354    )
1355}
1356
1357/// Per-dtype log-softmax wrapper. Geometry comes from
1358/// `OpParams::LogSoftmaxLastDim`.
1359macro_rules! cpu_log_softmax_wrapper {
1360    ($wrapper:ident, $kernel:path, $op_name:literal) => {
1361        pub(crate) fn $wrapper(
1362            inputs: &[Arc<RwLock<Storage>>],
1363            outputs: &mut [Arc<RwLock<Storage>>],
1364            _layouts: &[Layout],
1365            params: &OpParams,
1366        ) -> Result<()> {
1367            if inputs.len() != 1 || outputs.len() != 1 {
1368                return Err(Error::Msg(format!(
1369                    "{} wrapper expects 1 input + 1 output, got {} + {}",
1370                    $op_name,
1371                    inputs.len(),
1372                    outputs.len(),
1373                ))
1374                .bt());
1375            }
1376            let (outer, last_dim) = match params {
1377                OpParams::LogSoftmaxLastDim {
1378                    outer_count,
1379                    last_dim,
1380                } => (*outer_count, *last_dim),
1381                other => {
1382                    return Err(Error::Msg(format!(
1383                        "{} wrapper expects OpParams::LogSoftmaxLastDim, got {other:?}",
1384                        $op_name,
1385                    ))
1386                    .bt());
1387                }
1388            };
1389            let in_guard = read_storage(&inputs[0])?;
1390            let mut out_guard = write_storage(&outputs[0])?;
1391            let in_cpu = cpu_input(&in_guard)?;
1392            let out_cpu = cpu_output(&mut out_guard)?;
1393            $kernel(in_cpu, out_cpu, outer, last_dim)
1394        }
1395    };
1396}
1397
1398cpu_log_softmax_wrapper!(
1399    log_softmax_f32_cpu_wrapper,
1400    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_f32,
1401    "log_softmax_f32"
1402);
1403cpu_log_softmax_wrapper!(
1404    log_softmax_f64_cpu_wrapper,
1405    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_f64,
1406    "log_softmax_f64"
1407);
1408cpu_log_softmax_wrapper!(
1409    log_softmax_bf16_cpu_wrapper,
1410    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_bf16,
1411    "log_softmax_bf16"
1412);
1413cpu_log_softmax_wrapper!(
1414    log_softmax_f16_cpu_wrapper,
1415    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_f16,
1416    "log_softmax_f16"
1417);
1418
1419/// Per-dtype log-softmax-backward wrapper. Two inputs (y, g); same
1420/// geometry as forward.
1421macro_rules! cpu_log_softmax_backward_wrapper {
1422    ($wrapper:ident, $kernel:path, $op_name:literal) => {
1423        // `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the
1424        // real production wrapper and the importer can bind it FROM the contract.
1425        pub(crate) fn $wrapper(
1426            inputs: &[Arc<RwLock<Storage>>],
1427            outputs: &mut [Arc<RwLock<Storage>>],
1428            _layouts: &[Layout],
1429            params: &OpParams,
1430        ) -> Result<()> {
1431            if inputs.len() != 2 || outputs.len() != 1 {
1432                return Err(Error::Msg(format!(
1433                    "{} wrapper expects 2 inputs (y, g) + 1 output, got {} + {}",
1434                    $op_name,
1435                    inputs.len(),
1436                    outputs.len(),
1437                ))
1438                .bt());
1439            }
1440            let (outer, last_dim) = match params {
1441                OpParams::LogSoftmaxLastDim {
1442                    outer_count,
1443                    last_dim,
1444                } => (*outer_count, *last_dim),
1445                other => {
1446                    return Err(Error::Msg(format!(
1447                        "{} wrapper expects OpParams::LogSoftmaxLastDim, got {other:?}",
1448                        $op_name,
1449                    ))
1450                    .bt());
1451                }
1452            };
1453            let y_guard = read_storage(&inputs[0])?;
1454            let g_guard = read_storage(&inputs[1])?;
1455            let mut out_guard = write_storage(&outputs[0])?;
1456            let y_cpu = cpu_input(&y_guard)?;
1457            let g_cpu = cpu_input(&g_guard)?;
1458            let out_cpu = cpu_output(&mut out_guard)?;
1459            $kernel(y_cpu, g_cpu, out_cpu, outer, last_dim)
1460        }
1461    };
1462}
1463
1464cpu_log_softmax_backward_wrapper!(
1465    log_softmax_backward_f32_cpu_wrapper,
1466    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_backward_f32,
1467    "log_softmax_backward_f32"
1468);
1469cpu_log_softmax_backward_wrapper!(
1470    log_softmax_backward_f64_cpu_wrapper,
1471    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_backward_f64,
1472    "log_softmax_backward_f64"
1473);
1474cpu_log_softmax_backward_wrapper!(
1475    log_softmax_backward_bf16_cpu_wrapper,
1476    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_backward_bf16,
1477    "log_softmax_backward_bf16"
1478);
1479cpu_log_softmax_backward_wrapper!(
1480    log_softmax_backward_f16_cpu_wrapper,
1481    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_backward_f16,
1482    "log_softmax_backward_f16"
1483);
1484
1485/// Softmax-last-dim backward — 2 inputs (y, g) + 1 output, reuses
1486/// `OpParams::SoftmaxLastDim` (same outer × last_dim shape contract
1487/// as the forward).
1488macro_rules! cpu_softmax_last_dim_backward_wrapper {
1489    ($wrapper:ident, $kernel:path) => {
1490        // `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the
1491        // real production wrapper and the importer can bind it FROM the contract.
1492        pub(crate) fn $wrapper(
1493            inputs: &[Arc<RwLock<Storage>>],
1494            outputs: &mut [Arc<RwLock<Storage>>],
1495            _layouts: &[Layout],
1496            params: &OpParams,
1497        ) -> Result<()> {
1498            if inputs.len() != 2 || outputs.len() != 1 {
1499                return Err(Error::Msg(format!(
1500                    "softmax_last_dim_backward wrapper expects 2 inputs (y, g) + 1 output, got {} + {}",
1501                    inputs.len(), outputs.len(),
1502                )).bt());
1503            }
1504            let (outer, last_dim) = match params {
1505                OpParams::SoftmaxLastDim { outer_count, last_dim } => (*outer_count, *last_dim),
1506                other => {
1507                    return Err(Error::Msg(format!(
1508                        "softmax_last_dim_backward wrapper expects OpParams::SoftmaxLastDim, got {other:?}",
1509                    )).bt());
1510                }
1511            };
1512            let y_guard = read_storage(&inputs[0])?;
1513            let g_guard = read_storage(&inputs[1])?;
1514            let mut out_guard = write_storage(&outputs[0])?;
1515            let y_cpu = cpu_input(&y_guard)?;
1516            let g_cpu = cpu_input(&g_guard)?;
1517            let out_cpu = cpu_output(&mut out_guard)?;
1518            $kernel(y_cpu, g_cpu, out_cpu, outer, last_dim)
1519        }
1520    };
1521}
1522
1523cpu_softmax_last_dim_backward_wrapper!(
1524    softmax_last_dim_backward_f32_cpu_wrapper,
1525    fuel_cpu_backend::byte_kernels::softmax_last_dim_backward_f32
1526);
1527cpu_softmax_last_dim_backward_wrapper!(
1528    softmax_last_dim_backward_f64_cpu_wrapper,
1529    fuel_cpu_backend::byte_kernels::softmax_last_dim_backward_f64
1530);
1531cpu_softmax_last_dim_backward_wrapper!(
1532    softmax_last_dim_backward_bf16_cpu_wrapper,
1533    fuel_cpu_backend::byte_kernels::softmax_last_dim_backward_bf16
1534);
1535cpu_softmax_last_dim_backward_wrapper!(
1536    softmax_last_dim_backward_f16_cpu_wrapper,
1537    fuel_cpu_backend::byte_kernels::softmax_last_dim_backward_f16
1538);
1539
1540/// LayerNorm / RmsNorm backward share `OpParams::NormLastDim` (with
1541/// eps). Two inputs (x, g) + 1 output, same outer × last_dim shape.
1542macro_rules! cpu_norm_last_dim_backward_wrapper {
1543    ($wrapper:ident, $kernel:path, $op_name:literal) => {
1544        // `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the
1545        // real production wrapper and the importer can bind it FROM the contract.
1546        pub(crate) fn $wrapper(
1547            inputs: &[Arc<RwLock<Storage>>],
1548            outputs: &mut [Arc<RwLock<Storage>>],
1549            _layouts: &[Layout],
1550            params: &OpParams,
1551        ) -> Result<()> {
1552            if inputs.len() != 2 || outputs.len() != 1 {
1553                return Err(Error::Msg(format!(
1554                    "{} wrapper expects 2 inputs (x, g) + 1 output, got {} + {}",
1555                    $op_name,
1556                    inputs.len(),
1557                    outputs.len(),
1558                ))
1559                .bt());
1560            }
1561            let (outer, last_dim, eps) = match params {
1562                OpParams::NormLastDim {
1563                    outer_count,
1564                    last_dim,
1565                    eps,
1566                } => (*outer_count, *last_dim, *eps),
1567                other => {
1568                    return Err(Error::Msg(format!(
1569                        "{} wrapper expects OpParams::NormLastDim, got {other:?}",
1570                        $op_name,
1571                    ))
1572                    .bt());
1573                }
1574            };
1575            let x_guard = read_storage(&inputs[0])?;
1576            let g_guard = read_storage(&inputs[1])?;
1577            let mut out_guard = write_storage(&outputs[0])?;
1578            let x_cpu = cpu_input(&x_guard)?;
1579            let g_cpu = cpu_input(&g_guard)?;
1580            let out_cpu = cpu_output(&mut out_guard)?;
1581            $kernel(x_cpu, g_cpu, out_cpu, outer, last_dim, eps)
1582        }
1583    };
1584}
1585
1586cpu_norm_last_dim_backward_wrapper!(
1587    layer_norm_last_dim_backward_f32_cpu_wrapper,
1588    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_backward_f32,
1589    "layer_norm_backward_f32"
1590);
1591cpu_norm_last_dim_backward_wrapper!(
1592    layer_norm_last_dim_backward_f64_cpu_wrapper,
1593    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_backward_f64,
1594    "layer_norm_backward_f64"
1595);
1596cpu_norm_last_dim_backward_wrapper!(
1597    layer_norm_last_dim_backward_bf16_cpu_wrapper,
1598    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_backward_bf16,
1599    "layer_norm_backward_bf16"
1600);
1601cpu_norm_last_dim_backward_wrapper!(
1602    layer_norm_last_dim_backward_f16_cpu_wrapper,
1603    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_backward_f16,
1604    "layer_norm_backward_f16"
1605);
1606
1607cpu_norm_last_dim_backward_wrapper!(
1608    rms_norm_last_dim_backward_f32_cpu_wrapper,
1609    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_backward_f32,
1610    "rms_norm_backward_f32"
1611);
1612cpu_norm_last_dim_backward_wrapper!(
1613    rms_norm_last_dim_backward_f64_cpu_wrapper,
1614    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_backward_f64,
1615    "rms_norm_backward_f64"
1616);
1617cpu_norm_last_dim_backward_wrapper!(
1618    rms_norm_last_dim_backward_bf16_cpu_wrapper,
1619    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_backward_bf16,
1620    "rms_norm_backward_bf16"
1621);
1622cpu_norm_last_dim_backward_wrapper!(
1623    rms_norm_last_dim_backward_f16_cpu_wrapper,
1624    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_backward_f16,
1625    "rms_norm_backward_f16"
1626);
1627
1628/// ReduceMaxTo backward — 2 inputs (x, upstream) + 1 output. Carries
1629/// the shape pair via `OpParams::ReduceMaxToBackward`.
1630/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
1631/// production wrapper and the importer can bind it FROM the contract.
1632macro_rules! cpu_reduce_max_to_backward_wrapper {
1633    ($wrapper:ident, $kernel:path) => {
1634        pub(crate) fn $wrapper(
1635            inputs: &[Arc<RwLock<Storage>>],
1636            outputs: &mut [Arc<RwLock<Storage>>],
1637            _layouts: &[Layout],
1638            params: &OpParams,
1639        ) -> Result<()> {
1640            if inputs.len() != 2 || outputs.len() != 1 {
1641                return Err(Error::Msg(format!(
1642                    "reduce_max_to_backward wrapper expects 2 inputs (x, upstream) + 1 output, got {} + {}",
1643                    inputs.len(), outputs.len(),
1644                )).bt());
1645            }
1646            let (input_shape, output_shape) = match params {
1647                OpParams::ReduceMaxToBackward { input_shape, output_shape } => {
1648                    (input_shape.as_slice(), output_shape.as_slice())
1649                }
1650                other => {
1651                    return Err(Error::Msg(format!(
1652                        "reduce_max_to_backward wrapper expects OpParams::ReduceMaxToBackward, got {other:?}",
1653                    )).bt());
1654                }
1655            };
1656            let x_guard = read_storage(&inputs[0])?;
1657            let up_guard = read_storage(&inputs[1])?;
1658            let mut out_guard = write_storage(&outputs[0])?;
1659            let x_cpu = cpu_input(&x_guard)?;
1660            let up_cpu = cpu_input(&up_guard)?;
1661            let out_cpu = cpu_output(&mut out_guard)?;
1662            $kernel(x_cpu, up_cpu, out_cpu, input_shape, output_shape)
1663        }
1664    };
1665}
1666
1667cpu_reduce_max_to_backward_wrapper!(
1668    reduce_max_to_backward_f32_cpu_wrapper,
1669    fuel_cpu_backend::byte_kernels::reduce_max_to_backward_f32
1670);
1671cpu_reduce_max_to_backward_wrapper!(
1672    reduce_max_to_backward_f64_cpu_wrapper,
1673    fuel_cpu_backend::byte_kernels::reduce_max_to_backward_f64
1674);
1675cpu_reduce_max_to_backward_wrapper!(
1676    reduce_max_to_backward_bf16_cpu_wrapper,
1677    fuel_cpu_backend::byte_kernels::reduce_max_to_backward_bf16
1678);
1679cpu_reduce_max_to_backward_wrapper!(
1680    reduce_max_to_backward_f16_cpu_wrapper,
1681    fuel_cpu_backend::byte_kernels::reduce_max_to_backward_f16
1682);
1683
1684/// Single dtype-agnostic MaskedFill wrapper. Reads `fill_bytes`
1685/// (pre-encoded by `op_to_op_params`) and dtype_size from the output.
1686pub(crate) fn masked_fill_cpu_wrapper(
1687    inputs: &[Arc<RwLock<Storage>>],
1688    outputs: &mut [Arc<RwLock<Storage>>],
1689    _layouts: &[Layout],
1690    params: &OpParams,
1691) -> Result<()> {
1692    if inputs.len() != 2 || outputs.len() != 1 {
1693        return Err(Error::Msg(format!(
1694            "masked_fill_cpu_wrapper: expects 2 inputs (x, mask) + 1 output, got {} + {}",
1695            inputs.len(),
1696            outputs.len(),
1697        ))
1698        .bt());
1699    }
1700    let fill_bytes = match params {
1701        OpParams::MaskedFill { fill_bytes } => fill_bytes.clone(),
1702        other => {
1703            return Err(Error::Msg(format!(
1704                "masked_fill_cpu_wrapper: expects OpParams::MaskedFill, got {other:?}",
1705            ))
1706            .bt());
1707        }
1708    };
1709    let in_guard = read_storage(&inputs[0])?;
1710    let mask_guard = read_storage(&inputs[1])?;
1711    // GAP-168(c): validate the mask dtype at RUNTIME, matching `where`'s wrapper
1712    // and the Vulkan masked_fill. This wrapper previously did NOT check, so a U8
1713    // buffer flowed in under a Bool node and worked — the byte-identity hazard
1714    // exactly: `Bool` and `U8` are the same bytes, so the wrong wiring produces
1715    // the right answer and nothing complains. The graph builder already rejects a
1716    // non-Bool mask; this is the second line, for storage assembled directly.
1717    if mask_guard.dtype != DType::Bool {
1718        return Err(Error::Msg(format!(
1719            "masked_fill_cpu_wrapper: mask must be Bool, got {:?} (GAP-168(c))",
1720            mask_guard.dtype,
1721        ))
1722        .bt());
1723    }
1724    let mut out_guard = write_storage(&outputs[0])?;
1725    let dtype_size = out_guard.dtype.size_in_bytes();
1726    let in_cpu = cpu_input(&in_guard)?;
1727    let mask_cpu = cpu_input(&mask_guard)?;
1728    let out_cpu = cpu_output(&mut out_guard)?;
1729    fuel_cpu_backend::byte_kernels::masked_fill_cpu(
1730        in_cpu,
1731        mask_cpu,
1732        out_cpu,
1733        &fill_bytes,
1734        dtype_size,
1735    )
1736}
1737
1738/// Single dtype-agnostic dispatch wrapper for Pad. The kernel is
1739/// byte-level (`fill_bytes` is pre-encoded for the output dtype in
1740/// `op_to_op_params`); this wrapper just reads dtype_size from the
1741/// output Storage and passes through. One wrapper covers every
1742/// dtype the binding-table is registered for.
1743pub(crate) fn pad_cpu_wrapper(
1744    inputs: &[Arc<RwLock<Storage>>],
1745    outputs: &mut [Arc<RwLock<Storage>>],
1746    _layouts: &[Layout],
1747    params: &OpParams,
1748) -> Result<()> {
1749    if inputs.len() != 1 || outputs.len() != 1 {
1750        return Err(Error::Msg(format!(
1751            "pad wrapper expects 1 input + 1 output, got {} + {}",
1752            inputs.len(),
1753            outputs.len(),
1754        ))
1755        .bt());
1756    }
1757    let (in_shape, out_shape, padding, mode_tag, fill_bytes) = match params {
1758        OpParams::Pad {
1759            in_shape,
1760            out_shape,
1761            padding,
1762            mode_tag,
1763            fill_bytes,
1764        } => (in_shape, out_shape, padding, *mode_tag, fill_bytes),
1765        other => {
1766            return Err(
1767                Error::Msg(format!("pad wrapper expects OpParams::Pad, got {other:?}",)).bt(),
1768            );
1769        }
1770    };
1771    let in_guard = read_storage(&inputs[0])?;
1772    let mut out_guard = write_storage(&outputs[0])?;
1773    let dtype_size = out_guard.dtype.size_in_bytes();
1774    let in_cpu = cpu_input(&in_guard)?;
1775    let out_cpu = cpu_output(&mut out_guard)?;
1776    // Per-mode forward dispatch.
1777    match mode_tag {
1778        0 => fuel_cpu_backend::byte_kernels::pad_const_cpu(
1779            in_cpu, out_cpu, in_shape, out_shape, padding, dtype_size, fill_bytes,
1780        ),
1781        1 => {
1782            // Reflect: validate before/after <= n-1 per axis (otherwise
1783            // the reflection runs off the input).
1784            for (k, (&n, &(b, a))) in in_shape.iter().zip(padding.iter()).enumerate() {
1785                if n > 0 && (b > n - 1 || a > n - 1) {
1786                    return Err(Error::Msg(format!(
1787                        "pad reflect: axis {k} has dim_size {n}; before ({b}) and \
1788                         after ({a}) must each be <= dim_size - 1",
1789                    ))
1790                    .bt());
1791                }
1792            }
1793            fuel_cpu_backend::byte_kernels::pad_reflect_cpu(
1794                in_cpu, out_cpu, in_shape, out_shape, padding, dtype_size,
1795            )
1796        }
1797        2 => fuel_cpu_backend::byte_kernels::pad_replicate_cpu(
1798            in_cpu, out_cpu, in_shape, out_shape, padding, dtype_size,
1799        ),
1800        other => Err(Error::Msg(format!("pad: unknown mode_tag {other}",)).bt()),
1801    }
1802}
1803
1804/// Build a `(1 input, 1 output)` per-dtype dispatch wrapper for
1805/// `Op::PadBackward`. Per-dtype (unlike forward Pad) because the
1806/// backward kernel does typed addition (accumulation per input slot).
1807macro_rules! cpu_pad_backward_wrapper {
1808    ($wrapper:ident, $kernel:path, $op_name:literal) => {
1809        pub(crate) fn $wrapper(
1810            inputs: &[Arc<RwLock<Storage>>],
1811            outputs: &mut [Arc<RwLock<Storage>>],
1812            _layouts: &[Layout],
1813            params: &OpParams,
1814        ) -> Result<()> {
1815            if inputs.len() != 1 || outputs.len() != 1 {
1816                return Err(Error::Msg(format!(
1817                    "{} wrapper expects 1 input + 1 output, got {} + {}",
1818                    $op_name,
1819                    inputs.len(),
1820                    outputs.len(),
1821                ))
1822                .bt());
1823            }
1824            let (in_shape, out_shape, padding, mode_tag) = match params {
1825                OpParams::PadBackward {
1826                    in_shape,
1827                    out_shape,
1828                    padding,
1829                    mode_tag,
1830                } => (in_shape, out_shape, padding, *mode_tag),
1831                other => {
1832                    return Err(Error::Msg(format!(
1833                        "{} wrapper expects OpParams::PadBackward, got {other:?}",
1834                        $op_name,
1835                    ))
1836                    .bt())
1837                }
1838            };
1839            let in_guard = read_storage(&inputs[0])?;
1840            let mut out_guard = write_storage(&outputs[0])?;
1841            let in_cpu = cpu_input(&in_guard)?;
1842            let out_cpu = cpu_output(&mut out_guard)?;
1843            $kernel(in_cpu, out_cpu, in_shape, out_shape, padding, mode_tag)
1844        }
1845    };
1846}
1847
1848cpu_pad_backward_wrapper!(
1849    pad_backward_f32_cpu_wrapper,
1850    fuel_cpu_backend::byte_kernels::pad_backward_f32,
1851    "pad_backward_f32"
1852);
1853cpu_pad_backward_wrapper!(
1854    pad_backward_f64_cpu_wrapper,
1855    fuel_cpu_backend::byte_kernels::pad_backward_f64,
1856    "pad_backward_f64"
1857);
1858cpu_pad_backward_wrapper!(
1859    pad_backward_bf16_cpu_wrapper,
1860    fuel_cpu_backend::byte_kernels::pad_backward_bf16,
1861    "pad_backward_bf16"
1862);
1863cpu_pad_backward_wrapper!(
1864    pad_backward_f16_cpu_wrapper,
1865    fuel_cpu_backend::byte_kernels::pad_backward_f16,
1866    "pad_backward_f16"
1867);
1868
1869/// Dispatch wrapper for `(Roll, *, Cpu)`. Dtype-agnostic at the byte
1870/// level. Same shape as Flip plus a signed `shift`.
1871pub(crate) fn roll_cpu_wrapper(
1872    inputs: &[Arc<RwLock<Storage>>],
1873    outputs: &mut [Arc<RwLock<Storage>>],
1874    _layouts: &[Layout],
1875    params: &OpParams,
1876) -> Result<()> {
1877    if inputs.len() != 1 || outputs.len() != 1 {
1878        return Err(Error::Msg(format!(
1879            "roll wrapper expects 1 input + 1 output, got {} + {}",
1880            inputs.len(),
1881            outputs.len(),
1882        ))
1883        .bt());
1884    }
1885    let (outer, dim_size, inner, shift) = match params {
1886        OpParams::Roll {
1887            outer_count,
1888            dim_size,
1889            inner_count,
1890            shift,
1891            ..
1892        } => (*outer_count, *dim_size, *inner_count, *shift),
1893        other => {
1894            return Err(Error::Msg(format!(
1895                "roll wrapper expects OpParams::Roll, got {other:?}",
1896            ))
1897            .bt());
1898        }
1899    };
1900    let in_guard = read_storage(&inputs[0])?;
1901    let mut out_guard = write_storage(&outputs[0])?;
1902    let dtype_size = out_guard.dtype.size_in_bytes();
1903    let in_cpu = cpu_input(&in_guard)?;
1904    let out_cpu = cpu_output(&mut out_guard)?;
1905    fuel_cpu_backend::byte_kernels::roll_cpu(
1906        in_cpu, out_cpu, outer, dim_size, inner, shift, dtype_size,
1907    )
1908}
1909
1910/// Generate a CPU argextremum wrapper. Output dtype is U32; the
1911/// binding-table key is keyed on the OUTPUT dtype = U32. The
1912/// wrapper validates the input is F32 (only F32 is wired today).
1913macro_rules! cpu_arg_dim_wrapper {
1914    ($wrapper:ident, $kernel:path, $op_name:literal) => {
1915        fn $wrapper(
1916            inputs: &[Arc<RwLock<Storage>>],
1917            outputs: &mut [Arc<RwLock<Storage>>],
1918            layouts: &[Layout],
1919            params: &OpParams,
1920        ) -> Result<()> {
1921            if inputs.len() != 1 || outputs.len() != 1 {
1922                return Err(Error::Msg(format!(
1923                    "{} wrapper expects 1 input + 1 output, got {} + {}",
1924                    $op_name,
1925                    inputs.len(),
1926                    outputs.len(),
1927                ))
1928                .bt());
1929            }
1930            let dims = match params {
1931                OpParams::Reduce { dims, .. } => dims,
1932                other => {
1933                    return Err(Error::Msg(format!(
1934                        "{} wrapper expects OpParams::Reduce, got {other:?}",
1935                        $op_name,
1936                    ))
1937                    .bt())
1938                }
1939            };
1940            if dims.len() != 1 {
1941                return Err(Error::Msg(format!(
1942                    "{} wrapper expects exactly 1 reduce dim, got {dims:?}",
1943                    $op_name,
1944                ))
1945                .bt());
1946            }
1947            let dim = dims[0];
1948            let input_layout = layouts.first().ok_or_else(|| {
1949                Error::Msg(format!(
1950                    "{} wrapper: layouts empty (executor must pass input layout at [0])",
1951                    $op_name,
1952                ))
1953                .bt()
1954            })?;
1955            let in_guard = read_storage(&inputs[0])?;
1956            if in_guard.dtype != DType::F32 {
1957                return Err(Error::Msg(format!(
1958                    "{}: only F32 input is wired today, got {:?}",
1959                    $op_name, in_guard.dtype,
1960                ))
1961                .bt());
1962            }
1963            let mut out_guard = write_storage(&outputs[0])?;
1964            let in_cpu = cpu_input(&in_guard)?;
1965            let out_cpu = cpu_output(&mut out_guard)?;
1966            $kernel(in_cpu, out_cpu, input_layout.shape().dims(), dim)
1967        }
1968    };
1969}
1970
1971cpu_arg_dim_wrapper!(
1972    argmax_dim_u32_cpu_wrapper,
1973    fuel_cpu_backend::byte_kernels::argmax_dim_f32,
1974    "argmax_dim"
1975);
1976cpu_arg_dim_wrapper!(
1977    argmin_dim_u32_cpu_wrapper,
1978    fuel_cpu_backend::byte_kernels::argmin_dim_f32,
1979    "argmin_dim"
1980);
1981
1982/// Dispatch wrapper for `(IndexAdd, F32, Cpu)`. Three inputs:
1983/// `(base, indices, src)` (rank-1 U32 indices). Output shape == base.
1984/// `pub(crate)` so the FKC `CpuLinkRegistry` can bind this symbol from the
1985/// indexing contract.
1986pub(crate) fn index_add_f32_cpu_wrapper(
1987    inputs: &[Arc<RwLock<Storage>>],
1988    outputs: &mut [Arc<RwLock<Storage>>],
1989    _layouts: &[Layout],
1990    params: &OpParams,
1991) -> Result<()> {
1992    if inputs.len() != 3 || outputs.len() != 1 {
1993        return Err(Error::Msg(format!(
1994            "index_add wrapper expects 3 inputs (base, indices, src) + 1 output, got {} + {}",
1995            inputs.len(),
1996            outputs.len(),
1997        ))
1998        .bt());
1999    }
2000    let (outer_count, base_dim_size, n_indices, inner_count) = match params {
2001        OpParams::IndexAdd {
2002            outer_count,
2003            base_dim_size,
2004            n_indices,
2005            inner_count,
2006        } => (*outer_count, *base_dim_size, *n_indices, *inner_count),
2007        other => {
2008            return Err(Error::Msg(format!(
2009                "index_add wrapper expects OpParams::IndexAdd, got {other:?}",
2010            ))
2011            .bt());
2012        }
2013    };
2014    let base_guard = read_storage(&inputs[0])?;
2015    let idx_guard = read_storage(&inputs[1])?;
2016    if idx_guard.dtype != DType::U32 {
2017        return Err(Error::Msg(format!(
2018            "index_add: indices must be U32, got {:?}",
2019            idx_guard.dtype,
2020        ))
2021        .bt());
2022    }
2023    let src_guard = read_storage(&inputs[2])?;
2024    let mut out_guard = write_storage(&outputs[0])?;
2025    let base_cpu = cpu_input(&base_guard)?;
2026    let idx_cpu = cpu_input(&idx_guard)?;
2027    let src_cpu = cpu_input(&src_guard)?;
2028    let out_cpu = cpu_output(&mut out_guard)?;
2029    fuel_cpu_backend::byte_kernels::index_add_f32(
2030        base_cpu,
2031        idx_cpu,
2032        src_cpu,
2033        out_cpu,
2034        outer_count,
2035        base_dim_size,
2036        n_indices,
2037        inner_count,
2038    )
2039}
2040
2041/// Dispatch wrapper for `(ScatterAdd, F32, Cpu)`. Three inputs:
2042/// `(base, indices, src)` (same-rank U32 indices). Output shape == base.
2043/// `pub(crate)` so the FKC `CpuLinkRegistry` can bind this symbol from the
2044/// indexing contract.
2045pub(crate) fn scatter_add_f32_cpu_wrapper(
2046    inputs: &[Arc<RwLock<Storage>>],
2047    outputs: &mut [Arc<RwLock<Storage>>],
2048    _layouts: &[Layout],
2049    params: &OpParams,
2050) -> Result<()> {
2051    if inputs.len() != 3 || outputs.len() != 1 {
2052        return Err(Error::Msg(format!(
2053            "scatter_add wrapper expects 3 inputs (base, indices, src) + 1 output, got {} + {}",
2054            inputs.len(),
2055            outputs.len(),
2056        ))
2057        .bt());
2058    }
2059    let (base_shape, src_shape, dim) = match params {
2060        OpParams::ScatterAdd {
2061            base_shape,
2062            src_shape,
2063            dim,
2064        } => (base_shape, src_shape, *dim),
2065        other => {
2066            return Err(Error::Msg(format!(
2067                "scatter_add wrapper expects OpParams::ScatterAdd, got {other:?}",
2068            ))
2069            .bt());
2070        }
2071    };
2072    let base_guard = read_storage(&inputs[0])?;
2073    let idx_guard = read_storage(&inputs[1])?;
2074    if idx_guard.dtype != DType::U32 {
2075        return Err(Error::Msg(format!(
2076            "scatter_add: indices must be U32, got {:?}",
2077            idx_guard.dtype,
2078        ))
2079        .bt());
2080    }
2081    let src_guard = read_storage(&inputs[2])?;
2082    let mut out_guard = write_storage(&outputs[0])?;
2083    let base_cpu = cpu_input(&base_guard)?;
2084    let idx_cpu = cpu_input(&idx_guard)?;
2085    let src_cpu = cpu_input(&src_guard)?;
2086    let out_cpu = cpu_output(&mut out_guard)?;
2087    fuel_cpu_backend::byte_kernels::scatter_add_f32(
2088        base_cpu, idx_cpu, src_cpu, out_cpu, base_shape, src_shape, dim,
2089    )
2090}
2091
2092/// Dispatch wrapper for `(Rope, F32, Cpu)`. Three inputs:
2093/// `(x, cos, sin)`. `OpParams::Rope` carries the geometry.
2094/// `pub(crate)` so the FKC `CpuLinkRegistry` (`fkc::cpu_link`) can bind this
2095/// symbol from the rope contract.
2096pub(crate) fn rope_f32_cpu_wrapper(
2097    inputs: &[Arc<RwLock<Storage>>],
2098    outputs: &mut [Arc<RwLock<Storage>>],
2099    _layouts: &[Layout],
2100    params: &OpParams,
2101) -> Result<()> {
2102    if inputs.len() != 3 || outputs.len() != 1 {
2103        return Err(Error::Msg(format!(
2104            "rope wrapper expects 3 inputs (x, cos, sin) + 1 output, got {} + {}",
2105            inputs.len(),
2106            outputs.len(),
2107        ))
2108        .bt());
2109    }
2110    let (outer_count, seq, head_dim) = match params {
2111        OpParams::Rope {
2112            outer_count,
2113            seq,
2114            head_dim,
2115        } => (*outer_count, *seq, *head_dim),
2116        other => {
2117            return Err(Error::Msg(format!(
2118                "rope wrapper expects OpParams::Rope, got {other:?}",
2119            ))
2120            .bt());
2121        }
2122    };
2123    let x_guard = read_storage(&inputs[0])?;
2124    let cos_guard = read_storage(&inputs[1])?;
2125    let sin_guard = read_storage(&inputs[2])?;
2126    let mut out_guard = write_storage(&outputs[0])?;
2127    let x_cpu = cpu_input(&x_guard)?;
2128    let cos_cpu = cpu_input(&cos_guard)?;
2129    let sin_cpu = cpu_input(&sin_guard)?;
2130    let out_cpu = cpu_output(&mut out_guard)?;
2131    fuel_cpu_backend::byte_kernels::rope_f32(
2132        x_cpu,
2133        cos_cpu,
2134        sin_cpu,
2135        out_cpu,
2136        outer_count,
2137        seq,
2138        head_dim,
2139    )
2140}
2141
2142/// Dispatch wrapper for `(Gather, *, Cpu)`. Dtype-agnostic at
2143/// the byte level — `dtype_size` flows from the output Storage.
2144/// `pub(crate)` so the FKC `CpuLinkRegistry` can bind this symbol from the
2145/// indexing contract (the fabricated `gather_cpu_<dt>` symbols all resolve here).
2146pub(crate) fn gather_cpu_wrapper(
2147    inputs: &[Arc<RwLock<Storage>>],
2148    outputs: &mut [Arc<RwLock<Storage>>],
2149    _layouts: &[Layout],
2150    params: &OpParams,
2151) -> Result<()> {
2152    if inputs.len() != 2 || outputs.len() != 1 {
2153        return Err(Error::Msg(format!(
2154            "gather wrapper expects 2 inputs + 1 output, got {} + {}",
2155            inputs.len(),
2156            outputs.len(),
2157        ))
2158        .bt());
2159    }
2160    let (source_shape, output_shape, dim) = match params {
2161        OpParams::Gather {
2162            source_shape,
2163            output_shape,
2164            dim,
2165        } => (source_shape, output_shape, *dim),
2166        other => {
2167            return Err(Error::Msg(format!(
2168                "gather wrapper expects OpParams::Gather, got {other:?}",
2169            ))
2170            .bt());
2171        }
2172    };
2173    let src_guard = read_storage(&inputs[0])?;
2174    let idx_guard = read_storage(&inputs[1])?;
2175    if idx_guard.dtype != DType::U32 {
2176        return Err(Error::Msg(format!(
2177            "gather: indices must be U32, got {:?}",
2178            idx_guard.dtype,
2179        ))
2180        .bt());
2181    }
2182    let mut out_guard = write_storage(&outputs[0])?;
2183    let dtype_size = out_guard.dtype.size_in_bytes();
2184    let src_cpu = cpu_input(&src_guard)?;
2185    let idx_cpu = cpu_input(&idx_guard)?;
2186    let out_cpu = cpu_output(&mut out_guard)?;
2187    fuel_cpu_backend::byte_kernels::gather_cpu(
2188        src_cpu,
2189        idx_cpu,
2190        out_cpu,
2191        source_shape,
2192        output_shape,
2193        dim,
2194        dtype_size,
2195    )
2196}
2197
2198/// Dispatch wrapper for `(IndexSelect, *, Cpu)`. Dtype-agnostic
2199/// at the byte level — `dtype_size` flows from the output Storage.
2200/// Indices are always U32 (validated at runtime).
2201/// `pub(crate)` so the FKC `CpuLinkRegistry` can bind this symbol from the
2202/// indexing contract (the fabricated `index_select_cpu_<dt>` symbols resolve here).
2203pub(crate) fn index_select_cpu_wrapper(
2204    inputs: &[Arc<RwLock<Storage>>],
2205    outputs: &mut [Arc<RwLock<Storage>>],
2206    _layouts: &[Layout],
2207    params: &OpParams,
2208) -> Result<()> {
2209    if inputs.len() != 2 {
2210        return Err(Error::Msg(format!(
2211            "index_select wrapper expects 2 inputs (source, indices), got {}",
2212            inputs.len(),
2213        ))
2214        .bt());
2215    }
2216    if outputs.len() != 1 {
2217        return Err(Error::Msg(format!(
2218            "index_select wrapper expects 1 output, got {}",
2219            outputs.len(),
2220        ))
2221        .bt());
2222    }
2223    let (outer_count, source_dim_size, n_indices, inner_count) = match params {
2224        OpParams::IndexSelect {
2225            outer_count,
2226            source_dim_size,
2227            n_indices,
2228            inner_count,
2229        } => (*outer_count, *source_dim_size, *n_indices, *inner_count),
2230        other => {
2231            return Err(Error::Msg(format!(
2232                "index_select wrapper expects OpParams::IndexSelect, got {other:?}",
2233            ))
2234            .bt());
2235        }
2236    };
2237    let src_guard = read_storage(&inputs[0])?;
2238    let idx_guard = read_storage(&inputs[1])?;
2239    if idx_guard.dtype != DType::U32 {
2240        return Err(Error::Msg(format!(
2241            "index_select: indices must be U32, got {:?}",
2242            idx_guard.dtype,
2243        ))
2244        .bt());
2245    }
2246    let mut out_guard = write_storage(&outputs[0])?;
2247    let dtype_size = out_guard.dtype.size_in_bytes();
2248    let src_cpu = cpu_input(&src_guard)?;
2249    let idx_cpu = cpu_input(&idx_guard)?;
2250    let out_cpu = cpu_output(&mut out_guard)?;
2251    fuel_cpu_backend::byte_kernels::index_select_cpu(
2252        src_cpu,
2253        idx_cpu,
2254        out_cpu,
2255        outer_count,
2256        source_dim_size,
2257        n_indices,
2258        inner_count,
2259        dtype_size,
2260    )
2261}
2262
2263/// Generate a CPU last-dim norm wrapper that pulls
2264/// `(outer_count, last_dim, eps)` from `OpParams::NormLastDim`
2265/// and forwards to a typed kernel.
2266macro_rules! cpu_norm_last_dim_wrapper {
2267    ($wrapper:ident, $kernel:path, $op_name:literal) => {
2268        pub(crate) fn $wrapper(
2269            inputs: &[Arc<RwLock<Storage>>],
2270            outputs: &mut [Arc<RwLock<Storage>>],
2271            _layouts: &[Layout],
2272            params: &OpParams,
2273        ) -> Result<()> {
2274            if inputs.len() != 1 || outputs.len() != 1 {
2275                return Err(Error::Msg(format!(
2276                    "{} wrapper expects 1 input + 1 output, got {} + {}",
2277                    $op_name,
2278                    inputs.len(),
2279                    outputs.len(),
2280                ))
2281                .bt());
2282            }
2283            let (outer_count, last_dim, eps) = match params {
2284                OpParams::NormLastDim {
2285                    outer_count,
2286                    last_dim,
2287                    eps,
2288                } => (*outer_count, *last_dim, *eps),
2289                other => {
2290                    return Err(Error::Msg(format!(
2291                        "{} wrapper expects OpParams::NormLastDim, got {other:?}",
2292                        $op_name,
2293                    ))
2294                    .bt())
2295                }
2296            };
2297            let in_guard = read_storage(&inputs[0])?;
2298            let mut out_guard = write_storage(&outputs[0])?;
2299            let in_cpu = cpu_input(&in_guard)?;
2300            let out_cpu = cpu_output(&mut out_guard)?;
2301            $kernel(in_cpu, out_cpu, outer_count, last_dim, eps)
2302        }
2303    };
2304}
2305
2306cpu_norm_last_dim_wrapper!(
2307    rms_norm_last_dim_f32_cpu_wrapper,
2308    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_f32,
2309    "rms_norm_last_dim"
2310);
2311cpu_norm_last_dim_wrapper!(
2312    layer_norm_last_dim_f32_cpu_wrapper,
2313    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_f32,
2314    "layer_norm_last_dim"
2315);
2316cpu_norm_last_dim_wrapper!(
2317    rms_norm_last_dim_bf16_cpu_wrapper,
2318    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_bf16,
2319    "rms_norm_last_dim"
2320);
2321cpu_norm_last_dim_wrapper!(
2322    rms_norm_last_dim_f16_cpu_wrapper,
2323    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_f16,
2324    "rms_norm_last_dim"
2325);
2326cpu_norm_last_dim_wrapper!(
2327    layer_norm_last_dim_bf16_cpu_wrapper,
2328    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_bf16,
2329    "layer_norm_last_dim"
2330);
2331cpu_norm_last_dim_wrapper!(
2332    layer_norm_last_dim_f16_cpu_wrapper,
2333    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_f16,
2334    "layer_norm_last_dim"
2335);
2336cpu_norm_last_dim_wrapper!(
2337    rms_norm_last_dim_f64_cpu_wrapper,
2338    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_f64,
2339    "rms_norm_last_dim"
2340);
2341cpu_norm_last_dim_wrapper!(
2342    layer_norm_last_dim_f64_cpu_wrapper,
2343    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_f64,
2344    "layer_norm_last_dim"
2345);
2346
2347/// Dispatch wrapper for `(SoftmaxLastDim, F32, Cpu)`. Single
2348/// input + single output; (outer_count, last_dim) flow through
2349/// `OpParams::SoftmaxLastDim`.
2350/// Generate a CPU SoftmaxLastDim wrapper for any element type.
2351/// All entries share the (1 input, 1 output, OpParams::SoftmaxLastDim)
2352/// shape; only the underlying typed kernel differs.
2353macro_rules! cpu_softmax_last_dim_wrapper {
2354    ($wrapper:ident, $kernel:path) => {
2355        pub(crate) fn $wrapper(
2356            inputs: &[Arc<RwLock<Storage>>],
2357            outputs: &mut [Arc<RwLock<Storage>>],
2358            _layouts: &[Layout],
2359            params: &OpParams,
2360        ) -> Result<()> {
2361            if inputs.len() != 1 || outputs.len() != 1 {
2362                return Err(Error::Msg(format!(
2363                    "softmax_last_dim wrapper expects 1 input + 1 output, got {} + {}",
2364                    inputs.len(),
2365                    outputs.len(),
2366                ))
2367                .bt());
2368            }
2369            let (outer_count, last_dim) =
2370                match params {
2371                    OpParams::SoftmaxLastDim {
2372                        outer_count,
2373                        last_dim,
2374                    } => (*outer_count, *last_dim),
2375                    other => return Err(Error::Msg(format!(
2376                        "softmax_last_dim wrapper expects OpParams::SoftmaxLastDim, got {other:?}",
2377                    ))
2378                    .bt()),
2379                };
2380            let in_guard = read_storage(&inputs[0])?;
2381            let mut out_guard = write_storage(&outputs[0])?;
2382            let in_cpu = cpu_input(&in_guard)?;
2383            let out_cpu = cpu_output(&mut out_guard)?;
2384            $kernel(in_cpu, out_cpu, outer_count, last_dim)
2385        }
2386    };
2387}
2388
2389cpu_softmax_last_dim_wrapper!(
2390    softmax_last_dim_f32_cpu_wrapper,
2391    fuel_cpu_backend::byte_kernels::softmax_last_dim_f32
2392);
2393cpu_softmax_last_dim_wrapper!(
2394    softmax_last_dim_f64_cpu_wrapper,
2395    fuel_cpu_backend::byte_kernels::softmax_last_dim_f64
2396);
2397cpu_softmax_last_dim_wrapper!(
2398    softmax_last_dim_bf16_cpu_wrapper,
2399    fuel_cpu_backend::byte_kernels::softmax_last_dim_bf16
2400);
2401cpu_softmax_last_dim_wrapper!(
2402    softmax_last_dim_f16_cpu_wrapper,
2403    fuel_cpu_backend::byte_kernels::softmax_last_dim_f16
2404);
2405
2406/// Generate a CPU Rope wrapper for any element type. The wrapper
2407/// shape is identical across dtypes — three inputs (x, cos, sin)
2408/// and `OpParams::Rope` carries the geometry. `pub(crate)` so the FKC
2409/// `CpuLinkRegistry` (`fkc::cpu_link`) can bind these symbols from the rope
2410/// contract.
2411macro_rules! cpu_rope_wrapper {
2412    ($wrapper:ident, $kernel:path) => {
2413        pub(crate) fn $wrapper(
2414            inputs: &[Arc<RwLock<Storage>>],
2415            outputs: &mut [Arc<RwLock<Storage>>],
2416            _layouts: &[Layout],
2417            params: &OpParams,
2418        ) -> Result<()> {
2419            if inputs.len() != 3 || outputs.len() != 1 {
2420                return Err(Error::Msg(format!(
2421                    "rope wrapper expects 3 inputs + 1 output, got {} + {}",
2422                    inputs.len(),
2423                    outputs.len(),
2424                ))
2425                .bt());
2426            }
2427            let (outer_count, seq, head_dim) = match params {
2428                OpParams::Rope {
2429                    outer_count,
2430                    seq,
2431                    head_dim,
2432                } => (*outer_count, *seq, *head_dim),
2433                other => {
2434                    return Err(Error::Msg(format!(
2435                        "rope wrapper expects OpParams::Rope, got {other:?}",
2436                    ))
2437                    .bt())
2438                }
2439            };
2440            let x_guard = read_storage(&inputs[0])?;
2441            let cos_guard = read_storage(&inputs[1])?;
2442            let sin_guard = read_storage(&inputs[2])?;
2443            let mut out_guard = write_storage(&outputs[0])?;
2444            let x_cpu = cpu_input(&x_guard)?;
2445            let cos_cpu = cpu_input(&cos_guard)?;
2446            let sin_cpu = cpu_input(&sin_guard)?;
2447            let out_cpu = cpu_output(&mut out_guard)?;
2448            $kernel(x_cpu, cos_cpu, sin_cpu, out_cpu, outer_count, seq, head_dim)
2449        }
2450    };
2451}
2452
2453cpu_rope_wrapper!(
2454    rope_bf16_cpu_wrapper,
2455    fuel_cpu_backend::byte_kernels::rope_bf16
2456);
2457cpu_rope_wrapper!(
2458    rope_f16_cpu_wrapper,
2459    fuel_cpu_backend::byte_kernels::rope_f16
2460);
2461cpu_rope_wrapper!(
2462    rope_f64_cpu_wrapper,
2463    fuel_cpu_backend::byte_kernels::rope_f64
2464);
2465
2466/// The per-`QuantType` host kernel choice shared by [`qmatmul_f32_cpu_wrapper`] and the CUDA
2467/// wrapper's host fallback (`baracuda_dispatch`).
2468#[allow(clippy::too_many_arguments)]
2469pub fn qmatmul_cpu_by_type(
2470    quant_type: fuel_graph::QuantType,
2471    act_cpu: &fuel_cpu_backend::CpuStorageBytes,
2472    w_cpu: &fuel_cpu_backend::CpuStorageBytes,
2473    out_cpu: &mut fuel_cpu_backend::CpuStorageBytes,
2474    batch_count: usize,
2475    m: usize,
2476    n: usize,
2477    k: usize,
2478) -> Result<()> {
2479    use fuel_graph::QuantType;
2480    match quant_type {
2481        QuantType::Q4_0 => fuel_cpu_backend::byte_kernels::qmatmul_q4_0_f32(
2482            act_cpu,
2483            w_cpu,
2484            out_cpu,
2485            batch_count,
2486            m,
2487            n,
2488            k,
2489        ),
2490        QuantType::Q4_1 => fuel_cpu_backend::byte_kernels::qmatmul_q4_1_f32(
2491            act_cpu,
2492            w_cpu,
2493            out_cpu,
2494            batch_count,
2495            m,
2496            n,
2497            k,
2498        ),
2499        QuantType::Q5_0 => fuel_cpu_backend::byte_kernels::qmatmul_q5_0_f32(
2500            act_cpu,
2501            w_cpu,
2502            out_cpu,
2503            batch_count,
2504            m,
2505            n,
2506            k,
2507        ),
2508        QuantType::Q5_1 => fuel_cpu_backend::byte_kernels::qmatmul_q5_1_f32(
2509            act_cpu,
2510            w_cpu,
2511            out_cpu,
2512            batch_count,
2513            m,
2514            n,
2515            k,
2516        ),
2517        QuantType::Q8_0 => fuel_cpu_backend::byte_kernels::qmatmul_q8_0_f32(
2518            act_cpu,
2519            w_cpu,
2520            out_cpu,
2521            batch_count,
2522            m,
2523            n,
2524            k,
2525        ),
2526        QuantType::Q8_1 => fuel_cpu_backend::byte_kernels::qmatmul_q8_1_f32(
2527            act_cpu,
2528            w_cpu,
2529            out_cpu,
2530            batch_count,
2531            m,
2532            n,
2533            k,
2534        ),
2535        QuantType::Q2K => fuel_cpu_backend::byte_kernels::qmatmul_q2k_f32(
2536            act_cpu,
2537            w_cpu,
2538            out_cpu,
2539            batch_count,
2540            m,
2541            n,
2542            k,
2543        ),
2544        QuantType::Q3K => fuel_cpu_backend::byte_kernels::qmatmul_q3k_f32(
2545            act_cpu,
2546            w_cpu,
2547            out_cpu,
2548            batch_count,
2549            m,
2550            n,
2551            k,
2552        ),
2553        QuantType::Q4_K_M => fuel_cpu_backend::byte_kernels::qmatmul_q4_k_m_f32(
2554            act_cpu,
2555            w_cpu,
2556            out_cpu,
2557            batch_count,
2558            m,
2559            n,
2560            k,
2561        ),
2562        QuantType::Q5K => fuel_cpu_backend::byte_kernels::qmatmul_q5k_f32(
2563            act_cpu,
2564            w_cpu,
2565            out_cpu,
2566            batch_count,
2567            m,
2568            n,
2569            k,
2570        ),
2571        QuantType::Q6K => fuel_cpu_backend::byte_kernels::qmatmul_q6k_f32(
2572            act_cpu,
2573            w_cpu,
2574            out_cpu,
2575            batch_count,
2576            m,
2577            n,
2578            k,
2579        ),
2580        QuantType::Iq4Nl => fuel_cpu_backend::byte_kernels::qmatmul_iq4_nl_f32(
2581            act_cpu,
2582            w_cpu,
2583            out_cpu,
2584            batch_count,
2585            m,
2586            n,
2587            k,
2588        ),
2589        QuantType::Iq4Xs => fuel_cpu_backend::byte_kernels::qmatmul_iq4_xs_f32(
2590            act_cpu,
2591            w_cpu,
2592            out_cpu,
2593            batch_count,
2594            m,
2595            n,
2596            k,
2597        ),
2598        QuantType::Iq3S => fuel_cpu_backend::byte_kernels::qmatmul_iq3_s_f32(
2599            act_cpu,
2600            w_cpu,
2601            out_cpu,
2602            batch_count,
2603            m,
2604            n,
2605            k,
2606        ),
2607    }
2608}
2609
2610/// Dispatch wrapper for `(QMatMul, F32, Cpu)`. Two inputs:
2611/// activations (F32) and quantized weight bytes (U32-typed).
2612/// `OpParams::QMatMul` carries the quant_type + (batch, m, n, k);
2613/// the wrapper picks the right typed kernel based on quant_type.
2614///
2615/// `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the linear-quant fused
2616/// bundle's `qmatmul_cpu` `entry_point` symbol to this wrapper
2617/// (`CPU_FUSED_LINEAR_QUANT_ENTRY_POINTS`).
2618pub(crate) fn qmatmul_f32_cpu_wrapper(
2619    inputs: &[Arc<RwLock<Storage>>],
2620    outputs: &mut [Arc<RwLock<Storage>>],
2621    _layouts: &[Layout],
2622    params: &OpParams,
2623) -> Result<()> {
2624    if inputs.len() != 2 {
2625        return Err(Error::Msg(format!(
2626            "qmatmul wrapper expects 2 inputs (activations, weight_bytes), got {}",
2627            inputs.len(),
2628        ))
2629        .bt());
2630    }
2631    if outputs.len() != 1 {
2632        return Err(Error::Msg(format!(
2633            "qmatmul wrapper expects 1 output, got {}",
2634            outputs.len(),
2635        ))
2636        .bt());
2637    }
2638    let (quant_type, batch_count, m, n, k) = match params {
2639        OpParams::QMatMul {
2640            quant_type,
2641            batch_count,
2642            m,
2643            n,
2644            k,
2645        } => (*quant_type, *batch_count, *m, *n, *k),
2646        other => {
2647            return Err(Error::Msg(format!(
2648                "qmatmul wrapper expects OpParams::QMatMul, got {other:?}",
2649            ))
2650            .bt());
2651        }
2652    };
2653    let act_guard = read_storage(&inputs[0])?;
2654    let w_guard = read_storage(&inputs[1])?;
2655    if w_guard.dtype != DType::U32 {
2656        return Err(Error::Msg(format!(
2657            "qmatmul: weight bytes must be U32-typed (raw block stream), got {:?}",
2658            w_guard.dtype,
2659        ))
2660        .bt());
2661    }
2662    let mut out_guard = write_storage(&outputs[0])?;
2663    let act_cpu = cpu_input(&act_guard)?;
2664    let w_cpu = cpu_input(&w_guard)?;
2665    let out_cpu = cpu_output(&mut out_guard)?;
2666    qmatmul_cpu_by_type(quant_type, act_cpu, w_cpu, out_cpu, batch_count, m, n, k)
2667}
2668
2669/// Dispatch wrapper for `(WriteSlice, *, Cpu)`. Dtype-agnostic — the
2670/// underlying kernel is `write_slice_cpu(... dtype_size)`. The wrapper
2671/// reads dtype_size from the output (dest) Storage's dtype tag. Takes
2672/// 1 input (source) + 1 output (dest, mutated in place); the slab
2673/// offset rides in `OpParams::WriteSlice`. `pub(crate)` so the
2674/// shape-ops FKC contract can resolve its `write_slice_cpu` entry point
2675/// to this fn via [`crate::fkc::CPU_SHAPE_OPS_ENTRY_POINTS`].
2676pub(crate) fn write_slice_cpu_wrapper(
2677    inputs: &[Arc<RwLock<Storage>>],
2678    outputs: &mut [Arc<RwLock<Storage>>],
2679    _layouts: &[Layout],
2680    params: &OpParams,
2681) -> Result<()> {
2682    if inputs.len() != 1 || outputs.len() != 1 {
2683        return Err(Error::Msg(format!(
2684            "write_slice wrapper expects 1 input (source) + 1 output (dest), \
2685             got {} + {}",
2686            inputs.len(),
2687            outputs.len(),
2688        ))
2689        .bt());
2690    }
2691    let (dest_shape, ranges) = match params {
2692        OpParams::WriteSlice {
2693            dest_shape, ranges, ..
2694        } => (dest_shape, ranges),
2695        other => {
2696            return Err(Error::Msg(format!(
2697                "write_slice wrapper expects OpParams::WriteSlice, got {other:?}",
2698            ))
2699            .bt());
2700        }
2701    };
2702    let src_guard = read_storage(&inputs[0])?;
2703    let src_cpu = cpu_input(&src_guard)?;
2704    let mut dest_guard = write_storage(&outputs[0])?;
2705    let dtype_size = dest_guard.dtype.size_in_bytes();
2706    let dest_cpu = cpu_output(&mut dest_guard)?;
2707    fuel_cpu_backend::byte_kernels::write_slice_cpu(
2708        src_cpu, dest_cpu, dest_shape, ranges, dtype_size,
2709    )
2710}
2711
2712/// Dispatch wrapper for `(WriteSliceRotating, *, Cpu)`. Same shape
2713/// as `write_slice_cpu_wrapper` plus a second input carrying the
2714/// dynamic position scalar (a runtime U32 operand, NOT part of the
2715/// binding-table lookup key — see `build_lookup_dtypes`). `pub(crate)`
2716/// so the shape-ops FKC contract can resolve its
2717/// `write_slice_rotating_cpu` entry point to this fn via
2718/// [`crate::fkc::CPU_SHAPE_OPS_ENTRY_POINTS`].
2719pub(crate) fn write_slice_rotating_cpu_wrapper(
2720    inputs: &[Arc<RwLock<Storage>>],
2721    outputs: &mut [Arc<RwLock<Storage>>],
2722    _layouts: &[Layout],
2723    params: &OpParams,
2724) -> Result<()> {
2725    if inputs.len() != 2 || outputs.len() != 1 {
2726        return Err(Error::Msg(format!(
2727            "write_slice_rotating wrapper expects 2 inputs (source, position) + 1 output (dest), \
2728             got {} + {}",
2729            inputs.len(),
2730            outputs.len(),
2731        ))
2732        .bt());
2733    }
2734    let (dest_shape, axis, modulus, ranges) =
2735        match params {
2736            OpParams::WriteSliceRotating {
2737                dest_shape,
2738                axis,
2739                modulus,
2740                ranges,
2741            } => (dest_shape, *axis, *modulus, ranges),
2742            other => return Err(Error::Msg(format!(
2743                "write_slice_rotating wrapper expects OpParams::WriteSliceRotating, got {other:?}",
2744            ))
2745            .bt()),
2746        };
2747    let src_guard = read_storage(&inputs[0])?;
2748    let src_cpu = cpu_input(&src_guard)?;
2749    let pos_guard = read_storage(&inputs[1])?;
2750    let pos_cpu = cpu_input(&pos_guard)?;
2751    let mut dest_guard = write_storage(&outputs[0])?;
2752    let dtype_size = dest_guard.dtype.size_in_bytes();
2753    let dest_cpu = cpu_output(&mut dest_guard)?;
2754    fuel_cpu_backend::byte_kernels::write_slice_rotating_cpu(
2755        src_cpu, pos_cpu, dest_cpu, dest_shape, axis, modulus, ranges, dtype_size,
2756    )
2757}
2758
2759/// Dispatch wrapper for `(WriteSliceDoff, *, Cpu)`. Like
2760/// `write_slice_rotating_cpu_wrapper` but the second input is a
2761/// rank-0 `I64` offset (the device-resident start on `axis`; read
2762/// host-side here on CPU) and there is no modulus/wrap. `pub(crate)`
2763/// so the shape-ops FKC contract can resolve its `write_slice_doff_cpu`
2764/// entry point to this fn via [`crate::fkc::CPU_SHAPE_OPS_ENTRY_POINTS`].
2765pub(crate) fn write_slice_doff_cpu_wrapper(
2766    inputs: &[Arc<RwLock<Storage>>],
2767    outputs: &mut [Arc<RwLock<Storage>>],
2768    _layouts: &[Layout],
2769    params: &OpParams,
2770) -> Result<()> {
2771    if inputs.len() != 2 || outputs.len() != 1 {
2772        return Err(Error::Msg(format!(
2773            "write_slice_doff wrapper expects 2 inputs (source, offset) + 1 output (dest), \
2774             got {} + {}",
2775            inputs.len(),
2776            outputs.len(),
2777        ))
2778        .bt());
2779    }
2780    let (dest_shape, axis, ranges) = match params {
2781        OpParams::WriteSliceDoff {
2782            dest_shape,
2783            axis,
2784            ranges,
2785        } => (dest_shape, *axis, ranges),
2786        other => {
2787            return Err(Error::Msg(format!(
2788                "write_slice_doff wrapper expects OpParams::WriteSliceDoff, got {other:?}",
2789            ))
2790            .bt());
2791        }
2792    };
2793    let src_guard = read_storage(&inputs[0])?;
2794    let src_cpu = cpu_input(&src_guard)?;
2795    let off_guard = read_storage(&inputs[1])?;
2796    let off_cpu = cpu_input(&off_guard)?;
2797    let mut dest_guard = write_storage(&outputs[0])?;
2798    let dtype_size = dest_guard.dtype.size_in_bytes();
2799    let dest_cpu = cpu_output(&mut dest_guard)?;
2800    fuel_cpu_backend::byte_kernels::write_slice_doff_cpu(
2801        src_cpu, off_cpu, dest_cpu, dest_shape, axis, ranges, dtype_size,
2802    )
2803}
2804
2805pub(crate) fn concat_cpu_wrapper(
2806    inputs: &[Arc<RwLock<Storage>>],
2807    outputs: &mut [Arc<RwLock<Storage>>],
2808    _layouts: &[Layout],
2809    params: &OpParams,
2810) -> Result<()> {
2811    if inputs.is_empty() {
2812        return Err(Error::Msg("concat wrapper expects ≥ 1 input, got 0".to_string()).bt());
2813    }
2814    if outputs.len() != 1 {
2815        return Err(Error::Msg(format!(
2816            "concat wrapper expects 1 output, got {}",
2817            outputs.len(),
2818        ))
2819        .bt());
2820    }
2821    let (outer_count, input_dim_sizes, inner_count) = match params {
2822        OpParams::Concat {
2823            outer_count,
2824            input_dim_sizes,
2825            inner_count,
2826            ..
2827        } => (*outer_count, input_dim_sizes, *inner_count),
2828        other => {
2829            return Err(Error::Msg(format!(
2830                "concat wrapper expects OpParams::Concat, got {other:?}",
2831            ))
2832            .bt());
2833        }
2834    };
2835    if input_dim_sizes.len() != inputs.len() {
2836        return Err(Error::Msg(format!(
2837            "concat wrapper: OpParams declares {} inputs but the work item \
2838             carries {}",
2839            input_dim_sizes.len(),
2840            inputs.len(),
2841        ))
2842        .bt());
2843    }
2844    let in_guards: Vec<_> = inputs
2845        .iter()
2846        .map(read_storage)
2847        .collect::<Result<Vec<_>>>()?;
2848    let mut in_cpus: Vec<&fuel_cpu_backend::CpuStorageBytes> = Vec::with_capacity(in_guards.len());
2849    for g in &in_guards {
2850        in_cpus.push(cpu_input(g)?);
2851    }
2852    let mut out_guard = write_storage(&outputs[0])?;
2853    let dtype_size = out_guard.dtype.size_in_bytes();
2854    let out_cpu = cpu_output(&mut out_guard)?;
2855    fuel_cpu_backend::byte_kernels::concat_cpu(
2856        &in_cpus,
2857        out_cpu,
2858        outer_count,
2859        input_dim_sizes,
2860        inner_count,
2861        dtype_size,
2862    )
2863}
2864
2865/// Generate a CPU IndexAdd wrapper. Same shape across all dtypes;
2866/// only the underlying typed kernel differs.
2867macro_rules! cpu_index_add_wrapper {
2868    ($wrapper:ident, $kernel:path, $idx_ck:literal) => {
2869        // `pub(crate)` so the FKC `CpuLinkRegistry` (`fkc::cpu_link`) can bind
2870        // these symbols from the indexing contract.
2871        pub(crate) fn $wrapper(
2872            inputs: &[Arc<RwLock<Storage>>],
2873            outputs: &mut [Arc<RwLock<Storage>>],
2874            _layouts: &[Layout],
2875            params: &OpParams,
2876        ) -> Result<()> {
2877            if inputs.len() != 3 || outputs.len() != 1 {
2878                return Err(Error::Msg(format!(
2879                    "{}: expects 3 inputs + 1 output, got {} + {}",
2880                    $idx_ck,
2881                    inputs.len(),
2882                    outputs.len(),
2883                ))
2884                .bt());
2885            }
2886            let (outer_count, base_dim_size, n_indices, inner_count) = match params {
2887                OpParams::IndexAdd {
2888                    outer_count,
2889                    base_dim_size,
2890                    n_indices,
2891                    inner_count,
2892                } => (*outer_count, *base_dim_size, *n_indices, *inner_count),
2893                other => {
2894                    return Err(Error::Msg(format!(
2895                        "{}: expects OpParams::IndexAdd, got {other:?}",
2896                        $idx_ck,
2897                    ))
2898                    .bt())
2899                }
2900            };
2901            let base_guard = read_storage(&inputs[0])?;
2902            let idx_guard = read_storage(&inputs[1])?;
2903            if idx_guard.dtype != DType::U32 {
2904                return Err(Error::Msg(format!("{}: indices must be U32", $idx_ck,)).bt());
2905            }
2906            let src_guard = read_storage(&inputs[2])?;
2907            let mut out_guard = write_storage(&outputs[0])?;
2908            let base_cpu = cpu_input(&base_guard)?;
2909            let idx_cpu = cpu_input(&idx_guard)?;
2910            let src_cpu = cpu_input(&src_guard)?;
2911            let out_cpu = cpu_output(&mut out_guard)?;
2912            $kernel(
2913                base_cpu,
2914                idx_cpu,
2915                src_cpu,
2916                out_cpu,
2917                outer_count,
2918                base_dim_size,
2919                n_indices,
2920                inner_count,
2921            )
2922        }
2923    };
2924}
2925
2926cpu_index_add_wrapper!(
2927    index_add_f64_cpu_wrapper,
2928    fuel_cpu_backend::byte_kernels::index_add_f64,
2929    "index_add_f64"
2930);
2931cpu_index_add_wrapper!(
2932    index_add_bf16_cpu_wrapper,
2933    fuel_cpu_backend::byte_kernels::index_add_bf16,
2934    "index_add_bf16"
2935);
2936cpu_index_add_wrapper!(
2937    index_add_f16_cpu_wrapper,
2938    fuel_cpu_backend::byte_kernels::index_add_f16,
2939    "index_add_f16"
2940);
2941
2942/// Generate a CPU ScatterAdd wrapper.
2943macro_rules! cpu_scatter_add_wrapper {
2944    ($wrapper:ident, $kernel:path, $name_str:literal) => {
2945        // `pub(crate)` so the FKC `CpuLinkRegistry` can bind these symbols.
2946        pub(crate) fn $wrapper(
2947            inputs: &[Arc<RwLock<Storage>>],
2948            outputs: &mut [Arc<RwLock<Storage>>],
2949            _layouts: &[Layout],
2950            params: &OpParams,
2951        ) -> Result<()> {
2952            if inputs.len() != 3 || outputs.len() != 1 {
2953                return Err(Error::Msg(format!(
2954                    "{}: expects 3 inputs + 1 output, got {} + {}",
2955                    $name_str,
2956                    inputs.len(),
2957                    outputs.len(),
2958                ))
2959                .bt());
2960            }
2961            let (base_shape, src_shape, dim) = match params {
2962                OpParams::ScatterAdd {
2963                    base_shape,
2964                    src_shape,
2965                    dim,
2966                } => (base_shape, src_shape, *dim),
2967                other => {
2968                    return Err(Error::Msg(format!(
2969                        "{}: expects OpParams::ScatterAdd, got {other:?}",
2970                        $name_str,
2971                    ))
2972                    .bt())
2973                }
2974            };
2975            let base_guard = read_storage(&inputs[0])?;
2976            let idx_guard = read_storage(&inputs[1])?;
2977            if idx_guard.dtype != DType::U32 {
2978                return Err(Error::Msg(format!("{}: indices must be U32", $name_str,)).bt());
2979            }
2980            let src_guard = read_storage(&inputs[2])?;
2981            let mut out_guard = write_storage(&outputs[0])?;
2982            let base_cpu = cpu_input(&base_guard)?;
2983            let idx_cpu = cpu_input(&idx_guard)?;
2984            let src_cpu = cpu_input(&src_guard)?;
2985            let out_cpu = cpu_output(&mut out_guard)?;
2986            $kernel(
2987                base_cpu, idx_cpu, src_cpu, out_cpu, base_shape, src_shape, dim,
2988            )
2989        }
2990    };
2991}
2992
2993cpu_scatter_add_wrapper!(
2994    scatter_add_f64_cpu_wrapper,
2995    fuel_cpu_backend::byte_kernels::scatter_add_f64,
2996    "scatter_add_f64"
2997);
2998cpu_scatter_add_wrapper!(
2999    scatter_add_bf16_cpu_wrapper,
3000    fuel_cpu_backend::byte_kernels::scatter_add_bf16,
3001    "scatter_add_bf16"
3002);
3003cpu_scatter_add_wrapper!(
3004    scatter_add_f16_cpu_wrapper,
3005    fuel_cpu_backend::byte_kernels::scatter_add_f16,
3006    "scatter_add_f16"
3007);
3008
3009/// Build a CPU Affine wrapper for any element type. Cast from f64
3010/// scalars in OpParams::Affine to the target arithmetic type
3011/// happens inside the macro (different cast for f64 vs half).
3012macro_rules! cpu_affine_wrapper_native {
3013    ($wrapper:ident, $kernel:path, $T:ty) => {
3014        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3015        // real production wrapper for the affine-clamp-powi contract import.
3016        pub(crate) fn $wrapper(
3017            inputs: &[Arc<RwLock<Storage>>],
3018            outputs: &mut [Arc<RwLock<Storage>>],
3019            _layouts: &[Layout],
3020            params: &OpParams,
3021        ) -> Result<()> {
3022            if inputs.len() != 1 || outputs.len() != 1 {
3023                return Err(Error::Msg("affine: 1 input + 1 output".to_string()).bt());
3024            }
3025            let (mul, add) = match params {
3026                OpParams::Affine { mul, add } => (*mul as $T, *add as $T),
3027                other => return Err(Error::Msg(format!("affine: bad params {other:?}")).bt()),
3028            };
3029            let in_guard = read_storage(&inputs[0])?;
3030            let mut out_guard = write_storage(&outputs[0])?;
3031            let in_cpu = cpu_input(&in_guard)?;
3032            let out_cpu = cpu_output(&mut out_guard)?;
3033            $kernel(in_cpu, out_cpu, mul, add)
3034        }
3035    };
3036}
3037
3038cpu_affine_wrapper_native!(
3039    affine_f64_cpu_wrapper,
3040    fuel_cpu_backend::byte_kernels::affine_f64,
3041    f64
3042);
3043
3044macro_rules! cpu_affine_wrapper_half {
3045    ($wrapper:ident, $kernel:path) => {
3046        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3047        // real production wrapper for the affine-clamp-powi contract import.
3048        pub(crate) fn $wrapper(
3049            inputs: &[Arc<RwLock<Storage>>],
3050            outputs: &mut [Arc<RwLock<Storage>>],
3051            _layouts: &[Layout],
3052            params: &OpParams,
3053        ) -> Result<()> {
3054            if inputs.len() != 1 || outputs.len() != 1 {
3055                return Err(Error::Msg("affine: 1 input + 1 output".to_string()).bt());
3056            }
3057            let (mul, add) = match params {
3058                OpParams::Affine { mul, add } => (*mul as f32, *add as f32),
3059                other => return Err(Error::Msg(format!("affine: bad params {other:?}")).bt()),
3060            };
3061            let in_guard = read_storage(&inputs[0])?;
3062            let mut out_guard = write_storage(&outputs[0])?;
3063            let in_cpu = cpu_input(&in_guard)?;
3064            let out_cpu = cpu_output(&mut out_guard)?;
3065            $kernel(in_cpu, out_cpu, mul, add)
3066        }
3067    };
3068}
3069
3070cpu_affine_wrapper_half!(
3071    affine_bf16_cpu_wrapper,
3072    fuel_cpu_backend::byte_kernels::affine_bf16
3073);
3074cpu_affine_wrapper_half!(
3075    affine_f16_cpu_wrapper,
3076    fuel_cpu_backend::byte_kernels::affine_f16
3077);
3078
3079macro_rules! cpu_clamp_wrapper {
3080    ($wrapper:ident, $kernel:path, $T:ty) => {
3081        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3082        // real production wrapper for the affine-clamp-powi contract import.
3083        pub(crate) fn $wrapper(
3084            inputs: &[Arc<RwLock<Storage>>],
3085            outputs: &mut [Arc<RwLock<Storage>>],
3086            _layouts: &[Layout],
3087            params: &OpParams,
3088        ) -> Result<()> {
3089            if inputs.len() != 1 || outputs.len() != 1 {
3090                return Err(Error::Msg("clamp: 1 input + 1 output".to_string()).bt());
3091            }
3092            let (min, max) = match params {
3093                OpParams::Clamp { min, max } => (*min as $T, *max as $T),
3094                other => return Err(Error::Msg(format!("clamp: bad params {other:?}")).bt()),
3095            };
3096            let in_guard = read_storage(&inputs[0])?;
3097            let mut out_guard = write_storage(&outputs[0])?;
3098            let in_cpu = cpu_input(&in_guard)?;
3099            let out_cpu = cpu_output(&mut out_guard)?;
3100            $kernel(in_cpu, out_cpu, min, max)
3101        }
3102    };
3103}
3104
3105cpu_clamp_wrapper!(
3106    clamp_f64_cpu_wrapper,
3107    fuel_cpu_backend::byte_kernels::clamp_f64,
3108    f64
3109);
3110cpu_clamp_wrapper!(
3111    clamp_bf16_cpu_wrapper,
3112    fuel_cpu_backend::byte_kernels::clamp_bf16,
3113    f32
3114);
3115cpu_clamp_wrapper!(
3116    clamp_f16_cpu_wrapper,
3117    fuel_cpu_backend::byte_kernels::clamp_f16,
3118    f32
3119);
3120
3121macro_rules! cpu_powi_wrapper {
3122    ($wrapper:ident, $kernel:path) => {
3123        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3124        // real production wrapper for the affine-clamp-powi contract import.
3125        pub(crate) fn $wrapper(
3126            inputs: &[Arc<RwLock<Storage>>],
3127            outputs: &mut [Arc<RwLock<Storage>>],
3128            _layouts: &[Layout],
3129            params: &OpParams,
3130        ) -> Result<()> {
3131            if inputs.len() != 1 || outputs.len() != 1 {
3132                return Err(Error::Msg("powi: 1 input + 1 output".to_string()).bt());
3133            }
3134            let exp = match params {
3135                OpParams::PowI { exp } => *exp,
3136                other => return Err(Error::Msg(format!("powi: bad params {other:?}")).bt()),
3137            };
3138            let in_guard = read_storage(&inputs[0])?;
3139            let mut out_guard = write_storage(&outputs[0])?;
3140            let in_cpu = cpu_input(&in_guard)?;
3141            let out_cpu = cpu_output(&mut out_guard)?;
3142            $kernel(in_cpu, out_cpu, exp)
3143        }
3144    };
3145}
3146
3147cpu_powi_wrapper!(
3148    powi_f64_cpu_wrapper,
3149    fuel_cpu_backend::byte_kernels::powi_f64
3150);
3151cpu_powi_wrapper!(
3152    powi_bf16_cpu_wrapper,
3153    fuel_cpu_backend::byte_kernels::powi_bf16
3154);
3155cpu_powi_wrapper!(
3156    powi_f16_cpu_wrapper,
3157    fuel_cpu_backend::byte_kernels::powi_f16
3158);
3159
3160// ArgMax/ArgMin per-input-dtype wrappers. The existing
3161// `cpu_arg_dim_wrapper!` macro hardcodes F32 input — generalize it
3162// for non-F32 input dtypes.
3163macro_rules! cpu_arg_dim_wrapper_typed {
3164    ($wrapper:ident, $kernel:path, $expected_in_dtype:expr, $op_name:literal) => {
3165        fn $wrapper(
3166            inputs: &[Arc<RwLock<Storage>>],
3167            outputs: &mut [Arc<RwLock<Storage>>],
3168            layouts: &[Layout],
3169            params: &OpParams,
3170        ) -> Result<()> {
3171            if inputs.len() != 1 || outputs.len() != 1 {
3172                return Err(Error::Msg(format!("{}: 1 input + 1 output", $op_name,)).bt());
3173            }
3174            let dims = match params {
3175                OpParams::Reduce { dims, .. } => dims,
3176                other => {
3177                    return Err(Error::Msg(format!(
3178                        "{}: expects OpParams::Reduce, got {other:?}",
3179                        $op_name,
3180                    ))
3181                    .bt())
3182                }
3183            };
3184            if dims.len() != 1 {
3185                return Err(Error::Msg(format!(
3186                    "{}: expects exactly 1 reduce dim, got {dims:?}",
3187                    $op_name,
3188                ))
3189                .bt());
3190            }
3191            let dim = dims[0];
3192            let input_layout = layouts.first().ok_or_else(|| {
3193                Error::Msg(format!(
3194                    "{}: layouts empty (executor must pass input layout at [0])",
3195                    $op_name,
3196                ))
3197                .bt()
3198            })?;
3199            let in_guard = read_storage(&inputs[0])?;
3200            if in_guard.dtype != $expected_in_dtype {
3201                return Err(Error::Msg(format!(
3202                    "{}: expects input dtype {:?}, got {:?}",
3203                    $op_name, $expected_in_dtype, in_guard.dtype,
3204                ))
3205                .bt());
3206            }
3207            let mut out_guard = write_storage(&outputs[0])?;
3208            let in_cpu = cpu_input(&in_guard)?;
3209            let out_cpu = cpu_output(&mut out_guard)?;
3210            $kernel(in_cpu, out_cpu, input_layout.shape().dims(), dim)
3211        }
3212    };
3213}
3214
3215// New ArgMax/ArgMin entries are keyed on output U32 like the
3216// existing ones, but we need separate wrappers per input dtype.
3217// Use a dispatch macro that combines them.
3218fn argmax_dim_u32_cpu_dispatch(
3219    inputs: &[Arc<RwLock<Storage>>],
3220    outputs: &mut [Arc<RwLock<Storage>>],
3221    _layouts: &[Layout],
3222    params: &OpParams,
3223) -> Result<()> {
3224    let in_dtype = read_storage(&inputs[0])?.dtype;
3225    match in_dtype {
3226        DType::F32 => argmax_dim_u32_cpu_wrapper(inputs, outputs, _layouts, params),
3227        DType::F64 => argmax_dim_f64_only_wrapper(inputs, outputs, _layouts, params),
3228        DType::BF16 => argmax_dim_bf16_only_wrapper(inputs, outputs, _layouts, params),
3229        DType::F16 => argmax_dim_f16_only_wrapper(inputs, outputs, _layouts, params),
3230        other => Err(Error::Msg(format!("argmax_dim: unsupported input dtype {other:?}",)).bt()),
3231    }
3232}
3233
3234fn argmin_dim_u32_cpu_dispatch(
3235    inputs: &[Arc<RwLock<Storage>>],
3236    outputs: &mut [Arc<RwLock<Storage>>],
3237    _layouts: &[Layout],
3238    params: &OpParams,
3239) -> Result<()> {
3240    let in_dtype = read_storage(&inputs[0])?.dtype;
3241    match in_dtype {
3242        DType::F32 => argmin_dim_u32_cpu_wrapper(inputs, outputs, _layouts, params),
3243        DType::F64 => argmin_dim_f64_only_wrapper(inputs, outputs, _layouts, params),
3244        DType::BF16 => argmin_dim_bf16_only_wrapper(inputs, outputs, _layouts, params),
3245        DType::F16 => argmin_dim_f16_only_wrapper(inputs, outputs, _layouts, params),
3246        other => Err(Error::Msg(format!("argmin_dim: unsupported input dtype {other:?}",)).bt()),
3247    }
3248}
3249
3250cpu_arg_dim_wrapper_typed!(
3251    argmax_dim_f64_only_wrapper,
3252    fuel_cpu_backend::byte_kernels::argmax_dim_f64,
3253    DType::F64,
3254    "argmax_dim_f64"
3255);
3256cpu_arg_dim_wrapper_typed!(
3257    argmin_dim_f64_only_wrapper,
3258    fuel_cpu_backend::byte_kernels::argmin_dim_f64,
3259    DType::F64,
3260    "argmin_dim_f64"
3261);
3262cpu_arg_dim_wrapper_typed!(
3263    argmax_dim_bf16_only_wrapper,
3264    fuel_cpu_backend::byte_kernels::argmax_dim_bf16,
3265    DType::BF16,
3266    "argmax_dim_bf16"
3267);
3268cpu_arg_dim_wrapper_typed!(
3269    argmin_dim_bf16_only_wrapper,
3270    fuel_cpu_backend::byte_kernels::argmin_dim_bf16,
3271    DType::BF16,
3272    "argmin_dim_bf16"
3273);
3274cpu_arg_dim_wrapper_typed!(
3275    argmax_dim_f16_only_wrapper,
3276    fuel_cpu_backend::byte_kernels::argmax_dim_f16,
3277    DType::F16,
3278    "argmax_dim_f16"
3279);
3280cpu_arg_dim_wrapper_typed!(
3281    argmin_dim_f16_only_wrapper,
3282    fuel_cpu_backend::byte_kernels::argmin_dim_f16,
3283    DType::F16,
3284    "argmin_dim_f16"
3285);
3286
3287/// Dispatch wrapper for `(Affine, F32, Cpu)`. Extracts scalar
3288/// coefficients from `OpParams::Affine`.
3289pub(crate) fn affine_f32_cpu_wrapper(
3290    inputs: &[Arc<RwLock<Storage>>],
3291    outputs: &mut [Arc<RwLock<Storage>>],
3292    _layouts: &[Layout],
3293    params: &OpParams,
3294) -> Result<()> {
3295    if inputs.len() != 1 || outputs.len() != 1 {
3296        return Err(Error::Msg(format!(
3297            "affine wrapper expects 1 input + 1 output, got {} + {}",
3298            inputs.len(),
3299            outputs.len(),
3300        ))
3301        .bt());
3302    }
3303    let (mul, add) = match params {
3304        OpParams::Affine { mul, add } => (*mul as f32, *add as f32),
3305        other => {
3306            return Err(Error::Msg(format!(
3307                "affine wrapper expects OpParams::Affine, got {other:?}",
3308            ))
3309            .bt());
3310        }
3311    };
3312    let in_guard = read_storage(&inputs[0])?;
3313    let mut out_guard = write_storage(&outputs[0])?;
3314    let in_cpu = cpu_input(&in_guard)?;
3315    let out_cpu = cpu_output(&mut out_guard)?;
3316    fuel_cpu_backend::byte_kernels::affine_f32(in_cpu, out_cpu, mul, add)
3317}
3318
3319/// Dispatch wrapper macro for in-place affine on CPU. Inputs is
3320/// empty (the executor's `WorkItemKind::InplaceKernel` arm passes the
3321/// target Arc as `outputs[0]`); the kernel reads + writes through the
3322/// single write lock.
3323macro_rules! cpu_affine_inplace_wrapper {
3324    ($name:ident, $kernel:ident, $T:ty) => {
3325        pub(crate) fn $name(
3326            inputs: &[Arc<RwLock<Storage>>],
3327            outputs: &mut [Arc<RwLock<Storage>>],
3328            _layouts: &[Layout],
3329            params: &OpParams,
3330        ) -> Result<()> {
3331            if !inputs.is_empty() || outputs.len() != 1 {
3332                return Err(Error::Msg(format!(
3333                    concat!(
3334                        stringify!($name),
3335                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3336                    ),
3337                    inputs.len(),
3338                    outputs.len(),
3339                ))
3340                .bt());
3341            }
3342            let (mul, add) = match params {
3343                OpParams::Affine { mul, add } => (*mul as $T, *add as $T),
3344                other => {
3345                    return Err(Error::Msg(format!(
3346                        concat!(stringify!($name), ": expected OpParams::Affine, got {:?}"),
3347                        other,
3348                    ))
3349                    .bt())
3350                }
3351            };
3352            let mut out_guard = write_storage(&outputs[0])?;
3353            let out_cpu = cpu_output(&mut out_guard)?;
3354            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, mul, add)
3355        }
3356    };
3357    ($name:ident, $kernel:ident, $T:ty, half) => {
3358        pub(crate) fn $name(
3359            inputs: &[Arc<RwLock<Storage>>],
3360            outputs: &mut [Arc<RwLock<Storage>>],
3361            _layouts: &[Layout],
3362            params: &OpParams,
3363        ) -> Result<()> {
3364            if !inputs.is_empty() || outputs.len() != 1 {
3365                return Err(Error::Msg(format!(
3366                    concat!(
3367                        stringify!($name),
3368                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3369                    ),
3370                    inputs.len(),
3371                    outputs.len(),
3372                ))
3373                .bt());
3374            }
3375            let (mul, add) = match params {
3376                OpParams::Affine { mul, add } => (*mul, *add),
3377                other => {
3378                    return Err(Error::Msg(format!(
3379                        concat!(stringify!($name), ": expected OpParams::Affine, got {:?}"),
3380                        other,
3381                    ))
3382                    .bt())
3383                }
3384            };
3385            let mut out_guard = write_storage(&outputs[0])?;
3386            let out_cpu = cpu_output(&mut out_guard)?;
3387            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, mul, add)
3388        }
3389    };
3390}
3391
3392cpu_affine_inplace_wrapper!(inplace_affine_f32_cpu_wrapper, affine_inplace_f32, f32);
3393cpu_affine_inplace_wrapper!(inplace_affine_f64_cpu_wrapper, affine_inplace_f64, f64);
3394cpu_affine_inplace_wrapper!(
3395    inplace_affine_bf16_cpu_wrapper,
3396    affine_inplace_bf16,
3397    f64,
3398    half
3399);
3400cpu_affine_inplace_wrapper!(
3401    inplace_affine_f16_cpu_wrapper,
3402    affine_inplace_f16,
3403    f64,
3404    half
3405);
3406
3407/// Dispatch wrapper macro for in-place clamp on CPU. Same shape as
3408/// `cpu_affine_inplace_wrapper!` (no inputs, target as outputs[0]),
3409/// but pulls `(min, max)` from `OpParams::Clamp`.
3410macro_rules! cpu_clamp_inplace_wrapper {
3411    ($name:ident, $kernel:ident, $T:ty) => {
3412        pub(crate) fn $name(
3413            inputs: &[Arc<RwLock<Storage>>],
3414            outputs: &mut [Arc<RwLock<Storage>>],
3415            _layouts: &[Layout],
3416            params: &OpParams,
3417        ) -> Result<()> {
3418            if !inputs.is_empty() || outputs.len() != 1 {
3419                return Err(Error::Msg(format!(
3420                    concat!(
3421                        stringify!($name),
3422                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3423                    ),
3424                    inputs.len(),
3425                    outputs.len(),
3426                ))
3427                .bt());
3428            }
3429            let (min, max) = match params {
3430                OpParams::Clamp { min, max } => (*min as $T, *max as $T),
3431                other => {
3432                    return Err(Error::Msg(format!(
3433                        concat!(stringify!($name), ": expected OpParams::Clamp, got {:?}"),
3434                        other,
3435                    ))
3436                    .bt())
3437                }
3438            };
3439            let mut out_guard = write_storage(&outputs[0])?;
3440            let out_cpu = cpu_output(&mut out_guard)?;
3441            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, min, max)
3442        }
3443    };
3444    ($name:ident, $kernel:ident, $T:ty, half) => {
3445        pub(crate) fn $name(
3446            inputs: &[Arc<RwLock<Storage>>],
3447            outputs: &mut [Arc<RwLock<Storage>>],
3448            _layouts: &[Layout],
3449            params: &OpParams,
3450        ) -> Result<()> {
3451            if !inputs.is_empty() || outputs.len() != 1 {
3452                return Err(Error::Msg(format!(
3453                    concat!(
3454                        stringify!($name),
3455                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3456                    ),
3457                    inputs.len(),
3458                    outputs.len(),
3459                ))
3460                .bt());
3461            }
3462            let (min, max) = match params {
3463                OpParams::Clamp { min, max } => (*min, *max),
3464                other => {
3465                    return Err(Error::Msg(format!(
3466                        concat!(stringify!($name), ": expected OpParams::Clamp, got {:?}"),
3467                        other,
3468                    ))
3469                    .bt())
3470                }
3471            };
3472            let mut out_guard = write_storage(&outputs[0])?;
3473            let out_cpu = cpu_output(&mut out_guard)?;
3474            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, min, max)
3475        }
3476    };
3477}
3478
3479cpu_clamp_inplace_wrapper!(clamp_inplace_f32_cpu_wrapper, clamp_inplace_f32, f32);
3480cpu_clamp_inplace_wrapper!(clamp_inplace_f64_cpu_wrapper, clamp_inplace_f64, f64);
3481cpu_clamp_inplace_wrapper!(
3482    clamp_inplace_bf16_cpu_wrapper,
3483    clamp_inplace_bf16,
3484    f64,
3485    half
3486);
3487cpu_clamp_inplace_wrapper!(clamp_inplace_f16_cpu_wrapper, clamp_inplace_f16, f64, half);
3488
3489/// Dispatch wrapper macro for in-place powi on CPU. Pulls `exp` from
3490/// `OpParams::PowI`.
3491macro_rules! cpu_powi_inplace_wrapper {
3492    ($name:ident, $kernel:ident) => {
3493        pub(crate) fn $name(
3494            inputs: &[Arc<RwLock<Storage>>],
3495            outputs: &mut [Arc<RwLock<Storage>>],
3496            _layouts: &[Layout],
3497            params: &OpParams,
3498        ) -> Result<()> {
3499            if !inputs.is_empty() || outputs.len() != 1 {
3500                return Err(Error::Msg(format!(
3501                    concat!(
3502                        stringify!($name),
3503                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3504                    ),
3505                    inputs.len(),
3506                    outputs.len(),
3507                ))
3508                .bt());
3509            }
3510            let exp = match params {
3511                OpParams::PowI { exp } => *exp,
3512                other => {
3513                    return Err(Error::Msg(format!(
3514                        concat!(stringify!($name), ": expected OpParams::PowI, got {:?}"),
3515                        other,
3516                    ))
3517                    .bt())
3518                }
3519            };
3520            let mut out_guard = write_storage(&outputs[0])?;
3521            let out_cpu = cpu_output(&mut out_guard)?;
3522            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, exp)
3523        }
3524    };
3525}
3526
3527cpu_powi_inplace_wrapper!(powi_inplace_f32_cpu_wrapper, powi_inplace_f32);
3528cpu_powi_inplace_wrapper!(powi_inplace_f64_cpu_wrapper, powi_inplace_f64);
3529cpu_powi_inplace_wrapper!(powi_inplace_bf16_cpu_wrapper, powi_inplace_bf16);
3530cpu_powi_inplace_wrapper!(powi_inplace_f16_cpu_wrapper, powi_inplace_f16);
3531
3532/// Dispatch wrapper macro for in-place elementwise unary ops on CPU.
3533/// Same shape as `cpu_affine_inplace_wrapper!` (inputs empty, target
3534/// adopted as outputs[0] by the executor), but the kernel takes no
3535/// scalar params — just the target buffer.
3536macro_rules! cpu_unary_inplace_wrapper {
3537    ($name:ident, $kernel:ident) => {
3538        pub(crate) fn $name(
3539            inputs: &[Arc<RwLock<Storage>>],
3540            outputs: &mut [Arc<RwLock<Storage>>],
3541            _layouts: &[Layout],
3542            _params: &OpParams,
3543        ) -> Result<()> {
3544            if !inputs.is_empty() || outputs.len() != 1 {
3545                return Err(Error::Msg(format!(
3546                    concat!(
3547                        stringify!($name),
3548                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3549                    ),
3550                    inputs.len(),
3551                    outputs.len(),
3552                ))
3553                .bt());
3554            }
3555            let mut out_guard = write_storage(&outputs[0])?;
3556            let out_cpu = cpu_output(&mut out_guard)?;
3557            fuel_cpu_backend::byte_kernels::$kernel(out_cpu)
3558        }
3559    };
3560}
3561
3562cpu_unary_inplace_wrapper!(relu_inplace_f32_cpu_wrapper, relu_inplace_f32);
3563cpu_unary_inplace_wrapper!(silu_inplace_f32_cpu_wrapper, silu_inplace_f32);
3564cpu_unary_inplace_wrapper!(gelu_inplace_f32_cpu_wrapper, gelu_inplace_f32);
3565cpu_unary_inplace_wrapper!(tanh_inplace_f32_cpu_wrapper, tanh_inplace_f32);
3566cpu_unary_inplace_wrapper!(sigmoid_inplace_f32_cpu_wrapper, sigmoid_inplace_f32);
3567
3568cpu_unary_inplace_wrapper!(relu_inplace_f64_cpu_wrapper, relu_inplace_f64);
3569cpu_unary_inplace_wrapper!(silu_inplace_f64_cpu_wrapper, silu_inplace_f64);
3570cpu_unary_inplace_wrapper!(gelu_inplace_f64_cpu_wrapper, gelu_inplace_f64);
3571cpu_unary_inplace_wrapper!(tanh_inplace_f64_cpu_wrapper, tanh_inplace_f64);
3572cpu_unary_inplace_wrapper!(sigmoid_inplace_f64_cpu_wrapper, sigmoid_inplace_f64);
3573
3574cpu_unary_inplace_wrapper!(relu_inplace_bf16_cpu_wrapper, relu_inplace_bf16);
3575cpu_unary_inplace_wrapper!(silu_inplace_bf16_cpu_wrapper, silu_inplace_bf16);
3576cpu_unary_inplace_wrapper!(gelu_inplace_bf16_cpu_wrapper, gelu_inplace_bf16);
3577cpu_unary_inplace_wrapper!(tanh_inplace_bf16_cpu_wrapper, tanh_inplace_bf16);
3578cpu_unary_inplace_wrapper!(sigmoid_inplace_bf16_cpu_wrapper, sigmoid_inplace_bf16);
3579
3580cpu_unary_inplace_wrapper!(relu_inplace_f16_cpu_wrapper, relu_inplace_f16);
3581cpu_unary_inplace_wrapper!(silu_inplace_f16_cpu_wrapper, silu_inplace_f16);
3582cpu_unary_inplace_wrapper!(gelu_inplace_f16_cpu_wrapper, gelu_inplace_f16);
3583cpu_unary_inplace_wrapper!(tanh_inplace_f16_cpu_wrapper, tanh_inplace_f16);
3584cpu_unary_inplace_wrapper!(sigmoid_inplace_f16_cpu_wrapper, sigmoid_inplace_f16);
3585
3586// In-place unary op family expansion (2026-05-30) — 16 new ops × 4
3587// dtypes. Each wrapper is identical in shape to the original 5-op
3588// starter set; the chassis handles per-dtype math.
3589cpu_unary_inplace_wrapper!(neg_inplace_f32_cpu_wrapper, neg_inplace_f32);
3590cpu_unary_inplace_wrapper!(neg_inplace_f64_cpu_wrapper, neg_inplace_f64);
3591cpu_unary_inplace_wrapper!(neg_inplace_bf16_cpu_wrapper, neg_inplace_bf16);
3592cpu_unary_inplace_wrapper!(neg_inplace_f16_cpu_wrapper, neg_inplace_f16);
3593
3594cpu_unary_inplace_wrapper!(abs_inplace_f32_cpu_wrapper, abs_inplace_f32);
3595cpu_unary_inplace_wrapper!(abs_inplace_f64_cpu_wrapper, abs_inplace_f64);
3596cpu_unary_inplace_wrapper!(abs_inplace_bf16_cpu_wrapper, abs_inplace_bf16);
3597cpu_unary_inplace_wrapper!(abs_inplace_f16_cpu_wrapper, abs_inplace_f16);
3598
3599cpu_unary_inplace_wrapper!(sqr_inplace_f32_cpu_wrapper, sqr_inplace_f32);
3600cpu_unary_inplace_wrapper!(sqr_inplace_f64_cpu_wrapper, sqr_inplace_f64);
3601cpu_unary_inplace_wrapper!(sqr_inplace_bf16_cpu_wrapper, sqr_inplace_bf16);
3602cpu_unary_inplace_wrapper!(sqr_inplace_f16_cpu_wrapper, sqr_inplace_f16);
3603
3604cpu_unary_inplace_wrapper!(sqrt_inplace_f32_cpu_wrapper, sqrt_inplace_f32);
3605cpu_unary_inplace_wrapper!(sqrt_inplace_f64_cpu_wrapper, sqrt_inplace_f64);
3606cpu_unary_inplace_wrapper!(sqrt_inplace_bf16_cpu_wrapper, sqrt_inplace_bf16);
3607cpu_unary_inplace_wrapper!(sqrt_inplace_f16_cpu_wrapper, sqrt_inplace_f16);
3608
3609cpu_unary_inplace_wrapper!(rsqrt_inplace_f32_cpu_wrapper, rsqrt_inplace_f32);
3610cpu_unary_inplace_wrapper!(rsqrt_inplace_f64_cpu_wrapper, rsqrt_inplace_f64);
3611cpu_unary_inplace_wrapper!(rsqrt_inplace_bf16_cpu_wrapper, rsqrt_inplace_bf16);
3612cpu_unary_inplace_wrapper!(rsqrt_inplace_f16_cpu_wrapper, rsqrt_inplace_f16);
3613
3614cpu_unary_inplace_wrapper!(recip_inplace_f32_cpu_wrapper, recip_inplace_f32);
3615cpu_unary_inplace_wrapper!(recip_inplace_f64_cpu_wrapper, recip_inplace_f64);
3616cpu_unary_inplace_wrapper!(recip_inplace_bf16_cpu_wrapper, recip_inplace_bf16);
3617cpu_unary_inplace_wrapper!(recip_inplace_f16_cpu_wrapper, recip_inplace_f16);
3618
3619cpu_unary_inplace_wrapper!(exp_inplace_f32_cpu_wrapper, exp_inplace_f32);
3620cpu_unary_inplace_wrapper!(exp_inplace_f64_cpu_wrapper, exp_inplace_f64);
3621cpu_unary_inplace_wrapper!(exp_inplace_bf16_cpu_wrapper, exp_inplace_bf16);
3622cpu_unary_inplace_wrapper!(exp_inplace_f16_cpu_wrapper, exp_inplace_f16);
3623
3624cpu_unary_inplace_wrapper!(log_inplace_f32_cpu_wrapper, log_inplace_f32);
3625cpu_unary_inplace_wrapper!(log_inplace_f64_cpu_wrapper, log_inplace_f64);
3626cpu_unary_inplace_wrapper!(log_inplace_bf16_cpu_wrapper, log_inplace_bf16);
3627cpu_unary_inplace_wrapper!(log_inplace_f16_cpu_wrapper, log_inplace_f16);
3628
3629cpu_unary_inplace_wrapper!(sin_inplace_f32_cpu_wrapper, sin_inplace_f32);
3630cpu_unary_inplace_wrapper!(sin_inplace_f64_cpu_wrapper, sin_inplace_f64);
3631cpu_unary_inplace_wrapper!(sin_inplace_bf16_cpu_wrapper, sin_inplace_bf16);
3632cpu_unary_inplace_wrapper!(sin_inplace_f16_cpu_wrapper, sin_inplace_f16);
3633
3634cpu_unary_inplace_wrapper!(cos_inplace_f32_cpu_wrapper, cos_inplace_f32);
3635cpu_unary_inplace_wrapper!(cos_inplace_f64_cpu_wrapper, cos_inplace_f64);
3636cpu_unary_inplace_wrapper!(cos_inplace_bf16_cpu_wrapper, cos_inplace_bf16);
3637cpu_unary_inplace_wrapper!(cos_inplace_f16_cpu_wrapper, cos_inplace_f16);
3638
3639cpu_unary_inplace_wrapper!(sign_inplace_f32_cpu_wrapper, sign_inplace_f32);
3640cpu_unary_inplace_wrapper!(sign_inplace_f64_cpu_wrapper, sign_inplace_f64);
3641cpu_unary_inplace_wrapper!(sign_inplace_bf16_cpu_wrapper, sign_inplace_bf16);
3642cpu_unary_inplace_wrapper!(sign_inplace_f16_cpu_wrapper, sign_inplace_f16);
3643
3644cpu_unary_inplace_wrapper!(floor_inplace_f32_cpu_wrapper, floor_inplace_f32);
3645cpu_unary_inplace_wrapper!(floor_inplace_f64_cpu_wrapper, floor_inplace_f64);
3646cpu_unary_inplace_wrapper!(floor_inplace_bf16_cpu_wrapper, floor_inplace_bf16);
3647cpu_unary_inplace_wrapper!(floor_inplace_f16_cpu_wrapper, floor_inplace_f16);
3648
3649cpu_unary_inplace_wrapper!(ceil_inplace_f32_cpu_wrapper, ceil_inplace_f32);
3650cpu_unary_inplace_wrapper!(ceil_inplace_f64_cpu_wrapper, ceil_inplace_f64);
3651cpu_unary_inplace_wrapper!(ceil_inplace_bf16_cpu_wrapper, ceil_inplace_bf16);
3652cpu_unary_inplace_wrapper!(ceil_inplace_f16_cpu_wrapper, ceil_inplace_f16);
3653
3654cpu_unary_inplace_wrapper!(round_inplace_f32_cpu_wrapper, round_inplace_f32);
3655cpu_unary_inplace_wrapper!(round_inplace_f64_cpu_wrapper, round_inplace_f64);
3656cpu_unary_inplace_wrapper!(round_inplace_bf16_cpu_wrapper, round_inplace_bf16);
3657cpu_unary_inplace_wrapper!(round_inplace_f16_cpu_wrapper, round_inplace_f16);
3658
3659cpu_unary_inplace_wrapper!(erf_inplace_f32_cpu_wrapper, erf_inplace_f32);
3660cpu_unary_inplace_wrapper!(erf_inplace_f64_cpu_wrapper, erf_inplace_f64);
3661cpu_unary_inplace_wrapper!(erf_inplace_bf16_cpu_wrapper, erf_inplace_bf16);
3662cpu_unary_inplace_wrapper!(erf_inplace_f16_cpu_wrapper, erf_inplace_f16);
3663
3664cpu_unary_inplace_wrapper!(gelu_erf_inplace_f32_cpu_wrapper, gelu_erf_inplace_f32);
3665cpu_unary_inplace_wrapper!(gelu_erf_inplace_f64_cpu_wrapper, gelu_erf_inplace_f64);
3666cpu_unary_inplace_wrapper!(gelu_erf_inplace_bf16_cpu_wrapper, gelu_erf_inplace_bf16);
3667cpu_unary_inplace_wrapper!(gelu_erf_inplace_f16_cpu_wrapper, gelu_erf_inplace_f16);
3668
3669/// Dispatch wrapper for `(ClampElementwise, F32, Cpu)`.
3670pub(crate) fn clamp_elementwise_f32_cpu_wrapper(
3671    inputs: &[Arc<RwLock<Storage>>],
3672    outputs: &mut [Arc<RwLock<Storage>>],
3673    _layouts: &[Layout],
3674    params: &OpParams,
3675) -> Result<()> {
3676    if inputs.len() != 1 || outputs.len() != 1 {
3677        return Err(Error::Msg(format!(
3678            "clamp wrapper expects 1 input + 1 output, got {} + {}",
3679            inputs.len(),
3680            outputs.len(),
3681        ))
3682        .bt());
3683    }
3684    let (min, max) = match params {
3685        OpParams::Clamp { min, max } => (*min as f32, *max as f32),
3686        other => {
3687            return Err(Error::Msg(format!(
3688                "clamp wrapper expects OpParams::Clamp, got {other:?}",
3689            ))
3690            .bt());
3691        }
3692    };
3693    let in_guard = read_storage(&inputs[0])?;
3694    let mut out_guard = write_storage(&outputs[0])?;
3695    let in_cpu = cpu_input(&in_guard)?;
3696    let out_cpu = cpu_output(&mut out_guard)?;
3697    fuel_cpu_backend::byte_kernels::clamp_f32(in_cpu, out_cpu, min, max)
3698}
3699
3700/// Dispatch wrapper for `(PowIElementwise, F32, Cpu)`.
3701pub(crate) fn powi_elementwise_f32_cpu_wrapper(
3702    inputs: &[Arc<RwLock<Storage>>],
3703    outputs: &mut [Arc<RwLock<Storage>>],
3704    _layouts: &[Layout],
3705    params: &OpParams,
3706) -> Result<()> {
3707    if inputs.len() != 1 || outputs.len() != 1 {
3708        return Err(Error::Msg(format!(
3709            "powi wrapper expects 1 input + 1 output, got {} + {}",
3710            inputs.len(),
3711            outputs.len(),
3712        ))
3713        .bt());
3714    }
3715    let exp = match params {
3716        OpParams::PowI { exp } => *exp,
3717        other => {
3718            return Err(Error::Msg(format!(
3719                "powi wrapper expects OpParams::PowI, got {other:?}",
3720            ))
3721            .bt());
3722        }
3723    };
3724    let in_guard = read_storage(&inputs[0])?;
3725    let mut out_guard = write_storage(&outputs[0])?;
3726    let in_cpu = cpu_input(&in_guard)?;
3727    let out_cpu = cpu_output(&mut out_guard)?;
3728    fuel_cpu_backend::byte_kernels::powi_f32(in_cpu, out_cpu, exp)
3729}
3730
3731/// Build a `(2 inputs `(x, upstream)`, 1 output, OpParams::PowI)` CPU
3732/// dispatch wrapper for the per-dtype PowIBackward kernels.
3733macro_rules! cpu_powi_backward_wrapper {
3734    ($wrapper:ident, $kernel:path, $op_name:literal) => {
3735        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3736        // real production wrapper for the affine-clamp-powi contract import.
3737        pub(crate) fn $wrapper(
3738            inputs: &[Arc<RwLock<Storage>>],
3739            outputs: &mut [Arc<RwLock<Storage>>],
3740            _layouts: &[Layout],
3741            params: &OpParams,
3742        ) -> Result<()> {
3743            if inputs.len() != 2 || outputs.len() != 1 {
3744                return Err(Error::Msg(format!(
3745                    "{} wrapper expects 2 inputs + 1 output, got {} + {}",
3746                    $op_name,
3747                    inputs.len(),
3748                    outputs.len(),
3749                ))
3750                .bt());
3751            }
3752            let exp = match params {
3753                OpParams::PowI { exp } => *exp,
3754                other => {
3755                    return Err(Error::Msg(format!(
3756                        "{} wrapper expects OpParams::PowI, got {other:?}",
3757                        $op_name,
3758                    ))
3759                    .bt())
3760                }
3761            };
3762            let x_guard = read_storage(&inputs[0])?;
3763            let up_guard = read_storage(&inputs[1])?;
3764            let mut out_guard = write_storage(&outputs[0])?;
3765            let x_cpu = cpu_input(&x_guard)?;
3766            let up_cpu = cpu_input(&up_guard)?;
3767            let out_cpu = cpu_output(&mut out_guard)?;
3768            $kernel(x_cpu, up_cpu, out_cpu, exp)
3769        }
3770    };
3771}
3772
3773cpu_powi_backward_wrapper!(
3774    powi_backward_f32_cpu_wrapper,
3775    fuel_cpu_backend::byte_kernels::powi_backward_f32,
3776    "powi_backward_f32"
3777);
3778cpu_powi_backward_wrapper!(
3779    powi_backward_f64_cpu_wrapper,
3780    fuel_cpu_backend::byte_kernels::powi_backward_f64,
3781    "powi_backward_f64"
3782);
3783cpu_powi_backward_wrapper!(
3784    powi_backward_bf16_cpu_wrapper,
3785    fuel_cpu_backend::byte_kernels::powi_backward_bf16,
3786    "powi_backward_bf16"
3787);
3788cpu_powi_backward_wrapper!(
3789    powi_backward_f16_cpu_wrapper,
3790    fuel_cpu_backend::byte_kernels::powi_backward_f16,
3791    "powi_backward_f16"
3792);
3793
3794/// Build a CPU reduction wrapper that calls a typed `(input,
3795/// output, input_shape, dims)` reduce kernel. Verifies the
3796/// `OpParams::Reduce` variant and forwards the shape + dims to the
3797/// kernel.
3798macro_rules! cpu_reduce_wrapper {
3799    ($wrapper:ident, $kernel:path, $op_name:literal) => {
3800        pub(crate) fn $wrapper(
3801            inputs: &[Arc<RwLock<Storage>>],
3802            outputs: &mut [Arc<RwLock<Storage>>],
3803            layouts: &[Layout],
3804            params: &OpParams,
3805        ) -> Result<()> {
3806            if inputs.len() != 1 {
3807                return Err(Error::Msg(format!(
3808                    "{} wrapper expects 1 input, got {}",
3809                    $op_name,
3810                    inputs.len(),
3811                ))
3812                .bt());
3813            }
3814            if outputs.len() != 1 {
3815                return Err(Error::Msg(format!(
3816                    "{} wrapper expects 1 output, got {}",
3817                    $op_name,
3818                    outputs.len(),
3819                ))
3820                .bt());
3821            }
3822            let dims = match params {
3823                OpParams::Reduce { dims, .. } => dims,
3824                other => {
3825                    return Err(Error::Msg(format!(
3826                        "{} wrapper expects OpParams::Reduce, got {:?}",
3827                        $op_name, other,
3828                    ))
3829                    .bt())
3830                }
3831            };
3832            let input_layout = layouts.first().ok_or_else(|| {
3833                Error::Msg(format!(
3834                    "{} wrapper: layouts empty (executor must pass input layout at [0])",
3835                    $op_name,
3836                ))
3837                .bt()
3838            })?;
3839            // The pipelined executor's auto-Contiguize pass
3840            // (stage 4 of Layout-on-Node) materializes contiguous
3841            // bytes for every kernel input before this wrapper is
3842            // called — so by the time we reach here, the input
3843            // bytes match `input_layout.shape()` in row-major
3844            // order. We pass only the shape to the typed kernel.
3845            let input_shape: &[usize] = input_layout.shape().dims();
3846            let in_guard = read_storage(&inputs[0])?;
3847            let mut out_guard = write_storage(&outputs[0])?;
3848            let in_cpu = cpu_input(&in_guard)?;
3849            let out_cpu = cpu_output(&mut out_guard)?;
3850            $kernel(in_cpu, out_cpu, input_shape, dims)
3851        }
3852    };
3853}
3854
3855cpu_reduce_wrapper!(
3856    sum_reduce_f32_cpu_wrapper,
3857    fuel_cpu_backend::byte_kernels::sum_reduce_f32,
3858    "sum_reduce"
3859);
3860cpu_reduce_wrapper!(
3861    max_reduce_f32_cpu_wrapper,
3862    fuel_cpu_backend::byte_kernels::max_reduce_f32,
3863    "max_reduce"
3864);
3865cpu_reduce_wrapper!(
3866    min_reduce_f32_cpu_wrapper,
3867    fuel_cpu_backend::byte_kernels::min_reduce_f32,
3868    "min_reduce"
3869);
3870cpu_reduce_wrapper!(
3871    mean_reduce_f32_cpu_wrapper,
3872    fuel_cpu_backend::byte_kernels::mean_reduce_f32,
3873    "mean_reduce"
3874);
3875cpu_reduce_wrapper!(
3876    sum_reduce_f64_cpu_wrapper,
3877    fuel_cpu_backend::byte_kernels::sum_reduce_f64,
3878    "sum_reduce"
3879);
3880cpu_reduce_wrapper!(
3881    max_reduce_f64_cpu_wrapper,
3882    fuel_cpu_backend::byte_kernels::max_reduce_f64,
3883    "max_reduce"
3884);
3885cpu_reduce_wrapper!(
3886    min_reduce_f64_cpu_wrapper,
3887    fuel_cpu_backend::byte_kernels::min_reduce_f64,
3888    "min_reduce"
3889);
3890cpu_reduce_wrapper!(
3891    mean_reduce_f64_cpu_wrapper,
3892    fuel_cpu_backend::byte_kernels::mean_reduce_f64,
3893    "mean_reduce"
3894);
3895
3896cpu_reduce_wrapper!(
3897    sum_reduce_bf16_cpu_wrapper,
3898    fuel_cpu_backend::byte_kernels::sum_reduce_bf16,
3899    "sum_reduce"
3900);
3901cpu_reduce_wrapper!(
3902    max_reduce_bf16_cpu_wrapper,
3903    fuel_cpu_backend::byte_kernels::max_reduce_bf16,
3904    "max_reduce"
3905);
3906cpu_reduce_wrapper!(
3907    min_reduce_bf16_cpu_wrapper,
3908    fuel_cpu_backend::byte_kernels::min_reduce_bf16,
3909    "min_reduce"
3910);
3911cpu_reduce_wrapper!(
3912    mean_reduce_bf16_cpu_wrapper,
3913    fuel_cpu_backend::byte_kernels::mean_reduce_bf16,
3914    "mean_reduce"
3915);
3916
3917cpu_reduce_wrapper!(
3918    sum_reduce_f16_cpu_wrapper,
3919    fuel_cpu_backend::byte_kernels::sum_reduce_f16,
3920    "sum_reduce"
3921);
3922cpu_reduce_wrapper!(
3923    max_reduce_f16_cpu_wrapper,
3924    fuel_cpu_backend::byte_kernels::max_reduce_f16,
3925    "max_reduce"
3926);
3927cpu_reduce_wrapper!(
3928    min_reduce_f16_cpu_wrapper,
3929    fuel_cpu_backend::byte_kernels::min_reduce_f16,
3930    "min_reduce"
3931);
3932cpu_reduce_wrapper!(
3933    mean_reduce_f16_cpu_wrapper,
3934    fuel_cpu_backend::byte_kernels::mean_reduce_f16,
3935    "mean_reduce"
3936);
3937
3938/// Generate a dispatch wrapper for `(Cast, <target>, Cpu)`. The
3939/// binding-table key is keyed on the *target* dtype (= the
3940/// Node's dtype = the output Storage's dtype); the wrapper reads
3941/// the input Storage's dtype at runtime and dispatches to the
3942/// right typed conversion kernel.
3943macro_rules! cpu_cast_wrapper {
3944    (
3945        $wrapper:ident,
3946        $target_dtype:expr,
3947        $target_name:literal,
3948        { $( $source:pat => $kernel:path ),+ $(,)? } $(,)?
3949    ) => {
3950        // `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the
3951        // real production wrapper and the importer can bind it FROM the contract.
3952        pub(crate) fn $wrapper(
3953            inputs: &[Arc<RwLock<Storage>>],
3954            outputs: &mut [Arc<RwLock<Storage>>],
3955            _layouts: &[Layout],
3956            _params: &OpParams,
3957        ) -> Result<()> {
3958            if inputs.len() != 1 {
3959                return Err(Error::Msg(format!(
3960                    "cast→{} wrapper expects 1 input, got {}",
3961                    $target_name,
3962                    inputs.len(),
3963                ))
3964                .bt());
3965            }
3966            if outputs.len() != 1 {
3967                return Err(Error::Msg(format!(
3968                    "cast→{} wrapper expects 1 output, got {}",
3969                    $target_name,
3970                    outputs.len(),
3971                ))
3972                .bt());
3973            }
3974            let in_guard = read_storage(&inputs[0])?;
3975            let mut out_guard = write_storage(&outputs[0])?;
3976            let source_dtype = in_guard.dtype;
3977            let in_cpu = cpu_input(&in_guard)?;
3978            let out_cpu = cpu_output(&mut out_guard)?;
3979            match source_dtype {
3980                $( $source => $kernel(in_cpu, out_cpu), )+
3981                other => Err(Error::Msg(format!(
3982                    "cast→{}: source dtype {:?} not yet wired (Phase C \
3983                     extends the cast matrix as needed)",
3984                    $target_name, other,
3985                ))
3986                .bt()),
3987            }
3988        }
3989    };
3990}
3991
3992/// Dispatch wrapper for `(Conv2D, *, Cpu)`. Two or three inputs
3993/// (x, weight, optional bias). Shapes + geometry flow through
3994/// `OpParams::Conv2D`.
3995/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
3996/// production wrapper and the importer can bind it FROM the contract.
3997macro_rules! cpu_conv2d_wrapper {
3998    ($name:ident, $kernel:path) => {
3999        pub(crate) fn $name(
4000            inputs: &[Arc<RwLock<Storage>>],
4001            outputs: &mut [Arc<RwLock<Storage>>],
4002            _layouts: &[Layout],
4003            params: &OpParams,
4004        ) -> Result<()> {
4005            if inputs.len() != 2 && inputs.len() != 3 {
4006                return Err(Error::Msg(format!(
4007                    "conv2d wrapper expects 2 or 3 inputs (x, weight, [bias]), got {}",
4008                    inputs.len(),
4009                ))
4010                .bt());
4011            }
4012            if outputs.len() != 1 {
4013                return Err(Error::Msg(format!(
4014                    "conv2d wrapper expects 1 output, got {}",
4015                    outputs.len(),
4016                ))
4017                .bt());
4018            }
4019            let (x_shape, w_shape, out_shape, stride, padding, dilation, groups) = match params {
4020                OpParams::Conv2D {
4021                    x_shape,
4022                    w_shape,
4023                    out_shape,
4024                    stride,
4025                    padding,
4026                    dilation,
4027                    groups,
4028                } => (
4029                    *x_shape, *w_shape, *out_shape, *stride, *padding, *dilation, *groups,
4030                ),
4031                other => {
4032                    return Err(Error::Msg(format!(
4033                        "conv2d wrapper expects OpParams::Conv2D, got {other:?}",
4034                    ))
4035                    .bt())
4036                }
4037            };
4038            let x_guard = read_storage(&inputs[0])?;
4039            let w_guard = read_storage(&inputs[1])?;
4040            let bias_guard = match inputs.get(2) {
4041                Some(arc) => Some(read_storage(arc)?),
4042                None => None,
4043            };
4044            let mut out_guard = write_storage(&outputs[0])?;
4045            let x_cpu = cpu_input(&x_guard)?;
4046            let w_cpu = cpu_input(&w_guard)?;
4047            let bias_cpu = match &bias_guard {
4048                Some(g) => Some(cpu_input(g)?),
4049                None => None,
4050            };
4051            let out_cpu = cpu_output(&mut out_guard)?;
4052            $kernel(
4053                x_cpu, w_cpu, bias_cpu, out_cpu, x_shape, w_shape, out_shape, stride, padding,
4054                dilation, groups,
4055            )
4056        }
4057    };
4058}
4059
4060cpu_conv2d_wrapper!(
4061    conv2d_f32_cpu_wrapper,
4062    fuel_cpu_backend::byte_kernels::conv2d_f32
4063);
4064cpu_conv2d_wrapper!(
4065    conv2d_f64_cpu_wrapper,
4066    fuel_cpu_backend::byte_kernels::conv2d_f64
4067);
4068cpu_conv2d_wrapper!(
4069    conv2d_bf16_cpu_wrapper,
4070    fuel_cpu_backend::byte_kernels::conv2d_bf16
4071);
4072cpu_conv2d_wrapper!(
4073    conv2d_f16_cpu_wrapper,
4074    fuel_cpu_backend::byte_kernels::conv2d_f16
4075);
4076
4077/// Dispatch wrapper for `(ConvTranspose2D, *, Cpu)`. Two or three
4078/// inputs (x, weight, [bias]). Geometry flows through
4079/// `OpParams::ConvTranspose2D`.
4080/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
4081/// production wrapper and the importer can bind it FROM the contract.
4082macro_rules! cpu_conv_transpose2d_wrapper {
4083    ($name:ident, $kernel:path) => {
4084        pub(crate) fn $name(
4085            inputs: &[Arc<RwLock<Storage>>],
4086            outputs: &mut [Arc<RwLock<Storage>>],
4087            _layouts: &[Layout],
4088            params: &OpParams,
4089        ) -> Result<()> {
4090            if inputs.len() != 2 && inputs.len() != 3 {
4091                return Err(Error::Msg(format!(
4092                    "conv_transpose2d wrapper expects 2 or 3 inputs (x, weight, [bias]), got {}",
4093                    inputs.len(),
4094                ))
4095                .bt());
4096            }
4097            if outputs.len() != 1 {
4098                return Err(Error::Msg(format!(
4099                    "conv_transpose2d wrapper expects 1 output, got {}",
4100                    outputs.len(),
4101                ))
4102                .bt());
4103            }
4104            let (x_shape, w_shape, out_shape, stride, padding, dilation, groups) =
4105                match params {
4106                    OpParams::ConvTranspose2D {
4107                        x_shape,
4108                        w_shape,
4109                        out_shape,
4110                        stride,
4111                        padding,
4112                        output_padding: _,
4113                        dilation,
4114                        groups,
4115                    } => (
4116                        *x_shape, *w_shape, *out_shape, *stride, *padding, *dilation, *groups,
4117                    ),
4118                    other => return Err(Error::Msg(format!(
4119                        "conv_transpose2d wrapper expects OpParams::ConvTranspose2D, got {other:?}",
4120                    ))
4121                    .bt()),
4122                };
4123            let x_guard = read_storage(&inputs[0])?;
4124            let w_guard = read_storage(&inputs[1])?;
4125            let bias_guard = match inputs.get(2) {
4126                Some(arc) => Some(read_storage(arc)?),
4127                None => None,
4128            };
4129            let mut out_guard = write_storage(&outputs[0])?;
4130            let x_cpu = cpu_input(&x_guard)?;
4131            let w_cpu = cpu_input(&w_guard)?;
4132            let bias_cpu = match &bias_guard {
4133                Some(g) => Some(cpu_input(g)?),
4134                None => None,
4135            };
4136            let out_cpu = cpu_output(&mut out_guard)?;
4137            $kernel(
4138                x_cpu, w_cpu, bias_cpu, out_cpu, x_shape, w_shape, out_shape, stride, padding,
4139                dilation, groups,
4140            )
4141        }
4142    };
4143}
4144
4145cpu_conv_transpose2d_wrapper!(
4146    conv_transpose2d_f32_cpu_wrapper,
4147    fuel_cpu_backend::byte_kernels::conv_transpose2d_f32
4148);
4149cpu_conv_transpose2d_wrapper!(
4150    conv_transpose2d_f64_cpu_wrapper,
4151    fuel_cpu_backend::byte_kernels::conv_transpose2d_f64
4152);
4153cpu_conv_transpose2d_wrapper!(
4154    conv_transpose2d_bf16_cpu_wrapper,
4155    fuel_cpu_backend::byte_kernels::conv_transpose2d_bf16
4156);
4157cpu_conv_transpose2d_wrapper!(
4158    conv_transpose2d_f16_cpu_wrapper,
4159    fuel_cpu_backend::byte_kernels::conv_transpose2d_f16
4160);
4161
4162/// Dispatch wrapper for `(ReduceSumTo, *, Cpu)`. Single input → single
4163/// output; shapes flow through `OpParams::ReduceSumTo`.
4164/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
4165/// production wrapper and the importer can bind it FROM the contract.
4166macro_rules! cpu_reduce_sum_to_wrapper {
4167    ($name:ident, $kernel:path) => {
4168        pub(crate) fn $name(
4169            inputs: &[Arc<RwLock<Storage>>],
4170            outputs: &mut [Arc<RwLock<Storage>>],
4171            _layouts: &[Layout],
4172            params: &OpParams,
4173        ) -> Result<()> {
4174            if inputs.len() != 1 {
4175                return Err(Error::Msg(format!(
4176                    "reduce_sum_to wrapper expects 1 input, got {}",
4177                    inputs.len(),
4178                ))
4179                .bt());
4180            }
4181            if outputs.len() != 1 {
4182                return Err(Error::Msg(format!(
4183                    "reduce_sum_to wrapper expects 1 output, got {}",
4184                    outputs.len(),
4185                ))
4186                .bt());
4187            }
4188            let (input_shape, output_shape) = match params {
4189                OpParams::ReduceSumTo {
4190                    input_shape,
4191                    output_shape,
4192                } => (input_shape.clone(), output_shape.clone()),
4193                other => {
4194                    return Err(Error::Msg(format!(
4195                        "reduce_sum_to wrapper expects OpParams::ReduceSumTo, got {other:?}",
4196                    ))
4197                    .bt())
4198                }
4199            };
4200            let in_guard = read_storage(&inputs[0])?;
4201            let mut out_guard = write_storage(&outputs[0])?;
4202            let in_cpu = cpu_input(&in_guard)?;
4203            let out_cpu = cpu_output(&mut out_guard)?;
4204            $kernel(in_cpu, out_cpu, &input_shape, &output_shape)
4205        }
4206    };
4207}
4208
4209cpu_reduce_sum_to_wrapper!(
4210    reduce_sum_to_f32_cpu_wrapper,
4211    fuel_cpu_backend::byte_kernels::reduce_sum_to_f32
4212);
4213cpu_reduce_sum_to_wrapper!(
4214    reduce_sum_to_f64_cpu_wrapper,
4215    fuel_cpu_backend::byte_kernels::reduce_sum_to_f64
4216);
4217cpu_reduce_sum_to_wrapper!(
4218    reduce_sum_to_bf16_cpu_wrapper,
4219    fuel_cpu_backend::byte_kernels::reduce_sum_to_bf16
4220);
4221cpu_reduce_sum_to_wrapper!(
4222    reduce_sum_to_f16_cpu_wrapper,
4223    fuel_cpu_backend::byte_kernels::reduce_sum_to_f16
4224);
4225
4226/// Dispatch wrapper for `(ReduceMaxTo, *, Cpu)`. Single input → single
4227/// output; shapes flow through `OpParams::ReduceMaxTo`.
4228/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
4229/// production wrapper and the importer can bind it FROM the contract.
4230macro_rules! cpu_reduce_max_to_wrapper {
4231    ($name:ident, $kernel:path) => {
4232        pub(crate) fn $name(
4233            inputs: &[Arc<RwLock<Storage>>],
4234            outputs: &mut [Arc<RwLock<Storage>>],
4235            _layouts: &[Layout],
4236            params: &OpParams,
4237        ) -> Result<()> {
4238            if inputs.len() != 1 {
4239                return Err(Error::Msg(format!(
4240                    "reduce_max_to wrapper expects 1 input, got {}",
4241                    inputs.len(),
4242                ))
4243                .bt());
4244            }
4245            if outputs.len() != 1 {
4246                return Err(Error::Msg(format!(
4247                    "reduce_max_to wrapper expects 1 output, got {}",
4248                    outputs.len(),
4249                ))
4250                .bt());
4251            }
4252            let (input_shape, output_shape) = match params {
4253                OpParams::ReduceMaxTo {
4254                    input_shape,
4255                    output_shape,
4256                } => (input_shape.clone(), output_shape.clone()),
4257                other => {
4258                    return Err(Error::Msg(format!(
4259                        "reduce_max_to wrapper expects OpParams::ReduceMaxTo, got {other:?}",
4260                    ))
4261                    .bt())
4262                }
4263            };
4264            let in_guard = read_storage(&inputs[0])?;
4265            let mut out_guard = write_storage(&outputs[0])?;
4266            let in_cpu = cpu_input(&in_guard)?;
4267            let out_cpu = cpu_output(&mut out_guard)?;
4268            $kernel(in_cpu, out_cpu, &input_shape, &output_shape)
4269        }
4270    };
4271}
4272
4273cpu_reduce_max_to_wrapper!(
4274    reduce_max_to_f32_cpu_wrapper,
4275    fuel_cpu_backend::byte_kernels::reduce_max_to_f32
4276);
4277cpu_reduce_max_to_wrapper!(
4278    reduce_max_to_f64_cpu_wrapper,
4279    fuel_cpu_backend::byte_kernels::reduce_max_to_f64
4280);
4281cpu_reduce_max_to_wrapper!(
4282    reduce_max_to_bf16_cpu_wrapper,
4283    fuel_cpu_backend::byte_kernels::reduce_max_to_bf16
4284);
4285cpu_reduce_max_to_wrapper!(
4286    reduce_max_to_f16_cpu_wrapper,
4287    fuel_cpu_backend::byte_kernels::reduce_max_to_f16
4288);
4289
4290/// Dispatch wrapper for `(FusedLinear, *, Cpu)`. Three inputs
4291/// (lhs, rhs, bias). Reuses `OpParams::Matmul` for shape.
4292macro_rules! cpu_fused_linear_wrapper {
4293    ($wrapper:ident, $kernel:path) => {
4294        // `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the matmul
4295        // contract's `fused_linear_<dt>` `entry_point` symbols to these wrappers.
4296        pub(crate) fn $wrapper(
4297            inputs: &[Arc<RwLock<Storage>>],
4298            outputs: &mut [Arc<RwLock<Storage>>],
4299            _layouts: &[Layout],
4300            params: &OpParams,
4301        ) -> Result<()> {
4302            if inputs.len() != 3 {
4303                return Err(Error::Msg(format!(
4304                    "fused_linear wrapper expects 3 inputs (lhs, rhs, bias), got {}",
4305                    inputs.len(),
4306                ))
4307                .bt());
4308            }
4309            if outputs.len() != 1 {
4310                return Err(Error::Msg(format!(
4311                    "fused_linear wrapper expects 1 output, got {}",
4312                    outputs.len(),
4313                ))
4314                .bt());
4315            }
4316            let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
4317                OpParams::Matmul {
4318                    lhs_batch_dims,
4319                    rhs_batch_dims,
4320                    m,
4321                    n,
4322                    k,
4323                    ..
4324                } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k),
4325                other => {
4326                    return Err(Error::Msg(format!(
4327                        "fused_linear wrapper expects OpParams::Matmul, got {other:?}",
4328                    ))
4329                    .bt())
4330                }
4331            };
4332            let lhs_guard = read_storage(&inputs[0])?;
4333            let rhs_guard = read_storage(&inputs[1])?;
4334            let bias_guard = read_storage(&inputs[2])?;
4335            let mut out_guard = write_storage(&outputs[0])?;
4336            let lhs_cpu = cpu_input(&lhs_guard)?;
4337            let rhs_cpu = cpu_input(&rhs_guard)?;
4338            let bias_cpu = cpu_input(&bias_guard)?;
4339            let out_cpu = cpu_output(&mut out_guard)?;
4340            $kernel(
4341                lhs_cpu,
4342                rhs_cpu,
4343                bias_cpu,
4344                out_cpu,
4345                lhs_batch_dims,
4346                rhs_batch_dims,
4347                m,
4348                n,
4349                k,
4350            )
4351        }
4352    };
4353}
4354
4355cpu_fused_linear_wrapper!(
4356    fused_linear_f32_cpu_wrapper,
4357    fuel_cpu_backend::byte_kernels::fused_linear_f32
4358);
4359cpu_fused_linear_wrapper!(
4360    fused_linear_f64_cpu_wrapper,
4361    fuel_cpu_backend::byte_kernels::fused_linear_f64
4362);
4363cpu_fused_linear_wrapper!(
4364    fused_linear_bf16_cpu_wrapper,
4365    fuel_cpu_backend::byte_kernels::fused_linear_bf16
4366);
4367cpu_fused_linear_wrapper!(
4368    fused_linear_f16_cpu_wrapper,
4369    fuel_cpu_backend::byte_kernels::fused_linear_f16
4370);
4371
4372// RowScaledMatMul (row 172 item 1): same `(a, b, third, out)` + `OpParams::Matmul`
4373// shape as FusedLinear; the third input is the `[..., M, 1]` row scale.
4374cpu_fused_linear_wrapper!(
4375    row_scaled_matmul_f32_cpu_wrapper,
4376    fuel_cpu_backend::byte_kernels::row_scaled_matmul_f32
4377);
4378cpu_fused_linear_wrapper!(
4379    row_scaled_matmul_f64_cpu_wrapper,
4380    fuel_cpu_backend::byte_kernels::row_scaled_matmul_f64
4381);
4382cpu_fused_linear_wrapper!(
4383    row_scaled_matmul_bf16_cpu_wrapper,
4384    fuel_cpu_backend::byte_kernels::row_scaled_matmul_bf16
4385);
4386cpu_fused_linear_wrapper!(
4387    row_scaled_matmul_f16_cpu_wrapper,
4388    fuel_cpu_backend::byte_kernels::row_scaled_matmul_f16
4389);
4390
4391/// Per-dtype FusedSoftmaxCrossEntropy dispatch wrapper. Two inputs
4392/// (logits T, targets I64) → one F32 output (the FSCE declared dtype,
4393/// regardless of logits dtype — losses accumulate in f64, narrow to
4394/// f32). Translates the `Reduction` enum from the FusedOpParams
4395/// payload (which lives on the graph node) to the kernel's `u8` tag —
4396/// the kernel intentionally stays free of fuel-graph dependencies.
4397macro_rules! cpu_fused_softmax_cross_entropy_wrapper {
4398    ($wrapper:ident, $kernel:path) => {
4399        pub(crate) fn $wrapper(
4400            inputs: &[Arc<RwLock<Storage>>],
4401            outputs: &mut [Arc<RwLock<Storage>>],
4402            _layouts: &[Layout],
4403            params: &OpParams,
4404        ) -> Result<()> {
4405            if inputs.len() != 2 {
4406                return Err(Error::Msg(format!(
4407                    "fused_softmax_cross_entropy wrapper expects 2 inputs (logits, targets), got {}",
4408                    inputs.len(),
4409                ))
4410                .bt());
4411            }
4412            if outputs.len() != 1 {
4413                return Err(Error::Msg(format!(
4414                    "fused_softmax_cross_entropy wrapper expects 1 output, got {}",
4415                    outputs.len(),
4416                ))
4417                .bt());
4418            }
4419            let (n_rows, vocab, reduction, ignore_index) = match params {
4420                OpParams::FusedSoftmaxCrossEntropy {
4421                    n_rows, vocab, reduction, ignore_index,
4422                } => (*n_rows, *vocab, *reduction, *ignore_index),
4423                other => {
4424                    return Err(Error::Msg(format!(
4425                        "fused_softmax_cross_entropy wrapper expects \
4426                         OpParams::FusedSoftmaxCrossEntropy, got {other:?}",
4427                    ))
4428                    .bt());
4429                }
4430            };
4431            let reduction_tag = match reduction {
4432                fuel_graph::registry::Reduction::Mean => fuel_cpu_backend::byte_kernels::REDUCTION_MEAN,
4433                fuel_graph::registry::Reduction::Sum  => fuel_cpu_backend::byte_kernels::REDUCTION_SUM,
4434                fuel_graph::registry::Reduction::None => fuel_cpu_backend::byte_kernels::REDUCTION_NONE,
4435            };
4436            let logits_guard = read_storage(&inputs[0])?;
4437            let targets_guard = read_storage(&inputs[1])?;
4438            let mut out_guard = write_storage(&outputs[0])?;
4439            let logits_cpu = cpu_input(&logits_guard)?;
4440            let targets_cpu = cpu_input(&targets_guard)?;
4441            let out_cpu = cpu_output(&mut out_guard)?;
4442            $kernel(
4443                logits_cpu, targets_cpu, out_cpu,
4444                n_rows, vocab, reduction_tag, ignore_index,
4445            )
4446        }
4447    };
4448}
4449
4450cpu_fused_softmax_cross_entropy_wrapper!(
4451    fused_softmax_cross_entropy_f32_cpu_wrapper,
4452    fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_f32
4453);
4454cpu_fused_softmax_cross_entropy_wrapper!(
4455    fused_softmax_cross_entropy_f64_cpu_wrapper,
4456    fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_f64
4457);
4458cpu_fused_softmax_cross_entropy_wrapper!(
4459    fused_softmax_cross_entropy_bf16_cpu_wrapper,
4460    fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_bf16
4461);
4462cpu_fused_softmax_cross_entropy_wrapper!(
4463    fused_softmax_cross_entropy_f16_cpu_wrapper,
4464    fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_f16
4465);
4466
4467/// Per-dtype CausalConv1d dispatch wrapper. Three inputs (x, weight,
4468/// bias) → one output. Geometry + `use_silu` flow through
4469/// `OpParams::CausalConv1d`. All four inputs/outputs share the same
4470/// dtype `T`; the binding-table key is `[T, T, T, T]`.
4471macro_rules! cpu_causal_conv1d_wrapper {
4472    ($wrapper:ident, $kernel:path) => {
4473        pub(crate) fn $wrapper(
4474            inputs: &[Arc<RwLock<Storage>>],
4475            outputs: &mut [Arc<RwLock<Storage>>],
4476            _layouts: &[Layout],
4477            params: &OpParams,
4478        ) -> Result<()> {
4479            if inputs.len() != 3 {
4480                return Err(Error::Msg(format!(
4481                    "causal_conv1d wrapper expects 3 inputs (x, weight, bias), got {}",
4482                    inputs.len(),
4483                ))
4484                .bt());
4485            }
4486            if outputs.len() != 1 {
4487                return Err(Error::Msg(format!(
4488                    "causal_conv1d wrapper expects 1 output, got {}",
4489                    outputs.len(),
4490                ))
4491                .bt());
4492            }
4493            let (batch, channels, seq_in, seq_out, kernel, use_silu) = match params {
4494                OpParams::CausalConv1d {
4495                    batch,
4496                    channels,
4497                    seq_in,
4498                    seq_out,
4499                    kernel,
4500                    use_silu,
4501                } => (*batch, *channels, *seq_in, *seq_out, *kernel, *use_silu),
4502                other => {
4503                    return Err(Error::Msg(format!(
4504                        "causal_conv1d wrapper expects OpParams::CausalConv1d, got {other:?}",
4505                    ))
4506                    .bt());
4507                }
4508            };
4509            let x_guard = read_storage(&inputs[0])?;
4510            let w_guard = read_storage(&inputs[1])?;
4511            let bias_guard = read_storage(&inputs[2])?;
4512            let mut out_guard = write_storage(&outputs[0])?;
4513            let x_cpu = cpu_input(&x_guard)?;
4514            let w_cpu = cpu_input(&w_guard)?;
4515            let bias_cpu = cpu_input(&bias_guard)?;
4516            let out_cpu = cpu_output(&mut out_guard)?;
4517            $kernel(
4518                x_cpu, w_cpu, bias_cpu, out_cpu, batch, channels, seq_in, seq_out, kernel, use_silu,
4519            )
4520        }
4521    };
4522}
4523
4524cpu_causal_conv1d_wrapper!(
4525    causal_conv1d_f32_cpu_wrapper,
4526    fuel_cpu_backend::byte_kernels::causal_conv1d_f32
4527);
4528cpu_causal_conv1d_wrapper!(
4529    causal_conv1d_f64_cpu_wrapper,
4530    fuel_cpu_backend::byte_kernels::causal_conv1d_f64
4531);
4532cpu_causal_conv1d_wrapper!(
4533    causal_conv1d_bf16_cpu_wrapper,
4534    fuel_cpu_backend::byte_kernels::causal_conv1d_bf16
4535);
4536cpu_causal_conv1d_wrapper!(
4537    causal_conv1d_f16_cpu_wrapper,
4538    fuel_cpu_backend::byte_kernels::causal_conv1d_f16
4539);
4540
4541/// Per-dtype SelectiveScan dispatch wrapper. Five inputs (u, delta,
4542/// a, b, c) → one output (y). Geometry + `delta_softplus` flow
4543/// through `OpParams::SelectiveScan`. All six tensors share dtype `T`;
4544/// the binding-table key is `[T; 6]`.
4545macro_rules! cpu_selective_scan_wrapper {
4546    ($wrapper:ident, $kernel:path) => {
4547        pub(crate) fn $wrapper(
4548            inputs: &[Arc<RwLock<Storage>>],
4549            outputs: &mut [Arc<RwLock<Storage>>],
4550            _layouts: &[Layout],
4551            params: &OpParams,
4552        ) -> Result<()> {
4553            if inputs.len() != 5 {
4554                return Err(Error::Msg(format!(
4555                    "selective_scan wrapper expects 5 inputs (u, delta, a, b, c), got {}",
4556                    inputs.len(),
4557                ))
4558                .bt());
4559            }
4560            if outputs.len() != 1 {
4561                return Err(Error::Msg(format!(
4562                    "selective_scan wrapper expects 1 output, got {}",
4563                    outputs.len(),
4564                ))
4565                .bt());
4566            }
4567            let (batch, seqlen, dim, dstate, delta_softplus) = match params {
4568                OpParams::SelectiveScan {
4569                    batch,
4570                    seqlen,
4571                    dim,
4572                    dstate,
4573                    delta_softplus,
4574                } => (*batch, *seqlen, *dim, *dstate, *delta_softplus),
4575                other => {
4576                    return Err(Error::Msg(format!(
4577                        "selective_scan wrapper expects OpParams::SelectiveScan, got {other:?}",
4578                    ))
4579                    .bt());
4580                }
4581            };
4582            let u_guard = read_storage(&inputs[0])?;
4583            let delta_guard = read_storage(&inputs[1])?;
4584            let a_guard = read_storage(&inputs[2])?;
4585            let b_guard = read_storage(&inputs[3])?;
4586            let c_guard = read_storage(&inputs[4])?;
4587            let mut out_guard = write_storage(&outputs[0])?;
4588            let u_cpu = cpu_input(&u_guard)?;
4589            let delta_cpu = cpu_input(&delta_guard)?;
4590            let a_cpu = cpu_input(&a_guard)?;
4591            let b_cpu = cpu_input(&b_guard)?;
4592            let c_cpu = cpu_input(&c_guard)?;
4593            let out_cpu = cpu_output(&mut out_guard)?;
4594            $kernel(
4595                u_cpu,
4596                delta_cpu,
4597                a_cpu,
4598                b_cpu,
4599                c_cpu,
4600                out_cpu,
4601                batch,
4602                seqlen,
4603                dim,
4604                dstate,
4605                delta_softplus,
4606            )
4607        }
4608    };
4609}
4610
4611/// TopKLastDim dispatch wrapper (row 172 item 2). One input `x [.., n]`, ONE
4612/// bundled output `[values ; pad to 4 ; indices]`; the kernel writes both slots.
4613macro_rules! cpu_top_k_last_dim_wrapper {
4614    ($wrapper:ident, $kernel:path) => {
4615        pub(crate) fn $wrapper(
4616            inputs: &[Arc<RwLock<Storage>>],
4617            outputs: &mut [Arc<RwLock<Storage>>],
4618            _layouts: &[Layout],
4619            params: &OpParams,
4620        ) -> Result<()> {
4621            if inputs.len() != 1 || outputs.len() != 1 {
4622                return Err(Error::Msg(format!(
4623                    "top_k_last_dim wrapper expects 1 input and 1 (bundled) output, got {} and {}",
4624                    inputs.len(),
4625                    outputs.len(),
4626                ))
4627                .bt());
4628            }
4629            let (rows, n, k) = match params {
4630                OpParams::TopKLastDim { rows, n, k } => (*rows, *n, *k),
4631                other => {
4632                    return Err(Error::Msg(format!(
4633                        "top_k_last_dim wrapper expects OpParams::TopKLastDim, got {other:?}",
4634                    ))
4635                    .bt());
4636                }
4637            };
4638            let x_guard = read_storage(&inputs[0])?;
4639            let mut out_guard = write_storage(&outputs[0])?;
4640            let x_cpu = cpu_input(&x_guard)?;
4641            let out_cpu = cpu_output(&mut out_guard)?;
4642            $kernel(x_cpu, out_cpu, rows, n, k)
4643        }
4644    };
4645}
4646
4647cpu_top_k_last_dim_wrapper!(
4648    top_k_last_dim_f32_cpu_wrapper,
4649    fuel_cpu_backend::byte_kernels::top_k_last_dim_f32
4650);
4651cpu_top_k_last_dim_wrapper!(
4652    top_k_last_dim_f64_cpu_wrapper,
4653    fuel_cpu_backend::byte_kernels::top_k_last_dim_f64
4654);
4655cpu_top_k_last_dim_wrapper!(
4656    top_k_last_dim_bf16_cpu_wrapper,
4657    fuel_cpu_backend::byte_kernels::top_k_last_dim_bf16
4658);
4659cpu_top_k_last_dim_wrapper!(
4660    top_k_last_dim_f16_cpu_wrapper,
4661    fuel_cpu_backend::byte_kernels::top_k_last_dim_f16
4662);
4663
4664/// MatMulTopK dispatch wrapper (row 172 item 2 step B). Inputs `a`, `b`; ONE
4665/// bundled output `[values ; pad to 4 ; indices]`.
4666macro_rules! cpu_matmul_top_k_wrapper {
4667    ($wrapper:ident, $kernel:path) => {
4668        pub(crate) fn $wrapper(
4669            inputs: &[Arc<RwLock<Storage>>],
4670            outputs: &mut [Arc<RwLock<Storage>>],
4671            _layouts: &[Layout],
4672            params: &OpParams,
4673        ) -> Result<()> {
4674            if inputs.len() != 2 || outputs.len() != 1 {
4675                return Err(Error::Msg(format!(
4676                    "matmul_top_k wrapper expects 2 inputs and 1 (bundled) output, got {} and {}",
4677                    inputs.len(),
4678                    outputs.len(),
4679                ))
4680                .bt());
4681            }
4682            let (batch, m, n, k, top_k) = match params {
4683                OpParams::MatMulTopK {
4684                    batch,
4685                    m,
4686                    n,
4687                    k,
4688                    top_k,
4689                } => (*batch, *m, *n, *k, *top_k),
4690                other => {
4691                    return Err(Error::Msg(format!(
4692                        "matmul_top_k wrapper expects OpParams::MatMulTopK, got {other:?}",
4693                    ))
4694                    .bt());
4695                }
4696            };
4697            let lhs_guard = read_storage(&inputs[0])?;
4698            let rhs_guard = read_storage(&inputs[1])?;
4699            let mut out_guard = write_storage(&outputs[0])?;
4700            let lhs_cpu = cpu_input(&lhs_guard)?;
4701            let rhs_cpu = cpu_input(&rhs_guard)?;
4702            let out_cpu = cpu_output(&mut out_guard)?;
4703            $kernel(lhs_cpu, rhs_cpu, out_cpu, batch, m, n, k, top_k)
4704        }
4705    };
4706}
4707
4708cpu_matmul_top_k_wrapper!(
4709    matmul_top_k_f32_cpu_wrapper,
4710    fuel_cpu_backend::byte_kernels::matmul_top_k_f32
4711);
4712cpu_matmul_top_k_wrapper!(
4713    matmul_top_k_f64_cpu_wrapper,
4714    fuel_cpu_backend::byte_kernels::matmul_top_k_f64
4715);
4716cpu_matmul_top_k_wrapper!(
4717    matmul_top_k_bf16_cpu_wrapper,
4718    fuel_cpu_backend::byte_kernels::matmul_top_k_bf16
4719);
4720cpu_matmul_top_k_wrapper!(
4721    matmul_top_k_f16_cpu_wrapper,
4722    fuel_cpu_backend::byte_kernels::matmul_top_k_f16
4723);
4724
4725cpu_selective_scan_wrapper!(
4726    selective_scan_f32_cpu_wrapper,
4727    fuel_cpu_backend::byte_kernels::selective_scan_f32
4728);
4729cpu_selective_scan_wrapper!(
4730    selective_scan_f64_cpu_wrapper,
4731    fuel_cpu_backend::byte_kernels::selective_scan_f64
4732);
4733cpu_selective_scan_wrapper!(
4734    selective_scan_bf16_cpu_wrapper,
4735    fuel_cpu_backend::byte_kernels::selective_scan_bf16
4736);
4737cpu_selective_scan_wrapper!(
4738    selective_scan_f16_cpu_wrapper,
4739    fuel_cpu_backend::byte_kernels::selective_scan_f16
4740);
4741
4742/// Per-input-dtype NonZeroIndices dispatch wrapper. One input `x`
4743/// (the value tensor) → one bundled output `[indices [capacity] U32 ;
4744/// count [1] U32]`. `capacity` flows through `OpParams::NonZeroIndices`;
4745/// the binding-table key is `[input_dtype, U32]` (input + the primary
4746/// output-slot dtype). The `count_sym` field is consumed by the executor
4747/// after the kernel runs (the SymEnv bind seam), not here.
4748macro_rules! cpu_nonzero_indices_wrapper {
4749    ($wrapper:ident, $kernel:path) => {
4750        pub(crate) fn $wrapper(
4751            inputs: &[Arc<RwLock<Storage>>],
4752            outputs: &mut [Arc<RwLock<Storage>>],
4753            _layouts: &[Layout],
4754            params: &OpParams,
4755        ) -> Result<()> {
4756            if inputs.len() != 1 {
4757                return Err(Error::Msg(format!(
4758                    "nonzero_indices wrapper expects 1 input, got {}",
4759                    inputs.len(),
4760                ))
4761                .bt());
4762            }
4763            if outputs.len() != 1 {
4764                return Err(Error::Msg(format!(
4765                    "nonzero_indices wrapper expects 1 output, got {}",
4766                    outputs.len(),
4767                ))
4768                .bt());
4769            }
4770            let capacity = match params {
4771                OpParams::NonZeroIndices { capacity, .. } => *capacity,
4772                other => {
4773                    return Err(Error::Msg(format!(
4774                        "nonzero_indices wrapper expects OpParams::NonZeroIndices, got {other:?}",
4775                    ))
4776                    .bt());
4777                }
4778            };
4779            let x_guard = read_storage(&inputs[0])?;
4780            let mut out_guard = write_storage(&outputs[0])?;
4781            let x_cpu = cpu_input(&x_guard)?;
4782            let out_cpu = cpu_output(&mut out_guard)?;
4783            $kernel(x_cpu, out_cpu, capacity)
4784        }
4785    };
4786}
4787
4788cpu_nonzero_indices_wrapper!(
4789    nonzero_indices_f32_cpu_wrapper,
4790    fuel_cpu_backend::byte_kernels::nonzero_indices_f32
4791);
4792cpu_nonzero_indices_wrapper!(
4793    nonzero_indices_u32_cpu_wrapper,
4794    fuel_cpu_backend::byte_kernels::nonzero_indices_u32
4795);
4796
4797/// Per-dtype SsdChunkScan dispatch wrapper. Five inputs (x, dt, a,
4798/// b, c) → one output (y). Geometry + `chunk_size` flow through
4799/// `OpParams::SsdChunkScan`. All six tensors share dtype `T`; the
4800/// binding-table key is `[T; 6]`.
4801macro_rules! cpu_ssd_chunk_scan_wrapper {
4802    ($wrapper:ident, $kernel:path) => {
4803        pub(crate) fn $wrapper(
4804            inputs: &[Arc<RwLock<Storage>>],
4805            outputs: &mut [Arc<RwLock<Storage>>],
4806            _layouts: &[Layout],
4807            params: &OpParams,
4808        ) -> Result<()> {
4809            if inputs.len() != 5 {
4810                return Err(Error::Msg(format!(
4811                    "ssd_chunk_scan wrapper expects 5 inputs (x, dt, a, b, c), got {}",
4812                    inputs.len(),
4813                ))
4814                .bt());
4815            }
4816            if outputs.len() != 1 {
4817                return Err(Error::Msg(format!(
4818                    "ssd_chunk_scan wrapper expects 1 output, got {}",
4819                    outputs.len(),
4820                ))
4821                .bt());
4822            }
4823            let (batch, seqlen, heads, head_dim, state_dim, chunk_size) = match params {
4824                OpParams::SsdChunkScan {
4825                    batch,
4826                    seqlen,
4827                    heads,
4828                    head_dim,
4829                    state_dim,
4830                    chunk_size,
4831                } => (*batch, *seqlen, *heads, *head_dim, *state_dim, *chunk_size),
4832                other => {
4833                    return Err(Error::Msg(format!(
4834                        "ssd_chunk_scan wrapper expects OpParams::SsdChunkScan, got {other:?}",
4835                    ))
4836                    .bt());
4837                }
4838            };
4839            let x_guard = read_storage(&inputs[0])?;
4840            let dt_guard = read_storage(&inputs[1])?;
4841            let a_guard = read_storage(&inputs[2])?;
4842            let b_guard = read_storage(&inputs[3])?;
4843            let c_guard = read_storage(&inputs[4])?;
4844            let mut out_guard = write_storage(&outputs[0])?;
4845            let x_cpu = cpu_input(&x_guard)?;
4846            let dt_cpu = cpu_input(&dt_guard)?;
4847            let a_cpu = cpu_input(&a_guard)?;
4848            let b_cpu = cpu_input(&b_guard)?;
4849            let c_cpu = cpu_input(&c_guard)?;
4850            let out_cpu = cpu_output(&mut out_guard)?;
4851            $kernel(
4852                x_cpu, dt_cpu, a_cpu, b_cpu, c_cpu, out_cpu, batch, seqlen, heads, head_dim,
4853                state_dim, chunk_size,
4854            )
4855        }
4856    };
4857}
4858
4859cpu_ssd_chunk_scan_wrapper!(
4860    ssd_chunk_scan_f32_cpu_wrapper,
4861    fuel_cpu_backend::byte_kernels::ssd_chunk_scan_f32
4862);
4863cpu_ssd_chunk_scan_wrapper!(
4864    ssd_chunk_scan_f64_cpu_wrapper,
4865    fuel_cpu_backend::byte_kernels::ssd_chunk_scan_f64
4866);
4867cpu_ssd_chunk_scan_wrapper!(
4868    ssd_chunk_scan_bf16_cpu_wrapper,
4869    fuel_cpu_backend::byte_kernels::ssd_chunk_scan_bf16
4870);
4871cpu_ssd_chunk_scan_wrapper!(
4872    ssd_chunk_scan_f16_cpu_wrapper,
4873    fuel_cpu_backend::byte_kernels::ssd_chunk_scan_f16
4874);
4875
4876/// Per-dtype Nf4Matmul wrapper. Three inputs (activations, w_packed
4877/// U8, absmax F32) → one output of the activations' dtype.
4878/// `block_size` flows through `OpParams::Nf4Matmul`.
4879macro_rules! cpu_nf4_matmul_wrapper {
4880    ($wrapper:ident, $kernel:path) => {
4881        fn $wrapper(
4882            inputs: &[Arc<RwLock<Storage>>],
4883            outputs: &mut [Arc<RwLock<Storage>>],
4884            _layouts: &[Layout],
4885            params: &OpParams,
4886        ) -> Result<()> {
4887            if inputs.len() != 3 {
4888                return Err(Error::Msg(format!(
4889                    "nf4_matmul wrapper expects 3 inputs (activations, w_packed, absmax), got {}",
4890                    inputs.len(),
4891                ))
4892                .bt());
4893            }
4894            if outputs.len() != 1 {
4895                return Err(Error::Msg(format!(
4896                    "nf4_matmul wrapper expects 1 output, got {}",
4897                    outputs.len(),
4898                ))
4899                .bt());
4900            }
4901            let (batch, m, n, k, block_size) = match params {
4902                OpParams::Nf4Matmul {
4903                    batch,
4904                    m,
4905                    n,
4906                    k,
4907                    block_size,
4908                } => (*batch, *m, *n, *k, *block_size),
4909                other => {
4910                    return Err(Error::Msg(format!(
4911                        "nf4_matmul wrapper expects OpParams::Nf4Matmul, got {other:?}",
4912                    ))
4913                    .bt());
4914                }
4915            };
4916            let a_guard = read_storage(&inputs[0])?;
4917            let w_guard = read_storage(&inputs[1])?;
4918            let abs_guard = read_storage(&inputs[2])?;
4919            let mut out_guard = write_storage(&outputs[0])?;
4920            let a_cpu = cpu_input(&a_guard)?;
4921            let w_cpu = cpu_input(&w_guard)?;
4922            let abs_cpu = cpu_input(&abs_guard)?;
4923            let out_cpu = cpu_output(&mut out_guard)?;
4924            $kernel(a_cpu, w_cpu, abs_cpu, out_cpu, batch, m, n, k, block_size)
4925        }
4926    };
4927}
4928
4929cpu_nf4_matmul_wrapper!(
4930    nf4_matmul_f32_cpu_wrapper,
4931    fuel_cpu_backend::byte_kernels::nf4_matmul_f32
4932);
4933cpu_nf4_matmul_wrapper!(
4934    nf4_matmul_f16_cpu_wrapper,
4935    fuel_cpu_backend::byte_kernels::nf4_matmul_f16
4936);
4937cpu_nf4_matmul_wrapper!(
4938    nf4_matmul_bf16_cpu_wrapper,
4939    fuel_cpu_backend::byte_kernels::nf4_matmul_bf16
4940);
4941
4942/// Dispatch wrapper for `(FlashAttn, *, Cpu)`. Three or four inputs
4943/// (q, k, v, optional alibi_slopes). Geometry + math params flow
4944/// through `OpParams::FlashAttn`.
4945macro_rules! cpu_flash_attn_wrapper {
4946    ($wrapper:ident, $kernel:path) => {
4947        // `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the attention
4948        // contract's forward-FlashAttn `entry_point` symbols to these wrappers.
4949        pub(crate) fn $wrapper(
4950            inputs: &[Arc<RwLock<Storage>>],
4951            outputs: &mut [Arc<RwLock<Storage>>],
4952            _layouts: &[Layout],
4953            params: &OpParams,
4954        ) -> Result<()> {
4955            if inputs.len() != 3 && inputs.len() != 4 {
4956                return Err(Error::Msg(format!(
4957                    "flash_attn wrapper expects 3 or 4 inputs (q, k, v, [alibi]), got {}",
4958                    inputs.len(),
4959                ))
4960                .bt());
4961            }
4962            if outputs.len() != 1 {
4963                return Err(Error::Msg(format!(
4964                    "flash_attn wrapper expects 1 output, got {}",
4965                    outputs.len(),
4966                ))
4967                .bt());
4968            }
4969            let (b, hq, hkv, sq, sk, d, k_len, scale, causal, wl, wr, softcap) = match params {
4970                OpParams::FlashAttn {
4971                    b,
4972                    hq,
4973                    hkv,
4974                    sq,
4975                    sk,
4976                    d,
4977                    k_len,
4978                    softmax_scale,
4979                    causal,
4980                    window_size_left,
4981                    window_size_right,
4982                    softcap,
4983                } => (
4984                    *b,
4985                    *hq,
4986                    *hkv,
4987                    *sq,
4988                    *sk,
4989                    *d,
4990                    *k_len,
4991                    *softmax_scale,
4992                    *causal,
4993                    *window_size_left,
4994                    *window_size_right,
4995                    *softcap,
4996                ),
4997                other => {
4998                    return Err(Error::Msg(format!(
4999                        "flash_attn wrapper expects OpParams::FlashAttn, got {other:?}",
5000                    ))
5001                    .bt())
5002                }
5003            };
5004            let q_guard = read_storage(&inputs[0])?;
5005            let k_guard = read_storage(&inputs[1])?;
5006            let v_guard = read_storage(&inputs[2])?;
5007            let alibi_guard = match inputs.get(3) {
5008                Some(arc) => Some(read_storage(arc)?),
5009                None => None,
5010            };
5011            let mut out_guard = write_storage(&outputs[0])?;
5012            let q_cpu = cpu_input(&q_guard)?;
5013            let k_cpu = cpu_input(&k_guard)?;
5014            let v_cpu = cpu_input(&v_guard)?;
5015            let alibi_cpu = match &alibi_guard {
5016                Some(g) => Some(cpu_input(g)?),
5017                None => None,
5018            };
5019            let out_cpu = cpu_output(&mut out_guard)?;
5020            $kernel(
5021                q_cpu, k_cpu, v_cpu, alibi_cpu, out_cpu, b, hq, hkv, sq, sk, d, k_len, scale,
5022                causal, wl, wr, softcap,
5023            )
5024        }
5025    };
5026}
5027
5028cpu_flash_attn_wrapper!(
5029    flash_attn_f32_cpu_wrapper,
5030    fuel_cpu_backend::byte_kernels::flash_attn_f32
5031);
5032cpu_flash_attn_wrapper!(
5033    flash_attn_f64_cpu_wrapper,
5034    fuel_cpu_backend::byte_kernels::flash_attn_f64
5035);
5036cpu_flash_attn_wrapper!(
5037    flash_attn_bf16_cpu_wrapper,
5038    fuel_cpu_backend::byte_kernels::flash_attn_bf16
5039);
5040cpu_flash_attn_wrapper!(
5041    flash_attn_f16_cpu_wrapper,
5042    fuel_cpu_backend::byte_kernels::flash_attn_f16
5043);
5044
5045/// Dispatch wrapper for `(FlashAttnBackward{Q,K,V}, *, Cpu)`. Four or
5046/// five inputs `(q, k, v, do, [alibi])`; one output (one of dQ/dK/dV).
5047/// The CPU kernel always computes all three gradients; this wrapper
5048/// only persists the requested one.
5049macro_rules! cpu_flash_attn_backward_wrapper {
5050    ($wrapper:ident, $kernel:path, $which:expr) => {
5051        // `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the attention
5052        // contract's FlashAttnBackward{Q,K,V} `entry_point` symbols to these wrappers.
5053        pub(crate) fn $wrapper(
5054            inputs: &[Arc<RwLock<Storage>>],
5055            outputs: &mut [Arc<RwLock<Storage>>],
5056            _layouts: &[Layout],
5057            params: &OpParams,
5058        ) -> Result<()> {
5059            if inputs.len() != 4 && inputs.len() != 5 {
5060                return Err(Error::Msg(format!(
5061                    "flash_attn_backward wrapper expects 4 or 5 inputs (q, k, v, do, [alibi]), got {}",
5062                    inputs.len(),
5063                ))
5064                .bt());
5065            }
5066            if outputs.len() != 1 {
5067                return Err(Error::Msg(format!(
5068                    "flash_attn_backward wrapper expects 1 output, got {}",
5069                    outputs.len(),
5070                ))
5071                .bt());
5072            }
5073            let (b, hq, hkv, sq, sk, d, scale, causal, wl, wr, softcap) = match params {
5074                OpParams::FlashAttn {
5075                    b, hq, hkv, sq, sk, d,
5076                    softmax_scale, causal,
5077                    window_size_left, window_size_right, softcap,
5078                    // Backward is the static (full-K) training path; the
5079                    // recompute attends the full K extent. k_len ignored.
5080                    k_len: _,
5081                } => (
5082                    *b, *hq, *hkv, *sq, *sk, *d,
5083                    *softmax_scale, *causal,
5084                    *window_size_left, *window_size_right, *softcap,
5085                ),
5086                other => {
5087                    return Err(Error::Msg(format!(
5088                        "flash_attn_backward wrapper expects OpParams::FlashAttn, got {other:?}",
5089                    ))
5090                    .bt())
5091                }
5092            };
5093            let q_guard = read_storage(&inputs[0])?;
5094            let k_guard = read_storage(&inputs[1])?;
5095            let v_guard = read_storage(&inputs[2])?;
5096            let do_guard = read_storage(&inputs[3])?;
5097            let alibi_guard = match inputs.get(4) {
5098                Some(arc) => Some(read_storage(arc)?),
5099                None => None,
5100            };
5101            let mut out_guard = write_storage(&outputs[0])?;
5102            let q_cpu = cpu_input(&q_guard)?;
5103            let k_cpu = cpu_input(&k_guard)?;
5104            let v_cpu = cpu_input(&v_guard)?;
5105            let do_cpu = cpu_input(&do_guard)?;
5106            let alibi_cpu = match &alibi_guard {
5107                Some(g) => Some(cpu_input(g)?),
5108                None => None,
5109            };
5110            let out_cpu = cpu_output(&mut out_guard)?;
5111            $kernel(
5112                q_cpu, k_cpu, v_cpu, do_cpu, alibi_cpu, out_cpu, $which,
5113                b, hq, hkv, sq, sk, d,
5114                scale, causal, wl, wr, softcap,
5115            )
5116        }
5117    };
5118}
5119
5120cpu_flash_attn_backward_wrapper!(
5121    flash_attn_backward_q_f32_cpu_wrapper,
5122    fuel_cpu_backend::byte_kernels::flash_attn_backward_f32,
5123    fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
5124);
5125cpu_flash_attn_backward_wrapper!(
5126    flash_attn_backward_k_f32_cpu_wrapper,
5127    fuel_cpu_backend::byte_kernels::flash_attn_backward_f32,
5128    fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
5129);
5130cpu_flash_attn_backward_wrapper!(
5131    flash_attn_backward_v_f32_cpu_wrapper,
5132    fuel_cpu_backend::byte_kernels::flash_attn_backward_f32,
5133    fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
5134);
5135cpu_flash_attn_backward_wrapper!(
5136    flash_attn_backward_q_f64_cpu_wrapper,
5137    fuel_cpu_backend::byte_kernels::flash_attn_backward_f64,
5138    fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
5139);
5140cpu_flash_attn_backward_wrapper!(
5141    flash_attn_backward_k_f64_cpu_wrapper,
5142    fuel_cpu_backend::byte_kernels::flash_attn_backward_f64,
5143    fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
5144);
5145cpu_flash_attn_backward_wrapper!(
5146    flash_attn_backward_v_f64_cpu_wrapper,
5147    fuel_cpu_backend::byte_kernels::flash_attn_backward_f64,
5148    fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
5149);
5150cpu_flash_attn_backward_wrapper!(
5151    flash_attn_backward_q_bf16_cpu_wrapper,
5152    fuel_cpu_backend::byte_kernels::flash_attn_backward_bf16,
5153    fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
5154);
5155cpu_flash_attn_backward_wrapper!(
5156    flash_attn_backward_k_bf16_cpu_wrapper,
5157    fuel_cpu_backend::byte_kernels::flash_attn_backward_bf16,
5158    fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
5159);
5160cpu_flash_attn_backward_wrapper!(
5161    flash_attn_backward_v_bf16_cpu_wrapper,
5162    fuel_cpu_backend::byte_kernels::flash_attn_backward_bf16,
5163    fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
5164);
5165cpu_flash_attn_backward_wrapper!(
5166    flash_attn_backward_q_f16_cpu_wrapper,
5167    fuel_cpu_backend::byte_kernels::flash_attn_backward_f16,
5168    fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
5169);
5170cpu_flash_attn_backward_wrapper!(
5171    flash_attn_backward_k_f16_cpu_wrapper,
5172    fuel_cpu_backend::byte_kernels::flash_attn_backward_f16,
5173    fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
5174);
5175cpu_flash_attn_backward_wrapper!(
5176    flash_attn_backward_v_f16_cpu_wrapper,
5177    fuel_cpu_backend::byte_kernels::flash_attn_backward_f16,
5178    fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
5179);
5180
5181/// Dispatch wrapper for `(PagedAttn, *, Cpu)`. 5 or 6 inputs (q,
5182/// k_cache, v_cache, block_table, context_lens, optional alibi_slopes).
5183macro_rules! cpu_paged_attn_wrapper {
5184    ($wrapper:ident, $kernel:path) => {
5185        // `pub(crate)` so the FKC `CpuLinkRegistry` (`CPU_ATTENTION_ENTRY_POINTS`)
5186        // can resolve the paged sections' `byte_kernels::paged_attn_<dt>` symbols
5187        // to these wrappers (the attention family is contract-sourced; §3.9.1).
5188        pub(crate) fn $wrapper(
5189            inputs: &[Arc<RwLock<Storage>>],
5190            outputs: &mut [Arc<RwLock<Storage>>],
5191            _layouts: &[Layout],
5192            params: &OpParams,
5193        ) -> Result<()> {
5194            if inputs.len() != 5 && inputs.len() != 6 {
5195                return Err(Error::Msg(format!(
5196                    "paged_attn wrapper expects 5 or 6 inputs, got {}",
5197                    inputs.len(),
5198                ))
5199                .bt());
5200            }
5201            if outputs.len() != 1 {
5202                return Err(Error::Msg(format!(
5203                    "paged_attn wrapper expects 1 output, got {}",
5204                    outputs.len(),
5205                ))
5206                .bt());
5207            }
5208            let (b, hq, hkv, sq, d, block_size, max_blocks_per_seq, num_blocks, scale, softcap) =
5209                match params {
5210                    OpParams::PagedAttn {
5211                        b,
5212                        hq,
5213                        hkv,
5214                        sq,
5215                        d,
5216                        block_size,
5217                        max_blocks_per_seq,
5218                        num_blocks,
5219                        softmax_scale,
5220                        softcap,
5221                    } => (
5222                        *b,
5223                        *hq,
5224                        *hkv,
5225                        *sq,
5226                        *d,
5227                        *block_size,
5228                        *max_blocks_per_seq,
5229                        *num_blocks,
5230                        *softmax_scale,
5231                        *softcap,
5232                    ),
5233                    other => {
5234                        return Err(Error::Msg(format!(
5235                            "paged_attn wrapper expects OpParams::PagedAttn, got {other:?}",
5236                        ))
5237                        .bt())
5238                    }
5239                };
5240            let q_g = read_storage(&inputs[0])?;
5241            let kc_g = read_storage(&inputs[1])?;
5242            let vc_g = read_storage(&inputs[2])?;
5243            let bt_g = read_storage(&inputs[3])?;
5244            let cl_g = read_storage(&inputs[4])?;
5245            let alibi_g = match inputs.get(5) {
5246                Some(arc) => Some(read_storage(arc)?),
5247                None => None,
5248            };
5249            if bt_g.dtype != DType::U32 || cl_g.dtype != DType::U32 {
5250                return Err(Error::Msg(format!(
5251                    "paged_attn: block_table and context_lens must be U32, got {:?} / {:?}",
5252                    bt_g.dtype, cl_g.dtype,
5253                ))
5254                .bt());
5255            }
5256            let mut out_guard = write_storage(&outputs[0])?;
5257            let q_cpu = cpu_input(&q_g)?;
5258            let kc_cpu = cpu_input(&kc_g)?;
5259            let vc_cpu = cpu_input(&vc_g)?;
5260            let bt_cpu = cpu_input(&bt_g)?;
5261            let cl_cpu = cpu_input(&cl_g)?;
5262            let alibi_cpu = match &alibi_g {
5263                Some(g) => Some(cpu_input(g)?),
5264                None => None,
5265            };
5266            let out_cpu = cpu_output(&mut out_guard)?;
5267            $kernel(
5268                q_cpu,
5269                kc_cpu,
5270                vc_cpu,
5271                bt_cpu,
5272                cl_cpu,
5273                alibi_cpu,
5274                out_cpu,
5275                b,
5276                hq,
5277                hkv,
5278                sq,
5279                d,
5280                block_size,
5281                max_blocks_per_seq,
5282                num_blocks,
5283                scale,
5284                softcap,
5285            )
5286        }
5287    };
5288}
5289
5290cpu_paged_attn_wrapper!(
5291    paged_attn_f32_cpu_wrapper,
5292    fuel_cpu_backend::byte_kernels::paged_attn_f32
5293);
5294cpu_paged_attn_wrapper!(
5295    paged_attn_f64_cpu_wrapper,
5296    fuel_cpu_backend::byte_kernels::paged_attn_f64
5297);
5298cpu_paged_attn_wrapper!(
5299    paged_attn_bf16_cpu_wrapper,
5300    fuel_cpu_backend::byte_kernels::paged_attn_bf16
5301);
5302cpu_paged_attn_wrapper!(
5303    paged_attn_f16_cpu_wrapper,
5304    fuel_cpu_backend::byte_kernels::paged_attn_f16
5305);
5306
5307// Cast wrappers — one per TARGET dtype, each matching every other source
5308// dtype. Together they cover the full 11×10 = 110 directed pair matrix
5309// (identity pairs excluded; the optimizer elides them). Every real numeric
5310// dtype is a complete closed cast basis.
5311cpu_cast_wrapper!(
5312    cast_to_f32_cpu_wrapper,
5313    DType::F32,
5314    "f32",
5315    {
5316        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_f32,
5317        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_f32,
5318        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_f32,
5319        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_f32,
5320        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_f32,
5321        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_f32,
5322        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_f32,
5323        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_f32,
5324        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_f32,
5325        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_f32,
5326        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_f32,
5327    },
5328);
5329cpu_cast_wrapper!(
5330    cast_to_f64_cpu_wrapper,
5331    DType::F64,
5332    "f64",
5333    {
5334        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_f64,
5335        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_f64,
5336        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_f64,
5337        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_f64,
5338        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_f64,
5339        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_f64,
5340        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_f64,
5341        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_f64,
5342        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_f64,
5343        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_f64,
5344        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_f64,
5345    },
5346);
5347cpu_cast_wrapper!(
5348    cast_to_bf16_cpu_wrapper,
5349    DType::BF16,
5350    "bf16",
5351    {
5352        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_bf16,
5353        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_bf16,
5354        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_bf16,
5355        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_bf16,
5356        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_bf16,
5357        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_bf16,
5358        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_bf16,
5359        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_bf16,
5360        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_bf16,
5361        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_bf16,
5362        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_bf16,
5363    },
5364);
5365cpu_cast_wrapper!(
5366    cast_to_f16_cpu_wrapper,
5367    DType::F16,
5368    "f16",
5369    {
5370        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_f16,
5371        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_f16,
5372        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_f16,
5373        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_f16,
5374        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_f16,
5375        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_f16,
5376        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_f16,
5377        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_f16,
5378        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_f16,
5379        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_f16,
5380        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_f16,
5381    },
5382);
5383cpu_cast_wrapper!(
5384    cast_to_f8e4m3_cpu_wrapper,
5385    DType::F8E4M3,
5386    "f8e4m3",
5387    {
5388        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_f8e4m3,
5389        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_f8e4m3,
5390        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_f8e4m3,
5391        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_f8e4m3,
5392        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_f8e4m3,
5393        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_f8e4m3,
5394        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_f8e4m3,
5395        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_f8e4m3,
5396        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_f8e4m3,
5397        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_f8e4m3,
5398        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_f8e4m3,
5399    },
5400);
5401cpu_cast_wrapper!(
5402    cast_to_u8_cpu_wrapper,
5403    DType::U8,
5404    "u8",
5405    {
5406        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_u8,
5407        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_u8,
5408        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_u8,
5409        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_u8,
5410        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_u8,
5411        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_u8,
5412        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_u8,
5413        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_u8,
5414        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_u8,
5415        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_u8,
5416        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_u8,
5417    },
5418);
5419cpu_cast_wrapper!(
5420    cast_to_i8_cpu_wrapper,
5421    DType::I8,
5422    "i8",
5423    {
5424        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_i8,
5425        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_i8,
5426        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_i8,
5427        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_i8,
5428        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i8,
5429        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_i8,
5430        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_i8,
5431        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_i8,
5432        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_i8,
5433        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_i8,
5434        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_i8,
5435    },
5436);
5437cpu_cast_wrapper!(
5438    cast_to_u32_cpu_wrapper,
5439    DType::U32,
5440    "u32",
5441    {
5442        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_u32,
5443        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_u32,
5444        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_u32,
5445        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_u32,
5446        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_u32,
5447        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_u32,
5448        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_u32,
5449        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_u32,
5450        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_u32,
5451        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_u32,
5452        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_u32,
5453    },
5454);
5455cpu_cast_wrapper!(
5456    cast_to_i16_cpu_wrapper,
5457    DType::I16,
5458    "i16",
5459    {
5460        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_i16,
5461        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_i16,
5462        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_i16,
5463        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_i16,
5464        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i16,
5465        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_i16,
5466        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_i16,
5467        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_i16,
5468        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_i16,
5469        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_i16,
5470        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_i16,
5471    },
5472);
5473cpu_cast_wrapper!(
5474    cast_to_i32_cpu_wrapper,
5475    DType::I32,
5476    "i32",
5477    {
5478        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_i32,
5479        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_i32,
5480        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_i32,
5481        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_i32,
5482        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i32,
5483        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_i32,
5484        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_i32,
5485        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_i32,
5486        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_i32,
5487        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_i32,
5488        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_i32,
5489    },
5490);
5491cpu_cast_wrapper!(
5492    cast_to_i64_cpu_wrapper,
5493    DType::I64,
5494    "i64",
5495    {
5496        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_i64,
5497        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_i64,
5498        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_i64,
5499        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_i64,
5500        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i64,
5501        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_i64,
5502        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_i64,
5503        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_i64,
5504        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_i64,
5505        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_i64,
5506        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_i64,
5507    },
5508);
5509
5510// Cast TO Bool (GAP-168) -- the 12th target. `Bool` is byte-backed like `U8`,
5511// so this wrapper exists precisely to keep the two DISTINGUISHABLE: every arm
5512// runs a real `!= 0` conversion rather than reinterpreting the source bytes.
5513cpu_cast_wrapper!(
5514    cast_to_bool_cpu_wrapper,
5515    DType::Bool,
5516    "bool",
5517    {
5518        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_bool,
5519        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_bool,
5520        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_bool,
5521        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_bool,
5522        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_bool,
5523        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_bool,
5524        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_bool,
5525        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_bool,
5526        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_bool,
5527        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_bool,
5528        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_bool,
5529    },
5530);
5531
5532/// Dispatch wrapper for `(MatMul, F32, Cpu)`. Extracts the
5533/// `OpParams::Matmul { m, n, k }` and forwards to the typed
5534/// kernel. Both inputs are guaranteed contiguous f32 by the
5535/// executor's auto-Contiguize pass.
5536///
5537/// `pub(crate)` so the FKC `CpuLinkRegistry` (`fkc::cpu_link`,
5538/// [`crate::fkc::CPU_MATMUL_ENTRY_POINTS`]) can resolve the matmul contract's
5539/// `entry_point` symbol to this exact wrapper fn-pointer.
5540pub(crate) fn matmul_f32_cpu_wrapper(
5541    inputs: &[Arc<RwLock<Storage>>],
5542    outputs: &mut [Arc<RwLock<Storage>>],
5543    _layouts: &[Layout],
5544    params: &OpParams,
5545) -> Result<()> {
5546    if inputs.len() != 2 {
5547        return Err(Error::Msg(format!(
5548            "matmul wrapper expects 2 inputs, got {}",
5549            inputs.len(),
5550        ))
5551        .bt());
5552    }
5553    if outputs.len() != 1 {
5554        return Err(Error::Msg(format!(
5555            "matmul wrapper expects 1 output, got {}",
5556            outputs.len(),
5557        ))
5558        .bt());
5559    }
5560    let (lhs_batch_dims, rhs_batch_dims, m, n, k, m_compute) = match params {
5561        OpParams::Matmul {
5562            lhs_batch_dims,
5563            rhs_batch_dims,
5564            m,
5565            n,
5566            k,
5567            m_compute,
5568        } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k, m_compute),
5569        other => {
5570            return Err(Error::Msg(format!(
5571                "matmul wrapper expects OpParams::Matmul, got {other:?}",
5572            ))
5573            .bt());
5574        }
5575    };
5576    // Data-determined-M (sparse MoE): `m` is the row capacity; compute only
5577    // `rows`. `Deferred` must have been resolved at execute before the
5578    // kernel runs (see resolve_deferred_matmul).
5579    let rows = match m_compute {
5580        MatmulM::All => m,
5581        MatmulM::Rows(c) => *c,
5582        MatmulM::Deferred(d) => {
5583            return Err(Error::Msg(format!(
5584                "matmul_f32 wrapper: unresolved data-determined row count {d:?} \
5585                 (must be resolved at execute before the kernel runs)",
5586            ))
5587            .bt());
5588        }
5589    };
5590    let lhs_guard = read_storage(&inputs[0])?;
5591    let rhs_guard = read_storage(&inputs[1])?;
5592    let mut out_guard = write_storage(&outputs[0])?;
5593    let lhs_cpu = cpu_input(&lhs_guard)?;
5594    let rhs_cpu = cpu_input(&rhs_guard)?;
5595    let out_cpu = cpu_output(&mut out_guard)?;
5596    fuel_cpu_backend::byte_kernels::matmul_f32_capacity(
5597        lhs_cpu,
5598        rhs_cpu,
5599        out_cpu,
5600        lhs_batch_dims,
5601        rhs_batch_dims,
5602        m,
5603        rows,
5604        n,
5605        k,
5606    )
5607}
5608
5609/// Build a CPU matmul wrapper for any element type. The wrapper
5610/// shape is identical across dtypes — it just forwards to a typed
5611/// kernel that has the matching `(lhs, rhs, out, lhs_batch_dims,
5612/// rhs_batch_dims, m, n, k) -> Result<()>` signature.
5613macro_rules! cpu_matmul_wrapper {
5614    ($wrapper:ident, $kernel:path, $type_name:literal) => {
5615        // `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the matmul
5616        // contract's `entry_point` symbols to these wrapper fn-pointers.
5617        pub(crate) fn $wrapper(
5618            inputs: &[Arc<RwLock<Storage>>],
5619            outputs: &mut [Arc<RwLock<Storage>>],
5620            _layouts: &[Layout],
5621            params: &OpParams,
5622        ) -> Result<()> {
5623            if inputs.len() != 2 {
5624                return Err(Error::Msg(format!(
5625                    "matmul wrapper expects 2 inputs, got {}",
5626                    inputs.len(),
5627                ))
5628                .bt());
5629            }
5630            if outputs.len() != 1 {
5631                return Err(Error::Msg(format!(
5632                    "matmul wrapper expects 1 output, got {}",
5633                    outputs.len(),
5634                ))
5635                .bt());
5636            }
5637            let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
5638                OpParams::Matmul {
5639                    lhs_batch_dims,
5640                    rhs_batch_dims,
5641                    m,
5642                    n,
5643                    k,
5644                    ..
5645                } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k),
5646                other => {
5647                    return Err(Error::Msg(format!(
5648                        "matmul wrapper expects OpParams::Matmul, got {other:?}",
5649                    ))
5650                    .bt())
5651                }
5652            };
5653            let lhs_guard = read_storage(&inputs[0])?;
5654            let rhs_guard = read_storage(&inputs[1])?;
5655            let mut out_guard = write_storage(&outputs[0])?;
5656            let lhs_cpu = cpu_input(&lhs_guard)?;
5657            let rhs_cpu = cpu_input(&rhs_guard)?;
5658            let out_cpu = cpu_output(&mut out_guard)?;
5659            let _ = $type_name;
5660            $kernel(
5661                lhs_cpu,
5662                rhs_cpu,
5663                out_cpu,
5664                lhs_batch_dims,
5665                rhs_batch_dims,
5666                m,
5667                n,
5668                k,
5669            )
5670        }
5671    };
5672}
5673
5674cpu_matmul_wrapper!(
5675    matmul_bf16_cpu_wrapper,
5676    fuel_cpu_backend::byte_kernels::matmul_bf16,
5677    "matmul_bf16"
5678);
5679cpu_matmul_wrapper!(
5680    matmul_f16_cpu_wrapper,
5681    fuel_cpu_backend::byte_kernels::matmul_f16,
5682    "matmul_f16"
5683);
5684cpu_matmul_wrapper!(
5685    matmul_f32_bf16_cpu_wrapper,
5686    fuel_cpu_backend::byte_kernels::matmul_f32_bf16,
5687    "matmul_f32_bf16"
5688);
5689cpu_matmul_wrapper!(
5690    matmul_f32_f16_cpu_wrapper,
5691    fuel_cpu_backend::byte_kernels::matmul_f32_f16,
5692    "matmul_f32_f16"
5693);
5694cpu_matmul_wrapper!(
5695    matmul_i8_cpu_wrapper,
5696    fuel_cpu_backend::byte_kernels::matmul_i8,
5697    "matmul_i8"
5698);
5699cpu_matmul_wrapper!(
5700    matmul_u8_cpu_wrapper,
5701    fuel_cpu_backend::byte_kernels::matmul_u8,
5702    "matmul_u8"
5703);
5704
5705/// f64 mirror of [`matmul_f32_cpu_wrapper`]. Same OpKind
5706/// (MatMul); the binding-table key picks this entry when the
5707/// node's dtype is F64.
5708///
5709/// `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the matmul contract's
5710/// `entry_point` symbol to this exact wrapper fn-pointer.
5711pub(crate) fn matmul_f64_cpu_wrapper(
5712    inputs: &[Arc<RwLock<Storage>>],
5713    outputs: &mut [Arc<RwLock<Storage>>],
5714    _layouts: &[Layout],
5715    params: &OpParams,
5716) -> Result<()> {
5717    if inputs.len() != 2 {
5718        return Err(Error::Msg(format!(
5719            "matmul wrapper expects 2 inputs, got {}",
5720            inputs.len(),
5721        ))
5722        .bt());
5723    }
5724    if outputs.len() != 1 {
5725        return Err(Error::Msg(format!(
5726            "matmul wrapper expects 1 output, got {}",
5727            outputs.len(),
5728        ))
5729        .bt());
5730    }
5731    let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
5732        OpParams::Matmul {
5733            lhs_batch_dims,
5734            rhs_batch_dims,
5735            m,
5736            n,
5737            k,
5738            ..
5739        } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k),
5740        other => {
5741            return Err(Error::Msg(format!(
5742                "matmul wrapper expects OpParams::Matmul, got {other:?}",
5743            ))
5744            .bt());
5745        }
5746    };
5747    let lhs_guard = read_storage(&inputs[0])?;
5748    let rhs_guard = read_storage(&inputs[1])?;
5749    let mut out_guard = write_storage(&outputs[0])?;
5750    let lhs_cpu = cpu_input(&lhs_guard)?;
5751    let rhs_cpu = cpu_input(&rhs_guard)?;
5752    let out_cpu = cpu_output(&mut out_guard)?;
5753    fuel_cpu_backend::byte_kernels::matmul_f64(
5754        lhs_cpu,
5755        rhs_cpu,
5756        out_cpu,
5757        lhs_batch_dims,
5758        rhs_batch_dims,
5759        m,
5760        n,
5761        k,
5762    )
5763}
5764
5765/// Dispatch wrapper for `(OpKind::Copy, [T, T], Cpu)` — copy from a
5766/// CPU source storage into a freshly-allocated output on any target
5767/// backend. The executor allocates the output on `target_location`
5768/// via [`crate::pipelined::WorkItemKind::Copy`] before this wrapper
5769/// runs; the wrapper switches on the output's `BackendStorage`
5770/// variant to pick the H2D path.
5771///
5772/// - CPU output → memcpy (CPU→CPU).
5773/// - CUDA output → `CudaStorageBytes::write_from_host` (H2D via
5774///   `cuMemcpyHtoD`).
5775/// - Vulkan output → `VulkanBackend::write_bytes` (H2D via staging
5776///   buffer + `vkCmdCopyBuffer`).
5777///
5778/// Bridge-retirement Phase 2 (CPU→CPU) + Phase 3b (CPU→GPU). The
5779/// wrapper-internal match on output variant is the pragmatic shape
5780/// while the binding-table key `(op, dtypes, source_backend)` doesn't
5781/// yet encode the target. A future binding-table-key extension would
5782/// split this into per-(source, target) sub-wrappers without changing
5783/// the call surface.
5784///
5785/// Replaces:
5786/// * The per-variant `match self` in `BackendStorage::read_to_cpu_bytes`
5787///   (Phase 2 deletion).
5788/// * `fuel-tensor::pipelined_bridge::upload_host_buffer`'s per-
5789///   `DeviceLocation` match (Phase 3b deletion).
5790fn copy_from_cpu_wrapper(
5791    inputs: &[Arc<RwLock<Storage>>],
5792    outputs: &mut [Arc<RwLock<Storage>>],
5793    _layouts: &[Layout],
5794    _params: &OpParams,
5795) -> Result<()> {
5796    if inputs.len() != 1 || outputs.len() != 1 {
5797        return Err(Error::Msg(format!(
5798            "copy_from_cpu_wrapper: expected 1 input + 1 output, got {} + {}",
5799            inputs.len(),
5800            outputs.len(),
5801        ))
5802        .bt());
5803    }
5804    let in_guard = read_storage(&inputs[0])?;
5805    let src = cpu_input(&in_guard)?;
5806    let mut out_guard = write_storage(&outputs[0])?;
5807    // Truncate source bytes to the destination's byte count — the
5808    // executor allocates the output exactly `node.shape.elem_count *
5809    // dtype.size_in_bytes()` bytes. Host buffers from Op::Const slots
5810    // may be larger (shared storage across views); we copy only the
5811    // destination-sized prefix. Mirrors the deleted
5812    // `upload_host_buffer`'s `truncate_to` parameter.
5813    let n_out = out_guard.inner.len_bytes();
5814    let n_src = src.len_bytes();
5815    let n = n_src.min(n_out);
5816    let src_slice = &src.bytes()[..n];
5817    match &mut out_guard.inner {
5818        BackendStorage::Cpu(dst) => {
5819            dst.bytes_mut()[..n].copy_from_slice(src_slice);
5820        }
5821        #[cfg(feature = "cuda")]
5822        BackendStorage::Cuda(dst) => {
5823            // CUDA write_from_host requires src.len() == dst.len_bytes.
5824            // The executor sized the output to `n_out`; we truncated
5825            // src to `n` = min(n_src, n_out). When n < n_out the
5826            // remaining bytes stay uninit; for the Op::Const upload
5827            // path this matches the deleted upload_host_buffer's
5828            // behavior (truncated host bytes uploaded as-is).
5829            if n == n_out {
5830                dst.write_from_host(src_slice)?;
5831            } else {
5832                // Pad: copy src into a staging vec sized exactly n_out
5833                // with trailing zeros. Rare path (size mismatch).
5834                let mut staged = vec![0_u8; n_out];
5835                staged[..n].copy_from_slice(src_slice);
5836                dst.write_from_host(&staged)?;
5837            }
5838        }
5839        #[cfg(feature = "vulkan")]
5840        BackendStorage::Vulkan(dst) => {
5841            let backend = dst
5842                .backend()
5843                .ok_or_else(|| {
5844                    Error::Msg(
5845                        "copy_from_cpu_wrapper: Vulkan output has no attached \
5846                 backend handle. The executor's Op::Copy arm must allocate \
5847                 via VulkanBackend::alloc_bytes_handle (which attaches \
5848                 the handle)."
5849                            .to_string(),
5850                    )
5851                    .bt()
5852                })?
5853                .clone();
5854            if n == n_out {
5855                backend.write_bytes(dst, src_slice)?;
5856            } else {
5857                let mut staged = vec![0_u8; n_out];
5858                staged[..n].copy_from_slice(src_slice);
5859                backend.write_bytes(dst, &staged)?;
5860            }
5861        }
5862        #[allow(unreachable_patterns)]
5863        other => {
5864            return Err(Error::Msg(format!(
5865                "copy_from_cpu_wrapper: output backend not wired ({other:?}); \
5866                 CPU + CUDA + Vulkan covered, Metal extends when its \
5867                 byte-storage substrate is ready.",
5868            ))
5869            .bt());
5870        }
5871    }
5872    Ok(())
5873}
5874
5875/// The authored CPU elementwise-binary kernel contract, embedded into the
5876/// binary. This is the PRODUCTION `include_str!` (distinct from the identical
5877/// path used in the `fkc::register` test module); `register_cpu_binary_from_contract`
5878/// parses + lowers it and binds the family FROM THE CONTRACT.
5879const CPU_ELEMENTWISE_BINARY_CONTRACT: &str =
5880    include_str!("../kernel-contracts/cpu/elementwise-binary.fkc.md");
5881
5882/// Register the CPU elementwise-binary family (8 ops × 4 dtypes = 32
5883/// bindings) by IMPORTING its FKC kernel contract — the FIRST production
5884/// FKC consumer. FKC is unconditional core infrastructure, so this is the
5885/// ONE registration path for the family: there is no hand-written fallback
5886/// (deleting it was the point — a build that lost the importer would silently
5887/// lose the family).
5888///
5889/// The authored contract `fuel-dispatch/kernel-contracts/cpu/elementwise-binary.fkc.md`
5890/// is parsed + lowered and each `entry_point` symbol resolved through the
5891/// production [`crate::fkc::CpuLinkRegistry`] to the exact same wrapper
5892/// fn-pointers the CPU backend exposes (`add_elementwise_f32_cpu_wrapper`, …;
5893/// the very map [`crate::fkc::CPU_BINARY_ENTRY_POINTS`] holds). Relative to the
5894/// deleted hand-written registrations this is behavior-preserving: identical
5895/// kernels + caps; the binding's `kernel_source` becomes the contract's
5896/// `"portable-cpu"` tag and its precision the contract's audited claim. Cost is
5897/// preserved because this runs BEFORE the `fill_unset_cpu_cost` pass, which
5898/// upgrades the imported entries' `unknown_cost` sentinel to the same OpKind
5899/// cost fn every other CPU primitive gets.
5900///
5901/// Fused-registry decision: the elementwise-binary family declares NO fused
5902/// ops (`provider.fused` is empty), and `register_cpu_kernels` threads only a
5903/// `KernelBindingTable` — there is no paired global `FusedKernelRegistry` at
5904/// this seam (the static `crate::fused::default_kernel_registry()` is built
5905/// independently). So `register_into`'s required fused argument is a local
5906/// throwaway that provably stays empty.
5907///
5908/// Init-boundary fail-fast: a parse/lower/link failure of the embedded,
5909/// authored contract is a programmer error surfaced once here via `expect`
5910/// (mirroring the `finalize().expect(...)` convention in [`global_bindings`]).
5911/// It cannot fail for a runtime-data reason — the contract is `include_str!`'d
5912/// into the binary and the link registry is exhaustive for this family.
5913fn register_cpu_binary_from_contract(table: &mut KernelBindingTable) {
5914    let provider = crate::fkc::import_bundle_str(
5915        CPU_ELEMENTWISE_BINARY_CONTRACT,
5916        &crate::fkc::CpuLinkRegistry,
5917    )
5918    .expect(
5919        "authored CPU elementwise-binary contract must import \
5920                 (embedded via include_str!, resolved through CpuLinkRegistry)",
5921    );
5922    debug_assert!(
5923        provider.fused.is_empty(),
5924        "elementwise-binary contract declares no fused ops",
5925    );
5926    let mut fused = crate::fused::FusedKernelRegistry::new();
5927    provider
5928        .register_into(table, &mut fused)
5929        .expect("CPU elementwise-binary contract must register into the binding table");
5930}
5931
5932/// The authored CPU affine / clamp / powi kernel contract, embedded into the
5933/// binary (the PRODUCTION `include_str!`). `register_cpu_affine_clamp_powi_from_contract`
5934/// parses + lowers it and binds the family FROM THE CONTRACT.
5935const CPU_AFFINE_CLAMP_POWI_CONTRACT: &str =
5936    include_str!("../kernel-contracts/cpu/affine-clamp-powi.fkc.md");
5937
5938/// Register the CPU out-of-place scalar-param family (affine/clamp/powi × 4
5939/// dtypes + powi_backward × 4 = 16 bindings) by IMPORTING its FKC kernel
5940/// contract — the second production FKC consumer, mirroring
5941/// [`register_cpu_binary_from_contract`]. FKC is unconditional core
5942/// infrastructure, so this is the ONE registration path for the family: the
5943/// hand-written `table.register(...)` calls it used to carry are DELETED.
5944///
5945/// Each `entry_point` symbol resolves through the production
5946/// [`crate::fkc::CpuLinkRegistry`] (now chaining
5947/// [`crate::fkc::CPU_AFFINE_CLAMP_POWI_ENTRY_POINTS`]) to the exact same wrapper
5948/// fn-pointers the CPU backend exposes. Behavior-preserving vs. the deleted
5949/// hand-written path: identical kernels + caps (contiguous-only); the binding's
5950/// `kernel_source` becomes the contract's `"portable-cpu"` tag and its precision
5951/// the contract's audited bit-stable claim. Cost is preserved because this runs
5952/// BEFORE `fill_unset_cpu_cost`, which upgrades the imported entries'
5953/// `unknown_cost` sentinel to the same OpKind cost fn every CPU primitive gets.
5954///
5955/// The scalar params (affine mul/add, clamp min/max, powi exp) ride in
5956/// `OpParams`, NOT the dtype-list, so the imported binding keys are `[t, t]` for
5957/// the single-input forward ops and `[t, t, t]` for the two-input
5958/// `powi_backward` — identical to the deleted `&unary(t)` / `&binary(t)` regs.
5959///
5960/// The family declares NO fused ops (the FusedOps::POWI_BACKWARD fused-registry
5961/// registration is a SEPARATE seam, untouched), so `register_into`'s required
5962/// fused argument is a local throwaway that provably stays empty.
5963fn register_cpu_affine_clamp_powi_from_contract(table: &mut KernelBindingTable) {
5964    let provider =
5965        crate::fkc::import_bundle_str(CPU_AFFINE_CLAMP_POWI_CONTRACT, &crate::fkc::CpuLinkRegistry)
5966            .expect(
5967                "authored CPU affine/clamp/powi contract must import \
5968                 (embedded via include_str!, resolved through CpuLinkRegistry)",
5969            );
5970    debug_assert!(
5971        provider.fused.is_empty(),
5972        "affine/clamp/powi contract declares no fused ops",
5973    );
5974    let mut fused = crate::fused::FusedKernelRegistry::new();
5975    provider
5976        .register_into(table, &mut fused)
5977        .expect("CPU affine/clamp/powi contract must register into the binding table");
5978}
5979
5980/// The authored CPU elementwise-unary kernel contract, embedded into the binary
5981/// (the PRODUCTION `include_str!`). `register_cpu_unary_from_contract` parses +
5982/// lowers it and binds the family FROM THE CONTRACT.
5983const CPU_ELEMENTWISE_UNARY_CONTRACT: &str =
5984    include_str!("../kernel-contracts/cpu/elementwise-unary.fkc.md");
5985
5986/// Register the CPU elementwise-unary family (22 ops × 4 dtypes = 88 bindings)
5987/// by IMPORTING its FKC kernel contract — the third production FKC consumer,
5988/// mirroring [`register_cpu_binary_from_contract`] /
5989/// [`register_cpu_affine_clamp_powi_from_contract`]. FKC is unconditional core
5990/// infrastructure, so this is the ONE registration path for the family: the
5991/// hand-written `table.register(...)` calls it used to carry are DELETED.
5992///
5993/// This is the **first** consumer of the §3.4 multi-dtype fan-out: each per-op
5994/// section declares a BASE `entry_point` (e.g. `…::relu`) and enumerates
5995/// `dtypes: [F32, F64, BF16, F16]`; the importer fans it into one binding per
5996/// dtype, resolving `<base>_<dtype>` through the production
5997/// [`crate::fkc::CpuLinkRegistry`] (now chaining
5998/// [`crate::fkc::CPU_UNARY_ENTRY_POINTS`]) to the exact same wrapper fn-pointers
5999/// the CPU backend exposes. Behavior-preserving vs. the deleted hand-written
6000/// path: identical kernels + caps (contiguous-only, `[t, t]` keys); the
6001/// binding's `kernel_source` becomes the contract's `"portable-cpu"` tag and its
6002/// precision the contract's bit-stable claim. Cost is preserved because this
6003/// runs BEFORE `fill_unset_cpu_cost`, which upgrades the imported entries'
6004/// `unknown_cost` sentinel to the same OpKind cost fn every CPU primitive gets.
6005///
6006/// `gelu_tanh` (`OpKind::GeluTanhElementwise`, base `gelu_tanh`) and `gelu`
6007/// (`OpKind::GeluElementwise`, base `gelu`) stay DISTINCT — the exact-erf
6008/// GELU must never be confused with the tanh approximation under a Judge epsilon.
6009///
6010/// The family declares NO fused ops, so `register_into`'s required fused argument
6011/// is a local throwaway that provably stays empty.
6012fn register_cpu_unary_from_contract(table: &mut KernelBindingTable) {
6013    let provider =
6014        crate::fkc::import_bundle_str(CPU_ELEMENTWISE_UNARY_CONTRACT, &crate::fkc::CpuLinkRegistry)
6015            .expect(
6016                "authored CPU elementwise-unary contract must import \
6017                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6018            );
6019    debug_assert!(
6020        provider.fused.is_empty(),
6021        "elementwise-unary contract declares no fused ops",
6022    );
6023    let mut fused = crate::fused::FusedKernelRegistry::new();
6024    provider
6025        .register_into(table, &mut fused)
6026        .expect("CPU elementwise-unary contract must register into the binding table");
6027}
6028
6029/// The authored CPU compare + where kernel contract, embedded into the binary
6030/// (the PRODUCTION `include_str!`). `register_cpu_compare_where_from_contract`
6031/// parses + lowers it and binds the family FROM THE CONTRACT.
6032const CPU_COMPARE_WHERE_CONTRACT: &str =
6033    include_str!("../kernel-contracts/cpu/compare-where.fkc.md");
6034
6035/// Register the CPU compare (6 ops × 4 dtypes = 24) + where (1 op × 4 dtypes =
6036/// 4) family — 28 bindings — by IMPORTING its FKC kernel contract, the fourth
6037/// production FKC consumer (mirroring the binary / affine-clamp-powi / unary
6038/// importers). FKC is unconditional core infrastructure, so this is the ONE
6039/// registration path for the family: the hand-written `table.register(...)`
6040/// calls it used to carry are DELETED.
6041///
6042/// Two contract shapes, both resolved through the production
6043/// [`crate::fkc::CpuLinkRegistry`] (now chaining
6044/// [`crate::fkc::CPU_COMPARE_ENTRY_POINTS`] + [`crate::fkc::CPU_WHERE_ENTRY_POINTS`]):
6045///  - the 24 per-(op,dtype) COMPARE thunks are single-dtype sections → each
6046///    resolves its declared `_u8`-suffixed symbol (`eq_f32_u8`, …) AS-IS; the
6047///    binding key is `[T, T, U8]` (output is the `fixed(U8)` mask), identical
6048///    to the deleted `&compare(t)` regs.
6049///  - the single WHERE section rides the §3.4 multi-dtype fan-out — its BASE
6050///    `entry_point` `…::where` expands to `where_{f32,f64,bf16,f16}`, one
6051///    binding per dtype, key `[U8, T, T, T]` (cond U8 + `passthrough(a)` → T),
6052///    identical to the deleted `&where_dts(t)` regs.
6053///
6054/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6055/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6056/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
6057/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`,
6058/// which upgrades the imported entries' `unknown_cost` sentinel to the same
6059/// OpKind cost fn every CPU primitive gets. The `## compare` chassis umbrella is
6060/// `registrable: false` (§3.10) and never registers. The family declares NO
6061/// fused ops, so `register_into`'s required fused argument is a local throwaway
6062/// that provably stays empty.
6063fn register_cpu_compare_where_from_contract(table: &mut KernelBindingTable) {
6064    let provider =
6065        crate::fkc::import_bundle_str(CPU_COMPARE_WHERE_CONTRACT, &crate::fkc::CpuLinkRegistry)
6066            .expect(
6067                "authored CPU compare/where contract must import \
6068                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6069            );
6070    debug_assert!(
6071        provider.fused.is_empty(),
6072        "compare/where contract declares no fused ops",
6073    );
6074    let mut fused = crate::fused::FusedKernelRegistry::new();
6075    provider
6076        .register_into(table, &mut fused)
6077        .expect("CPU compare/where contract must register into the binding table");
6078}
6079
6080/// The authored CPU reduce kernel contract, embedded into the binary (the
6081/// PRODUCTION `include_str!`). `register_cpu_reduce_from_contract` parses +
6082/// lowers it and binds the family FROM THE CONTRACT.
6083const CPU_REDUCE_CONTRACT: &str = include_str!("../kernel-contracts/cpu/reduce.fkc.md");
6084
6085/// Register the CPU per-axis reduce family (Sum/Mean/Max/Min × 4 dtypes = 16
6086/// bindings) by IMPORTING its FKC kernel contract, the fifth production FKC
6087/// consumer (mirroring the binary / affine-clamp-powi / unary / compare-where
6088/// importers). FKC is unconditional core infrastructure, so this is the ONE
6089/// registration path for the family: the hand-written `table.register(...)`
6090/// calls it used to carry are DELETED.
6091///
6092/// Each of the 16 per-(op, dtype) sections (`## sum_reduce_f32`, …) is a SPECIFIC
6093/// single-dtype contract with a concrete `entry_point` (`…::sum_reduce_f32`), so
6094/// none of them fan — the importer resolves each declared symbol AS-IS through
6095/// the production [`crate::fkc::CpuLinkRegistry`] (now chaining
6096/// [`crate::fkc::CPU_REDUCE_ENTRY_POINTS`]) to the exact wrapper fn-pointer the
6097/// CPU backend exposes. The binding key is `[T, T]` (input + `passthrough(input)`
6098/// output; the reduce axes + keepdim ride in `OpParams::Reduce`, NOT the
6099/// dtype-list), identical to the deleted `&unary(t)` regs.
6100///
6101/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6102/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6103/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
6104/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`, which
6105/// upgrades the imported entries' `unknown_cost` sentinel to the same OpKind cost
6106/// fn every CPU primitive gets. The `## reduce` chassis umbrella is
6107/// `registrable: false` (§3.10) and never registers (without it the chassis would
6108/// double-register `SumReduce`/`[F32]` → `DuplicateKernelRef` at init). The
6109/// f32-only `argmax_dim_f32` / `argmin_dim_f32` sections are `registrable: false`
6110/// (DEFERRED — production registers `Arg{Max,Min}Dim` for ALL input dtypes via
6111/// the hand-written `arg{max,min}_dim_u32_cpu_dispatch`, which stays untouched
6112/// below). The family declares NO fused ops, so `register_into`'s required fused
6113/// argument is a local throwaway that provably stays empty.
6114fn register_cpu_reduce_from_contract(table: &mut KernelBindingTable) {
6115    let provider = crate::fkc::import_bundle_str(CPU_REDUCE_CONTRACT, &crate::fkc::CpuLinkRegistry)
6116        .expect(
6117            "authored CPU reduce contract must import \
6118                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6119        );
6120    debug_assert!(
6121        provider.fused.is_empty(),
6122        "reduce contract declares no fused ops",
6123    );
6124    let mut fused = crate::fused::FusedKernelRegistry::new();
6125    provider
6126        .register_into(table, &mut fused)
6127        .expect("CPU reduce contract must register into the binding table");
6128}
6129
6130/// The authored CPU reduce-to kernel contract, embedded into the binary (the
6131/// PRODUCTION `include_str!`). `register_cpu_reduce_to_from_contract` parses +
6132/// lowers it and binds the family FROM THE CONTRACT.
6133const CPU_REDUCE_TO_CONTRACT: &str = include_str!("../kernel-contracts/cpu/reduce-to.fkc.md");
6134
6135/// Register the CPU broadcast-target reduce-to family (ReduceSumTo /
6136/// ReduceMaxTo × 4 dtypes = 8, key `[T, T]`; ReduceMaxToBackward × 4 dtypes = 4,
6137/// key `[T, T, T]` = 12 bindings) by IMPORTING its FKC kernel contract, the
6138/// sixth production FKC consumer (mirroring the binary / affine-clamp-powi /
6139/// unary / compare-where / reduce importers). FKC is unconditional core
6140/// infrastructure, so this is the ONE registration path for the family: the
6141/// hand-written `table.register(...)` calls it used to carry are DELETED.
6142///
6143/// Each of the 12 per-(op, dtype) sections (`## reduce_sum_to_f32`, …) is a
6144/// SPECIFIC single-dtype contract with a concrete `entry_point`
6145/// (`…::reduce_sum_to_f32`), so none of them fan — the importer resolves each
6146/// declared symbol AS-IS through the production [`crate::fkc::CpuLinkRegistry`]
6147/// (now chaining [`crate::fkc::CPU_REDUCE_TO_ENTRY_POINTS`]) to the exact
6148/// wrapper fn-pointer the CPU backend exposes. The forward binding key is
6149/// `[T, T]` (input + `passthrough(input)` output — the target
6150/// `input_shape`/`output_shape` ride in `OpParams::ReduceSumTo` /
6151/// `OpParams::ReduceMaxTo`, NOT the dtype-list), identical to the deleted
6152/// `&unary(t)` regs; the backward key is `[T, T, T]` (x, upstream +
6153/// `passthrough(x)` output), identical to the deleted `&binary(t)` regs.
6154///
6155/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6156/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6157/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
6158/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`,
6159/// which upgrades the imported entries' `unknown_cost` sentinel to the same
6160/// OpKind cost fn every CPU primitive gets (ReduceMaxToBackward keeps its own
6161/// `cost_reduce_max_to_backward_cpu` fill). The `## reduce_to` chassis umbrella
6162/// is `registrable: false` (§3.10) and never registers (without it the chassis
6163/// would double-register `ReduceSumTo`/`[F32]` → `DuplicateKernelRef` at init).
6164/// The family declares NO fused ops, so `register_into`'s required fused
6165/// argument is a local throwaway that provably stays empty.
6166fn register_cpu_reduce_to_from_contract(table: &mut KernelBindingTable) {
6167    let provider =
6168        crate::fkc::import_bundle_str(CPU_REDUCE_TO_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6169            "authored CPU reduce-to contract must import \
6170                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6171        );
6172    debug_assert!(
6173        provider.fused.is_empty(),
6174        "reduce-to contract declares no fused ops",
6175    );
6176    let mut fused = crate::fused::FusedKernelRegistry::new();
6177    provider
6178        .register_into(table, &mut fused)
6179        .expect("CPU reduce-to contract must register into the binding table");
6180}
6181
6182/// The authored CPU norm (forward) kernel contract, embedded into the binary
6183/// (the PRODUCTION `include_str!`). `register_cpu_norm_from_contract` parses +
6184/// lowers it and binds the family FROM THE CONTRACT.
6185const CPU_NORM_CONTRACT: &str = include_str!("../kernel-contracts/cpu/norm.fkc.md");
6186
6187/// Register the CPU last-dim NORM (forward) family (Softmax / LogSoftmax /
6188/// RmsNorm / LayerNorm × 4 dtypes = 16 bindings, key `[T, T]`) by IMPORTING its
6189/// FKC kernel contract, the seventh production FKC consumer (mirroring the
6190/// binary / affine-clamp-powi / unary / compare-where / reduce / reduce-to
6191/// importers). FKC is unconditional core infrastructure, so this is the ONE
6192/// registration path for the family: the hand-written `table.register(...)`
6193/// calls it used to carry are DELETED.
6194///
6195/// Each of the 16 per-(op, dtype) sections (`## softmax_last_dim_f32`,
6196/// `## rms_norm_last_dim_f32`, …) is a SPECIFIC single-dtype contract with a
6197/// concrete `entry_point` (`…::softmax_last_dim_f32`), so none of them fan — the
6198/// importer resolves each declared symbol AS-IS through the production
6199/// [`crate::fkc::CpuLinkRegistry`] (now chaining [`crate::fkc::CPU_NORM_ENTRY_POINTS`])
6200/// to the exact wrapper fn-pointer the CPU backend exposes. The binding key is
6201/// `[T, T]` (a SINGLE input + `passthrough(input)` output — the RMS/LayerNorm
6202/// kernels carry NO affine gamma/beta operand; they are the bare normalization,
6203/// and `outer_count` / `last_dim` / `eps` ride in
6204/// `OpParams::{SoftmaxLastDim,LogSoftmaxLastDim,NormLastDim}`, NOT the dtype-list),
6205/// identical to the deleted `&unary(t)` regs.
6206///
6207/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6208/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6209/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
6210/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`, which
6211/// upgrades the imported entries' `unknown_cost` sentinel to the same OpKind cost
6212/// fn every CPU primitive gets. This contract has NO `##` chassis umbrella
6213/// section, so there is nothing marked `registrable: false` and no double-register
6214/// risk. The forward NORM ops are ALSO registered in the `FusedKernelRegistry`
6215/// (`register_default_fused_kernels`, `FusedOps::{SOFTMAX,RMS_NORM,LAYER_NORM}_LAST_DIM`)
6216/// — that is a SEPARATE registry seam and stays untouched; this migration only
6217/// moves the `KernelBindingTable` primitive path. The BACKWARD forms live in a
6218/// separate norm-backward contract and their hand-written regs stay authoritative.
6219/// The family declares NO fused ops, so `register_into`'s required fused argument
6220/// is a local throwaway that provably stays empty.
6221fn register_cpu_norm_from_contract(table: &mut KernelBindingTable) {
6222    let provider = crate::fkc::import_bundle_str(CPU_NORM_CONTRACT, &crate::fkc::CpuLinkRegistry)
6223        .expect(
6224            "authored CPU norm contract must import \
6225                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6226        );
6227    debug_assert!(
6228        provider.fused.is_empty(),
6229        "norm forward contract declares no fused ops",
6230    );
6231    let mut fused = crate::fused::FusedKernelRegistry::new();
6232    provider
6233        .register_into(table, &mut fused)
6234        .expect("CPU norm contract must register into the binding table");
6235}
6236
6237/// The authored CPU norm-BACKWARD kernel contract, embedded into the binary
6238/// (the PRODUCTION `include_str!`). `register_cpu_norm_backward_from_contract`
6239/// parses + lowers it and binds the family FROM THE CONTRACT.
6240const CPU_NORM_BACKWARD_CONTRACT: &str =
6241    include_str!("../kernel-contracts/cpu/norm-backward.fkc.md");
6242
6243/// Register the CPU last-dim NORM-BACKWARD family (Softmax / LogSoftmax /
6244/// RmsNorm / LayerNorm backward × 4 dtypes = 16 bindings, key `[T, T, T]`) by
6245/// IMPORTING its FKC kernel contract, the eighth production FKC consumer (the
6246/// BACKWARD sibling of `register_cpu_norm_from_contract`). FKC is unconditional
6247/// core infrastructure, so this is the ONE registration path for the family: the
6248/// hand-written `table.register(...)` calls it used to carry are DELETED.
6249///
6250/// Each of the 16 per-(op, dtype) sections (`## softmax_last_dim_backward_f32`,
6251/// `## rms_norm_last_dim_backward_f32`, …) is a SPECIFIC single-dtype contract
6252/// with a concrete `entry_point` (`…::softmax_last_dim_backward_f32`), so none of
6253/// them fan — the importer resolves each declared symbol AS-IS through the
6254/// production [`crate::fkc::CpuLinkRegistry`] (now chaining
6255/// [`crate::fkc::CPU_NORM_BACKWARD_ENTRY_POINTS`]) to the exact wrapper
6256/// fn-pointer the CPU backend exposes. The binding key is `[T, T, T]` — the BARE
6257/// backward takes TWO inputs (softmax/log-softmax: forward output `y` + upstream
6258/// gradient `g`; layer/rms-norm: forward input `x` + `g`, stats recomputed from
6259/// `x` + `eps`) and writes ONE `passthrough(y|x)` output; outer_count / last_dim /
6260/// eps ride in `OpParams::{SoftmaxLastDim,LogSoftmaxLastDim,NormLastDim}`, NOT the
6261/// dtype-list — identical to the deleted `&binary(t)` regs.
6262///
6263/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6264/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6265/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
6266/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`, which
6267/// upgrades the imported entries' `unknown_cost` sentinel to the same OpKind cost
6268/// fn every CPU primitive gets. This contract has NO `##` chassis umbrella
6269/// section, so there is nothing marked `registrable: false` and no double-register
6270/// risk. The backward NORM ops are ALSO registered in the `FusedKernelRegistry`
6271/// (`register_default_fused_kernels`, `FusedOps::{SOFTMAX,LAYER_NORM,RMS_NORM}_
6272/// LAST_DIM_BACKWARD`) — that is a SEPARATE registry seam and stays untouched;
6273/// this migration only moves the `KernelBindingTable` primitive path. The family
6274/// declares NO fused ops, so `register_into`'s required fused argument is a local
6275/// throwaway that provably stays empty.
6276fn register_cpu_norm_backward_from_contract(table: &mut KernelBindingTable) {
6277    let provider =
6278        crate::fkc::import_bundle_str(CPU_NORM_BACKWARD_CONTRACT, &crate::fkc::CpuLinkRegistry)
6279            .expect(
6280                "authored CPU norm-backward contract must import \
6281                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6282            );
6283    debug_assert!(
6284        provider.fused.is_empty(),
6285        "norm backward contract declares no fused ops",
6286    );
6287    let mut fused = crate::fused::FusedKernelRegistry::new();
6288    provider
6289        .register_into(table, &mut fused)
6290        .expect("CPU norm-backward contract must register into the binding table");
6291}
6292
6293/// The authored CPU RoPE kernel contract, embedded into the binary (the
6294/// PRODUCTION `include_str!`). `register_cpu_rope_from_contract` parses +
6295/// lowers it and binds the family FROM THE CONTRACT.
6296const CPU_ROPE_CONTRACT: &str = include_str!("../kernel-contracts/cpu/rope.fkc.md");
6297
6298/// Register the CPU RoPE family (rotary position embedding; 1 op × 4 dtypes =
6299/// 4 bindings, key `[T, T, T, T]`) by IMPORTING its FKC kernel contract, the
6300/// ninth production FKC consumer. FKC is unconditional core infrastructure, so
6301/// this is the ONE registration path for the family: the hand-written
6302/// `table.register(Rope, ...)` calls it used to carry are DELETED.
6303///
6304/// Each of the 4 per-dtype sections (`## rope_f32`, `## rope_f64`,
6305/// `## rope_bf16`, `## rope_f16`) is a SPECIFIC single-dtype contract with a
6306/// concrete `entry_point` (`…::rope_f32`), so none of them fan — the importer
6307/// resolves each declared symbol AS-IS through the production
6308/// [`crate::fkc::CpuLinkRegistry`] (now chaining
6309/// [`crate::fkc::CPU_ROPE_ENTRY_POINTS`]) to the exact wrapper fn-pointer the
6310/// CPU backend exposes. The binding key is `[T, T, T, T]` — RoPE takes THREE
6311/// inputs (`x` + the precomputed `cos`/`sin` tables of shape `[seq, head_dim]`,
6312/// all one dtype; the tables broadcast over the `outer_count` axis by the
6313/// kernel re-indexing them per outer, NOT a stride-0 view) and writes ONE
6314/// `passthrough(x)` output; outer_count / seq / head_dim ride in
6315/// `OpParams::Rope`, NOT the dtype-list — identical to the deleted
6316/// `rope_dts(t)` regs.
6317///
6318/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6319/// caps (contiguous-only, even `head_dim`); the binding's `kernel_source`
6320/// becomes the contract's `"portable-cpu"` tag and its precision the contract's
6321/// bit-stable claim. Cost is preserved because this runs BEFORE
6322/// `fill_unset_cpu_cost`, which upgrades the imported entries' `unknown_cost`
6323/// sentinel to the same OpKind cost fn every CPU primitive gets. This contract
6324/// has NO `##` chassis umbrella section, so there is nothing marked
6325/// `registrable: false` and no double-register risk. RoPE is ALSO registered in
6326/// the `FusedKernelRegistry` (`register_default_fused_kernels`,
6327/// `FusedOps::ROPE`) — that is a SEPARATE registry seam and stays untouched;
6328/// this migration only moves the `KernelBindingTable` primitive path. The
6329/// family declares NO fused ops, so `register_into`'s required fused argument is
6330/// a local throwaway that provably stays empty.
6331fn register_cpu_rope_from_contract(table: &mut KernelBindingTable) {
6332    let provider = crate::fkc::import_bundle_str(CPU_ROPE_CONTRACT, &crate::fkc::CpuLinkRegistry)
6333        .expect(
6334            "authored CPU rope contract must import \
6335                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6336        );
6337    debug_assert!(
6338        provider.fused.is_empty(),
6339        "rope contract declares no fused ops",
6340    );
6341    let mut fused = crate::fused::FusedKernelRegistry::new();
6342    provider
6343        .register_into(table, &mut fused)
6344        .expect("CPU rope contract must register into the binding table");
6345}
6346
6347/// The authored CPU SSM / Mamba kernel contract, embedded into the binary (the
6348/// PRODUCTION `include_str!`). `register_cpu_ssm_from_contract` parses + lowers
6349/// it and binds the MIGRATED subset of the family FROM THE CONTRACT.
6350const CPU_SSM_CONTRACT: &str = include_str!("../kernel-contracts/cpu/ssm.fkc.md");
6351
6352/// Register the ENTIRE CPU SSM / Mamba family —
6353/// FusedSoftmaxCrossEntropy (key `[T, I64, F32]`) + CausalConv1d (key
6354/// `[T, T, T, T]`) + SelectiveScan + SsdChunkScan (key `[T; 6]`), 4 ops ×
6355/// 4 dtypes = 16 bindings — by IMPORTING its FKC kernel contract, the tenth
6356/// production FKC consumer. FKC is unconditional core infrastructure, so this is
6357/// the ONE registration path for the whole family: every hand-written
6358/// `table.register(...)` call is DELETED.
6359///
6360/// Each per-(op, dtype) section (`## fused_softmax_cross_entropy_f32`,
6361/// `## selective_scan_f32`, …) is a SPECIFIC single-dtype contract with a
6362/// concrete `entry_point` (`…::selective_scan_f32`), so none of them fan — the
6363/// importer resolves each declared symbol AS-IS through the production
6364/// [`crate::fkc::CpuLinkRegistry`] (chaining [`crate::fkc::CPU_SSM_ENTRY_POINTS`])
6365/// to the exact wrapper fn-pointer the CPU backend exposes. FSCE takes TWO inputs
6366/// (logits T + I64 targets) → ONE `fixed(F32)` output; CausalConv1d takes THREE
6367/// inputs (x, weight, bias) → ONE `passthrough(x)` output; every geometry/knob
6368/// rides in `OpParams`, NOT the dtype-list — identical keys to the deleted
6369/// hand-written regs.
6370///
6371/// **The two SCAN ops (SelectiveScan / SsdChunkScan) return a `return.bundle`**
6372/// multi-output (Option C: one packed buffer `[y ; last_state]`). The importer's
6373/// key-builder (`fkc/lower.rs` `assemble_dtype_variants`) appends the bundle's
6374/// PRIMARY-slot dtype (`passthrough(u)` / `passthrough(x)` → T) to the key tail,
6375/// so a 5-input scan section keys `[T; 6]` (5 inputs + the one bundled output
6376/// slot) — byte-for-byte the deleted hand-written
6377/// `table.register(SelectiveScan/SsdChunkScan, &[dt; 6], ...)` regs. All four
6378/// ops are now `registrable: true` (the default), so `lower_file` imports the
6379/// whole family.
6380///
6381/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6382/// caps (contiguous-only); the binding's
6383/// `kernel_source` becomes the contract's `"portable-cpu"` tag and its
6384/// precision the contract's bit-stable claim. Cost is preserved because this
6385/// runs BEFORE `fill_unset_cpu_cost`, which upgrades the imported entries'
6386/// `unknown_cost` sentinel to the same OpKind cost fn every CPU primitive gets.
6387/// The family declares NO fused ops (the "fused" in FusedSoftmaxCrossEntropy is
6388/// an intra-op softmax+NLL fusion, not a graph `FusedOpId`), so `register_into`'s
6389/// required fused argument is a local throwaway that provably stays empty.
6390fn register_cpu_ssm_from_contract(table: &mut KernelBindingTable) {
6391    let provider = crate::fkc::import_bundle_str(CPU_SSM_CONTRACT, &crate::fkc::CpuLinkRegistry)
6392        .expect(
6393            "authored CPU ssm contract must import \
6394                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6395        );
6396    debug_assert!(
6397        provider.fused.is_empty(),
6398        "ssm contract declares no fused ops",
6399    );
6400    let mut fused = crate::fused::FusedKernelRegistry::new();
6401    provider
6402        .register_into(table, &mut fused)
6403        .expect("CPU ssm contract must register into the binding table");
6404}
6405
6406/// The authored CPU 2D-convolution kernel contract, embedded into the binary
6407/// (the PRODUCTION `include_str!`). `register_cpu_conv_from_contract` parses +
6408/// lowers it and binds the MIGRATED (with-bias) subset of the family FROM THE
6409/// CONTRACT.
6410const CPU_CONV_CONTRACT: &str = include_str!("../kernel-contracts/cpu/conv.fkc.md");
6411
6412/// Register the CPU 2D-convolution family FULLY — Conv2D + ConvTranspose2D at
6413/// BOTH the no-bias key `[T, T, T]` (x, weight + out) and the with-bias key
6414/// `[T, T, T, T]` (x, weight, bias + passthrough(x) output), 2 ops × 4 dtypes ×
6415/// 2 operand-counts = 16 bindings — by IMPORTING its FKC kernel contract, the
6416/// eleventh production FKC consumer. FKC is unconditional core infrastructure,
6417/// so this is the ONE registration path for the whole family: every hand-written
6418/// `table.register(...)` conv call is DELETED.
6419///
6420/// Each per-(op, dtype) section (`## conv2d_f32`, `## conv_transpose2d_f32`, …)
6421/// is a SPECIFIC single-dtype contract with a concrete `entry_point`
6422/// (`…::conv2d_f32`), so none of them dtype-fan — the importer resolves each
6423/// declared symbol AS-IS through the production [`crate::fkc::CpuLinkRegistry`]
6424/// (now chaining [`crate::fkc::CPU_CONV_ENTRY_POINTS`]) to the exact wrapper
6425/// fn-pointer the CPU backend exposes. Conv2D's weight is `[Cout, Cin/groups,
6426/// Kh, Kw]`; ConvTranspose2D's is the transposed `[Cin, Cout/groups, Kh, Kw]`
6427/// and it carries an extra `output_padding` op-param — but both are the same
6428/// (x, weight, optional bias) → one-output (passthrough(x)) accept shape, and
6429/// every geometry knob rides in `OpParams::{Conv2D, ConvTranspose2D}`, NOT the
6430/// dtype-list.
6431///
6432/// **The NO-BIAS key is now CONTRACT-SOURCED.** The conv contract declares
6433/// `bias` as `optional: true`, and the FKC importer's key-builder
6434/// (`fkc/lower.rs` `assemble_dtype_variants`) now supports optional operands: an
6435/// optional LAST input fans each section into TWO keys — one OMITTING `bias`
6436/// (`[T, T, T]`) and one INCLUDING it (`[T, T, T, T]`) — BOTH resolving the SAME
6437/// `entry_point`/wrapper (the same CPU wrapper handles 2 or 3 inputs). The
6438/// former no-bias deferral (hand-written `table.register(Conv2D /
6439/// ConvTranspose2D, &[dt; 3], ...)` regs) is closed and those regs deleted.
6440///
6441/// Behavior-preserving vs. the deleted hand-written path (for both operand-count
6442/// keys): identical kernels + caps (contiguous-only NCHW); the
6443/// binding's `kernel_source` becomes the contract's `"portable-cpu"` tag and its
6444/// precision the contract's bit-stable claim. Cost is preserved because this
6445/// runs BEFORE `fill_unset_cpu_cost`, which upgrades the imported entries'
6446/// `unknown_cost` sentinel to the same OpKind cost fn every CPU primitive gets.
6447/// The family declares NO fused ops (the SEPARATE FusedKernelRegistry
6448/// `FusedOps::{CONV2D, CONV_TRANSPOSE2D}` seam is hand-written, in
6449/// `register_default_fused_kernels`, and stays untouched), so `register_into`'s
6450/// required fused argument is a local throwaway that provably stays empty.
6451fn register_cpu_conv_from_contract(table: &mut KernelBindingTable) {
6452    let provider = crate::fkc::import_bundle_str(CPU_CONV_CONTRACT, &crate::fkc::CpuLinkRegistry)
6453        .expect(
6454            "authored CPU conv contract must import \
6455                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6456        );
6457    debug_assert!(
6458        provider.fused.is_empty(),
6459        "conv contract declares no fused ops",
6460    );
6461    let mut fused = crate::fused::FusedKernelRegistry::new();
6462    provider
6463        .register_into(table, &mut fused)
6464        .expect("CPU conv contract must register into the binding table");
6465}
6466
6467/// The authored CPU **padding** kernel contract, embedded into the binary (the
6468/// PRODUCTION `include_str!`). `register_cpu_padding_from_contract` parses +
6469/// lowers it and binds the FULL family (mode-unified forward `Pad` +
6470/// `PadBackward`) FROM THE CONTRACT.
6471const CPU_PADDING_CONTRACT: &str = include_str!("../kernel-contracts/cpu/padding.fkc.md");
6472
6473/// Register the FULL CPU padding family — mode-unified forward `Pad` × 6 dtypes
6474/// = 6 + `PadBackward` × 4 dtypes = 4 bindings (all key `[T, T]`) — by IMPORTING
6475/// its FKC kernel contract, the twelfth production FKC consumer.
6476///
6477/// - **Forward `Pad`** — the ONE mode-unified `## pad` section declares a BASE
6478///   `entry_point` (`…::pad_cpu`, a synthetic umbrella — the three real mode
6479///   byte-kernels are `pad_{const,reflect,replicate}_cpu`) + the 6 production
6480///   dtypes (`U8/U32/BF16/F16/F32/F64`), so the importer's §3.4 fan-out resolves
6481///   `pad_cpu_<dtype>` — every dtype variant mapping to the ONE mode-dispatching
6482///   `pad_cpu_wrapper` (which selects Constant/Reflect/Replicate at runtime via
6483///   `mode_tag`, incl. the reflect `before/after <= n-1` validation) through the
6484///   production [`crate::fkc::CpuLinkRegistry`] (chaining
6485///   [`crate::fkc::CPU_PADDING_ENTRY_POINTS`]). Key `[T, T]` (input +
6486///   `passthrough(input)` output; the in_shape/out_shape/padding/mode_tag/
6487///   fill_bytes ride in `OpParams::Pad`, NOT the dtype-list) — byte-for-byte the
6488///   deleted hand-written `table.register(Pad, &unary(t), …)` regs. The three
6489///   per-mode sections (`pad_const_cpu` / `pad_reflect_cpu` / `pad_replicate_cpu`)
6490///   and the `pad_walk_cpu` helper are `registrable: false` (§3.10 describe-only
6491///   mode documentation) and never resolve.
6492/// - **`PadBackward`** — each per-dtype section (`## pad_backward_f32`, …) carries
6493///   a SPECIFIC single-dtype `entry_point` (`…::pad_backward_f32`) resolved AS-IS
6494///   (no fan), key `[T, T]` (grad_out + `passthrough(grad_out)` grad_in; the
6495///   in_shape/out_shape/padding/mode_tag ride in `OpParams::PadBackward`) —
6496///   byte-for-byte the deleted `table.register(PadBackward, &unary(t), …)` regs.
6497///   `PadBackward` is per-dtype (unlike the dtype-agnostic forward `Pad`) because
6498///   gradient accumulation is typed (bf16/f16/f32 widen the scratch accumulator
6499///   to f64).
6500///
6501/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6502/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6503/// `"portable-cpu"` tag and its precision the contract's bit-stable claim. Cost
6504/// is preserved because this runs BEFORE `fill_unset_cpu_cost`, which upgrades
6505/// the imported entries' `unknown_cost` sentinel to the same OpKind cost fn every
6506/// CPU primitive gets. The family declares NO fused ops, so `register_into`'s
6507/// required fused argument is a local throwaway that provably stays empty.
6508fn register_cpu_padding_from_contract(table: &mut KernelBindingTable) {
6509    let provider =
6510        crate::fkc::import_bundle_str(CPU_PADDING_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6511            "authored CPU padding contract must import \
6512                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6513        );
6514    debug_assert!(
6515        provider.fused.is_empty(),
6516        "padding contract declares no fused ops",
6517    );
6518    let mut fused = crate::fused::FusedKernelRegistry::new();
6519    provider
6520        .register_into(table, &mut fused)
6521        .expect("CPU padding contract must register into the binding table");
6522}
6523
6524/// The authored CPU **shape-ops** kernel contract, embedded into the binary (the
6525/// PRODUCTION `include_str!`). `register_cpu_shape_ops_from_contract` parses +
6526/// lowers it and binds the MIGRATED subset of the family FROM THE CONTRACT.
6527const CPU_SHAPE_OPS_CONTRACT: &str = include_str!("../kernel-contracts/cpu/shape-ops.fkc.md");
6528
6529/// Register the MIGRATED CPU shape-ops subset — Flip + Roll + Concat +
6530/// MaskedFill + WriteSlice + WriteSliceRotating (dtype-agnostic byte kernels,
6531/// fanned per production dtype) and the four per-dtype CumSum kernels — by
6532/// IMPORTING its FKC kernel contract, the thirteenth production FKC consumer.
6533///
6534/// - **Flip** / **Roll** (key `[T, T]`, 6 dtypes each) and **Concat** (key
6535///   `[T, T]`, 9 dtypes) and **MaskedFill** (key `[T, U8, T]`, 6 dtypes) and
6536///   **WriteSlice** / **WriteSliceRotating** (key `[T, T]`, 6 dtypes each) are
6537///   ONE dtype-agnostic wrapper each. Their sections declare a BASE `entry_point`
6538///   (`…::flip_cpu`, …) + an enumerated `dtypes` list trimmed to the wired set,
6539///   so the §3.4 fan-out resolves `<base>_<dtype>` (`flip_cpu_f32`, …) — a
6540///   fabricated per-dtype symbol that every variant maps to the SAME wrapper via
6541///   [`crate::fkc::CPU_SHAPE_OPS_ENTRY_POINTS`]. MaskedFill's `input` is the sole
6542///   varying operand; `mask` stays the fixed U8 slot and `out: passthrough(input)`,
6543///   so the fan emits `[T, U8, T]` — byte-for-byte the deleted
6544///   `table.register(MaskedFill, &masked_dtypes(t), …)` regs. **WriteSlice /
6545///   WriteSliceRotating** model `dest` as the in-place OUTPUT slot (not a key
6546///   input) and — for the rotating op — the U32 `position` as a NON-KEY runtime
6547///   operand (both handled by the executor's dedicated `Op::WriteSlice{,Rotating}`
6548///   arms), so a source-only + `out: passthrough(source)` section keys
6549///   `[T_source, T_out]` = `[T, T]` — byte-for-byte the deleted
6550///   `table.register(WriteSlice{,Rotating}, &unary(t), …)` regs and matching
6551///   `build_lookup_dtypes`' canonicalization exactly.
6552/// - **CumSum** (key `[T, T]`, 4 dtypes) is per-dtype typed accumulation, so each
6553///   `cumsum_<dt>` section carries a SPECIFIC single-dtype `entry_point` resolved
6554///   AS-IS (no fan) to its OWN typed wrapper.
6555///
6556/// **DEFERRED (describe-only, NOT imported).** `contiguize` and `triangular` are
6557/// `registrable: false` chassis/describe-only sections (no `OpKind::Contiguize` —
6558/// it is an executor materialize pass; `triangular` is the umbrella backing the
6559/// two hand-written `Triu`/`Tril` OpKinds with distinct wrappers, not a keyable
6560/// section). Those hand-written `Triu`/`Tril` regs stay authoritative.
6561///
6562/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6563/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6564/// `"portable-cpu"` tag and its precision the contract's bit-stable claim. Cost
6565/// is preserved because this runs BEFORE `fill_unset_cpu_cost`, which upgrades
6566/// the imported entries' `unknown_cost` sentinel to the same OpKind cost fn every
6567/// CPU primitive gets. The family declares NO fused ops, so `register_into`'s
6568/// required fused argument is a local throwaway that provably stays empty.
6569fn register_cpu_shape_ops_from_contract(table: &mut KernelBindingTable) {
6570    let provider =
6571        crate::fkc::import_bundle_str(CPU_SHAPE_OPS_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6572            "authored CPU shape-ops contract must import \
6573                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6574        );
6575    debug_assert!(
6576        provider.fused.is_empty(),
6577        "shape-ops contract declares no fused ops",
6578    );
6579    let mut fused = crate::fused::FusedKernelRegistry::new();
6580    provider
6581        .register_into(table, &mut fused)
6582        .expect("CPU shape-ops contract must register into the binding table");
6583}
6584
6585/// The authored CPU **matmul** kernel contract, embedded into the binary (the
6586/// PRODUCTION `include_str!`). `register_cpu_matmul_from_contract` parses +
6587/// lowers it and binds the FULL portable family FROM THE CONTRACT.
6588const CPU_MATMUL_CONTRACT: &str = include_str!("../kernel-contracts/cpu/matmul.fkc.md");
6589
6590/// Register the CPU **matmul** family FULLY — bare batched `MatMul` (6 dtypes,
6591/// key `[T, T, T]`) + fused `FusedLinear` (matmul + bias-add, 4 dtypes, key
6592/// `[T, T, T, T]`) = 10 bindings — by IMPORTING its FKC kernel contract, the
6593/// fourteenth production FKC consumer. FKC is unconditional core infrastructure,
6594/// so this is the ONE registration path for the PORTABLE kernels: every
6595/// hand-written `table.register(MatMul / FusedLinear, …)` portable-CPU call is
6596/// DELETED.
6597///
6598/// Each per-(op, dtype) section (`## matmul_f32`, `## fused_linear_f32`, …) is a
6599/// SPECIFIC single-dtype contract with a concrete `entry_point`
6600/// (`…::matmul_f32`), so none of them dtype-fan — the importer resolves each
6601/// declared symbol AS-IS through the production [`crate::fkc::CpuLinkRegistry`]
6602/// (now chaining [`crate::fkc::CPU_MATMUL_ENTRY_POINTS`]) to the exact wrapper
6603/// fn-pointer the CPU backend exposes. MatMul is 2-input (lhs, rhs) →
6604/// `passthrough(lhs)` output; FusedLinear is 3-input (a, b, bias) →
6605/// `passthrough(a)` output with `bias` a REQUIRED 1-D `[N]` operand (NOT
6606/// `optional`, so a single 4-slot key per dtype — no optional {absent, present}
6607/// fan). Both reuse `OpParams::Matmul` for shape, so every batch-geometry knob
6608/// (lhs_batch_dims/rhs_batch_dims/m/n/k) rides in `OpParams`, NOT the dtype-list.
6609/// The float variants (F32/F64/BF16/F16) accumulate in f32/native; the integer
6610/// MatMul variants (I8/U8) accumulate in i32 and SATURATE on store.
6611///
6612/// **Alternatives at the same key.** The binding table supports MULTIPLE ranked
6613/// kernels per `(op, dtypes, backend)` key. This importer registers ONLY the
6614/// portable (`kernel_source: "portable-cpu"`) kernels the contract covers; the
6615/// MKL / AOCL BLAS siblings live in SEPARATE external backend crates
6616/// (`fuel-mkl-cpu-backend` / `fuel-aocl-cpu-backend`), register through the
6617/// exported dispatch helpers with their own `"mkl"`/`"aocl"` `kernel_source`
6618/// tags as ranked alternatives at these SAME keys, and are out of scope here
6619/// (untouched — never registered in this crate's default build).
6620///
6621/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6622/// caps (contiguous-only, GQA-divisible batch); the binding's `kernel_source`
6623/// becomes the contract's `"portable-cpu"` tag and its precision the contract's
6624/// bit-stable claim. Cost is preserved because this runs BEFORE
6625/// `fill_unset_cpu_cost`, which upgrades the imported entries' `unknown_cost`
6626/// sentinel to the same OpKind cost fn every CPU primitive gets. The family
6627/// declares NO fused ops (the SEPARATE `FusedKernelRegistry`
6628/// `FusedOps::FUSED_LINEAR` seam is hand-written, in
6629/// `register_default_fused_kernels`, and stays untouched — "fused" in
6630/// `FusedLinear` names an intra-op matmul+bias fusion, NOT a graph `FusedOpId`),
6631/// so `register_into`'s required fused argument is a local throwaway that
6632/// provably stays empty. The quant `QMatMul` / `Nf4Matmul` OpKinds have their
6633/// own contracts and stay hand-written.
6634fn register_cpu_matmul_from_contract(table: &mut KernelBindingTable) {
6635    let provider = crate::fkc::import_bundle_str(CPU_MATMUL_CONTRACT, &crate::fkc::CpuLinkRegistry)
6636        .expect(
6637            "authored CPU matmul contract must import \
6638                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6639        );
6640    debug_assert!(
6641        provider.fused.is_empty(),
6642        "matmul contract declares no fused ops",
6643    );
6644    let mut fused = crate::fused::FusedKernelRegistry::new();
6645    provider
6646        .register_into(table, &mut fused)
6647        .expect("CPU matmul contract must register into the binding table");
6648}
6649
6650/// The authored CPU **attention** kernel contract, embedded into the binary (the
6651/// PRODUCTION `include_str!`). `register_cpu_attention_from_contract` parses +
6652/// lowers it and binds the MIGRATED (`KernelBindingTable`) subset FROM THE
6653/// CONTRACT.
6654const CPU_ATTENTION_CONTRACT: &str = include_str!("../kernel-contracts/cpu/attention.fkc.md");
6655
6656/// Register the CPU **attention** family's `KernelBindingTable` path FROM its FKC
6657/// kernel contract, the fifteenth production FKC consumer: forward `FlashAttn`
6658/// (4 dtypes) + `FlashAttnBackward{Q,K,V}` (3 selectors × 4 dtypes), each
6659/// `alibi_slopes`-optional section fanning into BOTH the no-alibi and with-alibi
6660/// keys = 4 × 4 × 2 = 32 bindings. FKC is unconditional core infrastructure, so
6661/// this is the ONE registration path for the migrated subset: the hand-written
6662/// `table.register(FlashAttn / FlashAttnBackward{Q,K,V}, …)` regs (both alibi
6663/// keys) are DELETED.
6664///
6665/// Each per-(op, dtype) section (`## flash_attn_f32`,
6666/// `## flash_attn_backward_q_f32`, …) declares a SPECIFIC single-dtype
6667/// `entry_point`, so none of them dtype-fan — the importer resolves each declared
6668/// symbol AS-IS through the production [`crate::fkc::CpuLinkRegistry`] (now
6669/// chaining [`crate::fkc::CPU_ATTENTION_ENTRY_POINTS`]) to the exact wrapper
6670/// fn-pointer. Because the contract marks `alibi_slopes` as `optional: true` (the
6671/// LAST input), the importer's key-builder (`fkc/lower.rs`
6672/// `assemble_dtype_variants`) fans each section into BOTH the no-alibi key
6673/// (`[q,k,v,out]` forward / `[q,k,v,do,out]` backward) and the with-alibi key
6674/// (`+alibi`) — both resolving the SAME `entry_point`/wrapper (the CPU wrapper
6675/// handles the presence/absence of the alibi operand). Forward FlashAttn AND the
6676/// three backward selectors share the single `OpParams::FlashAttn` carrier (there
6677/// is NO dedicated backward `OpParams` variant), so every softmax/mask geometry
6678/// knob rides in `OpParams`, NOT the dtype-list.
6679///
6680/// **PagedAttn is REGISTRABLE (`registrable: true`) and contract-sourced too.**
6681/// Its paged KV pool carries an `fdx.gather: paged_blocks` operand (§3.9.1), but
6682/// that block is import METADATA describing what an FDX view of the pool will
6683/// someday carry (FDX §6.9: "Description only: no cost, no decision"), NOT a
6684/// registration dependency: the as-built ABI passes `block_table` /
6685/// `context_lens` as ordinary U32 graph inputs + the geometry in
6686/// `OpParams::PagedAttn`, and the kernel reads them directly. So the importer
6687/// validates the gather block for COHERENCE (kind / requires_ext /
6688/// symbolic_extent / real block_table+context_lens roles) and registers the four
6689/// paged sections onto the `KernelBindingTable` at `(OpKind::PagedAttn,
6690/// [T,T,T,U32,U32,T](+[T]), Cpu)` — the optional-operand fan builds both alibi
6691/// keys, byte-for-byte the deleted hand-written `paged_attn_{no,with}_alibi`
6692/// regs. What remains [consumer-ahead] is only the FDX VIEW/materialize seam
6693/// (`view_with_gather` + `Capability::DlpackExtGather`), which has no consumer
6694/// yet. (The SEPARATE `FusedKernelRegistry` `PAGED_ATTN` seam stays hand-written,
6695/// exactly like `FLASH_ATTN`.)
6696///
6697/// Behavior-preserving vs. the deleted hand-written path (both alibi keys):
6698/// identical kernels + caps (contiguous-only); the binding's `kernel_source`
6699/// becomes the contract's `"portable-cpu"` tag and its precision the contract's
6700/// bit-stable claim. Cost is preserved because this runs BEFORE
6701/// `fill_unset_cpu_cost`, which upgrades the imported entries' `unknown_cost`
6702/// sentinel to the same OpKind cost fn every CPU primitive gets (the CPU cost
6703/// dispatcher has `FlashAttn`/`PagedAttn` arms; the backward selectors keep
6704/// `unknown_cost`, exactly as under the deleted hand-written regs — they are not
6705/// on the cost-coverage lint's enumerated set). The family declares NO fused ops
6706/// (all sections are `op_kind:`, incl. the now-registrable PagedAttn), so
6707/// `register_into`'s required fused argument is a local throwaway that provably
6708/// stays empty. The
6709/// SEPARATE `FusedKernelRegistry` FLASH_ATTN* / PAGED_ATTN seam
6710/// (`register_default_fused_kernels`) is hand-written and stays untouched.
6711fn register_cpu_attention_from_contract(table: &mut KernelBindingTable) {
6712    let provider =
6713        crate::fkc::import_bundle_str(CPU_ATTENTION_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6714            "authored CPU attention contract must import \
6715                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6716        );
6717    debug_assert!(
6718        provider.fused.is_empty(),
6719        "attention contract declares no fused ops (all op_kind, incl. PagedAttn)",
6720    );
6721    let mut fused = crate::fused::FusedKernelRegistry::new();
6722    provider
6723        .register_into(table, &mut fused)
6724        .expect("CPU attention contract must register into the binding table");
6725}
6726
6727/// The authored CPU **in-place scalar-param** kernel contract, embedded into the
6728/// binary (the PRODUCTION `include_str!`). `register_cpu_inplace_from_contract`
6729/// parses + lowers it and binds the WHOLE family FROM THE CONTRACT.
6730const CPU_INPLACE_CONTRACT: &str =
6731    include_str!("../kernel-contracts/cpu/inplace-unary-affine.fkc.md");
6732
6733/// Register the CPU **in-place scalar-param** family's `KernelBindingTable` path
6734/// FROM its FKC kernel contract, the sixteenth production FKC consumer: 21
6735/// in-place unary ops (`<Op>Inplace`, each per-op section fanning `[F32,F64,
6736/// BF16,F16]` = 84 bindings) + `InplaceAffine` / `ClampInplace` / `PowIInplace`
6737/// (per-dtype single sections, 4 each = 12) = 96 bindings. FKC is unconditional
6738/// core infrastructure, so this is the ONE registration path for the whole
6739/// family: the hand-written `table.register(<Op>Inplace / InplaceAffine /
6740/// ClampInplace / PowIInplace, &unary(dt), …)` regs are DELETED.
6741///
6742/// Each per-op unary section (`## relu_inplace`, …) declares a BASE `entry_point`
6743/// (`…::relu_inplace`) + enumerates `dtypes: [F32,F64,BF16,F16]`, so the
6744/// importer's §3.4 multi-dtype fan-out resolves `<base>_<dtype>`
6745/// (`relu_inplace_f32`) through the production [`crate::fkc::CpuLinkRegistry`]
6746/// (now chaining [`crate::fkc::CPU_INPLACE_ENTRY_POINTS`]) to the exact wrapper
6747/// fn-pointer. The affine / clamp / powi sections are per-dtype SINGLE sections,
6748/// so they do NOT fan — their specific `<op>_inplace_<dt>` symbol resolves AS-IS
6749/// (the affine rows carry the three-way naming skew: symbol `affine_inplace_<dt>`
6750/// → wrapper `inplace_affine_<dt>_cpu_wrapper`, words swapped). Every binding
6751/// keys `[T, T]` (the single `out` operand + its `passthrough(out)` mirror; the
6752/// executor's `WorkItemKind::InplaceKernel` arm passes the target as
6753/// `outputs[0]`), byte-for-byte the deleted `&unary(dt)` regs. Scalar params
6754/// (affine `mul`/`add`, clamp `min`/`max`, powi `exp`) ride in
6755/// `OpParams::{Affine, Clamp, PowI}`, NOT the dtype-list.
6756///
6757/// The `## unary_inplace` chassis umbrella is `registrable: false` (§3.10
6758/// describe-only) — it binds no OpKind (each named op pins its own distinct
6759/// `<Op>Inplace`), so it never lowers/resolves and is excluded from
6760/// registration.
6761///
6762/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6763/// caps (contiguous-only, empty caps); the binding's `kernel_source` becomes the
6764/// contract's `"portable-cpu"` tag and its precision the contract's bit-stable
6765/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`: the
6766/// in-place OpKinds are NOT on the CPU cost-coverage lint's enumerated set and
6767/// have no arm in `default_cost_for_op_kind`, so they keep the `unknown_cost`
6768/// sentinel exactly as under the deleted hand-written regs. The family declares
6769/// NO fused ops (all sections are `op_kind:` or the describe-only umbrella), so
6770/// `register_into`'s required fused argument is a local throwaway that provably
6771/// stays empty.
6772fn register_cpu_inplace_from_contract(table: &mut KernelBindingTable) {
6773    let provider =
6774        crate::fkc::import_bundle_str(CPU_INPLACE_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6775            "authored CPU in-place contract must import \
6776                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6777        );
6778    debug_assert!(
6779        provider.fused.is_empty(),
6780        "in-place contract declares no fused ops (all op_kind or describe-only umbrella)",
6781    );
6782    let mut fused = crate::fused::FusedKernelRegistry::new();
6783    provider
6784        .register_into(table, &mut fused)
6785        .expect("CPU in-place contract must register into the binding table");
6786}
6787
6788/// The authored CPU **cast** kernel contract, embedded into the binary (the
6789/// PRODUCTION `include_str!`). `register_cpu_cast_from_contract` parses + lowers
6790/// it and binds the FULL directed-pair matrix FROM THE CONTRACT.
6791const CPU_CAST_CONTRACT: &str = include_str!("../kernel-contracts/cpu/cast.fkc.md");
6792
6793/// Register the CPU **cast** family FULLY — the COMPLETE directed-pair matrix,
6794/// every ordered pair of the 11 real numeric dtypes
6795/// {F32,F64,F16,BF16,F8E4M3,U8,I8,U32,I16,I32,I64} with identity excluded =
6796/// 11 × 10 = 110 bindings (all key `[SRC, DST]`) — by IMPORTING its FKC kernel
6797/// contract.
6798///
6799/// Each per-pair section (`## cast_f64_to_f32`, …) declares a SPECIFIC
6800/// single-dtype `src` input + a `fixed(DST)` output, so none of them dtype-fan —
6801/// the importer's key-builder emits `[SRC, DST]` (the src input dtype + the
6802/// `fixed(DST)` output dtype, byte-for-byte the deleted hand-written
6803/// `table.register(Cast, &[SRC, DST], …)` regs) and resolves the section's
6804/// SPECIFIC `cast_<src>_to_<dst>` byte-kernel `entry_point` AS-IS through the
6805/// production [`crate::fkc::CpuLinkRegistry`] (chaining
6806/// [`crate::fkc::CPU_CAST_ENTRY_POINTS`]). Because the binding lookup is keyed on
6807/// the TARGET dtype, all 10 of a target's source pairs bind the SAME per-target
6808/// `cast_to_<dst>_cpu_wrapper` (which `match`es on the source dtype internally) —
6809/// 10 distinct real byte-kernel entry_points → 1 wrapper (the synthetic-umbrella
6810/// precedent). This is the SOLE registration path for the whole family; every
6811/// hand-written `table.register(Cast, …)` reg is DELETED. Identity pairs
6812/// (`[T, T]`) are never registered — the optimizer elides identity `Cast` before
6813/// dispatch, and the per-target wrappers carry no identity arm.
6814///
6815/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6816/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6817/// `"portable-cpu"` tag and its precision the contract's bit-stable claim. Cost
6818/// is preserved because this runs BEFORE `fill_unset_cpu_cost`, which upgrades
6819/// the imported entries' `unknown_cost` sentinel to the same OpKind cost fn every
6820/// CPU primitive gets. The family declares NO fused ops, so `register_into`'s
6821/// required fused argument is a local throwaway that provably stays empty.
6822fn register_cpu_cast_from_contract(table: &mut KernelBindingTable) {
6823    let provider = crate::fkc::import_bundle_str(CPU_CAST_CONTRACT, &crate::fkc::CpuLinkRegistry)
6824        .expect(
6825            "authored CPU cast contract must import \
6826                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6827        );
6828    debug_assert!(
6829        provider.fused.is_empty(),
6830        "cast contract declares no fused ops",
6831    );
6832    let mut fused = crate::fused::FusedKernelRegistry::new();
6833    provider
6834        .register_into(table, &mut fused)
6835        .expect("CPU cast contract must register into the binding table");
6836}
6837
6838/// The authored CPU **indexing / gather / scatter** kernel contract, embedded
6839/// into the binary (the PRODUCTION `include_str!`).
6840/// `register_cpu_indexing_from_contract` parses + lowers it and binds the FULL
6841/// family (IndexSelect + Gather + IndexAdd + ScatterAdd) FROM THE CONTRACT.
6842const CPU_INDEXING_CONTRACT: &str = include_str!("../kernel-contracts/cpu/indexing.fkc.md");
6843
6844/// Register the FULL CPU indexing family — IndexSelect (9 dtypes, key
6845/// `[T, U32, T]`) + Gather (9 dtypes, key `[T, U32, T]`) + IndexAdd (4 dtypes,
6846/// key `[T, U32, T, T]`) + ScatterAdd (4 dtypes, key `[T, U32, T, T]`) = 26
6847/// bindings — by IMPORTING its FKC kernel contract, the eighteenth production
6848/// FKC consumer.
6849///
6850/// - **IndexSelect** / **Gather** — the ONE section each declares a BASE
6851///   `entry_point` (`…::index_select_cpu` / `…::gather_cpu`, a dtype-agnostic
6852///   byte copy) + an enumerated `dtypes` list, so the importer's §3.4 fan-out
6853///   resolves `<base>_<dtype>` — every dtype variant mapping to the ONE
6854///   dtype-agnostic `index_select_cpu_wrapper` / `gather_cpu_wrapper` through the
6855///   production [`crate::fkc::CpuLinkRegistry`] (chaining
6856///   [`crate::fkc::cpu_link::CPU_INDEXING_ENTRY_POINTS`]). The `indices` operand
6857///   is the FIXED U32 slot and `out: passthrough(source)`, so the fan emits key
6858///   `[T, U32, T]` — byte-for-byte the deleted hand-written
6859///   `table.register(IndexSelect/Gather, &index_select(dt)/&gather_dts(dt), …)`
6860///   regs. The contract's dtype list was trimmed to production's 9 wired dtypes
6861///   (F32/F64/BF16/F16/U32/U8/I16/I32/I64); I8 is describable (byte-agnostic) but
6862///   NOT wired in production, so it is dropped from the contract.
6863/// - **IndexAdd** / **ScatterAdd** — per-dtype typed accumulation (f32/f64
6864///   native, bf16/f16 widen to an f32 accumulator; out seeded from `base` then
6865///   `+= src`), so each `index_add_<dt>` / `scatter_add_<dt>` section carries a
6866///   SPECIFIC single-dtype `entry_point` resolved AS-IS (no fan), key
6867///   `[T, U32, T, T]` (`base`, U32 `indices`, `src`, `passthrough(base)` output)
6868///   — byte-for-byte the deleted `table.register(IndexAdd/ScatterAdd, …)` regs.
6869///
6870/// The `indices` slot being a FIXED single-dtype (U32) in every section means
6871/// there is NO independent index-dtype axis and no multi-axis
6872/// `FanoutDtypeMismatch` deferral — the whole family migrates (unlike the metal
6873/// indexing situation).
6874///
6875/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6876/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6877/// `"portable-cpu"` tag and its precision the contract's bit-stable claim. Cost
6878/// is preserved because this runs BEFORE `fill_unset_cpu_cost`, which upgrades
6879/// the imported entries' `unknown_cost` sentinel to the same OpKind cost fn every
6880/// CPU primitive gets. The family declares NO fused ops, so `register_into`'s
6881/// required fused argument is a local throwaway that provably stays empty.
6882fn register_cpu_indexing_from_contract(table: &mut KernelBindingTable) {
6883    let provider =
6884        crate::fkc::import_bundle_str(CPU_INDEXING_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6885            "authored CPU indexing contract must import \
6886                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6887        );
6888    debug_assert!(
6889        provider.fused.is_empty(),
6890        "indexing contract declares no fused ops",
6891    );
6892    let mut fused = crate::fused::FusedKernelRegistry::new();
6893    provider
6894        .register_into(table, &mut fused)
6895        .expect("CPU indexing contract must register into the binding table");
6896}
6897
6898/// Register CPU dispatch wrappers in the binding table. Call once
6899/// at process startup or on first table creation. The CPU backend
6900/// is the universal fallback; its bindings cover every standard
6901/// (op, dtype) combination after Phase C migration. Today's set
6902/// covers the elementwise binary + unary `f32` families.
6903pub fn register_cpu_kernels(table: &mut KernelBindingTable) {
6904    use OpKind::*;
6905    let cpu = BackendId::Cpu;
6906    let f32_dt = DType::F32;
6907    let f64_dt = DType::F64;
6908    let bf16_dt = DType::BF16;
6909    let f16_dt = DType::F16;
6910    let u32_dt = DType::U32;
6911
6912    // Per-operand dtype-list shape helpers. The list captures all
6913    // operands the kernel sees — inputs in order, then outputs.
6914    // Variadic Concat uses the `unary` shape as a canonical
6915    // shorthand for "uniform-dtype across N inputs + output."
6916    let unary = |t: DType| [t, t]; // (in, out)
6917    // (MatMul's (lhs, rhs, out) key shape is now built by the FKC importer from
6918    // fuel-dispatch/kernel-contracts/cpu/matmul.fkc.md — see
6919    // register_cpu_matmul_from_contract; the hand-written `binary` closure was
6920    // removed with its regs.)
6921    let u8_dt = DType::U8;
6922    // (Rope's (x, cos, sin, out) key shape is now built by the FKC importer
6923    // from fuel-dispatch/kernel-contracts/cpu/rope.fkc.md — see
6924    // register_cpu_rope_from_contract; the hand-written `rope_dts` closure was
6925    // removed with its regs.)
6926    // (Conv2D/ConvTranspose2D are now FULLY built by the FKC importer from
6927    // fuel-dispatch/kernel-contracts/cpu/conv.fkc.md — see register_cpu_conv_from_contract.
6928    // The contract marks `bias` as `optional: true`, so the importer's key-builder
6929    // now emits BOTH the no-bias (x, w, out) and with-bias (x, w, bias, out) keys
6930    // per (op, dtype); the hand-written `conv2d_with_bias` / `conv2d_no_bias`
6931    // closures + their regs were all removed.)
6932    // (FusedLinear's (lhs, rhs, bias, out) key shape is now built by the FKC
6933    // importer from fuel-dispatch/kernel-contracts/cpu/matmul.fkc.md — see
6934    // register_cpu_matmul_from_contract; the hand-written `fused_linear` closure
6935    // was removed with its regs.)
6936    // FlashAttn / FlashAttnBackward{Q,K,V} / PagedAttn key-shape closures were
6937    // DELETED with the migration to FKC-contract registration (the importer's
6938    // optional-operand fan builds both alibi keys from the contract).
6939    // (IndexSelect/Gather's (data, indices, out) = [T, U32, T] and IndexAdd/
6940    // ScatterAdd's (base, indices, src, out) = [T, U32, T, T] key shapes are now
6941    // built by the FKC importer from fuel-dispatch/kernel-contracts/cpu/indexing.fkc.md —
6942    // see register_cpu_indexing_from_contract; the hand-written `index_select` /
6943    // `gather_dts` / `index_add_dts` / `scatter_add` closures were removed with
6944    // their regs.)
6945
6946    // Elementwise binary family (8 ops × 4 dtypes = 32 bindings:
6947    // Add/Sub/Mul/Div/Maximum/Minimum/Pow/Rem × F32/F64/BF16/F16).
6948    //
6949    // This family is the FIRST production FKC-contract consumer: it is
6950    // IMPORTED from its kernel contract
6951    // (fuel-dispatch/kernel-contracts/cpu/elementwise-binary.fkc.md), resolving every
6952    // `entry_point` symbol through the production `CpuLinkRegistry` to the
6953    // exact same wrapper fn-pointers the CPU backend exposes. The hand-written
6954    // `table.register(...)` calls this family used to carry are DELETED — FKC
6955    // is unconditional core infrastructure, so this is the sole registration
6956    // path (no build config, no fallback). Placed here — BEFORE the
6957    // `fill_unset_cpu_*` passes — so the imported entries pick up the same CPU
6958    // cost fill every other CPU primitive gets.
6959    register_cpu_binary_from_contract(table);
6960
6961    // Out-of-place scalar-param family (affine/clamp/powi × 4 dtypes +
6962    // powi_backward × 4 = 16 bindings). Second production FKC-contract
6963    // consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/affine-clamp-powi.fkc.md
6964    // via the same `CpuLinkRegistry`. The hand-written `table.register(...)`
6965    // calls (Affine / ClampElementwise / PowIElementwise / PowIElementwiseBackward)
6966    // are DELETED — this is the sole registration path. Placed BEFORE the
6967    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU cost
6968    // fill. (The in-place InplaceAffine/ClampInplace/PowIInplace family and the
6969    // FusedOps::POWI_BACKWARD fused-registry seam are separate and untouched.)
6970    register_cpu_affine_clamp_powi_from_contract(table);
6971
6972    // Elementwise unary (22 ops × 4 dtypes = 88 bindings: relu/neg/sqr/sqrt/
6973    // recip/abs/tanh/exp/log/sin/cos/sigmoid/silu/step/gelu_tanh/floor/ceil/round/
6974    // sign/erf/gelu/rsqrt × F32/F64/BF16/F16). Third production FKC-contract
6975    // consumer and the FIRST user of the §3.4 multi-dtype fan-out: IMPORTED from
6976    // fuel-dispatch/kernel-contracts/cpu/elementwise-unary.fkc.md via the same
6977    // `CpuLinkRegistry`. Each per-op section declares a BASE entry_point that the
6978    // importer expands to `<base>_<dtype>`. The hand-written `table.register(...)`
6979    // calls (the F32/F64/BF16/F16 unary blocks + the rounding/sign/erf/gelu/
6980    // rsqrt block) are DELETED — this is the sole registration path. Placed
6981    // BEFORE the `fill_unset_cpu_*` passes so the imported entries pick up the CPU
6982    // cost fill. gelu_tanh (GeluTanhElementwise) and gelu (GeluElementwise)
6983    // stay DISTINCT.
6984    register_cpu_unary_from_contract(table);
6985
6986    // Compare (6 ops × 4 dtypes = 24, key [T, T, U8]) + where (1 op × 4 dtypes
6987    // = 4, key [U8, T, T, T]) = 28 bindings. Fourth production FKC-contract
6988    // consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/compare-where.fkc.md via
6989    // the same `CpuLinkRegistry`. The 24 compare thunks resolve their declared
6990    // `_u8`-suffixed symbols AS-IS; the single `where_kernel` section rides the
6991    // §3.4 multi-dtype fan-out (BASE `…::where` → `where_{f32,f64,bf16,f16}`)
6992    // and the `passthrough(a)` output rule. The hand-written `table.register(...)`
6993    // calls (the compare block + the `where_dts` block) are DELETED — this is the
6994    // sole registration path. Placed BEFORE the `fill_unset_cpu_*` passes so the
6995    // imported entries pick up the CPU cost fill.
6996    register_cpu_compare_where_from_contract(table);
6997
6998    // Per-axis reduce (Sum/Mean/Max/Min × 4 dtypes = 16 bindings, key [T, T]).
6999    // Fifth production FKC-contract consumer: IMPORTED from
7000    // fuel-dispatch/kernel-contracts/cpu/reduce.fkc.md via the same `CpuLinkRegistry`.
7001    // Each per-(op,dtype) section carries a SPECIFIC single-dtype entry_point
7002    // (`sum_reduce_f32`, …) resolved AS-IS (no fan-out). The hand-written
7003    // `table.register(...)` calls (the F32/F64 + BF16/F16 reduce blocks) are
7004    // DELETED — this is the sole registration path. Placed BEFORE the
7005    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU cost
7006    // fill. The `## reduce` chassis is `registrable: false` (§3.10) and the
7007    // f32-only argmax/argmin sections are deferred (registrable: false); the
7008    // hand-written Arg{Max,Min}Dim regs below stay authoritative.
7009    register_cpu_reduce_from_contract(table);
7010
7011    // Broadcast-target reduce-to (ReduceSumTo / ReduceMaxTo × 4 dtypes, key
7012    // [T, T]; ReduceMaxToBackward × 4 dtypes, key [T, T, T] = 12 bindings).
7013    // Sixth production FKC-contract consumer: IMPORTED from
7014    // fuel-dispatch/kernel-contracts/cpu/reduce-to.fkc.md via the same `CpuLinkRegistry`.
7015    // Each per-(op,dtype) section carries a SPECIFIC single-dtype entry_point
7016    // (`reduce_sum_to_f32`, …) resolved AS-IS (no fan-out). The hand-written
7017    // `table.register(...)` calls (the ReduceSumTo/ReduceMaxTo forward block +
7018    // the ReduceMaxToBackward block) are DELETED — this is the sole registration
7019    // path. Placed BEFORE the `fill_unset_cpu_*` passes so the imported entries
7020    // pick up the CPU cost fill. The `## reduce_to` chassis is
7021    // `registrable: false` (§3.10) and never registers.
7022    register_cpu_reduce_to_from_contract(table);
7023
7024    // Last-dim NORM forward (Softmax / LogSoftmax / RmsNorm / LayerNorm × 4
7025    // dtypes = 16 bindings, key [T, T]). Seventh production FKC-contract
7026    // consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/norm.fkc.md via the same
7027    // `CpuLinkRegistry`. Each per-(op,dtype) section carries a SPECIFIC
7028    // single-dtype entry_point (`softmax_last_dim_f32`, `rms_norm_last_dim_f32`,
7029    // …) resolved AS-IS (no fan-out). The RMS/LayerNorm kernels are the BARE
7030    // normalization (no affine gamma/beta operand); outer_count/last_dim/eps ride
7031    // in OpParams, so the key stays [T, T]. The hand-written `table.register(...)`
7032    // calls (the LogSoftmaxLastDim block above + the SoftmaxLastDim / RmsNormLastDim
7033    // / LayerNormLastDim block below) are DELETED — this is the sole registration
7034    // path. Placed BEFORE the `fill_unset_cpu_*` passes so the imported entries
7035    // pick up the CPU cost fill. The norm ops' SEPARATE FusedKernelRegistry seam
7036    // (register_default_fused_kernels) and the norm-BACKWARD hand-written regs stay
7037    // untouched.
7038    register_cpu_norm_from_contract(table);
7039
7040    // Last-dim NORM BACKWARD (Softmax / LogSoftmax / RmsNorm / LayerNorm backward
7041    // × 4 dtypes = 16 bindings, key [T, T, T]). Eighth production FKC-contract
7042    // consumer and the BACKWARD sibling of the norm-forward importer above:
7043    // IMPORTED from fuel-dispatch/kernel-contracts/cpu/norm-backward.fkc.md via the same
7044    // `CpuLinkRegistry`. Each per-(op,dtype) section carries a SPECIFIC
7045    // single-dtype entry_point (`softmax_last_dim_backward_f32`,
7046    // `rms_norm_last_dim_backward_f32`, …) resolved AS-IS (no fan-out). The BARE
7047    // backward takes TWO inputs (y/x + upstream gradient g) → ONE passthrough
7048    // output, so the key is [T, T, T]; outer_count/last_dim/eps ride in OpParams.
7049    // The hand-written `table.register(...)` calls (the LogSoftmaxLastDimBackward
7050    // block + the SoftmaxLastDimBackward / LayerNormLastDimBackward /
7051    // RmsNormLastDimBackward block below) are DELETED — this is the sole
7052    // registration path. Placed BEFORE the `fill_unset_cpu_*` passes so the
7053    // imported entries pick up the CPU cost fill. The norm-backward ops' SEPARATE
7054    // FusedKernelRegistry seam (register_default_fused_kernels) stays untouched.
7055    register_cpu_norm_backward_from_contract(table);
7056
7057    // RoPE (rotary position embedding; 1 op × 4 dtypes = 4 bindings, key
7058    // [T, T, T, T]). Ninth production FKC-contract consumer: IMPORTED from
7059    // fuel-dispatch/kernel-contracts/cpu/rope.fkc.md via the same `CpuLinkRegistry`.
7060    // Each per-dtype section carries a SPECIFIC single-dtype entry_point
7061    // (`rope_f32`, …) resolved AS-IS (no fan-out). RoPE takes THREE inputs
7062    // (x + the precomputed cos/sin tables, all one dtype) → ONE passthrough(x)
7063    // output, so the key is [T, T, T, T]; outer_count/seq/head_dim ride in
7064    // OpParams::Rope. The hand-written `table.register(Rope, ...)` calls (the
7065    // rope_dts block below) are DELETED — this is the sole registration path.
7066    // Placed BEFORE the `fill_unset_cpu_*` passes so the imported entries pick
7067    // up the CPU cost fill. RoPE's SEPARATE FusedKernelRegistry seam
7068    // (register_default_fused_kernels, FusedOps::ROPE) stays untouched.
7069    register_cpu_rope_from_contract(table);
7070
7071    // CPU SSM / Mamba family — the FULL family: FusedSoftmaxCrossEntropy
7072    // (key [T, I64, F32]) + CausalConv1d (key [T, T, T, T]) + SelectiveScan +
7073    // SsdChunkScan (key [T; 6]), 4 ops × 4 dtypes = 16 bindings. Tenth
7074    // production FKC-contract consumer: IMPORTED from
7075    // fuel-dispatch/kernel-contracts/cpu/ssm.fkc.md via the same `CpuLinkRegistry`. Each
7076    // per-(op,dtype) section carries a SPECIFIC single-dtype entry_point
7077    // (`fused_softmax_cross_entropy_f32`, `selective_scan_f32`, …) resolved AS-IS
7078    // (no fan-out). The two SCAN ops return a `return.bundle` multi-output
7079    // (Option C, one buffer [y ; last_state]); the importer now appends the
7080    // bundle's primary-slot dtype to the key tail, so they key [T; 6]
7081    // byte-for-byte the deleted hand-written regs. Every hand-written
7082    // `table.register(...)` call for the whole family is DELETED — this is its
7083    // sole registration path. Placed BEFORE the `fill_unset_cpu_*` passes so the
7084    // imported entries pick up the CPU cost fill.
7085    register_cpu_ssm_from_contract(table);
7086
7087    // NonZeroIndices — the keystone primitive for data-dependent dynamic
7088    // shapes (SSM decode / MoE sparsity / MLA KV compression). One input
7089    // `x` → one bundled output `[indices [capacity] U32 ; count [1] U32]`;
7090    // the binding key is `[input_dtype, U32]` (input + primary output-slot
7091    // dtype). Registered DIRECTLY (not yet FKC-contract-sourced): the
7092    // op's U32 output slot is a *constant* dtype, not a `passthrough` of a
7093    // T input, which the current contract key-builder does not express —
7094    // so this bring-up primitive registers by hand and is a candidate to
7095    // migrate once a data-dependent-ops contract family grows. Placed
7096    // BEFORE the `fill_unset_cpu_*` passes so the entries pick up the CPU
7097    // precision + cost fill (UNAUDITED → PRIMITIVE_DETERMINISTIC_CPU,
7098    // unknown_cost → the OpKind cost fn).
7099    table.register(
7100        NonZeroIndices,
7101        &[f32_dt, u32_dt],
7102        cpu,
7103        nonzero_indices_f32_cpu_wrapper,
7104    );
7105    table.register(
7106        NonZeroIndices,
7107        &[u32_dt, u32_dt],
7108        cpu,
7109        nonzero_indices_u32_cpu_wrapper,
7110    );
7111
7112    // CPU 2D-convolution family — FULLY contract-sourced: Conv2D +
7113    // ConvTranspose2D at BOTH the no-bias key [T, T, T] (x, weight, out) AND the
7114    // with-bias key [T, T, T, T] (x, weight, bias + passthrough(x) output), 2 ops
7115    // × 4 dtypes × 2 operand-counts = 16 bindings. Eleventh production
7116    // FKC-contract consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/conv.fkc.md
7117    // via the same `CpuLinkRegistry`. Each per-(op,dtype) section carries a
7118    // SPECIFIC single-dtype entry_point (`conv2d_f32`, `conv_transpose2d_f32`, …)
7119    // resolved AS-IS (no dtype fan-out); every geometry knob rides in
7120    // OpParams::{Conv2D, ConvTranspose2D}. The contract marks `bias` as
7121    // `optional: true`, so the importer's optional-operand key-builder fans each
7122    // section into both the no-bias and with-bias keys (same wrapper handles 2 or
7123    // 3 inputs) — ALL hand-written conv `table.register(...)` calls are DELETED,
7124    // this is the sole registration path for the whole family. Placed BEFORE the
7125    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU cost fill.
7126    // The conv ops' SEPARATE FusedKernelRegistry seam
7127    // (register_default_fused_kernels, FusedOps::{CONV2D, CONV_TRANSPOSE2D}) stays
7128    // untouched.
7129    register_cpu_conv_from_contract(table);
7130
7131    // CPU padding family (FULL) — mode-unified forward Pad × 6 dtypes = 6 +
7132    // PadBackward × 4 dtypes = 4 bindings (all key [T, T]). Twelfth production
7133    // FKC-contract consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/padding.fkc.md
7134    // via the same `CpuLinkRegistry`. The ONE mode-unified `## pad` forward section
7135    // declares a BASE entry_point (`pad_cpu`) + the 6 wired dtypes (U8/U32/BF16/
7136    // F16/F32/F64), so the fan resolves `pad_cpu_<dtype>` (all → the one
7137    // mode-dispatching `pad_cpu_wrapper`, which selects Constant/Reflect/Replicate
7138    // at runtime via mode_tag); each per-dtype backward section carries a SPECIFIC
7139    // single-dtype entry_point (`pad_backward_f32`, …) resolved AS-IS (no fan).
7140    // in_shape/out_shape/padding/mode_tag/fill_bytes ride in OpParams::{Pad,
7141    // PadBackward}. The three per-mode forward sections + the pad_walk_cpu helper
7142    // are `registrable: false` describe-only. ALL hand-written forward + backward
7143    // `table.register(Pad/PadBackward, …)` regs are DELETED — this is their sole
7144    // registration path. Placed BEFORE the `fill_unset_cpu_*` passes so the
7145    // imported entries pick up the CPU cost fill.
7146    register_cpu_padding_from_contract(table);
7147
7148    // CPU shape-ops family (migratable subset) — Flip + Roll + Concat +
7149    // MaskedFill + WriteSlice + WriteSliceRotating (dtype-agnostic byte kernels
7150    // fanned per production dtype: Flip/Roll/MaskedFill/WriteSlice/
7151    // WriteSliceRotating 6 dtypes, Concat 9) + the four per-dtype CumSum kernels.
7152    // Thirteenth production FKC-contract consumer: IMPORTED from
7153    // fuel-dispatch/kernel-contracts/cpu/shape-ops.fkc.md via the same `CpuLinkRegistry`.
7154    // Flip/Roll/Concat/MaskedFill/WriteSlice/WriteSliceRotating sections declare a
7155    // BASE entry_point + a dtypes list trimmed to the wired set, so the fan
7156    // resolves `<base>_<dtype>` (all → the one dtype-agnostic wrapper); CumSum's
7157    // per-dtype sections resolve their SPECIFIC `cumsum_<dt>` symbol AS-IS. Keys:
7158    // Flip/Roll/Concat/CumSum/WriteSlice/WriteSliceRotating [T, T], MaskedFill
7159    // [T, U8, T]. WriteSlice/WriteSliceRotating model `dest` as the in-place
7160    // OUTPUT slot (and rotating's `position` as a non-key runtime operand), so the
7161    // imported key matches build_lookup_dtypes' canonicalized [T_src, T_out]. The
7162    // migrated hand-written regs are DELETED — this is their sole registration
7163    // path. DEFERRED (hand-written kept): Triu/Tril (the contract carries only the
7164    // `triangular` describe-only chassis) + Contiguize (no OpKind — an executor
7165    // materialize pass). Placed BEFORE the `fill_unset_cpu_*` passes so the
7166    // imported entries pick up the CPU cost fill.
7167    register_cpu_shape_ops_from_contract(table);
7168
7169    // CPU matmul family — FULLY contract-sourced (PORTABLE kernels): bare
7170    // batched MatMul (6 dtypes F32/F64/BF16/F16/I8/U8, key [T, T, T]) + fused
7171    // FusedLinear (matmul + bias-add, 4 dtypes F32/F64/BF16/F16, key
7172    // [T, T, T, T]) = 10 bindings. Fourteenth production FKC-contract consumer:
7173    // IMPORTED from fuel-dispatch/kernel-contracts/cpu/matmul.fkc.md via the same
7174    // `CpuLinkRegistry`. Each per-(op,dtype) section carries a SPECIFIC
7175    // single-dtype entry_point (`matmul_f32`, `fused_linear_f32`, …) resolved
7176    // AS-IS (no fan-out); the batch geometry (lhs_batch_dims/rhs_batch_dims/
7177    // m/n/k) rides in OpParams::Matmul (FusedLinear reuses it). Integer MatMul
7178    // (I8/U8) accumulates in i32 and saturates on store. Every hand-written
7179    // portable `table.register(MatMul / FusedLinear, …)` call is DELETED — this
7180    // is the sole registration path for the portable family. Placed BEFORE the
7181    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU cost
7182    // fill. ALTERNATIVES-AT-KEY: the MKL/AOCL BLAS siblings register at these
7183    // SAME keys from SEPARATE external crates with their own `"mkl"`/`"aocl"`
7184    // kernel_source tags — SEPARATE and untouched (not registered in this build).
7185    // The SEPARATE FusedKernelRegistry FusedOps::FUSED_LINEAR seam
7186    // (register_default_fused_kernels) is hand-written and stays untouched; the
7187    // quant QMatMul/Nf4Matmul OpKinds have their own contracts and stay
7188    // hand-written below.
7189    register_cpu_matmul_from_contract(table);
7190
7191    // The CPU ATTENTION family's KernelBindingTable path — forward FlashAttn (4
7192    // dtypes) + FlashAttnBackward{Q,K,V} (3 selectors × 4 dtypes) + PagedAttn (4
7193    // dtypes), each alibi-optional section fanning into BOTH the no-alibi and
7194    // with-alibi keys = 40 bindings — is now registered FROM
7195    // fuel-dispatch/kernel-contracts/cpu/attention.fkc.md by
7196    // register_cpu_attention_from_contract. The contract marks `alibi_slopes`
7197    // as `optional: true`, so the importer's key-builder fans each (op, dtype)
7198    // section into both operand-count keys; FKC is the SOLE path for the migrated
7199    // family. All hand-written FlashAttn + FlashAttnBackward{Q,K,V} + PagedAttn
7200    // regs (both alibi keys) were DELETED. PagedAttn's fdx.gather pool is import
7201    // METADATA (§3.9.1: it dispatches via ordinary U32 block_table/context_lens
7202    // operands + OpParams::PagedAttn), so it registers here too; only the FDX VIEW
7203    // seam stays [consumer-ahead]. The SEPARATE FusedKernelRegistry
7204    // FLASH_ATTN*/PAGED_ATTN seam (register_default_fused_kernels) is untouched.
7205    // Placed BEFORE the `fill_unset_cpu_*` passes so the imported entries pick up
7206    // the CPU cost fill.
7207    register_cpu_attention_from_contract(table);
7208
7209    // The CPU IN-PLACE scalar-param family's KernelBindingTable path — 21 in-place
7210    // unary ops (each per-op section fanning [F32,F64,BF16,F16] = 84) +
7211    // InplaceAffine / ClampInplace / PowIInplace (per-dtype single sections, 4 each
7212    // = 12) = 96 bindings, all keyed [T, T] — is now registered FROM
7213    // fuel-dispatch/kernel-contracts/cpu/inplace-unary-affine.fkc.md by
7214    // register_cpu_inplace_from_contract. FKC is the SOLE path for the whole
7215    // family; all hand-written <Op>Inplace / InplaceAffine / ClampInplace /
7216    // PowIInplace regs were DELETED. The `unary_inplace` chassis section is
7217    // describe-only (registrable: false). Placed BEFORE the `fill_unset_cpu_*`
7218    // passes; the in-place OpKinds keep the `unknown_cost` sentinel (no arm in
7219    // default_cost_for_op_kind, not on the cost-coverage lint set) — identical to
7220    // the deleted hand-written regs.
7221    register_cpu_inplace_from_contract(table);
7222
7223    // (bf16 + f16 reductions are now registered from the reduce contract above,
7224    // alongside the f32/f64 variants — accumulate in f32 for stability.)
7225
7226    // Cast — the COMPLETE directed-pair matrix: every ordered pair of the 11
7227    // real numeric dtypes {F32,F64,F16,BF16,F8E4M3,U8,I8,U32,I16,I32,I64} with
7228    // identity excluded = 11 × 10 = 110 bindings (all key `[SRC, DST]`) — is now
7229    // registered FROM fuel-dispatch/kernel-contracts/cpu/cast.fkc.md by
7230    // register_cpu_cast_from_contract. Each per-pair section declares a
7231    // single-dtype `src` input + a `fixed(DST)` output (no dtype fan), so the
7232    // importer keys `[SRC, DST]` and resolves the SPECIFIC `cast_<src>_to_<dst>`
7233    // byte-kernel entry_point AS-IS; because the lookup is keyed on the TARGET
7234    // dtype, all 10 of a target's source pairs bind the SAME per-target
7235    // `cast_to_<dst>_cpu_wrapper` (10 real entry_points → 1 wrapper). FKC is the
7236    // SOLE path for the whole family; all hand-written `table.register(Cast, …)`
7237    // regs were DELETED. Identity pairs are never registered — the optimizer
7238    // elides identity Cast before dispatch. The MX dummy dtypes
7239    // (F6E2M3,F6E3M2,F4,F8E8M0) have no Rust scalar type and are excluded. Placed
7240    // BEFORE the `fill_unset_cpu_*` passes so the imported entries pick up the CPU
7241    // cost/precision fill.
7242    register_cpu_cast_from_contract(table);
7243
7244    // CPU indexing / gather / scatter family — IndexSelect + Gather
7245    // (dtype-agnostic byte copies fanned per dtype: 9 dtypes each, key
7246    // [T, U32, T], the fabricated `<base>_<dt>` symbol resolving to the ONE
7247    // wrapper) + IndexAdd + ScatterAdd (per-dtype typed accumulation: 4 dtypes
7248    // each, key [T, U32, T, T], `<op>_<dt>` resolved AS-IS). Eighteenth
7249    // production FKC consumer: IMPORTED from
7250    // fuel-dispatch/kernel-contracts/cpu/indexing.fkc.md via the same `CpuLinkRegistry`.
7251    // The `indices` slot is a FIXED U32 operand in every section (no independent
7252    // index-dtype axis), so there is no multi-axis fan-out deferral — the whole
7253    // family migrates. The contract's index_select/gather dtype list is trimmed
7254    // to production's 9 wired dtypes (I8 describable but NOT wired). ALL
7255    // hand-written `table.register(IndexSelect/Gather/IndexAdd/ScatterAdd, …)`
7256    // regs are DELETED — this is their sole registration path. Placed BEFORE the
7257    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU
7258    // cost/precision fill.
7259    register_cpu_indexing_from_contract(table);
7260
7261    // Conv2D / ConvTranspose2D — BOTH the no-bias key [T, T, T] (x, weight, out)
7262    // AND the with-bias key [T, T, T, T] (x, weight, bias, out) are now registered
7263    // FROM the conv FKC contract (`register_cpu_conv_from_contract`, above). The
7264    // contract marks `bias` as `optional: true`, so the importer's key-builder
7265    // fans each (op, dtype) section into both operand-count keys — FKC is the SOLE
7266    // path for the whole conv family (16 bindings). All hand-written conv regs were
7267    // DELETED (the no-bias deferral is closed).
7268
7269    // ReduceSumTo / ReduceMaxTo (× 4 dtypes, key [T, T]) are now registered
7270    // FROM the reduce-to FKC contract (`register_cpu_reduce_to_from_contract`,
7271    // above) — the hand-written regs were DELETED (FKC is the sole path). The
7272    // ReduceMaxToBackward regs (key [T, T, T]) below were likewise deleted.
7273
7274    // FusedLinear (3 inputs lhs, rhs, bias → out; key [T, T, T, T]) is now
7275    // registered FROM the matmul FKC contract
7276    // (`register_cpu_matmul_from_contract`, above) — the hand-written regs were
7277    // DELETED (FKC is the sole path for the portable family). The SEPARATE
7278    // FusedKernelRegistry FusedOps::FUSED_LINEAR seam
7279    // (`register_default_fused_kernels`) is hand-written and stays untouched.
7280
7281    // FlashAttn (forward) + FlashAttnBackward{Q,K,V} + PagedAttn — both the
7282    // no-alibi and with-alibi keys per dtype — are now registered FROM the
7283    // attention FKC contract (`register_cpu_attention_from_contract`, near the top
7284    // of this fn). The contract marks `alibi_slopes` as `optional: true`, so the
7285    // importer's key-builder fans each (op, dtype) section into both operand-count
7286    // keys — FKC is the SOLE path for the migrated attention family (40 bindings:
7287    // FlashAttn 8 + FlashAttnBackward{Q,K,V} 24 + PagedAttn 8). All hand-written
7288    // FlashAttn + FlashAttnBackward{Q,K,V} + PagedAttn regs (both alibi keys) were
7289    // DELETED. PagedAttn's `fdx.gather: paged_blocks` pool is import METADATA
7290    // (§3.9.1): block_table/context_lens ride as ordinary U32 operands +
7291    // OpParams::PagedAttn, so registration does not depend on the FDX gather VIEW
7292    // (that stays [consumer-ahead]).
7293
7294    // (Affine F32 is now registered from the affine-clamp-powi contract above.)
7295
7296    // The in-place scalar-param family — InplaceAffine / ClampInplace /
7297    // PowIInplace (each key [T, T], scalars in OpParams::{Affine, Clamp, PowI}) —
7298    // is now registered FROM fuel-dispatch/kernel-contracts/cpu/inplace-unary-affine.fkc.md
7299    // by register_cpu_inplace_from_contract near the top of this fn (alongside the
7300    // 21 in-place unary ops). The affine sections' op_kind was corrected from the
7301    // out-of-place `Affine` to `InplaceAffine`; all hand-written in-place scalar
7302    // regs were DELETED with the migration.
7303
7304    // The ENTIRE CPU SSM / Mamba family — FusedSoftmaxCrossEntropy (key
7305    // [T, I64, F32]), CausalConv1d (key [T, T, T, T]), and the two SCAN ops
7306    // SelectiveScan / SsdChunkScan (key [T; 6] — 5 inputs + the ONE bundled
7307    // output slot) — is now registered from fuel-dispatch/kernel-contracts/cpu/ssm.fkc.md
7308    // by register_cpu_ssm_from_contract near the top of this fn. The scans'
7309    // `return.bundle` multi-output is now key-buildable by the importer (it
7310    // appends the bundle's primary-slot dtype to the key tail), so their
7311    // hand-written `table.register(SelectiveScan/SsdChunkScan, &[dt; 6], ...)`
7312    // loops that used to live here were DELETED with the migration.
7313
7314    // Nf4Matmul: 3 inputs (activations T, w_packed U8, absmax F32) + 1
7315    // output T, where T ∈ {F32, F16, BF16}. The binding-table key
7316    // shape is [T, U8, F32, T].
7317    table.register(
7318        Nf4Matmul,
7319        &[DType::F32, DType::U8, DType::F32, DType::F32],
7320        cpu,
7321        nf4_matmul_f32_cpu_wrapper,
7322    );
7323    table.register(
7324        Nf4Matmul,
7325        &[DType::F16, DType::U8, DType::F32, DType::F16],
7326        cpu,
7327        nf4_matmul_f16_cpu_wrapper,
7328    );
7329    table.register(
7330        Nf4Matmul,
7331        &[DType::BF16, DType::U8, DType::F32, DType::BF16],
7332        cpu,
7333        nf4_matmul_bf16_cpu_wrapper,
7334    );
7335
7336    // The 21 in-place unary activations (Relu/Silu/GeluTanh/Tanh/Sigmoid/Neg/Abs/
7337    // Sqr/Sqrt/Rsqrt/Recip/Exp/Log/Sin/Cos/Sign/Floor/Ceil/Round/Erf/Gelu ×
7338    // F32/F64/BF16/F16 = 84 bindings, each key [T, T]) are now registered FROM
7339    // fuel-dispatch/kernel-contracts/cpu/inplace-unary-affine.fkc.md by
7340    // register_cpu_inplace_from_contract near the top of this fn: each per-op
7341    // section declares a BASE entry_point `<op>_inplace` + enumerates
7342    // [F32,F64,BF16,F16], so the importer's §3.4 dtype fan resolves
7343    // `<op>_inplace_<dt>` to the exact wrapper. All hand-written in-place unary
7344    // regs (the 5-op starter set + the 16-op expansion loop) were DELETED with
7345    // the migration; the shared `unary_inplace` chassis section is describe-only.
7346
7347    // (ClampElementwise / PowIElementwise F32 are now registered from the
7348    // affine-clamp-powi contract above.)
7349
7350    // Comparison (6 ops × 4 dtypes, key [T, T, U8]) + ternary select `where`
7351    // (4 dtypes, key [U8, T, T, T]) are now registered FROM the compare-where
7352    // FKC contract via register_cpu_compare_where_from_contract (near the top of
7353    // this fn) — the hand-written regs (and the `compare` / `where_dts`
7354    // dtype-list closures) are DELETED.
7355
7356    // Rounding / sign / transcendental unary ops (floor/ceil/round/sign/erf/
7357    // gelu/rsqrt × F32/F64/BF16/F16) are registered from the elementwise-unary
7358    // FKC contract via register_cpu_unary_from_contract (near the top of this fn).
7359
7360    // (Flip / Roll × 6 dtypes [T, T] and CumSum × 4 dtypes [T, T] are now
7361    // registered FROM the shape-ops FKC contract via
7362    // register_cpu_shape_ops_from_contract near the top of this fn — Flip/Roll are
7363    // one dtype-agnostic wrapper fanned per dtype; CumSum's per-dtype typed
7364    // sections resolve AS-IS. The hand-written regs were DELETED — FKC is the sole
7365    // path.)
7366
7367    // (WriteSlice + WriteSliceRotating × 6 dtypes, key [T, T], are now registered
7368    // FROM the shape-ops FKC contract via register_cpu_shape_ops_from_contract
7369    // near the top of this fn — one dtype-agnostic wrapper each, fanned per dtype.
7370    // Both model `dest` as the in-place OUTPUT slot (and rotating's `position` as a
7371    // non-key runtime operand), so the imported key matches build_lookup_dtypes'
7372    // canonicalized `[T_src, T_out]`. The hand-written regs were DELETED — FKC is
7373    // the sole path.)
7374
7375    // Triu / Tril share one byte-level kernel (dtype-agnostic).
7376    table.register(Triu, &unary(f32_dt), cpu, triu_cpu_wrapper);
7377    table.register(Triu, &unary(f64_dt), cpu, triu_cpu_wrapper);
7378    table.register(Triu, &unary(bf16_dt), cpu, triu_cpu_wrapper);
7379    table.register(Triu, &unary(f16_dt), cpu, triu_cpu_wrapper);
7380    table.register(Triu, &unary(u32_dt), cpu, triu_cpu_wrapper);
7381    table.register(Triu, &unary(u8_dt), cpu, triu_cpu_wrapper);
7382    table.register(Tril, &unary(f32_dt), cpu, tril_cpu_wrapper);
7383    table.register(Tril, &unary(f64_dt), cpu, tril_cpu_wrapper);
7384    table.register(Tril, &unary(bf16_dt), cpu, tril_cpu_wrapper);
7385    table.register(Tril, &unary(f16_dt), cpu, tril_cpu_wrapper);
7386    table.register(Tril, &unary(u32_dt), cpu, tril_cpu_wrapper);
7387    table.register(Tril, &unary(u8_dt), cpu, tril_cpu_wrapper);
7388
7389    // (LogSoftmaxLastDim × 4 dtypes is now registered FROM the norm FKC contract
7390    // via register_cpu_norm_from_contract near the top of this fn, alongside
7391    // Softmax / RmsNorm / LayerNorm forward.)
7392
7393    // (SoftmaxLastDimBackward / LogSoftmaxLastDimBackward / LayerNormLastDimBackward
7394    // / RmsNormLastDimBackward × 4 dtypes = 16 bindings, key [T, T, T]) are now
7395    // registered FROM the norm-backward FKC contract via
7396    // register_cpu_norm_backward_from_contract near the top of this fn — the BARE
7397    // backward (two inputs y/x + upstream gradient g → one passthrough output;
7398    // outer_count/last_dim/eps in OpParams). Their SEPARATE FusedKernelRegistry
7399    // seam (register_default_fused_kernels) stays untouched.
7400    // ReduceMaxToBackward (× 4 dtypes, key [T, T, T]) is now registered FROM the
7401    // reduce-to FKC contract (`register_cpu_reduce_to_from_contract`); the
7402    // hand-written regs were DELETED (FKC is the sole path).
7403
7404    // (MaskedFill × 6 dtypes, key [T, U8, T] — x dtype, mask U8, output == x — is
7405    // now registered FROM the shape-ops FKC contract via
7406    // register_cpu_shape_ops_from_contract near the top of this fn: `input` is the
7407    // sole varying operand that drives the fan, `mask` is the fixed U8 slot, and
7408    // `out: passthrough(input)`. The hand-written regs + the `masked_dtypes`
7409    // closure were DELETED — FKC is the sole path.)
7410
7411    // (Pad forward (Constant/Reflect/Replicate) × 6 dtypes — key [T, T], one
7412    // dtype-agnostic `pad_cpu_wrapper` dispatching all three modes at runtime via
7413    // `mode_tag` — is now registered FROM the padding FKC contract via
7414    // register_cpu_padding_from_contract near the top of this fn. The contract's
7415    // ONE mode-unified `## pad` section fans its 6 wired dtypes (U8/U32/BF16/F16/
7416    // F32/F64), ALL resolving `pad_cpu_wrapper`; the three per-mode sections +
7417    // the pad_walk_cpu helper are `registrable: false` describe-only. The
7418    // hand-written regs were DELETED — FKC is the sole path for the forward half.)
7419
7420    // (PadBackward × 4 dtypes — key [T, T], typed accumulation — is likewise
7421    // registered FROM the padding FKC contract via
7422    // register_cpu_padding_from_contract near the top of this fn; the
7423    // hand-written regs were DELETED — FKC is the sole path for the backward
7424    // half.)
7425
7426    // (Elementwise unary BF16 + F16 — like F32/F64 — are registered from the
7427    // elementwise-unary FKC contract via register_cpu_unary_from_contract near
7428    // the top of this fn; the importer fans each per-op section over all four
7429    // dtypes. The binary bf16/f16 ops likewise come from the elementwise-binary
7430    // contract.)
7431
7432    // (Concat — a variadic uniform-dtype op (N inputs, all the same dtype, plus
7433    // output) — is now registered FROM the shape-ops FKC contract via
7434    // register_cpu_shape_ops_from_contract near the top of this fn: the importer
7435    // treats the variadic list as ONE representative input, so the fan builds the
7436    // canonical `[T, T]` shorthand key per supported dtype (9 dtypes; the lookup
7437    // site collapses the actual N+1 dtype list to this same shorthand). The
7438    // hand-written loop was DELETED — FKC is the sole path.)
7439
7440    // (SoftmaxLastDim / RmsNormLastDim / LayerNormLastDim × 4 dtypes are now
7441    // registered FROM the norm FKC contract via register_cpu_norm_from_contract
7442    // near the top of this fn — key [T, T], bare normalization, no affine operand.
7443    // Their SEPARATE FusedKernelRegistry seam and the norm-backward regs stay
7444    // hand-written.)
7445
7446    // (IndexSelect / Gather × 9 dtypes (key [T, U32, T]) are now registered FROM
7447    // the indexing FKC contract via register_cpu_indexing_from_contract above —
7448    // one dtype-agnostic wrapper each, fanned per dtype from a BASE entry_point.
7449    // The hand-written loop was DELETED — FKC is the sole path.)
7450
7451    // (Rope × 4 dtypes is now registered FROM the rope FKC contract via
7452    // register_cpu_rope_from_contract near the top of this fn — key
7453    // [T, T, T, T] (x, cos, sin + passthrough output), geometry in
7454    // OpParams::Rope. Its SEPARATE FusedKernelRegistry seam
7455    // (register_default_fused_kernels, FusedOps::ROPE) stays hand-written.)
7456
7457    // QMatMul: F32 activations, U32 weight blocks, F32 output.
7458    table.register(
7459        QMatMul,
7460        &[f32_dt, u32_dt, f32_dt],
7461        cpu,
7462        qmatmul_f32_cpu_wrapper,
7463    );
7464
7465    // (IndexAdd / ScatterAdd × 4 dtypes (key [T, U32, T, T]) are now registered
7466    // FROM the indexing FKC contract via register_cpu_indexing_from_contract
7467    // above — each per-dtype `<op>_<dt>` entry_point resolved AS-IS to its OWN
7468    // typed wrapper. The hand-written regs were DELETED — FKC is the sole path.)
7469
7470    // ArgMax/ArgMin: input dtype varies, output is U32. The dispatch
7471    // wrapper still does its internal input-dtype match (preserves
7472    // current behavior). Register `[input_dt, U32]` once per input
7473    // dtype the dispatcher handles so the binding table can also
7474    // route directly when we collapse the wrapper later.
7475    for dt in [f32_dt, f64_dt, bf16_dt, f16_dt] {
7476        table.register(ArgMaxDim, &[dt, u32_dt], cpu, argmax_dim_u32_cpu_dispatch);
7477        table.register(ArgMinDim, &[dt, u32_dt], cpu, argmin_dim_u32_cpu_dispatch);
7478    }
7479
7480    // (Affine F64/BF16/F16 are now registered from the affine-clamp-powi
7481    // contract above.)
7482
7483    // Op::Copy — D2H / SameDevice byte-level transfer. The CPU
7484    // registration here is the CPU→CPU memcpy noop; per-source-
7485    // backend registrations live in their dispatch crates
7486    // (`register_cuda_kernels`, `vulkan_dispatch::register_vulkan_kernels`).
7487    // Bridge-retirement Phase 2 (post-9c): every realize root that
7488    // isn't on CPU gets an `Op::Copy { target: Cpu }` spliced in
7489    // before realize; the kernel dispatch resolves on the *source*
7490    // backend's BackendId. CPU→CPU is registered for uniformity (the
7491    // splice doesn't fire when device == Cpu, but kernels registered
7492    // here let direct executor tests round-trip through OpKind::Copy
7493    // on the universal fallback).
7494    let copy_dtypes = [
7495        f32_dt,
7496        f64_dt,
7497        bf16_dt,
7498        f16_dt,
7499        u32_dt,
7500        u8_dt,
7501        DType::I16,
7502        DType::I32,
7503        DType::I64,
7504        // GAP-168(c): Bool (a comparison mask) must be copyable — realize splices
7505        // Op::Copy to materialize a result to host.
7506        DType::Bool,
7507    ];
7508    for dt in copy_dtypes {
7509        table.register(Copy, &[dt, dt], cpu, copy_from_cpu_wrapper);
7510    }
7511    // (ClampElementwise / PowIElementwise F64/BF16/F16 and the two-input
7512    // PowIElementwiseBackward × 4 dtypes are now registered from the
7513    // affine-clamp-powi contract above. The FusedOps::POWI_BACKWARD
7514    // fused-registry seam remains separate and untouched.)
7515
7516    // Phase 7.6 step 7b — populate `PrecisionGuarantee` for every
7517    // CPU primitive registration. Every `table.register(...)` call
7518    // above defaulted to `PrecisionGuarantee::UNAUDITED`; this fill
7519    // pass upgrades them to `PRIMITIVE_DETERMINISTIC_CPU` (bit-stable
7520    // per hardware, deterministic iteration order, F32 accumulator
7521    // for half-precision). Sites that need a weaker claim should
7522    // call `table.register_with_precision(...)` explicitly *before*
7523    // this point — those won't be overwritten because the fill only
7524    // touches UNAUDITED entries.
7525    //
7526    // The architecture-target shape is precision-per-call-site,
7527    // but the 335+ CPU primitive registrations all share the same
7528    // deterministic property; bulk-applying the claim here keeps
7529    // the call sites concise while still ensuring every entry
7530    // carries an explicit, non-UNAUDITED PrecisionGuarantee that the
7531    // step-7b coverage lint can enforce.
7532    table.fill_unset_cpu_precision(crate::fused::PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU);
7533
7534    // Phase 7.6 step 8 — populate cost functions for every CPU
7535    // primitive registration. Every `table.register(...)` call
7536    // above defaulted to `unknown_cost`; this fill pass dispatches
7537    // each entry to its OpKind-appropriate cost-family function
7538    // (per `crate::cost::default_cost_for_op_kind`). Sites that
7539    // need a non-default cost claim should call
7540    // `table.register_full(...)` with their own `CostFn` *before*
7541    // this point — those won't be overwritten because the fill
7542    // only touches entries still bound to `unknown_cost`.
7543    //
7544    // Architecturally this is the same shape as the precision fill
7545    // above: bulk-apply the family-default at the end so the 335
7546    // CPU registration call sites stay concise, while the lint
7547    // (`precision_guarantee_lint_bit_stable_cpu_coverage_primitives`
7548    // companion: `cost_lint_per_op_kind_cpu_coverage`) enforces
7549    // that every OpKind ends up with a non-default cost function.
7550    table.fill_unset_cpu_cost(crate::cost::default_cost_for_op_kind);
7551}
7552
7553// =============================================================================
7554// Phase 7.5 — CUDA dispatch wrappers + registration
7555// =============================================================================
7556//
7557// First CUDA op through the unified binding table. Mirrors the CPU
7558// extractor + wrapper pattern but operates on `CudaStorageBytes`.
7559// Only `(AddElementwise, F32, Cuda)` is registered today; this is the
7560// "smallest possible first commit" that proves the CUDA migration
7561// pattern. Subsequent commits fan out to the rest of the op surface
7562// using the same wrapper-macro shape.
7563
7564/// Helper: extract `&CudaStorageBytes` from `&Storage`. Returns
7565/// Err if the variant isn't `BackendStorage::Cuda`.
7566#[cfg(feature = "cuda")]
7567pub fn cuda_input(s: &Storage) -> Result<&fuel_cuda_backend::CudaStorageBytes> {
7568    match &s.inner {
7569        BackendStorage::Cuda(c) => Ok(c),
7570        #[allow(unreachable_patterns)]
7571        _ => Err(Error::Msg("cuda kernel wrapper called with non-CUDA input".to_string()).bt()),
7572    }
7573}
7574
7575/// Helper: extract `&mut CudaStorageBytes` from `&mut Storage`.
7576#[cfg(feature = "cuda")]
7577pub fn cuda_output(s: &mut Storage) -> Result<&mut fuel_cuda_backend::CudaStorageBytes> {
7578    match &mut s.inner {
7579        BackendStorage::Cuda(c) => Ok(c),
7580        #[allow(unreachable_patterns)]
7581        _ => Err(Error::Msg("cuda kernel wrapper called with non-CUDA output".to_string()).bt()),
7582    }
7583}
7584
7585/// Dispatch wrapper for `(OpKind::Copy, [T, T], Cuda)` — copy FROM a
7586/// CUDA source storage. The key is the SOURCE backend; the
7587/// destination is whatever the executor pre-allocated the output as
7588/// (see [`crate::pipelined::WorkItemKind::Copy`]), so the wrapper
7589/// routes on the output's variant:
7590///
7591/// - **CPU output** → D2H via `CudaStorageBytes::to_cpu_bytes`
7592///   (the realize-root path; the original sole behavior).
7593/// - **CUDA output** → device-to-device via
7594///   `CudaStorageBytes::slot_copy_to_new` (one `memcpy_dtod`).
7595///   Same-device copies are emitted by `insert_safety_copies` for
7596///   destructive ops on GPU-placed tensors and by the residency
7597///   machinery — before this routing existed, any such Copy errored
7598///   with "cpu kernel wrapper called with non-CPU output"
7599///   (residency_eviction_live caught it).
7600///
7601/// Dtype-agnostic at the byte level — one wrapper covers every dtype
7602/// registered at this key.
7603///
7604/// Phase 2 of the bridge-retirement trajectory (post-9c). Replaces
7605/// the CUDA branch of `BackendStorage::read_to_cpu_bytes` (deleted
7606/// alongside).
7607#[cfg(feature = "cuda")]
7608fn copy_from_cuda_wrapper(
7609    inputs: &[Arc<RwLock<Storage>>],
7610    outputs: &mut [Arc<RwLock<Storage>>],
7611    _layouts: &[Layout],
7612    _params: &OpParams,
7613) -> Result<()> {
7614    if inputs.len() != 1 || outputs.len() != 1 {
7615        return Err(Error::Msg(format!(
7616            "copy_from_cuda_wrapper: expected 1 input + 1 output, got {} + {}",
7617            inputs.len(),
7618            outputs.len(),
7619        ))
7620        .bt());
7621    }
7622    let in_guard = read_storage(&inputs[0])?;
7623    // The key is the SOURCE backend: keep the typed error for a non-CUDA input.
7624    cuda_input(&in_guard)?;
7625    let mut out_guard = write_storage(&outputs[0])?;
7626    // The per-pair transfer (CPU output: finer D2H, no whole-device synchronize, the executor waited the
7627    // producer's CompletionHandle; CUDA output: write-into, no allocation, capture-safe) lives in
7628    // `BackendStorage::copy_from` (ROADMAP row 137, seam S3 step 2).
7629    out_guard.inner.copy_from(&in_guard.inner)
7630}
7631
7632/// Phase 7.5 CUDA registration — now `Op::Copy` D2H only.
7633///
7634/// **Scope (post-alpha.67, 2026-06-10):** every compute kernel has
7635/// migrated to `register_baracuda_cuda_kernels` — baracuda is the
7636/// single CUDA kernel home. The final migrations (answering
7637/// `docs/baracuda-ask-fp-gemm-reduce-to-2026-06-10.md`):
7638///
7639/// - **MatMul** (f32/f64/f16/bf16) → Phase 74 `gemm_dense` facade;
7640///   the local cuBLAS f32 path and CUTLASS bf16/f16 byte paths
7641///   retired with `byte_kernels`.
7642/// - **ReduceSumTo / ReduceMaxTo** (4 dtypes) → baracuda's
7643///   `reduce_{sum,max}_to_*` (sys symbols shipped since alpha.46).
7644/// - **CausalConv1d** → registration moved (was always
7645///   baracuda-backed via the Fuel-prepad bridge).
7646///
7647/// What stays: **Op::Copy** — D2H byte-buffer transfer, a
7648/// Fuel-specific cross-device path that lives at this layer rather
7649/// than in any kernel crate.
7650#[cfg(feature = "cuda")]
7651pub fn register_cuda_kernels(table: &mut KernelBindingTable) {
7652    use OpKind::*;
7653    let cuda = BackendId::Cuda;
7654
7655    // Op::Copy D2H — register at `(OpKind::Copy, [dt, dt], Cuda)` for
7656    // every dtype the byte-storage substrate supports. Source-backend
7657    // key (= Cuda); the wrapper produces a CPU output, copying through
7658    // `CudaStorageBytes::to_cpu_bytes`. Bridge-retirement Phase 2.
7659    let copy_dtypes = [
7660        DType::F32,
7661        DType::BF16,
7662        DType::F16,
7663        DType::U32,
7664        DType::F64,
7665        DType::U8,
7666        DType::I16,
7667        DType::I32,
7668        DType::I64,
7669        // GAP-168(c): Bool (a comparison mask) must be copyable — realize splices
7670        // `Op::Copy { target: Cpu }` to materialize a device result to host, so
7671        // WITHOUT this every realized CUDA comparison fails to dispatch. This is a
7672        // byte-level transfer via `to_cpu_bytes`, so no new kernel is required —
7673        // only the registration. Mirrors the CPU list above, which already has it.
7674        DType::Bool,
7675    ];
7676    for dt in copy_dtypes {
7677        table.register(Copy, &[dt, dt], cuda, copy_from_cuda_wrapper);
7678    }
7679}
7680
7681// =============================================================================
7682// Phase 7.5 B5+ — process-wide singleton (CapabilityRegistry + KernelBindingTable)
7683// =============================================================================
7684
7685/// Process-wide [`CapabilityRegistry`]. Initialized on first access
7686/// via [`global_registry`]; the CPU backend is auto-registered
7687/// always (universal fallback). Other backends register themselves
7688/// during their initialization or app startup.
7689///
7690/// Tests that need a private registry should construct one
7691/// directly with `CapabilityRegistry::new()` rather than touch the
7692/// global.
7693static GLOBAL_REGISTRY: OnceLock<RwLock<CapabilityRegistry>> = OnceLock::new();
7694
7695/// Process-wide topology generation counter. Bumped whenever the
7696/// set of registered backends / loaded kernels changes — so a
7697/// [`crate::topology::SystemTopology`] snapshot built at
7698/// generation N self-invalidates the next time a consumer asks for
7699/// a fresh view and the counter is N+1 or greater. See the
7700/// system-topology session prompt for the contract.
7701///
7702/// The two existing global-registry mutation sites
7703/// ([`register_backend_capabilities`] and [`extend_global_bindings`])
7704/// bump this counter unconditionally. Tests and a future device-loss
7705/// detector hook in via [`bump_topology_generation`].
7706static TOPOLOGY_GENERATION: AtomicU64 = AtomicU64::new(0);
7707
7708/// Read the current topology generation. Used by SystemTopology's
7709/// `current()` to decide whether its cached snapshot is still valid.
7710pub fn topology_generation() -> u64 {
7711    TOPOLOGY_GENERATION.load(Ordering::Acquire)
7712}
7713
7714/// Bump the topology generation counter. Every component that can
7715/// change the visible set of backends or devices should call this
7716/// after the mutation lands so consumers see a self-healing
7717/// `SystemTopology::current()` next call. Cheap (one atomic add);
7718/// `Release` ordering pairs with the `Acquire` load in
7719/// `topology_generation`.
7720pub fn bump_topology_generation() {
7721    // Test builds only: a test that needs the generation to hold still (it
7722    // optimizes a graph and then realizes it, and the executor returns
7723    // `Error::TopologyChanged` if the generation moved in between) holds
7724    // `TOPOLOGY_TEST_GATE` for writing; every bump waits on it for reading.
7725    // Without this, any other test in the same binary that registers a
7726    // kernel or backend can bump mid-way (ROADMAP row 165).
7727    #[cfg(test)]
7728    let _gate = TOPOLOGY_TEST_GATE
7729        .read()
7730        .unwrap_or_else(|poisoned| poisoned.into_inner());
7731    TOPOLOGY_GENERATION.fetch_add(1, Ordering::Release);
7732}
7733
7734/// Test-only gate; see [`bump_topology_generation`]. A holder must not call
7735/// anything that bumps the generation while it holds the write guard (that
7736/// would wait on itself): initialise the lazily built globals first.
7737#[cfg(test)]
7738pub(crate) static TOPOLOGY_TEST_GATE: RwLock<()> = RwLock::new(());
7739
7740// =============================================================================
7741// Step E Phase C / B1 — per-device in-flight async-op counter (the load signal)
7742// =============================================================================
7743
7744/// Process-wide per-[`DeviceLocation`] in-flight async-op counter — the
7745/// "queue depth / slot utilization" load signal `06-runtime` names. The
7746/// same idiom as [`TOPOLOGY_GENERATION`]: a lazily-initialized
7747/// process-wide table the executor mutates and a runtime selector reads.
7748///
7749/// **What it counts.** The number of GPU operations the executor has
7750/// SUBMITTED but not yet observed completed, per device. It is a
7751/// *fuel-internal* count derived from the A4b async-completion handle
7752/// lifecycle ([`compiled::execute_compiled`]'s CUDA event +
7753/// `pipelined`'s eager-submitted Vulkan batches), NOT a driver query
7754/// (`cuStreamQuery` is a busy/idle bool, not a depth). One `+1` per
7755/// async submit ([`inflight_inc`]), one `-1` per completion-handle
7756/// retirement ([`inflight_dec`], fired from the handle's `Drop`).
7757///
7758/// **Narrowed by "event only where waited" (A4b open question #4).** A CUDA
7759/// node the `pipelined` executor's `WaitSet` pre-scan elides never builds a
7760/// `CudaCompletion` at all (`produce_pending` returns `Ready` directly, no
7761/// `Event`, no `inc`/`dec`) — see `compiled::execute_compiled_with_wait_hint`.
7762/// So on `OrderSource::Default`/`Optimized` realizes this counter now tracks
7763/// only WAITED CUDA work (cross-device `Copy`/`Move` producers, plus whatever
7764/// handles are still alive when sampled) rather than literally every enqueued
7765/// op — same-device-only kernels never touch it, elided or not, on the theory
7766/// that they were never individually observable before this change either
7767/// (only swept up in the old per-node drain). `OrderSource::Streaming` — the
7768/// ONLY order source the production load-aware picker
7769/// (`ranker::DeviceLoadSelector` / `ChainedSelector`'s `load_tier` leg)
7770/// actually reads THIS counter through — never elides (falls back to
7771/// event-every-node), so the picker's own live-load signal is unaffected;
7772/// the narrowing only bites a caller reading `inflight_count` for a
7773/// *different*, concurrently-running `Default`/`Optimized` realize on the
7774/// same device, which would now under-report that realize's true same-device
7775/// backlog. No production caller does this today.
7776///
7777/// **Honesty / correctness.** This is a SCHEDULING HINT, never a
7778/// correctness gate — correctness rests entirely on the A4b waits (which for
7779/// elided nodes now come from `pipelined::sync_active_cuda_devices`'s
7780/// realize-end blanket stream sync instead of a per-node `Event`). So
7781/// the atomics are [`Ordering::Relaxed`] (no memory to synchronize) and
7782/// [`inflight_dec`] is underflow-saturating: a hint that briefly
7783/// mis-reads costs at most a sub-optimal route, never a wrong result.
7784///
7785/// **CPU.** Keyed uniformly by `DeviceLocation`, but the CPU dispatch
7786/// path is synchronous and never builds an async completion handle, so
7787/// `inflight_count(DeviceLocation::Cpu)` is always 0 — no special-case
7788/// needed. A `BackendStreams` impl reports CPU as `None` (no queue
7789/// concept) regardless (see `fuel-tensor::pipelined_bridge`).
7790static DEVICE_INFLIGHT: OnceLock<RwLock<HashMap<DeviceLocation, AtomicU32>>> = OnceLock::new();
7791
7792fn device_inflight_table() -> &'static RwLock<HashMap<DeviceLocation, AtomicU32>> {
7793    DEVICE_INFLIGHT.get_or_init(|| RwLock::new(HashMap::new()))
7794}
7795
7796/// Increment the in-flight async-op count for `loc` — called when the
7797/// executor SUBMITS an async op (the same site that builds an A4b
7798/// completion handle). Cheap: a single relaxed `fetch_add` once the
7799/// per-device slot exists (the slot is created once, under a brief write
7800/// lock, on the first submit to a device). A poisoned lock is swallowed
7801/// (the counter is a hint; a poisoned table just stops tracking — never
7802/// a panic on a production path).
7803pub fn inflight_inc(loc: DeviceLocation) {
7804    let table = device_inflight_table();
7805    // Fast path: slot already exists — read lock + relaxed add, no map mutation.
7806    if let Ok(guard) = table.read()
7807        && let Some(slot) = guard.get(&loc)
7808    {
7809        slot.fetch_add(1, Ordering::Relaxed);
7810        return;
7811    }
7812    // Slow path: create the slot. `entry().or_insert` is idempotent under the
7813    // write lock, so a racing inc that took the same slow path is harmless —
7814    // whichever lands second sees the slot and adds to it.
7815    if let Ok(mut guard) = table.write() {
7816        guard
7817            .entry(loc)
7818            .or_insert_with(|| AtomicU32::new(0))
7819            .fetch_add(1, Ordering::Relaxed);
7820    }
7821}
7822
7823/// Decrement the in-flight async-op count for `loc` — called when an A4b
7824/// completion handle RETIRES (its `Drop`). Underflow-saturating: if the
7825/// slot is missing or already 0 this is a no-op, so an unexpected extra
7826/// dec can never wrap the count to `u32::MAX` and poison future
7827/// scheduling. (Under the balance invariant — every `inc` is matched by
7828/// exactly one `dec` via the handle's `Drop` — this saturation never
7829/// actually fires; it is pure defense.)
7830pub fn inflight_dec(loc: DeviceLocation) {
7831    let table = device_inflight_table();
7832    if let Ok(guard) = table.read()
7833        && let Some(slot) = guard.get(&loc)
7834    {
7835        // saturating: never wrap below 0.
7836        let _ = slot.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
7837            Some(v.saturating_sub(1))
7838        });
7839    }
7840}
7841
7842/// Read the current in-flight async-op count for `loc`. The signal a
7843/// load-aware selector consults (Step E Phase C / C2, via
7844/// `BackendStreams::pending_work_count`). 0 for a device that has never
7845/// submitted async work (including CPU, which never submits any).
7846pub fn inflight_count(loc: DeviceLocation) -> u32 {
7847    let table = device_inflight_table();
7848    table
7849        .read()
7850        .ok()
7851        .and_then(|guard| guard.get(&loc).map(|slot| slot.load(Ordering::Relaxed)))
7852        .unwrap_or(0)
7853}
7854
7855/// Per-device ESTIMATED BACKLOG in nanoseconds: the executor's own
7856/// submitted-but-unfinished work x each op's estimated cost (row 158 slice
7857/// 2). Sibling of [`DEVICE_INFLIGHT`] (which counts ops); this sums their
7858/// estimated time, so a route picker can tell a 1 us queue from a 1 h one.
7859///
7860/// A slot exists only for a device that has had [`backlog_add_ns`] called, and
7861/// [`backlog_estimate_ns`] returns `None` until then: a device nobody feeds
7862/// reports NO estimate (never a fabricated "0 ns idle"), so a selector falls
7863/// back to the queue-depth tier. Relaxed atomics; a scheduling hint, never a
7864/// correctness gate; [`backlog_sub_ns`] saturates at 0.
7865static DEVICE_BACKLOG_NS: OnceLock<RwLock<HashMap<DeviceLocation, AtomicU64>>> = OnceLock::new();
7866
7867fn device_backlog_table() -> &'static RwLock<HashMap<DeviceLocation, AtomicU64>> {
7868    DEVICE_BACKLOG_NS.get_or_init(|| RwLock::new(HashMap::new()))
7869}
7870
7871/// Add `ns` of estimated work to `loc`'s backlog (call at submit, with the
7872/// op's estimated cost). Saturating; a poisoned lock stops tracking.
7873pub fn backlog_add_ns(loc: DeviceLocation, ns: u64) {
7874    let table = device_backlog_table();
7875    let add = |slot: &AtomicU64| {
7876        let _ = slot.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
7877            Some(v.saturating_add(ns))
7878        });
7879    };
7880    if let Ok(guard) = table.read()
7881        && let Some(slot) = guard.get(&loc)
7882    {
7883        add(slot);
7884        return;
7885    }
7886    if let Ok(mut guard) = table.write() {
7887        add(guard.entry(loc).or_insert_with(|| AtomicU64::new(0)));
7888    }
7889}
7890
7891/// Remove `ns` from `loc`'s backlog (call when the work it was added for
7892/// retires). Saturates at 0; a no-op for a device never fed.
7893pub fn backlog_sub_ns(loc: DeviceLocation, ns: u64) {
7894    if let Ok(guard) = device_backlog_table().read()
7895        && let Some(slot) = guard.get(&loc)
7896    {
7897        let _ = slot.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
7898            Some(v.saturating_sub(ns))
7899        });
7900    }
7901}
7902
7903/// The estimated backlog for `loc` in ns, or `None` when nothing has ever
7904/// been fed for it (no estimate; NOT idle).
7905pub fn backlog_estimate_ns(loc: DeviceLocation) -> Option<u64> {
7906    device_backlog_table()
7907        .read()
7908        .ok()
7909        .and_then(|guard| guard.get(&loc).map(|slot| slot.load(Ordering::Relaxed)))
7910}
7911
7912/// Name of the environment variable that turns the executor's backlog feed ON (any of `1`, `true`, `on`,
7913/// `yes`). The feed is OFF by default: with it on, a real Qwen3-0.6B Q4_K_M decode on Vulkan resolved ~85%
7914/// of its branches to the CPU arm and ran slower than without it (ROADMAP row 158, n = 3 alternating
7915/// pairs, direction only, one model, Vulkan only); the backlog accumulates within a realize and drains only at its end (ROADMAP row 158 CAUSE). Set the variable,
7916/// or call [`set_backlog_feed_enabled`], to measure it.
7917pub const BACKLOG_FEED_ENV: &str = "FUEL_BACKLOG_FEED";
7918
7919/// 0 = no override (read [`BACKLOG_FEED_ENV`]), 1 = forced on, 2 = forced off.
7920static BACKLOG_FEED_OVERRIDE: AtomicU32 = AtomicU32::new(0);
7921
7922/// Force the executor's backlog feed on or off for this process, overriding [`BACKLOG_FEED_ENV`]. For the
7923/// tests and probes that measure the feed.
7924pub fn set_backlog_feed_enabled(on: bool) {
7925    BACKLOG_FEED_OVERRIDE.store(if on { 1 } else { 2 }, Ordering::Relaxed);
7926}
7927
7928/// Seeded mutant for the acceptance test (`FUEL_BACKLOG_NO_RETIRE=1`): the feed never takes an estimate
7929/// back out until the realize ends, which is the cumulative behaviour that sent ~85% of a real model's
7930/// branches to the CPU arm (ROADMAP row 158). A test seam, never set in production.
7931pub(crate) fn backlog_retire_disabled() -> bool {
7932    static FROM_ENV: OnceLock<bool> = OnceLock::new();
7933    *FROM_ENV.get_or_init(|| {
7934        std::env::var("FUEL_BACKLOG_NO_RETIRE").is_ok_and(|v| {
7935            matches!(
7936                v.trim().to_ascii_lowercase().as_str(),
7937                "1" | "true" | "on" | "yes"
7938            )
7939        })
7940    })
7941}
7942
7943/// Whether the executor adds its in-flight work to the device backlog (default: no).
7944pub(crate) fn backlog_feed_enabled() -> bool {
7945    match BACKLOG_FEED_OVERRIDE.load(Ordering::Relaxed) {
7946        1 => true,
7947        2 => false,
7948        _ => {
7949            static FROM_ENV: OnceLock<bool> = OnceLock::new();
7950            *FROM_ENV.get_or_init(|| {
7951                std::env::var(BACKLOG_FEED_ENV).is_ok_and(|v| {
7952                    matches!(
7953                        v.trim().to_ascii_lowercase().as_str(),
7954                        "1" | "true" | "on" | "yes"
7955                    )
7956                })
7957            })
7958        }
7959    }
7960}
7961
7962/// What one realize added to the per-device backlog, taken back out when the realize ends (ROADMAP row
7963/// 158, the executor feed). The executor owns one for the length of a walk and calls [`Self::add`] for
7964/// each kernel it submits to a GPU, with that node's compile-time estimate
7965/// ([`crate::compiled::CompiledNode::est_ns`]); the guard's `Drop` subtracts exactly what was added, on
7966/// the `Ok` path AND when an error unwinds the realize, so the backlog cannot leak.
7967///
7968/// Granularity, stated: work is counted from submit until the END OF THE REALIZE that submitted it, not
7969/// until its fence signals. A realize ends by draining every device it used, so at its end the work has
7970/// retired; within it the figure is an upper bound on what is still queued. What it is for: a second
7971/// realize (multi-agent serving) resolving a branch while this one's work is outstanding.
7972///
7973/// A CPU location and a zero estimate add nothing: the CPU has no queue to estimate, and a device the
7974/// executor cannot price must keep reporting NO estimate ([`backlog_estimate_ns`] `None`), never idle.
7975#[derive(Default)]
7976pub struct BacklogLedger {
7977    entries: Vec<LedgerEntry>,
7978}
7979
7980/// One fed estimate: where it was added, how much, and (when the backend can say) a non-blocking probe
7981/// that turns true once the work it stands for has completed.
7982struct LedgerEntry {
7983    loc: DeviceLocation,
7984    ns: u64,
7985    done: Option<Box<dyn Fn() -> bool + Send + Sync>>,
7986}
7987
7988impl std::fmt::Debug for BacklogLedger {
7989    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7990        f.debug_struct("BacklogLedger")
7991            .field("entries", &self.entries.len())
7992            .finish()
7993    }
7994}
7995
7996impl BacklogLedger {
7997    /// An empty ledger.
7998    pub fn new() -> Self {
7999        Self::default()
8000    }
8001
8002    /// Add `ns` of estimated work to `loc`'s backlog and keep it until the ledger is dropped (the end of
8003    /// the realize). For work with no completion probe.
8004    pub fn add(&mut self, loc: DeviceLocation, ns: u64) {
8005        self.push(loc, ns, None);
8006    }
8007
8008    /// Add `ns` of estimated work to `loc`'s backlog and take it back out as soon as `done()` reports the
8009    /// work finished (checked by [`Self::retire_completed`], without blocking), or when the ledger is
8010    /// dropped, whichever comes first. `done` must not block.
8011    pub fn add_until(
8012        &mut self,
8013        loc: DeviceLocation,
8014        ns: u64,
8015        done: impl Fn() -> bool + Send + Sync + 'static,
8016    ) {
8017        self.push(loc, ns, Some(Box::new(done)));
8018    }
8019
8020    fn push(
8021        &mut self,
8022        loc: DeviceLocation,
8023        ns: u64,
8024        done: Option<Box<dyn Fn() -> bool + Send + Sync>>,
8025    ) {
8026        if ns == 0 || matches!(loc, DeviceLocation::Cpu) {
8027            return;
8028        }
8029        backlog_add_ns(loc, ns);
8030        crate::optimizer_trace::global().record_backlog_added(ns);
8031        self.entries.push(LedgerEntry { loc, ns, done });
8032    }
8033
8034    /// Take back every entry whose probe reports its work finished. Never blocks. Called as the executor
8035    /// walks, so the backlog the picker reads is the work still QUEUED, not everything submitted so far.
8036    pub fn retire_completed(&mut self) {
8037        self.entries.retain(|e| {
8038            if e.done.as_ref().is_some_and(|d| d()) {
8039                backlog_sub_ns(e.loc, e.ns);
8040                crate::optimizer_trace::global().record_backlog_retired(e.ns);
8041                false
8042            } else {
8043                true
8044            }
8045        });
8046    }
8047
8048    /// What this ledger has added to `loc` and has outstanding (added minus retired).
8049    pub fn outstanding_ns(&self, loc: DeviceLocation) -> u64 {
8050        self.entries
8051            .iter()
8052            .filter(|e| e.loc == loc)
8053            .fold(0, |acc, e| acc.saturating_add(e.ns))
8054    }
8055}
8056
8057impl Drop for BacklogLedger {
8058    fn drop(&mut self) {
8059        for e in self.entries.drain(..) {
8060            backlog_sub_ns(e.loc, e.ns);
8061            crate::optimizer_trace::global().record_backlog_retired(e.ns);
8062        }
8063    }
8064}
8065
8066/// Process-wide [`KernelBindingTable`]. Initialized on first access
8067/// with the CPU dispatch wrappers from [`register_cpu_kernels`].
8068/// Other backends extend it when they register.
8069///
8070/// **Copy-on-write (GAP-015).** The lock guards an `Arc` *pointer*, not the
8071/// table. [`global_bindings`] clones the `Arc` and drops the read guard
8072/// before returning, so no read guard ever escapes the accessor and a
8073/// caller cannot hold one across a re-entrant region. That is what makes
8074/// the deadlock unrepresentable rather than merely unlikely: std's
8075/// `RwLock` blocks new readers once a writer queues (anti-writer-
8076/// starvation), so under the old `RwLock<KernelBindingTable>` a thread
8077/// holding a read guard that requested a *second* read waited on a lock
8078/// its own guard was blocking. Writers clone-mutate-swap.
8079static GLOBAL_BINDINGS: OnceLock<RwLock<Arc<KernelBindingTable>>> = OnceLock::new();
8080
8081/// Serializes *writers* to [`GLOBAL_BINDINGS`], and it is required for
8082/// correctness, not just tidiness.
8083///
8084/// A bare clone-mutate-swap would lose updates: two writers could clone the
8085/// same base concurrently and the second swap would silently discard the
8086/// first one's registrations. Worse, it would break
8087/// [`crate::runtime_fused_kernels::adopt_runtime_fused`], whose contract
8088/// requires its check-then-bind ("is this exact `KernelRef` already bound?"
8089/// then register) to be **atomic with respect to other writers** — two
8090/// threads racing to adopt the same region+kernel would both observe "not
8091/// bound" and both register, producing the duplicate-`KernelRef` that
8092/// `finalize` rejects.
8093///
8094/// This is deliberately a separate lock from the `RwLock` above so that the
8095/// caller-supplied extender and `finalize` run *outside* the `RwLock`; the
8096/// write guard is taken only for the pointer swap. Two consequences: a
8097/// panic in `finalize` can no longer poison the read path (the second
8098/// incident on this lock — see `runtime_fused_kernels.rs`), and an extender
8099/// that happens to call [`global_bindings`] reads a snapshot instead of
8100/// self-deadlocking. Poisoning is tolerated on both locks via
8101/// `unwrap_or_else(PoisonError::into_inner)`: a panicked writer leaves the
8102/// published table untouched, so the state a later caller observes is the
8103/// last good one, not a torn one.
8104static BINDINGS_WRITER: Mutex<()> = Mutex::new(());
8105
8106/// Initialize-once accessor for the binding-table cell. Both
8107/// [`global_bindings`] and [`extend_global_bindings`] route through this so
8108/// the init body exists exactly once.
8109fn bindings_cell() -> &'static RwLock<Arc<KernelBindingTable>> {
8110    GLOBAL_BINDINGS.get_or_init(|| {
8111        lock_trace("  BINDINGS init: begin");
8112        let mut t = KernelBindingTable::new();
8113        register_cpu_kernels(&mut t);
8114        lock_trace("  BINDINGS init: cpu done, entering optional backends");
8115        register_optional_backends(&mut t);
8116        lock_trace("  BINDINGS init: optional backends done");
8117        // Single init-boundary fail-fast: a duplicate `KernelRef` in the
8118        // hand-written static tables is a programmer error, surfaced once
8119        // here after all backends register — the never-panic replacement
8120        // for the former inline registration panic (the dynamic FKC
8121        // importer will call `finalize()?`).
8122        t.finalize()
8123            .expect("KernelBindingTable: duplicate kernel registration at init");
8124        RwLock::new(Arc::new(t))
8125    })
8126}
8127
8128fn default_cpu_caps() -> BackendCapabilities {
8129    use OpKind::*;
8130    use std::collections::HashSet;
8131    let mut op_dtype_support = HashSet::new();
8132    // The CPU coverage set must stay in lockstep with
8133    // `register_cpu_kernels`: each (op, dtype) pair registered there
8134    // is advertised here so capability-driven dispatch picks it.
8135    let f32_dt = DType::F32;
8136    for op in [
8137        AddElementwise,
8138        SubElementwise,
8139        MulElementwise,
8140        DivElementwise,
8141        ReluElementwise,
8142        NegElementwise,
8143        SqrElementwise,
8144        SqrtElementwise,
8145        RecipElementwise,
8146        AbsElementwise,
8147        TanhElementwise,
8148        ExpElementwise,
8149        LogElementwise,
8150        SinElementwise,
8151        CosElementwise,
8152        SigmoidElementwise,
8153        SiluElementwise,
8154        GeluElementwise,
8155        StepElementwise,
8156        SumReduce,
8157        MaxReduce,
8158        MinReduce,
8159        MeanReduce,
8160        MatMul,
8161        Conv2D,
8162        ConvTranspose2D,
8163        ReduceSumTo,
8164        ReduceMaxTo,
8165        FusedLinear,
8166        FlashAttn,
8167        PagedAttn,
8168        Affine,
8169        ClampElementwise,
8170        PowIElementwise,
8171        MaximumElementwise,
8172        MinimumElementwise,
8173        Concat,
8174        SoftmaxLastDim,
8175        RmsNormLastDim,
8176        LayerNormLastDim,
8177        IndexSelect,
8178        Gather,
8179        Rope,
8180        IndexAdd,
8181        ScatterAdd,
8182        QMatMul,
8183        Copy,
8184    ] {
8185        op_dtype_support.insert((op, f32_dt));
8186    }
8187    // f64 elementwise families. Reductions, matmul, conv, composed
8188    // ops, indexing, and view ops will join the f64 set as their
8189    // kernels migrate.
8190    for op in [
8191        AddElementwise,
8192        SubElementwise,
8193        MulElementwise,
8194        DivElementwise,
8195        ReluElementwise,
8196        NegElementwise,
8197        SqrElementwise,
8198        SqrtElementwise,
8199        RecipElementwise,
8200        AbsElementwise,
8201        TanhElementwise,
8202        ExpElementwise,
8203        LogElementwise,
8204        SinElementwise,
8205        CosElementwise,
8206        SigmoidElementwise,
8207        SiluElementwise,
8208        GeluElementwise,
8209        StepElementwise,
8210        MaximumElementwise,
8211        MinimumElementwise,
8212        SumReduce,
8213        MaxReduce,
8214        MinReduce,
8215        MeanReduce,
8216        MatMul,
8217        Conv2D,
8218        ConvTranspose2D,
8219        ReduceSumTo,
8220        ReduceMaxTo,
8221        FusedLinear,
8222        FlashAttn,
8223        PagedAttn,
8224    ] {
8225        op_dtype_support.insert((op, DType::F64));
8226    }
8227    // bf16 and f16 elementwise families. Reductions/matmul/conv/
8228    // composed/indexing/Rope/scalar follow as kernels migrate.
8229    let half_elementwise_ops = [
8230        AddElementwise,
8231        SubElementwise,
8232        MulElementwise,
8233        DivElementwise,
8234        MaximumElementwise,
8235        MinimumElementwise,
8236        ReluElementwise,
8237        NegElementwise,
8238        SqrElementwise,
8239        SqrtElementwise,
8240        RecipElementwise,
8241        AbsElementwise,
8242        TanhElementwise,
8243        ExpElementwise,
8244        LogElementwise,
8245        SinElementwise,
8246        CosElementwise,
8247        SigmoidElementwise,
8248        SiluElementwise,
8249        GeluElementwise,
8250        StepElementwise,
8251    ];
8252    for op in half_elementwise_ops {
8253        op_dtype_support.insert((op, DType::BF16));
8254        op_dtype_support.insert((op, DType::F16));
8255    }
8256    // bf16/f16 reductions + matmul (kernels accumulate in f32).
8257    for op in [SumReduce, MaxReduce, MinReduce, MeanReduce, MatMul] {
8258        op_dtype_support.insert((op, DType::BF16));
8259        op_dtype_support.insert((op, DType::F16));
8260    }
8261    // bf16/f16 composed/fused ops (Softmax, RmsNorm, LayerNorm,
8262    // Rope, Conv2D, ConvTranspose2D, ReduceSumTo, ReduceMaxTo,
8263    // FusedLinear, FlashAttn, PagedAttn) — all use the f32-accumulator
8264    // pattern.
8265    for op in [
8266        SoftmaxLastDim,
8267        RmsNormLastDim,
8268        LayerNormLastDim,
8269        Rope,
8270        Conv2D,
8271        ConvTranspose2D,
8272        ReduceSumTo,
8273        ReduceMaxTo,
8274        FusedLinear,
8275        FlashAttn,
8276        PagedAttn,
8277    ] {
8278        op_dtype_support.insert((op, DType::BF16));
8279        op_dtype_support.insert((op, DType::F16));
8280    }
8281    // Concat / IndexSelect / Gather are dtype-agnostic at the
8282    // byte level — advertised across the universal float/int set.
8283    for dt in [
8284        DType::F64,
8285        DType::BF16,
8286        DType::F16,
8287        DType::U32,
8288        DType::U8,
8289        DType::I16,
8290        DType::I32,
8291        DType::I64,
8292    ] {
8293        op_dtype_support.insert((Concat, dt));
8294        op_dtype_support.insert((IndexSelect, dt));
8295        op_dtype_support.insert((Gather, dt));
8296    }
8297    // IndexAdd / ScatterAdd / Affine / Clamp / PowI for f64/bf16/f16.
8298    for dt in [DType::F64, DType::BF16, DType::F16] {
8299        op_dtype_support.insert((IndexAdd, dt));
8300        op_dtype_support.insert((ScatterAdd, dt));
8301        op_dtype_support.insert((Affine, dt));
8302        op_dtype_support.insert((ClampElementwise, dt));
8303        op_dtype_support.insert((PowIElementwise, dt));
8304    }
8305    // F64 composed/fused ops (Softmax, RmsNorm, LayerNorm, Rope).
8306    for op in [SoftmaxLastDim, RmsNormLastDim, LayerNormLastDim, Rope] {
8307        op_dtype_support.insert((op, DType::F64));
8308    }
8309    // Argmax/argmin always produce U32 indices.
8310    for op in [ArgMaxDim, ArgMinDim] {
8311        op_dtype_support.insert((op, DType::U32));
8312    }
8313    // Cast advertises every target dtype that has a wrapper
8314    // registered. The capability matrix says "this backend can
8315    // produce an F64 output via Cast"; the source-side coverage
8316    // is managed inside each wrapper's match arms.
8317    for target in [DType::F32, DType::F64, DType::BF16, DType::F16] {
8318        op_dtype_support.insert((Cast, target));
8319    }
8320    let (compute_throughput_flops_per_ns, mem_bandwidth_bytes_per_ns) =
8321        crate::ranker::default_backend_rates(BackendId::Cpu);
8322    BackendCapabilities {
8323        backend_id: BackendId::Cpu,
8324        device_location: DeviceLocation::Cpu,
8325        op_dtype_support,
8326        required_alignment: 64,
8327        access_granularity_bits: 8,
8328        transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
8329        storage_substrate: SubstrateClass::HostBytes,
8330        compute_throughput_flops_per_ns,
8331        mem_bandwidth_bytes_per_ns,
8332    }
8333}
8334
8335/// Default storage substrate for a backend, matching the storage type
8336/// each backend actually produces. Mirrors `topology::default_substrate_for`
8337/// (kept in lockstep; that one is private to `topology.rs`).
8338fn substrate_for_backend(backend: BackendId) -> SubstrateClass {
8339    match backend {
8340        BackendId::Cpu => SubstrateClass::HostBytes,
8341        BackendId::Cuda => SubstrateClass::CudaUntyped,
8342        BackendId::Vulkan => SubstrateClass::VulkanBuffer,
8343        BackendId::Metal => SubstrateClass::MetalBuffer,
8344        // `BackendId` is `#[non_exhaustive]`; a downstream variant
8345        // defaults to host bytes until it declares its own substrate.
8346        _ => SubstrateClass::HostBytes,
8347    }
8348}
8349
8350/// FKC cost unification — Part A.
8351///
8352/// Derive a [`BackendCapabilities`] for `backend` (at `device_location`)
8353/// from the kernel binding `table`. This is the general (any-backend)
8354/// analogue of `default_cpu_caps`: instead of a hand-maintained list,
8355/// it reads the backend's REGISTERED KERNELS out of the binding table
8356/// and advertises exactly the `(OpKind, DType)` pairs those kernels
8357/// cover.
8358///
8359/// The `(op, dtype)` derivation mirrors
8360/// [`crate::topology::SystemTopology`]'s `binding_op_coverage`: each
8361/// binding key carries per-operand dtypes (inputs then outputs); the
8362/// classic `(op, dtype)` shape takes the OUTPUT dtype — the last entry
8363/// in the key's dtype list. Single-dtype keys (most elementwise ops)
8364/// are unambiguous; multi-dtype keys (e.g. QMatMul `[F32, U32, F32]`)
8365/// still produce the consumer-relevant output-dtype entry.
8366///
8367/// **Why this fixes the placement cost model.** The placement cost
8368/// composer (`ranker::cost::compute_static_costs`) skips any candidate
8369/// whose backend has no `BackendCapabilities` in the registry —
8370/// leaving its `static_cost` at the default ZERO, so an uncapped GPU
8371/// candidate prices as free and can spuriously out-rank a real CPU
8372/// cost. Registering the caps this function derives makes
8373/// `capabilities_for(gpu)` return `Some`, so the GPU candidate's
8374/// FLOP/byte cost fn actually runs (see also
8375/// [`KernelBindingTable::fill_unset_cost_for_backend`], which ensures
8376/// those kernels carry a non-`unknown_cost` cost fn).
8377///
8378/// Alignment / granularity use conservative device defaults (256-byte
8379/// alignment for GPU buffers — covers CUDA's 256B and Vulkan's typical
8380/// storage-buffer alignment; byte-addressable). Transfer paths
8381/// advertise the universal `HostStaging` link back to the CPU so the
8382/// `TransferMatrix` can price GPU↔CPU crossings; richer paths (P2P,
8383/// shared memory) are a future refinement the backend can declare
8384/// explicitly. Never panics.
8385pub fn derive_backend_caps(
8386    backend: BackendId,
8387    device_location: DeviceLocation,
8388    table: &KernelBindingTable,
8389) -> BackendCapabilities {
8390    use std::collections::HashSet;
8391    let mut op_dtype_support: HashSet<(OpKind, DType)> = HashSet::new();
8392    for (op, dtypes, this_backend) in table.iter_keys() {
8393        if this_backend != backend {
8394            continue;
8395        }
8396        if let Some(&output_dt) = dtypes.last() {
8397            op_dtype_support.insert((op, output_dt));
8398        }
8399    }
8400    // GPU substrate + a universal host-staging path back to CPU so the
8401    // transfer matrix can price GPU↔CPU. CPU keeps its SameDevice self
8402    // edge (this function is general, but CPU has its own hand-tuned
8403    // `default_cpu_caps`; the CPU branch here is just defensive).
8404    let transfer_paths = if device_location == DeviceLocation::Cpu {
8405        vec![(DeviceLocation::Cpu, TransferPath::SameDevice)]
8406    } else {
8407        vec![(DeviceLocation::Cpu, TransferPath::HostStaging)]
8408    };
8409    let (required_alignment, access_granularity_bits) = match backend {
8410        BackendId::Cpu => (64, 8),
8411        // GPU buffer allocations: 256-byte alignment is a safe
8412        // superset (CUDA cudaMalloc is 256B-aligned; Vulkan storage
8413        // buffers meet this). Byte-addressable.
8414        _ => (256, 8),
8415    };
8416    let (compute_throughput_flops_per_ns, mem_bandwidth_bytes_per_ns) =
8417        crate::ranker::default_backend_rates(backend);
8418    BackendCapabilities {
8419        backend_id: backend,
8420        device_location,
8421        op_dtype_support,
8422        required_alignment,
8423        access_granularity_bits,
8424        transfer_paths,
8425        storage_substrate: substrate_for_backend(backend),
8426        compute_throughput_flops_per_ns,
8427        mem_bandwidth_bytes_per_ns,
8428    }
8429}
8430
8431/// FKC cost unification — Part A.
8432///
8433/// Register the [`BackendCapabilities`] for every non-CPU backend that
8434/// has kernels in `table` into the process-wide [`CapabilityRegistry`],
8435/// deriving each backend's caps from its registered kernels via
8436/// [`derive_backend_caps`]. Called once, at the same init boundary that
8437/// populates the global binding table (see [`global_bindings`]), AFTER
8438/// the kernels are registered — so the derivation sees the full kernel
8439/// set.
8440///
8441/// This is the registration half of Part A: it closes the gap where
8442/// only the CPU auto-registered caps, leaving CUDA/Vulkan candidates
8443/// priced at zero in the placement DP. CPU is skipped here because it
8444/// already auto-registers its hand-tuned [`default_cpu_caps`] via
8445/// [`global_registry`].
8446///
8447/// Idempotency: the registry appends and lookups pick the first match,
8448/// so this should run exactly once per backend. The single init
8449/// boundary in [`global_bindings`] guarantees that.
8450fn register_derived_gpu_caps(table: &KernelBindingTable) {
8451    use std::collections::HashSet;
8452    // Which non-CPU backends have at least one kernel registered?
8453    let gpu_backends: HashSet<BackendId> = table
8454        .iter_keys()
8455        .map(|(_, _, backend)| backend)
8456        .filter(|b| *b != BackendId::Cpu)
8457        .collect();
8458    for backend in gpu_backends {
8459        register_derived_caps_for(backend, table);
8460    }
8461}
8462
8463/// Derive and register the `BackendCapabilities` for ONE backend from the kernels `table` holds for it
8464/// (the per-backend step of [`register_derived_gpu_caps`]). A backend whose kernels are added to the
8465/// global table later, through [`extend_global_bindings`], calls this once from inside its extender
8466/// (ROADMAP row 137 step 6.1: `fuel-vulkan-dispatch`), because the init boundary no longer sees it.
8467/// The capability registry appends and lookups pick the first match, so call it exactly once per backend.
8468pub fn register_derived_caps_for(backend: BackendId, table: &KernelBindingTable) {
8469    // The backend's default place (GPU ordinal 0, or the CPU); one definition in `fuel-ir`.
8470    let device_location = backend.default_location();
8471    register_backend_capabilities(derive_backend_caps(backend, device_location, table));
8472}
8473
8474/// Read-lock the process-wide capability registry. CPU is auto-
8475/// registered on first access; subsequent backends register
8476/// themselves via [`register_backend_capabilities`].
8477/// TEMPORARY GAP-015 DIAGNOSTIC — env-gated (`FUEL_LOCK_TRACE=1`), off by
8478/// default, zero behavior change. Names the thread and the acquisition it is
8479/// ABOUT to attempt versus the one it completed; a thread that logs "want" and
8480/// never logs "got" IS the blocked party, which is what the deadlock's stack we
8481/// cannot capture (no debugger on this box) would otherwise have told us.
8482/// Revert once the opposing lock order is pinned.
8483#[inline]
8484pub(crate) fn lock_trace(what: &str) {
8485    if std::env::var_os("FUEL_LOCK_TRACE").is_some() {
8486        eprintln!("[locktrace] t={:?} {}", std::thread::current().id(), what);
8487    }
8488}
8489
8490pub fn global_registry() -> std::sync::RwLockReadGuard<'static, CapabilityRegistry> {
8491    lock_trace("want REGISTRY.oncelock+read");
8492    let l = GLOBAL_REGISTRY.get_or_init(|| {
8493        lock_trace("  REGISTRY init: begin");
8494        let mut r = CapabilityRegistry::new();
8495        r.register(default_cpu_caps());
8496        lock_trace("  REGISTRY init: end");
8497        RwLock::new(r)
8498    });
8499    let g = l.read().unwrap();
8500    lock_trace("got  REGISTRY.read");
8501    g
8502}
8503
8504/// Add a backend's capabilities to the process-wide registry.
8505/// Typically called by each backend's init / probe path during
8506/// app startup. Idempotent for the same `(backend_id,
8507/// device_location)` is the *caller's* responsibility — the
8508/// registry happily appends duplicates and the lookup picks the
8509/// first-registered match.
8510pub fn register_backend_capabilities(caps: BackendCapabilities) {
8511    lock_trace("want REGISTRY.oncelock+WRITE (from register_backend_capabilities)");
8512    let lock = GLOBAL_REGISTRY.get_or_init(|| {
8513        lock_trace("  REGISTRY init: begin (via register_backend_capabilities)");
8514        let mut r = CapabilityRegistry::new();
8515        r.register(default_cpu_caps());
8516        lock_trace("  REGISTRY init: end");
8517        RwLock::new(r)
8518    });
8519    lock.write().unwrap().register(caps);
8520    lock_trace("got+released REGISTRY.WRITE");
8521    bump_topology_generation();
8522}
8523
8524/// Take a **snapshot** of the process-wide kernel-binding table. CPU
8525/// dispatch wrappers are auto-registered on first access. When built with
8526/// the `cuda` feature, the CUDA PTX path + the baracuda-kernels-sys path
8527/// are also auto-registered — production callers picking up the
8528/// global table see all available backends without manual init.
8529///
8530/// Returns an owned `Arc`, **not** a lock guard (GAP-015). The read guard
8531/// is acquired and released entirely inside this function, so a caller
8532/// cannot hold one across a call that might write the table — the shape
8533/// that deadlocked. Holding the returned `Arc` indefinitely is safe and
8534/// cheap; it keeps that snapshot alive, it does not block anyone.
8535///
8536/// **Snapshot semantics are a correctness property, not just a side
8537/// effect.** A caller sees one point-in-time table for as long as it holds
8538/// the `Arc`, so a kernel adopted concurrently is invisible to a pass
8539/// already in flight. That makes an optimize pass a pure function of
8540/// `(graph, table snapshot)`. Under the old guard, a pass could observe the
8541/// table mutate mid-pass and emit a plan not reproducible from its own
8542/// inputs — which would break the `base_map_hash` recipe-identity property
8543/// that Tier-2 convergence depends on. Adoption exists to affect
8544/// *subsequent* passes, so no known path wants mid-pass visibility.
8545pub fn global_bindings() -> Arc<KernelBindingTable> {
8546    lock_trace("want BINDINGS.oncelock+snapshot");
8547    let cell = bindings_cell();
8548    let snapshot = {
8549        // Poison-tolerant: nothing that can panic runs under this guard
8550        // (it wraps an `Arc::clone` and nothing else), so a poisoned flag
8551        // here can only have come from an unrelated writer that already
8552        // left the published table intact.
8553        let guard = cell.read().unwrap_or_else(|e| e.into_inner());
8554        Arc::clone(&guard)
8555        // guard drops HERE, before returning — this is the whole fix.
8556    };
8557    lock_trace("got  BINDINGS snapshot (guard already released)");
8558    snapshot
8559}
8560
8561/// Auto-register every cargo-feature-gated backend that built. CPU is
8562/// always present (registered above); CUDA and Vulkan paths are
8563/// conditionally added. Future Metal / etc. paths hook in here.
8564fn register_optional_backends(table: &mut KernelBindingTable) {
8565    // CUDA is NOT registered here any more (ROADMAP row 137 step 6.2): the baracuda kernels live in
8566    // `fuel-cuda-dispatch`, above this crate, and reach the global table through `extend_global_bindings`
8567    // (`fuel_cuda_dispatch::install_global`, called by `fuel-tensor`), which also runs the CUDA cost fill
8568    // and the derived-capabilities step this function used to run.
8569    // Vulkan is NOT registered here any more (ROADMAP row 137 step 6.1): its kernels live in
8570    // `fuel-vulkan-dispatch`, above this crate, and reach the global table through
8571    // `extend_global_bindings` (`fuel_vulkan_dispatch::install_global`, called by `fuel-tensor`).
8572
8573    // FKC cost unification — Part A. Now that every compiled-in
8574    // backend's kernels are registered (and their cost fns filled),
8575    // derive + register the `BackendCapabilities` for every non-CPU
8576    // backend that has kernels, so the placement cost model's
8577    // `capabilities_for(gpu)` returns `Some` and the GPU candidate's
8578    // cost fn actually runs (instead of being skipped → priced at
8579    // zero). CPU already auto-registers its hand-tuned caps via
8580    // `global_registry`. Touches the separate `GLOBAL_REGISTRY` lock,
8581    // not this table's — no re-entrancy.
8582    register_derived_gpu_caps(table);
8583
8584    let _ = table;
8585}
8586
8587/// Add a backend's dispatch wrappers to the process-wide binding
8588/// table. Each backend exposes a `register_*_kernels(table)`
8589/// function (see [`register_cpu_kernels`]); per-backend init paths
8590/// call this to plug their wrappers into the global table.
8591///
8592/// Copy-on-write (GAP-015): clones the current table, runs `register` on
8593/// the clone, then swaps the published `Arc`. Writers are serialized by
8594/// `BINDINGS_WRITER` rather than by the `RwLock`, which is what keeps
8595/// `adopt_runtime_fused`'s check-then-bind atomic while still leaving
8596/// readers unblocked — see that static's docs for why both properties are
8597/// required. Readers in flight keep the pre-swap snapshot; they see this
8598/// registration on their next call.
8599pub fn extend_global_bindings(register: impl FnOnce(&mut KernelBindingTable)) {
8600    let cell = bindings_cell();
8601    {
8602        // Writer-side serialization. Held across clone → extend → finalize
8603        // → swap so two concurrent writers cannot lose each other's
8604        // updates, and so a check-then-bind extender observes a base no
8605        // other writer is mutating.
8606        lock_trace("want BINDINGS.WRITER (extend_global_bindings)");
8607        let _writer = BINDINGS_WRITER.lock().unwrap_or_else(|e| e.into_inner());
8608        lock_trace("got  BINDINGS.WRITER -- cloning table, extender runs OFF the RwLock");
8609
8610        let mut next = {
8611            let guard = cell.read().unwrap_or_else(|e| e.into_inner());
8612            (**guard).clone()
8613        };
8614        register(&mut next);
8615        lock_trace("  extender returned");
8616        // Re-validate after the extender adds its wrappers (same
8617        // never-panic fail-fast as the init boundary). This runs OUTSIDE
8618        // the `RwLock`, so the panic it can raise no longer poisons the
8619        // read path — and because `next` is thrown away on unwind, the
8620        // published table keeps its last good value instead of a torn one.
8621        next.finalize()
8622            .expect("KernelBindingTable: duplicate kernel registration after extend");
8623
8624        // Publish. The write guard covers a pointer swap and nothing else.
8625        {
8626            let mut guard = cell.write().unwrap_or_else(|e| e.into_inner());
8627            *guard = Arc::new(next);
8628        }
8629        lock_trace("released BINDINGS.WRITE (swap only)");
8630    }
8631    bump_topology_generation();
8632}
8633
8634/// The authored linear / quant-matmul FUSED kernel bundle, embedded into the
8635/// binary (the PRODUCTION `include_str!`). `register_cpu_linear_quant_fused_from_contract`
8636/// parses + lowers it and registers the MIGRATED subset FROM THE CONTRACT.
8637const FUSED_LINEAR_QUANT_CONTRACT: &str =
8638    include_str!("../kernel-contracts/fused/linear-quant.fkc.md");
8639
8640/// Register the linear / quant-matmul FUSED family — `FUSED_LINEAR` (4 dtypes,
8641/// key `[T, T, T, T]`) + `QMATMUL` (1 impl, key `[F32, U32, F32]`) +
8642/// `INPLACE_AFFINE` (4 dtypes, key `[T, T]`) + `FUSED_SOFTMAX_CROSS_ENTROPY`
8643/// (4 dtypes, key `[T, I64, F32]`) = **13 CPU `BackendImpl`s** — into the
8644/// [`crate::fused::FusedKernelRegistry`] by IMPORTING its `audited: true` FKC
8645/// contract (`fuel-dispatch/kernel-contracts/fused/linear-quant.fkc.md`), resolved
8646/// through the production [`crate::fkc::CpuLinkRegistry`] (chaining
8647/// [`crate::fkc::CPU_FUSED_LINEAR_QUANT_ENTRY_POINTS`]). FKC is unconditional
8648/// core infrastructure, so this is the ONE registration path for these four
8649/// fused ops — every hand-written `register_fused!(FUSED_LINEAR / QMATMUL /
8650/// INPLACE_AFFINE / FUSED_SOFTMAX_CROSS_ENTROPY, …)` call is DELETED.
8651///
8652/// The bundle's fifth section `nf4_matmul` is `registrable: false` (its
8653/// `fdx.quant.family: AFFINE_BLOCK` is consumer-ahead, §6), so it never
8654/// lowers/registers and NF4's hand-written `FusedOps::NF4_MATMUL` regs (below,
8655/// unchanged) stay authoritative. QMATMUL's contract keys its weight operand the
8656/// LOGICAL dispatch dtype `U32` (the physical GGML block byte-honesty rides the
8657/// `fdx.quant: GGML_BLOCK` block), so the fanned key is `[F32, U32, F32]` —
8658/// byte-for-byte the deleted `QM_F32` reg. FSCE's `logits` fans over
8659/// `{F32,F64,BF16,F16}` (targets I64, output always F32), matching the four
8660/// deleted `FSCE_<dt>` regs exactly.
8661///
8662/// The bundle is fused-only, so `register_into`'s required binding-table
8663/// argument is a local throwaway that provably stays empty. Behavior-preserving
8664/// vs. the deleted hand-written path: identical per-dtype kernels (bound by
8665/// pointer through the link registry), the contract's bit-stable `audited: true`
8666/// precision (same shape as the deleted `*_CPU_PRECISION` consts — no downgrade),
8667/// and the real `compute_revision` hash (hand-written stamped `UNTRACKED`). Cost
8668/// stays the Judge-bootstrapped `fused_unknown_cost` sentinel ([consumer-ahead]:
8669/// the fused cost trampoline is a follow-up slice — the same posture the primitive
8670/// FKC imports take before `fill_unset_cpu_cost`).
8671fn register_cpu_linear_quant_fused_from_contract(r: &mut crate::fused::FusedKernelRegistry) {
8672    let provider =
8673        crate::fkc::import_bundle_str(FUSED_LINEAR_QUANT_CONTRACT, &crate::fkc::CpuLinkRegistry)
8674            .expect(
8675                "authored linear-quant fused contract must import \
8676                 (embedded via include_str!, resolved through CpuLinkRegistry)",
8677            );
8678    debug_assert!(
8679        provider.primitives.is_empty(),
8680        "linear-quant bundle declares only fused ops",
8681    );
8682    let mut table = KernelBindingTable::new();
8683    provider
8684        .register_into(&mut table, r)
8685        .expect("linear-quant fused contract must register into the fused registry");
8686}
8687
8688/// The authored norm / softmax FUSED kernel bundle, embedded into the binary
8689/// (the PRODUCTION `include_str!`). `register_cpu_norm_softmax_fused_from_contract`
8690/// parses + lowers it and registers the FULL bundle FROM THE CONTRACT.
8691const FUSED_NORM_SOFTMAX_CONTRACT: &str =
8692    include_str!("../kernel-contracts/fused/norm-softmax.fkc.md");
8693
8694/// Register the norm / softmax FUSED family — all EIGHT `fused_op` sections
8695/// (`SOFTMAX_LAST_DIM` / `RMS_NORM_LAST_DIM` / `LAYER_NORM_LAST_DIM`, key `[T, T]`;
8696/// `SOFTMAX_LAST_DIM_BACKWARD` / `LAYER_NORM_LAST_DIM_BACKWARD` /
8697/// `RMS_NORM_LAST_DIM_BACKWARD` / `REDUCE_MAX_TO_BACKWARD` / `POWI_BACKWARD`, key
8698/// `[T, T, T]`), each dtype-fanned over `{F32, F64, BF16, F16}` = **32 CPU
8699/// `BackendImpl`s** — into the [`crate::fused::FusedKernelRegistry`] by IMPORTING
8700/// its `audited: true` FKC contract (`fuel-dispatch/kernel-contracts/fused/norm-softmax.fkc.md`),
8701/// resolved through the production [`crate::fkc::CpuLinkRegistry`] (chaining
8702/// [`crate::fkc::CPU_FUSED_NORM_ENTRY_POINTS`], the seam-proven 32-row table).
8703/// FKC is unconditional core infrastructure, so this is the ONE registration
8704/// path for these eight fused ops — every hand-written `register_fused!(SOFTMAX /
8705/// RMS_NORM / LAYER_NORM_LAST_DIM (+backward) / REDUCE_MAX_TO_BACKWARD /
8706/// POWI_BACKWARD, …)` call is DELETED.
8707///
8708/// Behavior-preserving vs. the deleted hand-written path: identical per-dtype
8709/// kernels (bound by pointer through the link registry), the contract's
8710/// bit-stable `audited: true` precision — the **2026-07-03 maintainer flip
8711/// (CireSnave)** that relocates the `NORM_FAMILY_CPU_PRECISION` /
8712/// `REDUCE_MAX_TO_BACKWARD_CPU_PRECISION` / `POWI_BACKWARD_CPU_PRECISION`
8713/// bit-stable claim onto the contract (same author, same guarantee — no
8714/// downgrade), and the real `compute_revision` hash (hand-written stamped
8715/// `UNTRACKED`). Cost stays the Judge-bootstrapped `fused_unknown_cost` sentinel
8716/// (the fused cost trampoline is a follow-up slice).
8717fn register_cpu_norm_softmax_fused_from_contract(r: &mut crate::fused::FusedKernelRegistry) {
8718    let provider =
8719        crate::fkc::import_bundle_str(FUSED_NORM_SOFTMAX_CONTRACT, &crate::fkc::CpuLinkRegistry)
8720            .expect(
8721                "authored norm-softmax fused contract must import \
8722                 (embedded via include_str!, resolved through CpuLinkRegistry)",
8723            );
8724    debug_assert!(
8725        provider.primitives.is_empty(),
8726        "norm-softmax bundle declares only fused ops",
8727    );
8728    let mut table = KernelBindingTable::new();
8729    provider
8730        .register_into(&mut table, r)
8731        .expect("norm-softmax fused contract must register into the fused registry");
8732}
8733
8734/// The authored conv / RoPE / SSM FUSED kernel bundle, embedded into the binary
8735/// (the PRODUCTION `include_str!`). `register_cpu_conv_rope_fused_from_contract`
8736/// parses + lowers it and registers the FULL bundle FROM THE CONTRACT.
8737const FUSED_CONV_ROPE_CONTRACT: &str = include_str!("../kernel-contracts/fused/conv-rope.fkc.md");
8738
8739/// Register the conv / RoPE / SSM FUSED family — all SIX `fused_op` sections,
8740/// each dtype-fanned over `{F32, F64, BF16, F16}` = **32 CPU `BackendImpl`s** —
8741/// into the [`crate::fused::FusedKernelRegistry`] by IMPORTING its `audited: true`
8742/// FKC contract (`fuel-dispatch/kernel-contracts/fused/conv-rope.fkc.md`), resolved
8743/// through the production [`crate::fkc::CpuLinkRegistry`] (chaining
8744/// [`crate::fkc::CPU_FUSED_CONV_ROPE_ENTRY_POINTS`], 24 rows). FKC is
8745/// unconditional core infrastructure, so this is the ONE registration path for
8746/// these six fused ops — every hand-written `register_fused!(ROPE / CONV2D /
8747/// CONV_TRANSPOSE2D / CAUSAL_CONV1D / SELECTIVE_SCAN / SSD_CHUNK_SCAN, …)` call
8748/// is DELETED.
8749///
8750/// The 24 symbol rows fan into **32 impls** (ROPE 4 + CONV2D 8 +
8751/// CONV_TRANSPOSE2D 8 + CAUSAL_CONV1D 4 + SELECTIVE_SCAN 4 + SSD_CHUNK_SCAN 4):
8752/// - CONV2D / CONV_TRANSPOSE2D mark `bias` `optional: true`, so the importer's
8753///   key-builder fans EACH per-dtype section into BOTH the no-bias key `[T, T, T]`
8754///   and the with-bias key `[T, T, T, T]` — 4 rows → 8 impls each, byte-for-byte
8755///   the deleted `CV_*_NOB` + `CV_*_BIAS` regs. **CONV_TRANSPOSE2D's contract was
8756///   WIDENED to declare the optional `bias` operand** (it previously described
8757///   only the no-bias form): production registered both tuples and the CPU
8758///   transposed-conv scatter kernel seeds the output with `bias[co]` (or `0`), so
8759///   the widening is truthful and preserves the 8-impl count the
8760///   `default_kernel_registry_step6_coverage` gate asserts.
8761/// - SELECTIVE_SCAN / SSD_CHUNK_SCAN declare a `return.bundle` multi-output
8762///   (Option C, `[y ; last_state]`), so the key-builder appends the bundle's
8763///   primary-slot dtype (`passthrough(u)` / `passthrough(x)` → T) to the 5-input
8764///   tail — each keys `[T; 6]` byte-for-byte the deleted `SS_*` / `SCS_*` regs.
8765///
8766/// Behavior-preserving vs. the deleted hand-written path: identical per-dtype
8767/// kernels (bound by pointer), the contract's bit-stable `audited: true`
8768/// precision — the **2026-07-03 maintainer flip (CireSnave)** relocating the
8769/// `ROPE_CPU_PRECISION` / `CONV2D_CPU_PRECISION` / `CONV_TRANSPOSE2D_CPU_PRECISION`
8770/// / `CAUSAL_CONV1D_CPU_PRECISION` / `SELECTIVE_SCAN_CPU_PRECISION` /
8771/// `SSD_CHUNK_SCAN_CPU_PRECISION` bit-stable claims onto the contract (same
8772/// author, same guarantee — no downgrade), and the real `compute_revision` hash
8773/// (hand-written stamped `UNTRACKED`). Cost stays the Judge-bootstrapped
8774/// `fused_unknown_cost` sentinel.
8775fn register_cpu_conv_rope_fused_from_contract(r: &mut crate::fused::FusedKernelRegistry) {
8776    let provider =
8777        crate::fkc::import_bundle_str(FUSED_CONV_ROPE_CONTRACT, &crate::fkc::CpuLinkRegistry)
8778            .expect(
8779                "authored conv-rope fused contract must import \
8780                 (embedded via include_str!, resolved through CpuLinkRegistry)",
8781            );
8782    debug_assert!(
8783        provider.primitives.is_empty(),
8784        "conv-rope bundle declares only fused ops",
8785    );
8786    let mut table = KernelBindingTable::new();
8787    provider
8788        .register_into(&mut table, r)
8789        .expect("conv-rope fused contract must register into the fused registry");
8790}
8791
8792/// Phase 7.6 step 6 — register the always-built fused-op kernels into
8793/// the [`crate::fused::FusedKernelRegistry`]. Called by
8794/// [`crate::fused::default_kernel_registry`]; kept here so the
8795/// crate-private CPU dispatch wrappers stay co-located with their
8796/// registration.
8797///
8798/// Today's coverage. Three `audited: true` FKC contracts are IMPORTED at the top
8799/// (contract-sourced, replacing the deleted hand-written `register_fused!`
8800/// entries); the attention family + deferred NF4 stay hand-written:
8801/// - **linear-quant** (`register_cpu_linear_quant_fused_from_contract`) — 13
8802///   impls: `FUSED_LINEAR` (4) + `QMATMUL` (1) + `INPLACE_AFFINE` (4) +
8803///   `FUSED_SOFTMAX_CROSS_ENTROPY` (4). The 5th section `NF4_MATMUL` is
8804///   `registrable: false` (AFFINE_BLOCK consumer-ahead) → stays hand-written.
8805/// - **norm-softmax** (`register_cpu_norm_softmax_fused_from_contract`) — 32
8806///   impls: `SOFTMAX_LAST_DIM` / `RMS_NORM_LAST_DIM` / `LAYER_NORM_LAST_DIM`
8807///   (+ their `_BACKWARD`) + `REDUCE_MAX_TO_BACKWARD` + `POWI_BACKWARD`
8808///   (8 sections × 4 dtypes).
8809/// - **conv-rope** (`register_cpu_conv_rope_fused_from_contract`) — 32 impls:
8810///   `ROPE` (4) + `CONV2D` (8, no-bias|with-bias) + `CONV_TRANSPOSE2D` (8,
8811///   no-bias|with-bias — bias operand WIDENED into the contract) +
8812///   `CAUSAL_CONV1D` (4) + `SELECTIVE_SCAN` (4, bundle) + `SSD_CHUNK_SCAN`
8813///   (4, bundle).
8814/// - hand-written below: `FLASH_ATTN` (8) + `FLASH_ATTN_BACKWARD_{Q,K,V}` (24) +
8815///   `PAGED_ATTN` (8) + `NF4_MATMUL` (3).
8816///
8817/// Total: 120 CPU BackendImpls registered across **all 24** registered
8818/// fused ops. The architecture v1.0 §05 bit-stable coverage
8819/// commitment is now compiler-enforced for the full fused-op set
8820/// (no `KNOWN_GAPS` allowlist in the step-7 lint).
8821///
8822/// Backend crates (fuel-cuda-backend, fuel-vulkan-backend) extend by
8823/// composing against the registry from their own startup paths or via
8824/// the step-9 binding-table refactor.
8825pub fn register_default_fused_kernels(r: &mut crate::fused::FusedKernelRegistry) {
8826    // NOTE: only the attention family (FLASH_ATTN / FLASH_ATTN_BACKWARD_{Q,K,V} /
8827    // PAGED_ATTN) + the deferred NF4_MATMUL keep hand-written cost fns + precision
8828    // consts here. The norm-softmax, linear-quant, and conv-rope bundles are
8829    // IMPORTED from their `audited: true` FKC contracts (below), so their cost fns
8830    // + `*_CPU_PRECISION` consts are no longer imported into this fn.
8831    use crate::fused::{
8832        ATTN_BACKWARD_CPU_PRECISION, ATTN_CPU_PRECISION, NF4_MATMUL_CPU_PRECISION,
8833        cost_attn_backward_cpu, cost_attn_cpu, cost_nf4_matmul_cpu,
8834    };
8835    use crate::register_fused;
8836    use fuel_graph::registry::FusedOps;
8837
8838    // Dtype tuples mirror the binding-table shape.
8839    // (FusedLinear's `(lhs, rhs, bias, out)` tuples are gone — FUSED_LINEAR is
8840    // now imported from the linear-quant FKC contract. Conv2D/ConvTranspose2D
8841    // `CV_*`, Softmax/RmsNorm/LayerNorm `UNARY_*`, `ROPE_*`, the norm/reduce/powi
8842    // backward `BW_*`, and the SSM `CC1D_*`/`SS_*`/`SCS_*` tuples are ALSO gone —
8843    // CONV2D/CONV_TRANSPOSE2D/ROPE + the norm-softmax bundle + CAUSAL_CONV1D/
8844    // SELECTIVE_SCAN/SSD_CHUNK_SCAN are now imported from the norm-softmax and
8845    // conv-rope FKC contracts, below.)
8846
8847    // FlashAttn: (q, k, v, [alibi], out) — no-alibi 4-tuple,
8848    // with-alibi 5-tuple. Same wrapper handles both.
8849    const FA_F32_NOA: &[DType] = &[DType::F32, DType::F32, DType::F32, DType::F32];
8850    const FA_F32_A: &[DType] = &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32];
8851    const FA_F64_NOA: &[DType] = &[DType::F64, DType::F64, DType::F64, DType::F64];
8852    const FA_F64_A: &[DType] = &[DType::F64, DType::F64, DType::F64, DType::F64, DType::F64];
8853    const FA_BF16_NOA: &[DType] = &[DType::BF16, DType::BF16, DType::BF16, DType::BF16];
8854    const FA_BF16_A: &[DType] = &[
8855        DType::BF16,
8856        DType::BF16,
8857        DType::BF16,
8858        DType::BF16,
8859        DType::BF16,
8860    ];
8861    const FA_F16_NOA: &[DType] = &[DType::F16, DType::F16, DType::F16, DType::F16];
8862    const FA_F16_A: &[DType] = &[DType::F16, DType::F16, DType::F16, DType::F16, DType::F16];
8863
8864    // FlashAttnBackward{Q,K,V}: (q, k, v, do, [alibi], out) —
8865    // no-alibi 5-tuple, with-alibi 6-tuple. Mirrors the binding-table
8866    // `fa_bw_no_alibi` / `fa_bw_with_alibi` key shapes.
8867    const FAB_F32_NOA: &[DType] = &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32];
8868    const FAB_F32_A: &[DType] = &[
8869        DType::F32,
8870        DType::F32,
8871        DType::F32,
8872        DType::F32,
8873        DType::F32,
8874        DType::F32,
8875    ];
8876    const FAB_F64_NOA: &[DType] = &[DType::F64, DType::F64, DType::F64, DType::F64, DType::F64];
8877    const FAB_F64_A: &[DType] = &[
8878        DType::F64,
8879        DType::F64,
8880        DType::F64,
8881        DType::F64,
8882        DType::F64,
8883        DType::F64,
8884    ];
8885    const FAB_BF16_NOA: &[DType] = &[
8886        DType::BF16,
8887        DType::BF16,
8888        DType::BF16,
8889        DType::BF16,
8890        DType::BF16,
8891    ];
8892    const FAB_BF16_A: &[DType] = &[
8893        DType::BF16,
8894        DType::BF16,
8895        DType::BF16,
8896        DType::BF16,
8897        DType::BF16,
8898        DType::BF16,
8899    ];
8900    const FAB_F16_NOA: &[DType] = &[DType::F16, DType::F16, DType::F16, DType::F16, DType::F16];
8901    const FAB_F16_A: &[DType] = &[
8902        DType::F16,
8903        DType::F16,
8904        DType::F16,
8905        DType::F16,
8906        DType::F16,
8907        DType::F16,
8908    ];
8909
8910    // PagedAttn: (q, kc, vc, bt:U32, cl:U32, [alibi], out).
8911    const PA_F32_NOA: &[DType] = &[
8912        DType::F32,
8913        DType::F32,
8914        DType::F32,
8915        DType::U32,
8916        DType::U32,
8917        DType::F32,
8918    ];
8919    const PA_F32_A: &[DType] = &[
8920        DType::F32,
8921        DType::F32,
8922        DType::F32,
8923        DType::U32,
8924        DType::U32,
8925        DType::F32,
8926        DType::F32,
8927    ];
8928    const PA_F64_NOA: &[DType] = &[
8929        DType::F64,
8930        DType::F64,
8931        DType::F64,
8932        DType::U32,
8933        DType::U32,
8934        DType::F64,
8935    ];
8936    const PA_F64_A: &[DType] = &[
8937        DType::F64,
8938        DType::F64,
8939        DType::F64,
8940        DType::U32,
8941        DType::U32,
8942        DType::F64,
8943        DType::F64,
8944    ];
8945    const PA_BF16_NOA: &[DType] = &[
8946        DType::BF16,
8947        DType::BF16,
8948        DType::BF16,
8949        DType::U32,
8950        DType::U32,
8951        DType::BF16,
8952    ];
8953    const PA_BF16_A: &[DType] = &[
8954        DType::BF16,
8955        DType::BF16,
8956        DType::BF16,
8957        DType::U32,
8958        DType::U32,
8959        DType::BF16,
8960        DType::BF16,
8961    ];
8962    const PA_F16_NOA: &[DType] = &[
8963        DType::F16,
8964        DType::F16,
8965        DType::F16,
8966        DType::U32,
8967        DType::U32,
8968        DType::F16,
8969    ];
8970    const PA_F16_A: &[DType] = &[
8971        DType::F16,
8972        DType::F16,
8973        DType::F16,
8974        DType::U32,
8975        DType::U32,
8976        DType::F16,
8977        DType::F16,
8978    ];
8979
8980    // (QMatMul's `(a:F32, w_q:U32, out:F32)` tuple is gone — QMATMUL is now
8981    // imported from the linear-quant FKC contract. The `[T, T, T]` backward-helper
8982    // `BW_*` tuples are gone too — SOFTMAX/LAYER/RMS_NORM_LAST_DIM_BACKWARD +
8983    // REDUCE_MAX_TO_BACKWARD + POWI_BACKWARD are now imported from the norm-softmax
8984    // FKC contract.)
8985
8986    let cpu = BackendId::Cpu;
8987
8988    // FUSED_LINEAR (4) + QMATMUL (1) + INPLACE_AFFINE (4) +
8989    // FUSED_SOFTMAX_CROSS_ENTROPY (4) = 13 CPU impls are IMPORTED from the
8990    // `audited: true` linear-quant FKC contract (resolved through the production
8991    // CpuLinkRegistry). This REPLACES the deleted hand-written register_fused!
8992    // entries for those four fused ops. The bundle's fifth section, nf4_matmul,
8993    // is `registrable: false` (AFFINE_BLOCK consumer-ahead, §6), so NF4's
8994    // hand-written FusedOps::NF4_MATMUL regs below stay authoritative.
8995    register_cpu_linear_quant_fused_from_contract(r);
8996
8997    // SOFTMAX / RMS_NORM / LAYER_NORM_LAST_DIM (+ backward) +
8998    // REDUCE_MAX_TO_BACKWARD + POWI_BACKWARD = 32 CPU impls are IMPORTED from the
8999    // `audited: true` norm-softmax FKC contract (8 sections × 4 dtypes), resolved
9000    // through the production CpuLinkRegistry (CPU_FUSED_NORM_ENTRY_POINTS). This
9001    // REPLACES the deleted hand-written register_fused! entries for those eight
9002    // fused ops.
9003    register_cpu_norm_softmax_fused_from_contract(r);
9004
9005    // ROPE + CONV2D + CONV_TRANSPOSE2D + CAUSAL_CONV1D + SELECTIVE_SCAN +
9006    // SSD_CHUNK_SCAN = 32 CPU impls are IMPORTED from the `audited: true`
9007    // conv-rope FKC contract (6 sections; CONV2D/CONV_TRANSPOSE2D fan the optional
9008    // bias into no-bias + with-bias keys → 8 impls each; SELECTIVE_SCAN/
9009    // SSD_CHUNK_SCAN key [T;6] via the return.bundle primary slot), resolved
9010    // through the production CpuLinkRegistry (CPU_FUSED_CONV_ROPE_ENTRY_POINTS).
9011    // This REPLACES the deleted hand-written register_fused! entries for those six
9012    // fused ops.
9013    register_cpu_conv_rope_fused_from_contract(r);
9014
9015    // NOTE (CapturedRun 4b-resume, 2026-07-13): a CUDA `FusedOps::ROPE`
9016    // candidate via baracuda's `rope_apply_<dt>_run` was registered here
9017    // (commit 3be28ab1) and then REVERTED — baracuda's `rope_apply` uses the
9018    // INTERLEAVED pairing `(2k, 2k+1)` (GPT-J) while Fuel's `FusedOps::ROPE`
9019    // (`Tensor::rope_with_tables`) is ROTATE-HALF `(j, j+head_dim/2)`
9020    // (Llama/HF). They compute DIFFERENT functions, so the interleaved kernel
9021    // must NOT be a candidate for the rotate-half op (a GPU numerical test
9022    // caught the divergence: `fuel_cuda_backend::baracuda::attention::
9023    // fused_rope_tests`). CUDA rope therefore runs via the correct rotate-half
9024    // primitive decompose until baracuda ships a rotate-half table-driven
9025    // `rope_apply` variant; the staged (unwired) driver + scratch cache live
9026    // in `fuel-cuda-backend` ready for that kernel.
9027
9028    // FlashAttn × 4 dtypes × {no-alibi, with-alibi}.
9029    register_fused!(
9030        r,
9031        FusedOps::FLASH_ATTN,
9032        cpu,
9033        FA_F32_NOA,
9034        flash_attn_f32_cpu_wrapper,
9035        cost = cost_attn_cpu,
9036        precision = ATTN_CPU_PRECISION
9037    );
9038    register_fused!(
9039        r,
9040        FusedOps::FLASH_ATTN,
9041        cpu,
9042        FA_F32_A,
9043        flash_attn_f32_cpu_wrapper,
9044        cost = cost_attn_cpu,
9045        precision = ATTN_CPU_PRECISION
9046    );
9047    register_fused!(
9048        r,
9049        FusedOps::FLASH_ATTN,
9050        cpu,
9051        FA_F64_NOA,
9052        flash_attn_f64_cpu_wrapper,
9053        cost = cost_attn_cpu,
9054        precision = ATTN_CPU_PRECISION
9055    );
9056    register_fused!(
9057        r,
9058        FusedOps::FLASH_ATTN,
9059        cpu,
9060        FA_F64_A,
9061        flash_attn_f64_cpu_wrapper,
9062        cost = cost_attn_cpu,
9063        precision = ATTN_CPU_PRECISION
9064    );
9065    register_fused!(
9066        r,
9067        FusedOps::FLASH_ATTN,
9068        cpu,
9069        FA_BF16_NOA,
9070        flash_attn_bf16_cpu_wrapper,
9071        cost = cost_attn_cpu,
9072        precision = ATTN_CPU_PRECISION
9073    );
9074    register_fused!(
9075        r,
9076        FusedOps::FLASH_ATTN,
9077        cpu,
9078        FA_BF16_A,
9079        flash_attn_bf16_cpu_wrapper,
9080        cost = cost_attn_cpu,
9081        precision = ATTN_CPU_PRECISION
9082    );
9083    register_fused!(
9084        r,
9085        FusedOps::FLASH_ATTN,
9086        cpu,
9087        FA_F16_NOA,
9088        flash_attn_f16_cpu_wrapper,
9089        cost = cost_attn_cpu,
9090        precision = ATTN_CPU_PRECISION
9091    );
9092    register_fused!(
9093        r,
9094        FusedOps::FLASH_ATTN,
9095        cpu,
9096        FA_F16_A,
9097        flash_attn_f16_cpu_wrapper,
9098        cost = cost_attn_cpu,
9099        precision = ATTN_CPU_PRECISION
9100    );
9101
9102    // FlashAttnBackward{Q,K,V} × 4 dtypes × {no-alibi, with-alibi}.
9103    // Reuses the binding-table dispatch wrappers — the CPU kernel
9104    // computes all three gradients each call and the wrapper persists
9105    // the one matching the OpKind; the cost model accounts for that.
9106    register_fused!(
9107        r,
9108        FusedOps::FLASH_ATTN_BACKWARD_Q,
9109        cpu,
9110        FAB_F32_NOA,
9111        flash_attn_backward_q_f32_cpu_wrapper,
9112        cost = cost_attn_backward_cpu,
9113        precision = ATTN_BACKWARD_CPU_PRECISION
9114    );
9115    register_fused!(
9116        r,
9117        FusedOps::FLASH_ATTN_BACKWARD_Q,
9118        cpu,
9119        FAB_F32_A,
9120        flash_attn_backward_q_f32_cpu_wrapper,
9121        cost = cost_attn_backward_cpu,
9122        precision = ATTN_BACKWARD_CPU_PRECISION
9123    );
9124    register_fused!(
9125        r,
9126        FusedOps::FLASH_ATTN_BACKWARD_Q,
9127        cpu,
9128        FAB_F64_NOA,
9129        flash_attn_backward_q_f64_cpu_wrapper,
9130        cost = cost_attn_backward_cpu,
9131        precision = ATTN_BACKWARD_CPU_PRECISION
9132    );
9133    register_fused!(
9134        r,
9135        FusedOps::FLASH_ATTN_BACKWARD_Q,
9136        cpu,
9137        FAB_F64_A,
9138        flash_attn_backward_q_f64_cpu_wrapper,
9139        cost = cost_attn_backward_cpu,
9140        precision = ATTN_BACKWARD_CPU_PRECISION
9141    );
9142    register_fused!(
9143        r,
9144        FusedOps::FLASH_ATTN_BACKWARD_Q,
9145        cpu,
9146        FAB_BF16_NOA,
9147        flash_attn_backward_q_bf16_cpu_wrapper,
9148        cost = cost_attn_backward_cpu,
9149        precision = ATTN_BACKWARD_CPU_PRECISION
9150    );
9151    register_fused!(
9152        r,
9153        FusedOps::FLASH_ATTN_BACKWARD_Q,
9154        cpu,
9155        FAB_BF16_A,
9156        flash_attn_backward_q_bf16_cpu_wrapper,
9157        cost = cost_attn_backward_cpu,
9158        precision = ATTN_BACKWARD_CPU_PRECISION
9159    );
9160    register_fused!(
9161        r,
9162        FusedOps::FLASH_ATTN_BACKWARD_Q,
9163        cpu,
9164        FAB_F16_NOA,
9165        flash_attn_backward_q_f16_cpu_wrapper,
9166        cost = cost_attn_backward_cpu,
9167        precision = ATTN_BACKWARD_CPU_PRECISION
9168    );
9169    register_fused!(
9170        r,
9171        FusedOps::FLASH_ATTN_BACKWARD_Q,
9172        cpu,
9173        FAB_F16_A,
9174        flash_attn_backward_q_f16_cpu_wrapper,
9175        cost = cost_attn_backward_cpu,
9176        precision = ATTN_BACKWARD_CPU_PRECISION
9177    );
9178
9179    register_fused!(
9180        r,
9181        FusedOps::FLASH_ATTN_BACKWARD_K,
9182        cpu,
9183        FAB_F32_NOA,
9184        flash_attn_backward_k_f32_cpu_wrapper,
9185        cost = cost_attn_backward_cpu,
9186        precision = ATTN_BACKWARD_CPU_PRECISION
9187    );
9188    register_fused!(
9189        r,
9190        FusedOps::FLASH_ATTN_BACKWARD_K,
9191        cpu,
9192        FAB_F32_A,
9193        flash_attn_backward_k_f32_cpu_wrapper,
9194        cost = cost_attn_backward_cpu,
9195        precision = ATTN_BACKWARD_CPU_PRECISION
9196    );
9197    register_fused!(
9198        r,
9199        FusedOps::FLASH_ATTN_BACKWARD_K,
9200        cpu,
9201        FAB_F64_NOA,
9202        flash_attn_backward_k_f64_cpu_wrapper,
9203        cost = cost_attn_backward_cpu,
9204        precision = ATTN_BACKWARD_CPU_PRECISION
9205    );
9206    register_fused!(
9207        r,
9208        FusedOps::FLASH_ATTN_BACKWARD_K,
9209        cpu,
9210        FAB_F64_A,
9211        flash_attn_backward_k_f64_cpu_wrapper,
9212        cost = cost_attn_backward_cpu,
9213        precision = ATTN_BACKWARD_CPU_PRECISION
9214    );
9215    register_fused!(
9216        r,
9217        FusedOps::FLASH_ATTN_BACKWARD_K,
9218        cpu,
9219        FAB_BF16_NOA,
9220        flash_attn_backward_k_bf16_cpu_wrapper,
9221        cost = cost_attn_backward_cpu,
9222        precision = ATTN_BACKWARD_CPU_PRECISION
9223    );
9224    register_fused!(
9225        r,
9226        FusedOps::FLASH_ATTN_BACKWARD_K,
9227        cpu,
9228        FAB_BF16_A,
9229        flash_attn_backward_k_bf16_cpu_wrapper,
9230        cost = cost_attn_backward_cpu,
9231        precision = ATTN_BACKWARD_CPU_PRECISION
9232    );
9233    register_fused!(
9234        r,
9235        FusedOps::FLASH_ATTN_BACKWARD_K,
9236        cpu,
9237        FAB_F16_NOA,
9238        flash_attn_backward_k_f16_cpu_wrapper,
9239        cost = cost_attn_backward_cpu,
9240        precision = ATTN_BACKWARD_CPU_PRECISION
9241    );
9242    register_fused!(
9243        r,
9244        FusedOps::FLASH_ATTN_BACKWARD_K,
9245        cpu,
9246        FAB_F16_A,
9247        flash_attn_backward_k_f16_cpu_wrapper,
9248        cost = cost_attn_backward_cpu,
9249        precision = ATTN_BACKWARD_CPU_PRECISION
9250    );
9251
9252    register_fused!(
9253        r,
9254        FusedOps::FLASH_ATTN_BACKWARD_V,
9255        cpu,
9256        FAB_F32_NOA,
9257        flash_attn_backward_v_f32_cpu_wrapper,
9258        cost = cost_attn_backward_cpu,
9259        precision = ATTN_BACKWARD_CPU_PRECISION
9260    );
9261    register_fused!(
9262        r,
9263        FusedOps::FLASH_ATTN_BACKWARD_V,
9264        cpu,
9265        FAB_F32_A,
9266        flash_attn_backward_v_f32_cpu_wrapper,
9267        cost = cost_attn_backward_cpu,
9268        precision = ATTN_BACKWARD_CPU_PRECISION
9269    );
9270    register_fused!(
9271        r,
9272        FusedOps::FLASH_ATTN_BACKWARD_V,
9273        cpu,
9274        FAB_F64_NOA,
9275        flash_attn_backward_v_f64_cpu_wrapper,
9276        cost = cost_attn_backward_cpu,
9277        precision = ATTN_BACKWARD_CPU_PRECISION
9278    );
9279    register_fused!(
9280        r,
9281        FusedOps::FLASH_ATTN_BACKWARD_V,
9282        cpu,
9283        FAB_F64_A,
9284        flash_attn_backward_v_f64_cpu_wrapper,
9285        cost = cost_attn_backward_cpu,
9286        precision = ATTN_BACKWARD_CPU_PRECISION
9287    );
9288    register_fused!(
9289        r,
9290        FusedOps::FLASH_ATTN_BACKWARD_V,
9291        cpu,
9292        FAB_BF16_NOA,
9293        flash_attn_backward_v_bf16_cpu_wrapper,
9294        cost = cost_attn_backward_cpu,
9295        precision = ATTN_BACKWARD_CPU_PRECISION
9296    );
9297    register_fused!(
9298        r,
9299        FusedOps::FLASH_ATTN_BACKWARD_V,
9300        cpu,
9301        FAB_BF16_A,
9302        flash_attn_backward_v_bf16_cpu_wrapper,
9303        cost = cost_attn_backward_cpu,
9304        precision = ATTN_BACKWARD_CPU_PRECISION
9305    );
9306    register_fused!(
9307        r,
9308        FusedOps::FLASH_ATTN_BACKWARD_V,
9309        cpu,
9310        FAB_F16_NOA,
9311        flash_attn_backward_v_f16_cpu_wrapper,
9312        cost = cost_attn_backward_cpu,
9313        precision = ATTN_BACKWARD_CPU_PRECISION
9314    );
9315    register_fused!(
9316        r,
9317        FusedOps::FLASH_ATTN_BACKWARD_V,
9318        cpu,
9319        FAB_F16_A,
9320        flash_attn_backward_v_f16_cpu_wrapper,
9321        cost = cost_attn_backward_cpu,
9322        precision = ATTN_BACKWARD_CPU_PRECISION
9323    );
9324
9325    // PagedAttn × 4 dtypes × {no-alibi, with-alibi}.
9326    register_fused!(
9327        r,
9328        FusedOps::PAGED_ATTN,
9329        cpu,
9330        PA_F32_NOA,
9331        paged_attn_f32_cpu_wrapper,
9332        cost = cost_attn_cpu,
9333        precision = ATTN_CPU_PRECISION
9334    );
9335    register_fused!(
9336        r,
9337        FusedOps::PAGED_ATTN,
9338        cpu,
9339        PA_F32_A,
9340        paged_attn_f32_cpu_wrapper,
9341        cost = cost_attn_cpu,
9342        precision = ATTN_CPU_PRECISION
9343    );
9344    register_fused!(
9345        r,
9346        FusedOps::PAGED_ATTN,
9347        cpu,
9348        PA_F64_NOA,
9349        paged_attn_f64_cpu_wrapper,
9350        cost = cost_attn_cpu,
9351        precision = ATTN_CPU_PRECISION
9352    );
9353    register_fused!(
9354        r,
9355        FusedOps::PAGED_ATTN,
9356        cpu,
9357        PA_F64_A,
9358        paged_attn_f64_cpu_wrapper,
9359        cost = cost_attn_cpu,
9360        precision = ATTN_CPU_PRECISION
9361    );
9362    register_fused!(
9363        r,
9364        FusedOps::PAGED_ATTN,
9365        cpu,
9366        PA_BF16_NOA,
9367        paged_attn_bf16_cpu_wrapper,
9368        cost = cost_attn_cpu,
9369        precision = ATTN_CPU_PRECISION
9370    );
9371    register_fused!(
9372        r,
9373        FusedOps::PAGED_ATTN,
9374        cpu,
9375        PA_BF16_A,
9376        paged_attn_bf16_cpu_wrapper,
9377        cost = cost_attn_cpu,
9378        precision = ATTN_CPU_PRECISION
9379    );
9380    register_fused!(
9381        r,
9382        FusedOps::PAGED_ATTN,
9383        cpu,
9384        PA_F16_NOA,
9385        paged_attn_f16_cpu_wrapper,
9386        cost = cost_attn_cpu,
9387        precision = ATTN_CPU_PRECISION
9388    );
9389    register_fused!(
9390        r,
9391        FusedOps::PAGED_ATTN,
9392        cpu,
9393        PA_F16_A,
9394        paged_attn_f16_cpu_wrapper,
9395        cost = cost_attn_cpu,
9396        precision = ATTN_CPU_PRECISION
9397    );
9398
9399    // (QMATMUL × F32 activations × U32 weights — 1 impl — is now IMPORTED from
9400    // the linear-quant FKC contract, above. The `[T, T, T]` backward helpers
9401    // SOFTMAX/LAYER/RMS_NORM_LAST_DIM_BACKWARD + REDUCE_MAX_TO_BACKWARD +
9402    // POWI_BACKWARD are IMPORTED from the norm-softmax FKC contract, and
9403    // CAUSAL_CONV1D + SELECTIVE_SCAN + SSD_CHUNK_SCAN (with INPLACE_AFFINE +
9404    // FUSED_SOFTMAX_CROSS_ENTROPY) are IMPORTED from the conv-rope / linear-quant
9405    // FKC contracts — all above.)
9406
9407    // NF4_MATMUL — four-tuple (activations T, w_packed U8, absmax
9408    // F32, out T), 3 dtype variants (T ∈ {F32, F16, BF16}).
9409    const NF4_F32: &[DType] = &[DType::F32, DType::U8, DType::F32, DType::F32];
9410    const NF4_F16: &[DType] = &[DType::F16, DType::U8, DType::F32, DType::F16];
9411    const NF4_BF16: &[DType] = &[DType::BF16, DType::U8, DType::F32, DType::BF16];
9412    register_fused!(
9413        r,
9414        FusedOps::NF4_MATMUL,
9415        cpu,
9416        NF4_F32,
9417        nf4_matmul_f32_cpu_wrapper,
9418        cost = cost_nf4_matmul_cpu,
9419        precision = NF4_MATMUL_CPU_PRECISION
9420    );
9421    register_fused!(
9422        r,
9423        FusedOps::NF4_MATMUL,
9424        cpu,
9425        NF4_F16,
9426        nf4_matmul_f16_cpu_wrapper,
9427        cost = cost_nf4_matmul_cpu,
9428        precision = NF4_MATMUL_CPU_PRECISION
9429    );
9430    register_fused!(
9431        r,
9432        FusedOps::NF4_MATMUL,
9433        cpu,
9434        NF4_BF16,
9435        nf4_matmul_bf16_cpu_wrapper,
9436        cost = cost_nf4_matmul_cpu,
9437        precision = NF4_MATMUL_CPU_PRECISION
9438    );
9439}
9440
9441#[cfg(test)]
9442mod tests {
9443    use super::*;
9444
9445    /// BORN-RED → GREEN: the `audited: true` linear-quant FUSED bundle is
9446    /// PRODUCTION-migrated into the `FusedKernelRegistry` FROM its FKC contract.
9447    ///
9448    /// `register_default_fused_kernels` now imports
9449    /// `fuel-dispatch/kernel-contracts/fused/linear-quant.fkc.md` through the production
9450    /// `CpuLinkRegistry` (chaining `CPU_FUSED_LINEAR_QUANT_ENTRY_POINTS`) INSTEAD
9451    /// of the hand-written `register_fused!(FUSED_LINEAR / QMATMUL / INPLACE_AFFINE
9452    /// / FUSED_SOFTMAX_CROSS_ENTROPY, …)` entries (deleted). Each migrated
9453    /// `(FusedOpId, Cpu, dtypes)` resolves to the EXACT per-dtype production
9454    /// wrapper (pointer identity) AND carries the contract's REAL revision hash.
9455    ///
9456    /// **Discriminator = `revision != UNTRACKED`.** Both the deleted hand-written
9457    /// regs and the imported impls bind the SAME wrapper fn-pointer, so pointer
9458    /// identity holds in BOTH states — it is not the red discriminator. The
9459    /// hand-written `register_fused!` path stamps `KernelRevisionHash::UNTRACKED`
9460    /// (the macro default); only the FKC import path stamps the contract's real
9461    /// `compute_revision` hash. RED (before the import wired + hand-written still
9462    /// present): `lookup_by_dtypes` returns the first-registered (hand-written)
9463    /// impl → `revision == UNTRACKED` → `assert_ne!` fails. GREEN (hand-written
9464    /// deleted, import wired): the imported impl is the sole source → real
9465    /// revision → passes.
9466    ///
9467    /// Guards: the unmigrated `FLASH_ATTN` still resolves its hand-written impl
9468    /// (UNTRACKED, unchanged); the DEFERRED `NF4_MATMUL` (contract section
9469    /// `registrable: false`, `AFFINE_BLOCK` consumer-ahead) also stays
9470    /// hand-written (UNTRACKED) — proving the migration is scoped to exactly the
9471    /// four registrable sections.
9472    #[test]
9473    fn linear_quant_fused_family_migrated_to_fkc_contract() {
9474        use crate::fused::{FusedKernelRegistry, KernelRevisionHash};
9475        use fuel_graph::registry::FusedOps;
9476
9477        let mut r = FusedKernelRegistry::new();
9478        register_default_fused_kernels(&mut r);
9479
9480        // --- FUSED_LINEAR: 4 dtypes, key [T, T, T, T] ---
9481        for (dt, expected) in [
9482            (
9483                DType::F32,
9484                fused_linear_f32_cpu_wrapper as *const () as usize,
9485            ),
9486            (
9487                DType::F64,
9488                fused_linear_f64_cpu_wrapper as *const () as usize,
9489            ),
9490            (
9491                DType::BF16,
9492                fused_linear_bf16_cpu_wrapper as *const () as usize,
9493            ),
9494            (
9495                DType::F16,
9496                fused_linear_f16_cpu_wrapper as *const () as usize,
9497            ),
9498        ] {
9499            let got = r
9500                .lookup_by_dtypes(FusedOps::FUSED_LINEAR, BackendId::Cpu, &[dt, dt, dt, dt])
9501                .unwrap_or_else(|| panic!("FUSED_LINEAR {dt:?} migrated impl present"));
9502            assert_eq!(
9503                got.kernel as usize, expected,
9504                "FUSED_LINEAR {dt:?} binds its exact per-dtype production wrapper",
9505            );
9506            assert_ne!(
9507                got.revision,
9508                KernelRevisionHash::UNTRACKED,
9509                "FKC-imported FUSED_LINEAR {dt:?} carries the contract's real revision \
9510                 (hand-written register_fused! stamps UNTRACKED)",
9511            );
9512        }
9513
9514        // --- QMATMUL: 1 impl, key [F32, U32, F32] (logical dispatch dtype U32) ---
9515        let qm = r
9516            .lookup_by_dtypes(
9517                FusedOps::QMATMUL,
9518                BackendId::Cpu,
9519                &[DType::F32, DType::U32, DType::F32],
9520            )
9521            .expect("QMATMUL migrated impl present at [F32, U32, F32]");
9522        assert_eq!(
9523            qm.kernel as usize,
9524            qmatmul_f32_cpu_wrapper as *const () as usize
9525        );
9526        assert_ne!(qm.revision, KernelRevisionHash::UNTRACKED);
9527
9528        // --- INPLACE_AFFINE: 4 dtypes, key [T, T] ---
9529        for (dt, expected) in [
9530            (
9531                DType::F32,
9532                inplace_affine_f32_cpu_wrapper as *const () as usize,
9533            ),
9534            (
9535                DType::F64,
9536                inplace_affine_f64_cpu_wrapper as *const () as usize,
9537            ),
9538            (
9539                DType::BF16,
9540                inplace_affine_bf16_cpu_wrapper as *const () as usize,
9541            ),
9542            (
9543                DType::F16,
9544                inplace_affine_f16_cpu_wrapper as *const () as usize,
9545            ),
9546        ] {
9547            let got = r
9548                .lookup_by_dtypes(FusedOps::INPLACE_AFFINE, BackendId::Cpu, &[dt, dt])
9549                .unwrap_or_else(|| panic!("INPLACE_AFFINE {dt:?} migrated impl present"));
9550            assert_eq!(got.kernel as usize, expected);
9551            assert_ne!(got.revision, KernelRevisionHash::UNTRACKED);
9552        }
9553
9554        // --- FUSED_SOFTMAX_CROSS_ENTROPY: 4 dtypes, key [T, I64, F32] ---
9555        for (dt, expected) in [
9556            (
9557                DType::F32,
9558                fused_softmax_cross_entropy_f32_cpu_wrapper as *const () as usize,
9559            ),
9560            (
9561                DType::F64,
9562                fused_softmax_cross_entropy_f64_cpu_wrapper as *const () as usize,
9563            ),
9564            (
9565                DType::BF16,
9566                fused_softmax_cross_entropy_bf16_cpu_wrapper as *const () as usize,
9567            ),
9568            (
9569                DType::F16,
9570                fused_softmax_cross_entropy_f16_cpu_wrapper as *const () as usize,
9571            ),
9572        ] {
9573            let got = r
9574                .lookup_by_dtypes(
9575                    FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
9576                    BackendId::Cpu,
9577                    &[dt, DType::I64, DType::F32],
9578                )
9579                .unwrap_or_else(|| panic!("FSCE {dt:?} migrated impl present"));
9580            assert_eq!(got.kernel as usize, expected);
9581            assert_ne!(got.revision, KernelRevisionHash::UNTRACKED);
9582        }
9583
9584        // --- GUARD: unmigrated FLASH_ATTN still resolves its hand-written impl ---
9585        let fa = r
9586            .lookup_by_dtypes(
9587                FusedOps::FLASH_ATTN,
9588                BackendId::Cpu,
9589                &[DType::F32, DType::F32, DType::F32, DType::F32],
9590            )
9591            .expect("FLASH_ATTN hand-written impl present");
9592        assert_eq!(
9593            fa.kernel as usize,
9594            flash_attn_f32_cpu_wrapper as *const () as usize
9595        );
9596        assert_eq!(
9597            fa.revision,
9598            KernelRevisionHash::UNTRACKED,
9599            "unmigrated FLASH_ATTN keeps its hand-written UNTRACKED revision",
9600        );
9601
9602        // --- GUARD: DEFERRED NF4_MATMUL stays hand-written (registrable: false) ---
9603        let nf4 = r
9604            .lookup_by_dtypes(
9605                FusedOps::NF4_MATMUL,
9606                BackendId::Cpu,
9607                &[DType::F32, DType::U8, DType::F32, DType::F32],
9608            )
9609            .expect("NF4_MATMUL hand-written impl present (AFFINE_BLOCK deferred)");
9610        assert_eq!(
9611            nf4.kernel as usize,
9612            nf4_matmul_f32_cpu_wrapper as *const () as usize
9613        );
9614        assert_eq!(
9615            nf4.revision,
9616            KernelRevisionHash::UNTRACKED,
9617            "deferred NF4_MATMUL keeps its hand-written UNTRACKED revision",
9618        );
9619    }
9620
9621    /// BORN-RED → GREEN: the `audited: true` norm/softmax FUSED bundle is
9622    /// PRODUCTION-migrated into the `FusedKernelRegistry` FROM its FKC contract.
9623    ///
9624    /// `register_default_fused_kernels` now imports
9625    /// `fuel-dispatch/kernel-contracts/fused/norm-softmax.fkc.md` through the production
9626    /// `CpuLinkRegistry` (chaining `CPU_FUSED_NORM_ENTRY_POINTS`) INSTEAD of the
9627    /// hand-written `register_fused!(SOFTMAX / RMS_NORM / LAYER_NORM_LAST_DIM
9628    /// (+backward) / REDUCE_MAX_TO_BACKWARD / POWI_BACKWARD, …)` entries (deleted).
9629    /// Each migrated `(FusedOpId, Cpu, dtypes)` resolves to the EXACT per-dtype
9630    /// production wrapper (pointer identity) AND carries the contract's REAL
9631    /// revision hash.
9632    ///
9633    /// **Discriminator = `revision != UNTRACKED`.** Both paths bind the SAME
9634    /// wrapper fn-pointer, so pointer identity holds in BOTH states — it is not
9635    /// the red discriminator. The hand-written `register_fused!` path stamps
9636    /// `KernelRevisionHash::UNTRACKED`; only the FKC import path stamps the
9637    /// contract's real `compute_revision`. RED (before wired + hand-written still
9638    /// present): `lookup_by_dtypes` returns the hand-written impl → `UNTRACKED` →
9639    /// `assert_ne!` fails. GREEN (deleted + imported): real revision → passes.
9640    ///
9641    /// Also asserts the **2026-07-03 maintainer flip rode through**: the imported
9642    /// precision is bit-stable (`bit_stable_on_same_hardware == true`), NOT the
9643    /// `UNAUDITED` an `audited: false` contract would have lowered to — the whole
9644    /// point of the flip.
9645    #[test]
9646    fn norm_softmax_fused_family_migrated_to_fkc_contract() {
9647        use crate::fused::{FusedKernelRegistry, KernelRevisionHash};
9648        use fuel_graph::registry::FusedOps;
9649
9650        let mut r = FusedKernelRegistry::new();
9651        register_default_fused_kernels(&mut r);
9652
9653        // FORWARD (key [T, T]) — Softmax / RmsNorm / LayerNorm last-dim.
9654        let forward = [
9655            (
9656                FusedOps::SOFTMAX_LAST_DIM,
9657                [
9658                    softmax_last_dim_f32_cpu_wrapper as *const () as usize,
9659                    softmax_last_dim_f64_cpu_wrapper as *const () as usize,
9660                    softmax_last_dim_bf16_cpu_wrapper as *const () as usize,
9661                    softmax_last_dim_f16_cpu_wrapper as *const () as usize,
9662                ],
9663            ),
9664            (
9665                FusedOps::RMS_NORM_LAST_DIM,
9666                [
9667                    rms_norm_last_dim_f32_cpu_wrapper as *const () as usize,
9668                    rms_norm_last_dim_f64_cpu_wrapper as *const () as usize,
9669                    rms_norm_last_dim_bf16_cpu_wrapper as *const () as usize,
9670                    rms_norm_last_dim_f16_cpu_wrapper as *const () as usize,
9671                ],
9672            ),
9673            (
9674                FusedOps::LAYER_NORM_LAST_DIM,
9675                [
9676                    layer_norm_last_dim_f32_cpu_wrapper as *const () as usize,
9677                    layer_norm_last_dim_f64_cpu_wrapper as *const () as usize,
9678                    layer_norm_last_dim_bf16_cpu_wrapper as *const () as usize,
9679                    layer_norm_last_dim_f16_cpu_wrapper as *const () as usize,
9680                ],
9681            ),
9682        ];
9683        for (id, wrappers) in forward {
9684            for (dt, expected) in [DType::F32, DType::F64, DType::BF16, DType::F16]
9685                .iter()
9686                .zip(wrappers)
9687            {
9688                let got = r
9689                    .lookup_by_dtypes(id, BackendId::Cpu, &[*dt, *dt])
9690                    .unwrap_or_else(|| panic!("{id:?} {dt:?} migrated impl present"));
9691                assert_eq!(
9692                    got.kernel as usize, expected,
9693                    "{id:?} {dt:?} binds its exact per-dtype production wrapper",
9694                );
9695                assert_ne!(
9696                    got.revision,
9697                    KernelRevisionHash::UNTRACKED,
9698                    "FKC-imported {id:?} {dt:?} carries the contract's real revision \
9699                     (hand-written register_fused! stamps UNTRACKED)",
9700                );
9701                assert!(
9702                    got.precision.bit_stable_on_same_hardware,
9703                    "the 2026-07-03 audited:true flip rode through as bit-stable for {id:?} {dt:?} \
9704                     (NOT the UNAUDITED an audited:false contract would have lowered to)",
9705                );
9706            }
9707        }
9708
9709        // BACKWARD (key [T, T, T]) — Softmax / Layer / Rms backward +
9710        // ReduceMaxTo / PowI backward (backward-of-primitive helpers).
9711        let backward = [
9712            (
9713                FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
9714                [
9715                    softmax_last_dim_backward_f32_cpu_wrapper as *const () as usize,
9716                    softmax_last_dim_backward_f64_cpu_wrapper as *const () as usize,
9717                    softmax_last_dim_backward_bf16_cpu_wrapper as *const () as usize,
9718                    softmax_last_dim_backward_f16_cpu_wrapper as *const () as usize,
9719                ],
9720            ),
9721            (
9722                FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
9723                [
9724                    layer_norm_last_dim_backward_f32_cpu_wrapper as *const () as usize,
9725                    layer_norm_last_dim_backward_f64_cpu_wrapper as *const () as usize,
9726                    layer_norm_last_dim_backward_bf16_cpu_wrapper as *const () as usize,
9727                    layer_norm_last_dim_backward_f16_cpu_wrapper as *const () as usize,
9728                ],
9729            ),
9730            (
9731                FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
9732                [
9733                    rms_norm_last_dim_backward_f32_cpu_wrapper as *const () as usize,
9734                    rms_norm_last_dim_backward_f64_cpu_wrapper as *const () as usize,
9735                    rms_norm_last_dim_backward_bf16_cpu_wrapper as *const () as usize,
9736                    rms_norm_last_dim_backward_f16_cpu_wrapper as *const () as usize,
9737                ],
9738            ),
9739            (
9740                FusedOps::REDUCE_MAX_TO_BACKWARD,
9741                [
9742                    reduce_max_to_backward_f32_cpu_wrapper as *const () as usize,
9743                    reduce_max_to_backward_f64_cpu_wrapper as *const () as usize,
9744                    reduce_max_to_backward_bf16_cpu_wrapper as *const () as usize,
9745                    reduce_max_to_backward_f16_cpu_wrapper as *const () as usize,
9746                ],
9747            ),
9748            (
9749                FusedOps::POWI_BACKWARD,
9750                [
9751                    powi_backward_f32_cpu_wrapper as *const () as usize,
9752                    powi_backward_f64_cpu_wrapper as *const () as usize,
9753                    powi_backward_bf16_cpu_wrapper as *const () as usize,
9754                    powi_backward_f16_cpu_wrapper as *const () as usize,
9755                ],
9756            ),
9757        ];
9758        for (id, wrappers) in backward {
9759            for (dt, expected) in [DType::F32, DType::F64, DType::BF16, DType::F16]
9760                .iter()
9761                .zip(wrappers)
9762            {
9763                let got = r
9764                    .lookup_by_dtypes(id, BackendId::Cpu, &[*dt, *dt, *dt])
9765                    .unwrap_or_else(|| panic!("{id:?} {dt:?} migrated impl present"));
9766                assert_eq!(got.kernel as usize, expected);
9767                assert_ne!(
9768                    got.revision,
9769                    KernelRevisionHash::UNTRACKED,
9770                    "FKC-imported {id:?} {dt:?} carries the contract's real revision",
9771                );
9772                assert!(
9773                    got.precision.bit_stable_on_same_hardware,
9774                    "the audited:true flip rode through as bit-stable for {id:?} {dt:?}",
9775                );
9776            }
9777        }
9778
9779        // GUARD: an UNMIGRATED fused op (FLASH_ATTN) still resolves its
9780        // hand-written impl at UNTRACKED — proves the migration is scoped.
9781        let fa = r
9782            .lookup_by_dtypes(
9783                FusedOps::FLASH_ATTN,
9784                BackendId::Cpu,
9785                &[DType::F32, DType::F32, DType::F32, DType::F32],
9786            )
9787            .expect("FLASH_ATTN hand-written impl present");
9788        assert_eq!(
9789            fa.revision,
9790            KernelRevisionHash::UNTRACKED,
9791            "unmigrated FLASH_ATTN keeps its hand-written UNTRACKED revision",
9792        );
9793    }
9794
9795    /// BORN-RED → GREEN: the `audited: true` conv / RoPE / SSM FUSED bundle is
9796    /// PRODUCTION-migrated into the `FusedKernelRegistry` FROM its FKC contract.
9797    ///
9798    /// `register_default_fused_kernels` now imports
9799    /// `fuel-dispatch/kernel-contracts/fused/conv-rope.fkc.md` through the production
9800    /// `CpuLinkRegistry` (chaining `CPU_FUSED_CONV_ROPE_ENTRY_POINTS`) INSTEAD of
9801    /// the hand-written `register_fused!(ROPE / CONV2D / CONV_TRANSPOSE2D /
9802    /// CAUSAL_CONV1D / SELECTIVE_SCAN / SSD_CHUNK_SCAN, …)` entries (deleted). Each
9803    /// migrated impl binds the EXACT per-dtype wrapper (pointer identity) AND
9804    /// carries the contract's REAL revision (hand-written stamps UNTRACKED — the
9805    /// red discriminator). Covers the two multi-key cases:
9806    /// - CONV2D / CONV_TRANSPOSE2D fan the optional bias into BOTH the no-bias
9807    ///   key `[T, T, T]` and the with-bias key `[T, T, T, T]` (8 impls each);
9808    /// - SELECTIVE_SCAN / SSD_CHUNK_SCAN key `[T; 6]` (5 inputs + the bundle's
9809    ///   primary output slot).
9810    ///
9811    /// Also asserts the **2026-07-03 maintainer flip rode through** as bit-stable
9812    /// (NOT `UNAUDITED`).
9813    #[test]
9814    fn conv_rope_fused_family_migrated_to_fkc_contract() {
9815        use crate::fused::{FusedKernelRegistry, KernelRevisionHash};
9816        use fuel_graph::registry::FusedOps;
9817
9818        let mut r = FusedKernelRegistry::new();
9819        register_default_fused_kernels(&mut r);
9820
9821        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
9822
9823        // ROPE — key [T, T, T, T] (x, cos, sin + out).
9824        let rope_w = [
9825            rope_f32_cpu_wrapper as *const () as usize,
9826            rope_f64_cpu_wrapper as *const () as usize,
9827            rope_bf16_cpu_wrapper as *const () as usize,
9828            rope_f16_cpu_wrapper as *const () as usize,
9829        ];
9830        for (dt, expected) in dts.iter().zip(rope_w) {
9831            let got = r
9832                .lookup_by_dtypes(FusedOps::ROPE, BackendId::Cpu, &[*dt, *dt, *dt, *dt])
9833                .unwrap_or_else(|| panic!("ROPE {dt:?} migrated impl present"));
9834            assert_eq!(got.kernel as usize, expected);
9835            assert_ne!(
9836                got.revision,
9837                KernelRevisionHash::UNTRACKED,
9838                "ROPE {dt:?} real revision"
9839            );
9840            assert!(
9841                got.precision.bit_stable_on_same_hardware,
9842                "audited:true rode through bit-stable for ROPE {dt:?}",
9843            );
9844        }
9845
9846        // CONV2D / CONV_TRANSPOSE2D — optional bias ⇒ BOTH no-bias [T,T,T] and
9847        // with-bias [T,T,T,T] resolve the SAME per-dtype wrapper (8 impls each).
9848        let conv = [
9849            (
9850                FusedOps::CONV2D,
9851                [
9852                    conv2d_f32_cpu_wrapper as *const () as usize,
9853                    conv2d_f64_cpu_wrapper as *const () as usize,
9854                    conv2d_bf16_cpu_wrapper as *const () as usize,
9855                    conv2d_f16_cpu_wrapper as *const () as usize,
9856                ],
9857            ),
9858            (
9859                FusedOps::CONV_TRANSPOSE2D,
9860                [
9861                    conv_transpose2d_f32_cpu_wrapper as *const () as usize,
9862                    conv_transpose2d_f64_cpu_wrapper as *const () as usize,
9863                    conv_transpose2d_bf16_cpu_wrapper as *const () as usize,
9864                    conv_transpose2d_f16_cpu_wrapper as *const () as usize,
9865                ],
9866            ),
9867        ];
9868        for (id, wrappers) in conv {
9869            for (dt, expected) in dts.iter().zip(wrappers) {
9870                for key in [vec![*dt, *dt, *dt], vec![*dt, *dt, *dt, *dt]] {
9871                    let with_bias = key.len() == 4;
9872                    let got = r
9873                        .lookup_by_dtypes(id, BackendId::Cpu, &key)
9874                        .unwrap_or_else(|| {
9875                            panic!("{id:?} {dt:?} (with_bias={with_bias}) migrated impl present")
9876                        });
9877                    assert_eq!(got.kernel as usize, expected);
9878                    assert_ne!(
9879                        got.revision,
9880                        KernelRevisionHash::UNTRACKED,
9881                        "{id:?} {dt:?} (with_bias={with_bias}) real revision",
9882                    );
9883                    assert!(
9884                        got.precision.bit_stable_on_same_hardware,
9885                        "audited:true rode through bit-stable for {id:?} {dt:?} (with_bias={with_bias})",
9886                    );
9887                }
9888            }
9889        }
9890
9891        // CAUSAL_CONV1D — key [T, T, T, T] (x, weight, bias + out).
9892        let cc1d_w = [
9893            causal_conv1d_f32_cpu_wrapper as *const () as usize,
9894            causal_conv1d_f64_cpu_wrapper as *const () as usize,
9895            causal_conv1d_bf16_cpu_wrapper as *const () as usize,
9896            causal_conv1d_f16_cpu_wrapper as *const () as usize,
9897        ];
9898        for (dt, expected) in dts.iter().zip(cc1d_w) {
9899            let got = r
9900                .lookup_by_dtypes(
9901                    FusedOps::CAUSAL_CONV1D,
9902                    BackendId::Cpu,
9903                    &[*dt, *dt, *dt, *dt],
9904                )
9905                .unwrap_or_else(|| panic!("CAUSAL_CONV1D {dt:?} migrated impl present"));
9906            assert_eq!(got.kernel as usize, expected);
9907            assert_ne!(got.revision, KernelRevisionHash::UNTRACKED);
9908            assert!(got.precision.bit_stable_on_same_hardware);
9909        }
9910
9911        // SELECTIVE_SCAN / SSD_CHUNK_SCAN — return.bundle ⇒ key [T; 6]
9912        // (5 inputs + the bundled primary output slot).
9913        let scan = [
9914            (
9915                FusedOps::SELECTIVE_SCAN,
9916                [
9917                    selective_scan_f32_cpu_wrapper as *const () as usize,
9918                    selective_scan_f64_cpu_wrapper as *const () as usize,
9919                    selective_scan_bf16_cpu_wrapper as *const () as usize,
9920                    selective_scan_f16_cpu_wrapper as *const () as usize,
9921                ],
9922            ),
9923            (
9924                FusedOps::SSD_CHUNK_SCAN,
9925                [
9926                    ssd_chunk_scan_f32_cpu_wrapper as *const () as usize,
9927                    ssd_chunk_scan_f64_cpu_wrapper as *const () as usize,
9928                    ssd_chunk_scan_bf16_cpu_wrapper as *const () as usize,
9929                    ssd_chunk_scan_f16_cpu_wrapper as *const () as usize,
9930                ],
9931            ),
9932        ];
9933        for (id, wrappers) in scan {
9934            for (dt, expected) in dts.iter().zip(wrappers) {
9935                let got = r
9936                    .lookup_by_dtypes(id, BackendId::Cpu, &[*dt; 6])
9937                    .unwrap_or_else(|| panic!("{id:?} {dt:?} migrated impl present"));
9938                assert_eq!(got.kernel as usize, expected);
9939                assert_ne!(
9940                    got.revision,
9941                    KernelRevisionHash::UNTRACKED,
9942                    "{id:?} {dt:?} real revision",
9943                );
9944                assert!(
9945                    got.precision.bit_stable_on_same_hardware,
9946                    "audited:true rode through bit-stable for {id:?} {dt:?}",
9947                );
9948            }
9949        }
9950
9951        // GUARD: the DEFERRED NF4_MATMUL (linear-quant `registrable: false`) stays
9952        // hand-written at UNTRACKED — proves this migration is scoped to conv-rope.
9953        let nf4 = r
9954            .lookup_by_dtypes(
9955                FusedOps::NF4_MATMUL,
9956                BackendId::Cpu,
9957                &[DType::F32, DType::U8, DType::F32, DType::F32],
9958            )
9959            .expect("NF4_MATMUL hand-written impl present");
9960        assert_eq!(
9961            nf4.revision,
9962            KernelRevisionHash::UNTRACKED,
9963            "deferred NF4_MATMUL keeps its hand-written UNTRACKED revision",
9964        );
9965    }
9966
9967    /// Phase 7.6 step 7b — the architecture v1.0 §05 "always-built
9968    /// backend bit-stable coverage commitment" lint, extended from
9969    /// the fused-op half (step 7a) to **primitive** ops.
9970    ///
9971    /// Every `OpKind` variant that flows through `KernelBindingTable`
9972    /// MUST have at least one CPU registration with
9973    /// `precision.bit_stable_on_same_hardware == true`. The
9974    /// architecture's correctness anchor is the always-built backend
9975    /// giving every downstream consumer a deterministic
9976    /// implementation to fall back on, so cross-backend equivalence
9977    /// tests have a fixed reference.
9978    ///
9979    /// The lint runs as a unit test so violations surface in CI
9980    /// rather than at runtime. Adding a new `OpKind` variant without
9981    /// a matching CPU registration fails this test immediately.
9982    ///
9983    /// As of step 7b (2026-05-11), every `OpKind` variant has CPU
9984    /// coverage via `register_cpu_kernels` + the
9985    /// `fill_unset_cpu_precision` pass at the end of that function.
9986    /// `KNOWN_GAPS` is empty.
9987    ///
9988    /// Note on the OpKind enumeration: there's no `strum`-style
9989    /// derive on the enum, so the test hardcodes the variant list.
9990    /// New OpKind variants must be added here AND to a matching
9991    /// CPU registration in `register_cpu_kernels`. The two-touch
9992    /// requirement is a feature — the test becomes the canonical
9993    /// "all kernels accounted for" reference.
9994    #[test]
9995    /// FKC-CLAUSE: FKC-4.8-0001 — the always-built coverage commitment. This is a
9996    /// CORPUS property (>=1 bit-stable CPU kernel per primitive op), not a
9997    /// per-contract rule, so it raises no FkcError and is invisible to the
9998    /// variant-anchored gate in tests/fkc_clause_coverage.rs.
9999    fn precision_guarantee_lint_bit_stable_cpu_coverage_primitives() {
10000        use fuel_ir::dispatch::OpKind;
10001        use fuel_ir::probe::BackendId;
10002
10003        // Allowlist for OpKind variants that *can't* have bit-stable
10004        // CPU coverage. Empty as of step 7b (every variant routes
10005        // through deterministic kernels). New entries must come with
10006        // a documented reason — and a follow-up to close the gap.
10007        const KNOWN_GAPS: &[(OpKind, &str)] = &[];
10008
10009        // The canonical list of every OpKind variant. Mirrors the
10010        // enum definition in fuel-core-types::dispatch. Adding a
10011        // new variant requires adding it here; that's the explicit
10012        // contract for "this OpKind exists and is expected to have
10013        // CPU coverage."
10014        const ALL_OP_KINDS: &[OpKind] = &[
10015            OpKind::MatMul,
10016            OpKind::AddElementwise,
10017            OpKind::SubElementwise,
10018            OpKind::MulElementwise,
10019            OpKind::DivElementwise,
10020            OpKind::ReluElementwise,
10021            OpKind::NegElementwise,
10022            OpKind::SqrElementwise,
10023            OpKind::SqrtElementwise,
10024            OpKind::RecipElementwise,
10025            OpKind::AbsElementwise,
10026            OpKind::TanhElementwise,
10027            OpKind::ExpElementwise,
10028            OpKind::LogElementwise,
10029            OpKind::SinElementwise,
10030            OpKind::CosElementwise,
10031            OpKind::SigmoidElementwise,
10032            OpKind::SiluElementwise,
10033            OpKind::GeluTanhElementwise,
10034            OpKind::StepElementwise,
10035            OpKind::SumReduce,
10036            OpKind::MaxReduce,
10037            OpKind::MinReduce,
10038            OpKind::MeanReduce,
10039            OpKind::Cast,
10040            OpKind::Conv2D,
10041            OpKind::ConvTranspose2D,
10042            OpKind::ReduceSumTo,
10043            OpKind::ReduceMaxTo,
10044            OpKind::FusedLinear,
10045            OpKind::FlashAttn,
10046            OpKind::PagedAttn,
10047            OpKind::Affine,
10048            OpKind::ClampElementwise,
10049            OpKind::PowIElementwise,
10050            OpKind::MaximumElementwise,
10051            OpKind::MinimumElementwise,
10052            OpKind::EqualElementwise,
10053            OpKind::NotEqualElementwise,
10054            OpKind::LessElementwise,
10055            OpKind::LessEqualElementwise,
10056            OpKind::GreaterElementwise,
10057            OpKind::GreaterEqualElementwise,
10058            OpKind::Where,
10059            OpKind::FloorElementwise,
10060            OpKind::CeilElementwise,
10061            OpKind::RoundElementwise,
10062            OpKind::SignElementwise,
10063            OpKind::ErfElementwise,
10064            OpKind::GeluElementwise,
10065            OpKind::PowElementwise,
10066            OpKind::RsqrtElementwise,
10067            OpKind::RemElementwise,
10068            OpKind::Flip,
10069            OpKind::Roll,
10070            OpKind::CumSum,
10071            OpKind::Pad,
10072            OpKind::PadBackward,
10073            OpKind::Triu,
10074            OpKind::Tril,
10075            OpKind::LogSoftmaxLastDim,
10076            OpKind::LogSoftmaxLastDimBackward,
10077            OpKind::MaskedFill,
10078            OpKind::Concat,
10079            OpKind::SoftmaxLastDim,
10080            OpKind::SoftmaxLastDimBackward,
10081            OpKind::RmsNormLastDim,
10082            OpKind::RmsNormLastDimBackward,
10083            OpKind::LayerNormLastDim,
10084            OpKind::LayerNormLastDimBackward,
10085            OpKind::ReduceMaxToBackward,
10086            OpKind::IndexSelect,
10087            OpKind::Gather,
10088            OpKind::Rope,
10089            OpKind::IndexAdd,
10090            OpKind::ScatterAdd,
10091            OpKind::ArgMaxDim,
10092            OpKind::ArgMinDim,
10093            OpKind::QMatMul,
10094            OpKind::Copy,
10095            OpKind::FusedSoftmaxCrossEntropy,
10096            OpKind::CausalConv1d,
10097            OpKind::SelectiveScan,
10098            OpKind::SsdChunkScan,
10099            OpKind::Nf4Matmul,
10100        ];
10101
10102        // Populate the binding table the same way the production
10103        // path does — via register_cpu_kernels including the
10104        // fill_unset_cpu_precision pass at the end.
10105        let mut table = KernelBindingTable::new();
10106        register_cpu_kernels(&mut table);
10107
10108        // Group all CPU registrations by OpKind so we can check
10109        // coverage per variant.
10110        let mut by_op_kind: std::collections::HashMap<
10111            OpKind,
10112            Vec<crate::fused::PrecisionGuarantee>,
10113        > = std::collections::HashMap::new();
10114        for (op, _dtypes, backend, precision) in table.iter_precision() {
10115            if backend == BackendId::Cpu {
10116                by_op_kind.entry(op).or_default().push(precision);
10117            }
10118        }
10119
10120        let mut failures: Vec<String> = Vec::new();
10121        let mut covered = 0usize;
10122        let mut allowlisted = 0usize;
10123
10124        for op in ALL_OP_KINDS.iter().copied() {
10125            if let Some((_, reason)) = KNOWN_GAPS.iter().find(|(g, _)| *g == op) {
10126                allowlisted += 1;
10127                if by_op_kind.contains_key(&op) {
10128                    failures.push(format!(
10129                        "OpKind::{op:?} is on the KNOWN_GAPS allowlist but DOES \
10130                         have a CPU registration now. Reason given was: \
10131                         {reason:?}. Remove the allowlist entry to enable the \
10132                         bit-stable lint for this op.",
10133                    ));
10134                }
10135                continue;
10136            }
10137            let precisions = by_op_kind.get(&op);
10138            let has_bit_stable_cpu =
10139                precisions.is_some_and(|ps| ps.iter().any(|p| p.bit_stable_on_same_hardware));
10140            if has_bit_stable_cpu {
10141                covered += 1;
10142            } else {
10143                failures.push(format!(
10144                    "OpKind::{op:?} has no bit-stable CPU registration. \
10145                     Architecture v1.0 §05 requires the always-built backend \
10146                     (fuel-cpu-backend) to provide at least one \
10147                     `bit_stable_on_same_hardware: true` kernel per primitive \
10148                     op. Either add a CPU registration in \
10149                     register_cpu_kernels (the fill_unset_cpu_precision pass \
10150                     at the end will upgrade it to PRIMITIVE_DETERMINISTIC_CPU \
10151                     automatically), or add a line to KNOWN_GAPS above with a \
10152                     documented reason.",
10153                ));
10154            }
10155        }
10156
10157        assert!(
10158            failures.is_empty(),
10159            "Architecture v1.0 bit-stable CPU coverage lint (primitives) failed:\n{}",
10160            failures.join("\n"),
10161        );
10162        assert_eq!(
10163            allowlisted, 0,
10164            "KNOWN_GAPS allowlist is empty by design; saw {allowlisted} allowlisted",
10165        );
10166        // Sanity: ALL_OP_KINDS should match the production
10167        // registration set. If a new variant lands in the enum
10168        // without being added here, the test's value is reduced —
10169        // catch the case by asserting the count.
10170        assert!(covered > 0, "lint covered 0 OpKinds — table appears empty",);
10171        // Sanity: every OpKind we enumerated should have ≥1 dtype
10172        // registration. The fill pass should have populated
10173        // precision for each.
10174        for op in ALL_OP_KINDS {
10175            assert!(
10176                by_op_kind.contains_key(op),
10177                "OpKind::{op:?} has no CPU registration at all — either add \
10178                 one in register_cpu_kernels or document the gap in \
10179                 KNOWN_GAPS.",
10180            );
10181        }
10182    }
10183
10184    /// Phase 7.6 step 8 — the "every OpKind has a real cost
10185    /// function" coverage lint. Companion to step 7b's bit-stable
10186    /// precision lint; the architectural commitment is that every
10187    /// primitive op carries both a `PrecisionGuarantee` and a
10188    /// `CostFn` (Layer-1 cost model: FLOPs + bandwidth + launch
10189    /// overhead) by the time the binding table is consulted at
10190    /// dispatch time.
10191    ///
10192    /// The lint runs as a unit test. Violations surface in CI
10193    /// rather than at runtime — a new `OpKind` variant without a
10194    /// matching arm in
10195    /// [`crate::cost::default_cost_for_op_kind`] fails this test
10196    /// immediately because the fill pass leaves it bound to
10197    /// `unknown_cost`.
10198    ///
10199    /// `KNOWN_GAPS` is empty as of step 8 (2026-05-12). Adding a
10200    /// future variant without immediate cost coverage needs a
10201    /// documented allowlist entry AND a follow-up.
10202    #[test]
10203    fn cost_lint_per_op_kind_cpu_coverage() {
10204        use fuel_ir::dispatch::OpKind;
10205        use fuel_ir::probe::BackendId;
10206
10207        const KNOWN_GAPS: &[(OpKind, &str)] = &[];
10208
10209        const ALL_OP_KINDS: &[OpKind] = &[
10210            OpKind::MatMul,
10211            OpKind::AddElementwise,
10212            OpKind::SubElementwise,
10213            OpKind::MulElementwise,
10214            OpKind::DivElementwise,
10215            OpKind::ReluElementwise,
10216            OpKind::NegElementwise,
10217            OpKind::SqrElementwise,
10218            OpKind::SqrtElementwise,
10219            OpKind::RecipElementwise,
10220            OpKind::AbsElementwise,
10221            OpKind::TanhElementwise,
10222            OpKind::ExpElementwise,
10223            OpKind::LogElementwise,
10224            OpKind::SinElementwise,
10225            OpKind::CosElementwise,
10226            OpKind::SigmoidElementwise,
10227            OpKind::SiluElementwise,
10228            OpKind::GeluTanhElementwise,
10229            OpKind::StepElementwise,
10230            OpKind::SumReduce,
10231            OpKind::MaxReduce,
10232            OpKind::MinReduce,
10233            OpKind::MeanReduce,
10234            OpKind::Cast,
10235            OpKind::Conv2D,
10236            OpKind::ConvTranspose2D,
10237            OpKind::ReduceSumTo,
10238            OpKind::ReduceMaxTo,
10239            OpKind::FusedLinear,
10240            OpKind::FlashAttn,
10241            OpKind::PagedAttn,
10242            OpKind::Affine,
10243            OpKind::ClampElementwise,
10244            OpKind::PowIElementwise,
10245            OpKind::MaximumElementwise,
10246            OpKind::MinimumElementwise,
10247            OpKind::EqualElementwise,
10248            OpKind::NotEqualElementwise,
10249            OpKind::LessElementwise,
10250            OpKind::LessEqualElementwise,
10251            OpKind::GreaterElementwise,
10252            OpKind::GreaterEqualElementwise,
10253            OpKind::Where,
10254            OpKind::FloorElementwise,
10255            OpKind::CeilElementwise,
10256            OpKind::RoundElementwise,
10257            OpKind::SignElementwise,
10258            OpKind::ErfElementwise,
10259            OpKind::GeluElementwise,
10260            OpKind::PowElementwise,
10261            OpKind::RsqrtElementwise,
10262            OpKind::RemElementwise,
10263            OpKind::Flip,
10264            OpKind::Roll,
10265            OpKind::CumSum,
10266            OpKind::Pad,
10267            OpKind::PadBackward,
10268            OpKind::Triu,
10269            OpKind::Tril,
10270            OpKind::LogSoftmaxLastDim,
10271            OpKind::LogSoftmaxLastDimBackward,
10272            OpKind::MaskedFill,
10273            OpKind::Concat,
10274            OpKind::SoftmaxLastDim,
10275            OpKind::SoftmaxLastDimBackward,
10276            OpKind::RmsNormLastDim,
10277            OpKind::RmsNormLastDimBackward,
10278            OpKind::LayerNormLastDim,
10279            OpKind::LayerNormLastDimBackward,
10280            OpKind::ReduceMaxToBackward,
10281            OpKind::IndexSelect,
10282            OpKind::Gather,
10283            OpKind::Rope,
10284            OpKind::IndexAdd,
10285            OpKind::ScatterAdd,
10286            OpKind::ArgMaxDim,
10287            OpKind::ArgMinDim,
10288            OpKind::QMatMul,
10289            OpKind::Copy,
10290            OpKind::FusedSoftmaxCrossEntropy,
10291            OpKind::CausalConv1d,
10292            OpKind::SelectiveScan,
10293            OpKind::SsdChunkScan,
10294            OpKind::Nf4Matmul,
10295        ];
10296
10297        let mut table = KernelBindingTable::new();
10298        register_cpu_kernels(&mut table);
10299
10300        // Group cost functions by OpKind for CPU registrations.
10301        let mut by_op_kind: std::collections::HashMap<OpKind, Vec<crate::kernel::CostFn>> =
10302            std::collections::HashMap::new();
10303        for (op, _dtypes, backend, cost) in table.iter_cost() {
10304            if backend == BackendId::Cpu {
10305                by_op_kind.entry(op).or_default().push(cost);
10306            }
10307        }
10308
10309        let unknown_sentinel = crate::kernel::unknown_cost as *const () as usize;
10310
10311        let mut failures: Vec<String> = Vec::new();
10312        for op in ALL_OP_KINDS.iter().copied() {
10313            if let Some((_, reason)) = KNOWN_GAPS.iter().find(|(g, _)| *g == op) {
10314                if let Some(costs) = by_op_kind.get(&op) {
10315                    let has_real = costs.iter().any(|c| (*c as usize) != unknown_sentinel);
10316                    if has_real {
10317                        failures.push(format!(
10318                            "OpKind::{op:?} is on the cost-lint KNOWN_GAPS \
10319                             allowlist but DOES have a non-default cost fn \
10320                             now. Reason given: {reason:?}. Remove the \
10321                             allowlist entry.",
10322                        ));
10323                    }
10324                }
10325                continue;
10326            }
10327            let costs = by_op_kind.get(&op);
10328            let has_real_cost =
10329                costs.is_some_and(|cs| cs.iter().any(|c| (*c as usize) != unknown_sentinel));
10330            if !has_real_cost {
10331                failures.push(format!(
10332                    "OpKind::{op:?} has no non-default cost fn in any CPU \
10333                     registration. Either add an arm in \
10334                     `crate::cost::default_cost_for_op_kind` (the \
10335                     fill_unset_cpu_cost pass at the end of \
10336                     register_cpu_kernels will pick it up automatically), \
10337                     register an explicit cost via `register_full(...)`, \
10338                     or add a line to KNOWN_GAPS with a documented reason.",
10339                ));
10340            }
10341        }
10342
10343        assert!(
10344            failures.is_empty(),
10345            "Phase 7.6 step 8 cost-coverage lint failed:\n{}",
10346            failures.join("\n"),
10347        );
10348        // Sanity: every OpKind we enumerated should have ≥1 CPU
10349        // registration (asserted separately by the step-7b lint,
10350        // but re-checked here for symmetry).
10351        for op in ALL_OP_KINDS {
10352            assert!(
10353                by_op_kind.contains_key(op),
10354                "OpKind::{op:?} has no CPU registration at all.",
10355            );
10356        }
10357    }
10358
10359    fn cpu_caps() -> BackendCapabilities {
10360        BackendCapabilities {
10361            backend_id: BackendId::Cpu,
10362            device_location: DeviceLocation::Cpu,
10363            op_dtype_support: [
10364                (OpKind::MatMul, DType::F32),
10365                (OpKind::MatMul, DType::F64),
10366                (OpKind::AddElementwise, DType::F32),
10367                (OpKind::AddElementwise, DType::F64),
10368            ]
10369            .into_iter()
10370            .collect(),
10371            required_alignment: 64,
10372            access_granularity_bits: 8,
10373            transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
10374            storage_substrate: SubstrateClass::HostBytes,
10375            compute_throughput_flops_per_ns: 1.0,
10376            mem_bandwidth_bytes_per_ns: 4.0,
10377        }
10378    }
10379
10380    fn cuda_caps() -> BackendCapabilities {
10381        BackendCapabilities {
10382            backend_id: BackendId::Cuda,
10383            device_location: DeviceLocation::Cuda { gpu_id: 0 },
10384            op_dtype_support: [
10385                (OpKind::MatMul, DType::F32),
10386                (OpKind::MatMul, DType::F16),
10387                (OpKind::AddElementwise, DType::F32),
10388            ]
10389            .into_iter()
10390            .collect(),
10391            required_alignment: 256,
10392            access_granularity_bits: 8,
10393            transfer_paths: vec![
10394                (DeviceLocation::Cpu, TransferPath::DeviceCopy),
10395                (DeviceLocation::Cuda { gpu_id: 0 }, TransferPath::SameDevice),
10396            ],
10397            storage_substrate: SubstrateClass::CudaUntyped,
10398            compute_throughput_flops_per_ns: 30.0,
10399            mem_bandwidth_bytes_per_ns: 40.0,
10400        }
10401    }
10402
10403    /// Smoke: empty registry has nothing.
10404    #[test]
10405    fn empty_registry() {
10406        let r = CapabilityRegistry::new();
10407        assert!(r.backends().is_empty());
10408        let result = r.find_backend_for(OpKind::MatMul, DType::F32);
10409        assert!(result.is_err());
10410    }
10411
10412    /// Find_backends returns matching backends in registration order.
10413    #[test]
10414    fn find_backends_order_preserved() {
10415        let mut r = CapabilityRegistry::new();
10416        r.register(cuda_caps()); // registered first → wins ties
10417        r.register(cpu_caps());
10418
10419        let backends = r.find_backends(OpKind::MatMul, DType::F32);
10420        assert_eq!(backends.len(), 2);
10421        assert_eq!(backends[0].backend_id, BackendId::Cuda);
10422        assert_eq!(backends[1].backend_id, BackendId::Cpu);
10423    }
10424
10425    /// Find_backend_for picks first match.
10426    #[test]
10427    fn find_backend_first_wins() {
10428        let mut r = CapabilityRegistry::new();
10429        r.register(cuda_caps());
10430        r.register(cpu_caps());
10431
10432        let chosen = r.find_backend_for(OpKind::MatMul, DType::F32).unwrap();
10433        assert_eq!(chosen.backend_id, BackendId::Cuda);
10434    }
10435
10436    /// CPU-only registry falls back when GPU dtypes aren't supported.
10437    #[test]
10438    fn cpu_handles_what_gpu_doesnt() {
10439        let mut r = CapabilityRegistry::new();
10440        r.register(cuda_caps());
10441        r.register(cpu_caps());
10442
10443        // CUDA doesn't support F64; CPU does.
10444        let chosen = r.find_backend_for(OpKind::MatMul, DType::F64).unwrap();
10445        assert_eq!(chosen.backend_id, BackendId::Cpu);
10446    }
10447
10448    /// Unsupported (op, dtype) returns NoBackendForOp with diagnostic data.
10449    #[test]
10450    fn unsupported_combo_errors_with_diagnostic() {
10451        let mut r = CapabilityRegistry::new();
10452        r.register(cpu_caps());
10453
10454        let err = match r.find_backend_for(OpKind::MatMul, DType::BF16) {
10455            Ok(_) => panic!("expected error"),
10456            Err(e) => e,
10457        };
10458        let msg = err.to_string();
10459        assert!(
10460            msg.contains("MatMul") || msg.contains("matmul"),
10461            "error names op: {msg}"
10462        );
10463        assert!(msg.contains("BF16"), "error names dtype: {msg}");
10464        assert!(msg.contains("Cpu"), "error names available backends: {msg}");
10465    }
10466
10467    /// TransferMatrix preserves SameDevice for src == dst always.
10468    #[test]
10469    fn transfer_matrix_same_device() {
10470        let r = CapabilityRegistry::new();
10471        let m = r.build_transfer_matrix();
10472        assert_eq!(
10473            m.path(DeviceLocation::Cpu, DeviceLocation::Cpu),
10474            Some(TransferPath::SameDevice)
10475        );
10476    }
10477
10478    /// TransferMatrix entries from registered backends.
10479    #[test]
10480    fn transfer_matrix_built_from_caps() {
10481        let mut r = CapabilityRegistry::new();
10482        r.register(cuda_caps());
10483        let m = r.build_transfer_matrix();
10484
10485        // CUDA → CPU is DeviceCopy (advertised).
10486        assert_eq!(
10487            m.path(DeviceLocation::Cuda { gpu_id: 0 }, DeviceLocation::Cpu),
10488            Some(TransferPath::DeviceCopy)
10489        );
10490    }
10491
10492    /// path_or_staging falls back to HostStaging for unadvertised
10493    /// pairs.
10494    #[test]
10495    fn host_staging_fallback() {
10496        let r = CapabilityRegistry::new();
10497        let m = r.build_transfer_matrix();
10498        // No CPU registered; CPU→Cuda has no entry; staging fallback.
10499        assert_eq!(
10500            m.path_or_staging(DeviceLocation::Cpu, DeviceLocation::Cuda { gpu_id: 0 }),
10501            TransferPath::HostStaging
10502        );
10503    }
10504
10505    /// resolve_target_backend picks the first registered backend
10506    /// supporting (op, dtype).
10507    #[test]
10508    fn resolve_picks_first_match() {
10509        let mut r = CapabilityRegistry::new();
10510        r.register(cuda_caps());
10511        r.register(cpu_caps());
10512        assert_eq!(
10513            resolve_target_backend(&r, OpKind::MatMul, DType::F32).unwrap(),
10514            BackendId::Cuda
10515        );
10516    }
10517
10518    /// resolve_target_backend falls back to CPU for dtypes GPU doesn't support.
10519    #[test]
10520    fn resolve_falls_back_to_cpu() {
10521        let mut r = CapabilityRegistry::new();
10522        r.register(cuda_caps());
10523        r.register(cpu_caps());
10524        assert_eq!(
10525            resolve_target_backend(&r, OpKind::MatMul, DType::F64).unwrap(),
10526            BackendId::Cpu
10527        );
10528    }
10529
10530    /// resolve_target_backend errors with NoBackendForOp on miss.
10531    #[test]
10532    fn resolve_errors_on_unsupported() {
10533        let mut r = CapabilityRegistry::new();
10534        r.register(cpu_caps());
10535        let result = resolve_target_backend(&r, OpKind::MatMul, DType::BF16);
10536        assert!(result.is_err());
10537    }
10538
10539    /// Residency-aware resolver picks a backend with input-local
10540    /// residency when available.
10541    #[test]
10542    fn resolve_residency_aware_prefers_local() {
10543        let mut r = CapabilityRegistry::new();
10544        // CUDA registered first (would normally win ties for f32).
10545        r.register(cuda_caps());
10546        r.register(cpu_caps());
10547
10548        // Inputs live on CPU; residency-aware prefers CPU even
10549        // though CUDA also supports (MatMul, F32).
10550        let chosen = resolve_target_backend_residency_aware(
10551            &r,
10552            OpKind::MatMul,
10553            DType::F32,
10554            &[DeviceLocation::Cpu],
10555        )
10556        .unwrap();
10557        assert_eq!(chosen, BackendId::Cpu);
10558    }
10559
10560    /// Residency-aware falls back to first match when no residency
10561    /// match exists.
10562    #[test]
10563    fn resolve_residency_aware_no_local_falls_back() {
10564        let mut r = CapabilityRegistry::new();
10565        r.register(cuda_caps());
10566        r.register(cpu_caps());
10567
10568        // Inputs on a Vulkan device — no candidate matches; falls
10569        // back to first (CUDA).
10570        let chosen = resolve_target_backend_residency_aware(
10571            &r,
10572            OpKind::MatMul,
10573            DType::F32,
10574            &[DeviceLocation::Vulkan { gpu_id: 0 }],
10575        )
10576        .unwrap();
10577        assert_eq!(chosen, BackendId::Cuda);
10578    }
10579
10580    // -------- B5: kernel binding table + CPU dispatch wrappers --------
10581
10582    /// Smoke: register_cpu_kernels populates the binding table.
10583    #[test]
10584    fn register_cpu_kernels_populates_table() {
10585        let mut table = KernelBindingTable::new();
10586        assert!(table.is_empty());
10587        register_cpu_kernels(&mut table);
10588        assert!(!table.is_empty());
10589        // The (AddElementwise, F32, Cpu) binding lands.
10590        let _kernel = table
10591            .lookup(
10592                OpKind::AddElementwise,
10593                &[DType::F32, DType::F32, DType::F32],
10594                BackendId::Cpu,
10595            )
10596            .expect("registered");
10597    }
10598
10599    /// FIRST PRODUCTION FKC CONSUMER (born-red gate). `global_bindings()`
10600    /// registers the CPU elementwise-binary family (8 ops × 4 dtypes = 32
10601    /// bindings) FROM ITS KERNEL CONTRACT
10602    /// (`fuel-dispatch/kernel-contracts/cpu/elementwise-binary.fkc.md`) — the sole
10603    /// registration path, now that the hand-written `table.register(...)`
10604    /// calls for this family are DELETED.
10605    ///
10606    /// For each of the 32 `(op, [dt; 3], Cpu)` keys this asserts:
10607    ///  - the binding resolves to the EXACT production wrapper fn-pointer
10608    ///    (behavior-preserving execution),
10609    ///  - `kernel_source == "portable-cpu"` — the contract's provenance tag
10610    ///    (the deleted hand-written path stamped `""`). THIS is the
10611    ///    discriminator that makes the test go red without the import wired:
10612    ///    with the hand-written binary regs removed and the import absent, the
10613    ///    family is simply missing from `global_bindings()`,
10614    ///  - caps stay empty (`strided_input == false`) and the contract's
10615    ///    audited bit-stable precision claim rode through.
10616    #[test]
10617    fn global_bindings_registers_binary_family_from_contract() {
10618        let table = global_bindings();
10619
10620        // (op, [f32, f64, bf16, f16] production wrappers) for all 8 ops.
10621        let families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10622            (
10623                OpKind::AddElementwise,
10624                [
10625                    add_elementwise_f32_cpu_wrapper,
10626                    add_elementwise_f64_cpu_wrapper,
10627                    add_elementwise_bf16_cpu_wrapper,
10628                    add_elementwise_f16_cpu_wrapper,
10629                ],
10630            ),
10631            (
10632                OpKind::SubElementwise,
10633                [
10634                    sub_elementwise_f32_cpu_wrapper,
10635                    sub_elementwise_f64_cpu_wrapper,
10636                    sub_elementwise_bf16_cpu_wrapper,
10637                    sub_elementwise_f16_cpu_wrapper,
10638                ],
10639            ),
10640            (
10641                OpKind::MulElementwise,
10642                [
10643                    mul_elementwise_f32_cpu_wrapper,
10644                    mul_elementwise_f64_cpu_wrapper,
10645                    mul_elementwise_bf16_cpu_wrapper,
10646                    mul_elementwise_f16_cpu_wrapper,
10647                ],
10648            ),
10649            (
10650                OpKind::DivElementwise,
10651                [
10652                    div_elementwise_f32_cpu_wrapper,
10653                    div_elementwise_f64_cpu_wrapper,
10654                    div_elementwise_bf16_cpu_wrapper,
10655                    div_elementwise_f16_cpu_wrapper,
10656                ],
10657            ),
10658            (
10659                OpKind::MaximumElementwise,
10660                [
10661                    maximum_elementwise_f32_cpu_wrapper,
10662                    maximum_elementwise_f64_cpu_wrapper,
10663                    maximum_elementwise_bf16_cpu_wrapper,
10664                    maximum_elementwise_f16_cpu_wrapper,
10665                ],
10666            ),
10667            (
10668                OpKind::MinimumElementwise,
10669                [
10670                    minimum_elementwise_f32_cpu_wrapper,
10671                    minimum_elementwise_f64_cpu_wrapper,
10672                    minimum_elementwise_bf16_cpu_wrapper,
10673                    minimum_elementwise_f16_cpu_wrapper,
10674                ],
10675            ),
10676            (
10677                OpKind::PowElementwise,
10678                [
10679                    pow_elementwise_f32_cpu_wrapper,
10680                    pow_elementwise_f64_cpu_wrapper,
10681                    pow_elementwise_bf16_cpu_wrapper,
10682                    pow_elementwise_f16_cpu_wrapper,
10683                ],
10684            ),
10685            (
10686                OpKind::RemElementwise,
10687                [
10688                    rem_elementwise_f32_cpu_wrapper,
10689                    rem_elementwise_f64_cpu_wrapper,
10690                    rem_elementwise_bf16_cpu_wrapper,
10691                    rem_elementwise_f16_cpu_wrapper,
10692                ],
10693            ),
10694        ];
10695        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10696
10697        let mut checked = 0usize;
10698        for (op, wrappers) in families {
10699            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10700                let alts = table.lookup_alternatives(*op, &[*dt, *dt, *dt], BackendId::Cpu);
10701                let entry = alts
10702                    .iter()
10703                    .find(|e| e.kernel as usize == *expected as usize)
10704                    .unwrap_or_else(|| {
10705                        panic!(
10706                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10707                             FROM the elementwise-binary contract in global_bindings() \
10708                             — found {} alternative(s) with sources {:?}",
10709                            alts.len(),
10710                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10711                        )
10712                    });
10713                assert_eq!(
10714                    entry.kernel_source, "portable-cpu",
10715                    "{op:?}/{dt:?}: binary family must be contract-sourced \
10716                     (kernel_source=\"portable-cpu\"); got {:?}",
10717                    entry.kernel_source,
10718                );
10719                assert!(
10720                    !entry.caps.strided_input,
10721                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10722                );
10723                assert!(
10724                    entry.precision.bit_stable_on_same_hardware,
10725                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
10726                );
10727                checked += 1;
10728            }
10729        }
10730        assert_eq!(checked, 32, "all 8 ops × 4 dtypes checked");
10731    }
10732
10733    /// FKC born-red gate for the CPU affine / clamp / powi family.
10734    /// `global_bindings()` registers the out-of-place scalar-param family
10735    /// (affine/clamp/powi × 4 dtypes + powi_backward × 4 = 16 bindings) FROM
10736    /// ITS KERNEL CONTRACT (`fuel-dispatch/kernel-contracts/cpu/affine-clamp-powi.fkc.md`)
10737    /// — the sole registration path, now that the hand-written
10738    /// `table.register(...)` calls are DELETED. Asserts each (op, dtype, Cpu)
10739    /// key resolves to the EXACT production wrapper fn-pointer, is
10740    /// contract-sourced (`kernel_source == "portable-cpu"`), caps stayed
10741    /// contiguous-only, and the audited bit-stable precision claim rode through.
10742    #[test]
10743    fn global_bindings_registers_affine_clamp_powi_family_from_contract() {
10744        let table = global_bindings();
10745        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10746
10747        // Single-input forward ops → key [dt, dt].
10748        let forward: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10749            (
10750                OpKind::Affine,
10751                [
10752                    affine_f32_cpu_wrapper,
10753                    affine_f64_cpu_wrapper,
10754                    affine_bf16_cpu_wrapper,
10755                    affine_f16_cpu_wrapper,
10756                ],
10757            ),
10758            (
10759                OpKind::ClampElementwise,
10760                [
10761                    clamp_elementwise_f32_cpu_wrapper,
10762                    clamp_f64_cpu_wrapper,
10763                    clamp_bf16_cpu_wrapper,
10764                    clamp_f16_cpu_wrapper,
10765                ],
10766            ),
10767            (
10768                OpKind::PowIElementwise,
10769                [
10770                    powi_elementwise_f32_cpu_wrapper,
10771                    powi_f64_cpu_wrapper,
10772                    powi_bf16_cpu_wrapper,
10773                    powi_f16_cpu_wrapper,
10774                ],
10775            ),
10776        ];
10777
10778        let mut checked = 0usize;
10779        for (op, wrappers) in forward {
10780            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10781                let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
10782                let entry = alts
10783                    .iter()
10784                    .find(|e| e.kernel as usize == *expected as usize)
10785                    .unwrap_or_else(|| {
10786                        panic!(
10787                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10788                             FROM the affine-clamp-powi contract in global_bindings() \
10789                             — found {} alternative(s) with sources {:?}",
10790                            alts.len(),
10791                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10792                        )
10793                    });
10794                assert_eq!(
10795                    entry.kernel_source, "portable-cpu",
10796                    "{op:?}/{dt:?}: family must be contract-sourced \
10797                     (kernel_source=\"portable-cpu\"); got {:?}",
10798                    entry.kernel_source,
10799                );
10800                assert!(
10801                    !entry.caps.strided_input,
10802                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10803                );
10804                assert!(
10805                    entry.precision.bit_stable_on_same_hardware,
10806                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
10807                );
10808                checked += 1;
10809            }
10810        }
10811
10812        // Two-input backward op → key [dt, dt, dt].
10813        let bw: [crate::kernel::KernelRef; 4] = [
10814            powi_backward_f32_cpu_wrapper,
10815            powi_backward_f64_cpu_wrapper,
10816            powi_backward_bf16_cpu_wrapper,
10817            powi_backward_f16_cpu_wrapper,
10818        ];
10819        for (dt, expected) in dts.iter().zip(bw.iter()) {
10820            let alts = table.lookup_alternatives(
10821                OpKind::PowIElementwiseBackward,
10822                &[*dt, *dt, *dt],
10823                BackendId::Cpu,
10824            );
10825            let entry = alts
10826                .iter()
10827                .find(|e| e.kernel as usize == *expected as usize)
10828                .unwrap_or_else(|| {
10829                    panic!(
10830                        "PowIElementwiseBackward/{dt:?}/Cpu: the production wrapper must \
10831                         be bound FROM the affine-clamp-powi contract in global_bindings() \
10832                         — found {} alternative(s) with sources {:?}",
10833                        alts.len(),
10834                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10835                    )
10836                });
10837            assert_eq!(
10838                entry.kernel_source, "portable-cpu",
10839                "PowIElementwiseBackward/{dt:?}: must be contract-sourced; got {:?}",
10840                entry.kernel_source,
10841            );
10842            assert!(
10843                !entry.caps.strided_input,
10844                "PowIElementwiseBackward/{dt:?}: caps preserved (contiguous-only)",
10845            );
10846            assert!(
10847                entry.precision.bit_stable_on_same_hardware,
10848                "PowIElementwiseBackward/{dt:?}: the audited bit-stable claim rode through",
10849            );
10850            checked += 1;
10851        }
10852
10853        assert_eq!(checked, 16, "3 forward ops × 4 dtypes + powi_backward × 4");
10854    }
10855
10856    /// FKC born-red gate for the CPU elementwise-unary family.
10857    /// `global_bindings()` registers the elementwise-unary family (22 ops × 4
10858    /// dtypes = 88 bindings) FROM ITS KERNEL CONTRACT
10859    /// (`fuel-dispatch/kernel-contracts/cpu/elementwise-unary.fkc.md`) via the §3.4
10860    /// multi-dtype fan-out (each per-op section declares a BASE `entry_point`
10861    /// that the importer expands to `<base>_<dtype>`) — the sole registration
10862    /// path, now that the hand-written `table.register(...)` calls are DELETED.
10863    /// Asserts each (op, dtype, Cpu) key resolves to the EXACT production
10864    /// wrapper fn-pointer, is contract-sourced (`kernel_source == "portable-cpu"`),
10865    /// caps stayed contiguous-only, and the audited bit-stable precision claim
10866    /// rode through. `gelu_tanh` (`GeluTanhElementwise`, base `gelu_tanh`) and `gelu`
10867    /// (`GeluElementwise`, base `gelu`) are kept DISTINCT.
10868    #[test]
10869    fn global_bindings_registers_unary_family_from_contract() {
10870        let table = global_bindings();
10871        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10872
10873        // (op, [f32, f64, bf16, f16] production wrappers) for all 22 ops.
10874        let families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10875            (
10876                OpKind::ReluElementwise,
10877                [
10878                    relu_elementwise_f32_cpu_wrapper,
10879                    relu_elementwise_f64_cpu_wrapper,
10880                    relu_elementwise_bf16_cpu_wrapper,
10881                    relu_elementwise_f16_cpu_wrapper,
10882                ],
10883            ),
10884            (
10885                OpKind::NegElementwise,
10886                [
10887                    neg_elementwise_f32_cpu_wrapper,
10888                    neg_elementwise_f64_cpu_wrapper,
10889                    neg_elementwise_bf16_cpu_wrapper,
10890                    neg_elementwise_f16_cpu_wrapper,
10891                ],
10892            ),
10893            (
10894                OpKind::SqrElementwise,
10895                [
10896                    sqr_elementwise_f32_cpu_wrapper,
10897                    sqr_elementwise_f64_cpu_wrapper,
10898                    sqr_elementwise_bf16_cpu_wrapper,
10899                    sqr_elementwise_f16_cpu_wrapper,
10900                ],
10901            ),
10902            (
10903                OpKind::SqrtElementwise,
10904                [
10905                    sqrt_elementwise_f32_cpu_wrapper,
10906                    sqrt_elementwise_f64_cpu_wrapper,
10907                    sqrt_elementwise_bf16_cpu_wrapper,
10908                    sqrt_elementwise_f16_cpu_wrapper,
10909                ],
10910            ),
10911            (
10912                OpKind::RecipElementwise,
10913                [
10914                    recip_elementwise_f32_cpu_wrapper,
10915                    recip_elementwise_f64_cpu_wrapper,
10916                    recip_elementwise_bf16_cpu_wrapper,
10917                    recip_elementwise_f16_cpu_wrapper,
10918                ],
10919            ),
10920            (
10921                OpKind::AbsElementwise,
10922                [
10923                    abs_elementwise_f32_cpu_wrapper,
10924                    abs_elementwise_f64_cpu_wrapper,
10925                    abs_elementwise_bf16_cpu_wrapper,
10926                    abs_elementwise_f16_cpu_wrapper,
10927                ],
10928            ),
10929            (
10930                OpKind::TanhElementwise,
10931                [
10932                    tanh_elementwise_f32_cpu_wrapper,
10933                    tanh_elementwise_f64_cpu_wrapper,
10934                    tanh_elementwise_bf16_cpu_wrapper,
10935                    tanh_elementwise_f16_cpu_wrapper,
10936                ],
10937            ),
10938            (
10939                OpKind::ExpElementwise,
10940                [
10941                    exp_elementwise_f32_cpu_wrapper,
10942                    exp_elementwise_f64_cpu_wrapper,
10943                    exp_elementwise_bf16_cpu_wrapper,
10944                    exp_elementwise_f16_cpu_wrapper,
10945                ],
10946            ),
10947            (
10948                OpKind::LogElementwise,
10949                [
10950                    log_elementwise_f32_cpu_wrapper,
10951                    log_elementwise_f64_cpu_wrapper,
10952                    log_elementwise_bf16_cpu_wrapper,
10953                    log_elementwise_f16_cpu_wrapper,
10954                ],
10955            ),
10956            (
10957                OpKind::SinElementwise,
10958                [
10959                    sin_elementwise_f32_cpu_wrapper,
10960                    sin_elementwise_f64_cpu_wrapper,
10961                    sin_elementwise_bf16_cpu_wrapper,
10962                    sin_elementwise_f16_cpu_wrapper,
10963                ],
10964            ),
10965            (
10966                OpKind::CosElementwise,
10967                [
10968                    cos_elementwise_f32_cpu_wrapper,
10969                    cos_elementwise_f64_cpu_wrapper,
10970                    cos_elementwise_bf16_cpu_wrapper,
10971                    cos_elementwise_f16_cpu_wrapper,
10972                ],
10973            ),
10974            (
10975                OpKind::SigmoidElementwise,
10976                [
10977                    sigmoid_elementwise_f32_cpu_wrapper,
10978                    sigmoid_elementwise_f64_cpu_wrapper,
10979                    sigmoid_elementwise_bf16_cpu_wrapper,
10980                    sigmoid_elementwise_f16_cpu_wrapper,
10981                ],
10982            ),
10983            (
10984                OpKind::SiluElementwise,
10985                [
10986                    silu_elementwise_f32_cpu_wrapper,
10987                    silu_elementwise_f64_cpu_wrapper,
10988                    silu_elementwise_bf16_cpu_wrapper,
10989                    silu_elementwise_f16_cpu_wrapper,
10990                ],
10991            ),
10992            (
10993                OpKind::StepElementwise,
10994                [
10995                    step_elementwise_f32_cpu_wrapper,
10996                    step_elementwise_f64_cpu_wrapper,
10997                    step_elementwise_bf16_cpu_wrapper,
10998                    step_elementwise_f16_cpu_wrapper,
10999                ],
11000            ),
11001            (
11002                OpKind::GeluTanhElementwise,
11003                [
11004                    gelu_elementwise_f32_cpu_wrapper,
11005                    gelu_elementwise_f64_cpu_wrapper,
11006                    gelu_elementwise_bf16_cpu_wrapper,
11007                    gelu_elementwise_f16_cpu_wrapper,
11008                ],
11009            ),
11010            (
11011                OpKind::FloorElementwise,
11012                [
11013                    floor_elementwise_f32_cpu_wrapper,
11014                    floor_elementwise_f64_cpu_wrapper,
11015                    floor_elementwise_bf16_cpu_wrapper,
11016                    floor_elementwise_f16_cpu_wrapper,
11017                ],
11018            ),
11019            (
11020                OpKind::CeilElementwise,
11021                [
11022                    ceil_elementwise_f32_cpu_wrapper,
11023                    ceil_elementwise_f64_cpu_wrapper,
11024                    ceil_elementwise_bf16_cpu_wrapper,
11025                    ceil_elementwise_f16_cpu_wrapper,
11026                ],
11027            ),
11028            (
11029                OpKind::RoundElementwise,
11030                [
11031                    round_elementwise_f32_cpu_wrapper,
11032                    round_elementwise_f64_cpu_wrapper,
11033                    round_elementwise_bf16_cpu_wrapper,
11034                    round_elementwise_f16_cpu_wrapper,
11035                ],
11036            ),
11037            (
11038                OpKind::SignElementwise,
11039                [
11040                    sign_elementwise_f32_cpu_wrapper,
11041                    sign_elementwise_f64_cpu_wrapper,
11042                    sign_elementwise_bf16_cpu_wrapper,
11043                    sign_elementwise_f16_cpu_wrapper,
11044                ],
11045            ),
11046            (
11047                OpKind::ErfElementwise,
11048                [
11049                    erf_elementwise_f32_cpu_wrapper,
11050                    erf_elementwise_f64_cpu_wrapper,
11051                    erf_elementwise_bf16_cpu_wrapper,
11052                    erf_elementwise_f16_cpu_wrapper,
11053                ],
11054            ),
11055            (
11056                OpKind::GeluElementwise,
11057                [
11058                    gelu_erf_elementwise_f32_cpu_wrapper,
11059                    gelu_erf_elementwise_f64_cpu_wrapper,
11060                    gelu_erf_elementwise_bf16_cpu_wrapper,
11061                    gelu_erf_elementwise_f16_cpu_wrapper,
11062                ],
11063            ),
11064            (
11065                OpKind::RsqrtElementwise,
11066                [
11067                    rsqrt_elementwise_f32_cpu_wrapper,
11068                    rsqrt_elementwise_f64_cpu_wrapper,
11069                    rsqrt_elementwise_bf16_cpu_wrapper,
11070                    rsqrt_elementwise_f16_cpu_wrapper,
11071                ],
11072            ),
11073        ];
11074
11075        let mut checked = 0usize;
11076        for (op, wrappers) in families {
11077            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11078                let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
11079                let entry = alts
11080                    .iter()
11081                    .find(|e| e.kernel as usize == *expected as usize)
11082                    .unwrap_or_else(|| {
11083                        panic!(
11084                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11085                             FROM the elementwise-unary contract in global_bindings() \
11086                             — found {} alternative(s) with sources {:?}",
11087                            alts.len(),
11088                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11089                        )
11090                    });
11091                assert_eq!(
11092                    entry.kernel_source, "portable-cpu",
11093                    "{op:?}/{dt:?}: unary family must be contract-sourced \
11094                     (kernel_source=\"portable-cpu\"); got {:?}",
11095                    entry.kernel_source,
11096                );
11097                assert!(
11098                    !entry.caps.strided_input,
11099                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11100                );
11101                assert!(
11102                    entry.precision.bit_stable_on_same_hardware,
11103                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11104                );
11105                checked += 1;
11106            }
11107        }
11108        assert_eq!(checked, 88, "all 22 ops × 4 dtypes checked");
11109    }
11110
11111    /// FKC production consumer (born-red gate). `global_bindings()` registers
11112    /// the CPU compare + where family FROM ITS KERNEL CONTRACT
11113    /// (`fuel-dispatch/kernel-contracts/cpu/compare-where.fkc.md`) — the sole path now
11114    /// that the hand-written `table.register(...)` calls for this family are
11115    /// DELETED.
11116    ///
11117    /// Two key shapes, and getting them right IS the point of the test:
11118    ///  - COMPARE (6 ops × 4 dtypes = 24): the U8-mask operand-dtype list
11119    ///    `[T, T, U8]` (`return.out` is always `fixed(U8)`), NOT `[T, T, T]`.
11120    ///  - WHERE (1 op × 4 dtypes = 4): the ternary-select list `[U8, T, T, T]`
11121    ///    (cond U8 + a/b/out share T). `where` exercises BOTH the §3.4
11122    ///    multi-dtype fan-out (one contract section → 4 per-dtype bindings) AND
11123    ///    the `passthrough(a)` fix (output mirrors `a`=T, not the U8 cond).
11124    ///
11125    /// For each key: resolves to the EXACT production wrapper fn-pointer and
11126    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11127    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11128    /// goes red until the import is wired) — with caps contiguous and the
11129    /// audited bit-stable precision riding through.
11130    #[test]
11131    fn global_bindings_registers_compare_where_family_from_contract() {
11132        let table = global_bindings();
11133        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11134
11135        // -- COMPARE: 6 ops × 4 dtypes, key [T, T, BOOL] (GAP-168c) --
11136        let compare_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11137            (
11138                OpKind::EqualElementwise,
11139                [
11140                    eq_elementwise_f32_cpu_wrapper,
11141                    eq_elementwise_f64_cpu_wrapper,
11142                    eq_elementwise_bf16_cpu_wrapper,
11143                    eq_elementwise_f16_cpu_wrapper,
11144                ],
11145            ),
11146            (
11147                OpKind::NotEqualElementwise,
11148                [
11149                    ne_elementwise_f32_cpu_wrapper,
11150                    ne_elementwise_f64_cpu_wrapper,
11151                    ne_elementwise_bf16_cpu_wrapper,
11152                    ne_elementwise_f16_cpu_wrapper,
11153                ],
11154            ),
11155            (
11156                OpKind::LessElementwise,
11157                [
11158                    lt_elementwise_f32_cpu_wrapper,
11159                    lt_elementwise_f64_cpu_wrapper,
11160                    lt_elementwise_bf16_cpu_wrapper,
11161                    lt_elementwise_f16_cpu_wrapper,
11162                ],
11163            ),
11164            (
11165                OpKind::LessEqualElementwise,
11166                [
11167                    le_elementwise_f32_cpu_wrapper,
11168                    le_elementwise_f64_cpu_wrapper,
11169                    le_elementwise_bf16_cpu_wrapper,
11170                    le_elementwise_f16_cpu_wrapper,
11171                ],
11172            ),
11173            (
11174                OpKind::GreaterElementwise,
11175                [
11176                    gt_elementwise_f32_cpu_wrapper,
11177                    gt_elementwise_f64_cpu_wrapper,
11178                    gt_elementwise_bf16_cpu_wrapper,
11179                    gt_elementwise_f16_cpu_wrapper,
11180                ],
11181            ),
11182            (
11183                OpKind::GreaterEqualElementwise,
11184                [
11185                    ge_elementwise_f32_cpu_wrapper,
11186                    ge_elementwise_f64_cpu_wrapper,
11187                    ge_elementwise_bf16_cpu_wrapper,
11188                    ge_elementwise_f16_cpu_wrapper,
11189                ],
11190            ),
11191        ];
11192
11193        let mut checked = 0usize;
11194        for (op, wrappers) in compare_families {
11195            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11196                // Bool-mask operand-dtype list: [T, T, Bool] — NOT [T, T, T].
11197                // GAP-168(c): comparisons key on Bool, not the retired U8 mask.
11198                let alts = table.lookup_alternatives(*op, &[*dt, *dt, DType::Bool], BackendId::Cpu);
11199                let entry = alts
11200                    .iter()
11201                    .find(|e| e.kernel as usize == *expected as usize)
11202                    .unwrap_or_else(|| {
11203                        panic!(
11204                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11205                             FROM the compare-where contract in global_bindings() \
11206                             — found {} alternative(s) with sources {:?}",
11207                            alts.len(),
11208                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11209                        )
11210                    });
11211                assert_eq!(
11212                    entry.kernel_source, "portable-cpu",
11213                    "{op:?}/{dt:?}: compare family must be contract-sourced \
11214                     (kernel_source=\"portable-cpu\"); got {:?}",
11215                    entry.kernel_source,
11216                );
11217                assert!(
11218                    !entry.caps.strided_input,
11219                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11220                );
11221                assert!(
11222                    entry.precision.bit_stable_on_same_hardware,
11223                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11224                );
11225                checked += 1;
11226            }
11227        }
11228
11229        // -- WHERE: 1 op × 4 dtypes, key [U8, T, T, T] (fan-out + passthrough(a)) --
11230        let where_wrappers: [crate::kernel::KernelRef; 4] = [
11231            where_f32_cpu_wrapper,
11232            where_f64_cpu_wrapper,
11233            where_bf16_cpu_wrapper,
11234            where_f16_cpu_wrapper,
11235        ];
11236        for (dt, expected) in dts.iter().zip(where_wrappers.iter()) {
11237            // Ternary-select list: [U8 cond, T a, T b, T out].
11238            let alts = table.lookup_alternatives(
11239                OpKind::Where,
11240                &[DType::Bool, *dt, *dt, *dt],
11241                BackendId::Cpu,
11242            );
11243            let entry = alts
11244                .iter()
11245                .find(|e| e.kernel as usize == *expected as usize)
11246                .unwrap_or_else(|| {
11247                    panic!(
11248                        "Where/{dt:?}/Cpu: the production wrapper must be bound FROM \
11249                         the compare-where contract (where fans to [U8,T,T,T]) in \
11250                         global_bindings() — found {} alternative(s) with sources {:?}",
11251                        alts.len(),
11252                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11253                    )
11254                });
11255            assert_eq!(
11256                entry.kernel_source, "portable-cpu",
11257                "Where/{dt:?}: where must be contract-sourced \
11258                 (kernel_source=\"portable-cpu\"); got {:?}",
11259                entry.kernel_source,
11260            );
11261            assert!(
11262                !entry.caps.strided_input,
11263                "Where/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11264            );
11265            checked += 1;
11266        }
11267
11268        assert_eq!(checked, 28, "24 compare (6×4) + 4 where keys checked");
11269    }
11270
11271    /// FKC production consumer (born-red gate). `global_bindings()` registers
11272    /// the CPU per-axis reduce family (Sum/Mean/Max/Min × F32/F64/BF16/F16 = 16)
11273    /// FROM ITS KERNEL CONTRACT (`fuel-dispatch/kernel-contracts/cpu/reduce.fkc.md`) — the
11274    /// sole path now that the hand-written `table.register(...)` calls for this
11275    /// family are DELETED.
11276    ///
11277    /// The binding key is the `[T, T]` operand-dtype list (input +
11278    /// `passthrough(input)` output; the reduce axes + keepdim ride in
11279    /// `OpParams::Reduce`, NOT the dtype-list). Each per-(op,dtype) section
11280    /// carries a SPECIFIC single-dtype `entry_point` resolved AS-IS (no fan-out).
11281    ///
11282    /// For each key: resolves to the EXACT production wrapper fn-pointer and
11283    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11284    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11285    /// goes red until the import is wired) — with caps contiguous and the audited
11286    /// bit-stable precision riding through.
11287    #[test]
11288    fn global_bindings_registers_reduce_family_from_contract() {
11289        let table = global_bindings();
11290        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11291
11292        // Sum/Mean/Max/Min × {f32,f64,bf16,f16}, key [T, T].
11293        let reduce_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11294            (
11295                OpKind::SumReduce,
11296                [
11297                    sum_reduce_f32_cpu_wrapper,
11298                    sum_reduce_f64_cpu_wrapper,
11299                    sum_reduce_bf16_cpu_wrapper,
11300                    sum_reduce_f16_cpu_wrapper,
11301                ],
11302            ),
11303            (
11304                OpKind::MeanReduce,
11305                [
11306                    mean_reduce_f32_cpu_wrapper,
11307                    mean_reduce_f64_cpu_wrapper,
11308                    mean_reduce_bf16_cpu_wrapper,
11309                    mean_reduce_f16_cpu_wrapper,
11310                ],
11311            ),
11312            (
11313                OpKind::MaxReduce,
11314                [
11315                    max_reduce_f32_cpu_wrapper,
11316                    max_reduce_f64_cpu_wrapper,
11317                    max_reduce_bf16_cpu_wrapper,
11318                    max_reduce_f16_cpu_wrapper,
11319                ],
11320            ),
11321            (
11322                OpKind::MinReduce,
11323                [
11324                    min_reduce_f32_cpu_wrapper,
11325                    min_reduce_f64_cpu_wrapper,
11326                    min_reduce_bf16_cpu_wrapper,
11327                    min_reduce_f16_cpu_wrapper,
11328                ],
11329            ),
11330        ];
11331
11332        let mut checked = 0usize;
11333        for (op, wrappers) in reduce_families {
11334            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11335                // [T, T] operand-dtype list (input + passthrough output).
11336                let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
11337                let entry = alts
11338                    .iter()
11339                    .find(|e| e.kernel as usize == *expected as usize)
11340                    .unwrap_or_else(|| {
11341                        panic!(
11342                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11343                             FROM the reduce contract in global_bindings() \
11344                             — found {} alternative(s) with sources {:?}",
11345                            alts.len(),
11346                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11347                        )
11348                    });
11349                assert_eq!(
11350                    entry.kernel_source, "portable-cpu",
11351                    "{op:?}/{dt:?}: reduce family must be contract-sourced \
11352                     (kernel_source=\"portable-cpu\"); got {:?}",
11353                    entry.kernel_source,
11354                );
11355                assert!(
11356                    !entry.caps.strided_input,
11357                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11358                );
11359                assert!(
11360                    entry.precision.bit_stable_on_same_hardware,
11361                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11362                );
11363                checked += 1;
11364            }
11365        }
11366        assert_eq!(checked, 16, "4 ops × 4 dtypes checked");
11367    }
11368
11369    /// Born-red guard for the CPU reduce-to family FKC migration. Mirrors the
11370    /// reduce-family test across the two key shapes this family carries:
11371    /// `ReduceSumTo` / `ReduceMaxTo` are single input → `passthrough` output,
11372    /// key `[T, T]`; `ReduceMaxToBackward` is two inputs (x, upstream) +
11373    /// `passthrough(x)` output, key `[T, T, T]`. Each × {f32,f64,bf16,f16}.
11374    ///
11375    /// For each key: resolves to the EXACT production wrapper fn-pointer with
11376    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11377    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11378    /// goes red until the import is wired) — caps contiguous, and the audited
11379    /// bit-stable precision riding through.
11380    #[test]
11381    fn global_bindings_registers_reduce_to_family_from_contract() {
11382        let table = global_bindings();
11383        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11384
11385        // ReduceSumTo / ReduceMaxTo — single input + passthrough output, key [T, T].
11386        let unary_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11387            (
11388                OpKind::ReduceSumTo,
11389                [
11390                    reduce_sum_to_f32_cpu_wrapper,
11391                    reduce_sum_to_f64_cpu_wrapper,
11392                    reduce_sum_to_bf16_cpu_wrapper,
11393                    reduce_sum_to_f16_cpu_wrapper,
11394                ],
11395            ),
11396            (
11397                OpKind::ReduceMaxTo,
11398                [
11399                    reduce_max_to_f32_cpu_wrapper,
11400                    reduce_max_to_f64_cpu_wrapper,
11401                    reduce_max_to_bf16_cpu_wrapper,
11402                    reduce_max_to_f16_cpu_wrapper,
11403                ],
11404            ),
11405        ];
11406        // ReduceMaxToBackward — two inputs (x, upstream) + passthrough(x)
11407        // output, key [T, T, T].
11408        let backward_family: (OpKind, [crate::kernel::KernelRef; 4]) = (
11409            OpKind::ReduceMaxToBackward,
11410            [
11411                reduce_max_to_backward_f32_cpu_wrapper,
11412                reduce_max_to_backward_f64_cpu_wrapper,
11413                reduce_max_to_backward_bf16_cpu_wrapper,
11414                reduce_max_to_backward_f16_cpu_wrapper,
11415            ],
11416        );
11417
11418        // Assert one (op, key, expected-wrapper) is bound FROM the contract.
11419        let assert_contract_bound =
11420            |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef| {
11421                let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11422                let entry = alts
11423                    .iter()
11424                    .find(|e| e.kernel as usize == expected as usize)
11425                    .unwrap_or_else(|| {
11426                        panic!(
11427                            "{op:?}/{key:?}/Cpu: the production wrapper must be bound \
11428                             FROM the reduce-to contract in global_bindings() \
11429                             — found {} alternative(s) with sources {:?}",
11430                            alts.len(),
11431                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11432                        )
11433                    });
11434                assert_eq!(
11435                    entry.kernel_source, "portable-cpu",
11436                    "{op:?}/{key:?}: reduce-to family must be contract-sourced \
11437                     (kernel_source=\"portable-cpu\"); got {:?}",
11438                    entry.kernel_source,
11439                );
11440                assert!(
11441                    !entry.caps.strided_input,
11442                    "{op:?}/{key:?}: caps preserved (contiguous-only, strided_input=false)",
11443                );
11444                assert!(
11445                    entry.precision.bit_stable_on_same_hardware,
11446                    "{op:?}/{key:?}: the contract's audited bit-stable claim rode through",
11447                );
11448            };
11449
11450        let mut checked = 0usize;
11451        for (op, wrappers) in unary_families {
11452            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11453                assert_contract_bound(*op, &[*dt, *dt], *expected);
11454                checked += 1;
11455            }
11456        }
11457        let (op, wrappers) = backward_family;
11458        for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11459            assert_contract_bound(op, &[*dt, *dt, *dt], *expected);
11460            checked += 1;
11461        }
11462        assert_eq!(checked, 12, "3 ops × 4 dtypes checked");
11463    }
11464
11465    /// Born-red guard for the CPU last-dim NORM (forward) family FKC migration.
11466    /// Softmax / LogSoftmax / RmsNorm / LayerNorm are each a SINGLE input →
11467    /// `passthrough` output, key `[T, T]` — the RMS/LayerNorm kernels carry NO
11468    /// affine gamma/beta operand (bare normalization), and outer_count/last_dim/
11469    /// eps ride in `OpParams`, so the key stays `[T, T]` (not a 3- or 4-operand
11470    /// key). Each × {f32,f64,bf16,f16} = 16 bindings.
11471    ///
11472    /// For each key: resolves to the EXACT production wrapper fn-pointer with
11473    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11474    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11475    /// goes red until the import is wired) — caps contiguous, and the audited
11476    /// bit-stable precision riding through.
11477    #[test]
11478    fn global_bindings_registers_norm_family_from_contract() {
11479        let table = global_bindings();
11480        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11481
11482        // Softmax / LogSoftmax / RmsNorm / LayerNorm — single input +
11483        // passthrough output, key [T, T]. Wrapper order matches `dts`.
11484        let norm_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11485            (
11486                OpKind::SoftmaxLastDim,
11487                [
11488                    softmax_last_dim_f32_cpu_wrapper,
11489                    softmax_last_dim_f64_cpu_wrapper,
11490                    softmax_last_dim_bf16_cpu_wrapper,
11491                    softmax_last_dim_f16_cpu_wrapper,
11492                ],
11493            ),
11494            (
11495                OpKind::LogSoftmaxLastDim,
11496                [
11497                    log_softmax_f32_cpu_wrapper,
11498                    log_softmax_f64_cpu_wrapper,
11499                    log_softmax_bf16_cpu_wrapper,
11500                    log_softmax_f16_cpu_wrapper,
11501                ],
11502            ),
11503            (
11504                OpKind::RmsNormLastDim,
11505                [
11506                    rms_norm_last_dim_f32_cpu_wrapper,
11507                    rms_norm_last_dim_f64_cpu_wrapper,
11508                    rms_norm_last_dim_bf16_cpu_wrapper,
11509                    rms_norm_last_dim_f16_cpu_wrapper,
11510                ],
11511            ),
11512            (
11513                OpKind::LayerNormLastDim,
11514                [
11515                    layer_norm_last_dim_f32_cpu_wrapper,
11516                    layer_norm_last_dim_f64_cpu_wrapper,
11517                    layer_norm_last_dim_bf16_cpu_wrapper,
11518                    layer_norm_last_dim_f16_cpu_wrapper,
11519                ],
11520            ),
11521        ];
11522
11523        let mut checked = 0usize;
11524        for (op, wrappers) in norm_families {
11525            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11526                // [T, T] operand-dtype list (input + passthrough output).
11527                let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
11528                let entry = alts
11529                    .iter()
11530                    .find(|e| e.kernel as usize == *expected as usize)
11531                    .unwrap_or_else(|| {
11532                        panic!(
11533                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11534                             FROM the norm contract in global_bindings() \
11535                             — found {} alternative(s) with sources {:?}",
11536                            alts.len(),
11537                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11538                        )
11539                    });
11540                assert_eq!(
11541                    entry.kernel_source, "portable-cpu",
11542                    "{op:?}/{dt:?}: norm family must be contract-sourced \
11543                     (kernel_source=\"portable-cpu\"); got {:?}",
11544                    entry.kernel_source,
11545                );
11546                assert!(
11547                    !entry.caps.strided_input,
11548                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11549                );
11550                assert!(
11551                    entry.precision.bit_stable_on_same_hardware,
11552                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11553                );
11554                checked += 1;
11555            }
11556        }
11557        assert_eq!(checked, 16, "4 ops × 4 dtypes checked");
11558    }
11559
11560    /// Born-red guard for the CPU last-dim NORM-BACKWARD family FKC migration.
11561    /// Softmax / LogSoftmax / LayerNorm / RmsNorm backward are each TWO inputs
11562    /// (the forward output-or-input `y`/`x` + the upstream gradient `g`) → ONE
11563    /// `passthrough` output — the BARE backward (no affine gamma/beta grad
11564    /// operand and no saved-stats operand; the norm kernels recompute mean/var
11565    /// or mean-square from `x` + `eps`), so the binding key is `[T, T, T]`
11566    /// (in, in, out) and outer_count / last_dim / eps ride in `OpParams`, NOT
11567    /// the dtype-list. Each × {f32,f64,bf16,f16} = 16 bindings.
11568    ///
11569    /// For each key: resolves to the EXACT production wrapper fn-pointer with
11570    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11571    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11572    /// goes red until the import is wired) — caps contiguous, and the audited
11573    /// bit-stable precision riding through.
11574    #[test]
11575    fn global_bindings_registers_norm_backward_family_from_contract() {
11576        let table = global_bindings();
11577        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11578
11579        // Softmax / LogSoftmax / LayerNorm / RmsNorm backward — two inputs
11580        // (y/x, g) + passthrough output, key [T, T, T]. Wrapper order matches
11581        // `dts`. (LogSoftmax's wrapper fn-name `log_softmax_backward_*` differs
11582        // from its `log_softmax_last_dim_backward_*` contract symbol — the same
11583        // fn-vs-symbol split as the forward `log_softmax` case.)
11584        let backward_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11585            (
11586                OpKind::SoftmaxLastDimBackward,
11587                [
11588                    softmax_last_dim_backward_f32_cpu_wrapper,
11589                    softmax_last_dim_backward_f64_cpu_wrapper,
11590                    softmax_last_dim_backward_bf16_cpu_wrapper,
11591                    softmax_last_dim_backward_f16_cpu_wrapper,
11592                ],
11593            ),
11594            (
11595                OpKind::LogSoftmaxLastDimBackward,
11596                [
11597                    log_softmax_backward_f32_cpu_wrapper,
11598                    log_softmax_backward_f64_cpu_wrapper,
11599                    log_softmax_backward_bf16_cpu_wrapper,
11600                    log_softmax_backward_f16_cpu_wrapper,
11601                ],
11602            ),
11603            (
11604                OpKind::LayerNormLastDimBackward,
11605                [
11606                    layer_norm_last_dim_backward_f32_cpu_wrapper,
11607                    layer_norm_last_dim_backward_f64_cpu_wrapper,
11608                    layer_norm_last_dim_backward_bf16_cpu_wrapper,
11609                    layer_norm_last_dim_backward_f16_cpu_wrapper,
11610                ],
11611            ),
11612            (
11613                OpKind::RmsNormLastDimBackward,
11614                [
11615                    rms_norm_last_dim_backward_f32_cpu_wrapper,
11616                    rms_norm_last_dim_backward_f64_cpu_wrapper,
11617                    rms_norm_last_dim_backward_bf16_cpu_wrapper,
11618                    rms_norm_last_dim_backward_f16_cpu_wrapper,
11619                ],
11620            ),
11621        ];
11622
11623        let mut checked = 0usize;
11624        for (op, wrappers) in backward_families {
11625            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11626                // [T, T, T] operand-dtype list (two inputs + passthrough output).
11627                let alts = table.lookup_alternatives(*op, &[*dt, *dt, *dt], BackendId::Cpu);
11628                let entry = alts
11629                    .iter()
11630                    .find(|e| e.kernel as usize == *expected as usize)
11631                    .unwrap_or_else(|| {
11632                        panic!(
11633                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11634                             FROM the norm-backward contract in global_bindings() \
11635                             — found {} alternative(s) with sources {:?}",
11636                            alts.len(),
11637                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11638                        )
11639                    });
11640                assert_eq!(
11641                    entry.kernel_source, "portable-cpu",
11642                    "{op:?}/{dt:?}: norm-backward family must be contract-sourced \
11643                     (kernel_source=\"portable-cpu\"); got {:?}",
11644                    entry.kernel_source,
11645                );
11646                assert!(
11647                    !entry.caps.strided_input,
11648                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11649                );
11650                assert!(
11651                    entry.precision.bit_stable_on_same_hardware,
11652                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11653                );
11654                checked += 1;
11655            }
11656        }
11657        assert_eq!(checked, 16, "4 ops × 4 dtypes checked");
11658    }
11659
11660    /// RoPE (rotary position embedding) is ONE primitive op (`OpKind::Rope`)
11661    /// monomorphized over the four float dtypes {F32, F64, BF16, F16}. Each
11662    /// dtype is a distinct single-dtype contract section (`## rope_f32`, …) with
11663    /// a concrete `entry_point` (`fuel_cpu_backend::byte_kernels::rope_f32`), so
11664    /// none of them fan — the importer resolves each declared symbol AS-IS. RoPE
11665    /// takes THREE inputs (`x` + the precomputed `cos`/`sin` tables, all one
11666    /// dtype; the tables broadcast over the outer axis by re-indexing, NOT a
11667    /// stride-0 view) and writes ONE `passthrough(x)` output, so the binding key
11668    /// is `[T, T, T, T]` (x, cos, sin, out); outer_count / seq / head_dim ride in
11669    /// `OpParams::Rope`, NOT the dtype-list — identical to the deleted
11670    /// `rope_dts(t)` regs.
11671    ///
11672    /// For each key: resolves to the EXACT production wrapper fn-pointer with
11673    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11674    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11675    /// goes red until the import is wired) — caps contiguous, and the audited
11676    /// bit-stable precision riding through.
11677    #[test]
11678    fn global_bindings_registers_rope_family_from_contract() {
11679        let table = global_bindings();
11680        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11681        // Wrapper order matches `dts`.
11682        let expected_wrappers: [crate::kernel::KernelRef; 4] = [
11683            rope_f32_cpu_wrapper,
11684            rope_f64_cpu_wrapper,
11685            rope_bf16_cpu_wrapper,
11686            rope_f16_cpu_wrapper,
11687        ];
11688
11689        let mut checked = 0usize;
11690        for (dt, expected) in dts.iter().zip(expected_wrappers.iter()) {
11691            // [T, T, T, T] operand-dtype list (x, cos, sin + passthrough output).
11692            let alts =
11693                table.lookup_alternatives(OpKind::Rope, &[*dt, *dt, *dt, *dt], BackendId::Cpu);
11694            let entry = alts
11695                .iter()
11696                .find(|e| e.kernel as usize == *expected as usize)
11697                .unwrap_or_else(|| {
11698                    panic!(
11699                        "Rope/{dt:?}/Cpu: the production wrapper must be bound \
11700                         FROM the rope contract in global_bindings() \
11701                         — found {} alternative(s) with sources {:?}",
11702                        alts.len(),
11703                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11704                    )
11705                });
11706            assert_eq!(
11707                entry.kernel_source, "portable-cpu",
11708                "Rope/{dt:?}: rope family must be contract-sourced \
11709                 (kernel_source=\"portable-cpu\"); got {:?}",
11710                entry.kernel_source,
11711            );
11712            assert!(
11713                !entry.caps.strided_input,
11714                "Rope/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11715            );
11716            assert!(
11717                entry.precision.bit_stable_on_same_hardware,
11718                "Rope/{dt:?}: the contract's audited bit-stable claim rode through",
11719            );
11720            checked += 1;
11721        }
11722        assert_eq!(checked, 4, "1 op × 4 dtypes checked");
11723    }
11724
11725    /// Gate for the CPU SSM / Mamba family FULLY migrated to FKC-contract
11726    /// registration. The WHOLE family — FusedSoftmaxCrossEntropy (key
11727    /// `[T, I64, F32]` — logits T + I64 targets → fixed(F32) output),
11728    /// CausalConv1d (key `[T, T, T, T]` — x, weight, bias + passthrough(x)
11729    /// output), and the two SCAN ops SelectiveScan / SsdChunkScan (key `[T; 6]`
11730    /// — 5 inputs + the ONE bundled output slot), 4 ops × 4 dtypes = 16
11731    /// bindings — is IMPORTED from `fuel-dispatch/kernel-contracts/cpu/ssm.fkc.md`.
11732    ///
11733    /// The scans' `[T; 6]` keys are now contract-sourced too: their sections
11734    /// return a `return.bundle` multi-output (Option C, one buffer
11735    /// `[y ; last_state]`), and the importer's key-builder appends the bundle's
11736    /// PRIMARY-slot dtype (`passthrough(u)` / `passthrough(x)` → T) to the key
11737    /// tail — byte-for-byte the deleted hand-written `&[dt; 6]` regs.
11738    ///
11739    /// For each of the 16 keys: resolves to the EXACT production wrapper
11740    /// fn-pointer with `kernel_source == "portable-cpu"` (the contract
11741    /// provenance tag; the deleted hand-written path stamped `""`), caps
11742    /// contiguous, and the contract's bit-stable precision riding through.
11743    #[test]
11744    fn global_bindings_registers_ssm_family_from_contract() {
11745        let table = global_bindings();
11746        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11747
11748        // Assert one (op, key) binds `expected` FROM the contract (portable-cpu,
11749        // contiguous caps, bit-stable precision). `key` is the full binding key.
11750        let check = |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
11751            let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11752            let entry = alts
11753                .iter()
11754                .find(|e| e.kernel as usize == expected as usize)
11755                .unwrap_or_else(|| {
11756                    panic!(
11757                        "{label}/Cpu (key {key:?}): the production wrapper must be bound \
11758                         FROM the ssm contract in global_bindings() — found {} \
11759                         alternative(s) with sources {:?}",
11760                        alts.len(),
11761                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11762                    )
11763                });
11764            assert_eq!(
11765                entry.kernel_source, "portable-cpu",
11766                "{label}: family must be contract-sourced (kernel_source=\"portable-cpu\"); \
11767                 got {:?}",
11768                entry.kernel_source,
11769            );
11770            assert!(
11771                !entry.caps.strided_input,
11772                "{label}: caps preserved (contiguous-only)"
11773            );
11774            assert!(
11775                entry.precision.bit_stable_on_same_hardware,
11776                "{label}: contract's bit-stable claim rode through",
11777            );
11778        };
11779
11780        // Per-op wrappers, indexed to match `dts` order.
11781        let fsce: [crate::kernel::KernelRef; 4] = [
11782            fused_softmax_cross_entropy_f32_cpu_wrapper,
11783            fused_softmax_cross_entropy_f64_cpu_wrapper,
11784            fused_softmax_cross_entropy_bf16_cpu_wrapper,
11785            fused_softmax_cross_entropy_f16_cpu_wrapper,
11786        ];
11787        let conv: [crate::kernel::KernelRef; 4] = [
11788            causal_conv1d_f32_cpu_wrapper,
11789            causal_conv1d_f64_cpu_wrapper,
11790            causal_conv1d_bf16_cpu_wrapper,
11791            causal_conv1d_f16_cpu_wrapper,
11792        ];
11793        let sscan: [crate::kernel::KernelRef; 4] = [
11794            selective_scan_f32_cpu_wrapper,
11795            selective_scan_f64_cpu_wrapper,
11796            selective_scan_bf16_cpu_wrapper,
11797            selective_scan_f16_cpu_wrapper,
11798        ];
11799        let ssd: [crate::kernel::KernelRef; 4] = [
11800            ssd_chunk_scan_f32_cpu_wrapper,
11801            ssd_chunk_scan_f64_cpu_wrapper,
11802            ssd_chunk_scan_bf16_cpu_wrapper,
11803            ssd_chunk_scan_f16_cpu_wrapper,
11804        ];
11805
11806        let mut checked = 0usize;
11807        for (i, dt) in dts.iter().enumerate() {
11808            // FSCE: [logits T, targets I64, out F32].
11809            check(
11810                OpKind::FusedSoftmaxCrossEntropy,
11811                &[*dt, DType::I64, DType::F32],
11812                fsce[i],
11813                "FusedSoftmaxCrossEntropy",
11814            );
11815            // CausalConv1d: [x, weight, bias, out] all T.
11816            check(OpKind::CausalConv1d, &[*dt; 4], conv[i], "CausalConv1d");
11817            // SelectiveScan: [u, delta, a, b, c, out] = [T; 6] (5 inputs + the
11818            // ONE bundled output slot, `passthrough(u)` → T).
11819            check(OpKind::SelectiveScan, &[*dt; 6], sscan[i], "SelectiveScan");
11820            // SsdChunkScan: [x, dt, a, b, c, out] = [T; 6] (5 inputs + the ONE
11821            // bundled output slot, `passthrough(x)` → T).
11822            check(OpKind::SsdChunkScan, &[*dt; 6], ssd[i], "SsdChunkScan");
11823
11824            checked += 1;
11825        }
11826        assert_eq!(
11827            checked, 4,
11828            "4 ops × 4 dtypes checked (16 contract-sourced bindings)"
11829        );
11830    }
11831
11832    /// Gate for the CPU conv family FULLY migrated to FKC-contract registration.
11833    /// The whole family — BOTH the no-bias keys (`[T, T, T]` — x, weight + out)
11834    /// AND the with-bias keys (`[T, T, T, T]` — x, weight, bias + passthrough(x)
11835    /// output) of Conv2D and ConvTranspose2D, 2 ops × 4 dtypes × 2 operand-counts
11836    /// = 16 bindings — is IMPORTED from `fuel-dispatch/kernel-contracts/cpu/conv.fkc.md`.
11837    ///
11838    /// The no-bias keys are now contract-sourced too: the conv contract declares
11839    /// `bias` as `optional: true`, and the importer's key-builder
11840    /// (`fkc/lower.rs` `assemble_dtype_variants`) now fans an optional LAST input
11841    /// into BOTH the with- and without-operand keys, both resolving the SAME
11842    /// wrapper. The former hand-written no-bias `table.register(...)` regs are
11843    /// DELETED (deferral closed).
11844    ///
11845    /// For each of the 16 keys: resolves to the EXACT production wrapper
11846    /// fn-pointer with `kernel_source == "portable-cpu"` — the contract
11847    /// provenance tag — caps contiguous, and the contract's bit-stable precision
11848    /// riding through.
11849    #[test]
11850    fn global_bindings_registers_conv_family_from_contract() {
11851        let table = global_bindings();
11852        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11853
11854        // Conv2D wrappers (order matches `dts`); the same wrapper serves both the
11855        // no-bias [x, weight, out] and with-bias [x, weight, bias, out] keys.
11856        let conv2d_wrappers: [crate::kernel::KernelRef; 4] = [
11857            conv2d_f32_cpu_wrapper,
11858            conv2d_f64_cpu_wrapper,
11859            conv2d_bf16_cpu_wrapper,
11860            conv2d_f16_cpu_wrapper,
11861        ];
11862        // ConvTranspose2D wrappers (order matches `dts`).
11863        let convt_wrappers: [crate::kernel::KernelRef; 4] = [
11864            conv_transpose2d_f32_cpu_wrapper,
11865            conv_transpose2d_f64_cpu_wrapper,
11866            conv_transpose2d_bf16_cpu_wrapper,
11867            conv_transpose2d_f16_cpu_wrapper,
11868        ];
11869
11870        let mut checked = 0usize;
11871        for (i, dt) in dts.iter().enumerate() {
11872            for (op, expected) in [
11873                (OpKind::Conv2D, conv2d_wrappers[i]),
11874                (OpKind::ConvTranspose2D, convt_wrappers[i]),
11875            ] {
11876                // BOTH operand-count keys: no-bias [x, weight, out] AND with-bias
11877                // [x, weight, bias, out] — all T, both bound to the SAME wrapper
11878                // from the contract's optional-operand fan.
11879                let no_bias: &[DType] = &[*dt, *dt, *dt];
11880                let with_bias: &[DType] = &[*dt, *dt, *dt, *dt];
11881                for (key, label) in [(no_bias, "no-bias"), (with_bias, "with-bias")] {
11882                    let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11883                    let entry = alts
11884                        .iter()
11885                        .find(|e| e.kernel as usize == expected as usize)
11886                        .unwrap_or_else(|| {
11887                            panic!(
11888                                "{op:?}/{dt:?}/Cpu ({label}): the production wrapper must be \
11889                                 bound FROM the conv contract in global_bindings() — found {} \
11890                                 alternative(s) with sources {:?}",
11891                                alts.len(),
11892                                alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11893                            )
11894                        });
11895                    assert_eq!(
11896                        entry.kernel_source, "portable-cpu",
11897                        "{op:?}/{dt:?} ({label}): family must be contract-sourced \
11898                         (kernel_source=\"portable-cpu\"); got {:?}",
11899                        entry.kernel_source,
11900                    );
11901                    assert!(
11902                        !entry.caps.strided_input,
11903                        "{op:?}/{dt:?} ({label}): caps preserved (contiguous-only)",
11904                    );
11905                    assert!(
11906                        entry.precision.bit_stable_on_same_hardware,
11907                        "{op:?}/{dt:?} ({label}): contract's bit-stable claim rode through",
11908                    );
11909                    checked += 1;
11910                }
11911            }
11912        }
11913        assert_eq!(
11914            checked, 16,
11915            "2 ops × 4 dtypes × 2 operand-counts checked (16 contract-sourced bindings)"
11916        );
11917    }
11918
11919    /// Gate for the CPU **padding** family's BACKWARD half migrated to
11920    /// FKC-contract registration. The four `PadBackward` per-dtype kernels
11921    /// (key `[T, T]` — grad_out + `passthrough(grad_out)` grad_in, T ∈
11922    /// {F32,F64,BF16,F16}) are IMPORTED from
11923    /// `fuel-dispatch/kernel-contracts/cpu/padding.fkc.md` — the `pad_backward_<dt>`
11924    /// single-dtype sections, each resolved AS-IS (no dtype fan-out) through the
11925    /// production `CpuLinkRegistry` (chaining `CPU_PADDING_ENTRY_POINTS`).
11926    ///
11927    /// The FORWARD `Pad` half (Constant/Reflect/Replicate) is ALSO migrated:
11928    /// the three runtime modes collapse to ONE mode-unified `(Pad, [T, T])`
11929    /// binding per dtype served by the single dtype-agnostic `pad_cpu_wrapper`
11930    /// (mode chosen at runtime via `mode_tag`). The contract's unified `## pad`
11931    /// section fans its 6 production dtypes (U8/U32/BF16/F16/F32/F64), ALL
11932    /// resolving `pad_cpu_wrapper` (the fabricated `pad_cpu_<dt>` symbol → the one
11933    /// wrapper, like Flip/Roll/Concat); the three per-mode sections
11934    /// (`pad_const_cpu`/`pad_reflect_cpu`/`pad_replicate_cpu`) and the
11935    /// `pad_walk_cpu` helper stay `registrable: false` describe-only mode docs.
11936    /// See `register_cpu_padding_from_contract`.
11937    ///
11938    /// For each of the 4 backward + 6 forward keys: resolves to the EXACT
11939    /// production wrapper with `kernel_source == "portable-cpu"` (the contract
11940    /// provenance tag), caps contiguous, and the contract's bit-stable precision
11941    /// riding through.
11942    #[test]
11943    fn global_bindings_registers_padding_family_from_contract() {
11944        let table = global_bindings();
11945        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11946        // PadBackward wrappers, indexed to match `dts` order.
11947        let pad_backward: [crate::kernel::KernelRef; 4] = [
11948            pad_backward_f32_cpu_wrapper,
11949            pad_backward_f64_cpu_wrapper,
11950            pad_backward_bf16_cpu_wrapper,
11951            pad_backward_f16_cpu_wrapper,
11952        ];
11953
11954        let mut checked = 0usize;
11955        for (i, dt) in dts.iter().enumerate() {
11956            // PadBackward: [grad_out T, grad_in T] = [T, T] (passthrough(grad_out)).
11957            let key: &[DType] = &[*dt, *dt];
11958            let expected = pad_backward[i];
11959            let alts = table.lookup_alternatives(OpKind::PadBackward, key, BackendId::Cpu);
11960            let entry = alts
11961                .iter()
11962                .find(|e| e.kernel as usize == expected as usize)
11963                .unwrap_or_else(|| {
11964                    panic!(
11965                        "PadBackward/{dt:?}/Cpu: the production wrapper must be bound \
11966                         FROM the padding contract in global_bindings() — found {} \
11967                         alternative(s) with sources {:?}",
11968                        alts.len(),
11969                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11970                    )
11971                });
11972            assert_eq!(
11973                entry.kernel_source, "portable-cpu",
11974                "PadBackward/{dt:?}: family must be contract-sourced \
11975                 (kernel_source=\"portable-cpu\"); got {:?}",
11976                entry.kernel_source,
11977            );
11978            assert!(
11979                !entry.caps.strided_input,
11980                "PadBackward/{dt:?}: caps preserved (contiguous-only)",
11981            );
11982            assert!(
11983                entry.precision.bit_stable_on_same_hardware,
11984                "PadBackward/{dt:?}: contract's bit-stable claim rode through",
11985            );
11986            checked += 1;
11987        }
11988
11989        // Forward Pad (Constant/Reflect/Replicate) — ONE mode-unified `(Pad, [T, T])`
11990        // binding per dtype served by the SINGLE dtype-agnostic `pad_cpu_wrapper`
11991        // (mode chosen at runtime via `mode_tag`). The contract's unified `## pad`
11992        // section fans its 6 production dtypes (U8/U32/BF16/F16/F32/F64), ALL
11993        // resolving `pad_cpu_wrapper` (fabricated `pad_cpu_<dt>` symbol → the one
11994        // wrapper, like Flip/Roll/Concat). in_shape/out_shape/padding/mode_tag/
11995        // fill_bytes ride in OpParams::Pad, NOT the dtype-list.
11996        let pad_forward_dts = [
11997            DType::U8,
11998            DType::U32,
11999            DType::BF16,
12000            DType::F16,
12001            DType::F32,
12002            DType::F64,
12003        ];
12004        for dt in pad_forward_dts {
12005            let key: &[DType] = &[dt, dt];
12006            let alts = table.lookup_alternatives(OpKind::Pad, key, BackendId::Cpu);
12007            let entry = alts
12008                .iter()
12009                .find(|e| e.kernel as usize == pad_cpu_wrapper as *const () as usize)
12010                .unwrap_or_else(|| {
12011                    panic!(
12012                        "Pad/{dt:?}/Cpu: the production wrapper must be bound \
12013                         FROM the padding contract in global_bindings() — found {} \
12014                         alternative(s) with sources {:?}",
12015                        alts.len(),
12016                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12017                    )
12018                });
12019            assert_eq!(
12020                entry.kernel_source, "portable-cpu",
12021                "Pad/{dt:?}: forward family must be contract-sourced \
12022                 (kernel_source=\"portable-cpu\"); got {:?}",
12023                entry.kernel_source,
12024            );
12025            assert!(
12026                !entry.caps.strided_input,
12027                "Pad/{dt:?}: caps preserved (contiguous-only)",
12028            );
12029            assert!(
12030                entry.precision.bit_stable_on_same_hardware,
12031                "Pad/{dt:?}: contract's bit-stable claim rode through",
12032            );
12033            checked += 1;
12034        }
12035
12036        assert_eq!(
12037            checked, 10,
12038            "4 PadBackward + 6 forward Pad dtypes checked (contract-sourced bindings)"
12039        );
12040    }
12041
12042    /// Gate for the CPU **shape-ops** family's migratable subset moved to
12043    /// FKC-contract registration. IMPORTED from
12044    /// `fuel-dispatch/kernel-contracts/cpu/shape-ops.fkc.md` via the production
12045    /// `CpuLinkRegistry` (chaining `CPU_SHAPE_OPS_ENTRY_POINTS`):
12046    /// - **Flip** / **Roll** — dtype-agnostic byte reorder, key `[T, T]`, one
12047    ///   `flip_cpu_wrapper` / `roll_cpu_wrapper` per dtype (fan over the 6
12048    ///   production dtypes F32/F64/BF16/F16/U32/U8; the contract's dtype list is
12049    ///   trimmed to match production, NOT the kernel's full byte-agnostic set).
12050    /// - **CumSum** — per-dtype typed accumulation (f32/f64 native, bf16/f16 with
12051    ///   an f32 accumulator), key `[T, T]`, its SPECIFIC `cumsum_<dt>` symbol
12052    ///   resolved AS-IS (no fan), 4 dtypes.
12053    /// - **MaskedFill** — dtype-agnostic data + U8 mask, key `[T, U8, T]`, one
12054    ///   `masked_fill_cpu_wrapper` per dtype (fan over the same 6 dtypes).
12055    /// - **Concat** — variadic uniform-dtype join collapsed to the `[T, T]`
12056    ///   shorthand key, one `concat_cpu_wrapper` per dtype (fan over the 9
12057    ///   production dtypes F32/F64/BF16/F16/U32/U8/I16/I32/I64).
12058    /// - **WriteSlice** / **WriteSliceRotating** — in-place rectangular / ring
12059    ///   scatter, key `[T, T]`, one dtype-agnostic wrapper each (fan over the same
12060    ///   6 dtypes). `dest` is the in-place OUTPUT slot (not a key input); for the
12061    ///   rotating op the U32 `position` is a NON-KEY runtime operand — so the
12062    ///   contract's source-only + `out: passthrough(source)` section keys
12063    ///   `[T_source, T_out]` = `[T, T]`, matching `build_lookup_dtypes` exactly.
12064    ///
12065    /// DEFERRED (hand-written / describe-only, NOT checked here): `Contiguize`
12066    /// (no `OpKind` — an executor materialize pass) and `Triu`/`Tril` (the contract
12067    /// carries only the `triangular` chassis umbrella, `registrable: false`, not
12068    /// two per-OpKind sections). See `register_cpu_shape_ops_from_contract`.
12069    ///
12070    /// For each migrated key: resolves to the EXACT production wrapper with
12071    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12072    /// contiguous, and the contract's bit-stable precision riding through.
12073    #[test]
12074    fn global_bindings_registers_shape_ops_family_from_contract() {
12075        let table = global_bindings();
12076        let mut checked = 0usize;
12077
12078        // Assert a (op, key) resolves to `expected` with the contract provenance.
12079        let mut check =
12080            |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
12081                let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12082                let entry = alts
12083                    .iter()
12084                    .find(|e| e.kernel as usize == expected as usize)
12085                    .unwrap_or_else(|| {
12086                        panic!(
12087                            "{op:?}/{label}/Cpu: the production wrapper must be bound \
12088                         FROM the shape-ops contract in global_bindings() — found {} \
12089                         alternative(s) with sources {:?}",
12090                            alts.len(),
12091                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12092                        )
12093                    });
12094                assert_eq!(
12095                    entry.kernel_source, "portable-cpu",
12096                    "{op:?}/{label}: family must be contract-sourced \
12097                 (kernel_source=\"portable-cpu\"); got {:?}",
12098                    entry.kernel_source,
12099                );
12100                assert!(
12101                    !entry.caps.strided_input,
12102                    "{op:?}/{label}: caps preserved (contiguous-only)",
12103                );
12104                assert!(
12105                    entry.precision.bit_stable_on_same_hardware,
12106                    "{op:?}/{label}: contract's bit-stable claim rode through",
12107                );
12108                checked += 1;
12109            };
12110
12111        // Flip / Roll — key [T, T], one dtype-agnostic wrapper fanned per dtype.
12112        let byte_dts = [
12113            DType::F32,
12114            DType::F64,
12115            DType::BF16,
12116            DType::F16,
12117            DType::U32,
12118            DType::U8,
12119        ];
12120        for dt in byte_dts {
12121            check(OpKind::Flip, &[dt, dt], flip_cpu_wrapper, "flip");
12122            check(OpKind::Roll, &[dt, dt], roll_cpu_wrapper, "roll");
12123            // MaskedFill — key [T, U8, T].
12124            check(
12125                OpKind::MaskedFill,
12126                &[dt, DType::Bool, dt], // GAP-168(c): mask slot is Bool; the outer dt list is DATA dtypes
12127                masked_fill_cpu_wrapper,
12128                "masked_fill",
12129            );
12130        }
12131
12132        // CumSum — per-dtype typed wrappers, key [T, T], resolved AS-IS.
12133        let cumsum_dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12134        let cumsum_wrappers: [crate::kernel::KernelRef; 4] = [
12135            cumsum_f32_cpu_wrapper,
12136            cumsum_f64_cpu_wrapper,
12137            cumsum_bf16_cpu_wrapper,
12138            cumsum_f16_cpu_wrapper,
12139        ];
12140        for (i, dt) in cumsum_dts.iter().enumerate() {
12141            check(OpKind::CumSum, &[*dt, *dt], cumsum_wrappers[i], "cumsum");
12142        }
12143
12144        // Concat — variadic uniform-dtype collapsed to [T, T], 9 dtypes.
12145        let concat_dts = [
12146            DType::F32,
12147            DType::F64,
12148            DType::BF16,
12149            DType::F16,
12150            DType::U32,
12151            DType::U8,
12152            DType::I16,
12153            DType::I32,
12154            DType::I64,
12155        ];
12156        for dt in concat_dts {
12157            check(OpKind::Concat, &[dt, dt], concat_cpu_wrapper, "concat");
12158        }
12159
12160        // WriteSlice / WriteSliceRotating — in-place rectangular / ring-buffer
12161        // scatter, key [T, T] (dest IS the output slot via in-place adoption;
12162        // WriteSliceRotating's `position` is a NON-KEY runtime U32 operand — see
12163        // `build_lookup_dtypes`). One dtype-agnostic wrapper each, fanned over the
12164        // 6 production dtypes (F32/F64/BF16/F16/U32/U8). The offset/modulus/axis/
12165        // ranges ride in OpParams::{WriteSlice,WriteSliceRotating}.
12166        let scatter_dts = [
12167            DType::F32,
12168            DType::F64,
12169            DType::BF16,
12170            DType::F16,
12171            DType::U32,
12172            DType::U8,
12173        ];
12174        for dt in scatter_dts {
12175            check(
12176                OpKind::WriteSlice,
12177                &[dt, dt],
12178                write_slice_cpu_wrapper,
12179                "write_slice",
12180            );
12181            check(
12182                OpKind::WriteSliceRotating,
12183                &[dt, dt],
12184                write_slice_rotating_cpu_wrapper,
12185                "write_slice_rotating",
12186            );
12187            // WriteSliceDoff — like WriteSliceRotating but the runtime operand is a
12188            // NON-KEY I64 `offset` (device-resident under CUDA), no wrap.
12189            check(
12190                OpKind::WriteSliceDoff,
12191                &[dt, dt],
12192                write_slice_doff_cpu_wrapper,
12193                "write_slice_doff",
12194            );
12195        }
12196
12197        assert_eq!(
12198            checked,
12199            6 + 6 + 6 + 4 + 9 + 6 + 6 + 6,
12200            "flip(6) + roll(6) + masked_fill(6) + cumsum(4) + concat(9) + \
12201             write_slice(6) + write_slice_rotating(6) + write_slice_doff(6) contract-sourced bindings",
12202        );
12203    }
12204
12205    /// Gate for the CPU **indexing / gather / scatter** family moved to
12206    /// FKC-contract registration. IMPORTED from
12207    /// `fuel-dispatch/kernel-contracts/cpu/indexing.fkc.md` via the production
12208    /// `CpuLinkRegistry` (chaining `CPU_INDEXING_ENTRY_POINTS`):
12209    /// - **IndexSelect** / **Gather** — dtype-agnostic byte copy, key
12210    ///   `[T, U32, T]` (`source`, fixed-U32 `indices`, `passthrough(source)`
12211    ///   output). One `index_select_cpu_wrapper` / `gather_cpu_wrapper` per dtype
12212    ///   (the contract's ONE section declares a BASE `entry_point`
12213    ///   (`…::index_select_cpu` / `…::gather_cpu`) fanned over its dtype list, the
12214    ///   fabricated `<base>_<dt>` symbol resolving to the ONE wrapper — the
12215    ///   pad/flip umbrella precedent). The contract's dtype list is trimmed to
12216    ///   production's 9 wired dtypes (F32/F64/BF16/F16/U32/U8/I16/I32/I64); I8 is
12217    ///   describable (byte-agnostic) but NOT wired in production, so it is dropped
12218    ///   from the contract, NOT the kernel's full byte-agnostic set.
12219    /// - **IndexAdd** / **ScatterAdd** — per-dtype typed accumulation (f32/f64
12220    ///   native, bf16/f16 via an f32 accumulator; out seeded from `base` then
12221    ///   `+= src`), key `[T, U32, T, T]` (`base`, fixed-U32 `indices`, `src`,
12222    ///   `passthrough(base)` output). Each `index_add_<dt>` / `scatter_add_<dt>`
12223    ///   section carries a SPECIFIC single-dtype `entry_point` resolved AS-IS (no
12224    ///   fan), 4 dtypes each, mapping to its OWN typed wrapper.
12225    ///
12226    /// The `indices` operand is a FIXED single-dtype (U32) slot in every section
12227    /// (like compare's U8 mask / paged's U32 block-table), so there is NO
12228    /// independent index-dtype axis and no multi-axis `FanoutDtypeMismatch`
12229    /// deferral — the whole family migrates.
12230    ///
12231    /// For each migrated key: resolves to the EXACT production wrapper with
12232    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12233    /// contiguous, and the contract's bit-stable precision riding through.
12234    #[test]
12235    fn global_bindings_registers_indexing_family_from_contract() {
12236        let table = global_bindings();
12237        let mut checked = 0usize;
12238
12239        // Assert a (op, key) resolves to `expected` with the contract provenance.
12240        let mut check =
12241            |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
12242                let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12243                let entry = alts
12244                    .iter()
12245                    .find(|e| e.kernel as usize == expected as usize)
12246                    .unwrap_or_else(|| {
12247                        panic!(
12248                            "{op:?}/{label}/Cpu: the production wrapper must be bound \
12249                         FROM the indexing contract in global_bindings() — found {} \
12250                         alternative(s) with sources {:?}",
12251                            alts.len(),
12252                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12253                        )
12254                    });
12255                assert_eq!(
12256                    entry.kernel_source, "portable-cpu",
12257                    "{op:?}/{label}: family must be contract-sourced \
12258                 (kernel_source=\"portable-cpu\"); got {:?}",
12259                    entry.kernel_source,
12260                );
12261                assert!(
12262                    !entry.caps.strided_input,
12263                    "{op:?}/{label}: caps preserved (contiguous-only)",
12264                );
12265                assert!(
12266                    entry.precision.bit_stable_on_same_hardware,
12267                    "{op:?}/{label}: contract's bit-stable claim rode through",
12268                );
12269                checked += 1;
12270            };
12271
12272        // IndexSelect / Gather — dtype-agnostic byte copy, key [T, U32, T], one
12273        // wrapper fanned per dtype (9 production dtypes; I8 trimmed).
12274        let byte_dts = [
12275            DType::F32,
12276            DType::F64,
12277            DType::BF16,
12278            DType::F16,
12279            DType::U32,
12280            DType::U8,
12281            DType::I16,
12282            DType::I32,
12283            DType::I64,
12284        ];
12285        for dt in byte_dts {
12286            check(
12287                OpKind::IndexSelect,
12288                &[dt, DType::U32, dt],
12289                index_select_cpu_wrapper,
12290                "index_select",
12291            );
12292            check(
12293                OpKind::Gather,
12294                &[dt, DType::U32, dt],
12295                gather_cpu_wrapper,
12296                "gather",
12297            );
12298        }
12299
12300        // IndexAdd / ScatterAdd — per-dtype typed accumulation, key
12301        // [T, U32, T, T], each `<op>_<dt>` symbol resolved AS-IS (no fan).
12302        let acc_dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12303        let index_add_wrappers: [crate::kernel::KernelRef; 4] = [
12304            index_add_f32_cpu_wrapper,
12305            index_add_f64_cpu_wrapper,
12306            index_add_bf16_cpu_wrapper,
12307            index_add_f16_cpu_wrapper,
12308        ];
12309        let scatter_add_wrappers: [crate::kernel::KernelRef; 4] = [
12310            scatter_add_f32_cpu_wrapper,
12311            scatter_add_f64_cpu_wrapper,
12312            scatter_add_bf16_cpu_wrapper,
12313            scatter_add_f16_cpu_wrapper,
12314        ];
12315        for (i, dt) in acc_dts.iter().enumerate() {
12316            check(
12317                OpKind::IndexAdd,
12318                &[*dt, DType::U32, *dt, *dt],
12319                index_add_wrappers[i],
12320                "index_add",
12321            );
12322            check(
12323                OpKind::ScatterAdd,
12324                &[*dt, DType::U32, *dt, *dt],
12325                scatter_add_wrappers[i],
12326                "scatter_add",
12327            );
12328        }
12329
12330        assert_eq!(
12331            checked,
12332            9 + 9 + 4 + 4,
12333            "index_select(9) + gather(9) + index_add(4) + scatter_add(4) \
12334             contract-sourced bindings",
12335        );
12336    }
12337
12338    /// Gate for the CPU **matmul** family moved to FKC-contract registration.
12339    /// IMPORTED from `fuel-dispatch/kernel-contracts/cpu/matmul.fkc.md` via the production
12340    /// `CpuLinkRegistry` (chaining `CPU_MATMUL_ENTRY_POINTS`):
12341    /// - **MatMul** — bare batched matmul (`OpKind::MatMul`), key `[T, T, T]`
12342    ///   (lhs, rhs + `passthrough(lhs)` output). Each per-dtype section
12343    ///   (`## matmul_f32`, …) carries a SPECIFIC single-dtype `entry_point`
12344    ///   resolved AS-IS (no fan), 6 dtypes (F32/F64/BF16/F16 with an f32/native
12345    ///   accumulator + I8/U8 with an i32 accumulator + saturating store).
12346    /// - **FusedLinear** — fused matmul + bias-add (`OpKind::FusedLinear`), key
12347    ///   `[T, T, T, T]` (a, b, bias + `passthrough(a)` output). Reuses
12348    ///   `OpParams::Matmul` for shape; bias is a REQUIRED 1-D `[N]` operand (no
12349    ///   optional fan). 4 dtypes (F32/F64/BF16/F16).
12350    ///
12351    /// This family exercises the CRITICAL alternatives-at-the-same-key path: the
12352    /// binding table supports MULTIPLE ranked kernels per `(op, dtypes, backend)`
12353    /// key, and the MKL/AOCL BLAS siblings (external `fuel-mkl-cpu-backend` /
12354    /// `fuel-aocl-cpu-backend` crates, registered through the exported dispatch
12355    /// helpers with their own `"mkl"`/`"aocl"` `kernel_source` tags) may register
12356    /// at these SAME keys — SEPARATE and out of scope here. So this gate does NOT
12357    /// assert the portable wrapper is the SOLE alternative; it `find`s the
12358    /// portable `"portable-cpu"`-sourced entry among the alternatives.
12359    ///
12360    /// SEPARATE seams left untouched: the `FusedKernelRegistry`
12361    /// `FusedOps::FUSED_LINEAR` registration (`register_default_fused_kernels`) is
12362    /// hand-written and not FKC-imported (the matmul contract declares NO
12363    /// `fused_op` sections); the quant `QMatMul` / `Nf4Matmul` OpKinds have their
12364    /// own contracts and stay hand-written.
12365    ///
12366    /// For each migrated key: the portable wrapper is bound with
12367    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12368    /// contiguous, and the contract's bit-stable precision riding through.
12369    #[test]
12370    fn global_bindings_registers_matmul_family_from_contract() {
12371        let table = global_bindings();
12372        let mut checked = 0usize;
12373
12374        // Assert a (op, key) resolves to `expected` (the portable wrapper) with
12375        // the contract provenance — `find`ing it among any BLAS-sibling
12376        // alternatives at the same key (never asserting single-alternative).
12377        let mut check =
12378            |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
12379                let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12380                let entry = alts
12381                    .iter()
12382                    .find(|e| e.kernel as usize == expected as usize)
12383                    .unwrap_or_else(|| {
12384                        panic!(
12385                            "{op:?}/{label}/Cpu: the portable wrapper must be bound \
12386                         FROM the matmul contract in global_bindings() — found {} \
12387                         alternative(s) with sources {:?}",
12388                            alts.len(),
12389                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12390                        )
12391                    });
12392                assert_eq!(
12393                    entry.kernel_source, "portable-cpu",
12394                    "{op:?}/{label}: portable kernel must be contract-sourced \
12395                 (kernel_source=\"portable-cpu\"); got {:?}",
12396                    entry.kernel_source,
12397                );
12398                assert!(
12399                    !entry.caps.strided_input,
12400                    "{op:?}/{label}: caps preserved (contiguous-only)",
12401                );
12402                assert!(
12403                    entry.precision.bit_stable_on_same_hardware,
12404                    "{op:?}/{label}: contract's bit-stable claim rode through",
12405                );
12406                checked += 1;
12407            };
12408
12409        // MatMul — key [T, T, T], per-dtype wrapper resolved AS-IS. 6 dtypes.
12410        let mm_dts = [
12411            DType::F32,
12412            DType::F64,
12413            DType::BF16,
12414            DType::F16,
12415            DType::I8,
12416            DType::U8,
12417        ];
12418        let mm_wrappers: [crate::kernel::KernelRef; 6] = [
12419            matmul_f32_cpu_wrapper,
12420            matmul_f64_cpu_wrapper,
12421            matmul_bf16_cpu_wrapper,
12422            matmul_f16_cpu_wrapper,
12423            matmul_i8_cpu_wrapper,
12424            matmul_u8_cpu_wrapper,
12425        ];
12426        for (i, dt) in mm_dts.iter().enumerate() {
12427            check(OpKind::MatMul, &[*dt, *dt, *dt], mm_wrappers[i], "matmul");
12428        }
12429
12430        // FusedLinear — key [T, T, T, T], per-dtype wrapper resolved AS-IS. 4 dtypes.
12431        let fl_dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12432        let fl_wrappers: [crate::kernel::KernelRef; 4] = [
12433            fused_linear_f32_cpu_wrapper,
12434            fused_linear_f64_cpu_wrapper,
12435            fused_linear_bf16_cpu_wrapper,
12436            fused_linear_f16_cpu_wrapper,
12437        ];
12438        for (i, dt) in fl_dts.iter().enumerate() {
12439            check(
12440                OpKind::FusedLinear,
12441                &[*dt, *dt, *dt, *dt],
12442                fl_wrappers[i],
12443                "fused_linear",
12444            );
12445        }
12446
12447        assert_eq!(
12448            checked,
12449            6 + 4,
12450            "matmul(6) + fused_linear(4) contract-sourced bindings",
12451        );
12452    }
12453
12454    /// Gate for the CPU **attention** family's `KernelBindingTable` path migrated
12455    /// to FKC-contract registration. FlashAttn (forward) + the three
12456    /// FlashAttnBackward{Q,K,V} selectors + PagedAttn — 5 ops × 4 dtypes ×
12457    /// {no-alibi, with-alibi} = 40 bindings — are IMPORTED from
12458    /// `fuel-dispatch/kernel-contracts/cpu/attention.fkc.md` (the `op_kind:` sections).
12459    /// Each section declares `alibi_slopes` as an `optional: true` LAST input, so
12460    /// the importer's optional-operand fan registers BOTH the no-alibi key
12461    /// (`[q,k,v(,do),out]` / `[q,kc,vc,bt,cl,out]`) and the with-alibi key
12462    /// (`+alibi`), both resolving the SAME wrapper — byte-for-byte the deleted
12463    /// hand-written `no_alibi`/`with_alibi` regs. Forward FlashAttn and the three
12464    /// backward selectors share the single `OpParams::FlashAttn` carrier (no
12465    /// dedicated backward variant); PagedAttn uses `OpParams::PagedAttn`.
12466    ///
12467    /// **PagedAttn is now REGISTRABLE + contract-sourced (FDX gather-sidecar arc,
12468    /// slice A).** Its `fdx.gather: paged_blocks` pool is import METADATA (§3.9.1):
12469    /// the block_table / context_lens ride as ordinary U32 operands +
12470    /// `OpParams::PagedAttn`, so registration does not depend on the FDX gather
12471    /// VIEW (which stays [consumer-ahead]). Its bindings are asserted
12472    /// contract-sourced alongside FlashAttn below — BORN-RED discriminator: the
12473    /// deleted hand-written regs stamped an empty `kernel_source`, so the
12474    /// `kernel_source == "portable-cpu"` assertion failed until the four paged
12475    /// sections were flipped `registrable: true` + wired into
12476    /// `CPU_ATTENTION_ENTRY_POINTS`. The SEPARATE `FusedKernelRegistry`
12477    /// FLASH_ATTN* / PAGED_ATTN seam (`register_default_fused_kernels`) is
12478    /// untouched (stays hand-written, exactly as before).
12479    ///
12480    /// For each of the 40 keys: resolves to the EXACT production wrapper with
12481    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12482    /// contiguous, and the contract's bit-stable precision riding through.
12483    #[test]
12484    fn global_bindings_registers_attention_family_from_contract() {
12485        let table = global_bindings();
12486        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12487
12488        // Forward FlashAttn wrappers (order matches `dts`); the same wrapper
12489        // serves both the no-alibi [q,k,v,out] and with-alibi [q,k,v,alibi,out] keys.
12490        let fa_wrappers: [crate::kernel::KernelRef; 4] = [
12491            flash_attn_f32_cpu_wrapper,
12492            flash_attn_f64_cpu_wrapper,
12493            flash_attn_bf16_cpu_wrapper,
12494            flash_attn_f16_cpu_wrapper,
12495        ];
12496        // FlashAttnBackward{Q,K,V} wrappers (order matches `dts`).
12497        let fabq: [crate::kernel::KernelRef; 4] = [
12498            flash_attn_backward_q_f32_cpu_wrapper,
12499            flash_attn_backward_q_f64_cpu_wrapper,
12500            flash_attn_backward_q_bf16_cpu_wrapper,
12501            flash_attn_backward_q_f16_cpu_wrapper,
12502        ];
12503        let fabk: [crate::kernel::KernelRef; 4] = [
12504            flash_attn_backward_k_f32_cpu_wrapper,
12505            flash_attn_backward_k_f64_cpu_wrapper,
12506            flash_attn_backward_k_bf16_cpu_wrapper,
12507            flash_attn_backward_k_f16_cpu_wrapper,
12508        ];
12509        let fabv: [crate::kernel::KernelRef; 4] = [
12510            flash_attn_backward_v_f32_cpu_wrapper,
12511            flash_attn_backward_v_f64_cpu_wrapper,
12512            flash_attn_backward_v_bf16_cpu_wrapper,
12513            flash_attn_backward_v_f16_cpu_wrapper,
12514        ];
12515        // PagedAttn wrappers (order matches `dts`); the same wrapper serves both
12516        // the no-alibi [q,kc,vc,bt,cl,out] and with-alibi (+alibi) keys.
12517        let pa_wrappers: [crate::kernel::KernelRef; 4] = [
12518            paged_attn_f32_cpu_wrapper,
12519            paged_attn_f64_cpu_wrapper,
12520            paged_attn_bf16_cpu_wrapper,
12521            paged_attn_f16_cpu_wrapper,
12522        ];
12523
12524        // Assert `op`/`key` resolves to `expected` with the contract provenance,
12525        // FINDING it among any alternatives at the key (never single-alternative).
12526        let check = |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
12527            let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12528            let entry = alts
12529                .iter()
12530                .find(|e| e.kernel as usize == expected as usize)
12531                .unwrap_or_else(|| {
12532                    panic!(
12533                        "{op:?}/{label}/Cpu: the production wrapper must be bound \
12534                         FROM the attention contract in global_bindings() — found {} \
12535                         alternative(s) with sources {:?}",
12536                        alts.len(),
12537                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12538                    )
12539                });
12540            assert_eq!(
12541                entry.kernel_source, "portable-cpu",
12542                "{op:?}/{label}: family must be contract-sourced \
12543                 (kernel_source=\"portable-cpu\"); got {:?}",
12544                entry.kernel_source,
12545            );
12546            assert!(
12547                !entry.caps.strided_input,
12548                "{op:?}/{label}: caps preserved (contiguous-only)",
12549            );
12550            assert!(
12551                entry.precision.bit_stable_on_same_hardware,
12552                "{op:?}/{label}: contract's bit-stable claim rode through",
12553            );
12554        };
12555
12556        let mut checked = 0usize;
12557        for (i, dt) in dts.iter().enumerate() {
12558            // Forward: no-alibi [q,k,v,out] + with-alibi [q,k,v,alibi,out].
12559            let fa_noa: &[DType] = &[*dt, *dt, *dt, *dt];
12560            let fa_a: &[DType] = &[*dt, *dt, *dt, *dt, *dt];
12561            check(OpKind::FlashAttn, fa_noa, fa_wrappers[i], "flash no-alibi");
12562            check(OpKind::FlashAttn, fa_a, fa_wrappers[i], "flash with-alibi");
12563            checked += 2;
12564
12565            // Backward Q/K/V: no-alibi [q,k,v,do,out] + with-alibi [q,k,v,do,alibi,out].
12566            let bw_noa: &[DType] = &[*dt, *dt, *dt, *dt, *dt];
12567            let bw_a: &[DType] = &[*dt, *dt, *dt, *dt, *dt, *dt];
12568            for (op, ws) in [
12569                (OpKind::FlashAttnBackwardQ, &fabq),
12570                (OpKind::FlashAttnBackwardK, &fabk),
12571                (OpKind::FlashAttnBackwardV, &fabv),
12572            ] {
12573                check(op, bw_noa, ws[i], "backward no-alibi");
12574                check(op, bw_a, ws[i], "backward with-alibi");
12575                checked += 2;
12576            }
12577
12578            // PagedAttn (FDX gather-sidecar arc, slice A): now CONTRACT-SOURCED
12579            // like FlashAttn. no-alibi [q,kc,vc,bt:U32,cl:U32,out] + with-alibi
12580            // (+alibi). BORN-RED discriminator: before the migration the paged
12581            // bindings were hand-written (`kernel_source == ""`); `check` requires
12582            // `kernel_source == "portable-cpu"`, so it fails until the four paged
12583            // sections are flipped `registrable: true` + resolved via
12584            // CPU_ATTENTION_ENTRY_POINTS. Proves the gather block is import
12585            // metadata, not a registration blocker.
12586            let pa_noa: &[DType] = &[*dt, *dt, *dt, DType::U32, DType::U32, *dt];
12587            let pa_a: &[DType] = &[*dt, *dt, *dt, DType::U32, DType::U32, *dt, *dt];
12588            check(OpKind::PagedAttn, pa_noa, pa_wrappers[i], "paged no-alibi");
12589            check(OpKind::PagedAttn, pa_a, pa_wrappers[i], "paged with-alibi");
12590            checked += 2;
12591        }
12592        assert_eq!(
12593            checked, 40,
12594            "FlashAttn(8) + FlashAttnBackward{{Q,K,V}}(24) + PagedAttn(8) = 40 \
12595             contract-sourced bindings",
12596        );
12597    }
12598
12599    /// The CPU **in-place scalar-param** family is registered FROM its FKC
12600    /// contract (`fuel-dispatch/kernel-contracts/cpu/inplace-unary-affine.fkc.md`) via
12601    /// `register_cpu_inplace_from_contract`, NOT the deleted hand-written
12602    /// `table.register(<Op>Inplace / InplaceAffine / ClampInplace / PowIInplace,
12603    /// &unary(dt), …)` regs. 21 in-place unary ops (each fanning `[F32,F64,BF16,
12604    /// F16]` = 84) + `InplaceAffine` / `ClampInplace` / `PowIInplace` (4 dtypes
12605    /// each = 12) = 96 bindings, all keyed `[T, T]` (the single `out` operand +
12606    /// its `passthrough(out)` mirror; the executor's `InplaceKernel` arm passes
12607    /// the target as `outputs[0]`, so the wrapper takes 0 inputs + 1 output, but
12608    /// the binding-table KEY is `[T, T]`).
12609    ///
12610    /// For each of the 96 keys: resolves to the EXACT production wrapper with
12611    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12612    /// contiguous, and the contract's bit-stable precision riding through.
12613    #[test]
12614    fn global_bindings_registers_inplace_family_from_contract() {
12615        let table = global_bindings();
12616        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12617
12618        // Assert `op`/`[dt,dt]` resolves to `expected` with the contract
12619        // provenance, FINDING it among any alternatives at the key.
12620        let check = |op: OpKind, dt: DType, expected: crate::kernel::KernelRef, label: &str| {
12621            let key: &[DType] = &[dt, dt];
12622            let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12623            let entry = alts
12624                .iter()
12625                .find(|e| e.kernel as usize == expected as usize)
12626                .unwrap_or_else(|| {
12627                    panic!(
12628                        "{op:?}/{label}/{dt:?}/Cpu: the production wrapper must be bound \
12629                         FROM the in-place contract in global_bindings() — found {} \
12630                         alternative(s) with sources {:?}",
12631                        alts.len(),
12632                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12633                    )
12634                });
12635            assert_eq!(
12636                entry.kernel_source, "portable-cpu",
12637                "{op:?}/{label}/{dt:?}: family must be contract-sourced \
12638                 (kernel_source=\"portable-cpu\"); got {:?}",
12639                entry.kernel_source,
12640            );
12641            assert!(
12642                !entry.caps.strided_input,
12643                "{op:?}/{label}/{dt:?}: caps preserved (contiguous-only)",
12644            );
12645            assert!(
12646                entry.precision.bit_stable_on_same_hardware,
12647                "{op:?}/{label}/{dt:?}: contract's bit-stable claim rode through",
12648            );
12649        };
12650
12651        // 21 in-place unary ops × 4 dtypes (wrapper order matches `dts`).
12652        // Each row: (OpKind, label, [f32, f64, bf16, f16] wrappers).
12653        let unary_family: &[(OpKind, &str, [crate::kernel::KernelRef; 4])] = &[
12654            (
12655                OpKind::ReluInplace,
12656                "relu",
12657                [
12658                    relu_inplace_f32_cpu_wrapper,
12659                    relu_inplace_f64_cpu_wrapper,
12660                    relu_inplace_bf16_cpu_wrapper,
12661                    relu_inplace_f16_cpu_wrapper,
12662                ],
12663            ),
12664            (
12665                OpKind::SiluInplace,
12666                "silu",
12667                [
12668                    silu_inplace_f32_cpu_wrapper,
12669                    silu_inplace_f64_cpu_wrapper,
12670                    silu_inplace_bf16_cpu_wrapper,
12671                    silu_inplace_f16_cpu_wrapper,
12672                ],
12673            ),
12674            (
12675                OpKind::GeluTanhInplace,
12676                "gelu_tanh",
12677                [
12678                    gelu_inplace_f32_cpu_wrapper,
12679                    gelu_inplace_f64_cpu_wrapper,
12680                    gelu_inplace_bf16_cpu_wrapper,
12681                    gelu_inplace_f16_cpu_wrapper,
12682                ],
12683            ),
12684            (
12685                OpKind::TanhInplace,
12686                "tanh",
12687                [
12688                    tanh_inplace_f32_cpu_wrapper,
12689                    tanh_inplace_f64_cpu_wrapper,
12690                    tanh_inplace_bf16_cpu_wrapper,
12691                    tanh_inplace_f16_cpu_wrapper,
12692                ],
12693            ),
12694            (
12695                OpKind::SigmoidInplace,
12696                "sigmoid",
12697                [
12698                    sigmoid_inplace_f32_cpu_wrapper,
12699                    sigmoid_inplace_f64_cpu_wrapper,
12700                    sigmoid_inplace_bf16_cpu_wrapper,
12701                    sigmoid_inplace_f16_cpu_wrapper,
12702                ],
12703            ),
12704            (
12705                OpKind::NegInplace,
12706                "neg",
12707                [
12708                    neg_inplace_f32_cpu_wrapper,
12709                    neg_inplace_f64_cpu_wrapper,
12710                    neg_inplace_bf16_cpu_wrapper,
12711                    neg_inplace_f16_cpu_wrapper,
12712                ],
12713            ),
12714            (
12715                OpKind::AbsInplace,
12716                "abs",
12717                [
12718                    abs_inplace_f32_cpu_wrapper,
12719                    abs_inplace_f64_cpu_wrapper,
12720                    abs_inplace_bf16_cpu_wrapper,
12721                    abs_inplace_f16_cpu_wrapper,
12722                ],
12723            ),
12724            (
12725                OpKind::SqrInplace,
12726                "sqr",
12727                [
12728                    sqr_inplace_f32_cpu_wrapper,
12729                    sqr_inplace_f64_cpu_wrapper,
12730                    sqr_inplace_bf16_cpu_wrapper,
12731                    sqr_inplace_f16_cpu_wrapper,
12732                ],
12733            ),
12734            (
12735                OpKind::SqrtInplace,
12736                "sqrt",
12737                [
12738                    sqrt_inplace_f32_cpu_wrapper,
12739                    sqrt_inplace_f64_cpu_wrapper,
12740                    sqrt_inplace_bf16_cpu_wrapper,
12741                    sqrt_inplace_f16_cpu_wrapper,
12742                ],
12743            ),
12744            (
12745                OpKind::RsqrtInplace,
12746                "rsqrt",
12747                [
12748                    rsqrt_inplace_f32_cpu_wrapper,
12749                    rsqrt_inplace_f64_cpu_wrapper,
12750                    rsqrt_inplace_bf16_cpu_wrapper,
12751                    rsqrt_inplace_f16_cpu_wrapper,
12752                ],
12753            ),
12754            (
12755                OpKind::RecipInplace,
12756                "recip",
12757                [
12758                    recip_inplace_f32_cpu_wrapper,
12759                    recip_inplace_f64_cpu_wrapper,
12760                    recip_inplace_bf16_cpu_wrapper,
12761                    recip_inplace_f16_cpu_wrapper,
12762                ],
12763            ),
12764            (
12765                OpKind::ExpInplace,
12766                "exp",
12767                [
12768                    exp_inplace_f32_cpu_wrapper,
12769                    exp_inplace_f64_cpu_wrapper,
12770                    exp_inplace_bf16_cpu_wrapper,
12771                    exp_inplace_f16_cpu_wrapper,
12772                ],
12773            ),
12774            (
12775                OpKind::LogInplace,
12776                "log",
12777                [
12778                    log_inplace_f32_cpu_wrapper,
12779                    log_inplace_f64_cpu_wrapper,
12780                    log_inplace_bf16_cpu_wrapper,
12781                    log_inplace_f16_cpu_wrapper,
12782                ],
12783            ),
12784            (
12785                OpKind::SinInplace,
12786                "sin",
12787                [
12788                    sin_inplace_f32_cpu_wrapper,
12789                    sin_inplace_f64_cpu_wrapper,
12790                    sin_inplace_bf16_cpu_wrapper,
12791                    sin_inplace_f16_cpu_wrapper,
12792                ],
12793            ),
12794            (
12795                OpKind::CosInplace,
12796                "cos",
12797                [
12798                    cos_inplace_f32_cpu_wrapper,
12799                    cos_inplace_f64_cpu_wrapper,
12800                    cos_inplace_bf16_cpu_wrapper,
12801                    cos_inplace_f16_cpu_wrapper,
12802                ],
12803            ),
12804            (
12805                OpKind::SignInplace,
12806                "sign",
12807                [
12808                    sign_inplace_f32_cpu_wrapper,
12809                    sign_inplace_f64_cpu_wrapper,
12810                    sign_inplace_bf16_cpu_wrapper,
12811                    sign_inplace_f16_cpu_wrapper,
12812                ],
12813            ),
12814            (
12815                OpKind::FloorInplace,
12816                "floor",
12817                [
12818                    floor_inplace_f32_cpu_wrapper,
12819                    floor_inplace_f64_cpu_wrapper,
12820                    floor_inplace_bf16_cpu_wrapper,
12821                    floor_inplace_f16_cpu_wrapper,
12822                ],
12823            ),
12824            (
12825                OpKind::CeilInplace,
12826                "ceil",
12827                [
12828                    ceil_inplace_f32_cpu_wrapper,
12829                    ceil_inplace_f64_cpu_wrapper,
12830                    ceil_inplace_bf16_cpu_wrapper,
12831                    ceil_inplace_f16_cpu_wrapper,
12832                ],
12833            ),
12834            (
12835                OpKind::RoundInplace,
12836                "round",
12837                [
12838                    round_inplace_f32_cpu_wrapper,
12839                    round_inplace_f64_cpu_wrapper,
12840                    round_inplace_bf16_cpu_wrapper,
12841                    round_inplace_f16_cpu_wrapper,
12842                ],
12843            ),
12844            (
12845                OpKind::ErfInplace,
12846                "erf",
12847                [
12848                    erf_inplace_f32_cpu_wrapper,
12849                    erf_inplace_f64_cpu_wrapper,
12850                    erf_inplace_bf16_cpu_wrapper,
12851                    erf_inplace_f16_cpu_wrapper,
12852                ],
12853            ),
12854            (
12855                OpKind::GeluInplace,
12856                "gelu",
12857                [
12858                    gelu_erf_inplace_f32_cpu_wrapper,
12859                    gelu_erf_inplace_f64_cpu_wrapper,
12860                    gelu_erf_inplace_bf16_cpu_wrapper,
12861                    gelu_erf_inplace_f16_cpu_wrapper,
12862                ],
12863            ),
12864        ];
12865
12866        // Affine / clamp / powi — scalar-param single sections. Note the affine
12867        // wrapper name is `inplace_affine_<dt>_cpu_wrapper` (words swapped vs the
12868        // `affine_inplace_<dt>` symbol).
12869        let scalar_family: &[(OpKind, &str, [crate::kernel::KernelRef; 4])] = &[
12870            (
12871                OpKind::InplaceAffine,
12872                "affine",
12873                [
12874                    inplace_affine_f32_cpu_wrapper,
12875                    inplace_affine_f64_cpu_wrapper,
12876                    inplace_affine_bf16_cpu_wrapper,
12877                    inplace_affine_f16_cpu_wrapper,
12878                ],
12879            ),
12880            (
12881                OpKind::ClampInplace,
12882                "clamp",
12883                [
12884                    clamp_inplace_f32_cpu_wrapper,
12885                    clamp_inplace_f64_cpu_wrapper,
12886                    clamp_inplace_bf16_cpu_wrapper,
12887                    clamp_inplace_f16_cpu_wrapper,
12888                ],
12889            ),
12890            (
12891                OpKind::PowIInplace,
12892                "powi",
12893                [
12894                    powi_inplace_f32_cpu_wrapper,
12895                    powi_inplace_f64_cpu_wrapper,
12896                    powi_inplace_bf16_cpu_wrapper,
12897                    powi_inplace_f16_cpu_wrapper,
12898                ],
12899            ),
12900        ];
12901
12902        let mut checked = 0usize;
12903        for (op, label, ws) in unary_family.iter().chain(scalar_family.iter()) {
12904            for (i, dt) in dts.iter().enumerate() {
12905                check(*op, *dt, ws[i], label);
12906                checked += 1;
12907            }
12908        }
12909        assert_eq!(
12910            checked, 96,
12911            "21 in-place unary (×4) + InplaceAffine/ClampInplace/PowIInplace (×4) = 96 \
12912             contract-sourced bindings",
12913        );
12914    }
12915
12916    /// Gate for the CPU **cast** family migrated to FKC-contract registration.
12917    /// The FULL directed-pair matrix — every ordered pair of the 11 real numeric
12918    /// dtypes {F32,F64,F16,BF16,F8E4M3,U8,I8,U32,I16,I32,I64}, identity excluded =
12919    /// 11 × 10 = 110 pairs — is IMPORTED from
12920    /// `fuel-dispatch/kernel-contracts/cpu/cast.fkc.md` (see
12921    /// `register_cpu_cast_from_contract`). Each per-pair section declares a
12922    /// single-dtype `src` input + `fixed(DST)` output, so it does NOT dtype-fan —
12923    /// the importer keys `[SRC, DST]` (byte-for-byte the deleted hand-written
12924    /// `table.register(Cast, &[SRC, DST], …)` regs) and resolves the SPECIFIC
12925    /// `cast_<src>_to_<dst>` byte-kernel symbol AS-IS through the production
12926    /// `CpuLinkRegistry` (chaining `CPU_CAST_ENTRY_POINTS`). Because the binding
12927    /// lookup is keyed on the TARGET dtype, every one of a target's 10 source
12928    /// pairs resolves to the SAME per-target `cast_to_<dst>_cpu_wrapper` (which
12929    /// dispatches on source internally) — the fanned byte-kernel symbols are the
12930    /// synthetic-umbrella precedent (10 distinct entry_points → 1 wrapper).
12931    ///
12932    /// For each of the 110 pairs: resolves to the EXACT production per-target
12933    /// wrapper with `kernel_source == "portable-cpu"` (the contract provenance
12934    /// tag), caps contiguous-only, and the contract's bit-stable precision riding
12935    /// through. FKC is the SOLE registration path for the whole family.
12936    #[test]
12937    fn global_bindings_registers_cast_family_from_contract() {
12938        let table = global_bindings();
12939
12940        // Per-target wrapper (the binding-table key is keyed on the TARGET dtype;
12941        // each wrapper dispatches on the source dtype internally).
12942        let targets: [(DType, crate::kernel::KernelRef); 11] = [
12943            (DType::F32, cast_to_f32_cpu_wrapper),
12944            (DType::F64, cast_to_f64_cpu_wrapper),
12945            (DType::F16, cast_to_f16_cpu_wrapper),
12946            (DType::BF16, cast_to_bf16_cpu_wrapper),
12947            (DType::F8E4M3, cast_to_f8e4m3_cpu_wrapper),
12948            (DType::U8, cast_to_u8_cpu_wrapper),
12949            (DType::I8, cast_to_i8_cpu_wrapper),
12950            (DType::U32, cast_to_u32_cpu_wrapper),
12951            (DType::I16, cast_to_i16_cpu_wrapper),
12952            (DType::I32, cast_to_i32_cpu_wrapper),
12953            (DType::I64, cast_to_i64_cpu_wrapper),
12954        ];
12955        let all_dts: [DType; 11] = [
12956            DType::F32,
12957            DType::F64,
12958            DType::F16,
12959            DType::BF16,
12960            DType::F8E4M3,
12961            DType::U8,
12962            DType::I8,
12963            DType::U32,
12964            DType::I16,
12965            DType::I32,
12966            DType::I64,
12967        ];
12968
12969        let mut checked = 0usize;
12970        for (dst, expected) in targets {
12971            for src in all_dts {
12972                if src == dst {
12973                    continue; // identity pairs are elided by the optimizer, not registered
12974                }
12975                let key: &[DType] = &[src, dst];
12976                let alts = table.lookup_alternatives(OpKind::Cast, key, BackendId::Cpu);
12977                let entry = alts
12978                    .iter()
12979                    .find(|e| e.kernel as usize == expected as usize)
12980                    .unwrap_or_else(|| {
12981                        panic!(
12982                            "Cast {src:?}->{dst:?}/Cpu: the production per-target wrapper must be \
12983                             bound FROM the cast contract in global_bindings() — found {} \
12984                             alternative(s) with sources {:?}",
12985                            alts.len(),
12986                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12987                        )
12988                    });
12989                assert_eq!(
12990                    entry.kernel_source, "portable-cpu",
12991                    "Cast {src:?}->{dst:?}: family must be contract-sourced \
12992                     (kernel_source=\"portable-cpu\"); got {:?}",
12993                    entry.kernel_source,
12994                );
12995                assert!(
12996                    !entry.caps.strided_input,
12997                    "Cast {src:?}->{dst:?}: caps preserved (contiguous-only)",
12998                );
12999                assert!(
13000                    entry.precision.bit_stable_on_same_hardware,
13001                    "Cast {src:?}->{dst:?}: contract's bit-stable claim rode through",
13002                );
13003                checked += 1;
13004            }
13005        }
13006        assert_eq!(
13007            checked, 110,
13008            "11 target dtypes × 10 sources each = 110 directed cast pairs (identity excluded)"
13009        );
13010    }
13011
13012    /// Lookup miss returns NoBackendForOp with diagnostic data.
13013    #[test]
13014    fn binding_table_lookup_miss_errors() {
13015        let mut table = KernelBindingTable::new();
13016        register_cpu_kernels(&mut table);
13017        // I64 isn't registered for any elementwise op — must error.
13018        // (BF16/F16/F32/F64 all have AddElementwise wrappers as of
13019        // Phase C's multi-dtype expansion.)
13020        let result = table.lookup(
13021            OpKind::AddElementwise,
13022            &[DType::I64, DType::I64, DType::I64],
13023            BackendId::Cpu,
13024        );
13025        assert!(result.is_err());
13026    }
13027
13028    /// F8E4M3 ↔ {F32, F16, BF16} casts (alpha.29 CastSubBytePlan sibling
13029    /// on the CPU side) are all reachable through the binding table.
13030    #[test]
13031    fn cpu_f8e4m3_cast_pairs_registered() {
13032        let mut table = KernelBindingTable::new();
13033        register_cpu_kernels(&mut table);
13034        for other in [DType::F32, DType::F16, DType::BF16] {
13035            for (src, dst) in [(DType::F8E4M3, other), (other, DType::F8E4M3)] {
13036                table
13037                    .lookup(OpKind::Cast, &[src, dst], BackendId::Cpu)
13038                    .unwrap_or_else(|e| panic!("Cast {src:?} → {dst:?} (CPU) not registered: {e}"));
13039            }
13040        }
13041    }
13042
13043    /// Integer MatMul (i8 / u8) registrations land under the same
13044    /// `(MatMul, [T, T, T], Cpu)` key shape as the float variants.
13045    #[test]
13046    fn cpu_int_matmul_registered() {
13047        let mut table = KernelBindingTable::new();
13048        register_cpu_kernels(&mut table);
13049        for t in [DType::I8, DType::U8] {
13050            table
13051                .lookup(OpKind::MatMul, &[t, t, t], BackendId::Cpu)
13052                .unwrap_or_else(|e| panic!("MatMul {t:?} (CPU) not registered: {e}"));
13053        }
13054    }
13055
13056    /// End-to-end: register, resolve target backend, look up the
13057    /// kernel, allocate input/output Storages, call the kernel,
13058    /// verify output bytes match the elementwise sum. This is the
13059    /// proof-of-concept for the entire B-phase dispatch path.
13060    #[test]
13061    fn b5_end_to_end_add_elementwise_f32() {
13062        // 1. Build registry + capability advertisement.
13063        let mut registry = CapabilityRegistry::new();
13064        registry.register(cpu_caps());
13065
13066        // 2. Resolve which backend handles (AddElementwise, F32).
13067        let backend =
13068            resolve_target_backend(&registry, OpKind::AddElementwise, DType::F32).expect("resolve");
13069        assert_eq!(backend, BackendId::Cpu);
13070
13071        // 3. Build binding table + register CPU wrappers.
13072        let mut bindings = KernelBindingTable::new();
13073        register_cpu_kernels(&mut bindings);
13074
13075        // 4. Look up the kernel for (op, dtypes, backend).
13076        let kernel = bindings
13077            .lookup(
13078                OpKind::AddElementwise,
13079                &[DType::F32, DType::F32, DType::F32],
13080                backend,
13081            )
13082            .expect("lookup");
13083
13084        // 5. Allocate input + output Storages.
13085        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
13086        let rhs = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0]);
13087        let out = fuel_memory::alloc_cpu_zeroed(DType::F32, 4).expect("alloc");
13088
13089        let inputs = vec![Arc::new(RwLock::new(lhs)), Arc::new(RwLock::new(rhs))];
13090        let mut outputs = vec![Arc::new(RwLock::new(out))];
13091
13092        // 6. Call the dispatch wrapper.
13093        kernel(&inputs, &mut outputs, &[], &OpParams::None).expect("kernel");
13094
13095        // 7. Verify output bytes match elementwise sum.
13096        let out_guard = outputs[0].read().unwrap();
13097        if let BackendStorage::Cpu(c) = &out_guard.inner {
13098            let typed: &[f32] = c.as_slice().expect("cast");
13099            assert_eq!(typed, &[11.0, 22.0, 33.0, 44.0]);
13100        } else {
13101            panic!("expected CPU output");
13102        }
13103    }
13104
13105    /// E2E: wrong number of inputs surfaces a typed error.
13106    #[test]
13107    fn b5_wrapper_arity_check() {
13108        let mut bindings = KernelBindingTable::new();
13109        register_cpu_kernels(&mut bindings);
13110        let kernel = bindings
13111            .lookup(
13112                OpKind::AddElementwise,
13113                &[DType::F32, DType::F32, DType::F32],
13114                BackendId::Cpu,
13115            )
13116            .unwrap();
13117
13118        // Only one input — should error, not panic.
13119        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
13120        let out = fuel_memory::alloc_cpu_zeroed(DType::F32, 2).unwrap();
13121        let inputs = vec![Arc::new(RwLock::new(lhs))];
13122        let mut outputs = vec![Arc::new(RwLock::new(out))];
13123
13124        let result = kernel(&inputs, &mut outputs, &[], &OpParams::None);
13125        assert!(result.is_err());
13126    }
13127
13128    /// GAP-015 regression: a held binding-table snapshot must not block a
13129    /// writer, and must not block the holder's own later reads.
13130    ///
13131    /// This is the deadlock reduced to ONE thread, which is what makes it a
13132    /// usable test. The suite-level reproducer needed `--test-threads=24+`
13133    /// to get a writer to queue against readers; here the same cycle is
13134    /// forced deterministically, because under the old
13135    /// `RwLock<KernelBindingTable>` the sequence below is a *self*-deadlock:
13136    /// `global_bindings()` returned a live `RwLockReadGuard`, so asking for
13137    /// the write lock while still holding it waited on a lock this very
13138    /// thread was blocking, forever. Under copy-on-write there is no guard
13139    /// to hold, so it just runs.
13140    ///
13141    /// Watchdog rather than a bare call, because the failure mode is a hang,
13142    /// not a panic: without the timeout this test would wedge the whole
13143    /// binary instead of reporting. Verified born-red — see the commit.
13144    #[test]
13145    fn held_snapshot_does_not_block_a_concurrent_write() {
13146        use std::sync::mpsc;
13147        use std::time::Duration;
13148
13149        let (tx, rx) = mpsc::channel();
13150        std::thread::spawn(move || {
13151            // 1. Take a snapshot and KEEP it across the write below.
13152            let snap = global_bindings();
13153            let before = snap
13154                .lookup(
13155                    OpKind::AddElementwise,
13156                    &[DType::F32, DType::F32, DType::F32],
13157                    BackendId::Cpu,
13158                )
13159                .is_ok();
13160
13161            // 2. Write while that snapshot is still alive. This is the step
13162            //    that deadlocked. The extender is intentionally a no-op —
13163            //    the hazard is the lock transition, not what gets written.
13164            extend_global_bindings(|_t| {});
13165
13166            // 3. Read again while STILL holding the original snapshot. Under
13167            //    std's anti-writer-starvation policy this is the second read
13168            //    that a queued writer would have blocked.
13169            let _snap2 = global_bindings();
13170
13171            // 4. The original snapshot stays usable — it is an owned Arc, so
13172            //    the swap in step 2 cannot invalidate it.
13173            let after = snap
13174                .lookup(
13175                    OpKind::AddElementwise,
13176                    &[DType::F32, DType::F32, DType::F32],
13177                    BackendId::Cpu,
13178                )
13179                .is_ok();
13180
13181            tx.send((before, after)).ok();
13182        });
13183
13184        match rx.recv_timeout(Duration::from_secs(30)) {
13185            Ok((before, after)) => {
13186                assert!(
13187                    before,
13188                    "CPU AddElementwise+F32 should resolve in the snapshot"
13189                );
13190                assert!(
13191                    after,
13192                    "snapshot must stay readable after a concurrent table swap"
13193                );
13194            }
13195            Err(_) => panic!(
13196                "GAP-015 regression: holding a binding-table snapshot across \
13197                 extend_global_bindings() deadlocked (30s watchdog). The read \
13198                 path must hand out an owned snapshot, not a lock guard."
13199            ),
13200        }
13201    }
13202
13203    /// Global registry auto-registers CPU on first access.
13204    #[test]
13205    fn global_registry_auto_registers_cpu() {
13206        // First access initializes the registry with CPU caps.
13207        let r = global_registry();
13208        assert!(!r.backends().is_empty());
13209        // CPU is registered.
13210        let cpu = r.backends().iter().find(|c| c.backend_id == BackendId::Cpu);
13211        assert!(cpu.is_some(), "CPU should be auto-registered");
13212    }
13213
13214    /// Global bindings auto-registers the CPU AddElementwise+F32
13215    /// wrapper on first access.
13216    #[test]
13217    fn global_bindings_auto_registers_cpu_wrappers() {
13218        let b = global_bindings();
13219        let result = b.lookup(
13220            OpKind::AddElementwise,
13221            &[DType::F32, DType::F32, DType::F32],
13222            BackendId::Cpu,
13223        );
13224        assert!(
13225            result.is_ok(),
13226            "CPU AddElementwise+F32 should be registered"
13227        );
13228    }
13229
13230    // `global_bindings_auto_registers_cuda_paths` moved to `fuel-cuda-dispatch/tests/cuda_global_install.rs` (row 137 step 6.2):
13231    // it needs the CUDA kernels in the global table, and they are registered above this crate now.
13232
13233    /// Picker-alternatives audit harness: enumerates the global binding
13234    /// table and prints every `(op, dtypes)` key with `>1` registered
13235    /// alternative (multi-backend or multi-impl within one backend). Read the
13236    /// table with `--nocapture`; the only assertion is that the table is
13237    /// non-empty, so a registry that silently emptied cannot pass as an
13238    /// empty audit.
13239    ///
13240    /// Run: `cargo test -p fuel-dispatch --features cuda,vulkan     ///     audit_multi_backend_coverage -- --nocapture`
13241    #[test]
13242    fn audit_multi_backend_coverage() {
13243        let b = global_bindings();
13244        assert!(
13245            !b.is_empty(),
13246            "the global binding table is empty, so this audit would report nothing"
13247        );
13248
13249        // Group by (op_kind, dtypes); each entry maps to the list of
13250        // (backend, n_alts_within_backend). Iterates via iter_precision
13251        // because that already exposes per-alternative tuples.
13252        // OpKind/DType aren't Ord, so we use Vec-based group lookup.
13253        /// `((op, dtypes), [(backend, count)])` -- one coverage group.
13254        type CoverageGroup = ((OpKind, Vec<DType>), Vec<(BackendId, usize)>);
13255        let mut grouped: Vec<CoverageGroup> = Vec::new();
13256        for (op, dtypes, backend, _precision) in b.iter_precision() {
13257            let key = (op, dtypes.to_vec());
13258            if let Some((_, entry)) = grouped.iter_mut().find(|(k, _)| *k == key) {
13259                if let Some(slot) = entry.iter_mut().find(|(be, _)| *be == backend) {
13260                    slot.1 += 1;
13261                } else {
13262                    entry.push((backend, 1));
13263                }
13264            } else {
13265                grouped.push((key, vec![(backend, 1)]));
13266            }
13267        }
13268        // Sort by op debug-string, then dtype list, for stable output.
13269        grouped.sort_by(|a, b| {
13270            let oa = format!("{:?}", a.0.0);
13271            let ob = format!("{:?}", b.0.0);
13272            oa.cmp(&ob).then_with(|| {
13273                let da = format!("{:?}", a.0.1);
13274                let db = format!("{:?}", b.0.1);
13275                da.cmp(&db)
13276            })
13277        });
13278
13279        let total_keys = grouped.len();
13280        let mut multi_backend = 0;
13281        let mut multi_impl_single_backend = 0;
13282        let mut single_alt = 0;
13283
13284        println!("\n=== Picker-alternatives audit ===");
13285        println!("Total unique (op, dtypes) keys: {total_keys}");
13286        println!("Total alternatives (sum):       {}", b.len());
13287        println!();
13288        println!("Keys with >1 alternative (per Judge-picking working set):");
13289        for ((op, dtypes), backends) in &grouped {
13290            let total_alts: usize = backends.iter().map(|(_, n)| *n).sum();
13291            if total_alts <= 1 {
13292                single_alt += 1;
13293                continue;
13294            }
13295            if backends.len() > 1 {
13296                multi_backend += 1;
13297            } else {
13298                multi_impl_single_backend += 1;
13299            }
13300            let backend_summary: Vec<String> = backends
13301                .iter()
13302                .map(|(be, n)| {
13303                    if *n == 1 {
13304                        format!("{be:?}")
13305                    } else {
13306                        format!("{be:?}×{n}")
13307                    }
13308                })
13309                .collect();
13310            println!(
13311                "  {op:?} {dtypes:?} → {} alts: [{}]",
13312                total_alts,
13313                backend_summary.join(", "),
13314            );
13315        }
13316        println!();
13317        println!("--- summary ---");
13318        println!("Single-alternative keys (no pick to make): {single_alt}");
13319        println!("Multi-backend keys (cross-backend pick):   {multi_backend}");
13320        println!("Multi-impl single-backend keys:            {multi_impl_single_backend}");
13321    }
13322
13323    // =========================================================================
13324    // Step E Phase C / B1 — DEVICE_INFLIGHT counter (the BALANCE gate)
13325    // =========================================================================
13326    //
13327    // The counter is PROCESS-WIDE, so these tests use sentinel `gpu_id`s no
13328    // real device uses (and that no other test in this binary touches) to stay
13329    // independent of any concurrent counter activity.
13330
13331    /// The crux of B1: after a balanced sequence of `inc`/`dec`, the per-device
13332    /// count returns to its baseline. Mirrors the executor's invariant — every
13333    /// async submit (`inc`) is matched by exactly one completion-handle `Drop`
13334    /// (`dec`), so after a realize fully drains the counter is back where it
13335    /// started (the `drain_handles` empty-map assert, in counter form).
13336    #[test]
13337    fn inflight_inc_dec_balances_to_baseline() {
13338        let loc = DeviceLocation::Cuda { gpu_id: 99_001 };
13339        let base = inflight_count(loc);
13340
13341        // N submits in flight → count rises by N.
13342        const N: u32 = 7;
13343        for i in 0..N {
13344            inflight_inc(loc);
13345            assert_eq!(
13346                inflight_count(loc),
13347                base + i + 1,
13348                "inc must raise the count"
13349            );
13350        }
13351        assert_eq!(inflight_count(loc), base + N);
13352
13353        // N completions retire → count falls back to baseline.
13354        for i in 0..N {
13355            inflight_dec(loc);
13356            assert_eq!(
13357                inflight_count(loc),
13358                base + N - i - 1,
13359                "dec must lower the count",
13360            );
13361        }
13362        assert_eq!(
13363            inflight_count(loc),
13364            base,
13365            "balanced inc/dec must return the count to its pre-sequence baseline",
13366        );
13367    }
13368
13369    /// `inflight_dec` is underflow-saturating: decrementing a device whose count
13370    /// is already 0 (or that has never been touched) leaves it at 0, never wraps
13371    /// to `u32::MAX`. A stray dec is harmless to scheduling, never a poison.
13372    #[test]
13373    fn backlog_unfed_device_has_no_estimate_then_balances() {
13374        // A location no other test touches (distinct gpu_id).
13375        let loc = DeviceLocation::Vulkan { gpu_id: 9_001 };
13376        assert_eq!(
13377            backlog_estimate_ns(loc),
13378            None,
13379            "a device nobody fed reports NO estimate, not 0"
13380        );
13381        backlog_add_ns(loc, 1_000);
13382        backlog_add_ns(loc, 500);
13383        assert_eq!(backlog_estimate_ns(loc), Some(1_500));
13384        backlog_sub_ns(loc, 1_000);
13385        assert_eq!(backlog_estimate_ns(loc), Some(500));
13386        backlog_sub_ns(loc, 9_999);
13387        assert_eq!(
13388            backlog_estimate_ns(loc),
13389            Some(0),
13390            "sub saturates at 0, and a fed-then-drained device reports 0 (idle), not None"
13391        );
13392        // Sabotage sibling: sub on a never-fed device must not create a slot.
13393        let other = DeviceLocation::Vulkan { gpu_id: 9_002 };
13394        backlog_sub_ns(other, 5);
13395        assert_eq!(backlog_estimate_ns(other), None);
13396    }
13397
13398    // ---- BacklogLedger (ROADMAP row 158, the executor feed). Each test uses its own `gpu_id` so the
13399    // process-wide table cannot be shared with another test; each clause has a sabotage sibling.
13400
13401    /// The guard's Drop subtracts EXACTLY what it added: after it the device reads Some(0) (fed, now idle),
13402    /// and while it lives the figure is the sum added.
13403    #[test]
13404    fn ledger_drop_subtracts_exactly_what_it_added() {
13405        let loc = DeviceLocation::Vulkan { gpu_id: 9_101 };
13406        {
13407            let mut ledger = BacklogLedger::new();
13408            ledger.add(loc, 1_000);
13409            ledger.add(loc, 500);
13410            assert_eq!(backlog_estimate_ns(loc), Some(1_500));
13411            assert_eq!(ledger.outstanding_ns(loc), 1_500);
13412        }
13413        assert_eq!(
13414            backlog_estimate_ns(loc),
13415            Some(0),
13416            "a realize that ended leaves its device idle (0), not stuck and not unknown"
13417        );
13418    }
13419
13420    /// Sabotage sibling of the above: a ledger that is LEAKED (never dropped) leaves the backlog up. Proves
13421    /// the balance in the test above comes from `Drop`, not from the adds cancelling by themselves.
13422    #[test]
13423    fn a_leaked_ledger_leaves_the_backlog_up() {
13424        let loc = DeviceLocation::Vulkan { gpu_id: 9_102 };
13425        let mut ledger = BacklogLedger::new();
13426        ledger.add(loc, 700);
13427        std::mem::forget(ledger);
13428        assert_eq!(
13429            backlog_estimate_ns(loc),
13430            Some(700),
13431            "without the Drop subtract the work stays counted: the guard is what balances it"
13432        );
13433    }
13434
13435    /// An error (here a panic standing in for any early `?` return) unwinding the realize still takes the
13436    /// work back out: the guard is not an Ok-path-only step.
13437    #[test]
13438    fn ledger_balances_when_the_realize_unwinds() {
13439        let loc = DeviceLocation::Vulkan { gpu_id: 9_103 };
13440        let r = std::panic::catch_unwind(|| {
13441            let mut ledger = BacklogLedger::new();
13442            ledger.add(loc, 4_000);
13443            assert_eq!(backlog_estimate_ns(loc), Some(4_000));
13444            panic!("a node failed mid-walk");
13445        });
13446        assert!(r.is_err(), "the closure must have panicked");
13447        assert_eq!(backlog_estimate_ns(loc), Some(0));
13448        // And an early `?` return, the other way a walk ends in an error.
13449        fn walk(loc: DeviceLocation) -> std::result::Result<(), &'static str> {
13450            let mut ledger = BacklogLedger::new();
13451            ledger.add(loc, 250);
13452            let failed: std::result::Result<(), &'static str> = Err("node failed");
13453            failed?;
13454            drop(ledger);
13455            Ok(())
13456        }
13457        let loc2 = DeviceLocation::Vulkan { gpu_id: 9_104 };
13458        assert!(walk(loc2).is_err());
13459        assert_eq!(backlog_estimate_ns(loc2), Some(0));
13460    }
13461
13462    /// Two realizes on one device (multi-agent serving): each takes back only its own work, so the second
13463    /// one's resolver sees the first one's outstanding backlog and nothing it did not add.
13464    #[test]
13465    fn concurrent_ledgers_each_subtract_only_their_own() {
13466        let loc = DeviceLocation::Vulkan { gpu_id: 9_105 };
13467        let mut first = BacklogLedger::new();
13468        first.add(loc, 3_000);
13469        {
13470            let mut second = BacklogLedger::new();
13471            second.add(loc, 200);
13472            assert_eq!(backlog_estimate_ns(loc), Some(3_200));
13473        }
13474        assert_eq!(
13475            backlog_estimate_ns(loc),
13476            Some(3_000),
13477            "the second realize ending must leave the first one's work counted"
13478        );
13479        drop(first);
13480        assert_eq!(backlog_estimate_ns(loc), Some(0));
13481    }
13482
13483    /// The CPU has no queue to estimate and a zero estimate is no estimate: neither may create a slot,
13484    /// because a device nobody priced must keep reporting NO estimate (`None`), never a fabricated idle.
13485    /// Positive control: a real add on the same ledger does create one.
13486    #[test]
13487    fn ledger_never_feeds_cpu_or_a_zero_estimate() {
13488        let unpriced = DeviceLocation::Vulkan { gpu_id: 9_106 };
13489        let mut ledger = BacklogLedger::new();
13490        ledger.add(DeviceLocation::Cpu, 5_000);
13491        ledger.add(unpriced, 0);
13492        assert_eq!(backlog_estimate_ns(DeviceLocation::Cpu), None);
13493        assert_eq!(backlog_estimate_ns(unpriced), None);
13494        assert_eq!(ledger.outstanding_ns(DeviceLocation::Cpu), 0);
13495        // Positive control: the same ledger, a real estimate on a real device.
13496        let priced = DeviceLocation::Vulkan { gpu_id: 9_107 };
13497        ledger.add(priced, 10);
13498        assert_eq!(backlog_estimate_ns(priced), Some(10));
13499    }
13500
13501    // ---- Retire on completion (ROADMAP row 158): the backlog is QUEUED work. A fed estimate carries a
13502    // non-blocking probe; `retire_completed` takes back exactly the estimates whose probe reports done.
13503
13504    /// Completion retires EXACTLY that op's estimate, not the others'.
13505    #[test]
13506    fn completion_retires_exactly_that_ops_estimate() {
13507        use std::sync::atomic::{AtomicBool, Ordering};
13508        let loc = DeviceLocation::Vulkan { gpu_id: 9_110 };
13509        let first = Arc::new(AtomicBool::new(false));
13510        let second = Arc::new(AtomicBool::new(false));
13511        let mut ledger = BacklogLedger::new();
13512        let (f, g) = (Arc::clone(&first), Arc::clone(&second));
13513        ledger.add_until(loc, 300, move || f.load(Ordering::Relaxed));
13514        ledger.add_until(loc, 200, move || g.load(Ordering::Relaxed));
13515        assert_eq!(backlog_estimate_ns(loc), Some(500));
13516        first.store(true, Ordering::Relaxed);
13517        ledger.retire_completed();
13518        assert_eq!(
13519            backlog_estimate_ns(loc),
13520            Some(200),
13521            "only the finished op's 300 ns left"
13522        );
13523        assert_eq!(ledger.outstanding_ns(loc), 200);
13524        second.store(true, Ordering::Relaxed);
13525        ledger.retire_completed();
13526        assert_eq!(
13527            backlog_estimate_ns(loc),
13528            Some(0),
13529            "drained, and idle (0), not unknown"
13530        );
13531        assert_eq!(ledger.outstanding_ns(loc), 0);
13532    }
13533
13534    /// Sabotage sibling: a probe that never fires retires nothing, however often `retire_completed` runs.
13535    /// (This is the cumulative behaviour the feature removes; the acceptance run reproduces it with
13536    /// `FUEL_BACKLOG_NO_RETIRE=1`.)
13537    #[test]
13538    fn a_probe_that_never_fires_retires_nothing() {
13539        let loc = DeviceLocation::Vulkan { gpu_id: 9_111 };
13540        let mut ledger = BacklogLedger::new();
13541        ledger.add_until(loc, 400, || false);
13542        ledger.add(loc, 100); // no probe at all
13543        for _ in 0..5 {
13544            ledger.retire_completed();
13545        }
13546        assert_eq!(backlog_estimate_ns(loc), Some(500));
13547        assert_eq!(ledger.outstanding_ns(loc), 500);
13548    }
13549
13550    /// An op that FAILS or is DROPPED never completes by its probe: the ledger's `Drop` still takes its
13551    /// estimate back, so the backlog cannot leak (here the ledger is dropped with a probe that never fired,
13552    /// as when an error unwinds the realize).
13553    #[test]
13554    fn a_failed_or_dropped_op_is_also_retired() {
13555        let loc = DeviceLocation::Vulkan { gpu_id: 9_112 };
13556        {
13557            let mut ledger = BacklogLedger::new();
13558            ledger.add_until(loc, 250, || false);
13559            assert_eq!(backlog_estimate_ns(loc), Some(250));
13560        }
13561        assert_eq!(backlog_estimate_ns(loc), Some(0));
13562    }
13563
13564    /// No negative backlog: retiring an estimate that something else already took back saturates at 0, it
13565    /// never wraps to a huge figure.
13566    #[test]
13567    fn retiring_never_drives_the_backlog_negative() {
13568        let loc = DeviceLocation::Vulkan { gpu_id: 9_113 };
13569        let mut ledger = BacklogLedger::new();
13570        ledger.add_until(loc, 100, || true);
13571        backlog_sub_ns(loc, 100); // another path already took it back
13572        ledger.retire_completed();
13573        assert_eq!(backlog_estimate_ns(loc), Some(0));
13574        // Positive control: the same figure after a second, normal add is exact, so the 0 above is a
13575        // saturation and not a dead counter.
13576        ledger.add_until(loc, 60, || true);
13577        assert_eq!(backlog_estimate_ns(loc), Some(60));
13578        ledger.retire_completed();
13579        assert_eq!(backlog_estimate_ns(loc), Some(0));
13580    }
13581
13582    #[test]
13583    fn inflight_dec_is_underflow_safe() {
13584        let untouched = DeviceLocation::Vulkan { gpu_id: 99_002 };
13585        // Never incremented: dec must not create a wrapped count.
13586        inflight_dec(untouched);
13587        assert_eq!(
13588            inflight_count(untouched),
13589            0,
13590            "dec on an untouched device stays 0"
13591        );
13592
13593        let loc = DeviceLocation::Vulkan { gpu_id: 99_003 };
13594        inflight_inc(loc);
13595        inflight_dec(loc);
13596        assert_eq!(inflight_count(loc), 0);
13597        // One extra dec past zero (the over-drain guard).
13598        inflight_dec(loc);
13599        assert_eq!(
13600            inflight_count(loc),
13601            0,
13602            "extra dec past zero must saturate, not wrap"
13603        );
13604    }
13605
13606    /// Distinct `DeviceLocation`s have independent slots — incrementing one
13607    /// device's count never perturbs another's (the per-device keying the
13608    /// selector relies on to compare CUDA vs Vulkan load).
13609    #[test]
13610    fn inflight_counts_are_per_device_independent() {
13611        let cuda = DeviceLocation::Cuda { gpu_id: 99_004 };
13612        let vulkan = DeviceLocation::Vulkan { gpu_id: 99_004 };
13613        let base_c = inflight_count(cuda);
13614        let base_v = inflight_count(vulkan);
13615
13616        inflight_inc(cuda);
13617        inflight_inc(cuda);
13618        inflight_inc(vulkan);
13619
13620        assert_eq!(inflight_count(cuda), base_c + 2);
13621        assert_eq!(inflight_count(vulkan), base_v + 1);
13622
13623        inflight_dec(cuda);
13624        inflight_dec(cuda);
13625        inflight_dec(vulkan);
13626        assert_eq!(inflight_count(cuda), base_c);
13627        assert_eq!(inflight_count(vulkan), base_v);
13628    }
13629
13630    /// FKC cost unification — Part A. `derive_backend_caps` reads a
13631    /// backend's kernels out of the binding table and advertises the
13632    /// `(OpKind, OUTPUT-dtype)` pairs those kernels cover — the general
13633    /// analogue of the hand-maintained `default_cpu_caps`. Verifies:
13634    /// (1) only the requested backend's keys are picked; (2) the OUTPUT
13635    /// dtype (last operand) is what's advertised for multi-dtype keys;
13636    /// (3) substrate/device match the backend. Feature-independent: it
13637    /// builds a fresh table with synthetic wrappers.
13638    #[test]
13639    fn derive_backend_caps_mirrors_binding_table_output_dtypes() {
13640        fn stub(
13641            _i: &[Arc<RwLock<Storage>>],
13642            _o: &mut [Arc<RwLock<Storage>>],
13643            _l: &[Layout],
13644            _p: &OpParams,
13645        ) -> Result<()> {
13646            Ok(())
13647        }
13648        fn stub_b(
13649            _i: &[Arc<RwLock<Storage>>],
13650            _o: &mut [Arc<RwLock<Storage>>],
13651            _l: &[Layout],
13652            _p: &OpParams,
13653        ) -> Result<()> {
13654            Ok(())
13655        }
13656        fn stub_c(
13657            _i: &[Arc<RwLock<Storage>>],
13658            _o: &mut [Arc<RwLock<Storage>>],
13659            _l: &[Layout],
13660            _p: &OpParams,
13661        ) -> Result<()> {
13662            Ok(())
13663        }
13664
13665        let mut table = KernelBindingTable::new();
13666        // A CPU key that MUST NOT bleed into the Vulkan derivation.
13667        table.register(
13668            OpKind::AddElementwise,
13669            &[DType::F32, DType::F32, DType::F32],
13670            BackendId::Cpu,
13671            stub,
13672        );
13673        // Vulkan: an elementwise key (single output dtype) ...
13674        table.register(
13675            OpKind::MulElementwise,
13676            &[DType::F32, DType::F32, DType::F32],
13677            BackendId::Vulkan,
13678            stub_b,
13679        );
13680        // ... and a MIXED-dtype key: inputs F16/F16, OUTPUT F32. The
13681        // derived pair must key on the OUTPUT dtype (F32), not an input.
13682        table.register(
13683            OpKind::MatMul,
13684            &[DType::F16, DType::F16, DType::F32],
13685            BackendId::Vulkan,
13686            stub_c,
13687        );
13688
13689        let vk0 = DeviceLocation::Vulkan { gpu_id: 0 };
13690        let caps = derive_backend_caps(BackendId::Vulkan, vk0, &table);
13691
13692        assert_eq!(caps.backend_id, BackendId::Vulkan);
13693        assert_eq!(caps.device_location, vk0);
13694        assert_eq!(caps.storage_substrate, SubstrateClass::VulkanBuffer);
13695        // Elementwise output dtype advertised.
13696        assert!(
13697            caps.op_dtype_support
13698                .contains(&(OpKind::MulElementwise, DType::F32))
13699        );
13700        // Multi-dtype key advertises the OUTPUT dtype (F32), not F16.
13701        assert!(
13702            caps.op_dtype_support
13703                .contains(&(OpKind::MatMul, DType::F32))
13704        );
13705        assert!(
13706            !caps
13707                .op_dtype_support
13708                .contains(&(OpKind::MatMul, DType::F16))
13709        );
13710        // The CPU key is NOT attributed to Vulkan.
13711        assert!(
13712            !caps
13713                .op_dtype_support
13714                .contains(&(OpKind::AddElementwise, DType::F32))
13715        );
13716        // A universal host-staging path back to CPU is advertised so the
13717        // transfer matrix can price GPU↔CPU crossings.
13718        assert!(caps
13719            .transfer_paths
13720            .iter()
13721            .any(|&(dst, path)| dst == DeviceLocation::Cpu && path == TransferPath::HostStaging));
13722    }
13723
13724    /// CapturedRun executor build-out (4b-ζ): `copy_from_cuda_wrapper`'s
13725    /// CUDA-output branch converted from allocate-and-replace
13726    /// (`slot_copy_to_new` + `*dst = copied`) to write-into
13727    /// (`CudaStorageBytes::copy_from_device`). Byte-compares the new
13728    /// write-into result against the OLD `slot_copy_to_new`-based behavior
13729    /// for a non-trivial (17-element, mixed-value) case, AND confirms the
13730    /// destination's buffer identity (device address) is preserved — the
13731    /// property capture-safety depends on (allocate-and-replace would swap
13732    /// in a fresh `Arc<DeviceBuffer<u8>>`, changing the address; write-into
13733    /// must not).
13734    #[test]
13735    #[ignore = "requires a live CUDA device"]
13736    #[cfg(feature = "cuda")]
13737    fn copy_from_cuda_wrapper_cuda_output_write_into_matches_old_behavior() {
13738        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
13739
13740        let Ok(dev) = CudaDevice::new(0) else {
13741            return fuel_test_support::hardware::skip(
13742                fuel_test_support::hardware::Hardware::Cuda,
13743                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
13744            );
13745        };
13746
13747        let src_data: Vec<f32> = (0..17).map(|i| i as f32 * 1.5 - 3.0).collect();
13748        let src_bytes: Vec<u8> = src_data.iter().flat_map(|f| f.to_le_bytes()).collect();
13749        let src_cb = CudaStorageBytes::from_cpu_bytes(&dev, &src_bytes).expect("h2d src");
13750        let src_arc: Arc<RwLock<Storage>> = Arc::new(RwLock::new(Storage::new(
13751            BackendStorage::Cuda(src_cb),
13752            DType::F32,
13753        )));
13754
13755        // Pre-allocated output filled with distinguishable garbage — proves
13756        // the write-into path actually overwrites every byte, not just
13757        // reads through stale garbage by luck.
13758        let garbage: Vec<u8> = vec![0xAAu8; src_bytes.len()];
13759        let dst_cb = CudaStorageBytes::from_cpu_bytes(&dev, &garbage).expect("h2d garbage");
13760        let dst_arc: Arc<RwLock<Storage>> = Arc::new(RwLock::new(Storage::new(
13761            BackendStorage::Cuda(dst_cb),
13762            DType::F32,
13763        )));
13764
13765        // Destination buffer identity BEFORE the wrapper runs.
13766        let before_ptr = {
13767            let g = dst_arc.read().unwrap();
13768            let BackendStorage::Cuda(c) = &g.inner else {
13769                panic!("not cuda")
13770            };
13771            c.buffer() as *const _ as usize
13772        };
13773
13774        let inputs = vec![Arc::clone(&src_arc)];
13775        let mut outputs = vec![Arc::clone(&dst_arc)];
13776        copy_from_cuda_wrapper(&inputs, &mut outputs, &[], &OpParams::None)
13777            .expect("copy_from_cuda_wrapper (write-into CUDA branch)");
13778
13779        let after_ptr = {
13780            let g = dst_arc.read().unwrap();
13781            let BackendStorage::Cuda(c) = &g.inner else {
13782                panic!("not cuda")
13783            };
13784            c.buffer() as *const _ as usize
13785        };
13786        assert_eq!(
13787            before_ptr, after_ptr,
13788            "write-into must preserve the output's buffer identity (device address)"
13789        );
13790
13791        let new_bytes = {
13792            let g = dst_arc.read().unwrap();
13793            let BackendStorage::Cuda(c) = &g.inner else {
13794                panic!("not cuda")
13795            };
13796            c.to_cpu_bytes().expect("d2h new")
13797        };
13798
13799        // Independently reproduce the OLD allocate-and-replace behavior
13800        // (`slot_copy_to_new`) from the SAME source, for comparison.
13801        let old_bytes = {
13802            let g = src_arc.read().unwrap();
13803            let BackendStorage::Cuda(c) = &g.inner else {
13804                panic!("not cuda")
13805            };
13806            let copied = c
13807                .slot_copy_to_new(0, c.len_bytes())
13808                .expect("slot_copy_to_new (old allocate-and-replace path)");
13809            copied.to_cpu_bytes().expect("d2h old")
13810        };
13811
13812        assert_eq!(
13813            new_bytes, old_bytes,
13814            "write-into result must byte-match the old slot_copy_to_new result"
13815        );
13816        assert_eq!(new_bytes, src_bytes, "and both must match the source bytes");
13817    }
13818}