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