Skip to main content

fuel_vulkan_dispatch/
vulkan_dispatch.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Dispatch wrappers + registration for Vulkan-backed kernels.
3//! Sibling to `baracuda_dispatch` (CUDA) and the CPU dispatch in
4//! `dispatch.rs`. Each kernel registers as an alternative at the
5//! `(op_kind, dtypes, BackendId::Vulkan)` decision point in the
6//! shared `KernelBindingTable`.
7//!
8//! ## V.1 status
9//!
10//! Phase 7.6 step 9c Vulkan catch-up V.1.C — the proof-of-life
11//! milestone. One op (`Add f32`) wired end-to-end through the
12//! pipelined-executor binding-table dispatch:
13//! 1. The executor's `fuel_dispatch::pipelined::execute_work_item` output-
14//!    allocation match arm sees `BackendId::Vulkan` and allocates
15//!    via [`fuel_vulkan_backend::VulkanBackend::alloc_bytes_handle`]
16//!    (V.1.B).
17//! 2. The kernel wrapper here reads inputs (also `VulkanStorageBytes`
18//!    with backend handle attached), pulls the backend Arc from the
19//!    first input, and calls
20//!    [`fuel_vulkan_backend::VulkanBackend::binary_add_f32_bytes`]
21//!    to dispatch.
22//! 3. The Slang `binary.spv` kernel runs on the Vulkan device; the
23//!    pre-allocated output buffer carries the result.
24//!
25//! V.2 fans out registrations to the ~25 already-compiled SPIR-V
26//! kernels in `fuel-vulkan-kernels`. V.3 writes new Slang for the
27//! kernel families CUDA has and Vulkan doesn't.
28
29use std::sync::{Arc, RwLock};
30
31// ⚠️ NOT UNUSED — `rustc` IS WRONG HERE, AND DELETING IT COSTS 177 ERRORS.
32//
33// `OpKind` is named on 178 code lines in this file, but 177 of them are inside
34// inner `mod`s that reach it through `use super::*`. `unused_imports` does not
35// count a use that arrives via a child module's glob, so it reports the import
36// as dead while the file cannot compile without it.
37//
38// Measured, not argued, and twice independently: removing this line and
39// building `--features vulkan --all-targets` gives
40// `could not compile fuel-dispatch (lib test) due to 177 previous errors`,
41// all `E0425: cannot find type/value OpKind in this scope`. Restored both
42// times.
43//
44// An `#[allow]` rather than a removal, and the reason is the point: "unused"
45// and "named on 178 lines" cannot both be true, so the lint is the thing that
46// is wrong. (Counting those errors with `grep -c '^error\[E0425\]'` gives 14,
47// not 177 -- rustc does not repeat the code prefix at line start for every
48// instance. Count the message text.)
49#[allow(unused_imports)]
50use fuel_ir::dispatch::OpKind;
51use fuel_ir::probe::BackendId;
52use fuel_ir::{DType, Error, Layout, Result};
53
54use fuel_dispatch::kernel::{KernelBindingTable, OpParams};
55use fuel_memory::Storage;
56
57// Re-use the storage-lock helpers from dispatch.rs.
58use fuel_dispatch::dispatch::{read_storage, write_storage};
59
60/// Helper: extract `&VulkanStorageBytes` from `&Storage`. Returns
61/// `Err` if the variant isn't `BackendStorage::Vulkan`.
62fn vulkan_input(s: &Storage) -> Result<&fuel_vulkan_backend::VulkanStorageBytes> {
63    match &s.inner {
64        fuel_memory::BackendStorage::Vulkan(v) => Ok(v),
65        #[allow(unreachable_patterns)]
66        _ => Err(Error::Msg("vulkan kernel wrapper called with non-Vulkan input".to_string()).bt()),
67    }
68}
69
70/// GAP-415: decline an out-of-range index READ before it is dispatched (KISS-OPS-6.11-0004/-0015).
71///
72/// The first `numel` U32 values of `ids` are read back and compared with `bound` before dispatch. The
73/// read flushes and waits for the device, once per call.
74fn decline_oob_index_read(
75    op: &'static str,
76    backend: &fuel_vulkan_backend::VulkanBackend,
77    ids: &fuel_vulkan_backend::VulkanStorageBytes,
78    numel: usize,
79    bound: usize,
80) -> Result<()> {
81    if numel == 0 {
82        return Ok(());
83    }
84    let bytes = backend.download_bytes(ids)?;
85    let words = bytes.as_chunks::<4>().0;
86    if words.len() < numel {
87        return Err(Error::Msg(format!(
88            "{op}: index buffer holds {} values, {numel} are needed",
89            words.len()
90        ))
91        .bt());
92    }
93    for raw in &words[..numel] {
94        let index = u32::from_le_bytes(*raw) as usize;
95        if index >= bound {
96            return Err(Error::InvalidIndex {
97                op,
98                index,
99                size: bound,
100            }
101            .bt());
102        }
103    }
104    Ok(())
105}
106
107/// Helper: extract `&mut VulkanStorageBytes` from `&mut Storage`.
108fn vulkan_output(s: &mut Storage) -> Result<&mut fuel_vulkan_backend::VulkanStorageBytes> {
109    match &mut s.inner {
110        fuel_memory::BackendStorage::Vulkan(v) => Ok(v),
111        #[allow(unreachable_patterns)]
112        _ => {
113            Err(Error::Msg("vulkan kernel wrapper called with non-Vulkan output".to_string()).bt())
114        }
115    }
116}
117
118// ===========================================================================
119// Binary — element-wise f32 (V.2.A: Add/Sub/Mul/Div/Max/Min)
120// ===========================================================================
121//
122// One wrapper per op; all six route through
123// `VulkanBackend::binary_f32_bytes(op_id, ...)` which uses the same
124// `binary.spv` Slang kernel with the `op_id` push constant
125// selecting the actual math. Mirrors baracuda_dispatch's per-op
126// wrapper shape.
127
128/// Generate one binary-f32 KernelRef-shaped wrapper that calls
129/// `VulkanBackend::binary_f32_bytes` with the given op_id + label.
130macro_rules! vk_binary_f32_wrapper {
131    ($name:ident, $op_id:expr, $label:expr $(,)?) => {
132        pub fn $name(
133            inputs: &[Arc<RwLock<Storage>>],
134            outputs: &mut [Arc<RwLock<Storage>>],
135            layouts: &[Layout],
136            _params: &OpParams,
137        ) -> Result<()> {
138            if inputs.len() != 2 || outputs.len() != 1 {
139                return Err(Error::Msg(format!(
140                    "vulkan_dispatch::binary::{}: expected 2 inputs + 1 output, got {} + {}",
141                    $label,
142                    inputs.len(),
143                    outputs.len(),
144                ))
145                .bt());
146            }
147            if layouts.len() < 2 {
148                return Err(Error::Msg(format!(
149                    "vulkan_dispatch::binary::{}: layouts.len() = {} < 2",
150                    $label,
151                    layouts.len(),
152                ))
153                .bt());
154            }
155            let in0_guard = read_storage(&inputs[0])?;
156            let in1_guard = read_storage(&inputs[1])?;
157            let mut out_guard = write_storage(&outputs[0])?;
158            let a = vulkan_input(&in0_guard)?;
159            let b = vulkan_input(&in1_guard)?;
160            let backend = a.backend().ok_or_else(|| {
161                Error::Msg(format!(
162                    "vulkan_dispatch::binary::{}: input[0] has no VulkanBackend handle. \
163                     Storages flowing through the pipelined-executor binding-table \
164                     dispatch must come from alloc_bytes_handle / upload_bytes_handle.",
165                    $label,
166                ))
167                .bt()
168            })?;
169            let out = vulkan_output(&mut out_guard)?;
170            backend.binary_f32_bytes($op_id, $label, a, b, out, &layouts[0], &layouts[1])
171        }
172    };
173}
174
175/// Vulkan dispatch wrappers for f32 elementwise binary ops (add, sub, mul, div, maximum, minimum).
176pub mod binary {
177    use super::*;
178
179    vk_binary_f32_wrapper!(add_f32, 0, "binary_add_f32");
180    vk_binary_f32_wrapper!(sub_f32, 1, "binary_sub_f32");
181    vk_binary_f32_wrapper!(mul_f32, 2, "binary_mul_f32");
182    vk_binary_f32_wrapper!(div_f32, 3, "binary_div_f32");
183    vk_binary_f32_wrapper!(maximum_f32, 4, "binary_maximum_f32");
184    vk_binary_f32_wrapper!(minimum_f32, 5, "binary_minimum_f32");
185}
186
187// V.3.E — f16 binary fan-out via native float16_t.
188
189macro_rules! vk_binary_f16_wrapper {
190    ($name:ident, $op_id:expr, $label:expr $(,)?) => {
191        pub fn $name(
192            inputs: &[Arc<RwLock<Storage>>],
193            outputs: &mut [Arc<RwLock<Storage>>],
194            layouts: &[Layout],
195            _params: &OpParams,
196        ) -> Result<()> {
197            if inputs.len() != 2 || outputs.len() != 1 {
198                return Err(Error::Msg(format!(
199                    "vulkan_dispatch::binary_f16::{}: expected 2 inputs + 1 output, got {} + {}",
200                    $label,
201                    inputs.len(),
202                    outputs.len(),
203                ))
204                .bt());
205            }
206            if layouts.len() < 2 {
207                return Err(Error::Msg(format!(
208                    "vulkan_dispatch::binary_f16::{}: layouts.len() = {} < 2",
209                    $label,
210                    layouts.len(),
211                ))
212                .bt());
213            }
214            let in0_guard = read_storage(&inputs[0])?;
215            let in1_guard = read_storage(&inputs[1])?;
216            let mut out_guard = write_storage(&outputs[0])?;
217            let a = vulkan_input(&in0_guard)?;
218            let b = vulkan_input(&in1_guard)?;
219            let backend = a.backend().ok_or_else(|| {
220                Error::Msg(format!(
221                    "vulkan_dispatch::binary_f16::{}: input[0] has no VulkanBackend handle. \
222                     Storages flowing through the pipelined-executor binding-table \
223                     dispatch must come from alloc_bytes_handle / upload_bytes_handle.",
224                    $label,
225                ))
226                .bt()
227            })?;
228            let out = vulkan_output(&mut out_guard)?;
229            backend.binary_f16_bytes($op_id, $label, a, b, out, &layouts[0], &layouts[1])
230        }
231    };
232}
233
234/// Vulkan dispatch wrappers for f16 elementwise binary ops (add, sub, mul, div, maximum, minimum).
235pub mod binary_f16 {
236    use super::*;
237
238    vk_binary_f16_wrapper!(add_f16, 0, "binary_add_f16");
239    vk_binary_f16_wrapper!(sub_f16, 1, "binary_sub_f16");
240    vk_binary_f16_wrapper!(mul_f16, 2, "binary_mul_f16");
241    vk_binary_f16_wrapper!(div_f16, 3, "binary_div_f16");
242    vk_binary_f16_wrapper!(maximum_f16, 4, "binary_maximum_f16");
243    vk_binary_f16_wrapper!(minimum_f16, 5, "binary_minimum_f16");
244}
245
246// V.3.E.5 — f64 binary fan-out via native `double`.
247
248macro_rules! vk_binary_f64_wrapper {
249    ($name:ident, $op_id:expr, $label:expr $(,)?) => {
250        pub fn $name(
251            inputs: &[Arc<RwLock<Storage>>],
252            outputs: &mut [Arc<RwLock<Storage>>],
253            layouts: &[Layout],
254            _params: &OpParams,
255        ) -> Result<()> {
256            if inputs.len() != 2 || outputs.len() != 1 {
257                return Err(Error::Msg(format!(
258                    "vulkan_dispatch::binary_f64::{}: expected 2 inputs + 1 output, got {} + {}",
259                    $label,
260                    inputs.len(),
261                    outputs.len(),
262                ))
263                .bt());
264            }
265            if layouts.len() < 2 {
266                return Err(Error::Msg(format!(
267                    "vulkan_dispatch::binary_f64::{}: layouts.len() = {} < 2",
268                    $label,
269                    layouts.len(),
270                ))
271                .bt());
272            }
273            let in0_guard = read_storage(&inputs[0])?;
274            let in1_guard = read_storage(&inputs[1])?;
275            let mut out_guard = write_storage(&outputs[0])?;
276            let a = vulkan_input(&in0_guard)?;
277            let b = vulkan_input(&in1_guard)?;
278            let backend = a.backend().ok_or_else(|| {
279                Error::Msg(format!(
280                    "vulkan_dispatch::binary_f64::{}: input[0] has no VulkanBackend handle.",
281                    $label,
282                ))
283                .bt()
284            })?;
285            let out = vulkan_output(&mut out_guard)?;
286            backend.binary_f64_bytes($op_id, $label, a, b, out, &layouts[0], &layouts[1])
287        }
288    };
289}
290
291/// Vulkan dispatch wrappers for f64 elementwise binary ops.
292pub mod binary_f64 {
293    use super::*;
294
295    vk_binary_f64_wrapper!(add_f64, 0, "binary_add_f64");
296    vk_binary_f64_wrapper!(sub_f64, 1, "binary_sub_f64");
297    vk_binary_f64_wrapper!(mul_f64, 2, "binary_mul_f64");
298    vk_binary_f64_wrapper!(div_f64, 3, "binary_div_f64");
299    vk_binary_f64_wrapper!(maximum_f64, 4, "binary_maximum_f64");
300    vk_binary_f64_wrapper!(minimum_f64, 5, "binary_minimum_f64");
301}
302
303// ===========================================================================
304// Unary — element-wise f32 (V.2.B: 13 ops via unary.slang's op_id)
305// ===========================================================================
306
307macro_rules! vk_unary_f32_wrapper {
308    ($name:ident, $op_id:expr, $label:expr $(,)?) => {
309        pub fn $name(
310            inputs: &[Arc<RwLock<Storage>>],
311            outputs: &mut [Arc<RwLock<Storage>>],
312            layouts: &[Layout],
313            _params: &OpParams,
314        ) -> Result<()> {
315            if inputs.len() != 1 || outputs.len() != 1 {
316                return Err(Error::Msg(format!(
317                    "vulkan_dispatch::unary::{}: expected 1 input + 1 output, got {} + {}",
318                    $label,
319                    inputs.len(),
320                    outputs.len(),
321                ))
322                .bt());
323            }
324            if layouts.is_empty() {
325                return Err(Error::Msg(format!(
326                    "vulkan_dispatch::unary::{}: layouts.len() = 0, expected >= 1",
327                    $label,
328                ))
329                .bt());
330            }
331            let in_guard = read_storage(&inputs[0])?;
332            let mut out_guard = write_storage(&outputs[0])?;
333            let a = vulkan_input(&in_guard)?;
334            let backend = a.backend().ok_or_else(|| {
335                Error::Msg(format!(
336                    "vulkan_dispatch::unary::{}: input has no VulkanBackend handle. \
337                     Storages flowing through the pipelined-executor binding-table \
338                     dispatch must come from alloc_bytes_handle / upload_bytes_handle.",
339                    $label,
340                ))
341                .bt()
342            })?;
343            let out = vulkan_output(&mut out_guard)?;
344            backend.unary_f32_bytes($op_id, $label, a, out, &layouts[0])
345        }
346    };
347}
348
349/// Vulkan dispatch wrappers for f32 elementwise unary ops (neg, sqr, sqrt, exp, log, sin, cos, tanh, ...).
350pub mod unary {
351    use super::*;
352
353    vk_unary_f32_wrapper!(neg_f32, 0, "unary_neg_f32");
354    vk_unary_f32_wrapper!(sqr_f32, 1, "unary_sqr_f32");
355    vk_unary_f32_wrapper!(sqrt_f32, 2, "unary_sqrt_f32");
356    vk_unary_f32_wrapper!(exp_f32, 3, "unary_exp_f32");
357    vk_unary_f32_wrapper!(log_f32, 4, "unary_log_f32");
358    vk_unary_f32_wrapper!(sin_f32, 5, "unary_sin_f32");
359    vk_unary_f32_wrapper!(cos_f32, 6, "unary_cos_f32");
360    vk_unary_f32_wrapper!(tanh_f32, 7, "unary_tanh_f32");
361    vk_unary_f32_wrapper!(sigmoid_f32, 8, "unary_sigmoid_f32");
362    vk_unary_f32_wrapper!(silu_f32, 9, "unary_silu_f32");
363    vk_unary_f32_wrapper!(gelu_f32, 10, "unary_gelu_f32");
364    vk_unary_f32_wrapper!(relu_f32, 11, "unary_relu_f32");
365    vk_unary_f32_wrapper!(step_f32, 12, "unary_step_f32");
366    vk_unary_f32_wrapper!(abs_f32, 13, "unary_abs_f32");
367    vk_unary_f32_wrapper!(sign_f32, 14, "unary_sign_f32");
368    vk_unary_f32_wrapper!(recip_f32, 15, "unary_recip_f32");
369}
370
371// V.3.E — f16 fan-out via native float16_t (shaderFloat16 + 16BitStorage).
372
373macro_rules! vk_unary_f16_wrapper {
374    ($name:ident, $op_id:expr, $label:expr $(,)?) => {
375        pub fn $name(
376            inputs: &[Arc<RwLock<Storage>>],
377            outputs: &mut [Arc<RwLock<Storage>>],
378            layouts: &[Layout],
379            _params: &OpParams,
380        ) -> Result<()> {
381            if inputs.len() != 1 || outputs.len() != 1 {
382                return Err(Error::Msg(format!(
383                    "vulkan_dispatch::unary_f16::{}: expected 1 input + 1 output, got {} + {}",
384                    $label,
385                    inputs.len(),
386                    outputs.len(),
387                ))
388                .bt());
389            }
390            if layouts.is_empty() {
391                return Err(Error::Msg(format!(
392                    "vulkan_dispatch::unary_f16::{}: layouts.len() = 0, expected >= 1",
393                    $label,
394                ))
395                .bt());
396            }
397            let in_guard = read_storage(&inputs[0])?;
398            let mut out_guard = write_storage(&outputs[0])?;
399            let a = vulkan_input(&in_guard)?;
400            let backend = a.backend().ok_or_else(|| {
401                Error::Msg(format!(
402                    "vulkan_dispatch::unary_f16::{}: input has no VulkanBackend handle. \
403                     Storages flowing through the pipelined-executor binding-table \
404                     dispatch must come from alloc_bytes_handle / upload_bytes_handle.",
405                    $label,
406                ))
407                .bt()
408            })?;
409            let out = vulkan_output(&mut out_guard)?;
410            backend.unary_f16_bytes($op_id, $label, a, out, &layouts[0])
411        }
412    };
413}
414
415/// Vulkan dispatch wrappers for f16 elementwise unary ops.
416pub mod unary_f16 {
417    use super::*;
418
419    vk_unary_f16_wrapper!(neg_f16, 0, "unary_neg_f16");
420    vk_unary_f16_wrapper!(sqr_f16, 1, "unary_sqr_f16");
421    vk_unary_f16_wrapper!(sqrt_f16, 2, "unary_sqrt_f16");
422    vk_unary_f16_wrapper!(exp_f16, 3, "unary_exp_f16");
423    vk_unary_f16_wrapper!(log_f16, 4, "unary_log_f16");
424    vk_unary_f16_wrapper!(sin_f16, 5, "unary_sin_f16");
425    vk_unary_f16_wrapper!(cos_f16, 6, "unary_cos_f16");
426    vk_unary_f16_wrapper!(tanh_f16, 7, "unary_tanh_f16");
427    vk_unary_f16_wrapper!(sigmoid_f16, 8, "unary_sigmoid_f16");
428    vk_unary_f16_wrapper!(silu_f16, 9, "unary_silu_f16");
429    vk_unary_f16_wrapper!(gelu_f16, 10, "unary_gelu_f16");
430    vk_unary_f16_wrapper!(relu_f16, 11, "unary_relu_f16");
431    vk_unary_f16_wrapper!(step_f16, 12, "unary_step_f16");
432    vk_unary_f16_wrapper!(abs_f16, 13, "unary_abs_f16");
433    vk_unary_f16_wrapper!(sign_f16, 14, "unary_sign_f16");
434    vk_unary_f16_wrapper!(recip_f16, 15, "unary_recip_f16");
435}
436
437// V.3.E.5 — f64 fan-out via native `double` (shaderFloat64).
438
439macro_rules! vk_unary_f64_wrapper {
440    ($name:ident, $op_id:expr, $label:expr $(,)?) => {
441        pub fn $name(
442            inputs: &[Arc<RwLock<Storage>>],
443            outputs: &mut [Arc<RwLock<Storage>>],
444            layouts: &[Layout],
445            _params: &OpParams,
446        ) -> Result<()> {
447            if inputs.len() != 1 || outputs.len() != 1 {
448                return Err(Error::Msg(format!(
449                    "vulkan_dispatch::unary_f64::{}: expected 1 input + 1 output, got {} + {}",
450                    $label,
451                    inputs.len(),
452                    outputs.len(),
453                ))
454                .bt());
455            }
456            if layouts.is_empty() {
457                return Err(Error::Msg(format!(
458                    "vulkan_dispatch::unary_f64::{}: layouts.len() = 0, expected >= 1",
459                    $label,
460                ))
461                .bt());
462            }
463            let in_guard = read_storage(&inputs[0])?;
464            let mut out_guard = write_storage(&outputs[0])?;
465            let a = vulkan_input(&in_guard)?;
466            let backend = a.backend().ok_or_else(|| {
467                Error::Msg(format!(
468                    "vulkan_dispatch::unary_f64::{}: input has no VulkanBackend handle. \
469                     Storages flowing through the pipelined-executor binding-table \
470                     dispatch must come from alloc_bytes_handle / upload_bytes_handle.",
471                    $label,
472                ))
473                .bt()
474            })?;
475            let out = vulkan_output(&mut out_guard)?;
476            backend.unary_f64_bytes($op_id, $label, a, out, &layouts[0])
477        }
478    };
479}
480
481/// Vulkan dispatch wrappers for f64 elementwise unary ops.
482pub mod unary_f64 {
483    use super::*;
484
485    vk_unary_f64_wrapper!(neg_f64, 0, "unary_neg_f64");
486    vk_unary_f64_wrapper!(sqr_f64, 1, "unary_sqr_f64");
487    vk_unary_f64_wrapper!(sqrt_f64, 2, "unary_sqrt_f64");
488    vk_unary_f64_wrapper!(exp_f64, 3, "unary_exp_f64");
489    vk_unary_f64_wrapper!(log_f64, 4, "unary_log_f64");
490    vk_unary_f64_wrapper!(sin_f64, 5, "unary_sin_f64");
491    vk_unary_f64_wrapper!(cos_f64, 6, "unary_cos_f64");
492    vk_unary_f64_wrapper!(tanh_f64, 7, "unary_tanh_f64");
493    vk_unary_f64_wrapper!(sigmoid_f64, 8, "unary_sigmoid_f64");
494    vk_unary_f64_wrapper!(silu_f64, 9, "unary_silu_f64");
495    vk_unary_f64_wrapper!(gelu_f64, 10, "unary_gelu_f64");
496    vk_unary_f64_wrapper!(relu_f64, 11, "unary_relu_f64");
497    vk_unary_f64_wrapper!(step_f64, 12, "unary_step_f64");
498    vk_unary_f64_wrapper!(abs_f64, 13, "unary_abs_f64");
499    vk_unary_f64_wrapper!(sign_f64, 14, "unary_sign_f64");
500    vk_unary_f64_wrapper!(recip_f64, 15, "unary_recip_f64");
501}
502
503// ===========================================================================
504// Softmax — last-dim f32 (V.2.C)
505// ===========================================================================
506//
507// One wrapper for Softmax (LogSoftmax is V.3 — no Slang kernel yet).
508// Pulls `(outer_count, last_dim)` from `OpParams::SoftmaxLastDim` and
509// forwards to `VulkanBackend::softmax_last_dim_f32_bytes`.
510
511/// Vulkan dispatch wrappers for softmax over the last dimension, forward and backward, per dtype.
512pub mod softmax {
513    use super::*;
514
515    // Internal helper: extract (outer_count, last_dim) from
516    // OpParams::SoftmaxLastDim, with a tagged error on mismatch.
517    fn softmax_params(fn_name: &str, params: &OpParams) -> Result<(usize, usize)> {
518        match params {
519            OpParams::SoftmaxLastDim { outer_count, last_dim } => Ok((*outer_count, *last_dim)),
520            other => Err(Error::Msg(format!(
521                "vulkan_dispatch::softmax::{fn_name}: expected OpParams::SoftmaxLastDim, got {other:?}",
522            )).bt()),
523        }
524    }
525
526    /// `softmax_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
527    pub fn softmax_f32(
528        inputs: &[Arc<RwLock<Storage>>],
529        outputs: &mut [Arc<RwLock<Storage>>],
530        _layouts: &[Layout],
531        params: &OpParams,
532    ) -> Result<()> {
533        if inputs.len() != 1 || outputs.len() != 1 {
534            return Err(Error::Msg(format!(
535                "vulkan_dispatch::softmax::softmax_f32: expected 1 input + 1 output, got {} + {}",
536                inputs.len(),
537                outputs.len(),
538            ))
539            .bt());
540        }
541        let (outer_count, last_dim) = softmax_params("softmax_f32", params)?;
542        let in_guard = read_storage(&inputs[0])?;
543        let mut out_guard = write_storage(&outputs[0])?;
544        let a = vulkan_input(&in_guard)?;
545        let backend = a.backend().ok_or_else(|| {
546            Error::Msg(
547                "vulkan_dispatch::softmax::softmax_f32: input has no VulkanBackend handle. \
548                 Storages flowing through the pipelined-executor binding-table dispatch \
549                 must come from alloc_bytes_handle / upload_bytes_handle."
550                    .to_string(),
551            )
552            .bt()
553        })?;
554        let out = vulkan_output(&mut out_guard)?;
555        backend.softmax_last_dim_f32_bytes(a, out, outer_count, last_dim)
556    }
557
558    /// `softmax_f16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
559    pub fn softmax_f16(
560        inputs: &[Arc<RwLock<Storage>>],
561        outputs: &mut [Arc<RwLock<Storage>>],
562        _layouts: &[Layout],
563        params: &OpParams,
564    ) -> Result<()> {
565        if inputs.len() != 1 || outputs.len() != 1 {
566            return Err(Error::Msg(format!(
567                "vulkan_dispatch::softmax::softmax_f16: expected 1 input + 1 output, got {} + {}",
568                inputs.len(),
569                outputs.len(),
570            ))
571            .bt());
572        }
573        let (outer_count, last_dim) = softmax_params("softmax_f16", params)?;
574        let in_guard = read_storage(&inputs[0])?;
575        let mut out_guard = write_storage(&outputs[0])?;
576        let a = vulkan_input(&in_guard)?;
577        let backend = a.backend().ok_or_else(|| {
578            Error::Msg(
579                "vulkan_dispatch::softmax::softmax_f16: input has no VulkanBackend handle."
580                    .to_string(),
581            )
582            .bt()
583        })?;
584        let out = vulkan_output(&mut out_guard)?;
585        backend.softmax_last_dim_f16_bytes(a, out, outer_count, last_dim)
586    }
587
588    /// `softmax_bf16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
589    pub fn softmax_bf16(
590        inputs: &[Arc<RwLock<Storage>>],
591        outputs: &mut [Arc<RwLock<Storage>>],
592        _layouts: &[Layout],
593        params: &OpParams,
594    ) -> Result<()> {
595        if inputs.len() != 1 || outputs.len() != 1 {
596            return Err(Error::Msg(format!(
597                "vulkan_dispatch::softmax::softmax_bf16: expected 1 input + 1 output, got {} + {}",
598                inputs.len(),
599                outputs.len(),
600            ))
601            .bt());
602        }
603        let (outer_count, last_dim) = softmax_params("softmax_bf16", params)?;
604        let in_guard = read_storage(&inputs[0])?;
605        let mut out_guard = write_storage(&outputs[0])?;
606        let a = vulkan_input(&in_guard)?;
607        let backend = a.backend().ok_or_else(|| {
608            Error::Msg(
609                "vulkan_dispatch::softmax::softmax_bf16: input has no VulkanBackend handle."
610                    .to_string(),
611            )
612            .bt()
613        })?;
614        let out = vulkan_output(&mut out_guard)?;
615        backend.softmax_last_dim_bf16_bytes(a, out, outer_count, last_dim)
616    }
617
618    /// `softmax_f64` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
619    pub fn softmax_f64(
620        inputs: &[Arc<RwLock<Storage>>],
621        outputs: &mut [Arc<RwLock<Storage>>],
622        _layouts: &[Layout],
623        params: &OpParams,
624    ) -> Result<()> {
625        if inputs.len() != 1 || outputs.len() != 1 {
626            return Err(Error::Msg(format!(
627                "vulkan_dispatch::softmax::softmax_f64: expected 1 input + 1 output, got {} + {}",
628                inputs.len(),
629                outputs.len(),
630            ))
631            .bt());
632        }
633        let (outer_count, last_dim) = softmax_params("softmax_f64", params)?;
634        let in_guard = read_storage(&inputs[0])?;
635        let mut out_guard = write_storage(&outputs[0])?;
636        let a = vulkan_input(&in_guard)?;
637        let backend = a.backend().ok_or_else(|| {
638            Error::Msg(
639                "vulkan_dispatch::softmax::softmax_f64: input has no VulkanBackend handle."
640                    .to_string(),
641            )
642            .bt()
643        })?;
644        let out = vulkan_output(&mut out_guard)?;
645        backend.softmax_last_dim_f64_bytes(a, out, outer_count, last_dim)
646    }
647
648    // ----- SoftmaxLastDimBackward (V.3.G.softmax-bwd, 2026-05-30) -----
649    // 2 inputs (y, g) → 1 output (dx). Reuses OpParams::SoftmaxLastDim
650    // (same outer × last_dim contract as the forward).
651
652    /// `softmax_last_dim_backward_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
653    pub fn softmax_last_dim_backward_f32(
654        inputs: &[Arc<RwLock<Storage>>],
655        outputs: &mut [Arc<RwLock<Storage>>],
656        layouts: &[Layout],
657        params: &OpParams,
658    ) -> Result<()> {
659        softmax_backward_typed(
660            "softmax_last_dim_backward_f32",
661            inputs,
662            outputs,
663            layouts,
664            params,
665            |b, y, g, dx, oc, ld| b.softmax_last_dim_backward_f32_bytes(y, g, dx, oc, ld),
666        )
667    }
668
669    /// `softmax_last_dim_backward_f16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
670    pub fn softmax_last_dim_backward_f16(
671        inputs: &[Arc<RwLock<Storage>>],
672        outputs: &mut [Arc<RwLock<Storage>>],
673        layouts: &[Layout],
674        params: &OpParams,
675    ) -> Result<()> {
676        softmax_backward_typed(
677            "softmax_last_dim_backward_f16",
678            inputs,
679            outputs,
680            layouts,
681            params,
682            |b, y, g, dx, oc, ld| b.softmax_last_dim_backward_f16_bytes(y, g, dx, oc, ld),
683        )
684    }
685
686    /// `softmax_last_dim_backward_bf16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
687    pub fn softmax_last_dim_backward_bf16(
688        inputs: &[Arc<RwLock<Storage>>],
689        outputs: &mut [Arc<RwLock<Storage>>],
690        layouts: &[Layout],
691        params: &OpParams,
692    ) -> Result<()> {
693        softmax_backward_typed(
694            "softmax_last_dim_backward_bf16",
695            inputs,
696            outputs,
697            layouts,
698            params,
699            |b, y, g, dx, oc, ld| b.softmax_last_dim_backward_bf16_bytes(y, g, dx, oc, ld),
700        )
701    }
702
703    /// `softmax_last_dim_backward_f64` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
704    pub fn softmax_last_dim_backward_f64(
705        inputs: &[Arc<RwLock<Storage>>],
706        outputs: &mut [Arc<RwLock<Storage>>],
707        layouts: &[Layout],
708        params: &OpParams,
709    ) -> Result<()> {
710        softmax_backward_typed(
711            "softmax_last_dim_backward_f64",
712            inputs,
713            outputs,
714            layouts,
715            params,
716            |b, y, g, dx, oc, ld| b.softmax_last_dim_backward_f64_bytes(y, g, dx, oc, ld),
717        )
718    }
719
720    fn softmax_backward_typed<F>(
721        label: &'static str,
722        inputs: &[Arc<RwLock<Storage>>],
723        outputs: &mut [Arc<RwLock<Storage>>],
724        _layouts: &[Layout],
725        params: &OpParams,
726        call: F,
727    ) -> Result<()>
728    where
729        F: FnOnce(
730            &fuel_vulkan_backend::VulkanBackend,
731            &fuel_vulkan_backend::VulkanStorageBytes,
732            &fuel_vulkan_backend::VulkanStorageBytes,
733            &mut fuel_vulkan_backend::VulkanStorageBytes,
734            usize,
735            usize,
736        ) -> fuel_ir::Result<()>,
737    {
738        if inputs.len() != 2 || outputs.len() != 1 {
739            return Err(Error::Msg(format!(
740                "vulkan_dispatch::softmax::{label}: expected 2 inputs (y, g) + 1 output, got {} + {}",
741                inputs.len(), outputs.len(),
742            )).bt());
743        }
744        let (outer_count, last_dim) = softmax_params(label, params)?;
745        let y_guard = read_storage(&inputs[0])?;
746        let g_guard = read_storage(&inputs[1])?;
747        let mut dx_guard = write_storage(&outputs[0])?;
748        let y = vulkan_input(&y_guard)?;
749        let g = vulkan_input(&g_guard)?;
750        let backend = y.backend().ok_or_else(|| {
751            Error::Msg(format!(
752                "vulkan_dispatch::softmax::{label}: y has no VulkanBackend handle.",
753            ))
754            .bt()
755        })?;
756        let dx = vulkan_output(&mut dx_guard)?;
757        call(backend, y, g, dx, outer_count, last_dim)
758    }
759}
760
761// ===========================================================================
762// Norm — RmsNorm last-dim f32 (V.2.C)
763// ===========================================================================
764//
765// LayerNorm is V.3 (no Slang kernel yet). RmsNorm pulls
766// `(outer_count, last_dim, eps)` from `OpParams::NormLastDim`.
767
768/// Vulkan dispatch wrappers for last-dimension normalisation (RMSNorm and LayerNorm, forward and backward), per dtype.
769pub mod norm {
770    use super::*;
771
772    // Internal helper: pull (outer_count, last_dim, eps) from the
773    // OpParams::NormLastDim variant, returning a tagged error if the
774    // executor passed the wrong params shape.
775    fn norm_params(fn_name: &str, params: &OpParams) -> Result<(usize, usize, f64)> {
776        match params {
777            OpParams::NormLastDim {
778                outer_count,
779                last_dim,
780                eps,
781            } => Ok((*outer_count, *last_dim, *eps)),
782            other => Err(Error::Msg(format!(
783                "vulkan_dispatch::norm::{fn_name}: expected OpParams::NormLastDim, got {other:?}",
784            ))
785            .bt()),
786        }
787    }
788
789    /// `rms_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
790    pub fn rms_f32(
791        inputs: &[Arc<RwLock<Storage>>],
792        outputs: &mut [Arc<RwLock<Storage>>],
793        _layouts: &[Layout],
794        params: &OpParams,
795    ) -> Result<()> {
796        if inputs.len() != 1 || outputs.len() != 1 {
797            return Err(Error::Msg(format!(
798                "vulkan_dispatch::norm::rms_f32: expected 1 input + 1 output, got {} + {}",
799                inputs.len(),
800                outputs.len(),
801            ))
802            .bt());
803        }
804        let (outer_count, last_dim, eps) = norm_params("rms_f32", params)?;
805        let in_guard = read_storage(&inputs[0])?;
806        let mut out_guard = write_storage(&outputs[0])?;
807        let a = vulkan_input(&in_guard)?;
808        let backend = a.backend().ok_or_else(|| {
809            Error::Msg(
810                "vulkan_dispatch::norm::rms_f32: input has no VulkanBackend handle. \
811                 Storages flowing through the pipelined-executor binding-table dispatch \
812                 must come from alloc_bytes_handle / upload_bytes_handle."
813                    .to_string(),
814            )
815            .bt()
816        })?;
817        let out = vulkan_output(&mut out_guard)?;
818        backend.rms_norm_last_dim_f32_bytes(a, out, outer_count, last_dim, eps)
819    }
820
821    /// `rms_f16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
822    pub fn rms_f16(
823        inputs: &[Arc<RwLock<Storage>>],
824        outputs: &mut [Arc<RwLock<Storage>>],
825        _layouts: &[Layout],
826        params: &OpParams,
827    ) -> Result<()> {
828        if inputs.len() != 1 || outputs.len() != 1 {
829            return Err(Error::Msg(format!(
830                "vulkan_dispatch::norm::rms_f16: expected 1 input + 1 output, got {} + {}",
831                inputs.len(),
832                outputs.len(),
833            ))
834            .bt());
835        }
836        let (outer_count, last_dim, eps) = norm_params("rms_f16", params)?;
837        let in_guard = read_storage(&inputs[0])?;
838        let mut out_guard = write_storage(&outputs[0])?;
839        let a = vulkan_input(&in_guard)?;
840        let backend = a.backend().ok_or_else(|| {
841            Error::Msg(
842                "vulkan_dispatch::norm::rms_f16: input has no VulkanBackend handle.".to_string(),
843            )
844            .bt()
845        })?;
846        let out = vulkan_output(&mut out_guard)?;
847        backend.rms_norm_last_dim_f16_bytes(a, out, outer_count, last_dim, eps)
848    }
849
850    /// `rms_bf16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
851    pub fn rms_bf16(
852        inputs: &[Arc<RwLock<Storage>>],
853        outputs: &mut [Arc<RwLock<Storage>>],
854        _layouts: &[Layout],
855        params: &OpParams,
856    ) -> Result<()> {
857        if inputs.len() != 1 || outputs.len() != 1 {
858            return Err(Error::Msg(format!(
859                "vulkan_dispatch::norm::rms_bf16: expected 1 input + 1 output, got {} + {}",
860                inputs.len(),
861                outputs.len(),
862            ))
863            .bt());
864        }
865        let (outer_count, last_dim, eps) = norm_params("rms_bf16", params)?;
866        let in_guard = read_storage(&inputs[0])?;
867        let mut out_guard = write_storage(&outputs[0])?;
868        let a = vulkan_input(&in_guard)?;
869        let backend = a.backend().ok_or_else(|| {
870            Error::Msg(
871                "vulkan_dispatch::norm::rms_bf16: input has no VulkanBackend handle.".to_string(),
872            )
873            .bt()
874        })?;
875        let out = vulkan_output(&mut out_guard)?;
876        backend.rms_norm_last_dim_bf16_bytes(a, out, outer_count, last_dim, eps)
877    }
878
879    // ----- LayerNormLastDimBackward (V.3.G.layer_norm_bwd, 2026-05-30) -----
880    // 2 inputs (x, g) → 1 output (dx). Reuses OpParams::NormLastDim.
881
882    /// `layer_norm_backward_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
883    pub fn layer_norm_backward_f32(
884        inputs: &[Arc<RwLock<Storage>>],
885        outputs: &mut [Arc<RwLock<Storage>>],
886        _layouts: &[Layout],
887        params: &OpParams,
888    ) -> Result<()> {
889        layer_norm_bwd_typed(
890            "layer_norm_backward_f32",
891            inputs,
892            outputs,
893            params,
894            |b, x, g, dx, oc, ld, eps| {
895                b.layer_norm_last_dim_backward_f32_bytes(x, g, dx, oc, ld, eps)
896            },
897        )
898    }
899    /// `layer_norm_backward_f16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
900    pub fn layer_norm_backward_f16(
901        inputs: &[Arc<RwLock<Storage>>],
902        outputs: &mut [Arc<RwLock<Storage>>],
903        _layouts: &[Layout],
904        params: &OpParams,
905    ) -> Result<()> {
906        layer_norm_bwd_typed(
907            "layer_norm_backward_f16",
908            inputs,
909            outputs,
910            params,
911            |b, x, g, dx, oc, ld, eps| {
912                b.layer_norm_last_dim_backward_f16_bytes(x, g, dx, oc, ld, eps)
913            },
914        )
915    }
916    /// `layer_norm_backward_bf16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
917    pub fn layer_norm_backward_bf16(
918        inputs: &[Arc<RwLock<Storage>>],
919        outputs: &mut [Arc<RwLock<Storage>>],
920        _layouts: &[Layout],
921        params: &OpParams,
922    ) -> Result<()> {
923        layer_norm_bwd_typed(
924            "layer_norm_backward_bf16",
925            inputs,
926            outputs,
927            params,
928            |b, x, g, dx, oc, ld, eps| {
929                b.layer_norm_last_dim_backward_bf16_bytes(x, g, dx, oc, ld, eps)
930            },
931        )
932    }
933    /// `layer_norm_backward_f64` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
934    pub fn layer_norm_backward_f64(
935        inputs: &[Arc<RwLock<Storage>>],
936        outputs: &mut [Arc<RwLock<Storage>>],
937        _layouts: &[Layout],
938        params: &OpParams,
939    ) -> Result<()> {
940        layer_norm_bwd_typed(
941            "layer_norm_backward_f64",
942            inputs,
943            outputs,
944            params,
945            |b, x, g, dx, oc, ld, eps| {
946                b.layer_norm_last_dim_backward_f64_bytes(x, g, dx, oc, ld, eps)
947            },
948        )
949    }
950
951    fn layer_norm_bwd_typed<F>(
952        label: &'static str,
953        inputs: &[Arc<RwLock<Storage>>],
954        outputs: &mut [Arc<RwLock<Storage>>],
955        params: &OpParams,
956        call: F,
957    ) -> Result<()>
958    where
959        F: FnOnce(
960            &fuel_vulkan_backend::VulkanBackend,
961            &fuel_vulkan_backend::VulkanStorageBytes,
962            &fuel_vulkan_backend::VulkanStorageBytes,
963            &mut fuel_vulkan_backend::VulkanStorageBytes,
964            usize,
965            usize,
966            f64,
967        ) -> fuel_ir::Result<()>,
968    {
969        if inputs.len() != 2 || outputs.len() != 1 {
970            return Err(Error::Msg(format!(
971                "vulkan_dispatch::norm::{label}: expected 2 inputs (x, g) + 1 output, got {} + {}",
972                inputs.len(),
973                outputs.len(),
974            ))
975            .bt());
976        }
977        let (outer_count, last_dim, eps) = norm_params(label, params)?;
978        let x_guard = read_storage(&inputs[0])?;
979        let g_guard = read_storage(&inputs[1])?;
980        let mut dx_guard = write_storage(&outputs[0])?;
981        let x = vulkan_input(&x_guard)?;
982        let g = vulkan_input(&g_guard)?;
983        let backend = x.backend().ok_or_else(|| {
984            Error::Msg(format!(
985                "vulkan_dispatch::norm::{label}: x has no VulkanBackend handle.",
986            ))
987            .bt()
988        })?;
989        let dx = vulkan_output(&mut dx_guard)?;
990        call(backend, x, g, dx, outer_count, last_dim, eps)
991    }
992
993    // ----- LayerNorm (V.3.G.layer_norm, 2026-05-30) -----
994
995    /// `layer_norm_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
996    pub fn layer_norm_f32(
997        inputs: &[Arc<RwLock<Storage>>],
998        outputs: &mut [Arc<RwLock<Storage>>],
999        _layouts: &[Layout],
1000        params: &OpParams,
1001    ) -> Result<()> {
1002        layer_norm_typed(
1003            "layer_norm_f32",
1004            inputs,
1005            outputs,
1006            params,
1007            |b, i, o, oc, ld, eps| b.layer_norm_last_dim_f32_bytes(i, o, oc, ld, eps),
1008        )
1009    }
1010    /// `layer_norm_f16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1011    pub fn layer_norm_f16(
1012        inputs: &[Arc<RwLock<Storage>>],
1013        outputs: &mut [Arc<RwLock<Storage>>],
1014        _layouts: &[Layout],
1015        params: &OpParams,
1016    ) -> Result<()> {
1017        layer_norm_typed(
1018            "layer_norm_f16",
1019            inputs,
1020            outputs,
1021            params,
1022            |b, i, o, oc, ld, eps| b.layer_norm_last_dim_f16_bytes(i, o, oc, ld, eps),
1023        )
1024    }
1025    /// `layer_norm_bf16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1026    pub fn layer_norm_bf16(
1027        inputs: &[Arc<RwLock<Storage>>],
1028        outputs: &mut [Arc<RwLock<Storage>>],
1029        _layouts: &[Layout],
1030        params: &OpParams,
1031    ) -> Result<()> {
1032        layer_norm_typed(
1033            "layer_norm_bf16",
1034            inputs,
1035            outputs,
1036            params,
1037            |b, i, o, oc, ld, eps| b.layer_norm_last_dim_bf16_bytes(i, o, oc, ld, eps),
1038        )
1039    }
1040    /// `layer_norm_f64` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1041    pub fn layer_norm_f64(
1042        inputs: &[Arc<RwLock<Storage>>],
1043        outputs: &mut [Arc<RwLock<Storage>>],
1044        _layouts: &[Layout],
1045        params: &OpParams,
1046    ) -> Result<()> {
1047        layer_norm_typed(
1048            "layer_norm_f64",
1049            inputs,
1050            outputs,
1051            params,
1052            |b, i, o, oc, ld, eps| b.layer_norm_last_dim_f64_bytes(i, o, oc, ld, eps),
1053        )
1054    }
1055
1056    fn layer_norm_typed<F>(
1057        label: &'static str,
1058        inputs: &[Arc<RwLock<Storage>>],
1059        outputs: &mut [Arc<RwLock<Storage>>],
1060        params: &OpParams,
1061        call: F,
1062    ) -> Result<()>
1063    where
1064        F: FnOnce(
1065            &fuel_vulkan_backend::VulkanBackend,
1066            &fuel_vulkan_backend::VulkanStorageBytes,
1067            &mut fuel_vulkan_backend::VulkanStorageBytes,
1068            usize,
1069            usize,
1070            f64,
1071        ) -> fuel_ir::Result<()>,
1072    {
1073        if inputs.len() != 1 || outputs.len() != 1 {
1074            return Err(Error::Msg(format!(
1075                "vulkan_dispatch::norm::{label}: expected 1 input + 1 output, got {} + {}",
1076                inputs.len(),
1077                outputs.len(),
1078            ))
1079            .bt());
1080        }
1081        let (outer_count, last_dim, eps) = norm_params(label, params)?;
1082        let in_guard = read_storage(&inputs[0])?;
1083        let mut out_guard = write_storage(&outputs[0])?;
1084        let a = vulkan_input(&in_guard)?;
1085        let backend = a.backend().ok_or_else(|| {
1086            Error::Msg(format!(
1087                "vulkan_dispatch::norm::{label}: input has no VulkanBackend handle.",
1088            ))
1089            .bt()
1090        })?;
1091        let out = vulkan_output(&mut out_guard)?;
1092        call(backend, a, out, outer_count, last_dim, eps)
1093    }
1094
1095    /// `rms_f64` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1096    pub fn rms_f64(
1097        inputs: &[Arc<RwLock<Storage>>],
1098        outputs: &mut [Arc<RwLock<Storage>>],
1099        _layouts: &[Layout],
1100        params: &OpParams,
1101    ) -> Result<()> {
1102        if inputs.len() != 1 || outputs.len() != 1 {
1103            return Err(Error::Msg(format!(
1104                "vulkan_dispatch::norm::rms_f64: expected 1 input + 1 output, got {} + {}",
1105                inputs.len(),
1106                outputs.len(),
1107            ))
1108            .bt());
1109        }
1110        let (outer_count, last_dim, eps) = norm_params("rms_f64", params)?;
1111        let in_guard = read_storage(&inputs[0])?;
1112        let mut out_guard = write_storage(&outputs[0])?;
1113        let a = vulkan_input(&in_guard)?;
1114        let backend = a.backend().ok_or_else(|| {
1115            Error::Msg(
1116                "vulkan_dispatch::norm::rms_f64: input has no VulkanBackend handle.".to_string(),
1117            )
1118            .bt()
1119        })?;
1120        let out = vulkan_output(&mut out_guard)?;
1121        backend.rms_norm_last_dim_f64_bytes(a, out, outer_count, last_dim, eps)
1122    }
1123}
1124
1125// ===========================================================================
1126// Attention — RoPE f32 (V.2.C)
1127// ===========================================================================
1128//
1129// 3 storage inputs: x, cos, sin. The Vulkan kernel uses pre-computed
1130// cos/sin tables (unlike the CUDA baracuda path which rebuilds them
1131// from `seq + head_dim`). `OpParams::Rope` carries the geometry.
1132
1133/// Vulkan dispatch wrappers for rotary position embedding (RoPE), per dtype.
1134pub mod attention {
1135    use super::*;
1136
1137    /// `rope_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1138    pub fn rope_f32(
1139        inputs: &[Arc<RwLock<Storage>>],
1140        outputs: &mut [Arc<RwLock<Storage>>],
1141        layouts: &[Layout],
1142        params: &OpParams,
1143    ) -> Result<()> {
1144        if inputs.len() != 3 || outputs.len() != 1 {
1145            return Err(Error::Msg(format!(
1146                "vulkan_dispatch::attention::rope_f32: expected 3 inputs (x,cos,sin) + 1 output, got {} + {}",
1147                inputs.len(), outputs.len(),
1148            )).bt());
1149        }
1150        // Validate params shape (we don't actually need to read the
1151        // fields — the x-layout carries the geometry the kernel
1152        // wants — but mismatched params signal an executor bug).
1153        match params {
1154            OpParams::Rope { .. } => {}
1155            other => {
1156                return Err(Error::Msg(format!(
1157                    "vulkan_dispatch::attention::rope_f32: expected OpParams::Rope, got {:?}",
1158                    other,
1159                ))
1160                .bt());
1161            }
1162        }
1163        if layouts.is_empty() {
1164            return Err(Error::Msg(
1165                "vulkan_dispatch::attention::rope_f32: layouts.len() = 0, need x-layout".into(),
1166            )
1167            .bt());
1168        }
1169        let x_guard = read_storage(&inputs[0])?;
1170        let cos_guard = read_storage(&inputs[1])?;
1171        let sin_guard = read_storage(&inputs[2])?;
1172        let mut out_guard = write_storage(&outputs[0])?;
1173        let x = vulkan_input(&x_guard)?;
1174        let cos = vulkan_input(&cos_guard)?;
1175        let sin = vulkan_input(&sin_guard)?;
1176        let backend = x.backend().ok_or_else(|| {
1177            Error::Msg(
1178                "vulkan_dispatch::attention::rope_f32: x has no VulkanBackend handle. \
1179                 Storages flowing through the pipelined-executor binding-table dispatch \
1180                 must come from alloc_bytes_handle / upload_bytes_handle."
1181                    .to_string(),
1182            )
1183            .bt()
1184        })?;
1185        let out = vulkan_output(&mut out_guard)?;
1186        backend.rope_f32_bytes(x, cos, sin, out, &layouts[0])
1187    }
1188
1189    /// `rope_f16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1190    pub fn rope_f16(
1191        inputs: &[Arc<RwLock<Storage>>],
1192        outputs: &mut [Arc<RwLock<Storage>>],
1193        layouts: &[Layout],
1194        params: &OpParams,
1195    ) -> Result<()> {
1196        rope_typed(
1197            "rope_f16",
1198            inputs,
1199            outputs,
1200            layouts,
1201            params,
1202            |b, x, c, s, o, l| b.rope_f16_bytes(x, c, s, o, l),
1203        )
1204    }
1205
1206    /// `rope_bf16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1207    pub fn rope_bf16(
1208        inputs: &[Arc<RwLock<Storage>>],
1209        outputs: &mut [Arc<RwLock<Storage>>],
1210        layouts: &[Layout],
1211        params: &OpParams,
1212    ) -> Result<()> {
1213        rope_typed(
1214            "rope_bf16",
1215            inputs,
1216            outputs,
1217            layouts,
1218            params,
1219            |b, x, c, s, o, l| b.rope_bf16_bytes(x, c, s, o, l),
1220        )
1221    }
1222
1223    /// `rope_f64` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1224    pub fn rope_f64(
1225        inputs: &[Arc<RwLock<Storage>>],
1226        outputs: &mut [Arc<RwLock<Storage>>],
1227        layouts: &[Layout],
1228        params: &OpParams,
1229    ) -> Result<()> {
1230        rope_typed(
1231            "rope_f64",
1232            inputs,
1233            outputs,
1234            layouts,
1235            params,
1236            |b, x, c, s, o, l| b.rope_f64_bytes(x, c, s, o, l),
1237        )
1238    }
1239
1240    fn rope_typed<F>(
1241        label: &'static str,
1242        inputs: &[Arc<RwLock<Storage>>],
1243        outputs: &mut [Arc<RwLock<Storage>>],
1244        layouts: &[Layout],
1245        params: &OpParams,
1246        call: F,
1247    ) -> Result<()>
1248    where
1249        F: FnOnce(
1250            &fuel_vulkan_backend::VulkanBackend,
1251            &fuel_vulkan_backend::VulkanStorageBytes,
1252            &fuel_vulkan_backend::VulkanStorageBytes,
1253            &fuel_vulkan_backend::VulkanStorageBytes,
1254            &mut fuel_vulkan_backend::VulkanStorageBytes,
1255            &Layout,
1256        ) -> fuel_ir::Result<()>,
1257    {
1258        if inputs.len() != 3 || outputs.len() != 1 {
1259            return Err(Error::Msg(format!(
1260                "vulkan_dispatch::attention::{label}: expected 3 inputs (x,cos,sin) + 1 output, got {} + {}",
1261                inputs.len(), outputs.len(),
1262            )).bt());
1263        }
1264        match params {
1265            OpParams::Rope { .. } => {}
1266            other => {
1267                return Err(Error::Msg(format!(
1268                    "vulkan_dispatch::attention::{label}: expected OpParams::Rope, got {other:?}",
1269                ))
1270                .bt());
1271            }
1272        }
1273        if layouts.is_empty() {
1274            return Err(Error::Msg(format!(
1275                "vulkan_dispatch::attention::{label}: layouts.len() = 0, need x-layout",
1276            ))
1277            .bt());
1278        }
1279        let x_guard = read_storage(&inputs[0])?;
1280        let cos_guard = read_storage(&inputs[1])?;
1281        let sin_guard = read_storage(&inputs[2])?;
1282        let mut out_guard = write_storage(&outputs[0])?;
1283        let x = vulkan_input(&x_guard)?;
1284        let cos = vulkan_input(&cos_guard)?;
1285        let sin = vulkan_input(&sin_guard)?;
1286        let backend = x.backend().ok_or_else(|| {
1287            Error::Msg(format!(
1288                "vulkan_dispatch::attention::{label}: x has no VulkanBackend handle.",
1289            ))
1290            .bt()
1291        })?;
1292        let out = vulkan_output(&mut out_guard)?;
1293        call(backend, x, cos, sin, out, &layouts[0])
1294    }
1295}
1296
1297// ===========================================================================
1298// PowI — y = x^exp, f32 (V.3.A.3)
1299// ===========================================================================
1300
1301/// Vulkan dispatch wrappers for integer power, `y = x^exp` (f32).
1302pub mod powi {
1303    use super::*;
1304
1305    /// `powi_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1306    pub fn powi_f32(
1307        inputs: &[Arc<RwLock<Storage>>],
1308        outputs: &mut [Arc<RwLock<Storage>>],
1309        layouts: &[Layout],
1310        params: &OpParams,
1311    ) -> Result<()> {
1312        if inputs.len() != 1 || outputs.len() != 1 {
1313            return Err(Error::Msg(format!(
1314                "vulkan_dispatch::powi::powi_f32: expected 1 input + 1 output, got {} + {}",
1315                inputs.len(),
1316                outputs.len(),
1317            ))
1318            .bt());
1319        }
1320        if layouts.is_empty() {
1321            return Err(Error::Msg(
1322                "vulkan_dispatch::powi::powi_f32: layouts.len() = 0, expected >= 1".into(),
1323            )
1324            .bt());
1325        }
1326        let exp = match params {
1327            OpParams::PowI { exp } => *exp,
1328            other => {
1329                return Err(Error::Msg(format!(
1330                    "vulkan_dispatch::powi::powi_f32: expected OpParams::PowI, got {:?}",
1331                    other,
1332                ))
1333                .bt());
1334            }
1335        };
1336        let in_guard = read_storage(&inputs[0])?;
1337        let mut out_guard = write_storage(&outputs[0])?;
1338        let a = vulkan_input(&in_guard)?;
1339        let backend = a.backend().ok_or_else(|| {
1340            Error::Msg(
1341                "vulkan_dispatch::powi::powi_f32: input has no VulkanBackend handle. \
1342                 Storages flowing through the pipelined-executor binding-table dispatch \
1343                 must come from alloc_bytes_handle / upload_bytes_handle."
1344                    .to_string(),
1345            )
1346            .bt()
1347        })?;
1348        let out = vulkan_output(&mut out_guard)?;
1349        backend.powi_f32_bytes(a, out, exp, &layouts[0])
1350    }
1351}
1352
1353// ===========================================================================
1354// WriteSlice — in-place rectangular slab assign (V.3.J)
1355// ===========================================================================
1356//
1357// Backs `Op::WriteSlice` for persistent KV-cache writes (matches the
1358// CUDA pattern from baracuda alpha.29). The pipelined executor wires
1359// `inputs=[source]` + `outputs=[dest_arc]` where outputs[0]'s Arc IS
1360// the destination's Storage Arc (zero-copy in-place adoption). The
1361// wrapper holds a write lock on outputs[0] and a read lock on
1362// inputs[0]; the kernel mutates dest in place.
1363//
1364// 4-byte-keyed (f32/i32/u32 only in V.3.J — b2/b8 are follow-up).
1365
1366/// Vulkan dispatch wrappers for in-place slice write into a destination buffer (4-byte element widths).
1367pub mod write_slice {
1368    use super::*;
1369
1370    macro_rules! vk_write_slice_wrapper {
1371        ($name:ident, $byte_width:expr $(,)?) => {
1372            pub fn $name(
1373                inputs: &[Arc<RwLock<Storage>>],
1374                outputs: &mut [Arc<RwLock<Storage>>],
1375                _layouts: &[Layout],
1376                params: &OpParams,
1377            ) -> Result<()> {
1378                if inputs.len() != 1 || outputs.len() != 1 {
1379                    return Err(Error::Msg(format!(
1380                        "vulkan_dispatch::write_slice::{}: expected 1 input + 1 output, got {} + {}",
1381                        stringify!($name), inputs.len(), outputs.len(),
1382                    )).bt());
1383                }
1384                let (dest_shape, ranges) = match params {
1385                    OpParams::WriteSlice { dest_shape, ranges, .. } => (dest_shape, ranges),
1386                    other => {
1387                        return Err(Error::Msg(format!(
1388                            "vulkan_dispatch::write_slice::{}: expected OpParams::WriteSlice, got {:?}",
1389                            stringify!($name), other,
1390                        )).bt());
1391                    }
1392                };
1393                let rank = dest_shape.len();
1394                let mut source_shape = Vec::with_capacity(rank);
1395                let mut range_start = Vec::with_capacity(rank);
1396                for &(start, end) in ranges.iter() {
1397                    source_shape.push(end - start);
1398                    range_start.push(start);
1399                }
1400
1401                let in_guard = read_storage(&inputs[0])?;
1402                let mut out_guard = write_storage(&outputs[0])?;
1403                let src_vk = vulkan_input(&in_guard)?;
1404                let backend = src_vk.backend().ok_or_else(|| {
1405                    Error::Msg(format!(
1406                        "vulkan_dispatch::write_slice::{}: src has no VulkanBackend handle. \
1407                         Storages flowing through the pipelined-executor binding-table dispatch \
1408                         must come from alloc_bytes_handle / upload_bytes_handle.",
1409                        stringify!($name),
1410                    )).bt()
1411                })?;
1412                let dst_vk = vulkan_output(&mut out_guard)?;
1413                backend.write_slice_bytes($byte_width, src_vk, dst_vk, dest_shape, &source_shape, &range_start)
1414            }
1415        };
1416    }
1417
1418    vk_write_slice_wrapper!(write_slice_b1, 1);
1419    vk_write_slice_wrapper!(write_slice_b2, 2);
1420    vk_write_slice_wrapper!(write_slice_b4, 4);
1421    vk_write_slice_wrapper!(write_slice_b8, 8);
1422}
1423
1424// ===========================================================================
1425// WriteSliceRotating — sliding-window KV cache writes (Phase C)
1426// ===========================================================================
1427//
1428// Mirrors the CUDA strategy in `baracuda_dispatch::write_slice_rotating`:
1429//   1. D2H the U32 position scalar (4 bytes) via
1430//      `VulkanBackend::download_bytes`.
1431//   2. Compute `wrapped_start = position % modulus`.
1432//   3. Split into up to two contiguous chunks across the ring
1433//      boundary.
1434//   4. Per chunk, extract the source prefix/suffix as a fresh
1435//      `VulkanStorageBytes` via `VulkanBackend::slot_copy_to_new_handle`
1436//      (vkCmdCopyBuffer-backed D2D), then reuse the existing
1437//      `VulkanBackend::write_slice_bytes` Slang kernels.
1438//
1439// v1 constraint: rotating axis must be axis 0 (matches Mistral /
1440// Phi-3 sliding-window K/V layout). Same v1 constraint as CPU + CUDA.
1441
1442/// Vulkan dispatch wrappers for rotating slice write for sliding-window K/V caches (rotating axis must be axis 0).
1443pub mod write_slice_rotating {
1444    use super::*;
1445
1446    macro_rules! vk_write_slice_rotating_wrapper {
1447        ($name:ident, $byte_width:expr $(,)?) => {
1448            pub fn $name(
1449                inputs: &[Arc<RwLock<Storage>>],
1450                outputs: &mut [Arc<RwLock<Storage>>],
1451                _layouts: &[Layout],
1452                params: &OpParams,
1453            ) -> Result<()> {
1454                if inputs.len() != 2 || outputs.len() != 1 {
1455                    return Err(Error::Msg(format!(
1456                        "vulkan_dispatch::write_slice_rotating::{}: expected 2 inputs \
1457                         (source, position) + 1 output (dest), got {} + {}",
1458                        stringify!($name), inputs.len(), outputs.len(),
1459                    )).bt());
1460                }
1461                let (dest_shape, axis, modulus, ranges) = match params {
1462                    OpParams::WriteSliceRotating { dest_shape, axis, modulus, ranges } => {
1463                        (dest_shape, *axis, *modulus, ranges)
1464                    }
1465                    other => {
1466                        return Err(Error::Msg(format!(
1467                            "vulkan_dispatch::write_slice_rotating::{}: expected \
1468                             OpParams::WriteSliceRotating, got {:?}",
1469                            stringify!($name), other,
1470                        )).bt());
1471                    }
1472                };
1473                let rank = dest_shape.len();
1474                if ranges.len() != rank {
1475                    return Err(Error::Msg(format!(
1476                        "vulkan_dispatch::write_slice_rotating::{}: ranges.len() {} != dest rank {}",
1477                        stringify!($name), ranges.len(), rank,
1478                    )).bt());
1479                }
1480
1481                // Position is rank-0 U32, stored on the same device as
1482                // the source. Grab a backend handle from the position
1483                // storage so we can do the D2H + per-chunk D2D.
1484                let pos_guard = read_storage(&inputs[1])?;
1485                let pos_vk = vulkan_input(&pos_guard)?;
1486                let backend = pos_vk.backend().ok_or_else(|| {
1487                    Error::Msg(format!(
1488                        "vulkan_dispatch::write_slice_rotating::{}: position storage has no \
1489                         VulkanBackend handle",
1490                        stringify!($name),
1491                    )).bt()
1492                })?;
1493                let pos_bytes = backend.download_bytes(pos_vk)?;
1494                if pos_bytes.len() < 4 {
1495                    return Err(Error::Msg(format!(
1496                        "vulkan_dispatch::write_slice_rotating::{}: position storage has {} bytes, need >= 4",
1497                        stringify!($name), pos_bytes.len(),
1498                    )).bt());
1499                }
1500                let position = u32::from_ne_bytes([
1501                    pos_bytes[0], pos_bytes[1], pos_bytes[2], pos_bytes[3],
1502                ]) as usize;
1503                let wrapped_start = position % modulus;
1504
1505                // Derive slab_shape from ranges.
1506                let mut slab_shape: Vec<usize> = Vec::with_capacity(rank);
1507                for (i, &(start, end)) in ranges.iter().enumerate() {
1508                    if end < start {
1509                        return Err(Error::Msg(format!(
1510                            "vulkan_dispatch::write_slice_rotating::{}: ranges[{}] = ({}, {}) has end < start",
1511                            stringify!($name), i, start, end,
1512                        )).bt());
1513                    }
1514                    let slab = end - start;
1515                    if i == axis && slab > modulus {
1516                        return Err(Error::Msg(format!(
1517                            "vulkan_dispatch::write_slice_rotating::{}: rotating-axis slab {} > modulus {}",
1518                            stringify!($name), slab, modulus,
1519                        )).bt());
1520                    }
1521                    slab_shape.push(slab);
1522                }
1523                let slab_axis_len = slab_shape[axis];
1524                let slab_elems: usize = slab_shape.iter().copied().product();
1525                if slab_elems == 0 {
1526                    return Ok(());
1527                }
1528
1529                let first_len = slab_axis_len.min(modulus - wrapped_start);
1530                let second_len = slab_axis_len - first_len;
1531
1532                // Outer/axis/inner decomposition for strided source extract.
1533                // For axis 0, outer_count is 1 and the strided extract
1534                // reduces to a single contiguous BufferCopy.
1535                let outer_count: usize = slab_shape[..axis].iter().copied().product();
1536                let inner_per_row: usize = slab_shape[axis + 1..].iter().copied().product();
1537                let row_bytes = inner_per_row * $byte_width;
1538                let stride_bytes = slab_axis_len * row_bytes;
1539
1540                let src_guard = read_storage(&inputs[0])?;
1541                let src_vk = vulkan_input(&src_guard)?;
1542
1543                if first_len > 0 {
1544                    let chunk_row_bytes = first_len * row_bytes;
1545                    let src_first = backend.extract_strided_to_new_handle(
1546                        src_vk, outer_count, stride_bytes, /* offset_in_outer */ 0, chunk_row_bytes,
1547                    )?;
1548                    let mut sub_source_shape = slab_shape.clone();
1549                    sub_source_shape[axis] = first_len;
1550                    let mut sub_range_start: Vec<usize> = ranges.iter().map(|r| r.0).collect();
1551                    sub_range_start[axis] = wrapped_start;
1552
1553                    let mut out_guard = write_storage(&outputs[0])?;
1554                    let dst_vk = vulkan_output(&mut out_guard)?;
1555                    backend.write_slice_bytes(
1556                        $byte_width, &src_first, dst_vk,
1557                        dest_shape, &sub_source_shape, &sub_range_start,
1558                    )?;
1559                }
1560                if second_len > 0 {
1561                    let chunk_row_bytes = second_len * row_bytes;
1562                    let offset_in_outer = first_len * row_bytes;
1563                    let src_second = backend.extract_strided_to_new_handle(
1564                        src_vk, outer_count, stride_bytes, offset_in_outer, chunk_row_bytes,
1565                    )?;
1566                    let mut sub_source_shape = slab_shape.clone();
1567                    sub_source_shape[axis] = second_len;
1568                    let mut sub_range_start: Vec<usize> = ranges.iter().map(|r| r.0).collect();
1569                    sub_range_start[axis] = 0;
1570
1571                    let mut out_guard = write_storage(&outputs[0])?;
1572                    let dst_vk = vulkan_output(&mut out_guard)?;
1573                    backend.write_slice_bytes(
1574                        $byte_width, &src_second, dst_vk,
1575                        dest_shape, &sub_source_shape, &sub_range_start,
1576                    )?;
1577                }
1578                Ok(())
1579            }
1580        };
1581    }
1582
1583    vk_write_slice_rotating_wrapper!(write_slice_rotating_b1, 1);
1584    vk_write_slice_rotating_wrapper!(write_slice_rotating_b2, 2);
1585    vk_write_slice_rotating_wrapper!(write_slice_rotating_b4, 4);
1586    vk_write_slice_rotating_wrapper!(write_slice_rotating_b8, 8);
1587}
1588
1589// ===========================================================================
1590// Cast — f32↔f16, f32↔bf16 (V.3.B)
1591// ===========================================================================
1592//
1593// One wrapper handles all 4 supported (src, dst) pairs by inspecting
1594// Storage.dtype. Element count derived from src bytes / src elem-size.
1595// Requires `n` even (half-precision dtypes are u32-packed 2-per-word);
1596// odd-count tensors return Err and the route picker falls back to CPU.
1597
1598/// Vulkan dispatch wrappers for dtype casts between f32 and f64 / half precision.
1599pub mod cast {
1600    use super::*;
1601
1602    /// `cast_f32_f64` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1603    pub fn cast_f32_f64(
1604        inputs: &[Arc<RwLock<Storage>>],
1605        outputs: &mut [Arc<RwLock<Storage>>],
1606        _layouts: &[Layout],
1607        _params: &OpParams,
1608    ) -> Result<()> {
1609        if inputs.len() != 1 || outputs.len() != 1 {
1610            return Err(Error::Msg(format!(
1611                "vulkan_dispatch::cast::cast_f32_f64: expected 1 input + 1 output, got {} + {}",
1612                inputs.len(),
1613                outputs.len(),
1614            ))
1615            .bt());
1616        }
1617        let in_guard = read_storage(&inputs[0])?;
1618        let mut out_guard = write_storage(&outputs[0])?;
1619        let src_dtype = in_guard.dtype;
1620        let dst_dtype = out_guard.dtype;
1621        let a = vulkan_input(&in_guard)?;
1622        let n_bytes = a.len_bytes();
1623        let src_elem = match src_dtype {
1624            DType::F32 => 4,
1625            DType::F64 => 8,
1626            other => {
1627                return Err(Error::Msg(format!(
1628                    "vulkan_dispatch::cast::cast_f32_f64: unsupported src dtype {other:?}",
1629                ))
1630                .bt());
1631            }
1632        };
1633        if n_bytes % src_elem != 0 {
1634            return Err(Error::Msg(format!(
1635                "vulkan_dispatch::cast::cast_f32_f64: input bytes {n_bytes} not a multiple of \
1636                 src elem size {src_elem} ({src_dtype:?})",
1637            ))
1638            .bt());
1639        }
1640        let n = n_bytes / src_elem;
1641        let backend = a.backend().ok_or_else(|| {
1642            Error::Msg(
1643                "vulkan_dispatch::cast::cast_f32_f64: input has no VulkanBackend handle."
1644                    .to_string(),
1645            )
1646            .bt()
1647        })?;
1648        let out = vulkan_output(&mut out_guard)?;
1649        backend.cast_f32_f64_bytes(a, out, n, src_dtype, dst_dtype)
1650    }
1651
1652    /// `cast_f32_half` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1653    pub fn cast_f32_half(
1654        inputs: &[Arc<RwLock<Storage>>],
1655        outputs: &mut [Arc<RwLock<Storage>>],
1656        _layouts: &[Layout],
1657        _params: &OpParams,
1658    ) -> Result<()> {
1659        if inputs.len() != 1 || outputs.len() != 1 {
1660            return Err(Error::Msg(format!(
1661                "vulkan_dispatch::cast::cast_f32_half: expected 1 input + 1 output, got {} + {}",
1662                inputs.len(),
1663                outputs.len(),
1664            ))
1665            .bt());
1666        }
1667        let in_guard = read_storage(&inputs[0])?;
1668        let mut out_guard = write_storage(&outputs[0])?;
1669        let src_dtype = in_guard.dtype;
1670        let dst_dtype = out_guard.dtype;
1671        let a = vulkan_input(&in_guard)?;
1672        let n_bytes = a.len_bytes();
1673        let src_elem = match src_dtype {
1674            DType::F32 => 4,
1675            DType::F16 => 2,
1676            DType::BF16 => 2,
1677            other => {
1678                return Err(Error::Msg(format!(
1679                    "vulkan_dispatch::cast::cast_f32_half: unsupported src dtype {other:?}",
1680                ))
1681                .bt());
1682            }
1683        };
1684        if n_bytes % src_elem != 0 {
1685            return Err(Error::Msg(format!(
1686                "vulkan_dispatch::cast::cast_f32_half: input bytes {n_bytes} not a multiple of \
1687                 src elem size {src_elem} ({src_dtype:?})",
1688            ))
1689            .bt());
1690        }
1691        let n = n_bytes / src_elem;
1692        let backend = a.backend().ok_or_else(|| {
1693            Error::Msg(
1694                "vulkan_dispatch::cast::cast_f32_half: input has no VulkanBackend handle. \
1695                 Storages flowing through the pipelined-executor binding-table dispatch \
1696                 must come from alloc_bytes_handle / upload_bytes_handle."
1697                    .to_string(),
1698            )
1699            .bt()
1700        })?;
1701        let out = vulkan_output(&mut out_guard)?;
1702        backend.cast_f32_bytes(a, out, n, src_dtype, dst_dtype)
1703    }
1704}
1705
1706// ===========================================================================
1707// Clamp — y = clamp(x, lo, hi), f32 (V.3.A.1)
1708// ===========================================================================
1709
1710/// Vulkan dispatch wrappers for `y = clamp(x, lo, hi)` (f32).
1711pub mod clamp {
1712    use super::*;
1713
1714    /// `clamp_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1715    pub fn clamp_f32(
1716        inputs: &[Arc<RwLock<Storage>>],
1717        outputs: &mut [Arc<RwLock<Storage>>],
1718        layouts: &[Layout],
1719        params: &OpParams,
1720    ) -> Result<()> {
1721        if inputs.len() != 1 || outputs.len() != 1 {
1722            return Err(Error::Msg(format!(
1723                "vulkan_dispatch::clamp::clamp_f32: expected 1 input + 1 output, got {} + {}",
1724                inputs.len(),
1725                outputs.len(),
1726            ))
1727            .bt());
1728        }
1729        if layouts.is_empty() {
1730            return Err(Error::Msg(
1731                "vulkan_dispatch::clamp::clamp_f32: layouts.len() = 0, expected >= 1".into(),
1732            )
1733            .bt());
1734        }
1735        let (lo, hi) = match params {
1736            OpParams::Clamp { min, max } => (*min, *max),
1737            other => {
1738                return Err(Error::Msg(format!(
1739                    "vulkan_dispatch::clamp::clamp_f32: expected OpParams::Clamp, got {:?}",
1740                    other,
1741                ))
1742                .bt());
1743            }
1744        };
1745        let in_guard = read_storage(&inputs[0])?;
1746        let mut out_guard = write_storage(&outputs[0])?;
1747        let a = vulkan_input(&in_guard)?;
1748        let backend = a.backend().ok_or_else(|| {
1749            Error::Msg(
1750                "vulkan_dispatch::clamp::clamp_f32: input has no VulkanBackend handle. \
1751                 Storages flowing through the pipelined-executor binding-table dispatch \
1752                 must come from alloc_bytes_handle / upload_bytes_handle."
1753                    .to_string(),
1754            )
1755            .bt()
1756        })?;
1757        let out = vulkan_output(&mut out_guard)?;
1758        backend.clamp_f32_bytes(a, out, lo, hi, &layouts[0])
1759    }
1760}
1761
1762// ===========================================================================
1763// Affine — y = mul*x + add, f32 (V.2.E)
1764// ===========================================================================
1765
1766/// Vulkan dispatch wrappers for `y = mul * x + add`, per dtype.
1767pub mod affine {
1768    use super::*;
1769
1770    /// `affine_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1771    pub fn affine_f32(
1772        inputs: &[Arc<RwLock<Storage>>],
1773        outputs: &mut [Arc<RwLock<Storage>>],
1774        layouts: &[Layout],
1775        params: &OpParams,
1776    ) -> Result<()> {
1777        if inputs.len() != 1 || outputs.len() != 1 {
1778            return Err(Error::Msg(format!(
1779                "vulkan_dispatch::affine::affine_f32: expected 1 input + 1 output, got {} + {}",
1780                inputs.len(),
1781                outputs.len(),
1782            ))
1783            .bt());
1784        }
1785        if layouts.is_empty() {
1786            return Err(Error::Msg(
1787                "vulkan_dispatch::affine::affine_f32: layouts.len() = 0, expected >= 1".into(),
1788            )
1789            .bt());
1790        }
1791        let (mul, add) = match params {
1792            OpParams::Affine { mul, add } => (*mul, *add),
1793            other => {
1794                return Err(Error::Msg(format!(
1795                    "vulkan_dispatch::affine::affine_f32: expected OpParams::Affine, got {:?}",
1796                    other,
1797                ))
1798                .bt());
1799            }
1800        };
1801        let in_guard = read_storage(&inputs[0])?;
1802        let mut out_guard = write_storage(&outputs[0])?;
1803        let a = vulkan_input(&in_guard)?;
1804        let backend = a.backend().ok_or_else(|| {
1805            Error::Msg(
1806                "vulkan_dispatch::affine::affine_f32: input has no VulkanBackend handle. \
1807                 Storages flowing through the pipelined-executor binding-table dispatch \
1808                 must come from alloc_bytes_handle / upload_bytes_handle."
1809                    .to_string(),
1810            )
1811            .bt()
1812        })?;
1813        let out = vulkan_output(&mut out_guard)?;
1814        backend.affine_f32_bytes(a, out, mul, add, &layouts[0])
1815    }
1816
1817    /// `affine_f64` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1818    pub fn affine_f64(
1819        inputs: &[Arc<RwLock<Storage>>],
1820        outputs: &mut [Arc<RwLock<Storage>>],
1821        layouts: &[Layout],
1822        params: &OpParams,
1823    ) -> Result<()> {
1824        affine_typed(
1825            "affine_f64",
1826            inputs,
1827            outputs,
1828            layouts,
1829            params,
1830            |b, a, out, mul, add, layout| b.affine_f64_bytes(a, out, mul, add, layout),
1831        )
1832    }
1833
1834    /// `affine_f16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1835    pub fn affine_f16(
1836        inputs: &[Arc<RwLock<Storage>>],
1837        outputs: &mut [Arc<RwLock<Storage>>],
1838        layouts: &[Layout],
1839        params: &OpParams,
1840    ) -> Result<()> {
1841        affine_typed(
1842            "affine_f16",
1843            inputs,
1844            outputs,
1845            layouts,
1846            params,
1847            |b, a, out, mul, add, layout| b.affine_f16_bytes(a, out, mul, add, layout),
1848        )
1849    }
1850
1851    /// `affine_bf16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1852    pub fn affine_bf16(
1853        inputs: &[Arc<RwLock<Storage>>],
1854        outputs: &mut [Arc<RwLock<Storage>>],
1855        layouts: &[Layout],
1856        params: &OpParams,
1857    ) -> Result<()> {
1858        affine_typed(
1859            "affine_bf16",
1860            inputs,
1861            outputs,
1862            layouts,
1863            params,
1864            |b, a, out, mul, add, layout| b.affine_bf16_bytes(a, out, mul, add, layout),
1865        )
1866    }
1867
1868    fn affine_typed<F>(
1869        debug_name: &'static str,
1870        inputs: &[Arc<RwLock<Storage>>],
1871        outputs: &mut [Arc<RwLock<Storage>>],
1872        layouts: &[Layout],
1873        params: &OpParams,
1874        f: F,
1875    ) -> Result<()>
1876    where
1877        F: FnOnce(
1878            &fuel_vulkan_backend::VulkanBackend,
1879            &fuel_vulkan_backend::VulkanStorageBytes,
1880            &mut fuel_vulkan_backend::VulkanStorageBytes,
1881            f64,
1882            f64,
1883            &Layout,
1884        ) -> Result<()>,
1885    {
1886        if inputs.len() != 1 || outputs.len() != 1 {
1887            return Err(Error::Msg(format!(
1888                "vulkan_dispatch::affine::{debug_name}: expected 1 input + 1 output, got {} + {}",
1889                inputs.len(),
1890                outputs.len(),
1891            ))
1892            .bt());
1893        }
1894        if layouts.is_empty() {
1895            return Err(Error::Msg(format!(
1896                "vulkan_dispatch::affine::{debug_name}: layouts.len() = 0",
1897            ))
1898            .bt());
1899        }
1900        let (mul, add) = match params {
1901            OpParams::Affine { mul, add } => (*mul, *add),
1902            other => {
1903                return Err(Error::Msg(format!(
1904                    "vulkan_dispatch::affine::{debug_name}: expected OpParams::Affine, got {other:?}",
1905                )).bt());
1906            }
1907        };
1908        let in_guard = read_storage(&inputs[0])?;
1909        let mut out_guard = write_storage(&outputs[0])?;
1910        let a = vulkan_input(&in_guard)?;
1911        let backend = a.backend().ok_or_else(|| {
1912            Error::Msg(format!(
1913                "vulkan_dispatch::affine::{debug_name}: input has no VulkanBackend handle.",
1914            ))
1915            .bt()
1916        })?;
1917        let out = vulkan_output(&mut out_guard)?;
1918        f(backend, a, out, mul, add, &layouts[0])
1919    }
1920}
1921
1922// ===========================================================================
1923// MatMul — f32 (V.2.D)
1924// ===========================================================================
1925//
1926// Selects among matvec (m==1) / reg-tile (m<32) / tiled (m>=32)
1927// kernels via `VulkanBackend::matmul_f32_bytes`. Mixed-bf16 and
1928// cooperative-matrix paths are deferred to V.3. GQA broadcast is
1929// honored (lhs_batch > rhs_batch with even divisibility).
1930
1931/// Vulkan dispatch wrappers for matrix multiplication entry points, per input/output dtype combination.
1932pub mod matmul {
1933    use super::*;
1934
1935    /// `matmul_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
1936    pub fn matmul_f32(
1937        inputs: &[Arc<RwLock<Storage>>],
1938        outputs: &mut [Arc<RwLock<Storage>>],
1939        _layouts: &[Layout],
1940        params: &OpParams,
1941    ) -> Result<()> {
1942        if inputs.len() != 2 || outputs.len() != 1 {
1943            return Err(Error::Msg(format!(
1944                "vulkan_dispatch::matmul::matmul_f32: expected 2 inputs + 1 output, got {} + {}",
1945                inputs.len(),
1946                outputs.len(),
1947            ))
1948            .bt());
1949        }
1950        let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
1951            OpParams::Matmul {
1952                lhs_batch_dims,
1953                rhs_batch_dims,
1954                m,
1955                n,
1956                k,
1957                ..
1958            } => (lhs_batch_dims.clone(), rhs_batch_dims.clone(), *m, *n, *k),
1959            other => {
1960                return Err(Error::Msg(format!(
1961                    "vulkan_dispatch::matmul::matmul_f32: expected OpParams::Matmul, got {:?}",
1962                    other,
1963                ))
1964                .bt());
1965            }
1966        };
1967        let lhs_guard = read_storage(&inputs[0])?;
1968        let rhs_guard = read_storage(&inputs[1])?;
1969        let mut out_guard = write_storage(&outputs[0])?;
1970        let lhs = vulkan_input(&lhs_guard)?;
1971        let rhs = vulkan_input(&rhs_guard)?;
1972        let backend = lhs.backend().ok_or_else(|| {
1973            Error::Msg(
1974                "vulkan_dispatch::matmul::matmul_f32: lhs has no VulkanBackend handle. \
1975                 Storages flowing through the pipelined-executor binding-table dispatch \
1976                 must come from alloc_bytes_handle / upload_bytes_handle."
1977                    .to_string(),
1978            )
1979            .bt()
1980        })?;
1981        let out = vulkan_output(&mut out_guard)?;
1982        backend.matmul_f32_bytes(lhs, rhs, out, &lhs_batch_dims, &rhs_batch_dims, m, n, k)
1983    }
1984
1985    /// Mixed-precision matmul: f32 LHS × bf16 RHS → f32 output.
1986    /// Vulkan-specific decision-point (CUDA registers full-bf16
1987    /// `[bf16, bf16, bf16]` instead). The route picker prefers this
1988    /// when the input dtypes match exactly; otherwise falls back to
1989    /// f32 matmul (after a Cast).
1990    pub fn matmul_f32_bf16_b(
1991        inputs: &[Arc<RwLock<Storage>>],
1992        outputs: &mut [Arc<RwLock<Storage>>],
1993        _layouts: &[Layout],
1994        params: &OpParams,
1995    ) -> Result<()> {
1996        if inputs.len() != 2 || outputs.len() != 1 {
1997            return Err(Error::Msg(format!(
1998                "vulkan_dispatch::matmul::matmul_f32_bf16_b: expected 2 inputs + 1 output, got {} + {}",
1999                inputs.len(), outputs.len(),
2000            )).bt());
2001        }
2002        let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
2003            OpParams::Matmul {
2004                lhs_batch_dims,
2005                rhs_batch_dims,
2006                m,
2007                n,
2008                k,
2009                ..
2010            } => (lhs_batch_dims.clone(), rhs_batch_dims.clone(), *m, *n, *k),
2011            other => {
2012                return Err(Error::Msg(format!(
2013                    "vulkan_dispatch::matmul::matmul_f32_bf16_b: expected OpParams::Matmul, got {:?}",
2014                    other,
2015                )).bt());
2016            }
2017        };
2018        let lhs_guard = read_storage(&inputs[0])?;
2019        let rhs_guard = read_storage(&inputs[1])?;
2020        let mut out_guard = write_storage(&outputs[0])?;
2021        if lhs_guard.dtype != DType::F32 {
2022            return Err(Error::Msg(format!(
2023                "vulkan_dispatch::matmul::matmul_f32_bf16_b: lhs must be F32, got {:?}",
2024                lhs_guard.dtype,
2025            ))
2026            .bt());
2027        }
2028        if rhs_guard.dtype != DType::BF16 {
2029            return Err(Error::Msg(format!(
2030                "vulkan_dispatch::matmul::matmul_f32_bf16_b: rhs must be BF16, got {:?}",
2031                rhs_guard.dtype,
2032            ))
2033            .bt());
2034        }
2035        let lhs = vulkan_input(&lhs_guard)?;
2036        let rhs = vulkan_input(&rhs_guard)?;
2037        let backend = lhs.backend().ok_or_else(|| {
2038            Error::Msg(
2039                "vulkan_dispatch::matmul::matmul_f32_bf16_b: lhs has no VulkanBackend handle. \
2040                 Storages flowing through the pipelined-executor binding-table dispatch \
2041                 must come from alloc_bytes_handle / upload_bytes_handle."
2042                    .to_string(),
2043            )
2044            .bt()
2045        })?;
2046        let out = vulkan_output(&mut out_guard)?;
2047        backend.matmul_f32_bf16_b_bytes(lhs, rhs, out, &lhs_batch_dims, &rhs_batch_dims, m, n, k)
2048    }
2049
2050    /// MatMul bf16 × bf16 → f32 via cooperative-matrix tensor cores
2051    /// (`coop[3]` tile: A=f16, B=f16, C=f32, R=f32; both inputs are
2052    /// stored as bf16 and downcast bf16→f16 on shared-mem load).
2053    /// COOP-ONLY — bails on small shapes; route picker should fall
2054    /// through to a cast-and-f32-matmul alternative.
2055    pub fn matmul_bf16_bf16_f32(
2056        inputs: &[Arc<RwLock<Storage>>],
2057        outputs: &mut [Arc<RwLock<Storage>>],
2058        _layouts: &[Layout],
2059        params: &OpParams,
2060    ) -> Result<()> {
2061        if inputs.len() != 2 || outputs.len() != 1 {
2062            return Err(Error::Msg(format!(
2063                "vulkan_dispatch::matmul::matmul_bf16_bf16_f32: expected 2 inputs + 1 output, got {} + {}",
2064                inputs.len(), outputs.len(),
2065            )).bt());
2066        }
2067        let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
2068            OpParams::Matmul {
2069                lhs_batch_dims,
2070                rhs_batch_dims,
2071                m,
2072                n,
2073                k,
2074                ..
2075            } => (lhs_batch_dims.clone(), rhs_batch_dims.clone(), *m, *n, *k),
2076            other => {
2077                return Err(Error::Msg(format!(
2078                    "vulkan_dispatch::matmul::matmul_bf16_bf16_f32: expected OpParams::Matmul, got {other:?}",
2079                )).bt());
2080            }
2081        };
2082        let lhs_guard = read_storage(&inputs[0])?;
2083        let rhs_guard = read_storage(&inputs[1])?;
2084        let mut out_guard = write_storage(&outputs[0])?;
2085        if lhs_guard.dtype != DType::BF16 {
2086            return Err(Error::Msg(format!(
2087                "vulkan_dispatch::matmul::matmul_bf16_bf16_f32: lhs must be BF16, got {:?}",
2088                lhs_guard.dtype,
2089            ))
2090            .bt());
2091        }
2092        if rhs_guard.dtype != DType::BF16 {
2093            return Err(Error::Msg(format!(
2094                "vulkan_dispatch::matmul::matmul_bf16_bf16_f32: rhs must be BF16, got {:?}",
2095                rhs_guard.dtype,
2096            ))
2097            .bt());
2098        }
2099        let lhs = vulkan_input(&lhs_guard)?;
2100        let rhs = vulkan_input(&rhs_guard)?;
2101        let backend = lhs.backend().ok_or_else(|| {
2102            Error::Msg(
2103                "vulkan_dispatch::matmul::matmul_bf16_bf16_f32: lhs has no VulkanBackend handle."
2104                    .to_string(),
2105            )
2106            .bt()
2107        })?;
2108        let out = vulkan_output(&mut out_guard)?;
2109        backend.matmul_bf16_bf16_f32_bytes(lhs, rhs, out, &lhs_batch_dims, &rhs_batch_dims, m, n, k)
2110    }
2111
2112    /// MatMul f16 × f16 → f32 via cooperative-matrix tensor cores.
2113    /// Same constraints as the bf16 sibling.
2114    pub fn matmul_f16_f16_f32(
2115        inputs: &[Arc<RwLock<Storage>>],
2116        outputs: &mut [Arc<RwLock<Storage>>],
2117        _layouts: &[Layout],
2118        params: &OpParams,
2119    ) -> Result<()> {
2120        if inputs.len() != 2 || outputs.len() != 1 {
2121            return Err(Error::Msg(format!(
2122                "vulkan_dispatch::matmul::matmul_f16_f16_f32: expected 2 inputs + 1 output, got {} + {}",
2123                inputs.len(), outputs.len(),
2124            )).bt());
2125        }
2126        let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
2127            OpParams::Matmul {
2128                lhs_batch_dims,
2129                rhs_batch_dims,
2130                m,
2131                n,
2132                k,
2133                ..
2134            } => (lhs_batch_dims.clone(), rhs_batch_dims.clone(), *m, *n, *k),
2135            other => {
2136                return Err(Error::Msg(format!(
2137                    "vulkan_dispatch::matmul::matmul_f16_f16_f32: expected OpParams::Matmul, got {other:?}",
2138                )).bt());
2139            }
2140        };
2141        let lhs_guard = read_storage(&inputs[0])?;
2142        let rhs_guard = read_storage(&inputs[1])?;
2143        let mut out_guard = write_storage(&outputs[0])?;
2144        if lhs_guard.dtype != DType::F16 {
2145            return Err(Error::Msg(format!(
2146                "vulkan_dispatch::matmul::matmul_f16_f16_f32: lhs must be F16, got {:?}",
2147                lhs_guard.dtype,
2148            ))
2149            .bt());
2150        }
2151        if rhs_guard.dtype != DType::F16 {
2152            return Err(Error::Msg(format!(
2153                "vulkan_dispatch::matmul::matmul_f16_f16_f32: rhs must be F16, got {:?}",
2154                rhs_guard.dtype,
2155            ))
2156            .bt());
2157        }
2158        let lhs = vulkan_input(&lhs_guard)?;
2159        let rhs = vulkan_input(&rhs_guard)?;
2160        let backend = lhs.backend().ok_or_else(|| {
2161            Error::Msg(
2162                "vulkan_dispatch::matmul::matmul_f16_f16_f32: lhs has no VulkanBackend handle."
2163                    .to_string(),
2164            )
2165            .bt()
2166        })?;
2167        let out = vulkan_output(&mut out_guard)?;
2168        backend.matmul_f16_f16_f32_bytes(lhs, rhs, out, &lhs_batch_dims, &rhs_batch_dims, m, n, k)
2169    }
2170
2171    /// MatMul bf16 × bf16 → bf16 (downcast store). Coop kernel with
2172    /// f32 accumulator + shared-memory staging + per-lane f32→bf16
2173    /// conversion. Closes the bf16 inference chain.
2174    pub fn matmul_bf16_bf16_bf16(
2175        inputs: &[Arc<RwLock<Storage>>],
2176        outputs: &mut [Arc<RwLock<Storage>>],
2177        _layouts: &[Layout],
2178        params: &OpParams,
2179    ) -> Result<()> {
2180        if inputs.len() != 2 || outputs.len() != 1 {
2181            return Err(Error::Msg(format!(
2182                "vulkan_dispatch::matmul::matmul_bf16_bf16_bf16: expected 2 inputs + 1 output, got {} + {}",
2183                inputs.len(), outputs.len(),
2184            )).bt());
2185        }
2186        let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
2187            OpParams::Matmul {
2188                lhs_batch_dims,
2189                rhs_batch_dims,
2190                m,
2191                n,
2192                k,
2193                ..
2194            } => (lhs_batch_dims.clone(), rhs_batch_dims.clone(), *m, *n, *k),
2195            other => {
2196                return Err(Error::Msg(format!(
2197                    "vulkan_dispatch::matmul::matmul_bf16_bf16_bf16: expected OpParams::Matmul, got {other:?}",
2198                )).bt());
2199            }
2200        };
2201        let lhs_guard = read_storage(&inputs[0])?;
2202        let rhs_guard = read_storage(&inputs[1])?;
2203        let mut out_guard = write_storage(&outputs[0])?;
2204        if lhs_guard.dtype != DType::BF16 || rhs_guard.dtype != DType::BF16 {
2205            return Err(Error::Msg(format!(
2206                "vulkan_dispatch::matmul::matmul_bf16_bf16_bf16: lhs/rhs must be BF16, got ({:?}, {:?})",
2207                lhs_guard.dtype, rhs_guard.dtype,
2208            )).bt());
2209        }
2210        let lhs = vulkan_input(&lhs_guard)?;
2211        let rhs = vulkan_input(&rhs_guard)?;
2212        let backend = lhs.backend().ok_or_else(|| {
2213            Error::Msg(
2214                "vulkan_dispatch::matmul::matmul_bf16_bf16_bf16: lhs has no VulkanBackend handle."
2215                    .to_string(),
2216            )
2217            .bt()
2218        })?;
2219        let out = vulkan_output(&mut out_guard)?;
2220        backend.matmul_bf16_bf16_bf16_bytes(
2221            lhs,
2222            rhs,
2223            out,
2224            &lhs_batch_dims,
2225            &rhs_batch_dims,
2226            m,
2227            n,
2228            k,
2229        )
2230    }
2231
2232    /// MatMul f16 × f16 → f16 (downcast store). Native float16_t
2233    /// inputs; f32 accumulator + shared-mem staging + per-lane
2234    /// `float16BitsToUint16` pack.
2235    pub fn matmul_f16_f16_f16(
2236        inputs: &[Arc<RwLock<Storage>>],
2237        outputs: &mut [Arc<RwLock<Storage>>],
2238        _layouts: &[Layout],
2239        params: &OpParams,
2240    ) -> Result<()> {
2241        if inputs.len() != 2 || outputs.len() != 1 {
2242            return Err(Error::Msg(format!(
2243                "vulkan_dispatch::matmul::matmul_f16_f16_f16: expected 2 inputs + 1 output, got {} + {}",
2244                inputs.len(), outputs.len(),
2245            )).bt());
2246        }
2247        let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
2248            OpParams::Matmul {
2249                lhs_batch_dims,
2250                rhs_batch_dims,
2251                m,
2252                n,
2253                k,
2254                ..
2255            } => (lhs_batch_dims.clone(), rhs_batch_dims.clone(), *m, *n, *k),
2256            other => {
2257                return Err(Error::Msg(format!(
2258                    "vulkan_dispatch::matmul::matmul_f16_f16_f16: expected OpParams::Matmul, got {other:?}",
2259                )).bt());
2260            }
2261        };
2262        let lhs_guard = read_storage(&inputs[0])?;
2263        let rhs_guard = read_storage(&inputs[1])?;
2264        let mut out_guard = write_storage(&outputs[0])?;
2265        if lhs_guard.dtype != DType::F16 || rhs_guard.dtype != DType::F16 {
2266            return Err(Error::Msg(format!(
2267                "vulkan_dispatch::matmul::matmul_f16_f16_f16: lhs/rhs must be F16, got ({:?}, {:?})",
2268                lhs_guard.dtype, rhs_guard.dtype,
2269            )).bt());
2270        }
2271        let lhs = vulkan_input(&lhs_guard)?;
2272        let rhs = vulkan_input(&rhs_guard)?;
2273        let backend = lhs.backend().ok_or_else(|| {
2274            Error::Msg(
2275                "vulkan_dispatch::matmul::matmul_f16_f16_f16: lhs has no VulkanBackend handle."
2276                    .to_string(),
2277            )
2278            .bt()
2279        })?;
2280        let out = vulkan_output(&mut out_guard)?;
2281        backend.matmul_f16_f16_f16_bytes(lhs, rhs, out, &lhs_batch_dims, &rhs_batch_dims, m, n, k)
2282    }
2283}
2284
2285// ===========================================================================
2286// Concat — f32, binary (V.2.D)
2287// ===========================================================================
2288//
2289// Vulkan's legacy `concat_along_dim` kernel is 2-input. Fuel's
2290// `OpKind::Concat` is N-input. This wrapper handles N == 2 only —
2291// for N > 2 it errors and the route picker falls back to a CPU /
2292// CUDA alternative. Chain-for-N>2 is V.3 work.
2293//
2294// The concat `dim` is recovered from `OpParams::Concat.outer_count`
2295// + the first input's layout (outer_count = product of dims before
2296// the concat axis).
2297
2298/// Vulkan dispatch wrappers for gather along a dimension.
2299pub mod gather {
2300    use super::*;
2301
2302    /// Gather along `dim`. 2 inputs (src, U32 indices) + 1 output.
2303    /// Output dtype determines byte width.
2304    pub fn gather(
2305        inputs: &[Arc<RwLock<Storage>>],
2306        outputs: &mut [Arc<RwLock<Storage>>],
2307        _layouts: &[Layout],
2308        params: &OpParams,
2309    ) -> Result<()> {
2310        if inputs.len() != 2 || outputs.len() != 1 {
2311            return Err(Error::Msg(format!(
2312                "vulkan_dispatch::gather::gather: expected 2 inputs (src, indices) + 1 output, got {} + {}",
2313                inputs.len(), outputs.len(),
2314            )).bt());
2315        }
2316        let (source_shape, output_shape, dim) = match params {
2317            OpParams::Gather {
2318                source_shape,
2319                output_shape,
2320                dim,
2321            } => (source_shape.clone(), output_shape.clone(), *dim),
2322            other => {
2323                return Err(Error::Msg(format!(
2324                    "vulkan_dispatch::gather::gather: expected OpParams::Gather, got {other:?}",
2325                ))
2326                .bt());
2327            }
2328        };
2329        let src_guard = read_storage(&inputs[0])?;
2330        let idx_guard = read_storage(&inputs[1])?;
2331        if idx_guard.dtype != DType::U32 {
2332            return Err(Error::Msg(format!(
2333                "vulkan_dispatch::gather::gather: indices must be U32, got {:?}",
2334                idx_guard.dtype,
2335            ))
2336            .bt());
2337        }
2338        let mut out_guard = write_storage(&outputs[0])?;
2339        let elem_bytes = out_guard.dtype.size_in_bytes();
2340        let src = vulkan_input(&src_guard)?;
2341        let indices = vulkan_input(&idx_guard)?;
2342        let backend = src.backend().ok_or_else(|| {
2343            Error::Msg(
2344                "vulkan_dispatch::gather::gather: src has no VulkanBackend handle.".to_string(),
2345            )
2346            .bt()
2347        })?;
2348        let bound = source_shape.get(dim).copied().ok_or_else(|| {
2349            Error::Msg(format!("gather: dim {dim} is outside {source_shape:?}")).bt()
2350        })?;
2351        let numel = output_shape.iter().product();
2352        decline_oob_index_read("gather", backend, indices, numel, bound)?;
2353        let out = vulkan_output(&mut out_guard)?;
2354        backend.gather_bytes(
2355            src,
2356            indices,
2357            out,
2358            &source_shape,
2359            &output_shape,
2360            dim,
2361            elem_bytes,
2362        )
2363    }
2364}
2365
2366/// Vulkan dispatch wrappers for masked fill with a Bool mask.
2367pub mod masked_fill {
2368    use super::*;
2369
2370    /// MaskedFill — 2 inputs (input, mask) + 1 output. mask is **Bool** (GAP-168(c)).
2371    /// Byte width is taken from the OUTPUT dtype size; same dispatch
2372    /// shim handles all dtypes.
2373    pub fn masked_fill(
2374        inputs: &[Arc<RwLock<Storage>>],
2375        outputs: &mut [Arc<RwLock<Storage>>],
2376        _layouts: &[Layout],
2377        params: &OpParams,
2378    ) -> Result<()> {
2379        if inputs.len() != 2 || outputs.len() != 1 {
2380            return Err(Error::Msg(format!(
2381                "vulkan_dispatch::masked_fill::masked_fill: expected 2 inputs (input, mask) + 1 output, got {} + {}",
2382                inputs.len(), outputs.len(),
2383            )).bt());
2384        }
2385        let fill_bytes = match params {
2386            OpParams::MaskedFill { fill_bytes } => fill_bytes.clone(),
2387            other => {
2388                return Err(Error::Msg(format!(
2389                    "vulkan_dispatch::masked_fill::masked_fill: expected OpParams::MaskedFill, got {other:?}",
2390                )).bt());
2391            }
2392        };
2393        let in_guard = read_storage(&inputs[0])?;
2394        let mask_guard = read_storage(&inputs[1])?;
2395        // GAP-168(c): mask is Bool, matching vulkan/select.fkc.md and
2396        // vulkan/padding.fkc.md. Vulkan storage is raw bytes tagged by dtype, so
2397        // this check is the only thing distinguishing a Bool mask from a
2398        // byte-identical U8 buffer.
2399        if mask_guard.dtype != DType::Bool {
2400            return Err(Error::Msg(format!(
2401                "vulkan_dispatch::masked_fill::masked_fill: mask must be Bool, got {:?} (GAP-168(c))",
2402                mask_guard.dtype,
2403            )).bt());
2404        }
2405        let mut out_guard = write_storage(&outputs[0])?;
2406        let elem_bytes = out_guard.dtype.size_in_bytes();
2407        let a = vulkan_input(&in_guard)?;
2408        let mask = vulkan_input(&mask_guard)?;
2409        let backend = a.backend().ok_or_else(|| {
2410            Error::Msg(
2411                "vulkan_dispatch::masked_fill::masked_fill: input has no VulkanBackend handle."
2412                    .to_string(),
2413            )
2414            .bt()
2415        })?;
2416        let out = vulkan_output(&mut out_guard)?;
2417        let n_elem = a.len_bytes() / elem_bytes;
2418        backend.masked_fill_bytes(a, mask, out, n_elem, elem_bytes, &fill_bytes)
2419    }
2420}
2421
2422/// Vulkan dispatch wrappers for padding forward/backward.
2423pub mod pad {
2424    use super::*;
2425
2426    /// PadBackward — 1 input (grad_out) + 1 output (grad_in). Reads
2427    /// geometry from OpParams::PadBackward. Currently handles
2428    /// mode_tag == 0 (constant) only; reflect/replicate need atomic
2429    /// float add (not yet wired) and fall through to CPU.
2430    pub fn pad_backward(
2431        inputs: &[Arc<RwLock<Storage>>],
2432        outputs: &mut [Arc<RwLock<Storage>>],
2433        _layouts: &[Layout],
2434        params: &OpParams,
2435    ) -> Result<()> {
2436        if inputs.len() != 1 || outputs.len() != 1 {
2437            return Err(Error::Msg(format!(
2438                "vulkan_dispatch::pad::pad_backward: expected 1 input + 1 output, got {} + {}",
2439                inputs.len(),
2440                outputs.len(),
2441            ))
2442            .bt());
2443        }
2444        let (in_shape, out_shape, padding, mode_tag) = match params {
2445            OpParams::PadBackward {
2446                in_shape,
2447                out_shape,
2448                padding,
2449                mode_tag,
2450            } => (in_shape, out_shape, padding, *mode_tag),
2451            other => {
2452                return Err(Error::Msg(format!(
2453                    "vulkan_dispatch::pad::pad_backward: expected OpParams::PadBackward, got {other:?}",
2454                )).bt());
2455            }
2456        };
2457        let in_guard = read_storage(&inputs[0])?;
2458        let mut out_guard = write_storage(&outputs[0])?;
2459        let dtype = out_guard.dtype;
2460        let elem_bytes = dtype.size_in_bytes();
2461        let go = vulkan_input(&in_guard)?;
2462        let backend = go.backend().ok_or_else(|| {
2463            Error::Msg(
2464                "vulkan_dispatch::pad::pad_backward: grad_out has no VulkanBackend handle."
2465                    .to_string(),
2466            )
2467            .bt()
2468        })?;
2469        let gi = vulkan_output(&mut out_guard)?;
2470        let left_pad: Vec<usize> = padding.iter().map(|&(b, _)| b).collect();
2471        match mode_tag {
2472            0 => {
2473                backend.pad_backward_const_bytes(go, gi, in_shape, out_shape, &left_pad, elem_bytes)
2474            }
2475            1 | 2 => match dtype {
2476                DType::F32 | DType::F64 | DType::BF16 | DType::F16 => backend
2477                    .pad_backward_atomic_bytes(
2478                        dtype, go, gi, in_shape, out_shape, &left_pad, mode_tag,
2479                    ),
2480                _ => Err(Error::Msg(format!(
2481                    "vulkan_dispatch::pad::pad_backward: mode_tag {mode_tag} only \
2482                     supports F32/F64/BF16/F16 on Vulkan (atomic CAS path); got {dtype:?}",
2483                ))
2484                .bt()),
2485            },
2486            other => Err(Error::Msg(format!(
2487                "vulkan_dispatch::pad::pad_backward: unknown mode_tag {other}",
2488            ))
2489            .bt()),
2490        }
2491    }
2492
2493    /// Pad — 1 input + 1 output. Reads geometry from OpParams::Pad.
2494    /// `mode_tag == 0` (constant) is the only mode this dispatch
2495    /// shim handles; other modes fall through to CPU.
2496    /// Byte width is taken from the OUTPUT dtype's size.
2497    pub fn pad_const(
2498        inputs: &[Arc<RwLock<Storage>>],
2499        outputs: &mut [Arc<RwLock<Storage>>],
2500        _layouts: &[Layout],
2501        params: &OpParams,
2502    ) -> Result<()> {
2503        if inputs.len() != 1 || outputs.len() != 1 {
2504            return Err(Error::Msg(format!(
2505                "vulkan_dispatch::pad::pad_const: expected 1 input + 1 output, got {} + {}",
2506                inputs.len(),
2507                outputs.len(),
2508            ))
2509            .bt());
2510        }
2511        let (in_shape, out_shape, padding, mode_tag, fill_bytes) = match params {
2512            OpParams::Pad {
2513                in_shape,
2514                out_shape,
2515                padding,
2516                mode_tag,
2517                fill_bytes,
2518            } => (in_shape, out_shape, padding, *mode_tag, fill_bytes),
2519            other => {
2520                return Err(Error::Msg(format!(
2521                    "vulkan_dispatch::pad::pad_const: expected OpParams::Pad, got {other:?}",
2522                ))
2523                .bt());
2524            }
2525        };
2526        let in_guard = read_storage(&inputs[0])?;
2527        let mut out_guard = write_storage(&outputs[0])?;
2528        let elem_bytes = out_guard.dtype.size_in_bytes();
2529        let a = vulkan_input(&in_guard)?;
2530        let backend = a.backend().ok_or_else(|| {
2531            Error::Msg(
2532                "vulkan_dispatch::pad::pad_const: input has no VulkanBackend handle.".to_string(),
2533            )
2534            .bt()
2535        })?;
2536        let out = vulkan_output(&mut out_guard)?;
2537        let left_pad: Vec<usize> = padding.iter().map(|&(b, _)| b).collect();
2538        match mode_tag {
2539            0 => backend.pad_const_bytes(
2540                a, out, in_shape, out_shape, &left_pad, elem_bytes, fill_bytes,
2541            ),
2542            1 => backend.pad_reflect_bytes(a, out, in_shape, out_shape, &left_pad, elem_bytes),
2543            2 => backend.pad_replicate_bytes(a, out, in_shape, out_shape, &left_pad, elem_bytes),
2544            other => Err(Error::Msg(format!(
2545                "vulkan_dispatch::pad::pad_const: unknown mode_tag {other}",
2546            ))
2547            .bt()),
2548        }
2549    }
2550}
2551
2552/// Vulkan dispatch wrappers for concatenation along an axis, per dtype.
2553pub mod concat {
2554    use super::*;
2555    use fuel_ir::Shape;
2556    use fuel_memory::BackendStorage;
2557
2558    /// Generic concat dispatcher. Takes the per-pair concat call
2559    /// (which knows the source/destination dtype) plus the per-element
2560    /// byte size for sizing intermediates in the N>2 chain. The same
2561    /// N=1/N=2/N>2 shape works across all float dtypes.
2562    fn concat_typed<F>(
2563        label: &'static str,
2564        elem_bytes: usize,
2565        dtype: DType,
2566        inputs: &[Arc<RwLock<Storage>>],
2567        outputs: &mut [Arc<RwLock<Storage>>],
2568        layouts: &[Layout],
2569        params: &OpParams,
2570        pair_call: F,
2571    ) -> Result<()>
2572    where
2573        F: Fn(
2574            &fuel_vulkan_backend::VulkanBackend,
2575            &fuel_vulkan_backend::VulkanStorageBytes,
2576            &fuel_vulkan_backend::VulkanStorageBytes,
2577            &mut fuel_vulkan_backend::VulkanStorageBytes,
2578            usize,
2579            &Layout,
2580            &Layout,
2581        ) -> fuel_ir::Result<()>,
2582    {
2583        if outputs.len() != 1 {
2584            return Err(Error::Msg(format!(
2585                "vulkan_dispatch::concat::{label}: expected 1 output, got {}",
2586                outputs.len(),
2587            ))
2588            .bt());
2589        }
2590        if inputs.is_empty() {
2591            return Err(Error::Msg(format!("vulkan_dispatch::concat::{label}: 0 inputs",)).bt());
2592        }
2593        let (outer_count, input_dim_sizes, inner_count, dim) = match params {
2594            OpParams::Concat {
2595                outer_count,
2596                input_dim_sizes,
2597                inner_count,
2598                axis,
2599            } => (*outer_count, input_dim_sizes.clone(), *inner_count, *axis),
2600            other => {
2601                return Err(Error::Msg(format!(
2602                    "vulkan_dispatch::concat::{label}: expected OpParams::Concat, got {other:?}",
2603                ))
2604                .bt());
2605            }
2606        };
2607        if input_dim_sizes.len() != inputs.len() {
2608            return Err(Error::Msg(format!(
2609                "vulkan_dispatch::concat::{label}: OpParams declares {} inputs but work item carries {}",
2610                input_dim_sizes.len(), inputs.len(),
2611            )).bt());
2612        }
2613        if layouts.len() < inputs.len() {
2614            return Err(Error::Msg(format!(
2615                "vulkan_dispatch::concat::{label}: layouts.len() = {} < inputs.len() = {}",
2616                layouts.len(),
2617                inputs.len(),
2618            ))
2619            .bt());
2620        }
2621
2622        let n_inputs = inputs.len();
2623
2624        if n_inputs == 1 {
2625            return Err(Error::Msg(format!(
2626                "vulkan_dispatch::concat::{label}: N=1 concat unsupported \
2627                 (should be elided at graph level)",
2628            ))
2629            .bt());
2630        }
2631
2632        if n_inputs == 2 {
2633            let a_guard = read_storage(&inputs[0])?;
2634            let b_guard = read_storage(&inputs[1])?;
2635            let mut out_guard = write_storage(&outputs[0])?;
2636            let a = vulkan_input(&a_guard)?;
2637            let b = vulkan_input(&b_guard)?;
2638            let backend = a.backend().ok_or_else(|| {
2639                Error::Msg(format!(
2640                    "vulkan_dispatch::concat::{label}: a has no VulkanBackend handle.",
2641                ))
2642                .bt()
2643            })?;
2644            let out = vulkan_output(&mut out_guard)?;
2645            return pair_call(backend, a, b, out, dim, &layouts[0], &layouts[1]);
2646        }
2647
2648        // N > 2: chain pair-wise.
2649        let in_guards: Vec<_> = inputs
2650            .iter()
2651            .map(read_storage)
2652            .collect::<Result<Vec<_>>>()?;
2653        let mut in_vk: Vec<&fuel_vulkan_backend::VulkanStorageBytes> = Vec::with_capacity(n_inputs);
2654        for g in &in_guards {
2655            in_vk.push(vulkan_input(g)?);
2656        }
2657        let backend = in_vk[0]
2658            .backend()
2659            .ok_or_else(|| {
2660                Error::Msg(format!(
2661                    "vulkan_dispatch::concat::{label}: inputs[0] has no VulkanBackend handle.",
2662                ))
2663                .bt()
2664            })?
2665            .clone();
2666
2667        let template_dims: Vec<usize> = layouts[0].shape().dims().to_vec();
2668        let make_layout = |cum_dim: usize| -> Layout {
2669            let mut dims = template_dims.clone();
2670            dims[dim] = cum_dim;
2671            Layout::contiguous(Shape::from_dims(&dims))
2672        };
2673
2674        let mut acc_dim = input_dim_sizes[0] + input_dim_sizes[1];
2675        let acc_elems = outer_count * acc_dim * inner_count;
2676        let acc_bytes = backend
2677            .alloc_bytes_handle(acc_elems * elem_bytes)
2678            .map_err(|e| {
2679                Error::Msg(format!(
2680                    "vulkan_dispatch::concat::{label}: alloc intermediate failed: {e}",
2681                ))
2682                .bt()
2683            })?;
2684        let mut acc_storage = Storage::new(BackendStorage::Vulkan(acc_bytes), dtype);
2685        {
2686            let acc_vk = match &mut acc_storage.inner {
2687                BackendStorage::Vulkan(v) => v,
2688                _ => unreachable!("just allocated as Vulkan"),
2689            };
2690            pair_call(
2691                &backend,
2692                in_vk[0],
2693                in_vk[1],
2694                acc_vk,
2695                dim,
2696                &layouts[0],
2697                &layouts[1],
2698            )?;
2699        }
2700
2701        for i in 2..(n_inputs - 1) {
2702            let new_acc_dim = acc_dim + input_dim_sizes[i];
2703            let new_elems = outer_count * new_acc_dim * inner_count;
2704            let new_bytes = backend
2705                .alloc_bytes_handle(new_elems * elem_bytes)
2706                .map_err(|e| {
2707                    Error::Msg(format!(
2708                        "vulkan_dispatch::concat::{label}: alloc intermediate {i} failed: {e}",
2709                    ))
2710                    .bt()
2711                })?;
2712            let mut new_storage = Storage::new(BackendStorage::Vulkan(new_bytes), dtype);
2713
2714            let acc_layout = make_layout(acc_dim);
2715            let acc_vk_ref = match &acc_storage.inner {
2716                BackendStorage::Vulkan(v) => v,
2717                _ => unreachable!(),
2718            };
2719            let new_vk = match &mut new_storage.inner {
2720                BackendStorage::Vulkan(v) => v,
2721                _ => unreachable!(),
2722            };
2723            pair_call(
2724                &backend,
2725                acc_vk_ref,
2726                in_vk[i],
2727                new_vk,
2728                dim,
2729                &acc_layout,
2730                &layouts[i],
2731            )?;
2732
2733            acc_storage = new_storage;
2734            acc_dim = new_acc_dim;
2735        }
2736
2737        let acc_layout = make_layout(acc_dim);
2738        let acc_vk_ref = match &acc_storage.inner {
2739            BackendStorage::Vulkan(v) => v,
2740            _ => unreachable!(),
2741        };
2742        let mut out_guard = write_storage(&outputs[0])?;
2743        let out_vk = vulkan_output(&mut out_guard)?;
2744        pair_call(
2745            &backend,
2746            acc_vk_ref,
2747            in_vk[n_inputs - 1],
2748            out_vk,
2749            dim,
2750            &acc_layout,
2751            &layouts[n_inputs - 1],
2752        )
2753    }
2754
2755    /// `concat_f16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
2756    pub fn concat_f16(
2757        inputs: &[Arc<RwLock<Storage>>],
2758        outputs: &mut [Arc<RwLock<Storage>>],
2759        layouts: &[Layout],
2760        params: &OpParams,
2761    ) -> Result<()> {
2762        concat_typed(
2763            "concat_f16",
2764            2,
2765            DType::F16,
2766            inputs,
2767            outputs,
2768            layouts,
2769            params,
2770            |b, a, bb, o, dim, la, lb| b.concat_along_dim_f16_bytes(a, bb, o, dim, la, lb),
2771        )
2772    }
2773
2774    /// `concat_bf16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
2775    pub fn concat_bf16(
2776        inputs: &[Arc<RwLock<Storage>>],
2777        outputs: &mut [Arc<RwLock<Storage>>],
2778        layouts: &[Layout],
2779        params: &OpParams,
2780    ) -> Result<()> {
2781        concat_typed(
2782            "concat_bf16",
2783            2,
2784            DType::BF16,
2785            inputs,
2786            outputs,
2787            layouts,
2788            params,
2789            |b, a, bb, o, dim, la, lb| b.concat_along_dim_bf16_bytes(a, bb, o, dim, la, lb),
2790        )
2791    }
2792
2793    /// `concat_f64` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
2794    pub fn concat_f64(
2795        inputs: &[Arc<RwLock<Storage>>],
2796        outputs: &mut [Arc<RwLock<Storage>>],
2797        layouts: &[Layout],
2798        params: &OpParams,
2799    ) -> Result<()> {
2800        concat_typed(
2801            "concat_f64",
2802            8,
2803            DType::F64,
2804            inputs,
2805            outputs,
2806            layouts,
2807            params,
2808            |b, a, bb, o, dim, la, lb| b.concat_along_dim_f64_bytes(a, bb, o, dim, la, lb),
2809        )
2810    }
2811
2812    /// `concat_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
2813    pub fn concat_f32(
2814        inputs: &[Arc<RwLock<Storage>>],
2815        outputs: &mut [Arc<RwLock<Storage>>],
2816        layouts: &[Layout],
2817        params: &OpParams,
2818    ) -> Result<()> {
2819        if outputs.len() != 1 {
2820            return Err(Error::Msg(format!(
2821                "vulkan_dispatch::concat::concat_f32: expected 1 output, got {}",
2822                outputs.len(),
2823            ))
2824            .bt());
2825        }
2826        if inputs.is_empty() {
2827            return Err(
2828                Error::Msg("vulkan_dispatch::concat::concat_f32: 0 inputs".to_string()).bt(),
2829            );
2830        }
2831        let (outer_count, input_dim_sizes, inner_count, dim) = match params {
2832            OpParams::Concat {
2833                outer_count,
2834                input_dim_sizes,
2835                inner_count,
2836                axis,
2837            } => (*outer_count, input_dim_sizes.clone(), *inner_count, *axis),
2838            other => {
2839                return Err(Error::Msg(format!(
2840                    "vulkan_dispatch::concat::concat_f32: expected OpParams::Concat, got {:?}",
2841                    other,
2842                ))
2843                .bt());
2844            }
2845        };
2846        if input_dim_sizes.len() != inputs.len() {
2847            return Err(Error::Msg(format!(
2848                "vulkan_dispatch::concat::concat_f32: OpParams declares {} inputs but work item carries {}",
2849                input_dim_sizes.len(), inputs.len(),
2850            )).bt());
2851        }
2852        if layouts.len() < inputs.len() {
2853            return Err(Error::Msg(format!(
2854                "vulkan_dispatch::concat::concat_f32: layouts.len() = {} < inputs.len() = {}",
2855                layouts.len(),
2856                inputs.len(),
2857            ))
2858            .bt());
2859        }
2860
2861        let n_inputs = inputs.len();
2862
2863        // N == 1 degenerate: copy input → out.
2864        if n_inputs == 1 {
2865            let in_guard = read_storage(&inputs[0])?;
2866            let mut out_guard = write_storage(&outputs[0])?;
2867            let a = vulkan_input(&in_guard)?;
2868            let _backend = a.backend().ok_or_else(|| {
2869                Error::Msg(
2870                    "vulkan_dispatch::concat::concat_f32: input has no VulkanBackend handle."
2871                        .to_string(),
2872                )
2873                .bt()
2874            })?;
2875            let out = vulkan_output(&mut out_guard)?;
2876            let a_bytes = a
2877                .buffer_opt()
2878                .ok_or_else(|| Error::Msg("concat_f32 N=1: a is host-evicted".into()).bt())?;
2879            let out_buf = out
2880                .buffer_opt()
2881                .ok_or_else(|| Error::Msg("concat_f32 N=1: out is host-evicted".into()).bt())?;
2882            // Equal sizes — direct memcpy via the legacy queue.one_shot.
2883            // For now, error: N=1 should be optimized at the graph level
2884            // (skip the concat entirely), not via dispatch.
2885            let _ = (a_bytes, out_buf);
2886            return Err(Error::Msg(
2887                "vulkan_dispatch::concat::concat_f32: N=1 concat unsupported \
2888                 (should be elided at graph level)"
2889                    .into(),
2890            )
2891            .bt());
2892        }
2893
2894        // Fast path: N == 2. Direct single-call.
2895        if n_inputs == 2 {
2896            let a_guard = read_storage(&inputs[0])?;
2897            let b_guard = read_storage(&inputs[1])?;
2898            let mut out_guard = write_storage(&outputs[0])?;
2899            let a = vulkan_input(&a_guard)?;
2900            let b = vulkan_input(&b_guard)?;
2901            let backend = a.backend().ok_or_else(|| {
2902                Error::Msg(
2903                    "vulkan_dispatch::concat::concat_f32: a has no VulkanBackend handle."
2904                        .to_string(),
2905                )
2906                .bt()
2907            })?;
2908            let out = vulkan_output(&mut out_guard)?;
2909            return backend.concat_along_dim_f32_bytes(a, b, out, dim, &layouts[0], &layouts[1]);
2910        }
2911
2912        // N > 2: chain pair-wise via intermediate byte-storages. The
2913        // accumulator grows by `input_dim_sizes[i]` at each step.
2914        // We acquire all input guards up front to satisfy the borrow
2915        // checker (concat reads inputs sequentially).
2916        let in_guards: Vec<_> = inputs
2917            .iter()
2918            .map(read_storage)
2919            .collect::<Result<Vec<_>>>()?;
2920        let mut in_vk: Vec<&fuel_vulkan_backend::VulkanStorageBytes> = Vec::with_capacity(n_inputs);
2921        for g in &in_guards {
2922            in_vk.push(vulkan_input(g)?);
2923        }
2924        let backend = in_vk[0]
2925            .backend()
2926            .ok_or_else(|| {
2927                Error::Msg(
2928                    "vulkan_dispatch::concat::concat_f32: inputs[0] has no VulkanBackend handle. \
2929                 Storages flowing through the pipelined-executor binding-table dispatch \
2930                 must come from alloc_bytes_handle / upload_bytes_handle."
2931                        .to_string(),
2932                )
2933                .bt()
2934            })?
2935            .clone();
2936
2937        // Helper: construct the layout for an intermediate whose
2938        // concat-dim size is `cum_dim`. Uses the first input's shape
2939        // as the template (all inputs share every dim except the
2940        // concat axis).
2941        let template_dims: Vec<usize> = layouts[0].shape().dims().to_vec();
2942        let make_layout = |cum_dim: usize| -> Layout {
2943            let mut dims = template_dims.clone();
2944            dims[dim] = cum_dim;
2945            Layout::contiguous(Shape::from_dims(&dims))
2946        };
2947
2948        // Step 0: concat inputs[0] + inputs[1] → tmp0 (or out if N==2).
2949        let mut acc_dim = input_dim_sizes[0] + input_dim_sizes[1];
2950        let acc_elems = outer_count * acc_dim * inner_count;
2951        let mut acc_storage = if n_inputs == 2 {
2952            // unreachable here — N==2 fast path returned earlier.
2953            unreachable!()
2954        } else {
2955            let bytes = backend.alloc_bytes_handle(acc_elems * 4).map_err(|e| {
2956                Error::Msg(format!(
2957                    "vulkan_dispatch::concat::concat_f32: alloc intermediate failed: {e}",
2958                ))
2959                .bt()
2960            })?;
2961            Storage::new(BackendStorage::Vulkan(bytes), DType::F32)
2962        };
2963        {
2964            let acc_vk = match &mut acc_storage.inner {
2965                BackendStorage::Vulkan(v) => v,
2966                _ => unreachable!("just allocated as Vulkan"),
2967            };
2968            backend.concat_along_dim_f32_bytes(
2969                in_vk[0],
2970                in_vk[1],
2971                acc_vk,
2972                dim,
2973                &layouts[0],
2974                &layouts[1],
2975            )?;
2976        }
2977
2978        // Middle steps: concat acc + inputs[i] → new tmp.
2979        for i in 2..(n_inputs - 1) {
2980            let new_acc_dim = acc_dim + input_dim_sizes[i];
2981            let new_elems = outer_count * new_acc_dim * inner_count;
2982            let new_bytes = backend.alloc_bytes_handle(new_elems * 4).map_err(|e| {
2983                Error::Msg(format!(
2984                    "vulkan_dispatch::concat::concat_f32: alloc intermediate {i} failed: {e}",
2985                ))
2986                .bt()
2987            })?;
2988            let mut new_storage = Storage::new(BackendStorage::Vulkan(new_bytes), DType::F32);
2989
2990            let acc_layout = make_layout(acc_dim);
2991            let acc_vk_ref = match &acc_storage.inner {
2992                BackendStorage::Vulkan(v) => v,
2993                _ => unreachable!(),
2994            };
2995            let new_vk = match &mut new_storage.inner {
2996                BackendStorage::Vulkan(v) => v,
2997                _ => unreachable!(),
2998            };
2999            backend.concat_along_dim_f32_bytes(
3000                acc_vk_ref,
3001                in_vk[i],
3002                new_vk,
3003                dim,
3004                &acc_layout,
3005                &layouts[i],
3006            )?;
3007
3008            // Drop old acc (releases its buffer back to the VMA pool).
3009            acc_storage = new_storage;
3010            acc_dim = new_acc_dim;
3011        }
3012
3013        // Final step: concat acc + inputs[N-1] → outputs[0] (the
3014        // pre-allocated final output).
3015        let acc_layout = make_layout(acc_dim);
3016        let acc_vk_ref = match &acc_storage.inner {
3017            BackendStorage::Vulkan(v) => v,
3018            _ => unreachable!(),
3019        };
3020        let mut out_guard = write_storage(&outputs[0])?;
3021        let out_vk = vulkan_output(&mut out_guard)?;
3022        backend.concat_along_dim_f32_bytes(
3023            acc_vk_ref,
3024            in_vk[n_inputs - 1],
3025            out_vk,
3026            dim,
3027            &acc_layout,
3028            &layouts[n_inputs - 1],
3029        )
3030    }
3031}
3032
3033// ===========================================================================
3034// Reduce — Sum / Max / Min f32 (V.2.D)
3035// ===========================================================================
3036//
3037// The Vulkan kernel handles two fast paths only:
3038//   - full reduction (all dims or empty dims)
3039//   - single last-dim reduction
3040// Other dim combinations bail; the route picker can fall back to CPU.
3041//
3042// `MeanReduce` is deferred to V.3 — the legacy Vulkan kernel doesn't
3043// support it (no scalar-divide pass; would need a sum + affine
3044// follow-up).
3045
3046macro_rules! vk_reduce_f32_wrapper {
3047    ($name:ident, $op_id:expr, $label:expr $(,)?) => {
3048        pub fn $name(
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(format!(
3056                    "vulkan_dispatch::reduce::{}: expected 1 input + 1 output, got {} + {}",
3057                    $label,
3058                    inputs.len(),
3059                    outputs.len(),
3060                ))
3061                .bt());
3062            }
3063            let dims = match params {
3064                OpParams::Reduce { dims, keepdim: _ } => dims.clone(),
3065                other => {
3066                    return Err(Error::Msg(format!(
3067                        "vulkan_dispatch::reduce::{}: expected OpParams::Reduce, got {:?}",
3068                        $label, other,
3069                    ))
3070                    .bt());
3071                }
3072            };
3073            let layout = layouts.first().ok_or_else(|| {
3074                Error::Msg(format!(
3075                    "vulkan_dispatch::reduce::{}: layouts[0] required",
3076                    $label,
3077                ))
3078                .bt()
3079            })?;
3080            let in_guard = read_storage(&inputs[0])?;
3081            let mut out_guard = write_storage(&outputs[0])?;
3082            let a = vulkan_input(&in_guard)?;
3083            let backend = a.backend().ok_or_else(|| {
3084                Error::Msg(format!(
3085                    "vulkan_dispatch::reduce::{}: input has no VulkanBackend handle. \
3086                     Storages flowing through the pipelined-executor binding-table \
3087                     dispatch must come from alloc_bytes_handle / upload_bytes_handle.",
3088                    $label,
3089                ))
3090                .bt()
3091            })?;
3092            let out = vulkan_output(&mut out_guard)?;
3093            backend.reduce_f32_bytes($op_id, $label, a, out, layout, &dims)
3094        }
3095    };
3096}
3097
3098// V.3.G (2026-05-30): non-f32 dtypes only support the last-dim fast
3099// path. The macro parameterizes the backend method so f16/bf16/f64
3100// each get their 4-op surface (sum/max/min/mean) without dispatching
3101// through the f32 unified entry point. For dim combos other than the
3102// single-last-dim case, the backend method bails and the executor
3103// falls back to CPU.
3104// ----- ArgMax / ArgMin along last-dim (V.3.G.arg_reduce, 2026-05-30).
3105// Output is U32 indices (one per row). Reuses OpParams::Reduce with
3106// a single-dim constraint matching CUDA. Only last-dim is native;
3107// other dim combos fall back to CPU.
3108macro_rules! vk_arg_reduce_wrapper {
3109    ($name:ident, $op_id:expr, $label:expr, $dtype:expr $(,)?) => {
3110        pub fn $name(
3111            inputs: &[Arc<RwLock<Storage>>],
3112            outputs: &mut [Arc<RwLock<Storage>>],
3113            layouts: &[Layout],
3114            params: &OpParams,
3115        ) -> Result<()> {
3116            if inputs.len() != 1 || outputs.len() != 1 {
3117                return Err(Error::Msg(format!(
3118                    "vulkan_dispatch::arg_reduce::{}: expected 1 input + 1 output, got {} + {}",
3119                    $label, inputs.len(), outputs.len(),
3120                )).bt());
3121            }
3122            let dim = match params {
3123                OpParams::Reduce { dims, keepdim: _ } => {
3124                    if dims.len() != 1 {
3125                        return Err(Error::Msg(format!(
3126                            "vulkan_dispatch::arg_reduce::{}: expected single reduce dim, got {dims:?}",
3127                            $label,
3128                        )).bt());
3129                    }
3130                    dims[0]
3131                }
3132                other => {
3133                    return Err(Error::Msg(format!(
3134                        "vulkan_dispatch::arg_reduce::{}: expected OpParams::Reduce, got {other:?}",
3135                        $label,
3136                    )).bt());
3137                }
3138            };
3139            let layout = layouts.first().ok_or_else(|| {
3140                Error::Msg(format!(
3141                    "vulkan_dispatch::arg_reduce::{}: layouts empty", $label,
3142                )).bt()
3143            })?;
3144            let shape = layout.shape();
3145            let rank = shape.dims().len();
3146            if dim >= rank {
3147                return Err(Error::Msg(format!(
3148                    "vulkan_dispatch::arg_reduce::{}: dim {dim} >= rank {rank}",
3149                    $label,
3150                )).bt());
3151            }
3152            let dims_slice = shape.dims();
3153            let in_guard = read_storage(&inputs[0])?;
3154            let mut out_guard = write_storage(&outputs[0])?;
3155            let a = vulkan_input(&in_guard)?;
3156            let backend = a.backend().ok_or_else(|| {
3157                Error::Msg(format!(
3158                    "vulkan_dispatch::arg_reduce::{}: input has no VulkanBackend handle.",
3159                    $label,
3160                )).bt()
3161            })?;
3162            let out = vulkan_output(&mut out_guard)?;
3163            if dim == rank - 1 {
3164                let last_dim = dims_slice[rank - 1];
3165                let outer_count: usize = dims_slice[..rank - 1].iter().product::<usize>().max(1);
3166                backend.arg_reduce_last_dim_bytes($dtype, $op_id, $label, a, out, outer_count, last_dim)
3167            } else {
3168                let n_outer: usize = dims_slice[..dim].iter().product::<usize>().max(1);
3169                let d_dim = dims_slice[dim];
3170                let n_inner: usize = dims_slice[dim + 1..].iter().product::<usize>().max(1);
3171                backend.arg_reduce_any_dim_bytes($dtype, $op_id, $label, a, out, n_outer, d_dim, n_inner)
3172            }
3173        }
3174    };
3175}
3176
3177/// Vulkan dispatch wrappers for `index_add` along a dimension, per dtype.
3178pub mod index_add {
3179    use super::*;
3180
3181    /// `index_add_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
3182    pub fn index_add_f32(
3183        inputs: &[Arc<RwLock<Storage>>],
3184        outputs: &mut [Arc<RwLock<Storage>>],
3185        _layouts: &[Layout],
3186        params: &OpParams,
3187    ) -> Result<()> {
3188        index_add_dispatch(
3189            inputs,
3190            outputs,
3191            params,
3192            "index_add_f32",
3193            |b, base, idx, src, out, oc, bds, ni, ic| {
3194                b.index_add_f32_bytes(base, idx, src, out, oc, bds, ni, ic)
3195            },
3196        )
3197    }
3198
3199    /// `index_add_f64` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
3200    pub fn index_add_f64(
3201        inputs: &[Arc<RwLock<Storage>>],
3202        outputs: &mut [Arc<RwLock<Storage>>],
3203        _layouts: &[Layout],
3204        params: &OpParams,
3205    ) -> Result<()> {
3206        index_add_dispatch(
3207            inputs,
3208            outputs,
3209            params,
3210            "index_add_f64",
3211            |b, base, idx, src, out, oc, bds, ni, ic| {
3212                b.index_add_f64_bytes(base, idx, src, out, oc, bds, ni, ic)
3213            },
3214        )
3215    }
3216
3217    /// `index_add_bf16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
3218    pub fn index_add_bf16(
3219        inputs: &[Arc<RwLock<Storage>>],
3220        outputs: &mut [Arc<RwLock<Storage>>],
3221        _layouts: &[Layout],
3222        params: &OpParams,
3223    ) -> Result<()> {
3224        index_add_dispatch(
3225            inputs,
3226            outputs,
3227            params,
3228            "index_add_bf16",
3229            |b, base, idx, src, out, oc, bds, ni, ic| {
3230                b.index_add_bf16_bytes(base, idx, src, out, oc, bds, ni, ic)
3231            },
3232        )
3233    }
3234
3235    /// `index_add_f16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
3236    pub fn index_add_f16(
3237        inputs: &[Arc<RwLock<Storage>>],
3238        outputs: &mut [Arc<RwLock<Storage>>],
3239        _layouts: &[Layout],
3240        params: &OpParams,
3241    ) -> Result<()> {
3242        index_add_dispatch(
3243            inputs,
3244            outputs,
3245            params,
3246            "index_add_f16",
3247            |b, base, idx, src, out, oc, bds, ni, ic| {
3248                b.index_add_f16_bytes(base, idx, src, out, oc, bds, ni, ic)
3249            },
3250        )
3251    }
3252
3253    fn index_add_dispatch<F>(
3254        inputs: &[Arc<RwLock<Storage>>],
3255        outputs: &mut [Arc<RwLock<Storage>>],
3256        params: &OpParams,
3257        debug_name: &'static str,
3258        f: F,
3259    ) -> Result<()>
3260    where
3261        F: FnOnce(
3262            &fuel_vulkan_backend::VulkanBackend,
3263            &fuel_vulkan_backend::VulkanStorageBytes,
3264            &fuel_vulkan_backend::VulkanStorageBytes,
3265            &fuel_vulkan_backend::VulkanStorageBytes,
3266            &mut fuel_vulkan_backend::VulkanStorageBytes,
3267            usize,
3268            usize,
3269            usize,
3270            usize,
3271        ) -> Result<()>,
3272    {
3273        if inputs.len() != 3 || outputs.len() != 1 {
3274            return Err(Error::Msg(format!(
3275                "vulkan_dispatch::index_add::{debug_name}: expected 3 inputs + 1 output, got {} + {}",
3276                inputs.len(), outputs.len(),
3277            )).bt());
3278        }
3279        let (outer_count, base_dim_size, n_indices, inner_count) = match params {
3280            OpParams::IndexAdd {
3281                outer_count,
3282                base_dim_size,
3283                n_indices,
3284                inner_count,
3285            } => (*outer_count, *base_dim_size, *n_indices, *inner_count),
3286            other => {
3287                return Err(Error::Msg(format!(
3288                    "vulkan_dispatch::index_add::{debug_name}: expected OpParams::IndexAdd, got {other:?}",
3289                )).bt());
3290            }
3291        };
3292        let base_guard = read_storage(&inputs[0])?;
3293        let idx_guard = read_storage(&inputs[1])?;
3294        if idx_guard.dtype != DType::U32 {
3295            return Err(Error::Msg(format!(
3296                "vulkan_dispatch::index_add::{debug_name}: indices must be U32, got {:?}",
3297                idx_guard.dtype,
3298            ))
3299            .bt());
3300        }
3301        let src_guard = read_storage(&inputs[2])?;
3302        let mut out_guard = write_storage(&outputs[0])?;
3303        let base = vulkan_input(&base_guard)?;
3304        let indices = vulkan_input(&idx_guard)?;
3305        let src = vulkan_input(&src_guard)?;
3306        let backend = base.backend().ok_or_else(|| {
3307            Error::Msg(format!(
3308                "vulkan_dispatch::index_add::{debug_name}: base has no VulkanBackend handle.",
3309            ))
3310            .bt()
3311        })?;
3312        let out = vulkan_output(&mut out_guard)?;
3313        f(
3314            backend,
3315            base,
3316            indices,
3317            src,
3318            out,
3319            outer_count,
3320            base_dim_size,
3321            n_indices,
3322            inner_count,
3323        )
3324    }
3325}
3326
3327/// Vulkan dispatch wrappers for `scatter_add` along a dimension, per dtype.
3328pub mod scatter_add {
3329    use super::*;
3330
3331    /// ScatterAdd along `dim` — f32. 3 inputs (base, U32 indices, src)
3332    /// → 1 output (same shape as base). Output starts initialized to
3333    /// base; the kernel atomically accumulates src into the indexed
3334    /// positions.
3335    pub fn scatter_add_f32(
3336        inputs: &[Arc<RwLock<Storage>>],
3337        outputs: &mut [Arc<RwLock<Storage>>],
3338        _layouts: &[Layout],
3339        params: &OpParams,
3340    ) -> Result<()> {
3341        if inputs.len() != 3 || outputs.len() != 1 {
3342            return Err(Error::Msg(format!(
3343                "vulkan_dispatch::scatter_add::scatter_add_f32: expected 3 inputs + 1 output, got {} + {}",
3344                inputs.len(), outputs.len(),
3345            )).bt());
3346        }
3347        let (base_shape, src_shape, dim) = match params {
3348            OpParams::ScatterAdd {
3349                base_shape,
3350                src_shape,
3351                dim,
3352            } => (base_shape.clone(), src_shape.clone(), *dim),
3353            other => {
3354                return Err(Error::Msg(format!(
3355                    "vulkan_dispatch::scatter_add::scatter_add_f32: expected OpParams::ScatterAdd, got {other:?}",
3356                )).bt());
3357            }
3358        };
3359        let base_guard = read_storage(&inputs[0])?;
3360        let idx_guard = read_storage(&inputs[1])?;
3361        if idx_guard.dtype != DType::U32 {
3362            return Err(Error::Msg(format!(
3363                "vulkan_dispatch::scatter_add::scatter_add_f32: indices must be U32, got {:?}",
3364                idx_guard.dtype,
3365            ))
3366            .bt());
3367        }
3368        let src_guard = read_storage(&inputs[2])?;
3369        let mut out_guard = write_storage(&outputs[0])?;
3370        let base = vulkan_input(&base_guard)?;
3371        let indices = vulkan_input(&idx_guard)?;
3372        let src = vulkan_input(&src_guard)?;
3373        let backend = base.backend().ok_or_else(|| {
3374            Error::Msg(
3375                "vulkan_dispatch::scatter_add::scatter_add_f32: base has no VulkanBackend handle."
3376                    .to_string(),
3377            )
3378            .bt()
3379        })?;
3380        let out = vulkan_output(&mut out_guard)?;
3381        backend.scatter_add_f32_bytes(base, indices, src, out, &base_shape, &src_shape, dim)
3382    }
3383
3384    /// ScatterAdd along `dim` — f64. Same shape as scatter_add_f32 but
3385    /// uses u64 CAS for atomic double add. Requires shaderFloat64 +
3386    /// shaderInt64.
3387    pub fn scatter_add_f64(
3388        inputs: &[Arc<RwLock<Storage>>],
3389        outputs: &mut [Arc<RwLock<Storage>>],
3390        _layouts: &[Layout],
3391        params: &OpParams,
3392    ) -> Result<()> {
3393        if inputs.len() != 3 || outputs.len() != 1 {
3394            return Err(Error::Msg(format!(
3395                "vulkan_dispatch::scatter_add::scatter_add_f64: expected 3 inputs + 1 output, got {} + {}",
3396                inputs.len(), outputs.len(),
3397            )).bt());
3398        }
3399        let (base_shape, src_shape, dim) = match params {
3400            OpParams::ScatterAdd {
3401                base_shape,
3402                src_shape,
3403                dim,
3404            } => (base_shape.clone(), src_shape.clone(), *dim),
3405            other => {
3406                return Err(Error::Msg(format!(
3407                    "vulkan_dispatch::scatter_add::scatter_add_f64: expected OpParams::ScatterAdd, got {other:?}",
3408                )).bt());
3409            }
3410        };
3411        let base_guard = read_storage(&inputs[0])?;
3412        let idx_guard = read_storage(&inputs[1])?;
3413        if idx_guard.dtype != DType::U32 {
3414            return Err(Error::Msg(format!(
3415                "vulkan_dispatch::scatter_add::scatter_add_f64: indices must be U32, got {:?}",
3416                idx_guard.dtype,
3417            ))
3418            .bt());
3419        }
3420        let src_guard = read_storage(&inputs[2])?;
3421        let mut out_guard = write_storage(&outputs[0])?;
3422        let base = vulkan_input(&base_guard)?;
3423        let indices = vulkan_input(&idx_guard)?;
3424        let src = vulkan_input(&src_guard)?;
3425        let backend = base.backend().ok_or_else(|| {
3426            Error::Msg(
3427                "vulkan_dispatch::scatter_add::scatter_add_f64: base has no VulkanBackend handle."
3428                    .to_string(),
3429            )
3430            .bt()
3431        })?;
3432        let out = vulkan_output(&mut out_guard)?;
3433        backend.scatter_add_f64_bytes(base, indices, src, out, &base_shape, &src_shape, dim)
3434    }
3435
3436    /// ScatterAdd along `dim` — bf16. 2-byte elements; backend runs
3437    /// a sub-word CAS on packed-u32 output.
3438    pub fn scatter_add_bf16(
3439        inputs: &[Arc<RwLock<Storage>>],
3440        outputs: &mut [Arc<RwLock<Storage>>],
3441        _layouts: &[Layout],
3442        params: &OpParams,
3443    ) -> Result<()> {
3444        scatter_add_subword(
3445            inputs,
3446            outputs,
3447            params,
3448            DType::BF16,
3449            "scatter_add_bf16",
3450            |backend, base, indices, src, out, bs, ss, dim| {
3451                backend.scatter_add_bf16_bytes(base, indices, src, out, bs, ss, dim)
3452            },
3453        )
3454    }
3455
3456    /// ScatterAdd along `dim` — f16. Same shape as bf16 path.
3457    pub fn scatter_add_f16(
3458        inputs: &[Arc<RwLock<Storage>>],
3459        outputs: &mut [Arc<RwLock<Storage>>],
3460        _layouts: &[Layout],
3461        params: &OpParams,
3462    ) -> Result<()> {
3463        scatter_add_subword(
3464            inputs,
3465            outputs,
3466            params,
3467            DType::F16,
3468            "scatter_add_f16",
3469            |backend, base, indices, src, out, bs, ss, dim| {
3470                backend.scatter_add_f16_bytes(base, indices, src, out, bs, ss, dim)
3471            },
3472        )
3473    }
3474
3475    fn scatter_add_subword<F>(
3476        inputs: &[Arc<RwLock<Storage>>],
3477        outputs: &mut [Arc<RwLock<Storage>>],
3478        params: &OpParams,
3479        expected_dtype: DType,
3480        debug_name: &'static str,
3481        f: F,
3482    ) -> Result<()>
3483    where
3484        F: FnOnce(
3485            &fuel_vulkan_backend::VulkanBackend,
3486            &fuel_vulkan_backend::VulkanStorageBytes,
3487            &fuel_vulkan_backend::VulkanStorageBytes,
3488            &fuel_vulkan_backend::VulkanStorageBytes,
3489            &mut fuel_vulkan_backend::VulkanStorageBytes,
3490            &[usize],
3491            &[usize],
3492            usize,
3493        ) -> Result<()>,
3494    {
3495        if inputs.len() != 3 || outputs.len() != 1 {
3496            return Err(Error::Msg(format!(
3497                "vulkan_dispatch::scatter_add::{debug_name}: expected 3 inputs + 1 output, got {} + {}",
3498                inputs.len(), outputs.len(),
3499            )).bt());
3500        }
3501        let (base_shape, src_shape, dim) = match params {
3502            OpParams::ScatterAdd {
3503                base_shape,
3504                src_shape,
3505                dim,
3506            } => (base_shape.clone(), src_shape.clone(), *dim),
3507            other => {
3508                return Err(Error::Msg(format!(
3509                    "vulkan_dispatch::scatter_add::{debug_name}: expected OpParams::ScatterAdd, got {other:?}",
3510                )).bt());
3511            }
3512        };
3513        let _ = expected_dtype;
3514        let base_guard = read_storage(&inputs[0])?;
3515        let idx_guard = read_storage(&inputs[1])?;
3516        if idx_guard.dtype != DType::U32 {
3517            return Err(Error::Msg(format!(
3518                "vulkan_dispatch::scatter_add::{debug_name}: indices must be U32, got {:?}",
3519                idx_guard.dtype,
3520            ))
3521            .bt());
3522        }
3523        let src_guard = read_storage(&inputs[2])?;
3524        let mut out_guard = write_storage(&outputs[0])?;
3525        let base = vulkan_input(&base_guard)?;
3526        let indices = vulkan_input(&idx_guard)?;
3527        let src = vulkan_input(&src_guard)?;
3528        let backend = base.backend().ok_or_else(|| {
3529            Error::Msg(format!(
3530                "vulkan_dispatch::scatter_add::{debug_name}: base has no VulkanBackend handle.",
3531            ))
3532            .bt()
3533        })?;
3534        let out = vulkan_output(&mut out_guard)?;
3535        f(
3536            backend,
3537            base,
3538            indices,
3539            src,
3540            out,
3541            &base_shape,
3542            &src_shape,
3543            dim,
3544        )
3545    }
3546}
3547
3548/// Vulkan dispatch wrappers for argmax / argmin reductions, per dtype.
3549pub mod arg_reduce {
3550    use super::*;
3551
3552    vk_arg_reduce_wrapper!(argmax_f32, 0, "argmax_f32", DType::F32);
3553    vk_arg_reduce_wrapper!(argmin_f32, 1, "argmin_f32", DType::F32);
3554    vk_arg_reduce_wrapper!(argmax_f16, 0, "argmax_f16", DType::F16);
3555    vk_arg_reduce_wrapper!(argmin_f16, 1, "argmin_f16", DType::F16);
3556    vk_arg_reduce_wrapper!(argmax_bf16, 0, "argmax_bf16", DType::BF16);
3557    vk_arg_reduce_wrapper!(argmin_bf16, 1, "argmin_bf16", DType::BF16);
3558    vk_arg_reduce_wrapper!(argmax_f64, 0, "argmax_f64", DType::F64);
3559    vk_arg_reduce_wrapper!(argmin_f64, 1, "argmin_f64", DType::F64);
3560}
3561
3562macro_rules! vk_reduce_last_dim_wrapper {
3563    ($name:ident, $op_id:expr, $label:expr, $method:ident $(,)?) => {
3564        pub fn $name(
3565            inputs: &[Arc<RwLock<Storage>>],
3566            outputs: &mut [Arc<RwLock<Storage>>],
3567            layouts: &[Layout],
3568            params: &OpParams,
3569        ) -> Result<()> {
3570            if inputs.len() != 1 || outputs.len() != 1 {
3571                return Err(Error::Msg(format!(
3572                    "vulkan_dispatch::reduce::{}: expected 1 input + 1 output, got {} + {}",
3573                    $label,
3574                    inputs.len(),
3575                    outputs.len(),
3576                ))
3577                .bt());
3578            }
3579            let dims = match params {
3580                OpParams::Reduce { dims, keepdim: _ } => dims.clone(),
3581                other => {
3582                    return Err(Error::Msg(format!(
3583                        "vulkan_dispatch::reduce::{}: expected OpParams::Reduce, got {:?}",
3584                        $label, other,
3585                    ))
3586                    .bt());
3587                }
3588            };
3589            let layout = layouts.first().ok_or_else(|| {
3590                Error::Msg(format!(
3591                    "vulkan_dispatch::reduce::{}: layouts[0] required",
3592                    $label,
3593                ))
3594                .bt()
3595            })?;
3596            let in_guard = read_storage(&inputs[0])?;
3597            let mut out_guard = write_storage(&outputs[0])?;
3598            let a = vulkan_input(&in_guard)?;
3599            let backend = a.backend().ok_or_else(|| {
3600                Error::Msg(format!(
3601                    "vulkan_dispatch::reduce::{}: input has no VulkanBackend handle.",
3602                    $label,
3603                ))
3604                .bt()
3605            })?;
3606            let out = vulkan_output(&mut out_guard)?;
3607            backend.$method($op_id, $label, a, out, layout, &dims)
3608        }
3609    };
3610}
3611
3612/// Vulkan dispatch wrappers for sum / max / min / mean reductions.
3613pub mod reduce {
3614    use super::*;
3615
3616    vk_reduce_f32_wrapper!(sum_f32, 0, "reduce_sum_f32");
3617    vk_reduce_f32_wrapper!(max_f32, 1, "reduce_max_f32");
3618    vk_reduce_f32_wrapper!(min_f32, 2, "reduce_min_f32");
3619    // V.3.A.2: Mean added to reduce.slang + reduce_last_dim.slang as
3620    // op_id=3 (sum then divide by element count).
3621    vk_reduce_f32_wrapper!(mean_f32, 3, "reduce_mean_f32");
3622
3623    // ----- V.3.G (2026-05-30): f16/bf16/f64 per-row reductions.
3624    vk_reduce_last_dim_wrapper!(sum_f16, 0, "reduce_sum_f16", reduce_f16_bytes);
3625    vk_reduce_last_dim_wrapper!(max_f16, 1, "reduce_max_f16", reduce_f16_bytes);
3626    vk_reduce_last_dim_wrapper!(min_f16, 2, "reduce_min_f16", reduce_f16_bytes);
3627    vk_reduce_last_dim_wrapper!(mean_f16, 3, "reduce_mean_f16", reduce_f16_bytes);
3628
3629    vk_reduce_last_dim_wrapper!(sum_bf16, 0, "reduce_sum_bf16", reduce_bf16_bytes);
3630    vk_reduce_last_dim_wrapper!(max_bf16, 1, "reduce_max_bf16", reduce_bf16_bytes);
3631    vk_reduce_last_dim_wrapper!(min_bf16, 2, "reduce_min_bf16", reduce_bf16_bytes);
3632    vk_reduce_last_dim_wrapper!(mean_bf16, 3, "reduce_mean_bf16", reduce_bf16_bytes);
3633
3634    vk_reduce_last_dim_wrapper!(sum_f64, 0, "reduce_sum_f64", reduce_f64_bytes);
3635    vk_reduce_last_dim_wrapper!(max_f64, 1, "reduce_max_f64", reduce_f64_bytes);
3636    vk_reduce_last_dim_wrapper!(min_f64, 2, "reduce_min_f64", reduce_f64_bytes);
3637    vk_reduce_last_dim_wrapper!(mean_f64, 3, "reduce_mean_f64", reduce_f64_bytes);
3638}
3639
3640// ===========================================================================
3641// IndexSelect — f32 source + u32 ids (V.2.D)
3642// ===========================================================================
3643//
3644// Two inputs (src, ids) + one output. `OpParams::IndexSelect` carries
3645// the pre-computed geometry (outer/inner counts, source dim size,
3646// index count). The Slang kernel is dtype-aware via the descriptor
3647// binding (f32 storage buffer); V.3 fans out to other source dtypes.
3648
3649/// Vulkan dispatch wrappers for `index_select`, per dtype.
3650pub mod indexing {
3651    use super::*;
3652
3653    /// `index_select_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
3654    pub fn index_select_f32(
3655        inputs: &[Arc<RwLock<Storage>>],
3656        outputs: &mut [Arc<RwLock<Storage>>],
3657        _layouts: &[Layout],
3658        params: &OpParams,
3659    ) -> Result<()> {
3660        if inputs.len() != 2 || outputs.len() != 1 {
3661            return Err(Error::Msg(format!(
3662                "vulkan_dispatch::indexing::index_select_f32: expected 2 inputs + 1 output, got {} + {}",
3663                inputs.len(), outputs.len(),
3664            )).bt());
3665        }
3666        let (outer_count, source_dim_size, n_indices, inner_count) = match params {
3667            OpParams::IndexSelect {
3668                outer_count,
3669                source_dim_size,
3670                n_indices,
3671                inner_count,
3672            } => (*outer_count, *source_dim_size, *n_indices, *inner_count),
3673            other => {
3674                return Err(Error::Msg(format!(
3675                    "vulkan_dispatch::indexing::index_select_f32: expected OpParams::IndexSelect, got {:?}",
3676                    other,
3677                )).bt());
3678            }
3679        };
3680        let src_guard = read_storage(&inputs[0])?;
3681        let ids_guard = read_storage(&inputs[1])?;
3682        if ids_guard.dtype != DType::U32 {
3683            return Err(Error::Msg(format!(
3684                "vulkan_dispatch::indexing::index_select_f32: ids must be U32, got {:?}",
3685                ids_guard.dtype,
3686            ))
3687            .bt());
3688        }
3689        let mut out_guard = write_storage(&outputs[0])?;
3690        let src = vulkan_input(&src_guard)?;
3691        let ids = vulkan_input(&ids_guard)?;
3692        let backend = src.backend().ok_or_else(|| {
3693            Error::Msg(
3694                "vulkan_dispatch::indexing::index_select_f32: src has no VulkanBackend handle. \
3695                 Storages flowing through the pipelined-executor binding-table dispatch \
3696                 must come from alloc_bytes_handle / upload_bytes_handle."
3697                    .to_string(),
3698            )
3699            .bt()
3700        })?;
3701        decline_oob_index_read("index_select", backend, ids, n_indices, source_dim_size)?;
3702        let out = vulkan_output(&mut out_guard)?;
3703        backend.index_select_f32_bytes(
3704            src,
3705            ids,
3706            out,
3707            outer_count,
3708            source_dim_size,
3709            n_indices,
3710            inner_count,
3711        )
3712    }
3713
3714    /// `index_select_f16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
3715    pub fn index_select_f16(
3716        inputs: &[Arc<RwLock<Storage>>],
3717        outputs: &mut [Arc<RwLock<Storage>>],
3718        layouts: &[Layout],
3719        params: &OpParams,
3720    ) -> Result<()> {
3721        index_select_typed(
3722            "index_select_f16",
3723            inputs,
3724            outputs,
3725            layouts,
3726            params,
3727            |b, s, i, o, oc, sd, ni, ic| b.index_select_f16_bytes(s, i, o, oc, sd, ni, ic),
3728        )
3729    }
3730
3731    /// `index_select_bf16` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
3732    pub fn index_select_bf16(
3733        inputs: &[Arc<RwLock<Storage>>],
3734        outputs: &mut [Arc<RwLock<Storage>>],
3735        layouts: &[Layout],
3736        params: &OpParams,
3737    ) -> Result<()> {
3738        index_select_typed(
3739            "index_select_bf16",
3740            inputs,
3741            outputs,
3742            layouts,
3743            params,
3744            |b, s, i, o, oc, sd, ni, ic| b.index_select_bf16_bytes(s, i, o, oc, sd, ni, ic),
3745        )
3746    }
3747
3748    /// `index_select_f64` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
3749    pub fn index_select_f64(
3750        inputs: &[Arc<RwLock<Storage>>],
3751        outputs: &mut [Arc<RwLock<Storage>>],
3752        layouts: &[Layout],
3753        params: &OpParams,
3754    ) -> Result<()> {
3755        index_select_typed(
3756            "index_select_f64",
3757            inputs,
3758            outputs,
3759            layouts,
3760            params,
3761            |b, s, i, o, oc, sd, ni, ic| b.index_select_f64_bytes(s, i, o, oc, sd, ni, ic),
3762        )
3763    }
3764
3765    fn index_select_typed<F>(
3766        label: &'static str,
3767        inputs: &[Arc<RwLock<Storage>>],
3768        outputs: &mut [Arc<RwLock<Storage>>],
3769        _layouts: &[Layout],
3770        params: &OpParams,
3771        call: F,
3772    ) -> Result<()>
3773    where
3774        F: FnOnce(
3775            &fuel_vulkan_backend::VulkanBackend,
3776            &fuel_vulkan_backend::VulkanStorageBytes,
3777            &fuel_vulkan_backend::VulkanStorageBytes,
3778            &mut fuel_vulkan_backend::VulkanStorageBytes,
3779            usize,
3780            usize,
3781            usize,
3782            usize,
3783        ) -> fuel_ir::Result<()>,
3784    {
3785        if inputs.len() != 2 || outputs.len() != 1 {
3786            return Err(Error::Msg(format!(
3787                "vulkan_dispatch::indexing::{label}: expected 2 inputs + 1 output, got {} + {}",
3788                inputs.len(),
3789                outputs.len(),
3790            ))
3791            .bt());
3792        }
3793        let (outer_count, source_dim_size, n_indices, inner_count) = match params {
3794            OpParams::IndexSelect {
3795                outer_count,
3796                source_dim_size,
3797                n_indices,
3798                inner_count,
3799            } => (*outer_count, *source_dim_size, *n_indices, *inner_count),
3800            other => {
3801                return Err(Error::Msg(format!(
3802                    "vulkan_dispatch::indexing::{label}: expected OpParams::IndexSelect, got {other:?}",
3803                )).bt());
3804            }
3805        };
3806        let src_guard = read_storage(&inputs[0])?;
3807        let ids_guard = read_storage(&inputs[1])?;
3808        if ids_guard.dtype != DType::U32 {
3809            return Err(Error::Msg(format!(
3810                "vulkan_dispatch::indexing::{label}: ids must be U32, got {:?}",
3811                ids_guard.dtype,
3812            ))
3813            .bt());
3814        }
3815        let mut out_guard = write_storage(&outputs[0])?;
3816        let src = vulkan_input(&src_guard)?;
3817        let ids = vulkan_input(&ids_guard)?;
3818        let backend = src.backend().ok_or_else(|| {
3819            Error::Msg(format!(
3820                "vulkan_dispatch::indexing::{label}: src has no VulkanBackend handle.",
3821            ))
3822            .bt()
3823        })?;
3824        decline_oob_index_read("index_select", backend, ids, n_indices, source_dim_size)?;
3825        let out = vulkan_output(&mut out_guard)?;
3826        call(
3827            backend,
3828            src,
3829            ids,
3830            out,
3831            outer_count,
3832            source_dim_size,
3833            n_indices,
3834            inner_count,
3835        )
3836    }
3837}
3838
3839// ===========================================================================
3840// V.3.E.3+4 — bf16 fan-out via u32-packed manual math
3841// ===========================================================================
3842
3843macro_rules! vk_unary_bf16_wrapper {
3844    ($name:ident, $op_id:expr, $label:expr $(,)?) => {
3845        pub fn $name(
3846            inputs: &[Arc<RwLock<Storage>>],
3847            outputs: &mut [Arc<RwLock<Storage>>],
3848            _layouts: &[Layout],
3849            _params: &OpParams,
3850        ) -> Result<()> {
3851            if inputs.len() != 1 || outputs.len() != 1 {
3852                return Err(Error::Msg(format!(
3853                    "vulkan_dispatch::unary_bf16::{}: expected 1 input + 1 output, got {} + {}",
3854                    $label,
3855                    inputs.len(),
3856                    outputs.len(),
3857                ))
3858                .bt());
3859            }
3860            let in_guard = read_storage(&inputs[0])?;
3861            let mut out_guard = write_storage(&outputs[0])?;
3862            let a = vulkan_input(&in_guard)?;
3863            let backend = a.backend().ok_or_else(|| {
3864                Error::Msg(format!(
3865                    "vulkan_dispatch::unary_bf16::{}: input has no VulkanBackend handle.",
3866                    $label,
3867                ))
3868                .bt()
3869            })?;
3870            let out = vulkan_output(&mut out_guard)?;
3871            backend.unary_bf16_bytes($op_id, $label, a, out)
3872        }
3873    };
3874}
3875
3876/// Vulkan dispatch wrappers for bf16 elementwise unary ops (neg, sqr, sqrt, exp, log, sin, cos, tanh, ...).
3877pub mod unary_bf16 {
3878    use super::*;
3879    vk_unary_bf16_wrapper!(neg_bf16, 0, "unary_neg_bf16");
3880    vk_unary_bf16_wrapper!(sqr_bf16, 1, "unary_sqr_bf16");
3881    vk_unary_bf16_wrapper!(sqrt_bf16, 2, "unary_sqrt_bf16");
3882    vk_unary_bf16_wrapper!(exp_bf16, 3, "unary_exp_bf16");
3883    vk_unary_bf16_wrapper!(log_bf16, 4, "unary_log_bf16");
3884    vk_unary_bf16_wrapper!(sin_bf16, 5, "unary_sin_bf16");
3885    vk_unary_bf16_wrapper!(cos_bf16, 6, "unary_cos_bf16");
3886    vk_unary_bf16_wrapper!(tanh_bf16, 7, "unary_tanh_bf16");
3887    vk_unary_bf16_wrapper!(sigmoid_bf16, 8, "unary_sigmoid_bf16");
3888    vk_unary_bf16_wrapper!(silu_bf16, 9, "unary_silu_bf16");
3889    vk_unary_bf16_wrapper!(gelu_bf16, 10, "unary_gelu_bf16");
3890    vk_unary_bf16_wrapper!(relu_bf16, 11, "unary_relu_bf16");
3891    vk_unary_bf16_wrapper!(step_bf16, 12, "unary_step_bf16");
3892    vk_unary_bf16_wrapper!(abs_bf16, 13, "unary_abs_bf16");
3893    vk_unary_bf16_wrapper!(sign_bf16, 14, "unary_sign_bf16");
3894    vk_unary_bf16_wrapper!(recip_bf16, 15, "unary_recip_bf16");
3895}
3896
3897macro_rules! vk_binary_bf16_wrapper {
3898    ($name:ident, $op_id:expr, $label:expr $(,)?) => {
3899        pub fn $name(
3900            inputs: &[Arc<RwLock<Storage>>],
3901            outputs: &mut [Arc<RwLock<Storage>>],
3902            layouts: &[Layout],
3903            _params: &OpParams,
3904        ) -> Result<()> {
3905            if inputs.len() != 2 || outputs.len() != 1 {
3906                return Err(Error::Msg(format!(
3907                    "vulkan_dispatch::binary_bf16::{}: expected 2 inputs + 1 output, got {} + {}",
3908                    $label,
3909                    inputs.len(),
3910                    outputs.len(),
3911                ))
3912                .bt());
3913            }
3914            if layouts.len() < 2 {
3915                return Err(Error::Msg(format!(
3916                    "vulkan_dispatch::binary_bf16::{}: layouts.len() = {} < 2",
3917                    $label,
3918                    layouts.len(),
3919                ))
3920                .bt());
3921            }
3922            let in0_guard = read_storage(&inputs[0])?;
3923            let in1_guard = read_storage(&inputs[1])?;
3924            let mut out_guard = write_storage(&outputs[0])?;
3925            let a = vulkan_input(&in0_guard)?;
3926            let b = vulkan_input(&in1_guard)?;
3927            let backend = a.backend().ok_or_else(|| {
3928                Error::Msg(format!(
3929                    "vulkan_dispatch::binary_bf16::{}: input[0] has no VulkanBackend handle.",
3930                    $label,
3931                ))
3932                .bt()
3933            })?;
3934            let out = vulkan_output(&mut out_guard)?;
3935            backend.binary_bf16_bytes($op_id, $label, a, b, out, &layouts[0], &layouts[1])
3936        }
3937    };
3938}
3939
3940/// Vulkan dispatch wrappers for bf16 elementwise binary ops (add, sub, mul, div, maximum, minimum).
3941pub mod binary_bf16 {
3942    use super::*;
3943    vk_binary_bf16_wrapper!(add_bf16, 0, "binary_add_bf16");
3944    vk_binary_bf16_wrapper!(sub_bf16, 1, "binary_sub_bf16");
3945    vk_binary_bf16_wrapper!(mul_bf16, 2, "binary_mul_bf16");
3946    vk_binary_bf16_wrapper!(div_bf16, 3, "binary_div_bf16");
3947    vk_binary_bf16_wrapper!(maximum_bf16, 4, "binary_maximum_bf16");
3948    vk_binary_bf16_wrapper!(minimum_bf16, 5, "binary_minimum_bf16");
3949}
3950
3951// ===========================================================================
3952// Triu / Tril / Flip / Roll — byte-width-keyed (b2/b4/b8) via dtype
3953// ===========================================================================
3954
3955fn byte_width_for_dtype(label: &str, dt: DType) -> Result<usize> {
3956    match dt {
3957        DType::F32 | DType::I32 | DType::U32 => Ok(4),
3958        DType::F16 | DType::BF16 => Ok(2),
3959        DType::F64 | DType::I64 => Ok(8),
3960        other => Err(Error::Msg(format!(
3961            "{label}: unsupported dtype {other:?} (need 2/4/8-byte elem)"
3962        ))
3963        .bt()),
3964    }
3965}
3966
3967macro_rules! vk_triangular_wrapper {
3968    ($name:ident, $keep_upper:expr, $label:expr $(,)?) => {
3969        pub fn $name(
3970            inputs: &[Arc<RwLock<Storage>>],
3971            outputs: &mut [Arc<RwLock<Storage>>],
3972            _layouts: &[Layout],
3973            params: &OpParams,
3974        ) -> Result<()> {
3975            if inputs.len() != 1 || outputs.len() != 1 {
3976                return Err(Error::Msg(format!(
3977                    "vulkan_dispatch::triangular::{}: expected 1 input + 1 output, got {} + {}",
3978                    $label,
3979                    inputs.len(),
3980                    outputs.len(),
3981                ))
3982                .bt());
3983            }
3984            let (batch_count, rows, cols, diagonal) = match params {
3985                OpParams::Triangular {
3986                    batch_count,
3987                    rows,
3988                    cols,
3989                    diagonal,
3990                } => (*batch_count, *rows, *cols, *diagonal),
3991                other => {
3992                    return Err(Error::Msg(format!(
3993                        "vulkan_dispatch::triangular::{}: expected OpParams::Triangular, got {:?}",
3994                        $label, other,
3995                    ))
3996                    .bt());
3997                }
3998            };
3999            let in_guard = read_storage(&inputs[0])?;
4000            let mut out_guard = write_storage(&outputs[0])?;
4001            let dt = in_guard.dtype;
4002            let byte_width = byte_width_for_dtype($label, dt)?;
4003            let a = vulkan_input(&in_guard)?;
4004            let backend = a.backend().ok_or_else(|| {
4005                Error::Msg(format!(
4006                    "vulkan_dispatch::triangular::{}: input has no VulkanBackend handle.",
4007                    $label,
4008                ))
4009                .bt()
4010            })?;
4011            let out = vulkan_output(&mut out_guard)?;
4012            backend.triangular_bytes(
4013                byte_width,
4014                $keep_upper,
4015                a,
4016                out,
4017                batch_count,
4018                rows,
4019                cols,
4020                diagonal,
4021            )
4022        }
4023    };
4024}
4025
4026/// Vulkan dispatch wrappers for `triu` / `tril`.
4027pub mod triangular {
4028    use super::*;
4029    vk_triangular_wrapper!(triu, true, "triu");
4030    vk_triangular_wrapper!(tril, false, "tril");
4031}
4032
4033/// Vulkan dispatch wrappers for flip along an axis.
4034pub mod flip {
4035    use super::*;
4036
4037    /// `flip` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
4038    pub fn flip(
4039        inputs: &[Arc<RwLock<Storage>>],
4040        outputs: &mut [Arc<RwLock<Storage>>],
4041        layouts: &[Layout],
4042        params: &OpParams,
4043    ) -> Result<()> {
4044        if inputs.len() != 1 || outputs.len() != 1 {
4045            return Err(Error::Msg(format!(
4046                "vulkan_dispatch::flip::flip: expected 1 input + 1 output, got {} + {}",
4047                inputs.len(),
4048                outputs.len(),
4049            ))
4050            .bt());
4051        }
4052        let axis = match params {
4053            OpParams::Flip { axis, .. } => *axis,
4054            other => {
4055                return Err(Error::Msg(format!(
4056                    "vulkan_dispatch::flip::flip: expected OpParams::Flip, got {:?}",
4057                    other,
4058                ))
4059                .bt());
4060            }
4061        };
4062        let layout = layouts.first().ok_or_else(|| {
4063            Error::Msg(
4064                "vulkan_dispatch::flip::flip: Flip requires an input layout (layouts[0])"
4065                    .to_string(),
4066            )
4067            .bt()
4068        })?;
4069        let in_guard = read_storage(&inputs[0])?;
4070        let mut out_guard = write_storage(&outputs[0])?;
4071        let byte_width = byte_width_for_dtype("flip", in_guard.dtype)?;
4072        let a = vulkan_input(&in_guard)?;
4073        let backend = a.backend().ok_or_else(|| {
4074            Error::Msg(
4075                "vulkan_dispatch::flip::flip: input has no VulkanBackend handle.".to_string(),
4076            )
4077            .bt()
4078        })?;
4079        let out = vulkan_output(&mut out_guard)?;
4080        backend.flip_bytes(byte_width, a, out, layout, axis)
4081    }
4082}
4083
4084/// Vulkan dispatch wrappers for roll along an axis.
4085pub mod roll {
4086    use super::*;
4087
4088    /// `roll` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
4089    pub fn roll(
4090        inputs: &[Arc<RwLock<Storage>>],
4091        outputs: &mut [Arc<RwLock<Storage>>],
4092        layouts: &[Layout],
4093        params: &OpParams,
4094    ) -> Result<()> {
4095        if inputs.len() != 1 || outputs.len() != 1 {
4096            return Err(Error::Msg(format!(
4097                "vulkan_dispatch::roll::roll: expected 1 input + 1 output, got {} + {}",
4098                inputs.len(),
4099                outputs.len(),
4100            ))
4101            .bt());
4102        }
4103        let (shift, axis) = match params {
4104            OpParams::Roll { shift, axis, .. } => (*shift, *axis),
4105            other => {
4106                return Err(Error::Msg(format!(
4107                    "vulkan_dispatch::roll::roll: expected OpParams::Roll, got {:?}",
4108                    other,
4109                ))
4110                .bt());
4111            }
4112        };
4113        let layout = layouts.first().ok_or_else(|| {
4114            Error::Msg(
4115                "vulkan_dispatch::roll::roll: Roll requires an input layout (layouts[0])"
4116                    .to_string(),
4117            )
4118            .bt()
4119        })?;
4120        let in_guard = read_storage(&inputs[0])?;
4121        let mut out_guard = write_storage(&outputs[0])?;
4122        let byte_width = byte_width_for_dtype("roll", in_guard.dtype)?;
4123        let a = vulkan_input(&in_guard)?;
4124        let backend = a.backend().ok_or_else(|| {
4125            Error::Msg(
4126                "vulkan_dispatch::roll::roll: input has no VulkanBackend handle.".to_string(),
4127            )
4128            .bt()
4129        })?;
4130        let out = vulkan_output(&mut out_guard)?;
4131        backend.roll_bytes(byte_width, a, out, layout, axis, shift)
4132    }
4133}
4134
4135/// Vulkan dispatch wrappers for cumulative sum, per dtype.
4136pub mod cumsum {
4137    use super::*;
4138
4139    macro_rules! vk_cumsum_wrapper {
4140        ($name:ident, $backend_fn:ident, $dt:expr, $op_label:expr) => {
4141            pub fn $name(
4142                inputs: &[Arc<RwLock<Storage>>],
4143                outputs: &mut [Arc<RwLock<Storage>>],
4144                layouts: &[Layout],
4145                params: &OpParams,
4146            ) -> Result<()> {
4147                if inputs.len() != 1 || outputs.len() != 1 {
4148                    return Err(Error::Msg(format!(
4149                        "vulkan_dispatch::cumsum::{}: expected 1 input + 1 output, got {} + {}",
4150                        $op_label,
4151                        inputs.len(),
4152                        outputs.len(),
4153                    ))
4154                    .bt());
4155                }
4156                let axis = match params {
4157                    OpParams::CumSum { axis, .. } => *axis,
4158                    other => {
4159                        return Err(Error::Msg(format!(
4160                            "vulkan_dispatch::cumsum::{}: expected OpParams::CumSum, got {:?}",
4161                            $op_label, other,
4162                        ))
4163                        .bt());
4164                    }
4165                };
4166                let layout = layouts.first().ok_or_else(|| {
4167                    Error::Msg(format!(
4168                        "vulkan_dispatch::cumsum::{}: CumSum requires an input layout (layouts[0])",
4169                        $op_label,
4170                    ))
4171                    .bt()
4172                })?;
4173                let in_guard = read_storage(&inputs[0])?;
4174                let mut out_guard = write_storage(&outputs[0])?;
4175                if in_guard.dtype != $dt {
4176                    return Err(Error::Msg(format!(
4177                        "vulkan_dispatch::cumsum::{}: dtype mismatch (got {:?}, expected {:?})",
4178                        $op_label, in_guard.dtype, $dt,
4179                    ))
4180                    .bt());
4181                }
4182                let a = vulkan_input(&in_guard)?;
4183                let backend = a.backend().ok_or_else(|| {
4184                    Error::Msg(format!(
4185                        "vulkan_dispatch::cumsum::{}: input has no VulkanBackend handle.",
4186                        $op_label,
4187                    ))
4188                    .bt()
4189                })?;
4190                let out = vulkan_output(&mut out_guard)?;
4191                backend.$backend_fn(a, out, layout, axis)
4192            }
4193        };
4194    }
4195
4196    vk_cumsum_wrapper!(cumsum_f32, cumsum_f32_bytes, DType::F32, "cumsum_f32");
4197    vk_cumsum_wrapper!(cumsum_f64, cumsum_f64_bytes, DType::F64, "cumsum_f64");
4198    vk_cumsum_wrapper!(cumsum_f16, cumsum_f16_bytes, DType::F16, "cumsum_f16");
4199    vk_cumsum_wrapper!(cumsum_bf16, cumsum_bf16_bytes, DType::BF16, "cumsum_bf16");
4200}
4201
4202// ===========================================================================
4203// QMatMul Q4_0 / Q4_K_M / Q8_0 — F32 activation × quant weight → F32 output.
4204// ===========================================================================
4205//
4206// The quantization type is carried in `OpParams::QMatMul.quant_type`; the
4207// wrapper switches per family to the right Vulkan kernel:
4208//   - Q4_0  → fused qmatvec_q4_0 (M=1) or matmul_q4_0_tiled (M>1).
4209//   - Q4_K_M → dequantize_q4_km to f32 scratch, then matmul_f32_bytes.
4210//   - Q8_0   → fused qmatvec_q8_0 (M=1); dequantize_q8_0 to f32 scratch, then matmul_f32_bytes (M>1).
4211//   - Q6_K   → fused qmatvec_q6_k for every row (no tiled or dequant kernel yet).
4212// Other QuantTypes (Q4_1, Q5_*, Q2K/Q3K/Q5K, Q8_1) have no Vulkan kernel —
4213// the wrapper returns an error so the route picker falls back to CPU.
4214
4215/// Vulkan dispatch wrappers for quantized matmul (only the quant types with a Vulkan kernel; others return an error so the route picker falls back to CPU).
4216pub mod qmatmul {
4217    use super::*;
4218    use fuel_graph::QuantType;
4219
4220    /// Whether [`qmatmul_vk`] has a kernel for `quant_type`. The ONE list of wired types: `qmatmul_vk`
4221    /// refuses every other type before its match, and `fuel-tensor`'s `WeightStorage::from_ggml_bytes`
4222    /// (feature `vulkan`) keeps a GGUF weight quantized only when this returns true, so the two cannot
4223    /// drift apart. Add a type here in the same change that adds its arm to `qmatmul_vk`.
4224    pub const fn qmatmul_wired(quant_type: QuantType) -> bool {
4225        matches!(
4226            quant_type,
4227            QuantType::Q4_0
4228                | QuantType::Q4_K_M
4229                | QuantType::Q8_0
4230                | QuantType::Q6K
4231                | QuantType::Q5K
4232                | QuantType::Q3K
4233                | QuantType::Iq4Nl
4234                | QuantType::Iq4Xs
4235                | QuantType::Iq3S
4236        )
4237    }
4238
4239    /// `qmatmul_vk` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
4240    pub fn qmatmul_vk(
4241        inputs: &[Arc<RwLock<Storage>>],
4242        outputs: &mut [Arc<RwLock<Storage>>],
4243        _layouts: &[Layout],
4244        params: &OpParams,
4245    ) -> Result<()> {
4246        if inputs.len() != 2 || outputs.len() != 1 {
4247            return Err(Error::Msg(format!(
4248                "vulkan_dispatch::qmatmul: expected 2 inputs + 1 output, got {} + {}",
4249                inputs.len(),
4250                outputs.len(),
4251            ))
4252            .bt());
4253        }
4254        let (quant_type, batch_count, m, n, k) = match params {
4255            OpParams::QMatMul {
4256                quant_type,
4257                batch_count,
4258                m,
4259                n,
4260                k,
4261            } => (*quant_type, *batch_count, *m, *n, *k),
4262            other => {
4263                return Err(Error::Msg(format!(
4264                    "vulkan_dispatch::qmatmul: expected OpParams::QMatMul, got {:?}",
4265                    other,
4266                ))
4267                .bt());
4268            }
4269        };
4270        if !qmatmul_wired(quant_type) {
4271            return Err(Error::Msg(format!(
4272                "vulkan_dispatch::qmatmul: QuantType {quant_type:?} not wired on Vulkan;                  add a dequant-then-matmul path or a fused kernel and retry"
4273            ))
4274            .bt());
4275        }
4276        let a_guard = read_storage(&inputs[0])?;
4277        let w_guard = read_storage(&inputs[1])?;
4278        let mut out_guard = write_storage(&outputs[0])?;
4279        let a = vulkan_input(&a_guard)?;
4280        let w = vulkan_input(&w_guard)?;
4281        let backend = a.backend().ok_or_else(|| {
4282            Error::Msg("vulkan_dispatch::qmatmul: input has no VulkanBackend handle.".to_string())
4283                .bt()
4284        })?;
4285        let out = vulkan_output(&mut out_guard)?;
4286        match quant_type {
4287            QuantType::Q4_0 => backend.matmul_q4_0_bytes(a, w, out, batch_count, m, k, n),
4288            QuantType::Q4_K_M => backend.matmul_q4_km_bytes(a, w, out, batch_count, m, k, n),
4289            QuantType::Q8_0 => backend.matmul_q8_0_bytes(a, w, out, batch_count, m, k, n),
4290            QuantType::Q6K => backend.matmul_q6_k_bytes(a, w, out, batch_count, m, k, n),
4291            QuantType::Q5K => backend.matmul_q5_k_bytes(a, w, out, batch_count, m, k, n),
4292            QuantType::Q3K => backend.matmul_q3_k_bytes(a, w, out, batch_count, m, k, n),
4293            QuantType::Iq4Nl => backend.matmul_iq4_nl_bytes(a, w, out, batch_count, m, k, n),
4294            QuantType::Iq4Xs => backend.matmul_iq4_xs_bytes(a, w, out, batch_count, m, k, n),
4295            QuantType::Iq3S => backend.matmul_iq3_s_bytes(a, w, out, batch_count, m, k, n),
4296            other => Err(Error::Msg(format!(
4297                "vulkan_dispatch::qmatmul: QuantType {other:?} not wired on Vulkan; \
4298                 add a dequant-then-matmul path or a fused kernel and retry"
4299            ))
4300            .bt()),
4301        }
4302    }
4303}
4304
4305// ===========================================================================
4306// Conv2D f32 — im2col + matmul, groups=1.
4307// ===========================================================================
4308
4309/// Vulkan dispatch wrappers for FlashAttention-shape attention forward and backward.
4310pub mod flash_attn {
4311    use super::*;
4312
4313    /// FlashAttention-shape multi-head attention forward, f32 only.
4314    /// Naive single-pass kernel (NOT tiled). Supports GQA, causal,
4315    /// scale, alibi; falls through to other backends on window_left /
4316    /// window_right / softcap.
4317    pub fn flash_attn_f32(
4318        inputs: &[Arc<RwLock<Storage>>],
4319        outputs: &mut [Arc<RwLock<Storage>>],
4320        _layouts: &[Layout],
4321        params: &OpParams,
4322    ) -> Result<()> {
4323        if inputs.len() < 3 || inputs.len() > 4 || outputs.len() != 1 {
4324            return Err(Error::Msg(format!(
4325                "vulkan_dispatch::flash_attn::flash_attn_f32: expected 3-4 inputs (q, k, v, [alibi]) + 1 output, got {} + {}",
4326                inputs.len(), outputs.len(),
4327            )).bt());
4328        }
4329        let (b, hq, hkv, sq, sk, d, scale, causal, wl, wr, softcap) = match params {
4330            OpParams::FlashAttn {
4331                b,
4332                hq,
4333                hkv,
4334                sq,
4335                sk,
4336                d,
4337                k_len,
4338                softmax_scale,
4339                causal,
4340                window_size_left,
4341                window_size_right,
4342                softcap,
4343            } => {
4344                // Vulkan flash v1 reads the full K extent; a runtime
4345                // k_len (capacity-K, Phase D) isn't supported here. The
4346                // route picker keeps decode's capacity-K flash on CUDA.
4347                if *k_len != *sk {
4348                    return Err(Error::Msg(format!(
4349                        "vulkan_dispatch::flash_attn: runtime k_len ({}) != K capacity ({}) \
4350                         not supported on Vulkan v1; route picker should fall back to CPU/CUDA",
4351                        *k_len, *sk,
4352                    ))
4353                    .bt());
4354                }
4355                (
4356                    *b,
4357                    *hq,
4358                    *hkv,
4359                    *sq,
4360                    *sk,
4361                    *d,
4362                    *softmax_scale,
4363                    *causal,
4364                    *window_size_left,
4365                    *window_size_right,
4366                    *softcap,
4367                )
4368            }
4369            other => {
4370                return Err(Error::Msg(format!(
4371                    "vulkan_dispatch::flash_attn::flash_attn_f32: expected OpParams::FlashAttn, got {other:?}",
4372                )).bt());
4373            }
4374        };
4375        if wl.is_some() || wr.is_some() || softcap.is_some() {
4376            return Err(Error::Msg(format!(
4377                "vulkan_dispatch::flash_attn::flash_attn_f32: window_left={wl:?}, window_right={wr:?}, softcap={softcap:?} \
4378                 not supported on Vulkan v1; route picker should fall back to CPU/CUDA",
4379            )).bt());
4380        }
4381
4382        let q_guard = read_storage(&inputs[0])?;
4383        let k_guard = read_storage(&inputs[1])?;
4384        let v_guard = read_storage(&inputs[2])?;
4385        let alibi_guard = match inputs.get(3) {
4386            Some(arc) => Some(read_storage(arc)?),
4387            None => None,
4388        };
4389        let mut out_guard = write_storage(&outputs[0])?;
4390        let q = vulkan_input(&q_guard)?;
4391        let k = vulkan_input(&k_guard)?;
4392        let v = vulkan_input(&v_guard)?;
4393        let alibi = match &alibi_guard {
4394            Some(g) => Some(vulkan_input(g)?),
4395            None => None,
4396        };
4397        let backend = q.backend().ok_or_else(|| {
4398            Error::Msg(
4399                "vulkan_dispatch::flash_attn::flash_attn_f32: q has no VulkanBackend handle."
4400                    .to_string(),
4401            )
4402            .bt()
4403        })?;
4404        let out = vulkan_output(&mut out_guard)?;
4405        match decode_splits(b, hq, sq, sk) {
4406            Some(splits) => backend.flash_attn_f32_split_bytes(
4407                q, k, v, alibi, out, b, hq, hkv, sq, sk, d, scale, causal, splits,
4408            ),
4409            None => backend
4410                .flash_attn_f32_bytes(q, k, v, alibi, out, b, hq, hkv, sq, sk, d, scale, causal),
4411        }
4412    }
4413
4414    /// FlashAttention forward, bf16. Inputs / outputs / alibi all
4415    /// bf16; math at f32. Same shape contract and constraint set as
4416    /// the f32 variant.
4417    pub fn flash_attn_bf16(
4418        inputs: &[Arc<RwLock<Storage>>],
4419        outputs: &mut [Arc<RwLock<Storage>>],
4420        _layouts: &[Layout],
4421        params: &OpParams,
4422    ) -> Result<()> {
4423        flash_attn_half_typed(
4424            inputs,
4425            outputs,
4426            params,
4427            DType::BF16,
4428            "flash_attn_bf16",
4429            |backend, q, k, v, a, out, b, hq, hkv, sq, sk, d, scale, causal| match decode_splits(
4430                b, hq, sq, sk,
4431            ) {
4432                Some(n) => backend.flash_attn_bf16_split_bytes(
4433                    q, k, v, a, out, b, hq, hkv, sq, sk, d, scale, causal, n,
4434                ),
4435                None => backend
4436                    .flash_attn_bf16_bytes(q, k, v, a, out, b, hq, hkv, sq, sk, d, scale, causal),
4437            },
4438        )
4439    }
4440
4441    /// FlashAttention forward, f16. Inputs / outputs / alibi all f16.
4442    pub fn flash_attn_f16(
4443        inputs: &[Arc<RwLock<Storage>>],
4444        outputs: &mut [Arc<RwLock<Storage>>],
4445        _layouts: &[Layout],
4446        params: &OpParams,
4447    ) -> Result<()> {
4448        flash_attn_half_typed(
4449            inputs,
4450            outputs,
4451            params,
4452            DType::F16,
4453            "flash_attn_f16",
4454            |backend, q, k, v, a, out, b, hq, hkv, sq, sk, d, scale, causal| match decode_splits(
4455                b, hq, sq, sk,
4456            ) {
4457                Some(n) => backend.flash_attn_f16_split_bytes(
4458                    q, k, v, a, out, b, hq, hkv, sq, sk, d, scale, causal, n,
4459                ),
4460                None => backend
4461                    .flash_attn_f16_bytes(q, k, v, a, out, b, hq, hkv, sq, sk, d, scale, causal),
4462            },
4463        )
4464    }
4465
4466    fn flash_attn_half_typed<F>(
4467        inputs: &[Arc<RwLock<Storage>>],
4468        outputs: &mut [Arc<RwLock<Storage>>],
4469        params: &OpParams,
4470        expected_dtype: DType,
4471        debug_name: &'static str,
4472        f: F,
4473    ) -> Result<()>
4474    where
4475        F: FnOnce(
4476            &fuel_vulkan_backend::VulkanBackend,
4477            &fuel_vulkan_backend::VulkanStorageBytes,
4478            &fuel_vulkan_backend::VulkanStorageBytes,
4479            &fuel_vulkan_backend::VulkanStorageBytes,
4480            Option<&fuel_vulkan_backend::VulkanStorageBytes>,
4481            &mut fuel_vulkan_backend::VulkanStorageBytes,
4482            usize,
4483            usize,
4484            usize,
4485            usize,
4486            usize,
4487            usize,
4488            f32,
4489            bool,
4490        ) -> Result<()>,
4491    {
4492        if inputs.len() < 3 || inputs.len() > 4 || outputs.len() != 1 {
4493            return Err(Error::Msg(format!(
4494                "vulkan_dispatch::flash_attn::{debug_name}: expected 3-4 inputs + 1 output, got {} + {}",
4495                inputs.len(), outputs.len(),
4496            )).bt());
4497        }
4498        let (b, hq, hkv, sq, sk, d, scale, causal, wl, wr, softcap) = match params {
4499            OpParams::FlashAttn {
4500                b,
4501                hq,
4502                hkv,
4503                sq,
4504                sk,
4505                d,
4506                k_len,
4507                softmax_scale,
4508                causal,
4509                window_size_left,
4510                window_size_right,
4511                softcap,
4512            } => {
4513                // Vulkan flash v1 reads the full K extent; a runtime
4514                // k_len (capacity-K, Phase D) isn't supported here. The
4515                // route picker keeps decode's capacity-K flash on CUDA.
4516                if *k_len != *sk {
4517                    return Err(Error::Msg(format!(
4518                        "vulkan_dispatch::flash_attn: runtime k_len ({}) != K capacity ({}) \
4519                         not supported on Vulkan v1; route picker should fall back to CPU/CUDA",
4520                        *k_len, *sk,
4521                    ))
4522                    .bt());
4523                }
4524                (
4525                    *b,
4526                    *hq,
4527                    *hkv,
4528                    *sq,
4529                    *sk,
4530                    *d,
4531                    *softmax_scale,
4532                    *causal,
4533                    *window_size_left,
4534                    *window_size_right,
4535                    *softcap,
4536                )
4537            }
4538            other => {
4539                return Err(Error::Msg(format!(
4540                    "vulkan_dispatch::flash_attn::{debug_name}: expected OpParams::FlashAttn, got {other:?}",
4541                )).bt());
4542            }
4543        };
4544        if wl.is_some() || wr.is_some() || softcap.is_some() {
4545            return Err(Error::Msg(format!(
4546                "vulkan_dispatch::flash_attn::{debug_name}: window/softcap not supported on Vulkan v1",
4547            )).bt());
4548        }
4549
4550        let q_guard = read_storage(&inputs[0])?;
4551        let k_guard = read_storage(&inputs[1])?;
4552        let v_guard = read_storage(&inputs[2])?;
4553        let alibi_guard = match inputs.get(3) {
4554            Some(arc) => Some(read_storage(arc)?),
4555            None => None,
4556        };
4557        for (name, dt) in [
4558            ("q", q_guard.dtype),
4559            ("k", k_guard.dtype),
4560            ("v", v_guard.dtype),
4561        ] {
4562            if dt != expected_dtype {
4563                return Err(Error::Msg(format!(
4564                    "vulkan_dispatch::flash_attn::{debug_name}: {name} must be {expected_dtype:?}, got {dt:?}",
4565                )).bt());
4566            }
4567        }
4568        if let Some(g) = &alibi_guard
4569            && g.dtype != expected_dtype
4570        {
4571            return Err(Error::Msg(format!(
4572                "vulkan_dispatch::flash_attn::{debug_name}: alibi must be {expected_dtype:?}, got {:?}", g.dtype,
4573            )).bt());
4574        }
4575        let mut out_guard = write_storage(&outputs[0])?;
4576        let q = vulkan_input(&q_guard)?;
4577        let k = vulkan_input(&k_guard)?;
4578        let v = vulkan_input(&v_guard)?;
4579        let alibi = match &alibi_guard {
4580            Some(g) => Some(vulkan_input(g)?),
4581            None => None,
4582        };
4583        let backend = q.backend().ok_or_else(|| {
4584            Error::Msg(format!(
4585                "vulkan_dispatch::flash_attn::{debug_name}: q has no VulkanBackend handle.",
4586            ))
4587            .bt()
4588        })?;
4589        let out = vulkan_output(&mut out_guard)?;
4590        f(
4591            backend, q, k, v, alibi, out, b, hq, hkv, sq, sk, d, scale, causal,
4592        )
4593    }
4594
4595    /// FlashAttention backward — dQ, f32. Inputs (q, k, v, dO, `[alibi]`);
4596    /// output dQ (same shape as Q). Bails on window/softcap (route
4597    /// picker falls through to CPU).
4598    pub fn flash_attn_backward_q_f32(
4599        inputs: &[Arc<RwLock<Storage>>],
4600        outputs: &mut [Arc<RwLock<Storage>>],
4601        _layouts: &[Layout],
4602        params: &OpParams,
4603    ) -> Result<()> {
4604        flash_attn_backward_f32_typed(
4605            inputs,
4606            outputs,
4607            params,
4608            "flash_attn_backward_q_f32",
4609            |backend, q, k, v, dgrad, a, out, b, hq, hkv, sq, sk, d, scale, causal| {
4610                backend.flash_attn_backward_q_f32_bytes(
4611                    q, k, v, dgrad, a, out, b, hq, hkv, sq, sk, d, scale, causal,
4612                )
4613            },
4614        )
4615    }
4616
4617    /// FlashAttention backward — dK, f32.
4618    pub fn flash_attn_backward_k_f32(
4619        inputs: &[Arc<RwLock<Storage>>],
4620        outputs: &mut [Arc<RwLock<Storage>>],
4621        _layouts: &[Layout],
4622        params: &OpParams,
4623    ) -> Result<()> {
4624        flash_attn_backward_f32_typed(
4625            inputs,
4626            outputs,
4627            params,
4628            "flash_attn_backward_k_f32",
4629            |backend, q, k, v, dgrad, a, out, b, hq, hkv, sq, sk, d, scale, causal| {
4630                backend.flash_attn_backward_k_f32_bytes(
4631                    q, k, v, dgrad, a, out, b, hq, hkv, sq, sk, d, scale, causal,
4632                )
4633            },
4634        )
4635    }
4636
4637    /// FlashAttention backward — dV, f32.
4638    pub fn flash_attn_backward_v_f32(
4639        inputs: &[Arc<RwLock<Storage>>],
4640        outputs: &mut [Arc<RwLock<Storage>>],
4641        _layouts: &[Layout],
4642        params: &OpParams,
4643    ) -> Result<()> {
4644        flash_attn_backward_f32_typed(
4645            inputs,
4646            outputs,
4647            params,
4648            "flash_attn_backward_v_f32",
4649            |backend, q, k, v, dgrad, a, out, b, hq, hkv, sq, sk, d, scale, causal| {
4650                backend.flash_attn_backward_v_f32_bytes(
4651                    q, k, v, dgrad, a, out, b, hq, hkv, sq, sk, d, scale, causal,
4652                )
4653            },
4654        )
4655    }
4656
4657    /// Shared dispatch shim body for the three FA backward variants.
4658    /// Validates input counts (4-5: Q, K, V, dO, optional alibi),
4659    /// extracts shape params, asserts all inputs are F32, then hands
4660    /// off to the per-variant backend method.
4661    fn flash_attn_backward_f32_typed<F>(
4662        inputs: &[Arc<RwLock<Storage>>],
4663        outputs: &mut [Arc<RwLock<Storage>>],
4664        params: &OpParams,
4665        debug_name: &'static str,
4666        f: F,
4667    ) -> Result<()>
4668    where
4669        F: FnOnce(
4670            &fuel_vulkan_backend::VulkanBackend,
4671            &fuel_vulkan_backend::VulkanStorageBytes,
4672            &fuel_vulkan_backend::VulkanStorageBytes,
4673            &fuel_vulkan_backend::VulkanStorageBytes,
4674            &fuel_vulkan_backend::VulkanStorageBytes,
4675            Option<&fuel_vulkan_backend::VulkanStorageBytes>,
4676            &mut fuel_vulkan_backend::VulkanStorageBytes,
4677            usize,
4678            usize,
4679            usize,
4680            usize,
4681            usize,
4682            usize,
4683            f32,
4684            bool,
4685        ) -> Result<()>,
4686    {
4687        if inputs.len() < 4 || inputs.len() > 5 || outputs.len() != 1 {
4688            return Err(Error::Msg(format!(
4689                "vulkan_dispatch::flash_attn::{debug_name}: expected 4-5 inputs (q, k, v, do, [alibi]) + 1 output, got {} + {}",
4690                inputs.len(), outputs.len(),
4691            )).bt());
4692        }
4693        let (b, hq, hkv, sq, sk, d, scale, causal, wl, wr, softcap) = match params {
4694            OpParams::FlashAttn {
4695                b,
4696                hq,
4697                hkv,
4698                sq,
4699                sk,
4700                d,
4701                k_len,
4702                softmax_scale,
4703                causal,
4704                window_size_left,
4705                window_size_right,
4706                softcap,
4707            } => {
4708                // Vulkan flash v1 reads the full K extent; a runtime
4709                // k_len (capacity-K, Phase D) isn't supported here. The
4710                // route picker keeps decode's capacity-K flash on CUDA.
4711                if *k_len != *sk {
4712                    return Err(Error::Msg(format!(
4713                        "vulkan_dispatch::flash_attn: runtime k_len ({}) != K capacity ({}) \
4714                         not supported on Vulkan v1; route picker should fall back to CPU/CUDA",
4715                        *k_len, *sk,
4716                    ))
4717                    .bt());
4718                }
4719                (
4720                    *b,
4721                    *hq,
4722                    *hkv,
4723                    *sq,
4724                    *sk,
4725                    *d,
4726                    *softmax_scale,
4727                    *causal,
4728                    *window_size_left,
4729                    *window_size_right,
4730                    *softcap,
4731                )
4732            }
4733            other => {
4734                return Err(Error::Msg(format!(
4735                    "vulkan_dispatch::flash_attn::{debug_name}: expected OpParams::FlashAttn, got {other:?}",
4736                )).bt());
4737            }
4738        };
4739        if wl.is_some() || wr.is_some() || softcap.is_some() {
4740            return Err(Error::Msg(format!(
4741                "vulkan_dispatch::flash_attn::{debug_name}: window/softcap not supported on Vulkan v1",
4742            )).bt());
4743        }
4744
4745        let q_guard = read_storage(&inputs[0])?;
4746        let k_guard = read_storage(&inputs[1])?;
4747        let v_guard = read_storage(&inputs[2])?;
4748        let do_guard = read_storage(&inputs[3])?;
4749        let alibi_guard = match inputs.get(4) {
4750            Some(arc) => Some(read_storage(arc)?),
4751            None => None,
4752        };
4753        for (name, dt) in [
4754            ("q", q_guard.dtype),
4755            ("k", k_guard.dtype),
4756            ("v", v_guard.dtype),
4757            ("do", do_guard.dtype),
4758        ] {
4759            if dt != DType::F32 {
4760                return Err(Error::Msg(format!(
4761                    "vulkan_dispatch::flash_attn::{debug_name}: {name} must be F32, got {dt:?}",
4762                ))
4763                .bt());
4764            }
4765        }
4766        if let Some(g) = &alibi_guard
4767            && g.dtype != DType::F32
4768        {
4769            return Err(Error::Msg(format!(
4770                "vulkan_dispatch::flash_attn::{debug_name}: alibi must be F32, got {:?}",
4771                g.dtype,
4772            ))
4773            .bt());
4774        }
4775        let mut out_guard = write_storage(&outputs[0])?;
4776        let q = vulkan_input(&q_guard)?;
4777        let k = vulkan_input(&k_guard)?;
4778        let v = vulkan_input(&v_guard)?;
4779        let do_storage = vulkan_input(&do_guard)?;
4780        let alibi = match &alibi_guard {
4781            Some(g) => Some(vulkan_input(g)?),
4782            None => None,
4783        };
4784        let backend = q.backend().ok_or_else(|| {
4785            Error::Msg(format!(
4786                "vulkan_dispatch::flash_attn::{debug_name}: q has no VulkanBackend handle.",
4787            ))
4788            .bt()
4789        })?;
4790        let out = vulkan_output(&mut out_guard)?;
4791        f(
4792            backend, q, k, v, do_storage, alibi, out, b, hq, hkv, sq, sk, d, scale, causal,
4793        )
4794    }
4795}
4796
4797/// Vulkan dispatch wrappers for 2-D convolution, per dtype.
4798pub mod conv2d {
4799    use super::*;
4800
4801    /// `conv2d_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
4802    pub fn conv2d_f32(
4803        inputs: &[Arc<RwLock<Storage>>],
4804        outputs: &mut [Arc<RwLock<Storage>>],
4805        _layouts: &[Layout],
4806        params: &OpParams,
4807    ) -> Result<()> {
4808        if inputs.len() < 2 || inputs.len() > 3 || outputs.len() != 1 {
4809            return Err(Error::Msg(format!(
4810                "vulkan_dispatch::conv2d::conv2d_f32: expected 2-3 inputs + 1 output, got {} + {}",
4811                inputs.len(),
4812                outputs.len(),
4813            ))
4814            .bt());
4815        }
4816        if inputs.len() == 3 {
4817            // Vulkan conv2d doesn't fuse bias yet; route picker should
4818            // pick a different alternative (CPU/CUDA fused). Bail loudly
4819            // rather than silently producing wrong output.
4820            return Err(Error::Msg(
4821                "vulkan_dispatch::conv2d::conv2d_f32: bias-fused conv2d not supported \
4822                 on Vulkan yet; bias is a follow-up. Route picker should choose a \
4823                 fused-conv alternative (CPU/CUDA) when bias is present."
4824                    .to_string(),
4825            )
4826            .bt());
4827        }
4828        let (x_shape, w_shape, stride, padding, dilation, groups) = match params {
4829            OpParams::Conv2D {
4830                x_shape,
4831                w_shape,
4832                out_shape: _,
4833                stride,
4834                padding,
4835                dilation,
4836                groups,
4837            } => (*x_shape, *w_shape, *stride, *padding, *dilation, *groups),
4838            other => {
4839                return Err(Error::Msg(format!(
4840                    "vulkan_dispatch::conv2d::conv2d_f32: expected OpParams::Conv2D, got {:?}",
4841                    other,
4842                ))
4843                .bt());
4844            }
4845        };
4846        if dilation != (1, 1) {
4847            return Err(Error::Msg(format!(
4848                "vulkan_dispatch::conv2d::conv2d_f32: dilation {dilation:?} != (1,1) \
4849                 not yet supported on Vulkan; route picker should fall back to CPU/CUDA"
4850            ))
4851            .bt());
4852        }
4853        let in_guard = read_storage(&inputs[0])?;
4854        let w_guard = read_storage(&inputs[1])?;
4855        let mut out_guard = write_storage(&outputs[0])?;
4856        let input = vulkan_input(&in_guard)?;
4857        let weight = vulkan_input(&w_guard)?;
4858        let backend = input.backend().ok_or_else(|| {
4859            Error::Msg(
4860                "vulkan_dispatch::conv2d::conv2d_f32: input has no VulkanBackend handle."
4861                    .to_string(),
4862            )
4863            .bt()
4864        })?;
4865        let out = vulkan_output(&mut out_guard)?;
4866        backend.conv2d_f32_bytes(
4867            input, weight, out, x_shape, w_shape, stride, padding, groups,
4868        )
4869    }
4870
4871    /// Conv2D bf16 via im2col_bf16 + cooperative-matrix bf16 matmul.
4872    /// Same shape contract as the f32 path; activations + weights +
4873    /// output all bf16. COOP-ONLY shape constraints: c_out % 16 == 0
4874    /// AND (h_out * w_out) % 16 == 0. Bails on small shapes — route
4875    /// picker should fall through to f32 conv2d via Cast.
4876    pub fn conv2d_bf16(
4877        inputs: &[Arc<RwLock<Storage>>],
4878        outputs: &mut [Arc<RwLock<Storage>>],
4879        _layouts: &[Layout],
4880        params: &OpParams,
4881    ) -> Result<()> {
4882        if inputs.len() < 2 || inputs.len() > 3 || outputs.len() != 1 {
4883            return Err(Error::Msg(format!(
4884                "vulkan_dispatch::conv2d::conv2d_bf16: expected 2-3 inputs + 1 output, got {} + {}",
4885                inputs.len(),
4886                outputs.len(),
4887            ))
4888            .bt());
4889        }
4890        if inputs.len() == 3 {
4891            return Err(Error::Msg(
4892                "vulkan_dispatch::conv2d::conv2d_bf16: bias-fused conv2d not supported \
4893                 on Vulkan yet; route picker should pick a fused-conv alternative when \
4894                 bias is present."
4895                    .to_string(),
4896            )
4897            .bt());
4898        }
4899        let (x_shape, w_shape, stride, padding, dilation, groups) = match params {
4900            OpParams::Conv2D {
4901                x_shape,
4902                w_shape,
4903                out_shape: _,
4904                stride,
4905                padding,
4906                dilation,
4907                groups,
4908            } => (*x_shape, *w_shape, *stride, *padding, *dilation, *groups),
4909            other => {
4910                return Err(Error::Msg(format!(
4911                    "vulkan_dispatch::conv2d::conv2d_bf16: expected OpParams::Conv2D, got {other:?}",
4912                )).bt());
4913            }
4914        };
4915        if dilation != (1, 1) {
4916            return Err(Error::Msg(format!(
4917                "vulkan_dispatch::conv2d::conv2d_bf16: dilation {dilation:?} != (1,1) \
4918                 not yet supported on Vulkan; route picker should fall back to CPU/CUDA",
4919            ))
4920            .bt());
4921        }
4922        let in_guard = read_storage(&inputs[0])?;
4923        let w_guard = read_storage(&inputs[1])?;
4924        let mut out_guard = write_storage(&outputs[0])?;
4925        let input = vulkan_input(&in_guard)?;
4926        let weight = vulkan_input(&w_guard)?;
4927        let backend = input.backend().ok_or_else(|| {
4928            Error::Msg(
4929                "vulkan_dispatch::conv2d::conv2d_bf16: input has no VulkanBackend handle."
4930                    .to_string(),
4931            )
4932            .bt()
4933        })?;
4934        let out = vulkan_output(&mut out_guard)?;
4935        backend.conv2d_bf16_bytes(
4936            input, weight, out, x_shape, w_shape, stride, padding, groups,
4937        )
4938    }
4939
4940    /// Conv2D f16 — sibling of `conv2d_bf16`. Reuses the bf16 im2col
4941    /// shader (2-byte shuffle is dtype-opaque) + matmul_coop_f16_f16_f16.
4942    pub fn conv2d_f16(
4943        inputs: &[Arc<RwLock<Storage>>],
4944        outputs: &mut [Arc<RwLock<Storage>>],
4945        _layouts: &[Layout],
4946        params: &OpParams,
4947    ) -> Result<()> {
4948        if inputs.len() < 2 || inputs.len() > 3 || outputs.len() != 1 {
4949            return Err(Error::Msg(format!(
4950                "vulkan_dispatch::conv2d::conv2d_f16: expected 2-3 inputs + 1 output, got {} + {}",
4951                inputs.len(),
4952                outputs.len(),
4953            ))
4954            .bt());
4955        }
4956        if inputs.len() == 3 {
4957            return Err(Error::Msg(
4958                "vulkan_dispatch::conv2d::conv2d_f16: bias-fused conv2d not supported \
4959                 on Vulkan yet"
4960                    .to_string(),
4961            )
4962            .bt());
4963        }
4964        let (x_shape, w_shape, stride, padding, dilation, groups) = match params {
4965            OpParams::Conv2D {
4966                x_shape,
4967                w_shape,
4968                out_shape: _,
4969                stride,
4970                padding,
4971                dilation,
4972                groups,
4973            } => (*x_shape, *w_shape, *stride, *padding, *dilation, *groups),
4974            other => {
4975                return Err(Error::Msg(format!(
4976                    "vulkan_dispatch::conv2d::conv2d_f16: expected OpParams::Conv2D, got {other:?}",
4977                ))
4978                .bt());
4979            }
4980        };
4981        if dilation != (1, 1) {
4982            return Err(Error::Msg(format!(
4983                "vulkan_dispatch::conv2d::conv2d_f16: dilation {dilation:?} != (1,1) \
4984                 not yet supported on Vulkan",
4985            ))
4986            .bt());
4987        }
4988        let in_guard = read_storage(&inputs[0])?;
4989        let w_guard = read_storage(&inputs[1])?;
4990        let mut out_guard = write_storage(&outputs[0])?;
4991        let input = vulkan_input(&in_guard)?;
4992        let weight = vulkan_input(&w_guard)?;
4993        let backend = input.backend().ok_or_else(|| {
4994            Error::Msg(
4995                "vulkan_dispatch::conv2d::conv2d_f16: input has no VulkanBackend handle."
4996                    .to_string(),
4997            )
4998            .bt()
4999        })?;
5000        let out = vulkan_output(&mut out_guard)?;
5001        backend.conv2d_f16_bytes(
5002            input, weight, out, x_shape, w_shape, stride, padding, groups,
5003        )
5004    }
5005}
5006
5007// ===========================================================================
5008// Cast F8E4M3 ↔ {F32, F16, BF16} — single wrapper dispatches by dtype pair
5009// ===========================================================================
5010
5011/// Vulkan dispatch wrappers for casts between F8E4M3 and F32 / F16 / BF16.
5012pub mod cast_f8e4m3 {
5013    use super::*;
5014
5015    /// `cast_f8e4m3` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
5016    pub fn cast_f8e4m3(
5017        inputs: &[Arc<RwLock<Storage>>],
5018        outputs: &mut [Arc<RwLock<Storage>>],
5019        _layouts: &[Layout],
5020        _params: &OpParams,
5021    ) -> Result<()> {
5022        if inputs.len() != 1 || outputs.len() != 1 {
5023            return Err(Error::Msg(format!(
5024                "vulkan_dispatch::cast_f8e4m3: expected 1 input + 1 output, got {} + {}",
5025                inputs.len(),
5026                outputs.len(),
5027            ))
5028            .bt());
5029        }
5030        let in_guard = read_storage(&inputs[0])?;
5031        let mut out_guard = write_storage(&outputs[0])?;
5032        let src_dtype = in_guard.dtype;
5033        let dst_dtype = out_guard.dtype;
5034        let src_elem = match src_dtype {
5035            DType::F32 => 4,
5036            DType::F16 => 2,
5037            DType::BF16 => 2,
5038            DType::F8E4M3 => 1,
5039            other => {
5040                return Err(Error::Msg(format!(
5041                    "vulkan_dispatch::cast_f8e4m3: unsupported src dtype {other:?}",
5042                ))
5043                .bt());
5044            }
5045        };
5046        let a = vulkan_input(&in_guard)?;
5047        let n_bytes = a.len_bytes();
5048        if n_bytes % src_elem != 0 {
5049            return Err(Error::Msg(format!(
5050                "vulkan_dispatch::cast_f8e4m3: input bytes {n_bytes} not a multiple of \
5051                 src elem size {src_elem} ({src_dtype:?})",
5052            ))
5053            .bt());
5054        }
5055        let n = n_bytes / src_elem;
5056        let backend = a.backend().ok_or_else(|| {
5057            Error::Msg(
5058                "vulkan_dispatch::cast_f8e4m3: input has no VulkanBackend handle.".to_string(),
5059            )
5060            .bt()
5061        })?;
5062        let out = vulkan_output(&mut out_guard)?;
5063        backend.cast_f8e4m3_bytes(src_dtype, dst_dtype, a, out, n)
5064    }
5065}
5066
5067// ===========================================================================
5068// Op::Copy D2H — Vulkan → CPU (bridge-retirement Phase 2, post-9c)
5069// ===========================================================================
5070
5071/// Dispatch wrapper for `(OpKind::Copy, [T, T], Vulkan)` — D2H from a
5072/// Vulkan source storage into a freshly-allocated CPU output. The
5073/// executor allocates the CPU output before this wrapper runs
5074/// (see `fuel_dispatch::pipelined::WorkItemKind::Copy`); the wrapper calls
5075/// `VulkanBackend::download_bytes` on the input's attached backend
5076/// handle and copies the result into the CPU storage.
5077///
5078/// Dtype-agnostic at the byte level — one wrapper covers every dtype
5079/// registered at this key.
5080///
5081/// Replaces the Vulkan branch of `BackendStorage::read_to_cpu_bytes`
5082/// (deleted alongside) — the placeholder that
5083/// [commit 7a95001a](https://github.com/anthropics/fuel/commit/7a95001a)
5084/// introduced. After this lands, D2H is a graph node the optimizer
5085/// can see (identity check #1: "more decisions visible to the
5086/// DAG-level optimizer").
5087pub fn copy_to_cpu_vulkan(
5088    inputs: &[Arc<RwLock<Storage>>],
5089    outputs: &mut [Arc<RwLock<Storage>>],
5090    _layouts: &[Layout],
5091    _params: &OpParams,
5092) -> Result<()> {
5093    if inputs.len() != 1 || outputs.len() != 1 {
5094        return Err(Error::Msg(format!(
5095            "copy_to_cpu_vulkan: expected 1 input + 1 output, got {} + {}",
5096            inputs.len(),
5097            outputs.len(),
5098        ))
5099        .bt());
5100    }
5101    let in_guard = read_storage(&inputs[0])?;
5102    // The key is the SOURCE backend: keep the typed error for a non-Vulkan input.
5103    vulkan_input(&in_guard)?;
5104    let mut out_guard = write_storage(&outputs[0])?;
5105    // CPU output: download; Vulkan output: one vkCmdCopyBuffer into a fresh buffer. Both, and the
5106    // error for a Vulkan source with no backend handle, live in `BackendStorage::copy_from`
5107    // (ROADMAP row 137, seam S3 step 2).
5108    out_guard.inner.copy_from(&in_guard.inner)
5109}
5110
5111// ===========================================================================
5112// register_vulkan_kernels — binding-table population
5113// ===========================================================================
5114
5115/// The authored Vulkan cast (dtype-conversion) kernel contract, embedded into
5116/// the binary via `include_str!` (the PRODUCTION contract). Parsed + lowered by
5117/// [`register_vulkan_cast_from_contract`].
5118const VULKAN_CAST_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/cast.fkc.md");
5119
5120/// Register the Vulkan cast family (12 (SRC, DST) pairs → 3 production wrappers:
5121/// `cast::cast_f32_half` for f32↔f16 / f32↔bf16, `cast::cast_f32_f64` for
5122/// f32↔f64, `cast_f8e4m3::cast_f8e4m3` for the six F8E4M3 pairs) by IMPORTING
5123/// its FKC kernel contract — the **first Vulkan-backend FKC consumer**, the GPU
5124/// analogue of the CPU `register_cpu_*_from_contract` family. FKC is
5125/// unconditional core infrastructure, so this is the ONE registration path for
5126/// the family: the hand-written `table.register_with_precision(OpKind::Cast, …)`
5127/// calls (both the half/f64 block and the F8E4M3 block) are DELETED.
5128///
5129/// Each per-pair section declares a single-dtype `src` input + a `fixed(DST)`
5130/// output, so the importer keys `[SRC, DST]` — byte-for-byte the deleted regs
5131/// (the `cast(output)` dtype-rule the sections used to carry was NOT an
5132/// importer-recognized form and would have dropped the output slot from the
5133/// key; it was rewritten to the canonical `fixed(DST)` per section's documented
5134/// destination). Every `entry_point` symbol resolves through the production
5135/// [`crate::link::VulkanLinkRegistry`] to the exact same wrapper fn-pointer.
5136///
5137/// Behavior-preserving vs. the deleted hand-written path on dispatch: identical
5138/// wrappers + contiguous-only caps (`awkward_layout_strategy: requires_contiguous`
5139/// ⇒ `strided_input == false`). The binding's `kernel_source` becomes the
5140/// contract's `"vulkan-slang"` tag and its precision the contract's audited
5141/// claim — the shared `VULKAN_CAST_PRECISION` const the regs used to carry
5142/// (`max_ulp: Some(0)`) is retired; the contract's per-section `max_ulp: ~`
5143/// author seed is what the Judge now audits (both keep
5144/// `bit_stable_on_same_hardware: true`). Cost is preserved because this runs
5145/// BEFORE the `fill_unset_cost_for_backend` pass, which upgrades the imported
5146/// entries' `unknown_cost` sentinel to the same OpKind cost fn every Vulkan
5147/// primitive gets.
5148///
5149/// The family declares NO fused ops, so `register_into`'s required fused
5150/// argument is a local throwaway that provably stays empty. Init-boundary
5151/// fail-fast: a parse/lower/link failure of the embedded, authored contract is
5152/// a programmer error surfaced once here via `expect` (mirroring the CPU
5153/// `register_cpu_*_from_contract` convention); it cannot fail for a runtime-data
5154/// reason.
5155fn register_vulkan_cast_from_contract(table: &mut KernelBindingTable) {
5156    let provider = fuel_dispatch::fkc::import_bundle_str(
5157        VULKAN_CAST_CONTRACT,
5158        &crate::link::VulkanLinkRegistry,
5159    )
5160    .expect(
5161        "authored Vulkan cast contract must import \
5162                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5163    );
5164    debug_assert!(
5165        provider.fused.is_empty(),
5166        "vulkan cast contract declares no fused ops",
5167    );
5168    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5169    provider
5170        .register_into(table, &mut fused)
5171        .expect("Vulkan cast contract must register into the binding table");
5172}
5173
5174/// The authored Vulkan elementwise kernel contract (unary / binary / affine /
5175/// clamp / powi), embedded via `include_str!` (the PRODUCTION contract). Parsed
5176/// + lowered by [`register_vulkan_elementwise_from_contract`].
5177const VULKAN_ELEMENTWISE_CONTRACT: &str =
5178    include_str!("../kernel-contracts/vulkan/elementwise.fkc.md");
5179
5180/// Register the Vulkan elementwise family (94 (op, dtype) bindings) by IMPORTING
5181/// its RE-AUTHORED FKC kernel contract — the SECOND Vulkan-backend FKC consumer
5182/// after the cast family, and the first **caps-through-import** production proof.
5183///
5184/// The contract was re-authored per-op (the CPU inplace precedent): the old
5185/// representative-chassis `unary`/`binary` op_id-selector sections could each
5186/// register only ONE OpKind, so they are SUPERSEDED by 16 per-op unary sections
5187/// (each fanning `[F32, F16, F64]` on a base `entry_point`, §3.4) + 16 bf16-unary
5188/// sections + 6 per-op binary sections (fanning `[F32, F16, F64, BF16]`) + an
5189/// affine strided-fan + affine_bf16 + clamp + powi. Every `entry_point` symbol
5190/// resolves through [`crate::link::VulkanLinkRegistry`] to the exact same
5191/// per-(op, dtype) wrapper the deleted hand-written regs used.
5192///
5193/// **Caps ride through truthfully.** Each section's per-operand five-flag layout
5194/// projects onto `KernelCaps.strided_input` (`caps_map::project_kernel_caps`),
5195/// stamped onto the binding by the importer: the strided unary/binary/affine/
5196/// clamp/powi sections yield `strided_input=true` (byte-for-byte the deleted
5197/// `register_with_caps_and_precision(strided)` regs) and the contiguous-only
5198/// bf16-unary / affine_bf16 sections yield `strided_input=false` (the deleted
5199/// plain `register_with_precision` regs). Precision becomes the contract's author
5200/// seed (`audited: false` ⇒ `PrecisionGuarantee::UNAUDITED`; the Judge audits
5201/// later) — the same posture the cast migration took; the hand-written
5202/// `VULKAN_{FLOAT,HALF,TRANSCENDENTAL}_POINTWISE_PRECISION` consts are retired
5203/// from this seam. Cost is preserved because this runs BEFORE
5204/// `fill_unset_cost_for_backend`, which upgrades the imported `unknown_cost`
5205/// sentinels to the same OpKind cost fn.
5206///
5207/// The contract's `add_assign_scaled` + `unary`/`binary` chassis sections are
5208/// `registrable: false` describe-only (§3.10) and register nothing. Init-boundary
5209/// fail-fast: a parse/lower/link failure of the embedded contract is a programmer
5210/// error surfaced once here via `expect`.
5211fn register_vulkan_elementwise_from_contract(table: &mut KernelBindingTable) {
5212    let provider = fuel_dispatch::fkc::import_bundle_str(
5213        VULKAN_ELEMENTWISE_CONTRACT,
5214        &crate::link::VulkanLinkRegistry,
5215    )
5216    .expect(
5217        "authored Vulkan elementwise contract must import \
5218         (embedded via include_str!, resolved through VulkanLinkRegistry)",
5219    );
5220    debug_assert!(
5221        provider.fused.is_empty(),
5222        "vulkan elementwise contract declares no fused ops",
5223    );
5224    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5225    provider
5226        .register_into(table, &mut fused)
5227        .expect("Vulkan elementwise contract must register into the binding table");
5228}
5229
5230/// The authored Vulkan matmul kernel contract (6 per-combo GEMM/GEMV wrapper
5231/// bindings), embedded via `include_str!` (the PRODUCTION contract). Parsed +
5232/// lowered by [`register_vulkan_matmul_from_contract`].
5233const VULKAN_MATMUL_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/matmul.fkc.md");
5234
5235/// Register the Vulkan matmul family (6 (MatMul, [lhs,rhs,out]) bindings) by
5236/// IMPORTING its RE-AUTHORED FKC kernel contract — the THIRD Vulkan-backend FKC
5237/// consumer after cast + elementwise. FKC is unconditional core infrastructure,
5238/// so this is the ONE registration path for the family: the hand-written
5239/// `table.register_with_precision(OpKind::MatMul, …)` regs (the f32 GEMM +
5240/// the five mixed-precision / tensor-core combos) are DELETED.
5241///
5242/// The contract was re-authored per-combo (the cast family's per-pair
5243/// precedent): the aspirational multi-dtype `dispatch/matmul.fkc.md ::
5244/// matmul_mixed_precision` section (lhs `[F32,BF16,F16]` vs rhs `[BF16,F16]` —
5245/// DIFFERENT lists, a `FanoutDtypeMismatch` the uniform fan-out importer cannot
5246/// key) is SUPERSEDED by six single-dtype-per-operand sections, each declaring a
5247/// specific `entry_point` symbol that resolves through
5248/// [`crate::link::VulkanLinkRegistry`] to the exact production wrapper. Each
5249/// wrapper route-picks its internal Slang kernels (matvec / reg-tile / tiled for
5250/// f32; matvec_bf16_b / matmul_tiled_bf16_b / matmul_coop* + matmul_small_*
5251/// fallbacks for the mixed combos) at dispatch time — that route-pick is NOT a
5252/// binding, so there is exactly ONE `KernelRef` per key.
5253///
5254/// **Caps ride through truthfully.** Each section's `requires_contiguous`
5255/// layout projects `strided_input == false` — byte-for-byte the deleted
5256/// `register_with_precision` regs (the coop / vec4 loads require canonical
5257/// row-major; a strided / transposed / offset operand is auto-Contiguized by the
5258/// planner first). Precision becomes the contract's audited seed
5259/// (nondeterministic, `bit_stable_on_same_hardware: false`, audited `none(reason)`
5260/// — the corrected 2026-06-18 posture, honest about scheduler-dependent
5261/// FADD/subgroup order) rather than the retired hand-written
5262/// `VULKAN_MATMUL_PRECISION` / `VULKAN_MATMUL_TENSORCORE_PRECISION` consts (which
5263/// mis-declared `bit_stable_on_same_hardware: true`). At the matmul migration
5264/// those consts were left in use by the Vulkan conv2d family; conv2d has since
5265/// migrated to its own FKC contract, so they are now dropped from this seam too
5266/// (the `pub const` defs stay in `fused.rs`, mirroring VULKAN_TRANSCENDENTAL).
5267/// Cost is preserved because this runs BEFORE `fill_unset_cost_for_backend`,
5268/// which upgrades the imported `unknown_cost` sentinels to the same OpKind cost fn.
5269///
5270/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5271/// failure of the embedded, authored contract is a programmer error surfaced once
5272/// here via `expect`.
5273fn register_vulkan_matmul_from_contract(table: &mut KernelBindingTable) {
5274    let provider = fuel_dispatch::fkc::import_bundle_str(
5275        VULKAN_MATMUL_CONTRACT,
5276        &crate::link::VulkanLinkRegistry,
5277    )
5278    .expect(
5279        "authored Vulkan matmul contract must import \
5280                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5281    );
5282    debug_assert!(
5283        provider.fused.is_empty(),
5284        "vulkan matmul contract declares no fused ops",
5285    );
5286    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5287    provider
5288        .register_into(table, &mut fused)
5289        .expect("Vulkan matmul contract must register into the binding table");
5290}
5291
5292/// The authored Vulkan conv2d kernel contract (3 per-(op, dtype) Conv2D
5293/// bindings), embedded via `include_str!` (the PRODUCTION contract). Parsed +
5294/// lowered by [`register_vulkan_conv_from_contract`].
5295const VULKAN_CONV_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/conv.fkc.md");
5296
5297/// Register the Vulkan conv2d family (3 `(Conv2D, [x, weight, out])` bindings —
5298/// f32 / bf16 / f16) by IMPORTING its RE-AUTHORED FKC kernel contract — the
5299/// FOURTH Vulkan-backend FKC consumer after cast + elementwise + matmul. FKC is
5300/// unconditional core infrastructure, so this is the ONE registration path for
5301/// the family: the hand-written `table.register_with_precision(OpKind::Conv2D,
5302/// …)` regs (f32 + the bf16 / f16 cooperative-matrix combos) are DELETED.
5303///
5304/// The contract was RE-AUTHORED per-(op, dtype) (the matmul family's per-combo
5305/// precedent): the corpus's `vulkan/conv-attn-rope.fkc.md` describes conv2d as an
5306/// ASPIRATIONAL `fused_op: CONV2D` **im2col STAGE** (`conv2d_im2col_f32` /
5307/// `conv2d_im2col_bf16`, whose output is the intermediate patches matrix, NOT the
5308/// conv output) — that future *fused* decomposition is a SEPARATE concern and does
5309/// NOT register the primitive `OpKind::Conv2D` binding production actually wires,
5310/// whose wrapper (`conv2d::conv2d_f32` → `VulkanBackend::conv2d_*_bytes`) runs the
5311/// WHOLE conv (im2col + GEMM internally). So the migration authors THREE faithful
5312/// single-dtype-per-operand `op_kind: Conv2D` sections in the new production
5313/// `fuel-dispatch/kernel-contracts/vulkan/conv.fkc.md`, each `entry_point` resolving through
5314/// [`crate::link::VulkanLinkRegistry`] to the exact production wrapper.
5315///
5316/// **No bias key.** The Vulkan conv wrappers BAIL on a 3-input (bias) call, so —
5317/// UNLIKE the CPU conv contract's `optional: true` bias that fans a `[T,T,T,T]`
5318/// with-bias key — the sections declare NO bias operand and each keys ONLY the
5319/// 3-slot `[x, weight, out]`, byte-for-byte the deleted hand-written regs.
5320///
5321/// **Caps ride through truthfully.** Each section's `requires_contiguous` layout
5322/// projects `strided_input == false` — byte-for-byte the deleted
5323/// `register_with_precision` regs (conv2d_im2col reads canonical row-major NCHW;
5324/// a strided / transposed / offset operand is auto-Contiguized by the planner
5325/// first). Precision becomes the contract's audited seed (nondeterministic,
5326/// `bit_stable_on_same_hardware: false`, audited `none(reason)` — the corrected,
5327/// honest posture) rather than the retired hand-written `VULKAN_MATMUL_PRECISION`
5328/// / `VULKAN_MATMUL_TENSORCORE_PRECISION` consts (which mis-declared
5329/// `bit_stable_on_same_hardware: true`; conv was their LAST code user, so they are
5330/// dropped from this seam — the matmul migration deferred that retirement to here).
5331/// Cost is preserved because this runs BEFORE `fill_unset_cost_for_backend`, which
5332/// upgrades the imported `unknown_cost` sentinels to the same OpKind cost fn.
5333///
5334/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5335/// failure of the embedded, authored contract is a programmer error surfaced once
5336/// here via `expect`.
5337fn register_vulkan_conv_from_contract(table: &mut KernelBindingTable) {
5338    let provider = fuel_dispatch::fkc::import_bundle_str(
5339        VULKAN_CONV_CONTRACT,
5340        &crate::link::VulkanLinkRegistry,
5341    )
5342    .expect(
5343        "authored Vulkan conv contract must import \
5344                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5345    );
5346    debug_assert!(
5347        provider.fused.is_empty(),
5348        "vulkan conv contract declares no fused ops",
5349    );
5350    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5351    provider
5352        .register_into(table, &mut fused)
5353        .expect("Vulkan conv contract must register into the binding table");
5354}
5355
5356/// The authored Vulkan QMatMul kernel contract (ONE `(QMatMul, [F32, U32, F32])`
5357/// binding), embedded via `include_str!` (the PRODUCTION contract). Parsed +
5358/// lowered by [`register_vulkan_qmatmul_from_contract`].
5359const VULKAN_QMATMUL_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/qmatmul.fkc.md");
5360
5361/// Register the Vulkan QMatMul binding (ONE `(QMatMul, [F32, U32, F32])` key) by
5362/// IMPORTING its RE-AUTHORED FKC kernel contract — the FOURTEENTH Vulkan-backend
5363/// FKC consumer. FKC is unconditional core infrastructure, so this is the ONE
5364/// registration path for the family: the hand-written
5365/// `table.register_with_precision(OpKind::QMatMul, &[F32, U32, F32], …)` reg is
5366/// DELETED.
5367///
5368/// The corpus `vulkan/quantized.fkc.md` models QMATMUL as TWO aspirational
5369/// `fused_op: QMATMUL` Q4_0 sections (`qmatvec_q4_0` gemv + `matmul_q4_0_tiled`
5370/// prefill), which mismatch production on BOTH axes: production registers the
5371/// PRIMITIVE `OpKind::QMatMul` (not the fused op) at a key whose weight slot is the
5372/// LOGICAL `U32` dispatch dtype (not the physical `U8` block stream). So the
5373/// migration authors ONE faithful single-dtype-per-operand `op_kind: QMatMul`
5374/// section in the new production `fuel-dispatch/kernel-contracts/vulkan/qmatmul.fkc.md`
5375/// (the CPU quant-matmul primitive precedent), applying the maintainer-approved
5376/// CPU linear-quant reconciliation:
5377///  - **weight U8 → U32**: `accept.dtypes` carries the LOGICAL dispatch dtype the
5378///    binding key + `BackendImpl.dtypes` actually use (`[F32, U32, F32]`, per the
5379///    DType-logical / SType-physical split in `docs/specs/storage-encoding.md`);
5380///    the `fdx.quant` GGML_BLOCK block keeps the physical byte-honesty
5381///    (`quant_coherence` does not pin the operand base dtype for GGML_BLOCK).
5382///
5383/// and flips the two corpus fused sections to `registrable: false` describe-only
5384/// cross-referencing it (the matmul_mixed_precision precedent).
5385///
5386/// The section's `entry_point` resolves through [`crate::link::VulkanLinkRegistry`]
5387/// to the exact production wrapper `qmatmul::qmatmul_vk`, which route-picks the
5388/// per-format kernels (`qmatvec_q4_0` / `matmul_q4_0_tiled` for Q4_0;
5389/// dequant-then-`matmul_f32` for Q4_K_M / Q8_0) at dispatch time by
5390/// `OpParams::QMatMul.quant_type` — that route-pick is NOT a binding, so there is
5391/// exactly ONE `KernelRef` at the key.
5392///
5393/// **Caps ride through truthfully.** The section's `requires_contiguous` layout
5394/// projects `strided_input == false` — byte-for-byte the deleted
5395/// `register_with_precision` reg (the GGML weight stream has a fixed per-block
5396/// layout; a strided / transposed / offset operand is auto-Contiguized by the
5397/// planner first). Precision becomes the contract's audited seed (nondeterministic,
5398/// `bit_stable_on_same_hardware: false`, audited `none(reason)` — the corrected,
5399/// honest posture: the Q4_0 kernels reduce over K with a scheduler-dependent
5400/// subgroup / tiled reduction, and the Q4_K_M / Q8_0 routes contract through the
5401/// same `matmul_f32` GEMM) rather than the retired hand-written
5402/// `VULKAN_QMATMUL_PRECISION` const (which mis-declared
5403/// `bit_stable_on_same_hardware: true`, the same over-claim the retired
5404/// `VULKAN_MATMUL_PRECISION` made; the `pub const` def stays in `fused.rs`,
5405/// mirroring VULKAN_TRANSCENDENTAL). Cost is preserved because this runs BEFORE
5406/// `fill_unset_cost_for_backend`, which upgrades the imported `unknown_cost`
5407/// sentinel to the same OpKind cost fn.
5408///
5409/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5410/// failure of the embedded, authored contract is a programmer error surfaced once
5411/// here via `expect`.
5412fn register_vulkan_qmatmul_from_contract(table: &mut KernelBindingTable) {
5413    let provider = fuel_dispatch::fkc::import_bundle_str(
5414        VULKAN_QMATMUL_CONTRACT,
5415        &crate::link::VulkanLinkRegistry,
5416    )
5417    .expect(
5418        "authored Vulkan qmatmul contract must import \
5419                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5420    );
5421    debug_assert!(
5422        provider.fused.is_empty(),
5423        "vulkan qmatmul contract declares no fused ops",
5424    );
5425    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5426    provider
5427        .register_into(table, &mut fused)
5428        .expect("Vulkan qmatmul contract must register into the binding table");
5429}
5430
5431/// The authored Vulkan select (IndexSelect / Gather / MaskedFill) kernel
5432/// contract, embedded via `include_str!` (the PRODUCTION contract). Parsed +
5433/// lowered by [`register_vulkan_select_from_contract`].
5434const VULKAN_SELECT_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/select.fkc.md");
5435
5436/// Register the Vulkan select family (16 (op, dtype) bindings — IndexSelect (4),
5437/// Gather (6), MaskedFill (6)) by IMPORTING its FKC kernel contract — the FIFTH
5438/// Vulkan-backend FKC consumer after cast + elementwise + matmul + conv. FKC is
5439/// unconditional core infrastructure, so this is the ONE registration path for
5440/// the family: the hand-written `register_with_precision(OpKind::{IndexSelect,
5441/// Gather, MaskedFill}, …)` regs are DELETED.
5442///
5443/// Each section fans a BASE `entry_point` over its dtype list (§3.4): IndexSelect
5444/// resolves `index_select_<suffix>` to FOUR distinct per-dtype wrappers; Gather /
5445/// MaskedFill resolve every `<base>_<suffix>` to the ONE dtype-agnostic wrapper
5446/// (`gather::gather` / `masked_fill::masked_fill`) that picks its element
5447/// byte-width from the output dtype — a synthetic-base umbrella (the pad_cpu
5448/// precedent). The importer keys `[data, index, out]` (data dtype + fixed index
5449/// dtype U32/U8 + `passthrough(data)` output), byte-for-byte the deleted regs.
5450///
5451/// **Caps ride through truthfully.** Each section's `requires_contiguous` layout
5452/// projects `strided_input == false` — byte-for-byte the deleted plain
5453/// `register_with_precision` regs (byte-level data movers read/write own-shape
5454/// flat buffers; a strided operand is auto-Contiguized first). Precision is the
5455/// contract's audited byte-exact seed (`bit_stable`, `max_ulp: 0`,
5456/// `determinism: bitwise`) — the honest posture for a pure byte copy, byte-for-byte
5457/// the deleted regs' `VULKAN_BYTE_LEVEL_PRECISION`. Cost is preserved because this
5458/// runs BEFORE `fill_unset_cost_for_backend`, which upgrades the imported
5459/// `unknown_cost` sentinels to the same OpKind cost fn.
5460///
5461/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5462/// failure of the embedded, authored contract is a programmer error surfaced once
5463/// here via `expect`.
5464fn register_vulkan_select_from_contract(table: &mut KernelBindingTable) {
5465    let provider = fuel_dispatch::fkc::import_bundle_str(
5466        VULKAN_SELECT_CONTRACT,
5467        &crate::link::VulkanLinkRegistry,
5468    )
5469    .expect(
5470        "authored Vulkan select contract must import \
5471                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5472    );
5473    debug_assert!(
5474        provider.fused.is_empty(),
5475        "vulkan select contract declares no fused ops",
5476    );
5477    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5478    provider
5479        .register_into(table, &mut fused)
5480        .expect("Vulkan select contract must register into the binding table");
5481}
5482
5483/// The authored Vulkan scatter (IndexAdd / ScatterAdd) kernel contract, embedded
5484/// via `include_str!` (the PRODUCTION contract). Parsed + lowered by
5485/// [`register_vulkan_scatter_from_contract`].
5486const VULKAN_SCATTER_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/scatter.fkc.md");
5487
5488/// Register the Vulkan scatter family (8 (op, dtype) bindings — IndexAdd (4) +
5489/// ScatterAdd (4)) by IMPORTING its FKC kernel contract — the SIXTH Vulkan-backend
5490/// FKC consumer. FKC is unconditional core infrastructure, so this is the ONE
5491/// registration path for the family: the hand-written
5492/// `register_with_precision(OpKind::{IndexAdd,ScatterAdd}, …)` regs are DELETED.
5493///
5494/// Each section fans a BASE `entry_point` over `[F32, F64, BF16, F16]` (the `base`
5495/// + `src` operands share the list ⇒ they fan together, §3.4), resolving
5496///
5497/// `<base>_<suffix>` to each distinct per-dtype wrapper and keying the 4-slot
5498/// `[base, U32, src, out]` (`passthrough(base)` output), byte-for-byte the deleted
5499/// regs. Caps ride through contiguous-only (`requires_contiguous` ⇒
5500/// `strided_input == false`). Precision is the contract's audited nondeterministic
5501/// `none(reason)` seed (bounded-CAS atomic accumulate, scheduler-dependent order)
5502/// — byte-for-byte the deleted regs' `PrecisionGuarantee::none(reason)`. Cost is
5503/// preserved because this runs BEFORE `fill_unset_cost_for_backend`.
5504///
5505/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5506/// failure of the embedded, authored contract is a programmer error surfaced once
5507/// here via `expect`.
5508fn register_vulkan_scatter_from_contract(table: &mut KernelBindingTable) {
5509    let provider = fuel_dispatch::fkc::import_bundle_str(
5510        VULKAN_SCATTER_CONTRACT,
5511        &crate::link::VulkanLinkRegistry,
5512    )
5513    .expect(
5514        "authored Vulkan scatter contract must import \
5515                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5516    );
5517    debug_assert!(
5518        provider.fused.is_empty(),
5519        "vulkan scatter contract declares no fused ops",
5520    );
5521    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5522    provider
5523        .register_into(table, &mut fused)
5524        .expect("Vulkan scatter contract must register into the binding table");
5525}
5526
5527/// The authored Vulkan movement (Concat / CumSum) kernel contract, embedded via
5528/// `include_str!` (the PRODUCTION contract). Parsed + lowered by
5529/// [`register_vulkan_movement_from_contract`].
5530const VULKAN_MOVEMENT_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/movement.fkc.md");
5531
5532/// Register the Vulkan movement family (8 (op, dtype) bindings — Concat (4) +
5533/// CumSum (4)) by IMPORTING its FKC kernel contract — the SEVENTH Vulkan-backend
5534/// FKC consumer. FKC is unconditional core infrastructure, so this is the ONE
5535/// registration path for the family: the hand-written
5536/// `register_with_caps_and_precision(OpKind::{Concat,CumSum}, …, strided, …)` regs
5537/// are DELETED.
5538///
5539/// Each section fans a BASE `entry_point` over its dtype list (§3.4), resolving
5540/// `<base>_<suffix>` to each distinct per-dtype wrapper and keying `[T, T]`
5541/// (`passthrough(input)` output), byte-for-byte the deleted regs. Both are
5542/// STRIDE-AWARE (`strided: accepted` ⇒ `strided_input == true`) — the
5543/// caps-through-import proof for this family. Concat precision is byte-exact
5544/// (bitwise); CumSum takes the conservative UNAUDITED author seed (the elementwise
5545/// pointwise precedent — the retired `VULKAN_{FLOAT,HALF}_POINTWISE_PRECISION`
5546/// consts are not re-asserted). Cost is preserved because this runs BEFORE
5547/// `fill_unset_cost_for_backend`.
5548///
5549/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5550/// failure of the embedded, authored contract is a programmer error surfaced once
5551/// here via `expect`.
5552fn register_vulkan_movement_from_contract(table: &mut KernelBindingTable) {
5553    let provider = fuel_dispatch::fkc::import_bundle_str(
5554        VULKAN_MOVEMENT_CONTRACT,
5555        &crate::link::VulkanLinkRegistry,
5556    )
5557    .expect(
5558        "authored Vulkan movement contract must import \
5559                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5560    );
5561    debug_assert!(
5562        provider.fused.is_empty(),
5563        "vulkan movement contract declares no fused ops",
5564    );
5565    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5566    provider
5567        .register_into(table, &mut fused)
5568        .expect("Vulkan movement contract must register into the binding table");
5569}
5570
5571/// The authored Vulkan shape (Triu / Tril / Flip / Roll) kernel contract, embedded
5572/// via `include_str!` (the PRODUCTION contract). Parsed + lowered by
5573/// [`register_vulkan_shape_from_contract`].
5574const VULKAN_SHAPE_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/shape.fkc.md");
5575
5576/// Register the Vulkan shape family (28 (op, dtype) bindings — Triu (7) + Tril (7)
5577/// + Flip (7) + Roll (7)) by IMPORTING its FKC kernel contract — the EIGHTH
5578///
5579/// Vulkan-backend FKC consumer. FKC is unconditional core infrastructure, so this
5580/// is the ONE registration path for the family: the hand-written
5581/// `register_with_precision(OpKind::{Triu,Tril}, …)` +
5582/// `register_with_caps_and_precision(OpKind::{Flip,Roll}, …, strided, …)` regs are
5583/// DELETED.
5584///
5585/// Each op is ONE dtype-agnostic wrapper across its 7 dtype keys; each section fans
5586/// the BASE `entry_point` over `[F32, F16, BF16, F64, I32, U32, I64]` and the link
5587/// registry maps every `<base>_<suffix>` symbol to the one wrapper (a
5588/// synthetic-base umbrella, the pad_cpu precedent), keying `[T, T]` byte-for-byte
5589/// the deleted regs. Caps split by op: Triu/Tril contiguous
5590/// (`strided_input == false`), Flip/Roll stride-aware (`strided_input == true`) —
5591/// the caps-through-import proof. Precision is byte-exact (bitwise, `max_ulp: 0`),
5592/// byte-for-byte the deleted regs' `VULKAN_BYTE_LEVEL_PRECISION`. Cost is preserved
5593/// because this runs BEFORE `fill_unset_cost_for_backend`.
5594///
5595/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5596/// failure of the embedded, authored contract is a programmer error surfaced once
5597/// here via `expect`.
5598fn register_vulkan_shape_from_contract(table: &mut KernelBindingTable) {
5599    let provider = fuel_dispatch::fkc::import_bundle_str(
5600        VULKAN_SHAPE_CONTRACT,
5601        &crate::link::VulkanLinkRegistry,
5602    )
5603    .expect(
5604        "authored Vulkan shape contract must import \
5605                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5606    );
5607    debug_assert!(
5608        provider.fused.is_empty(),
5609        "vulkan shape contract declares no fused ops",
5610    );
5611    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5612    provider
5613        .register_into(table, &mut fused)
5614        .expect("Vulkan shape contract must register into the binding table");
5615}
5616
5617/// The authored Vulkan pad-copy (Pad / PadBackward / Copy) kernel contract,
5618/// embedded via `include_str!` (the PRODUCTION contract). Parsed + lowered by
5619/// [`register_vulkan_pad_copy_from_contract`].
5620const VULKAN_PAD_COPY_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/pad-copy.fkc.md");
5621
5622/// Register the Vulkan pad-copy family (21 (op, dtype) bindings — Pad (6) +
5623/// PadBackward (6) + Copy (9)) by IMPORTING its FKC kernel contract — the NINTH
5624/// Vulkan-backend FKC consumer. FKC is unconditional core infrastructure, so this
5625/// is the ONE registration path for the family: the hand-written
5626/// `register_with_precision(OpKind::{Pad,PadBackward,Copy}, …)` regs are DELETED.
5627///
5628/// Each op is ONE dtype-agnostic wrapper across its dtype keys; each section fans
5629/// the BASE `entry_point` over its dtype list and the link registry maps every
5630/// `<base>_<suffix>` symbol to the one wrapper (a synthetic-base umbrella, the
5631/// pad_cpu precedent), keying `[T, T]` byte-for-byte the deleted regs. Caps ride
5632/// through contiguous-only (`requires_contiguous` ⇒ `strided_input == false`);
5633/// precision is byte-exact (bitwise, `max_ulp: 0`), byte-for-byte the deleted regs'
5634/// `VULKAN_BYTE_LEVEL_PRECISION`. Cost is preserved because this runs BEFORE
5635/// `fill_unset_cost_for_backend`.
5636///
5637/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5638/// failure of the embedded, authored contract is a programmer error surfaced once
5639/// here via `expect`.
5640fn register_vulkan_pad_copy_from_contract(table: &mut KernelBindingTable) {
5641    let provider = fuel_dispatch::fkc::import_bundle_str(
5642        VULKAN_PAD_COPY_CONTRACT,
5643        &crate::link::VulkanLinkRegistry,
5644    )
5645    .expect(
5646        "authored Vulkan pad-copy contract must import \
5647                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5648    );
5649    debug_assert!(
5650        provider.fused.is_empty(),
5651        "vulkan pad-copy contract declares no fused ops",
5652    );
5653    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5654    provider
5655        .register_into(table, &mut fused)
5656        .expect("Vulkan pad-copy contract must register into the binding table");
5657}
5658
5659/// The authored Vulkan write-slice (WriteSlice / WriteSliceRotating) kernel
5660/// contract, embedded via `include_str!` (the PRODUCTION contract). Parsed +
5661/// lowered by [`register_vulkan_write_slice_from_contract`].
5662const VULKAN_WRITE_SLICE_CONTRACT: &str =
5663    include_str!("../kernel-contracts/vulkan/write-slice.fkc.md");
5664
5665/// Register the Vulkan write-slice family (18 (op, dtype) bindings — WriteSlice (9)
5666/// + WriteSliceRotating (9)) by IMPORTING its FKC kernel contract — the TENTH
5667///
5668/// Vulkan-backend FKC consumer. FKC is unconditional core infrastructure, so this
5669/// is the ONE registration path for the family: the hand-written
5670/// `register_with_precision(OpKind::{WriteSlice,WriteSliceRotating}, …)` regs are
5671/// DELETED.
5672///
5673/// BYTE-WIDTH-keyed: each op's 9 dtype keys collapse to 4 byte-width wrappers
5674/// (`b1/b2/b4/b8`) — the cast family's "several sections share one wrapper"
5675/// precedent. Each section fans the BASE `entry_point` over the 9-dtype list and
5676/// the link registry maps each `<base>_<suffix>` symbol to the byte-width wrapper
5677/// for that dtype's size, keying `[T, T]` byte-for-byte the deleted regs. Caps ride
5678/// through contiguous-only (`requires_contiguous` ⇒ `strided_input == false`);
5679/// precision is byte-exact (bitwise, `max_ulp: 0`), byte-for-byte the deleted regs'
5680/// `VULKAN_BYTE_LEVEL_PRECISION`. Cost is preserved because this runs BEFORE
5681/// `fill_unset_cost_for_backend`.
5682///
5683/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5684/// failure of the embedded, authored contract is a programmer error surfaced once
5685/// here via `expect`.
5686fn register_vulkan_write_slice_from_contract(table: &mut KernelBindingTable) {
5687    let provider = fuel_dispatch::fkc::import_bundle_str(
5688        VULKAN_WRITE_SLICE_CONTRACT,
5689        &crate::link::VulkanLinkRegistry,
5690    )
5691    .expect(
5692        "authored Vulkan write-slice contract must import \
5693                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5694    );
5695    debug_assert!(
5696        provider.fused.is_empty(),
5697        "vulkan write-slice contract declares no fused ops",
5698    );
5699    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5700    provider
5701        .register_into(table, &mut fused)
5702        .expect("Vulkan write-slice contract must register into the binding table");
5703}
5704
5705/// The authored Vulkan rope kernel contract, embedded via `include_str!` (the
5706/// PRODUCTION contract). Parsed + lowered by [`register_vulkan_rope_from_contract`].
5707const VULKAN_ROPE_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/rope.fkc.md");
5708
5709/// Register the Vulkan rope family (4 (Rope, [x, cos, sin, out]) per-dtype
5710/// bindings) by IMPORTING its FKC kernel contract — the ELEVENTH Vulkan-backend
5711/// FKC consumer. FKC is unconditional core infrastructure, so this is the ONE
5712/// registration path for the family: the hand-written
5713/// `register_with_caps_and_precision(OpKind::Rope, …, strided, …)` regs are DELETED.
5714///
5715/// The single section fans a BASE `entry_point` over `[F32, F16, F64, BF16]` (the
5716/// `x` + `cos` + `sin` operands share the list ⇒ they fan together, §3.4),
5717/// resolving `rope_<suffix>` to each distinct per-dtype wrapper and keying the
5718/// 4-slot `[x, cos, sin, out]` (`passthrough(x)` output), byte-for-byte the deleted
5719/// regs. STRIDE-AWARE (`strided: accepted` ⇒ `strided_input == true`) — the
5720/// caps-through-import proof. Precision is the conservative UNAUDITED author seed
5721/// (the elementwise pointwise precedent — the retired
5722/// `VULKAN_{FLOAT,HALF}_POINTWISE_PRECISION` consts are not re-asserted). Cost is
5723/// preserved because this runs BEFORE `fill_unset_cost_for_backend`.
5724///
5725/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5726/// failure of the embedded, authored contract is a programmer error surfaced once
5727/// here via `expect`.
5728fn register_vulkan_rope_from_contract(table: &mut KernelBindingTable) {
5729    let provider = fuel_dispatch::fkc::import_bundle_str(
5730        VULKAN_ROPE_CONTRACT,
5731        &crate::link::VulkanLinkRegistry,
5732    )
5733    .expect(
5734        "authored Vulkan rope contract must import \
5735                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5736    );
5737    debug_assert!(
5738        provider.fused.is_empty(),
5739        "vulkan rope contract declares no fused ops",
5740    );
5741    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5742    provider
5743        .register_into(table, &mut fused)
5744        .expect("Vulkan rope contract must register into the binding table");
5745}
5746
5747/// The authored Vulkan reduce-primitives kernel contract (production per-(op,
5748/// dtype) bindings), embedded via `include_str!`. Parsed + lowered by
5749/// [`register_vulkan_reduce_from_contract`].
5750const VULKAN_REDUCE_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/reduce-prims.fkc.md");
5751
5752/// Register the Vulkan reduce family (24 (op, dtype) bindings — SumReduce /
5753/// MaxReduce / MinReduce / MeanReduce (16) + ArgMaxDim / ArgMinDim (8)) by
5754/// IMPORTING its FKC kernel contract — the TWELFTH Vulkan-backend FKC consumer.
5755/// FKC is unconditional core infrastructure, so this is the ONE registration path
5756/// for the family: the hand-written `register_with_precision(OpKind::{SumReduce,…,
5757/// ArgMinDim}, …)` regs are DELETED.
5758///
5759/// This production contract (`reduce-prims.fkc.md`) supersedes the aspirational
5760/// `vulkan/reduce.fkc.md` corpus (an op-id-selector binding model FKC's
5761/// one-`op_kind`-per-section importer cannot express): it authors ONE section per
5762/// OpKind, fanned over `[F32, F16, BF16, F64]` to the DISTINCT per-dtype wrapper
5763/// (`reduce::{sum,max,min,mean}_*`, `arg_reduce::{argmax,argmin}_*`), keying value
5764/// reduces `[T, T]` (`passthrough`) and index reduces `[T, U32]` (`fixed(U32)`),
5765/// byte-for-byte the deleted regs. Caps ride through contiguous-only
5766/// (`requires_contiguous` ⇒ `strided_input == false`). Precision: value reduces are
5767/// the audited nondeterministic `none(reason)` seed (subgroup-tree FADD order, the
5768/// matmul/conv precedent); arg reduces are bitwise exact (integer index). Cost is
5769/// preserved because this runs BEFORE `fill_unset_cost_for_backend`.
5770///
5771/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5772/// failure of the embedded, authored contract is a programmer error surfaced once
5773/// here via `expect`.
5774fn register_vulkan_reduce_from_contract(table: &mut KernelBindingTable) {
5775    let provider = fuel_dispatch::fkc::import_bundle_str(
5776        VULKAN_REDUCE_CONTRACT,
5777        &crate::link::VulkanLinkRegistry,
5778    )
5779    .expect(
5780        "authored Vulkan reduce contract must import \
5781                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5782    );
5783    debug_assert!(
5784        provider.fused.is_empty(),
5785        "vulkan reduce contract declares no fused ops",
5786    );
5787    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5788    provider
5789        .register_into(table, &mut fused)
5790        .expect("Vulkan reduce contract must register into the binding table");
5791}
5792
5793/// The authored Vulkan normalization / softmax primitives kernel contract,
5794/// embedded via `include_str!`. Parsed + lowered by
5795/// [`register_vulkan_norm_from_contract`].
5796const VULKAN_NORM_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/norm.fkc.md");
5797
5798/// Register the Vulkan norm family (20 (op, dtype) bindings — SoftmaxLastDim (4) +
5799/// SoftmaxLastDimBackward (4) + LayerNormLastDim (4) + LayerNormLastDimBackward (4)
5800/// + RmsNormLastDim (4)) by IMPORTING its FKC kernel contract — the THIRTEENTH
5801///
5802/// Vulkan-backend FKC consumer. FKC is unconditional core infrastructure, so this
5803/// is the ONE registration path for the family: the hand-written
5804/// `register_with_precision(OpKind::{SoftmaxLastDim,…,RmsNormLastDim}, …)` regs are
5805/// DELETED.
5806///
5807/// Each section fans a BASE `entry_point` over `[F32, F16, BF16, F64]` to its
5808/// DISTINCT per-dtype wrapper (`softmax::*`, `norm::*`), keying forward families
5809/// `[T, T]` and backward families `[T, T, T]` (both inputs sharing the fanned list),
5810/// byte-for-byte the deleted regs. Caps ride through contiguous-only
5811/// (`requires_contiguous` ⇒ `strided_input == false`); precision is the audited
5812/// nondeterministic `none(reason)` seed (per-row subgroup-tree FADD order, the
5813/// matmul/conv/value-reduce precedent). Cost is preserved because this runs BEFORE
5814/// `fill_unset_cost_for_backend`.
5815///
5816/// The family declares NO fused ops (the FUSED softmax/norm decompositions register
5817/// separately via the fused registry). Init-boundary fail-fast: a parse/lower/link
5818/// failure of the embedded, authored contract is a programmer error surfaced once
5819/// here via `expect`.
5820fn register_vulkan_norm_from_contract(table: &mut KernelBindingTable) {
5821    let provider = fuel_dispatch::fkc::import_bundle_str(
5822        VULKAN_NORM_CONTRACT,
5823        &crate::link::VulkanLinkRegistry,
5824    )
5825    .expect(
5826        "authored Vulkan norm contract must import \
5827                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5828    );
5829    debug_assert!(
5830        provider.fused.is_empty(),
5831        "vulkan norm contract declares no fused ops",
5832    );
5833    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5834    provider
5835        .register_into(table, &mut fused)
5836        .expect("Vulkan norm contract must register into the binding table");
5837}
5838
5839/// The authored Vulkan FlashAttention kernel contract (6 sections — forward
5840/// f32/bf16/f16 + backward Q/K/V f32, each fanning a no-alibi + a with-alibi
5841/// key ⇒ 12 bindings), embedded via `include_str!` (the PRODUCTION contract).
5842/// Parsed + lowered by [`register_vulkan_attention_from_contract`].
5843const VULKAN_ATTENTION_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/attention.fkc.md");
5844
5845/// Register the Vulkan FlashAttention family (12 bindings — forward
5846/// `OpKind::FlashAttn` at f32/bf16/f16 + backward `OpKind::FlashAttnBackward{Q,K,V}`
5847/// at f32, each with a no-alibi AND a with-alibi binding shape) by IMPORTING its
5848/// AUTHORED FKC kernel contract — the FIFTEENTH (and LAST) Vulkan-backend FKC
5849/// consumer. FKC is unconditional core infrastructure, so this is the ONE
5850/// registration path for the family: the hand-written
5851/// `table.register_with_precision(OpKind::{FlashAttn,FlashAttnBackwardQ,
5852/// FlashAttnBackwardK,FlashAttnBackwardV}, …)` regs are DELETED. This was the
5853/// LAST hand-written `table.register*` call in `register_vulkan_kernels`, so the
5854/// Vulkan backend is now 100% contract-sourced.
5855///
5856/// The corpus's `vulkan/conv-attn-rope.fkc.md` models this family as aspirational
5857/// `fused_op: FLASH_ATTN` / `FLASH_ATTN_BACKWARD_*` decompositions (plus the tiled
5858/// FA-2 `flash_attention`), a SEPARATE future FUSED-registry seam that does NOT
5859/// register the primitive `OpKind::FlashAttn*` bindings production wires (the same
5860/// primitive-vs-fused split conv2d / matmul draw). So the migration authors SIX
5861/// faithful single-dtype-per-operand `op_kind:` sections in the new production
5862/// `fuel-dispatch/kernel-contracts/vulkan/attention.fkc.md`:
5863///  - **Forward wrappers are DISTINCT per dtype** (`flash_attn::flash_attn_{f32,
5864///    bf16,f16}`), so — like conv2d's `conv2d_{f32,bf16,f16}` and the CPU attention
5865///    contract's per-dtype `flash_attn_*` sections — each dtype is its OWN
5866///    single-dtype section resolving its `entry_point` AS-IS (no dtype-fan
5867///    umbrella); backward is three f32-only sections.
5868///  - **`alibi_slopes` is an `optional: true` LAST input**, so the importer's
5869///    optional-last fan (§3.4) keys EACH section TWICE (with + without the
5870///    operand), byte-for-byte the deleted regs' dual `[q,k,v,out]` /
5871///    `[q,k,v,alibi,out]` (forward) and `[q,k,v,do,out]` / `[q,k,v,do,alibi,out]`
5872///    (backward) shapes. The forward + all three backward selectors share the ONE
5873///    `OpParams::FlashAttn` carrier (`op_params.variant: FlashAttn` — the CPU
5874///    precedent; no dedicated backward variant).
5875///
5876/// **Caps ride through truthfully.** Each section's `requires_contiguous` layout
5877/// projects `strided_input == false` — byte-for-byte the deleted plain
5878/// `register_with_precision` regs (the kernels read canonical row-major q/k/v/do;
5879/// a strided operand is auto-Contiguized by the planner first). Precision becomes
5880/// the contract's corrected audited seed (`bit_stable_on_same_hardware: false`,
5881/// audited `none(reason)`, `determinism: nondeterministic`): the naive single-pass
5882/// kernel does its softmax over the `[Sk]` score row with a per-`(b,h,q)` workgroup
5883/// shared-memory reduction whose FADD order is scheduler-dependent, so the retired
5884/// hand-written `VULKAN_FLOAT_POINTWISE_PRECISION` / `VULKAN_HALF_POINTWISE_PRECISION`
5885/// consts (which mis-declared `bit_stable_on_same_hardware: true` + `max_ulp: 1`,
5886/// a per-thread-pointwise claim) OVER-CLAIMED bit-stability — the aspirational
5887/// `conv-attn-rope.fkc.md` already carries this honest posture; the consts are
5888/// retired from this seam (their `pub const` defs stay in `fused.rs`). Cost is
5889/// preserved because this runs BEFORE `fill_unset_cost_for_backend`, which upgrades
5890/// the imported `unknown_cost` sentinels to the same OpKind cost fn.
5891///
5892/// The family declares NO fused ops (the FUSED flash decompositions register
5893/// separately via the fused registry). Init-boundary fail-fast: a parse/lower/link
5894/// failure of the embedded, authored contract is a programmer error surfaced once
5895/// here via `expect`.
5896fn register_vulkan_attention_from_contract(table: &mut KernelBindingTable) {
5897    let provider = fuel_dispatch::fkc::import_bundle_str(
5898        VULKAN_ATTENTION_CONTRACT,
5899        &crate::link::VulkanLinkRegistry,
5900    )
5901    .expect(
5902        "authored Vulkan attention contract must import \
5903                 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5904    );
5905    debug_assert!(
5906        provider.fused.is_empty(),
5907        "vulkan attention contract declares no fused ops",
5908    );
5909    let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5910    provider
5911        .register_into(table, &mut fused)
5912        .expect("Vulkan attention contract must register into the binding table");
5913}
5914
5915/// Register every Vulkan kernel wrapper against its `(OpKind, dtypes,
5916/// BackendId::Vulkan)` decision-point key in the shared
5917/// `KernelBindingTable`. Each wrapper appears as an alternative
5918/// alongside any CPU / CUDA / future-backend registrations at the
5919/// same key. The route picker (architecture v1.0 §04) selects among
5920/// them at plan time based on input residency + telemetry.
5921///
5922/// V.1.C coverage: `AddElementwise [F32, F32, F32]` only. The
5923/// proof-of-life single op. V.2 fans out to the ~25 already-compiled
5924/// SPIR-V kernels; V.3 adds new Slang for the kernel families CUDA
5925/// has and Vulkan doesn't.
5926pub fn register_vulkan_kernels(table: &mut KernelBindingTable) {
5927    // NB: the `use fuel_dispatch::fused::{ PrecisionGuarantee, VULKAN_FLOAT_POINTWISE_PRECISION,
5928    // VULKAN_HALF_POINTWISE_PRECISION }` seam is RETIRED — the FlashAttention family was
5929    // their LAST code user, and it now registers from the FKC attention contract (see
5930    // `register_vulkan_attention_from_contract`), which carries the corrected
5931    // audited-nondeterministic per-section precision (the two POINTWISE consts
5932    // over-claimed `bit_stable_on_same_hardware: true` + `max_ulp: 1` for a shared-mem
5933    // softmax reduction). With the FlashAttn regs gone there are NO hand-written
5934    // `table.register*` calls left, so NO `PrecisionGuarantee` / precision-const import
5935    // is needed. The `pub const` defs stay in `fused.rs`, mirroring VULKAN_TRANSCENDENTAL.
5936    // (VULKAN_BYTE_LEVEL_PRECISION / VULKAN_QMATMUL_PRECISION / VULKAN_TRANSCENDENTAL_PRECISION
5937    // / VULKAN_MATMUL_PRECISION / VULKAN_MATMUL_TENSORCORE_PRECISION / VULKAN_CAST_PRECISION
5938    // were retired by the earlier family migrations; KernelCaps likewise — every strided
5939    // Vulkan family projects `strided_input` from its FKC contract's layout.)
5940    let vk = BackendId::Vulkan;
5941    // NB: EVERY Vulkan family now registers from its FKC contract (the
5942    // `register_vulkan_*_from_contract` calls at the END of this fn are the SOLE
5943    // registration path). There are ZERO hand-written `table.register*` calls remaining
5944    // — the Vulkan backend is 100% contract-sourced. `vk` is used only by the
5945    // `fill_unset_cost_for_backend` pass below.
5946
5947    // Phase 7.6 step 9c follow-up (2026-05-23 + 2026-05-24):
5948    // - Per-kernel `PrecisionGuarantee` + cost (session 1, shipped).
5949    // - Per-kernel `KernelCaps::strided_input` (session 2, this commit).
5950    //   Each Slang kernel was audited to determine whether it walks
5951    //   per-input strides (and so can consume non-contiguous inputs
5952    //   like broadcast / transpose / slice views directly) or
5953    //   requires the executor's auto-Contiguize pass to materialize
5954    //   contiguous inputs first.
5955    //
5956    // **Conventions for this file**:
5957    // - Stride-aware kernels opt in via
5958    //   `KernelCaps::strided_input()`. The executor skips
5959    //   auto-Contiguize for these so lazy views reach the kernel
5960    //   unmaterialized.
5961    // - Contiguous-only kernels keep `KernelCaps::empty()`
5962    //   (the default) AND get a `// strided-input candidate: <reason>`
5963    //   comment iff the kernel SHAPE would support an arbitrary-
5964    //   stride extension. Future perf sweeps grep for that marker
5965    //   to find conversion work.
5966    // - Contiguous-only kernels whose shape inherently needs flat
5967    //   layout (subgroup-tree reductions, tiled matmul, im2col,
5968    //   destination-as-layout WriteSlice, byte-level
5969    //   Triu/Tril/Flip/Roll) carry a family-level comment but no
5970    //   candidate marker.
5971    //
5972    // Cost functions are bulk-filled at the end via
5973    // `fill_unset_cost_for_backend(Vulkan, default_cost_for_op_kind)`.
5974
5975    // ----- Binary + Unary f32 (V.2.A/B) — MIGRATED to FKC contract import.
5976    // The hand-written `register_with_caps_and_precision` regs (6 binary + 16
5977    // unary, all strided f32) are DELETED; the whole elementwise family now
5978    // registers from `fuel-dispatch/kernel-contracts/vulkan/elementwise.fkc.md` via
5979    // `register_vulkan_elementwise_from_contract` (the SOLE path, called at the
5980    // END of this fn before the cost-fill pass). The top-level `strided`
5981    // `KernelCaps` binding that Rope / Concat / Flip / Roll / CumSum used to consume
5982    // is retired now those families all register from their FKC contracts
5983    // (movement / shape / rope), which project `strided_input` from their
5984    // `strided: accepted` layouts. -----
5985
5986    // ----- Softmax + RmsNorm last-dim (V.2.C, f32) — per-row reductions
5987    // with subgroup-tree internal accumulation. CONTIGUOUS-ONLY by
5988    // design: the kernel issues one workgroup per row and reads the
5989    // row's elements flat; an arbitrary stride on the last-dim axis
5990    // would break the workgroup-shared-memory reduction. Auto-
5991    // Contiguize materializes broadcast/transpose views first. -----
5992    // ----- Softmax + RmsNorm + LayerNorm (+ softmax/layernorm backward) last-dim —
5993    // MIGRATED to FKC contract import. The hand-written `register_with_precision(
5994    // OpKind::{SoftmaxLastDim,SoftmaxLastDimBackward,LayerNormLastDim,
5995    // LayerNormLastDimBackward,RmsNormLastDim}, …)` regs (20 per-(op, dtype)
5996    // bindings, all contiguous) are DELETED; the whole norm family now registers
5997    // from `fuel-dispatch/kernel-contracts/vulkan/norm.fkc.md` via
5998    // `register_vulkan_norm_from_contract` (called at the END of this fn, before the
5999    // cost-fill pass). Forward families key [T, T], backward families [T, T, T];
6000    // precision becomes the audited nondeterministic none(reason) seed (per-row
6001    // subgroup-tree FADD order). Contiguous-only. -----
6002
6003    // ----- SoftmaxLastDimBackward, f32 + f16/bf16/f64 (V.3.G.softmax-bwd,
6004    // 2026-05-30). 2 inputs (y, g) → 1 output (dx); reuses
6005    // OpParams::SoftmaxLastDim. Reduction order is scheduler-determined. -----
6006    // ----- SoftmaxLastDimBackward — MIGRATED to FKC contract import (deleted; now
6007    // registered from the norm contract, key [y, g, dx]). -----
6008
6009    // ----- Softmax f16/bf16/f64 — MIGRATED to FKC contract import (deleted; now
6010    // registered from the norm contract, alongside the f32 combo). -----
6011
6012    // ----- LayerNormLastDimBackward — MIGRATED to FKC contract import (deleted; now
6013    // registered from the norm contract, key [x, g, dx]). -----
6014
6015    // ----- LayerNorm last-dim — MIGRATED to FKC contract import (deleted; now
6016    // registered from the norm contract). -----
6017
6018    // ----- RmsNorm f16/bf16/f64 — MIGRATED to FKC contract import (deleted; now
6019    // registered from the norm contract, alongside the f32 combo). -----
6020
6021    // ----- RoPE (V.2.C, f32) — pointwise rotation with cos/sin tables.
6022    // STRIDE-AWARE on `x`: rope.slang's Params struct carries
6023    // `x_s0/x_s1/x_s_seq/x_s_hd` + an `x_contiguous` fast-path flag
6024    // and decomposes per-thread index into per-dim coordinates. cos/sin
6025    // are documented as always-contiguous (the wrapper enforces).
6026    // Binding-shape MUST match the CPU registration `[x, cos, sin, out]`
6027    // (4 dtypes). The strided_input cap signals "ANY input may be non-
6028    // contiguous" — for Rope specifically, only x; the wrapper handles
6029    // forcing cos/sin contiguous through its own path. -----
6030    // ----- RoPE (f32/f16/f64/bf16) — MIGRATED to FKC contract import. The
6031    // hand-written `register_with_caps_and_precision(OpKind::Rope, …, strided, …)`
6032    // regs (4-slot [x, cos, sin, out] key, 4 per-dtype wrappers) are DELETED; the
6033    // rope family now registers from `fuel-dispatch/kernel-contracts/vulkan/rope.fkc.md` via
6034    // `register_vulkan_rope_from_contract` (called at the END of this fn, before the
6035    // cost-fill pass). Stride-aware (strided_input=true); precision becomes the
6036    // conservative UNAUDITED author seed (the elementwise pointwise precedent; the
6037    // retired VULKAN_{FLOAT,HALF}_POINTWISE_PRECISION consts are not re-asserted). -----
6038
6039    // ----- IndexSelect (V.2.D, f32 src + u32 ids) — pure gather (byte-level).
6040    // strided-input candidate: index_select.slang flattens input to
6041    // (outer, axis, inner) and reads via own-shape strides. Could be
6042    // extended to walk arbitrary input layout strides at gather time
6043    // (saves an auto-Contiguize when the source is a transpose view).
6044    // Indices are u32; their layout-strided variant is a follow-up. -----
6045    // ----- IndexSelect (f32/f16/bf16/f64 src + u32 ids) — MIGRATED to FKC
6046    // contract import. The hand-written `register_with_precision(OpKind::
6047    // IndexSelect, …)` regs (4 per-dtype wrappers) are DELETED; the whole select
6048    // family (IndexSelect + Gather + MaskedFill) now registers from
6049    // `fuel-dispatch/kernel-contracts/vulkan/select.fkc.md` via
6050    // `register_vulkan_select_from_contract` (called at the END of this fn, before
6051    // the cost-fill pass). Caps stay contiguous-only (strided_input=false). -----
6052
6053    // ----- Reduce f32 (V.2.D + V.3.A.2) — Sum / Max / Min / Mean.
6054    // CONTIGUOUS-ONLY by design: reduce.slang does a tree reduction
6055    // into workgroup-shared memory; the input is read flat. Strided
6056    // inputs would require either pre-materialization (current
6057    // behaviour via auto-Contiguize) or a redesigned reduction
6058    // schedule that's unlikely to outperform the auto-Contiguize +
6059    // current kernel. -----
6060    // ----- Reduce (Sum/Max/Min/Mean) + ArgMax/ArgMin — MIGRATED to FKC contract
6061    // import. The hand-written per-(op, dtype) `register_with_precision(OpKind::
6062    // {SumReduce,…,ArgMinDim}, …)` regs (16 value + 8 arg, all contiguous) are
6063    // DELETED; the whole reduce family now registers from
6064    // `fuel-dispatch/kernel-contracts/vulkan/reduce-prims.fkc.md` via
6065    // `register_vulkan_reduce_from_contract` (called at the END of this fn, before
6066    // the cost-fill pass). Value reduces carry the audited nondeterministic
6067    // none(reason) seed (subgroup-tree FADD order); arg reduces are bitwise exact
6068    // (integer index). Contiguous-only. -----
6069
6070    // ----- IndexAdd + ScatterAdd (atomic bounded-CAS accumulate) — MIGRATED to
6071    // FKC contract import. The hand-written `register_with_precision(OpKind::
6072    // {IndexAdd,ScatterAdd}, …)` regs (4 per-dtype wrappers each, 4-slot
6073    // [base, U32, src, out] key) are DELETED; the whole scatter family now
6074    // registers from `fuel-dispatch/kernel-contracts/vulkan/scatter.fkc.md` via
6075    // `register_vulkan_scatter_from_contract` (called at the END of this fn,
6076    // before the cost-fill pass). Caps stay contiguous-only (strided_input=false);
6077    // precision becomes the contract's audited nondeterministic none(reason) seed
6078    // (the same posture as the deleted PrecisionGuarantee::none regs). -----
6079
6080    // ----- ArgMaxDim / ArgMinDim — MIGRATED to FKC contract import (deleted; now
6081    // registered from the reduce-prims contract, key [T, U32] with a fixed(U32)
6082    // index output; bitwise exact). -----
6083
6084    // ----- Reduce last-dim f16/bf16/f64 — MIGRATED to FKC contract import (deleted;
6085    // now registered from the reduce-prims contract, alongside the f32 combos). -----
6086
6087    // ----- Concat (f32/f16/bf16/f64) — MIGRATED to FKC contract import (deleted;
6088    // now registered from `fuel-dispatch/kernel-contracts/vulkan/movement.fkc.md` via
6089    // `register_vulkan_movement_from_contract`, alongside CumSum). Stride-aware
6090    // (strided_input=true) byte-level data movement. -----
6091
6092    // ----- Pad with constant fill (V.3.G.pad, 2026-05-30).
6093    // Byte-level kernels (b1/b2/b4/b8) dispatched by the OUTPUT dtype's
6094    // size at the shim. Reflect/replicate modes fall through to CPU.
6095    // ----- Pad + PadBackward — MIGRATED to FKC contract import. The hand-written
6096    // per-dtype (6 dtypes) `register_with_precision(OpKind::{Pad,PadBackward}, …)`
6097    // regs are DELETED; the whole pad-copy family (Pad + PadBackward + Copy) now
6098    // registers from `fuel-dispatch/kernel-contracts/vulkan/pad-copy.fkc.md` via
6099    // `register_vulkan_pad_copy_from_contract` (called at the END of this fn,
6100    // before the cost-fill pass). Each op is ONE dtype-agnostic wrapper
6101    // (synthetic-base umbrella); const mode only; contiguous-only. -----
6102    {
6103        // ----- MaskedFill + Gather — MIGRATED to FKC contract import (deleted;
6104        // now registered from `fuel-dispatch/kernel-contracts/vulkan/select.fkc.md` via
6105        // `register_vulkan_select_from_contract`, alongside IndexSelect). Both are
6106        // ONE dtype-agnostic wrapper across their 6 dtype keys (byte-width from the
6107        // output dtype) — a synthetic-base umbrella. Contiguous-only. -----
6108    }
6109    // V.3.G.concat f16/bf16/f64 — MIGRATED to FKC contract import (deleted; now
6110    // registered from the movement contract, alongside the f32 combo above). -----
6111
6112    // ----- MatMul (f32 GEMM + the five mixed-precision / tensor-core combos)
6113    // — MIGRATED to FKC contract import. The hand-written
6114    // `table.register_with_precision(OpKind::MatMul, …)` regs (f32, f32×bf16→f32,
6115    // bf16×bf16→{f32,bf16}, f16×f16→{f16,f32}) are DELETED; they now register from
6116    // the vulkan matmul contract via `register_vulkan_matmul_from_contract`
6117    // (called at the END of this fn, before the cost fill pass). Caps stay
6118    // contiguous-only (`requires_contiguous` ⇒ strided_input=false); precision
6119    // becomes the contract's audited-none(reason) seed. The
6120    // VULKAN_MATMUL_PRECISION / VULKAN_MATMUL_TENSORCORE_PRECISION consts the
6121    // matmul migration left in use for the Vulkan conv2d family are now ALSO
6122    // retired — conv2d migrated to its own FKC contract
6123    // (`register_vulkan_conv_from_contract`). See
6124    // `fuel-dispatch/kernel-contracts/vulkan/matmul.fkc.md`.
6125
6126    // ----- Affine / Clamp / PowI — MIGRATED to FKC contract import.
6127    // The hand-written Affine (f32/f16/f64 strided + bf16 contiguous-only),
6128    // ClampElementwise (f32), and PowIElementwise (f32) regs are DELETED; they now
6129    // register from the elementwise contract via
6130    // `register_vulkan_elementwise_from_contract` (called at the END of this fn).
6131    // Affine's bf16 variant keeps its contiguous-only caps
6132    // (`strided_input=false`) via the `affine_bf16` section's
6133    // `contiguous: required` layout. -----
6134
6135    // ----- Cast (all pairs) — MIGRATED to FKC contract import.
6136    // The hand-written `table.register_with_precision(OpKind::Cast, …)`
6137    // regs (f32↔f16, f32↔bf16, f32↔f64, and — further below — the six
6138    // F8E4M3↔{f32,f16,bf16} pairs) are DELETED. The whole family now
6139    // registers from `fuel-dispatch/kernel-contracts/vulkan/cast.fkc.md` via
6140    // `register_vulkan_cast_from_contract`, called at the END of this fn
6141    // (before the cost-fill pass), the SOLE registration path.
6142    // The top-level `f16` / `bf16_d` bindings that the WriteSlice / Copy byte-width
6143    // fan-outs used to consume are retired with those families' migration to the
6144    // FKC pad-copy + write-slice contracts (the remaining half-precision users —
6145    // reduce / norm / flash-attn / rope — declare their own block-scoped locals). -----
6146
6147    // ----- Binary + Unary f16 — MIGRATED to FKC contract import (deleted; now
6148    // registered from the elementwise contract, all strided). -----
6149
6150    // ----- Binary + Unary f64 — MIGRATED to FKC contract import (deleted; now
6151    // registered from the elementwise contract, all strided). The top-level
6152    // `f64_d` binding that CumSum used to consume is retired with CumSum's
6153    // migration to the FKC movement contract. -----
6154
6155    // ----- WriteSlice (V.3.J) — byte-width-keyed (b1/b2/b4/b8). Pure
6156    // byte-level data movement; no FP math.
6157    // CONTIGUOUS-ONLY: write_slice_b*.slang reads `src` contiguously
6158    // in its own rank-N shape and writes the matching slab inside
6159    // `dst` (also contiguous in its larger rank-N shape). The
6160    // destination's slab geometry IS the layout — strided inputs
6161    // wouldn't compose with the slab-walk's own-shape strides.
6162    // Auto-Contiguize materializes any non-contiguous source. -----
6163    // ----- WriteSlice + WriteSliceRotating — MIGRATED to FKC contract import. The
6164    // hand-written byte-width-keyed (9 dtypes → b1/b2/b4/b8) `register_with_precision(
6165    // OpKind::{WriteSlice,WriteSliceRotating}, …)` regs are DELETED; the whole
6166    // write-slice family now registers from
6167    // `fuel-dispatch/kernel-contracts/vulkan/write-slice.fkc.md` via
6168    // `register_vulkan_write_slice_from_contract` (called at the END of this fn,
6169    // before the cost-fill pass). Each op's 9 dtype keys share 4 byte-width wrappers
6170    // (the cast family's shared-wrapper precedent); contiguous-only. -----
6171
6172    // ----- Binary + Unary bf16 — MIGRATED to FKC contract import (deleted). The
6173    // binary_bf16 regs were strided (lane-masked); the unary_bf16 regs were plain
6174    // `register_with_precision` (contiguous-only, `strided_input=false`) — both
6175    // reproduced by the contract's per-section layout projection. -----
6176
6177    // ----- Triu / Tril — pure byte-level mask kernel (rank-3 reshape).
6178    // CONTIGUOUS-ONLY by design: triu_b4 / tril_b4 view inputs as a
6179    // flat (outer, dim_size, inner) 3-tuple. Arbitrary layout strides
6180    // would require a different decomposition; auto-Contiguize handles
6181    // non-contiguous inputs upstream.
6182    //
6183    // Flip / Roll — STRIDE-AWARE (alpha.31 sweep follow-up): the
6184    // flip_b* / roll_b* kernels now walk rank-N + per-input strides
6185    // with the axis from OpParams::{Flip, Roll}.axis. Output is contig
6186    // over the input's shape.
6187    // ----- Triu / Tril / Flip / Roll — MIGRATED to FKC contract import. The
6188    // hand-written per-dtype (7 dtypes) `register_with_precision(OpKind::
6189    // {Triu,Tril}, …)` + `register_with_caps_and_precision(OpKind::{Flip,Roll},
6190    // …, strided, …)` regs are DELETED; the whole shape family now registers from
6191    // `fuel-dispatch/kernel-contracts/vulkan/shape.fkc.md` via
6192    // `register_vulkan_shape_from_contract` (called at the END of this fn, before
6193    // the cost-fill pass). Each op is ONE dtype-agnostic wrapper (synthetic-base
6194    // umbrella). Caps split by op: Triu/Tril contiguous, Flip/Roll strided. -----
6195
6196    // ----- CumSum (inclusive prefix sum along one axis) — MIGRATED to FKC
6197    // contract import (deleted; now registered from
6198    // `fuel-dispatch/kernel-contracts/vulkan/movement.fkc.md` via
6199    // `register_vulkan_movement_from_contract`, alongside Concat). Stride-aware
6200    // (strided_input=true); precision becomes the conservative UNAUDITED author
6201    // seed (the elementwise pointwise precedent; the retired
6202    // VULKAN_{FLOAT,HALF}_POINTWISE_PRECISION consts are not re-asserted). -----
6203
6204    // ----- QMatMul (Q4_0 / Q4_K_M / Q8_0) — F32 × U32-quant → F32 —
6205    // MIGRATED to FKC contract import. The hand-written
6206    // `table.register_with_precision(OpKind::QMatMul, &[F32, U32, F32], …)` reg is
6207    // DELETED; the single binding now registers from
6208    // `fuel-dispatch/kernel-contracts/vulkan/qmatmul.fkc.md` via
6209    // `register_vulkan_qmatmul_from_contract` (called at the END of this fn, before
6210    // the cost-fill pass). ONE wrapper `qmatmul_vk` route-picks Q4_0 (fused
6211    // gemv/tiled) / Q4_K_M / Q8_0 (dequant-then-matmul_f32) by
6212    // `OpParams::QMatMul.quant_type` — the contract keys the weight slot with the
6213    // LOGICAL `U32` dispatch dtype (the CPU linear-quant U8→U32 reconciliation; the
6214    // physical GGML block-byte honesty rides `fdx.quant`). CONTIGUOUS-ONLY: the
6215    // quantized weight stream has a fixed block layout (per-block scale + N
6216    // quantized lanes); arbitrary strides on the weight buffer would break the
6217    // dequant kernel's block walk (`requires_contiguous` ⇒ strided_input=false).
6218    // Precision becomes the contract's corrected nondeterministic seed (the retired
6219    // `VULKAN_QMATMUL_PRECISION` const over-claimed bit-stability, like the retired
6220    // `VULKAN_MATMUL_PRECISION`; the const def stays in `fused.rs`). -----
6221
6222    // ----- Conv2D (f32 + bf16/f16 cooperative-matrix) — MIGRATED to FKC
6223    // contract import. The hand-written `table.register_with_precision(
6224    // OpKind::Conv2D, …)` regs (f32 here + the bf16/f16 coop combos further
6225    // below) are DELETED; the whole family now registers from
6226    // `fuel-dispatch/kernel-contracts/vulkan/conv.fkc.md` via
6227    // `register_vulkan_conv_from_contract` (called at the END of this fn, before
6228    // the cost-fill pass). Caps stay contiguous-only (`requires_contiguous` ⇒
6229    // strided_input=false); no bias key (the wrappers bail on a 3-input call);
6230    // precision becomes the contract's corrected nondeterministic seed (the
6231    // retired VULKAN_MATMUL_PRECISION / VULKAN_MATMUL_TENSORCORE_PRECISION consts
6232    // over-claimed bit-stability). -----
6233
6234    // ----- FlashAttn (forward f32/bf16/f16) + FlashAttnBackward{Q,K,V} (f32)
6235    // — MIGRATED to FKC contract import. The hand-written
6236    // `table.register_with_precision(OpKind::{FlashAttn,FlashAttnBackwardQ,
6237    // FlashAttnBackwardK,FlashAttnBackwardV}, …)` regs (naive single-pass SDPA;
6238    // both the no-alibi [q,k,v,(do,)out] and with-alibi [q,k,v,(do,)alibi,out]
6239    // binding shapes) are DELETED; the whole FlashAttention family now registers
6240    // from `fuel-dispatch/kernel-contracts/vulkan/attention.fkc.md` via
6241    // `register_vulkan_attention_from_contract` (called at the END of this fn,
6242    // before the cost-fill pass). Forward is THREE distinct per-dtype wrappers
6243    // (per-dtype sections, the conv2d + CPU-attention precedent); backward is
6244    // f32-only. `alibi_slopes` is an optional-LAST input (dual-key fan);
6245    // op_params.variant: FlashAttn shared across forward + backward. Caps stay
6246    // contiguous-only (`requires_contiguous` ⇒ strided_input=false); precision
6247    // becomes the contract's corrected audited-nondeterministic none(reason) seed
6248    // (single-pass shared-mem softmax reduction is scheduler-dependent — the
6249    // retired VULKAN_{FLOAT,HALF}_POINTWISE_PRECISION consts over-claimed
6250    // bit-stability). This was the LAST hand-written table.register* call — the
6251    // Vulkan backend is now 100% contract-sourced. -----
6252
6253    // ----- Conv2D bf16 + f16 (V.3.I extended) — im2col + cooperative-matrix
6254    // GEMM — MIGRATED to FKC contract import (deleted; now registered from
6255    // `fuel-dispatch/kernel-contracts/vulkan/conv.fkc.md` via
6256    // `register_vulkan_conv_from_contract`, alongside the f32 combo above). -----
6257
6258    // ----- Cast F8E4M3 ↔ {F32, F16, BF16} — MIGRATED to FKC contract
6259    // import (`register_vulkan_cast_from_contract`, called below). The six
6260    // hand-written `OpKind::Cast` F8E4M3 regs are DELETED — the contract is
6261    // now the sole registration path for the whole cast family. -----
6262
6263    // ----- Op::Copy D2H (bridge-retirement Phase 2). Byte-level.
6264    // CONTIGUOUS-ONLY: the wrapper downloads the source's bytes via
6265    // a Vulkan staging buffer (vkCmdCopyBuffer). The staging buffer
6266    // is sized to the source's flat byte count; stride-aware D2H
6267    // would require either per-row staging or an explicit pre-
6268    // Contiguize step. Auto-Contiguize handles non-contiguous
6269    // sources upstream of this kernel. -----
6270    // Op::Copy (D2H) — MIGRATED to FKC contract import (deleted; now registered
6271    // from `fuel-dispatch/kernel-contracts/vulkan/pad-copy.fkc.md` via
6272    // `register_vulkan_pad_copy_from_contract`, alongside Pad + PadBackward). ONE
6273    // dtype-agnostic wrapper (`copy_to_cpu_vulkan`) across 9 dtype keys
6274    // (synthetic-base umbrella); contiguous-only. -----
6275
6276    // ----- Cast family (all 12 SRC↔DST pairs) — registered FROM its FKC
6277    // kernel contract, the SOLE path (hand-written Cast regs deleted above).
6278    // Runs BEFORE the cost-fill pass so its imported `unknown_cost` sentinels
6279    // are upgraded to the same OpKind cost fn every other Vulkan primitive
6280    // gets. -----
6281    register_vulkan_cast_from_contract(table);
6282
6283    // ----- Elementwise family (unary / binary / affine / clamp / powi, 94
6284    // (op, dtype) bindings) — registered FROM its RE-AUTHORED FKC kernel contract,
6285    // the SOLE path (all hand-written elementwise regs deleted above). Runs BEFORE
6286    // the cost-fill pass so its imported `unknown_cost` sentinels are upgraded to
6287    // the same OpKind cost fn every other Vulkan primitive gets. This is the first
6288    // caps-through-import proof: the strided sections' layout projects
6289    // `strided_input=true`, the bf16-unary / affine_bf16 sections' `false`. -----
6290    register_vulkan_elementwise_from_contract(table);
6291
6292    // ----- MatMul family (f32 GEMM + the five mixed-precision / tensor-core
6293    // combos, 6 (MatMul, [lhs,rhs,out]) bindings) — registered FROM its
6294    // RE-AUTHORED FKC kernel contract, the SOLE path (all hand-written MatMul regs
6295    // deleted above). Runs BEFORE the cost-fill pass so its imported
6296    // `unknown_cost` sentinels are upgraded to the same OpKind cost fn every other
6297    // Vulkan primitive gets. Caps ride through contiguous-only
6298    // (`requires_contiguous` ⇒ strided_input=false). -----
6299    register_vulkan_matmul_from_contract(table);
6300
6301    // ----- Conv2D family (f32 + bf16/f16 cooperative-matrix, 3 (Conv2D,
6302    // [x, weight, out]) bindings) — registered FROM its RE-AUTHORED FKC kernel
6303    // contract, the SOLE path (all hand-written Conv2D regs deleted above). Runs
6304    // BEFORE the cost-fill pass so its imported `unknown_cost` sentinels are
6305    // upgraded to the same OpKind cost fn every other Vulkan primitive gets. Caps
6306    // ride through contiguous-only (`requires_contiguous` ⇒ strided_input=false);
6307    // no bias key (the wrappers bail on a 3-input call). -----
6308    register_vulkan_conv_from_contract(table);
6309
6310    // ----- Select family (IndexSelect (4) + Gather (6) + MaskedFill (6), 16
6311    // (op, dtype) bindings) — registered FROM its FKC kernel contract, the SOLE
6312    // path (all hand-written IndexSelect/Gather/MaskedFill regs deleted above).
6313    // Runs BEFORE the cost-fill pass so its imported `unknown_cost` sentinels are
6314    // upgraded to the same OpKind cost fn. Caps ride through contiguous-only
6315    // (`requires_contiguous` ⇒ strided_input=false); Gather/MaskedFill are a
6316    // synthetic-base umbrella (one wrapper per op across its dtype keys). -----
6317    register_vulkan_select_from_contract(table);
6318
6319    // ----- Scatter family (IndexAdd (4) + ScatterAdd (4), 8 (op, dtype) bindings)
6320    // — registered FROM its FKC kernel contract, the SOLE path (all hand-written
6321    // IndexAdd/ScatterAdd regs deleted above). Runs BEFORE the cost-fill pass.
6322    // Caps ride through contiguous-only; precision is the audited nondeterministic
6323    // none(reason) seed (bounded-CAS atomic accumulate). -----
6324    register_vulkan_scatter_from_contract(table);
6325
6326    // ----- Movement family (Concat (4) + CumSum (4), 8 (op, dtype) bindings) —
6327    // registered FROM its FKC kernel contract, the SOLE path (all hand-written
6328    // Concat/CumSum regs deleted above). Runs BEFORE the cost-fill pass. Both are
6329    // stride-aware (`strided: accepted` ⇒ strided_input=true); Concat byte-exact,
6330    // CumSum conservative UNAUDITED (the elementwise pointwise precedent). -----
6331    register_vulkan_movement_from_contract(table);
6332
6333    // ----- Shape family (Triu (7) + Tril (7) + Flip (7) + Roll (7), 28 (op, dtype)
6334    // bindings) — registered FROM its FKC kernel contract, the SOLE path (all
6335    // hand-written Triu/Tril/Flip/Roll regs deleted above). Runs BEFORE the
6336    // cost-fill pass. Each op is a synthetic-base umbrella (one dtype-agnostic
6337    // wrapper); Triu/Tril contiguous, Flip/Roll stride-aware. -----
6338    register_vulkan_shape_from_contract(table);
6339
6340    // ----- Pad-copy family (Pad (6) + PadBackward (6) + Copy (9), 21 (op, dtype)
6341    // bindings) — registered FROM its FKC kernel contract, the SOLE path (all
6342    // hand-written Pad/PadBackward/Copy regs deleted above). Runs BEFORE the
6343    // cost-fill pass. Each op is a synthetic-base umbrella (one dtype-agnostic
6344    // wrapper); const mode only; contiguous-only. -----
6345    register_vulkan_pad_copy_from_contract(table);
6346
6347    // ----- Write-slice family (WriteSlice (9) + WriteSliceRotating (9), 18
6348    // (op, dtype) bindings) — registered FROM its FKC kernel contract, the SOLE
6349    // path (all hand-written WriteSlice/WriteSliceRotating regs deleted above). Runs
6350    // BEFORE the cost-fill pass. Byte-width-keyed (9 dtypes share 4 b1/b2/b4/b8
6351    // wrappers per op); contiguous-only. -----
6352    register_vulkan_write_slice_from_contract(table);
6353
6354    // ----- RoPE family (4 (Rope, [x, cos, sin, out]) per-dtype bindings) —
6355    // registered FROM its FKC kernel contract, the SOLE path (all hand-written Rope
6356    // regs deleted above). Runs BEFORE the cost-fill pass. Stride-aware
6357    // (strided_input=true); precision is the conservative UNAUDITED author seed. -----
6358    register_vulkan_rope_from_contract(table);
6359
6360    // ----- Reduce family (SumReduce/MaxReduce/MinReduce/MeanReduce (16) +
6361    // ArgMaxDim/ArgMinDim (8), 24 (op, dtype) bindings) — registered FROM its FKC
6362    // kernel contract, the SOLE path (all hand-written reduce/arg-reduce regs
6363    // deleted above). Runs BEFORE the cost-fill pass. Contiguous-only; value reduces
6364    // audited nondeterministic none(reason), arg reduces bitwise exact. -----
6365    register_vulkan_reduce_from_contract(table);
6366
6367    // ----- Norm family (SoftmaxLastDim (4) + SoftmaxLastDimBackward (4) +
6368    // LayerNormLastDim (4) + LayerNormLastDimBackward (4) + RmsNormLastDim (4), 20
6369    // (op, dtype) bindings) — registered FROM its FKC kernel contract, the SOLE path
6370    // (all hand-written norm/softmax regs deleted above). Runs BEFORE the cost-fill
6371    // pass. Contiguous-only; audited nondeterministic none(reason) (per-row
6372    // subgroup-tree FADD order). -----
6373    register_vulkan_norm_from_contract(table);
6374
6375    // ----- QMatMul family (ONE (QMatMul, [F32, U32, F32]) binding) — registered
6376    // FROM its RE-AUTHORED FKC kernel contract, the SOLE path (the hand-written
6377    // `register_with_precision(OpKind::QMatMul, …)` reg deleted above). Runs BEFORE
6378    // the cost-fill pass so its imported `unknown_cost` sentinel is upgraded to the
6379    // same OpKind cost fn every other Vulkan primitive gets. ONE wrapper
6380    // (`qmatmul::qmatmul_vk`) route-picks Q4_0 / Q4_K_M / Q8_0 by
6381    // `OpParams::QMatMul.quant_type`; weight slot keyed with the LOGICAL U32 dtype
6382    // (the CPU linear-quant U8→U32 reconciliation; physical GGML block-byte honesty
6383    // on `fdx.quant`). Contiguous-only (`requires_contiguous` ⇒ strided_input=false);
6384    // precision is the audited nondeterministic none(reason) seed (the retired
6385    // VULKAN_QMATMUL_PRECISION over-claimed bit-stability). -----
6386    register_vulkan_qmatmul_from_contract(table);
6387
6388    // ----- FlashAttention family (forward FlashAttn f32/bf16/f16 + backward
6389    // FlashAttnBackward{Q,K,V} f32, 12 bindings) — registered FROM its AUTHORED
6390    // FKC kernel contract, the SOLE path (the LAST hand-written table.register*
6391    // calls, all deleted above). Runs BEFORE the cost-fill pass so its imported
6392    // `unknown_cost` sentinels are upgraded to the same OpKind cost fn every other
6393    // Vulkan primitive gets. Forward is three distinct per-dtype wrappers
6394    // (per-dtype sections); backward is f32-only; `alibi_slopes` optional-LAST
6395    // (dual-key fan). Contiguous-only (`requires_contiguous` ⇒ strided_input=false);
6396    // precision is the corrected audited-nondeterministic none(reason) seed
6397    // (single-pass shared-mem softmax reduction). With this call the Vulkan backend
6398    // is 100% contract-sourced: `register_vulkan_kernels` contains ZERO hand-written
6399    // `table.register*` calls. -----
6400    register_vulkan_attention_from_contract(table);
6401
6402    // ----- Bulk-fill cost functions for every Vulkan registration above.
6403    // The CPU dispatcher (`default_cost_for_op_kind`) captures the
6404    // FLOP/bandwidth model; backend-specific kernel_overhead_ns
6405    // adjustments are deferred to a Vulkan-flavored dispatcher (or to
6406    // the empirical calibration framework). Every entry above started
6407    // at `unknown_cost`; this pass upgrades them to a real cost
6408    // function so the optimizer's cost-ranking can admit Vulkan
6409    // alternatives.
6410    table.fill_unset_cost_for_backend(vk, fuel_dispatch::cost::default_cost_for_op_kind);
6411}
6412
6413// ===========================================================================
6414// FKC contract-migration tests (born-red gate for the Vulkan cast family)
6415// ===========================================================================
6416//
6417// This whole crate is the Vulkan crate (the file used to carry `#![cfg(feature = "vulkan")]`), so this module always compiles
6418// and no device is touched (registration is pure
6419// binding-table population; `register_vulkan_kernels` never probes hardware).
6420
6421/// Split-KV heuristic for the Vulkan flash-attention routes (f32, bf16, f16;
6422/// ROADMAP 17, H12). `Some(splits)` only for a decode step (`sq == 1`) whose
6423/// `b * hq` workgroups leave the GPU underfilled and whose key range is long
6424/// enough to pay for the second dispatch. Thresholds come from
6425/// `docs/research/split-kv-decode-measurement.md` (RTX 4070 Laptop, D=128,
6426/// one run per cell, about +-15% spread): f32 1.3-1.9x at `b*hq <= 8`,
6427/// `Sk >= 2048`; bf16/f16 1.3-1.8x at `b*hq <= 16` for `Sk >= 2048`; about
6428/// 1.15x at 32-64 heads (not taken: the merge reorders float adds, so the
6429/// split path is only used where it clearly wins); no gain at `Sk = 1024`.
6430/// One device: a prior, not a tuned value.
6431fn decode_splits(b: usize, hq: usize, sq: usize, sk: usize) -> Option<usize> {
6432    const MAX_ROWS: usize = 16;
6433    const MIN_SK: usize = 2048;
6434    const SPLITS: usize = 8;
6435    if sq == 1 && b * hq <= MAX_ROWS && (MIN_SK..=4096).contains(&sk) {
6436        Some(SPLITS)
6437    } else {
6438        None
6439    }
6440}
6441
6442#[cfg(test)]
6443mod decode_splits_tests {
6444    use super::decode_splits;
6445
6446    #[test]
6447    fn splits_only_underfilled_long_decode() {
6448        // Measured wins: few heads, long cache, decode.
6449        assert_eq!(decode_splits(1, 8, 1, 4096), Some(8));
6450        assert_eq!(decode_splits(1, 8, 1, 2048), Some(8));
6451        // Sabotage siblings: each condition alone must flip the answer.
6452        assert_eq!(decode_splits(1, 8, 2, 4096), None, "prefill");
6453        assert_eq!(decode_splits(1, 8, 1, 1024), None, "short cache");
6454        assert_eq!(decode_splits(1, 32, 1, 4096), None, "heads fill the GPU");
6455        assert_eq!(decode_splits(4, 8, 1, 4096), None, "batch fills the GPU");
6456        assert_eq!(decode_splits(1, 8, 1, 4097), None, "beyond the kernel cap");
6457    }
6458
6459    #[test]
6460    fn chosen_splits_satisfy_the_wrapper_chunk_limit() {
6461        for sk in 1..=4200 {
6462            if let Some(n) = decode_splits(1, 8, 1, sk) {
6463                assert!(sk.div_ceil(n) <= 1024 && (1..=64).contains(&n), "sk={sk}");
6464            }
6465        }
6466    }
6467}
6468
6469#[cfg(test)]
6470mod cast_contract_tests {
6471    use super::*;
6472    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
6473
6474    /// FIRST VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
6475    /// registers the whole `OpKind::Cast` family (12 (SRC, DST) pairs) FROM ITS
6476    /// KERNEL CONTRACT (`fuel-dispatch/kernel-contracts/vulkan/cast.fkc.md`) via
6477    /// `register_vulkan_cast_from_contract` — the sole registration path, now
6478    /// that the hand-written `table.register_with_precision(OpKind::Cast, …)`
6479    /// calls (half/f64 + F8E4M3) are DELETED.
6480    ///
6481    /// For each `(Cast, [SRC, DST], Vulkan)` key this asserts:
6482    ///  - the binding resolves to the EXACT production wrapper fn-pointer
6483    ///    (behavior-preserving execution — the SAME 3 wrappers the deleted regs
6484    ///    used, several pairs sharing one wrapper),
6485    ///  - `kernel_source == "vulkan-slang"` — the contract's provenance tag (the
6486    ///    deleted hand-written path stamped `""`). THIS is the discriminator
6487    ///    that makes the test go red without the import wired: with the
6488    ///    hand-written cast regs removed and the import absent, the family is
6489    ///    simply missing from the table (lookup finds 0 alternatives),
6490    ///  - caps stay contiguous-only (`strided_input == false`).
6491    ///
6492    /// Precision is contract-sourced and correctly lowered per FKC §4.8, so it
6493    /// is NOT asserted uniformly here: the 5 `audited: true` sections carry
6494    /// `bit_stable_on_same_hardware`, while the 7 `audited: false` author-seed
6495    /// sections lower to `PrecisionGuarantee::UNAUDITED` (bit_stable=false) —
6496    /// the correct "no audited claim yet" posture, which DIFFERS from the
6497    /// retired hand-written `VULKAN_CAST_PRECISION` (which asserted bit-stable +
6498    /// `max_ulp: Some(0)` uniformly). The Judge audits the seeds later.
6499    #[test]
6500    fn register_vulkan_kernels_binds_cast_family_from_contract() {
6501        let mut table = KernelBindingTable::new();
6502        register_vulkan_kernels(&mut table);
6503        let vk = BackendId::Vulkan;
6504
6505        // (SRC, DST, expected production wrapper) for all 12 cast pairs — the
6506        // exact wrapper each deleted hand-written reg carried.
6507        let cases: &[(DType, DType, KernelRef)] = &[
6508            (DType::F32, DType::F16, cast::cast_f32_half),
6509            (DType::F16, DType::F32, cast::cast_f32_half),
6510            (DType::F32, DType::BF16, cast::cast_f32_half),
6511            (DType::BF16, DType::F32, cast::cast_f32_half),
6512            (DType::F32, DType::F64, cast::cast_f32_f64),
6513            (DType::F64, DType::F32, cast::cast_f32_f64),
6514            (DType::F32, DType::F8E4M3, cast_f8e4m3::cast_f8e4m3),
6515            (DType::F8E4M3, DType::F32, cast_f8e4m3::cast_f8e4m3),
6516            (DType::F16, DType::F8E4M3, cast_f8e4m3::cast_f8e4m3),
6517            (DType::F8E4M3, DType::F16, cast_f8e4m3::cast_f8e4m3),
6518            (DType::BF16, DType::F8E4M3, cast_f8e4m3::cast_f8e4m3),
6519            (DType::F8E4M3, DType::BF16, cast_f8e4m3::cast_f8e4m3),
6520        ];
6521
6522        let mut checked = 0usize;
6523        for (src, dst, expected) in cases {
6524            let alts = table.lookup_alternatives(OpKind::Cast, &[*src, *dst], vk);
6525            let entry = alts
6526                .iter()
6527                .find(|e| e.kernel as usize == *expected as usize)
6528                .unwrap_or_else(|| {
6529                    panic!(
6530                        "Cast [{src:?}, {dst:?}]/Vulkan: the production wrapper must be bound \
6531                         FROM the vulkan cast contract in register_vulkan_kernels — found {} \
6532                         alternative(s) with sources {:?}",
6533                        alts.len(),
6534                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
6535                    )
6536                });
6537            assert_eq!(
6538                entry.kernel_source, "vulkan-slang",
6539                "Cast [{src:?}, {dst:?}]: cast family must be contract-sourced \
6540                 (kernel_source=\"vulkan-slang\"); got {:?}",
6541                entry.kernel_source,
6542            );
6543            assert!(
6544                !entry.caps.strided_input,
6545                "Cast [{src:?}, {dst:?}]: caps preserved (contiguous-only, strided_input=false)",
6546            );
6547            checked += 1;
6548        }
6549        assert_eq!(checked, 12, "all 12 (SRC, DST) cast pairs checked");
6550    }
6551}
6552
6553// ===========================================================================
6554// FKC contract-migration tests (born-red gate for the Vulkan elementwise family)
6555// ===========================================================================
6556//
6557// Same always-on gating (this crate IS the Vulkan crate) as the cast tests above: this
6558// module always compiles (this crate has no feature gate) and touches NO device
6559// (registration is pure binding-table population).
6560
6561#[cfg(test)]
6562mod elementwise_contract_tests {
6563    use super::*;
6564    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
6565
6566    /// SECOND VULKAN-BACKEND FKC CONSUMER (born-red gate) + the FIRST
6567    /// caps-through-import proof. `register_vulkan_kernels` registers the whole
6568    /// elementwise family (94 (op, dtype) bindings) FROM ITS RE-AUTHORED KERNEL
6569    /// CONTRACT (`fuel-dispatch/kernel-contracts/vulkan/elementwise.fkc.md`) via
6570    /// `register_vulkan_elementwise_from_contract` -- the sole registration path,
6571    /// now that the hand-written per-(op,dtype) unary(16)/binary(6)/affine/clamp/
6572    /// powi regs are DELETED.
6573    ///
6574    /// For each `(OpKind, [T..], Vulkan)` key this asserts: the binding resolves
6575    /// to the EXACT production wrapper fn-pointer (behavior-preserving); the
6576    /// `kernel_source == "vulkan-slang"` (the RED discriminator -- the deleted
6577    /// hand path stamped `""`); and `caps.strided_input` MATCHES THE HAND-WRITTEN
6578    /// TRUTH PER KEY -- true for the strided unary(f32/f16/f64)/binary(all 4)/
6579    /// affine(f32/f16/f64)/clamp/powi keys, false for the contiguous-only
6580    /// bf16-unary / affine_bf16 keys. That last assertion is the
6581    /// caps-through-import proof: the contract's per-operand five-flag layout
6582    /// projects onto the binding's `KernelCaps.strided_input` exactly as the hand
6583    /// path set it. Precision is contract-sourced (`audited: false` -> UNAUDITED,
6584    /// the cast-migration precedent) and NOT asserted here.
6585    #[test]
6586    fn register_vulkan_kernels_binds_elementwise_family_from_contract() {
6587        let mut table = KernelBindingTable::new();
6588        register_vulkan_kernels(&mut table);
6589        let vk = BackendId::Vulkan;
6590
6591        // (OpKind, key dtypes, expected production wrapper, expected strided_input)
6592        let cases: &[(OpKind, &[DType], KernelRef, bool)] = &[
6593            // ---- Unary: 16 ops x {f32,f16,f64 strided; bf16 contiguous} -- key [T, T]. ----
6594            (
6595                OpKind::NegElementwise,
6596                &[DType::F32, DType::F32],
6597                unary::neg_f32 as KernelRef,
6598                true,
6599            ),
6600            (
6601                OpKind::NegElementwise,
6602                &[DType::F16, DType::F16],
6603                unary_f16::neg_f16 as KernelRef,
6604                true,
6605            ),
6606            (
6607                OpKind::NegElementwise,
6608                &[DType::F64, DType::F64],
6609                unary_f64::neg_f64 as KernelRef,
6610                true,
6611            ),
6612            (
6613                OpKind::NegElementwise,
6614                &[DType::BF16, DType::BF16],
6615                unary_bf16::neg_bf16 as KernelRef,
6616                false,
6617            ),
6618            (
6619                OpKind::SqrElementwise,
6620                &[DType::F32, DType::F32],
6621                unary::sqr_f32 as KernelRef,
6622                true,
6623            ),
6624            (
6625                OpKind::SqrElementwise,
6626                &[DType::F16, DType::F16],
6627                unary_f16::sqr_f16 as KernelRef,
6628                true,
6629            ),
6630            (
6631                OpKind::SqrElementwise,
6632                &[DType::F64, DType::F64],
6633                unary_f64::sqr_f64 as KernelRef,
6634                true,
6635            ),
6636            (
6637                OpKind::SqrElementwise,
6638                &[DType::BF16, DType::BF16],
6639                unary_bf16::sqr_bf16 as KernelRef,
6640                false,
6641            ),
6642            (
6643                OpKind::SqrtElementwise,
6644                &[DType::F32, DType::F32],
6645                unary::sqrt_f32 as KernelRef,
6646                true,
6647            ),
6648            (
6649                OpKind::SqrtElementwise,
6650                &[DType::F16, DType::F16],
6651                unary_f16::sqrt_f16 as KernelRef,
6652                true,
6653            ),
6654            (
6655                OpKind::SqrtElementwise,
6656                &[DType::F64, DType::F64],
6657                unary_f64::sqrt_f64 as KernelRef,
6658                true,
6659            ),
6660            (
6661                OpKind::SqrtElementwise,
6662                &[DType::BF16, DType::BF16],
6663                unary_bf16::sqrt_bf16 as KernelRef,
6664                false,
6665            ),
6666            (
6667                OpKind::ExpElementwise,
6668                &[DType::F32, DType::F32],
6669                unary::exp_f32 as KernelRef,
6670                true,
6671            ),
6672            (
6673                OpKind::ExpElementwise,
6674                &[DType::F16, DType::F16],
6675                unary_f16::exp_f16 as KernelRef,
6676                true,
6677            ),
6678            (
6679                OpKind::ExpElementwise,
6680                &[DType::F64, DType::F64],
6681                unary_f64::exp_f64 as KernelRef,
6682                true,
6683            ),
6684            (
6685                OpKind::ExpElementwise,
6686                &[DType::BF16, DType::BF16],
6687                unary_bf16::exp_bf16 as KernelRef,
6688                false,
6689            ),
6690            (
6691                OpKind::LogElementwise,
6692                &[DType::F32, DType::F32],
6693                unary::log_f32 as KernelRef,
6694                true,
6695            ),
6696            (
6697                OpKind::LogElementwise,
6698                &[DType::F16, DType::F16],
6699                unary_f16::log_f16 as KernelRef,
6700                true,
6701            ),
6702            (
6703                OpKind::LogElementwise,
6704                &[DType::F64, DType::F64],
6705                unary_f64::log_f64 as KernelRef,
6706                true,
6707            ),
6708            (
6709                OpKind::LogElementwise,
6710                &[DType::BF16, DType::BF16],
6711                unary_bf16::log_bf16 as KernelRef,
6712                false,
6713            ),
6714            (
6715                OpKind::SinElementwise,
6716                &[DType::F32, DType::F32],
6717                unary::sin_f32 as KernelRef,
6718                true,
6719            ),
6720            (
6721                OpKind::SinElementwise,
6722                &[DType::F16, DType::F16],
6723                unary_f16::sin_f16 as KernelRef,
6724                true,
6725            ),
6726            (
6727                OpKind::SinElementwise,
6728                &[DType::F64, DType::F64],
6729                unary_f64::sin_f64 as KernelRef,
6730                true,
6731            ),
6732            (
6733                OpKind::SinElementwise,
6734                &[DType::BF16, DType::BF16],
6735                unary_bf16::sin_bf16 as KernelRef,
6736                false,
6737            ),
6738            (
6739                OpKind::CosElementwise,
6740                &[DType::F32, DType::F32],
6741                unary::cos_f32 as KernelRef,
6742                true,
6743            ),
6744            (
6745                OpKind::CosElementwise,
6746                &[DType::F16, DType::F16],
6747                unary_f16::cos_f16 as KernelRef,
6748                true,
6749            ),
6750            (
6751                OpKind::CosElementwise,
6752                &[DType::F64, DType::F64],
6753                unary_f64::cos_f64 as KernelRef,
6754                true,
6755            ),
6756            (
6757                OpKind::CosElementwise,
6758                &[DType::BF16, DType::BF16],
6759                unary_bf16::cos_bf16 as KernelRef,
6760                false,
6761            ),
6762            (
6763                OpKind::TanhElementwise,
6764                &[DType::F32, DType::F32],
6765                unary::tanh_f32 as KernelRef,
6766                true,
6767            ),
6768            (
6769                OpKind::TanhElementwise,
6770                &[DType::F16, DType::F16],
6771                unary_f16::tanh_f16 as KernelRef,
6772                true,
6773            ),
6774            (
6775                OpKind::TanhElementwise,
6776                &[DType::F64, DType::F64],
6777                unary_f64::tanh_f64 as KernelRef,
6778                true,
6779            ),
6780            (
6781                OpKind::TanhElementwise,
6782                &[DType::BF16, DType::BF16],
6783                unary_bf16::tanh_bf16 as KernelRef,
6784                false,
6785            ),
6786            (
6787                OpKind::SigmoidElementwise,
6788                &[DType::F32, DType::F32],
6789                unary::sigmoid_f32 as KernelRef,
6790                true,
6791            ),
6792            (
6793                OpKind::SigmoidElementwise,
6794                &[DType::F16, DType::F16],
6795                unary_f16::sigmoid_f16 as KernelRef,
6796                true,
6797            ),
6798            (
6799                OpKind::SigmoidElementwise,
6800                &[DType::F64, DType::F64],
6801                unary_f64::sigmoid_f64 as KernelRef,
6802                true,
6803            ),
6804            (
6805                OpKind::SigmoidElementwise,
6806                &[DType::BF16, DType::BF16],
6807                unary_bf16::sigmoid_bf16 as KernelRef,
6808                false,
6809            ),
6810            (
6811                OpKind::SiluElementwise,
6812                &[DType::F32, DType::F32],
6813                unary::silu_f32 as KernelRef,
6814                true,
6815            ),
6816            (
6817                OpKind::SiluElementwise,
6818                &[DType::F16, DType::F16],
6819                unary_f16::silu_f16 as KernelRef,
6820                true,
6821            ),
6822            (
6823                OpKind::SiluElementwise,
6824                &[DType::F64, DType::F64],
6825                unary_f64::silu_f64 as KernelRef,
6826                true,
6827            ),
6828            (
6829                OpKind::SiluElementwise,
6830                &[DType::BF16, DType::BF16],
6831                unary_bf16::silu_bf16 as KernelRef,
6832                false,
6833            ),
6834            (
6835                OpKind::GeluTanhElementwise,
6836                &[DType::F32, DType::F32],
6837                unary::gelu_f32 as KernelRef,
6838                true,
6839            ),
6840            (
6841                OpKind::GeluTanhElementwise,
6842                &[DType::F16, DType::F16],
6843                unary_f16::gelu_f16 as KernelRef,
6844                true,
6845            ),
6846            (
6847                OpKind::GeluTanhElementwise,
6848                &[DType::F64, DType::F64],
6849                unary_f64::gelu_f64 as KernelRef,
6850                true,
6851            ),
6852            (
6853                OpKind::GeluTanhElementwise,
6854                &[DType::BF16, DType::BF16],
6855                unary_bf16::gelu_bf16 as KernelRef,
6856                false,
6857            ),
6858            (
6859                OpKind::ReluElementwise,
6860                &[DType::F32, DType::F32],
6861                unary::relu_f32 as KernelRef,
6862                true,
6863            ),
6864            (
6865                OpKind::ReluElementwise,
6866                &[DType::F16, DType::F16],
6867                unary_f16::relu_f16 as KernelRef,
6868                true,
6869            ),
6870            (
6871                OpKind::ReluElementwise,
6872                &[DType::F64, DType::F64],
6873                unary_f64::relu_f64 as KernelRef,
6874                true,
6875            ),
6876            (
6877                OpKind::ReluElementwise,
6878                &[DType::BF16, DType::BF16],
6879                unary_bf16::relu_bf16 as KernelRef,
6880                false,
6881            ),
6882            (
6883                OpKind::StepElementwise,
6884                &[DType::F32, DType::F32],
6885                unary::step_f32 as KernelRef,
6886                true,
6887            ),
6888            (
6889                OpKind::StepElementwise,
6890                &[DType::F16, DType::F16],
6891                unary_f16::step_f16 as KernelRef,
6892                true,
6893            ),
6894            (
6895                OpKind::StepElementwise,
6896                &[DType::F64, DType::F64],
6897                unary_f64::step_f64 as KernelRef,
6898                true,
6899            ),
6900            (
6901                OpKind::StepElementwise,
6902                &[DType::BF16, DType::BF16],
6903                unary_bf16::step_bf16 as KernelRef,
6904                false,
6905            ),
6906            (
6907                OpKind::AbsElementwise,
6908                &[DType::F32, DType::F32],
6909                unary::abs_f32 as KernelRef,
6910                true,
6911            ),
6912            (
6913                OpKind::AbsElementwise,
6914                &[DType::F16, DType::F16],
6915                unary_f16::abs_f16 as KernelRef,
6916                true,
6917            ),
6918            (
6919                OpKind::AbsElementwise,
6920                &[DType::F64, DType::F64],
6921                unary_f64::abs_f64 as KernelRef,
6922                true,
6923            ),
6924            (
6925                OpKind::AbsElementwise,
6926                &[DType::BF16, DType::BF16],
6927                unary_bf16::abs_bf16 as KernelRef,
6928                false,
6929            ),
6930            (
6931                OpKind::SignElementwise,
6932                &[DType::F32, DType::F32],
6933                unary::sign_f32 as KernelRef,
6934                true,
6935            ),
6936            (
6937                OpKind::SignElementwise,
6938                &[DType::F16, DType::F16],
6939                unary_f16::sign_f16 as KernelRef,
6940                true,
6941            ),
6942            (
6943                OpKind::SignElementwise,
6944                &[DType::F64, DType::F64],
6945                unary_f64::sign_f64 as KernelRef,
6946                true,
6947            ),
6948            (
6949                OpKind::SignElementwise,
6950                &[DType::BF16, DType::BF16],
6951                unary_bf16::sign_bf16 as KernelRef,
6952                false,
6953            ),
6954            (
6955                OpKind::RecipElementwise,
6956                &[DType::F32, DType::F32],
6957                unary::recip_f32 as KernelRef,
6958                true,
6959            ),
6960            (
6961                OpKind::RecipElementwise,
6962                &[DType::F16, DType::F16],
6963                unary_f16::recip_f16 as KernelRef,
6964                true,
6965            ),
6966            (
6967                OpKind::RecipElementwise,
6968                &[DType::F64, DType::F64],
6969                unary_f64::recip_f64 as KernelRef,
6970                true,
6971            ),
6972            (
6973                OpKind::RecipElementwise,
6974                &[DType::BF16, DType::BF16],
6975                unary_bf16::recip_bf16 as KernelRef,
6976                false,
6977            ),
6978            // ---- Binary: 6 ops x {f32,f16,f64,bf16} all strided -- key [T, T, T]. ----
6979            (
6980                OpKind::AddElementwise,
6981                &[DType::F32, DType::F32, DType::F32],
6982                binary::add_f32 as KernelRef,
6983                true,
6984            ),
6985            (
6986                OpKind::AddElementwise,
6987                &[DType::F16, DType::F16, DType::F16],
6988                binary_f16::add_f16 as KernelRef,
6989                true,
6990            ),
6991            (
6992                OpKind::AddElementwise,
6993                &[DType::F64, DType::F64, DType::F64],
6994                binary_f64::add_f64 as KernelRef,
6995                true,
6996            ),
6997            (
6998                OpKind::AddElementwise,
6999                &[DType::BF16, DType::BF16, DType::BF16],
7000                binary_bf16::add_bf16 as KernelRef,
7001                true,
7002            ),
7003            (
7004                OpKind::SubElementwise,
7005                &[DType::F32, DType::F32, DType::F32],
7006                binary::sub_f32 as KernelRef,
7007                true,
7008            ),
7009            (
7010                OpKind::SubElementwise,
7011                &[DType::F16, DType::F16, DType::F16],
7012                binary_f16::sub_f16 as KernelRef,
7013                true,
7014            ),
7015            (
7016                OpKind::SubElementwise,
7017                &[DType::F64, DType::F64, DType::F64],
7018                binary_f64::sub_f64 as KernelRef,
7019                true,
7020            ),
7021            (
7022                OpKind::SubElementwise,
7023                &[DType::BF16, DType::BF16, DType::BF16],
7024                binary_bf16::sub_bf16 as KernelRef,
7025                true,
7026            ),
7027            (
7028                OpKind::MulElementwise,
7029                &[DType::F32, DType::F32, DType::F32],
7030                binary::mul_f32 as KernelRef,
7031                true,
7032            ),
7033            (
7034                OpKind::MulElementwise,
7035                &[DType::F16, DType::F16, DType::F16],
7036                binary_f16::mul_f16 as KernelRef,
7037                true,
7038            ),
7039            (
7040                OpKind::MulElementwise,
7041                &[DType::F64, DType::F64, DType::F64],
7042                binary_f64::mul_f64 as KernelRef,
7043                true,
7044            ),
7045            (
7046                OpKind::MulElementwise,
7047                &[DType::BF16, DType::BF16, DType::BF16],
7048                binary_bf16::mul_bf16 as KernelRef,
7049                true,
7050            ),
7051            (
7052                OpKind::DivElementwise,
7053                &[DType::F32, DType::F32, DType::F32],
7054                binary::div_f32 as KernelRef,
7055                true,
7056            ),
7057            (
7058                OpKind::DivElementwise,
7059                &[DType::F16, DType::F16, DType::F16],
7060                binary_f16::div_f16 as KernelRef,
7061                true,
7062            ),
7063            (
7064                OpKind::DivElementwise,
7065                &[DType::F64, DType::F64, DType::F64],
7066                binary_f64::div_f64 as KernelRef,
7067                true,
7068            ),
7069            (
7070                OpKind::DivElementwise,
7071                &[DType::BF16, DType::BF16, DType::BF16],
7072                binary_bf16::div_bf16 as KernelRef,
7073                true,
7074            ),
7075            (
7076                OpKind::MaximumElementwise,
7077                &[DType::F32, DType::F32, DType::F32],
7078                binary::maximum_f32 as KernelRef,
7079                true,
7080            ),
7081            (
7082                OpKind::MaximumElementwise,
7083                &[DType::F16, DType::F16, DType::F16],
7084                binary_f16::maximum_f16 as KernelRef,
7085                true,
7086            ),
7087            (
7088                OpKind::MaximumElementwise,
7089                &[DType::F64, DType::F64, DType::F64],
7090                binary_f64::maximum_f64 as KernelRef,
7091                true,
7092            ),
7093            (
7094                OpKind::MaximumElementwise,
7095                &[DType::BF16, DType::BF16, DType::BF16],
7096                binary_bf16::maximum_bf16 as KernelRef,
7097                true,
7098            ),
7099            (
7100                OpKind::MinimumElementwise,
7101                &[DType::F32, DType::F32, DType::F32],
7102                binary::minimum_f32 as KernelRef,
7103                true,
7104            ),
7105            (
7106                OpKind::MinimumElementwise,
7107                &[DType::F16, DType::F16, DType::F16],
7108                binary_f16::minimum_f16 as KernelRef,
7109                true,
7110            ),
7111            (
7112                OpKind::MinimumElementwise,
7113                &[DType::F64, DType::F64, DType::F64],
7114                binary_f64::minimum_f64 as KernelRef,
7115                true,
7116            ),
7117            (
7118                OpKind::MinimumElementwise,
7119                &[DType::BF16, DType::BF16, DType::BF16],
7120                binary_bf16::minimum_bf16 as KernelRef,
7121                true,
7122            ),
7123            // ---- Affine: f32/f16/f64 strided + bf16 contiguous -- key [T, T]. ----
7124            (
7125                OpKind::Affine,
7126                &[DType::F32, DType::F32],
7127                affine::affine_f32 as KernelRef,
7128                true,
7129            ),
7130            (
7131                OpKind::Affine,
7132                &[DType::F16, DType::F16],
7133                affine::affine_f16 as KernelRef,
7134                true,
7135            ),
7136            (
7137                OpKind::Affine,
7138                &[DType::F64, DType::F64],
7139                affine::affine_f64 as KernelRef,
7140                true,
7141            ),
7142            (
7143                OpKind::Affine,
7144                &[DType::BF16, DType::BF16],
7145                affine::affine_bf16 as KernelRef,
7146                false,
7147            ),
7148            // ---- Clamp / PowI: single-dtype f32 strided -- key [T, T]. ----
7149            (
7150                OpKind::ClampElementwise,
7151                &[DType::F32, DType::F32],
7152                clamp::clamp_f32 as KernelRef,
7153                true,
7154            ),
7155            (
7156                OpKind::PowIElementwise,
7157                &[DType::F32, DType::F32],
7158                powi::powi_f32 as KernelRef,
7159                true,
7160            ),
7161        ];
7162
7163        let mut checked = 0usize;
7164        for (op, key, expected, expect_strided) in cases {
7165            let alts = table.lookup_alternatives(*op, key, vk);
7166            let entry = alts
7167                .iter()
7168                .find(|e| e.kernel as usize == *expected as usize);
7169            let entry = match entry {
7170                Some(e) => e,
7171                None => panic!(
7172                    "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan elementwise contract; found {} alt(s) with sources {:?}",
7173                    alts.len(),
7174                    alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7175                ),
7176            };
7177            assert_eq!(
7178                entry.kernel_source, "vulkan-slang",
7179                "{op:?} {key:?}: elementwise family must be contract-sourced (kernel_source=vulkan-slang); got {:?}",
7180                entry.kernel_source,
7181            );
7182            assert_eq!(
7183                entry.caps.strided_input, *expect_strided,
7184                "{op:?} {key:?}: caps must ride through the import truthfully (strided_input matches the hand-written reg)",
7185            );
7186            checked += 1;
7187        }
7188        assert_eq!(
7189            checked, 94,
7190            "all 94 (op, dtype) elementwise bindings checked"
7191        );
7192    }
7193}
7194
7195// ===========================================================================
7196// FKC contract-migration tests (born-red gate for the Vulkan matmul family)
7197// ===========================================================================
7198//
7199// Same always-on gating (this crate IS the Vulkan crate) as the cast / elementwise tests
7200// above: this module always compiles (this crate has no feature gate) and touches NO
7201// device (registration is pure binding-table population).
7202
7203#[cfg(test)]
7204mod matmul_contract_tests {
7205    use super::*;
7206    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7207
7208    /// THIRD VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7209    /// registers the whole Vulkan matmul family (6 per-combo `(MatMul, [lhs,rhs,out])`
7210    /// bindings) FROM ITS RE-AUTHORED KERNEL CONTRACT
7211    /// (`fuel-dispatch/kernel-contracts/vulkan/matmul.fkc.md`) via
7212    /// `register_vulkan_matmul_from_contract` — the sole registration path, now
7213    /// that the hand-written `table.register_with_precision(OpKind::MatMul, …)`
7214    /// regs (the f32 GEMM + the five mixed-precision / tensor-core combos) are
7215    /// DELETED.
7216    ///
7217    /// This ALSO dissolves the `dispatch/matmul.fkc.md :: matmul_mixed_precision`
7218    /// multi-axis `FanoutDtypeMismatch` corpus deferral: the aspirational single
7219    /// multi-dtype section (lhs `[F32,BF16,F16]` vs rhs `[BF16,F16]`) is replaced
7220    /// by EXPLICIT single-dtype-per-operand per-combo sections, exactly the cast
7221    /// family's per-pair precedent.
7222    ///
7223    /// For each `(MatMul, [lhs,rhs,out], Vulkan)` key this asserts: the binding
7224    /// resolves to the EXACT production wrapper fn-pointer (behavior-preserving);
7225    /// `kernel_source == "vulkan-slang"` (the RED discriminator — the deleted hand
7226    /// path stamped `""`, so before the import is wired this assert fails on the
7227    /// empty source); and `caps.strided_input == false` — the contiguous-only
7228    /// truth of the deleted `register_with_precision` regs (the coop / vec4 loads
7229    /// require canonical row-major, so a strided operand is auto-Contiguized
7230    /// first). Precision is contract-sourced (the cast/elementwise precedent) and
7231    /// NOT asserted here.
7232    #[test]
7233    fn register_vulkan_kernels_binds_matmul_family_from_contract() {
7234        let mut table = KernelBindingTable::new();
7235        register_vulkan_kernels(&mut table);
7236        let vk = BackendId::Vulkan;
7237
7238        // (key dtypes [lhs, rhs, out], expected production wrapper). Every matmul
7239        // binding is contiguous-only (strided_input == false), so that is checked
7240        // uniformly below rather than per-row.
7241        let cases: &[(&[DType], KernelRef)] = &[
7242            (
7243                &[DType::F32, DType::F32, DType::F32],
7244                matmul::matmul_f32 as KernelRef,
7245            ),
7246            (
7247                &[DType::F32, DType::BF16, DType::F32],
7248                matmul::matmul_f32_bf16_b as KernelRef,
7249            ),
7250            (
7251                &[DType::BF16, DType::BF16, DType::F32],
7252                matmul::matmul_bf16_bf16_f32 as KernelRef,
7253            ),
7254            (
7255                &[DType::BF16, DType::BF16, DType::BF16],
7256                matmul::matmul_bf16_bf16_bf16 as KernelRef,
7257            ),
7258            (
7259                &[DType::F16, DType::F16, DType::F16],
7260                matmul::matmul_f16_f16_f16 as KernelRef,
7261            ),
7262            (
7263                &[DType::F16, DType::F16, DType::F32],
7264                matmul::matmul_f16_f16_f32 as KernelRef,
7265            ),
7266        ];
7267
7268        let mut checked = 0usize;
7269        for (key, expected) in cases {
7270            let alts = table.lookup_alternatives(OpKind::MatMul, key, vk);
7271            let entry = alts
7272                .iter()
7273                .find(|e| e.kernel as usize == *expected as usize);
7274            let entry = match entry {
7275                Some(e) => e,
7276                None => panic!(
7277                    "MatMul {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7278                     matmul contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7279                    alts.len(),
7280                    alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7281                ),
7282            };
7283            assert_eq!(
7284                entry.kernel_source, "vulkan-slang",
7285                "MatMul {key:?}: matmul family must be contract-sourced \
7286                 (kernel_source=\"vulkan-slang\"); got {:?}",
7287                entry.kernel_source,
7288            );
7289            assert!(
7290                !entry.caps.strided_input,
7291                "MatMul {key:?}: caps preserved (contiguous-only, strided_input=false)",
7292            );
7293            checked += 1;
7294        }
7295        assert_eq!(
7296            checked, 6,
7297            "all 6 (MatMul, [lhs,rhs,out]) Vulkan combos checked"
7298        );
7299    }
7300}
7301
7302// ===========================================================================
7303// FKC contract-migration tests (born-red gate for the Vulkan conv2d family)
7304// ===========================================================================
7305//
7306// Same always-on gating (this crate IS the Vulkan crate) as the cast/elementwise/matmul
7307// tests above: this module always compiles (this crate has no feature gate) and touches
7308// NO device (registration is pure binding-table population).
7309
7310#[cfg(test)]
7311mod conv_contract_tests {
7312    use super::*;
7313    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7314
7315    /// FOURTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7316    /// registers the whole Vulkan conv2d family (3 per-(op, dtype) `(Conv2D,
7317    /// [x, weight, out])` bindings) FROM ITS RE-AUTHORED KERNEL CONTRACT
7318    /// (`fuel-dispatch/kernel-contracts/vulkan/conv.fkc.md`) via
7319    /// `register_vulkan_conv_from_contract` — the sole registration path, now that
7320    /// the hand-written `table.register_with_precision(OpKind::Conv2D, …)` regs
7321    /// (f32 / bf16 / f16) are DELETED.
7322    ///
7323    /// The corpus's `vulkan/conv-attn-rope.fkc.md` describes conv2d as an
7324    /// ASPIRATIONAL `fused_op: CONV2D` **im2col STAGE** (`conv2d_im2col_f32` /
7325    /// `conv2d_im2col_bf16`, output = the patches matrix), which is NOT what
7326    /// production registers: production registers a PRIMITIVE `OpKind::Conv2D`
7327    /// binding whose wrapper (`conv2d::conv2d_f32` → `VulkanBackend::conv2d_*_bytes`)
7328    /// runs the WHOLE conv (im2col + matmul internally). This mirrors the matmul
7329    /// migration (aspirational `matmul_mixed_precision` chassis superseded by
7330    /// EXPLICIT per-combo `op_kind` sections in the production `vulkan/matmul.fkc.md`).
7331    ///
7332    /// For each `(Conv2D, [x, weight, out], Vulkan)` key this asserts: the binding
7333    /// resolves to the EXACT production wrapper fn-pointer (behavior-preserving);
7334    /// `kernel_source == "vulkan-slang"` (the RED discriminator — the deleted hand
7335    /// path stamped `""`, so before the import is wired this assert fails on the
7336    /// empty source); and `caps.strided_input == false` — the contiguous-only truth
7337    /// of the deleted `register_with_precision` regs (conv2d_im2col reads NCHW with
7338    /// canonical strides, so a strided operand is auto-Contiguized first). No bias
7339    /// key is registered: the Vulkan wrappers bail on a 3-input (bias) call, so the
7340    /// contract declares NO optional bias operand and each section keys ONLY the
7341    /// 3-slot `[x, weight, out]` (unlike the CPU conv contract's optional-bias dual
7342    /// key). Precision is contract-sourced (the cast/elementwise/matmul precedent)
7343    /// and NOT asserted here.
7344    #[test]
7345    fn register_vulkan_kernels_binds_conv_family_from_contract() {
7346        let mut table = KernelBindingTable::new();
7347        register_vulkan_kernels(&mut table);
7348        let vk = BackendId::Vulkan;
7349
7350        // (key dtypes [x, weight, out], expected production wrapper). Every conv
7351        // binding is contiguous-only (strided_input == false), so that is checked
7352        // uniformly below rather than per-row.
7353        let cases: &[(&[DType], KernelRef)] = &[
7354            (
7355                &[DType::F32, DType::F32, DType::F32],
7356                conv2d::conv2d_f32 as KernelRef,
7357            ),
7358            (
7359                &[DType::BF16, DType::BF16, DType::BF16],
7360                conv2d::conv2d_bf16 as KernelRef,
7361            ),
7362            (
7363                &[DType::F16, DType::F16, DType::F16],
7364                conv2d::conv2d_f16 as KernelRef,
7365            ),
7366        ];
7367
7368        let mut checked = 0usize;
7369        for (key, expected) in cases {
7370            let alts = table.lookup_alternatives(OpKind::Conv2D, key, vk);
7371            let entry = alts
7372                .iter()
7373                .find(|e| e.kernel as usize == *expected as usize);
7374            let entry = match entry {
7375                Some(e) => e,
7376                None => panic!(
7377                    "Conv2D {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7378                     conv contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7379                    alts.len(),
7380                    alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7381                ),
7382            };
7383            assert_eq!(
7384                entry.kernel_source, "vulkan-slang",
7385                "Conv2D {key:?}: conv family must be contract-sourced \
7386                 (kernel_source=\"vulkan-slang\"); got {:?}",
7387                entry.kernel_source,
7388            );
7389            assert!(
7390                !entry.caps.strided_input,
7391                "Conv2D {key:?}: caps preserved (contiguous-only, strided_input=false)",
7392            );
7393            checked += 1;
7394        }
7395        assert_eq!(
7396            checked, 3,
7397            "all 3 (Conv2D, [x, weight, out]) Vulkan combos checked"
7398        );
7399    }
7400}
7401
7402// ===========================================================================
7403// FKC contract-migration tests (born-red gate for the Vulkan select family)
7404// ===========================================================================
7405//
7406// Same always-on gating (this crate IS the Vulkan crate): always compiles (this crate has no feature gate) and touches NO device (registration is pure binding-table
7407// population).
7408
7409#[cfg(test)]
7410mod select_contract_tests {
7411    use super::*;
7412    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7413
7414    /// FIFTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7415    /// registers the whole Vulkan **select** family — IndexSelect (4 per-dtype
7416    /// wrappers), Gather (6 dtype keys → the ONE `gather::gather` synthetic-base
7417    /// umbrella wrapper), MaskedFill (6 dtype keys → the ONE
7418    /// `masked_fill::masked_fill` umbrella wrapper) — FROM ITS FKC KERNEL CONTRACT
7419    /// (`fuel-dispatch/kernel-contracts/vulkan/select.fkc.md`) via
7420    /// `register_vulkan_select_from_contract`, the sole registration path now that
7421    /// the hand-written `register_with_precision(OpKind::{IndexSelect,Gather,
7422    /// MaskedFill}, …)` regs are DELETED.
7423    ///
7424    /// Per key: the binding resolves to the EXACT production wrapper fn-pointer
7425    /// (behavior-preserving; several Gather/MaskedFill keys share ONE wrapper, the
7426    /// pad_cpu synthetic-umbrella precedent); `kernel_source == "vulkan-slang"`
7427    /// (the RED discriminator — the deleted hand path stamped `""`); and
7428    /// `caps.strided_input == false` — the contiguous-only truth of the deleted
7429    /// plain `register_with_precision` regs (byte-level data movers read/write
7430    /// their own-shape flat buffers; a strided operand is auto-Contiguized first).
7431    /// Precision is contract-sourced (byte-exact `audited: true`, the cast/matmul
7432    /// precedent) and NOT asserted here.
7433    #[test]
7434    fn register_vulkan_kernels_binds_select_family_from_contract() {
7435        let mut table = KernelBindingTable::new();
7436        register_vulkan_kernels(&mut table);
7437        let vk = BackendId::Vulkan;
7438
7439        let f32 = DType::F32;
7440        let f16 = DType::F16;
7441        let bf16 = DType::BF16;
7442        let f64 = DType::F64;
7443        let u8 = DType::U8;
7444        let u32 = DType::U32;
7445        let boolean = DType::Bool;
7446
7447        // (OpKind, key dtypes, expected production wrapper). Every select binding
7448        // is contiguous-only (strided_input == false), checked uniformly below.
7449        let cases: &[(OpKind, &[DType], KernelRef)] = &[
7450            // IndexSelect: [source, U32, out]; 4 distinct per-dtype wrappers.
7451            (
7452                OpKind::IndexSelect,
7453                &[f32, u32, f32],
7454                indexing::index_select_f32 as KernelRef,
7455            ),
7456            (
7457                OpKind::IndexSelect,
7458                &[f16, u32, f16],
7459                indexing::index_select_f16 as KernelRef,
7460            ),
7461            (
7462                OpKind::IndexSelect,
7463                &[bf16, u32, bf16],
7464                indexing::index_select_bf16 as KernelRef,
7465            ),
7466            (
7467                OpKind::IndexSelect,
7468                &[f64, u32, f64],
7469                indexing::index_select_f64 as KernelRef,
7470            ),
7471            // Gather: [source, U32, out]; ONE dtype-agnostic wrapper across 6 keys.
7472            (
7473                OpKind::Gather,
7474                &[f32, u32, f32],
7475                gather::gather as KernelRef,
7476            ),
7477            (
7478                OpKind::Gather,
7479                &[f16, u32, f16],
7480                gather::gather as KernelRef,
7481            ),
7482            (
7483                OpKind::Gather,
7484                &[bf16, u32, bf16],
7485                gather::gather as KernelRef,
7486            ),
7487            (
7488                OpKind::Gather,
7489                &[f64, u32, f64],
7490                gather::gather as KernelRef,
7491            ),
7492            (OpKind::Gather, &[u8, u32, u8], gather::gather as KernelRef),
7493            (
7494                OpKind::Gather,
7495                &[u32, u32, u32],
7496                gather::gather as KernelRef,
7497            ),
7498            // MaskedFill: [data, BOOL mask, out]; ONE wrapper across 6 keys.
7499            //
7500            // The mask slot is `Bool`, NOT `U8`. GAP-168(c) moved it;
7501            // `Graph::masked_fill` enforces it at BUILD time
7502            // (fuel-graph/src/lib.rs:5716 — "`mask` must be `Bool`
7503            // (GAP-168(c))"), and all five backend contracts declare
7504            // `dtypes: [BOOL]`. This test still asserted the pre-Bool
7505            // `[T, U8, T]` key, so it looked up a binding that no longer exists
7506            // and reported `found 0 alt(s) with sources []` — which reads like a
7507            // MISSING REGISTRATION rather than a stale key, and cost a full
7508            // diagnostic pass to tell apart. The registration is fine: the
7509            // IndexSelect and Gather cases above import from the same contract
7510            // file and pass.
7511            //
7512            // It survived the Bool cut because it needs `--features vulkan`:
7513            // that sweep was gated with `--lib`, and CI could not build the
7514            // workspace at all, so nothing executed this until today.
7515            (
7516                OpKind::MaskedFill,
7517                &[f32, boolean, f32],
7518                masked_fill::masked_fill as KernelRef,
7519            ),
7520            (
7521                OpKind::MaskedFill,
7522                &[f16, boolean, f16],
7523                masked_fill::masked_fill as KernelRef,
7524            ),
7525            (
7526                OpKind::MaskedFill,
7527                &[bf16, boolean, bf16],
7528                masked_fill::masked_fill as KernelRef,
7529            ),
7530            (
7531                OpKind::MaskedFill,
7532                &[f64, boolean, f64],
7533                masked_fill::masked_fill as KernelRef,
7534            ),
7535            (
7536                OpKind::MaskedFill,
7537                &[u8, boolean, u8],
7538                masked_fill::masked_fill as KernelRef,
7539            ),
7540            (
7541                OpKind::MaskedFill,
7542                &[u32, boolean, u32],
7543                masked_fill::masked_fill as KernelRef,
7544            ),
7545        ];
7546
7547        let mut checked = 0usize;
7548        for (op, key, expected) in cases {
7549            let alts = table.lookup_alternatives(*op, key, vk);
7550            let entry = alts
7551                .iter()
7552                .find(|e| e.kernel as usize == *expected as usize);
7553            let entry = match entry {
7554                Some(e) => e,
7555                None => panic!(
7556                    "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7557                     select contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7558                    alts.len(),
7559                    alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7560                ),
7561            };
7562            assert_eq!(
7563                entry.kernel_source, "vulkan-slang",
7564                "{op:?} {key:?}: select family must be contract-sourced \
7565                 (kernel_source=\"vulkan-slang\"); got {:?}",
7566                entry.kernel_source,
7567            );
7568            assert!(
7569                !entry.caps.strided_input,
7570                "{op:?} {key:?}: caps preserved (contiguous-only, strided_input=false)",
7571            );
7572            checked += 1;
7573        }
7574        assert_eq!(
7575            checked, 16,
7576            "all 16 (IndexSelect/Gather/MaskedFill) select keys checked"
7577        );
7578    }
7579}
7580
7581// ===========================================================================
7582// FKC contract-migration tests (born-red gate for the Vulkan scatter family)
7583// ===========================================================================
7584
7585#[cfg(test)]
7586mod scatter_contract_tests {
7587    use super::*;
7588    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7589
7590    /// SIXTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7591    /// registers the whole Vulkan **scatter** family — IndexAdd (4 per-dtype) +
7592    /// ScatterAdd (4 per-dtype), 4-slot key `[base, U32, src, out]` — FROM ITS FKC
7593    /// KERNEL CONTRACT (`fuel-dispatch/kernel-contracts/vulkan/scatter.fkc.md`) via
7594    /// `register_vulkan_scatter_from_contract`, the sole path now that the
7595    /// hand-written `register_with_precision(OpKind::{IndexAdd,ScatterAdd}, …)` regs
7596    /// are DELETED. Each section fans `base` + `src` over the SAME `[F32,F64,BF16,F16]`
7597    /// list (§3.4; both operands share the list ⇒ one fan, not a mismatch), keying
7598    /// `[T, U32, T, T]`.
7599    ///
7600    /// Per key: EXACT production wrapper fn-pointer; `kernel_source == "vulkan-slang"`
7601    /// (RED discriminator); `caps.strided_input == false` (contiguous-only atomic
7602    /// scatter). Precision is contract-sourced (nondeterministic bounded-CAS,
7603    /// audited none(reason) — the matmul/conv precedent) and NOT asserted here.
7604    #[test]
7605    fn register_vulkan_kernels_binds_scatter_family_from_contract() {
7606        let mut table = KernelBindingTable::new();
7607        register_vulkan_kernels(&mut table);
7608        let vk = BackendId::Vulkan;
7609
7610        let f32 = DType::F32;
7611        let f16 = DType::F16;
7612        let bf16 = DType::BF16;
7613        let f64 = DType::F64;
7614        let u32 = DType::U32;
7615
7616        let cases: &[(OpKind, &[DType], KernelRef)] = &[
7617            (
7618                OpKind::IndexAdd,
7619                &[f32, u32, f32, f32],
7620                index_add::index_add_f32 as KernelRef,
7621            ),
7622            (
7623                OpKind::IndexAdd,
7624                &[f64, u32, f64, f64],
7625                index_add::index_add_f64 as KernelRef,
7626            ),
7627            (
7628                OpKind::IndexAdd,
7629                &[bf16, u32, bf16, bf16],
7630                index_add::index_add_bf16 as KernelRef,
7631            ),
7632            (
7633                OpKind::IndexAdd,
7634                &[f16, u32, f16, f16],
7635                index_add::index_add_f16 as KernelRef,
7636            ),
7637            (
7638                OpKind::ScatterAdd,
7639                &[f32, u32, f32, f32],
7640                scatter_add::scatter_add_f32 as KernelRef,
7641            ),
7642            (
7643                OpKind::ScatterAdd,
7644                &[f64, u32, f64, f64],
7645                scatter_add::scatter_add_f64 as KernelRef,
7646            ),
7647            (
7648                OpKind::ScatterAdd,
7649                &[bf16, u32, bf16, bf16],
7650                scatter_add::scatter_add_bf16 as KernelRef,
7651            ),
7652            (
7653                OpKind::ScatterAdd,
7654                &[f16, u32, f16, f16],
7655                scatter_add::scatter_add_f16 as KernelRef,
7656            ),
7657        ];
7658
7659        let mut checked = 0usize;
7660        for (op, key, expected) in cases {
7661            let alts = table.lookup_alternatives(*op, key, vk);
7662            let entry = alts
7663                .iter()
7664                .find(|e| e.kernel as usize == *expected as usize);
7665            let entry = match entry {
7666                Some(e) => e,
7667                None => panic!(
7668                    "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7669                     scatter contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7670                    alts.len(),
7671                    alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7672                ),
7673            };
7674            assert_eq!(
7675                entry.kernel_source, "vulkan-slang",
7676                "{op:?} {key:?}: scatter family must be contract-sourced \
7677                 (kernel_source=\"vulkan-slang\"); got {:?}",
7678                entry.kernel_source,
7679            );
7680            assert!(
7681                !entry.caps.strided_input,
7682                "{op:?} {key:?}: caps preserved (contiguous-only, strided_input=false)",
7683            );
7684            checked += 1;
7685        }
7686        assert_eq!(
7687            checked, 8,
7688            "all 8 (IndexAdd/ScatterAdd) scatter keys checked"
7689        );
7690    }
7691}
7692
7693// ===========================================================================
7694// FKC contract-migration tests (born-red gate for the Vulkan movement family)
7695// ===========================================================================
7696
7697#[cfg(test)]
7698mod movement_contract_tests {
7699    use super::*;
7700    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7701
7702    /// SEVENTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7703    /// registers the whole Vulkan **movement** family — Concat (4 per-dtype) +
7704    /// CumSum (4 per-dtype), key `[T, T]` — FROM ITS FKC KERNEL CONTRACT
7705    /// (`fuel-dispatch/kernel-contracts/vulkan/movement.fkc.md`) via
7706    /// `register_vulkan_movement_from_contract`, the sole path now that the
7707    /// hand-written `register_with_caps_and_precision(OpKind::{Concat,CumSum}, …,
7708    /// strided, …)` regs are DELETED.
7709    ///
7710    /// Both are STRIDE-AWARE (the deleted regs carried `strided`), so
7711    /// `caps.strided_input == true` is the caps-through-import proof here (the
7712    /// contract's `strided: accepted` layout projects it). `kernel_source ==
7713    /// "vulkan-slang"` is the RED discriminator. Precision is contract-sourced and
7714    /// NOT asserted here.
7715    #[test]
7716    fn register_vulkan_kernels_binds_movement_family_from_contract() {
7717        let mut table = KernelBindingTable::new();
7718        register_vulkan_kernels(&mut table);
7719        let vk = BackendId::Vulkan;
7720
7721        let f32 = DType::F32;
7722        let f16 = DType::F16;
7723        let bf16 = DType::BF16;
7724        let f64 = DType::F64;
7725
7726        // Every movement binding is stride-aware (strided_input == true).
7727        let cases: &[(OpKind, &[DType], KernelRef)] = &[
7728            (OpKind::Concat, &[f32, f32], concat::concat_f32 as KernelRef),
7729            (OpKind::Concat, &[f16, f16], concat::concat_f16 as KernelRef),
7730            (
7731                OpKind::Concat,
7732                &[bf16, bf16],
7733                concat::concat_bf16 as KernelRef,
7734            ),
7735            (OpKind::Concat, &[f64, f64], concat::concat_f64 as KernelRef),
7736            (OpKind::CumSum, &[f32, f32], cumsum::cumsum_f32 as KernelRef),
7737            (OpKind::CumSum, &[f64, f64], cumsum::cumsum_f64 as KernelRef),
7738            (OpKind::CumSum, &[f16, f16], cumsum::cumsum_f16 as KernelRef),
7739            (
7740                OpKind::CumSum,
7741                &[bf16, bf16],
7742                cumsum::cumsum_bf16 as KernelRef,
7743            ),
7744        ];
7745
7746        let mut checked = 0usize;
7747        for (op, key, expected) in cases {
7748            let alts = table.lookup_alternatives(*op, key, vk);
7749            let entry = alts
7750                .iter()
7751                .find(|e| e.kernel as usize == *expected as usize);
7752            let entry = match entry {
7753                Some(e) => e,
7754                None => panic!(
7755                    "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7756                     movement contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7757                    alts.len(),
7758                    alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7759                ),
7760            };
7761            assert_eq!(
7762                entry.kernel_source, "vulkan-slang",
7763                "{op:?} {key:?}: movement family must be contract-sourced \
7764                 (kernel_source=\"vulkan-slang\"); got {:?}",
7765                entry.kernel_source,
7766            );
7767            assert!(
7768                entry.caps.strided_input,
7769                "{op:?} {key:?}: caps must ride through the import truthfully (strided_input=true)",
7770            );
7771            checked += 1;
7772        }
7773        assert_eq!(checked, 8, "all 8 (Concat/CumSum) movement keys checked");
7774    }
7775}
7776
7777// ===========================================================================
7778// FKC contract-migration tests (born-red gate for the Vulkan shape family)
7779// ===========================================================================
7780
7781#[cfg(test)]
7782mod shape_contract_tests {
7783    use super::*;
7784    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7785
7786    /// EIGHTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7787    /// registers the whole Vulkan **shape** family — Triu (7 dtypes) + Tril (7) +
7788    /// Flip (7) + Roll (7), key `[T, T]` — FROM ITS FKC KERNEL CONTRACT
7789    /// (`fuel-dispatch/kernel-contracts/vulkan/shape.fkc.md`) via
7790    /// `register_vulkan_shape_from_contract`, the sole path now that the
7791    /// hand-written `register_with_precision(OpKind::{Triu,Tril}, …)` +
7792    /// `register_with_caps_and_precision(OpKind::{Flip,Roll}, …, strided, …)` regs
7793    /// are DELETED.
7794    ///
7795    /// Each op is ONE dtype-agnostic wrapper across its 7 dtype keys (a
7796    /// synthetic-base umbrella; the fan resolves `<base>_<suffix>` to the one
7797    /// wrapper). `kernel_source == "vulkan-slang"` (RED discriminator).
7798    /// `caps.strided_input` MATCHES per op: Triu/Tril contiguous (false),
7799    /// Flip/Roll stride-aware (true) — the caps-through-import proof. Precision is
7800    /// contract-sourced and NOT asserted here.
7801    #[test]
7802    fn register_vulkan_kernels_binds_shape_family_from_contract() {
7803        let mut table = KernelBindingTable::new();
7804        register_vulkan_kernels(&mut table);
7805        let vk = BackendId::Vulkan;
7806
7807        let dts = [
7808            DType::F32,
7809            DType::F16,
7810            DType::BF16,
7811            DType::F64,
7812            DType::I32,
7813            DType::U32,
7814            DType::I64,
7815        ];
7816        // (OpKind, wrapper, expected strided_input)
7817        let ops: &[(OpKind, KernelRef, bool)] = &[
7818            (OpKind::Triu, triangular::triu as KernelRef, false),
7819            (OpKind::Tril, triangular::tril as KernelRef, false),
7820            (OpKind::Flip, flip::flip as KernelRef, true),
7821            (OpKind::Roll, roll::roll as KernelRef, true),
7822        ];
7823
7824        let mut checked = 0usize;
7825        for &dt in &dts {
7826            for (op, expected, expect_strided) in ops {
7827                let key = [dt, dt];
7828                let alts = table.lookup_alternatives(*op, &key, vk);
7829                let entry = alts
7830                    .iter()
7831                    .find(|e| e.kernel as usize == *expected as usize);
7832                let entry = match entry {
7833                    Some(e) => e,
7834                    None => panic!(
7835                        "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7836                         shape contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7837                        alts.len(),
7838                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7839                    ),
7840                };
7841                assert_eq!(
7842                    entry.kernel_source, "vulkan-slang",
7843                    "{op:?} {key:?}: shape family must be contract-sourced \
7844                     (kernel_source=\"vulkan-slang\"); got {:?}",
7845                    entry.kernel_source,
7846                );
7847                assert_eq!(
7848                    entry.caps.strided_input, *expect_strided,
7849                    "{op:?} {key:?}: caps must ride through the import truthfully (strided_input)",
7850                );
7851                checked += 1;
7852            }
7853        }
7854        assert_eq!(
7855            checked, 28,
7856            "all 28 (Triu/Tril/Flip/Roll × 7 dtypes) shape keys checked"
7857        );
7858    }
7859}
7860
7861// ===========================================================================
7862// FKC contract-migration tests (born-red gate for the Vulkan pad-copy family)
7863// ===========================================================================
7864
7865#[cfg(test)]
7866mod pad_copy_contract_tests {
7867    use super::*;
7868    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7869
7870    /// NINTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7871    /// registers the whole Vulkan **pad-copy** family — Pad (6 dtypes) +
7872    /// PadBackward (6) + Copy (9) — FROM ITS FKC KERNEL CONTRACT
7873    /// (`fuel-dispatch/kernel-contracts/vulkan/pad-copy.fkc.md`) via
7874    /// `register_vulkan_pad_copy_from_contract`, the sole path now that the
7875    /// hand-written `register_with_precision(OpKind::{Pad,PadBackward,Copy}, …)`
7876    /// regs are DELETED. Each op is ONE dtype-agnostic wrapper across its dtype keys
7877    /// (a synthetic-base umbrella). `kernel_source == "vulkan-slang"` (RED
7878    /// discriminator); `caps.strided_input == false` (contiguous-only byte movers).
7879    /// Precision is contract-sourced (byte-exact) and NOT asserted here.
7880    #[test]
7881    fn register_vulkan_kernels_binds_pad_copy_family_from_contract() {
7882        let mut table = KernelBindingTable::new();
7883        register_vulkan_kernels(&mut table);
7884        let vk = BackendId::Vulkan;
7885
7886        let pad_dts = [
7887            DType::F32,
7888            DType::F16,
7889            DType::BF16,
7890            DType::F64,
7891            DType::U8,
7892            DType::U32,
7893        ];
7894        let copy_dts = [
7895            DType::F32,
7896            DType::F16,
7897            DType::BF16,
7898            DType::F64,
7899            DType::U32,
7900            DType::U8,
7901            DType::I16,
7902            DType::I32,
7903            DType::I64,
7904        ];
7905
7906        let mut checked = 0usize;
7907        let mut check = |op: OpKind, key: &[DType], expected: KernelRef| {
7908            let alts = table.lookup_alternatives(op, key, vk);
7909            let entry = alts.iter().find(|e| e.kernel as usize == expected as usize);
7910            let entry = match entry {
7911                Some(e) => e,
7912                None => panic!(
7913                    "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7914                     pad-copy contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7915                    alts.len(),
7916                    alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7917                ),
7918            };
7919            assert_eq!(
7920                entry.kernel_source, "vulkan-slang",
7921                "{op:?} {key:?}: pad-copy family must be contract-sourced \
7922                 (kernel_source=\"vulkan-slang\"); got {:?}",
7923                entry.kernel_source,
7924            );
7925            assert!(
7926                !entry.caps.strided_input,
7927                "{op:?} {key:?}: caps preserved (contiguous-only, strided_input=false)",
7928            );
7929            checked += 1;
7930        };
7931
7932        for &dt in &pad_dts {
7933            check(OpKind::Pad, &[dt, dt], pad::pad_const as KernelRef);
7934            check(
7935                OpKind::PadBackward,
7936                &[dt, dt],
7937                pad::pad_backward as KernelRef,
7938            );
7939        }
7940        for &dt in &copy_dts {
7941            check(OpKind::Copy, &[dt, dt], copy_to_cpu_vulkan as KernelRef);
7942        }
7943        assert_eq!(
7944            checked, 21,
7945            "all 21 (Pad/PadBackward/Copy) pad-copy keys checked"
7946        );
7947    }
7948}
7949
7950// ===========================================================================
7951// FKC contract-migration tests (born-red gate for the Vulkan write-slice family)
7952// ===========================================================================
7953
7954#[cfg(test)]
7955mod write_slice_contract_tests {
7956    use super::*;
7957    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7958
7959    /// TENTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7960    /// registers the whole Vulkan **write-slice** family — WriteSlice (9 dtypes) +
7961    /// WriteSliceRotating (9), key `[T, T]` — FROM ITS FKC KERNEL CONTRACT
7962    /// (`fuel-dispatch/kernel-contracts/vulkan/write-slice.fkc.md`) via
7963    /// `register_vulkan_write_slice_from_contract`, the sole path now that the
7964    /// hand-written `register_with_precision(OpKind::{WriteSlice,WriteSliceRotating},
7965    /// …)` regs are DELETED. Each op is BYTE-WIDTH-keyed: 9 dtype keys resolve to 4
7966    /// byte-width wrappers (b1/b2/b4/b8) — the cast family's "several sections share
7967    /// one wrapper" precedent. `kernel_source == "vulkan-slang"` (RED discriminator);
7968    /// `caps.strided_input == false` (contiguous slab writes). Precision is
7969    /// contract-sourced (byte-exact) and NOT asserted here.
7970    #[test]
7971    fn register_vulkan_kernels_binds_write_slice_family_from_contract() {
7972        let mut table = KernelBindingTable::new();
7973        register_vulkan_kernels(&mut table);
7974        let vk = BackendId::Vulkan;
7975
7976        // (dtype, WriteSlice wrapper, WriteSliceRotating wrapper) by byte width.
7977        let cases: &[(DType, KernelRef, KernelRef)] = &[
7978            (
7979                DType::F32,
7980                write_slice::write_slice_b4 as KernelRef,
7981                write_slice_rotating::write_slice_rotating_b4 as KernelRef,
7982            ),
7983            (
7984                DType::I32,
7985                write_slice::write_slice_b4 as KernelRef,
7986                write_slice_rotating::write_slice_rotating_b4 as KernelRef,
7987            ),
7988            (
7989                DType::U32,
7990                write_slice::write_slice_b4 as KernelRef,
7991                write_slice_rotating::write_slice_rotating_b4 as KernelRef,
7992            ),
7993            (
7994                DType::F16,
7995                write_slice::write_slice_b2 as KernelRef,
7996                write_slice_rotating::write_slice_rotating_b2 as KernelRef,
7997            ),
7998            (
7999                DType::BF16,
8000                write_slice::write_slice_b2 as KernelRef,
8001                write_slice_rotating::write_slice_rotating_b2 as KernelRef,
8002            ),
8003            (
8004                DType::F64,
8005                write_slice::write_slice_b8 as KernelRef,
8006                write_slice_rotating::write_slice_rotating_b8 as KernelRef,
8007            ),
8008            (
8009                DType::I64,
8010                write_slice::write_slice_b8 as KernelRef,
8011                write_slice_rotating::write_slice_rotating_b8 as KernelRef,
8012            ),
8013            (
8014                DType::U8,
8015                write_slice::write_slice_b1 as KernelRef,
8016                write_slice_rotating::write_slice_rotating_b1 as KernelRef,
8017            ),
8018            (
8019                DType::I8,
8020                write_slice::write_slice_b1 as KernelRef,
8021                write_slice_rotating::write_slice_rotating_b1 as KernelRef,
8022            ),
8023        ];
8024
8025        let mut checked = 0usize;
8026        let mut check = |op: OpKind, key: &[DType], expected: KernelRef| {
8027            let alts = table.lookup_alternatives(op, key, vk);
8028            let entry = alts.iter().find(|e| e.kernel as usize == expected as usize);
8029            let entry = match entry {
8030                Some(e) => e,
8031                None => panic!(
8032                    "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
8033                     write-slice contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
8034                    alts.len(),
8035                    alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
8036                ),
8037            };
8038            assert_eq!(
8039                entry.kernel_source, "vulkan-slang",
8040                "{op:?} {key:?}: write-slice family must be contract-sourced \
8041                 (kernel_source=\"vulkan-slang\"); got {:?}",
8042                entry.kernel_source,
8043            );
8044            assert!(
8045                !entry.caps.strided_input,
8046                "{op:?} {key:?}: caps preserved (contiguous-only, strided_input=false)",
8047            );
8048            checked += 1;
8049        };
8050
8051        for (dt, ws, wsr) in cases {
8052            check(OpKind::WriteSlice, &[*dt, *dt], *ws);
8053            check(OpKind::WriteSliceRotating, &[*dt, *dt], *wsr);
8054        }
8055        assert_eq!(
8056            checked, 18,
8057            "all 18 (WriteSlice/WriteSliceRotating × 9 dtypes) write-slice keys checked"
8058        );
8059    }
8060}
8061
8062// ===========================================================================
8063// FKC contract-migration tests (born-red gate for the Vulkan rope family)
8064// ===========================================================================
8065
8066#[cfg(test)]
8067mod rope_contract_tests {
8068    use super::*;
8069    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
8070
8071    /// ELEVENTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
8072    /// registers the whole Vulkan **rope** family — RoPE (4 per-dtype), 4-slot key
8073    /// `[x, cos, sin, out]` — FROM ITS FKC KERNEL CONTRACT
8074    /// (`fuel-dispatch/kernel-contracts/vulkan/rope.fkc.md`) via
8075    /// `register_vulkan_rope_from_contract`, the sole path now that the hand-written
8076    /// `register_with_caps_and_precision(OpKind::Rope, …, strided, …)` regs are
8077    /// DELETED. One section fans `x` + `cos` + `sin` over the SAME `[F32,F16,F64,BF16]`
8078    /// list (§3.4), keying `[T, T, T, T]`.
8079    ///
8080    /// RoPE is STRIDE-AWARE (the deleted regs carried `strided`), so
8081    /// `caps.strided_input == true` is the caps-through-import proof here.
8082    /// `kernel_source == "vulkan-slang"` is the RED discriminator. Precision is
8083    /// contract-sourced and NOT asserted here.
8084    #[test]
8085    fn register_vulkan_kernels_binds_rope_family_from_contract() {
8086        let mut table = KernelBindingTable::new();
8087        register_vulkan_kernels(&mut table);
8088        let vk = BackendId::Vulkan;
8089
8090        let f32 = DType::F32;
8091        let f16 = DType::F16;
8092        let bf16 = DType::BF16;
8093        let f64 = DType::F64;
8094        let cases: &[(&[DType], KernelRef)] = &[
8095            (&[f32, f32, f32, f32], attention::rope_f32 as KernelRef),
8096            (&[f16, f16, f16, f16], attention::rope_f16 as KernelRef),
8097            (&[f64, f64, f64, f64], attention::rope_f64 as KernelRef),
8098            (&[bf16, bf16, bf16, bf16], attention::rope_bf16 as KernelRef),
8099        ];
8100
8101        let mut checked = 0usize;
8102        for (key, expected) in cases {
8103            let alts = table.lookup_alternatives(OpKind::Rope, key, vk);
8104            let entry = alts
8105                .iter()
8106                .find(|e| e.kernel as usize == *expected as usize);
8107            let entry = match entry {
8108                Some(e) => e,
8109                None => panic!(
8110                    "Rope {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
8111                     rope contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
8112                    alts.len(),
8113                    alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
8114                ),
8115            };
8116            assert_eq!(
8117                entry.kernel_source, "vulkan-slang",
8118                "Rope {key:?}: rope family must be contract-sourced \
8119                 (kernel_source=\"vulkan-slang\"); got {:?}",
8120                entry.kernel_source,
8121            );
8122            assert!(
8123                entry.caps.strided_input,
8124                "Rope {key:?}: caps must ride through the import truthfully (strided_input=true)",
8125            );
8126            checked += 1;
8127        }
8128        assert_eq!(checked, 4, "all 4 (RoPE × dtype) rope keys checked");
8129    }
8130}
8131
8132// ===========================================================================
8133// FKC contract-migration tests (born-red gate for the Vulkan reduce family)
8134// ===========================================================================
8135
8136#[cfg(test)]
8137mod reduce_contract_tests {
8138    use super::*;
8139    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
8140
8141    /// TWELFTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
8142    /// registers the whole Vulkan **reduce** family — SumReduce / MaxReduce /
8143    /// MinReduce / MeanReduce (4 per-dtype each = 16, key `[T, T]`) + ArgMaxDim /
8144    /// ArgMinDim (4 per-dtype each = 8, key `[T, U32]`) — FROM ITS FKC KERNEL
8145    /// CONTRACT (`fuel-dispatch/kernel-contracts/vulkan/reduce.fkc.md`) via
8146    /// `register_vulkan_reduce_from_contract`, the sole path now that the
8147    /// hand-written `register_with_precision(OpKind::{SumReduce,…,ArgMinDim}, …)`
8148    /// regs are DELETED. Each OpKind is its own section fanned over the dtype list to
8149    /// its distinct per-dtype wrapper. `kernel_source == "vulkan-slang"` (RED
8150    /// discriminator); `caps.strided_input == false` (contiguous subgroup-tree
8151    /// reductions). Precision is contract-sourced and NOT asserted here.
8152    #[test]
8153    fn register_vulkan_kernels_binds_reduce_family_from_contract() {
8154        let mut table = KernelBindingTable::new();
8155        register_vulkan_kernels(&mut table);
8156        let vk = BackendId::Vulkan;
8157        let u32 = DType::U32;
8158
8159        let mut checked = 0usize;
8160        let mut check = |op: OpKind, key: &[DType], expected: KernelRef| {
8161            let alts = table.lookup_alternatives(op, key, vk);
8162            let entry = alts.iter().find(|e| e.kernel as usize == expected as usize);
8163            let entry = match entry {
8164                Some(e) => e,
8165                None => panic!(
8166                    "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
8167                     reduce contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
8168                    alts.len(),
8169                    alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
8170                ),
8171            };
8172            assert_eq!(
8173                entry.kernel_source, "vulkan-slang",
8174                "{op:?} {key:?}: reduce family must be contract-sourced \
8175                 (kernel_source=\"vulkan-slang\"); got {:?}",
8176                entry.kernel_source,
8177            );
8178            assert!(
8179                !entry.caps.strided_input,
8180                "{op:?} {key:?}: contiguous-only (strided_input=false)"
8181            );
8182            checked += 1;
8183        };
8184
8185        // Value reduces: 4 ops × 4 dtypes, key [T, T].
8186        let val: &[(OpKind, [KernelRef; 4])] = &[
8187            (
8188                OpKind::SumReduce,
8189                [
8190                    reduce::sum_f32,
8191                    reduce::sum_f16,
8192                    reduce::sum_bf16,
8193                    reduce::sum_f64,
8194                ],
8195            ),
8196            (
8197                OpKind::MaxReduce,
8198                [
8199                    reduce::max_f32,
8200                    reduce::max_f16,
8201                    reduce::max_bf16,
8202                    reduce::max_f64,
8203                ],
8204            ),
8205            (
8206                OpKind::MinReduce,
8207                [
8208                    reduce::min_f32,
8209                    reduce::min_f16,
8210                    reduce::min_bf16,
8211                    reduce::min_f64,
8212                ],
8213            ),
8214            (
8215                OpKind::MeanReduce,
8216                [
8217                    reduce::mean_f32,
8218                    reduce::mean_f16,
8219                    reduce::mean_bf16,
8220                    reduce::mean_f64,
8221                ],
8222            ),
8223        ];
8224        let dts = [DType::F32, DType::F16, DType::BF16, DType::F64];
8225        for (op, wraps) in val {
8226            for (i, &dt) in dts.iter().enumerate() {
8227                check(*op, &[dt, dt], wraps[i]);
8228            }
8229        }
8230        // Arg reduces: 2 ops × 4 dtypes, key [T, U32].
8231        let arg: &[(OpKind, [KernelRef; 4])] = &[
8232            (
8233                OpKind::ArgMaxDim,
8234                [
8235                    arg_reduce::argmax_f32,
8236                    arg_reduce::argmax_f16,
8237                    arg_reduce::argmax_bf16,
8238                    arg_reduce::argmax_f64,
8239                ],
8240            ),
8241            (
8242                OpKind::ArgMinDim,
8243                [
8244                    arg_reduce::argmin_f32,
8245                    arg_reduce::argmin_f16,
8246                    arg_reduce::argmin_bf16,
8247                    arg_reduce::argmin_f64,
8248                ],
8249            ),
8250        ];
8251        for (op, wraps) in arg {
8252            for (i, &dt) in dts.iter().enumerate() {
8253                check(*op, &[dt, u32], wraps[i]);
8254            }
8255        }
8256        assert_eq!(
8257            checked, 24,
8258            "all 24 (Sum/Max/Min/Mean + ArgMax/ArgMin × 4 dtypes) reduce keys checked"
8259        );
8260    }
8261}
8262
8263// ===========================================================================
8264// FKC contract-migration tests (born-red gate for the Vulkan norm family)
8265// ===========================================================================
8266
8267#[cfg(test)]
8268mod norm_contract_tests {
8269    use super::*;
8270    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
8271
8272    /// THIRTEENTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
8273    /// registers the whole Vulkan **norm** family — SoftmaxLastDim (4, key `[T, T]`),
8274    /// SoftmaxLastDimBackward (4, key `[y, g, dx]`), LayerNormLastDim (4, `[T, T]`),
8275    /// LayerNormLastDimBackward (4, `[x, g, dx]`), RmsNormLastDim (4, `[T, T]`) —
8276    /// FROM ITS FKC KERNEL CONTRACT (`fuel-dispatch/kernel-contracts/vulkan/norm.fkc.md`) via
8277    /// `register_vulkan_norm_from_contract`, the sole path now that the hand-written
8278    /// `register_with_precision(OpKind::{SoftmaxLastDim,…,RmsNormLastDim}, …)` regs
8279    /// are DELETED. Each OpKind is its own section fanned over `[F32, F16, BF16, F64]`
8280    /// to its distinct per-dtype wrapper. `kernel_source == "vulkan-slang"` (RED
8281    /// discriminator); `caps.strided_input == false` (contiguous per-row
8282    /// reductions). Precision is contract-sourced and NOT asserted here.
8283    #[test]
8284    fn register_vulkan_kernels_binds_norm_family_from_contract() {
8285        let mut table = KernelBindingTable::new();
8286        register_vulkan_kernels(&mut table);
8287        let vk = BackendId::Vulkan;
8288
8289        let mut checked = 0usize;
8290        let mut check = |op: OpKind, key: &[DType], expected: KernelRef| {
8291            let alts = table.lookup_alternatives(op, key, vk);
8292            let entry = alts.iter().find(|e| e.kernel as usize == expected as usize);
8293            let entry = match entry {
8294                Some(e) => e,
8295                None => panic!(
8296                    "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
8297                     norm contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
8298                    alts.len(),
8299                    alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
8300                ),
8301            };
8302            assert_eq!(
8303                entry.kernel_source, "vulkan-slang",
8304                "{op:?} {key:?}: norm family must be contract-sourced \
8305                 (kernel_source=\"vulkan-slang\"); got {:?}",
8306                entry.kernel_source,
8307            );
8308            assert!(
8309                !entry.caps.strided_input,
8310                "{op:?} {key:?}: contiguous-only (strided_input=false)"
8311            );
8312            checked += 1;
8313        };
8314
8315        let dts = [DType::F32, DType::F16, DType::BF16, DType::F64];
8316        // Unary [T, T] families.
8317        let un: &[(OpKind, [KernelRef; 4])] = &[
8318            (
8319                OpKind::SoftmaxLastDim,
8320                [
8321                    softmax::softmax_f32,
8322                    softmax::softmax_f16,
8323                    softmax::softmax_bf16,
8324                    softmax::softmax_f64,
8325                ],
8326            ),
8327            (
8328                OpKind::LayerNormLastDim,
8329                [
8330                    norm::layer_norm_f32,
8331                    norm::layer_norm_f16,
8332                    norm::layer_norm_bf16,
8333                    norm::layer_norm_f64,
8334                ],
8335            ),
8336            (
8337                OpKind::RmsNormLastDim,
8338                [norm::rms_f32, norm::rms_f16, norm::rms_bf16, norm::rms_f64],
8339            ),
8340        ];
8341        for (op, wraps) in un {
8342            for (i, &dt) in dts.iter().enumerate() {
8343                check(*op, &[dt, dt], wraps[i]);
8344            }
8345        }
8346        // Backward [T, T, T] families.
8347        let bwd: &[(OpKind, [KernelRef; 4])] = &[
8348            (
8349                OpKind::SoftmaxLastDimBackward,
8350                [
8351                    softmax::softmax_last_dim_backward_f32,
8352                    softmax::softmax_last_dim_backward_f16,
8353                    softmax::softmax_last_dim_backward_bf16,
8354                    softmax::softmax_last_dim_backward_f64,
8355                ],
8356            ),
8357            (
8358                OpKind::LayerNormLastDimBackward,
8359                [
8360                    norm::layer_norm_backward_f32,
8361                    norm::layer_norm_backward_f16,
8362                    norm::layer_norm_backward_bf16,
8363                    norm::layer_norm_backward_f64,
8364                ],
8365            ),
8366        ];
8367        for (op, wraps) in bwd {
8368            for (i, &dt) in dts.iter().enumerate() {
8369                check(*op, &[dt, dt, dt], wraps[i]);
8370            }
8371        }
8372        assert_eq!(
8373            checked, 20,
8374            "all 20 (Softmax/SoftmaxBwd/LayerNorm/LayerNormBwd/RmsNorm × 4 dtypes) norm keys checked"
8375        );
8376    }
8377}
8378
8379// ===========================================================================
8380// FKC contract-migration tests (born-red gate for the Vulkan QMatMul family)
8381// ===========================================================================
8382//
8383// Same always-on gating (this crate IS the Vulkan crate) as the cast/…/norm tests above:
8384// this module always compiles (this crate has no feature gate) and touches NO device
8385// (registration is pure binding-table population).
8386
8387#[cfg(test)]
8388mod qmatmul_contract_tests {
8389    use super::*;
8390    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
8391
8392    /// FOURTEENTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
8393    /// registers the single Vulkan **QMatMul** binding (`(QMatMul, [F32, U32, F32],
8394    /// Vulkan)` — F32 activation × U32-typed GGML block-quant weight → F32 output, the
8395    /// one wrapper `qmatmul::qmatmul_vk` route-picking Q4_0 / Q4_K_M / Q8_0 internally
8396    /// by `OpParams::QMatMul.quant_type`) FROM ITS RE-AUTHORED FKC KERNEL CONTRACT
8397    /// (`fuel-dispatch/kernel-contracts/vulkan/qmatmul.fkc.md`) via
8398    /// `register_vulkan_qmatmul_from_contract` — the sole registration path now that
8399    /// the hand-written `table.register_with_precision(OpKind::QMatMul, …)` reg is
8400    /// DELETED.
8401    ///
8402    /// The corpus's `vulkan/quantized.fkc.md` models QMATMUL as TWO aspirational
8403    /// `fused_op: QMATMUL` Q4_0 sections (`qmatvec_q4_0` gemv + `matmul_q4_0_tiled`),
8404    /// which mismatch production on BOTH axes: production registers the PRIMITIVE
8405    /// `OpKind::QMatMul` (not the fused op) keyed with the LOGICAL U32 weight dtype
8406    /// (not the physical U8 block stream). So the migration authors ONE faithful
8407    /// single-dtype-per-operand `op_kind: QMatMul` section in the new production
8408    /// `fuel-dispatch/kernel-contracts/vulkan/qmatmul.fkc.md` (weight `U32`, `fdx.quant`
8409    /// GGML_BLOCK keeping byte-honesty — the CPU linear-quant U8→U32 precedent), and
8410    /// flips the two corpus fused sections to `registrable: false` describe-only
8411    /// cross-referencing it (the matmul_mixed_precision precedent).
8412    ///
8413    /// This asserts: the `(QMatMul, [F32, U32, F32], Vulkan)` key resolves to the
8414    /// EXACT production wrapper fn-pointer `qmatmul::qmatmul_vk` (behavior-preserving);
8415    /// `kernel_source == "vulkan-slang"` (the RED discriminator — the deleted hand
8416    /// path stamped `""`, so before the import is wired this assert fails on the empty
8417    /// source); and `caps.strided_input == false` — the contiguous-only truth of the
8418    /// deleted `register_with_precision` reg (the GGML block stream has a fixed block
8419    /// layout; a strided operand is auto-Contiguized first). Precision is
8420    /// contract-sourced (the matmul/conv precedent: the hand-written
8421    /// `VULKAN_QMATMUL_PRECISION` over-claimed `bit_stable_on_same_hardware: true`; the
8422    /// contract seeds the truthful audited-nondeterministic posture) and NOT asserted
8423    /// here.
8424    #[test]
8425    fn register_vulkan_kernels_binds_qmatmul_from_contract() {
8426        let mut table = KernelBindingTable::new();
8427        register_vulkan_kernels(&mut table);
8428        let vk = BackendId::Vulkan;
8429
8430        let key: &[DType] = &[DType::F32, DType::U32, DType::F32];
8431        let expected = qmatmul::qmatmul_vk as KernelRef;
8432        let alts = table.lookup_alternatives(OpKind::QMatMul, key, vk);
8433        let entry = alts.iter().find(|e| e.kernel as usize == expected as usize);
8434        let entry = match entry {
8435            Some(e) => e,
8436            None => panic!(
8437                "QMatMul {key:?}/Vulkan: production wrapper (qmatmul_vk) must be bound FROM the \
8438                 vulkan qmatmul contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
8439                alts.len(),
8440                alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
8441            ),
8442        };
8443        assert_eq!(
8444            entry.kernel_source, "vulkan-slang",
8445            "QMatMul {key:?}: qmatmul must be contract-sourced \
8446             (kernel_source=\"vulkan-slang\"); got {:?}",
8447            entry.kernel_source,
8448        );
8449        assert!(
8450            !entry.caps.strided_input,
8451            "QMatMul {key:?}: caps preserved (contiguous-only, strided_input=false)",
8452        );
8453    }
8454}
8455
8456// ===========================================================================
8457// FKC contract-migration tests (born-red gate for the Vulkan FlashAttn family)
8458// ===========================================================================
8459//
8460// Same always-on gating (this crate IS the Vulkan crate) as the cast/…/qmatmul tests
8461// above: this module always compiles (this crate has no feature gate) and touches NO
8462// device (registration is pure binding-table population).
8463
8464#[cfg(test)]
8465mod attention_contract_tests {
8466    use super::*;
8467    use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
8468
8469    /// FIFTEENTH (and LAST) VULKAN-BACKEND FKC CONSUMER (born-red gate).
8470    /// `register_vulkan_kernels` registers the whole Vulkan **FlashAttention**
8471    /// family (12 `KernelRef`s: forward `OpKind::FlashAttn` at f32/bf16/f16 +
8472    /// backward `OpKind::FlashAttnBackward{Q,K,V}` at f32, each with a
8473    /// no-alibi AND a with-alibi binding shape) FROM ITS AUTHORED FKC KERNEL
8474    /// CONTRACT (`fuel-dispatch/kernel-contracts/vulkan/attention.fkc.md`) via
8475    /// `register_vulkan_attention_from_contract` — the sole registration path
8476    /// now that the hand-written `table.register_with_precision(OpKind::{FlashAttn,
8477    /// FlashAttnBackwardQ,FlashAttnBackwardK,FlashAttnBackwardV}, …)` regs are
8478    /// DELETED. This was the LAST hand-written `table.register*` call in
8479    /// `register_vulkan_kernels`, so the Vulkan backend is now 100%
8480    /// contract-sourced.
8481    ///
8482    /// The forward wrappers are DISTINCT per dtype
8483    /// (`flash_attn::flash_attn_{f32,bf16,f16}`), so the contract authors THREE
8484    /// single-dtype-per-operand forward sections (the conv2d + CPU-attention
8485    /// per-dtype-section precedent) rather than one dtype-fanned umbrella; the
8486    /// three backward selectors are f32-only single sections. In every section
8487    /// `alibi_slopes` is an `optional: true` LAST input, so the importer's
8488    /// optional-last fan (§3.4) registers EACH as TWO keys (with + without the
8489    /// operand) — byte-for-byte the deleted regs' dual `[q,k,v,out]` /
8490    /// `[q,k,v,alibi,out]` (forward) and `[q,k,v,do,out]` / `[q,k,v,do,alibi,out]`
8491    /// (backward) shapes.
8492    ///
8493    /// For each `(OpKind, [T..], Vulkan)` key this asserts: the binding resolves
8494    /// to the EXACT production wrapper fn-pointer (behavior-preserving);
8495    /// `kernel_source == "vulkan-slang"` (the RED discriminator — the deleted
8496    /// hand path stamped `""`, so before the import is wired this assert fails on
8497    /// the empty source); and `caps.strided_input == false` — the contiguous-only
8498    /// truth of the deleted plain `register_with_precision` regs. Precision is
8499    /// contract-sourced (the retired `VULKAN_{FLOAT,HALF}_POINTWISE_PRECISION`
8500    /// consts over-claimed `bit_stable_on_same_hardware: true` for a shared-mem
8501    /// softmax reduction; the contract seeds the truthful audited-nondeterministic
8502    /// posture, matching the aspirational `conv-attn-rope.fkc.md`) and NOT
8503    /// asserted here.
8504    #[test]
8505    fn register_vulkan_kernels_binds_flash_attn_family_from_contract() {
8506        let mut table = KernelBindingTable::new();
8507        register_vulkan_kernels(&mut table);
8508        let vk = BackendId::Vulkan;
8509
8510        // (OpKind, key dtypes [inputs.., out], expected production wrapper). Both the
8511        // no-alibi and the with-alibi (one extra pre-output slot) shapes per op/dtype.
8512        // Every FlashAttn binding is contiguous-only (strided_input == false), checked
8513        // uniformly below.
8514        let cases: &[(OpKind, &[DType], KernelRef)] = &[
8515            // ---- Forward FlashAttn: f32 / bf16 / f16, no-alibi [q,k,v,out] + with-alibi [q,k,v,alibi,out]. ----
8516            (
8517                OpKind::FlashAttn,
8518                &[DType::F32, DType::F32, DType::F32, DType::F32],
8519                flash_attn::flash_attn_f32 as KernelRef,
8520            ),
8521            (
8522                OpKind::FlashAttn,
8523                &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32],
8524                flash_attn::flash_attn_f32 as KernelRef,
8525            ),
8526            (
8527                OpKind::FlashAttn,
8528                &[DType::BF16, DType::BF16, DType::BF16, DType::BF16],
8529                flash_attn::flash_attn_bf16 as KernelRef,
8530            ),
8531            (
8532                OpKind::FlashAttn,
8533                &[
8534                    DType::BF16,
8535                    DType::BF16,
8536                    DType::BF16,
8537                    DType::BF16,
8538                    DType::BF16,
8539                ],
8540                flash_attn::flash_attn_bf16 as KernelRef,
8541            ),
8542            (
8543                OpKind::FlashAttn,
8544                &[DType::F16, DType::F16, DType::F16, DType::F16],
8545                flash_attn::flash_attn_f16 as KernelRef,
8546            ),
8547            (
8548                OpKind::FlashAttn,
8549                &[DType::F16, DType::F16, DType::F16, DType::F16, DType::F16],
8550                flash_attn::flash_attn_f16 as KernelRef,
8551            ),
8552            // ---- Backward Q/K/V f32: no-alibi [q,k,v,do,out] + with-alibi [q,k,v,do,alibi,out]. ----
8553            (
8554                OpKind::FlashAttnBackwardQ,
8555                &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32],
8556                flash_attn::flash_attn_backward_q_f32 as KernelRef,
8557            ),
8558            (
8559                OpKind::FlashAttnBackwardQ,
8560                &[
8561                    DType::F32,
8562                    DType::F32,
8563                    DType::F32,
8564                    DType::F32,
8565                    DType::F32,
8566                    DType::F32,
8567                ],
8568                flash_attn::flash_attn_backward_q_f32 as KernelRef,
8569            ),
8570            (
8571                OpKind::FlashAttnBackwardK,
8572                &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32],
8573                flash_attn::flash_attn_backward_k_f32 as KernelRef,
8574            ),
8575            (
8576                OpKind::FlashAttnBackwardK,
8577                &[
8578                    DType::F32,
8579                    DType::F32,
8580                    DType::F32,
8581                    DType::F32,
8582                    DType::F32,
8583                    DType::F32,
8584                ],
8585                flash_attn::flash_attn_backward_k_f32 as KernelRef,
8586            ),
8587            (
8588                OpKind::FlashAttnBackwardV,
8589                &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32],
8590                flash_attn::flash_attn_backward_v_f32 as KernelRef,
8591            ),
8592            (
8593                OpKind::FlashAttnBackwardV,
8594                &[
8595                    DType::F32,
8596                    DType::F32,
8597                    DType::F32,
8598                    DType::F32,
8599                    DType::F32,
8600                    DType::F32,
8601                ],
8602                flash_attn::flash_attn_backward_v_f32 as KernelRef,
8603            ),
8604        ];
8605
8606        let mut checked = 0usize;
8607        for (op, key, expected) in cases {
8608            let alts = table.lookup_alternatives(*op, key, vk);
8609            let entry = alts
8610                .iter()
8611                .find(|e| e.kernel as usize == *expected as usize);
8612            let entry = match entry {
8613                Some(e) => e,
8614                None => panic!(
8615                    "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
8616                     attention contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
8617                    alts.len(),
8618                    alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
8619                ),
8620            };
8621            assert_eq!(
8622                entry.kernel_source, "vulkan-slang",
8623                "{op:?} {key:?}: FlashAttn family must be contract-sourced \
8624                 (kernel_source=\"vulkan-slang\"); got {:?}",
8625                entry.kernel_source,
8626            );
8627            assert!(
8628                !entry.caps.strided_input,
8629                "{op:?} {key:?}: caps preserved (contiguous-only, strided_input=false)",
8630            );
8631            checked += 1;
8632        }
8633        assert_eq!(
8634            checked, 12,
8635            "all 12 FlashAttn family bindings (6 forward + 6 backward) checked"
8636        );
8637    }
8638}
8639
8640/// The wired-type list ([`qmatmul::qmatmul_wired`]) and the arms of `qmatmul_vk`'s `match quant_type`
8641/// must name the same types: `fuel-tensor`'s loader keeps a GGUF weight quantized exactly when the list
8642/// says wired, so a type with an arm and no list entry stays on the f32 path for no reason, and a type
8643/// in the list with no arm errors at realize ("not wired on Vulkan"). Source-scanning, no GPU.
8644#[cfg(test)]
8645mod qmatmul_wired_list_matches_arms {
8646    use super::qmatmul::qmatmul_wired;
8647    use fuel_graph::QuantType;
8648    use std::collections::BTreeSet;
8649
8650    /// Every variant, named. The `match` is exhaustive, so a new `QuantType` variant is a compile
8651    /// error here until it is added and given a verdict.
8652    fn all() -> Vec<(QuantType, &'static str)> {
8653        let v = [
8654            (QuantType::Q4_0, "Q4_0"),
8655            (QuantType::Q4_1, "Q4_1"),
8656            (QuantType::Q5_0, "Q5_0"),
8657            (QuantType::Q5_1, "Q5_1"),
8658            (QuantType::Q8_0, "Q8_0"),
8659            (QuantType::Q8_1, "Q8_1"),
8660            (QuantType::Q2K, "Q2K"),
8661            (QuantType::Q3K, "Q3K"),
8662            (QuantType::Q4_K_M, "Q4_K_M"),
8663            (QuantType::Q5K, "Q5K"),
8664            (QuantType::Q6K, "Q6K"),
8665            (QuantType::Iq4Nl, "Iq4Nl"),
8666            (QuantType::Iq4Xs, "Iq4Xs"),
8667            (QuantType::Iq3S, "Iq3S"),
8668        ];
8669        for (q, _) in &v {
8670            match q {
8671                QuantType::Q4_0
8672                | QuantType::Q4_1
8673                | QuantType::Q5_0
8674                | QuantType::Q5_1
8675                | QuantType::Q8_0
8676                | QuantType::Q8_1
8677                | QuantType::Q2K
8678                | QuantType::Q3K
8679                | QuantType::Q4_K_M
8680                | QuantType::Q5K
8681                | QuantType::Q6K
8682                | QuantType::Iq4Nl
8683                | QuantType::Iq4Xs
8684                | QuantType::Iq3S => {}
8685            }
8686        }
8687        v.to_vec()
8688    }
8689
8690    /// The `QuantType::X =>` arms of the `match quant_type {` inside `qmatmul_vk`, read from this file.
8691    fn arms_in(src: &str) -> BTreeSet<String> {
8692        let start = src
8693            .find("pub fn qmatmul_vk(")
8694            .expect("qmatmul_vk is in this file");
8695        let body = &src[start..];
8696        let m = body
8697            .find("match quant_type {")
8698            .expect("qmatmul_vk matches on quant_type");
8699        let mut arms = BTreeSet::new();
8700        for line in body[m..].lines().skip(1) {
8701            let t = line.trim_start();
8702            if t.starts_with("other =>") || t.starts_with("_ =>") {
8703                break;
8704            }
8705            if let Some(rest) = t.strip_prefix("QuantType::")
8706                && let Some((name, _)) = rest.split_once(" =>")
8707            {
8708                arms.insert(name.to_string());
8709            }
8710        }
8711        arms
8712    }
8713
8714    fn listed() -> BTreeSet<String> {
8715        all()
8716            .into_iter()
8717            .filter(|(q, _)| qmatmul_wired(*q))
8718            .map(|(_, n)| n.to_string())
8719            .collect()
8720    }
8721
8722    #[test]
8723    fn the_list_and_the_arms_name_the_same_types() {
8724        let arms = arms_in(include_str!("vulkan_dispatch.rs"));
8725        assert_eq!(
8726            arms,
8727            listed(),
8728            "qmatmul_wired and qmatmul_vk's match arms disagree: change both in one commit"
8729        );
8730        // Control: the scan finds the arms that exist today (so an empty parse cannot pass).
8731        assert!(arms.contains("Q4_K_M") && arms.len() == 9, "{arms:?}");
8732    }
8733
8734    /// The mutant the divergence test exists for: an arm added without the list entry.
8735    #[test]
8736    fn an_arm_without_a_list_entry_is_caught() {
8737        let src = include_str!("vulkan_dispatch.rs");
8738        // Built from pieces so this test's own text does not contain the text it counts.
8739        let needle = concat!("QuantType::Q8_0 =", "> backend.matmul_q8_0_bytes");
8740        assert_eq!(src.matches(needle).count(), 1);
8741        let mutated = src.replacen(
8742            needle,
8743            concat!(
8744                "QuantType::Q2K =",
8745                "> backend.matmul_q2_k_bytes(a, w, out, batch_count, m, k, n),
8746            ",
8747                "QuantType::Q8_0 =",
8748                "> backend.matmul_q8_0_bytes"
8749            ),
8750            1,
8751        );
8752        assert_ne!(arms_in(&mutated), listed(), "the mutant was not caught");
8753    }
8754}