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 /// Whether [`qmatmul_vk`] has a kernel for `quant_type`. The ONE list of wired types: `qmatmul_vk`
4177 /// refuses every other type before its match, and `fuel-tensor`'s `WeightStorage::from_ggml_bytes`
4178 /// (feature `vulkan`) keeps a GGUF weight quantized only when this returns true, so the two cannot
4179 /// drift apart. Add a type here in the same change that adds its arm to `qmatmul_vk`.
4180 pub const fn qmatmul_wired(quant_type: QuantType) -> bool {
4181 matches!(
4182 quant_type,
4183 QuantType::Q4_0
4184 | QuantType::Q4_K_M
4185 | QuantType::Q8_0
4186 | QuantType::Q6K
4187 | QuantType::Q5K
4188 | QuantType::Q3K
4189 | QuantType::Iq4Nl
4190 | QuantType::Iq4Xs
4191 | QuantType::Iq3S
4192 )
4193 }
4194
4195 /// `qmatmul_vk` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
4196 pub fn qmatmul_vk(
4197 inputs: &[Arc<RwLock<Storage>>],
4198 outputs: &mut [Arc<RwLock<Storage>>],
4199 _layouts: &[Layout],
4200 params: &OpParams,
4201 ) -> Result<()> {
4202 if inputs.len() != 2 || outputs.len() != 1 {
4203 return Err(Error::Msg(format!(
4204 "vulkan_dispatch::qmatmul: expected 2 inputs + 1 output, got {} + {}",
4205 inputs.len(),
4206 outputs.len(),
4207 ))
4208 .bt());
4209 }
4210 let (quant_type, batch_count, m, n, k) = match params {
4211 OpParams::QMatMul {
4212 quant_type,
4213 batch_count,
4214 m,
4215 n,
4216 k,
4217 } => (*quant_type, *batch_count, *m, *n, *k),
4218 other => {
4219 return Err(Error::Msg(format!(
4220 "vulkan_dispatch::qmatmul: expected OpParams::QMatMul, got {:?}",
4221 other,
4222 ))
4223 .bt());
4224 }
4225 };
4226 if !qmatmul_wired(quant_type) {
4227 return Err(Error::Msg(format!(
4228 "vulkan_dispatch::qmatmul: QuantType {quant_type:?} not wired on Vulkan; add a dequant-then-matmul path or a fused kernel and retry"
4229 ))
4230 .bt());
4231 }
4232 let a_guard = read_storage(&inputs[0])?;
4233 let w_guard = read_storage(&inputs[1])?;
4234 let mut out_guard = write_storage(&outputs[0])?;
4235 let a = vulkan_input(&a_guard)?;
4236 let w = vulkan_input(&w_guard)?;
4237 let backend = a.backend().ok_or_else(|| {
4238 Error::Msg("vulkan_dispatch::qmatmul: input has no VulkanBackend handle.".to_string())
4239 .bt()
4240 })?;
4241 let out = vulkan_output(&mut out_guard)?;
4242 match quant_type {
4243 QuantType::Q4_0 => backend.matmul_q4_0_bytes(a, w, out, batch_count, m, k, n),
4244 QuantType::Q4_K_M => backend.matmul_q4_km_bytes(a, w, out, batch_count, m, k, n),
4245 QuantType::Q8_0 => backend.matmul_q8_0_bytes(a, w, out, batch_count, m, k, n),
4246 QuantType::Q6K => backend.matmul_q6_k_bytes(a, w, out, batch_count, m, k, n),
4247 QuantType::Q5K => backend.matmul_q5_k_bytes(a, w, out, batch_count, m, k, n),
4248 QuantType::Q3K => backend.matmul_q3_k_bytes(a, w, out, batch_count, m, k, n),
4249 QuantType::Iq4Nl => backend.matmul_iq4_nl_bytes(a, w, out, batch_count, m, k, n),
4250 QuantType::Iq4Xs => backend.matmul_iq4_xs_bytes(a, w, out, batch_count, m, k, n),
4251 QuantType::Iq3S => backend.matmul_iq3_s_bytes(a, w, out, batch_count, m, k, n),
4252 other => Err(Error::Msg(format!(
4253 "vulkan_dispatch::qmatmul: QuantType {other:?} not wired on Vulkan; \
4254 add a dequant-then-matmul path or a fused kernel and retry"
4255 ))
4256 .bt()),
4257 }
4258 }
4259}
4260
4261// ===========================================================================
4262// Conv2D f32 — im2col + matmul, groups=1.
4263// ===========================================================================
4264
4265/// Vulkan dispatch wrappers for FlashAttention-shape attention forward and backward.
4266pub mod flash_attn {
4267 use super::*;
4268
4269 /// FlashAttention-shape multi-head attention forward, f32 only.
4270 /// Naive single-pass kernel (NOT tiled). Supports GQA, causal,
4271 /// scale, alibi; falls through to other backends on window_left /
4272 /// window_right / softcap.
4273 pub fn flash_attn_f32(
4274 inputs: &[Arc<RwLock<Storage>>],
4275 outputs: &mut [Arc<RwLock<Storage>>],
4276 _layouts: &[Layout],
4277 params: &OpParams,
4278 ) -> Result<()> {
4279 if inputs.len() < 3 || inputs.len() > 4 || outputs.len() != 1 {
4280 return Err(Error::Msg(format!(
4281 "vulkan_dispatch::flash_attn::flash_attn_f32: expected 3-4 inputs (q, k, v, [alibi]) + 1 output, got {} + {}",
4282 inputs.len(), outputs.len(),
4283 )).bt());
4284 }
4285 let (b, hq, hkv, sq, sk, d, scale, causal, wl, wr, softcap) = match params {
4286 OpParams::FlashAttn {
4287 b,
4288 hq,
4289 hkv,
4290 sq,
4291 sk,
4292 d,
4293 k_len,
4294 softmax_scale,
4295 causal,
4296 window_size_left,
4297 window_size_right,
4298 softcap,
4299 } => {
4300 // Vulkan flash v1 reads the full K extent; a runtime
4301 // k_len (capacity-K, Phase D) isn't supported here. The
4302 // route picker keeps decode's capacity-K flash on CUDA.
4303 if *k_len != *sk {
4304 return Err(Error::Msg(format!(
4305 "vulkan_dispatch::flash_attn: runtime k_len ({}) != K capacity ({}) \
4306 not supported on Vulkan v1; route picker should fall back to CPU/CUDA",
4307 *k_len, *sk,
4308 ))
4309 .bt());
4310 }
4311 (
4312 *b,
4313 *hq,
4314 *hkv,
4315 *sq,
4316 *sk,
4317 *d,
4318 *softmax_scale,
4319 *causal,
4320 *window_size_left,
4321 *window_size_right,
4322 *softcap,
4323 )
4324 }
4325 other => {
4326 return Err(Error::Msg(format!(
4327 "vulkan_dispatch::flash_attn::flash_attn_f32: expected OpParams::FlashAttn, got {other:?}",
4328 )).bt());
4329 }
4330 };
4331 if wl.is_some() || wr.is_some() || softcap.is_some() {
4332 return Err(Error::Msg(format!(
4333 "vulkan_dispatch::flash_attn::flash_attn_f32: window_left={wl:?}, window_right={wr:?}, softcap={softcap:?} \
4334 not supported on Vulkan v1; route picker should fall back to CPU/CUDA",
4335 )).bt());
4336 }
4337
4338 let q_guard = read_storage(&inputs[0])?;
4339 let k_guard = read_storage(&inputs[1])?;
4340 let v_guard = read_storage(&inputs[2])?;
4341 let alibi_guard = match inputs.get(3) {
4342 Some(arc) => Some(read_storage(arc)?),
4343 None => None,
4344 };
4345 let mut out_guard = write_storage(&outputs[0])?;
4346 let q = vulkan_input(&q_guard)?;
4347 let k = vulkan_input(&k_guard)?;
4348 let v = vulkan_input(&v_guard)?;
4349 let alibi = match &alibi_guard {
4350 Some(g) => Some(vulkan_input(g)?),
4351 None => None,
4352 };
4353 let backend = q.backend().ok_or_else(|| {
4354 Error::Msg(
4355 "vulkan_dispatch::flash_attn::flash_attn_f32: q has no VulkanBackend handle."
4356 .to_string(),
4357 )
4358 .bt()
4359 })?;
4360 let out = vulkan_output(&mut out_guard)?;
4361 match decode_splits(b, hq, sq, sk) {
4362 Some(splits) => backend.flash_attn_f32_split_bytes(
4363 q, k, v, alibi, out, b, hq, hkv, sq, sk, d, scale, causal, splits,
4364 ),
4365 None => backend
4366 .flash_attn_f32_bytes(q, k, v, alibi, out, b, hq, hkv, sq, sk, d, scale, causal),
4367 }
4368 }
4369
4370 /// FlashAttention forward, bf16. Inputs / outputs / alibi all
4371 /// bf16; math at f32. Same shape contract and constraint set as
4372 /// the f32 variant.
4373 pub fn flash_attn_bf16(
4374 inputs: &[Arc<RwLock<Storage>>],
4375 outputs: &mut [Arc<RwLock<Storage>>],
4376 _layouts: &[Layout],
4377 params: &OpParams,
4378 ) -> Result<()> {
4379 flash_attn_half_typed(
4380 inputs,
4381 outputs,
4382 params,
4383 DType::BF16,
4384 "flash_attn_bf16",
4385 |backend, q, k, v, a, out, b, hq, hkv, sq, sk, d, scale, causal| match decode_splits(
4386 b, hq, sq, sk,
4387 ) {
4388 Some(n) => backend.flash_attn_bf16_split_bytes(
4389 q, k, v, a, out, b, hq, hkv, sq, sk, d, scale, causal, n,
4390 ),
4391 None => backend
4392 .flash_attn_bf16_bytes(q, k, v, a, out, b, hq, hkv, sq, sk, d, scale, causal),
4393 },
4394 )
4395 }
4396
4397 /// FlashAttention forward, f16. Inputs / outputs / alibi all f16.
4398 pub fn flash_attn_f16(
4399 inputs: &[Arc<RwLock<Storage>>],
4400 outputs: &mut [Arc<RwLock<Storage>>],
4401 _layouts: &[Layout],
4402 params: &OpParams,
4403 ) -> Result<()> {
4404 flash_attn_half_typed(
4405 inputs,
4406 outputs,
4407 params,
4408 DType::F16,
4409 "flash_attn_f16",
4410 |backend, q, k, v, a, out, b, hq, hkv, sq, sk, d, scale, causal| match decode_splits(
4411 b, hq, sq, sk,
4412 ) {
4413 Some(n) => backend.flash_attn_f16_split_bytes(
4414 q, k, v, a, out, b, hq, hkv, sq, sk, d, scale, causal, n,
4415 ),
4416 None => backend
4417 .flash_attn_f16_bytes(q, k, v, a, out, b, hq, hkv, sq, sk, d, scale, causal),
4418 },
4419 )
4420 }
4421
4422 fn flash_attn_half_typed<F>(
4423 inputs: &[Arc<RwLock<Storage>>],
4424 outputs: &mut [Arc<RwLock<Storage>>],
4425 params: &OpParams,
4426 expected_dtype: DType,
4427 debug_name: &'static str,
4428 f: F,
4429 ) -> Result<()>
4430 where
4431 F: FnOnce(
4432 &fuel_vulkan_backend::VulkanBackend,
4433 &fuel_vulkan_backend::VulkanStorageBytes,
4434 &fuel_vulkan_backend::VulkanStorageBytes,
4435 &fuel_vulkan_backend::VulkanStorageBytes,
4436 Option<&fuel_vulkan_backend::VulkanStorageBytes>,
4437 &mut fuel_vulkan_backend::VulkanStorageBytes,
4438 usize,
4439 usize,
4440 usize,
4441 usize,
4442 usize,
4443 usize,
4444 f32,
4445 bool,
4446 ) -> Result<()>,
4447 {
4448 if inputs.len() < 3 || inputs.len() > 4 || outputs.len() != 1 {
4449 return Err(Error::Msg(format!(
4450 "vulkan_dispatch::flash_attn::{debug_name}: expected 3-4 inputs + 1 output, got {} + {}",
4451 inputs.len(), outputs.len(),
4452 )).bt());
4453 }
4454 let (b, hq, hkv, sq, sk, d, scale, causal, wl, wr, softcap) = match params {
4455 OpParams::FlashAttn {
4456 b,
4457 hq,
4458 hkv,
4459 sq,
4460 sk,
4461 d,
4462 k_len,
4463 softmax_scale,
4464 causal,
4465 window_size_left,
4466 window_size_right,
4467 softcap,
4468 } => {
4469 // Vulkan flash v1 reads the full K extent; a runtime
4470 // k_len (capacity-K, Phase D) isn't supported here. The
4471 // route picker keeps decode's capacity-K flash on CUDA.
4472 if *k_len != *sk {
4473 return Err(Error::Msg(format!(
4474 "vulkan_dispatch::flash_attn: runtime k_len ({}) != K capacity ({}) \
4475 not supported on Vulkan v1; route picker should fall back to CPU/CUDA",
4476 *k_len, *sk,
4477 ))
4478 .bt());
4479 }
4480 (
4481 *b,
4482 *hq,
4483 *hkv,
4484 *sq,
4485 *sk,
4486 *d,
4487 *softmax_scale,
4488 *causal,
4489 *window_size_left,
4490 *window_size_right,
4491 *softcap,
4492 )
4493 }
4494 other => {
4495 return Err(Error::Msg(format!(
4496 "vulkan_dispatch::flash_attn::{debug_name}: expected OpParams::FlashAttn, got {other:?}",
4497 )).bt());
4498 }
4499 };
4500 if wl.is_some() || wr.is_some() || softcap.is_some() {
4501 return Err(Error::Msg(format!(
4502 "vulkan_dispatch::flash_attn::{debug_name}: window/softcap not supported on Vulkan v1",
4503 )).bt());
4504 }
4505
4506 let q_guard = read_storage(&inputs[0])?;
4507 let k_guard = read_storage(&inputs[1])?;
4508 let v_guard = read_storage(&inputs[2])?;
4509 let alibi_guard = match inputs.get(3) {
4510 Some(arc) => Some(read_storage(arc)?),
4511 None => None,
4512 };
4513 for (name, dt) in [
4514 ("q", q_guard.dtype),
4515 ("k", k_guard.dtype),
4516 ("v", v_guard.dtype),
4517 ] {
4518 if dt != expected_dtype {
4519 return Err(Error::Msg(format!(
4520 "vulkan_dispatch::flash_attn::{debug_name}: {name} must be {expected_dtype:?}, got {dt:?}",
4521 )).bt());
4522 }
4523 }
4524 if let Some(g) = &alibi_guard
4525 && g.dtype != expected_dtype
4526 {
4527 return Err(Error::Msg(format!(
4528 "vulkan_dispatch::flash_attn::{debug_name}: alibi must be {expected_dtype:?}, got {:?}", g.dtype,
4529 )).bt());
4530 }
4531 let mut out_guard = write_storage(&outputs[0])?;
4532 let q = vulkan_input(&q_guard)?;
4533 let k = vulkan_input(&k_guard)?;
4534 let v = vulkan_input(&v_guard)?;
4535 let alibi = match &alibi_guard {
4536 Some(g) => Some(vulkan_input(g)?),
4537 None => None,
4538 };
4539 let backend = q.backend().ok_or_else(|| {
4540 Error::Msg(format!(
4541 "vulkan_dispatch::flash_attn::{debug_name}: q has no VulkanBackend handle.",
4542 ))
4543 .bt()
4544 })?;
4545 let out = vulkan_output(&mut out_guard)?;
4546 f(
4547 backend, q, k, v, alibi, out, b, hq, hkv, sq, sk, d, scale, causal,
4548 )
4549 }
4550
4551 /// FlashAttention backward — dQ, f32. Inputs (q, k, v, dO, `[alibi]`);
4552 /// output dQ (same shape as Q). Bails on window/softcap (route
4553 /// picker falls through to CPU).
4554 pub fn flash_attn_backward_q_f32(
4555 inputs: &[Arc<RwLock<Storage>>],
4556 outputs: &mut [Arc<RwLock<Storage>>],
4557 _layouts: &[Layout],
4558 params: &OpParams,
4559 ) -> Result<()> {
4560 flash_attn_backward_f32_typed(
4561 inputs,
4562 outputs,
4563 params,
4564 "flash_attn_backward_q_f32",
4565 |backend, q, k, v, dgrad, a, out, b, hq, hkv, sq, sk, d, scale, causal| {
4566 backend.flash_attn_backward_q_f32_bytes(
4567 q, k, v, dgrad, a, out, b, hq, hkv, sq, sk, d, scale, causal,
4568 )
4569 },
4570 )
4571 }
4572
4573 /// FlashAttention backward — dK, f32.
4574 pub fn flash_attn_backward_k_f32(
4575 inputs: &[Arc<RwLock<Storage>>],
4576 outputs: &mut [Arc<RwLock<Storage>>],
4577 _layouts: &[Layout],
4578 params: &OpParams,
4579 ) -> Result<()> {
4580 flash_attn_backward_f32_typed(
4581 inputs,
4582 outputs,
4583 params,
4584 "flash_attn_backward_k_f32",
4585 |backend, q, k, v, dgrad, a, out, b, hq, hkv, sq, sk, d, scale, causal| {
4586 backend.flash_attn_backward_k_f32_bytes(
4587 q, k, v, dgrad, a, out, b, hq, hkv, sq, sk, d, scale, causal,
4588 )
4589 },
4590 )
4591 }
4592
4593 /// FlashAttention backward — dV, f32.
4594 pub fn flash_attn_backward_v_f32(
4595 inputs: &[Arc<RwLock<Storage>>],
4596 outputs: &mut [Arc<RwLock<Storage>>],
4597 _layouts: &[Layout],
4598 params: &OpParams,
4599 ) -> Result<()> {
4600 flash_attn_backward_f32_typed(
4601 inputs,
4602 outputs,
4603 params,
4604 "flash_attn_backward_v_f32",
4605 |backend, q, k, v, dgrad, a, out, b, hq, hkv, sq, sk, d, scale, causal| {
4606 backend.flash_attn_backward_v_f32_bytes(
4607 q, k, v, dgrad, a, out, b, hq, hkv, sq, sk, d, scale, causal,
4608 )
4609 },
4610 )
4611 }
4612
4613 /// Shared dispatch shim body for the three FA backward variants.
4614 /// Validates input counts (4-5: Q, K, V, dO, optional alibi),
4615 /// extracts shape params, asserts all inputs are F32, then hands
4616 /// off to the per-variant backend method.
4617 fn flash_attn_backward_f32_typed<F>(
4618 inputs: &[Arc<RwLock<Storage>>],
4619 outputs: &mut [Arc<RwLock<Storage>>],
4620 params: &OpParams,
4621 debug_name: &'static str,
4622 f: F,
4623 ) -> Result<()>
4624 where
4625 F: FnOnce(
4626 &fuel_vulkan_backend::VulkanBackend,
4627 &fuel_vulkan_backend::VulkanStorageBytes,
4628 &fuel_vulkan_backend::VulkanStorageBytes,
4629 &fuel_vulkan_backend::VulkanStorageBytes,
4630 &fuel_vulkan_backend::VulkanStorageBytes,
4631 Option<&fuel_vulkan_backend::VulkanStorageBytes>,
4632 &mut fuel_vulkan_backend::VulkanStorageBytes,
4633 usize,
4634 usize,
4635 usize,
4636 usize,
4637 usize,
4638 usize,
4639 f32,
4640 bool,
4641 ) -> Result<()>,
4642 {
4643 if inputs.len() < 4 || inputs.len() > 5 || outputs.len() != 1 {
4644 return Err(Error::Msg(format!(
4645 "vulkan_dispatch::flash_attn::{debug_name}: expected 4-5 inputs (q, k, v, do, [alibi]) + 1 output, got {} + {}",
4646 inputs.len(), outputs.len(),
4647 )).bt());
4648 }
4649 let (b, hq, hkv, sq, sk, d, scale, causal, wl, wr, softcap) = match params {
4650 OpParams::FlashAttn {
4651 b,
4652 hq,
4653 hkv,
4654 sq,
4655 sk,
4656 d,
4657 k_len,
4658 softmax_scale,
4659 causal,
4660 window_size_left,
4661 window_size_right,
4662 softcap,
4663 } => {
4664 // Vulkan flash v1 reads the full K extent; a runtime
4665 // k_len (capacity-K, Phase D) isn't supported here. The
4666 // route picker keeps decode's capacity-K flash on CUDA.
4667 if *k_len != *sk {
4668 return Err(Error::Msg(format!(
4669 "vulkan_dispatch::flash_attn: runtime k_len ({}) != K capacity ({}) \
4670 not supported on Vulkan v1; route picker should fall back to CPU/CUDA",
4671 *k_len, *sk,
4672 ))
4673 .bt());
4674 }
4675 (
4676 *b,
4677 *hq,
4678 *hkv,
4679 *sq,
4680 *sk,
4681 *d,
4682 *softmax_scale,
4683 *causal,
4684 *window_size_left,
4685 *window_size_right,
4686 *softcap,
4687 )
4688 }
4689 other => {
4690 return Err(Error::Msg(format!(
4691 "vulkan_dispatch::flash_attn::{debug_name}: expected OpParams::FlashAttn, got {other:?}",
4692 )).bt());
4693 }
4694 };
4695 if wl.is_some() || wr.is_some() || softcap.is_some() {
4696 return Err(Error::Msg(format!(
4697 "vulkan_dispatch::flash_attn::{debug_name}: window/softcap not supported on Vulkan v1",
4698 )).bt());
4699 }
4700
4701 let q_guard = read_storage(&inputs[0])?;
4702 let k_guard = read_storage(&inputs[1])?;
4703 let v_guard = read_storage(&inputs[2])?;
4704 let do_guard = read_storage(&inputs[3])?;
4705 let alibi_guard = match inputs.get(4) {
4706 Some(arc) => Some(read_storage(arc)?),
4707 None => None,
4708 };
4709 for (name, dt) in [
4710 ("q", q_guard.dtype),
4711 ("k", k_guard.dtype),
4712 ("v", v_guard.dtype),
4713 ("do", do_guard.dtype),
4714 ] {
4715 if dt != DType::F32 {
4716 return Err(Error::Msg(format!(
4717 "vulkan_dispatch::flash_attn::{debug_name}: {name} must be F32, got {dt:?}",
4718 ))
4719 .bt());
4720 }
4721 }
4722 if let Some(g) = &alibi_guard
4723 && g.dtype != DType::F32
4724 {
4725 return Err(Error::Msg(format!(
4726 "vulkan_dispatch::flash_attn::{debug_name}: alibi must be F32, got {:?}",
4727 g.dtype,
4728 ))
4729 .bt());
4730 }
4731 let mut out_guard = write_storage(&outputs[0])?;
4732 let q = vulkan_input(&q_guard)?;
4733 let k = vulkan_input(&k_guard)?;
4734 let v = vulkan_input(&v_guard)?;
4735 let do_storage = vulkan_input(&do_guard)?;
4736 let alibi = match &alibi_guard {
4737 Some(g) => Some(vulkan_input(g)?),
4738 None => None,
4739 };
4740 let backend = q.backend().ok_or_else(|| {
4741 Error::Msg(format!(
4742 "vulkan_dispatch::flash_attn::{debug_name}: q has no VulkanBackend handle.",
4743 ))
4744 .bt()
4745 })?;
4746 let out = vulkan_output(&mut out_guard)?;
4747 f(
4748 backend, q, k, v, do_storage, alibi, out, b, hq, hkv, sq, sk, d, scale, causal,
4749 )
4750 }
4751}
4752
4753/// Vulkan dispatch wrappers for 2-D convolution, per dtype.
4754pub mod conv2d {
4755 use super::*;
4756
4757 /// `conv2d_f32` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
4758 pub fn conv2d_f32(
4759 inputs: &[Arc<RwLock<Storage>>],
4760 outputs: &mut [Arc<RwLock<Storage>>],
4761 _layouts: &[Layout],
4762 params: &OpParams,
4763 ) -> Result<()> {
4764 if inputs.len() < 2 || inputs.len() > 3 || outputs.len() != 1 {
4765 return Err(Error::Msg(format!(
4766 "vulkan_dispatch::conv2d::conv2d_f32: expected 2-3 inputs + 1 output, got {} + {}",
4767 inputs.len(),
4768 outputs.len(),
4769 ))
4770 .bt());
4771 }
4772 if inputs.len() == 3 {
4773 // Vulkan conv2d doesn't fuse bias yet; route picker should
4774 // pick a different alternative (CPU/CUDA fused). Bail loudly
4775 // rather than silently producing wrong output.
4776 return Err(Error::Msg(
4777 "vulkan_dispatch::conv2d::conv2d_f32: bias-fused conv2d not supported \
4778 on Vulkan yet; bias is a follow-up. Route picker should choose a \
4779 fused-conv alternative (CPU/CUDA) when bias is present."
4780 .to_string(),
4781 )
4782 .bt());
4783 }
4784 let (x_shape, w_shape, stride, padding, dilation, groups) = match params {
4785 OpParams::Conv2D {
4786 x_shape,
4787 w_shape,
4788 out_shape: _,
4789 stride,
4790 padding,
4791 dilation,
4792 groups,
4793 } => (*x_shape, *w_shape, *stride, *padding, *dilation, *groups),
4794 other => {
4795 return Err(Error::Msg(format!(
4796 "vulkan_dispatch::conv2d::conv2d_f32: expected OpParams::Conv2D, got {:?}",
4797 other,
4798 ))
4799 .bt());
4800 }
4801 };
4802 if dilation != (1, 1) {
4803 return Err(Error::Msg(format!(
4804 "vulkan_dispatch::conv2d::conv2d_f32: dilation {dilation:?} != (1,1) \
4805 not yet supported on Vulkan; route picker should fall back to CPU/CUDA"
4806 ))
4807 .bt());
4808 }
4809 let in_guard = read_storage(&inputs[0])?;
4810 let w_guard = read_storage(&inputs[1])?;
4811 let mut out_guard = write_storage(&outputs[0])?;
4812 let input = vulkan_input(&in_guard)?;
4813 let weight = vulkan_input(&w_guard)?;
4814 let backend = input.backend().ok_or_else(|| {
4815 Error::Msg(
4816 "vulkan_dispatch::conv2d::conv2d_f32: input has no VulkanBackend handle."
4817 .to_string(),
4818 )
4819 .bt()
4820 })?;
4821 let out = vulkan_output(&mut out_guard)?;
4822 backend.conv2d_f32_bytes(
4823 input, weight, out, x_shape, w_shape, stride, padding, groups,
4824 )
4825 }
4826
4827 /// Conv2D bf16 via im2col_bf16 + cooperative-matrix bf16 matmul.
4828 /// Same shape contract as the f32 path; activations + weights +
4829 /// output all bf16. COOP-ONLY shape constraints: c_out % 16 == 0
4830 /// AND (h_out * w_out) % 16 == 0. Bails on small shapes — route
4831 /// picker should fall through to f32 conv2d via Cast.
4832 pub fn conv2d_bf16(
4833 inputs: &[Arc<RwLock<Storage>>],
4834 outputs: &mut [Arc<RwLock<Storage>>],
4835 _layouts: &[Layout],
4836 params: &OpParams,
4837 ) -> Result<()> {
4838 if inputs.len() < 2 || inputs.len() > 3 || outputs.len() != 1 {
4839 return Err(Error::Msg(format!(
4840 "vulkan_dispatch::conv2d::conv2d_bf16: expected 2-3 inputs + 1 output, got {} + {}",
4841 inputs.len(),
4842 outputs.len(),
4843 ))
4844 .bt());
4845 }
4846 if inputs.len() == 3 {
4847 return Err(Error::Msg(
4848 "vulkan_dispatch::conv2d::conv2d_bf16: bias-fused conv2d not supported \
4849 on Vulkan yet; route picker should pick a fused-conv alternative when \
4850 bias is present."
4851 .to_string(),
4852 )
4853 .bt());
4854 }
4855 let (x_shape, w_shape, stride, padding, dilation, groups) = match params {
4856 OpParams::Conv2D {
4857 x_shape,
4858 w_shape,
4859 out_shape: _,
4860 stride,
4861 padding,
4862 dilation,
4863 groups,
4864 } => (*x_shape, *w_shape, *stride, *padding, *dilation, *groups),
4865 other => {
4866 return Err(Error::Msg(format!(
4867 "vulkan_dispatch::conv2d::conv2d_bf16: expected OpParams::Conv2D, got {other:?}",
4868 )).bt());
4869 }
4870 };
4871 if dilation != (1, 1) {
4872 return Err(Error::Msg(format!(
4873 "vulkan_dispatch::conv2d::conv2d_bf16: dilation {dilation:?} != (1,1) \
4874 not yet supported on Vulkan; route picker should fall back to CPU/CUDA",
4875 ))
4876 .bt());
4877 }
4878 let in_guard = read_storage(&inputs[0])?;
4879 let w_guard = read_storage(&inputs[1])?;
4880 let mut out_guard = write_storage(&outputs[0])?;
4881 let input = vulkan_input(&in_guard)?;
4882 let weight = vulkan_input(&w_guard)?;
4883 let backend = input.backend().ok_or_else(|| {
4884 Error::Msg(
4885 "vulkan_dispatch::conv2d::conv2d_bf16: input has no VulkanBackend handle."
4886 .to_string(),
4887 )
4888 .bt()
4889 })?;
4890 let out = vulkan_output(&mut out_guard)?;
4891 backend.conv2d_bf16_bytes(
4892 input, weight, out, x_shape, w_shape, stride, padding, groups,
4893 )
4894 }
4895
4896 /// Conv2D f16 — sibling of `conv2d_bf16`. Reuses the bf16 im2col
4897 /// shader (2-byte shuffle is dtype-opaque) + matmul_coop_f16_f16_f16.
4898 pub fn conv2d_f16(
4899 inputs: &[Arc<RwLock<Storage>>],
4900 outputs: &mut [Arc<RwLock<Storage>>],
4901 _layouts: &[Layout],
4902 params: &OpParams,
4903 ) -> Result<()> {
4904 if inputs.len() < 2 || inputs.len() > 3 || outputs.len() != 1 {
4905 return Err(Error::Msg(format!(
4906 "vulkan_dispatch::conv2d::conv2d_f16: expected 2-3 inputs + 1 output, got {} + {}",
4907 inputs.len(),
4908 outputs.len(),
4909 ))
4910 .bt());
4911 }
4912 if inputs.len() == 3 {
4913 return Err(Error::Msg(
4914 "vulkan_dispatch::conv2d::conv2d_f16: bias-fused conv2d not supported \
4915 on Vulkan yet"
4916 .to_string(),
4917 )
4918 .bt());
4919 }
4920 let (x_shape, w_shape, stride, padding, dilation, groups) = match params {
4921 OpParams::Conv2D {
4922 x_shape,
4923 w_shape,
4924 out_shape: _,
4925 stride,
4926 padding,
4927 dilation,
4928 groups,
4929 } => (*x_shape, *w_shape, *stride, *padding, *dilation, *groups),
4930 other => {
4931 return Err(Error::Msg(format!(
4932 "vulkan_dispatch::conv2d::conv2d_f16: expected OpParams::Conv2D, got {other:?}",
4933 ))
4934 .bt());
4935 }
4936 };
4937 if dilation != (1, 1) {
4938 return Err(Error::Msg(format!(
4939 "vulkan_dispatch::conv2d::conv2d_f16: dilation {dilation:?} != (1,1) \
4940 not yet supported on Vulkan",
4941 ))
4942 .bt());
4943 }
4944 let in_guard = read_storage(&inputs[0])?;
4945 let w_guard = read_storage(&inputs[1])?;
4946 let mut out_guard = write_storage(&outputs[0])?;
4947 let input = vulkan_input(&in_guard)?;
4948 let weight = vulkan_input(&w_guard)?;
4949 let backend = input.backend().ok_or_else(|| {
4950 Error::Msg(
4951 "vulkan_dispatch::conv2d::conv2d_f16: input has no VulkanBackend handle."
4952 .to_string(),
4953 )
4954 .bt()
4955 })?;
4956 let out = vulkan_output(&mut out_guard)?;
4957 backend.conv2d_f16_bytes(
4958 input, weight, out, x_shape, w_shape, stride, padding, groups,
4959 )
4960 }
4961}
4962
4963// ===========================================================================
4964// Cast F8E4M3 ↔ {F32, F16, BF16} — single wrapper dispatches by dtype pair
4965// ===========================================================================
4966
4967/// Vulkan dispatch wrappers for casts between F8E4M3 and F32 / F16 / BF16.
4968pub mod cast_f8e4m3 {
4969 use super::*;
4970
4971 /// `cast_f8e4m3` kernel-binding wrapper: takes the executor's inputs, outputs, layouts and `OpParams` and runs the Vulkan kernel for that op and dtype.
4972 pub fn cast_f8e4m3(
4973 inputs: &[Arc<RwLock<Storage>>],
4974 outputs: &mut [Arc<RwLock<Storage>>],
4975 _layouts: &[Layout],
4976 _params: &OpParams,
4977 ) -> Result<()> {
4978 if inputs.len() != 1 || outputs.len() != 1 {
4979 return Err(Error::Msg(format!(
4980 "vulkan_dispatch::cast_f8e4m3: expected 1 input + 1 output, got {} + {}",
4981 inputs.len(),
4982 outputs.len(),
4983 ))
4984 .bt());
4985 }
4986 let in_guard = read_storage(&inputs[0])?;
4987 let mut out_guard = write_storage(&outputs[0])?;
4988 let src_dtype = in_guard.dtype;
4989 let dst_dtype = out_guard.dtype;
4990 let src_elem = match src_dtype {
4991 DType::F32 => 4,
4992 DType::F16 => 2,
4993 DType::BF16 => 2,
4994 DType::F8E4M3 => 1,
4995 other => {
4996 return Err(Error::Msg(format!(
4997 "vulkan_dispatch::cast_f8e4m3: unsupported src dtype {other:?}",
4998 ))
4999 .bt());
5000 }
5001 };
5002 let a = vulkan_input(&in_guard)?;
5003 let n_bytes = a.len_bytes();
5004 if n_bytes % src_elem != 0 {
5005 return Err(Error::Msg(format!(
5006 "vulkan_dispatch::cast_f8e4m3: input bytes {n_bytes} not a multiple of \
5007 src elem size {src_elem} ({src_dtype:?})",
5008 ))
5009 .bt());
5010 }
5011 let n = n_bytes / src_elem;
5012 let backend = a.backend().ok_or_else(|| {
5013 Error::Msg(
5014 "vulkan_dispatch::cast_f8e4m3: input has no VulkanBackend handle.".to_string(),
5015 )
5016 .bt()
5017 })?;
5018 let out = vulkan_output(&mut out_guard)?;
5019 backend.cast_f8e4m3_bytes(src_dtype, dst_dtype, a, out, n)
5020 }
5021}
5022
5023// ===========================================================================
5024// Op::Copy D2H — Vulkan → CPU (bridge-retirement Phase 2, post-9c)
5025// ===========================================================================
5026
5027/// Dispatch wrapper for `(OpKind::Copy, [T, T], Vulkan)` — D2H from a
5028/// Vulkan source storage into a freshly-allocated CPU output. The
5029/// executor allocates the CPU output before this wrapper runs
5030/// (see `fuel_dispatch::pipelined::WorkItemKind::Copy`); the wrapper calls
5031/// `VulkanBackend::download_bytes` on the input's attached backend
5032/// handle and copies the result into the CPU storage.
5033///
5034/// Dtype-agnostic at the byte level — one wrapper covers every dtype
5035/// registered at this key.
5036///
5037/// Replaces the Vulkan branch of `BackendStorage::read_to_cpu_bytes`
5038/// (deleted alongside) — the placeholder that
5039/// [commit 7a95001a](https://github.com/anthropics/fuel/commit/7a95001a)
5040/// introduced. After this lands, D2H is a graph node the optimizer
5041/// can see (identity check #1: "more decisions visible to the
5042/// DAG-level optimizer").
5043pub fn copy_to_cpu_vulkan(
5044 inputs: &[Arc<RwLock<Storage>>],
5045 outputs: &mut [Arc<RwLock<Storage>>],
5046 _layouts: &[Layout],
5047 _params: &OpParams,
5048) -> Result<()> {
5049 if inputs.len() != 1 || outputs.len() != 1 {
5050 return Err(Error::Msg(format!(
5051 "copy_to_cpu_vulkan: expected 1 input + 1 output, got {} + {}",
5052 inputs.len(),
5053 outputs.len(),
5054 ))
5055 .bt());
5056 }
5057 let in_guard = read_storage(&inputs[0])?;
5058 // The key is the SOURCE backend: keep the typed error for a non-Vulkan input.
5059 vulkan_input(&in_guard)?;
5060 let mut out_guard = write_storage(&outputs[0])?;
5061 // CPU output: download; Vulkan output: one vkCmdCopyBuffer into a fresh buffer. Both, and the
5062 // error for a Vulkan source with no backend handle, live in `BackendStorage::copy_from`
5063 // (ROADMAP row 137, seam S3 step 2).
5064 out_guard.inner.copy_from(&in_guard.inner)
5065}
5066
5067// ===========================================================================
5068// register_vulkan_kernels — binding-table population
5069// ===========================================================================
5070
5071/// The authored Vulkan cast (dtype-conversion) kernel contract, embedded into
5072/// the binary via `include_str!` (the PRODUCTION contract). Parsed + lowered by
5073/// [`register_vulkan_cast_from_contract`].
5074const VULKAN_CAST_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/cast.fkc.md");
5075
5076/// Register the Vulkan cast family (12 (SRC, DST) pairs → 3 production wrappers:
5077/// `cast::cast_f32_half` for f32↔f16 / f32↔bf16, `cast::cast_f32_f64` for
5078/// f32↔f64, `cast_f8e4m3::cast_f8e4m3` for the six F8E4M3 pairs) by IMPORTING
5079/// its FKC kernel contract — the **first Vulkan-backend FKC consumer**, the GPU
5080/// analogue of the CPU `register_cpu_*_from_contract` family. FKC is
5081/// unconditional core infrastructure, so this is the ONE registration path for
5082/// the family: the hand-written `table.register_with_precision(OpKind::Cast, …)`
5083/// calls (both the half/f64 block and the F8E4M3 block) are DELETED.
5084///
5085/// Each per-pair section declares a single-dtype `src` input + a `fixed(DST)`
5086/// output, so the importer keys `[SRC, DST]` — byte-for-byte the deleted regs
5087/// (the `cast(output)` dtype-rule the sections used to carry was NOT an
5088/// importer-recognized form and would have dropped the output slot from the
5089/// key; it was rewritten to the canonical `fixed(DST)` per section's documented
5090/// destination). Every `entry_point` symbol resolves through the production
5091/// [`crate::link::VulkanLinkRegistry`] to the exact same wrapper fn-pointer.
5092///
5093/// Behavior-preserving vs. the deleted hand-written path on dispatch: identical
5094/// wrappers + contiguous-only caps (`awkward_layout_strategy: requires_contiguous`
5095/// ⇒ `strided_input == false`). The binding's `kernel_source` becomes the
5096/// contract's `"vulkan-slang"` tag and its precision the contract's audited
5097/// claim — the shared `VULKAN_CAST_PRECISION` const the regs used to carry
5098/// (`max_ulp: Some(0)`) is retired; the contract's per-section `max_ulp: ~`
5099/// author seed is what the Judge now audits (both keep
5100/// `bit_stable_on_same_hardware: true`). Cost is preserved because this runs
5101/// BEFORE the `fill_unset_cost_for_backend` pass, which upgrades the imported
5102/// entries' `unknown_cost` sentinel to the same OpKind cost fn every Vulkan
5103/// primitive gets.
5104///
5105/// The family declares NO fused ops, so `register_into`'s required fused
5106/// argument is a local throwaway that provably stays empty. Init-boundary
5107/// fail-fast: a parse/lower/link failure of the embedded, authored contract is
5108/// a programmer error surfaced once here via `expect` (mirroring the CPU
5109/// `register_cpu_*_from_contract` convention); it cannot fail for a runtime-data
5110/// reason.
5111fn register_vulkan_cast_from_contract(table: &mut KernelBindingTable) {
5112 let provider = fuel_dispatch::fkc::import_bundle_str(
5113 VULKAN_CAST_CONTRACT,
5114 &crate::link::VulkanLinkRegistry,
5115 )
5116 .expect(
5117 "authored Vulkan cast contract must import \
5118 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5119 );
5120 debug_assert!(
5121 provider.fused.is_empty(),
5122 "vulkan cast contract declares no fused ops",
5123 );
5124 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5125 provider
5126 .register_into(table, &mut fused)
5127 .expect("Vulkan cast contract must register into the binding table");
5128}
5129
5130/// The authored Vulkan elementwise kernel contract (unary / binary / affine /
5131/// clamp / powi), embedded via `include_str!` (the PRODUCTION contract). Parsed
5132/// + lowered by [`register_vulkan_elementwise_from_contract`].
5133const VULKAN_ELEMENTWISE_CONTRACT: &str =
5134 include_str!("../kernel-contracts/vulkan/elementwise.fkc.md");
5135
5136/// Register the Vulkan elementwise family (94 (op, dtype) bindings) by IMPORTING
5137/// its RE-AUTHORED FKC kernel contract — the SECOND Vulkan-backend FKC consumer
5138/// after the cast family, and the first **caps-through-import** production proof.
5139///
5140/// The contract was re-authored per-op (the CPU inplace precedent): the old
5141/// representative-chassis `unary`/`binary` op_id-selector sections could each
5142/// register only ONE OpKind, so they are SUPERSEDED by 16 per-op unary sections
5143/// (each fanning `[F32, F16, F64]` on a base `entry_point`, §3.4) + 16 bf16-unary
5144/// sections + 6 per-op binary sections (fanning `[F32, F16, F64, BF16]`) + an
5145/// affine strided-fan + affine_bf16 + clamp + powi. Every `entry_point` symbol
5146/// resolves through [`crate::link::VulkanLinkRegistry`] to the exact same
5147/// per-(op, dtype) wrapper the deleted hand-written regs used.
5148///
5149/// **Caps ride through truthfully.** Each section's per-operand five-flag layout
5150/// projects onto `KernelCaps.strided_input` (`caps_map::project_kernel_caps`),
5151/// stamped onto the binding by the importer: the strided unary/binary/affine/
5152/// clamp/powi sections yield `strided_input=true` (byte-for-byte the deleted
5153/// `register_with_caps_and_precision(strided)` regs) and the contiguous-only
5154/// bf16-unary / affine_bf16 sections yield `strided_input=false` (the deleted
5155/// plain `register_with_precision` regs). Precision becomes the contract's author
5156/// seed (`audited: false` ⇒ `PrecisionGuarantee::UNAUDITED`; the Judge audits
5157/// later) — the same posture the cast migration took; the hand-written
5158/// `VULKAN_{FLOAT,HALF,TRANSCENDENTAL}_POINTWISE_PRECISION` consts are retired
5159/// from this seam. Cost is preserved because this runs BEFORE
5160/// `fill_unset_cost_for_backend`, which upgrades the imported `unknown_cost`
5161/// sentinels to the same OpKind cost fn.
5162///
5163/// The contract's `add_assign_scaled` + `unary`/`binary` chassis sections are
5164/// `registrable: false` describe-only (§3.10) and register nothing. Init-boundary
5165/// fail-fast: a parse/lower/link failure of the embedded contract is a programmer
5166/// error surfaced once here via `expect`.
5167fn register_vulkan_elementwise_from_contract(table: &mut KernelBindingTable) {
5168 let provider = fuel_dispatch::fkc::import_bundle_str(
5169 VULKAN_ELEMENTWISE_CONTRACT,
5170 &crate::link::VulkanLinkRegistry,
5171 )
5172 .expect(
5173 "authored Vulkan elementwise contract must import \
5174 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5175 );
5176 debug_assert!(
5177 provider.fused.is_empty(),
5178 "vulkan elementwise contract declares no fused ops",
5179 );
5180 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5181 provider
5182 .register_into(table, &mut fused)
5183 .expect("Vulkan elementwise contract must register into the binding table");
5184}
5185
5186/// The authored Vulkan matmul kernel contract (6 per-combo GEMM/GEMV wrapper
5187/// bindings), embedded via `include_str!` (the PRODUCTION contract). Parsed +
5188/// lowered by [`register_vulkan_matmul_from_contract`].
5189const VULKAN_MATMUL_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/matmul.fkc.md");
5190
5191/// Register the Vulkan matmul family (6 (MatMul, [lhs,rhs,out]) bindings) by
5192/// IMPORTING its RE-AUTHORED FKC kernel contract — the THIRD Vulkan-backend FKC
5193/// consumer after cast + elementwise. FKC is unconditional core infrastructure,
5194/// so this is the ONE registration path for the family: the hand-written
5195/// `table.register_with_precision(OpKind::MatMul, …)` regs (the f32 GEMM +
5196/// the five mixed-precision / tensor-core combos) are DELETED.
5197///
5198/// The contract was re-authored per-combo (the cast family's per-pair
5199/// precedent): the aspirational multi-dtype `dispatch/matmul.fkc.md ::
5200/// matmul_mixed_precision` section (lhs `[F32,BF16,F16]` vs rhs `[BF16,F16]` —
5201/// DIFFERENT lists, a `FanoutDtypeMismatch` the uniform fan-out importer cannot
5202/// key) is SUPERSEDED by six single-dtype-per-operand sections, each declaring a
5203/// specific `entry_point` symbol that resolves through
5204/// [`crate::link::VulkanLinkRegistry`] to the exact production wrapper. Each
5205/// wrapper route-picks its internal Slang kernels (matvec / reg-tile / tiled for
5206/// f32; matvec_bf16_b / matmul_tiled_bf16_b / matmul_coop* + matmul_small_*
5207/// fallbacks for the mixed combos) at dispatch time — that route-pick is NOT a
5208/// binding, so there is exactly ONE `KernelRef` per key.
5209///
5210/// **Caps ride through truthfully.** Each section's `requires_contiguous`
5211/// layout projects `strided_input == false` — byte-for-byte the deleted
5212/// `register_with_precision` regs (the coop / vec4 loads require canonical
5213/// row-major; a strided / transposed / offset operand is auto-Contiguized by the
5214/// planner first). Precision becomes the contract's audited seed
5215/// (nondeterministic, `bit_stable_on_same_hardware: false`, audited `none(reason)`
5216/// — the corrected 2026-06-18 posture, honest about scheduler-dependent
5217/// FADD/subgroup order) rather than the retired hand-written
5218/// `VULKAN_MATMUL_PRECISION` / `VULKAN_MATMUL_TENSORCORE_PRECISION` consts (which
5219/// mis-declared `bit_stable_on_same_hardware: true`). At the matmul migration
5220/// those consts were left in use by the Vulkan conv2d family; conv2d has since
5221/// migrated to its own FKC contract, so they are now dropped from this seam too
5222/// (the `pub const` defs stay in `fused.rs`, mirroring VULKAN_TRANSCENDENTAL).
5223/// Cost is preserved because this runs BEFORE `fill_unset_cost_for_backend`,
5224/// which upgrades the imported `unknown_cost` sentinels to the same OpKind cost fn.
5225///
5226/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5227/// failure of the embedded, authored contract is a programmer error surfaced once
5228/// here via `expect`.
5229fn register_vulkan_matmul_from_contract(table: &mut KernelBindingTable) {
5230 let provider = fuel_dispatch::fkc::import_bundle_str(
5231 VULKAN_MATMUL_CONTRACT,
5232 &crate::link::VulkanLinkRegistry,
5233 )
5234 .expect(
5235 "authored Vulkan matmul contract must import \
5236 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5237 );
5238 debug_assert!(
5239 provider.fused.is_empty(),
5240 "vulkan matmul contract declares no fused ops",
5241 );
5242 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5243 provider
5244 .register_into(table, &mut fused)
5245 .expect("Vulkan matmul contract must register into the binding table");
5246}
5247
5248/// The authored Vulkan conv2d kernel contract (3 per-(op, dtype) Conv2D
5249/// bindings), embedded via `include_str!` (the PRODUCTION contract). Parsed +
5250/// lowered by [`register_vulkan_conv_from_contract`].
5251const VULKAN_CONV_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/conv.fkc.md");
5252
5253/// Register the Vulkan conv2d family (3 `(Conv2D, [x, weight, out])` bindings —
5254/// f32 / bf16 / f16) by IMPORTING its RE-AUTHORED FKC kernel contract — the
5255/// FOURTH Vulkan-backend FKC consumer after cast + elementwise + matmul. FKC is
5256/// unconditional core infrastructure, so this is the ONE registration path for
5257/// the family: the hand-written `table.register_with_precision(OpKind::Conv2D,
5258/// …)` regs (f32 + the bf16 / f16 cooperative-matrix combos) are DELETED.
5259///
5260/// The contract was RE-AUTHORED per-(op, dtype) (the matmul family's per-combo
5261/// precedent): the corpus's `vulkan/conv-attn-rope.fkc.md` describes conv2d as an
5262/// ASPIRATIONAL `fused_op: CONV2D` **im2col STAGE** (`conv2d_im2col_f32` /
5263/// `conv2d_im2col_bf16`, whose output is the intermediate patches matrix, NOT the
5264/// conv output) — that future *fused* decomposition is a SEPARATE concern and does
5265/// NOT register the primitive `OpKind::Conv2D` binding production actually wires,
5266/// whose wrapper (`conv2d::conv2d_f32` → `VulkanBackend::conv2d_*_bytes`) runs the
5267/// WHOLE conv (im2col + GEMM internally). So the migration authors THREE faithful
5268/// single-dtype-per-operand `op_kind: Conv2D` sections in the new production
5269/// `fuel-dispatch/kernel-contracts/vulkan/conv.fkc.md`, each `entry_point` resolving through
5270/// [`crate::link::VulkanLinkRegistry`] to the exact production wrapper.
5271///
5272/// **No bias key.** The Vulkan conv wrappers BAIL on a 3-input (bias) call, so —
5273/// UNLIKE the CPU conv contract's `optional: true` bias that fans a `[T,T,T,T]`
5274/// with-bias key — the sections declare NO bias operand and each keys ONLY the
5275/// 3-slot `[x, weight, out]`, byte-for-byte the deleted hand-written regs.
5276///
5277/// **Caps ride through truthfully.** Each section's `requires_contiguous` layout
5278/// projects `strided_input == false` — byte-for-byte the deleted
5279/// `register_with_precision` regs (conv2d_im2col reads canonical row-major NCHW;
5280/// a strided / transposed / offset operand is auto-Contiguized by the planner
5281/// first). Precision becomes the contract's audited seed (nondeterministic,
5282/// `bit_stable_on_same_hardware: false`, audited `none(reason)` — the corrected,
5283/// honest posture) rather than the retired hand-written `VULKAN_MATMUL_PRECISION`
5284/// / `VULKAN_MATMUL_TENSORCORE_PRECISION` consts (which mis-declared
5285/// `bit_stable_on_same_hardware: true`; conv was their LAST code user, so they are
5286/// dropped from this seam — the matmul migration deferred that retirement to here).
5287/// Cost is preserved because this runs BEFORE `fill_unset_cost_for_backend`, which
5288/// upgrades the imported `unknown_cost` sentinels to the same OpKind cost fn.
5289///
5290/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5291/// failure of the embedded, authored contract is a programmer error surfaced once
5292/// here via `expect`.
5293fn register_vulkan_conv_from_contract(table: &mut KernelBindingTable) {
5294 let provider = fuel_dispatch::fkc::import_bundle_str(
5295 VULKAN_CONV_CONTRACT,
5296 &crate::link::VulkanLinkRegistry,
5297 )
5298 .expect(
5299 "authored Vulkan conv contract must import \
5300 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5301 );
5302 debug_assert!(
5303 provider.fused.is_empty(),
5304 "vulkan conv contract declares no fused ops",
5305 );
5306 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5307 provider
5308 .register_into(table, &mut fused)
5309 .expect("Vulkan conv contract must register into the binding table");
5310}
5311
5312/// The authored Vulkan QMatMul kernel contract (ONE `(QMatMul, [F32, U32, F32])`
5313/// binding), embedded via `include_str!` (the PRODUCTION contract). Parsed +
5314/// lowered by [`register_vulkan_qmatmul_from_contract`].
5315const VULKAN_QMATMUL_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/qmatmul.fkc.md");
5316
5317/// Register the Vulkan QMatMul binding (ONE `(QMatMul, [F32, U32, F32])` key) by
5318/// IMPORTING its RE-AUTHORED FKC kernel contract — the FOURTEENTH Vulkan-backend
5319/// FKC consumer. FKC is unconditional core infrastructure, so this is the ONE
5320/// registration path for the family: the hand-written
5321/// `table.register_with_precision(OpKind::QMatMul, &[F32, U32, F32], …)` reg is
5322/// DELETED.
5323///
5324/// The corpus `vulkan/quantized.fkc.md` models QMATMUL as TWO aspirational
5325/// `fused_op: QMATMUL` Q4_0 sections (`qmatvec_q4_0` gemv + `matmul_q4_0_tiled`
5326/// prefill), which mismatch production on BOTH axes: production registers the
5327/// PRIMITIVE `OpKind::QMatMul` (not the fused op) at a key whose weight slot is the
5328/// LOGICAL `U32` dispatch dtype (not the physical `U8` block stream). So the
5329/// migration authors ONE faithful single-dtype-per-operand `op_kind: QMatMul`
5330/// section in the new production `fuel-dispatch/kernel-contracts/vulkan/qmatmul.fkc.md`
5331/// (the CPU quant-matmul primitive precedent), applying the maintainer-approved
5332/// CPU linear-quant reconciliation:
5333/// - **weight U8 → U32**: `accept.dtypes` carries the LOGICAL dispatch dtype the
5334/// binding key + `BackendImpl.dtypes` actually use (`[F32, U32, F32]`, per the
5335/// DType-logical / SType-physical split in `docs/specs/storage-encoding.md`);
5336/// the `fdx.quant` GGML_BLOCK block keeps the physical byte-honesty
5337/// (`quant_coherence` does not pin the operand base dtype for GGML_BLOCK).
5338///
5339/// and flips the two corpus fused sections to `registrable: false` describe-only
5340/// cross-referencing it (the matmul_mixed_precision precedent).
5341///
5342/// The section's `entry_point` resolves through [`crate::link::VulkanLinkRegistry`]
5343/// to the exact production wrapper `qmatmul::qmatmul_vk`, which route-picks the
5344/// per-format kernels (`qmatvec_q4_0` / `matmul_q4_0_tiled` for Q4_0;
5345/// dequant-then-`matmul_f32` for Q4_K_M / Q8_0) at dispatch time by
5346/// `OpParams::QMatMul.quant_type` — that route-pick is NOT a binding, so there is
5347/// exactly ONE `KernelRef` at the key.
5348///
5349/// **Caps ride through truthfully.** The section's `requires_contiguous` layout
5350/// projects `strided_input == false` — byte-for-byte the deleted
5351/// `register_with_precision` reg (the GGML weight stream has a fixed per-block
5352/// layout; a strided / transposed / offset operand is auto-Contiguized by the
5353/// planner first). Precision becomes the contract's audited seed (nondeterministic,
5354/// `bit_stable_on_same_hardware: false`, audited `none(reason)` — the corrected,
5355/// honest posture: the Q4_0 kernels reduce over K with a scheduler-dependent
5356/// subgroup / tiled reduction, and the Q4_K_M / Q8_0 routes contract through the
5357/// same `matmul_f32` GEMM) rather than the retired hand-written
5358/// `VULKAN_QMATMUL_PRECISION` const (which mis-declared
5359/// `bit_stable_on_same_hardware: true`, the same over-claim the retired
5360/// `VULKAN_MATMUL_PRECISION` made; the `pub const` def stays in `fused.rs`,
5361/// mirroring VULKAN_TRANSCENDENTAL). Cost is preserved because this runs BEFORE
5362/// `fill_unset_cost_for_backend`, which upgrades the imported `unknown_cost`
5363/// sentinel to the same OpKind cost fn.
5364///
5365/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5366/// failure of the embedded, authored contract is a programmer error surfaced once
5367/// here via `expect`.
5368fn register_vulkan_qmatmul_from_contract(table: &mut KernelBindingTable) {
5369 let provider = fuel_dispatch::fkc::import_bundle_str(
5370 VULKAN_QMATMUL_CONTRACT,
5371 &crate::link::VulkanLinkRegistry,
5372 )
5373 .expect(
5374 "authored Vulkan qmatmul contract must import \
5375 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5376 );
5377 debug_assert!(
5378 provider.fused.is_empty(),
5379 "vulkan qmatmul contract declares no fused ops",
5380 );
5381 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5382 provider
5383 .register_into(table, &mut fused)
5384 .expect("Vulkan qmatmul contract must register into the binding table");
5385}
5386
5387/// The authored Vulkan select (IndexSelect / Gather / MaskedFill) kernel
5388/// contract, embedded via `include_str!` (the PRODUCTION contract). Parsed +
5389/// lowered by [`register_vulkan_select_from_contract`].
5390const VULKAN_SELECT_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/select.fkc.md");
5391
5392/// Register the Vulkan select family (16 (op, dtype) bindings — IndexSelect (4),
5393/// Gather (6), MaskedFill (6)) by IMPORTING its FKC kernel contract — the FIFTH
5394/// Vulkan-backend FKC consumer after cast + elementwise + matmul + conv. FKC is
5395/// unconditional core infrastructure, so this is the ONE registration path for
5396/// the family: the hand-written `register_with_precision(OpKind::{IndexSelect,
5397/// Gather, MaskedFill}, …)` regs are DELETED.
5398///
5399/// Each section fans a BASE `entry_point` over its dtype list (§3.4): IndexSelect
5400/// resolves `index_select_<suffix>` to FOUR distinct per-dtype wrappers; Gather /
5401/// MaskedFill resolve every `<base>_<suffix>` to the ONE dtype-agnostic wrapper
5402/// (`gather::gather` / `masked_fill::masked_fill`) that picks its element
5403/// byte-width from the output dtype — a synthetic-base umbrella (the pad_cpu
5404/// precedent). The importer keys `[data, index, out]` (data dtype + fixed index
5405/// dtype U32/U8 + `passthrough(data)` output), byte-for-byte the deleted regs.
5406///
5407/// **Caps ride through truthfully.** Each section's `requires_contiguous` layout
5408/// projects `strided_input == false` — byte-for-byte the deleted plain
5409/// `register_with_precision` regs (byte-level data movers read/write own-shape
5410/// flat buffers; a strided operand is auto-Contiguized first). Precision is the
5411/// contract's audited byte-exact seed (`bit_stable`, `max_ulp: 0`,
5412/// `determinism: bitwise`) — the honest posture for a pure byte copy, byte-for-byte
5413/// the deleted regs' `VULKAN_BYTE_LEVEL_PRECISION`. Cost is preserved because this
5414/// runs BEFORE `fill_unset_cost_for_backend`, which upgrades the imported
5415/// `unknown_cost` sentinels to the same OpKind cost fn.
5416///
5417/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5418/// failure of the embedded, authored contract is a programmer error surfaced once
5419/// here via `expect`.
5420fn register_vulkan_select_from_contract(table: &mut KernelBindingTable) {
5421 let provider = fuel_dispatch::fkc::import_bundle_str(
5422 VULKAN_SELECT_CONTRACT,
5423 &crate::link::VulkanLinkRegistry,
5424 )
5425 .expect(
5426 "authored Vulkan select contract must import \
5427 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5428 );
5429 debug_assert!(
5430 provider.fused.is_empty(),
5431 "vulkan select contract declares no fused ops",
5432 );
5433 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5434 provider
5435 .register_into(table, &mut fused)
5436 .expect("Vulkan select contract must register into the binding table");
5437}
5438
5439/// The authored Vulkan scatter (IndexAdd / ScatterAdd) kernel contract, embedded
5440/// via `include_str!` (the PRODUCTION contract). Parsed + lowered by
5441/// [`register_vulkan_scatter_from_contract`].
5442const VULKAN_SCATTER_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/scatter.fkc.md");
5443
5444/// Register the Vulkan scatter family (8 (op, dtype) bindings — IndexAdd (4) +
5445/// ScatterAdd (4)) by IMPORTING its FKC kernel contract — the SIXTH Vulkan-backend
5446/// FKC consumer. FKC is unconditional core infrastructure, so this is the ONE
5447/// registration path for the family: the hand-written
5448/// `register_with_precision(OpKind::{IndexAdd,ScatterAdd}, …)` regs are DELETED.
5449///
5450/// Each section fans a BASE `entry_point` over `[F32, F64, BF16, F16]` (the `base`
5451/// + `src` operands share the list ⇒ they fan together, §3.4), resolving
5452///
5453/// `<base>_<suffix>` to each distinct per-dtype wrapper and keying the 4-slot
5454/// `[base, U32, src, out]` (`passthrough(base)` output), byte-for-byte the deleted
5455/// regs. Caps ride through contiguous-only (`requires_contiguous` ⇒
5456/// `strided_input == false`). Precision is the contract's audited nondeterministic
5457/// `none(reason)` seed (bounded-CAS atomic accumulate, scheduler-dependent order)
5458/// — byte-for-byte the deleted regs' `PrecisionGuarantee::none(reason)`. Cost is
5459/// preserved because this runs BEFORE `fill_unset_cost_for_backend`.
5460///
5461/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5462/// failure of the embedded, authored contract is a programmer error surfaced once
5463/// here via `expect`.
5464fn register_vulkan_scatter_from_contract(table: &mut KernelBindingTable) {
5465 let provider = fuel_dispatch::fkc::import_bundle_str(
5466 VULKAN_SCATTER_CONTRACT,
5467 &crate::link::VulkanLinkRegistry,
5468 )
5469 .expect(
5470 "authored Vulkan scatter contract must import \
5471 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5472 );
5473 debug_assert!(
5474 provider.fused.is_empty(),
5475 "vulkan scatter contract declares no fused ops",
5476 );
5477 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5478 provider
5479 .register_into(table, &mut fused)
5480 .expect("Vulkan scatter contract must register into the binding table");
5481}
5482
5483/// The authored Vulkan movement (Concat / CumSum) kernel contract, embedded via
5484/// `include_str!` (the PRODUCTION contract). Parsed + lowered by
5485/// [`register_vulkan_movement_from_contract`].
5486const VULKAN_MOVEMENT_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/movement.fkc.md");
5487
5488/// Register the Vulkan movement family (8 (op, dtype) bindings — Concat (4) +
5489/// CumSum (4)) by IMPORTING its FKC kernel contract — the SEVENTH Vulkan-backend
5490/// FKC consumer. FKC is unconditional core infrastructure, so this is the ONE
5491/// registration path for the family: the hand-written
5492/// `register_with_caps_and_precision(OpKind::{Concat,CumSum}, …, strided, …)` regs
5493/// are DELETED.
5494///
5495/// Each section fans a BASE `entry_point` over its dtype list (§3.4), resolving
5496/// `<base>_<suffix>` to each distinct per-dtype wrapper and keying `[T, T]`
5497/// (`passthrough(input)` output), byte-for-byte the deleted regs. Both are
5498/// STRIDE-AWARE (`strided: accepted` ⇒ `strided_input == true`) — the
5499/// caps-through-import proof for this family. Concat precision is byte-exact
5500/// (bitwise); CumSum takes the conservative UNAUDITED author seed (the elementwise
5501/// pointwise precedent — the retired `VULKAN_{FLOAT,HALF}_POINTWISE_PRECISION`
5502/// consts are not re-asserted). Cost is preserved because this runs BEFORE
5503/// `fill_unset_cost_for_backend`.
5504///
5505/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5506/// failure of the embedded, authored contract is a programmer error surfaced once
5507/// here via `expect`.
5508fn register_vulkan_movement_from_contract(table: &mut KernelBindingTable) {
5509 let provider = fuel_dispatch::fkc::import_bundle_str(
5510 VULKAN_MOVEMENT_CONTRACT,
5511 &crate::link::VulkanLinkRegistry,
5512 )
5513 .expect(
5514 "authored Vulkan movement contract must import \
5515 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5516 );
5517 debug_assert!(
5518 provider.fused.is_empty(),
5519 "vulkan movement contract declares no fused ops",
5520 );
5521 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5522 provider
5523 .register_into(table, &mut fused)
5524 .expect("Vulkan movement contract must register into the binding table");
5525}
5526
5527/// The authored Vulkan shape (Triu / Tril / Flip / Roll) kernel contract, embedded
5528/// via `include_str!` (the PRODUCTION contract). Parsed + lowered by
5529/// [`register_vulkan_shape_from_contract`].
5530const VULKAN_SHAPE_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/shape.fkc.md");
5531
5532/// Register the Vulkan shape family (28 (op, dtype) bindings — Triu (7) + Tril (7)
5533/// + Flip (7) + Roll (7)) by IMPORTING its FKC kernel contract — the EIGHTH
5534///
5535/// Vulkan-backend FKC consumer. FKC is unconditional core infrastructure, so this
5536/// is the ONE registration path for the family: the hand-written
5537/// `register_with_precision(OpKind::{Triu,Tril}, …)` +
5538/// `register_with_caps_and_precision(OpKind::{Flip,Roll}, …, strided, …)` regs are
5539/// DELETED.
5540///
5541/// Each op is ONE dtype-agnostic wrapper across its 7 dtype keys; each section fans
5542/// the BASE `entry_point` over `[F32, F16, BF16, F64, I32, U32, I64]` and the link
5543/// registry maps every `<base>_<suffix>` symbol to the one wrapper (a
5544/// synthetic-base umbrella, the pad_cpu precedent), keying `[T, T]` byte-for-byte
5545/// the deleted regs. Caps split by op: Triu/Tril contiguous
5546/// (`strided_input == false`), Flip/Roll stride-aware (`strided_input == true`) —
5547/// the caps-through-import proof. Precision is byte-exact (bitwise, `max_ulp: 0`),
5548/// byte-for-byte the deleted regs' `VULKAN_BYTE_LEVEL_PRECISION`. Cost is preserved
5549/// because this runs BEFORE `fill_unset_cost_for_backend`.
5550///
5551/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5552/// failure of the embedded, authored contract is a programmer error surfaced once
5553/// here via `expect`.
5554fn register_vulkan_shape_from_contract(table: &mut KernelBindingTable) {
5555 let provider = fuel_dispatch::fkc::import_bundle_str(
5556 VULKAN_SHAPE_CONTRACT,
5557 &crate::link::VulkanLinkRegistry,
5558 )
5559 .expect(
5560 "authored Vulkan shape contract must import \
5561 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5562 );
5563 debug_assert!(
5564 provider.fused.is_empty(),
5565 "vulkan shape contract declares no fused ops",
5566 );
5567 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5568 provider
5569 .register_into(table, &mut fused)
5570 .expect("Vulkan shape contract must register into the binding table");
5571}
5572
5573/// The authored Vulkan pad-copy (Pad / PadBackward / Copy) kernel contract,
5574/// embedded via `include_str!` (the PRODUCTION contract). Parsed + lowered by
5575/// [`register_vulkan_pad_copy_from_contract`].
5576const VULKAN_PAD_COPY_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/pad-copy.fkc.md");
5577
5578/// Register the Vulkan pad-copy family (21 (op, dtype) bindings — Pad (6) +
5579/// PadBackward (6) + Copy (9)) by IMPORTING its FKC kernel contract — the NINTH
5580/// Vulkan-backend FKC consumer. FKC is unconditional core infrastructure, so this
5581/// is the ONE registration path for the family: the hand-written
5582/// `register_with_precision(OpKind::{Pad,PadBackward,Copy}, …)` regs are DELETED.
5583///
5584/// Each op is ONE dtype-agnostic wrapper across its dtype keys; each section fans
5585/// the BASE `entry_point` over its dtype list and the link registry maps every
5586/// `<base>_<suffix>` symbol to the one wrapper (a synthetic-base umbrella, the
5587/// pad_cpu precedent), keying `[T, T]` byte-for-byte the deleted regs. Caps ride
5588/// through contiguous-only (`requires_contiguous` ⇒ `strided_input == false`);
5589/// precision is byte-exact (bitwise, `max_ulp: 0`), byte-for-byte the deleted regs'
5590/// `VULKAN_BYTE_LEVEL_PRECISION`. Cost is preserved because this runs BEFORE
5591/// `fill_unset_cost_for_backend`.
5592///
5593/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5594/// failure of the embedded, authored contract is a programmer error surfaced once
5595/// here via `expect`.
5596fn register_vulkan_pad_copy_from_contract(table: &mut KernelBindingTable) {
5597 let provider = fuel_dispatch::fkc::import_bundle_str(
5598 VULKAN_PAD_COPY_CONTRACT,
5599 &crate::link::VulkanLinkRegistry,
5600 )
5601 .expect(
5602 "authored Vulkan pad-copy contract must import \
5603 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5604 );
5605 debug_assert!(
5606 provider.fused.is_empty(),
5607 "vulkan pad-copy contract declares no fused ops",
5608 );
5609 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5610 provider
5611 .register_into(table, &mut fused)
5612 .expect("Vulkan pad-copy contract must register into the binding table");
5613}
5614
5615/// The authored Vulkan write-slice (WriteSlice / WriteSliceRotating) kernel
5616/// contract, embedded via `include_str!` (the PRODUCTION contract). Parsed +
5617/// lowered by [`register_vulkan_write_slice_from_contract`].
5618const VULKAN_WRITE_SLICE_CONTRACT: &str =
5619 include_str!("../kernel-contracts/vulkan/write-slice.fkc.md");
5620
5621/// Register the Vulkan write-slice family (18 (op, dtype) bindings — WriteSlice (9)
5622/// + WriteSliceRotating (9)) by IMPORTING its FKC kernel contract — the TENTH
5623///
5624/// Vulkan-backend FKC consumer. FKC is unconditional core infrastructure, so this
5625/// is the ONE registration path for the family: the hand-written
5626/// `register_with_precision(OpKind::{WriteSlice,WriteSliceRotating}, …)` regs are
5627/// DELETED.
5628///
5629/// BYTE-WIDTH-keyed: each op's 9 dtype keys collapse to 4 byte-width wrappers
5630/// (`b1/b2/b4/b8`) — the cast family's "several sections share one wrapper"
5631/// precedent. Each section fans the BASE `entry_point` over the 9-dtype list and
5632/// the link registry maps each `<base>_<suffix>` symbol to the byte-width wrapper
5633/// for that dtype's size, keying `[T, T]` byte-for-byte the deleted regs. Caps ride
5634/// through contiguous-only (`requires_contiguous` ⇒ `strided_input == false`);
5635/// precision is byte-exact (bitwise, `max_ulp: 0`), byte-for-byte the deleted regs'
5636/// `VULKAN_BYTE_LEVEL_PRECISION`. Cost is preserved because this runs BEFORE
5637/// `fill_unset_cost_for_backend`.
5638///
5639/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5640/// failure of the embedded, authored contract is a programmer error surfaced once
5641/// here via `expect`.
5642fn register_vulkan_write_slice_from_contract(table: &mut KernelBindingTable) {
5643 let provider = fuel_dispatch::fkc::import_bundle_str(
5644 VULKAN_WRITE_SLICE_CONTRACT,
5645 &crate::link::VulkanLinkRegistry,
5646 )
5647 .expect(
5648 "authored Vulkan write-slice contract must import \
5649 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5650 );
5651 debug_assert!(
5652 provider.fused.is_empty(),
5653 "vulkan write-slice contract declares no fused ops",
5654 );
5655 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5656 provider
5657 .register_into(table, &mut fused)
5658 .expect("Vulkan write-slice contract must register into the binding table");
5659}
5660
5661/// The authored Vulkan rope kernel contract, embedded via `include_str!` (the
5662/// PRODUCTION contract). Parsed + lowered by [`register_vulkan_rope_from_contract`].
5663const VULKAN_ROPE_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/rope.fkc.md");
5664
5665/// Register the Vulkan rope family (4 (Rope, [x, cos, sin, out]) per-dtype
5666/// bindings) by IMPORTING its FKC kernel contract — the ELEVENTH Vulkan-backend
5667/// FKC consumer. FKC is unconditional core infrastructure, so this is the ONE
5668/// registration path for the family: the hand-written
5669/// `register_with_caps_and_precision(OpKind::Rope, …, strided, …)` regs are DELETED.
5670///
5671/// The single section fans a BASE `entry_point` over `[F32, F16, F64, BF16]` (the
5672/// `x` + `cos` + `sin` operands share the list ⇒ they fan together, §3.4),
5673/// resolving `rope_<suffix>` to each distinct per-dtype wrapper and keying the
5674/// 4-slot `[x, cos, sin, out]` (`passthrough(x)` output), byte-for-byte the deleted
5675/// regs. STRIDE-AWARE (`strided: accepted` ⇒ `strided_input == true`) — the
5676/// caps-through-import proof. Precision is the conservative UNAUDITED author seed
5677/// (the elementwise pointwise precedent — the retired
5678/// `VULKAN_{FLOAT,HALF}_POINTWISE_PRECISION` consts are not re-asserted). Cost is
5679/// preserved because this runs BEFORE `fill_unset_cost_for_backend`.
5680///
5681/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5682/// failure of the embedded, authored contract is a programmer error surfaced once
5683/// here via `expect`.
5684fn register_vulkan_rope_from_contract(table: &mut KernelBindingTable) {
5685 let provider = fuel_dispatch::fkc::import_bundle_str(
5686 VULKAN_ROPE_CONTRACT,
5687 &crate::link::VulkanLinkRegistry,
5688 )
5689 .expect(
5690 "authored Vulkan rope contract must import \
5691 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5692 );
5693 debug_assert!(
5694 provider.fused.is_empty(),
5695 "vulkan rope contract declares no fused ops",
5696 );
5697 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5698 provider
5699 .register_into(table, &mut fused)
5700 .expect("Vulkan rope contract must register into the binding table");
5701}
5702
5703/// The authored Vulkan reduce-primitives kernel contract (production per-(op,
5704/// dtype) bindings), embedded via `include_str!`. Parsed + lowered by
5705/// [`register_vulkan_reduce_from_contract`].
5706const VULKAN_REDUCE_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/reduce-prims.fkc.md");
5707
5708/// Register the Vulkan reduce family (24 (op, dtype) bindings — SumReduce /
5709/// MaxReduce / MinReduce / MeanReduce (16) + ArgMaxDim / ArgMinDim (8)) by
5710/// IMPORTING its FKC kernel contract — the TWELFTH Vulkan-backend FKC consumer.
5711/// FKC is unconditional core infrastructure, so this is the ONE registration path
5712/// for the family: the hand-written `register_with_precision(OpKind::{SumReduce,…,
5713/// ArgMinDim}, …)` regs are DELETED.
5714///
5715/// This production contract (`reduce-prims.fkc.md`) supersedes the aspirational
5716/// `vulkan/reduce.fkc.md` corpus (an op-id-selector binding model FKC's
5717/// one-`op_kind`-per-section importer cannot express): it authors ONE section per
5718/// OpKind, fanned over `[F32, F16, BF16, F64]` to the DISTINCT per-dtype wrapper
5719/// (`reduce::{sum,max,min,mean}_*`, `arg_reduce::{argmax,argmin}_*`), keying value
5720/// reduces `[T, T]` (`passthrough`) and index reduces `[T, U32]` (`fixed(U32)`),
5721/// byte-for-byte the deleted regs. Caps ride through contiguous-only
5722/// (`requires_contiguous` ⇒ `strided_input == false`). Precision: value reduces are
5723/// the audited nondeterministic `none(reason)` seed (subgroup-tree FADD order, the
5724/// matmul/conv precedent); arg reduces are bitwise exact (integer index). Cost is
5725/// preserved because this runs BEFORE `fill_unset_cost_for_backend`.
5726///
5727/// The family declares NO fused ops. Init-boundary fail-fast: a parse/lower/link
5728/// failure of the embedded, authored contract is a programmer error surfaced once
5729/// here via `expect`.
5730fn register_vulkan_reduce_from_contract(table: &mut KernelBindingTable) {
5731 let provider = fuel_dispatch::fkc::import_bundle_str(
5732 VULKAN_REDUCE_CONTRACT,
5733 &crate::link::VulkanLinkRegistry,
5734 )
5735 .expect(
5736 "authored Vulkan reduce contract must import \
5737 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5738 );
5739 debug_assert!(
5740 provider.fused.is_empty(),
5741 "vulkan reduce contract declares no fused ops",
5742 );
5743 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5744 provider
5745 .register_into(table, &mut fused)
5746 .expect("Vulkan reduce contract must register into the binding table");
5747}
5748
5749/// The authored Vulkan normalization / softmax primitives kernel contract,
5750/// embedded via `include_str!`. Parsed + lowered by
5751/// [`register_vulkan_norm_from_contract`].
5752const VULKAN_NORM_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/norm.fkc.md");
5753
5754/// Register the Vulkan norm family (20 (op, dtype) bindings — SoftmaxLastDim (4) +
5755/// SoftmaxLastDimBackward (4) + LayerNormLastDim (4) + LayerNormLastDimBackward (4)
5756/// + RmsNormLastDim (4)) by IMPORTING its FKC kernel contract — the THIRTEENTH
5757///
5758/// Vulkan-backend FKC consumer. FKC is unconditional core infrastructure, so this
5759/// is the ONE registration path for the family: the hand-written
5760/// `register_with_precision(OpKind::{SoftmaxLastDim,…,RmsNormLastDim}, …)` regs are
5761/// DELETED.
5762///
5763/// Each section fans a BASE `entry_point` over `[F32, F16, BF16, F64]` to its
5764/// DISTINCT per-dtype wrapper (`softmax::*`, `norm::*`), keying forward families
5765/// `[T, T]` and backward families `[T, T, T]` (both inputs sharing the fanned list),
5766/// byte-for-byte the deleted regs. Caps ride through contiguous-only
5767/// (`requires_contiguous` ⇒ `strided_input == false`); precision is the audited
5768/// nondeterministic `none(reason)` seed (per-row subgroup-tree FADD order, the
5769/// matmul/conv/value-reduce precedent). Cost is preserved because this runs BEFORE
5770/// `fill_unset_cost_for_backend`.
5771///
5772/// The family declares NO fused ops (the FUSED softmax/norm decompositions register
5773/// separately via the fused registry). Init-boundary fail-fast: a parse/lower/link
5774/// failure of the embedded, authored contract is a programmer error surfaced once
5775/// here via `expect`.
5776fn register_vulkan_norm_from_contract(table: &mut KernelBindingTable) {
5777 let provider = fuel_dispatch::fkc::import_bundle_str(
5778 VULKAN_NORM_CONTRACT,
5779 &crate::link::VulkanLinkRegistry,
5780 )
5781 .expect(
5782 "authored Vulkan norm contract must import \
5783 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5784 );
5785 debug_assert!(
5786 provider.fused.is_empty(),
5787 "vulkan norm contract declares no fused ops",
5788 );
5789 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5790 provider
5791 .register_into(table, &mut fused)
5792 .expect("Vulkan norm contract must register into the binding table");
5793}
5794
5795/// The authored Vulkan FlashAttention kernel contract (6 sections — forward
5796/// f32/bf16/f16 + backward Q/K/V f32, each fanning a no-alibi + a with-alibi
5797/// key ⇒ 12 bindings), embedded via `include_str!` (the PRODUCTION contract).
5798/// Parsed + lowered by [`register_vulkan_attention_from_contract`].
5799const VULKAN_ATTENTION_CONTRACT: &str = include_str!("../kernel-contracts/vulkan/attention.fkc.md");
5800
5801/// Register the Vulkan FlashAttention family (12 bindings — forward
5802/// `OpKind::FlashAttn` at f32/bf16/f16 + backward `OpKind::FlashAttnBackward{Q,K,V}`
5803/// at f32, each with a no-alibi AND a with-alibi binding shape) by IMPORTING its
5804/// AUTHORED FKC kernel contract — the FIFTEENTH (and LAST) Vulkan-backend FKC
5805/// consumer. FKC is unconditional core infrastructure, so this is the ONE
5806/// registration path for the family: the hand-written
5807/// `table.register_with_precision(OpKind::{FlashAttn,FlashAttnBackwardQ,
5808/// FlashAttnBackwardK,FlashAttnBackwardV}, …)` regs are DELETED. This was the
5809/// LAST hand-written `table.register*` call in `register_vulkan_kernels`, so the
5810/// Vulkan backend is now 100% contract-sourced.
5811///
5812/// The corpus's `vulkan/conv-attn-rope.fkc.md` models this family as aspirational
5813/// `fused_op: FLASH_ATTN` / `FLASH_ATTN_BACKWARD_*` decompositions (plus the tiled
5814/// FA-2 `flash_attention`), a SEPARATE future FUSED-registry seam that does NOT
5815/// register the primitive `OpKind::FlashAttn*` bindings production wires (the same
5816/// primitive-vs-fused split conv2d / matmul draw). So the migration authors SIX
5817/// faithful single-dtype-per-operand `op_kind:` sections in the new production
5818/// `fuel-dispatch/kernel-contracts/vulkan/attention.fkc.md`:
5819/// - **Forward wrappers are DISTINCT per dtype** (`flash_attn::flash_attn_{f32,
5820/// bf16,f16}`), so — like conv2d's `conv2d_{f32,bf16,f16}` and the CPU attention
5821/// contract's per-dtype `flash_attn_*` sections — each dtype is its OWN
5822/// single-dtype section resolving its `entry_point` AS-IS (no dtype-fan
5823/// umbrella); backward is three f32-only sections.
5824/// - **`alibi_slopes` is an `optional: true` LAST input**, so the importer's
5825/// optional-last fan (§3.4) keys EACH section TWICE (with + without the
5826/// operand), byte-for-byte the deleted regs' dual `[q,k,v,out]` /
5827/// `[q,k,v,alibi,out]` (forward) and `[q,k,v,do,out]` / `[q,k,v,do,alibi,out]`
5828/// (backward) shapes. The forward + all three backward selectors share the ONE
5829/// `OpParams::FlashAttn` carrier (`op_params.variant: FlashAttn` — the CPU
5830/// precedent; no dedicated backward variant).
5831///
5832/// **Caps ride through truthfully.** Each section's `requires_contiguous` layout
5833/// projects `strided_input == false` — byte-for-byte the deleted plain
5834/// `register_with_precision` regs (the kernels read canonical row-major q/k/v/do;
5835/// a strided operand is auto-Contiguized by the planner first). Precision becomes
5836/// the contract's corrected audited seed (`bit_stable_on_same_hardware: false`,
5837/// audited `none(reason)`, `determinism: nondeterministic`): the naive single-pass
5838/// kernel does its softmax over the `[Sk]` score row with a per-`(b,h,q)` workgroup
5839/// shared-memory reduction whose FADD order is scheduler-dependent, so the retired
5840/// hand-written `VULKAN_FLOAT_POINTWISE_PRECISION` / `VULKAN_HALF_POINTWISE_PRECISION`
5841/// consts (which mis-declared `bit_stable_on_same_hardware: true` + `max_ulp: 1`,
5842/// a per-thread-pointwise claim) OVER-CLAIMED bit-stability — the aspirational
5843/// `conv-attn-rope.fkc.md` already carries this honest posture; the consts are
5844/// retired from this seam (their `pub const` defs stay in `fused.rs`). Cost is
5845/// preserved because this runs BEFORE `fill_unset_cost_for_backend`, which upgrades
5846/// the imported `unknown_cost` sentinels to the same OpKind cost fn.
5847///
5848/// The family declares NO fused ops (the FUSED flash decompositions register
5849/// separately via the fused registry). Init-boundary fail-fast: a parse/lower/link
5850/// failure of the embedded, authored contract is a programmer error surfaced once
5851/// here via `expect`.
5852fn register_vulkan_attention_from_contract(table: &mut KernelBindingTable) {
5853 let provider = fuel_dispatch::fkc::import_bundle_str(
5854 VULKAN_ATTENTION_CONTRACT,
5855 &crate::link::VulkanLinkRegistry,
5856 )
5857 .expect(
5858 "authored Vulkan attention contract must import \
5859 (embedded via include_str!, resolved through VulkanLinkRegistry)",
5860 );
5861 debug_assert!(
5862 provider.fused.is_empty(),
5863 "vulkan attention contract declares no fused ops",
5864 );
5865 let mut fused = fuel_dispatch::fused::FusedKernelRegistry::new();
5866 provider
5867 .register_into(table, &mut fused)
5868 .expect("Vulkan attention contract must register into the binding table");
5869}
5870
5871/// Register every Vulkan kernel wrapper against its `(OpKind, dtypes,
5872/// BackendId::Vulkan)` decision-point key in the shared
5873/// `KernelBindingTable`. Each wrapper appears as an alternative
5874/// alongside any CPU / CUDA / future-backend registrations at the
5875/// same key. The route picker (architecture v1.0 §04) selects among
5876/// them at plan time based on input residency + telemetry.
5877///
5878/// V.1.C coverage: `AddElementwise [F32, F32, F32]` only. The
5879/// proof-of-life single op. V.2 fans out to the ~25 already-compiled
5880/// SPIR-V kernels; V.3 adds new Slang for the kernel families CUDA
5881/// has and Vulkan doesn't.
5882pub fn register_vulkan_kernels(table: &mut KernelBindingTable) {
5883 // NB: the `use fuel_dispatch::fused::{ PrecisionGuarantee, VULKAN_FLOAT_POINTWISE_PRECISION,
5884 // VULKAN_HALF_POINTWISE_PRECISION }` seam is RETIRED — the FlashAttention family was
5885 // their LAST code user, and it now registers from the FKC attention contract (see
5886 // `register_vulkan_attention_from_contract`), which carries the corrected
5887 // audited-nondeterministic per-section precision (the two POINTWISE consts
5888 // over-claimed `bit_stable_on_same_hardware: true` + `max_ulp: 1` for a shared-mem
5889 // softmax reduction). With the FlashAttn regs gone there are NO hand-written
5890 // `table.register*` calls left, so NO `PrecisionGuarantee` / precision-const import
5891 // is needed. The `pub const` defs stay in `fused.rs`, mirroring VULKAN_TRANSCENDENTAL.
5892 // (VULKAN_BYTE_LEVEL_PRECISION / VULKAN_QMATMUL_PRECISION / VULKAN_TRANSCENDENTAL_PRECISION
5893 // / VULKAN_MATMUL_PRECISION / VULKAN_MATMUL_TENSORCORE_PRECISION / VULKAN_CAST_PRECISION
5894 // were retired by the earlier family migrations; KernelCaps likewise — every strided
5895 // Vulkan family projects `strided_input` from its FKC contract's layout.)
5896 let vk = BackendId::Vulkan;
5897 // NB: EVERY Vulkan family now registers from its FKC contract (the
5898 // `register_vulkan_*_from_contract` calls at the END of this fn are the SOLE
5899 // registration path). There are ZERO hand-written `table.register*` calls remaining
5900 // — the Vulkan backend is 100% contract-sourced. `vk` is used only by the
5901 // `fill_unset_cost_for_backend` pass below.
5902
5903 // Phase 7.6 step 9c follow-up (2026-05-23 + 2026-05-24):
5904 // - Per-kernel `PrecisionGuarantee` + cost (session 1, shipped).
5905 // - Per-kernel `KernelCaps::strided_input` (session 2, this commit).
5906 // Each Slang kernel was audited to determine whether it walks
5907 // per-input strides (and so can consume non-contiguous inputs
5908 // like broadcast / transpose / slice views directly) or
5909 // requires the executor's auto-Contiguize pass to materialize
5910 // contiguous inputs first.
5911 //
5912 // **Conventions for this file**:
5913 // - Stride-aware kernels opt in via
5914 // `KernelCaps::strided_input()`. The executor skips
5915 // auto-Contiguize for these so lazy views reach the kernel
5916 // unmaterialized.
5917 // - Contiguous-only kernels keep `KernelCaps::empty()`
5918 // (the default) AND get a `// strided-input candidate: <reason>`
5919 // comment iff the kernel SHAPE would support an arbitrary-
5920 // stride extension. Future perf sweeps grep for that marker
5921 // to find conversion work.
5922 // - Contiguous-only kernels whose shape inherently needs flat
5923 // layout (subgroup-tree reductions, tiled matmul, im2col,
5924 // destination-as-layout WriteSlice, byte-level
5925 // Triu/Tril/Flip/Roll) carry a family-level comment but no
5926 // candidate marker.
5927 //
5928 // Cost functions are bulk-filled at the end via
5929 // `fill_unset_cost_for_backend(Vulkan, default_cost_for_op_kind)`.
5930
5931 // ----- Binary + Unary f32 (V.2.A/B) — MIGRATED to FKC contract import.
5932 // The hand-written `register_with_caps_and_precision` regs (6 binary + 16
5933 // unary, all strided f32) are DELETED; the whole elementwise family now
5934 // registers from `fuel-dispatch/kernel-contracts/vulkan/elementwise.fkc.md` via
5935 // `register_vulkan_elementwise_from_contract` (the SOLE path, called at the
5936 // END of this fn before the cost-fill pass). The top-level `strided`
5937 // `KernelCaps` binding that Rope / Concat / Flip / Roll / CumSum used to consume
5938 // is retired now those families all register from their FKC contracts
5939 // (movement / shape / rope), which project `strided_input` from their
5940 // `strided: accepted` layouts. -----
5941
5942 // ----- Softmax + RmsNorm last-dim (V.2.C, f32) — per-row reductions
5943 // with subgroup-tree internal accumulation. CONTIGUOUS-ONLY by
5944 // design: the kernel issues one workgroup per row and reads the
5945 // row's elements flat; an arbitrary stride on the last-dim axis
5946 // would break the workgroup-shared-memory reduction. Auto-
5947 // Contiguize materializes broadcast/transpose views first. -----
5948 // ----- Softmax + RmsNorm + LayerNorm (+ softmax/layernorm backward) last-dim —
5949 // MIGRATED to FKC contract import. The hand-written `register_with_precision(
5950 // OpKind::{SoftmaxLastDim,SoftmaxLastDimBackward,LayerNormLastDim,
5951 // LayerNormLastDimBackward,RmsNormLastDim}, …)` regs (20 per-(op, dtype)
5952 // bindings, all contiguous) are DELETED; the whole norm family now registers
5953 // from `fuel-dispatch/kernel-contracts/vulkan/norm.fkc.md` via
5954 // `register_vulkan_norm_from_contract` (called at the END of this fn, before the
5955 // cost-fill pass). Forward families key [T, T], backward families [T, T, T];
5956 // precision becomes the audited nondeterministic none(reason) seed (per-row
5957 // subgroup-tree FADD order). Contiguous-only. -----
5958
5959 // ----- SoftmaxLastDimBackward, f32 + f16/bf16/f64 (V.3.G.softmax-bwd,
5960 // 2026-05-30). 2 inputs (y, g) → 1 output (dx); reuses
5961 // OpParams::SoftmaxLastDim. Reduction order is scheduler-determined. -----
5962 // ----- SoftmaxLastDimBackward — MIGRATED to FKC contract import (deleted; now
5963 // registered from the norm contract, key [y, g, dx]). -----
5964
5965 // ----- Softmax f16/bf16/f64 — MIGRATED to FKC contract import (deleted; now
5966 // registered from the norm contract, alongside the f32 combo). -----
5967
5968 // ----- LayerNormLastDimBackward — MIGRATED to FKC contract import (deleted; now
5969 // registered from the norm contract, key [x, g, dx]). -----
5970
5971 // ----- LayerNorm last-dim — MIGRATED to FKC contract import (deleted; now
5972 // registered from the norm contract). -----
5973
5974 // ----- RmsNorm f16/bf16/f64 — MIGRATED to FKC contract import (deleted; now
5975 // registered from the norm contract, alongside the f32 combo). -----
5976
5977 // ----- RoPE (V.2.C, f32) — pointwise rotation with cos/sin tables.
5978 // STRIDE-AWARE on `x`: rope.slang's Params struct carries
5979 // `x_s0/x_s1/x_s_seq/x_s_hd` + an `x_contiguous` fast-path flag
5980 // and decomposes per-thread index into per-dim coordinates. cos/sin
5981 // are documented as always-contiguous (the wrapper enforces).
5982 // Binding-shape MUST match the CPU registration `[x, cos, sin, out]`
5983 // (4 dtypes). The strided_input cap signals "ANY input may be non-
5984 // contiguous" — for Rope specifically, only x; the wrapper handles
5985 // forcing cos/sin contiguous through its own path. -----
5986 // ----- RoPE (f32/f16/f64/bf16) — MIGRATED to FKC contract import. The
5987 // hand-written `register_with_caps_and_precision(OpKind::Rope, …, strided, …)`
5988 // regs (4-slot [x, cos, sin, out] key, 4 per-dtype wrappers) are DELETED; the
5989 // rope family now registers from `fuel-dispatch/kernel-contracts/vulkan/rope.fkc.md` via
5990 // `register_vulkan_rope_from_contract` (called at the END of this fn, before the
5991 // cost-fill pass). Stride-aware (strided_input=true); precision becomes the
5992 // conservative UNAUDITED author seed (the elementwise pointwise precedent; the
5993 // retired VULKAN_{FLOAT,HALF}_POINTWISE_PRECISION consts are not re-asserted). -----
5994
5995 // ----- IndexSelect (V.2.D, f32 src + u32 ids) — pure gather (byte-level).
5996 // strided-input candidate: index_select.slang flattens input to
5997 // (outer, axis, inner) and reads via own-shape strides. Could be
5998 // extended to walk arbitrary input layout strides at gather time
5999 // (saves an auto-Contiguize when the source is a transpose view).
6000 // Indices are u32; their layout-strided variant is a follow-up. -----
6001 // ----- IndexSelect (f32/f16/bf16/f64 src + u32 ids) — MIGRATED to FKC
6002 // contract import. The hand-written `register_with_precision(OpKind::
6003 // IndexSelect, …)` regs (4 per-dtype wrappers) are DELETED; the whole select
6004 // family (IndexSelect + Gather + MaskedFill) now registers from
6005 // `fuel-dispatch/kernel-contracts/vulkan/select.fkc.md` via
6006 // `register_vulkan_select_from_contract` (called at the END of this fn, before
6007 // the cost-fill pass). Caps stay contiguous-only (strided_input=false). -----
6008
6009 // ----- Reduce f32 (V.2.D + V.3.A.2) — Sum / Max / Min / Mean.
6010 // CONTIGUOUS-ONLY by design: reduce.slang does a tree reduction
6011 // into workgroup-shared memory; the input is read flat. Strided
6012 // inputs would require either pre-materialization (current
6013 // behaviour via auto-Contiguize) or a redesigned reduction
6014 // schedule that's unlikely to outperform the auto-Contiguize +
6015 // current kernel. -----
6016 // ----- Reduce (Sum/Max/Min/Mean) + ArgMax/ArgMin — MIGRATED to FKC contract
6017 // import. The hand-written per-(op, dtype) `register_with_precision(OpKind::
6018 // {SumReduce,…,ArgMinDim}, …)` regs (16 value + 8 arg, all contiguous) are
6019 // DELETED; the whole reduce family now registers from
6020 // `fuel-dispatch/kernel-contracts/vulkan/reduce-prims.fkc.md` via
6021 // `register_vulkan_reduce_from_contract` (called at the END of this fn, before
6022 // the cost-fill pass). Value reduces carry the audited nondeterministic
6023 // none(reason) seed (subgroup-tree FADD order); arg reduces are bitwise exact
6024 // (integer index). Contiguous-only. -----
6025
6026 // ----- IndexAdd + ScatterAdd (atomic bounded-CAS accumulate) — MIGRATED to
6027 // FKC contract import. The hand-written `register_with_precision(OpKind::
6028 // {IndexAdd,ScatterAdd}, …)` regs (4 per-dtype wrappers each, 4-slot
6029 // [base, U32, src, out] key) are DELETED; the whole scatter family now
6030 // registers from `fuel-dispatch/kernel-contracts/vulkan/scatter.fkc.md` via
6031 // `register_vulkan_scatter_from_contract` (called at the END of this fn,
6032 // before the cost-fill pass). Caps stay contiguous-only (strided_input=false);
6033 // precision becomes the contract's audited nondeterministic none(reason) seed
6034 // (the same posture as the deleted PrecisionGuarantee::none regs). -----
6035
6036 // ----- ArgMaxDim / ArgMinDim — MIGRATED to FKC contract import (deleted; now
6037 // registered from the reduce-prims contract, key [T, U32] with a fixed(U32)
6038 // index output; bitwise exact). -----
6039
6040 // ----- Reduce last-dim f16/bf16/f64 — MIGRATED to FKC contract import (deleted;
6041 // now registered from the reduce-prims contract, alongside the f32 combos). -----
6042
6043 // ----- Concat (f32/f16/bf16/f64) — MIGRATED to FKC contract import (deleted;
6044 // now registered from `fuel-dispatch/kernel-contracts/vulkan/movement.fkc.md` via
6045 // `register_vulkan_movement_from_contract`, alongside CumSum). Stride-aware
6046 // (strided_input=true) byte-level data movement. -----
6047
6048 // ----- Pad with constant fill (V.3.G.pad, 2026-05-30).
6049 // Byte-level kernels (b1/b2/b4/b8) dispatched by the OUTPUT dtype's
6050 // size at the shim. Reflect/replicate modes fall through to CPU.
6051 // ----- Pad + PadBackward — MIGRATED to FKC contract import. The hand-written
6052 // per-dtype (6 dtypes) `register_with_precision(OpKind::{Pad,PadBackward}, …)`
6053 // regs are DELETED; the whole pad-copy family (Pad + PadBackward + Copy) now
6054 // registers from `fuel-dispatch/kernel-contracts/vulkan/pad-copy.fkc.md` via
6055 // `register_vulkan_pad_copy_from_contract` (called at the END of this fn,
6056 // before the cost-fill pass). Each op is ONE dtype-agnostic wrapper
6057 // (synthetic-base umbrella); const mode only; contiguous-only. -----
6058 {
6059 // ----- MaskedFill + Gather — MIGRATED to FKC contract import (deleted;
6060 // now registered from `fuel-dispatch/kernel-contracts/vulkan/select.fkc.md` via
6061 // `register_vulkan_select_from_contract`, alongside IndexSelect). Both are
6062 // ONE dtype-agnostic wrapper across their 6 dtype keys (byte-width from the
6063 // output dtype) — a synthetic-base umbrella. Contiguous-only. -----
6064 }
6065 // V.3.G.concat f16/bf16/f64 — MIGRATED to FKC contract import (deleted; now
6066 // registered from the movement contract, alongside the f32 combo above). -----
6067
6068 // ----- MatMul (f32 GEMM + the five mixed-precision / tensor-core combos)
6069 // — MIGRATED to FKC contract import. The hand-written
6070 // `table.register_with_precision(OpKind::MatMul, …)` regs (f32, f32×bf16→f32,
6071 // bf16×bf16→{f32,bf16}, f16×f16→{f16,f32}) are DELETED; they now register from
6072 // the vulkan matmul contract via `register_vulkan_matmul_from_contract`
6073 // (called at the END of this fn, before the cost fill pass). Caps stay
6074 // contiguous-only (`requires_contiguous` ⇒ strided_input=false); precision
6075 // becomes the contract's audited-none(reason) seed. The
6076 // VULKAN_MATMUL_PRECISION / VULKAN_MATMUL_TENSORCORE_PRECISION consts the
6077 // matmul migration left in use for the Vulkan conv2d family are now ALSO
6078 // retired — conv2d migrated to its own FKC contract
6079 // (`register_vulkan_conv_from_contract`). See
6080 // `fuel-dispatch/kernel-contracts/vulkan/matmul.fkc.md`.
6081
6082 // ----- Affine / Clamp / PowI — MIGRATED to FKC contract import.
6083 // The hand-written Affine (f32/f16/f64 strided + bf16 contiguous-only),
6084 // ClampElementwise (f32), and PowIElementwise (f32) regs are DELETED; they now
6085 // register from the elementwise contract via
6086 // `register_vulkan_elementwise_from_contract` (called at the END of this fn).
6087 // Affine's bf16 variant keeps its contiguous-only caps
6088 // (`strided_input=false`) via the `affine_bf16` section's
6089 // `contiguous: required` layout. -----
6090
6091 // ----- Cast (all pairs) — MIGRATED to FKC contract import.
6092 // The hand-written `table.register_with_precision(OpKind::Cast, …)`
6093 // regs (f32↔f16, f32↔bf16, f32↔f64, and — further below — the six
6094 // F8E4M3↔{f32,f16,bf16} pairs) are DELETED. The whole family now
6095 // registers from `fuel-dispatch/kernel-contracts/vulkan/cast.fkc.md` via
6096 // `register_vulkan_cast_from_contract`, called at the END of this fn
6097 // (before the cost-fill pass), the SOLE registration path.
6098 // The top-level `f16` / `bf16_d` bindings that the WriteSlice / Copy byte-width
6099 // fan-outs used to consume are retired with those families' migration to the
6100 // FKC pad-copy + write-slice contracts (the remaining half-precision users —
6101 // reduce / norm / flash-attn / rope — declare their own block-scoped locals). -----
6102
6103 // ----- Binary + Unary f16 — MIGRATED to FKC contract import (deleted; now
6104 // registered from the elementwise contract, all strided). -----
6105
6106 // ----- Binary + Unary f64 — MIGRATED to FKC contract import (deleted; now
6107 // registered from the elementwise contract, all strided). The top-level
6108 // `f64_d` binding that CumSum used to consume is retired with CumSum's
6109 // migration to the FKC movement contract. -----
6110
6111 // ----- WriteSlice (V.3.J) — byte-width-keyed (b1/b2/b4/b8). Pure
6112 // byte-level data movement; no FP math.
6113 // CONTIGUOUS-ONLY: write_slice_b*.slang reads `src` contiguously
6114 // in its own rank-N shape and writes the matching slab inside
6115 // `dst` (also contiguous in its larger rank-N shape). The
6116 // destination's slab geometry IS the layout — strided inputs
6117 // wouldn't compose with the slab-walk's own-shape strides.
6118 // Auto-Contiguize materializes any non-contiguous source. -----
6119 // ----- WriteSlice + WriteSliceRotating — MIGRATED to FKC contract import. The
6120 // hand-written byte-width-keyed (9 dtypes → b1/b2/b4/b8) `register_with_precision(
6121 // OpKind::{WriteSlice,WriteSliceRotating}, …)` regs are DELETED; the whole
6122 // write-slice family now registers from
6123 // `fuel-dispatch/kernel-contracts/vulkan/write-slice.fkc.md` via
6124 // `register_vulkan_write_slice_from_contract` (called at the END of this fn,
6125 // before the cost-fill pass). Each op's 9 dtype keys share 4 byte-width wrappers
6126 // (the cast family's shared-wrapper precedent); contiguous-only. -----
6127
6128 // ----- Binary + Unary bf16 — MIGRATED to FKC contract import (deleted). The
6129 // binary_bf16 regs were strided (lane-masked); the unary_bf16 regs were plain
6130 // `register_with_precision` (contiguous-only, `strided_input=false`) — both
6131 // reproduced by the contract's per-section layout projection. -----
6132
6133 // ----- Triu / Tril — pure byte-level mask kernel (rank-3 reshape).
6134 // CONTIGUOUS-ONLY by design: triu_b4 / tril_b4 view inputs as a
6135 // flat (outer, dim_size, inner) 3-tuple. Arbitrary layout strides
6136 // would require a different decomposition; auto-Contiguize handles
6137 // non-contiguous inputs upstream.
6138 //
6139 // Flip / Roll — STRIDE-AWARE (alpha.31 sweep follow-up): the
6140 // flip_b* / roll_b* kernels now walk rank-N + per-input strides
6141 // with the axis from OpParams::{Flip, Roll}.axis. Output is contig
6142 // over the input's shape.
6143 // ----- Triu / Tril / Flip / Roll — MIGRATED to FKC contract import. The
6144 // hand-written per-dtype (7 dtypes) `register_with_precision(OpKind::
6145 // {Triu,Tril}, …)` + `register_with_caps_and_precision(OpKind::{Flip,Roll},
6146 // …, strided, …)` regs are DELETED; the whole shape family now registers from
6147 // `fuel-dispatch/kernel-contracts/vulkan/shape.fkc.md` via
6148 // `register_vulkan_shape_from_contract` (called at the END of this fn, before
6149 // the cost-fill pass). Each op is ONE dtype-agnostic wrapper (synthetic-base
6150 // umbrella). Caps split by op: Triu/Tril contiguous, Flip/Roll strided. -----
6151
6152 // ----- CumSum (inclusive prefix sum along one axis) — MIGRATED to FKC
6153 // contract import (deleted; now registered from
6154 // `fuel-dispatch/kernel-contracts/vulkan/movement.fkc.md` via
6155 // `register_vulkan_movement_from_contract`, alongside Concat). Stride-aware
6156 // (strided_input=true); precision becomes the conservative UNAUDITED author
6157 // seed (the elementwise pointwise precedent; the retired
6158 // VULKAN_{FLOAT,HALF}_POINTWISE_PRECISION consts are not re-asserted). -----
6159
6160 // ----- QMatMul (Q4_0 / Q4_K_M / Q8_0) — F32 × U32-quant → F32 —
6161 // MIGRATED to FKC contract import. The hand-written
6162 // `table.register_with_precision(OpKind::QMatMul, &[F32, U32, F32], …)` reg is
6163 // DELETED; the single binding now registers from
6164 // `fuel-dispatch/kernel-contracts/vulkan/qmatmul.fkc.md` via
6165 // `register_vulkan_qmatmul_from_contract` (called at the END of this fn, before
6166 // the cost-fill pass). ONE wrapper `qmatmul_vk` route-picks Q4_0 (fused
6167 // gemv/tiled) / Q4_K_M / Q8_0 (dequant-then-matmul_f32) by
6168 // `OpParams::QMatMul.quant_type` — the contract keys the weight slot with the
6169 // LOGICAL `U32` dispatch dtype (the CPU linear-quant U8→U32 reconciliation; the
6170 // physical GGML block-byte honesty rides `fdx.quant`). CONTIGUOUS-ONLY: the
6171 // quantized weight stream has a fixed block layout (per-block scale + N
6172 // quantized lanes); arbitrary strides on the weight buffer would break the
6173 // dequant kernel's block walk (`requires_contiguous` ⇒ strided_input=false).
6174 // Precision becomes the contract's corrected nondeterministic seed (the retired
6175 // `VULKAN_QMATMUL_PRECISION` const over-claimed bit-stability, like the retired
6176 // `VULKAN_MATMUL_PRECISION`; the const def stays in `fused.rs`). -----
6177
6178 // ----- Conv2D (f32 + bf16/f16 cooperative-matrix) — MIGRATED to FKC
6179 // contract import. The hand-written `table.register_with_precision(
6180 // OpKind::Conv2D, …)` regs (f32 here + the bf16/f16 coop combos further
6181 // below) are DELETED; the whole family now registers from
6182 // `fuel-dispatch/kernel-contracts/vulkan/conv.fkc.md` via
6183 // `register_vulkan_conv_from_contract` (called at the END of this fn, before
6184 // the cost-fill pass). Caps stay contiguous-only (`requires_contiguous` ⇒
6185 // strided_input=false); no bias key (the wrappers bail on a 3-input call);
6186 // precision becomes the contract's corrected nondeterministic seed (the
6187 // retired VULKAN_MATMUL_PRECISION / VULKAN_MATMUL_TENSORCORE_PRECISION consts
6188 // over-claimed bit-stability). -----
6189
6190 // ----- FlashAttn (forward f32/bf16/f16) + FlashAttnBackward{Q,K,V} (f32)
6191 // — MIGRATED to FKC contract import. The hand-written
6192 // `table.register_with_precision(OpKind::{FlashAttn,FlashAttnBackwardQ,
6193 // FlashAttnBackwardK,FlashAttnBackwardV}, …)` regs (naive single-pass SDPA;
6194 // both the no-alibi [q,k,v,(do,)out] and with-alibi [q,k,v,(do,)alibi,out]
6195 // binding shapes) are DELETED; the whole FlashAttention family now registers
6196 // from `fuel-dispatch/kernel-contracts/vulkan/attention.fkc.md` via
6197 // `register_vulkan_attention_from_contract` (called at the END of this fn,
6198 // before the cost-fill pass). Forward is THREE distinct per-dtype wrappers
6199 // (per-dtype sections, the conv2d + CPU-attention precedent); backward is
6200 // f32-only. `alibi_slopes` is an optional-LAST input (dual-key fan);
6201 // op_params.variant: FlashAttn shared across forward + backward. Caps stay
6202 // contiguous-only (`requires_contiguous` ⇒ strided_input=false); precision
6203 // becomes the contract's corrected audited-nondeterministic none(reason) seed
6204 // (single-pass shared-mem softmax reduction is scheduler-dependent — the
6205 // retired VULKAN_{FLOAT,HALF}_POINTWISE_PRECISION consts over-claimed
6206 // bit-stability). This was the LAST hand-written table.register* call — the
6207 // Vulkan backend is now 100% contract-sourced. -----
6208
6209 // ----- Conv2D bf16 + f16 (V.3.I extended) — im2col + cooperative-matrix
6210 // GEMM — MIGRATED to FKC contract import (deleted; now registered from
6211 // `fuel-dispatch/kernel-contracts/vulkan/conv.fkc.md` via
6212 // `register_vulkan_conv_from_contract`, alongside the f32 combo above). -----
6213
6214 // ----- Cast F8E4M3 ↔ {F32, F16, BF16} — MIGRATED to FKC contract
6215 // import (`register_vulkan_cast_from_contract`, called below). The six
6216 // hand-written `OpKind::Cast` F8E4M3 regs are DELETED — the contract is
6217 // now the sole registration path for the whole cast family. -----
6218
6219 // ----- Op::Copy D2H (bridge-retirement Phase 2). Byte-level.
6220 // CONTIGUOUS-ONLY: the wrapper downloads the source's bytes via
6221 // a Vulkan staging buffer (vkCmdCopyBuffer). The staging buffer
6222 // is sized to the source's flat byte count; stride-aware D2H
6223 // would require either per-row staging or an explicit pre-
6224 // Contiguize step. Auto-Contiguize handles non-contiguous
6225 // sources upstream of this kernel. -----
6226 // Op::Copy (D2H) — MIGRATED to FKC contract import (deleted; now registered
6227 // from `fuel-dispatch/kernel-contracts/vulkan/pad-copy.fkc.md` via
6228 // `register_vulkan_pad_copy_from_contract`, alongside Pad + PadBackward). ONE
6229 // dtype-agnostic wrapper (`copy_to_cpu_vulkan`) across 9 dtype keys
6230 // (synthetic-base umbrella); contiguous-only. -----
6231
6232 // ----- Cast family (all 12 SRC↔DST pairs) — registered FROM its FKC
6233 // kernel contract, the SOLE path (hand-written Cast regs deleted above).
6234 // Runs BEFORE the cost-fill pass so its imported `unknown_cost` sentinels
6235 // are upgraded to the same OpKind cost fn every other Vulkan primitive
6236 // gets. -----
6237 register_vulkan_cast_from_contract(table);
6238
6239 // ----- Elementwise family (unary / binary / affine / clamp / powi, 94
6240 // (op, dtype) bindings) — registered FROM its RE-AUTHORED FKC kernel contract,
6241 // the SOLE path (all hand-written elementwise regs deleted above). Runs BEFORE
6242 // the cost-fill pass so its imported `unknown_cost` sentinels are upgraded to
6243 // the same OpKind cost fn every other Vulkan primitive gets. This is the first
6244 // caps-through-import proof: the strided sections' layout projects
6245 // `strided_input=true`, the bf16-unary / affine_bf16 sections' `false`. -----
6246 register_vulkan_elementwise_from_contract(table);
6247
6248 // ----- MatMul family (f32 GEMM + the five mixed-precision / tensor-core
6249 // combos, 6 (MatMul, [lhs,rhs,out]) bindings) — registered FROM its
6250 // RE-AUTHORED FKC kernel contract, the SOLE path (all hand-written MatMul regs
6251 // deleted above). Runs BEFORE the cost-fill pass so its imported
6252 // `unknown_cost` sentinels are upgraded to the same OpKind cost fn every other
6253 // Vulkan primitive gets. Caps ride through contiguous-only
6254 // (`requires_contiguous` ⇒ strided_input=false). -----
6255 register_vulkan_matmul_from_contract(table);
6256
6257 // ----- Conv2D family (f32 + bf16/f16 cooperative-matrix, 3 (Conv2D,
6258 // [x, weight, out]) bindings) — registered FROM its RE-AUTHORED FKC kernel
6259 // contract, the SOLE path (all hand-written Conv2D regs deleted above). Runs
6260 // BEFORE the cost-fill pass so its imported `unknown_cost` sentinels are
6261 // upgraded to the same OpKind cost fn every other Vulkan primitive gets. Caps
6262 // ride through contiguous-only (`requires_contiguous` ⇒ strided_input=false);
6263 // no bias key (the wrappers bail on a 3-input call). -----
6264 register_vulkan_conv_from_contract(table);
6265
6266 // ----- Select family (IndexSelect (4) + Gather (6) + MaskedFill (6), 16
6267 // (op, dtype) bindings) — registered FROM its FKC kernel contract, the SOLE
6268 // path (all hand-written IndexSelect/Gather/MaskedFill regs deleted above).
6269 // Runs BEFORE the cost-fill pass so its imported `unknown_cost` sentinels are
6270 // upgraded to the same OpKind cost fn. Caps ride through contiguous-only
6271 // (`requires_contiguous` ⇒ strided_input=false); Gather/MaskedFill are a
6272 // synthetic-base umbrella (one wrapper per op across its dtype keys). -----
6273 register_vulkan_select_from_contract(table);
6274
6275 // ----- Scatter family (IndexAdd (4) + ScatterAdd (4), 8 (op, dtype) bindings)
6276 // — registered FROM its FKC kernel contract, the SOLE path (all hand-written
6277 // IndexAdd/ScatterAdd regs deleted above). Runs BEFORE the cost-fill pass.
6278 // Caps ride through contiguous-only; precision is the audited nondeterministic
6279 // none(reason) seed (bounded-CAS atomic accumulate). -----
6280 register_vulkan_scatter_from_contract(table);
6281
6282 // ----- Movement family (Concat (4) + CumSum (4), 8 (op, dtype) bindings) —
6283 // registered FROM its FKC kernel contract, the SOLE path (all hand-written
6284 // Concat/CumSum regs deleted above). Runs BEFORE the cost-fill pass. Both are
6285 // stride-aware (`strided: accepted` ⇒ strided_input=true); Concat byte-exact,
6286 // CumSum conservative UNAUDITED (the elementwise pointwise precedent). -----
6287 register_vulkan_movement_from_contract(table);
6288
6289 // ----- Shape family (Triu (7) + Tril (7) + Flip (7) + Roll (7), 28 (op, dtype)
6290 // bindings) — registered FROM its FKC kernel contract, the SOLE path (all
6291 // hand-written Triu/Tril/Flip/Roll regs deleted above). Runs BEFORE the
6292 // cost-fill pass. Each op is a synthetic-base umbrella (one dtype-agnostic
6293 // wrapper); Triu/Tril contiguous, Flip/Roll stride-aware. -----
6294 register_vulkan_shape_from_contract(table);
6295
6296 // ----- Pad-copy family (Pad (6) + PadBackward (6) + Copy (9), 21 (op, dtype)
6297 // bindings) — registered FROM its FKC kernel contract, the SOLE path (all
6298 // hand-written Pad/PadBackward/Copy regs deleted above). Runs BEFORE the
6299 // cost-fill pass. Each op is a synthetic-base umbrella (one dtype-agnostic
6300 // wrapper); const mode only; contiguous-only. -----
6301 register_vulkan_pad_copy_from_contract(table);
6302
6303 // ----- Write-slice family (WriteSlice (9) + WriteSliceRotating (9), 18
6304 // (op, dtype) bindings) — registered FROM its FKC kernel contract, the SOLE
6305 // path (all hand-written WriteSlice/WriteSliceRotating regs deleted above). Runs
6306 // BEFORE the cost-fill pass. Byte-width-keyed (9 dtypes share 4 b1/b2/b4/b8
6307 // wrappers per op); contiguous-only. -----
6308 register_vulkan_write_slice_from_contract(table);
6309
6310 // ----- RoPE family (4 (Rope, [x, cos, sin, out]) per-dtype bindings) —
6311 // registered FROM its FKC kernel contract, the SOLE path (all hand-written Rope
6312 // regs deleted above). Runs BEFORE the cost-fill pass. Stride-aware
6313 // (strided_input=true); precision is the conservative UNAUDITED author seed. -----
6314 register_vulkan_rope_from_contract(table);
6315
6316 // ----- Reduce family (SumReduce/MaxReduce/MinReduce/MeanReduce (16) +
6317 // ArgMaxDim/ArgMinDim (8), 24 (op, dtype) bindings) — registered FROM its FKC
6318 // kernel contract, the SOLE path (all hand-written reduce/arg-reduce regs
6319 // deleted above). Runs BEFORE the cost-fill pass. Contiguous-only; value reduces
6320 // audited nondeterministic none(reason), arg reduces bitwise exact. -----
6321 register_vulkan_reduce_from_contract(table);
6322
6323 // ----- Norm family (SoftmaxLastDim (4) + SoftmaxLastDimBackward (4) +
6324 // LayerNormLastDim (4) + LayerNormLastDimBackward (4) + RmsNormLastDim (4), 20
6325 // (op, dtype) bindings) — registered FROM its FKC kernel contract, the SOLE path
6326 // (all hand-written norm/softmax regs deleted above). Runs BEFORE the cost-fill
6327 // pass. Contiguous-only; audited nondeterministic none(reason) (per-row
6328 // subgroup-tree FADD order). -----
6329 register_vulkan_norm_from_contract(table);
6330
6331 // ----- QMatMul family (ONE (QMatMul, [F32, U32, F32]) binding) — registered
6332 // FROM its RE-AUTHORED FKC kernel contract, the SOLE path (the hand-written
6333 // `register_with_precision(OpKind::QMatMul, …)` reg deleted above). Runs BEFORE
6334 // the cost-fill pass so its imported `unknown_cost` sentinel is upgraded to the
6335 // same OpKind cost fn every other Vulkan primitive gets. ONE wrapper
6336 // (`qmatmul::qmatmul_vk`) route-picks Q4_0 / Q4_K_M / Q8_0 by
6337 // `OpParams::QMatMul.quant_type`; weight slot keyed with the LOGICAL U32 dtype
6338 // (the CPU linear-quant U8→U32 reconciliation; physical GGML block-byte honesty
6339 // on `fdx.quant`). Contiguous-only (`requires_contiguous` ⇒ strided_input=false);
6340 // precision is the audited nondeterministic none(reason) seed (the retired
6341 // VULKAN_QMATMUL_PRECISION over-claimed bit-stability). -----
6342 register_vulkan_qmatmul_from_contract(table);
6343
6344 // ----- FlashAttention family (forward FlashAttn f32/bf16/f16 + backward
6345 // FlashAttnBackward{Q,K,V} f32, 12 bindings) — registered FROM its AUTHORED
6346 // FKC kernel contract, the SOLE path (the LAST hand-written table.register*
6347 // calls, all deleted above). Runs BEFORE the cost-fill pass so its imported
6348 // `unknown_cost` sentinels are upgraded to the same OpKind cost fn every other
6349 // Vulkan primitive gets. Forward is three distinct per-dtype wrappers
6350 // (per-dtype sections); backward is f32-only; `alibi_slopes` optional-LAST
6351 // (dual-key fan). Contiguous-only (`requires_contiguous` ⇒ strided_input=false);
6352 // precision is the corrected audited-nondeterministic none(reason) seed
6353 // (single-pass shared-mem softmax reduction). With this call the Vulkan backend
6354 // is 100% contract-sourced: `register_vulkan_kernels` contains ZERO hand-written
6355 // `table.register*` calls. -----
6356 register_vulkan_attention_from_contract(table);
6357
6358 // ----- Bulk-fill cost functions for every Vulkan registration above.
6359 // The CPU dispatcher (`default_cost_for_op_kind`) captures the
6360 // FLOP/bandwidth model; backend-specific kernel_overhead_ns
6361 // adjustments are deferred to a Vulkan-flavored dispatcher (or to
6362 // the empirical calibration framework). Every entry above started
6363 // at `unknown_cost`; this pass upgrades them to a real cost
6364 // function so the optimizer's cost-ranking can admit Vulkan
6365 // alternatives.
6366 table.fill_unset_cost_for_backend(vk, fuel_dispatch::cost::default_cost_for_op_kind);
6367}
6368
6369// ===========================================================================
6370// FKC contract-migration tests (born-red gate for the Vulkan cast family)
6371// ===========================================================================
6372//
6373// This whole crate is the Vulkan crate (the file used to carry `#![cfg(feature = "vulkan")]`), so this module always compiles
6374// and no device is touched (registration is pure
6375// binding-table population; `register_vulkan_kernels` never probes hardware).
6376
6377/// Split-KV heuristic for the Vulkan flash-attention routes (f32, bf16, f16;
6378/// ROADMAP 17, H12). `Some(splits)` only for a decode step (`sq == 1`) whose
6379/// `b * hq` workgroups leave the GPU underfilled and whose key range is long
6380/// enough to pay for the second dispatch. Thresholds come from
6381/// `docs/research/split-kv-decode-measurement.md` (RTX 4070 Laptop, D=128,
6382/// one run per cell, about +-15% spread): f32 1.3-1.9x at `b*hq <= 8`,
6383/// `Sk >= 2048`; bf16/f16 1.3-1.8x at `b*hq <= 16` for `Sk >= 2048`; about
6384/// 1.15x at 32-64 heads (not taken: the merge reorders float adds, so the
6385/// split path is only used where it clearly wins); no gain at `Sk = 1024`.
6386/// One device: a prior, not a tuned value.
6387fn decode_splits(b: usize, hq: usize, sq: usize, sk: usize) -> Option<usize> {
6388 const MAX_ROWS: usize = 16;
6389 const MIN_SK: usize = 2048;
6390 const SPLITS: usize = 8;
6391 if sq == 1 && b * hq <= MAX_ROWS && (MIN_SK..=4096).contains(&sk) {
6392 Some(SPLITS)
6393 } else {
6394 None
6395 }
6396}
6397
6398#[cfg(test)]
6399mod decode_splits_tests {
6400 use super::decode_splits;
6401
6402 #[test]
6403 fn splits_only_underfilled_long_decode() {
6404 // Measured wins: few heads, long cache, decode.
6405 assert_eq!(decode_splits(1, 8, 1, 4096), Some(8));
6406 assert_eq!(decode_splits(1, 8, 1, 2048), Some(8));
6407 // Sabotage siblings: each condition alone must flip the answer.
6408 assert_eq!(decode_splits(1, 8, 2, 4096), None, "prefill");
6409 assert_eq!(decode_splits(1, 8, 1, 1024), None, "short cache");
6410 assert_eq!(decode_splits(1, 32, 1, 4096), None, "heads fill the GPU");
6411 assert_eq!(decode_splits(4, 8, 1, 4096), None, "batch fills the GPU");
6412 assert_eq!(decode_splits(1, 8, 1, 4097), None, "beyond the kernel cap");
6413 }
6414
6415 #[test]
6416 fn chosen_splits_satisfy_the_wrapper_chunk_limit() {
6417 for sk in 1..=4200 {
6418 if let Some(n) = decode_splits(1, 8, 1, sk) {
6419 assert!(sk.div_ceil(n) <= 1024 && (1..=64).contains(&n), "sk={sk}");
6420 }
6421 }
6422 }
6423}
6424
6425#[cfg(test)]
6426mod cast_contract_tests {
6427 use super::*;
6428 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
6429
6430 /// FIRST VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
6431 /// registers the whole `OpKind::Cast` family (12 (SRC, DST) pairs) FROM ITS
6432 /// KERNEL CONTRACT (`fuel-dispatch/kernel-contracts/vulkan/cast.fkc.md`) via
6433 /// `register_vulkan_cast_from_contract` — the sole registration path, now
6434 /// that the hand-written `table.register_with_precision(OpKind::Cast, …)`
6435 /// calls (half/f64 + F8E4M3) are DELETED.
6436 ///
6437 /// For each `(Cast, [SRC, DST], Vulkan)` key this asserts:
6438 /// - the binding resolves to the EXACT production wrapper fn-pointer
6439 /// (behavior-preserving execution — the SAME 3 wrappers the deleted regs
6440 /// used, several pairs sharing one wrapper),
6441 /// - `kernel_source == "vulkan-slang"` — the contract's provenance tag (the
6442 /// deleted hand-written path stamped `""`). THIS is the discriminator
6443 /// that makes the test go red without the import wired: with the
6444 /// hand-written cast regs removed and the import absent, the family is
6445 /// simply missing from the table (lookup finds 0 alternatives),
6446 /// - caps stay contiguous-only (`strided_input == false`).
6447 ///
6448 /// Precision is contract-sourced and correctly lowered per FKC §4.8, so it
6449 /// is NOT asserted uniformly here: the 5 `audited: true` sections carry
6450 /// `bit_stable_on_same_hardware`, while the 7 `audited: false` author-seed
6451 /// sections lower to `PrecisionGuarantee::UNAUDITED` (bit_stable=false) —
6452 /// the correct "no audited claim yet" posture, which DIFFERS from the
6453 /// retired hand-written `VULKAN_CAST_PRECISION` (which asserted bit-stable +
6454 /// `max_ulp: Some(0)` uniformly). The Judge audits the seeds later.
6455 #[test]
6456 fn register_vulkan_kernels_binds_cast_family_from_contract() {
6457 let mut table = KernelBindingTable::new();
6458 register_vulkan_kernels(&mut table);
6459 let vk = BackendId::Vulkan;
6460
6461 // (SRC, DST, expected production wrapper) for all 12 cast pairs — the
6462 // exact wrapper each deleted hand-written reg carried.
6463 let cases: &[(DType, DType, KernelRef)] = &[
6464 (DType::F32, DType::F16, cast::cast_f32_half),
6465 (DType::F16, DType::F32, cast::cast_f32_half),
6466 (DType::F32, DType::BF16, cast::cast_f32_half),
6467 (DType::BF16, DType::F32, cast::cast_f32_half),
6468 (DType::F32, DType::F64, cast::cast_f32_f64),
6469 (DType::F64, DType::F32, cast::cast_f32_f64),
6470 (DType::F32, DType::F8E4M3, cast_f8e4m3::cast_f8e4m3),
6471 (DType::F8E4M3, DType::F32, cast_f8e4m3::cast_f8e4m3),
6472 (DType::F16, DType::F8E4M3, cast_f8e4m3::cast_f8e4m3),
6473 (DType::F8E4M3, DType::F16, cast_f8e4m3::cast_f8e4m3),
6474 (DType::BF16, DType::F8E4M3, cast_f8e4m3::cast_f8e4m3),
6475 (DType::F8E4M3, DType::BF16, cast_f8e4m3::cast_f8e4m3),
6476 ];
6477
6478 let mut checked = 0usize;
6479 for (src, dst, expected) in cases {
6480 let alts = table.lookup_alternatives(OpKind::Cast, &[*src, *dst], vk);
6481 let entry = alts
6482 .iter()
6483 .find(|e| e.kernel as usize == *expected as usize)
6484 .unwrap_or_else(|| {
6485 panic!(
6486 "Cast [{src:?}, {dst:?}]/Vulkan: the production wrapper must be bound \
6487 FROM the vulkan cast contract in register_vulkan_kernels — found {} \
6488 alternative(s) with sources {:?}",
6489 alts.len(),
6490 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
6491 )
6492 });
6493 assert_eq!(
6494 entry.kernel_source, "vulkan-slang",
6495 "Cast [{src:?}, {dst:?}]: cast family must be contract-sourced \
6496 (kernel_source=\"vulkan-slang\"); got {:?}",
6497 entry.kernel_source,
6498 );
6499 assert!(
6500 !entry.caps.strided_input,
6501 "Cast [{src:?}, {dst:?}]: caps preserved (contiguous-only, strided_input=false)",
6502 );
6503 checked += 1;
6504 }
6505 assert_eq!(checked, 12, "all 12 (SRC, DST) cast pairs checked");
6506 }
6507}
6508
6509// ===========================================================================
6510// FKC contract-migration tests (born-red gate for the Vulkan elementwise family)
6511// ===========================================================================
6512//
6513// Same always-on gating (this crate IS the Vulkan crate) as the cast tests above: this
6514// module always compiles (this crate has no feature gate) and touches NO device
6515// (registration is pure binding-table population).
6516
6517#[cfg(test)]
6518mod elementwise_contract_tests {
6519 use super::*;
6520 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
6521
6522 /// SECOND VULKAN-BACKEND FKC CONSUMER (born-red gate) + the FIRST
6523 /// caps-through-import proof. `register_vulkan_kernels` registers the whole
6524 /// elementwise family (94 (op, dtype) bindings) FROM ITS RE-AUTHORED KERNEL
6525 /// CONTRACT (`fuel-dispatch/kernel-contracts/vulkan/elementwise.fkc.md`) via
6526 /// `register_vulkan_elementwise_from_contract` -- the sole registration path,
6527 /// now that the hand-written per-(op,dtype) unary(16)/binary(6)/affine/clamp/
6528 /// powi regs are DELETED.
6529 ///
6530 /// For each `(OpKind, [T..], Vulkan)` key this asserts: the binding resolves
6531 /// to the EXACT production wrapper fn-pointer (behavior-preserving); the
6532 /// `kernel_source == "vulkan-slang"` (the RED discriminator -- the deleted
6533 /// hand path stamped `""`); and `caps.strided_input` MATCHES THE HAND-WRITTEN
6534 /// TRUTH PER KEY -- true for the strided unary(f32/f16/f64)/binary(all 4)/
6535 /// affine(f32/f16/f64)/clamp/powi keys, false for the contiguous-only
6536 /// bf16-unary / affine_bf16 keys. That last assertion is the
6537 /// caps-through-import proof: the contract's per-operand five-flag layout
6538 /// projects onto the binding's `KernelCaps.strided_input` exactly as the hand
6539 /// path set it. Precision is contract-sourced (`audited: false` -> UNAUDITED,
6540 /// the cast-migration precedent) and NOT asserted here.
6541 #[test]
6542 fn register_vulkan_kernels_binds_elementwise_family_from_contract() {
6543 let mut table = KernelBindingTable::new();
6544 register_vulkan_kernels(&mut table);
6545 let vk = BackendId::Vulkan;
6546
6547 // (OpKind, key dtypes, expected production wrapper, expected strided_input)
6548 let cases: &[(OpKind, &[DType], KernelRef, bool)] = &[
6549 // ---- Unary: 16 ops x {f32,f16,f64 strided; bf16 contiguous} -- key [T, T]. ----
6550 (
6551 OpKind::NegElementwise,
6552 &[DType::F32, DType::F32],
6553 unary::neg_f32 as KernelRef,
6554 true,
6555 ),
6556 (
6557 OpKind::NegElementwise,
6558 &[DType::F16, DType::F16],
6559 unary_f16::neg_f16 as KernelRef,
6560 true,
6561 ),
6562 (
6563 OpKind::NegElementwise,
6564 &[DType::F64, DType::F64],
6565 unary_f64::neg_f64 as KernelRef,
6566 true,
6567 ),
6568 (
6569 OpKind::NegElementwise,
6570 &[DType::BF16, DType::BF16],
6571 unary_bf16::neg_bf16 as KernelRef,
6572 false,
6573 ),
6574 (
6575 OpKind::SqrElementwise,
6576 &[DType::F32, DType::F32],
6577 unary::sqr_f32 as KernelRef,
6578 true,
6579 ),
6580 (
6581 OpKind::SqrElementwise,
6582 &[DType::F16, DType::F16],
6583 unary_f16::sqr_f16 as KernelRef,
6584 true,
6585 ),
6586 (
6587 OpKind::SqrElementwise,
6588 &[DType::F64, DType::F64],
6589 unary_f64::sqr_f64 as KernelRef,
6590 true,
6591 ),
6592 (
6593 OpKind::SqrElementwise,
6594 &[DType::BF16, DType::BF16],
6595 unary_bf16::sqr_bf16 as KernelRef,
6596 false,
6597 ),
6598 (
6599 OpKind::SqrtElementwise,
6600 &[DType::F32, DType::F32],
6601 unary::sqrt_f32 as KernelRef,
6602 true,
6603 ),
6604 (
6605 OpKind::SqrtElementwise,
6606 &[DType::F16, DType::F16],
6607 unary_f16::sqrt_f16 as KernelRef,
6608 true,
6609 ),
6610 (
6611 OpKind::SqrtElementwise,
6612 &[DType::F64, DType::F64],
6613 unary_f64::sqrt_f64 as KernelRef,
6614 true,
6615 ),
6616 (
6617 OpKind::SqrtElementwise,
6618 &[DType::BF16, DType::BF16],
6619 unary_bf16::sqrt_bf16 as KernelRef,
6620 false,
6621 ),
6622 (
6623 OpKind::ExpElementwise,
6624 &[DType::F32, DType::F32],
6625 unary::exp_f32 as KernelRef,
6626 true,
6627 ),
6628 (
6629 OpKind::ExpElementwise,
6630 &[DType::F16, DType::F16],
6631 unary_f16::exp_f16 as KernelRef,
6632 true,
6633 ),
6634 (
6635 OpKind::ExpElementwise,
6636 &[DType::F64, DType::F64],
6637 unary_f64::exp_f64 as KernelRef,
6638 true,
6639 ),
6640 (
6641 OpKind::ExpElementwise,
6642 &[DType::BF16, DType::BF16],
6643 unary_bf16::exp_bf16 as KernelRef,
6644 false,
6645 ),
6646 (
6647 OpKind::LogElementwise,
6648 &[DType::F32, DType::F32],
6649 unary::log_f32 as KernelRef,
6650 true,
6651 ),
6652 (
6653 OpKind::LogElementwise,
6654 &[DType::F16, DType::F16],
6655 unary_f16::log_f16 as KernelRef,
6656 true,
6657 ),
6658 (
6659 OpKind::LogElementwise,
6660 &[DType::F64, DType::F64],
6661 unary_f64::log_f64 as KernelRef,
6662 true,
6663 ),
6664 (
6665 OpKind::LogElementwise,
6666 &[DType::BF16, DType::BF16],
6667 unary_bf16::log_bf16 as KernelRef,
6668 false,
6669 ),
6670 (
6671 OpKind::SinElementwise,
6672 &[DType::F32, DType::F32],
6673 unary::sin_f32 as KernelRef,
6674 true,
6675 ),
6676 (
6677 OpKind::SinElementwise,
6678 &[DType::F16, DType::F16],
6679 unary_f16::sin_f16 as KernelRef,
6680 true,
6681 ),
6682 (
6683 OpKind::SinElementwise,
6684 &[DType::F64, DType::F64],
6685 unary_f64::sin_f64 as KernelRef,
6686 true,
6687 ),
6688 (
6689 OpKind::SinElementwise,
6690 &[DType::BF16, DType::BF16],
6691 unary_bf16::sin_bf16 as KernelRef,
6692 false,
6693 ),
6694 (
6695 OpKind::CosElementwise,
6696 &[DType::F32, DType::F32],
6697 unary::cos_f32 as KernelRef,
6698 true,
6699 ),
6700 (
6701 OpKind::CosElementwise,
6702 &[DType::F16, DType::F16],
6703 unary_f16::cos_f16 as KernelRef,
6704 true,
6705 ),
6706 (
6707 OpKind::CosElementwise,
6708 &[DType::F64, DType::F64],
6709 unary_f64::cos_f64 as KernelRef,
6710 true,
6711 ),
6712 (
6713 OpKind::CosElementwise,
6714 &[DType::BF16, DType::BF16],
6715 unary_bf16::cos_bf16 as KernelRef,
6716 false,
6717 ),
6718 (
6719 OpKind::TanhElementwise,
6720 &[DType::F32, DType::F32],
6721 unary::tanh_f32 as KernelRef,
6722 true,
6723 ),
6724 (
6725 OpKind::TanhElementwise,
6726 &[DType::F16, DType::F16],
6727 unary_f16::tanh_f16 as KernelRef,
6728 true,
6729 ),
6730 (
6731 OpKind::TanhElementwise,
6732 &[DType::F64, DType::F64],
6733 unary_f64::tanh_f64 as KernelRef,
6734 true,
6735 ),
6736 (
6737 OpKind::TanhElementwise,
6738 &[DType::BF16, DType::BF16],
6739 unary_bf16::tanh_bf16 as KernelRef,
6740 false,
6741 ),
6742 (
6743 OpKind::SigmoidElementwise,
6744 &[DType::F32, DType::F32],
6745 unary::sigmoid_f32 as KernelRef,
6746 true,
6747 ),
6748 (
6749 OpKind::SigmoidElementwise,
6750 &[DType::F16, DType::F16],
6751 unary_f16::sigmoid_f16 as KernelRef,
6752 true,
6753 ),
6754 (
6755 OpKind::SigmoidElementwise,
6756 &[DType::F64, DType::F64],
6757 unary_f64::sigmoid_f64 as KernelRef,
6758 true,
6759 ),
6760 (
6761 OpKind::SigmoidElementwise,
6762 &[DType::BF16, DType::BF16],
6763 unary_bf16::sigmoid_bf16 as KernelRef,
6764 false,
6765 ),
6766 (
6767 OpKind::SiluElementwise,
6768 &[DType::F32, DType::F32],
6769 unary::silu_f32 as KernelRef,
6770 true,
6771 ),
6772 (
6773 OpKind::SiluElementwise,
6774 &[DType::F16, DType::F16],
6775 unary_f16::silu_f16 as KernelRef,
6776 true,
6777 ),
6778 (
6779 OpKind::SiluElementwise,
6780 &[DType::F64, DType::F64],
6781 unary_f64::silu_f64 as KernelRef,
6782 true,
6783 ),
6784 (
6785 OpKind::SiluElementwise,
6786 &[DType::BF16, DType::BF16],
6787 unary_bf16::silu_bf16 as KernelRef,
6788 false,
6789 ),
6790 (
6791 OpKind::GeluTanhElementwise,
6792 &[DType::F32, DType::F32],
6793 unary::gelu_f32 as KernelRef,
6794 true,
6795 ),
6796 (
6797 OpKind::GeluTanhElementwise,
6798 &[DType::F16, DType::F16],
6799 unary_f16::gelu_f16 as KernelRef,
6800 true,
6801 ),
6802 (
6803 OpKind::GeluTanhElementwise,
6804 &[DType::F64, DType::F64],
6805 unary_f64::gelu_f64 as KernelRef,
6806 true,
6807 ),
6808 (
6809 OpKind::GeluTanhElementwise,
6810 &[DType::BF16, DType::BF16],
6811 unary_bf16::gelu_bf16 as KernelRef,
6812 false,
6813 ),
6814 (
6815 OpKind::ReluElementwise,
6816 &[DType::F32, DType::F32],
6817 unary::relu_f32 as KernelRef,
6818 true,
6819 ),
6820 (
6821 OpKind::ReluElementwise,
6822 &[DType::F16, DType::F16],
6823 unary_f16::relu_f16 as KernelRef,
6824 true,
6825 ),
6826 (
6827 OpKind::ReluElementwise,
6828 &[DType::F64, DType::F64],
6829 unary_f64::relu_f64 as KernelRef,
6830 true,
6831 ),
6832 (
6833 OpKind::ReluElementwise,
6834 &[DType::BF16, DType::BF16],
6835 unary_bf16::relu_bf16 as KernelRef,
6836 false,
6837 ),
6838 (
6839 OpKind::StepElementwise,
6840 &[DType::F32, DType::F32],
6841 unary::step_f32 as KernelRef,
6842 true,
6843 ),
6844 (
6845 OpKind::StepElementwise,
6846 &[DType::F16, DType::F16],
6847 unary_f16::step_f16 as KernelRef,
6848 true,
6849 ),
6850 (
6851 OpKind::StepElementwise,
6852 &[DType::F64, DType::F64],
6853 unary_f64::step_f64 as KernelRef,
6854 true,
6855 ),
6856 (
6857 OpKind::StepElementwise,
6858 &[DType::BF16, DType::BF16],
6859 unary_bf16::step_bf16 as KernelRef,
6860 false,
6861 ),
6862 (
6863 OpKind::AbsElementwise,
6864 &[DType::F32, DType::F32],
6865 unary::abs_f32 as KernelRef,
6866 true,
6867 ),
6868 (
6869 OpKind::AbsElementwise,
6870 &[DType::F16, DType::F16],
6871 unary_f16::abs_f16 as KernelRef,
6872 true,
6873 ),
6874 (
6875 OpKind::AbsElementwise,
6876 &[DType::F64, DType::F64],
6877 unary_f64::abs_f64 as KernelRef,
6878 true,
6879 ),
6880 (
6881 OpKind::AbsElementwise,
6882 &[DType::BF16, DType::BF16],
6883 unary_bf16::abs_bf16 as KernelRef,
6884 false,
6885 ),
6886 (
6887 OpKind::SignElementwise,
6888 &[DType::F32, DType::F32],
6889 unary::sign_f32 as KernelRef,
6890 true,
6891 ),
6892 (
6893 OpKind::SignElementwise,
6894 &[DType::F16, DType::F16],
6895 unary_f16::sign_f16 as KernelRef,
6896 true,
6897 ),
6898 (
6899 OpKind::SignElementwise,
6900 &[DType::F64, DType::F64],
6901 unary_f64::sign_f64 as KernelRef,
6902 true,
6903 ),
6904 (
6905 OpKind::SignElementwise,
6906 &[DType::BF16, DType::BF16],
6907 unary_bf16::sign_bf16 as KernelRef,
6908 false,
6909 ),
6910 (
6911 OpKind::RecipElementwise,
6912 &[DType::F32, DType::F32],
6913 unary::recip_f32 as KernelRef,
6914 true,
6915 ),
6916 (
6917 OpKind::RecipElementwise,
6918 &[DType::F16, DType::F16],
6919 unary_f16::recip_f16 as KernelRef,
6920 true,
6921 ),
6922 (
6923 OpKind::RecipElementwise,
6924 &[DType::F64, DType::F64],
6925 unary_f64::recip_f64 as KernelRef,
6926 true,
6927 ),
6928 (
6929 OpKind::RecipElementwise,
6930 &[DType::BF16, DType::BF16],
6931 unary_bf16::recip_bf16 as KernelRef,
6932 false,
6933 ),
6934 // ---- Binary: 6 ops x {f32,f16,f64,bf16} all strided -- key [T, T, T]. ----
6935 (
6936 OpKind::AddElementwise,
6937 &[DType::F32, DType::F32, DType::F32],
6938 binary::add_f32 as KernelRef,
6939 true,
6940 ),
6941 (
6942 OpKind::AddElementwise,
6943 &[DType::F16, DType::F16, DType::F16],
6944 binary_f16::add_f16 as KernelRef,
6945 true,
6946 ),
6947 (
6948 OpKind::AddElementwise,
6949 &[DType::F64, DType::F64, DType::F64],
6950 binary_f64::add_f64 as KernelRef,
6951 true,
6952 ),
6953 (
6954 OpKind::AddElementwise,
6955 &[DType::BF16, DType::BF16, DType::BF16],
6956 binary_bf16::add_bf16 as KernelRef,
6957 true,
6958 ),
6959 (
6960 OpKind::SubElementwise,
6961 &[DType::F32, DType::F32, DType::F32],
6962 binary::sub_f32 as KernelRef,
6963 true,
6964 ),
6965 (
6966 OpKind::SubElementwise,
6967 &[DType::F16, DType::F16, DType::F16],
6968 binary_f16::sub_f16 as KernelRef,
6969 true,
6970 ),
6971 (
6972 OpKind::SubElementwise,
6973 &[DType::F64, DType::F64, DType::F64],
6974 binary_f64::sub_f64 as KernelRef,
6975 true,
6976 ),
6977 (
6978 OpKind::SubElementwise,
6979 &[DType::BF16, DType::BF16, DType::BF16],
6980 binary_bf16::sub_bf16 as KernelRef,
6981 true,
6982 ),
6983 (
6984 OpKind::MulElementwise,
6985 &[DType::F32, DType::F32, DType::F32],
6986 binary::mul_f32 as KernelRef,
6987 true,
6988 ),
6989 (
6990 OpKind::MulElementwise,
6991 &[DType::F16, DType::F16, DType::F16],
6992 binary_f16::mul_f16 as KernelRef,
6993 true,
6994 ),
6995 (
6996 OpKind::MulElementwise,
6997 &[DType::F64, DType::F64, DType::F64],
6998 binary_f64::mul_f64 as KernelRef,
6999 true,
7000 ),
7001 (
7002 OpKind::MulElementwise,
7003 &[DType::BF16, DType::BF16, DType::BF16],
7004 binary_bf16::mul_bf16 as KernelRef,
7005 true,
7006 ),
7007 (
7008 OpKind::DivElementwise,
7009 &[DType::F32, DType::F32, DType::F32],
7010 binary::div_f32 as KernelRef,
7011 true,
7012 ),
7013 (
7014 OpKind::DivElementwise,
7015 &[DType::F16, DType::F16, DType::F16],
7016 binary_f16::div_f16 as KernelRef,
7017 true,
7018 ),
7019 (
7020 OpKind::DivElementwise,
7021 &[DType::F64, DType::F64, DType::F64],
7022 binary_f64::div_f64 as KernelRef,
7023 true,
7024 ),
7025 (
7026 OpKind::DivElementwise,
7027 &[DType::BF16, DType::BF16, DType::BF16],
7028 binary_bf16::div_bf16 as KernelRef,
7029 true,
7030 ),
7031 (
7032 OpKind::MaximumElementwise,
7033 &[DType::F32, DType::F32, DType::F32],
7034 binary::maximum_f32 as KernelRef,
7035 true,
7036 ),
7037 (
7038 OpKind::MaximumElementwise,
7039 &[DType::F16, DType::F16, DType::F16],
7040 binary_f16::maximum_f16 as KernelRef,
7041 true,
7042 ),
7043 (
7044 OpKind::MaximumElementwise,
7045 &[DType::F64, DType::F64, DType::F64],
7046 binary_f64::maximum_f64 as KernelRef,
7047 true,
7048 ),
7049 (
7050 OpKind::MaximumElementwise,
7051 &[DType::BF16, DType::BF16, DType::BF16],
7052 binary_bf16::maximum_bf16 as KernelRef,
7053 true,
7054 ),
7055 (
7056 OpKind::MinimumElementwise,
7057 &[DType::F32, DType::F32, DType::F32],
7058 binary::minimum_f32 as KernelRef,
7059 true,
7060 ),
7061 (
7062 OpKind::MinimumElementwise,
7063 &[DType::F16, DType::F16, DType::F16],
7064 binary_f16::minimum_f16 as KernelRef,
7065 true,
7066 ),
7067 (
7068 OpKind::MinimumElementwise,
7069 &[DType::F64, DType::F64, DType::F64],
7070 binary_f64::minimum_f64 as KernelRef,
7071 true,
7072 ),
7073 (
7074 OpKind::MinimumElementwise,
7075 &[DType::BF16, DType::BF16, DType::BF16],
7076 binary_bf16::minimum_bf16 as KernelRef,
7077 true,
7078 ),
7079 // ---- Affine: f32/f16/f64 strided + bf16 contiguous -- key [T, T]. ----
7080 (
7081 OpKind::Affine,
7082 &[DType::F32, DType::F32],
7083 affine::affine_f32 as KernelRef,
7084 true,
7085 ),
7086 (
7087 OpKind::Affine,
7088 &[DType::F16, DType::F16],
7089 affine::affine_f16 as KernelRef,
7090 true,
7091 ),
7092 (
7093 OpKind::Affine,
7094 &[DType::F64, DType::F64],
7095 affine::affine_f64 as KernelRef,
7096 true,
7097 ),
7098 (
7099 OpKind::Affine,
7100 &[DType::BF16, DType::BF16],
7101 affine::affine_bf16 as KernelRef,
7102 false,
7103 ),
7104 // ---- Clamp / PowI: single-dtype f32 strided -- key [T, T]. ----
7105 (
7106 OpKind::ClampElementwise,
7107 &[DType::F32, DType::F32],
7108 clamp::clamp_f32 as KernelRef,
7109 true,
7110 ),
7111 (
7112 OpKind::PowIElementwise,
7113 &[DType::F32, DType::F32],
7114 powi::powi_f32 as KernelRef,
7115 true,
7116 ),
7117 ];
7118
7119 let mut checked = 0usize;
7120 for (op, key, expected, expect_strided) in cases {
7121 let alts = table.lookup_alternatives(*op, key, vk);
7122 let entry = alts
7123 .iter()
7124 .find(|e| e.kernel as usize == *expected as usize);
7125 let entry = match entry {
7126 Some(e) => e,
7127 None => panic!(
7128 "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan elementwise contract; found {} alt(s) with sources {:?}",
7129 alts.len(),
7130 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7131 ),
7132 };
7133 assert_eq!(
7134 entry.kernel_source, "vulkan-slang",
7135 "{op:?} {key:?}: elementwise family must be contract-sourced (kernel_source=vulkan-slang); got {:?}",
7136 entry.kernel_source,
7137 );
7138 assert_eq!(
7139 entry.caps.strided_input, *expect_strided,
7140 "{op:?} {key:?}: caps must ride through the import truthfully (strided_input matches the hand-written reg)",
7141 );
7142 checked += 1;
7143 }
7144 assert_eq!(
7145 checked, 94,
7146 "all 94 (op, dtype) elementwise bindings checked"
7147 );
7148 }
7149}
7150
7151// ===========================================================================
7152// FKC contract-migration tests (born-red gate for the Vulkan matmul family)
7153// ===========================================================================
7154//
7155// Same always-on gating (this crate IS the Vulkan crate) as the cast / elementwise tests
7156// above: this module always compiles (this crate has no feature gate) and touches NO
7157// device (registration is pure binding-table population).
7158
7159#[cfg(test)]
7160mod matmul_contract_tests {
7161 use super::*;
7162 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7163
7164 /// THIRD VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7165 /// registers the whole Vulkan matmul family (6 per-combo `(MatMul, [lhs,rhs,out])`
7166 /// bindings) FROM ITS RE-AUTHORED KERNEL CONTRACT
7167 /// (`fuel-dispatch/kernel-contracts/vulkan/matmul.fkc.md`) via
7168 /// `register_vulkan_matmul_from_contract` — the sole registration path, now
7169 /// that the hand-written `table.register_with_precision(OpKind::MatMul, …)`
7170 /// regs (the f32 GEMM + the five mixed-precision / tensor-core combos) are
7171 /// DELETED.
7172 ///
7173 /// This ALSO dissolves the `dispatch/matmul.fkc.md :: matmul_mixed_precision`
7174 /// multi-axis `FanoutDtypeMismatch` corpus deferral: the aspirational single
7175 /// multi-dtype section (lhs `[F32,BF16,F16]` vs rhs `[BF16,F16]`) is replaced
7176 /// by EXPLICIT single-dtype-per-operand per-combo sections, exactly the cast
7177 /// family's per-pair precedent.
7178 ///
7179 /// For each `(MatMul, [lhs,rhs,out], Vulkan)` key this asserts: the binding
7180 /// resolves to the EXACT production wrapper fn-pointer (behavior-preserving);
7181 /// `kernel_source == "vulkan-slang"` (the RED discriminator — the deleted hand
7182 /// path stamped `""`, so before the import is wired this assert fails on the
7183 /// empty source); and `caps.strided_input == false` — the contiguous-only
7184 /// truth of the deleted `register_with_precision` regs (the coop / vec4 loads
7185 /// require canonical row-major, so a strided operand is auto-Contiguized
7186 /// first). Precision is contract-sourced (the cast/elementwise precedent) and
7187 /// NOT asserted here.
7188 #[test]
7189 fn register_vulkan_kernels_binds_matmul_family_from_contract() {
7190 let mut table = KernelBindingTable::new();
7191 register_vulkan_kernels(&mut table);
7192 let vk = BackendId::Vulkan;
7193
7194 // (key dtypes [lhs, rhs, out], expected production wrapper). Every matmul
7195 // binding is contiguous-only (strided_input == false), so that is checked
7196 // uniformly below rather than per-row.
7197 let cases: &[(&[DType], KernelRef)] = &[
7198 (
7199 &[DType::F32, DType::F32, DType::F32],
7200 matmul::matmul_f32 as KernelRef,
7201 ),
7202 (
7203 &[DType::F32, DType::BF16, DType::F32],
7204 matmul::matmul_f32_bf16_b as KernelRef,
7205 ),
7206 (
7207 &[DType::BF16, DType::BF16, DType::F32],
7208 matmul::matmul_bf16_bf16_f32 as KernelRef,
7209 ),
7210 (
7211 &[DType::BF16, DType::BF16, DType::BF16],
7212 matmul::matmul_bf16_bf16_bf16 as KernelRef,
7213 ),
7214 (
7215 &[DType::F16, DType::F16, DType::F16],
7216 matmul::matmul_f16_f16_f16 as KernelRef,
7217 ),
7218 (
7219 &[DType::F16, DType::F16, DType::F32],
7220 matmul::matmul_f16_f16_f32 as KernelRef,
7221 ),
7222 ];
7223
7224 let mut checked = 0usize;
7225 for (key, expected) in cases {
7226 let alts = table.lookup_alternatives(OpKind::MatMul, key, vk);
7227 let entry = alts
7228 .iter()
7229 .find(|e| e.kernel as usize == *expected as usize);
7230 let entry = match entry {
7231 Some(e) => e,
7232 None => panic!(
7233 "MatMul {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7234 matmul contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7235 alts.len(),
7236 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7237 ),
7238 };
7239 assert_eq!(
7240 entry.kernel_source, "vulkan-slang",
7241 "MatMul {key:?}: matmul family must be contract-sourced \
7242 (kernel_source=\"vulkan-slang\"); got {:?}",
7243 entry.kernel_source,
7244 );
7245 assert!(
7246 !entry.caps.strided_input,
7247 "MatMul {key:?}: caps preserved (contiguous-only, strided_input=false)",
7248 );
7249 checked += 1;
7250 }
7251 assert_eq!(
7252 checked, 6,
7253 "all 6 (MatMul, [lhs,rhs,out]) Vulkan combos checked"
7254 );
7255 }
7256}
7257
7258// ===========================================================================
7259// FKC contract-migration tests (born-red gate for the Vulkan conv2d family)
7260// ===========================================================================
7261//
7262// Same always-on gating (this crate IS the Vulkan crate) as the cast/elementwise/matmul
7263// tests above: this module always compiles (this crate has no feature gate) and touches
7264// NO device (registration is pure binding-table population).
7265
7266#[cfg(test)]
7267mod conv_contract_tests {
7268 use super::*;
7269 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7270
7271 /// FOURTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7272 /// registers the whole Vulkan conv2d family (3 per-(op, dtype) `(Conv2D,
7273 /// [x, weight, out])` bindings) FROM ITS RE-AUTHORED KERNEL CONTRACT
7274 /// (`fuel-dispatch/kernel-contracts/vulkan/conv.fkc.md`) via
7275 /// `register_vulkan_conv_from_contract` — the sole registration path, now that
7276 /// the hand-written `table.register_with_precision(OpKind::Conv2D, …)` regs
7277 /// (f32 / bf16 / f16) are DELETED.
7278 ///
7279 /// The corpus's `vulkan/conv-attn-rope.fkc.md` describes conv2d as an
7280 /// ASPIRATIONAL `fused_op: CONV2D` **im2col STAGE** (`conv2d_im2col_f32` /
7281 /// `conv2d_im2col_bf16`, output = the patches matrix), which is NOT what
7282 /// production registers: production registers a PRIMITIVE `OpKind::Conv2D`
7283 /// binding whose wrapper (`conv2d::conv2d_f32` → `VulkanBackend::conv2d_*_bytes`)
7284 /// runs the WHOLE conv (im2col + matmul internally). This mirrors the matmul
7285 /// migration (aspirational `matmul_mixed_precision` chassis superseded by
7286 /// EXPLICIT per-combo `op_kind` sections in the production `vulkan/matmul.fkc.md`).
7287 ///
7288 /// For each `(Conv2D, [x, weight, out], Vulkan)` key this asserts: the binding
7289 /// resolves to the EXACT production wrapper fn-pointer (behavior-preserving);
7290 /// `kernel_source == "vulkan-slang"` (the RED discriminator — the deleted hand
7291 /// path stamped `""`, so before the import is wired this assert fails on the
7292 /// empty source); and `caps.strided_input == false` — the contiguous-only truth
7293 /// of the deleted `register_with_precision` regs (conv2d_im2col reads NCHW with
7294 /// canonical strides, so a strided operand is auto-Contiguized first). No bias
7295 /// key is registered: the Vulkan wrappers bail on a 3-input (bias) call, so the
7296 /// contract declares NO optional bias operand and each section keys ONLY the
7297 /// 3-slot `[x, weight, out]` (unlike the CPU conv contract's optional-bias dual
7298 /// key). Precision is contract-sourced (the cast/elementwise/matmul precedent)
7299 /// and NOT asserted here.
7300 #[test]
7301 fn register_vulkan_kernels_binds_conv_family_from_contract() {
7302 let mut table = KernelBindingTable::new();
7303 register_vulkan_kernels(&mut table);
7304 let vk = BackendId::Vulkan;
7305
7306 // (key dtypes [x, weight, out], expected production wrapper). Every conv
7307 // binding is contiguous-only (strided_input == false), so that is checked
7308 // uniformly below rather than per-row.
7309 let cases: &[(&[DType], KernelRef)] = &[
7310 (
7311 &[DType::F32, DType::F32, DType::F32],
7312 conv2d::conv2d_f32 as KernelRef,
7313 ),
7314 (
7315 &[DType::BF16, DType::BF16, DType::BF16],
7316 conv2d::conv2d_bf16 as KernelRef,
7317 ),
7318 (
7319 &[DType::F16, DType::F16, DType::F16],
7320 conv2d::conv2d_f16 as KernelRef,
7321 ),
7322 ];
7323
7324 let mut checked = 0usize;
7325 for (key, expected) in cases {
7326 let alts = table.lookup_alternatives(OpKind::Conv2D, key, vk);
7327 let entry = alts
7328 .iter()
7329 .find(|e| e.kernel as usize == *expected as usize);
7330 let entry = match entry {
7331 Some(e) => e,
7332 None => panic!(
7333 "Conv2D {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7334 conv contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7335 alts.len(),
7336 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7337 ),
7338 };
7339 assert_eq!(
7340 entry.kernel_source, "vulkan-slang",
7341 "Conv2D {key:?}: conv family must be contract-sourced \
7342 (kernel_source=\"vulkan-slang\"); got {:?}",
7343 entry.kernel_source,
7344 );
7345 assert!(
7346 !entry.caps.strided_input,
7347 "Conv2D {key:?}: caps preserved (contiguous-only, strided_input=false)",
7348 );
7349 checked += 1;
7350 }
7351 assert_eq!(
7352 checked, 3,
7353 "all 3 (Conv2D, [x, weight, out]) Vulkan combos checked"
7354 );
7355 }
7356}
7357
7358// ===========================================================================
7359// FKC contract-migration tests (born-red gate for the Vulkan select family)
7360// ===========================================================================
7361//
7362// 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
7363// population).
7364
7365#[cfg(test)]
7366mod select_contract_tests {
7367 use super::*;
7368 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7369
7370 /// FIFTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7371 /// registers the whole Vulkan **select** family — IndexSelect (4 per-dtype
7372 /// wrappers), Gather (6 dtype keys → the ONE `gather::gather` synthetic-base
7373 /// umbrella wrapper), MaskedFill (6 dtype keys → the ONE
7374 /// `masked_fill::masked_fill` umbrella wrapper) — FROM ITS FKC KERNEL CONTRACT
7375 /// (`fuel-dispatch/kernel-contracts/vulkan/select.fkc.md`) via
7376 /// `register_vulkan_select_from_contract`, the sole registration path now that
7377 /// the hand-written `register_with_precision(OpKind::{IndexSelect,Gather,
7378 /// MaskedFill}, …)` regs are DELETED.
7379 ///
7380 /// Per key: the binding resolves to the EXACT production wrapper fn-pointer
7381 /// (behavior-preserving; several Gather/MaskedFill keys share ONE wrapper, the
7382 /// pad_cpu synthetic-umbrella precedent); `kernel_source == "vulkan-slang"`
7383 /// (the RED discriminator — the deleted hand path stamped `""`); and
7384 /// `caps.strided_input == false` — the contiguous-only truth of the deleted
7385 /// plain `register_with_precision` regs (byte-level data movers read/write
7386 /// their own-shape flat buffers; a strided operand is auto-Contiguized first).
7387 /// Precision is contract-sourced (byte-exact `audited: true`, the cast/matmul
7388 /// precedent) and NOT asserted here.
7389 #[test]
7390 fn register_vulkan_kernels_binds_select_family_from_contract() {
7391 let mut table = KernelBindingTable::new();
7392 register_vulkan_kernels(&mut table);
7393 let vk = BackendId::Vulkan;
7394
7395 let f32 = DType::F32;
7396 let f16 = DType::F16;
7397 let bf16 = DType::BF16;
7398 let f64 = DType::F64;
7399 let u8 = DType::U8;
7400 let u32 = DType::U32;
7401 let boolean = DType::Bool;
7402
7403 // (OpKind, key dtypes, expected production wrapper). Every select binding
7404 // is contiguous-only (strided_input == false), checked uniformly below.
7405 let cases: &[(OpKind, &[DType], KernelRef)] = &[
7406 // IndexSelect: [source, U32, out]; 4 distinct per-dtype wrappers.
7407 (
7408 OpKind::IndexSelect,
7409 &[f32, u32, f32],
7410 indexing::index_select_f32 as KernelRef,
7411 ),
7412 (
7413 OpKind::IndexSelect,
7414 &[f16, u32, f16],
7415 indexing::index_select_f16 as KernelRef,
7416 ),
7417 (
7418 OpKind::IndexSelect,
7419 &[bf16, u32, bf16],
7420 indexing::index_select_bf16 as KernelRef,
7421 ),
7422 (
7423 OpKind::IndexSelect,
7424 &[f64, u32, f64],
7425 indexing::index_select_f64 as KernelRef,
7426 ),
7427 // Gather: [source, U32, out]; ONE dtype-agnostic wrapper across 6 keys.
7428 (
7429 OpKind::Gather,
7430 &[f32, u32, f32],
7431 gather::gather as KernelRef,
7432 ),
7433 (
7434 OpKind::Gather,
7435 &[f16, u32, f16],
7436 gather::gather as KernelRef,
7437 ),
7438 (
7439 OpKind::Gather,
7440 &[bf16, u32, bf16],
7441 gather::gather as KernelRef,
7442 ),
7443 (
7444 OpKind::Gather,
7445 &[f64, u32, f64],
7446 gather::gather as KernelRef,
7447 ),
7448 (OpKind::Gather, &[u8, u32, u8], gather::gather as KernelRef),
7449 (
7450 OpKind::Gather,
7451 &[u32, u32, u32],
7452 gather::gather as KernelRef,
7453 ),
7454 // MaskedFill: [data, BOOL mask, out]; ONE wrapper across 6 keys.
7455 //
7456 // The mask slot is `Bool`, NOT `U8`. GAP-168(c) moved it;
7457 // `Graph::masked_fill` enforces it at BUILD time
7458 // (fuel-graph/src/lib.rs:5716 — "`mask` must be `Bool`
7459 // (GAP-168(c))"), and all five backend contracts declare
7460 // `dtypes: [BOOL]`. This test still asserted the pre-Bool
7461 // `[T, U8, T]` key, so it looked up a binding that no longer exists
7462 // and reported `found 0 alt(s) with sources []` — which reads like a
7463 // MISSING REGISTRATION rather than a stale key, and cost a full
7464 // diagnostic pass to tell apart. The registration is fine: the
7465 // IndexSelect and Gather cases above import from the same contract
7466 // file and pass.
7467 //
7468 // It survived the Bool cut because it needs `--features vulkan`:
7469 // that sweep was gated with `--lib`, and CI could not build the
7470 // workspace at all, so nothing executed this until today.
7471 (
7472 OpKind::MaskedFill,
7473 &[f32, boolean, f32],
7474 masked_fill::masked_fill as KernelRef,
7475 ),
7476 (
7477 OpKind::MaskedFill,
7478 &[f16, boolean, f16],
7479 masked_fill::masked_fill as KernelRef,
7480 ),
7481 (
7482 OpKind::MaskedFill,
7483 &[bf16, boolean, bf16],
7484 masked_fill::masked_fill as KernelRef,
7485 ),
7486 (
7487 OpKind::MaskedFill,
7488 &[f64, boolean, f64],
7489 masked_fill::masked_fill as KernelRef,
7490 ),
7491 (
7492 OpKind::MaskedFill,
7493 &[u8, boolean, u8],
7494 masked_fill::masked_fill as KernelRef,
7495 ),
7496 (
7497 OpKind::MaskedFill,
7498 &[u32, boolean, u32],
7499 masked_fill::masked_fill as KernelRef,
7500 ),
7501 ];
7502
7503 let mut checked = 0usize;
7504 for (op, key, expected) in cases {
7505 let alts = table.lookup_alternatives(*op, key, vk);
7506 let entry = alts
7507 .iter()
7508 .find(|e| e.kernel as usize == *expected as usize);
7509 let entry = match entry {
7510 Some(e) => e,
7511 None => panic!(
7512 "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7513 select contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7514 alts.len(),
7515 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7516 ),
7517 };
7518 assert_eq!(
7519 entry.kernel_source, "vulkan-slang",
7520 "{op:?} {key:?}: select family must be contract-sourced \
7521 (kernel_source=\"vulkan-slang\"); got {:?}",
7522 entry.kernel_source,
7523 );
7524 assert!(
7525 !entry.caps.strided_input,
7526 "{op:?} {key:?}: caps preserved (contiguous-only, strided_input=false)",
7527 );
7528 checked += 1;
7529 }
7530 assert_eq!(
7531 checked, 16,
7532 "all 16 (IndexSelect/Gather/MaskedFill) select keys checked"
7533 );
7534 }
7535}
7536
7537// ===========================================================================
7538// FKC contract-migration tests (born-red gate for the Vulkan scatter family)
7539// ===========================================================================
7540
7541#[cfg(test)]
7542mod scatter_contract_tests {
7543 use super::*;
7544 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7545
7546 /// SIXTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7547 /// registers the whole Vulkan **scatter** family — IndexAdd (4 per-dtype) +
7548 /// ScatterAdd (4 per-dtype), 4-slot key `[base, U32, src, out]` — FROM ITS FKC
7549 /// KERNEL CONTRACT (`fuel-dispatch/kernel-contracts/vulkan/scatter.fkc.md`) via
7550 /// `register_vulkan_scatter_from_contract`, the sole path now that the
7551 /// hand-written `register_with_precision(OpKind::{IndexAdd,ScatterAdd}, …)` regs
7552 /// are DELETED. Each section fans `base` + `src` over the SAME `[F32,F64,BF16,F16]`
7553 /// list (§3.4; both operands share the list ⇒ one fan, not a mismatch), keying
7554 /// `[T, U32, T, T]`.
7555 ///
7556 /// Per key: EXACT production wrapper fn-pointer; `kernel_source == "vulkan-slang"`
7557 /// (RED discriminator); `caps.strided_input == false` (contiguous-only atomic
7558 /// scatter). Precision is contract-sourced (nondeterministic bounded-CAS,
7559 /// audited none(reason) — the matmul/conv precedent) and NOT asserted here.
7560 #[test]
7561 fn register_vulkan_kernels_binds_scatter_family_from_contract() {
7562 let mut table = KernelBindingTable::new();
7563 register_vulkan_kernels(&mut table);
7564 let vk = BackendId::Vulkan;
7565
7566 let f32 = DType::F32;
7567 let f16 = DType::F16;
7568 let bf16 = DType::BF16;
7569 let f64 = DType::F64;
7570 let u32 = DType::U32;
7571
7572 let cases: &[(OpKind, &[DType], KernelRef)] = &[
7573 (
7574 OpKind::IndexAdd,
7575 &[f32, u32, f32, f32],
7576 index_add::index_add_f32 as KernelRef,
7577 ),
7578 (
7579 OpKind::IndexAdd,
7580 &[f64, u32, f64, f64],
7581 index_add::index_add_f64 as KernelRef,
7582 ),
7583 (
7584 OpKind::IndexAdd,
7585 &[bf16, u32, bf16, bf16],
7586 index_add::index_add_bf16 as KernelRef,
7587 ),
7588 (
7589 OpKind::IndexAdd,
7590 &[f16, u32, f16, f16],
7591 index_add::index_add_f16 as KernelRef,
7592 ),
7593 (
7594 OpKind::ScatterAdd,
7595 &[f32, u32, f32, f32],
7596 scatter_add::scatter_add_f32 as KernelRef,
7597 ),
7598 (
7599 OpKind::ScatterAdd,
7600 &[f64, u32, f64, f64],
7601 scatter_add::scatter_add_f64 as KernelRef,
7602 ),
7603 (
7604 OpKind::ScatterAdd,
7605 &[bf16, u32, bf16, bf16],
7606 scatter_add::scatter_add_bf16 as KernelRef,
7607 ),
7608 (
7609 OpKind::ScatterAdd,
7610 &[f16, u32, f16, f16],
7611 scatter_add::scatter_add_f16 as KernelRef,
7612 ),
7613 ];
7614
7615 let mut checked = 0usize;
7616 for (op, key, expected) in cases {
7617 let alts = table.lookup_alternatives(*op, key, vk);
7618 let entry = alts
7619 .iter()
7620 .find(|e| e.kernel as usize == *expected as usize);
7621 let entry = match entry {
7622 Some(e) => e,
7623 None => panic!(
7624 "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7625 scatter contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7626 alts.len(),
7627 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7628 ),
7629 };
7630 assert_eq!(
7631 entry.kernel_source, "vulkan-slang",
7632 "{op:?} {key:?}: scatter family must be contract-sourced \
7633 (kernel_source=\"vulkan-slang\"); got {:?}",
7634 entry.kernel_source,
7635 );
7636 assert!(
7637 !entry.caps.strided_input,
7638 "{op:?} {key:?}: caps preserved (contiguous-only, strided_input=false)",
7639 );
7640 checked += 1;
7641 }
7642 assert_eq!(
7643 checked, 8,
7644 "all 8 (IndexAdd/ScatterAdd) scatter keys checked"
7645 );
7646 }
7647}
7648
7649// ===========================================================================
7650// FKC contract-migration tests (born-red gate for the Vulkan movement family)
7651// ===========================================================================
7652
7653#[cfg(test)]
7654mod movement_contract_tests {
7655 use super::*;
7656 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7657
7658 /// SEVENTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7659 /// registers the whole Vulkan **movement** family — Concat (4 per-dtype) +
7660 /// CumSum (4 per-dtype), key `[T, T]` — FROM ITS FKC KERNEL CONTRACT
7661 /// (`fuel-dispatch/kernel-contracts/vulkan/movement.fkc.md`) via
7662 /// `register_vulkan_movement_from_contract`, the sole path now that the
7663 /// hand-written `register_with_caps_and_precision(OpKind::{Concat,CumSum}, …,
7664 /// strided, …)` regs are DELETED.
7665 ///
7666 /// Both are STRIDE-AWARE (the deleted regs carried `strided`), so
7667 /// `caps.strided_input == true` is the caps-through-import proof here (the
7668 /// contract's `strided: accepted` layout projects it). `kernel_source ==
7669 /// "vulkan-slang"` is the RED discriminator. Precision is contract-sourced and
7670 /// NOT asserted here.
7671 #[test]
7672 fn register_vulkan_kernels_binds_movement_family_from_contract() {
7673 let mut table = KernelBindingTable::new();
7674 register_vulkan_kernels(&mut table);
7675 let vk = BackendId::Vulkan;
7676
7677 let f32 = DType::F32;
7678 let f16 = DType::F16;
7679 let bf16 = DType::BF16;
7680 let f64 = DType::F64;
7681
7682 // Every movement binding is stride-aware (strided_input == true).
7683 let cases: &[(OpKind, &[DType], KernelRef)] = &[
7684 (OpKind::Concat, &[f32, f32], concat::concat_f32 as KernelRef),
7685 (OpKind::Concat, &[f16, f16], concat::concat_f16 as KernelRef),
7686 (
7687 OpKind::Concat,
7688 &[bf16, bf16],
7689 concat::concat_bf16 as KernelRef,
7690 ),
7691 (OpKind::Concat, &[f64, f64], concat::concat_f64 as KernelRef),
7692 (OpKind::CumSum, &[f32, f32], cumsum::cumsum_f32 as KernelRef),
7693 (OpKind::CumSum, &[f64, f64], cumsum::cumsum_f64 as KernelRef),
7694 (OpKind::CumSum, &[f16, f16], cumsum::cumsum_f16 as KernelRef),
7695 (
7696 OpKind::CumSum,
7697 &[bf16, bf16],
7698 cumsum::cumsum_bf16 as KernelRef,
7699 ),
7700 ];
7701
7702 let mut checked = 0usize;
7703 for (op, key, expected) in cases {
7704 let alts = table.lookup_alternatives(*op, key, vk);
7705 let entry = alts
7706 .iter()
7707 .find(|e| e.kernel as usize == *expected as usize);
7708 let entry = match entry {
7709 Some(e) => e,
7710 None => panic!(
7711 "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7712 movement contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7713 alts.len(),
7714 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7715 ),
7716 };
7717 assert_eq!(
7718 entry.kernel_source, "vulkan-slang",
7719 "{op:?} {key:?}: movement family must be contract-sourced \
7720 (kernel_source=\"vulkan-slang\"); got {:?}",
7721 entry.kernel_source,
7722 );
7723 assert!(
7724 entry.caps.strided_input,
7725 "{op:?} {key:?}: caps must ride through the import truthfully (strided_input=true)",
7726 );
7727 checked += 1;
7728 }
7729 assert_eq!(checked, 8, "all 8 (Concat/CumSum) movement keys checked");
7730 }
7731}
7732
7733// ===========================================================================
7734// FKC contract-migration tests (born-red gate for the Vulkan shape family)
7735// ===========================================================================
7736
7737#[cfg(test)]
7738mod shape_contract_tests {
7739 use super::*;
7740 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7741
7742 /// EIGHTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7743 /// registers the whole Vulkan **shape** family — Triu (7 dtypes) + Tril (7) +
7744 /// Flip (7) + Roll (7), key `[T, T]` — FROM ITS FKC KERNEL CONTRACT
7745 /// (`fuel-dispatch/kernel-contracts/vulkan/shape.fkc.md`) via
7746 /// `register_vulkan_shape_from_contract`, the sole path now that the
7747 /// hand-written `register_with_precision(OpKind::{Triu,Tril}, …)` +
7748 /// `register_with_caps_and_precision(OpKind::{Flip,Roll}, …, strided, …)` regs
7749 /// are DELETED.
7750 ///
7751 /// Each op is ONE dtype-agnostic wrapper across its 7 dtype keys (a
7752 /// synthetic-base umbrella; the fan resolves `<base>_<suffix>` to the one
7753 /// wrapper). `kernel_source == "vulkan-slang"` (RED discriminator).
7754 /// `caps.strided_input` MATCHES per op: Triu/Tril contiguous (false),
7755 /// Flip/Roll stride-aware (true) — the caps-through-import proof. Precision is
7756 /// contract-sourced and NOT asserted here.
7757 #[test]
7758 fn register_vulkan_kernels_binds_shape_family_from_contract() {
7759 let mut table = KernelBindingTable::new();
7760 register_vulkan_kernels(&mut table);
7761 let vk = BackendId::Vulkan;
7762
7763 let dts = [
7764 DType::F32,
7765 DType::F16,
7766 DType::BF16,
7767 DType::F64,
7768 DType::I32,
7769 DType::U32,
7770 DType::I64,
7771 ];
7772 // (OpKind, wrapper, expected strided_input)
7773 let ops: &[(OpKind, KernelRef, bool)] = &[
7774 (OpKind::Triu, triangular::triu as KernelRef, false),
7775 (OpKind::Tril, triangular::tril as KernelRef, false),
7776 (OpKind::Flip, flip::flip as KernelRef, true),
7777 (OpKind::Roll, roll::roll as KernelRef, true),
7778 ];
7779
7780 let mut checked = 0usize;
7781 for &dt in &dts {
7782 for (op, expected, expect_strided) in ops {
7783 let key = [dt, dt];
7784 let alts = table.lookup_alternatives(*op, &key, vk);
7785 let entry = alts
7786 .iter()
7787 .find(|e| e.kernel as usize == *expected as usize);
7788 let entry = match entry {
7789 Some(e) => e,
7790 None => panic!(
7791 "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7792 shape contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7793 alts.len(),
7794 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7795 ),
7796 };
7797 assert_eq!(
7798 entry.kernel_source, "vulkan-slang",
7799 "{op:?} {key:?}: shape family must be contract-sourced \
7800 (kernel_source=\"vulkan-slang\"); got {:?}",
7801 entry.kernel_source,
7802 );
7803 assert_eq!(
7804 entry.caps.strided_input, *expect_strided,
7805 "{op:?} {key:?}: caps must ride through the import truthfully (strided_input)",
7806 );
7807 checked += 1;
7808 }
7809 }
7810 assert_eq!(
7811 checked, 28,
7812 "all 28 (Triu/Tril/Flip/Roll × 7 dtypes) shape keys checked"
7813 );
7814 }
7815}
7816
7817// ===========================================================================
7818// FKC contract-migration tests (born-red gate for the Vulkan pad-copy family)
7819// ===========================================================================
7820
7821#[cfg(test)]
7822mod pad_copy_contract_tests {
7823 use super::*;
7824 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7825
7826 /// NINTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7827 /// registers the whole Vulkan **pad-copy** family — Pad (6 dtypes) +
7828 /// PadBackward (6) + Copy (9) — FROM ITS FKC KERNEL CONTRACT
7829 /// (`fuel-dispatch/kernel-contracts/vulkan/pad-copy.fkc.md`) via
7830 /// `register_vulkan_pad_copy_from_contract`, the sole path now that the
7831 /// hand-written `register_with_precision(OpKind::{Pad,PadBackward,Copy}, …)`
7832 /// regs are DELETED. Each op is ONE dtype-agnostic wrapper across its dtype keys
7833 /// (a synthetic-base umbrella). `kernel_source == "vulkan-slang"` (RED
7834 /// discriminator); `caps.strided_input == false` (contiguous-only byte movers).
7835 /// Precision is contract-sourced (byte-exact) and NOT asserted here.
7836 #[test]
7837 fn register_vulkan_kernels_binds_pad_copy_family_from_contract() {
7838 let mut table = KernelBindingTable::new();
7839 register_vulkan_kernels(&mut table);
7840 let vk = BackendId::Vulkan;
7841
7842 let pad_dts = [
7843 DType::F32,
7844 DType::F16,
7845 DType::BF16,
7846 DType::F64,
7847 DType::U8,
7848 DType::U32,
7849 ];
7850 let copy_dts = [
7851 DType::F32,
7852 DType::F16,
7853 DType::BF16,
7854 DType::F64,
7855 DType::U32,
7856 DType::U8,
7857 DType::I16,
7858 DType::I32,
7859 DType::I64,
7860 ];
7861
7862 let mut checked = 0usize;
7863 let mut check = |op: OpKind, key: &[DType], expected: KernelRef| {
7864 let alts = table.lookup_alternatives(op, key, vk);
7865 let entry = alts.iter().find(|e| e.kernel as usize == expected as usize);
7866 let entry = match entry {
7867 Some(e) => e,
7868 None => panic!(
7869 "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7870 pad-copy contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7871 alts.len(),
7872 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7873 ),
7874 };
7875 assert_eq!(
7876 entry.kernel_source, "vulkan-slang",
7877 "{op:?} {key:?}: pad-copy family must be contract-sourced \
7878 (kernel_source=\"vulkan-slang\"); got {:?}",
7879 entry.kernel_source,
7880 );
7881 assert!(
7882 !entry.caps.strided_input,
7883 "{op:?} {key:?}: caps preserved (contiguous-only, strided_input=false)",
7884 );
7885 checked += 1;
7886 };
7887
7888 for &dt in &pad_dts {
7889 check(OpKind::Pad, &[dt, dt], pad::pad_const as KernelRef);
7890 check(
7891 OpKind::PadBackward,
7892 &[dt, dt],
7893 pad::pad_backward as KernelRef,
7894 );
7895 }
7896 for &dt in ©_dts {
7897 check(OpKind::Copy, &[dt, dt], copy_to_cpu_vulkan as KernelRef);
7898 }
7899 assert_eq!(
7900 checked, 21,
7901 "all 21 (Pad/PadBackward/Copy) pad-copy keys checked"
7902 );
7903 }
7904}
7905
7906// ===========================================================================
7907// FKC contract-migration tests (born-red gate for the Vulkan write-slice family)
7908// ===========================================================================
7909
7910#[cfg(test)]
7911mod write_slice_contract_tests {
7912 use super::*;
7913 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
7914
7915 /// TENTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
7916 /// registers the whole Vulkan **write-slice** family — WriteSlice (9 dtypes) +
7917 /// WriteSliceRotating (9), key `[T, T]` — FROM ITS FKC KERNEL CONTRACT
7918 /// (`fuel-dispatch/kernel-contracts/vulkan/write-slice.fkc.md`) via
7919 /// `register_vulkan_write_slice_from_contract`, the sole path now that the
7920 /// hand-written `register_with_precision(OpKind::{WriteSlice,WriteSliceRotating},
7921 /// …)` regs are DELETED. Each op is BYTE-WIDTH-keyed: 9 dtype keys resolve to 4
7922 /// byte-width wrappers (b1/b2/b4/b8) — the cast family's "several sections share
7923 /// one wrapper" precedent. `kernel_source == "vulkan-slang"` (RED discriminator);
7924 /// `caps.strided_input == false` (contiguous slab writes). Precision is
7925 /// contract-sourced (byte-exact) and NOT asserted here.
7926 #[test]
7927 fn register_vulkan_kernels_binds_write_slice_family_from_contract() {
7928 let mut table = KernelBindingTable::new();
7929 register_vulkan_kernels(&mut table);
7930 let vk = BackendId::Vulkan;
7931
7932 // (dtype, WriteSlice wrapper, WriteSliceRotating wrapper) by byte width.
7933 let cases: &[(DType, KernelRef, KernelRef)] = &[
7934 (
7935 DType::F32,
7936 write_slice::write_slice_b4 as KernelRef,
7937 write_slice_rotating::write_slice_rotating_b4 as KernelRef,
7938 ),
7939 (
7940 DType::I32,
7941 write_slice::write_slice_b4 as KernelRef,
7942 write_slice_rotating::write_slice_rotating_b4 as KernelRef,
7943 ),
7944 (
7945 DType::U32,
7946 write_slice::write_slice_b4 as KernelRef,
7947 write_slice_rotating::write_slice_rotating_b4 as KernelRef,
7948 ),
7949 (
7950 DType::F16,
7951 write_slice::write_slice_b2 as KernelRef,
7952 write_slice_rotating::write_slice_rotating_b2 as KernelRef,
7953 ),
7954 (
7955 DType::BF16,
7956 write_slice::write_slice_b2 as KernelRef,
7957 write_slice_rotating::write_slice_rotating_b2 as KernelRef,
7958 ),
7959 (
7960 DType::F64,
7961 write_slice::write_slice_b8 as KernelRef,
7962 write_slice_rotating::write_slice_rotating_b8 as KernelRef,
7963 ),
7964 (
7965 DType::I64,
7966 write_slice::write_slice_b8 as KernelRef,
7967 write_slice_rotating::write_slice_rotating_b8 as KernelRef,
7968 ),
7969 (
7970 DType::U8,
7971 write_slice::write_slice_b1 as KernelRef,
7972 write_slice_rotating::write_slice_rotating_b1 as KernelRef,
7973 ),
7974 (
7975 DType::I8,
7976 write_slice::write_slice_b1 as KernelRef,
7977 write_slice_rotating::write_slice_rotating_b1 as KernelRef,
7978 ),
7979 ];
7980
7981 let mut checked = 0usize;
7982 let mut check = |op: OpKind, key: &[DType], expected: KernelRef| {
7983 let alts = table.lookup_alternatives(op, key, vk);
7984 let entry = alts.iter().find(|e| e.kernel as usize == expected as usize);
7985 let entry = match entry {
7986 Some(e) => e,
7987 None => panic!(
7988 "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
7989 write-slice contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
7990 alts.len(),
7991 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
7992 ),
7993 };
7994 assert_eq!(
7995 entry.kernel_source, "vulkan-slang",
7996 "{op:?} {key:?}: write-slice family must be contract-sourced \
7997 (kernel_source=\"vulkan-slang\"); got {:?}",
7998 entry.kernel_source,
7999 );
8000 assert!(
8001 !entry.caps.strided_input,
8002 "{op:?} {key:?}: caps preserved (contiguous-only, strided_input=false)",
8003 );
8004 checked += 1;
8005 };
8006
8007 for (dt, ws, wsr) in cases {
8008 check(OpKind::WriteSlice, &[*dt, *dt], *ws);
8009 check(OpKind::WriteSliceRotating, &[*dt, *dt], *wsr);
8010 }
8011 assert_eq!(
8012 checked, 18,
8013 "all 18 (WriteSlice/WriteSliceRotating × 9 dtypes) write-slice keys checked"
8014 );
8015 }
8016}
8017
8018// ===========================================================================
8019// FKC contract-migration tests (born-red gate for the Vulkan rope family)
8020// ===========================================================================
8021
8022#[cfg(test)]
8023mod rope_contract_tests {
8024 use super::*;
8025 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
8026
8027 /// ELEVENTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
8028 /// registers the whole Vulkan **rope** family — RoPE (4 per-dtype), 4-slot key
8029 /// `[x, cos, sin, out]` — FROM ITS FKC KERNEL CONTRACT
8030 /// (`fuel-dispatch/kernel-contracts/vulkan/rope.fkc.md`) via
8031 /// `register_vulkan_rope_from_contract`, the sole path now that the hand-written
8032 /// `register_with_caps_and_precision(OpKind::Rope, …, strided, …)` regs are
8033 /// DELETED. One section fans `x` + `cos` + `sin` over the SAME `[F32,F16,F64,BF16]`
8034 /// list (§3.4), keying `[T, T, T, T]`.
8035 ///
8036 /// RoPE is STRIDE-AWARE (the deleted regs carried `strided`), so
8037 /// `caps.strided_input == true` is the caps-through-import proof here.
8038 /// `kernel_source == "vulkan-slang"` is the RED discriminator. Precision is
8039 /// contract-sourced and NOT asserted here.
8040 #[test]
8041 fn register_vulkan_kernels_binds_rope_family_from_contract() {
8042 let mut table = KernelBindingTable::new();
8043 register_vulkan_kernels(&mut table);
8044 let vk = BackendId::Vulkan;
8045
8046 let f32 = DType::F32;
8047 let f16 = DType::F16;
8048 let bf16 = DType::BF16;
8049 let f64 = DType::F64;
8050 let cases: &[(&[DType], KernelRef)] = &[
8051 (&[f32, f32, f32, f32], attention::rope_f32 as KernelRef),
8052 (&[f16, f16, f16, f16], attention::rope_f16 as KernelRef),
8053 (&[f64, f64, f64, f64], attention::rope_f64 as KernelRef),
8054 (&[bf16, bf16, bf16, bf16], attention::rope_bf16 as KernelRef),
8055 ];
8056
8057 let mut checked = 0usize;
8058 for (key, expected) in cases {
8059 let alts = table.lookup_alternatives(OpKind::Rope, key, vk);
8060 let entry = alts
8061 .iter()
8062 .find(|e| e.kernel as usize == *expected as usize);
8063 let entry = match entry {
8064 Some(e) => e,
8065 None => panic!(
8066 "Rope {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
8067 rope contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
8068 alts.len(),
8069 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
8070 ),
8071 };
8072 assert_eq!(
8073 entry.kernel_source, "vulkan-slang",
8074 "Rope {key:?}: rope family must be contract-sourced \
8075 (kernel_source=\"vulkan-slang\"); got {:?}",
8076 entry.kernel_source,
8077 );
8078 assert!(
8079 entry.caps.strided_input,
8080 "Rope {key:?}: caps must ride through the import truthfully (strided_input=true)",
8081 );
8082 checked += 1;
8083 }
8084 assert_eq!(checked, 4, "all 4 (RoPE × dtype) rope keys checked");
8085 }
8086}
8087
8088// ===========================================================================
8089// FKC contract-migration tests (born-red gate for the Vulkan reduce family)
8090// ===========================================================================
8091
8092#[cfg(test)]
8093mod reduce_contract_tests {
8094 use super::*;
8095 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
8096
8097 /// TWELFTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
8098 /// registers the whole Vulkan **reduce** family — SumReduce / MaxReduce /
8099 /// MinReduce / MeanReduce (4 per-dtype each = 16, key `[T, T]`) + ArgMaxDim /
8100 /// ArgMinDim (4 per-dtype each = 8, key `[T, U32]`) — FROM ITS FKC KERNEL
8101 /// CONTRACT (`fuel-dispatch/kernel-contracts/vulkan/reduce.fkc.md`) via
8102 /// `register_vulkan_reduce_from_contract`, the sole path now that the
8103 /// hand-written `register_with_precision(OpKind::{SumReduce,…,ArgMinDim}, …)`
8104 /// regs are DELETED. Each OpKind is its own section fanned over the dtype list to
8105 /// its distinct per-dtype wrapper. `kernel_source == "vulkan-slang"` (RED
8106 /// discriminator); `caps.strided_input == false` (contiguous subgroup-tree
8107 /// reductions). Precision is contract-sourced and NOT asserted here.
8108 #[test]
8109 fn register_vulkan_kernels_binds_reduce_family_from_contract() {
8110 let mut table = KernelBindingTable::new();
8111 register_vulkan_kernels(&mut table);
8112 let vk = BackendId::Vulkan;
8113 let u32 = DType::U32;
8114
8115 let mut checked = 0usize;
8116 let mut check = |op: OpKind, key: &[DType], expected: KernelRef| {
8117 let alts = table.lookup_alternatives(op, key, vk);
8118 let entry = alts.iter().find(|e| e.kernel as usize == expected as usize);
8119 let entry = match entry {
8120 Some(e) => e,
8121 None => panic!(
8122 "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
8123 reduce contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
8124 alts.len(),
8125 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
8126 ),
8127 };
8128 assert_eq!(
8129 entry.kernel_source, "vulkan-slang",
8130 "{op:?} {key:?}: reduce family must be contract-sourced \
8131 (kernel_source=\"vulkan-slang\"); got {:?}",
8132 entry.kernel_source,
8133 );
8134 assert!(
8135 !entry.caps.strided_input,
8136 "{op:?} {key:?}: contiguous-only (strided_input=false)"
8137 );
8138 checked += 1;
8139 };
8140
8141 // Value reduces: 4 ops × 4 dtypes, key [T, T].
8142 let val: &[(OpKind, [KernelRef; 4])] = &[
8143 (
8144 OpKind::SumReduce,
8145 [
8146 reduce::sum_f32,
8147 reduce::sum_f16,
8148 reduce::sum_bf16,
8149 reduce::sum_f64,
8150 ],
8151 ),
8152 (
8153 OpKind::MaxReduce,
8154 [
8155 reduce::max_f32,
8156 reduce::max_f16,
8157 reduce::max_bf16,
8158 reduce::max_f64,
8159 ],
8160 ),
8161 (
8162 OpKind::MinReduce,
8163 [
8164 reduce::min_f32,
8165 reduce::min_f16,
8166 reduce::min_bf16,
8167 reduce::min_f64,
8168 ],
8169 ),
8170 (
8171 OpKind::MeanReduce,
8172 [
8173 reduce::mean_f32,
8174 reduce::mean_f16,
8175 reduce::mean_bf16,
8176 reduce::mean_f64,
8177 ],
8178 ),
8179 ];
8180 let dts = [DType::F32, DType::F16, DType::BF16, DType::F64];
8181 for (op, wraps) in val {
8182 for (i, &dt) in dts.iter().enumerate() {
8183 check(*op, &[dt, dt], wraps[i]);
8184 }
8185 }
8186 // Arg reduces: 2 ops × 4 dtypes, key [T, U32].
8187 let arg: &[(OpKind, [KernelRef; 4])] = &[
8188 (
8189 OpKind::ArgMaxDim,
8190 [
8191 arg_reduce::argmax_f32,
8192 arg_reduce::argmax_f16,
8193 arg_reduce::argmax_bf16,
8194 arg_reduce::argmax_f64,
8195 ],
8196 ),
8197 (
8198 OpKind::ArgMinDim,
8199 [
8200 arg_reduce::argmin_f32,
8201 arg_reduce::argmin_f16,
8202 arg_reduce::argmin_bf16,
8203 arg_reduce::argmin_f64,
8204 ],
8205 ),
8206 ];
8207 for (op, wraps) in arg {
8208 for (i, &dt) in dts.iter().enumerate() {
8209 check(*op, &[dt, u32], wraps[i]);
8210 }
8211 }
8212 assert_eq!(
8213 checked, 24,
8214 "all 24 (Sum/Max/Min/Mean + ArgMax/ArgMin × 4 dtypes) reduce keys checked"
8215 );
8216 }
8217}
8218
8219// ===========================================================================
8220// FKC contract-migration tests (born-red gate for the Vulkan norm family)
8221// ===========================================================================
8222
8223#[cfg(test)]
8224mod norm_contract_tests {
8225 use super::*;
8226 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
8227
8228 /// THIRTEENTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
8229 /// registers the whole Vulkan **norm** family — SoftmaxLastDim (4, key `[T, T]`),
8230 /// SoftmaxLastDimBackward (4, key `[y, g, dx]`), LayerNormLastDim (4, `[T, T]`),
8231 /// LayerNormLastDimBackward (4, `[x, g, dx]`), RmsNormLastDim (4, `[T, T]`) —
8232 /// FROM ITS FKC KERNEL CONTRACT (`fuel-dispatch/kernel-contracts/vulkan/norm.fkc.md`) via
8233 /// `register_vulkan_norm_from_contract`, the sole path now that the hand-written
8234 /// `register_with_precision(OpKind::{SoftmaxLastDim,…,RmsNormLastDim}, …)` regs
8235 /// are DELETED. Each OpKind is its own section fanned over `[F32, F16, BF16, F64]`
8236 /// to its distinct per-dtype wrapper. `kernel_source == "vulkan-slang"` (RED
8237 /// discriminator); `caps.strided_input == false` (contiguous per-row
8238 /// reductions). Precision is contract-sourced and NOT asserted here.
8239 #[test]
8240 fn register_vulkan_kernels_binds_norm_family_from_contract() {
8241 let mut table = KernelBindingTable::new();
8242 register_vulkan_kernels(&mut table);
8243 let vk = BackendId::Vulkan;
8244
8245 let mut checked = 0usize;
8246 let mut check = |op: OpKind, key: &[DType], expected: KernelRef| {
8247 let alts = table.lookup_alternatives(op, key, vk);
8248 let entry = alts.iter().find(|e| e.kernel as usize == expected as usize);
8249 let entry = match entry {
8250 Some(e) => e,
8251 None => panic!(
8252 "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
8253 norm contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
8254 alts.len(),
8255 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
8256 ),
8257 };
8258 assert_eq!(
8259 entry.kernel_source, "vulkan-slang",
8260 "{op:?} {key:?}: norm family must be contract-sourced \
8261 (kernel_source=\"vulkan-slang\"); got {:?}",
8262 entry.kernel_source,
8263 );
8264 assert!(
8265 !entry.caps.strided_input,
8266 "{op:?} {key:?}: contiguous-only (strided_input=false)"
8267 );
8268 checked += 1;
8269 };
8270
8271 let dts = [DType::F32, DType::F16, DType::BF16, DType::F64];
8272 // Unary [T, T] families.
8273 let un: &[(OpKind, [KernelRef; 4])] = &[
8274 (
8275 OpKind::SoftmaxLastDim,
8276 [
8277 softmax::softmax_f32,
8278 softmax::softmax_f16,
8279 softmax::softmax_bf16,
8280 softmax::softmax_f64,
8281 ],
8282 ),
8283 (
8284 OpKind::LayerNormLastDim,
8285 [
8286 norm::layer_norm_f32,
8287 norm::layer_norm_f16,
8288 norm::layer_norm_bf16,
8289 norm::layer_norm_f64,
8290 ],
8291 ),
8292 (
8293 OpKind::RmsNormLastDim,
8294 [norm::rms_f32, norm::rms_f16, norm::rms_bf16, norm::rms_f64],
8295 ),
8296 ];
8297 for (op, wraps) in un {
8298 for (i, &dt) in dts.iter().enumerate() {
8299 check(*op, &[dt, dt], wraps[i]);
8300 }
8301 }
8302 // Backward [T, T, T] families.
8303 let bwd: &[(OpKind, [KernelRef; 4])] = &[
8304 (
8305 OpKind::SoftmaxLastDimBackward,
8306 [
8307 softmax::softmax_last_dim_backward_f32,
8308 softmax::softmax_last_dim_backward_f16,
8309 softmax::softmax_last_dim_backward_bf16,
8310 softmax::softmax_last_dim_backward_f64,
8311 ],
8312 ),
8313 (
8314 OpKind::LayerNormLastDimBackward,
8315 [
8316 norm::layer_norm_backward_f32,
8317 norm::layer_norm_backward_f16,
8318 norm::layer_norm_backward_bf16,
8319 norm::layer_norm_backward_f64,
8320 ],
8321 ),
8322 ];
8323 for (op, wraps) in bwd {
8324 for (i, &dt) in dts.iter().enumerate() {
8325 check(*op, &[dt, dt, dt], wraps[i]);
8326 }
8327 }
8328 assert_eq!(
8329 checked, 20,
8330 "all 20 (Softmax/SoftmaxBwd/LayerNorm/LayerNormBwd/RmsNorm × 4 dtypes) norm keys checked"
8331 );
8332 }
8333}
8334
8335// ===========================================================================
8336// FKC contract-migration tests (born-red gate for the Vulkan QMatMul family)
8337// ===========================================================================
8338//
8339// Same always-on gating (this crate IS the Vulkan crate) as the cast/…/norm tests above:
8340// this module always compiles (this crate has no feature gate) and touches NO device
8341// (registration is pure binding-table population).
8342
8343#[cfg(test)]
8344mod qmatmul_contract_tests {
8345 use super::*;
8346 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
8347
8348 /// FOURTEENTH VULKAN-BACKEND FKC CONSUMER (born-red gate). `register_vulkan_kernels`
8349 /// registers the single Vulkan **QMatMul** binding (`(QMatMul, [F32, U32, F32],
8350 /// Vulkan)` — F32 activation × U32-typed GGML block-quant weight → F32 output, the
8351 /// one wrapper `qmatmul::qmatmul_vk` route-picking Q4_0 / Q4_K_M / Q8_0 internally
8352 /// by `OpParams::QMatMul.quant_type`) FROM ITS RE-AUTHORED FKC KERNEL CONTRACT
8353 /// (`fuel-dispatch/kernel-contracts/vulkan/qmatmul.fkc.md`) via
8354 /// `register_vulkan_qmatmul_from_contract` — the sole registration path now that
8355 /// the hand-written `table.register_with_precision(OpKind::QMatMul, …)` reg is
8356 /// DELETED.
8357 ///
8358 /// The corpus's `vulkan/quantized.fkc.md` models QMATMUL as TWO aspirational
8359 /// `fused_op: QMATMUL` Q4_0 sections (`qmatvec_q4_0` gemv + `matmul_q4_0_tiled`),
8360 /// which mismatch production on BOTH axes: production registers the PRIMITIVE
8361 /// `OpKind::QMatMul` (not the fused op) keyed with the LOGICAL U32 weight dtype
8362 /// (not the physical U8 block stream). So the migration authors ONE faithful
8363 /// single-dtype-per-operand `op_kind: QMatMul` section in the new production
8364 /// `fuel-dispatch/kernel-contracts/vulkan/qmatmul.fkc.md` (weight `U32`, `fdx.quant`
8365 /// GGML_BLOCK keeping byte-honesty — the CPU linear-quant U8→U32 precedent), and
8366 /// flips the two corpus fused sections to `registrable: false` describe-only
8367 /// cross-referencing it (the matmul_mixed_precision precedent).
8368 ///
8369 /// This asserts: the `(QMatMul, [F32, U32, F32], Vulkan)` key resolves to the
8370 /// EXACT production wrapper fn-pointer `qmatmul::qmatmul_vk` (behavior-preserving);
8371 /// `kernel_source == "vulkan-slang"` (the RED discriminator — the deleted hand
8372 /// path stamped `""`, so before the import is wired this assert fails on the empty
8373 /// source); and `caps.strided_input == false` — the contiguous-only truth of the
8374 /// deleted `register_with_precision` reg (the GGML block stream has a fixed block
8375 /// layout; a strided operand is auto-Contiguized first). Precision is
8376 /// contract-sourced (the matmul/conv precedent: the hand-written
8377 /// `VULKAN_QMATMUL_PRECISION` over-claimed `bit_stable_on_same_hardware: true`; the
8378 /// contract seeds the truthful audited-nondeterministic posture) and NOT asserted
8379 /// here.
8380 #[test]
8381 fn register_vulkan_kernels_binds_qmatmul_from_contract() {
8382 let mut table = KernelBindingTable::new();
8383 register_vulkan_kernels(&mut table);
8384 let vk = BackendId::Vulkan;
8385
8386 let key: &[DType] = &[DType::F32, DType::U32, DType::F32];
8387 let expected = qmatmul::qmatmul_vk as KernelRef;
8388 let alts = table.lookup_alternatives(OpKind::QMatMul, key, vk);
8389 let entry = alts.iter().find(|e| e.kernel as usize == expected as usize);
8390 let entry = match entry {
8391 Some(e) => e,
8392 None => panic!(
8393 "QMatMul {key:?}/Vulkan: production wrapper (qmatmul_vk) must be bound FROM the \
8394 vulkan qmatmul contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
8395 alts.len(),
8396 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
8397 ),
8398 };
8399 assert_eq!(
8400 entry.kernel_source, "vulkan-slang",
8401 "QMatMul {key:?}: qmatmul must be contract-sourced \
8402 (kernel_source=\"vulkan-slang\"); got {:?}",
8403 entry.kernel_source,
8404 );
8405 assert!(
8406 !entry.caps.strided_input,
8407 "QMatMul {key:?}: caps preserved (contiguous-only, strided_input=false)",
8408 );
8409 }
8410}
8411
8412// ===========================================================================
8413// FKC contract-migration tests (born-red gate for the Vulkan FlashAttn family)
8414// ===========================================================================
8415//
8416// Same always-on gating (this crate IS the Vulkan crate) as the cast/…/qmatmul tests
8417// above: this module always compiles (this crate has no feature gate) and touches NO
8418// device (registration is pure binding-table population).
8419
8420#[cfg(test)]
8421mod attention_contract_tests {
8422 use super::*;
8423 use fuel_dispatch::kernel::{KernelBindingTable, KernelRef};
8424
8425 /// FIFTEENTH (and LAST) VULKAN-BACKEND FKC CONSUMER (born-red gate).
8426 /// `register_vulkan_kernels` registers the whole Vulkan **FlashAttention**
8427 /// family (12 `KernelRef`s: forward `OpKind::FlashAttn` at f32/bf16/f16 +
8428 /// backward `OpKind::FlashAttnBackward{Q,K,V}` at f32, each with a
8429 /// no-alibi AND a with-alibi binding shape) FROM ITS AUTHORED FKC KERNEL
8430 /// CONTRACT (`fuel-dispatch/kernel-contracts/vulkan/attention.fkc.md`) via
8431 /// `register_vulkan_attention_from_contract` — the sole registration path
8432 /// now that the hand-written `table.register_with_precision(OpKind::{FlashAttn,
8433 /// FlashAttnBackwardQ,FlashAttnBackwardK,FlashAttnBackwardV}, …)` regs are
8434 /// DELETED. This was the LAST hand-written `table.register*` call in
8435 /// `register_vulkan_kernels`, so the Vulkan backend is now 100%
8436 /// contract-sourced.
8437 ///
8438 /// The forward wrappers are DISTINCT per dtype
8439 /// (`flash_attn::flash_attn_{f32,bf16,f16}`), so the contract authors THREE
8440 /// single-dtype-per-operand forward sections (the conv2d + CPU-attention
8441 /// per-dtype-section precedent) rather than one dtype-fanned umbrella; the
8442 /// three backward selectors are f32-only single sections. In every section
8443 /// `alibi_slopes` is an `optional: true` LAST input, so the importer's
8444 /// optional-last fan (§3.4) registers EACH as TWO keys (with + without the
8445 /// operand) — byte-for-byte the deleted regs' dual `[q,k,v,out]` /
8446 /// `[q,k,v,alibi,out]` (forward) and `[q,k,v,do,out]` / `[q,k,v,do,alibi,out]`
8447 /// (backward) shapes.
8448 ///
8449 /// For each `(OpKind, [T..], Vulkan)` key this asserts: the binding resolves
8450 /// to the EXACT production wrapper fn-pointer (behavior-preserving);
8451 /// `kernel_source == "vulkan-slang"` (the RED discriminator — the deleted
8452 /// hand path stamped `""`, so before the import is wired this assert fails on
8453 /// the empty source); and `caps.strided_input == false` — the contiguous-only
8454 /// truth of the deleted plain `register_with_precision` regs. Precision is
8455 /// contract-sourced (the retired `VULKAN_{FLOAT,HALF}_POINTWISE_PRECISION`
8456 /// consts over-claimed `bit_stable_on_same_hardware: true` for a shared-mem
8457 /// softmax reduction; the contract seeds the truthful audited-nondeterministic
8458 /// posture, matching the aspirational `conv-attn-rope.fkc.md`) and NOT
8459 /// asserted here.
8460 #[test]
8461 fn register_vulkan_kernels_binds_flash_attn_family_from_contract() {
8462 let mut table = KernelBindingTable::new();
8463 register_vulkan_kernels(&mut table);
8464 let vk = BackendId::Vulkan;
8465
8466 // (OpKind, key dtypes [inputs.., out], expected production wrapper). Both the
8467 // no-alibi and the with-alibi (one extra pre-output slot) shapes per op/dtype.
8468 // Every FlashAttn binding is contiguous-only (strided_input == false), checked
8469 // uniformly below.
8470 let cases: &[(OpKind, &[DType], KernelRef)] = &[
8471 // ---- Forward FlashAttn: f32 / bf16 / f16, no-alibi [q,k,v,out] + with-alibi [q,k,v,alibi,out]. ----
8472 (
8473 OpKind::FlashAttn,
8474 &[DType::F32, DType::F32, DType::F32, DType::F32],
8475 flash_attn::flash_attn_f32 as KernelRef,
8476 ),
8477 (
8478 OpKind::FlashAttn,
8479 &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32],
8480 flash_attn::flash_attn_f32 as KernelRef,
8481 ),
8482 (
8483 OpKind::FlashAttn,
8484 &[DType::BF16, DType::BF16, DType::BF16, DType::BF16],
8485 flash_attn::flash_attn_bf16 as KernelRef,
8486 ),
8487 (
8488 OpKind::FlashAttn,
8489 &[
8490 DType::BF16,
8491 DType::BF16,
8492 DType::BF16,
8493 DType::BF16,
8494 DType::BF16,
8495 ],
8496 flash_attn::flash_attn_bf16 as KernelRef,
8497 ),
8498 (
8499 OpKind::FlashAttn,
8500 &[DType::F16, DType::F16, DType::F16, DType::F16],
8501 flash_attn::flash_attn_f16 as KernelRef,
8502 ),
8503 (
8504 OpKind::FlashAttn,
8505 &[DType::F16, DType::F16, DType::F16, DType::F16, DType::F16],
8506 flash_attn::flash_attn_f16 as KernelRef,
8507 ),
8508 // ---- Backward Q/K/V f32: no-alibi [q,k,v,do,out] + with-alibi [q,k,v,do,alibi,out]. ----
8509 (
8510 OpKind::FlashAttnBackwardQ,
8511 &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32],
8512 flash_attn::flash_attn_backward_q_f32 as KernelRef,
8513 ),
8514 (
8515 OpKind::FlashAttnBackwardQ,
8516 &[
8517 DType::F32,
8518 DType::F32,
8519 DType::F32,
8520 DType::F32,
8521 DType::F32,
8522 DType::F32,
8523 ],
8524 flash_attn::flash_attn_backward_q_f32 as KernelRef,
8525 ),
8526 (
8527 OpKind::FlashAttnBackwardK,
8528 &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32],
8529 flash_attn::flash_attn_backward_k_f32 as KernelRef,
8530 ),
8531 (
8532 OpKind::FlashAttnBackwardK,
8533 &[
8534 DType::F32,
8535 DType::F32,
8536 DType::F32,
8537 DType::F32,
8538 DType::F32,
8539 DType::F32,
8540 ],
8541 flash_attn::flash_attn_backward_k_f32 as KernelRef,
8542 ),
8543 (
8544 OpKind::FlashAttnBackwardV,
8545 &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32],
8546 flash_attn::flash_attn_backward_v_f32 as KernelRef,
8547 ),
8548 (
8549 OpKind::FlashAttnBackwardV,
8550 &[
8551 DType::F32,
8552 DType::F32,
8553 DType::F32,
8554 DType::F32,
8555 DType::F32,
8556 DType::F32,
8557 ],
8558 flash_attn::flash_attn_backward_v_f32 as KernelRef,
8559 ),
8560 ];
8561
8562 let mut checked = 0usize;
8563 for (op, key, expected) in cases {
8564 let alts = table.lookup_alternatives(*op, key, vk);
8565 let entry = alts
8566 .iter()
8567 .find(|e| e.kernel as usize == *expected as usize);
8568 let entry = match entry {
8569 Some(e) => e,
8570 None => panic!(
8571 "{op:?} {key:?}/Vulkan: production wrapper must be bound FROM the vulkan \
8572 attention contract in register_vulkan_kernels; found {} alt(s) with sources {:?}",
8573 alts.len(),
8574 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
8575 ),
8576 };
8577 assert_eq!(
8578 entry.kernel_source, "vulkan-slang",
8579 "{op:?} {key:?}: FlashAttn family must be contract-sourced \
8580 (kernel_source=\"vulkan-slang\"); got {:?}",
8581 entry.kernel_source,
8582 );
8583 assert!(
8584 !entry.caps.strided_input,
8585 "{op:?} {key:?}: caps preserved (contiguous-only, strided_input=false)",
8586 );
8587 checked += 1;
8588 }
8589 assert_eq!(
8590 checked, 12,
8591 "all 12 FlashAttn family bindings (6 forward + 6 backward) checked"
8592 );
8593 }
8594}
8595
8596/// The wired-type list ([`qmatmul::qmatmul_wired`]) and the arms of `qmatmul_vk`'s `match quant_type`
8597/// must name the same types: `fuel-tensor`'s loader keeps a GGUF weight quantized exactly when the list
8598/// says wired, so a type with an arm and no list entry stays on the f32 path for no reason, and a type
8599/// in the list with no arm errors at realize ("not wired on Vulkan"). Source-scanning, no GPU.
8600#[cfg(test)]
8601mod qmatmul_wired_list_matches_arms {
8602 use super::qmatmul::qmatmul_wired;
8603 use fuel_graph::QuantType;
8604 use std::collections::BTreeSet;
8605
8606 /// Every variant, named. The `match` is exhaustive, so a new `QuantType` variant is a compile
8607 /// error here until it is added and given a verdict.
8608 fn all() -> Vec<(QuantType, &'static str)> {
8609 let v = [
8610 (QuantType::Q4_0, "Q4_0"),
8611 (QuantType::Q4_1, "Q4_1"),
8612 (QuantType::Q5_0, "Q5_0"),
8613 (QuantType::Q5_1, "Q5_1"),
8614 (QuantType::Q8_0, "Q8_0"),
8615 (QuantType::Q8_1, "Q8_1"),
8616 (QuantType::Q2K, "Q2K"),
8617 (QuantType::Q3K, "Q3K"),
8618 (QuantType::Q4_K_M, "Q4_K_M"),
8619 (QuantType::Q5K, "Q5K"),
8620 (QuantType::Q6K, "Q6K"),
8621 (QuantType::Iq4Nl, "Iq4Nl"),
8622 (QuantType::Iq4Xs, "Iq4Xs"),
8623 (QuantType::Iq3S, "Iq3S"),
8624 ];
8625 for (q, _) in &v {
8626 match q {
8627 QuantType::Q4_0
8628 | QuantType::Q4_1
8629 | QuantType::Q5_0
8630 | QuantType::Q5_1
8631 | QuantType::Q8_0
8632 | QuantType::Q8_1
8633 | QuantType::Q2K
8634 | QuantType::Q3K
8635 | QuantType::Q4_K_M
8636 | QuantType::Q5K
8637 | QuantType::Q6K
8638 | QuantType::Iq4Nl
8639 | QuantType::Iq4Xs
8640 | QuantType::Iq3S => {}
8641 }
8642 }
8643 v.to_vec()
8644 }
8645
8646 /// The `QuantType::X =>` arms of the `match quant_type {` inside `qmatmul_vk`, read from this file.
8647 fn arms_in(src: &str) -> BTreeSet<String> {
8648 let start = src
8649 .find("pub fn qmatmul_vk(")
8650 .expect("qmatmul_vk is in this file");
8651 let body = &src[start..];
8652 let m = body
8653 .find("match quant_type {")
8654 .expect("qmatmul_vk matches on quant_type");
8655 let mut arms = BTreeSet::new();
8656 for line in body[m..].lines().skip(1) {
8657 let t = line.trim_start();
8658 if t.starts_with("other =>") || t.starts_with("_ =>") {
8659 break;
8660 }
8661 if let Some(rest) = t.strip_prefix("QuantType::")
8662 && let Some((name, _)) = rest.split_once(" =>")
8663 {
8664 arms.insert(name.to_string());
8665 }
8666 }
8667 arms
8668 }
8669
8670 fn listed() -> BTreeSet<String> {
8671 all()
8672 .into_iter()
8673 .filter(|(q, _)| qmatmul_wired(*q))
8674 .map(|(_, n)| n.to_string())
8675 .collect()
8676 }
8677
8678 #[test]
8679 fn the_list_and_the_arms_name_the_same_types() {
8680 let arms = arms_in(include_str!("vulkan_dispatch.rs"));
8681 assert_eq!(
8682 arms,
8683 listed(),
8684 "qmatmul_wired and qmatmul_vk's match arms disagree: change both in one commit"
8685 );
8686 // Control: the scan finds the arms that exist today (so an empty parse cannot pass).
8687 assert!(arms.contains("Q4_K_M") && arms.len() == 9, "{arms:?}");
8688 }
8689
8690 /// The mutant the divergence test exists for: an arm added without the list entry.
8691 #[test]
8692 fn an_arm_without_a_list_entry_is_caught() {
8693 let src = include_str!("vulkan_dispatch.rs");
8694 // Built from pieces so this test's own text does not contain the text it counts.
8695 let needle = concat!("QuantType::Q8_0 =", "> backend.matmul_q8_0_bytes");
8696 assert_eq!(src.matches(needle).count(), 1);
8697 let mutated = src.replacen(
8698 needle,
8699 concat!(
8700 "QuantType::Q2K =",
8701 "> backend.matmul_q2_k_bytes(a, w, out, batch_count, m, k, n),
8702 ",
8703 "QuantType::Q8_0 =",
8704 "> backend.matmul_q8_0_bytes"
8705 ),
8706 1,
8707 );
8708 assert_ne!(arms_in(&mutated), listed(), "the mutant was not caught");
8709 }
8710}