Skip to main content

cortiq_engine/
gpu.rs

1//! Facade for GPU backends: a single call entry point for qtensor/pipeline/
2//! linear_core. Job types and the threshold are canonical HERE; behind the
3//! facade dispatch goes to a platform backend:
4//!   - `gpu_metal` (Apple Silicon, unified memory + no-copy buffers);
5//!   - `gpu_wgpu` (C1: Vulkan/DX12/Metal — NVIDIA/Radeon/Intel/Apple,
6//!     weights resident in VRAM), available under `--features gpu`.
7//!
8//! Runtime selection via `CMF_GPU`: `1` — native Metal (macOS) or wgpu
9//! (other OSes); `wgpu` — force wgpu (including for the local
10//! Metal-via-wgpu parity test). Any backend refusal — `false` and the honest
11//! CPU path, no partial results.
12
13use cortiq_core::CmfModel;
14use std::cell::Cell;
15use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
16use std::sync::{Arc, OnceLock};
17
18thread_local! {
19    /// Index of the current forward layer (−1 = outside a numbered layer:
20    /// lm_head/embed — always allowed). The pipeline sets it before
21    /// each layer so that the GPU/CPU layer-split works.
22    static CUR_LAYER: Cell<i64> = const { Cell::new(-1) };
23    /// Inside `cpu_scope` every GPU gate reports disabled: the timed CPU
24    /// arm of a probe (and a class that lost its probe) must run PURE
25    /// CPU, or inner per-op hooks would re-enter the GPU and poison the
26    /// comparison.
27    static CPU_ONLY: Cell<bool> = const { Cell::new(false) };
28    /// "This op paid a one-off cost" (weight upload / first pipeline
29    /// build): backends set it, `probe_record` discards the sample so
30    /// only steady-state timings compete.
31    static PROBE_COLD: Cell<bool> = const { Cell::new(false) };
32}
33
34/// Run `f` with the GPU gates off on this thread (pure-CPU arm).
35pub fn cpu_scope<R>(f: impl FnOnce() -> R) -> R {
36    struct Restore(bool);
37    impl Drop for Restore {
38        fn drop(&mut self) {
39            CPU_ONLY.with(|c| c.set(self.0));
40        }
41    }
42    let previous = CPU_ONLY.with(|c| c.replace(true));
43    let _restore = Restore(previous);
44    f()
45}
46
47/// Backends: note a one-off cost (weight upload, buffer-cache fill) so
48/// the probe discards this sample.
49pub(crate) fn probe_note_cold() {
50    PROBE_COLD.with(|c| c.set(true));
51}
52
53/// Peek the cold flag without consuming it (`probe_record` consumes).
54/// Contention heuristics use this: a slow COLD op is a one-off build
55/// cost, not evidence the device is busy.
56pub(crate) fn probe_was_cold() -> bool {
57    PROBE_COLD.with(|c| c.get())
58}
59
60/// Pipeline: mark the current layer (or −1 outside layers) for layer-split.
61pub fn set_layer(l: i64) {
62    CUR_LAYER.with(|c| c.set(l));
63}
64
65/// The layer `set_layer` last marked on this thread (−1 outside layers).
66pub fn cur_layer() -> i64 {
67    CUR_LAYER.with(|c| c.get())
68}
69
70/// Parse `CMF_GPU_LAYERS` («0-19», «0,2,4», «0-9,30-39») once.
71/// None = no restriction (all layers on GPU). Garbage → also no restriction.
72fn layer_ranges() -> &'static Option<Vec<(i64, i64)>> {
73    static R: OnceLock<Option<Vec<(i64, i64)>>> = OnceLock::new();
74    R.get_or_init(|| {
75        let s = std::env::var("CMF_GPU_LAYERS").ok()?;
76        let mut v = Vec::new();
77        for part in s.split(',') {
78            let part = part.trim();
79            match part.split_once('-') {
80                Some((a, b)) => v.push((a.trim().parse().ok()?, b.trim().parse().ok()?)),
81                None => {
82                    let x: i64 = part.parse().ok()?;
83                    v.push((x, x));
84                }
85            }
86        }
87        Some(v)
88    })
89}
90
91fn layer_allowed() -> bool {
92    match layer_ranges() {
93        None => true,
94        Some(ranges) => {
95            let cur = CUR_LAYER.with(|c| c.get());
96            cur < 0 || ranges.iter().any(|(a, b)| cur >= *a && cur <= *b)
97        }
98    }
99}
100
101/// GPU allowed FOR THE CURRENT LAYER: backend is initialized AND the layer
102/// falls within `CMF_GPU_LAYERS` (GPU/CPU layer-split) AND we are not
103/// inside a `cpu_scope`. Op gates call this.
104pub fn enabled_here() -> bool {
105    !CPU_ONLY.with(|c| c.get()) && enabled() && layer_allowed()
106}
107
108// ── Runtime GPU-vs-CPU probe ────────────────────────────────────────────
109// CMF_GPU=1 does not TRUST that the device wins — it MEASURES. For each
110// op class the first calls alternate arms: GPU timed vs pure-CPU timed
111// (under cpu_scope). Cold GPU calls (weight upload / cache fill) are
112// discarded; after PROBE_SAMPLES clean samples per arm the faster arm is
113// chosen for the rest of the process. Rationale: submit+poll latency
114// differs by an order of magnitude across driver stacks (Metal/PCIe
115// ~3-4 ms, Vulkan/4090 ~0.3 ms) — a static threshold cannot know whether
116// per-op offload pays off HERE. CMF_GPU_PROBE=0 → always trust the GPU.
117
118/// GPU-eligible op classes, each with an independent probe.
119#[derive(Clone, Copy)]
120pub enum OpClass {
121    /// Whole FFN chain in one submission (dense / MoE block).
122    Ffn = 0,
123    /// Large hybrid CPU∥GPU matvec (lm_head class).
124    Matvec = 1,
125    /// Prefill GEMM (matmat).
126    Matmat = 2,
127    /// Batched matvecs of one input (QKV).
128    Batch = 3,
129    /// Prefill GEMM at image-diffusion widths (b ≥ 128). Probed apart
130    /// from `Matmat`: one imagegen process runs BOTH populations
131    /// (prompt encode b≈40 where the GPU wins big, DiT b≥256 where
132    /// the CPU AMX arm is competitive) — a single shared verdict locks
133    /// the wrong arm for whichever population samples second.
134    MatmatWide = 4,
135}
136
137/// Probe verdict for one call.
138pub enum ProbeArm {
139    /// Run the GPU path (during probing: timed, recorded).
140    Gpu,
141    /// Probing: run the CPU path under `cpu_scope`, timed, recorded.
142    CpuTimed,
143    /// Decided: CPU won — run the CPU path (under `cpu_scope`).
144    Cpu,
145}
146
147/// Clean samples per arm before a class decides.
148const PROBE_SAMPLES: u32 = 6;
149
150struct Probe {
151    /// 0 = probing, 1 = GPU won, 2 = CPU won.
152    state: AtomicU8,
153    flip: AtomicU32,
154    gpu_ns: AtomicU64,
155    gpu_n: AtomicU32,
156    cpu_ns: AtomicU64,
157    cpu_n: AtomicU32,
158    /// Best (minimum) sample per arm. The DECISION compares these:
159    /// means are poisoned by one-off cold costs the cold-flag cannot
160    /// see — e.g. the CPU arm's first mmap-cold expert matvec page
161    /// faults its weights in and reads 3× its steady state, which
162    /// locked the GPU arm on a 35B MoE at a 4× real-world loss. The
163    /// minimum is each arm's honest steady-state pace.
164    gpu_min: AtomicU64,
165    cpu_min: AtomicU64,
166}
167
168impl Probe {
169    const fn new() -> Self {
170        Self {
171            state: AtomicU8::new(0),
172            flip: AtomicU32::new(0),
173            gpu_ns: AtomicU64::new(0),
174            gpu_n: AtomicU32::new(0),
175            cpu_ns: AtomicU64::new(0),
176            cpu_n: AtomicU32::new(0),
177            gpu_min: AtomicU64::new(u64::MAX),
178            cpu_min: AtomicU64::new(u64::MAX),
179        }
180    }
181}
182
183static PROBES: [Probe; 5] = [
184    Probe::new(),
185    Probe::new(),
186    Probe::new(),
187    Probe::new(),
188    Probe::new(),
189];
190
191fn probe_on() -> bool {
192    static ON: OnceLock<bool> = OnceLock::new();
193    *ON.get_or_init(|| {
194        std::env::var("CMF_GPU_PROBE")
195            .map(|v| v != "0" && v != "off")
196            .unwrap_or(true)
197    })
198}
199
200/// q1 ops on the native Metal backend skip the probe entirely: the CPU
201/// q1 kernel is load-port-bound, the GPU one wins warm — and probe
202/// alternation itself cools the device between samples (measured: block
203/// times 5.8 ms warm vs 8.8 ms mixed). Other backends keep probing.
204pub fn q1_force() -> bool {
205    #[cfg(target_os = "macos")]
206    {
207        backend() == Backend::Metal
208    }
209    #[cfg(not(target_os = "macos"))]
210    {
211        false
212    }
213}
214
215/// Should a FUSED whole-block path trust the device instead of asking
216/// the per-op probe? True on native Metal and on discrete wgpu adapters.
217///
218/// The probe answers "is one wide matmat faster on the GPU", and for the
219/// DiT on Metal that is a coin flip — measured 2.62 ms GPU vs 2.56 ms
220/// CPU, a 2% spread that lands on either arm run to run. But the fused
221/// block's advantage is not per-op speed, it is that the hidden state,
222/// the packs and the attention panels never leave the device: end to end
223/// the whole-block path renders a 512² Lumina step in ~5.4 s against
224/// ~8.4 s when the probe happens to pick the CPU. Gating a fusion win on
225/// a per-op tie made every second render half-speed at random.
226///
227/// On a discrete card the verdict is never in doubt — an RTX 3090 against
228/// a 256-core EPYC measured 11.5 ms vs 31 ms per wide op, four runs out
229/// of four — so the probe's sampling phase is pure cost: it alone was 10%
230/// of a 512² render (74.3 s against 66.9 s with the probe off). Integrated
231/// and mobile adapters keep probing; there the submit latency is real and
232/// can genuinely lose.
233pub fn fused_block_trusted() -> bool {
234    #[cfg(target_os = "macos")]
235    if backend() == Backend::Metal {
236        return true;
237    }
238    wgpu_graph_default()
239}
240
241/// Which arm should this GPU-eligible call take? Consult AFTER the
242/// eligibility gates (`enabled_here` / `min_rows`) so only real
243/// candidates alternate.
244pub fn probe_arm(c: OpClass) -> ProbeArm {
245    // Every arbitrated call starts with a clean cold flag: both the
246    // sample discard in `probe_record` and the contention kill-switch
247    // read it AFTER the op, so a stale note from a previous call on
248    // this thread must not leak in.
249    PROBE_COLD.with(|f| f.set(false));
250    if !probe_on() {
251        return ProbeArm::Gpu;
252    }
253    let p = &PROBES[c as usize];
254    match p.state.load(Ordering::Relaxed) {
255        1 => ProbeArm::Gpu,
256        2 => ProbeArm::Cpu,
257        _ => {
258            if p.flip.fetch_add(1, Ordering::Relaxed) % 2 == 0 {
259                ProbeArm::Gpu
260            } else {
261                ProbeArm::CpuTimed
262            }
263        }
264    }
265}
266
267/// Record a timed arm sample; on the `PROBE_SAMPLES`-th clean sample of
268/// BOTH arms the class decides for the rest of the process.
269pub fn probe_record(c: OpClass, gpu: bool, dur: std::time::Duration) {
270    let p = &PROBES[c as usize];
271    if p.state.load(Ordering::Relaxed) != 0 {
272        return;
273    }
274    if gpu && PROBE_COLD.with(|f| f.replace(false)) {
275        return; // one-off cost in this call — not a steady-state sample
276    }
277    let ns = dur.as_nanos().min(u64::MAX as u128) as u64;
278    if gpu {
279        p.gpu_ns.fetch_add(ns, Ordering::Relaxed);
280        p.gpu_n.fetch_add(1, Ordering::Relaxed);
281        p.gpu_min.fetch_min(ns, Ordering::Relaxed);
282    } else {
283        p.cpu_ns.fetch_add(ns, Ordering::Relaxed);
284        p.cpu_n.fetch_add(1, Ordering::Relaxed);
285        p.cpu_min.fetch_min(ns, Ordering::Relaxed);
286    }
287    let (gn, cn) = (
288        p.gpu_n.load(Ordering::Relaxed),
289        p.cpu_n.load(Ordering::Relaxed),
290    );
291    if gn >= 2 && cn >= 2 {
292        // Decide on each arm's BEST sample — the steady-state pace.
293        // Means carry one-off cold costs (mmap page-in on the CPU arm)
294        // that the cold-flag machinery cannot see.
295        let g = p.gpu_min.load(Ordering::Relaxed) as f64;
296        let cp = p.cpu_min.load(Ordering::Relaxed) as f64;
297        // Early verdict on a ≥3× gap — no reason to keep feeding the
298        // losing arm; close races take the full sample count.
299        if (gn < PROBE_SAMPLES || cn < PROBE_SAMPLES) && g < cp * 3.0 && cp < g * 3.0 {
300            return;
301        }
302        let winner = if g <= cp { 1 } else { 2 };
303        if p.state
304            .compare_exchange(0, winner, Ordering::Relaxed, Ordering::Relaxed)
305            .is_ok()
306        {
307            tracing::info!(
308                "gpu probe [{}]: gpu {:.2} ms vs cpu {:.2} ms per op → {}",
309                ["ffn", "matvec", "matmat", "qkv-batch", "matmat-wide"][c as usize],
310                g / 1e6,
311                cp / 1e6,
312                if winner == 1 { "gpu" } else { "cpu" },
313            );
314        }
315    }
316}
317
318/// Is the class still collecting samples? (Call sites use this to route
319/// cold-weight calls away from the GPU arm during probing.)
320pub fn probe_deciding(c: OpClass) -> bool {
321    probe_on() && PROBES[c as usize].state.load(Ordering::Relaxed) == 0
322}
323
324/// Probing helper: true — tensor `idx`'s quant weights are ALREADY
325/// device-resident (a clean GPU sample is possible now); false — they
326/// were not (the upload starts within the VRAM budget, so a later call
327/// finds them warm) or the tensor cannot go to the GPU at all. Keeps the
328/// probe from billing a full cold dispatch+readback to a sample it will
329/// discard anyway. The verdict needs only a couple of warm tensors, so
330/// probe-driven uploads are capped — the losing-GPU machine should not
331/// pay for uploading the whole layer stack it will never use; if the GPU
332/// wins, the rest uploads lazily on demand, in the same first-touch order.
333#[allow(unused_variables)]
334pub fn q8_resident_or_upload(model: &Arc<CmfModel>, idx: usize) -> bool {
335    static PROBE_UPLOADS: AtomicU32 = AtomicU32::new(0);
336    let may_upload = PROBE_UPLOADS.load(Ordering::Relaxed) < 4;
337    let resident = match backend() {
338        #[cfg(target_os = "macos")]
339        Backend::Metal => crate::gpu_metal::q8_resident_or_upload(model, idx, may_upload),
340        #[cfg(feature = "gpu")]
341        Backend::Wgpu => crate::gpu_wgpu::q8_resident_or_upload(model, idx, may_upload),
342        Backend::None => false,
343    };
344    if !resident && may_upload {
345        PROBE_UPLOADS.fetch_add(1, Ordering::Relaxed);
346    }
347    resident
348}
349
350/// Test hook: reset all probes to the undecided state.
351#[cfg(test)]
352pub(crate) fn probe_reset() {
353    for p in &PROBES {
354        p.state.store(0, Ordering::Relaxed);
355        p.flip.store(0, Ordering::Relaxed);
356        p.gpu_ns.store(0, Ordering::Relaxed);
357        p.gpu_n.store(0, Ordering::Relaxed);
358        p.cpu_ns.store(0, Ordering::Relaxed);
359        p.cpu_n.store(0, Ordering::Relaxed);
360    }
361}
362
363#[cfg(test)]
364mod probe_tests {
365    use super::*;
366    use std::time::Duration;
367
368    // One test fn: PROBES is process-global and probe_reset touches all
369    // classes — parallel test threads would race.
370    #[test]
371    fn probe_alternates_discards_cold_and_decides() {
372        probe_reset();
373        // Probing: arms alternate.
374        assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
375        assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::CpuTimed));
376
377        // A cold GPU sample (upload noted) must be discarded: feed a
378        // catastrophic cold sample, then clean fast-GPU samples — GPU
379        // wins only if the cold one did not count.
380        probe_note_cold();
381        probe_record(OpClass::Ffn, true, Duration::from_secs(1000));
382        for _ in 0..PROBE_SAMPLES {
383            probe_record(OpClass::Ffn, true, Duration::from_millis(1));
384            probe_record(OpClass::Ffn, false, Duration::from_millis(4));
385        }
386        assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
387
388        // The reverse: a class where the CPU arm is faster decides CPU.
389        for _ in 0..PROBE_SAMPLES {
390            probe_record(OpClass::Matmat, true, Duration::from_millis(4));
391            probe_record(OpClass::Matmat, false, Duration::from_millis(1));
392        }
393        assert!(matches!(probe_arm(OpClass::Matmat), ProbeArm::Cpu));
394
395        // cpu_scope: gates off inside, restored after.
396        cpu_scope(|| CPU_ONLY.with(|c| assert!(c.get())));
397        CPU_ONLY.with(|c| assert!(!c.get()));
398        cpu_scope(|| {
399            cpu_scope(|| CPU_ONLY.with(|c| assert!(c.get())));
400            CPU_ONLY.with(|c| assert!(c.get()));
401        });
402        let _ = std::panic::catch_unwind(|| cpu_scope(|| panic!("scope test")));
403        CPU_ONLY.with(|c| assert!(!c.get()));
404        probe_reset();
405    }
406}
407
408/// Default row threshold: the GPU takes only larger matrices (lm_head
409/// class). Below it, the dispatch/readback cost does not pay off on unified memory.
410pub const GPU_MIN_ROWS: usize = 65_536;
411
412/// Effective threshold: `CMF_GPU_MIN_ROWS` overrides. Defaults differ
413/// by device class: on a DISCRETE card VRAM bandwidth pays off even for
414/// FFN/QKV-class matrices (4096), on unified memory only lm_head-class
415/// is worth the dispatch/readback (65536). Field case behind this: a
416/// 35B model on an RTX 4090 saw ~0 offload because every layer matrix
417/// sat below the old universal 65536.
418pub fn min_rows() -> usize {
419    if let Some(v) = std::env::var("CMF_GPU_MIN_ROWS")
420        .ok()
421        .and_then(|v| v.parse().ok())
422    {
423        return v;
424    }
425    if discrete() { 4096 } else { GPU_MIN_ROWS }
426}
427
428/// Is the active backend a discrete card (PCIe VRAM)?
429pub fn discrete() -> bool {
430    match backend() {
431        #[cfg(feature = "gpu")]
432        Backend::Wgpu => crate::gpu_wgpu::is_discrete(),
433        #[cfg(target_os = "macos")]
434        Backend::Metal => false, // UMA by the init() guard
435        Backend::None => false,
436    }
437}
438
439/// A single MoE-FFN job (an expert with its own weight), executed in one
440/// submission: (rows, cols, idx, row_scale) for gate/up/down + prescaled
441/// inputs + the down θ-field + the blending weight.
442pub struct MoeJob<'a> {
443    pub gate: (usize, usize, usize, &'a [f32]),
444    pub up: (usize, usize, usize, &'a [f32]),
445    pub down: (usize, usize, usize, &'a [f32]),
446    pub xs_gate: Vec<f32>,
447    pub xs_up: Vec<f32>,
448    pub down_col: &'a [f32],
449    pub w: f32,
450    /// q1 trio: scales live inside the 6-byte tiles (row_scale slices
451    /// empty, xs raw f32). Backends without a q1 kernel refuse the job.
452    pub q1: bool,
453    /// q4_tiled trio: scales inside the 18-byte tiles (row_scale
454    /// slices empty, xs raw f32) — the MoE-hybrid coder class.
455    pub q4t: bool,
456    /// q4tp trio: same raw-xs contract, 16-byte nibble stride and the scale
457    /// on a per-row ladder. Without this the experts of a q4tp MoE model fall
458    /// to the CPU while every other dtype rides the device.
459    pub q4tp: bool,
460}
461
462/// A single independent batch matvec (GDN projections of one input).
463pub struct BatchJob<'a> {
464    pub idx: usize,
465    pub rows: usize,
466    pub cols: usize,
467    pub row_scale: &'a [f32],
468    pub xs: Vec<f32>,
469    /// Weight layout. Was a bare `q1: bool`, which could only ever spell two
470    /// of the four and silently sent everything else back to the CPU — the
471    /// GDN projections of a q4t/q4tp model never reached the device at all.
472    pub layout: BatchLayout,
473}
474
475/// Which kernel a batched matvec needs. q8 carries row scales in a side
476/// buffer; the rest embed them in the payload and differ in stride.
477#[derive(Clone, Copy, PartialEq, Eq, Debug)]
478pub enum BatchLayout {
479    Q8,
480    Q1,
481    Q4t,
482    Q4tp,
483}
484
485#[derive(Clone, Copy, PartialEq, Eq)]
486enum Backend {
487    None,
488    #[cfg(target_os = "macos")]
489    Metal,
490    #[cfg(feature = "gpu")]
491    Wgpu,
492}
493
494fn backend() -> Backend {
495    #[cfg(feature = "gpu")]
496    if crate::gpu_wgpu::selected() {
497        return if crate::gpu_wgpu::enabled() {
498            Backend::Wgpu
499        } else {
500            Backend::None
501        };
502    }
503    #[cfg(target_os = "macos")]
504    if crate::gpu_metal::enabled() {
505        return Backend::Metal;
506    }
507    Backend::None
508}
509
510/// GPU enabled and initialized on the selected backend?
511/// Whether THIS build can bring a GPU up on THIS device: a compiled-in
512/// backend plus a live adapter. The mobile FFI exposes it so an app can
513/// tell "GPU off" from "GPU impossible" (a CPU-only .so ships no
514/// backend at all). Cached after the first call.
515pub fn backend_available() -> bool {
516    #[cfg(target_os = "macos")]
517    {
518        // The Metal path is always compiled on macOS.
519        true
520    }
521    #[cfg(all(feature = "gpu", not(target_os = "macos")))]
522    {
523        static AVAIL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
524        *AVAIL.get_or_init(crate::gpu_wgpu::adapter_probe)
525    }
526    #[cfg(all(not(feature = "gpu"), not(target_os = "macos")))]
527    {
528        false
529    }
530}
531
532pub fn enabled() -> bool {
533    backend() != Backend::None
534}
535
536/// Default-on condition for the wgpu whole-token graph: the wgpu
537/// backend on a DISCRETE adapter. NOT plain `enabled()` (macOS/Metal
538/// must not pay a per-token layer scan for a graph its backend
539/// refuses), and NOT integrated adapters: the graph's ~300 barriered
540/// dispatches per token are cheap on desktop immediate-mode GPUs but
541/// tiled mobile GPUs (Adreno/Mali) drain the pipeline at every barrier
542/// — field report: 0.2 tok/s on-graph vs 15 tok/s on the CPU. On
543/// integrated adapters the per-op probe path arbitrates each op class
544/// against the CPU instead; CMF_GPU_WGPU_GRAPH=1 still forces the
545/// graph anywhere.
546/// Is the wgpu backend active at all (any adapter)? Eligibility gate
547/// for the whole-token graph — whether it actually RUNS is decided by
548/// `wgpu_graph_default` (trusted on discrete) or the generation race.
549pub fn wgpu_active() -> bool {
550    #[cfg(feature = "gpu")]
551    {
552        matches!(backend(), Backend::Wgpu)
553    }
554    #[cfg(not(feature = "gpu"))]
555    {
556        false
557    }
558}
559
560pub fn wgpu_graph_default() -> bool {
561    #[cfg(feature = "gpu")]
562    {
563        matches!(backend(), Backend::Wgpu) && crate::gpu_wgpu::discrete_active()
564    }
565    #[cfg(not(feature = "gpu"))]
566    {
567        false
568    }
569}
570
571/// q8_row/q8_2f matvec, rows [row0, row0+rows). `xs` — prescaled by the θ-field.
572#[allow(clippy::too_many_arguments, unused_variables)]
573pub fn q8_matvec_range(
574    model: &Arc<CmfModel>,
575    idx: usize,
576    row0: usize,
577    row_scale: &[f32],
578    xs: &[f32],
579    rows: usize,
580    cols: usize,
581    out: &mut [f32],
582) -> bool {
583    match backend() {
584        #[cfg(target_os = "macos")]
585        Backend::Metal => {
586            crate::gpu_metal::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
587        }
588        #[cfg(feature = "gpu")]
589        Backend::Wgpu => {
590            crate::gpu_wgpu::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
591        }
592        Backend::None => false,
593    }
594}
595
596/// GEMM of a prefill batch: `pre` — prescaled inputs row-major [b, cols],
597/// out — row-major [b, rows].
598#[allow(clippy::too_many_arguments, unused_variables)]
599pub fn q8_matmat(
600    model: &Arc<CmfModel>,
601    idx: usize,
602    row_scale: &[f32],
603    pre: &[f32],
604    b: usize,
605    rows: usize,
606    cols: usize,
607    out: &mut [f32],
608) -> bool {
609    match backend() {
610        #[cfg(target_os = "macos")]
611        Backend::Metal => {
612            crate::gpu_metal::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out)
613        }
614        #[cfg(feature = "gpu")]
615        Backend::Wgpu => crate::gpu_wgpu::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out),
616        Backend::None => false,
617    }
618}
619
620/// q1 matvec: raw f32 activations, tile-embedded scales. Metal only
621/// for now (wgpu q1 WGSL is queued); false = CPU fallback.
622#[allow(unused_variables)]
623pub fn q1_matvec(
624    model: &Arc<CmfModel>,
625    idx: usize,
626    xs: &[f32],
627    rows: usize,
628    cols: usize,
629    out: &mut [f32],
630) -> bool {
631    match backend() {
632        #[cfg(target_os = "macos")]
633        Backend::Metal => crate::gpu_metal::q1_matvec(model, idx, xs, rows, cols, out),
634        #[cfg(feature = "gpu")]
635        Backend::Wgpu => crate::gpu_wgpu::q1_matvec(model, idx, xs, rows, cols, out),
636        Backend::None => false,
637    }
638}
639
640/// Whole attention sub-block on the wgpu token graph (drop-in for
641/// `qwen_attention`): normed hidden in, O-projection out, resident device
642/// K/V mirror. false = refusal / not the wgpu backend → CPU path.
643#[allow(clippy::too_many_arguments)]
644pub fn attn_dropin(
645    model: &Arc<CmfModel>,
646    kv_id: u64,
647    layer: usize,
648    normed: &[f32],
649    wq_idx: usize,
650    wk_idx: usize,
651    wv_idx: usize,
652    wo_idx: usize,
653    q_norm: Option<&[f32]>,
654    k_norm: Option<&[f32]>,
655    invf: &[f32],
656    nh: usize,
657    nkv: usize,
658    hd: usize,
659    rd: usize,
660    hidden: usize,
661    pos: usize,
662    cap: usize,
663    gemma: bool,
664    eps: f32,
665    cpu_k: &[Vec<f32>],
666    cpu_v: &[Vec<f32>],
667    out: &mut [f32],
668) -> bool {
669    match backend() {
670        #[cfg(feature = "gpu")]
671        Backend::Wgpu => crate::gpu_wgpu::attn_dropin_gpu(
672            model, kv_id, layer, normed, wq_idx, wk_idx, wv_idx, wo_idx, q_norm, k_norm, invf, nh,
673            nkv, hd, rd, hidden, pos, cap, gemma, eps, cpu_k, cpu_v, out,
674        ),
675        #[allow(unused_variables)]
676        _ => false,
677    }
678}
679
680/// One weight in the whole-token graph: tensor idx + a codec tag (0=q8_row,
681/// 1=q1, 2=q4_tiled, 3=q1t, 4=f32) + per-row scales (q8_row only) + the raw f32
682/// data (kind 4 only — small unquantized projections like GDN in_proj_a/b).
683pub struct GraphW<'a> {
684    pub idx: usize,
685    pub kind: u8,
686    pub row_scale: &'a [f32],
687    pub data: &'a [f32],
688}
689
690/// A layer's token-mixing op: standard attention or a GDN (linear-attention)
691/// block. The surrounding norms + SwiGLU FFN are common to both.
692pub enum GraphAttn<'a> {
693    Full {
694        wq: GraphW<'a>,
695        wk: GraphW<'a>,
696        wv: GraphW<'a>,
697        wo: GraphW<'a>,
698        q_norm: Option<&'a [f32]>,
699        k_norm: Option<&'a [f32]>,
700        /// (bq, bk, bv) attention biases (Qwen2). None ⇒ no bias.
701        bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
702        /// Qwen3.5 gated attention: wq emits 2·nh·hd (q||gate per head), the
703        /// attention output is scaled by sigmoid(gate) before the O projection.
704        output_gate: bool,
705        cpu_k: &'a [Vec<f32>],
706        cpu_v: &'a [Vec<f32>],
707    },
708    Gdn {
709        qkv: GraphW<'a>,
710        z: GraphW<'a>,
711        a: GraphW<'a>,
712        b: GraphW<'a>,
713        out: GraphW<'a>,
714        conv1d: &'a [f32],
715        a_log: &'a [f32],
716        dt_bias: &'a [f32],
717        norm: &'a [f32],
718        nv: usize,
719        nk: usize,
720        dk: usize,
721        dv: usize,
722        kk: usize,
723        /// CPU recurrent state `[ring (kk-1)·cdim | S nv·dk·dv]` — seeds the
724        /// device mirror when prefill ran on the host (o1 collection, CPU
725        /// fallback): a zero-initialized device state at decode is exactly
726        /// the "coherent but contextless" garble.
727        cpu_state: &'a [f32],
728    },
729}
730
731/// Per-layer weights for the whole-token wgpu graph.
732pub struct GraphLayer<'a> {
733    pub input_norm: &'a [f32],
734    pub attn: GraphAttn<'a>,
735    pub post_norm: &'a [f32],
736    pub ffn: GraphFfn<'a>,
737}
738
739/// The FFN of one graph layer: a dense SwiGLU trio, or a routed MoE —
740/// router + top-k selection + all selected experts run ON DEVICE (the
741/// routing decision depends on the resident hidden state, so a CPU
742/// round-trip per layer would forfeit the one-submit design).
743pub enum GraphFfn<'a> {
744    Dense {
745        gate: GraphW<'a>,
746        up: GraphW<'a>,
747        down: GraphW<'a>,
748    },
749    Moe {
750        /// Router logits weight (f32, kind 4) `[n_exp, hidden]`.
751        router: GraphW<'a>,
752        /// Shared-expert sigmoid gate (f32) `[1, hidden]`.
753        shared_gate: GraphW<'a>,
754        /// Per-expert q4_tiled directory indices `(gate, up, down)`;
755        /// the SHARED expert rides as the LAST entry — the select
756        /// kernel pins it with the sigmoid weight.
757        experts: Vec<(usize, usize, usize)>,
758        /// Routed experts (shared excluded).
759        n_exp: usize,
760        top_k: usize,
761        inter: usize,
762        norm_topk: bool,
763        /// Expert weight layout, uniform across the layer: `false` =
764        /// q4_tiled (18 B tiles, inline f16 scale), `true` = q4tp
765        /// (16 B nibbles + a per-row ladder plane). The two differ only
766        /// in where the scale comes from, so they share every kernel
767        /// but the weight-staging block.
768        q4tp: bool,
769    },
770}
771
772/// Whole-token decode graph on wgpu: the entire layer stack in ONE submit,
773/// hidden resident, one readback. Updates `h` in place. false = refusal.
774/// `loop_norm_at`: virtual layer indices after which `final_norm` is applied
775/// (Looped Transformer mid-stack norm). Empty for standard models.
776#[allow(clippy::too_many_arguments)]
777pub fn forward_token_graph(
778    model: &Arc<CmfModel>,
779    kv_id: u64,
780    layers: &[GraphLayer],
781    // Per-layer sealed o1 (Nystrom) state; Some = replace this layer's
782    // exact attention with the O(1) kernels. wgpu only.
783    o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
784    o1_epoch: u64,
785    invf: &[f32],
786    h: &mut [f32],
787    nh: usize,
788    nkv: usize,
789    hd: usize,
790    rd: usize,
791    hidden: usize,
792    inter: usize,
793    position: usize,
794    cap: usize,
795    gemma: bool,
796    eps: f32,
797    lm_head: Option<(&GraphW, usize)>,
798    final_norm: &[f32],
799    logits: &mut Vec<f32>,
800    loop_norm_at: &[usize],
801) -> bool {
802    match backend() {
803        #[cfg(feature = "gpu")]
804        Backend::Wgpu => crate::gpu_wgpu::forward_token_graph(
805            model,
806            kv_id,
807            layers,
808            o1,
809            o1_epoch,
810            invf,
811            h,
812            nh,
813            nkv,
814            hd,
815            rd,
816            hidden,
817            inter,
818            position,
819            cap,
820            gemma,
821            eps,
822            lm_head,
823            final_norm,
824            logits,
825            loop_norm_at,
826        ),
827        #[allow(unused_variables)]
828        _ => {
829            let _ = (lm_head, final_norm, logits, loop_norm_at);
830            false
831        }
832    }
833}
834
835/// Batched prefill: k contiguous positions through the whole graph in one submit
836/// (projections/FFN as GEMMs, attention/GDN looped over scratch). `h` is
837/// [k·hidden] in/out; `positions` len k. wgpu only.
838#[allow(clippy::too_many_arguments)]
839pub fn forward_batch_graph(
840    model: &Arc<CmfModel>,
841    kv_id: u64,
842    layers: &[GraphLayer],
843    invf: &[f32],
844    h: &mut [f32],
845    nh: usize,
846    nkv: usize,
847    hd: usize,
848    rd: usize,
849    hidden: usize,
850    inter: usize,
851    positions: &[usize],
852    cap: usize,
853    gemma: bool,
854    eps: f32,
855    k: usize,
856) -> bool {
857    match backend() {
858        #[cfg(feature = "gpu")]
859        Backend::Wgpu => crate::gpu_wgpu::forward_batch_graph(
860            model, kv_id, layers, invf, h, nh, nkv, hd, rd, hidden, inter, positions, cap, gemma,
861            eps, k,
862        ),
863        _ => false,
864    }
865}
866
867/// Drop the wgpu token graph's device K/V mirror for a pipeline.
868pub fn graph_kv_reset(_kv_id: u64) {
869    #[cfg(feature = "gpu")]
870    if backend() == Backend::Wgpu {
871        crate::gpu_wgpu::kv_mirror_reset(_kv_id);
872    }
873}
874
875/// Ternary (q1t) BASE matvec on the GPU — fills `out` with the base dot; the
876/// caller adds the sparse overlay on the CPU. Metal only for now (wgpu q1t not
877/// yet written → CPU fallback).
878pub fn q1t_matvec(
879    model: &Arc<CmfModel>,
880    idx: usize,
881    xs: &[f32],
882    rows: usize,
883    cols: usize,
884    out: &mut [f32],
885) -> bool {
886    match backend() {
887        #[cfg(target_os = "macos")]
888        Backend::Metal => {
889            if metal_q1t_enabled() {
890                crate::gpu_metal::q1t_matvec(model, idx, xs, rows, cols, out)
891            } else {
892                false
893            }
894        }
895        #[cfg(feature = "gpu")]
896        Backend::Wgpu => crate::gpu_wgpu::q1t_matvec(model, idx, xs, rows, cols, out),
897        Backend::None => false,
898    }
899}
900
901/// q4_block matvec on the GPU — wgpu only (Metal drives q4_block through the
902/// whole-token graph, not a standalone matvec).
903#[allow(unused_variables)]
904pub fn q4b_matvec(
905    model: &Arc<CmfModel>,
906    idx: usize,
907    xs: &[f32],
908    rows: usize,
909    cols: usize,
910    out: &mut [f32],
911) -> bool {
912    match backend() {
913        #[cfg(target_os = "macos")]
914        Backend::Metal => false,
915        #[cfg(feature = "gpu")]
916        Backend::Wgpu => crate::gpu_wgpu::q4b_matvec(model, idx, xs, rows, cols, out),
917        Backend::None => false,
918    }
919}
920
921/// q1t batched GEMM (prefill) — base + overlay on-device (Metal simdgroup or
922/// wgpu register-blocked).
923pub fn q1t_matmat(
924    model: &Arc<CmfModel>,
925    idx: usize,
926    xs: &[f32],
927    b: usize,
928    rows: usize,
929    cols: usize,
930    out: &mut [f32],
931) -> bool {
932    match backend() {
933        #[cfg(target_os = "macos")]
934        // Batched prefill and single-token decode are both enabled. On the
935        // real 14.8B Q1T model prefill PPL was within 0.3% of CPU (7.942 vs
936        // 7.966), and the alignment-safe decode kernel reached 3.52e-6 max_rel.
937        Backend::Metal => crate::gpu_metal::q1t_matmat(model, idx, xs, b, rows, cols, out),
938        #[cfg(feature = "gpu")]
939        Backend::Wgpu => crate::gpu_wgpu::q1t_matmat(model, idx, xs, b, rows, cols, out),
940        Backend::None => false,
941    }
942}
943
944/// Native Metal Q1T switch. Enabled by default after the byte-packed Q1T
945/// fields were changed to alignment-safe loads; keep an explicit emergency
946/// fallback for device/driver diagnostics.
947#[cfg(target_os = "macos")]
948pub(crate) fn metal_q1t_enabled() -> bool {
949    std::env::var("CMF_METAL_Q1T")
950        .map(|v| v != "0" && !v.eq_ignore_ascii_case("off"))
951        .unwrap_or(true)
952}
953
954/// Batched q1 GEMM (prefill). wgpu only — Metal has its own block path.
955pub fn q1_matmat(
956    model: &Arc<CmfModel>,
957    idx: usize,
958    xs: &[f32],
959    b: usize,
960    rows: usize,
961    cols: usize,
962    out: &mut [f32],
963) -> bool {
964    match backend() {
965        #[cfg(feature = "gpu")]
966        Backend::Wgpu => crate::gpu_wgpu::q1_matmat(model, idx, xs, b, rows, cols, out),
967        #[allow(unused_variables)]
968        _ => false,
969    }
970}
971
972/// Contention kill for the wide imagegen GEMM/FFN paths: one grossly
973/// slow op under a work-proportional budget (fair-device ops are
974/// ≤~100 ms even at 1024px) means another process owns the device —
975/// verdicts are per-process, so CPU for the rest of this one.
976static MM_KILL: AtomicBool = AtomicBool::new(false);
977pub(crate) fn mm_killed() -> bool {
978    MM_KILL.load(Ordering::Relaxed)
979}
980pub(crate) fn mm_kill() {
981    MM_KILL.store(true, Ordering::Relaxed);
982}
983
984/// Fused DiT SwiGLU FFN on the device: g=X·W1ᵀ, u=X·W3ᵀ, silu(g)·u,
985/// Causal chunk attention on the device: `b` queries against `s0 + b`
986/// cached keys. wgpu only — Metal's chunk graph keeps attention inside
987/// the resident block and never calls out.
988#[allow(unused_variables, clippy::too_many_arguments)]
989pub fn chunk_attend(
990    q: &[f32],
991    k: &[&[f32]],
992    v: &[&[f32]],
993    b: usize,
994    s0: usize,
995    nh: usize,
996    nkv: usize,
997    hd: usize,
998    scale: f32,
999    out: &mut [f32],
1000) -> bool {
1001    match backend() {
1002        #[cfg(feature = "gpu")]
1003        Backend::Wgpu => {
1004            crate::gpu_wgpu::chunk_attend(q, k, v, b, s0, nh, nkv, hd, scale, out)
1005        }
1006        #[allow(unreachable_patterns)]
1007        _ => false,
1008    }
1009}
1010
1011/// Fused QKV projection: one upload of the normed chunk, three GEMMs,
1012/// one readback of Q|K|V back to back. Metal has no twin yet — its
1013/// chunk graph keeps the whole layer resident and never surfaces QKV.
1014#[allow(unused_variables, clippy::too_many_arguments)]
1015pub fn q4t_qkv(
1016    model: &Arc<CmfModel>,
1017    wq: usize,
1018    wk: usize,
1019    wv: usize,
1020    xs: &[f32],
1021    b: usize,
1022    cols: usize,
1023    rq: usize,
1024    rk: usize,
1025    rv: usize,
1026    out: &mut [f32],
1027) -> bool {
1028    match backend() {
1029        #[cfg(feature = "gpu")]
1030        Backend::Wgpu => {
1031            crate::gpu_wgpu::q4t_qkv(model, wq, wk, wv, xs, b, cols, rq, rk, rv, out)
1032        }
1033        #[allow(unreachable_patterns)]
1034        _ => false,
1035    }
1036}
1037
1038/// y=·W2ᵀ — one command buffer, only X and Y cross the CPU boundary.
1039#[allow(unused_variables, clippy::too_many_arguments)]
1040pub fn q4tp_ffn(
1041    model: &Arc<CmfModel>,
1042    w1: usize,
1043    w3: usize,
1044    w2: usize,
1045    xs: &[f32],
1046    b: usize,
1047    hidden: usize,
1048    inter: usize,
1049    out: &mut [f32],
1050) -> bool {
1051    match backend() {
1052        #[cfg(target_os = "macos")]
1053        Backend::Metal => crate::gpu_metal::q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
1054        #[cfg(feature = "gpu")]
1055        // No wgpu twin yet: the fused DiT chain there is q4t-only, so a q4tp
1056        // model keeps the unfused wgpu path rather than a wrong kernel.
1057        Backend::Wgpu => false,
1058        #[allow(unreachable_patterns)]
1059        _ => false,
1060    }
1061}
1062
1063pub fn q4t_ffn(
1064    model: &Arc<CmfModel>,
1065    w1: usize,
1066    w3: usize,
1067    w2: usize,
1068    xs: &[f32],
1069    b: usize,
1070    hidden: usize,
1071    inter: usize,
1072    out: &mut [f32],
1073) -> bool {
1074    match backend() {
1075        #[cfg(target_os = "macos")]
1076        Backend::Metal => crate::gpu_metal::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
1077        #[cfg(feature = "gpu")]
1078        Backend::Wgpu => crate::gpu_wgpu::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
1079        #[allow(unreachable_patterns)]
1080        _ => false,
1081    }
1082}
1083
1084/// One whole modulated DiT block for `dit_block`: geometry, norm
1085/// weights, AdaLN scale/gate vectors (gates pre-tanh'd), a per-token
1086/// f32 RoPE cos/sin table, and the directory indices of the seven
1087/// q4t projections. `x` is in-out `[n, hidden]`.
1088pub struct DitBlockArgs<'a> {
1089    pub n: usize,
1090    pub hidden: usize,
1091    pub inter: usize,
1092    pub nh: usize,
1093    pub nkv: usize,
1094    pub hd: usize,
1095    pub eps: f32,
1096    pub rope_cos: &'a [f32],
1097    pub rope_sin: &'a [f32],
1098    pub norm1: &'a [f32],
1099    pub norm2: &'a [f32],
1100    pub ffn_norm1: &'a [f32],
1101    pub ffn_norm2: &'a [f32],
1102    pub norm_q: &'a [f32],
1103    pub norm_k: &'a [f32],
1104    pub s_msa: &'a [f32],
1105    pub gate_msa: &'a [f32],
1106    pub s_mlp: &'a [f32],
1107    pub gate_mlp: &'a [f32],
1108    pub wq: usize,
1109    pub wk: usize,
1110    pub wv: usize,
1111    pub wo: usize,
1112    pub w1: usize,
1113    pub w3: usize,
1114    pub w2: usize,
1115}
1116
1117/// One whole modulated DiT block on the device — norms, qkv, RoPE,
1118/// attention, residuals and the SwiGLU FFN in a single command
1119/// buffer; only `x` crosses the CPU boundary (in and out).
1120#[allow(unused_variables)]
1121pub fn dit_block(model: &Arc<CmfModel>, a: &DitBlockArgs, x: &mut [f32]) -> bool {
1122    match backend() {
1123        #[cfg(target_os = "macos")]
1124        Backend::Metal => crate::gpu_metal::dit_block(model, a, x),
1125        _ => false,
1126    }
1127}
1128
1129/// One VAE resnet block for `vae_resnet`: norm/conv weights and the
1130/// channel/shape geometry. `shortcut` is the 1×1 projection (w, b, k)
1131/// when in/out channels differ.
1132pub struct VaeResnetArgs<'a> {
1133    pub groups: usize,
1134    pub ic: usize,
1135    pub oc: usize,
1136    pub h: usize,
1137    pub w: usize,
1138    pub n1w: &'a [f32],
1139    pub n1b: &'a [f32],
1140    pub c1w: &'a [f32],
1141    pub c1b: &'a [f32],
1142    pub c1k: usize,
1143    pub n2w: &'a [f32],
1144    pub n2b: &'a [f32],
1145    pub c2w: &'a [f32],
1146    pub c2b: &'a [f32],
1147    pub c2k: usize,
1148    pub shortcut: Option<(&'a [f32], &'a [f32], usize)>,
1149}
1150
1151/// One whole VAE resnet block on the device (norm+silu → conv ×2 →
1152/// shortcut → add, one command buffer).
1153#[allow(unused_variables)]
1154pub fn vae_resnet(a: &VaeResnetArgs, x: &[f32], out: &mut [f32]) -> bool {
1155    match backend() {
1156        #[cfg(target_os = "macos")]
1157        Backend::Metal => crate::gpu_metal::vae_resnet(a, x, out),
1158        _ => false,
1159    }
1160}
1161
1162/// Nearest-2× upsample fused with the following conv — the small
1163/// pre-upsample image is what crosses the CPU boundary.
1164#[allow(unused_variables, clippy::too_many_arguments)]
1165pub fn vae_upsample_conv(
1166    w: &[f32],
1167    bias: &[f32],
1168    x: &[f32],
1169    ic: usize,
1170    oc: usize,
1171    h: usize,
1172    w_img: usize,
1173    k: usize,
1174    out: &mut [f32],
1175) -> bool {
1176    match backend() {
1177        #[cfg(target_os = "macos")]
1178        Backend::Metal => crate::gpu_metal::vae_upsample_conv(w, bias, x, ic, oc, h, w_img, k, out),
1179        _ => false,
1180    }
1181}
1182
1183/// VAE conv2d on the device (implicit GEMM — the CPU path pays for a
1184/// multi-GB im2col matrix at high resolutions).
1185#[allow(unused_variables, clippy::too_many_arguments)]
1186pub fn vae_conv2d(
1187    w: &[f32],
1188    bias: &[f32],
1189    x: &[f32],
1190    ic: usize,
1191    oc: usize,
1192    h: usize,
1193    w_img: usize,
1194    k: usize,
1195    out: &mut [f32],
1196) -> bool {
1197    match backend() {
1198        #[cfg(target_os = "macos")]
1199        Backend::Metal => crate::gpu_metal::vae_conv2d(w, bias, x, ic, oc, h, w_img, k, out),
1200        _ => false,
1201    }
1202}
1203
1204/// DiT full bidirectional attention on the device (all heads:
1205/// scores GEMM → row softmax → P·V → panel unstack, one command
1206/// buffer). Head-major inputs; out is [n, nh·hd].
1207#[allow(unused_variables, clippy::too_many_arguments)]
1208pub fn dit_attention(
1209    qh: &[f32],
1210    kh: &[f32],
1211    vh: &[f32],
1212    nh: usize,
1213    nkv: usize,
1214    n: usize,
1215    hd: usize,
1216    scale: f32,
1217    out: &mut [f32],
1218) -> bool {
1219    match backend() {
1220        #[cfg(target_os = "macos")]
1221        Backend::Metal => crate::gpu_metal::dit_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
1222        #[cfg(feature = "gpu")]
1223        Backend::Wgpu => crate::gpu_wgpu::dit_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
1224        #[allow(unreachable_patterns)]
1225        _ => false,
1226    }
1227}
1228
1229/// Batched q4t GEMM on the device (imagegen DiT prefill shapes).
1230/// Metal: q4t_mul_mm decodes the mmap-resident tiles inside the
1231/// GEMM's K loop. wgpu (Vulkan/DX12 → NVIDIA/AMD/Intel/Adreno/Mali):
1232/// the register-blocked WGSL twin, weights cached in VRAM.
1233#[allow(unused_variables)]
1234pub fn q4tp_matmat(
1235    model: &Arc<CmfModel>,
1236    idx: usize,
1237    xs: &[f32],
1238    b: usize,
1239    rows: usize,
1240    cols: usize,
1241    out: &mut [f32],
1242) -> bool {
1243    match backend() {
1244        #[cfg(target_os = "macos")]
1245        Backend::Metal => crate::gpu_metal::q4tp_matmat(model, idx, xs, b, rows, cols, out),
1246        #[cfg(feature = "gpu")]
1247        Backend::Wgpu => crate::gpu_wgpu::q4tp_matmat(model, idx, xs, b, rows, cols, out),
1248        #[allow(unreachable_patterns)]
1249        _ => false,
1250    }
1251}
1252
1253pub fn q4t_matmat(
1254    model: &Arc<CmfModel>,
1255    idx: usize,
1256    xs: &[f32],
1257    b: usize,
1258    rows: usize,
1259    cols: usize,
1260    out: &mut [f32],
1261) -> bool {
1262    match backend() {
1263        #[cfg(target_os = "macos")]
1264        Backend::Metal => crate::gpu_metal::q4t_matmat(model, idx, xs, b, rows, cols, out),
1265        #[cfg(feature = "gpu")]
1266        Backend::Wgpu => crate::gpu_wgpu::q4t_matmat(model, idx, xs, b, rows, cols, out),
1267        #[allow(unreachable_patterns)]
1268        _ => false,
1269    }
1270}
1271
1272/// Whole-block token-graph types re-exported from the Metal backend.
1273#[cfg(target_os = "macos")]
1274pub use crate::gpu_metal::{
1275    AttnDeviceParams, AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, GraphDims, TokenGraph, kv_mirror_drop,
1276    kv_mirror_read_last, kv_mirror_take_imp,
1277};
1278
1279/// A BLOCK of consecutive q1 GDN layers in one submission (Metal only).
1280#[cfg(target_os = "macos")]
1281pub fn gdn_block(
1282    model: &Arc<CmfModel>,
1283    layers: &[GdnGpuLayer],
1284    states: &mut [&mut [f32]],
1285    cfg: &GdnGpuCfg,
1286    h: &mut [f32],
1287) -> bool {
1288    match backend() {
1289        Backend::Metal => crate::gpu_metal::gdn_block(model, layers, states, cfg, h),
1290        _ => false,
1291    }
1292}
1293
1294/// A layer's MoE-FFN in one submission (amortizing the dispatch cost).
1295#[allow(unused_variables)]
1296pub fn moe_block(model: &Arc<CmfModel>, jobs: &[MoeJob], out: &mut [f32]) -> bool {
1297    match backend() {
1298        #[cfg(target_os = "macos")]
1299        Backend::Metal => crate::gpu_metal::moe_block(model, jobs, out),
1300        #[cfg(feature = "gpu")]
1301        Backend::Wgpu => crate::gpu_wgpu::moe_block(model, jobs, out),
1302        Backend::None => false,
1303    }
1304}
1305
1306/// Independent matvecs of one input in a single submission (GDN projections).
1307#[allow(unused_variables)]
1308pub fn matvec_batch(model: &Arc<CmfModel>, jobs: &[BatchJob], out: &mut [&mut [f32]]) -> bool {
1309    match backend() {
1310        #[cfg(target_os = "macos")]
1311        Backend::Metal => crate::gpu_metal::matvec_batch(model, jobs, out),
1312        #[cfg(feature = "gpu")]
1313        Backend::Wgpu => crate::gpu_wgpu::matvec_batch(model, jobs, out),
1314        Backend::None => false,
1315    }
1316}
1317
1318// ── Whole-token wgpu graph race (generation granularity) ─────────────
1319// On integrated/mobile adapters the graph is neither trusted nor banned
1320// a priori — it RACES the normal path: generations alternate arms (the
1321// normal path first — known-good UX — then the graph), per-token wall
1322// times accumulate per arm, and once both arms have enough steady
1323// samples the faster one wins for the process. Arm switches happen ONLY
1324// at generation boundaries (`kv_cache.clear()` resets state), so the
1325// device KV mirror and the CPU cache never diverge mid-sequence. The
1326// single exception is the first-token bail: the very first decode token
1327// of a graph generation may be discarded and recomputed on the CPU
1328// path (the prompt KV is CPU-owned at that point, so this is safe) —
1329// a tiled mobile GPU that drains its pipeline at every barrier turns
1330// the ~300-dispatch graph into seconds per token (field report: 0.2
1331// tok/s vs 15 on the CPU), and one token is all it takes to see that.
1332static GRAPH_RACE_STATE: AtomicU8 = AtomicU8::new(0); // 0 racing, 1 graph won, 2 normal won
1333static GRAPH_RACE_FLIP: AtomicU32 = AtomicU32::new(0);
1334static GRAPH_RACE_ARM_GRAPH: AtomicU8 = AtomicU8::new(0); // this generation's arm
1335static GRAPH_RACE_TOK: AtomicU32 = AtomicU32::new(0); // token index within the generation
1336static GRAPH_NS: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; // [normal, graph]
1337static GRAPH_N: [AtomicU32; 2] = [AtomicU32::new(0), AtomicU32::new(0)];
1338
1339/// Steady per-token samples per arm before the race decides.
1340const GRAPH_RACE_SAMPLES: u32 = 4;
1341
1342/// Called at every generation start (fresh KV). Applies a pending
1343/// verdict and picks this generation's arm while racing.
1344pub fn graph_race_begin_generation() {
1345    GRAPH_RACE_TOK.store(0, Ordering::Relaxed);
1346    if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
1347        return;
1348    }
1349    let (gn, cn) = (
1350        GRAPH_N[1].load(Ordering::Relaxed),
1351        GRAPH_N[0].load(Ordering::Relaxed),
1352    );
1353    if gn >= GRAPH_RACE_SAMPLES && cn >= GRAPH_RACE_SAMPLES {
1354        let g_avg = GRAPH_NS[1].load(Ordering::Relaxed) / gn as u64;
1355        let c_avg = GRAPH_NS[0].load(Ordering::Relaxed) / cn as u64;
1356        let verdict = if g_avg < c_avg { 1 } else { 2 };
1357        GRAPH_RACE_STATE.store(verdict, Ordering::Relaxed);
1358        tracing::info!(
1359            "wgpu graph race: graph {:.2} ms/tok vs normal {:.2} ms/tok -> {}",
1360            g_avg as f64 / 1e6,
1361            c_avg as f64 / 1e6,
1362            if verdict == 1 { "graph" } else { "normal path" }
1363        );
1364        return;
1365    }
1366    let flip = GRAPH_RACE_FLIP.fetch_add(1, Ordering::Relaxed);
1367    GRAPH_RACE_ARM_GRAPH.store((flip % 2 == 1) as u8, Ordering::Relaxed);
1368}
1369
1370/// Should this decode token try the graph? `trusted` (discrete adapter,
1371/// explicit env, or a GDN hybrid whose state lives on the device) skips
1372/// the race entirely.
1373pub fn graph_race_use_graph(trusted: bool) -> bool {
1374    if trusted {
1375        return true;
1376    }
1377    match GRAPH_RACE_STATE.load(Ordering::Relaxed) {
1378        1 => true,
1379        2 => false,
1380        _ => GRAPH_RACE_ARM_GRAPH.load(Ordering::Relaxed) == 1,
1381    }
1382}
1383
1384/// First decode token of a racing graph generation: hopeless already?
1385/// (>4x the normal path's per-token average AND over a second.) Settles
1386/// the race immediately; the caller discards the graph result and
1387/// recomputes this token on the normal path.
1388pub fn graph_race_first_token_hopeless(dur: std::time::Duration) -> bool {
1389    if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
1390        return false;
1391    }
1392    let first = GRAPH_RACE_TOK.load(Ordering::Relaxed) == 0;
1393    let cn = GRAPH_N[0].load(Ordering::Relaxed);
1394    if !first || cn == 0 {
1395        return false;
1396    }
1397    let c_avg = GRAPH_NS[0].load(Ordering::Relaxed) / cn as u64;
1398    let ns = dur.as_nanos() as u64;
1399    if ns > 1_000_000_000 && ns > 4 * c_avg {
1400        GRAPH_RACE_STATE.store(2, Ordering::Relaxed);
1401        tracing::info!(
1402            "wgpu graph race: first graph token {:.0} ms vs normal {:.2} ms/tok — hopeless, normal path wins",
1403            ns as f64 / 1e6,
1404            c_avg as f64 / 1e6
1405        );
1406        return true;
1407    }
1408    false
1409}
1410
1411/// Record one decode-token wall time for the racing arm. The first
1412/// token of each generation is discarded (KV-mirror upload / cold
1413/// caches on the graph arm; cold mmap on the normal arm).
1414pub fn graph_race_record(used_graph: bool, dur: std::time::Duration) {
1415    if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
1416        return;
1417    }
1418    let tok = GRAPH_RACE_TOK.fetch_add(1, Ordering::Relaxed);
1419    if tok == 0 {
1420        return;
1421    }
1422    let i = used_graph as usize;
1423    GRAPH_NS[i].fetch_add(dur.as_nanos() as u64, Ordering::Relaxed);
1424    GRAPH_N[i].fetch_add(1, Ordering::Relaxed);
1425}