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
18/// Packed, f32-only Embryo model consumed by the resident Vulkan graph.
19///
20/// This is deliberately a separate representation from `CmfModel`: the
21/// Embryo graph owns one contiguous device copy and never dereferences the
22/// mmap or asks the ordinary per-op residency path for a tensor.  `meta`
23/// contains byte-free element offsets into `weights`; `UINT_MAX` marks an
24/// absent optional matrix.  The builder lives in `pipeline.rs`, where the
25/// architecture-specific weight types are visible.
26pub struct EmbryoGraphModel {
27    pub id: u64,
28    pub hidden: usize,
29    pub intermediate: usize,
30    pub vocab: usize,
31    pub layers: usize,
32    pub phase_heads: usize,
33    pub nphase: usize,
34    pub phase_dv: usize,
35    pub anchor_q_heads: usize,
36    pub anchor_kv_heads: usize,
37    pub anchor_head_dim: usize,
38    pub rotary_dim: usize,
39    pub max_seq: usize,
40    pub cluster_count: usize,
41    pub cluster_size: usize,
42    pub phase_state_len: usize,
43    pub state_stride: usize,
44    pub kv_stride: usize,
45    pub norm_gemma: bool,
46    pub phase_mass: f32,
47    pub weights: Vec<f32>,
48    pub meta: Vec<u32>,
49    pub lm_head: Vec<f32>,
50    pub clusters: Vec<f32>,
51    pub final_norm: Vec<f32>,
52    pub inv_freq: Vec<f32>,
53    /// Natively bounded anchors (`swa_sink_v1`): every anchor layer owns a
54    /// ring of `anchor_window` raw keys/values instead of a `max_seq` KV
55    /// plane, so `kv_stride` is the ring size, `kv_layers` counts the
56    /// anchors, and no position cap applies (the operator has none).
57    pub bounded: bool,
58    /// Layers that own a KV/ring slot of `kv_stride` f32 (all layers for
59    /// the legacy full anchor — offsets are `layer·kv_stride` — or the
60    /// bounded anchors only).
61    pub kv_layers: usize,
62    /// Recurrent (phase or GDN) layers — the state buffer holds one
63    /// `state_stride` per such layer; anchors own none.
64    pub state_layers: usize,
65    pub anchor_window: usize,
66    pub anchor_sink: usize,
67    /// vmf_phase mixer layers (kind 0/1) in the stack.
68    pub phase_layers: usize,
69    /// GatedDeltaNet mixer layers (kind 4) in the stack; their geometry
70    /// is `gdn_heads` (nv), `gdn_k_heads` (nk), `gdn_dk`, `gdn_dv`,
71    /// `gdn_kk` (conv taps) — header words 24..29 of `meta`.
72    pub gdn_layers: usize,
73    pub gdn_heads: usize,
74    pub gdn_k_heads: usize,
75    pub gdn_dk: usize,
76    pub gdn_dv: usize,
77    pub gdn_kk: usize,
78}
79
80impl EmbryoGraphModel {
81    /// Fused q/k/v projection width of the GDN mixer (`2·nk·dk + nv·dv`).
82    pub fn gdn_c_dim(&self) -> usize {
83        2 * self.gdn_k_heads * self.gdn_dk + self.gdn_heads * self.gdn_dv
84    }
85}
86
87/// Words in the resident graph's `meta` header before the per-layer
88/// records (64 words each). Shared by the host packer and the encoder.
89pub const EMBRYO_META_HEADER: usize = 32;
90
91/// Positions one chunked-prefill submit of the resident Embryo graph
92/// covers (the shader's `CMAX`; the chunk window of the scratch buffer is
93/// sized by it).
94pub const EMBRYO_CHUNK_MAX: usize = 64;
95
96/// `n` contiguous prompt positions (`rows` = n × hidden embeddings from
97/// `position`) through the resident Embryo graph in one submit; logits of
98/// the last position. False = refused before any device work (the caller
99/// keeps the per-position path), or the sequence went cold.
100pub fn forward_embryo_graph_chunk(
101    model: &Arc<EmbryoGraphModel>,
102    kv_id: u64,
103    rows: &[f32],
104    position: usize,
105    n: usize,
106    logits: &mut Vec<f32>,
107) -> bool {
108    #[cfg(feature = "gpu")]
109    if backend() == Backend::Wgpu {
110        return crate::gpu_wgpu::forward_embryo_graph_chunk(model, kv_id, rows, position, n, logits);
111    }
112    let _ = (model, kv_id, rows, position, n, logits);
113    false
114}
115
116/// Bytes the resident Embryo graph holds on the device for a sequence:
117/// `(recurrent state, anchor KV/ring)`. None when the sequence has no
118/// device image (host path, or not started yet). This is the measured
119/// long-context claim of the resident path — a bounded genome reports
120/// the same two numbers at every context depth.
121pub fn embryo_device_state_bytes(kv_id: u64) -> Option<(u64, u64)> {
122    #[cfg(feature = "gpu")]
123    if backend() == Backend::Wgpu {
124        return crate::gpu_wgpu::embryo_device_state_bytes(kv_id);
125    }
126    let _ = kv_id;
127    None
128}
129
130/// Does this directory entry count as WEIGHT in the device placement
131/// heuristics (layer prefix, live-weight budget, `serve` replicas vs
132/// split)? On a genome file only the trunk does: skill tensors replace
133/// trunk tensors of the same shape inside their own lane, so counting
134/// them would give the backbone of F1 another GPU prefix than F0's
135/// (NF-7). Other files keep the historical whole-directory count.
136pub fn counts_as_placement_weight(model: &CmfModel, name: &str) -> bool {
137    model.header.genome.is_none() || cortiq_core::knowledge::is_trunk_tensor(name)
138}
139
140/// Weight bytes the placement heuristics budget for `model`: the trunk's
141/// payload on a genome file ([`counts_as_placement_weight`]), the whole
142/// mapped file otherwise (the historical measure).
143pub fn placement_weight_bytes(model: &CmfModel) -> u64 {
144    if model.header.genome.is_none() {
145        return model.primary_bytes().len() as u64;
146    }
147    model
148        .tensors
149        .iter()
150        .filter(|t| counts_as_placement_weight(model, &t.name))
151        .map(|t| t.nbytes)
152        .sum()
153}
154
155/// Next position of the resident Embryo sequence `kv_id` (`Some(n)` = the
156/// device holds positions `0..n` of it), `None` when the device holds no
157/// initialized image of that sequence — the host owns it (or none began).
158pub fn embryo_device_next_position(kv_id: u64) -> Option<usize> {
159    #[cfg(feature = "gpu")]
160    if backend() == Backend::Wgpu {
161        return crate::gpu_wgpu::embryo_device_next_position(kv_id);
162    }
163    let _ = kv_id;
164    None
165}
166
167thread_local! {
168    /// Index of the current forward layer (−1 = outside a numbered layer:
169    /// lm_head/embed — always allowed). The pipeline sets it before
170    /// each layer so that the GPU/CPU layer-split works.
171    static CUR_LAYER: Cell<i64> = const { Cell::new(-1) };
172    /// Inside `cpu_scope` every GPU gate reports disabled: the timed CPU
173    /// arm of a probe (and a class that lost its probe) must run PURE
174    /// CPU, or inner per-op hooks would re-enter the GPU and poison the
175    /// comparison.
176    static CPU_ONLY: Cell<bool> = const { Cell::new(false) };
177    /// "This op paid a one-off cost" (weight upload / first pipeline
178    /// build): backends set it, `probe_record` discards the sample so
179    /// only steady-state timings compete.
180    static PROBE_COLD: Cell<bool> = const { Cell::new(false) };
181}
182
183/// RAII form of `cpu_scope`, used when a device-prefix graph hands a whole
184/// remainder of the forward pass to the host. Without a guard around that
185/// tail, its ordinary per-op hooks re-entered the GPU and streamed the rest of
186/// an over-size model through the residency arena, defeating the prefix's VRAM
187/// bound at the driver-allocation level.
188pub struct CpuScopeGuard(bool);
189
190impl Drop for CpuScopeGuard {
191    fn drop(&mut self) {
192        CPU_ONLY.with(|c| c.set(self.0));
193    }
194}
195
196pub fn enter_cpu_scope() -> CpuScopeGuard {
197    let previous = CPU_ONLY.with(|c| c.replace(true));
198    CpuScopeGuard(previous)
199}
200
201/// Run `f` with the GPU gates off on this thread (pure-CPU arm).
202pub fn cpu_scope<R>(f: impl FnOnce() -> R) -> R {
203    let _restore = enter_cpu_scope();
204    f()
205}
206
207/// Capture CPU-only placement before dispatching whole operators to workers.
208/// `cpu_scope` is thread-local, while a MoE panel worker calls QTensor again;
209/// without inheritance, which expert happened to land on the caller changed
210/// its precision/backend from run to run.
211pub(crate) fn inherit_cpu_scope() -> impl Fn() -> Option<CpuScopeGuard> + Copy {
212    let on = CPU_ONLY.get();
213    move || on.then(enter_cpu_scope)
214}
215
216/// Backends: name the device once at init. The probe cache is keyed by
217/// it, because a verdict is a property of THIS silicon and nothing else.
218/// First writer wins: a process runs one backend, and on the rare host
219/// where two initialize, the one that came up first is the one in use.
220pub fn probe_set_device(label: &str) {
221    let _ = DEVICE_LABEL.set(label.to_string());
222}
223
224fn device_label() -> &'static str {
225    DEVICE_LABEL.get().map(String::as_str).unwrap_or("unknown")
226}
227
228static DEVICE_LABEL: std::sync::OnceLock<String> = std::sync::OnceLock::new();
229
230/// Somewhere this process may write small caches.
231///
232/// `std::env::temp_dir()` is NOT that place on Android: with no `TMPDIR`
233/// it answers `/tmp`, which does not exist in an app sandbox, and every
234/// write fails silently — measured, after the pipeline cache appeared to
235/// work in a shell (where `TMPDIR=/data/local/tmp`) and did nothing at
236/// all in the app. The loader points this at the model's own directory,
237/// which is somewhere the caller already writes.
238static CACHE_DIR: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();
239
240/// Loader: name a directory this process can write to. First call wins.
241pub fn set_cache_dir(dir: std::path::PathBuf) {
242    let _ = CACHE_DIR.set(dir);
243}
244
245/// Same directory, for the backends.
246pub fn cache_dir_pub() -> std::path::PathBuf {
247    cache_dir()
248}
249
250fn cache_dir() -> std::path::PathBuf {
251    if let Some(d) = CACHE_DIR.get() {
252        return d.clone();
253    }
254    match std::env::var_os("TMPDIR") {
255        Some(t) => std::path::PathBuf::from(t),
256        None => std::env::temp_dir(),
257    }
258}
259
260/// Where decided verdicts are remembered between runs. `CMF_PROBE_CACHE`
261/// overrides the path; `0` disables the cache entirely.
262fn probe_cache_path() -> Option<std::path::PathBuf> {
263    match std::env::var("CMF_PROBE_CACHE") {
264        Ok(v) if v == "0" => None,
265        Ok(v) => Some(std::path::PathBuf::from(v)),
266        Err(_) => Some(cache_dir().join("cortiq-gpu-probe.tsv")),
267    }
268}
269
270/// One line per decided class: `version \t device \t class \t winner`.
271/// A different engine build or a different device simply does not match,
272/// so a stale file is inert rather than wrong.
273fn probe_cache_key_named(class: &str) -> String {
274    format!(
275        "{}\t{}\t{}",
276        env!("CARGO_PKG_VERSION"),
277        device_label(),
278        class
279    )
280}
281
282const CLASS_NAMES: [&str; 8] = [
283    "ffn",
284    "matvec",
285    "matmat",
286    "qkv-batch",
287    "matmat-wide",
288    "lm-head",
289    "gemm-nt",
290    // MoE has a different residency policy from a dense FFN. In
291    // particular, an out-of-core Metal MoE block can become viable after a
292    // dense `ffn` probe has (correctly) decided that ordinary per-op FFNs
293    // lose. Never let that remembered verdict suppress the separate path.
294    "moe",
295];
296
297/// Adopt every verdict this device already reached in an earlier run.
298///
299/// Probing is not cheap and it is not free of consequences: on a
300/// Snapdragon 778G the three deciding classes took **three minutes of
301/// wall clock** before the first token, every process, and in the phone
302/// app that was the whole first answer — 209.6 s for 25 tokens against
303/// 10.5 s on the CPU path. The verdict itself was the same every time.
304/// Paying to rediscover it is the defect; the answer is to write it down.
305fn probe_cache_load() {
306    static ONCE: std::sync::Once = std::sync::Once::new();
307    ONCE.call_once(|| {
308        let Some(path) = probe_cache_path() else {
309            return;
310        };
311        // Unit tests share this process and its default cache path; a
312        // verdict left by an earlier run would decide a class before the
313        // arbitration tests get to watch it alternate. Tests that mean to
314        // exercise the cache point `CMF_PROBE_CACHE` at their own file.
315        if cfg!(test) && std::env::var("CMF_PROBE_CACHE").is_err() {
316            return;
317        }
318        let Ok(text) = std::fs::read_to_string(&path) else {
319            return;
320        };
321        probe_cache_adopt(&text);
322    });
323}
324
325/// Apply verdicts from a cache file's text. Split out from the file
326/// reading so the adoption rule — including which lines must be IGNORED
327/// — is testable without a filesystem.
328fn probe_cache_adopt(text: &str) {
329    for line in text.lines() {
330        let Some((key, verdict)) = line.rsplit_once('\t') else {
331            continue;
332        };
333        let winner = match verdict.trim() {
334            "gpu" => 1u8,
335            "cpu" => 2u8,
336            _ => continue,
337        };
338        for (i, name) in CLASS_NAMES.iter().enumerate() {
339            if probe_cache_key_named(name) == key {
340                let _ = PROBES[i].state.compare_exchange(
341                    0,
342                    winner,
343                    Ordering::Relaxed,
344                    Ordering::Relaxed,
345                );
346                tracing::debug!("gpu probe [{name}]: remembered → {verdict}");
347            }
348        }
349    }
350}
351
352/// Remember a verdict for the next run. Best-effort: a read-only cache
353/// directory costs a re-probe, never a failure.
354fn probe_cache_store(c: OpClass, winner: u8) {
355    let Some(path) = probe_cache_path() else {
356        return;
357    };
358    let line = format!(
359        "{}\t{}\n",
360        probe_cache_key_named(CLASS_NAMES[c as usize]),
361        if winner == 1 { "gpu" } else { "cpu" }
362    );
363    use std::io::Write;
364    if let Ok(mut f) = std::fs::OpenOptions::new()
365        .create(true)
366        .append(true)
367        .open(&path)
368    {
369        let _ = f.write_all(line.as_bytes());
370    }
371}
372
373/// Backends: note a one-off cost (weight upload, buffer-cache fill) so
374/// the probe discards this sample.
375/// Every buffer creation anywhere bumps this; the graph's bind-group
376/// cache treats any cold event as total invalidation — a stale bind
377/// group is silent corruption, a cleared cache is one re-encoded token.
378pub fn cold_epoch() -> u64 {
379    COLD_EPOCH.load(std::sync::atomic::Ordering::Relaxed)
380}
381static COLD_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
382
383pub(crate) fn probe_note_cold() {
384    COLD_EPOCH.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
385    PROBE_COLD.with(|c| c.set(true));
386}
387
388/// Peek the cold flag without consuming it (`probe_record` consumes).
389/// Contention heuristics use this: a slow COLD op is a one-off build
390/// cost, not evidence the device is busy.
391pub(crate) fn probe_was_cold() -> bool {
392    PROBE_COLD.with(|c| c.get())
393}
394
395/// Pipeline: mark the current layer (or −1 outside layers) for layer-split.
396pub fn set_layer(l: i64) {
397    CUR_LAYER.with(|c| c.set(l));
398}
399
400/// The layer `set_layer` last marked on this thread (−1 outside layers).
401pub fn cur_layer() -> i64 {
402    CUR_LAYER.with(|c| c.get())
403}
404
405/// Capacity-derived layer prefix for per-op walks. The explicit
406/// `CMF_GPU_LAYERS` override is handled by the backend and takes precedence.
407pub fn automatic_layer_prefix(
408    model: &Arc<CmfModel>,
409    num_layers: usize,
410    physical_layers: usize,
411) -> Option<usize> {
412    match backend() {
413        #[cfg(feature = "gpu")]
414        Backend::Wgpu => {
415            crate::gpu_wgpu::automatic_layer_prefix(model, num_layers, physical_layers)
416        }
417        _ => None,
418    }
419}
420
421/// Parse `CMF_GPU_LAYERS` («0-19», «0,2,4», «0-9,30-39») once.
422/// None = no restriction (all layers on GPU). Garbage → also no restriction.
423fn layer_ranges() -> &'static Option<Vec<(i64, i64)>> {
424    static R: OnceLock<Option<Vec<(i64, i64)>>> = OnceLock::new();
425    R.get_or_init(|| {
426        let s = std::env::var("CMF_GPU_LAYERS").ok()?;
427        let mut v = Vec::new();
428        for part in s.split(',') {
429            let part = part.trim();
430            match part.split_once('-') {
431                Some((a, b)) => v.push((a.trim().parse().ok()?, b.trim().parse().ok()?)),
432                None => {
433                    let x: i64 = part.parse().ok()?;
434                    v.push((x, x));
435                }
436            }
437        }
438        Some(v)
439    })
440}
441
442fn layer_allowed() -> bool {
443    match layer_ranges() {
444        None => true,
445        Some(ranges) => {
446            let cur = CUR_LAYER.with(|c| c.get());
447            cur < 0 || ranges.iter().any(|(a, b)| cur >= *a && cur <= *b)
448        }
449    }
450}
451
452/// GPU allowed FOR THE CURRENT LAYER: backend is initialized AND the layer
453/// falls within `CMF_GPU_LAYERS` (GPU/CPU layer-split) AND we are not
454/// inside a `cpu_scope`. Op gates call this.
455pub fn enabled_here() -> bool {
456    !CPU_ONLY.with(|c| c.get()) && enabled() && layer_allowed()
457}
458
459/// Descriptor-aware q2tp Vulkan kernels are kept behind an explicit opt-in
460/// until the Prism full-graph/resident-weight path has a coherent generation
461/// gate.  `CMF_GPU=1` alone must not silently turn synchronous per-op
462/// readbacks into the default model path; callers and validation tests can
463/// request the measured kernels with `CMF_Q2TP_GPU=1`.
464pub fn q2tp_gpu_opt_in() -> bool {
465    std::env::var("CMF_Q2TP_GPU").as_deref() == Ok("1")
466}
467
468// ── Runtime GPU-vs-CPU probe ────────────────────────────────────────────
469// CMF_GPU=1 does not TRUST that the device wins — it MEASURES. For each
470// op class the first calls alternate arms: GPU timed vs pure-CPU timed
471// (under cpu_scope). Cold GPU calls (weight upload / cache fill) are
472// discarded; after PROBE_SAMPLES clean samples per arm the faster arm is
473// chosen for the rest of the process. Rationale: submit+poll latency
474// differs by an order of magnitude across driver stacks (Metal/PCIe
475// ~3-4 ms, Vulkan/4090 ~0.3 ms) — a static threshold cannot know whether
476// per-op offload pays off HERE. CMF_GPU_PROBE=0 → always trust the GPU.
477
478/// GPU-eligible op classes, each with an independent probe.
479#[derive(Clone, Copy)]
480pub enum OpClass {
481    /// Whole FFN chain in one submission (dense / MoE block).
482    Ffn = 0,
483    /// Large hybrid CPU∥GPU matvec (lm_head class).
484    Matvec = 1,
485    /// Prefill GEMM (matmat).
486    Matmat = 2,
487    /// Batched matvecs of one input (QKV).
488    Batch = 3,
489    /// Prefill GEMM at image-diffusion widths (b ≥ 128). Probed apart
490    /// from `Matmat`: one imagegen process runs BOTH populations
491    /// (prompt encode b≈40 where the GPU wins big, DiT b≥256 where
492    /// the CPU AMX arm is competitive) — a single shared verdict locks
493    /// the wrong arm for whichever population samples second.
494    MatmatWide = 4,
495    /// The lm_head itself, apart from the merely-large matvecs. Same
496    /// reasoning as `MatmatWide`, and DeepSeek-V4 is where it bit: its
497    /// attention projections are 37M weights and its head is 529M, so
498    /// the projections' verdict — CPU, honestly measured at 0.19 ms —
499    /// decided for a matvec fourteen times their size that took 11 ms
500    /// a token on the host.
501    MatvecHead = 5,
502    /// The blocked f32 GEMM (`fcd_ops::gemm_nt`): attention's QKᵀ and
503    /// AV, and the VAE decoders' projections. It used to take every job
504    /// over 4 M MACs on sight, with no CPU arm to lose to — which on
505    /// the MiniMax-H3 video decoder was three times SLOWER than the
506    /// host it displaced. Its population is per-head slices, nothing
507    /// like the weight GEMMs above, so it probes on its own.
508    GemmNt = 6,
509    /// A host-routed MoE block. Kept separate from [`Self::Ffn`] because
510    /// its selected-weight pager has different memory and latency costs.
511    Moe = 7,
512}
513
514/// Which probe a large matvec belongs to. The head is an order of
515/// magnitude bigger than anything else that reaches this gate, and the
516/// two populations do not have the same answer.
517pub fn matvec_class(rows: usize, cols: usize) -> OpClass {
518    if rows * cols >= 67_108_864 {
519        OpClass::MatvecHead
520    } else {
521        OpClass::Matvec
522    }
523}
524
525/// Probe verdict for one call.
526pub enum ProbeArm {
527    /// Run the GPU path (during probing: timed, recorded).
528    Gpu,
529    /// Probing: run the CPU path under `cpu_scope`, timed, recorded.
530    CpuTimed,
531    /// Decided: CPU won — run the CPU path (under `cpu_scope`).
532    Cpu,
533}
534
535/// Clean samples per arm before a class decides.
536const PROBE_SAMPLES: u32 = 6;
537
538/// Declines before a class gives the work to the host for good. High
539/// enough that a transient refusal — an unsealed state during prefill, a
540/// shape the kernel skips this once — cannot settle the question.
541const PROBE_DECLINE_LIMIT: u32 = 16;
542
543/// Device samples discarded before any count — see `Probe::gpu_burn`.
544const PROBE_WARMUP: u32 = 1;
545
546struct Probe {
547    /// 0 = probing, 1 = GPU won, 2 = CPU won.
548    state: AtomicU8,
549    flip: AtomicU32,
550    gpu_ns: AtomicU64,
551    gpu_n: AtomicU32,
552    /// Times the device arm was chosen and the device DECLINED.
553    ///
554    /// A decline carries no timing, so nothing is recorded — and a class
555    /// whose device path always refuses therefore never reaches a
556    /// verdict, alternates arms forever, and pays a failed device
557    /// attempt on half of every token's calls. Measured on an M4 with
558    /// LFM2.5-2.6B: `ffn` was still undecided after 9000 calls, and a
559    /// token cost 83.55 ms against 41.85 with the device off — twice the
560    /// price for work the host did anyway.
561    declines: AtomicU32,
562    /// GPU samples still to discard as warm-up.
563    ///
564    /// The cold flag catches buffer and weight uploads, but a compute
565    /// pipeline is compiled on first use and not every creation site
566    /// raises it — the wgpu path has 21 pipeline creations against 12
567    /// cold notes. One uncaught shader compile is enough to lose a
568    /// class for the whole process: `gemm-nt` on an A100 was recorded at
569    /// 117.01 ms against the host's 3.19 and sent to the CPU, which
570    /// parked a 27B bake on 2.6 cores with the card idle. The decision
571    /// already uses each arm's BEST sample, so discarding the first
572    /// GPU sample costs one extra round trip and removes the whole
573    /// class of first-call artefacts.
574    gpu_burn: AtomicU32,
575    cpu_ns: AtomicU64,
576    cpu_n: AtomicU32,
577    /// Best (minimum) sample per arm. The DECISION compares these:
578    /// means are poisoned by one-off cold costs the cold-flag cannot
579    /// see — e.g. the CPU arm's first mmap-cold expert matvec page
580    /// faults its weights in and reads 3× its steady state, which
581    /// locked the GPU arm on a 35B MoE at a 4× real-world loss. The
582    /// minimum is each arm's honest steady-state pace.
583    gpu_min: AtomicU64,
584    cpu_min: AtomicU64,
585}
586
587impl Probe {
588    const fn new() -> Self {
589        Self {
590            state: AtomicU8::new(0),
591            flip: AtomicU32::new(0),
592            gpu_ns: AtomicU64::new(0),
593            gpu_n: AtomicU32::new(0),
594            declines: AtomicU32::new(0),
595            gpu_burn: AtomicU32::new(PROBE_WARMUP),
596            cpu_ns: AtomicU64::new(0),
597            cpu_n: AtomicU32::new(0),
598            gpu_min: AtomicU64::new(u64::MAX),
599            cpu_min: AtomicU64::new(u64::MAX),
600        }
601    }
602}
603
604static PROBES: [Probe; 8] = [
605    Probe::new(),
606    Probe::new(),
607    Probe::new(),
608    Probe::new(),
609    Probe::new(),
610    Probe::new(),
611    Probe::new(),
612    Probe::new(),
613];
614
615/// A caller that knows its loop is long, uniform and warm can say so: the
616/// probe times ops in isolation and alternates arms to do it, which reads a
617/// sustained diffusion step as slower on the device than it is. Measured on
618/// an M4 at 672 video tokens: the probe picked the CPU at 1.25 ms against
619/// 0.88 ms per op, and the loop it picked for ran 23.9 s a step against the
620/// device's 19.7 s.
621static TRUST_GPU: AtomicBool = AtomicBool::new(false);
622
623/// Take the probe out of the loop until the guard drops.
624pub fn trust_gpu() -> GpuTrust {
625    let was = TRUST_GPU.swap(true, Ordering::Relaxed);
626    GpuTrust(was)
627}
628
629pub struct GpuTrust(bool);
630
631impl Drop for GpuTrust {
632    fn drop(&mut self) {
633        TRUST_GPU.store(self.0, Ordering::Relaxed);
634    }
635}
636
637fn probe_on_for(c: OpClass) -> bool {
638    // The trust is only for the *wide* class. A sustained diffusion step is
639    // where the probe reads a warm device as cold; the narrow batches inside
640    // the same loop — an audio stream of fifty-one tokens against the same
641    // weights — are small enough that submit latency can genuinely beat the
642    // arithmetic, and there the probe is right and should keep deciding.
643    if TRUST_GPU.load(Ordering::Relaxed) && matches!(c, OpClass::MatmatWide | OpClass::Ffn) {
644        return false;
645    }
646    probe_on()
647}
648
649/// Is the per-op GPU/CPU probe enabled (`CMF_GPU_PROBE`, default on)?
650/// The native Metal decode route never consults it — `q1_force` routes
651/// the token graph to the device outright — so it is reported, not used.
652pub fn probe_enabled() -> bool {
653    probe_on()
654}
655
656fn probe_on() -> bool {
657    static ON: OnceLock<bool> = OnceLock::new();
658    *ON.get_or_init(|| {
659        std::env::var("CMF_GPU_PROBE")
660            .map(|v| v != "0" && v != "off")
661            .unwrap_or(true)
662    })
663}
664
665/// q1 ops on the native Metal backend skip the probe entirely: the CPU
666/// q1 kernel is load-port-bound, the GPU one wins warm — and probe
667/// alternation itself cools the device between samples (measured: block
668/// times 5.8 ms warm vs 8.8 ms mixed). Other backends keep probing.
669pub fn q1_force() -> bool {
670    #[cfg(target_os = "macos")]
671    {
672        backend() == Backend::Metal
673    }
674    #[cfg(not(target_os = "macos"))]
675    {
676        false
677    }
678}
679
680/// Should a FUSED whole-block path trust the device instead of asking
681/// the per-op probe? True on native Metal and on discrete wgpu adapters.
682///
683/// The probe answers "is one wide matmat faster on the GPU", and for the
684/// DiT on Metal that is a coin flip — measured 2.62 ms GPU vs 2.56 ms
685/// CPU, a 2% spread that lands on either arm run to run. But the fused
686/// block's advantage is not per-op speed, it is that the hidden state,
687/// the packs and the attention panels never leave the device: end to end
688/// the whole-block path renders a 512² Lumina step in ~5.4 s against
689/// ~8.4 s when the probe happens to pick the CPU. Gating a fusion win on
690/// a per-op tie made every second render half-speed at random.
691///
692/// On a discrete card the verdict is never in doubt — an RTX 3090 against
693/// a 256-core EPYC measured 11.5 ms vs 31 ms per wide op, four runs out
694/// of four — so the probe's sampling phase is pure cost: it alone was 10%
695/// of a 512² render (74.3 s against 66.9 s with the probe off). Integrated
696/// and mobile adapters keep probing; there the submit latency is real and
697/// can genuinely lose.
698pub fn fused_block_trusted() -> bool {
699    #[cfg(target_os = "macos")]
700    if backend() == Backend::Metal {
701        return true;
702    }
703    wgpu_graph_default()
704}
705
706/// Which arm should this GPU-eligible call take? Consult AFTER the
707/// eligibility gates (`enabled_here` / `min_rows`) so only real
708/// candidates alternate.
709/// While a class is still probing, a call whose weights are NOT yet on
710/// the card should take the GPU arm anyway: the upload is work the next
711/// step needs regardless, and the sample it produces is discarded as
712/// cold — so handing that call to the CPU arm buys nothing and costs a
713/// host GEMM. Measured on a diffusion stack, where every layer is
714/// touched once per step and therefore EVERY first-step GPU sample is
715/// cold: one projection drew the CPU arm for the whole first step, 9.8 s
716/// against the 2.8 s it costs once the weights are warm.
717pub fn weight_is_resident(model: &Arc<CmfModel>, idx: usize) -> bool {
718    #[cfg(all(feature = "gpu", not(target_os = "macos")))]
719    {
720        return crate::gpu_wgpu::weight_is_resident(model, idx);
721    }
722    #[cfg(not(all(feature = "gpu", not(target_os = "macos"))))]
723    {
724        let _ = (model, idx);
725        true
726    }
727}
728
729pub fn probe_arm_cold_prefers_gpu(c: OpClass, weights_resident: bool) -> ProbeArm {
730    if !weights_resident && probe_deciding(c) {
731        return ProbeArm::Gpu;
732    }
733    probe_arm(c)
734}
735
736pub fn probe_arm(c: OpClass) -> ProbeArm {
737    // Every arbitrated call starts with a clean cold flag: both the
738    // sample discard in `probe_record` and the contention kill-switch
739    // read it AFTER the op, so a stale note from a previous call on
740    // this thread must not leak in.
741    PROBE_COLD.with(|f| f.set(false));
742    if !probe_on_for(c) {
743        return ProbeArm::Gpu;
744    }
745    probe_cache_load();
746    let p = &PROBES[c as usize];
747    match p.state.load(Ordering::Relaxed) {
748        1 => ProbeArm::Gpu,
749        2 => ProbeArm::Cpu,
750        _ => {
751            if p.flip.fetch_add(1, Ordering::Relaxed) % 2 == 0 {
752                ProbeArm::Gpu
753            } else {
754                ProbeArm::CpuTimed
755            }
756        }
757    }
758}
759
760/// The device arm was chosen and the device refused the work, so there
761/// is no time to record. Callers that fall through to the host MUST say
762/// so here, or the class can never decide.
763pub fn probe_note_decline(c: OpClass) {
764    let p = &PROBES[c as usize];
765    if p.state.load(Ordering::Relaxed) != 0 {
766        return;
767    }
768    let n = p.declines.fetch_add(1, Ordering::Relaxed) + 1;
769    if n >= PROBE_DECLINE_LIMIT
770        && p.state
771            .compare_exchange(0, 2, Ordering::Relaxed, Ordering::Relaxed)
772            .is_ok()
773    {
774        tracing::info!(
775            "gpu probe [{}]: device declined {n} times → cpu",
776            CLASS_NAMES[c as usize]
777        );
778    }
779}
780
781/// Record a timed arm sample; on the `PROBE_SAMPLES`-th clean sample of
782/// BOTH arms the class decides for the rest of the process.
783pub fn probe_record(c: OpClass, gpu: bool, dur: std::time::Duration) {
784    probe_record_into(
785        &PROBES[c as usize],
786        CLASS_NAMES[c as usize],
787        Some(c),
788        gpu,
789        dur,
790    )
791}
792
793/// The body of `probe_record` over ONE probe, so the decision can be
794/// driven in a test without touching the process-wide array.
795fn probe_record_into(
796    p: &Probe,
797    class_name: &str,
798    cache: Option<OpClass>,
799    gpu: bool,
800    dur: std::time::Duration,
801) {
802    if p.state.load(Ordering::Relaxed) != 0 {
803        return;
804    }
805    if gpu && PROBE_COLD.with(|f| f.replace(false)) {
806        return; // one-off cost in this call — not a steady-state sample
807    }
808    if gpu {
809        // Load-then-store rather than fetch_sub: a blind decrement at
810        // zero wraps a u32 to its maximum and mutes the arm forever.
811        // A benign race here burns one extra sample, which is free.
812        let left = p.gpu_burn.load(Ordering::Relaxed);
813        if left > 0 {
814            p.gpu_burn.store(left - 1, Ordering::Relaxed);
815            return; // warm-up: the first device sample builds its pipeline
816        }
817    }
818    let ns = dur.as_nanos().min(u64::MAX as u128) as u64;
819    if gpu {
820        p.gpu_ns.fetch_add(ns, Ordering::Relaxed);
821        p.gpu_n.fetch_add(1, Ordering::Relaxed);
822        p.gpu_min.fetch_min(ns, Ordering::Relaxed);
823    } else {
824        p.cpu_ns.fetch_add(ns, Ordering::Relaxed);
825        p.cpu_n.fetch_add(1, Ordering::Relaxed);
826        p.cpu_min.fetch_min(ns, Ordering::Relaxed);
827    }
828    let (gn, cn) = (
829        p.gpu_n.load(Ordering::Relaxed),
830        p.cpu_n.load(Ordering::Relaxed),
831    );
832    if gn >= 2 && cn >= 2 {
833        // Decide on each arm's BEST sample — the steady-state pace.
834        // Means carry one-off cold costs (mmap page-in on the CPU arm)
835        // that the cold-flag machinery cannot see.
836        let g = p.gpu_min.load(Ordering::Relaxed) as f64;
837        let cp = p.cpu_min.load(Ordering::Relaxed) as f64;
838        // Early verdict on a ≥2× gap — no reason to keep feeding the
839        // losing arm; close races take the full sample count. It was 3×,
840        // and the cost of that half-octave was measured: a DiT whose
841        // wide GEMMs run 11.4 ms on the device against 32.2 on the host
842        // (2.8×) kept ALTERNATING through the whole diffusion stack, and
843        // because the alternation counter is shared per class in call
844        // order, one projection drew the CPU arm every single time — 9.9
845        // seconds a step on a kernel that needs 0.4. Both arms are
846        // compared on their BEST sample, so a 2× gap is not noise.
847        if (gn < PROBE_SAMPLES || cn < PROBE_SAMPLES) && g < cp * 2.0 && cp < g * 2.0 {
848            return;
849        }
850        let winner = if g <= cp { 1 } else { 2 };
851        if p.state
852            .compare_exchange(0, winner, Ordering::Relaxed, Ordering::Relaxed)
853            .is_ok()
854        {
855            tracing::info!(
856                "gpu probe [{}]: gpu {:.2} ms vs cpu {:.2} ms per op → {}",
857                class_name,
858                g / 1e6,
859                cp / 1e6,
860                if winner == 1 { "gpu" } else { "cpu" },
861            );
862            if let Some(c) = cache {
863                probe_cache_store(c, winner);
864            }
865        }
866    }
867}
868
869/// Is the class still collecting samples? (Call sites use this to route
870/// cold-weight calls away from the GPU arm during probing.)
871pub fn probe_deciding(c: OpClass) -> bool {
872    probe_on_for(c) && PROBES[c as usize].state.load(Ordering::Relaxed) == 0
873}
874
875/// Probing helper: true — tensor `idx`'s quant weights are ALREADY
876/// device-resident (a clean GPU sample is possible now); false — they
877/// were not (the upload starts within the VRAM budget, so a later call
878/// finds them warm) or the tensor cannot go to the GPU at all. Keeps the
879/// probe from billing a full cold dispatch+readback to a sample it will
880/// discard anyway. The verdict needs only a couple of warm tensors, so
881/// probe-driven uploads are capped — the losing-GPU machine should not
882/// pay for uploading the whole layer stack it will never use; if the GPU
883/// wins, the rest uploads lazily on demand, in the same first-touch order.
884#[allow(unused_variables)]
885pub fn q8_resident_or_upload(model: &Arc<CmfModel>, idx: usize) -> bool {
886    static PROBE_UPLOADS: AtomicU32 = AtomicU32::new(0);
887    let may_upload = PROBE_UPLOADS.load(Ordering::Relaxed) < 4;
888    let resident = match backend() {
889        #[cfg(target_os = "macos")]
890        Backend::Metal => crate::gpu_metal::q8_resident_or_upload(model, idx, may_upload),
891        #[cfg(feature = "gpu")]
892        Backend::Wgpu => crate::gpu_wgpu::q8_resident_or_upload(model, idx, may_upload),
893        Backend::None => false,
894    };
895    if !resident && may_upload {
896        PROBE_UPLOADS.fetch_add(1, Ordering::Relaxed);
897    }
898    resident
899}
900
901/// Test hook: reset all probes to the undecided state.
902#[cfg(test)]
903pub(crate) fn probe_reset() {
904    for p in &PROBES {
905        p.state.store(0, Ordering::Relaxed);
906        p.flip.store(0, Ordering::Relaxed);
907        p.gpu_ns.store(0, Ordering::Relaxed);
908        p.gpu_n.store(0, Ordering::Relaxed);
909        p.cpu_ns.store(0, Ordering::Relaxed);
910        p.cpu_n.store(0, Ordering::Relaxed);
911    }
912}
913
914/// The probe table is process-global by design, while these unit tests reset
915/// and seed selected entries to exercise arbitration. Keep only those tests
916/// out of each other's way; production callers still probe concurrently.
917#[cfg(test)]
918static PROBE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
919
920#[cfg(test)]
921fn probe_test_guard() -> std::sync::MutexGuard<'static, ()> {
922    PROBE_TEST_LOCK
923        .lock()
924        .unwrap_or_else(std::sync::PoisonError::into_inner)
925}
926
927#[cfg(test)]
928mod probe_tests {
929    use super::*;
930    use std::time::Duration;
931
932    #[test]
933    fn cpu_only_whole_operator_dispatch_inherits_and_restores_scope() {
934        let pool = crate::pool::Pool::with_spin(3, 0);
935        cpu_scope(|| {
936            let inherit = inherit_cpu_scope();
937            pool.run_rows(64, &|_, _| {
938                let _guard = inherit();
939                assert!(CPU_ONLY.get());
940            });
941        });
942        pool.run_rows(64, &|_, _| assert!(!CPU_ONLY.get()));
943    }
944
945    // One test fn: PROBES is process-global and probe_reset touches all
946    // classes — parallel test threads would race.
947    #[test]
948    fn probe_alternates_discards_cold_and_decides() {
949        let _probe_guard = probe_test_guard();
950        probe_reset();
951        // Probing: arms alternate.
952        assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
953        assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::CpuTimed));
954
955        // A cold GPU sample (upload noted) must be discarded: feed a
956        // catastrophic cold sample, then clean fast-GPU samples — GPU
957        // wins only if the cold one did not count.
958        probe_note_cold();
959        probe_record(OpClass::Ffn, true, Duration::from_secs(1000));
960        for _ in 0..PROBE_SAMPLES {
961            probe_record(OpClass::Ffn, true, Duration::from_millis(1));
962            probe_record(OpClass::Ffn, false, Duration::from_millis(4));
963        }
964        assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
965
966        // The reverse: a class where the CPU arm is faster decides CPU.
967        for _ in 0..PROBE_SAMPLES {
968            probe_record(OpClass::Matmat, true, Duration::from_millis(4));
969            probe_record(OpClass::Matmat, false, Duration::from_millis(1));
970        }
971        assert!(matches!(probe_arm(OpClass::Matmat), ProbeArm::Cpu));
972
973        // cpu_scope: gates off inside, restored after.
974        cpu_scope(|| CPU_ONLY.with(|c| assert!(c.get())));
975        CPU_ONLY.with(|c| assert!(!c.get()));
976        cpu_scope(|| {
977            cpu_scope(|| CPU_ONLY.with(|c| assert!(c.get())));
978            CPU_ONLY.with(|c| assert!(c.get()));
979        });
980        let _ = std::panic::catch_unwind(|| cpu_scope(|| panic!("scope test")));
981        CPU_ONLY.with(|c| assert!(!c.get()));
982        probe_reset();
983    }
984
985    #[test]
986    fn a_remembered_verdict_is_adopted_and_a_stranger_is_not() {
987        let _probe_guard = probe_test_guard();
988        // Probing is not free: on a Snapdragon 778G the deciding classes
989        // cost minutes of wall clock before the first token, every
990        // process, and reached the same verdict every time. The cache
991        // exists so that price is paid once.
992        //
993        // The key is built from THIS process's device, never a name this
994        // test sets: `probe_set_device` is first-writer-wins and on a Mac
995        // the Metal backend may already have named the silicon before the
996        // tests run — which is exactly how this test failed on CI while
997        // passing locally. GemmNt on purpose: the arbitration test never
998        // touches it, and both run in one process.
999        let mine = probe_cache_key_named("gemm-nt");
1000        let state = || {
1001            PROBES[OpClass::GemmNt as usize]
1002                .state
1003                .load(Ordering::Relaxed)
1004        };
1005
1006        // Another device's verdict is not mine, whatever it claims.
1007        probe_cache_adopt("SomeOtherGPU/Vulkan\tgemm-nt\tgpu\n");
1008        assert_eq!(state(), 0);
1009        // Neither is one from another build of this engine.
1010        let older = mine.replacen(env!("CARGO_PKG_VERSION"), "0.0.0-old", 1);
1011        assert_ne!(older, mine);
1012        probe_cache_adopt(&format!("{older}\tgpu\n"));
1013        assert_eq!(state(), 0);
1014        // Mine is.
1015        probe_cache_adopt(&format!("{mine}\tcpu\n"));
1016        assert_eq!(state(), 2);
1017
1018        PROBES[OpClass::GemmNt as usize]
1019            .state
1020            .store(0, Ordering::Relaxed);
1021    }
1022}
1023
1024/// Default row threshold: the GPU takes only larger matrices (lm_head
1025/// class). Below it, the dispatch/readback cost does not pay off on unified memory.
1026pub const GPU_MIN_ROWS: usize = 65_536;
1027
1028/// Effective threshold: `CMF_GPU_MIN_ROWS` overrides. Defaults differ
1029/// by device class: on a DISCRETE card VRAM bandwidth pays off even for
1030/// FFN/QKV-class matrices (4096), on unified memory only lm_head-class
1031/// is worth the dispatch/readback (65536). Field case behind this: a
1032/// 35B model on an RTX 4090 saw ~0 offload because every layer matrix
1033/// sat below the old universal 65536.
1034pub fn min_rows() -> usize {
1035    if let Some(v) = std::env::var("CMF_GPU_MIN_ROWS")
1036        .ok()
1037        .and_then(|v| v.parse().ok())
1038    {
1039        return v;
1040    }
1041    if discrete() { 4096 } else { GPU_MIN_ROWS }
1042}
1043
1044/// Is the active backend a discrete card (PCIe VRAM)?
1045pub fn discrete() -> bool {
1046    match backend() {
1047        #[cfg(feature = "gpu")]
1048        Backend::Wgpu => crate::gpu_wgpu::is_discrete(),
1049        #[cfg(target_os = "macos")]
1050        Backend::Metal => false, // UMA by the init() guard
1051        Backend::None => false,
1052    }
1053}
1054
1055/// A single MoE-FFN job (an expert with its own weight), executed in one
1056/// submission: (rows, cols, idx, row_scale) for gate/up/down + prescaled
1057/// inputs + the down column scale + the blending weight.
1058pub struct MoeJob<'a> {
1059    pub gate: (usize, usize, usize, &'a [f32]),
1060    pub up: (usize, usize, usize, &'a [f32]),
1061    pub down: (usize, usize, usize, &'a [f32]),
1062    pub xs_gate: Vec<f32>,
1063    pub xs_up: Vec<f32>,
1064    pub down_col: &'a [f32],
1065    pub w: f32,
1066    /// q1 trio: scales live inside the 6-byte tiles (row_scale slices
1067    /// empty, xs raw f32). Backends without a q1 kernel refuse the job.
1068    pub q1: bool,
1069    /// q4_tiled trio: scales inside the 18-byte tiles (row_scale
1070    /// slices empty, xs raw f32) — the MoE-hybrid coder class.
1071    pub q4t: bool,
1072    /// q4tp trio: same raw-xs contract, 16-byte nibble stride and the scale
1073    /// on a per-row ladder. Without this the experts of a q4tp MoE model fall
1074    /// to the CPU while every other dtype rides the device.
1075    pub q4tp: bool,
1076    /// Mixed 2-bit profile: gate/up are q2tp (8-byte chunks, zero rung),
1077    /// down stays q4tp. Set together with `q4tp`; a backend without the
1078    /// 2-bit kernel must refuse the whole job.
1079    pub gu_q2: bool,
1080    /// The reference's `swiglu_limit`; 0 disables the clamp. A backend that
1081    /// cannot apply it must REFUSE the job rather than drop it silently —
1082    /// the difference only shows on saturating activations, which is the
1083    /// hardest kind of divergence to notice.
1084    pub swiglu_limit: f32,
1085    /// `GraphAct::code` of act(gate)·up: 0 SiLU (every MoE expert), 1 exact
1086    /// GELU, 2 tanh-GELU (a Gemma dense FFN riding the single-job block).
1087    /// A backend without the activation must refuse the job.
1088    pub act: u32,
1089}
1090
1091/// A single independent batch matvec (GDN projections of one input).
1092pub struct BatchJob<'a> {
1093    pub idx: usize,
1094    pub rows: usize,
1095    pub cols: usize,
1096    pub row_scale: &'a [f32],
1097    pub xs: Vec<f32>,
1098    /// Weight layout. Was a bare `q1: bool`, which could only ever spell two
1099    /// of the four and silently sent everything else back to the CPU — the
1100    /// GDN projections of a q4t/q4tp model never reached the device at all.
1101    pub layout: BatchLayout,
1102}
1103
1104/// Which kernel a batched matvec needs. q8 carries row scales in a side
1105/// buffer; the rest embed them in the payload and differ in stride.
1106#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1107pub enum BatchLayout {
1108    Q8,
1109    Q1,
1110    /// q1g: sign + scale planes, one scale per 128 (q1's raw-xs contract).
1111    Q1g,
1112    Q4t,
1113    Q4tp,
1114}
1115
1116#[derive(Clone, Copy, PartialEq, Eq)]
1117enum Backend {
1118    None,
1119    #[cfg(target_os = "macos")]
1120    Metal,
1121    #[cfg(feature = "gpu")]
1122    Wgpu,
1123}
1124
1125fn backend() -> Backend {
1126    #[cfg(feature = "gpu")]
1127    if crate::gpu_wgpu::selected() {
1128        return if crate::gpu_wgpu::enabled() {
1129            Backend::Wgpu
1130        } else {
1131            Backend::None
1132        };
1133    }
1134    #[cfg(target_os = "macos")]
1135    if crate::gpu_metal::enabled() {
1136        return Backend::Metal;
1137    }
1138    Backend::None
1139}
1140
1141/// GPU enabled and initialized on the selected backend?
1142/// Whether THIS build can bring a GPU up on THIS device: a compiled-in
1143/// backend plus a live adapter. The mobile FFI exposes it so an app can
1144/// tell "GPU off" from "GPU impossible" (a CPU-only .so ships no
1145/// backend at all). Cached after the first call.
1146pub fn backend_available() -> bool {
1147    #[cfg(target_os = "macos")]
1148    {
1149        // The Metal path is always compiled on macOS.
1150        true
1151    }
1152    #[cfg(all(feature = "gpu", not(target_os = "macos")))]
1153    {
1154        static AVAIL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1155        *AVAIL.get_or_init(crate::gpu_wgpu::adapter_probe)
1156    }
1157    #[cfg(all(not(feature = "gpu"), not(target_os = "macos")))]
1158    {
1159        false
1160    }
1161}
1162
1163/// A process-wide, phase-scoped GPU gate. `cpu_scope` is thread-local and
1164/// the pool's workers do not inherit it, so a caller that wants a whole
1165/// *phase* off the device — a prompt encoder whose weights live in a part of
1166/// the file the hot loop never touches, on a machine that cannot keep both
1167/// wired — has to say so globally.
1168static GPU_PAUSED: AtomicBool = AtomicBool::new(false);
1169
1170/// Park the device for every thread until the returned guard drops.
1171pub fn pause_gpu() -> GpuPause {
1172    GPU_PAUSED.store(true, Ordering::Relaxed);
1173    GpuPause(())
1174}
1175
1176pub struct GpuPause(());
1177
1178impl Drop for GpuPause {
1179    fn drop(&mut self) {
1180        GPU_PAUSED.store(false, Ordering::Relaxed);
1181    }
1182}
1183
1184pub fn enabled() -> bool {
1185    !GPU_PAUSED.load(Ordering::Relaxed) && backend() != Backend::None
1186}
1187
1188/// Default-on condition for the wgpu whole-token graph: the wgpu
1189/// backend on a DISCRETE adapter. NOT plain `enabled()` (macOS/Metal
1190/// must not pay a per-token layer scan for a graph its backend
1191/// refuses), and NOT integrated adapters: the graph's ~300 barriered
1192/// dispatches per token are cheap on desktop immediate-mode GPUs but
1193/// tiled mobile GPUs (Adreno/Mali) drain the pipeline at every barrier
1194/// — field report: 0.2 tok/s on-graph vs 15 tok/s on the CPU. On
1195/// integrated adapters the per-op probe path arbitrates each op class
1196/// against the CPU instead; CMF_GPU_WGPU_GRAPH=1 still forces the
1197/// graph anywhere.
1198/// Is the wgpu backend active at all (any adapter)? Eligibility gate
1199/// for the whole-token graph — whether it actually RUNS is decided by
1200/// `wgpu_graph_default` (trusted on discrete) or the generation race.
1201pub fn wgpu_active() -> bool {
1202    #[cfg(feature = "gpu")]
1203    {
1204        matches!(backend(), Backend::Wgpu)
1205    }
1206    #[cfg(not(feature = "gpu"))]
1207    {
1208        false
1209    }
1210}
1211
1212/// Which GPU this thread's engine calls address. Multi-card hosts hold
1213/// one wgpu context PER card (weights, KV mirrors and scratch live
1214/// inside a context, so per-device contexts give per-device caches for
1215/// free); this thread-local says which one is current. Default: the
1216/// process pin (CMF_GPU_ADAPTER) or 0 — so single-card runs behave
1217/// exactly as they always have.
1218pub fn default_device() -> usize {
1219    static D: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1220    *D.get_or_init(|| {
1221        std::env::var("CMF_GPU_ADAPTER")
1222            .ok()
1223            .and_then(|v| v.trim().parse::<usize>().ok())
1224            .unwrap_or(0)
1225    })
1226}
1227
1228thread_local! {
1229    static CUR_DEV: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
1230}
1231
1232/// The device this thread is pinned to.
1233pub fn current_device() -> usize {
1234    CUR_DEV.with(|c| c.get()).unwrap_or_else(default_device)
1235}
1236
1237/// Pin this thread to a device. Server slots call it once per request;
1238/// the worker pool propagates it into its threads, so a dispatch begun
1239/// on card 1 does not finish on card 0.
1240pub fn set_current_device(i: usize) {
1241    CUR_DEV.with(|c| c.set(Some(i)));
1242}
1243
1244/// Run `f` with this thread pinned to `dev`, restoring the previous pin.
1245pub fn with_device<R>(dev: usize, f: impl FnOnce() -> R) -> R {
1246    let prev = CUR_DEV.with(|c| c.replace(Some(dev)));
1247    let r = f();
1248    CUR_DEV.with(|c| c.set(prev));
1249    r
1250}
1251
1252/// How many GPUs this process can address (wgpu adapter count; 1 on
1253/// Metal, 0 without a backend).
1254pub fn device_count() -> usize {
1255    #[cfg(all(feature = "gpu", not(target_os = "macos")))]
1256    {
1257        return crate::gpu_wgpu::adapter_count();
1258    }
1259    #[cfg(not(all(feature = "gpu", not(target_os = "macos"))))]
1260    {
1261        usize::from(backend_available())
1262    }
1263}
1264
1265/// Weight budget of the current GPU in bytes; 0 when there is none and
1266/// u64::MAX on unified memory (where the OS pages shared RAM and the
1267/// question "does the model fit the card" has no separate answer).
1268pub fn vram_budget() -> u64 {
1269    #[cfg(all(feature = "gpu", not(target_os = "macos")))]
1270    {
1271        return crate::gpu_wgpu::device_vram_budget();
1272    }
1273    #[cfg(not(all(feature = "gpu", not(target_os = "macos"))))]
1274    {
1275        if backend_available() { u64::MAX } else { 0 }
1276    }
1277}
1278
1279/// Bytes currently accounted as resident weight buffers on the active wgpu
1280/// adapter.  This is the logical device-local weight set; physical driver
1281/// allocations are reported separately by the platform tools.
1282pub fn resident_bytes() -> u64 {
1283    #[cfg(feature = "gpu")]
1284    {
1285        if backend() == Backend::Wgpu {
1286            return crate::gpu_wgpu::resident_bytes();
1287        }
1288    }
1289    0
1290}
1291
1292/// Sealed O(1) device mirror count and logical bytes for one pipeline id.
1293/// Zero is returned when wgpu is unavailable or the sequence has not reached
1294/// an O(1) seal yet.
1295pub fn o1_device_stats(kv_id: u64) -> (usize, u64) {
1296    #[cfg(feature = "gpu")]
1297    {
1298        if backend() == Backend::Wgpu {
1299            return crate::gpu_wgpu::o1_device_stats(kv_id);
1300        }
1301    }
1302    let _ = kv_id;
1303    (0, 0)
1304}
1305
1306/// Device weight bytes uploaded so far (wgpu; 0 on other backends).
1307/// Steady-state windows must show a ZERO delta — growth mid-benchmark
1308/// means eviction/re-upload and disqualifies the number.
1309pub fn upload_bytes() -> u64 {
1310    #[cfg(feature = "gpu")]
1311    {
1312        return crate::gpu_wgpu::UPLOAD_BYTES.load(std::sync::atomic::Ordering::Relaxed);
1313    }
1314    #[cfg(not(feature = "gpu"))]
1315    0
1316}
1317
1318/// Measure a transient host-to-device upload when the wgpu backend is
1319/// compiled in. CPU-only builds keep the benchmark command available and
1320/// report no device measurement instead of referring to the gated module.
1321pub fn upload_bandwidth_probe(block: usize, rounds: usize) -> Option<f64> {
1322    #[cfg(feature = "gpu")]
1323    {
1324        return crate::gpu_wgpu::upload_bandwidth_probe(block, rounds);
1325    }
1326    let _ = (block, rounds);
1327    None
1328}
1329
1330/// Which half of the run is asking.
1331///
1332/// The phase exists because the graph is plausibly two decisions, not
1333/// one — but on the hardware measured so far it is only ever a decode
1334/// decision. On an Adreno 642L with bonsai-1.7b, from identical clean
1335/// starts and two repeats each: decode 11.6 tok/s without it and 0.72
1336/// with, while prefill is 4.2 either way. A first reading of 3.4 -> 18.0
1337/// for prefill did not survive a controlled re-run — it was a dirty
1338/// probe cache between configurations, not the graph, and the prefill
1339/// route through the graph is GDN-only in the first place, which this
1340/// dense model never takes.
1341#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1342pub enum GraphPhase {
1343    Prefill,
1344    Decode,
1345}
1346
1347/// The one place that decides whether the whole-token graph runs.
1348///
1349/// `CMF_GPU_WGPU_GRAPH`: `0` off everywhere, `prefill` only for the
1350/// prompt, anything else on everywhere. Unset: desktop-class GPUs take
1351/// it for both phases; phone-class UMA takes it for PREFILL only, which
1352/// is the measurement above rather than a guess — the per-op path keeps
1353/// decode, where it is seventeen times better.
1354pub fn wgpu_graph_on(phase: GraphPhase) -> bool {
1355    match std::env::var("CMF_GPU_WGPU_GRAPH").ok().as_deref() {
1356        Some("0") => false,
1357        Some("prefill") => phase == GraphPhase::Prefill,
1358        Some(_) => true,
1359        None => {
1360            if wgpu_graph_default() {
1361                return true;
1362            }
1363            // Integrated/mobile keeps the per-op path for BOTH phases —
1364            // unchanged, because the measurement that would have bought
1365            // prefill a graph did not reproduce. `=prefill` is there for
1366            // the device where it does; the default does not guess.
1367            let _ = phase;
1368            false
1369        }
1370    }
1371}
1372
1373pub fn wgpu_graph_default() -> bool {
1374    #[cfg(feature = "gpu")]
1375    {
1376        // Discrete cards always; Apple-silicon UMA on macOS too — desktop
1377        // -class GPUs where the graph measured ~2x the CPU on the Qwen3.6
1378        // family (M4: 13.3 tok/s against 7.3). Phone-class UMA (Android/
1379        // iOS builds) keeps the per-op probe path: tiled mobile GPUs have
1380        // turned the ~300-dispatch graph into seconds per token.
1381        matches!(backend(), Backend::Wgpu)
1382            && (crate::gpu_wgpu::discrete_active()
1383                || (cfg!(target_os = "macos") && crate::gpu_wgpu::adapter_up()))
1384    }
1385    #[cfg(not(feature = "gpu"))]
1386    {
1387        false
1388    }
1389}
1390
1391/// q8_row/q8_2f matvec, rows [row0, row0+rows). `xs` — prescaled by the column scale.
1392#[allow(clippy::too_many_arguments, unused_variables)]
1393pub fn q8_matvec_range(
1394    model: &Arc<CmfModel>,
1395    idx: usize,
1396    row0: usize,
1397    row_scale: &[f32],
1398    xs: &[f32],
1399    rows: usize,
1400    cols: usize,
1401    out: &mut [f32],
1402) -> bool {
1403    match backend() {
1404        #[cfg(target_os = "macos")]
1405        Backend::Metal => {
1406            crate::gpu_metal::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
1407        }
1408        #[cfg(feature = "gpu")]
1409        Backend::Wgpu => {
1410            crate::gpu_wgpu::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
1411        }
1412        Backend::None => false,
1413    }
1414}
1415
1416/// Decode-exact short q8_2f panel for the banked MiMo head.
1417pub(crate) fn q82_short_rows(
1418    model: &Arc<CmfModel>,
1419    idx: usize,
1420    xs: &[f32],
1421    b: usize,
1422    rows: usize,
1423    cols: usize,
1424    out: &mut [f32],
1425) -> bool {
1426    #[cfg(feature = "gpu")]
1427    if enabled_here() && backend() == Backend::Wgpu {
1428        return crate::gpu_wgpu::q82_short_rows(model, idx, xs, b, rows, cols, out);
1429    }
1430    let _ = (model, idx, xs, b, rows, cols, out);
1431    false
1432}
1433
1434/// GEMM of a prefill batch: `pre` — prescaled inputs row-major [b, cols],
1435/// out — row-major [b, rows].
1436#[allow(clippy::too_many_arguments, unused_variables)]
1437/// The two-field int8 GEMM with the column field left for the device.
1438/// wgpu only — Metal's int8 kernel takes a pre-scaled activation, so the
1439/// caller keeps that path when this returns `false`.
1440#[allow(clippy::too_many_arguments)]
1441pub fn q8_matmat_2f(
1442    model: &Arc<CmfModel>,
1443    idx: usize,
1444    row_scale: &[f32],
1445    col_field: &[f32],
1446    xs: &[f32],
1447    b: usize,
1448    rows: usize,
1449    cols: usize,
1450    out: &mut [f32],
1451) -> bool {
1452    #[allow(unreachable_patterns)]
1453    match backend() {
1454        #[cfg(feature = "gpu")]
1455        Backend::Wgpu => {
1456            crate::gpu_wgpu::q8_matmat_2f(model, idx, row_scale, col_field, xs, b, rows, cols, out)
1457        }
1458        _ => false,
1459    }
1460}
1461
1462pub fn q8_matmat(
1463    model: &Arc<CmfModel>,
1464    idx: usize,
1465    row_scale: &[f32],
1466    pre: &[f32],
1467    b: usize,
1468    rows: usize,
1469    cols: usize,
1470    out: &mut [f32],
1471) -> bool {
1472    match backend() {
1473        #[cfg(target_os = "macos")]
1474        Backend::Metal => {
1475            crate::gpu_metal::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out)
1476        }
1477        #[cfg(feature = "gpu")]
1478        Backend::Wgpu => crate::gpu_wgpu::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out),
1479        Backend::None => false,
1480    }
1481}
1482
1483/// q1 matvec: raw f32 activations, tile-embedded scales. Metal only
1484/// for now (wgpu q1 WGSL is queued); false = CPU fallback.
1485#[allow(unused_variables)]
1486pub fn q1_matvec(
1487    model: &Arc<CmfModel>,
1488    idx: usize,
1489    xs: &[f32],
1490    rows: usize,
1491    cols: usize,
1492    out: &mut [f32],
1493) -> bool {
1494    match backend() {
1495        #[cfg(target_os = "macos")]
1496        Backend::Metal => crate::gpu_metal::q1_matvec(model, idx, xs, rows, cols, out),
1497        #[cfg(feature = "gpu")]
1498        Backend::Wgpu => crate::gpu_wgpu::q1_matvec(model, idx, xs, rows, cols, out),
1499        Backend::None => false,
1500    }
1501}
1502
1503/// q1g matvec (sign + scale planes, raw f32 activations); the q1 kernel's
1504/// walk and sums, so a uniform-scale repack matches `q1_matvec` bit for
1505/// bit. false = CPU fallback.
1506#[allow(unused_variables)]
1507pub fn q1g_matvec(
1508    model: &Arc<CmfModel>,
1509    idx: usize,
1510    xs: &[f32],
1511    rows: usize,
1512    cols: usize,
1513    out: &mut [f32],
1514) -> bool {
1515    match backend() {
1516        #[cfg(target_os = "macos")]
1517        Backend::Metal => crate::gpu_metal::q1g_matvec(model, idx, xs, rows, cols, out),
1518        #[cfg(feature = "gpu")]
1519        Backend::Wgpu => crate::gpu_wgpu::q1g_matvec(model, idx, xs, rows, cols, out),
1520        Backend::None => false,
1521    }
1522}
1523
1524/// Whole attention sub-block on the wgpu token graph (drop-in for
1525/// `qwen_attention`): normed hidden in, O-projection out, resident device
1526/// K/V mirror. false = refusal / not the wgpu backend → CPU path.
1527#[allow(clippy::too_many_arguments)]
1528pub fn attn_dropin(
1529    model: &Arc<CmfModel>,
1530    kv_id: u64,
1531    layer: usize,
1532    normed: &[f32],
1533    wq_idx: usize,
1534    wk_idx: usize,
1535    wv_idx: usize,
1536    wo_idx: usize,
1537    q_norm: Option<&[f32]>,
1538    k_norm: Option<&[f32]>,
1539    late_qk_norm: bool,
1540    invf: &[f32],
1541    nh: usize,
1542    nkv: usize,
1543    hd: usize,
1544    rd: usize,
1545    hidden: usize,
1546    pos: usize,
1547    cap: usize,
1548    gemma: bool,
1549    eps: f32,
1550    cpu_k: &[Vec<f32>],
1551    cpu_v: &[Vec<f32>],
1552    out: &mut [f32],
1553) -> bool {
1554    match backend() {
1555        #[cfg(feature = "gpu")]
1556        Backend::Wgpu => crate::gpu_wgpu::attn_dropin_gpu(
1557            model, kv_id, layer, normed, wq_idx, wk_idx, wv_idx, wo_idx, q_norm, k_norm,
1558            late_qk_norm, invf, nh, nkv, hd, rd, hidden, pos, cap, gemma, eps, cpu_k, cpu_v, out,
1559        ),
1560        #[allow(unused_variables)]
1561        _ => false,
1562    }
1563}
1564
1565/// Descriptor operation attached to a graph weight.  `None` is the default
1566/// for ordinary CMF files; Prism weights are admitted only when the token
1567/// graph carries this explicit transform contract.
1568#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1569pub enum GraphPrismOp {
1570    None,
1571    Forward,
1572    InverseEmbedding,
1573}
1574
1575/// Graph kind of a binary low-rank (`blr`, dtype 19) weight: two stage
1576/// dispatches (V, U) over the resident payload instead of one matvec. Only
1577/// the wgpu token graph builder asks for it (`QTensor::graph_weight_or_blr`).
1578pub const GRAPH_KIND_BLR: u8 = 11;
1579
1580/// One weight in the whole-token graph: tensor idx + a codec tag (0=q8_row,
1581/// 1=q1, 2=q4_tiled, 3=q1t, 4=f32, … 11=blr) + per-row scales (q8_row only) + the raw f32
1582/// data (kind 4 only — small unquantized projections like GDN in_proj_a/b).
1583pub struct GraphW<'a> {
1584    pub idx: usize,
1585    pub kind: u8,
1586    pub row_scale: &'a [f32],
1587    pub data: &'a [f32],
1588    pub prism: GraphPrismOp,
1589    pub affine: bool,
1590}
1591
1592/// A layer's token-mixing op: standard attention or a GDN (linear-attention)
1593/// block. The surrounding norms + SwiGLU FFN are common to both.
1594pub enum GraphAttn<'a> {
1595    Full {
1596        wq: GraphW<'a>,
1597        wk: GraphW<'a>,
1598        wv: GraphW<'a>,
1599        wo: GraphW<'a>,
1600        q_norm: Option<&'a [f32]>,
1601        k_norm: Option<&'a [f32]>,
1602        /// HunYuan dense: q/k norm after RoPE (rope-kernel flag bit 32).
1603        late_qk_norm: bool,
1604        /// (bq, bk, bv) attention biases (Qwen2). None ⇒ no bias.
1605        bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
1606        /// Qwen3.5 gated attention: wq emits 2·nh·hd (q||gate per head), the
1607        /// attention output is scaled by sigmoid(gate) before the O projection.
1608        output_gate: bool,
1609        cpu_k: &'a [Vec<f32>],
1610        cpu_v: &'a [Vec<f32>],
1611        /// Absolute position of `cpu_k`/`cpu_v` row 0
1612        /// (`LayerKvCache::base`): a sliding layer that keeps only its
1613        /// tail stores rows from there on. 0 for every untrimmed layer.
1614        cpu_base: usize,
1615        /// This layer's own attention geometry, when the model's layers do
1616        /// not share one (MiMo-V2: 4/8 KV heads, 128-wide V under 192-wide
1617        /// heads, sliding windows with learned sinks, two RoPE tables).
1618        /// None = the call-wide (nkv, hd, rd, invf), V as wide as K, full
1619        /// context and a plain softmax — the historical contract, whose
1620        /// kernels and dispatch are untouched.
1621        geom: Option<GraphAttnGeom<'a>>,
1622        /// Spark-X2.5 head-wise output gate: `self_attn.g_proj`
1623        /// `[num_heads, hidden]` against the attention's normed input; head
1624        /// h's output is scaled by sigmoid(g[h]) before the O projection.
1625        /// None = no such gate (every other model).
1626        head_gate: Option<GraphW<'a>>,
1627    },
1628    Gdn {
1629        qkv: GraphW<'a>,
1630        z: GraphW<'a>,
1631        a: GraphW<'a>,
1632        b: GraphW<'a>,
1633        out: GraphW<'a>,
1634        conv1d: &'a [f32],
1635        a_log: &'a [f32],
1636        dt_bias: &'a [f32],
1637        norm: &'a [f32],
1638        nv: usize,
1639        nk: usize,
1640        dk: usize,
1641        dv: usize,
1642        kk: usize,
1643        /// CPU recurrent state `[ring (kk-1)·cdim | S nv·dk·dv]` — seeds the
1644        /// device mirror when prefill ran on the host (o1 collection, CPU
1645        /// fallback): a zero-initialized device state at decode is exactly
1646        /// the "coherent but contextless" garble.
1647        cpu_state: &'a [f32],
1648    },
1649    /// LFM2 gated short convolution: a fused (B, C, x) projection, a
1650    /// depthwise causal conv over a (kernel−1)-deep per-channel ring,
1651    /// C-gating, and an output projection. This mixer is what most of an
1652    /// LFM2 stack is (22 of the 2.6B's 30 layers), and before it had a
1653    /// graph arm the whole model fell to the per-op path — ~100 submits
1654    /// a token, 22 tok/s on an A100 for a 1.4 GB file.
1655    ShortConv {
1656        /// [3·hidden, hidden] fused input projection.
1657        inp: GraphW<'a>,
1658        /// [hidden, hidden] output projection.
1659        out: GraphW<'a>,
1660        /// [hidden · kernel] depthwise taps, `[channel][tap]`, tap
1661        /// kernel−1 multiplying the current position.
1662        taps: &'a [f32],
1663        kernel: usize,
1664        /// CPU conv ring `[channel][kernel−1]`, slot 0 newest — seeds
1665        /// the device mirror when prefill ran on the host, which for
1666        /// this mixer is always (the batch graph declines it).
1667        cpu_state: &'a [f32],
1668    },
1669}
1670
1671/// Per-layer attention geometry for the wgpu graphs (see
1672/// `GraphAttn::Full::geom`). The layer's CPU cache keeps K rows `hd` wide
1673/// and V rows zero-padded to `hd`; the device mirror stores V `dv` wide,
1674/// and a windowed layer keeps a ring of the last positions only.
1675#[derive(Clone, Copy)]
1676pub struct GraphAttnGeom<'a> {
1677    /// KV heads of this layer (divides the Q heads).
1678    pub nkv: usize,
1679    /// Q/K head width of this layer. The call-wide `hd` for every model
1680    /// but Gemma-4, whose global layers are 512 wide over 256-wide sliding
1681    /// ones (`<= 512`, a multiple of 4).
1682    pub hd: usize,
1683    /// V head width, `4 <= dv <= hd`, a multiple of 4.
1684    pub dv: usize,
1685    /// Rotary width of this layer (NeoX half-split over `[0, rd)`).
1686    pub rd: usize,
1687    /// This layer's RoPE inverse frequencies (`rd / 2` of them).
1688    pub invf: &'a [f32],
1689    /// YaRN attention-amplitude factor applied after the rotary pair
1690    /// transform. `1.0` is ordinary RoPE; Mellum's global layers use
1691    /// `1.277258872…`. This is deliberately per-layer: local and global
1692    /// layers may have different RoPE tables and factors.
1693    pub rope_scale: f32,
1694    /// Positions a query sees, its own included (MiMo-V2 SWA: 128);
1695    /// None = the whole context.
1696    pub window: Option<usize>,
1697    /// Learned per-Q-head sink logits (gpt-oss / MiMo-V2): they join the
1698    /// softmax max and denominator and carry no value row.
1699    pub sink: Option<&'a [f32]>,
1700    /// Gemma-4's scale-less V norm: every V head is RMS-normalized (no
1701    /// weight) before it is cached, as `attention::vnorm_head` does.
1702    pub v_norm: bool,
1703}
1704
1705/// Activation of a graph layer's dense FFN, `act(gate)·up`. The code is
1706/// the word the kernels read (`silu_mul_pre`'s `_c`, the fused gate+up
1707/// kernels' `_p1`): 0 keeps the historical SiLU expression untouched.
1708#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1709pub enum GraphAct {
1710    Silu,
1711    /// Exact erf GELU (HF `gelu`), erf by Abramowitz–Stegun 7.1.26 — the
1712    /// formula `inference::erf_f32` uses on the host.
1713    GeluErf,
1714    /// tanh-approximated GELU (HF `gelu_pytorch_tanh`, the Gemma family):
1715    /// `inference::gelu_tanh` term for term.
1716    GeluTanh,
1717}
1718
1719impl GraphAct {
1720    pub fn code(self) -> u32 {
1721        match self {
1722            Self::Silu => 0,
1723            Self::GeluErf => 1,
1724            Self::GeluTanh => 2,
1725        }
1726    }
1727}
1728
1729/// Per-layer weights for the whole-token wgpu graph.
1730pub struct GraphLayer<'a> {
1731    pub input_norm: &'a [f32],
1732    pub attn: GraphAttn<'a>,
1733    pub post_norm: &'a [f32],
1734    pub ffn: GraphFfn<'a>,
1735    /// Gemma sandwich norms: the token mixer's output and the FFN's output
1736    /// are RMS-normed with these weights before their residual adds.
1737    pub attn_out_norm: Option<&'a [f32]>,
1738    pub ffn_out_norm: Option<&'a [f32]>,
1739    /// Gemma-4 `layer_scalar`: the residual stream is multiplied by it at
1740    /// the end of the layer.
1741    pub layer_scale: Option<f32>,
1742}
1743
1744/// The FFN of one graph layer: a dense SwiGLU trio, or a routed MoE —
1745/// router + top-k selection + all selected experts run ON DEVICE (the
1746/// routing decision depends on the resident hidden state, so a CPU
1747/// round-trip per layer would forfeit the one-submit design).
1748pub enum GraphFfn<'a> {
1749    /// A singleton attention-only batch graph. Returns the post-attention
1750    /// residual, allowing a dynamic expert bank to own the FFN separately.
1751    AttentionOnly,
1752    Dense {
1753        gate: GraphW<'a>,
1754        up: GraphW<'a>,
1755        down: GraphW<'a>,
1756        /// act(gate)·up. The builders refuse an activation with no arm here
1757        /// (before this field the graph computed SiLU for any dense FFN).
1758        act: GraphAct,
1759    },
1760    Moe {
1761        /// Router logits weight (f32, kind 4) `[n_exp, hidden]`.
1762        router: GraphW<'a>,
1763        /// Shared-expert sigmoid gate (f32) `[1, hidden]`.
1764        shared_gate: GraphW<'a>,
1765        /// Per-expert q4_tiled directory indices `(gate, up, down)`;
1766        /// the SHARED expert rides as the LAST entry — the select
1767        /// kernel pins it with the sigmoid weight.
1768        experts: Vec<(usize, usize, usize)>,
1769        /// Routed experts (shared excluded).
1770        n_exp: usize,
1771        top_k: usize,
1772        inter: usize,
1773        norm_topk: bool,
1774        /// Expert weight layout, uniform across the layer: `false` =
1775        /// q4_tiled (18 B tiles, inline f16 scale), `true` = q4tp
1776        /// (16 B nibbles + a per-row ladder plane). The two differ only
1777        /// in where the scale comes from, so they share every kernel
1778        /// but the weight-staging block.
1779        q4tp: bool,
1780        /// `true` = the gate/up experts are `q2tp` (2-bit plane) while
1781        /// `down` stays q4tp — the mixed profile a 2-bit-class checkpoint
1782        /// converts into. Only meaningful with `q4tp: true`.
1783        gu_q2: bool,
1784        /// `true` = every expert's gate, up AND down is q8_2f (int8 body,
1785        /// f16 row scales, f16 column field; Mellum2.1's quality file).
1786        /// `q4tp` and `gu_q2` are false then. Its own kernels: each
1787        /// expert's input is multiplied by THAT expert's column field.
1788        q82: bool,
1789        /// LFM2-MoE / DeepSeek-V3 `noaux_tc` routing: per-expert sigmoid
1790        /// scores instead of a softmax, and `norm_topk` renormalises with
1791        /// the 1e-6 floor. The softmax arm is bit-identical to before.
1792        sigmoid: bool,
1793        /// Per-expert SELECTION bias: added to the score for the top-k
1794        /// choice only — the mixing weights stay unbiased (noaux_tc).
1795        bias: Option<&'a [f32]>,
1796        /// Whether a shared expert rides as the last `experts` entry.
1797        /// LFM2-MoE has none; the select kernel then leaves slot `top_k`
1798        /// unwritten and the expert loop runs `top_k` slots, not +1.
1799        has_shared: bool,
1800        /// The shared expert carries a sigmoid gate (Qwen2/3-MoE). `false`
1801        /// with `has_shared`: the shared expert enters with weight 1
1802        /// (DeepSeek-V3 / HunYuan hy_v3) and `shared_gate` is a stand-in
1803        /// the select kernels ignore.
1804        shared_gated: bool,
1805        /// Multiplier on the routed mixing weights after the optional
1806        /// renormalization (`routed_scaling_factor`); 1.0 = none.
1807        route_scale: f32,
1808    },
1809}
1810
1811/// Outcome of one whole-token graph attempt. A failed attempt after sealed
1812/// O(1) state was admitted must not fall through to the stale CPU state.
1813#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1814pub enum TokenGraphOutcome {
1815    /// No command was committed; the caller may use its ordinary path.
1816    Declined,
1817    /// The graph completed and its hidden/logits output is valid.
1818    Completed,
1819    /// Sealed O(1) state was admitted and a later graph operation failed.
1820    Failed,
1821}
1822
1823/// Whole-token decode graph on wgpu: the entire layer stack in ONE submit,
1824/// hidden resident, one readback. Updates `h` in place.
1825/// `loop_norm_at`: virtual layer indices after which `final_norm` is applied
1826/// (Looped Transformer mid-stack norm). Empty for standard models.
1827#[allow(clippy::too_many_arguments)]
1828pub fn forward_token_graph(
1829    model: &Arc<CmfModel>,
1830    kv_id: u64,
1831    layers: &[GraphLayer],
1832    // Per-layer sealed o1 (Nystrom) state; Some = replace this layer's
1833    // exact attention with the O(1) kernels. wgpu only.
1834    o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
1835    o1_epoch: u64,
1836    invf: &[f32],
1837    h: &mut [f32],
1838    nh: usize,
1839    nkv: usize,
1840    hd: usize,
1841    attn_scale: f32,
1842    rd: usize,
1843    hidden: usize,
1844    inter: usize,
1845    position: usize,
1846    cap: usize,
1847    gemma: bool,
1848    eps: f32,
1849    lm_head: Option<(&GraphW, usize)>,
1850    final_norm: &[f32],
1851    logits: &mut Vec<f32>,
1852    loop_norm_at: &[usize],
1853    steps: usize,
1854    embed: Option<(&GraphW, usize, f32)>,
1855    ids_out: Option<&mut Vec<u32>>,
1856    // How many leading layers the graph ran (see the wgpu twin) — smaller
1857    // than layers.len() when the expert budget ended the device prefix.
1858    layers_run: Option<&mut usize>,
1859    // Absolute index of layers[0] in the model — the KV/state mirrors key
1860    // on it, so a layer SPAN (network split segment) shares mirrors with
1861    // a full-stack run instead of colliding at slot 0.
1862    layer_base: usize,
1863    // Read the final hidden back alongside the fused head's logits.
1864    hidden_too: bool,
1865) -> TokenGraphOutcome {
1866    match backend() {
1867        #[cfg(feature = "gpu")]
1868        Backend::Wgpu => crate::gpu_wgpu::forward_token_graph(
1869            model,
1870            kv_id,
1871            layers,
1872            o1,
1873            o1_epoch,
1874            invf,
1875            h,
1876            nh,
1877            nkv,
1878            hd,
1879            attn_scale,
1880            rd,
1881            hidden,
1882            inter,
1883            position,
1884            cap,
1885            gemma,
1886            eps,
1887            lm_head,
1888            final_norm,
1889            logits,
1890            loop_norm_at,
1891            steps,
1892            embed,
1893            ids_out,
1894            layers_run,
1895            layer_base,
1896            hidden_too,
1897        ),
1898        #[allow(unused_variables)]
1899        _ => {
1900            let _ = (
1901                attn_scale,
1902                lm_head,
1903                final_norm,
1904                logits,
1905                loop_norm_at,
1906                layers_run,
1907                layer_base,
1908                hidden_too,
1909            );
1910            TokenGraphOutcome::Declined
1911        }
1912    }
1913}
1914
1915/// Whole-token resident graph for the Embryo working model.  Unlike the
1916/// generic graph this path accepts a packed f32 model and keeps both phase
1917/// recurrent state and the anchor KV cache on the device.  `false` is an
1918/// honest capability refusal; callers must retain the CPU executor.
1919pub fn forward_embryo_graph(
1920    model: &Arc<EmbryoGraphModel>,
1921    kv_id: u64,
1922    hidden: &[f32],
1923    position: usize,
1924    logits: &mut Vec<f32>,
1925) -> bool {
1926    #[cfg(feature = "gpu")]
1927    if backend() == Backend::Wgpu {
1928        return crate::gpu_wgpu::forward_embryo_graph(model, kv_id, hidden, position, logits);
1929    }
1930    let _ = (model, kv_id, hidden, position, logits);
1931    false
1932}
1933
1934/// Speculative-verify tail for the batched graph: fold final-norm + lm_head
1935/// over every batch position and read all k logit rows back; the batch also
1936/// snapshots the GDN state per position for `gdn_spec_restore`.
1937#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1938pub enum BatchGraphOutcome {
1939    /// The graph declined before mutating persistent device state. Callers may
1940    /// safely use the existing per-position path.
1941    Declined,
1942    /// The complete batch committed and its readback succeeded.
1943    Completed,
1944    /// A batch that had admitted sealed O(1) state failed after admission.
1945    /// Falling back to CPU would mix two state machines, so the caller must
1946    /// abort and clear the sequence instead.
1947    Failed,
1948}
1949
1950pub struct SpecTail<'a> {
1951    pub lm: GraphW<'a>,
1952    pub lm_rows: usize,
1953    pub final_norm: &'a [f32],
1954    pub logits_out: &'a mut Vec<f32>,
1955}
1956
1957/// Batched prefill: k contiguous positions through the whole graph in one submit
1958/// (projections/FFN as GEMMs, attention/GDN looped over scratch). `h` is
1959/// [k·hidden] in/out; `positions` len k. wgpu only.
1960#[allow(clippy::too_many_arguments)]
1961pub fn forward_batch_graph(
1962    model: &Arc<CmfModel>,
1963    kv_id: u64,
1964    layers: &[GraphLayer],
1965    invf: &[f32],
1966    h: &mut [f32],
1967    nh: usize,
1968    nkv: usize,
1969    hd: usize,
1970    rd: usize,
1971    hidden: usize,
1972    inter: usize,
1973    positions: &[usize],
1974    cap: usize,
1975    gemma: bool,
1976    eps: f32,
1977    attn_scale: f32,
1978    k: usize,
1979    // Per-layer sealed O(1) device views. An empty slice means the ordinary
1980    // exact-KV path; otherwise it must have one entry per graph layer.
1981    o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
1982    o1_epoch: u64,
1983    spec: Option<SpecTail<'_>>,
1984    // Device-prefix mode (plain prefill only): Some = when the whole stack
1985    // does not fit the weight budget, run the leading layers that do — the
1986    // same prefix rule as the token graph — leave the boundary hidden in
1987    // `h` and report the count here; the caller runs the rest on the host.
1988    // None = all layers or a decline, as before.
1989    layers_run: Option<&mut usize>,
1990) -> BatchGraphOutcome {
1991    forward_batch_graph_at(model, kv_id, 0, layers, invf, h, nh, nkv, hd, rd, hidden, inter, positions, cap, gemma, eps, attn_scale, k, o1, o1_epoch, spec, layers_run)
1992}
1993
1994thread_local! {
1995    static MIMO_ATTN_SCRATCH: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
1996}
1997
1998pub(crate) fn mimo_attention_scratch_enabled() -> bool {
1999    MIMO_ATTN_SCRATCH.with(std::cell::Cell::get)
2000}
2001
2002/// Scoped diagnostic A/B switch; unlike process environment mutations it
2003/// cannot race a model's background workers. Restores on panic as well.
2004#[doc(hidden)]
2005pub fn mimo_attention_scratch_scope<R>(enabled: bool, f: impl FnOnce() -> R) -> R {
2006    struct Restore(bool);
2007    impl Drop for Restore {
2008        fn drop(&mut self) {
2009            MIMO_ATTN_SCRATCH.with(|v| v.set(self.0));
2010        }
2011    }
2012    let _restore = Restore(MIMO_ATTN_SCRATCH.with(|v| v.replace(enabled)));
2013    f()
2014}
2015
2016/// Gemma-4's prompt on the batched wgpu graph (`CMF_G4_BATCH=0` keeps the
2017/// chunked host prefill it used before).
2018pub fn g4_batch_on() -> bool {
2019    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2020    *ON.get_or_init(|| std::env::var("CMF_G4_BATCH").as_deref() != Ok("0"))
2021}
2022
2023/// q8_2f MoE experts on the wgpu token and batch graphs (`CMF_MOE_Q82=0`
2024/// keeps them off the graphs: every op on its own, the 0.8.15 route).
2025pub(crate) fn moe_q82_graph_on() -> bool {
2026    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2027    *ON.get_or_init(|| std::env::var("CMF_MOE_Q82").as_deref() != Ok("0"))
2028}
2029
2030thread_local! {
2031    static MIMO_Q8_SHORT: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
2032}
2033
2034pub(crate) fn mimo_q8_short_enabled() -> bool {
2035    MIMO_Q8_SHORT.with(std::cell::Cell::get)
2036}
2037
2038/// Diagnostic A/B switch for row-exact short q8 graph kernels.
2039#[doc(hidden)]
2040pub fn mimo_q8_short_scope<R>(enabled: bool, f: impl FnOnce() -> R) -> R {
2041    struct Restore(bool);
2042    impl Drop for Restore {
2043        fn drop(&mut self) {
2044            MIMO_Q8_SHORT.with(|v| v.set(self.0));
2045        }
2046    }
2047    let _restore = Restore(MIMO_Q8_SHORT.with(|v| v.replace(enabled)));
2048    f()
2049}
2050
2051/// Batched graph over a span whose first absolute layer is `layer_base`.
2052#[allow(clippy::too_many_arguments)]
2053pub fn forward_batch_graph_at(
2054    model: &Arc<CmfModel>,
2055    kv_id: u64,
2056    layer_base: usize,
2057    layers: &[GraphLayer],
2058    invf: &[f32],
2059    h: &mut [f32],
2060    nh: usize,
2061    nkv: usize,
2062    hd: usize,
2063    rd: usize,
2064    hidden: usize,
2065    inter: usize,
2066    positions: &[usize],
2067    cap: usize,
2068    gemma: bool,
2069    eps: f32,
2070    attn_scale: f32,
2071    k: usize,
2072    // Per-layer sealed O(1) device views. An empty slice means the ordinary
2073    // exact-KV path; otherwise it must have one entry per graph layer.
2074    o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
2075    o1_epoch: u64,
2076    spec: Option<SpecTail<'_>>,
2077    // Device-prefix mode (plain prefill only): Some = when the whole stack
2078    // does not fit the weight budget, run the leading layers that do — the
2079    // same prefix rule as the token graph — leave the boundary hidden in
2080    // `h` and report the count here; the caller runs the rest on the host.
2081    // None = all layers or a decline, as before.
2082    layers_run: Option<&mut usize>,
2083) -> BatchGraphOutcome {
2084    match backend() {
2085        #[cfg(feature = "gpu")]
2086        Backend::Wgpu => crate::gpu_wgpu::forward_batch_graph_at(
2087            model, kv_id, layer_base, layers, invf, h, nh, nkv, hd, rd, hidden, inter, positions,
2088            cap, gemma, eps, attn_scale, k, o1, o1_epoch, spec, layers_run,
2089        ),
2090        #[allow(unreachable_patterns)]
2091        _ => {
2092            let _ = (o1, o1_epoch, spec, layers_run);
2093            BatchGraphOutcome::Declined
2094        }
2095    }
2096}
2097
2098/// After a partial speculative acceptance: restore every GDN layer's device
2099/// state to the snapshot after batch position `slot`. `base_pos` is the
2100/// absolute position of the first verify row and `expected_layers` makes the
2101/// restore all-or-nothing across the model's recurrent layers. wgpu only.
2102pub fn gdn_spec_restore(kv_id: u64, slot: usize, base_pos: usize, expected_layers: usize) -> bool {
2103    #[cfg(feature = "gpu")]
2104    if backend() == Backend::Wgpu {
2105        return crate::gpu_wgpu::gdn_spec_restore(kv_id, slot, base_pos, expected_layers);
2106    }
2107    #[allow(unreachable_code)]
2108    {
2109        let _ = (kv_id, slot, base_pos, expected_layers);
2110        false
2111    }
2112}
2113
2114/// Re-point one exact-attention device mirror after a speculative round has
2115/// discarded unaccepted rows. The rows beyond `stored` remain allocated and
2116/// are overwritten by the next append; only the logical cursor moves. This
2117/// is the wgpu twin of Metal's existing mirror cursor helper and keeps the
2118/// MTP graph's speculative/device cache coherent with its real anchor.
2119pub fn graph_kv_set_stored(kv_id: u64, layer: usize, stored: usize) -> bool {
2120    #[cfg(feature = "gpu")]
2121    if backend() == Backend::Wgpu {
2122        return crate::gpu_wgpu::kv_mirror_set_stored(kv_id, layer, stored);
2123    }
2124    #[cfg(target_os = "macos")]
2125    if backend() == Backend::Metal {
2126        crate::gpu_metal::kv_mirror_set_stored(kv_id, layer, stored);
2127        return true;
2128    }
2129    false
2130}
2131
2132/// Rows the wgpu token graph's exact-attention mirror holds for one layer
2133/// (None: no wgpu mirror). Metal keeps its owner cache current per token
2134/// and reports None here.
2135pub fn graph_kv_stored(_kv_id: u64, _layer: usize) -> Option<usize> {
2136    #[cfg(feature = "gpu")]
2137    if backend() == Backend::Wgpu {
2138        return crate::gpu_wgpu::kv_mirror_stored(_kv_id, _layer);
2139    }
2140    None
2141}
2142
2143/// Does the wgpu token graph hold a device-resident recurrent state for
2144/// this layer (one the host `linear_state` has not seen)?
2145pub fn graph_state_resident(_kv_id: u64, _layer: usize) -> bool {
2146    #[cfg(feature = "gpu")]
2147    if backend() == Backend::Wgpu {
2148        return crate::gpu_wgpu::graph_state_resident(_kv_id, _layer);
2149    }
2150    false
2151}
2152
2153/// Copy rows back from the wgpu token graph's K/V mirrors in one submit:
2154/// for each `(layer, from, to)` the K and V rows `[from..to)`, position-major
2155/// (`[(to − from) × nkv × hd]` each).
2156pub fn graph_kv_read_rows(
2157    _kv_id: u64,
2158    _reqs: &[(usize, usize, usize)],
2159    _nkv: usize,
2160    _hd: usize,
2161) -> Option<Vec<(Vec<f32>, Vec<f32>)>> {
2162    #[cfg(feature = "gpu")]
2163    if backend() == Backend::Wgpu {
2164        return crate::gpu_wgpu::kv_mirror_read_rows(_kv_id, _reqs, _nkv, _hd);
2165    }
2166    None
2167}
2168
2169/// Rows `[from, to)` of one wgpu exact-attention mirror in the host
2170/// cache's layout (V zero-padded to `hd`), whatever the mirror's geometry
2171/// (narrow V, a sliding layer's ring). The third value is the first
2172/// position actually read: a ring returns zeros below it. None: no wgpu
2173/// mirror holding those rows at (nkv, hd).
2174pub fn graph_kv_pull_host(
2175    _kv_id: u64,
2176    _layer: usize,
2177    _from: usize,
2178    _to: usize,
2179    _nkv: usize,
2180    _hd: usize,
2181) -> Option<(Vec<f32>, Vec<f32>, usize)> {
2182    #[cfg(feature = "gpu")]
2183    if backend() == Backend::Wgpu {
2184        return crate::gpu_wgpu::kv_mirror_pull_host(_kv_id, _layer, _from, _to, _nkv, _hd);
2185    }
2186    None
2187}
2188
2189/// Drop the wgpu token graph's device K/V mirror for a pipeline.
2190pub fn graph_kv_reset(_kv_id: u64) {
2191    #[cfg(feature = "gpu")]
2192    if backend() == Backend::Wgpu {
2193        crate::gpu_wgpu::kv_mirror_reset(_kv_id);
2194        crate::gpu_wgpu::embryo_graph_reset(_kv_id);
2195    }
2196}
2197
2198/// Ternary (q1t) BASE matvec on the GPU — fills `out` with the base dot; the
2199/// caller adds the sparse overlay on the CPU. Metal only for now (wgpu q1t not
2200/// yet written → CPU fallback).
2201pub fn q1t_matvec(
2202    model: &Arc<CmfModel>,
2203    idx: usize,
2204    xs: &[f32],
2205    rows: usize,
2206    cols: usize,
2207    out: &mut [f32],
2208) -> bool {
2209    match backend() {
2210        #[cfg(target_os = "macos")]
2211        Backend::Metal => {
2212            if metal_q1t_enabled() {
2213                crate::gpu_metal::q1t_matvec(model, idx, xs, rows, cols, out)
2214            } else {
2215                false
2216            }
2217        }
2218        #[cfg(feature = "gpu")]
2219        Backend::Wgpu => crate::gpu_wgpu::q1t_matvec(model, idx, xs, rows, cols, out),
2220        Backend::None => false,
2221    }
2222}
2223
2224/// q4_block matvec on the GPU — wgpu only (Metal drives q4_block through the
2225/// whole-token graph, not a standalone matvec).
2226#[allow(unused_variables)]
2227pub fn q4b_matvec(
2228    model: &Arc<CmfModel>,
2229    idx: usize,
2230    xs: &[f32],
2231    rows: usize,
2232    cols: usize,
2233    out: &mut [f32],
2234) -> bool {
2235    match backend() {
2236        #[cfg(target_os = "macos")]
2237        Backend::Metal => false,
2238        #[cfg(feature = "gpu")]
2239        Backend::Wgpu => crate::gpu_wgpu::q4b_matvec(model, idx, xs, rows, cols, out),
2240        Backend::None => false,
2241    }
2242}
2243
2244/// q1t batched GEMM (prefill) — base + overlay on-device (Metal simdgroup or
2245/// wgpu register-blocked).
2246pub fn q1t_matmat(
2247    model: &Arc<CmfModel>,
2248    idx: usize,
2249    xs: &[f32],
2250    b: usize,
2251    rows: usize,
2252    cols: usize,
2253    out: &mut [f32],
2254) -> bool {
2255    match backend() {
2256        #[cfg(target_os = "macos")]
2257        // Batched prefill and single-token decode are both enabled. On the
2258        // real 14.8B Q1T model prefill PPL was within 0.3% of CPU (7.942 vs
2259        // 7.966), and the alignment-safe decode kernel reached 3.52e-6 max_rel.
2260        Backend::Metal => crate::gpu_metal::q1t_matmat(model, idx, xs, b, rows, cols, out),
2261        #[cfg(feature = "gpu")]
2262        Backend::Wgpu => crate::gpu_wgpu::q1t_matmat(model, idx, xs, b, rows, cols, out),
2263        Backend::None => false,
2264    }
2265}
2266
2267/// Native Metal Q1T switch. Enabled by default after the byte-packed Q1T
2268/// fields were changed to alignment-safe loads; keep an explicit emergency
2269/// fallback for device/driver diagnostics.
2270#[cfg(target_os = "macos")]
2271pub(crate) fn metal_q1t_enabled() -> bool {
2272    std::env::var("CMF_METAL_Q1T")
2273        .map(|v| v != "0" && !v.eq_ignore_ascii_case("off"))
2274        .unwrap_or(true)
2275}
2276
2277/// Batched q1 GEMM (prefill). wgpu only — Metal has its own block path.
2278pub fn q1_matmat(
2279    model: &Arc<CmfModel>,
2280    idx: usize,
2281    xs: &[f32],
2282    b: usize,
2283    rows: usize,
2284    cols: usize,
2285    out: &mut [f32],
2286) -> bool {
2287    match backend() {
2288        #[cfg(feature = "gpu")]
2289        Backend::Wgpu => crate::gpu_wgpu::q1_matmat(model, idx, xs, b, rows, cols, out),
2290        #[allow(unused_variables)]
2291        _ => false,
2292    }
2293}
2294
2295/// Batched q1g GEMM (prefill). wgpu only, like `q1_matmat`.
2296pub fn q1g_matmat(
2297    model: &Arc<CmfModel>,
2298    idx: usize,
2299    xs: &[f32],
2300    b: usize,
2301    rows: usize,
2302    cols: usize,
2303    out: &mut [f32],
2304) -> bool {
2305    match backend() {
2306        #[cfg(feature = "gpu")]
2307        Backend::Wgpu => crate::gpu_wgpu::q1g_matmat(model, idx, xs, b, rows, cols, out),
2308        #[allow(unused_variables)]
2309        _ => false,
2310    }
2311}
2312
2313/// Contention kill for the wide imagegen GEMM/FFN paths: one grossly
2314/// slow op under a work-proportional budget (fair-device ops are
2315/// ≤~100 ms even at 1024px) means another process owns the device —
2316/// verdicts are per-process, so CPU for the rest of this one.
2317static MM_KILL: AtomicBool = AtomicBool::new(false);
2318pub(crate) fn mm_killed() -> bool {
2319    MM_KILL.load(Ordering::Relaxed)
2320}
2321pub(crate) fn mm_kill() {
2322    MM_KILL.store(true, Ordering::Relaxed);
2323}
2324
2325/// Consecutive over-budget ops. ONE slow op is not contention: on a
2326/// 24 GB Mac running the 25.7 GB fl2va file the first ops after the
2327/// prompt encode page their weights in from the SSD and take seconds —
2328/// a field report (hololabs, HF discussion #2) had to neuter the kill
2329/// to keep the denoise on the GPU, and then measured 48 s/step where the
2330/// CPU fallback took >60. Contention is persistent; a page-in is not.
2331static MM_STRIKES: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
2332const MM_STRIKES_TO_KILL: u32 = 3;
2333/// Whether the kill is armed at all. A one-shot phase whose slowness is
2334/// expected and not contention — the video prompt encoder streaming
2335/// 12 GB off the SSD on a 24 GB Mac (HF discussion #4: users had to
2336/// gut `mm_kill` to keep the denoise loop on the GPU) — disarms it and
2337/// re-arms it when the phase is over; strikes taken meanwhile are
2338/// forgotten.
2339static MM_ARMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
2340
2341/// Disarm / re-arm the contention kill around a phase whose GEMMs are
2342/// slow for reasons that are not another process (see `MM_ARMED`).
2343pub fn mm_kill_arm(on: bool) {
2344    MM_ARMED.store(on, Ordering::Relaxed);
2345    if on {
2346        MM_STRIKES.store(0, Ordering::Relaxed);
2347    }
2348}
2349
2350/// The contention verdict for one wide op: `el` against its
2351/// work-proportional `budget`. `exempt` marks ops whose time is not
2352/// evidence — the cold probe, or a weight that was not resident before
2353/// the call and rode in with it. Kills after `MM_STRIKES_TO_KILL`
2354/// consecutive strikes; a within-budget op clears the count.
2355/// `CMF_MM_KILL=0` disables the kill entirely (the device is trusted).
2356pub(crate) fn mm_budget_check(
2357    what: &str,
2358    el: std::time::Duration,
2359    budget: std::time::Duration,
2360    exempt: bool,
2361) {
2362    if el <= budget {
2363        MM_STRIKES.store(0, Ordering::Relaxed);
2364        return;
2365    }
2366    if exempt || !MM_ARMED.load(Ordering::Relaxed) {
2367        return;
2368    }
2369    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2370    let on = *ON.get_or_init(|| std::env::var("CMF_MM_KILL").as_deref() != Ok("0"));
2371    let n = MM_STRIKES.fetch_add(1, Ordering::Relaxed) + 1;
2372    if !on {
2373        tracing::info!(
2374            "gpu {what} took {el:?} (budget {budget:?}) — over budget, CMF_MM_KILL=0 keeps the device"
2375        );
2376        return;
2377    }
2378    if n >= MM_STRIKES_TO_KILL {
2379        tracing::warn!(
2380            "gpu {what} took {el:?} (budget {budget:?}), {n} in a row — \
2381             device contended, CPU for the rest of the process (CMF_MM_KILL=0 to override)"
2382        );
2383        mm_kill();
2384    } else {
2385        tracing::info!(
2386            "gpu {what} took {el:?} (budget {budget:?}) — strike {n} of {MM_STRIKES_TO_KILL}"
2387        );
2388    }
2389}
2390
2391/// Fused DiT SwiGLU FFN on the device: g=X·W1ᵀ, u=X·W3ᵀ, silu(g)·u,
2392/// Causal chunk attention on the device: `b` queries against `s0 + b`
2393/// cached keys. wgpu only — Metal's chunk graph keeps attention inside
2394/// the resident block and never calls out.
2395#[allow(unused_variables, clippy::too_many_arguments)]
2396pub fn chunk_attend(
2397    q: &[f32],
2398    k: &[&[f32]],
2399    v: &[&[f32]],
2400    b: usize,
2401    s0: usize,
2402    nh: usize,
2403    nkv: usize,
2404    hd: usize,
2405    scale: f32,
2406    out: &mut [f32],
2407) -> bool {
2408    match backend() {
2409        #[cfg(feature = "gpu")]
2410        Backend::Wgpu => crate::gpu_wgpu::chunk_attend(q, k, v, b, s0, nh, nkv, hd, scale, out),
2411        #[allow(unreachable_patterns)]
2412        _ => false,
2413    }
2414}
2415
2416/// `chunk_attend` under a sliding window (`window` keys, the query's own
2417/// included). wgpu only; see `chunk_attend_windowed`.
2418#[allow(unused_variables, clippy::too_many_arguments)]
2419pub fn chunk_attend_win(
2420    q: &[f32],
2421    k: &[&[f32]],
2422    v: &[&[f32]],
2423    b: usize,
2424    s0: usize,
2425    nh: usize,
2426    nkv: usize,
2427    hd: usize,
2428    scale: f32,
2429    window: usize,
2430    out: &mut [f32],
2431) -> bool {
2432    match backend() {
2433        #[cfg(feature = "gpu")]
2434        Backend::Wgpu => {
2435            crate::gpu_wgpu::chunk_attend_win(q, k, v, b, s0, nh, nkv, hd, scale, window, out)
2436        }
2437        #[allow(unreachable_patterns)]
2438        _ => false,
2439    }
2440}
2441
2442/// Several projections of one host activation, read back in one trip:
2443/// `out` = [P0 | P1 | …], each `idxs` entry (tensor, rows). wgpu only.
2444#[allow(unused_variables)]
2445pub fn gemm_many_keep(
2446    model: &Arc<CmfModel>,
2447    idxs: &[(usize, usize)],
2448    xs: &[f32],
2449    b: usize,
2450    cols: usize,
2451    out: &mut [f32],
2452) -> bool {
2453    match backend() {
2454        #[cfg(feature = "gpu")]
2455        Backend::Wgpu => crate::gpu_wgpu::gemm_many_keep(model, idxs, xs, b, cols, out),
2456        #[allow(unreachable_patterns)]
2457        _ => false,
2458    }
2459}
2460
2461thread_local! {
2462    /// Set by the pipeline around a layer of Spark-X2.5's batched prefill:
2463    /// its int8 matrix-unit GEMMs may take the `zi_mm` tile, and the
2464    /// projections that read one activation share its upload (wgpu).
2465    static PREFILL_FAST_GEMM: Cell<bool> = const { Cell::new(false) };
2466}
2467
2468/// Restores the previous flag on drop.
2469pub struct PrefillFastGemmGuard(bool);
2470
2471impl Drop for PrefillFastGemmGuard {
2472    fn drop(&mut self) {
2473        PREFILL_FAST_GEMM.with(|c| c.set(self.0));
2474    }
2475}
2476
2477/// Let this thread's int8 matrix-unit GEMMs take the `zi_mm` tile for the
2478/// guard's lifetime (bit-identical to the 64x64 kernel; see
2479/// `gpu_wgpu::zi_gemm_route`).
2480pub fn enter_prefill_fast_gemm() -> PrefillFastGemmGuard {
2481    PrefillFastGemmGuard(PREFILL_FAST_GEMM.with(|c| c.replace(true)))
2482}
2483
2484/// Whether `enter_prefill_fast_gemm` is in force on this thread.
2485pub fn prefill_fast_gemm() -> bool {
2486    PREFILL_FAST_GEMM.with(|c| c.get())
2487}
2488
2489/// The largest finite f16. An operand the matrix-unit attention casts to
2490/// f16 must stay within it, or the cast overflows to inf.
2491pub const F16_MAX: f32 = 65504.0;
2492
2493/// max |x| over `xs`, or +inf when an entry is inf or NaN: the value the
2494/// f16 operand guards compare with `F16_MAX`. Sixteen independent lanes
2495/// and a flag, so it vectorizes (a single `fold` chain does not).
2496pub fn abs_max_or_inf(xs: &[f32]) -> f32 {
2497    let mut acc = [0f32; 16];
2498    let mut bad = [false; 16];
2499    let mut it = xs.chunks_exact(16);
2500    for c in &mut it {
2501        for ((a, f), &v) in acc.iter_mut().zip(bad.iter_mut()).zip(c) {
2502            let v = v.abs();
2503            // NaN compares false both ways: flagged, never taken.
2504            *f |= !(v < f32::INFINITY);
2505            *a = if v > *a { v } else { *a };
2506        }
2507    }
2508    let mut m = 0f32;
2509    for &v in it.remainder() {
2510        let v = v.abs();
2511        if !(v < f32::INFINITY) {
2512            return f32::INFINITY;
2513        }
2514        m = m.max(v);
2515    }
2516    if bad.iter().any(|&f| f) {
2517        return f32::INFINITY;
2518    }
2519    acc.iter().fold(m, |m, &a| m.max(a))
2520}
2521
2522/// The decode graph's device K/V mirror a prefill chunk of one layer also
2523/// writes to (wgpu): `kv_id` is the pipeline's graph id, `layer` the
2524/// virtual layer index, `limit` the cache's `max_seq_len` — the same key
2525/// and capacity ceiling the token graph uses, so the mirror the prefill
2526/// fills is the one the first decode token reads.
2527#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2528pub struct PrefillMirror {
2529    pub kv_id: u64,
2530    pub layer: usize,
2531    pub limit: usize,
2532}
2533
2534thread_local! {
2535    /// Set by the pipeline around one layer's batched attention (see
2536    /// `enter_prefill_mirror`); every other caller of the batched
2537    /// attention (MTP heads, tests) sees None and keeps the host upload.
2538    static PREFILL_MIRROR: Cell<Option<PrefillMirror>> = const { Cell::new(None) };
2539}
2540
2541/// Restores the previous target on drop.
2542pub struct PrefillMirrorGuard(Option<PrefillMirror>);
2543
2544impl Drop for PrefillMirrorGuard {
2545    fn drop(&mut self) {
2546        PREFILL_MIRROR.with(|c| c.set(self.0));
2547    }
2548}
2549
2550/// Name the device mirror the current layer's prefill chunk appends to
2551/// and attends against, for the guard's lifetime.
2552pub fn enter_prefill_mirror(t: PrefillMirror) -> PrefillMirrorGuard {
2553    PrefillMirrorGuard(PREFILL_MIRROR.with(|c| c.replace(Some(t))))
2554}
2555
2556/// The mirror `enter_prefill_mirror` named on this thread, if any.
2557pub fn prefill_mirror() -> Option<PrefillMirror> {
2558    PREFILL_MIRROR.with(|c| c.get())
2559}
2560
2561/// `chunk_attend_win` against the decode graph's device mirror instead of
2562/// an upload of the whole prefix: the host rows the mirror lacks (the
2563/// chunk's own `b`, or more after a host-only chunk) are appended first,
2564/// then the attention binds the mirror rows in place. `s0` is the chunk's
2565/// first position and `base` the position of host row 0
2566/// (`LayerKvCache::base`: past 0 on a trimmed sliding tail). `ring` is the
2567/// layer's window as the mirror geometry (Some on every sliding layer),
2568/// `window` the window the softmax masks with (0 while it masks nothing).
2569/// `operand_max` = max |x| over `q` and every K/V row the attend reads
2570/// (`abs_max_or_inf`; +inf when unknown): past `F16_MAX` the f32 kernels
2571/// run instead of the matrix units. wgpu only; false = nothing attended
2572/// (the caller uploads as before).
2573#[allow(unused_variables, clippy::too_many_arguments)]
2574pub fn chunk_attend_mirror(
2575    t: PrefillMirror,
2576    cpu_k: &[Vec<f32>],
2577    cpu_v: &[Vec<f32>],
2578    base: usize,
2579    q: &[f32],
2580    b: usize,
2581    s0: usize,
2582    nh: usize,
2583    nkv: usize,
2584    hd: usize,
2585    scale: f32,
2586    ring: Option<usize>,
2587    window: usize,
2588    operand_max: f32,
2589    out: &mut [f32],
2590) -> bool {
2591    match backend() {
2592        #[cfg(feature = "gpu")]
2593        // QKᵀ and P·V on the matrix units where the device has them (f16
2594        // operands, f32 accumulators — not bit-identical to the f32
2595        // kernels: Spark-X2.5 4B q8_2f wiki ppl 10.677 -> 10.672);
2596        // `CMF_PREFILL_ATTN_COOP=0` keeps the f32 ones (A/B).
2597        Backend::Wgpu => crate::gpu_wgpu::chunk_attend_mirror(
2598            t.kv_id,
2599            t.layer,
2600            t.limit,
2601            cpu_k,
2602            cpu_v,
2603            base,
2604            q,
2605            b,
2606            s0,
2607            nh,
2608            nkv,
2609            hd,
2610            scale,
2611            ring,
2612            window,
2613            std::env::var("CMF_PREFILL_ATTN_COOP").as_deref() != Ok("0"),
2614            operand_max,
2615            out,
2616        ),
2617        #[allow(unreachable_patterns)]
2618        _ => false,
2619    }
2620}
2621
2622/// `chunk_attend_mirror`, then the head gate (`gains`, b × nh, computed on
2623/// the host) and the O projection `wo` on the card: the attention output
2624/// never comes home. `out` = [b][hidden]. The card scans the O operand
2625/// itself, which is the host path's product bit for bit only while max
2626/// |gated output| <= 1000: the caller vouches for that (Spark-X2.5's
2627/// prefill, max |v| <= 990). wgpu only; false = nothing written to `out`
2628/// (the caller attends and projects as before).
2629#[allow(unused_variables, clippy::too_many_arguments)]
2630pub fn chunk_attend_mirror_wo(
2631    t: PrefillMirror,
2632    cpu_k: &[Vec<f32>],
2633    cpu_v: &[Vec<f32>],
2634    base: usize,
2635    q: &[f32],
2636    b: usize,
2637    s0: usize,
2638    nh: usize,
2639    nkv: usize,
2640    hd: usize,
2641    scale: f32,
2642    ring: Option<usize>,
2643    window: usize,
2644    operand_max: f32,
2645    gains: Option<&[f32]>,
2646    wo: (&Arc<CmfModel>, usize),
2647    hidden: usize,
2648    out: &mut [f32],
2649) -> bool {
2650    match backend() {
2651        #[cfg(feature = "gpu")]
2652        Backend::Wgpu => crate::gpu_wgpu::chunk_attend_mirror_wo(
2653            t.kv_id,
2654            t.layer,
2655            t.limit,
2656            cpu_k,
2657            cpu_v,
2658            base,
2659            q,
2660            b,
2661            s0,
2662            nh,
2663            nkv,
2664            hd,
2665            scale,
2666            ring,
2667            window,
2668            std::env::var("CMF_PREFILL_ATTN_COOP").as_deref() != Ok("0"),
2669            operand_max,
2670            gains,
2671            wo,
2672            hidden,
2673            out,
2674        ),
2675        #[allow(unreachable_patterns)]
2676        _ => false,
2677    }
2678}
2679
2680/// Whether the active backend's chunk attend can apply a sliding window.
2681pub fn chunk_attend_windowed() -> bool {
2682    match backend() {
2683        #[cfg(feature = "gpu")]
2684        Backend::Wgpu => true,
2685        #[allow(unreachable_patterns)]
2686        _ => false,
2687    }
2688}
2689
2690/// Fused QKV projection: one upload of the normed chunk, three GEMMs,
2691/// one readback of Q|K|V back to back. Metal has no twin yet — its
2692/// chunk graph keeps the whole layer resident and never surfaces QKV.
2693#[allow(unused_variables, clippy::too_many_arguments)]
2694pub fn q4t_qkv(
2695    model: &Arc<CmfModel>,
2696    wq: usize,
2697    wk: usize,
2698    wv: usize,
2699    xs: &[f32],
2700    b: usize,
2701    cols: usize,
2702    rq: usize,
2703    rk: usize,
2704    rv: usize,
2705    out: &mut [f32],
2706) -> bool {
2707    match backend() {
2708        #[cfg(feature = "gpu")]
2709        Backend::Wgpu => crate::gpu_wgpu::q4t_qkv(model, wq, wk, wv, xs, b, cols, rq, rk, rv, out),
2710        #[allow(unreachable_patterns)]
2711        _ => false,
2712    }
2713}
2714
2715/// y=·W2ᵀ — one command buffer, only X and Y cross the CPU boundary.
2716#[allow(unused_variables, clippy::too_many_arguments)]
2717/// SwiGLU FFN with a row-packed [gate|up] fc1 (MiniMax-H3's DiT), run
2718/// end to end on the device. wgpu only: Metal keeps the host loop until
2719/// its own packed kernel exists.
2720#[allow(clippy::too_many_arguments, unused_variables)]
2721pub fn q4tp_ffn_packed(
2722    model: &Arc<CmfModel>,
2723    w1: usize,
2724    w2: usize,
2725    xs: &[f32],
2726    b: usize,
2727    hidden: usize,
2728    inter: usize,
2729    bias: Option<&[f32]>,
2730    out: &mut [f32],
2731) -> bool {
2732    match backend() {
2733        #[cfg(feature = "gpu")]
2734        Backend::Wgpu => {
2735            crate::gpu_wgpu::ffn_packed(model, w1, w2, xs, b, hidden, inter, bias, out)
2736        }
2737        #[allow(unreachable_patterns)]
2738        _ => false,
2739    }
2740}
2741
2742pub fn q4tp_ffn(
2743    model: &Arc<CmfModel>,
2744    w1: usize,
2745    w3: usize,
2746    w2: usize,
2747    xs: &[f32],
2748    b: usize,
2749    hidden: usize,
2750    inter: usize,
2751    out: &mut [f32],
2752) -> bool {
2753    match backend() {
2754        #[cfg(target_os = "macos")]
2755        Backend::Metal => crate::gpu_metal::q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
2756        #[cfg(feature = "gpu")]
2757        Backend::Wgpu => crate::gpu_wgpu::q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
2758        #[allow(unreachable_patterns)]
2759        _ => false,
2760    }
2761}
2762
2763/// `q4tp_ffn` (`q4tp` = true) / `q4t_ffn` with the activation named:
2764/// SiLU takes the plain entry points (every backend), the exact GELU of
2765/// Spark-X2.5 has a wgpu arm only — other backends decline it.
2766#[allow(clippy::too_many_arguments, unused_variables)]
2767pub fn q4_ffn_act(
2768    model: &Arc<CmfModel>,
2769    w1: usize,
2770    w3: usize,
2771    w2: usize,
2772    xs: &[f32],
2773    b: usize,
2774    hidden: usize,
2775    inter: usize,
2776    q4tp: bool,
2777    act: GraphAct,
2778    out: &mut [f32],
2779) -> bool {
2780    match act {
2781        GraphAct::Silu if q4tp => q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
2782        GraphAct::Silu => q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
2783        GraphAct::GeluErf | GraphAct::GeluTanh => match backend() {
2784            #[cfg(feature = "gpu")]
2785            Backend::Wgpu => crate::gpu_wgpu::q4_ffn_act(
2786                model,
2787                w1,
2788                w3,
2789                w2,
2790                xs,
2791                b,
2792                hidden,
2793                inter,
2794                q4tp,
2795                act.code(),
2796                out,
2797            ),
2798            #[allow(unreachable_patterns)]
2799            _ => false,
2800        },
2801    }
2802}
2803
2804/// The LLM prefill's dense FFN for separate gate/up/down weights in any
2805/// codec with a device GEMM (int8, q4tp, or a mix of them): the panels
2806/// stay on the card between the projections. wgpu only; other backends
2807/// decline and the caller keeps its per-GEMM path.
2808#[allow(clippy::too_many_arguments, unused_variables)]
2809pub fn ffn_act_keep(
2810    model: &Arc<CmfModel>,
2811    w1: usize,
2812    w3: usize,
2813    w2: usize,
2814    xs: &[f32],
2815    b: usize,
2816    hidden: usize,
2817    inter: usize,
2818    act: GraphAct,
2819    out: &mut [f32],
2820) -> bool {
2821    match backend() {
2822        #[cfg(feature = "gpu")]
2823        Backend::Wgpu => crate::gpu_wgpu::ffn_act_keep(
2824            model,
2825            w1,
2826            w3,
2827            w2,
2828            xs,
2829            b,
2830            hidden,
2831            inter,
2832            act.code(),
2833            out,
2834        ),
2835        #[allow(unreachable_patterns)]
2836        _ => false,
2837    }
2838}
2839
2840/// Qwen Image's exact two-projection tanh-GELU FFN.  The WGPU arm keeps the
2841/// intermediate on the device; other backends decline so the caller retains
2842/// its bounded CPU path.  `bias_in` is applied before GELU and `bias_out`
2843/// after the second projection, matching the official transformer.
2844#[allow(clippy::too_many_arguments, unused_variables)]
2845pub fn q4tp_gelu_ffn(
2846    model: &Arc<CmfModel>,
2847    w_in: usize,
2848    w_out: usize,
2849    xs: &[f32],
2850    b: usize,
2851    hidden: usize,
2852    inter: usize,
2853    bias_in: &[f32],
2854    bias_out: &[f32],
2855    out: &mut [f32],
2856) -> bool {
2857    match backend() {
2858        #[cfg(feature = "gpu")]
2859        Backend::Wgpu => crate::gpu_wgpu::q4tp_gelu_ffn(
2860            model, w_in, w_out, xs, b, hidden, inter, bias_in, bias_out, out,
2861        ),
2862        #[allow(unreachable_patterns)]
2863        _ => false,
2864    }
2865}
2866
2867pub fn q4t_ffn(
2868    model: &Arc<CmfModel>,
2869    w1: usize,
2870    w3: usize,
2871    w2: usize,
2872    xs: &[f32],
2873    b: usize,
2874    hidden: usize,
2875    inter: usize,
2876    out: &mut [f32],
2877) -> bool {
2878    match backend() {
2879        #[cfg(target_os = "macos")]
2880        Backend::Metal => crate::gpu_metal::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
2881        #[cfg(feature = "gpu")]
2882        Backend::Wgpu => crate::gpu_wgpu::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
2883        #[allow(unreachable_patterns)]
2884        _ => false,
2885    }
2886}
2887
2888/// One whole modulated DiT block for `dit_block`: geometry, norm
2889/// weights, AdaLN scale/gate vectors (gates pre-tanh'd), a per-token
2890/// f32 RoPE cos/sin table, and the directory indices of the seven
2891/// q4t projections. `x` is in-out `[n, hidden]`.
2892pub struct DitBlockArgs<'a> {
2893    pub n: usize,
2894    pub hidden: usize,
2895    pub inter: usize,
2896    pub nh: usize,
2897    pub nkv: usize,
2898    pub hd: usize,
2899    pub eps: f32,
2900    pub rope_cos: &'a [f32],
2901    pub rope_sin: &'a [f32],
2902    pub norm1: &'a [f32],
2903    pub norm2: &'a [f32],
2904    pub ffn_norm1: &'a [f32],
2905    pub ffn_norm2: &'a [f32],
2906    pub norm_q: &'a [f32],
2907    pub norm_k: &'a [f32],
2908    pub s_msa: &'a [f32],
2909    pub gate_msa: &'a [f32],
2910    pub s_mlp: &'a [f32],
2911    pub gate_mlp: &'a [f32],
2912    pub wq: usize,
2913    pub wk: usize,
2914    pub wv: usize,
2915    pub wo: usize,
2916    pub w1: usize,
2917    pub w3: usize,
2918    pub w2: usize,
2919    /// The projections' layout: q4tp (ladder scales) vs plain q4_tiled.
2920    /// The recommended Lumina file is q4tp, and a backend that only
2921    /// knows q4t must decline rather than decode with the wrong reader.
2922    pub q4tp: bool,
2923    /// The hidden state is already on the device from the previous block,
2924    /// so `x` need not be uploaded.
2925    pub resident_in: bool,
2926    /// Leave the result on the device instead of reading it back. The DiT
2927    /// loop does not touch `x` between blocks, so 27 of every 28 readbacks
2928    /// were moving 19 MB across PCIe and stalling on it for nothing.
2929    pub resident_out: bool,
2930}
2931
2932/// Can the selected backend keep the DiT's hidden state on the device
2933/// between blocks? Only the wgpu whole-block path; the Metal entry takes
2934/// and returns host memory every call.
2935pub fn dit_chain_supported() -> bool {
2936    #[cfg(feature = "gpu")]
2937    {
2938        return matches!(backend(), Backend::Wgpu) && fused_dit_block_available();
2939    }
2940    #[allow(unreachable_code)]
2941    false
2942}
2943
2944/// Pull the resident hidden state back to the host. For the caller that
2945/// chained blocks and then hit one the device declined.
2946pub fn dit_state_fetch(_x: &mut [f32]) -> bool {
2947    #[cfg(feature = "gpu")]
2948    {
2949        if matches!(backend(), Backend::Wgpu) {
2950            return crate::gpu_wgpu::dit_state_fetch(_x);
2951        }
2952    }
2953    false
2954}
2955
2956/// One whole modulated DiT block on the device — norms, qkv, RoPE,
2957/// attention, residuals and the SwiGLU FFN in a single command
2958/// buffer; only `x` crosses the CPU boundary (in and out).
2959#[allow(unused_variables)]
2960/// The DiT's three projections in one submission (wgpu only; the
2961/// Metal path fuses the whole block instead). False = the caller keeps
2962/// its three separate calls.
2963#[allow(unused_variables, clippy::too_many_arguments)]
2964pub fn dit_qkv(
2965    model: &Arc<CmfModel>,
2966    wq: usize,
2967    wk: usize,
2968    wv: usize,
2969    xs: &[f32],
2970    b: usize,
2971    hidden: usize,
2972    qrows: usize,
2973    kvrows: usize,
2974    q_out: &mut [f32],
2975    k_out: &mut [f32],
2976    v_out: &mut [f32],
2977) -> bool {
2978    match backend() {
2979        #[cfg(feature = "gpu")]
2980        Backend::Wgpu => crate::gpu_wgpu::q4tp_qkv(
2981            model, wq, wk, wv, xs, b, hidden, qrows, kvrows, q_out, k_out, v_out,
2982        ),
2983        #[allow(unreachable_patterns)]
2984        _ => false,
2985    }
2986}
2987
2988/// The Qwen Image double-stream attention half.  The WGPU implementation
2989/// keeps the six Q/K/V projections, the stream join, qk-norm/RoPE, joint
2990/// attention, and both output projections on the device; the caller only
2991/// supplies the two normalized streams and receives the two projected
2992/// streams.  A backend or codec that cannot satisfy the full contract
2993/// returns `false` before changing either output, so the native host path
2994/// remains the portable fallback.
2995pub struct QwenImageAttentionArgs<'a> {
2996    pub image: &'a [f32],
2997    pub text: &'a [f32],
2998    pub image_tokens: usize,
2999    pub text_tokens: usize,
3000    pub heads: usize,
3001    pub head_dim: usize,
3002    pub image_q: usize,
3003    pub image_k: usize,
3004    pub image_v: usize,
3005    pub text_q: usize,
3006    pub text_k: usize,
3007    pub text_v: usize,
3008    pub image_out: usize,
3009    pub text_out: usize,
3010    pub image_q_norm: &'a [f32],
3011    pub image_k_norm: &'a [f32],
3012    pub text_q_norm: &'a [f32],
3013    pub text_k_norm: &'a [f32],
3014    pub image_cos: &'a [f32],
3015    pub image_sin: &'a [f32],
3016    pub text_cos: &'a [f32],
3017    pub text_sin: &'a [f32],
3018    pub image_q_bias: &'a [f32],
3019    pub image_k_bias: &'a [f32],
3020    pub image_v_bias: &'a [f32],
3021    pub text_q_bias: &'a [f32],
3022    pub text_k_bias: &'a [f32],
3023    pub text_v_bias: &'a [f32],
3024    pub image_out_bias: &'a [f32],
3025    pub text_out_bias: &'a [f32],
3026    pub image_proj: &'a mut [f32],
3027    pub text_proj: &'a mut [f32],
3028}
3029
3030/// The per-layer controls and Q4TP directory indices used by the native
3031/// Qwen block.  Keeping this descriptor separate from the stream buffers
3032/// lets a whole transformer forward reuse one explicit device state without
3033/// a global scratch slot or a hidden context label.
3034#[allow(clippy::too_many_fields)]
3035pub struct QwenImageChainBlock<'a> {
3036    pub image_mod: &'a [f32],
3037    pub text_mod: &'a [f32],
3038    pub image_q: usize,
3039    pub image_k: usize,
3040    pub image_v: usize,
3041    pub text_q: usize,
3042    pub text_k: usize,
3043    pub text_v: usize,
3044    pub image_out: usize,
3045    pub text_out: usize,
3046    pub image_q_norm: &'a [f32],
3047    pub image_k_norm: &'a [f32],
3048    pub text_q_norm: &'a [f32],
3049    pub text_k_norm: &'a [f32],
3050    pub image_q_bias: &'a [f32],
3051    pub image_k_bias: &'a [f32],
3052    pub image_v_bias: &'a [f32],
3053    pub text_q_bias: &'a [f32],
3054    pub text_k_bias: &'a [f32],
3055    pub text_v_bias: &'a [f32],
3056    pub image_out_bias: &'a [f32],
3057    pub text_out_bias: &'a [f32],
3058    pub image_attn_gate: &'a [f32],
3059    pub text_attn_gate: &'a [f32],
3060    pub image_mlp_in: usize,
3061    pub image_mlp_out: usize,
3062    pub text_mlp_in: usize,
3063    pub text_mlp_out: usize,
3064    pub image_mlp_in_bias: &'a [f32],
3065    pub image_mlp_out_bias: &'a [f32],
3066    pub text_mlp_in_bias: &'a [f32],
3067    pub text_mlp_out_bias: &'a [f32],
3068}
3069
3070/// Complete Qwen Image transformer block contract. The first norm/mod
3071/// panels are supplied by the native caller; the WGPU arm keeps both streams
3072/// resident through QKV, QK/RoPE, joint attention, output projections, both
3073/// gated residuals, and the exact tanh-GELU MLPs. A backend that cannot
3074/// satisfy the whole graph returns `false` without changing either output.
3075#[allow(clippy::too_many_fields)]
3076pub struct QwenImageBlockArgs<'a> {
3077    /// Raw stream state is read for the first gated residual and overwritten
3078    /// with the block's final state after the one readback.
3079    pub image: &'a mut [f32],
3080    pub text: &'a mut [f32],
3081    pub image_norm: &'a [f32],
3082    pub text_norm: &'a [f32],
3083    pub image_tokens: usize,
3084    pub text_tokens: usize,
3085    pub heads: usize,
3086    pub head_dim: usize,
3087    pub image_cos: &'a [f32],
3088    pub image_sin: &'a [f32],
3089    pub text_cos: &'a [f32],
3090    pub text_sin: &'a [f32],
3091    pub image_q: usize,
3092    pub image_k: usize,
3093    pub image_v: usize,
3094    pub text_q: usize,
3095    pub text_k: usize,
3096    pub text_v: usize,
3097    pub image_out: usize,
3098    pub text_out: usize,
3099    pub image_q_norm: &'a [f32],
3100    pub image_k_norm: &'a [f32],
3101    pub text_q_norm: &'a [f32],
3102    pub text_k_norm: &'a [f32],
3103    pub image_q_bias: &'a [f32],
3104    pub image_k_bias: &'a [f32],
3105    pub image_v_bias: &'a [f32],
3106    pub text_q_bias: &'a [f32],
3107    pub text_k_bias: &'a [f32],
3108    pub text_v_bias: &'a [f32],
3109    pub image_out_bias: &'a [f32],
3110    pub text_out_bias: &'a [f32],
3111    pub image_attn_gate: &'a [f32],
3112    pub text_attn_gate: &'a [f32],
3113    pub image_mlp_in: usize,
3114    pub image_mlp_out: usize,
3115    pub text_mlp_in: usize,
3116    pub text_mlp_out: usize,
3117    pub image_mlp_in_bias: &'a [f32],
3118    pub image_mlp_out_bias: &'a [f32],
3119    pub text_mlp_in_bias: &'a [f32],
3120    pub text_mlp_out_bias: &'a [f32],
3121    pub image_mlp_mod: &'a [f32],
3122    pub text_mlp_mod: &'a [f32],
3123    pub image_mlp_gate: &'a [f32],
3124    pub text_mlp_gate: &'a [f32],
3125}
3126
3127/// Explicit whole-forward Qwen state contract.  The WGPU backend uploads the
3128/// two initial streams once, encodes a bounded number of complete blocks per
3129/// submission, and reads the final state once.  `blocks` is immutable for the
3130/// call, while the two stream slices receive only the final readback.
3131pub struct QwenImageChainArgs<'a> {
3132    pub image: &'a mut [f32],
3133    pub text: &'a mut [f32],
3134    pub image_tokens: usize,
3135    pub text_tokens: usize,
3136    pub heads: usize,
3137    pub head_dim: usize,
3138    pub image_cos: &'a [f32],
3139    pub image_sin: &'a [f32],
3140    pub text_cos: &'a [f32],
3141    pub text_sin: &'a [f32],
3142    pub blocks: &'a [QwenImageChainBlock<'a>],
3143}
3144
3145#[allow(unused_variables)]
3146pub fn qwen_image_attention(
3147    model: &Arc<CmfModel>,
3148    args: &mut QwenImageAttentionArgs<'_>,
3149) -> bool {
3150    match backend() {
3151        #[cfg(feature = "gpu")]
3152        Backend::Wgpu => crate::gpu_wgpu::qwen_image_attention(model, args),
3153        #[allow(unreachable_patterns)]
3154        _ => false,
3155    }
3156}
3157
3158#[allow(unused_variables)]
3159pub fn qwen_image_block(model: &Arc<CmfModel>, args: &mut QwenImageBlockArgs<'_>) -> bool {
3160    match backend() {
3161        #[cfg(feature = "gpu")]
3162        Backend::Wgpu => crate::gpu_wgpu::qwen_image_block(model, args),
3163        #[allow(unreachable_patterns)]
3164        _ => false,
3165    }
3166}
3167
3168/// Keep all Qwen transformer blocks on the selected WGPU device, with only
3169/// bounded chunk submissions and one final readback.  Other backends decline
3170/// so the native caller can use its exact portable block loop.
3171#[allow(unused_variables)]
3172pub fn qwen_image_chain(model: &Arc<CmfModel>, args: &mut QwenImageChainArgs<'_>) -> bool {
3173    match backend() {
3174        #[cfg(feature = "gpu")]
3175        Backend::Wgpu => crate::gpu_wgpu::qwen_image_chain(model, args),
3176        #[allow(unreachable_patterns)]
3177        _ => false,
3178    }
3179}
3180
3181/// The Qwen Image second sub-block on WGPU: affine-free LayerNorm,
3182/// shift/scale modulation, Q4TP input projection, exact tanh-GELU, output
3183/// projection, bias and gated residual.  `data` is updated in place after a
3184/// single final readback.  Backends/codecs that cannot keep this chain on the
3185/// device return `false` before changing `data`, leaving the caller's
3186/// portable per-op path intact.
3187#[allow(unused_variables, clippy::too_many_arguments)]
3188pub fn qwen_image_mlp_inplace(
3189    model: &Arc<CmfModel>,
3190    w_in: usize,
3191    w_out: usize,
3192    data: &mut [f32],
3193    batch: usize,
3194    hidden: usize,
3195    inter: usize,
3196    bias_in: &[f32],
3197    bias_out: &[f32],
3198    modulation: &[f32],
3199    gate: &[f32],
3200) -> bool {
3201    match backend() {
3202        #[cfg(feature = "gpu")]
3203        Backend::Wgpu => crate::gpu_wgpu::qwen_image_mlp_inplace(
3204            model,
3205            w_in,
3206            w_out,
3207            data,
3208            batch,
3209            hidden,
3210            inter,
3211            bias_in,
3212            bias_out,
3213            modulation,
3214            gate,
3215        ),
3216        #[allow(unreachable_patterns)]
3217        _ => false,
3218    }
3219}
3220
3221/// Is a FUSED whole-block device path on offer? The batched-CFG shape
3222/// (two sequences in one tall batch) and the fused block (one sequence,
3223/// one command buffer) are alternatives, and the caller picks.
3224pub fn fused_dit_block_available() -> bool {
3225    #[cfg(target_os = "macos")]
3226    {
3227        matches!(backend(), Backend::Metal) && fused_block_trusted()
3228    }
3229    #[cfg(not(target_os = "macos"))]
3230    {
3231        false
3232    }
3233}
3234
3235pub fn dit_block(model: &Arc<CmfModel>, a: &DitBlockArgs, x: &mut [f32]) -> bool {
3236    dit_block_seg(model, a, &[a.n], x)
3237}
3238
3239/// The same block over a CONCATENATION of independent sequences:
3240/// attention per segment, everything position-wise batched. wgpu only —
3241/// the Metal path takes the single-sequence entry above.
3242pub fn dit_block_seg(
3243    model: &Arc<CmfModel>,
3244    a: &DitBlockArgs,
3245    segs: &[usize],
3246    x: &mut [f32],
3247) -> bool {
3248    match backend() {
3249        #[cfg(target_os = "macos")]
3250        Backend::Metal if segs.len() <= 1 => crate::gpu_metal::dit_block(model, a, x),
3251        // The wgpu whole-block path. What it buys is host round trips —
3252        // six a block become one — so it defaults ON where those cost
3253        // real time (a discrete card across PCIe) and OFF on unified
3254        // memory, where the per-op path shares the same pages and the
3255        // fusion measured slightly slower on an M4. `CMF_DIT_FUSED=1`
3256        // forces it anywhere, `=0` forbids it.
3257        #[cfg(feature = "gpu")]
3258        Backend::Wgpu
3259            if match std::env::var("CMF_DIT_FUSED").ok().as_deref() {
3260                Some("0") => false,
3261                Some(_) => true,
3262                None => crate::gpu_wgpu::discrete_active(),
3263            } =>
3264        {
3265            crate::gpu_wgpu::dit_block_seg(model, a, segs, x)
3266        }
3267        #[allow(unreachable_patterns)]
3268        _ => false,
3269    }
3270}
3271
3272/// One VAE resnet block for `vae_resnet`: norm/conv weights and the
3273/// channel/shape geometry. `shortcut` is the 1×1 projection (w, b, k)
3274/// when in/out channels differ.
3275pub struct VaeResnetArgs<'a> {
3276    pub groups: usize,
3277    pub ic: usize,
3278    pub oc: usize,
3279    pub h: usize,
3280    pub w: usize,
3281    pub n1w: &'a [f32],
3282    pub n1b: &'a [f32],
3283    pub c1w: &'a [f32],
3284    pub c1b: &'a [f32],
3285    pub c1k: usize,
3286    pub n2w: &'a [f32],
3287    pub n2b: &'a [f32],
3288    pub c2w: &'a [f32],
3289    pub c2b: &'a [f32],
3290    pub c2k: usize,
3291    pub shortcut: Option<(&'a [f32], &'a [f32], usize)>,
3292}
3293
3294/// One whole VAE resnet block on the device (norm+silu → conv ×2 →
3295/// shortcut → add, one command buffer).
3296#[allow(unused_variables)]
3297pub fn vae_resnet(a: &VaeResnetArgs, x: &[f32], out: &mut [f32]) -> bool {
3298    match backend() {
3299        #[cfg(target_os = "macos")]
3300        Backend::Metal => crate::gpu_metal::vae_resnet(a, x, out),
3301        _ => false,
3302    }
3303}
3304
3305/// Nearest-2× upsample fused with the following conv — the small
3306/// pre-upsample image is what crosses the CPU boundary.
3307#[allow(unused_variables, clippy::too_many_arguments)]
3308pub fn vae_upsample_conv(
3309    w: &[f32],
3310    bias: &[f32],
3311    x: &[f32],
3312    ic: usize,
3313    oc: usize,
3314    h: usize,
3315    w_img: usize,
3316    k: usize,
3317    out: &mut [f32],
3318) -> bool {
3319    match backend() {
3320        #[cfg(target_os = "macos")]
3321        Backend::Metal => crate::gpu_metal::vae_upsample_conv(w, bias, x, ic, oc, h, w_img, k, out),
3322        #[cfg(feature = "gpu")]
3323        Backend::Wgpu => crate::gpu_wgpu::vae_upsample_conv(w, bias, x, ic, oc, h, w_img, k, out),
3324        #[allow(unreachable_patterns)]
3325        _ => false,
3326    }
3327}
3328
3329/// VAE conv2d on the device (implicit GEMM — the CPU path pays for a
3330/// multi-GB im2col matrix at high resolutions).
3331#[allow(unused_variables, clippy::too_many_arguments)]
3332pub fn vae_conv2d(
3333    w: &[f32],
3334    bias: &[f32],
3335    x: &[f32],
3336    ic: usize,
3337    oc: usize,
3338    h: usize,
3339    w_img: usize,
3340    k: usize,
3341    out: &mut [f32],
3342) -> bool {
3343    match backend() {
3344        #[cfg(target_os = "macos")]
3345        Backend::Metal => crate::gpu_metal::vae_conv2d(w, bias, x, ic, oc, h, w_img, k, out),
3346        #[cfg(feature = "gpu")]
3347        Backend::Wgpu => crate::gpu_wgpu::vae_conv2d(w, bias, x, ic, oc, h, w_img, k, out),
3348        #[allow(unreachable_patterns)]
3349        _ => false,
3350    }
3351}
3352
3353/// DiT full bidirectional attention on the device (all heads:
3354/// scores GEMM → row softmax → P·V → panel unstack, one command
3355/// buffer). Head-major inputs; out is [n, nh·hd].
3356#[allow(unused_variables, clippy::too_many_arguments)]
3357/// Attention from an interleaved qkv panel, splitting into head-major
3358/// planes ON the device. wgpu only; `false` elsewhere so the caller
3359/// keeps its host repack.
3360#[allow(unused_variables)]
3361#[allow(clippy::too_many_arguments)]
3362/// qkv projection + attention with the panel never leaving the card.
3363/// wgpu only; `false` elsewhere and the caller keeps its host chain.
3364#[allow(clippy::too_many_arguments, unused_variables)]
3365pub fn dit_qkv_attention(
3366    model: &Arc<CmfModel>,
3367    qkv_idx: usize,
3368    xn: &[f32],
3369    n: usize,
3370    hidden: usize,
3371    nh: usize,
3372    hd: usize,
3373    scale: f32,
3374    nr: (&[f32], &[f32], &[f32], f32),
3375    out: &mut [f32],
3376) -> bool {
3377    match backend() {
3378        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
3379        Backend::Wgpu => crate::gpu_wgpu::dit_qkv_attention(
3380            model, qkv_idx, xn, n, hidden, nh, hd, scale, nr, out,
3381        ),
3382        #[allow(unreachable_patterns)]
3383        _ => false,
3384    }
3385}
3386
3387/// The whole attention half of a DiT block on the card: qkv GEMM,
3388/// attention, output projection. Only `proj` comes home.
3389#[allow(clippy::too_many_arguments)]
3390pub fn dit_qkv_attn_out(
3391    model: &Arc<CmfModel>,
3392    qkv_idx: usize,
3393    out_idx: usize,
3394    xn: &[f32],
3395    n: usize,
3396    hidden: usize,
3397    nh: usize,
3398    hd: usize,
3399    scale: f32,
3400    nr: (&[f32], &[f32], &[f32], f32),
3401    proj: &mut [f32],
3402) -> bool {
3403    match backend() {
3404        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
3405        Backend::Wgpu => crate::gpu_wgpu::dit_qkv_attn_out(
3406            model, qkv_idx, out_idx, xn, n, hidden, nh, hd, scale, nr, proj,
3407        ),
3408        #[allow(unreachable_patterns)]
3409        _ => false,
3410    }
3411}
3412
3413/// The VAE decoder's attention half on the card. Only `proj` returns.
3414#[allow(clippy::too_many_arguments)]
3415pub fn vae_qkv_attn_out(
3416    model: &Arc<CmfModel>,
3417    qkv_idx: usize,
3418    out_idx: usize,
3419    xn: &[f32],
3420    n: usize,
3421    dim: usize,
3422    nh: usize,
3423    hd: usize,
3424    scale: f32,
3425    angles: &[f32],
3426    eps: f32,
3427    qkv_bias: &[f32],
3428    proj: &mut [f32],
3429) -> bool {
3430    match backend() {
3431        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
3432        Backend::Wgpu => crate::gpu_wgpu::vae_qkv_attn_out(
3433            model, qkv_idx, out_idx, xn, n, dim, nh, hd, scale, angles, eps, qkv_bias, proj,
3434        ),
3435        #[allow(unreachable_patterns)]
3436        _ => false,
3437    }
3438}
3439
3440#[allow(clippy::too_many_arguments)]
3441pub fn vae_attention_packed(
3442    qkv: &[f32],
3443    nh: usize,
3444    n: usize,
3445    hd: usize,
3446    scale: f32,
3447    angles: &[f32],
3448    eps: f32,
3449    out: &mut [f32],
3450) -> bool {
3451    vae_attention_packed_layout(qkv, nh, n, hd, scale, angles, eps, out, 1)
3452}
3453
3454#[allow(clippy::too_many_arguments)]
3455pub fn vae_attention_packed_layout(
3456    qkv: &[f32],
3457    nh: usize,
3458    n: usize,
3459    hd: usize,
3460    scale: f32,
3461    angles: &[f32],
3462    eps: f32,
3463    out: &mut [f32],
3464    layout: u32,
3465) -> bool {
3466    match backend() {
3467        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
3468        Backend::Wgpu => crate::gpu_wgpu::vae_attention_packed_layout(
3469            qkv, nh, n, hd, scale, angles, eps, out, layout,
3470        ),
3471        #[allow(unreachable_patterns)]
3472        _ => false,
3473    }
3474}
3475
3476#[allow(clippy::too_many_arguments)]
3477pub fn dit_split_only(
3478    qkv: &[f32],
3479    nh: usize,
3480    n: usize,
3481    hd: usize,
3482    layout: u32,
3483    norm: Option<(&[f32], f32)>,
3484    out_q: &mut [f32],
3485) -> bool {
3486    match backend() {
3487        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
3488        Backend::Wgpu => crate::gpu_wgpu::dit_split_only(qkv, nh, n, hd, layout, norm, out_q),
3489        #[allow(unreachable_patterns)]
3490        _ => false,
3491    }
3492}
3493
3494/// The backend's f32 NT GEMM: `y[n×m] = x[n×k] · wᵀ[m×k]`. Tensor
3495/// cores where the card has them. Refuses under `CMF_BAKE_GPU=0` or
3496/// strict f32, and for jobs below n·k·m = 4M, where the round trip
3497/// costs more than the arithmetic saves.
3498/// `gemm_nt_f32` whose `w` is known to change every call (an
3499/// accumulation over fresh activations, not a weight): it skips the
3500/// resident ledger and its per-call fingerprint of the whole operand.
3501pub fn gemm_nt_f32_transient(
3502    x: &[f32],
3503    w: &[f32],
3504    y: &mut [f32],
3505    n: usize,
3506    k: usize,
3507    m: usize,
3508) -> bool {
3509    match backend() {
3510        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
3511        Backend::Wgpu => crate::gpu_wgpu::gemm_nt_f32_transient(x, w, y, n, k, m),
3512        #[allow(unreachable_patterns)]
3513        _ => false,
3514    }
3515}
3516
3517pub fn gemm_nt_f32(x: &[f32], w: &[f32], y: &mut [f32], n: usize, k: usize, m: usize) -> bool {
3518    match backend() {
3519        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
3520        Backend::Wgpu => crate::gpu_wgpu::gemm_nt_f32(x, w, y, n, k, m),
3521        #[allow(unreachable_patterns)]
3522        _ => false,
3523    }
3524}
3525
3526/// Music-3's FFN chain resident on the device — two GEMMs and the GLU
3527/// between them with no host round trip. `false` = refused, host runs.
3528#[allow(clippy::too_many_arguments)]
3529pub fn music3_ffn(
3530    model: &std::sync::Arc<CmfModel>,
3531    idx_in: usize,
3532    idx_out: usize,
3533    h: &[f32],
3534    bias_in: &[f32],
3535    n: usize,
3536    hs: usize,
3537    inter: usize,
3538    out: &mut [f32],
3539) -> bool {
3540    match backend() {
3541        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
3542        Backend::Wgpu => {
3543            crate::gpu_wgpu::music3_ffn(model, idx_in, idx_out, h, bias_in, n, hs, inter, out)
3544        }
3545        #[allow(unreachable_patterns)]
3546        _ => false,
3547    }
3548}
3549
3550/// A 1D convolution as a GEMM whose column matrix is expanded on the
3551/// device instead of being built, transposed and uploaded by the host.
3552/// `yt` comes back `[out_n x oc]`. `false` = refused, caller runs host.
3553#[allow(clippy::too_many_arguments)]
3554pub fn conv1d_gemm(
3555    x: &[f32],
3556    w: &[f32],
3557    ic: usize,
3558    oc: usize,
3559    n: usize,
3560    k: usize,
3561    pad: usize,
3562    dil: usize,
3563    out_n: usize,
3564    yt: &mut [f32],
3565) -> bool {
3566    match backend() {
3567        #[cfg(target_os = "macos")]
3568        Backend::Metal => crate::gpu_metal::conv1d_gemm(x, w, ic, oc, n, k, pad, dil, out_n, yt),
3569        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
3570        Backend::Wgpu => crate::gpu_wgpu::conv1d_gemm(x, w, ic, oc, n, k, pad, dil, out_n, yt),
3571        #[allow(unreachable_patterns)]
3572        _ => false,
3573    }
3574}
3575
3576/// The convolution as a GEMM on the matrix units. `false` = refused.
3577#[allow(clippy::too_many_arguments)]
3578pub fn vae_conv2d_coop(
3579    w: &[f32],
3580    bias: Option<&[f32]>,
3581    x: &[f32],
3582    ic: usize,
3583    oc: usize,
3584    h: usize,
3585    wi: usize,
3586    k: usize,
3587    out: &mut [f32],
3588) -> bool {
3589    match backend() {
3590        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
3591        Backend::Wgpu => crate::gpu_wgpu::vae_conv2d_coop(w, bias, x, ic, oc, h, wi, k, out),
3592        #[allow(unreachable_patterns)]
3593        _ => false,
3594    }
3595}
3596
3597pub fn dit_attention_packed(
3598    qkv: &[f32],
3599    nh: usize,
3600    n: usize,
3601    hd: usize,
3602    scale: f32,
3603    // (rope angles, q norm weights, k norm weights, eps) when the device
3604    // should apply qk-norm and RoPE itself; None when the host already did.
3605    nr: Option<(&[f32], &[f32], &[f32], f32)>,
3606    out: &mut [f32],
3607) -> bool {
3608    match backend() {
3609        // wgpu carries the only implementation, and it is not
3610        // platform-specific: `CMF_GPU=wgpu` on macOS runs it over Metal
3611        // like anywhere else. It used to be compiled out here on macOS,
3612        // which made the call a silent `false` — and the caller's
3613        // `assert!` turned that refusal into a panic on every
3614        // `cortiq animate` this platform ever ran.
3615        #[cfg(feature = "gpu")]
3616        Backend::Wgpu => crate::gpu_wgpu::dit_attention_packed(qkv, nh, n, hd, scale, nr, out),
3617        #[allow(unreachable_patterns)]
3618        _ => false,
3619    }
3620}
3621
3622/// Whether `dit_attention_packed` has an implementation on the backend
3623/// that is actually selected.
3624///
3625/// The caller has to know BEFORE it skips the host qk-norm: deferring
3626/// the norm to a device that then refuses leaves q/k unnormalized with
3627/// no way back. Native Metal has no packed kernel, so on macOS this is
3628/// false unless `CMF_GPU=wgpu` picked the other backend.
3629pub fn dit_attention_packed_available() -> bool {
3630    #[allow(unreachable_patterns)]
3631    match backend() {
3632        #[cfg(feature = "gpu")]
3633        Backend::Wgpu => crate::gpu_wgpu::dit_attention_packed_ready(),
3634        _ => false,
3635    }
3636}
3637
3638pub fn dit_attention(
3639    qh: &[f32],
3640    kh: &[f32],
3641    vh: &[f32],
3642    nh: usize,
3643    nkv: usize,
3644    n: usize,
3645    hd: usize,
3646    scale: f32,
3647    out: &mut [f32],
3648) -> bool {
3649    match backend() {
3650        #[cfg(target_os = "macos")]
3651        Backend::Metal => crate::gpu_metal::dit_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
3652        #[cfg(feature = "gpu")]
3653        Backend::Wgpu => crate::gpu_wgpu::dit_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
3654        #[allow(unreachable_patterns)]
3655        _ => false,
3656    }
3657}
3658
3659/// GPTQ calibration: a zeroed `cols × cols` Hessian accumulator on the
3660/// device (wgpu only), or None — the caller keeps the host fold then.
3661pub fn gram_alloc(cols: usize) -> Option<u64> {
3662    #[cfg(feature = "gpu")]
3663    if backend() == Backend::Wgpu {
3664        return crate::gpu_wgpu::gram::alloc(cols);
3665    }
3666    let _ = cols;
3667    None
3668}
3669
3670/// `H[id] += XᵀX` over `b` rows of `xs` (`[b·cols]`).
3671pub fn gram_add(id: u64, xs: &[f32], b: usize) -> bool {
3672    #[cfg(feature = "gpu")]
3673    if backend() == Backend::Wgpu {
3674        return crate::gpu_wgpu::gram::add(id, xs, b);
3675    }
3676    let _ = (id, xs, b);
3677    false
3678}
3679
3680/// `H[id] += XᵀX` over `b` rows of a device-resident f32 buffer.
3681#[cfg(feature = "gpu")]
3682pub fn gram_add_dev(id: u64, x: &wgpu::Buffer, b: usize) -> bool {
3683    if backend() == Backend::Wgpu {
3684        return crate::gpu_wgpu::gram::add_dev(id, x, b);
3685    }
3686    false
3687}
3688
3689/// The accumulated Hessian as a full symmetric f64 matrix (frees it).
3690pub fn gram_take(id: u64) -> Option<Vec<f64>> {
3691    #[cfg(feature = "gpu")]
3692    if backend() == Backend::Wgpu {
3693        return crate::gpu_wgpu::gram::take(id);
3694    }
3695    let _ = id;
3696    None
3697}
3698
3699/// GPTQ fold of the device Hessian `h_id` on the device: the upper Cholesky
3700/// factor of `(H + λ·mean(diag)·I)⁻¹` stays there under the returned id and
3701/// the Hessian is freed. None (no wgpu device, it does not fit, it does not
3702/// factor): the Hessian is left for `gram_take`.
3703pub fn gptq_fold_dev(h_id: u64, n: usize, lambda: f64) -> Option<u64> {
3704    #[cfg(feature = "gpu")]
3705    if backend() == Backend::Wgpu {
3706        return crate::gpu_wgpu::gptq_dev::fold(h_id, n, lambda);
3707    }
3708    let _ = (h_id, n, lambda);
3709    None
3710}
3711
3712/// (dead channels, raw H diagonal, damping used) of a device fold.
3713pub fn gptq_fold_info(id: u64) -> Option<(Vec<bool>, Vec<f32>, f64)> {
3714    #[cfg(feature = "gpu")]
3715    if backend() == Backend::Wgpu {
3716        return crate::gpu_wgpu::gptq_dev::info(id);
3717    }
3718    let _ = id;
3719    None
3720}
3721
3722/// A device fold's operator read back (n×n f32, upper).
3723pub fn gptq_fold_read(id: u64) -> Option<Vec<f32>> {
3724    #[cfg(feature = "gpu")]
3725    if backend() == Backend::Wgpu {
3726        return crate::gpu_wgpu::gptq_dev::read_u(id);
3727    }
3728    let _ = id;
3729    None
3730}
3731
3732/// Free a device fold.
3733pub fn gptq_fold_free(id: u64) {
3734    #[cfg(feature = "gpu")]
3735    if backend() == Backend::Wgpu {
3736        crate::gpu_wgpu::gptq_dev::free(id);
3737    }
3738    let _ = id;
3739}
3740
3741/// The q4tp GPTQ sweep on the device (see `gpu_wgpu::gptq_dev::sweep_q4tp`).
3742#[allow(clippy::too_many_arguments)]
3743pub fn gptq_sweep_q4tp_dev(
3744    id: u64,
3745    w: &[f32],
3746    rows: usize,
3747    tab: &[f32],
3748    lost: &[f32],
3749    nib: &mut [u8],
3750    codes: &mut [u32],
3751) -> bool {
3752    #[cfg(feature = "gpu")]
3753    if backend() == Backend::Wgpu {
3754        return crate::gpu_wgpu::gptq_dev::sweep_q4tp(id, w, rows, tab, lost, nib, codes);
3755    }
3756    let _ = (id, w, rows, tab, lost, nib, codes);
3757    false
3758}
3759
3760/// The q2tp GPTQ sweep ("placed" rule) on the device.
3761pub fn gptq_sweep_q2tp_dev(
3762    id: u64,
3763    w: &[f32],
3764    rows: usize,
3765    tab: &[f32],
3766    hw: &[f32],
3767    chunks: &mut [u8],
3768    codes: &mut [u32],
3769) -> bool {
3770    #[cfg(feature = "gpu")]
3771    if backend() == Backend::Wgpu {
3772        return crate::gpu_wgpu::gptq_dev::sweep_q2tp(id, w, rows, tab, hw, chunks, codes);
3773    }
3774    let _ = (id, w, rows, tab, hw, chunks, codes);
3775    false
3776}
3777
3778/// A device Hessian read back as a full symmetric f64 matrix, left on the
3779/// device.
3780pub fn gram_read(id: u64) -> Option<Vec<f64>> {
3781    #[cfg(feature = "gpu")]
3782    if backend() == Backend::Wgpu {
3783        return crate::gpu_wgpu::gram::read(id);
3784    }
3785    let _ = id;
3786    None
3787}
3788
3789/// Free every device Hessian (an aborted calibration pass).
3790pub fn gram_clear() {
3791    #[cfg(feature = "gpu")]
3792    if backend() == Backend::Wgpu {
3793        crate::gpu_wgpu::gram::clear();
3794    }
3795}
3796
3797/// Batched q4t GEMM on the device (imagegen DiT prefill shapes).
3798/// Metal: q4t_mul_mm decodes the mmap-resident tiles inside the
3799/// GEMM's K loop. wgpu (Vulkan/DX12 → NVIDIA/AMD/Intel/Adreno/Mali):
3800/// the register-blocked WGSL twin, weights cached in VRAM.
3801#[allow(unused_variables)]
3802pub fn q4tp_matmat(
3803    model: &Arc<CmfModel>,
3804    idx: usize,
3805    xs: &[f32],
3806    b: usize,
3807    rows: usize,
3808    cols: usize,
3809    out: &mut [f32],
3810) -> bool {
3811    match backend() {
3812        #[cfg(target_os = "macos")]
3813        Backend::Metal => crate::gpu_metal::q4tp_matmat(model, idx, xs, b, rows, cols, out),
3814        #[cfg(feature = "gpu")]
3815        Backend::Wgpu => crate::gpu_wgpu::q4tp_matmat(model, idx, xs, b, rows, cols, out),
3816        #[allow(unreachable_patterns)]
3817        _ => false,
3818    }
3819}
3820
3821/// The same over a two-bit weight plane. Native Metal uses the dedicated
3822/// q2tp tile; unsupported shapes return false and preserve the host fallback.
3823pub fn q2tp_matmat(
3824    model: &Arc<CmfModel>,
3825    idx: usize,
3826    xs: &[f32],
3827    b: usize,
3828    rows: usize,
3829    cols: usize,
3830    out: &mut [f32],
3831) -> bool {
3832    match backend() {
3833        #[cfg(target_os = "macos")]
3834        Backend::Metal => crate::gpu_metal::q2tp_matmat(model, idx, xs, b, rows, cols, out),
3835        #[cfg(feature = "gpu")]
3836        Backend::Wgpu => crate::gpu_wgpu::q2tp_matmat(model, idx, xs, b, rows, cols, out),
3837        #[allow(unreachable_patterns)]
3838        _ => false,
3839    }
3840}
3841
3842/// Descriptor-aware q2tp GEMM. The affine center is selected only for a
3843/// validated q2tp_affine target; the raw dtype16 payload remains unchanged.
3844pub fn q2tp_affine_matmat(
3845    model: &Arc<CmfModel>,
3846    idx: usize,
3847    xs: &[f32],
3848    b: usize,
3849    rows: usize,
3850    cols: usize,
3851    out: &mut [f32],
3852) -> bool {
3853    match backend() {
3854        #[cfg(target_os = "macos")]
3855        Backend::Metal => crate::gpu_metal::q2tp_affine_matmat(model, idx, xs, b, rows, cols, out),
3856        #[cfg(feature = "gpu")]
3857        Backend::Wgpu => crate::gpu_wgpu::q2tp_affine_matmat(model, idx, xs, b, rows, cols, out),
3858        #[allow(unreachable_patterns)]
3859        _ => false,
3860    }
3861}
3862
3863/// Binary low-rank (`blr`) product on the device: `out[b·rows] = xs[b·cols] ·
3864/// Wᵀ` through the two ±1 stages (V then U). `b = 1` is the decode GEMV.
3865/// False = not taken (no wgpu backend — Metal has no blr kernel yet — or a
3866/// shape outside the kernel's contract): the caller runs the CPU kernels.
3867pub fn blr_matmat(t: &crate::blr::BlrTensor, xs: &[f32], b: usize, out: &mut [f32]) -> bool {
3868    match backend() {
3869        #[cfg(feature = "gpu")]
3870        Backend::Wgpu => crate::gpu_wgpu::blr_matmat(t, xs, b, out),
3871        #[allow(unreachable_patterns)]
3872        _ => {
3873            let _ = (t, xs, b, out);
3874            false
3875        }
3876    }
3877}
3878
3879/// Single-token q2tp matvec through the ordinary (center=1.5) WGSL kernel.
3880pub fn q2tp_matvec(
3881    model: &Arc<CmfModel>,
3882    idx: usize,
3883    xs: &[f32],
3884    rows: usize,
3885    cols: usize,
3886    out: &mut [f32],
3887) -> bool {
3888    match backend() {
3889        #[cfg(target_os = "macos")]
3890        Backend::Metal => crate::gpu_metal::q2tp_matvec(model, idx, xs, rows, cols, out),
3891        #[cfg(feature = "gpu")]
3892        Backend::Wgpu => crate::gpu_wgpu::q2tp_matvec(model, idx, xs, rows, cols, out),
3893        #[allow(unreachable_patterns)]
3894        _ => false,
3895    }
3896}
3897
3898/// Single-token q2tp matvec with the explicit affine center=1 descriptor
3899/// operator. This is kept separate from ordinary q2tp to make accidental
3900/// center changes impossible at a call site.
3901pub fn q2tp_affine_matvec(
3902    model: &Arc<CmfModel>,
3903    idx: usize,
3904    xs: &[f32],
3905    rows: usize,
3906    cols: usize,
3907    out: &mut [f32],
3908) -> bool {
3909    match backend() {
3910        #[cfg(target_os = "macos")]
3911        Backend::Metal => crate::gpu_metal::q2tp_affine_matvec(model, idx, xs, rows, cols, out),
3912        #[cfg(feature = "gpu")]
3913        Backend::Wgpu => crate::gpu_wgpu::q2tp_affine_matvec(model, idx, xs, rows, cols, out),
3914        #[allow(unreachable_patterns)]
3915        _ => false,
3916    }
3917}
3918
3919/// Single-token q4tp matvec on the device — the lm_head class. Through the
3920/// DEDICATED matvec kernel: the batched GEMM at b=1 measured 11.73 ms
3921/// against the host's 9.51 on the release head, so the route that was
3922/// supposed to save eleven milliseconds a token lost its own probe instead.
3923pub fn q4tp_matvec(
3924    model: &Arc<CmfModel>,
3925    idx: usize,
3926    xs: &[f32],
3927    rows: usize,
3928    cols: usize,
3929    out: &mut [f32],
3930) -> bool {
3931    match backend() {
3932        #[cfg(target_os = "macos")]
3933        Backend::Metal => crate::gpu_metal::q4tp_matvec_for_test(model, idx, xs, rows, cols, out),
3934        #[cfg(feature = "gpu")]
3935        Backend::Wgpu => crate::gpu_wgpu::q4tp_matvec(model, idx, xs, rows, cols, out),
3936        #[allow(unreachable_patterns)]
3937        _ => false,
3938    }
3939}
3940
3941/// Single-token q4_tiled matvec on the device — the lm_head class (a
3942/// q4t checkpoint's head is its biggest host matvec, exactly like the
3943/// q4tp twin above). wgpu holds q4t_mv pipelines only inside the graph
3944/// encoder — the standalone arm stays an honest refusal until a
3945/// discrete-GPU q4t model reaches the bench.
3946pub fn q4t_matvec(
3947    model: &Arc<CmfModel>,
3948    idx: usize,
3949    xs: &[f32],
3950    rows: usize,
3951    cols: usize,
3952    out: &mut [f32],
3953) -> bool {
3954    match backend() {
3955        #[cfg(target_os = "macos")]
3956        Backend::Metal => crate::gpu_metal::q4t_matvec_for_test(model, idx, xs, rows, cols, out),
3957        #[allow(unreachable_patterns)]
3958        _ => false,
3959    }
3960}
3961
3962pub fn q4t_matmat(
3963    model: &Arc<CmfModel>,
3964    idx: usize,
3965    xs: &[f32],
3966    b: usize,
3967    rows: usize,
3968    cols: usize,
3969    out: &mut [f32],
3970) -> bool {
3971    match backend() {
3972        #[cfg(target_os = "macos")]
3973        Backend::Metal => crate::gpu_metal::q4t_matmat(model, idx, xs, b, rows, cols, out),
3974        #[cfg(feature = "gpu")]
3975        Backend::Wgpu => crate::gpu_wgpu::q4t_matmat(model, idx, xs, b, rows, cols, out),
3976        #[allow(unreachable_patterns)]
3977        _ => false,
3978    }
3979}
3980
3981/// Whole-block token-graph types re-exported from the Metal backend.
3982#[cfg(target_os = "macos")]
3983pub use crate::gpu_metal::{
3984    AttnDeviceParams, AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, GpuMoe, GraphDims, MetalFfn,
3985    O1AttnParams, TokenGraph, kv_mirror_drop, kv_mirror_read_last, kv_mirror_take_imp,
3986};
3987
3988/// A BLOCK of consecutive q1 GDN layers in one submission (Metal only).
3989#[cfg(target_os = "macos")]
3990pub fn gdn_block(
3991    model: &Arc<CmfModel>,
3992    layers: &[GdnGpuLayer],
3993    states: &mut [&mut [f32]],
3994    cfg: &GdnGpuCfg,
3995    h: &mut [f32],
3996) -> bool {
3997    match backend() {
3998        Backend::Metal => crate::gpu_metal::gdn_block(model, layers, states, cfg, h),
3999        _ => false,
4000    }
4001}
4002
4003/// A layer's MoE-FFN in one submission (amortizing the dispatch cost).
4004#[allow(unused_variables)]
4005pub fn moe_block(model: &Arc<CmfModel>, jobs: &[MoeJob], out: &mut [f32]) -> bool {
4006    match backend() {
4007        // The Metal block applies SiLU only: any other activation is an
4008        // honest refusal (the caller keeps its host path).
4009        #[cfg(target_os = "macos")]
4010        Backend::Metal if jobs.iter().any(|j| j.act != 0) => false,
4011        #[cfg(target_os = "macos")]
4012        Backend::Metal => crate::gpu_metal::moe_block(model, jobs, out),
4013        #[cfg(feature = "gpu")]
4014        Backend::Wgpu => crate::gpu_wgpu::moe_block(model, jobs, out),
4015        Backend::None => false,
4016    }
4017}
4018
4019/// Independent matvecs of one input in a single submission (GDN projections).
4020#[allow(unused_variables)]
4021pub fn matvec_batch(model: &Arc<CmfModel>, jobs: &[BatchJob], out: &mut [&mut [f32]]) -> bool {
4022    match backend() {
4023        #[cfg(target_os = "macos")]
4024        Backend::Metal => crate::gpu_metal::matvec_batch(model, jobs, out),
4025        #[cfg(feature = "gpu")]
4026        Backend::Wgpu => crate::gpu_wgpu::matvec_batch(model, jobs, out),
4027        Backend::None => false,
4028    }
4029}
4030
4031// ── Whole-token wgpu graph race (generation granularity) ─────────────
4032// On integrated/mobile adapters the graph is neither trusted nor banned
4033// a priori — it RACES the normal path: generations alternate arms (the
4034// normal path first — known-good UX — then the graph), per-token wall
4035// times accumulate per arm, and once both arms have enough steady
4036// samples the faster one wins for the process. Arm switches happen ONLY
4037// at generation boundaries (`kv_cache.clear()` resets state), so the
4038// device KV mirror and the CPU cache never diverge mid-sequence. The
4039// single exception is the first-token bail: the very first decode token
4040// of a graph generation may be discarded and recomputed on the CPU
4041// path (the prompt KV is CPU-owned at that point, so this is safe) —
4042// a tiled mobile GPU that drains its pipeline at every barrier turns
4043// the ~300-dispatch graph into seconds per token (field report: 0.2
4044// tok/s vs 15 on the CPU), and one token is all it takes to see that.
4045static GRAPH_RACE_STATE: AtomicU8 = AtomicU8::new(0); // 0 racing, 1 graph won, 2 normal won
4046static GRAPH_RACE_FLIP: AtomicU32 = AtomicU32::new(0);
4047static GRAPH_RACE_ARM_GRAPH: AtomicU8 = AtomicU8::new(0); // this generation's arm
4048static GRAPH_RACE_TOK: AtomicU32 = AtomicU32::new(0); // token index within the generation
4049static GRAPH_NS: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; // [normal, graph]
4050static GRAPH_N: [AtomicU32; 2] = [AtomicU32::new(0), AtomicU32::new(0)];
4051
4052/// Steady per-token samples per arm before the race decides.
4053const GRAPH_RACE_SAMPLES: u32 = 4;
4054
4055// A graph that cannot be built for THIS model will never build: the
4056// refusal is a property of the weights, not of the moment. Retrying it
4057// per token is not free — the builder walks every layer and asks each
4058// tensor for a graph view before giving up at layer 0 — and on an
4059// Adreno 642L that retry cost 3x: forcing the graph on a model it
4060// refuses measured 0.3 tok/s against 0.905 for the per-op path it falls
4061// back to. Remembered once, the fallback runs at its own speed.
4062//
4063// The verdict is kept PER PIPELINE (`Pipeline::graph_refused` /
4064// `mark_graph_refused`), not in a process-wide flag: several pipelines
4065// of one file share a process in `serve` (backbone slots + skill lanes
4066// loaded mid-traffic), and a refusal in one lane — or the reset a new
4067// lane used to issue — must not move another lane's running sequence
4068// between the device and the host (R4/NF-2). Callers must NOT report
4069// transient refusals (an unsealed o1 state during prefill, a softcap).
4070
4071/// Called at every generation start (fresh KV). Applies a pending
4072/// verdict and picks this generation's arm while racing.
4073pub fn graph_race_begin_generation() {
4074    // One generation has now compiled whatever this model needs; keep it
4075    // for the next process. Once per run: the blob does not grow after
4076    // the pipelines exist, and the write is megabytes against the ~200 s
4077    // of compiling it saves on the device that needed this.
4078    #[cfg(feature = "gpu")]
4079    {
4080        // Save once, at the start of the SECOND generation: the first
4081        // has dispatched, so there is something to keep, and nothing is
4082        // saved before any work (the driver compiles at first use, not
4083        // at pipeline creation — the context comes up in 1.5 s while the
4084        // compiling costs minutes).
4085        //
4086        // Flushing again on 4, 8, 16 … was tried on the theory that a
4087        // chat turn compiles shapes the first one did not. It buys
4088        // nothing: a fresh app process still spent 49.0 s, then 58.7,
4089        // then 61.3 on its first answer with the backoff in place. One
4090        // flush it is.
4091        static FLUSHED: std::sync::Once = std::sync::Once::new();
4092        static FIRST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
4093        if FIRST.swap(false, Ordering::Relaxed) {
4094            // Nothing dispatched yet.
4095        } else {
4096            FLUSHED.call_once(crate::gpu_wgpu::pipeline_cache_flush);
4097        }
4098    }
4099    GRAPH_RACE_TOK.store(0, Ordering::Relaxed);
4100    if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
4101        return;
4102    }
4103    let (gn, cn) = (
4104        GRAPH_N[1].load(Ordering::Relaxed),
4105        GRAPH_N[0].load(Ordering::Relaxed),
4106    );
4107    if gn >= GRAPH_RACE_SAMPLES && cn >= GRAPH_RACE_SAMPLES {
4108        let g_avg = GRAPH_NS[1].load(Ordering::Relaxed) / gn as u64;
4109        let c_avg = GRAPH_NS[0].load(Ordering::Relaxed) / cn as u64;
4110        let verdict = if g_avg < c_avg { 1 } else { 2 };
4111        GRAPH_RACE_STATE.store(verdict, Ordering::Relaxed);
4112        tracing::info!(
4113            "wgpu graph race: graph {:.2} ms/tok vs normal {:.2} ms/tok -> {}",
4114            g_avg as f64 / 1e6,
4115            c_avg as f64 / 1e6,
4116            if verdict == 1 { "graph" } else { "normal path" }
4117        );
4118        return;
4119    }
4120    let flip = GRAPH_RACE_FLIP.fetch_add(1, Ordering::Relaxed);
4121    GRAPH_RACE_ARM_GRAPH.store((flip % 2 == 1) as u8, Ordering::Relaxed);
4122}
4123
4124/// Should this decode token try the graph? `trusted` (discrete adapter,
4125/// explicit env, or a GDN hybrid whose state lives on the device) skips
4126/// the race entirely.
4127pub fn graph_race_use_graph(trusted: bool) -> bool {
4128    if trusted {
4129        return true;
4130    }
4131    match GRAPH_RACE_STATE.load(Ordering::Relaxed) {
4132        1 => true,
4133        2 => false,
4134        _ => GRAPH_RACE_ARM_GRAPH.load(Ordering::Relaxed) == 1,
4135    }
4136}
4137
4138/// First decode token of a racing graph generation: hopeless already?
4139/// (>4x the normal path's per-token average AND over a second.) Settles
4140/// the race immediately; the caller discards the graph result and
4141/// recomputes this token on the normal path.
4142pub fn graph_race_first_token_hopeless(dur: std::time::Duration) -> bool {
4143    if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
4144        return false;
4145    }
4146    let first = GRAPH_RACE_TOK.load(Ordering::Relaxed) == 0;
4147    let cn = GRAPH_N[0].load(Ordering::Relaxed);
4148    if !first || cn == 0 {
4149        return false;
4150    }
4151    let c_avg = GRAPH_NS[0].load(Ordering::Relaxed) / cn as u64;
4152    let ns = dur.as_nanos() as u64;
4153    if ns > 1_000_000_000 && ns > 4 * c_avg {
4154        GRAPH_RACE_STATE.store(2, Ordering::Relaxed);
4155        tracing::info!(
4156            "wgpu graph race: first graph token {:.0} ms vs normal {:.2} ms/tok — hopeless, normal path wins",
4157            ns as f64 / 1e6,
4158            c_avg as f64 / 1e6
4159        );
4160        return true;
4161    }
4162    false
4163}
4164
4165/// Record one decode-token wall time for the racing arm. The first
4166/// token of each generation is discarded (KV-mirror upload / cold
4167/// caches on the graph arm; cold mmap on the normal arm).
4168pub fn graph_race_record(used_graph: bool, dur: std::time::Duration) {
4169    if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
4170        return;
4171    }
4172    let tok = GRAPH_RACE_TOK.fetch_add(1, Ordering::Relaxed);
4173    if tok == 0 {
4174        return;
4175    }
4176    let i = used_graph as usize;
4177    GRAPH_NS[i].fetch_add(dur.as_nanos() as u64, Ordering::Relaxed);
4178    GRAPH_N[i].fetch_add(1, Ordering::Relaxed);
4179}
4180
4181/// Bounded-cost content fingerprint for the backends' pointer-keyed device
4182/// caches: FNV over the whole slice up to 4 KiB, over 64 spread 64-byte
4183/// windows (plus the length) above. An address-keyed hit must also prove
4184/// the bytes are still the ones it uploaded — the allocator reuses heap
4185/// and mmap addresses freely, so a reloaded model or a re-dequantized
4186/// layer lands where the old bytes were — and sampling keeps that proof at
4187/// ~a microsecond even for a 126 MB matrix. Real replacements (another
4188/// model's tensor, an Adam-updated master) differ densely, so a 4 KiB
4189/// spread cannot miss them.
4190pub(crate) fn fp_bytes(data: &[u8]) -> u64 {
4191    #[inline]
4192    fn fnv(mut h: u64, bytes: &[u8]) -> u64 {
4193        let (chunks, tail) = bytes.split_at(bytes.len() & !7);
4194        for c in chunks.chunks_exact(8) {
4195            h ^= u64::from_le_bytes(c.try_into().unwrap());
4196            h = h.wrapping_mul(0x100_0000_01b3);
4197        }
4198        for &b in tail {
4199            h ^= b as u64;
4200            h = h.wrapping_mul(0x100_0000_01b3);
4201        }
4202        h
4203    }
4204    let mut h = 0xcbf2_9ce4_8422_2325u64 ^ (data.len() as u64);
4205    if data.len() <= 4096 {
4206        return fnv(h, data);
4207    }
4208    let step = (data.len() - 64) / 63;
4209    for i in 0..64 {
4210        h = fnv(h, &data[i * step..i * step + 64]);
4211    }
4212    h
4213}
4214
4215/// `fp_bytes` over an f32 slice without a bytemuck dependency (the Metal
4216/// backend builds with no GPU feature flags).
4217pub(crate) fn fp_f32(data: &[f32]) -> u64 {
4218    let bytes = unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, data.len() * 4) };
4219    fp_bytes(bytes)
4220}
4221
4222#[cfg(test)]
4223mod fp_tests {
4224    use super::fp_bytes;
4225
4226    /// The pointer-keyed caches survive on `fp_bytes` telling two different
4227    /// tensors apart at a reused address. Its sampling must therefore see a
4228    /// change ANYWHERE — head, tail, and the stretches between windows are
4229    /// the places a cheaper hash would go blind.
4230    #[test]
4231    fn fp_bytes_sees_a_change_anywhere_in_a_sampled_slice() {
4232        let n = 1 << 20; // 1 MiB — far above the 4 KiB full-hash threshold
4233        let base: Vec<u8> = (0..n).map(|i| (i * 31 + 7) as u8).collect();
4234        let h0 = fp_bytes(&base);
4235        assert_eq!(h0, fp_bytes(&base), "fingerprint must be deterministic");
4236        // A DENSE change (every requantized/redequantized tensor is one)
4237        // must flip the fingerprint no matter how the windows fall.
4238        let mut dense = base.clone();
4239        for b in dense.iter_mut() {
4240            *b = b.wrapping_add(1);
4241        }
4242        assert_ne!(
4243            h0,
4244            fp_bytes(&dense),
4245            "a fully different tensor slipped through"
4246        );
4247        // Length participates: the same prefix at a shorter length is a
4248        // different key AND a different fingerprint.
4249        assert_ne!(h0, fp_bytes(&base[..n - 64]));
4250        // Below the threshold the hash is exact: a single flipped byte in
4251        // a norm-sized vector must be seen.
4252        let mut small = vec![3u8; 4096];
4253        let hs = fp_bytes(&small);
4254        small[2048] ^= 1;
4255        assert_ne!(hs, fp_bytes(&small), "full hash missed a one-byte change");
4256        // And the sampled windows land within bounds on awkward sizes.
4257        for n in [4097usize, 5000, 64 * 64, 1 << 16] {
4258            let v = vec![9u8; n];
4259            let _ = fp_bytes(&v); // must not panic on window math
4260        }
4261    }
4262}
4263
4264/// Hand the card back after a bake: drop its resident weights, planes and
4265/// pools so the ordinary engine (the runtime gate, a serve that follows)
4266/// starts from a clean budget. No-op off the wgpu backend.
4267pub fn bake_release() {
4268    #[cfg(feature = "gpu")]
4269    crate::gpu_wgpu::bake_release();
4270}
4271
4272/// Strict-f32 for the bake's GEMMs (phase A mask training): the mask
4273/// selects neurons by a gradient signal, and f16 operand rounding on
4274/// that signal closes the wrong ones. No-op off the wgpu backend.
4275pub fn bake_precision_strict(on: bool) {
4276    #[cfg(feature = "gpu")]
4277    crate::gpu_wgpu::bake_precision_strict(on);
4278    #[cfg(not(feature = "gpu"))]
4279    let _ = on;
4280}
4281
4282/// CMF_GRAPH_HOSTPROF=1: how a graph token's wall splits between the
4283/// host encoding the command stream and the tail the GPU still owes
4284/// after encode. Fifteen GPU-side suspects measured null while the
4285/// bench counted 17.7k allocations a token — this is the instrument
4286/// that says whether the thief was on the host all along.
4287pub fn hostprof_encode_done(t0: std::time::Instant) {
4288    use std::sync::atomic::{AtomicU64, Ordering};
4289    static ENC: AtomicU64 = AtomicU64::new(0);
4290    static N: AtomicU64 = AtomicU64::new(0);
4291    if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() != Ok("1") {
4292        return;
4293    }
4294    ENC.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);
4295    let n = N.fetch_add(1, Ordering::Relaxed) + 1;
4296    if n % 100 == 0 {
4297        eprintln!(
4298            "hostprof: encode {:.2} ms/token over {n} tokens",
4299            ENC.load(Ordering::Relaxed) as f64 / n as f64 / 1e6
4300        );
4301    }
4302}
4303
4304pub fn hostprof_total(t0: std::time::Instant) {
4305    use std::sync::atomic::{AtomicU64, Ordering};
4306    static TOT: AtomicU64 = AtomicU64::new(0);
4307    static N: AtomicU64 = AtomicU64::new(0);
4308    if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() != Ok("1") {
4309        return;
4310    }
4311    TOT.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);
4312    let n = N.fetch_add(1, Ordering::Relaxed) + 1;
4313    if n % 100 == 0 {
4314        eprintln!(
4315            "hostprof: total {:.2} ms/token over {n} tokens",
4316            TOT.load(Ordering::Relaxed) as f64 / n as f64 / 1e6
4317        );
4318    }
4319}
4320
4321/// Per-stage host-encode accumulator for the Metal token loop
4322/// (CMF_GRAPH_HOSTPROF=1). Stage 0 = GDN-run encode; everything else
4323/// falls out by subtraction from hostprof's encode total.
4324pub fn stageprof(stage: u32, dt: std::time::Duration) {
4325    use std::sync::atomic::{AtomicU64, Ordering};
4326    static NS: [AtomicU64; 4] = [
4327        AtomicU64::new(0),
4328        AtomicU64::new(0),
4329        AtomicU64::new(0),
4330        AtomicU64::new(0),
4331    ];
4332    static N: AtomicU64 = AtomicU64::new(0);
4333    if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() != Ok("1") {
4334        return;
4335    }
4336    NS[stage as usize % 4].fetch_add(dt.as_nanos() as u64, Ordering::Relaxed);
4337    if stage == 1 {
4338        let n = N.fetch_add(1, Ordering::Relaxed) + 1;
4339        if n % 200 == 0 {
4340            eprintln!(
4341                "stageprof: planning {:.2} ms/tok | gdn-item {:.2} ms/tok | attn-item {:.2} ms/tok ({n} tok)",
4342                NS[1].load(Ordering::Relaxed) as f64 / n as f64 / 1e6,
4343                NS[2].load(Ordering::Relaxed) as f64 / n as f64 / 1e6,
4344                NS[3].load(Ordering::Relaxed) as f64 / n as f64 / 1e6
4345            );
4346        }
4347    }
4348}
4349
4350/// Active weight bytes dispatched so far (Metal decode path); 0 where
4351/// the backend does not count. The honest floor's numerator.
4352pub fn weight_bytes_dispatched() -> u64 {
4353    let mut total = 0u64;
4354    #[cfg(target_os = "macos")]
4355    {
4356        total += crate::gpu_metal::WEIGHT_BYTES.load(std::sync::atomic::Ordering::Relaxed);
4357    }
4358    #[cfg(feature = "gpu")]
4359    {
4360        total += crate::gpu_wgpu::WEIGHT_BYTES.load(std::sync::atomic::Ordering::Relaxed);
4361    }
4362    total
4363}
4364
4365/// The per-stage split of `weight_bytes_dispatched`:
4366/// [misc, dense-ffn, moe, attn, gdn, head].
4367pub fn weight_bytes_by() -> [u64; 6] {
4368    #[cfg(target_os = "macos")]
4369    {
4370        let mut o = [0u64; 6];
4371        for (i, a) in crate::gpu_metal::WEIGHT_BYTES_BY.iter().enumerate() {
4372            o[i] = a.load(std::sync::atomic::Ordering::Relaxed);
4373        }
4374        return o;
4375    }
4376    #[allow(unreachable_code)]
4377    [0; 6]
4378}
4379
4380#[cfg(test)]
4381mod f16_guard_tests {
4382    use super::*;
4383
4384    /// The f16 guard's maximum: the largest magnitude through the lanes and
4385    /// the remainder, +inf for an inf or a NaN anywhere.
4386    #[test]
4387    fn abs_max_or_inf_is_the_magnitude_maximum() {
4388        let mut xs: Vec<f32> = (0..37).map(|i| (i as f32 - 18.0) * 0.5).collect();
4389        assert_eq!(abs_max_or_inf(&xs), 9.0);
4390        xs[36] = -70000.0; // the remainder
4391        assert_eq!(abs_max_or_inf(&xs), 70000.0);
4392        xs[3] = f32::NAN; // a lane
4393        assert_eq!(abs_max_or_inf(&xs), f32::INFINITY);
4394        xs[3] = 0.0;
4395        xs[35] = f32::NEG_INFINITY;
4396        assert_eq!(abs_max_or_inf(&xs), f32::INFINITY);
4397        assert_eq!(abs_max_or_inf(&[]), 0.0);
4398        assert_eq!(abs_max_or_inf(&[-0.0, -1e-30]), 1e-30);
4399    }
4400}
4401
4402#[cfg(test)]
4403mod probe_warmup_tests {
4404    use super::*;
4405    use std::time::Duration;
4406
4407    fn ms(v: f64) -> Duration {
4408        Duration::from_nanos((v * 1e6) as u64)
4409    }
4410
4411    /// The bug this pins, measured on an A100: the first device call for
4412    /// a class compiles its pipeline, was timed at 117.01 ms against the
4413    /// host's 3.19, and sent `gemm-nt` to the CPU for the whole process —
4414    /// which ran a 27B bake on 2.6 cores with the card idle.
4415    #[test]
4416    fn one_cold_first_sample_does_not_lose_the_class() {
4417        let p = Probe::new();
4418        // First device sample is the pipeline build. Then the truth.
4419        probe_record_into(&p, "gemm-nt", None, true, ms(117.01));
4420        probe_record_into(&p, "gemm-nt", None, true, ms(1.1));
4421        probe_record_into(&p, "gemm-nt", None, true, ms(1.0));
4422        probe_record_into(&p, "gemm-nt", None, false, ms(3.19));
4423        probe_record_into(&p, "gemm-nt", None, false, ms(3.20));
4424        assert_eq!(
4425            p.state.load(Ordering::Relaxed),
4426            1,
4427            "the device is 3x faster once warm and must win"
4428        );
4429    }
4430
4431    /// The warm-up must not become a way to never decide, and must not
4432    /// underflow: a blind decrement at zero wraps a u32 to its maximum
4433    /// and mutes the arm for the life of the process.
4434    #[test]
4435    fn the_warmup_is_spent_once_and_never_underflows() {
4436        let p = Probe::new();
4437        for _ in 0..8 {
4438            probe_record_into(&p, "matmat", None, true, ms(10.0));
4439        }
4440        assert_eq!(p.gpu_burn.load(Ordering::Relaxed), 0, "spent, not wrapped");
4441        assert_eq!(
4442            p.gpu_n.load(Ordering::Relaxed),
4443            7,
4444            "one sample burned, the rest counted"
4445        );
4446    }
4447
4448    /// A device path that always refuses records no timing, so without
4449    /// counting the refusals the class can never reach a verdict. On an
4450    /// M4 with LFM2.5-2.6B `ffn` was still undecided after 9000 calls,
4451    /// alternating arms and paying a failed device attempt on half of
4452    /// them.
4453    #[test]
4454    fn a_class_whose_device_always_declines_settles_on_the_host() {
4455        let _probe_guard = probe_test_guard();
4456        // A class no other test in this file touches: `probe_note_decline`
4457        // works on the process-wide probes by design, and the tests in
4458        // this binary share them.
4459        let c = OpClass::MatmatWide;
4460        let p = &PROBES[c as usize];
4461        p.state.store(0, Ordering::Relaxed);
4462        p.declines.store(0, Ordering::Relaxed);
4463        for _ in 0..(PROBE_DECLINE_LIMIT - 1) {
4464            probe_note_decline(c);
4465        }
4466        assert_eq!(
4467            p.state.load(Ordering::Relaxed),
4468            0,
4469            "one short of the limit is still a question, not an answer"
4470        );
4471        probe_note_decline(c);
4472        assert_eq!(p.state.load(Ordering::Relaxed), 2, "settled on the host");
4473        assert!(matches!(probe_arm(c), ProbeArm::Cpu));
4474        p.state.store(0, Ordering::Relaxed);
4475        p.declines.store(0, Ordering::Relaxed);
4476    }
4477
4478    /// A genuinely slower device still loses — the warm-up removes an
4479    /// artefact, it does not put a thumb on the scale.
4480    #[test]
4481    fn a_slow_device_still_loses_after_the_warmup() {
4482        let p = Probe::new();
4483        for _ in 0..4 {
4484            probe_record_into(&p, "matvec", None, true, ms(40.0));
4485        }
4486        for _ in 0..4 {
4487            probe_record_into(&p, "matvec", None, false, ms(2.0));
4488        }
4489        assert_eq!(p.state.load(Ordering::Relaxed), 2, "host wins on merit");
4490    }
4491}
4492
4493/// Scratch/weight lifetime for a synchronous image-pipeline stage. Declare
4494/// this before the stage model so the model drops before cache collection.
4495pub(crate) struct ImageStageGuard {
4496    #[cfg(target_os = "macos")]
4497    metal: Option<crate::gpu_metal::ImageStageGuard>,
4498    #[cfg(feature = "gpu")]
4499    wgpu: crate::gpu_wgpu::ImageStageGuard,
4500}
4501
4502pub(crate) fn image_stage_scope() -> ImageStageGuard {
4503    ImageStageGuard {
4504        #[cfg(target_os = "macos")]
4505        metal: if matches!(backend(), Backend::Metal) {
4506            Some(crate::gpu_metal::image_stage_scope())
4507        } else {
4508            None
4509        },
4510        #[cfg(feature = "gpu")]
4511        wgpu: crate::gpu_wgpu::image_stage_scope(),
4512    }
4513}
4514
4515impl ImageStageGuard {
4516    pub(crate) fn track_model(&mut self, uid: u64) {
4517        #[cfg(target_os = "macos")]
4518        if let Some(metal) = &mut self.metal {
4519            metal.track_model(uid);
4520        }
4521        #[cfg(feature = "gpu")]
4522        self.wgpu.track_model(uid);
4523        #[cfg(not(target_os = "macos"))]
4524        let _ = uid;
4525    }
4526}
4527
4528// ════════════════════════════════════════════════════════════════════
4529// Z-Image-Turbo device contract (WP0 scaffold, plan §2.1). APPEND-ONLY.
4530//
4531// Owner of the contract: the WP1 lead. The backends implement it in their
4532// own child modules — `gpu_wgpu/zimage.rs` (WP2) and `gpu_metal/zimage.rs`
4533// (WP3) — and never edit the parent files. New fields are added only as
4534// `Option<…>` with agreed semantics; existing fields never change meaning.
4535//
4536// Convention (the same as every `gpu::*` entry): `false` = "not handled",
4537// nothing observable was changed, and the caller runs the CPU path
4538// (`zimage::ZImageDit::step_cpu` etc.), which is the bit-level reference.
4539//
4540// Sequence order everywhere is diffusers' [img rows…, cap rows…], with
4541// padded lengths n_img_p = ceil32(n_img) and n_cap_p = ceil32(L).
4542// ════════════════════════════════════════════════════════════════════
4543
4544// ───────────────────── Qwen-Image-2.1 device contract ─────────────────────
4545
4546/// Geometry of the Qwen-Image-2.1 denoiser.
4547#[derive(Clone, Copy, Debug, PartialEq)]
4548pub struct Qi21Geom {
4549    pub hidden: usize,
4550    pub nh: usize,
4551    pub hd: usize,
4552    pub inter: usize,
4553    pub in_ch: usize,
4554    pub eps: f32,
4555}
4556
4557/// One block's weights: tensor indices of `to_q, to_k, to_v, to_out.0,
4558/// gate_layer, proj (up), out (down)` and the per-head q/k norm weights.
4559pub struct Qi21BlockRef<'a> {
4560    pub w: [usize; 7],
4561    pub norm_q: &'a [f32],
4562    pub norm_k: &'a [f32],
4563}
4564
4565/// Everything the device needs to build a program and run its prefix.
4566pub struct Qi21PrefillArgs<'a> {
4567    pub model: &'a Arc<CmfModel>,
4568    pub geom: Qi21Geom,
4569    pub blocks: &'a [Qi21BlockRef<'a>],
4570    /// `img_in` [hidden, 64] and `proj_out` [64, hidden], f32.
4571    pub img_in: &'a [f32],
4572    pub proj_out: &'a [f32],
4573    pub key: u64,
4574    /// Prefix rows after `txt_in` / `img_in`, `[lp, hidden]`.
4575    pub x: &'a [f32],
4576    pub lp: usize,
4577    /// RoPE cos/sin of the prefix rows and of the target rows, `[rows, 64]`.
4578    pub rope_p: (&'a [f32], &'a [f32]),
4579    pub rope_t: (&'a [f32], &'a [f32]),
4580    /// Keys each prefix row sees (a leading run; non-decreasing).
4581    pub vis: &'a [u32],
4582    /// The t = 0 modulation `[s1|g1|s2|g2]`.
4583    pub mods0: &'a [f32],
4584    /// Target rows.
4585    pub n: usize,
4586}
4587
4588/// Build the program `a.key` and run its prefix on the device.
4589#[allow(unused_variables)]
4590pub fn qi21_prefill(a: &Qi21PrefillArgs) -> bool {
4591    match backend() {
4592        #[cfg(target_os = "macos")]
4593        Backend::Metal => crate::gpu_metal::qi21::prefill(a),
4594        #[cfg(feature = "gpu")]
4595        Backend::Wgpu => crate::gpu_wgpu::qi21::prefill(a),
4596        #[allow(unreachable_patterns)]
4597        _ => false,
4598    }
4599}
4600
4601/// One denoiser call of program `key`: `xtok [n, 64]` → `out [n, 64]`.
4602#[allow(unused_variables)]
4603pub fn qi21_step(key: u64, xtok: &[f32], mods: &[f32], fs: &[f32], out: &mut [f32]) -> bool {
4604    match backend() {
4605        #[cfg(target_os = "macos")]
4606        Backend::Metal => crate::gpu_metal::qi21::step(key, xtok, mods, fs, out),
4607        #[cfg(feature = "gpu")]
4608        Backend::Wgpu => crate::gpu_wgpu::qi21::step(key, xtok, mods, fs, out),
4609        #[allow(unreachable_patterns)]
4610        _ => false,
4611    }
4612}
4613
4614/// Drop program `key`. The wgpu module is released directly (module-local
4615/// state only), so a release never brings a device up.
4616#[allow(unused_variables)]
4617pub fn qi21_release_key(key: u64) {
4618    #[cfg(target_os = "macos")]
4619    if matches!(backend(), Backend::Metal) {
4620        crate::gpu_metal::qi21::release_key(key);
4621    }
4622    #[cfg(feature = "gpu")]
4623    crate::gpu_wgpu::qi21::release_key(key);
4624}
4625
4626/// Drop the denoiser's device state (see `qi21_release_key`), and the
4627/// resident VAE decoder's weights.
4628pub fn qi21_release() {
4629    #[cfg(target_os = "macos")]
4630    if matches!(backend(), Backend::Metal) {
4631        crate::gpu_metal::qi21::release();
4632    }
4633    #[cfg(feature = "gpu")]
4634    {
4635        crate::gpu_wgpu::qi21::release();
4636        crate::gpu_wgpu::qi21_vae::release();
4637    }
4638}
4639
4640/// One conv of the Qwen-Image-2.1 VAE decoder: host f32 weights
4641/// `[co][ci][k][k]` and bias `[co]` (k = 1 or 3, stride 1, same padding).
4642#[derive(Clone, Copy)]
4643pub struct Qi21VaeConvRef<'a> {
4644    pub w: &'a [f32],
4645    pub b: &'a [f32],
4646    pub ci: usize,
4647    pub co: usize,
4648    pub k: usize,
4649}
4650
4651/// A residual block: `conv2(φ(conv1(φ(x)))) + x` (through the 1×1
4652/// shortcut when ci ≠ co), φ = RMS_norm over channels (x/‖x‖·√C·γ), SiLU.
4653pub struct Qi21VaeResRef<'a> {
4654    pub g1: &'a [f32],
4655    pub c1: Qi21VaeConvRef<'a>,
4656    pub g2: &'a [f32],
4657    pub c2: Qi21VaeConvRef<'a>,
4658    pub shortcut: Option<Qi21VaeConvRef<'a>>,
4659}
4660
4661/// An up block: its resnets, then (all but the last block) nearest-2× +
4662/// the 3×3 conv, plus the DupUp shortcut of the block's input (`in_dim` →
4663/// `out_dim` channels, temporal factor `ft`).
4664pub struct Qi21VaeUpRef<'a> {
4665    pub resnets: Vec<Qi21VaeResRef<'a>>,
4666    pub up: Option<(Qi21VaeConvRef<'a>, usize)>,
4667    pub in_dim: usize,
4668    pub out_dim: usize,
4669}
4670
4671/// The Qwen-Image-2.1 VAE decoder (`qwen_image21_vae.rs`) for a resident
4672/// device decode.
4673pub struct Qi21VaeDecodeArgs<'a> {
4674    /// Identity of the weights: a backend caches its planes by it.
4675    pub key: u64,
4676    pub post_quant: Qi21VaeConvRef<'a>,
4677    pub conv_in: Qi21VaeConvRef<'a>,
4678    pub mid_res: [Qi21VaeResRef<'a>; 2],
4679    /// The mid attention: RMS_norm γ, `to_qkv` (1×1, 3c outputs: q, k, v),
4680    /// `proj` (1×1); single head, residual.
4681    pub attn_gamma: &'a [f32],
4682    pub attn_qkv: Qi21VaeConvRef<'a>,
4683    pub attn_proj: Qi21VaeConvRef<'a>,
4684    pub ups: Vec<Qi21VaeUpRef<'a>>,
4685    pub norm_out: &'a [f32],
4686    pub conv_out: Qi21VaeConvRef<'a>,
4687}
4688
4689/// Resident VAE decode: `z` = raw latent planes `[z_dim, h·w]` → `out`
4690/// `[out_channels, 16h·16w]` (before the clamp). `false` = not handled,
4691/// `out` untouched: the per-conv path runs.
4692#[allow(unused_variables)]
4693pub fn qi21_vae_decode(a: &Qi21VaeDecodeArgs, z: &[f32], h: usize, w: usize, out: &mut [f32]) -> bool {
4694    match backend() {
4695        #[cfg(feature = "gpu")]
4696        Backend::Wgpu => crate::gpu_wgpu::qi21_vae::decode(a, z, h, w, out),
4697        #[allow(unreachable_patterns)]
4698        _ => false,
4699    }
4700}
4701
4702/// One Z-Image transformer block's device inputs (noise refiner, context
4703/// refiner or main layer — all share this shape). Weights are tensor
4704/// indices into `model.tensors` (diffusers names under `dit.`); the codec
4705/// is whatever the container holds (F16/Bf16/Q8Row/Q8_2f/Q4TiledP…), and a
4706/// backend that cannot expand a codec declines (returns `false`).
4707/// Norm vectors are f32 host slices that live as long as the caller's
4708/// `ZImageDit`; a backend may cache them by pointer (they do not change).
4709#[derive(Clone, Copy)]
4710pub struct ZBlockRef<'a> {
4711    /// `attention.to_q/to_k/to_v/to_out.0.weight`, each [hidden, hidden].
4712    pub wq: usize,
4713    pub wk: usize,
4714    pub wv: usize,
4715    pub wo: usize,
4716    /// `feed_forward.w1` (gate) / `w3` (up) [inter, hidden], `w2` (down)
4717    /// [hidden, inter]. FFN = w2(silu(w1·x) ⊙ w3·x).
4718    pub w1: usize,
4719    pub w3: usize,
4720    pub w2: usize,
4721    /// `attention_norm1` / `attention_norm2`, [hidden] (plain-w RMSNorm).
4722    pub norm1: &'a [f32],
4723    pub norm2: &'a [f32],
4724    /// `ffn_norm1` / `ffn_norm2`, [hidden].
4725    pub ffn_norm1: &'a [f32],
4726    pub ffn_norm2: &'a [f32],
4727    /// `attention.norm_q` / `norm_k`, [hd] (per-head RMSNorm before RoPE).
4728    pub norm_q: &'a [f32],
4729    pub norm_k: &'a [f32],
4730}
4731
4732/// Z-Image geometry. Turbo: hidden 3840, nh 30 (MHA, no GQA), hd 128,
4733/// inter 10240, eps 1e-5 (all RMSNorms incl. qk-norm), final_eps 1e-6
4734/// (the affine-free final LayerNorm), patch_dim 64 (2×2×16).
4735#[derive(Clone, Copy, Debug, PartialEq)]
4736pub struct ZGeom {
4737    pub hidden: usize,
4738    pub nh: usize,
4739    pub hd: usize,
4740    pub inter: usize,
4741    pub eps: f32,
4742    pub final_eps: f32,
4743    pub patch_dim: usize,
4744}
4745
4746/// Once per (prompt, resolution). The backend uploads/caches what it needs
4747/// keyed by `key`; weight planes are keyed by the MODEL (not by `key`) and
4748/// survive across prompts until `zimage_release`.
4749pub struct ZPrepareArgs<'a> {
4750    pub model: &'a Arc<CmfModel>,
4751    pub geom: ZGeom,
4752    /// Caller-chosen identity of this (prompt, resolution) state; every
4753    /// `ZStepArgs` of the same image carries the same key.
4754    pub key: u64,
4755    /// Image tokens (H/16 · W/16), padded count ceil32(n_img), caption
4756    /// padded count ceil32(L). S = n_img_p + n_cap_p.
4757    pub n_img: usize,
4758    pub n_img_p: usize,
4759    pub n_cap_p: usize,
4760    /// The patch grid (H/16, W/16); n_img = grid.0 · grid.1. Row-major
4761    /// token order `hp·grid.1 + wp`.
4762    pub grid: (usize, usize),
4763    /// [n_cap_p, hidden], ALREADY context-refined (host or device).
4764    pub cap: &'a [f32],
4765    /// Noise-refiner RoPE: [n_img_p · hd/2] cos, sin (complex-interleaved
4766    /// pairs, hd/2 angles per token).
4767    pub rope_img: (&'a [f32], &'a [f32]),
4768    /// Main-layer RoPE: [(n_img_p + n_cap_p) · hd/2], rows ordered [img, cap].
4769    pub rope_joint: (&'a [f32], &'a [f32]),
4770    /// `all_x_embedder.2-1.weight` [hidden, 64], `.bias` [hidden],
4771    /// `x_pad_token` [hidden] (replaces rows ≥ n_img after the embed).
4772    pub x_emb_w: &'a [f32],
4773    pub x_emb_b: &'a [f32],
4774    pub x_pad: &'a [f32],
4775    /// `all_final_layer.2-1.linear.weight` [64, hidden], `.bias` [64].
4776    pub final_w: &'a [f32],
4777    pub final_b: &'a [f32],
4778    /// 2 noise-refiner blocks (image rows only) and 30 main layers.
4779    pub noise_refiner: &'a [ZBlockRef<'a>],
4780    pub layers: &'a [ZBlockRef<'a>],
4781    /// OPTIONAL (backends may ignore): the modulation of EVERY step of this
4782    /// image, [steps][(2+30)·4·hidden] in the `ZStepArgs::mods` layout, and
4783    /// [steps][hidden] final scales, so a backend can upload them once per
4784    /// image and index them by `ZStepArgs::step`. `ZStepArgs::mods` is still
4785    /// always supplied and is authoritative.
4786    pub mods_all: Option<&'a [f32]>,
4787    pub final_scale_all: Option<&'a [f32]>,
4788    /// OPTIONAL (B2): the CFG negative item. When `Some`, the backend
4789    /// prepares ONE batch-2 program under `key` — item 0 is this prompt,
4790    /// item 1 the negative — and every `ZStepArgs` of that key must carry
4791    /// `out_neg`. A backend without batch 2 returns `false` (the caller
4792    /// then prepares the two items separately or runs the CPU path).
4793    pub neg: Option<ZNegArgs<'a>>,
4794}
4795
4796/// The negative (unconditional) item of a CFG pair: its own refined
4797/// caption, padded caption length and joint RoPE table (the image ids sit
4798/// at axis-0 position L_p+1, so both tables depend on the item's L_p).
4799pub struct ZNegArgs<'a> {
4800    /// [n_cap_p, hidden], context-refined.
4801    pub cap: &'a [f32],
4802    pub n_cap_p: usize,
4803    /// [n_img_p · hd/2] cos, sin (noise refiner) of this item.
4804    pub rope_img: (&'a [f32], &'a [f32]),
4805    /// [(n_img_p + n_cap_p) · hd/2] cos, sin, rows [img, cap].
4806    pub rope_joint: (&'a [f32], &'a [f32]),
4807}
4808
4809/// Once per denoising step.
4810pub struct ZStepArgs<'a> {
4811    /// The `ZPrepareArgs::key` this step belongs to. A key the backend has
4812    /// not prepared → `false`.
4813    pub key: u64,
4814    /// Step index into the schedule (0..steps); selects the row of
4815    /// `ZPrepareArgs::mods_all` when a backend uses it.
4816    pub step: usize,
4817    /// [n_img_p, 64] patchified latent, inner order (dy·2+dx)·16+c. Rows
4818    /// ≥ n_img are copies of the last row; the backend replaces them with
4819    /// `x_pad` after the embed.
4820    pub x_tok: &'a [f32],
4821    /// Per block (noise_refiner then layers) the RAW chunks
4822    /// [scale_msa, gate_msa, scale_mlp, gate_mlp] of Linear(temb) (no SiLU
4823    /// before it), [(2+30)·4·hidden]. The backend applies (1+s) and tanh(g).
4824    pub mods: &'a [f32],
4825    /// [hidden] = 1 + Linear(SiLU(temb)) — already includes the +1.
4826    pub final_scale: &'a [f32],
4827    /// [n_img, 64]: the model output v (before the pipeline's negation),
4828    /// image rows only, patchified order.
4829    pub out: &'a mut [f32],
4830    /// [n_img, 64]: the negative item's v — required (and only valid) for
4831    /// a key prepared with `ZPrepareArgs::neg`. Both items see `x_tok`.
4832    pub out_neg: Option<&'a mut [f32]>,
4833}
4834
4835/// Prepare the per-(prompt, resolution) device state. Backends: wgpu →
4836/// `gpu_wgpu::zimage::prepare` (WP2), Metal → `gpu_metal::zimage::prepare`
4837/// (WP3).
4838#[allow(unused_variables)]
4839pub fn zimage_prepare(a: &ZPrepareArgs) -> bool {
4840    match backend() {
4841        #[cfg(target_os = "macos")]
4842        Backend::Metal => crate::gpu_metal::zimage::prepare(a),
4843        #[cfg(feature = "gpu")]
4844        Backend::Wgpu => crate::gpu_wgpu::zimage::prepare(a),
4845        #[allow(unreachable_patterns)]
4846        _ => false,
4847    }
4848}
4849
4850/// One full DiT forward on the device: x_embed → pad rows → noise refiner
4851/// ×2 → concat [img, cap] → 30 layers → final LayerNorm·scale → Linear →
4852/// image rows into `a.out`.
4853#[allow(unused_variables)]
4854pub fn zimage_step(a: &mut ZStepArgs) -> bool {
4855    match backend() {
4856        #[cfg(target_os = "macos")]
4857        Backend::Metal => crate::gpu_metal::zimage::step(a),
4858        #[cfg(feature = "gpu")]
4859        Backend::Wgpu => crate::gpu_wgpu::zimage::step(a),
4860        #[allow(unreachable_patterns)]
4861        _ => false,
4862    }
4863}
4864
4865/// OPTIONAL (B2): build the backend's weight planes for the per-step blocks
4866/// and the context refiner ahead of `zimage_prepare`, so the caller can
4867/// overlap the upload with the (CPU) text encoder. `false` = not done;
4868/// `zimage_prepare` builds whatever is missing either way.
4869#[allow(unused_variables)]
4870pub fn zimage_preload(
4871    model: &Arc<CmfModel>,
4872    geom: &ZGeom,
4873    noise_refiner: &[ZBlockRef],
4874    layers: &[ZBlockRef],
4875    context_refiner: &[ZBlockRef],
4876) -> bool {
4877    match backend() {
4878        #[cfg(target_os = "macos")]
4879        Backend::Metal => {
4880            crate::gpu_metal::zimage::preload(model, geom, noise_refiner, layers, context_refiner)
4881        }
4882        #[cfg(feature = "gpu")]
4883        Backend::Wgpu => crate::gpu_wgpu::zimage::preload(model, geom, noise_refiner, layers, context_refiner),
4884        #[allow(unreachable_patterns)]
4885        _ => false,
4886    }
4887}
4888
4889/// Persist the driver's compiled pipelines after a Z-Image generation (the
4890/// chain's kernels are built at first use, after the context came up), so
4891/// the next process skips the compile. Best-effort, no-op off wgpu.
4892pub fn zimage_flush_pipelines() {
4893    #[cfg(feature = "gpu")]
4894    if matches!(backend(), Backend::Wgpu) {
4895        crate::gpu_wgpu::pipeline_cache_flush();
4896    }
4897}
4898
4899/// OPTIONAL (B2): bring the device up and compile the Z-Image kernels, on
4900/// a helper thread at the start of a generation (the context and the
4901/// compiles cost ~1 s cold, beside the host-side loading). `false` = no
4902/// device path here.
4903pub fn zimage_warmup() -> bool {
4904    match backend() {
4905        #[cfg(target_os = "macos")]
4906        Backend::Metal => crate::gpu_metal::zimage::warmup(),
4907        #[cfg(feature = "gpu")]
4908        Backend::Wgpu => crate::gpu_wgpu::zimage::warmup(),
4909        #[allow(unreachable_patterns)]
4910        _ => false,
4911    }
4912}
4913
4914/// OPTIONAL (B2): upload the resident VAE's weights and compile its
4915/// kernels ahead of `vae_decode_chain` (the caller runs it on a helper
4916/// thread while the DiT steps keep the device busy). `false` = not done.
4917#[allow(unused_variables)]
4918pub fn vae_prewarm(a: &crate::vae::VaeChainArgs) -> bool {
4919    match backend() {
4920        #[cfg(target_os = "macos")]
4921        Backend::Metal => crate::gpu_metal::zimage::vae_prewarm(a),
4922        #[cfg(feature = "gpu")]
4923        Backend::Wgpu => crate::gpu_wgpu::zimage::vae_prewarm(a),
4924        #[allow(unreachable_patterns)]
4925        _ => false,
4926    }
4927}
4928
4929/// Drop the Z-Image DiT device state (planes, prepared programs) but keep
4930/// the VAE chain (B2: the generator frees the DiT before decoding).
4931pub fn zimage_release_dit() {
4932    #[cfg(target_os = "macos")]
4933    crate::gpu_metal::zimage::release_dit();
4934    #[cfg(feature = "gpu")]
4935    crate::gpu_wgpu::zimage::release_dit();
4936}
4937
4938/// Drop every Z-Image device resource (planes, prepared states, VAE chain
4939/// buffers): stage change or process end. Calls each compiled backend's
4940/// release directly, without `backend()`, so it never brings a device up;
4941/// the child modules' `release` must touch module-local state only.
4942pub fn zimage_release() {
4943    #[cfg(target_os = "macos")]
4944    crate::gpu_metal::zimage::release();
4945    #[cfg(feature = "gpu")]
4946    crate::gpu_wgpu::zimage::release();
4947}
4948
4949/// Optional device context refiner: the same block math with scale = 0 and
4950/// gate = 1 (unmodulated): x += norm2(attn(norm1(x))); x += ffn_norm2(ffn(
4951/// ffn_norm1(x))). `cap` is [n_cap_p, hidden] in/out (the cap_embedder
4952/// output with pad rows already = cap_pad_token); `rope_cap` is
4953/// [n_cap_p · hd/2] cos, sin. `false` = untouched, run the CPU refiner.
4954#[allow(unused_variables)]
4955pub fn zimage_refine_caption(
4956    model: &Arc<CmfModel>,
4957    geom: &ZGeom,
4958    blocks: &[ZBlockRef],
4959    rope_cap: (&[f32], &[f32]),
4960    cap: &mut [f32],
4961) -> bool {
4962    match backend() {
4963        #[cfg(target_os = "macos")]
4964        Backend::Metal => {
4965            crate::gpu_metal::zimage::refine_caption(model, geom, blocks, rope_cap, cap)
4966        }
4967        #[cfg(feature = "gpu")]
4968        Backend::Wgpu => {
4969            crate::gpu_wgpu::zimage::refine_caption(model, geom, blocks, rope_cap, cap)
4970        }
4971        #[allow(unreachable_patterns)]
4972        _ => false,
4973    }
4974}
4975
4976/// Resident Flux-VAE decode (the whole decoder on the device, one latent
4977/// upload, one RGB readback). `a` comes from `VaeDecoder::chain_args()`.
4978/// `z` is [latent_channels, h, w] ALREADY de-normalised
4979/// (z/scaling_factor + shift_factor — the conv_in input); `out` is
4980/// [3, 8h, 8w], the raw decoder output (≈[-1, 1], before x/2+0.5).
4981#[allow(unused_variables)]
4982pub fn vae_decode_chain(
4983    a: &crate::vae::VaeChainArgs,
4984    z: &[f32],
4985    h: usize,
4986    w: usize,
4987    out: &mut [f32],
4988) -> bool {
4989    match backend() {
4990        #[cfg(target_os = "macos")]
4991        Backend::Metal => crate::gpu_metal::zimage::vae_decode_chain(a, z, h, w, out),
4992        #[cfg(feature = "gpu")]
4993        Backend::Wgpu => crate::gpu_wgpu::zimage::vae_decode_chain(a, z, h, w, out),
4994        #[allow(unreachable_patterns)]
4995        _ => false,
4996    }
4997}