Skip to main content

ferrox_core/weight_matrix/
gpu_backend.rs

1//! The seam every GPU backend goes through.
2//!
3//! Four things used to exist once per backend as free functions in
4//! `weight_matrix.rs`, with no shape holding them together:
5//!
6//! | Axis | Metal | CUDA |
7//! |---|---|---|
8//! | kind → matvec | `metal_matvec_kind_name` → `Option<&str>` | `cuda_matvec_kind_supported` → `bool` |
9//! | kind → GEMM | `metal_mul_mm_kind_supported` | `cuda_mul_mm_kind_supported` |
10//! | launch alias | `MetalMatvecLaunchFn`, 4 args | `CudaMatvecLaunchFn`, 5 args |
11//! | enable probe | `metal_dense_enabled` | `cuda_dense_enabled`, byte-identical body |
12//!
13//! and they were re-selected by hand at every dispatch site, so
14//! `apply_gpu` carried two near-identical `match kind` tables that could
15//! only be kept honest by a `debug_assert!`. A third backend would have
16//! copied all four. This module is the shape they now share.
17//!
18//! # What a third backend has to provide
19//!
20//! Exactly this, and nothing else:
21//!
22//! 1. A unit type (`pub struct Vulkan;`).
23//! 2. [`BackendCaps`] — the two capability tables plus an id and a
24//!    display name. **Compiled unconditionally**, with no dependency on
25//!    the backend crate, because the tables are a property of the kernel
26//!    set rather than of the build, and gating them would make them
27//!    untestable on the CPU builds that run `cargo test --workspace`.
28//!    This is the rule that kept `metal_matvec_kind_name` un-`cfg`'d and
29//!    it is load-bearing: `probe_kernels_for` asks what Metal *would*
30//!    resolve from a build with no Metal.
31//! 3. [`BackendDispatch`] under `#[cfg(feature = "…")]` — the enable
32//!    probe, a device-free launch table, and one launch entry point.
33//! 4. One line in [`gpu_backend_table`], which is **the** ordered list:
34//!    enum variant, cargo feature / registry name, and seam type, once.
35//!
36//! `Vulkan` is what that recipe looks like when it is followed: a
37//! one-kernel backend (Q8_0 matvec, no GEMM, no batch path) added
38//! without touching `apply_gpu` or `active_backend`.
39//!
40//! # The one list, and its three consumers
41//!
42//! [`gpu_backend_table`] is expanded by exactly three things, so a
43//! backend cannot exist in one of them and not the others:
44//!
45//! - [`crate::kernel_registry::Backend`]'s variants and their names.
46//!   This is verdict point 4 — "a backend cannot be dispatched to
47//!   without being reportable" — and it is now structural rather than
48//!   hand-kept. It works because the registry and this module are the
49//!   same crate; a `macro_rules!` cannot generate an enum in a
50//!   *different* crate, so a backend crate could never own its own
51//!   variant.
52//! - [`with_gpu_backends`], the `#[cfg]`-gated dispatch order, which
53//!   [`crate::weight_matrix::WeightMatrix::apply_gpu`] and
54//!   [`crate::weight_matrix::active_backend`] both expand.
55//! - [`with_gpu_backend_caps`], the **ungated** one, which
56//!   `probe_kernels_for` expands so a CPU-only build can still ask what
57//!   Metal or Vulkan *would* resolve.
58//!
59//! # The launch signature, and the fifth argument
60//!
61//! `ferrox-cuda`'s `launch_*_matvec` takes
62//! `(weights, x, rows, row_bytes, n_blocks_per_row)`; `ferrox-metal`'s
63//! takes the first four. [`BackendDispatch::launch_matvec`] takes the
64//! four plus the [`QuantKind`], and every backend derives the rest.
65//!
66//! That is deliberate, and it is not the wider arity the beachhead
67//! verdict proposed. `n_blocks_per_row` is **redundant information**,
68//! not missing information: it is `row_bytes / block_bytes(kind)`, and
69//! Metal already recomputes exactly that inside
70//! `ferrox_metal::gpu::matvec_launch_meta`, which hands back the block
71//! size for the kind. Hoisting it into the shared signature would buy a
72//! backend nothing it cannot derive, and would cost a
73//! `block_bytes(kind)` that is total over all 21 `QuantKind`s — the
74//! existing one, `WeightMatrix::block_bytes_for_kind`, is deliberately
75//! partial and `unreachable!()`s outside the five CUDA kinds, and
76//! Metal's `IQ4_XS` is not one of them. So the seam passes the kind and
77//! lets each backend ask its own table.
78
79use crate::kernel_registry::Backend;
80use crate::weight_matrix::QuantKind;
81
82/// A backend launch failure, flattened to its rendered message.
83///
84/// `ferrox_metal::gpu::MetalError` and `ferrox_cuda::gpu::CudaError` are
85/// different types living behind different features, and the only thing
86/// any caller does with either is print it before falling back — so the
87/// seam carries the message rather than an enum that would have to grow
88/// a variant per backend crate.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct BackendError(String);
91
92impl BackendError {
93    /// Renders any backend error into the one shape the seam carries.
94    pub fn new(e: impl std::fmt::Display) -> Self {
95        BackendError(e.to_string())
96    }
97}
98
99impl std::fmt::Display for BackendError {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        f.write_str(&self.0)
102    }
103}
104
105/// What a backend can run, asked without the backend crate present.
106///
107/// Every member is an associated function with no receiver, which is
108/// what the free functions this replaced already were, so implementing
109/// it is a lift rather than a redesign.
110pub trait BackendCaps {
111    /// How [`crate::kernel_registry`] reports this backend. Dispatch and
112    /// observability read the same constant, so a backend cannot be
113    /// dispatched to under one name and reported under another.
114    const ID: Backend;
115
116    /// Human-readable name, for the one message a dispatch failure
117    /// prints.
118    const NAME: &'static str;
119
120    /// What a batched prefill actually runs on for a kind this backend
121    /// has a matvec but no GEMM for — the string
122    /// `probe_kernels_for` records as the fallback.
123    ///
124    /// It lives here because it is a property of the backend and it was
125    /// previously a `match backend` arm inside `probe_kernels_for`: a
126    /// third `Backend` variant would have silently inherited Metal's
127    /// wording (`"Metal N x matvec batch"`) by falling through `_`, and
128    /// the registry's whole job is to name the path that will really
129    /// run. Ungated, like the rest of [`BackendCaps`], because the
130    /// probe is ungated.
131    const GEMM_FALLBACK: &'static str;
132
133    /// Which quant kinds have a **matvec** kernel (the decode path), as
134    /// the kernel name the backend's own launch-meta table is keyed by,
135    /// or `None` for a kind with no kernel.
136    ///
137    /// Returning the name rather than a `bool` is what let the two
138    /// backends share one member: CUDA only ever needed the `bool`
139    /// (`.is_some()`), Metal needs the name to look up
140    /// `ferrox_metal::gpu::matvec_launch_meta`, and a `bool` cannot be
141    /// widened after the fact without another table.
142    fn matvec_kernel(kind: QuantKind) -> Option<&'static str>;
143
144    /// Which quant kinds have a **batched GEMM** (the prefill path). A
145    /// kind with a matvec but no GEMM still runs on the accelerator — as
146    /// `batch` separate matvecs over the same weights, which is the
147    /// 13.7x shape, and which is why these are two predicates and not
148    /// one.
149    fn gemm_supported(kind: QuantKind) -> bool;
150}
151
152/// What a backend can actually do, which needs its crate compiled in.
153pub trait BackendDispatch: BackendCaps {
154    /// What [`crate::weight_matrix::WeightMatrix::apply_gpu`] will do
155    /// next if this backend's launch fails, named for the log line.
156    /// A property of this backend's position in
157    /// [`with_gpu_backends`], not of the backend itself.
158    const MATVEC_FALLBACK: &'static str;
159
160    /// Whether dense matmuls should try this backend in this process.
161    /// Decided once from the environment, then cached for the process
162    /// lifetime. See `env_or_probe` for the grammar, which is shared.
163    fn dense_enabled() -> bool;
164
165    /// Whether a launch **function** exists for `kind`, asked without a
166    /// device and without launching anything.
167    ///
168    /// This is the question [`BackendCaps::matvec_kernel`] claims to
169    /// answer, asked of the code that actually runs. They are two
170    /// structures that must agree about one thing, and they cannot be
171    /// merged: the kernel NAMES are needed on builds where the backend
172    /// crate is not a dependency and these function pointers do not
173    /// exist. So the agreement is a test —
174    /// `every_kind_a_compiled_backend_claims_can_actually_be_launched`,
175    /// over every backend and all 21 kinds — rather than the
176    /// `debug_assert!` that used to guard it, which fired only for
177    /// kinds a run actually reached and only in debug.
178    ///
179    /// `Q5_0` is why. It was in Metal's capability table with no launch
180    /// function behind it from the day it was added, so batched prefill
181    /// ran on the GPU while single-token decode silently fell to the
182    /// CPU, and a release build just ran slower.
183    fn has_launch(kind: QuantKind) -> bool;
184
185    /// One matvec. `None` means "this backend has no kernel for `kind`",
186    /// which is a different answer from `Some(Err(_))`, "the kernel
187    /// exists and the launch failed" — the caller logs only the second.
188    fn launch_matvec(
189        kind: QuantKind,
190        weights: &[u8],
191        x: &[f32],
192        rows: usize,
193        row_bytes: usize,
194    ) -> Option<Result<Vec<f32>, BackendError>>;
195}
196
197/// The per-kind Metal launch table, split out of
198/// [`BackendDispatch::launch_matvec`] so it can be checked for EVERY
199/// kind without a device.
200///
201/// It has to agree with [`Metal::matvec_kernel`], and it cannot be the
202/// same table: the kernel NAMES are needed on builds where
203/// `ferrox-metal` is not a dependency and these function pointers do not
204/// exist. So the agreement is asserted, and asserting it only inside
205/// `launch_matvec` was not enough -- that fires just for kinds a run
206/// actually reaches, in debug. `Q5_0` was in the capability table and
207/// missing here from the day it was added, and the symptom was
208/// single-token decode silently falling to the CPU while batched
209/// prefill ran on the GPU.
210#[cfg(feature = "metal")]
211fn metal_matvec_launch(kind: QuantKind) -> Option<MetalMatvecLaunchFn> {
212    match kind {
213        QuantKind::Q8_0 => Some(ferrox_metal::gpu::launch_q8_0_matvec),
214        QuantKind::Q4_0 => Some(ferrox_metal::gpu::launch_q4_0_matvec),
215        QuantKind::Q4K => Some(ferrox_metal::gpu::launch_q4_k_matvec),
216        QuantKind::Q5_0 => Some(ferrox_metal::gpu::launch_q5_0_matvec),
217        QuantKind::Q5K => Some(ferrox_metal::gpu::launch_q5_k_matvec),
218        QuantKind::Q6K => Some(ferrox_metal::gpu::launch_q6_k_matvec),
219        QuantKind::IQ4XS => Some(ferrox_metal::gpu::launch_iq4_xs_matvec),
220        _ => None,
221    }
222}
223
224/// The per-kind CUDA launch table, split out of
225/// [`BackendDispatch::launch_matvec`] for the same reason
226/// [`metal_matvec_launch`] was: so
227/// [`BackendDispatch::has_launch`] can check it against
228/// [`Cuda::matvec_kernel`] for EVERY kind, without a GPU. It was inline
229/// in `launch_matvec` and therefore had no guard at all — the hole that
230/// cost Metal a Q5_0 decode path.
231#[cfg(feature = "cuda")]
232pub(crate) fn cuda_matvec_launch(kind: QuantKind) -> Option<CudaMatvecLaunchFn> {
233    match kind {
234        QuantKind::Q8_0 => Some(ferrox_cuda::gpu::launch_q8_0_matvec),
235        QuantKind::Q4_0 => Some(ferrox_cuda::gpu::launch_q4_0_matvec),
236        QuantKind::Q5_0 => Some(ferrox_cuda::gpu::launch_q5_0_matvec),
237        QuantKind::Q2K => Some(ferrox_cuda::gpu::launch_q2_k_matvec),
238        QuantKind::Q3K => Some(ferrox_cuda::gpu::launch_q3_k_matvec),
239        QuantKind::Q4K => Some(ferrox_cuda::gpu::launch_q4_k_matvec),
240        QuantKind::Q5K => Some(ferrox_cuda::gpu::launch_q5_k_matvec),
241        QuantKind::Q6K => Some(ferrox_cuda::gpu::launch_q6_k_matvec),
242        QuantKind::IQ4NL => Some(ferrox_cuda::gpu::launch_iq4_nl_matvec),
243        QuantKind::IQ4XS => Some(ferrox_cuda::gpu::launch_iq4_xs_matvec),
244        QuantKind::Mxfp4Gguf => Some(ferrox_cuda::gpu::launch_mxfp4_matvec),
245        _ => None,
246    }
247}
248
249/// The per-kind Vulkan launch table. One row, and the guard test is
250/// what keeps it one row: adding a kind to [`Vulkan::matvec_kernel`]
251/// without a shader here fails
252/// `every_kind_a_compiled_backend_claims_can_actually_be_launched`.
253#[cfg(feature = "vulkan")]
254fn vulkan_matvec_launch(kind: QuantKind) -> Option<VulkanMatvecLaunchFn> {
255    match kind {
256        QuantKind::Q8_0 => Some(ferrox_vulkan::dispatch::q8_0_matvec),
257        _ => None,
258    }
259}
260
261/// The Metal backend (`ferrox-metal`).
262pub struct Metal;
263
264/// The CUDA backend (`ferrox-cuda`).
265pub struct Cuda;
266
267/// The Vulkan backend (`ferrox-vulkan`) — **one kernel wide**.
268///
269/// `ferrox-vulkan` is the `vulkan-beachhead` GO/NO-GO slice, not a
270/// backend: a single hand-emitted SPIR-V Q8_0 matvec, checked against a
271/// scalar twin and run on a real device through MoltenVK. See
272/// `docs/plans/vulkan-beachhead-verdict.md`.
273///
274/// This impl is what wiring that slice into the seam costs, and it is
275/// deliberately not more than the slice supports:
276///
277/// - **Q8_0 and nothing else.** [`Vulkan::matvec_kernel`] names one
278///   kind; every other kind reports no kernel, which is the honest
279///   answer and is what makes the registry say "NO KERNEL … falls back
280///   to CPU apply_cpu" instead of quietly running slow.
281/// - **No GEMM at all.** [`Vulkan::gemm_supported`] is false for every
282///   kind. There is no `mul_mm` shader, and `apply_batch_with_acts` has
283///   no Vulkan arm, so a batched prefill runs on the host —
284///   [`Vulkan::GEMM_FALLBACK`] says exactly that.
285/// - **No performance claim.** `q8_0_matvec` rebuilds its entire
286///   pipeline per call. Nothing here may be reported as a measured
287///   capability; the verdict says so and this comment repeats it
288///   because the code is now reachable.
289pub struct Vulkan;
290
291impl BackendCaps for Metal {
292    const ID: Backend = Backend::Metal;
293    const NAME: &'static str = "Metal";
294    /// `apply_gpu_batch` re-reads the whole weight matrix once per
295    /// position, on the GPU. Still Metal, still the 13.7x shape.
296    const GEMM_FALLBACK: &'static str = "Metal N x matvec batch";
297
298    /// As the kernel name [`ferrox_metal::gpu::matvec_launch_meta`]
299    /// resolves.
300    ///
301    /// This is the single source of truth for that question. It is *not*
302    /// `#[cfg(feature = "metal")]`-gated deliberately: the table is a
303    /// property of the kernel set, and gating it would make it
304    /// untestable on the builds that run `cargo test --workspace`.
305    ///
306    /// Duplicating this list is how IQ4_XS batched prefill silently ran
307    /// on the CPU — `metal_kind_supported` and `apply_gpu_batch`'s kind
308    /// table disagreed by exactly one entry, and the only symptom was a
309    /// benchmark row 13.7x behind. Every Metal-kind question now routes
310    /// through here.
311    fn matvec_kernel(kind: QuantKind) -> Option<&'static str> {
312        match kind {
313            QuantKind::Q8_0
314            | QuantKind::Q4_0
315            | QuantKind::Q5_0
316            | QuantKind::Q4K
317            | QuantKind::Q5K
318            | QuantKind::Q6K
319            | QuantKind::IQ4XS => Some(kind.name()),
320            _ => None,
321        }
322    }
323
324    /// The `*_mul_mm_sg` simdgroup GEMMs.
325    ///
326    /// The invariant that this set equals [`Metal::matvec_kernel`]'s is
327    /// asserted by a test, so adding a matvec kernel without a GEMM
328    /// fails the suite instead of a benchmark.
329    fn gemm_supported(kind: QuantKind) -> bool {
330        // Q5_0 JOINED 2026-09-01, and the two-year-old comment this
331        // replaced named the exact condition: "the honest close is a
332        // `q5_0_matvec` plus a Q5_0 row in the bench suite, not a sixth
333        // entry in this list."
334        //
335        // The matvec now exists (`Q5_0_MATVEC_KERNEL_SRC`), so the split
336        // this list was protecting against is gone: Q5_0 was already
337        // getting GPU prefill through `mul_mm_sg_launch` and `mapped_sg`,
338        // which never consulted this table, while every decode step fell
339        // back to the CPU for want of the matvec. That is the mixed
340        // CPU/GPU path the old comment feared, and it was live rather
341        // than hypothetical.
342        //
343        // The bench row is still owed: there is no Q5_0 checkpoint in
344        // `benchmarks/suite.json`, so this path is
345        // CORRECT-BY-CONSTRUCTION and UNMEASURED.
346        // `Llama-3.2-1B-Instruct-Q5_K_M` is Q5_K, not Q5_0.
347        matches!(
348            kind,
349            QuantKind::Q8_0
350                | QuantKind::Q4_0
351                | QuantKind::Q5_0
352                | QuantKind::Q4K
353                | QuantKind::Q5K
354                | QuantKind::Q6K
355                | QuantKind::IQ4XS
356        )
357    }
358}
359
360impl BackendCaps for Cuda {
361    const ID: Backend = Backend::Cuda;
362    const NAME: &'static str = "CUDA";
363    /// `apply_batch_with_acts` decomposes a CUDA prefill into one
364    /// matvec per position for every kind off [`Cuda::gemm_supported`].
365    const GEMM_FALLBACK: &'static str = "CUDA per-position matvec";
366
367    /// The decode path, and the arm that has actually run on a GPU --
368    /// for six of its nine kinds.
369    ///
370    /// **DERIVED from `ferrox_cuda::matvec_kinds::KINDS`, not restated.**
371    /// That table is compiled on every build (it is CUDA C text and
372    /// three strings per row; nothing in it needs `cudarc`), and
373    /// `ferrox-cuda` is an unconditional dependency for exactly this
374    /// reason. The set used to be written out here as a `matches!` and
375    /// checked against the kernel table by a test that only ran under
376    /// `--features cuda`; over-claiming there sends a decode to an
377    /// NVRTC module that does not exist, and under-claiming leaves a
378    /// kernel nothing ever calls. Both have happened.
379    ///
380    /// The name is returned only to share
381    /// [`BackendCaps::matvec_kernel`]'s shape with Metal; nothing on the
382    /// CUDA path reads it, because `ferrox-cuda`'s launchers are named
383    /// functions rather than entries in a string-keyed table.
384    fn matvec_kernel(kind: QuantKind) -> Option<&'static str> {
385        ferrox_cuda::matvec_kinds::kind_by_name(kind.name()).map(|_| kind.name())
386    }
387
388    /// The `mul_mm` prefill path.
389    ///
390    /// **DERIVED from `ferrox_cuda::mul_mm::KINDS`**, for the same
391    /// reason and by the same mechanism as [`Cuda::matvec_kernel`]
392    /// above. It equals that set, and
393    /// `the_matvec_table_and_the_mul_mm_table_name_the_same_kinds` in
394    /// `ferrox-cuda` is what keeps it equal -- a kind with one kernel
395    /// and not the other splits a forward pass across two devices.
396    ///
397    /// It did not until 2026-09-04: only Q8_0 and Q4_0 had a
398    /// matrix-matrix product, so a K-quant prefill decomposed into one
399    /// matvec launch per position. Measured on a GTX 1080, that cost
400    /// Llama-3.2-3B Q4_K_M 4.88 tok/s of pp512 against llama.cpp's
401    /// 1586.80, a 325x gap on the most common quantization in
402    /// circulation (#131). IQ4_XS is still absent: it is a codebook
403    /// lookup rather than an affine dequant.
404    ///
405    /// Q5_0 joined on 2026-09-05, matvec and GEMM together, because
406    /// `a_cuda_kind_with_a_matvec_also_has_a_gemm` makes half of it
407    /// fail the suite -- and because half of it is the shape that cost
408    /// Metal a Q5_0 decode path: GPU prefill with every decode step on
409    /// the host.
410    ///
411    /// IQ4_NL, IQ4_XS and MXFP4 joined on 2026-09-09, matvec and GEMM
412    /// together. They are CODEBOOK formats: the stored 4-bit code is an
413    /// index into a sixteen-entry table, not a magnitude, so the kernel
414    /// carries that table in `__constant__` memory. gpt-oss ships
415    /// MXFP4 and no GPU backend had it at all, so every expert decoded
416    /// on the host with the device idle.
417    ///
418    /// **UNRUN ON HARDWARE.** The kernel is checked against a scalar
419    /// twin and by executing the emitted CUDA C on the host, and has
420    /// never executed on a GPU. See `crates/ferrox-cuda/src/mul_mm.rs`.
421    fn gemm_supported(kind: QuantKind) -> bool {
422        ferrox_cuda::mul_mm::kind_by_name(kind.name()).is_some()
423    }
424}
425
426impl BackendCaps for Vulkan {
427    const ID: Backend = Backend::Vulkan;
428    const NAME: &'static str = "Vulkan";
429    /// There is no Vulkan batch entry point of any kind:
430    /// `apply_gpu_batch` is `#[cfg(feature = "metal")]` and
431    /// `apply_batch_with_acts` has a CUDA arm and a Metal arm. So a
432    /// prefill against a Vulkan-resident kind runs on the host, and
433    /// this names the host path rather than inventing a GPU one.
434    const GEMM_FALLBACK: &'static str = "CPU apply_batch";
435
436    /// Exactly one kind, because there is exactly one shader:
437    /// `ferrox_vulkan::q8_0_shader`.
438    ///
439    /// Everything else must report `None` rather than something
440    /// plausible. A capability table that over-claims is how a kind ends
441    /// up "supported" with no kernel behind it, which this repo has now
442    /// paid for twice (IQ4_XS prefill, Q5_0 decode). The guard test
443    /// checks this against [`vulkan_matvec_launch`] for all 21 kinds.
444    fn matvec_kernel(kind: QuantKind) -> Option<&'static str> {
445        match kind {
446            QuantKind::Q8_0 => Some(kind.name()),
447            _ => None,
448        }
449    }
450
451    /// No kind, for any kind. The beachhead emitted one matvec shader
452    /// and deliberately no `mul_mm`; the verdict puts a real GEMM in
453    /// `vulkan-prefill-gemm`, which is where the backend decision
454    /// actually lives.
455    ///
456    /// This is the one place the Metal invariant
457    /// (`every_metal_matvec_kind_also_has_a_metal_gemm`: matvec set ==
458    /// GEMM set) is knowingly not held, and it is held open rather than
459    /// papered over: Q8_0 decodes on Vulkan and prefills on the CPU,
460    /// the registry records the split by name, and `ferrox bench` would
461    /// show it.
462    fn gemm_supported(_kind: QuantKind) -> bool {
463        false
464    }
465}
466
467/// The `FERROX_METAL` / `FERROX_CUDA` grammar, which was written out
468/// twice in bodies that were byte-identical apart from the alias:
469///
470/// - `0|false|off|cpu` — force CPU
471/// - `1|true|on|<alias>` — force this backend
472/// - unset / anything else — whatever `probe` says
473///
474/// `probe` is only called when the environment did not decide, which is
475/// what keeps a forced-off build from opening a device.
476///
477/// Compiled when a backend needs it, and under `test` so the grammar
478/// stays checked on the CPU-only builds that run `cargo test`.
479#[cfg(any(feature = "metal", feature = "cuda", feature = "vulkan", test))]
480fn env_or_probe(value: Option<&str>, on_alias: &str, probe: impl FnOnce() -> bool) -> bool {
481    match value {
482        Some("0") | Some("false") | Some("off") | Some("cpu") => false,
483        Some("1") | Some("true") | Some("on") => true,
484        Some(v) if v == on_alias => true,
485        _ => probe(),
486    }
487}
488
489/// A `ferrox_metal::gpu::launch_*_matvec` function pointer's signature
490/// (`weights`/`x` borrowed; row block count is derived inside
491/// `ferrox_metal::gpu`).
492#[cfg(feature = "metal")]
493type MetalMatvecLaunchFn =
494    fn(&[u8], &[f32], usize, usize) -> Result<Vec<f32>, ferrox_metal::gpu::MetalError>;
495
496/// A `ferrox_cuda::gpu::launch_*_matvec` function pointer's signature
497/// (all five real kernels share it exactly).
498#[cfg(feature = "cuda")]
499type CudaMatvecLaunchFn =
500    fn(&[u8], &[f32], usize, usize, usize) -> Result<Vec<f32>, ferrox_cuda::gpu::CudaError>;
501
502/// A `ferrox_vulkan::dispatch` matvec's signature. Same five arguments
503/// as [`CudaMatvecLaunchFn`] -- `ferrox-vulkan` was written to this
504/// list on purpose -- plus the borrowed [`ferrox_vulkan::device::Context`]
505/// in front, because Vulkan keeps no process-global device inside its
506/// own crate the way `ferrox_metal::gpu` and `ferrox_cuda::gpu` do.
507/// [`vulkan_context`] is that global, and it lives here so the beachhead
508/// crate stays a beachhead.
509#[cfg(feature = "vulkan")]
510type VulkanMatvecLaunchFn = fn(
511    &ferrox_vulkan::device::Context,
512    &[u8],
513    &[f32],
514    usize,
515    usize,
516    usize,
517) -> Result<Vec<f32>, ferrox_vulkan::device::VulkanError>;
518
519#[cfg(feature = "metal")]
520impl BackendDispatch for Metal {
521    const MATVEC_FALLBACK: &'static str = "falling back to CPU";
522
523    fn has_launch(kind: QuantKind) -> bool {
524        metal_matvec_launch(kind).is_some()
525    }
526
527    fn dense_enabled() -> bool {
528        use std::sync::OnceLock;
529        // A `static` inside a generic function is shared across every
530        // monomorphization, so this cache cannot be hoisted into a
531        // default trait method: each backend needs its own cell.
532        static ENABLED: OnceLock<bool> = OnceLock::new();
533        *ENABLED.get_or_init(|| {
534            let v = std::env::var("FERROX_METAL").ok();
535            env_or_probe(v.as_deref(), "metal", || {
536                ferrox_metal::gpu::probe().is_some()
537            })
538        })
539    }
540
541    fn launch_matvec(
542        kind: QuantKind,
543        weights: &[u8],
544        x: &[f32],
545        rows: usize,
546        row_bytes: usize,
547    ) -> Option<Result<Vec<f32>, BackendError>> {
548        let launch = metal_matvec_launch(kind);
549        // This table and `Metal::matvec_kernel` answer the same question
550        // and must never diverge; when they did, IQ4_XS prefill silently
551        // moved to the CPU. They CANNOT be one table -- the names are
552        // needed on builds where `ferrox-metal` is not a dependency and
553        // these function pointers do not exist -- so the agreement stays
554        // asserted rather than structural.
555        debug_assert_eq!(
556            launch.is_some(),
557            Self::matvec_kernel(kind).is_some(),
558            "apply_gpu's Metal launch table disagrees with metal_matvec_kind_name for {:?}",
559            kind
560        );
561        let launch = launch?;
562        Some(launch(weights, x, rows, row_bytes).map_err(BackendError::new))
563    }
564}
565
566#[cfg(feature = "cuda")]
567impl BackendDispatch for Cuda {
568    const MATVEC_FALLBACK: &'static str = "trying next backend / CPU";
569
570    fn has_launch(kind: QuantKind) -> bool {
571        cuda_matvec_launch(kind).is_some()
572    }
573
574    fn dense_enabled() -> bool {
575        use std::sync::OnceLock;
576        // See the note on `Metal::dense_enabled` for why this cell is
577        // not shared through a default method.
578        static ENABLED: OnceLock<bool> = OnceLock::new();
579        *ENABLED.get_or_init(|| {
580            let v = std::env::var("FERROX_CUDA").ok();
581            env_or_probe(v.as_deref(), "cuda", || ferrox_cuda::gpu::probe().is_some())
582        })
583    }
584
585    fn launch_matvec(
586        kind: QuantKind,
587        weights: &[u8],
588        x: &[f32],
589        rows: usize,
590        row_bytes: usize,
591    ) -> Option<Result<Vec<f32>, BackendError>> {
592        let launch = cuda_matvec_launch(kind)?;
593
594        // `FERROX_CUDA=0` must mean the CPU, and a build with the
595        // `cuda` feature on a host with no driver must fall back, not
596        // die. Neither was true here until 2026-09-09.
597        //
598        // `Vulkan::launch_matvec` has carried this guard since it
599        // landed, and its comment said Metal and CUDA did not need one
600        // because "their launchers no-op into an error when their
601        // device is absent". That is true of Metal. It is NOT true of
602        // CUDA: `cudarc` resolves `libcuda` through a lazily loaded
603        // symbol table and PANICS (`cudarc-0.11.9/src/lib.rs:98`,
604        // "Unable to dynamically load the cuda shared library") rather
605        // than returning an error, so the `Result` this arm is written
606        // around never gets a chance to be `Err`. A panic in a rayon
607        // worker is not a fallback.
608        //
609        // It was latent rather than harmless: any quantized matvec on
610        // such a build aborted the process. Nothing in the suite
611        // reached it because the one test that dispatches a real kind
612        // through here is `#[ignore]`d, and the test that dispatches an
613        // unsupported one picked a kind that returned `None` above --
614        // until Q2_K gained a kernel and stopped being unsupported.
615        //
616        // `dense_enabled()` is a `OnceLock` over a probe that catches
617        // its own panics, so this costs one atomic load after the first
618        // call.
619        if !Self::dense_enabled() {
620            return None;
621        }
622
623        // Derived here rather than at the seam: `block_bytes_for_kind`
624        // is `unreachable!()` outside the CUDA-dispatchable kinds, and
625        // reaching it is gated on the match above having named one.
626        let n_blocks_per_row =
627            row_bytes / crate::weight_matrix::WeightMatrix::block_bytes_for_kind(kind);
628        Some(launch(weights, x, rows, row_bytes, n_blocks_per_row).map_err(BackendError::new))
629    }
630}
631
632/// The process-wide Vulkan device, opened at most once.
633///
634/// `ferrox_metal::gpu` and `ferrox_cuda::gpu` each keep their device
635/// inside their own crate, so their launch functions take no context.
636/// `ferrox-vulkan` deliberately does not: it is a beachhead whose
637/// `Context` is created and dropped by its own tests, and giving it a
638/// hidden global would have made the GO/NO-GO slice into infrastructure.
639/// So the global lives here, on the seam's side of the boundary.
640///
641/// `Mutex`, not a bare `Context`: a `vk::Queue` must be externally
642/// synchronized, and `apply_gpu` is called from rayon workers.
643/// Serializing them is correct and is not a regression, because
644/// `q8_0_matvec` rebuilds its entire pipeline per call and is not a
645/// performance path in the first place — see the verdict.
646///
647/// `None` means the device could not be opened. That is reported once,
648/// here, rather than once per matvec.
649#[cfg(feature = "vulkan")]
650fn vulkan_context() -> Option<&'static std::sync::Mutex<ferrox_vulkan::device::Context>> {
651    use std::sync::{Mutex, OnceLock};
652    static CTX: OnceLock<Option<Mutex<ferrox_vulkan::device::Context>>> = OnceLock::new();
653    CTX.get_or_init(|| match ferrox_vulkan::device::Context::new() {
654        Ok(ctx) => Some(Mutex::new(ctx)),
655        Err(e) => {
656            eprintln!(
657                "ferrox: Vulkan device unavailable, {}: {e}",
658                Vulkan::MATVEC_FALLBACK
659            );
660            None
661        }
662    })
663    .as_ref()
664}
665
666#[cfg(feature = "vulkan")]
667impl BackendDispatch for Vulkan {
668    /// Last in [`gpu_backend_table`], so there is nothing after it.
669    const MATVEC_FALLBACK: &'static str = "falling back to CPU";
670
671    fn has_launch(kind: QuantKind) -> bool {
672        vulkan_matvec_launch(kind).is_some()
673    }
674
675    fn dense_enabled() -> bool {
676        use std::sync::OnceLock;
677        // See the note on `Metal::dense_enabled` for why this cell is
678        // not shared through a default method.
679        static ENABLED: OnceLock<bool> = OnceLock::new();
680        *ENABLED.get_or_init(|| {
681            let v = std::env::var("FERROX_VULKAN").ok();
682            env_or_probe(v.as_deref(), "vulkan", || {
683                ferrox_vulkan::device::probe().is_ok()
684            })
685        })
686    }
687
688    fn launch_matvec(
689        kind: QuantKind,
690        weights: &[u8],
691        x: &[f32],
692        rows: usize,
693        row_bytes: usize,
694    ) -> Option<Result<Vec<f32>, BackendError>> {
695        let launch = vulkan_matvec_launch(kind)?;
696
697        // Unlike Metal, whose launcher no-ops into an error when its
698        // device is absent, `ferrox-vulkan` has no global to consult --
699        // so the env grammar is honoured here or not at all. (CUDA was
700        // in this sentence too, and should not have been: see
701        // `Cuda::launch_matvec`, which now carries the same guard.)
702        // `FERROX_VULKAN=0` must mean the CPU, not "open a device
703        // anyway". Returning `None` (rather than an error) is right:
704        // "this backend is not running here" is the same answer as "no
705        // kernel", and both mean try the next backend.
706        if !Self::dense_enabled() {
707            return None;
708        }
709        let ctx = vulkan_context()?;
710
711        // `ferrox_vulkan::dispatch::q8_0_matvec` asserts its shape
712        // invariants, which is right for a test-driven beachhead and
713        // wrong for a dispatch path: a panic in a rayon worker is not a
714        // fallback. Checked here so a mismatch is an error the caller
715        // logs and recovers from.
716        let block_bytes = crate::weight_matrix::WeightMatrix::block_bytes_for_kind(kind);
717        let n_blocks_per_row = row_bytes / block_bytes;
718        if weights.len() != rows * row_bytes
719            || row_bytes != n_blocks_per_row * block_bytes
720            || x.len() != n_blocks_per_row * ferrox_vulkan::q8_0_shader::BLOCK_ELEMS
721            || rows == 0
722            || n_blocks_per_row == 0
723        {
724            return Some(Err(BackendError::new(format!(
725                "Vulkan {} matvec shape rejected: {} weight bytes, {} activations, \
726                 rows={rows} row_bytes={row_bytes}",
727                kind.name(),
728                weights.len(),
729                x.len(),
730            ))));
731        }
732
733        let guard = match ctx.lock() {
734            Ok(g) => g,
735            // A poisoned mutex means another thread panicked mid-
736            // dispatch; the device may be mid-submission, so refuse
737            // rather than reuse it.
738            Err(_) => {
739                return Some(Err(BackendError::new(
740                    "Vulkan context poisoned by an earlier panic",
741                )))
742            }
743        };
744        Some(
745            launch(&guard, weights, x, rows, row_bytes, n_blocks_per_row)
746                .map_err(BackendError::new),
747        )
748    }
749}
750
751/// **The** backend table: one row per GPU backend, in dispatch
752/// precedence order — CUDA first, then Metal, then Vulkan, then the CPU
753/// fallthrough the caller supplies.
754///
755/// Vulkan is last on purpose. On the only machine that can run all
756/// three it reaches the GPU through MoltenVK, i.e. through Metal, and
757/// it has one kernel; a native backend must win over a translation
758/// layer wrapping it.
759///
760/// Each row is `(enum variant, feature / registry name, seam type)`.
761/// The three are the same string in three grammars, and that is exactly
762/// why they are written once: the cargo feature, the
763/// [`crate::kernel_registry::Backend`] variant and the type were three
764/// hand-kept lists, and "two structures that must agree about one
765/// thing" is the dominant bug shape in this repo.
766///
767/// It expands `$mac!` ONCE with every row, so a consumer can build a
768/// single item (an `enum`) from it and not just a sequence of
769/// statements. `$extra` is passed through in brackets ahead of the rows
770/// so a consumer that needs its own callback — [`with_gpu_backends`] —
771/// can forward one without re-listing the table.
772macro_rules! gpu_backend_table {
773    ($mac:path $(, $extra:tt)*) => {
774        $mac! {
775            [$($extra),*]
776            (Cuda, "cuda", Cuda),
777            (Metal, "metal", Metal),
778            (Vulkan, "vulkan", Vulkan),
779        }
780    };
781}
782pub(crate) use gpu_backend_table;
783
784/// Expands `$mac!(Backend)` once per **compiled-in** backend, in
785/// [`gpu_backend_table`] order.
786///
787/// This exists because the order was hand-copied at every dispatch site
788/// and in `active_backend`, and a macro is the only way to keep static
789/// dispatch, per-backend `#[cfg]`, and one written-down order at the
790/// same time. A third backend is one line in the table, not here.
791///
792/// `$mac` must tolerate being expanded zero times: on a CPU-only build
793/// this produces nothing, so define it `#[allow(unused_macros)]`.
794macro_rules! with_gpu_backends {
795    ($mac:ident) => {
796        $crate::weight_matrix::gpu_backend::gpu_backend_table!(
797            $crate::weight_matrix::gpu_backend::gpu_backend_dispatch_rows,
798            $mac
799        );
800    };
801}
802pub(crate) use with_gpu_backends;
803
804/// [`with_gpu_backends`]'s row expander. The `#[cfg(feature = …)]` is
805/// built from the table's own name column, so a backend cannot be in
806/// the list under one feature and gated on another.
807macro_rules! gpu_backend_dispatch_rows {
808    ([$mac:ident] $(($variant:ident, $feature:literal, $ty:ident)),* $(,)?) => {
809        $(
810            #[cfg(feature = $feature)]
811            $mac!($crate::weight_matrix::gpu_backend::$ty);
812        )*
813    };
814}
815pub(crate) use gpu_backend_dispatch_rows;
816
817/// Expands `$mac!(Backend)` once per backend **whether or not it is
818/// compiled in**, in [`gpu_backend_table`] order.
819///
820/// The ungated twin of [`with_gpu_backends`], and the reason
821/// [`BackendCaps`] is ungated: `probe_kernels_for` has to answer "what
822/// would Metal resolve for this kind" on a build with no Metal, which
823/// is the only way the kernel-coverage tests run under a plain
824/// `cargo test`. A consumer of this must therefore stay inside
825/// [`BackendCaps`] — [`BackendDispatch`] does not exist for a backend
826/// whose feature is off.
827///
828/// Never expands zero times, so `$mac` needs no `unused_macros` cover.
829macro_rules! with_gpu_backend_caps {
830    ($mac:ident) => {
831        $crate::weight_matrix::gpu_backend::gpu_backend_table!(
832            $crate::weight_matrix::gpu_backend::gpu_backend_caps_rows,
833            $mac
834        );
835    };
836}
837pub(crate) use with_gpu_backend_caps;
838
839/// [`with_gpu_backend_caps`]'s row expander.
840macro_rules! gpu_backend_caps_rows {
841    ([$mac:ident] $(($variant:ident, $feature:literal, $ty:ident)),* $(,)?) => {
842        $(
843            $mac!($crate::weight_matrix::gpu_backend::$ty);
844        )*
845    };
846}
847pub(crate) use gpu_backend_caps_rows;
848
849#[cfg(test)]
850mod tests {
851    use super::*;
852
853    /// The env grammar both enable probes share. `probe` must not be
854    /// consulted when the environment already decided — a forced-off
855    /// build must never open a device.
856    #[test]
857    fn env_decides_before_the_probe_is_consulted() {
858        for forced_off in ["0", "false", "off", "cpu"] {
859            assert!(!env_or_probe(Some(forced_off), "metal", || panic!(
860                "probed after {forced_off}"
861            )));
862        }
863        for forced_on in ["1", "true", "on"] {
864            assert!(env_or_probe(Some(forced_on), "metal", || panic!(
865                "probed after {forced_on}"
866            )));
867        }
868    }
869
870    /// Each backend's own alias forces it on; the *other* backend's
871    /// alias is not a value it understands, so it falls through to the
872    /// probe rather than silently forcing.
873    #[test]
874    fn the_alias_is_per_backend() {
875        assert!(env_or_probe(Some("metal"), "metal", || false));
876        assert!(env_or_probe(Some("cuda"), "cuda", || false));
877        assert!(!env_or_probe(Some("cuda"), "metal", || false));
878        assert!(!env_or_probe(Some("metal"), "cuda", || false));
879    }
880
881    /// Unset, or a value the grammar does not name, defers to the probe.
882    #[test]
883    fn an_unrecognised_value_defers_to_the_probe() {
884        assert!(env_or_probe(None, "metal", || true));
885        assert!(!env_or_probe(None, "metal", || false));
886        assert!(env_or_probe(Some("auto"), "metal", || true));
887        assert!(!env_or_probe(Some("auto"), "metal", || false));
888    }
889
890    /// A backend cannot be dispatched to under one name and reported
891    /// under another: dispatch and the registry read the same constant.
892    ///
893    /// [`Backend`]'s variants are generated from the same table these
894    /// impls are listed in, so a *missing* variant is now impossible —
895    /// but `const ID` is still written by hand in each impl, so naming
896    /// another backend's variant is not. That is what the distinctness
897    /// check catches, and the count check catches a variant with no
898    /// backend behind it.
899    #[test]
900    fn every_backend_id_is_distinct_and_an_accelerator() {
901        let mut ids = Vec::new();
902        macro_rules! collect_id {
903            ($b:ty) => {
904                assert!(
905                    <$b as BackendCaps>::ID.is_accelerator(),
906                    "{} is reported as the CPU",
907                    <$b as BackendCaps>::NAME
908                );
909                ids.push((<$b as BackendCaps>::ID, <$b as BackendCaps>::NAME));
910            };
911        }
912        with_gpu_backend_caps!(collect_id);
913
914        for (i, (id, name)) in ids.iter().enumerate() {
915            for (other_id, other_name) in &ids[i + 1..] {
916                assert_ne!(
917                    id, other_id,
918                    "{name} and {other_name} both report as {id} -- one of them is \
919                     dispatched to under a registry identity that is not its own"
920                );
921            }
922        }
923        assert_eq!(
924            ids.len() + 1,
925            Backend::ALL.len(),
926            "the registry has a backend variant no BackendCaps impl claims: {:?} vs {ids:?}",
927            Backend::ALL
928        );
929    }
930
931    /// Vulkan is **one kernel wide** and the seam must keep saying so.
932    ///
933    /// `ferrox-vulkan` has exactly one shader, `q8_0_shader`. If this
934    /// table ever grows a kind, either a shader landed with it (and this
935    /// test is the place to say so) or the table now over-claims — which
936    /// is how IQ4_XS prefill and Q5_0 decode each silently moved to the
937    /// CPU while the capability report said "GPU".
938    ///
939    /// Ungated on purpose, like [`BackendCaps`] itself: this is a
940    /// property of the kernel set, so it is checked on every build,
941    /// including the CPU-only one that runs `cargo test --workspace`.
942    #[test]
943    fn vulkan_claims_exactly_one_matvec_kind_and_no_gemm() {
944        let claimed: Vec<QuantKind> = QuantKind::ALL
945            .iter()
946            .copied()
947            .filter(|&k| Vulkan::matvec_kernel(k).is_some())
948            .collect();
949        assert_eq!(
950            claimed,
951            vec![QuantKind::Q8_0],
952            "ferrox-vulkan has one shader (q8_0_shader); the capability table claims {claimed:?}"
953        );
954        for &k in QuantKind::ALL {
955            assert!(
956                !Vulkan::gemm_supported(k),
957                "{k:?}: there is no Vulkan mul_mm shader, so a claimed GEMM would send \
958                 prefill to a kernel that does not exist"
959            );
960        }
961    }
962
963    /// Every kind a **compiled-in** backend's capability table CLAIMS
964    /// must have a launch function behind it, for all 21 kinds and
965    /// without a device.
966    ///
967    /// `Q5_0` did not, on Metal, from the day it was added. The kernel
968    /// source and the `matvec_launch_meta` row landed together and both
969    /// capability tables were widened on the strength of them — but
970    /// `apply_gpu`'s single-matvec decode path dispatches through a
971    /// per-kind `launch_*_matvec` FUNCTION, and there was no Q5_0 one.
972    /// So batched prefill ran on the GPU while single-token decode
973    /// silently fell to the CPU: exactly the mixed CPU/GPU split that
974    /// widening was supposed to close.
975    ///
976    /// The `debug_assert_eq!` in `Metal::launch_matvec` did guard this,
977    /// but only for kinds a run actually reaches, and only in debug. A
978    /// release build just ran slower. This checks the whole table up
979    /// front — and, since it expands over
980    /// [`with_gpu_backends`] rather than naming Metal, CUDA and Vulkan
981    /// each get it for free instead of Metal getting it three times.
982    /// CUDA had no such guard at all before its launch table was split
983    /// out of `launch_matvec`; Vulkan gets one on its first day.
984    #[test]
985    fn every_kind_a_compiled_backend_claims_can_actually_be_launched() {
986        #[allow(unused_macros)]
987        macro_rules! check_launch_table {
988            ($b:ty) => {
989                let mut claimed_without_launch = Vec::new();
990                let mut launchable_unclaimed = Vec::new();
991                for &kind in QuantKind::ALL {
992                    let claimed = <$b as BackendCaps>::matvec_kernel(kind).is_some();
993                    let launchable = <$b as BackendDispatch>::has_launch(kind);
994                    if claimed && !launchable {
995                        claimed_without_launch.push(kind);
996                    }
997                    if launchable && !claimed {
998                        launchable_unclaimed.push(kind);
999                    }
1000                }
1001                assert!(
1002                    claimed_without_launch.is_empty(),
1003                    "{} claims a matvec nothing can launch: {claimed_without_launch:?} -- \
1004                     decode falls to the CPU for these while batched prefill runs on the GPU",
1005                    <$b as BackendCaps>::NAME
1006                );
1007                assert!(
1008                    launchable_unclaimed.is_empty(),
1009                    "{} has a launch for {launchable_unclaimed:?} that its capability \
1010                     table does not claim, so nothing will ever call it",
1011                    <$b as BackendCaps>::NAME
1012                );
1013            };
1014        }
1015        with_gpu_backends!(check_launch_table);
1016    }
1017
1018    /// A kind that claims a matvec must name itself the way the
1019    /// backend's launch-meta table is keyed, for every backend and not
1020    /// just Metal. Expanded over the ungated table, so it holds on a
1021    /// CPU-only build and a third backend gets it for free — which it
1022    /// did not when the body hand-listed `[Metal, Cuda]`.
1023    #[test]
1024    fn a_claimed_matvec_kernel_is_named_after_its_kind() {
1025        macro_rules! check_names {
1026            ($b:ty) => {
1027                for &k in QuantKind::ALL {
1028                    if let Some(name) = <$b as BackendCaps>::matvec_kernel(k) {
1029                        assert_eq!(
1030                            name,
1031                            k.name(),
1032                            "{} names {k:?} {name:?}",
1033                            <$b as BackendCaps>::NAME
1034                        );
1035                    }
1036                }
1037            };
1038        }
1039        with_gpu_backend_caps!(check_names);
1040    }
1041
1042    /// The GPU matvec against the CPU one, on a real device.
1043    ///
1044    /// This is the only test here that opens a device, and it is the
1045    /// only one that can catch the seam wiring the right kernel to the
1046    /// wrong arguments — a `row_bytes` that is not `n_blocks * 34`, or
1047    /// an activation length derived from the wrong block size, are both
1048    /// legal calls that produce a wrong number. `ferrox-vulkan`'s own
1049    /// twin test proves the shader; this proves the *call*.
1050    ///
1051    /// Skips, loudly, when no device is reachable, so it is not a test
1052    /// that cannot fail: on a host with Vulkan it asserts, and it was
1053    /// checked by sabotage (feeding `rows + 1`) before being committed.
1054    #[cfg(feature = "vulkan")]
1055    #[test]
1056    fn the_vulkan_seam_matvec_matches_the_cpu_matvec() {
1057        use crate::weight_matrix::{WeightBytes, WeightMatrix};
1058
1059        if !Vulkan::dense_enabled() {
1060            eprintln!("no Vulkan device reachable; the seam matvec was NOT checked");
1061            return;
1062        }
1063
1064        // Three blocks per row: 3 * 34 = 102 bytes, deliberately not a
1065        // multiple of 4, which is the alignment case the shader's byte
1066        // extraction exists for.
1067        let (rows, blocks) = (9usize, 3usize);
1068        let cols = blocks * 32;
1069        let f32_weights: Vec<f32> = (0..rows * cols)
1070            .map(|i| ((i % 37) as f32 - 18.0) / 11.0)
1071            .collect();
1072        let mut data = Vec::new();
1073        for r in 0..rows {
1074            data.extend_from_slice(&ferrox_quant::quantize_q8_0(
1075                &f32_weights[r * cols..(r + 1) * cols],
1076            ));
1077        }
1078        let x: Vec<f32> = (0..cols).map(|i| ((i % 13) as f32 - 6.0) / 5.0).collect();
1079
1080        let m = WeightMatrix::Quantized {
1081            data: WeightBytes::Owned(data),
1082            rows,
1083            cols,
1084            kind: QuantKind::Q8_0,
1085        };
1086        let WeightMatrix::Quantized { data, .. } = &m else {
1087            unreachable!()
1088        };
1089        let got = Vulkan::launch_matvec(QuantKind::Q8_0, data.as_slice(), &x, rows, blocks * 34)
1090            .expect("Q8_0 has a Vulkan kernel")
1091            .expect("the launch must succeed once a device is open");
1092        let want = m.apply(&x);
1093
1094        assert_eq!(got.len(), want.len());
1095        for (r, (g, w)) in got.iter().zip(&want).enumerate() {
1096            // The same 1e-4 relative tolerance ferrox-cuda's hardware
1097            // test uses, and for the same reason: a GPU may contract
1098            // `acc + a * b` into an FMA.
1099            assert!(
1100                (g - w).abs() <= 1e-4 * w.abs().max(1.0),
1101                "row {r}: vulkan {g} vs cpu {w}"
1102            );
1103        }
1104    }
1105
1106    /// A shape the kernel cannot honour must come back as an ERROR the
1107    /// caller logs, never as a panic in a rayon worker.
1108    /// `ferrox_vulkan::dispatch::q8_0_matvec` asserts its invariants,
1109    /// which is right for a beachhead and fatal on a dispatch path, so
1110    /// the seam checks them first. Needs no device: the check runs
1111    /// before the context is used.
1112    #[cfg(feature = "vulkan")]
1113    #[test]
1114    fn a_mismatched_vulkan_shape_is_an_error_not_a_panic() {
1115        if !Vulkan::dense_enabled() {
1116            eprintln!("no Vulkan device reachable; the shape guard was NOT checked");
1117            return;
1118        }
1119        // 2 rows of 1 block each, but an activation sized for 2 blocks.
1120        let weights = vec![0u8; 2 * 34];
1121        let x = vec![0.0f32; 64];
1122        let out = Vulkan::launch_matvec(QuantKind::Q8_0, &weights, &x, 2, 34);
1123        assert!(
1124            matches!(out, Some(Err(_))),
1125            "a mismatched shape must be a reported error, got {out:?}"
1126        );
1127    }
1128}