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