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::{AtomicU32, AtomicU64, AtomicU8, 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    CPU_ONLY.with(|c| c.set(true));
37    let r = f();
38    CPU_ONLY.with(|c| c.set(false));
39    r
40}
41
42/// Backends: note a one-off cost (weight upload, buffer-cache fill) so
43/// the probe discards this sample.
44pub(crate) fn probe_note_cold() {
45    PROBE_COLD.with(|c| c.set(true));
46}
47
48/// Pipeline: mark the current layer (or −1 outside layers) for layer-split.
49pub fn set_layer(l: i64) {
50    CUR_LAYER.with(|c| c.set(l));
51}
52
53/// Parse `CMF_GPU_LAYERS` («0-19», «0,2,4», «0-9,30-39») once.
54/// None = no restriction (all layers on GPU). Garbage → also no restriction.
55fn layer_ranges() -> &'static Option<Vec<(i64, i64)>> {
56    static R: OnceLock<Option<Vec<(i64, i64)>>> = OnceLock::new();
57    R.get_or_init(|| {
58        let s = std::env::var("CMF_GPU_LAYERS").ok()?;
59        let mut v = Vec::new();
60        for part in s.split(',') {
61            let part = part.trim();
62            match part.split_once('-') {
63                Some((a, b)) => v.push((a.trim().parse().ok()?, b.trim().parse().ok()?)),
64                None => {
65                    let x: i64 = part.parse().ok()?;
66                    v.push((x, x));
67                }
68            }
69        }
70        Some(v)
71    })
72}
73
74fn layer_allowed() -> bool {
75    match layer_ranges() {
76        None => true,
77        Some(ranges) => {
78            let cur = CUR_LAYER.with(|c| c.get());
79            cur < 0 || ranges.iter().any(|(a, b)| cur >= *a && cur <= *b)
80        }
81    }
82}
83
84/// GPU allowed FOR THE CURRENT LAYER: backend is initialized AND the layer
85/// falls within `CMF_GPU_LAYERS` (GPU/CPU layer-split) AND we are not
86/// inside a `cpu_scope`. Op gates call this.
87pub fn enabled_here() -> bool {
88    !CPU_ONLY.with(|c| c.get()) && enabled() && layer_allowed()
89}
90
91// ── Runtime GPU-vs-CPU probe ────────────────────────────────────────────
92// CMF_GPU=1 does not TRUST that the device wins — it MEASURES. For each
93// op class the first calls alternate arms: GPU timed vs pure-CPU timed
94// (under cpu_scope). Cold GPU calls (weight upload / cache fill) are
95// discarded; after PROBE_SAMPLES clean samples per arm the faster arm is
96// chosen for the rest of the process. Rationale: submit+poll latency
97// differs by an order of magnitude across driver stacks (Metal/PCIe
98// ~3-4 ms, Vulkan/4090 ~0.3 ms) — a static threshold cannot know whether
99// per-op offload pays off HERE. CMF_GPU_PROBE=0 → always trust the GPU.
100
101/// GPU-eligible op classes, each with an independent probe.
102#[derive(Clone, Copy)]
103pub enum OpClass {
104    /// Whole FFN chain in one submission (dense / MoE block).
105    Ffn = 0,
106    /// Large hybrid CPU∥GPU matvec (lm_head class).
107    Matvec = 1,
108    /// Prefill GEMM (matmat).
109    Matmat = 2,
110    /// Batched matvecs of one input (QKV).
111    Batch = 3,
112}
113
114/// Probe verdict for one call.
115pub enum ProbeArm {
116    /// Run the GPU path (during probing: timed, recorded).
117    Gpu,
118    /// Probing: run the CPU path under `cpu_scope`, timed, recorded.
119    CpuTimed,
120    /// Decided: CPU won — run the CPU path (under `cpu_scope`).
121    Cpu,
122}
123
124/// Clean samples per arm before a class decides.
125const PROBE_SAMPLES: u32 = 6;
126
127struct Probe {
128    /// 0 = probing, 1 = GPU won, 2 = CPU won.
129    state: AtomicU8,
130    flip: AtomicU32,
131    gpu_ns: AtomicU64,
132    gpu_n: AtomicU32,
133    cpu_ns: AtomicU64,
134    cpu_n: AtomicU32,
135}
136
137impl Probe {
138    const fn new() -> Self {
139        Self {
140            state: AtomicU8::new(0),
141            flip: AtomicU32::new(0),
142            gpu_ns: AtomicU64::new(0),
143            gpu_n: AtomicU32::new(0),
144            cpu_ns: AtomicU64::new(0),
145            cpu_n: AtomicU32::new(0),
146        }
147    }
148}
149
150static PROBES: [Probe; 4] = [Probe::new(), Probe::new(), Probe::new(), Probe::new()];
151
152fn probe_on() -> bool {
153    static ON: OnceLock<bool> = OnceLock::new();
154    *ON.get_or_init(|| {
155        std::env::var("CMF_GPU_PROBE")
156            .map(|v| v != "0" && v != "off")
157            .unwrap_or(true)
158    })
159}
160
161/// q1 ops on the native Metal backend skip the probe entirely: the CPU
162/// q1 kernel is load-port-bound, the GPU one wins warm — and probe
163/// alternation itself cools the device between samples (measured: block
164/// times 5.8 ms warm vs 8.8 ms mixed). Other backends keep probing.
165pub fn q1_force() -> bool {
166    #[cfg(target_os = "macos")]
167    {
168        backend() == Backend::Metal
169    }
170    #[cfg(not(target_os = "macos"))]
171    {
172        false
173    }
174}
175
176/// Which arm should this GPU-eligible call take? Consult AFTER the
177/// eligibility gates (`enabled_here` / `min_rows`) so only real
178/// candidates alternate.
179pub fn probe_arm(c: OpClass) -> ProbeArm {
180    if !probe_on() {
181        return ProbeArm::Gpu;
182    }
183    let p = &PROBES[c as usize];
184    match p.state.load(Ordering::Relaxed) {
185        1 => ProbeArm::Gpu,
186        2 => ProbeArm::Cpu,
187        _ => {
188            PROBE_COLD.with(|f| f.set(false));
189            if p.flip.fetch_add(1, Ordering::Relaxed) % 2 == 0 {
190                ProbeArm::Gpu
191            } else {
192                ProbeArm::CpuTimed
193            }
194        }
195    }
196}
197
198/// Record a timed arm sample; on the `PROBE_SAMPLES`-th clean sample of
199/// BOTH arms the class decides for the rest of the process.
200pub fn probe_record(c: OpClass, gpu: bool, dur: std::time::Duration) {
201    let p = &PROBES[c as usize];
202    if p.state.load(Ordering::Relaxed) != 0 {
203        return;
204    }
205    if gpu && PROBE_COLD.with(|f| f.replace(false)) {
206        return; // one-off cost in this call — not a steady-state sample
207    }
208    let ns = dur.as_nanos().min(u64::MAX as u128) as u64;
209    if gpu {
210        p.gpu_ns.fetch_add(ns, Ordering::Relaxed);
211        p.gpu_n.fetch_add(1, Ordering::Relaxed);
212    } else {
213        p.cpu_ns.fetch_add(ns, Ordering::Relaxed);
214        p.cpu_n.fetch_add(1, Ordering::Relaxed);
215    }
216    let (gn, cn) = (p.gpu_n.load(Ordering::Relaxed), p.cpu_n.load(Ordering::Relaxed));
217    if gn >= 2 && cn >= 2 {
218        let g = p.gpu_ns.load(Ordering::Relaxed) as f64 / gn as f64;
219        let cp = p.cpu_ns.load(Ordering::Relaxed) as f64 / cn as f64;
220        // Early verdict on a ≥3× gap — no reason to keep feeding the
221        // losing arm; close races take the full sample count.
222        if (gn < PROBE_SAMPLES || cn < PROBE_SAMPLES) && g < cp * 3.0 && cp < g * 3.0 {
223            return;
224        }
225        let winner = if g <= cp { 1 } else { 2 };
226        if p
227            .state
228            .compare_exchange(0, winner, Ordering::Relaxed, Ordering::Relaxed)
229            .is_ok()
230        {
231            tracing::info!(
232                "gpu probe [{}]: gpu {:.2} ms vs cpu {:.2} ms per op → {}",
233                ["ffn", "matvec", "matmat", "qkv-batch"][c as usize],
234                g / 1e6,
235                cp / 1e6,
236                if winner == 1 { "gpu" } else { "cpu" },
237            );
238        }
239    }
240}
241
242/// Is the class still collecting samples? (Call sites use this to route
243/// cold-weight calls away from the GPU arm during probing.)
244pub fn probe_deciding(c: OpClass) -> bool {
245    probe_on() && PROBES[c as usize].state.load(Ordering::Relaxed) == 0
246}
247
248/// Probing helper: true — tensor `idx`'s quant weights are ALREADY
249/// device-resident (a clean GPU sample is possible now); false — they
250/// were not (the upload starts within the VRAM budget, so a later call
251/// finds them warm) or the tensor cannot go to the GPU at all. Keeps the
252/// probe from billing a full cold dispatch+readback to a sample it will
253/// discard anyway. The verdict needs only a couple of warm tensors, so
254/// probe-driven uploads are capped — the losing-GPU machine should not
255/// pay for uploading the whole layer stack it will never use; if the GPU
256/// wins, the rest uploads lazily on demand, in the same first-touch order.
257#[allow(unused_variables)]
258pub fn q8_resident_or_upload(model: &Arc<CmfModel>, idx: usize) -> bool {
259    static PROBE_UPLOADS: AtomicU32 = AtomicU32::new(0);
260    let may_upload = PROBE_UPLOADS.load(Ordering::Relaxed) < 4;
261    let resident = match backend() {
262        #[cfg(target_os = "macos")]
263        Backend::Metal => crate::gpu_metal::q8_resident_or_upload(model, idx, may_upload),
264        #[cfg(feature = "gpu")]
265        Backend::Wgpu => crate::gpu_wgpu::q8_resident_or_upload(model, idx, may_upload),
266        Backend::None => false,
267    };
268    if !resident && may_upload {
269        PROBE_UPLOADS.fetch_add(1, Ordering::Relaxed);
270    }
271    resident
272}
273
274/// Test hook: reset all probes to the undecided state.
275#[cfg(test)]
276pub(crate) fn probe_reset() {
277    for p in &PROBES {
278        p.state.store(0, Ordering::Relaxed);
279        p.flip.store(0, Ordering::Relaxed);
280        p.gpu_ns.store(0, Ordering::Relaxed);
281        p.gpu_n.store(0, Ordering::Relaxed);
282        p.cpu_ns.store(0, Ordering::Relaxed);
283        p.cpu_n.store(0, Ordering::Relaxed);
284    }
285}
286
287#[cfg(test)]
288mod probe_tests {
289    use super::*;
290    use std::time::Duration;
291
292    // One test fn: PROBES is process-global and probe_reset touches all
293    // classes — parallel test threads would race.
294    #[test]
295    fn probe_alternates_discards_cold_and_decides() {
296        probe_reset();
297        // Probing: arms alternate.
298        assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
299        assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::CpuTimed));
300
301        // A cold GPU sample (upload noted) must be discarded: feed a
302        // catastrophic cold sample, then clean fast-GPU samples — GPU
303        // wins only if the cold one did not count.
304        probe_note_cold();
305        probe_record(OpClass::Ffn, true, Duration::from_secs(1000));
306        for _ in 0..PROBE_SAMPLES {
307            probe_record(OpClass::Ffn, true, Duration::from_millis(1));
308            probe_record(OpClass::Ffn, false, Duration::from_millis(4));
309        }
310        assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
311
312        // The reverse: a class where the CPU arm is faster decides CPU.
313        for _ in 0..PROBE_SAMPLES {
314            probe_record(OpClass::Matmat, true, Duration::from_millis(4));
315            probe_record(OpClass::Matmat, false, Duration::from_millis(1));
316        }
317        assert!(matches!(probe_arm(OpClass::Matmat), ProbeArm::Cpu));
318
319        // cpu_scope: gates off inside, restored after.
320        cpu_scope(|| CPU_ONLY.with(|c| assert!(c.get())));
321        CPU_ONLY.with(|c| assert!(!c.get()));
322        probe_reset();
323    }
324}
325
326/// Default row threshold: the GPU takes only larger matrices (lm_head
327/// class). Below it, the dispatch/readback cost does not pay off on unified memory.
328pub const GPU_MIN_ROWS: usize = 65_536;
329
330/// Effective threshold: `CMF_GPU_MIN_ROWS` overrides. Defaults differ
331/// by device class: on a DISCRETE card VRAM bandwidth pays off even for
332/// FFN/QKV-class matrices (4096), on unified memory only lm_head-class
333/// is worth the dispatch/readback (65536). Field case behind this: a
334/// 35B model on an RTX 4090 saw ~0 offload because every layer matrix
335/// sat below the old universal 65536.
336pub fn min_rows() -> usize {
337    if let Some(v) = std::env::var("CMF_GPU_MIN_ROWS").ok().and_then(|v| v.parse().ok()) {
338        return v;
339    }
340    if discrete() {
341        4096
342    } else {
343        GPU_MIN_ROWS
344    }
345}
346
347/// Is the active backend a discrete card (PCIe VRAM)?
348pub fn discrete() -> bool {
349    match backend() {
350        #[cfg(feature = "gpu")]
351        Backend::Wgpu => crate::gpu_wgpu::is_discrete(),
352        #[cfg(target_os = "macos")]
353        Backend::Metal => false, // UMA by the init() guard
354        Backend::None => false,
355    }
356}
357
358/// A single MoE-FFN job (an expert with its own weight), executed in one
359/// submission: (rows, cols, idx, row_scale) for gate/up/down + prescaled
360/// inputs + the down θ-field + the blending weight.
361pub struct MoeJob<'a> {
362    pub gate: (usize, usize, usize, &'a [f32]),
363    pub up: (usize, usize, usize, &'a [f32]),
364    pub down: (usize, usize, usize, &'a [f32]),
365    pub xs_gate: Vec<f32>,
366    pub xs_up: Vec<f32>,
367    pub down_col: &'a [f32],
368    pub w: f32,
369    /// q1 trio: scales live inside the 6-byte tiles (row_scale slices
370    /// empty, xs raw f32). Backends without a q1 kernel refuse the job.
371    pub q1: bool,
372}
373
374/// A single independent batch matvec (GDN projections of one input).
375pub struct BatchJob<'a> {
376    pub idx: usize,
377    pub rows: usize,
378    pub cols: usize,
379    pub row_scale: &'a [f32],
380    pub xs: Vec<f32>,
381    /// q1 tensor: tile-embedded scales, raw f32 xs (see `MoeJob::q1`).
382    pub q1: bool,
383}
384
385#[derive(Clone, Copy, PartialEq, Eq)]
386enum Backend {
387    None,
388    #[cfg(target_os = "macos")]
389    Metal,
390    #[cfg(feature = "gpu")]
391    Wgpu,
392}
393
394fn backend() -> Backend {
395    #[cfg(feature = "gpu")]
396    if crate::gpu_wgpu::selected() {
397        return if crate::gpu_wgpu::enabled() { Backend::Wgpu } else { Backend::None };
398    }
399    #[cfg(target_os = "macos")]
400    if crate::gpu_metal::enabled() {
401        return Backend::Metal;
402    }
403    Backend::None
404}
405
406/// GPU enabled and initialized on the selected backend?
407pub fn enabled() -> bool {
408    backend() != Backend::None
409}
410
411/// q8_row/q8_2f matvec, rows [row0, row0+rows). `xs` — prescaled by the θ-field.
412#[allow(clippy::too_many_arguments, unused_variables)]
413pub fn q8_matvec_range(
414    model: &Arc<CmfModel>,
415    idx: usize,
416    row0: usize,
417    row_scale: &[f32],
418    xs: &[f32],
419    rows: usize,
420    cols: usize,
421    out: &mut [f32],
422) -> bool {
423    match backend() {
424        #[cfg(target_os = "macos")]
425        Backend::Metal => {
426            crate::gpu_metal::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
427        }
428        #[cfg(feature = "gpu")]
429        Backend::Wgpu => {
430            crate::gpu_wgpu::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
431        }
432        Backend::None => false,
433    }
434}
435
436/// GEMM of a prefill batch: `pre` — prescaled inputs row-major [b, cols],
437/// out — row-major [b, rows].
438#[allow(clippy::too_many_arguments, unused_variables)]
439pub fn q8_matmat(
440    model: &Arc<CmfModel>,
441    idx: usize,
442    row_scale: &[f32],
443    pre: &[f32],
444    b: usize,
445    rows: usize,
446    cols: usize,
447    out: &mut [f32],
448) -> bool {
449    match backend() {
450        #[cfg(target_os = "macos")]
451        Backend::Metal => {
452            crate::gpu_metal::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out)
453        }
454        #[cfg(feature = "gpu")]
455        Backend::Wgpu => {
456            crate::gpu_wgpu::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out)
457        }
458        Backend::None => false,
459    }
460}
461
462/// q1 matvec: raw f32 activations, tile-embedded scales. Metal only
463/// for now (wgpu q1 WGSL is queued); false = CPU fallback.
464#[allow(unused_variables)]
465pub fn q1_matvec(
466    model: &Arc<CmfModel>,
467    idx: usize,
468    xs: &[f32],
469    rows: usize,
470    cols: usize,
471    out: &mut [f32],
472) -> bool {
473    match backend() {
474        #[cfg(target_os = "macos")]
475        Backend::Metal => crate::gpu_metal::q1_matvec(model, idx, xs, rows, cols, out),
476        #[cfg(feature = "gpu")]
477        Backend::Wgpu => false,
478        Backend::None => false,
479    }
480}
481
482/// Whole-block GDN types re-exported from the Metal backend.
483#[cfg(target_os = "macos")]
484pub use crate::gpu_metal::{GdnGpuCfg, GdnGpuLayer};
485
486/// A BLOCK of consecutive q1 GDN layers in one submission (Metal only).
487#[cfg(target_os = "macos")]
488pub fn gdn_block(
489    model: &Arc<CmfModel>,
490    layers: &[GdnGpuLayer],
491    states: &mut [&mut [f32]],
492    cfg: &GdnGpuCfg,
493    h: &mut [f32],
494) -> bool {
495    match backend() {
496        Backend::Metal => crate::gpu_metal::gdn_block(model, layers, states, cfg, h),
497        _ => false,
498    }
499}
500
501/// A layer's MoE-FFN in one submission (amortizing the dispatch cost).
502#[allow(unused_variables)]
503pub fn moe_block(model: &Arc<CmfModel>, jobs: &[MoeJob], out: &mut [f32]) -> bool {
504    match backend() {
505        #[cfg(target_os = "macos")]
506        Backend::Metal => crate::gpu_metal::moe_block(model, jobs, out),
507        #[cfg(feature = "gpu")]
508        Backend::Wgpu => crate::gpu_wgpu::moe_block(model, jobs, out),
509        Backend::None => false,
510    }
511}
512
513/// Independent matvecs of one input in a single submission (GDN projections).
514#[allow(unused_variables)]
515pub fn matvec_batch(model: &Arc<CmfModel>, jobs: &[BatchJob], out: &mut [&mut [f32]]) -> bool {
516    match backend() {
517        #[cfg(target_os = "macos")]
518        Backend::Metal => crate::gpu_metal::matvec_batch(model, jobs, out),
519        #[cfg(feature = "gpu")]
520        Backend::Wgpu => crate::gpu_wgpu::matvec_batch(model, jobs, out),
521        Backend::None => false,
522    }
523}