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    /// The frequencies of the rotary pairs: the wide path rotates by the absolute
40    /// position and the host writes those angles per token.
41    pub rope_freq: Vec<f32>,
42    pub max_seq: usize,
43    pub cluster_count: usize,
44    pub cluster_size: usize,
45    pub phase_state_len: usize,
46    pub state_stride: usize,
47    pub kv_stride: usize,
48    pub norm_gemma: bool,
49    pub phase_mass: f32,
50    pub weights: Vec<f32>,
51    pub meta: Vec<u32>,
52    pub lm_head: Vec<f32>,
53    /// The wide token path: matrices and head in the file's f16 or q8_2f, read
54    /// by `gpu_wgpu/embryo_wide.wgsl`. `weights` then holds only the small tensors.
55    pub wide: bool,
56    pub wide_q8: bool,
57    pub mats: Vec<u8>,
58    pub lm_head_packed: Vec<u8>,
59    pub clusters: Vec<f32>,
60    pub final_norm: Vec<f32>,
61    pub inv_freq: Vec<f32>,
62    /// Natively bounded anchors (`swa_sink_v1`): every anchor layer owns a
63    /// ring of `anchor_window` raw keys/values instead of a `max_seq` KV
64    /// plane, so `kv_stride` is the ring size, `kv_layers` counts the
65    /// anchors, and no position cap applies (the operator has none).
66    pub bounded: bool,
67    /// Layers that own a KV/ring slot of `kv_stride` f32 (all layers for
68    /// the legacy full anchor — offsets are `layer·kv_stride` — or the
69    /// bounded anchors only).
70    pub kv_layers: usize,
71    /// Recurrent (phase or GDN) layers — the state buffer holds one
72    /// `state_stride` per such layer; anchors own none.
73    pub state_layers: usize,
74    pub anchor_window: usize,
75    pub anchor_sink: usize,
76    /// vmf_phase mixer layers (kind 0/1) in the stack.
77    pub phase_layers: usize,
78    /// GatedDeltaNet mixer layers (kind 4) in the stack; their geometry
79    /// is `gdn_heads` (nv), `gdn_k_heads` (nk), `gdn_dk`, `gdn_dv`,
80    /// `gdn_kk` (conv taps) — header words 24..29 of `meta`.
81    pub gdn_layers: usize,
82    pub gdn_heads: usize,
83    pub gdn_k_heads: usize,
84    pub gdn_dk: usize,
85    pub gdn_dv: usize,
86    pub gdn_kk: usize,
87}
88
89impl EmbryoGraphModel {
90    /// Fused q/k/v projection width of the GDN mixer (`2·nk·dk + nv·dv`).
91    pub fn gdn_c_dim(&self) -> usize {
92        2 * self.gdn_k_heads * self.gdn_dk + self.gdn_heads * self.gdn_dv
93    }
94}
95
96/// Words in the resident graph's `meta` header before the per-layer
97/// records (64 words each). Shared by the host packer and the encoder.
98pub const EMBRYO_META_HEADER: usize = 32;
99
100/// Positions one chunked-prefill submit of the resident Embryo graph
101/// covers (the shader's `CMAX`; the chunk window of the scratch buffer is
102/// sized by it).
103pub const EMBRYO_CHUNK_MAX: usize = 64;
104
105/// `n` contiguous prompt positions (`rows` = n × hidden embeddings from
106/// `position`) through the resident Embryo graph in one submit; logits of
107/// the last position. False = refused before any device work (the caller
108/// keeps the per-position path), or the sequence went cold.
109pub fn forward_embryo_graph_chunk(
110    model: &Arc<EmbryoGraphModel>,
111    kv_id: u64,
112    rows: &[f32],
113    position: usize,
114    n: usize,
115    logits: &mut Vec<f32>,
116) -> bool {
117    #[cfg(feature = "cuda")]
118    if backend() == Backend::Cuda {
119        return crate::gpu_cuda::forward_embryo_graph_chunk(model, kv_id, rows, position, n, logits);
120    }
121    #[cfg(feature = "gpu")]
122    if backend() == Backend::Wgpu {
123        return crate::gpu_wgpu::forward_embryo_graph_chunk(model, kv_id, rows, position, n, logits);
124    }
125    let _ = (model, kv_id, rows, position, n, logits);
126    false
127}
128
129/// Bytes the resident Embryo graph holds on the device for a sequence:
130/// `(recurrent state, anchor KV/ring)`. None when the sequence has no
131/// device image (host path, or not started yet). This is the measured
132/// long-context claim of the resident path — a bounded genome reports
133/// the same two numbers at every context depth.
134pub fn embryo_device_state_bytes(kv_id: u64) -> Option<(u64, u64)> {
135    #[cfg(feature = "cuda")]
136    if backend() == Backend::Cuda {
137        return crate::gpu_cuda::embryo_device_state_bytes(kv_id);
138    }
139    #[cfg(feature = "gpu")]
140    if backend() == Backend::Wgpu {
141        return crate::gpu_wgpu::embryo_device_state_bytes(kv_id);
142    }
143    let _ = kv_id;
144    None
145}
146
147/// Does this directory entry count as WEIGHT in the device placement
148/// heuristics (layer prefix, live-weight budget, `serve` replicas vs
149/// split)? On a genome file only the trunk does: skill tensors replace
150/// trunk tensors of the same shape inside their own lane, so counting
151/// them would give the backbone of F1 another GPU prefix than F0's
152/// (NF-7). Other files keep the historical whole-directory count.
153pub fn counts_as_placement_weight(model: &CmfModel, name: &str) -> bool {
154    model.header.genome.is_none() || cortiq_core::knowledge::is_trunk_tensor(name)
155}
156
157/// Weight bytes the placement heuristics budget for `model`: the trunk's
158/// payload on a genome file ([`counts_as_placement_weight`]), the whole
159/// mapped file otherwise (the historical measure).
160pub fn placement_weight_bytes(model: &CmfModel) -> u64 {
161    if model.header.genome.is_none() {
162        return model.primary_bytes().len() as u64;
163    }
164    model
165        .tensors
166        .iter()
167        .filter(|t| counts_as_placement_weight(model, &t.name))
168        .map(|t| t.nbytes)
169        .sum()
170}
171
172/// Next position of the resident Embryo sequence `kv_id` (`Some(n)` = the
173/// device holds positions `0..n` of it), `None` when the device holds no
174/// initialized image of that sequence — the host owns it (or none began).
175pub fn embryo_device_next_position(kv_id: u64) -> Option<usize> {
176    #[cfg(feature = "cuda")]
177    if backend() == Backend::Cuda {
178        return crate::gpu_cuda::embryo_device_next_position(kv_id);
179    }
180    #[cfg(feature = "gpu")]
181    if backend() == Backend::Wgpu {
182        return crate::gpu_wgpu::embryo_device_next_position(kv_id);
183    }
184    let _ = kv_id;
185    None
186}
187
188thread_local! {
189    /// Index of the current forward layer (−1 = outside a numbered layer:
190    /// lm_head/embed — always allowed). The pipeline sets it before
191    /// each layer so that the GPU/CPU layer-split works.
192    static CUR_LAYER: Cell<i64> = const { Cell::new(-1) };
193    /// Inside `cpu_scope` every GPU gate reports disabled: the timed CPU
194    /// arm of a probe (and a class that lost its probe) must run PURE
195    /// CPU, or inner per-op hooks would re-enter the GPU and poison the
196    /// comparison.
197    static CPU_ONLY: Cell<bool> = const { Cell::new(false) };
198    /// "This op paid a one-off cost" (weight upload / first pipeline
199    /// build): backends set it, `probe_record` discards the sample so
200    /// only steady-state timings compete.
201    static PROBE_COLD: Cell<bool> = const { Cell::new(false) };
202}
203
204/// RAII form of `cpu_scope`, used when a device-prefix graph hands a whole
205/// remainder of the forward pass to the host. Without a guard around that
206/// tail, its ordinary per-op hooks re-entered the GPU and streamed the rest of
207/// an over-size model through the residency arena, defeating the prefix's VRAM
208/// bound at the driver-allocation level.
209pub struct CpuScopeGuard(bool);
210
211impl Drop for CpuScopeGuard {
212    fn drop(&mut self) {
213        CPU_ONLY.with(|c| c.set(self.0));
214    }
215}
216
217pub fn enter_cpu_scope() -> CpuScopeGuard {
218    let previous = CPU_ONLY.with(|c| c.replace(true));
219    CpuScopeGuard(previous)
220}
221
222/// Temporarily turn the CPU-only gate back ON inside a held
223/// [`enter_cpu_scope`] (the host tail holds one for its per-op layers).
224/// The pooled tail's own device frames are explicitly device-owned — the
225/// same escape hatch the MiniCPM prepared frame documents — and must not be
226/// declined by the surrounding scope. Restores the previous flag on drop.
227pub fn gpu_scope<R>(f: impl FnOnce() -> R) -> R {
228    struct Restore(bool);
229    impl Drop for Restore {
230        fn drop(&mut self) {
231            CPU_ONLY.with(|c| c.set(self.0));
232        }
233    }
234    let prev = CPU_ONLY.with(|c| c.replace(false));
235    let restore = Restore(prev);
236    let out = f();
237    drop(restore);
238    out
239}
240
241/// Run `f` with the GPU gates off on this thread (pure-CPU arm).
242pub fn cpu_scope<R>(f: impl FnOnce() -> R) -> R {
243    let _restore = enter_cpu_scope();
244    f()
245}
246
247/// Capture CPU-only placement before dispatching whole operators to workers.
248/// `cpu_scope` is thread-local, while a MoE panel worker calls QTensor again;
249/// without inheritance, which expert happened to land on the caller changed
250/// its precision/backend from run to run.
251pub(crate) fn inherit_cpu_scope() -> impl Fn() -> Option<CpuScopeGuard> + Copy {
252    let on = CPU_ONLY.get();
253    move || on.then(enter_cpu_scope)
254}
255
256/// Backends: name the device once at init. The probe cache is keyed by
257/// it, because a verdict is a property of THIS silicon and nothing else.
258/// First writer wins: a process runs one backend, and on the rare host
259/// where two initialize, the one that came up first is the one in use.
260pub fn probe_set_device(label: &str) {
261    let _ = DEVICE_LABEL.set(label.to_string());
262}
263
264fn device_label() -> &'static str {
265    DEVICE_LABEL.get().map(String::as_str).unwrap_or("unknown")
266}
267
268static DEVICE_LABEL: std::sync::OnceLock<String> = std::sync::OnceLock::new();
269
270/// Somewhere this process may write small caches.
271///
272/// `std::env::temp_dir()` is NOT that place on Android: with no `TMPDIR`
273/// it answers `/tmp`, which does not exist in an app sandbox, and every
274/// write fails silently — measured, after the pipeline cache appeared to
275/// work in a shell (where `TMPDIR=/data/local/tmp`) and did nothing at
276/// all in the app. The loader points this at the model's own directory,
277/// which is somewhere the caller already writes.
278static CACHE_DIR: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();
279
280/// Loader: name a directory this process can write to. First call wins.
281pub fn set_cache_dir(dir: std::path::PathBuf) {
282    let _ = CACHE_DIR.set(dir);
283}
284
285/// Same directory, for the backends.
286pub fn cache_dir_pub() -> std::path::PathBuf {
287    cache_dir()
288}
289
290fn cache_dir() -> std::path::PathBuf {
291    if let Some(d) = CACHE_DIR.get() {
292        return d.clone();
293    }
294    match std::env::var_os("TMPDIR") {
295        Some(t) => std::path::PathBuf::from(t),
296        None => std::env::temp_dir(),
297    }
298}
299
300/// Where decided verdicts are remembered between runs. `CMF_PROBE_CACHE`
301/// overrides the path; `0` disables the cache entirely.
302fn probe_cache_path() -> Option<std::path::PathBuf> {
303    match std::env::var("CMF_PROBE_CACHE") {
304        Ok(v) if v == "0" => None,
305        Ok(v) => Some(std::path::PathBuf::from(v)),
306        Err(_) => Some(cache_dir().join("cortiq-gpu-probe.tsv")),
307    }
308}
309
310/// One line per decided class: `version \t device \t class \t winner`.
311/// A different engine build or a different device simply does not match,
312/// so a stale file is inert rather than wrong.
313fn probe_cache_key_named(class: &str) -> String {
314    format!(
315        "{}\t{}\t{}",
316        env!("CARGO_PKG_VERSION"),
317        device_label(),
318        class
319    )
320}
321
322const CLASS_NAMES: [&str; 8] = [
323    "ffn",
324    "matvec",
325    "matmat",
326    "qkv-batch",
327    "matmat-wide",
328    "lm-head",
329    "gemm-nt",
330    // MoE has a different residency policy from a dense FFN. In
331    // particular, an out-of-core Metal MoE block can become viable after a
332    // dense `ffn` probe has (correctly) decided that ordinary per-op FFNs
333    // lose. Never let that remembered verdict suppress the separate path.
334    "moe",
335];
336
337/// Adopt every verdict this device already reached in an earlier run.
338///
339/// Probing is not cheap and it is not free of consequences: on a
340/// Snapdragon 778G the three deciding classes took **three minutes of
341/// wall clock** before the first token, every process, and in the phone
342/// app that was the whole first answer — 209.6 s for 25 tokens against
343/// 10.5 s on the CPU path. The verdict itself was the same every time.
344/// Paying to rediscover it is the defect; the answer is to write it down.
345fn probe_cache_load() {
346    static ONCE: std::sync::Once = std::sync::Once::new();
347    ONCE.call_once(|| {
348        let Some(path) = probe_cache_path() else {
349            return;
350        };
351        // Unit tests share this process and its default cache path; a
352        // verdict left by an earlier run would decide a class before the
353        // arbitration tests get to watch it alternate. Tests that mean to
354        // exercise the cache point `CMF_PROBE_CACHE` at their own file.
355        if cfg!(test) && std::env::var("CMF_PROBE_CACHE").is_err() {
356            return;
357        }
358        let Ok(text) = std::fs::read_to_string(&path) else {
359            return;
360        };
361        probe_cache_adopt(&text);
362    });
363}
364
365/// Apply verdicts from a cache file's text. Split out from the file
366/// reading so the adoption rule — including which lines must be IGNORED
367/// — is testable without a filesystem.
368fn probe_cache_adopt(text: &str) {
369    for line in text.lines() {
370        let Some((key, verdict)) = line.rsplit_once('\t') else {
371            continue;
372        };
373        let winner = match verdict.trim() {
374            "gpu" => 1u8,
375            "cpu" => 2u8,
376            _ => continue,
377        };
378        for (i, name) in CLASS_NAMES.iter().enumerate() {
379            if probe_cache_key_named(name) == key {
380                let _ = PROBES[i].state.compare_exchange(
381                    0,
382                    winner,
383                    Ordering::Relaxed,
384                    Ordering::Relaxed,
385                );
386                tracing::debug!("gpu probe [{name}]: remembered → {verdict}");
387            }
388        }
389    }
390}
391
392/// Remember a verdict for the next run. Best-effort: a read-only cache
393/// directory costs a re-probe, never a failure.
394fn probe_cache_store(c: OpClass, winner: u8) {
395    let Some(path) = probe_cache_path() else {
396        return;
397    };
398    let line = format!(
399        "{}\t{}\n",
400        probe_cache_key_named(CLASS_NAMES[c as usize]),
401        if winner == 1 { "gpu" } else { "cpu" }
402    );
403    use std::io::Write;
404    if let Ok(mut f) = std::fs::OpenOptions::new()
405        .create(true)
406        .append(true)
407        .open(&path)
408    {
409        let _ = f.write_all(line.as_bytes());
410    }
411}
412
413/// Backends: note a one-off cost (weight upload, buffer-cache fill) so
414/// the probe discards this sample.
415/// Every buffer creation anywhere bumps this; the graph's bind-group
416/// cache treats any cold event as total invalidation — a stale bind
417/// group is silent corruption, a cleared cache is one re-encoded token.
418pub fn cold_epoch() -> u64 {
419    COLD_EPOCH.load(std::sync::atomic::Ordering::Relaxed)
420}
421static COLD_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
422
423pub(crate) fn probe_note_cold() {
424    COLD_EPOCH.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
425    PROBE_COLD.with(|c| c.set(true));
426}
427
428/// Peek the cold flag without consuming it (`probe_record` consumes).
429/// Contention heuristics use this: a slow COLD op is a one-off build
430/// cost, not evidence the device is busy.
431pub(crate) fn probe_was_cold() -> bool {
432    PROBE_COLD.with(|c| c.get())
433}
434
435/// Pipeline: mark the current layer (or −1 outside layers) for layer-split.
436pub fn set_layer(l: i64) {
437    CUR_LAYER.with(|c| c.set(l));
438}
439
440/// The layer `set_layer` last marked on this thread (−1 outside layers).
441pub fn cur_layer() -> i64 {
442    CUR_LAYER.with(|c| c.get())
443}
444
445/// Capacity-derived layer prefix for per-op walks. The explicit
446/// `CMF_GPU_LAYERS` override is handled by the backend and takes precedence.
447pub fn automatic_layer_prefix(
448    model: &Arc<CmfModel>,
449    num_layers: usize,
450    physical_layers: usize,
451) -> Option<usize> {
452    match backend() {
453        #[cfg(feature = "gpu")]
454        Backend::Wgpu => {
455            crate::gpu_wgpu::automatic_layer_prefix(model, num_layers, physical_layers)
456        }
457        _ => None,
458    }
459}
460
461/// Parse `CMF_GPU_LAYERS` («0-19», «0,2,4», «0-9,30-39») once.
462/// None = no restriction (all layers on GPU). Garbage → also no restriction.
463fn layer_ranges() -> &'static Option<Vec<(i64, i64)>> {
464    static R: OnceLock<Option<Vec<(i64, i64)>>> = OnceLock::new();
465    R.get_or_init(|| {
466        let s = std::env::var("CMF_GPU_LAYERS").ok()?;
467        let mut v = Vec::new();
468        for part in s.split(',') {
469            let part = part.trim();
470            match part.split_once('-') {
471                Some((a, b)) => v.push((a.trim().parse().ok()?, b.trim().parse().ok()?)),
472                None => {
473                    let x: i64 = part.parse().ok()?;
474                    v.push((x, x));
475                }
476            }
477        }
478        Some(v)
479    })
480}
481
482fn layer_allowed() -> bool {
483    match layer_ranges() {
484        None => true,
485        Some(ranges) => {
486            let cur = CUR_LAYER.with(|c| c.get());
487            cur < 0 || ranges.iter().any(|(a, b)| cur >= *a && cur <= *b)
488        }
489    }
490}
491
492/// GPU allowed FOR THE CURRENT LAYER: backend is initialized AND the layer
493/// falls within `CMF_GPU_LAYERS` (GPU/CPU layer-split) AND we are not
494/// inside a `cpu_scope`. Op gates call this.
495pub fn enabled_here() -> bool {
496    !CPU_ONLY.with(|c| c.get()) && enabled() && layer_allowed()
497}
498
499/// Descriptor-aware q2tp Vulkan kernels are kept behind an explicit opt-in
500/// until the Prism full-graph/resident-weight path has a coherent generation
501/// gate.  `CMF_GPU=1` alone must not silently turn synchronous per-op
502/// readbacks into the default model path; callers and validation tests can
503/// request the measured kernels with `CMF_Q2TP_GPU=1`.
504pub fn q2tp_gpu_opt_in() -> bool {
505    std::env::var("CMF_Q2TP_GPU").as_deref() == Ok("1")
506}
507
508// ── Runtime GPU-vs-CPU probe ────────────────────────────────────────────
509// CMF_GPU=1 does not TRUST that the device wins — it MEASURES. For each
510// op class the first calls alternate arms: GPU timed vs pure-CPU timed
511// (under cpu_scope). Cold GPU calls (weight upload / cache fill) are
512// discarded; after PROBE_SAMPLES clean samples per arm the faster arm is
513// chosen for the rest of the process. Rationale: submit+poll latency
514// differs by an order of magnitude across driver stacks (Metal/PCIe
515// ~3-4 ms, Vulkan/4090 ~0.3 ms) — a static threshold cannot know whether
516// per-op offload pays off HERE. CMF_GPU_PROBE=0 → always trust the GPU.
517
518/// GPU-eligible op classes, each with an independent probe.
519#[derive(Clone, Copy)]
520pub enum OpClass {
521    /// Whole FFN chain in one submission (dense / MoE block).
522    Ffn = 0,
523    /// Large hybrid CPU∥GPU matvec (lm_head class).
524    Matvec = 1,
525    /// Prefill GEMM (matmat).
526    Matmat = 2,
527    /// Batched matvecs of one input (QKV).
528    Batch = 3,
529    /// Prefill GEMM at image-diffusion widths (b ≥ 128). Probed apart
530    /// from `Matmat`: one imagegen process runs BOTH populations
531    /// (prompt encode b≈40 where the GPU wins big, DiT b≥256 where
532    /// the CPU AMX arm is competitive) — a single shared verdict locks
533    /// the wrong arm for whichever population samples second.
534    MatmatWide = 4,
535    /// The lm_head itself, apart from the merely-large matvecs. Same
536    /// reasoning as `MatmatWide`, and DeepSeek-V4 is where it bit: its
537    /// attention projections are 37M weights and its head is 529M, so
538    /// the projections' verdict — CPU, honestly measured at 0.19 ms —
539    /// decided for a matvec fourteen times their size that took 11 ms
540    /// a token on the host.
541    MatvecHead = 5,
542    /// The blocked f32 GEMM (`fcd_ops::gemm_nt`): attention's QKᵀ and
543    /// AV, and the VAE decoders' projections. It used to take every job
544    /// over 4 M MACs on sight, with no CPU arm to lose to — which on
545    /// the MiniMax-H3 video decoder was three times SLOWER than the
546    /// host it displaced. Its population is per-head slices, nothing
547    /// like the weight GEMMs above, so it probes on its own.
548    GemmNt = 6,
549    /// A host-routed MoE block. Kept separate from [`Self::Ffn`] because
550    /// its selected-weight pager has different memory and latency costs.
551    Moe = 7,
552}
553
554/// Which probe a large matvec belongs to. The head is an order of
555/// magnitude bigger than anything else that reaches this gate, and the
556/// two populations do not have the same answer.
557pub fn matvec_class(rows: usize, cols: usize) -> OpClass {
558    if rows * cols >= 67_108_864 {
559        OpClass::MatvecHead
560    } else {
561        OpClass::Matvec
562    }
563}
564
565/// Probe verdict for one call.
566pub enum ProbeArm {
567    /// Run the GPU path (during probing: timed, recorded).
568    Gpu,
569    /// Probing: run the CPU path under `cpu_scope`, timed, recorded.
570    CpuTimed,
571    /// Decided: CPU won — run the CPU path (under `cpu_scope`).
572    Cpu,
573}
574
575/// Clean samples per arm before a class decides.
576const PROBE_SAMPLES: u32 = 6;
577
578/// Declines before a class gives the work to the host for good. High
579/// enough that a transient refusal — an unsealed state during prefill, a
580/// shape the kernel skips this once — cannot settle the question.
581const PROBE_DECLINE_LIMIT: u32 = 16;
582
583/// Device samples discarded before any count — see `Probe::gpu_burn`.
584const PROBE_WARMUP: u32 = 1;
585
586struct Probe {
587    /// 0 = probing, 1 = GPU won, 2 = CPU won.
588    state: AtomicU8,
589    flip: AtomicU32,
590    gpu_ns: AtomicU64,
591    gpu_n: AtomicU32,
592    /// Times the device arm was chosen and the device DECLINED.
593    ///
594    /// A decline carries no timing, so nothing is recorded — and a class
595    /// whose device path always refuses therefore never reaches a
596    /// verdict, alternates arms forever, and pays a failed device
597    /// attempt on half of every token's calls. Measured on an M4 with
598    /// LFM2.5-2.6B: `ffn` was still undecided after 9000 calls, and a
599    /// token cost 83.55 ms against 41.85 with the device off — twice the
600    /// price for work the host did anyway.
601    declines: AtomicU32,
602    /// GPU samples still to discard as warm-up.
603    ///
604    /// The cold flag catches buffer and weight uploads, but a compute
605    /// pipeline is compiled on first use and not every creation site
606    /// raises it — the wgpu path has 21 pipeline creations against 12
607    /// cold notes. One uncaught shader compile is enough to lose a
608    /// class for the whole process: `gemm-nt` on an A100 was recorded at
609    /// 117.01 ms against the host's 3.19 and sent to the CPU, which
610    /// parked a 27B bake on 2.6 cores with the card idle. The decision
611    /// already uses each arm's BEST sample, so discarding the first
612    /// GPU sample costs one extra round trip and removes the whole
613    /// class of first-call artefacts.
614    gpu_burn: AtomicU32,
615    cpu_ns: AtomicU64,
616    cpu_n: AtomicU32,
617    /// Best (minimum) sample per arm. The DECISION compares these:
618    /// means are poisoned by one-off cold costs the cold-flag cannot
619    /// see — e.g. the CPU arm's first mmap-cold expert matvec page
620    /// faults its weights in and reads 3× its steady state, which
621    /// locked the GPU arm on a 35B MoE at a 4× real-world loss. The
622    /// minimum is each arm's honest steady-state pace.
623    gpu_min: AtomicU64,
624    cpu_min: AtomicU64,
625}
626
627impl Probe {
628    const fn new() -> Self {
629        Self {
630            state: AtomicU8::new(0),
631            flip: AtomicU32::new(0),
632            gpu_ns: AtomicU64::new(0),
633            gpu_n: AtomicU32::new(0),
634            declines: AtomicU32::new(0),
635            gpu_burn: AtomicU32::new(PROBE_WARMUP),
636            cpu_ns: AtomicU64::new(0),
637            cpu_n: AtomicU32::new(0),
638            gpu_min: AtomicU64::new(u64::MAX),
639            cpu_min: AtomicU64::new(u64::MAX),
640        }
641    }
642}
643
644static PROBES: [Probe; 8] = [
645    Probe::new(),
646    Probe::new(),
647    Probe::new(),
648    Probe::new(),
649    Probe::new(),
650    Probe::new(),
651    Probe::new(),
652    Probe::new(),
653];
654
655/// A caller that knows its loop is long, uniform and warm can say so: the
656/// probe times ops in isolation and alternates arms to do it, which reads a
657/// sustained diffusion step as slower on the device than it is. Measured on
658/// an M4 at 672 video tokens: the probe picked the CPU at 1.25 ms against
659/// 0.88 ms per op, and the loop it picked for ran 23.9 s a step against the
660/// device's 19.7 s.
661static TRUST_GPU: AtomicBool = AtomicBool::new(false);
662
663/// Take the probe out of the loop until the guard drops.
664pub fn trust_gpu() -> GpuTrust {
665    let was = TRUST_GPU.swap(true, Ordering::Relaxed);
666    GpuTrust(was)
667}
668
669pub struct GpuTrust(bool);
670
671impl Drop for GpuTrust {
672    fn drop(&mut self) {
673        TRUST_GPU.store(self.0, Ordering::Relaxed);
674    }
675}
676
677fn probe_on_for(c: OpClass) -> bool {
678    // The trust is only for the *wide* class. A sustained diffusion step is
679    // where the probe reads a warm device as cold; the narrow batches inside
680    // the same loop — an audio stream of fifty-one tokens against the same
681    // weights — are small enough that submit latency can genuinely beat the
682    // arithmetic, and there the probe is right and should keep deciding.
683    if TRUST_GPU.load(Ordering::Relaxed) && matches!(c, OpClass::MatmatWide | OpClass::Ffn) {
684        return false;
685    }
686    probe_on()
687}
688
689/// Is the per-op GPU/CPU probe enabled (`CMF_GPU_PROBE`, default on)?
690/// The native Metal decode route never consults it — `q1_force` routes
691/// the token graph to the device outright — so it is reported, not used.
692pub fn probe_enabled() -> bool {
693    probe_on()
694}
695
696fn probe_on() -> bool {
697    static ON: OnceLock<bool> = OnceLock::new();
698    *ON.get_or_init(|| {
699        std::env::var("CMF_GPU_PROBE")
700            .map(|v| v != "0" && v != "off")
701            .unwrap_or(true)
702    })
703}
704
705/// q1 ops on the native Metal backend skip the probe entirely: the CPU
706/// q1 kernel is load-port-bound, the GPU one wins warm — and probe
707/// alternation itself cools the device between samples (measured: block
708/// times 5.8 ms warm vs 8.8 ms mixed). Other backends keep probing.
709pub fn q1_force() -> bool {
710    #[cfg(target_os = "macos")]
711    {
712        backend() == Backend::Metal
713    }
714    #[cfg(not(target_os = "macos"))]
715    {
716        false
717    }
718}
719
720/// Should a FUSED whole-block path trust the device instead of asking
721/// the per-op probe? True on native Metal and on discrete wgpu adapters.
722///
723/// The probe answers "is one wide matmat faster on the GPU", and for the
724/// DiT on Metal that is a coin flip — measured 2.62 ms GPU vs 2.56 ms
725/// CPU, a 2% spread that lands on either arm run to run. But the fused
726/// block's advantage is not per-op speed, it is that the hidden state,
727/// the packs and the attention panels never leave the device: end to end
728/// the whole-block path renders a 512² Lumina step in ~5.4 s against
729/// ~8.4 s when the probe happens to pick the CPU. Gating a fusion win on
730/// a per-op tie made every second render half-speed at random.
731///
732/// On a discrete card the verdict is never in doubt — an RTX 3090 against
733/// a 256-core EPYC measured 11.5 ms vs 31 ms per wide op, four runs out
734/// of four — so the probe's sampling phase is pure cost: it alone was 10%
735/// of a 512² render (74.3 s against 66.9 s with the probe off). Integrated
736/// and mobile adapters keep probing; there the submit latency is real and
737/// can genuinely lose.
738pub fn fused_block_trusted() -> bool {
739    #[cfg(target_os = "macos")]
740    if backend() == Backend::Metal {
741        return true;
742    }
743    wgpu_graph_default()
744}
745
746/// Which arm should this GPU-eligible call take? Consult AFTER the
747/// eligibility gates (`enabled_here` / `min_rows`) so only real
748/// candidates alternate.
749/// While a class is still probing, a call whose weights are NOT yet on
750/// the card should take the GPU arm anyway: the upload is work the next
751/// step needs regardless, and the sample it produces is discarded as
752/// cold — so handing that call to the CPU arm buys nothing and costs a
753/// host GEMM. Measured on a diffusion stack, where every layer is
754/// touched once per step and therefore EVERY first-step GPU sample is
755/// cold: one projection drew the CPU arm for the whole first step, 9.8 s
756/// against the 2.8 s it costs once the weights are warm.
757pub fn weight_is_resident(model: &Arc<CmfModel>, idx: usize) -> bool {
758    #[cfg(all(feature = "gpu", not(target_os = "macos")))]
759    {
760        return crate::gpu_wgpu::weight_is_resident(model, idx);
761    }
762    #[cfg(not(all(feature = "gpu", not(target_os = "macos"))))]
763    {
764        let _ = (model, idx);
765        true
766    }
767}
768
769pub fn probe_arm_cold_prefers_gpu(c: OpClass, weights_resident: bool) -> ProbeArm {
770    if !weights_resident && probe_deciding(c) {
771        return ProbeArm::Gpu;
772    }
773    probe_arm(c)
774}
775
776pub fn probe_arm(c: OpClass) -> ProbeArm {
777    // Every arbitrated call starts with a clean cold flag: both the
778    // sample discard in `probe_record` and the contention kill-switch
779    // read it AFTER the op, so a stale note from a previous call on
780    // this thread must not leak in.
781    PROBE_COLD.with(|f| f.set(false));
782    if !probe_on_for(c) {
783        return ProbeArm::Gpu;
784    }
785    probe_cache_load();
786    let p = &PROBES[c as usize];
787    match p.state.load(Ordering::Relaxed) {
788        1 => ProbeArm::Gpu,
789        2 => ProbeArm::Cpu,
790        _ => {
791            if p.flip.fetch_add(1, Ordering::Relaxed) % 2 == 0 {
792                ProbeArm::Gpu
793            } else {
794                ProbeArm::CpuTimed
795            }
796        }
797    }
798}
799
800/// The device arm was chosen and the device refused the work, so there
801/// is no time to record. Callers that fall through to the host MUST say
802/// so here, or the class can never decide.
803pub fn probe_note_decline(c: OpClass) {
804    let p = &PROBES[c as usize];
805    if p.state.load(Ordering::Relaxed) != 0 {
806        return;
807    }
808    let n = p.declines.fetch_add(1, Ordering::Relaxed) + 1;
809    if n >= PROBE_DECLINE_LIMIT
810        && p.state
811            .compare_exchange(0, 2, Ordering::Relaxed, Ordering::Relaxed)
812            .is_ok()
813    {
814        tracing::info!(
815            "gpu probe [{}]: device declined {n} times → cpu",
816            CLASS_NAMES[c as usize]
817        );
818    }
819}
820
821/// Record a timed arm sample; on the `PROBE_SAMPLES`-th clean sample of
822/// BOTH arms the class decides for the rest of the process.
823pub fn probe_record(c: OpClass, gpu: bool, dur: std::time::Duration) {
824    probe_record_into(
825        &PROBES[c as usize],
826        CLASS_NAMES[c as usize],
827        Some(c),
828        gpu,
829        dur,
830    )
831}
832
833/// The body of `probe_record` over ONE probe, so the decision can be
834/// driven in a test without touching the process-wide array.
835fn probe_record_into(
836    p: &Probe,
837    class_name: &str,
838    cache: Option<OpClass>,
839    gpu: bool,
840    dur: std::time::Duration,
841) {
842    if p.state.load(Ordering::Relaxed) != 0 {
843        return;
844    }
845    if gpu && PROBE_COLD.with(|f| f.replace(false)) {
846        return; // one-off cost in this call — not a steady-state sample
847    }
848    if gpu {
849        // Load-then-store rather than fetch_sub: a blind decrement at
850        // zero wraps a u32 to its maximum and mutes the arm forever.
851        // A benign race here burns one extra sample, which is free.
852        let left = p.gpu_burn.load(Ordering::Relaxed);
853        if left > 0 {
854            p.gpu_burn.store(left - 1, Ordering::Relaxed);
855            return; // warm-up: the first device sample builds its pipeline
856        }
857    }
858    let ns = dur.as_nanos().min(u64::MAX as u128) as u64;
859    if gpu {
860        p.gpu_ns.fetch_add(ns, Ordering::Relaxed);
861        p.gpu_n.fetch_add(1, Ordering::Relaxed);
862        p.gpu_min.fetch_min(ns, Ordering::Relaxed);
863    } else {
864        p.cpu_ns.fetch_add(ns, Ordering::Relaxed);
865        p.cpu_n.fetch_add(1, Ordering::Relaxed);
866        p.cpu_min.fetch_min(ns, Ordering::Relaxed);
867    }
868    let (gn, cn) = (
869        p.gpu_n.load(Ordering::Relaxed),
870        p.cpu_n.load(Ordering::Relaxed),
871    );
872    if gn >= 2 && cn >= 2 {
873        // Decide on each arm's BEST sample — the steady-state pace.
874        // Means carry one-off cold costs (mmap page-in on the CPU arm)
875        // that the cold-flag machinery cannot see.
876        let g = p.gpu_min.load(Ordering::Relaxed) as f64;
877        let cp = p.cpu_min.load(Ordering::Relaxed) as f64;
878        // Early verdict on a ≥2× gap — no reason to keep feeding the
879        // losing arm; close races take the full sample count. It was 3×,
880        // and the cost of that half-octave was measured: a DiT whose
881        // wide GEMMs run 11.4 ms on the device against 32.2 on the host
882        // (2.8×) kept ALTERNATING through the whole diffusion stack, and
883        // because the alternation counter is shared per class in call
884        // order, one projection drew the CPU arm every single time — 9.9
885        // seconds a step on a kernel that needs 0.4. Both arms are
886        // compared on their BEST sample, so a 2× gap is not noise.
887        if (gn < PROBE_SAMPLES || cn < PROBE_SAMPLES) && g < cp * 2.0 && cp < g * 2.0 {
888            return;
889        }
890        let winner = if g <= cp { 1 } else { 2 };
891        if p.state
892            .compare_exchange(0, winner, Ordering::Relaxed, Ordering::Relaxed)
893            .is_ok()
894        {
895            tracing::info!(
896                "gpu probe [{}]: gpu {:.2} ms vs cpu {:.2} ms per op → {}",
897                class_name,
898                g / 1e6,
899                cp / 1e6,
900                if winner == 1 { "gpu" } else { "cpu" },
901            );
902            if let Some(c) = cache {
903                probe_cache_store(c, winner);
904            }
905        }
906    }
907}
908
909/// Is the class still collecting samples? (Call sites use this to route
910/// cold-weight calls away from the GPU arm during probing.)
911pub fn probe_deciding(c: OpClass) -> bool {
912    probe_on_for(c) && PROBES[c as usize].state.load(Ordering::Relaxed) == 0
913}
914
915/// Probing helper: true — tensor `idx`'s quant weights are ALREADY
916/// device-resident (a clean GPU sample is possible now); false — they
917/// were not (the upload starts within the VRAM budget, so a later call
918/// finds them warm) or the tensor cannot go to the GPU at all. Keeps the
919/// probe from billing a full cold dispatch+readback to a sample it will
920/// discard anyway. The verdict needs only a couple of warm tensors, so
921/// probe-driven uploads are capped — the losing-GPU machine should not
922/// pay for uploading the whole layer stack it will never use; if the GPU
923/// wins, the rest uploads lazily on demand, in the same first-touch order.
924#[allow(unused_variables)]
925pub fn q8_resident_or_upload(model: &Arc<CmfModel>, idx: usize) -> bool {
926    static PROBE_UPLOADS: AtomicU32 = AtomicU32::new(0);
927    let may_upload = PROBE_UPLOADS.load(Ordering::Relaxed) < 4;
928    let resident = match backend() {
929        #[cfg(target_os = "macos")]
930        Backend::Metal => crate::gpu_metal::q8_resident_or_upload(model, idx, may_upload),
931        #[cfg(feature = "gpu")]
932        Backend::Wgpu => crate::gpu_wgpu::q8_resident_or_upload(model, idx, may_upload),
933        Backend::None => false,
934        #[cfg(feature = "cuda")]
935        Backend::Cuda => crate::gpu_cuda::h3_plane_ready(model, idx, may_upload),
936    };
937    if !resident && may_upload {
938        PROBE_UPLOADS.fetch_add(1, Ordering::Relaxed);
939    }
940    resident
941}
942
943/// Test hook: reset all probes to the undecided state.
944#[cfg(test)]
945pub(crate) fn probe_reset() {
946    for p in &PROBES {
947        p.state.store(0, Ordering::Relaxed);
948        p.flip.store(0, Ordering::Relaxed);
949        p.gpu_ns.store(0, Ordering::Relaxed);
950        p.gpu_n.store(0, Ordering::Relaxed);
951        p.cpu_ns.store(0, Ordering::Relaxed);
952        p.cpu_n.store(0, Ordering::Relaxed);
953    }
954}
955
956/// The probe table is process-global by design, while these unit tests reset
957/// and seed selected entries to exercise arbitration. Keep only those tests
958/// out of each other's way; production callers still probe concurrently.
959#[cfg(test)]
960static PROBE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
961
962#[cfg(test)]
963fn probe_test_guard() -> std::sync::MutexGuard<'static, ()> {
964    PROBE_TEST_LOCK
965        .lock()
966        .unwrap_or_else(std::sync::PoisonError::into_inner)
967}
968
969#[cfg(test)]
970mod probe_tests {
971    use super::*;
972    use std::time::Duration;
973
974    #[test]
975    fn cpu_only_whole_operator_dispatch_inherits_and_restores_scope() {
976        let pool = crate::pool::Pool::with_spin(3, 0);
977        cpu_scope(|| {
978            let inherit = inherit_cpu_scope();
979            pool.run_rows(64, &|_, _| {
980                let _guard = inherit();
981                assert!(CPU_ONLY.get());
982            });
983        });
984        pool.run_rows(64, &|_, _| assert!(!CPU_ONLY.get()));
985    }
986
987    // One test fn: PROBES is process-global and probe_reset touches all
988    // classes — parallel test threads would race.
989    #[test]
990    fn probe_alternates_discards_cold_and_decides() {
991        let _probe_guard = probe_test_guard();
992        probe_reset();
993        // Probing: arms alternate.
994        assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
995        assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::CpuTimed));
996
997        // A cold GPU sample (upload noted) must be discarded: feed a
998        // catastrophic cold sample, then clean fast-GPU samples — GPU
999        // wins only if the cold one did not count.
1000        probe_note_cold();
1001        probe_record(OpClass::Ffn, true, Duration::from_secs(1000));
1002        for _ in 0..PROBE_SAMPLES {
1003            probe_record(OpClass::Ffn, true, Duration::from_millis(1));
1004            probe_record(OpClass::Ffn, false, Duration::from_millis(4));
1005        }
1006        assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
1007
1008        // The reverse: a class where the CPU arm is faster decides CPU.
1009        for _ in 0..PROBE_SAMPLES {
1010            probe_record(OpClass::Matmat, true, Duration::from_millis(4));
1011            probe_record(OpClass::Matmat, false, Duration::from_millis(1));
1012        }
1013        assert!(matches!(probe_arm(OpClass::Matmat), ProbeArm::Cpu));
1014
1015        // cpu_scope: gates off inside, restored after.
1016        cpu_scope(|| CPU_ONLY.with(|c| assert!(c.get())));
1017        CPU_ONLY.with(|c| assert!(!c.get()));
1018        cpu_scope(|| {
1019            cpu_scope(|| CPU_ONLY.with(|c| assert!(c.get())));
1020            CPU_ONLY.with(|c| assert!(c.get()));
1021        });
1022        let _ = std::panic::catch_unwind(|| cpu_scope(|| panic!("scope test")));
1023        CPU_ONLY.with(|c| assert!(!c.get()));
1024        probe_reset();
1025    }
1026
1027    #[test]
1028    fn a_remembered_verdict_is_adopted_and_a_stranger_is_not() {
1029        let _probe_guard = probe_test_guard();
1030        // Probing is not free: on a Snapdragon 778G the deciding classes
1031        // cost minutes of wall clock before the first token, every
1032        // process, and reached the same verdict every time. The cache
1033        // exists so that price is paid once.
1034        //
1035        // The key is built from THIS process's device, never a name this
1036        // test sets: `probe_set_device` is first-writer-wins and on a Mac
1037        // the Metal backend may already have named the silicon before the
1038        // tests run — which is exactly how this test failed on CI while
1039        // passing locally. GemmNt on purpose: the arbitration test never
1040        // touches it, and both run in one process.
1041        let mine = probe_cache_key_named("gemm-nt");
1042        let state = || {
1043            PROBES[OpClass::GemmNt as usize]
1044                .state
1045                .load(Ordering::Relaxed)
1046        };
1047
1048        // Another device's verdict is not mine, whatever it claims.
1049        probe_cache_adopt("SomeOtherGPU/Vulkan\tgemm-nt\tgpu\n");
1050        assert_eq!(state(), 0);
1051        // Neither is one from another build of this engine.
1052        let older = mine.replacen(env!("CARGO_PKG_VERSION"), "0.0.0-old", 1);
1053        assert_ne!(older, mine);
1054        probe_cache_adopt(&format!("{older}\tgpu\n"));
1055        assert_eq!(state(), 0);
1056        // Mine is.
1057        probe_cache_adopt(&format!("{mine}\tcpu\n"));
1058        assert_eq!(state(), 2);
1059
1060        PROBES[OpClass::GemmNt as usize]
1061            .state
1062            .store(0, Ordering::Relaxed);
1063    }
1064}
1065
1066/// Default row threshold: the GPU takes only larger matrices (lm_head
1067/// class). Below it, the dispatch/readback cost does not pay off on unified memory.
1068pub const GPU_MIN_ROWS: usize = 65_536;
1069
1070/// Effective threshold: `CMF_GPU_MIN_ROWS` overrides. Defaults differ
1071/// by device class: on a DISCRETE card VRAM bandwidth pays off even for
1072/// FFN/QKV-class matrices (4096), on unified memory only lm_head-class
1073/// is worth the dispatch/readback (65536). Field case behind this: a
1074/// 35B model on an RTX 4090 saw ~0 offload because every layer matrix
1075/// sat below the old universal 65536.
1076pub fn min_rows() -> usize {
1077    if let Some(v) = std::env::var("CMF_GPU_MIN_ROWS")
1078        .ok()
1079        .and_then(|v| v.parse().ok())
1080    {
1081        return v;
1082    }
1083    if discrete() { 4096 } else { GPU_MIN_ROWS }
1084}
1085
1086/// Is the active backend a discrete card (PCIe VRAM)?
1087pub fn discrete() -> bool {
1088    match backend() {
1089        #[cfg(feature = "gpu")]
1090        Backend::Wgpu => crate::gpu_wgpu::is_discrete(),
1091        #[cfg(target_os = "macos")]
1092        Backend::Metal => false, // UMA by the init() guard
1093        Backend::None => false,
1094        #[cfg(feature = "cuda")]
1095        Backend::Cuda => true,
1096    }
1097}
1098
1099/// A single MoE-FFN job (an expert with its own weight), executed in one
1100/// submission: (rows, cols, idx, row_scale) for gate/up/down + prescaled
1101/// inputs + the down column scale + the blending weight.
1102pub struct MoeJob<'a> {
1103    pub gate: (usize, usize, usize, &'a [f32]),
1104    pub up: (usize, usize, usize, &'a [f32]),
1105    pub down: (usize, usize, usize, &'a [f32]),
1106    pub xs_gate: Vec<f32>,
1107    pub xs_up: Vec<f32>,
1108    pub down_col: &'a [f32],
1109    pub w: f32,
1110    /// q1 trio: scales live inside the 6-byte tiles (row_scale slices
1111    /// empty, xs raw f32). Backends without a q1 kernel refuse the job.
1112    pub q1: bool,
1113    /// q4_tiled trio: scales inside the 18-byte tiles (row_scale
1114    /// slices empty, xs raw f32) — the MoE-hybrid coder class.
1115    pub q4t: bool,
1116    /// q4tp trio: same raw-xs contract, 16-byte nibble stride and the scale
1117    /// on a per-row ladder. Without this the experts of a q4tp MoE model fall
1118    /// to the CPU while every other dtype rides the device.
1119    pub q4tp: bool,
1120    /// Mixed 2-bit profile: gate/up are q2tp (8-byte chunks, zero rung),
1121    /// down stays q4tp. Set together with `q4tp`; a backend without the
1122    /// 2-bit kernel must refuse the whole job.
1123    pub gu_q2: bool,
1124    /// The reference's `swiglu_limit`; 0 disables the clamp. A backend that
1125    /// cannot apply it must REFUSE the job rather than drop it silently —
1126    /// the difference only shows on saturating activations, which is the
1127    /// hardest kind of divergence to notice.
1128    pub swiglu_limit: f32,
1129    /// `GraphAct::code` of act(gate)·up: 0 SiLU, 1 exact GELU, 2 tanh-GELU
1130    /// (a Gemma dense FFN riding the single-job block), or 3 MiniMax M3's
1131    /// frozen SwiGLU-OAI contract. Code 3 is valid only with its exact 7.0
1132    /// `swiglu_limit`; a backend without the complete activation must refuse
1133    /// the job rather than reinterpret it as SiLU.
1134    pub act: u32,
1135}
1136
1137/// A single independent batch matvec (GDN projections of one input).
1138pub struct BatchJob<'a> {
1139    pub idx: usize,
1140    pub rows: usize,
1141    pub cols: usize,
1142    pub row_scale: &'a [f32],
1143    pub xs: Vec<f32>,
1144    /// Weight layout. Was a bare `q1: bool`, which could only ever spell two
1145    /// of the four and silently sent everything else back to the CPU — the
1146    /// GDN projections of a q4t/q4tp model never reached the device at all.
1147    pub layout: BatchLayout,
1148}
1149
1150/// Which kernel a batched matvec needs. q8 carries row scales in a side
1151/// buffer; the rest embed them in the payload and differ in stride.
1152#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1153pub enum BatchLayout {
1154    Q8,
1155    Q1,
1156    /// q1g: sign + scale planes, one scale per 128 (q1's raw-xs contract).
1157    Q1g,
1158    Q4t,
1159    Q4tp,
1160}
1161
1162#[derive(Clone, Copy, PartialEq, Eq)]
1163enum Backend {
1164    None,
1165    #[cfg(target_os = "macos")]
1166    Metal,
1167    #[cfg(feature = "gpu")]
1168    Wgpu,
1169    /// The native CUDA backend (`gpu_cuda`, `CMF_GPU=cuda`).
1170    #[cfg(feature = "cuda")]
1171    Cuda,
1172}
1173
1174/// The selected backend's name for reports: "metal", "wgpu" or "cpu".
1175pub fn backend_name() -> String {
1176    match backend() {
1177        #[cfg(target_os = "macos")]
1178        Backend::Metal => "metal".into(),
1179        #[cfg(feature = "gpu")]
1180        Backend::Wgpu => "wgpu".into(),
1181        Backend::None => "cpu".into(),
1182        #[cfg(feature = "cuda")]
1183        Backend::Cuda => "cuda".into(),
1184    }
1185}
1186
1187fn backend() -> Backend {
1188    // `CMF_GPU=cuda`: the native CUDA backend, or the CPU when it did not
1189    // come up — never wgpu behind the user's back.
1190    #[cfg(feature = "cuda")]
1191    if crate::gpu_cuda::selected() {
1192        return if crate::gpu_cuda::enabled() {
1193            Backend::Cuda
1194        } else {
1195            Backend::None
1196        };
1197    }
1198    // Asked for by name in a build that does not carry it: say so once (the
1199    // run continues on whatever `CMF_GPU=<anything>` selects here).
1200    #[cfg(not(feature = "cuda"))]
1201    {
1202        static SAID: std::sync::Once = std::sync::Once::new();
1203        SAID.call_once(|| {
1204            if std::env::var("CMF_GPU").as_deref() == Ok("cuda") {
1205                tracing::warn!(
1206                    "CMF_GPU=cuda: this build has no CUDA backend (build with `--features cuda`)"
1207                );
1208            }
1209        });
1210    }
1211    #[cfg(feature = "gpu")]
1212    if crate::gpu_wgpu::selected() {
1213        return if crate::gpu_wgpu::enabled() {
1214            Backend::Wgpu
1215        } else {
1216            Backend::None
1217        };
1218    }
1219    #[cfg(target_os = "macos")]
1220    if crate::gpu_metal::enabled() {
1221        return Backend::Metal;
1222    }
1223    Backend::None
1224}
1225
1226/// GPU enabled and initialized on the selected backend?
1227/// Whether THIS build can bring a GPU up on THIS device: a compiled-in
1228/// backend plus a live adapter. The mobile FFI exposes it so an app can
1229/// tell "GPU off" from "GPU impossible" (a CPU-only .so ships no
1230/// backend at all). Cached after the first call.
1231pub fn backend_available() -> bool {
1232    #[cfg(target_os = "macos")]
1233    {
1234        // The Metal path is always compiled on macOS.
1235        true
1236    }
1237    #[cfg(all(feature = "gpu", not(target_os = "macos")))]
1238    {
1239        static AVAIL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1240        *AVAIL.get_or_init(crate::gpu_wgpu::adapter_probe)
1241    }
1242    #[cfg(all(not(feature = "gpu"), not(target_os = "macos")))]
1243    {
1244        false
1245    }
1246}
1247
1248/// A process-wide, phase-scoped GPU gate. `cpu_scope` is thread-local and
1249/// the pool's workers do not inherit it, so a caller that wants a whole
1250/// *phase* off the device — a prompt encoder whose weights live in a part of
1251/// the file the hot loop never touches, on a machine that cannot keep both
1252/// wired — has to say so globally.
1253static GPU_PAUSED: PauseGate = PauseGate::new();
1254
1255/// The pause as a count of live guards, not a flag: with a flag, the first
1256/// guard to drop lifted every other holder's pause too — two overlapping
1257/// phases, or two tests of one binary (a bit-exact CPU reference whose
1258/// neighbour's guard drops mid-forward), put the device back early.
1259struct PauseGate(std::sync::atomic::AtomicUsize);
1260
1261impl PauseGate {
1262    const fn new() -> Self {
1263        Self(std::sync::atomic::AtomicUsize::new(0))
1264    }
1265
1266    fn enter(&self) {
1267        self.0.fetch_add(1, Ordering::Relaxed);
1268    }
1269
1270    fn leave(&self) {
1271        self.0.fetch_sub(1, Ordering::Relaxed);
1272    }
1273
1274    fn paused(&self) -> bool {
1275        self.0.load(Ordering::Relaxed) != 0
1276    }
1277}
1278
1279/// Park the device for every thread until the returned guard drops (and
1280/// every other live guard with it).
1281pub fn pause_gpu() -> GpuPause {
1282    GPU_PAUSED.enter();
1283    GpuPause(())
1284}
1285
1286pub struct GpuPause(());
1287
1288impl Drop for GpuPause {
1289    fn drop(&mut self) {
1290        GPU_PAUSED.leave();
1291    }
1292}
1293
1294pub fn enabled() -> bool {
1295    !GPU_LOST.load(std::sync::atomic::Ordering::Relaxed) && !GPU_PAUSED.paused() && backend() != Backend::None
1296}
1297
1298/// Set once a frame found the device gone: every later op of the process runs
1299/// on the host instead of building buffers on a dead device (Edge0 on an A40:
1300/// after the device was lost the host fallback's first upload panicked inside
1301/// wgpu, the other threads on its poisoned lock, and the process hung).
1302static GPU_LOST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1303
1304/// The device is lost (`why`: what found it): the GPU path is off for good.
1305pub fn mark_lost(why: &str) {
1306    if !GPU_LOST.swap(true, std::sync::atomic::Ordering::Relaxed) {
1307        tracing::error!("GPU device lost ({why}): the rest of this run stays on the CPU");
1308    }
1309}
1310
1311#[cfg(test)]
1312mod pause_gate_tests {
1313    use super::PauseGate;
1314
1315    /// Overlapping holders: the pause lasts until the last one leaves (a
1316    /// local gate, so the process-wide one other tests see is untouched).
1317    #[test]
1318    fn pause_holds_until_the_last_guard() {
1319        let g = PauseGate::new();
1320        assert!(!g.paused());
1321        g.enter();
1322        g.enter();
1323        g.leave();
1324        assert!(g.paused(), "one holder left, the other's pause was lifted");
1325        g.leave();
1326        assert!(!g.paused());
1327    }
1328}
1329
1330/// Default-on condition for the wgpu whole-token graph: the wgpu
1331/// backend on a DISCRETE adapter. NOT plain `enabled()` (macOS/Metal
1332/// must not pay a per-token layer scan for a graph its backend
1333/// refuses), and NOT integrated adapters: the graph's ~300 barriered
1334/// dispatches per token are cheap on desktop immediate-mode GPUs but
1335/// tiled mobile GPUs (Adreno/Mali) drain the pipeline at every barrier
1336/// — field report: 0.2 tok/s on-graph vs 15 tok/s on the CPU. On
1337/// integrated adapters the per-op probe path arbitrates each op class
1338/// against the CPU instead; CMF_GPU_WGPU_GRAPH=1 still forces the
1339/// graph anywhere.
1340/// Is the wgpu backend active at all (any adapter)? Eligibility gate
1341/// for the whole-token graph — whether it actually RUNS is decided by
1342/// `wgpu_graph_default` (trusted on discrete) or the generation race.
1343pub fn wgpu_active() -> bool {
1344    #[cfg(feature = "gpu")]
1345    {
1346        matches!(backend(), Backend::Wgpu)
1347    }
1348    #[cfg(not(feature = "gpu"))]
1349    {
1350        false
1351    }
1352}
1353
1354/// Which GPU this thread's engine calls address. Multi-card hosts hold
1355/// one wgpu context PER card (weights, KV mirrors and scratch live
1356/// inside a context, so per-device contexts give per-device caches for
1357/// free); this thread-local says which one is current. Default: the
1358/// process pin (CMF_GPU_ADAPTER) or 0 — so single-card runs behave
1359/// exactly as they always have.
1360pub fn default_device() -> usize {
1361    static D: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1362    *D.get_or_init(|| {
1363        std::env::var("CMF_GPU_ADAPTER")
1364            .ok()
1365            .and_then(|v| v.trim().parse::<usize>().ok())
1366            .unwrap_or(0)
1367    })
1368}
1369
1370thread_local! {
1371    static CUR_DEV: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
1372}
1373
1374/// The device this thread is pinned to.
1375pub fn current_device() -> usize {
1376    CUR_DEV.with(|c| c.get()).unwrap_or_else(default_device)
1377}
1378
1379/// Pin this thread to a device. Server slots call it once per request;
1380/// the worker pool propagates it into its threads, so a dispatch begun
1381/// on card 1 does not finish on card 0.
1382pub fn set_current_device(i: usize) {
1383    CUR_DEV.with(|c| c.set(Some(i)));
1384}
1385
1386/// Run `f` with this thread pinned to `dev`, restoring the previous pin.
1387pub fn with_device<R>(dev: usize, f: impl FnOnce() -> R) -> R {
1388    let prev = CUR_DEV.with(|c| c.replace(Some(dev)));
1389    let r = f();
1390    CUR_DEV.with(|c| c.set(prev));
1391    r
1392}
1393
1394/// How many GPUs this process can address (wgpu adapter count; 1 on
1395/// Metal, 0 without a backend).
1396pub fn device_count() -> usize {
1397    #[cfg(all(feature = "gpu", not(target_os = "macos")))]
1398    {
1399        return crate::gpu_wgpu::adapter_count();
1400    }
1401    #[cfg(not(all(feature = "gpu", not(target_os = "macos"))))]
1402    {
1403        usize::from(backend_available())
1404    }
1405}
1406
1407/// Weight budget of the current GPU in bytes; 0 when there is none and
1408/// u64::MAX on unified memory (where the OS pages shared RAM and the
1409/// question "does the model fit the card" has no separate answer).
1410pub fn vram_budget() -> u64 {
1411    #[cfg(feature = "cuda")]
1412    if backend() == Backend::Cuda {
1413        return crate::gpu_cuda::vram_budget();
1414    }
1415    #[cfg(all(feature = "gpu", not(target_os = "macos")))]
1416    {
1417        return crate::gpu_wgpu::device_vram_budget();
1418    }
1419    // Apple silicon: wgpu's own budget while it runs (its share of the
1420    // shared memory, `uma_budget`); the native Metal path keeps none
1421    #[cfg(all(feature = "gpu", target_os = "macos"))]
1422    if backend() == Backend::Wgpu {
1423        return crate::gpu_wgpu::device_vram_budget();
1424    }
1425    #[cfg(not(all(feature = "gpu", not(target_os = "macos"))))]
1426    {
1427        if backend_available() { u64::MAX } else { 0 }
1428    }
1429}
1430
1431/// The card the selected GPU backend runs on, for status reports: "<name> /
1432/// CUDA" or "<name> / Vulkan" (DX12, …); None on the CPU and on Apple's Metal
1433/// path. Brings the backend up when it is selected and not up yet, as the
1434/// first request would.
1435pub fn active_device() -> Option<String> {
1436    match backend() {
1437        #[cfg(feature = "cuda")]
1438        Backend::Cuda => crate::gpu_cuda::device_name().map(|n| format!("{n} / CUDA")),
1439        #[cfg(feature = "gpu")]
1440        Backend::Wgpu => crate::gpu_wgpu::device_label(),
1441        _ => None,
1442    }
1443}
1444
1445/// Memory in use on the active card for status reports: the allocator's
1446/// blocks on wgpu, the driver's count on CUDA; None on the CPU and Metal.
1447pub fn device_bytes_in_use() -> Option<u64> {
1448    match backend() {
1449        #[cfg(feature = "cuda")]
1450        Backend::Cuda => crate::gpu_cuda::device_bytes_in_use(),
1451        #[cfg(feature = "gpu")]
1452        Backend::Wgpu => crate::gpu_wgpu::device_bytes_in_use(),
1453        _ => None,
1454    }
1455}
1456
1457/// Bytes currently accounted as resident weight buffers on the active wgpu
1458/// adapter.  This is the logical device-local weight set; physical driver
1459/// allocations are reported separately by the platform tools.
1460pub fn resident_bytes() -> u64 {
1461    #[cfg(feature = "cuda")]
1462    if backend() == Backend::Cuda {
1463        return crate::gpu_cuda::resident_bytes();
1464    }
1465    #[cfg(feature = "gpu")]
1466    {
1467        if backend() == Backend::Wgpu {
1468            return crate::gpu_wgpu::resident_bytes();
1469        }
1470    }
1471    0
1472}
1473
1474/// Sealed O(1) device mirror count and logical bytes for one pipeline id.
1475/// Zero is returned when wgpu is unavailable or the sequence has not reached
1476/// an O(1) seal yet.
1477pub fn o1_device_stats(kv_id: u64) -> (usize, u64) {
1478    #[cfg(feature = "gpu")]
1479    {
1480        if backend() == Backend::Wgpu {
1481            return crate::gpu_wgpu::o1_device_stats(kv_id);
1482        }
1483        #[cfg(feature = "cuda")]
1484        if backend() == Backend::Cuda {
1485            return crate::gpu_cuda::o1_device_stats(kv_id);
1486        }
1487    }
1488    let _ = kv_id;
1489    (0, 0)
1490}
1491
1492/// Device weight bytes uploaded so far (wgpu; 0 on other backends).
1493/// Steady-state windows must show a ZERO delta — growth mid-benchmark
1494/// means eviction/re-upload and disqualifies the number.
1495pub fn upload_bytes() -> u64 {
1496    #[cfg(feature = "gpu")]
1497    {
1498        return crate::gpu_wgpu::UPLOAD_BYTES.load(std::sync::atomic::Ordering::Relaxed);
1499    }
1500    #[cfg(not(feature = "gpu"))]
1501    0
1502}
1503
1504/// Measure a transient host-to-device upload when the wgpu backend is
1505/// compiled in. CPU-only builds keep the benchmark command available and
1506/// report no device measurement instead of referring to the gated module.
1507pub fn upload_bandwidth_probe(block: usize, rounds: usize) -> Option<f64> {
1508    #[cfg(feature = "gpu")]
1509    {
1510        return crate::gpu_wgpu::upload_bandwidth_probe(block, rounds);
1511    }
1512    let _ = (block, rounds);
1513    None
1514}
1515
1516/// Which half of the run is asking.
1517///
1518/// The phase exists because the graph is plausibly two decisions, not
1519/// one — but on the hardware measured so far it is only ever a decode
1520/// decision. On an Adreno 642L with bonsai-1.7b, from identical clean
1521/// starts and two repeats each: decode 11.6 tok/s without it and 0.72
1522/// with, while prefill is 4.2 either way. A first reading of 3.4 -> 18.0
1523/// for prefill did not survive a controlled re-run — it was a dirty
1524/// probe cache between configurations, not the graph, and the prefill
1525/// route through the graph is GDN-only in the first place, which this
1526/// dense model never takes.
1527#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1528pub enum GraphPhase {
1529    Prefill,
1530    Decode,
1531}
1532
1533/// The one place that decides whether the whole-token graph runs.
1534///
1535/// `CMF_GPU_WGPU_GRAPH`: `0` off everywhere, `prefill` only for the
1536/// prompt, anything else on everywhere. Unset: desktop-class GPUs take
1537/// it for both phases; phone-class UMA takes it for PREFILL only, which
1538/// is the measurement above rather than a guess — the per-op path keeps
1539/// decode, where it is seventeen times better.
1540pub fn wgpu_graph_on(phase: GraphPhase) -> bool {
1541    match std::env::var("CMF_GPU_WGPU_GRAPH").ok().as_deref() {
1542        Some("0") => false,
1543        Some("prefill") => phase == GraphPhase::Prefill,
1544        Some(_) => true,
1545        None => {
1546            if wgpu_graph_default() {
1547                return true;
1548            }
1549            // Integrated/mobile keeps the per-op path for BOTH phases —
1550            // unchanged, because the measurement that would have bought
1551            // prefill a graph did not reproduce. `=prefill` is there for
1552            // the device where it does; the default does not guess.
1553            let _ = phase;
1554            false
1555        }
1556    }
1557}
1558
1559/// The batched prefill's whole-run attend is tiled on this device (see
1560/// `gpu_wgpu::batched_attend_tiled`); false without the wgpu feature.
1561pub fn batched_attend_tiled() -> bool {
1562    // The CUDA batch graph attends a whole chunk with two GEMMs a head.
1563    #[cfg(feature = "cuda")]
1564    if backend() == Backend::Cuda {
1565        return true;
1566    }
1567    #[cfg(feature = "gpu")]
1568    {
1569        crate::gpu_wgpu::batched_attend_tiled()
1570    }
1571    #[cfg(not(feature = "gpu"))]
1572    {
1573        false
1574    }
1575}
1576
1577/// Prompt rows per batched-graph chunk when the CUDA backend runs the
1578/// graphs (`CMF_CUDA_BATCH`), None on every other backend.
1579pub fn cuda_batch_rows() -> Option<usize> {
1580    #[cfg(feature = "cuda")]
1581    if backend() == Backend::Cuda {
1582        return Some(crate::gpu_cuda::batch_rows());
1583    }
1584    None
1585}
1586
1587/// The CUDA backend is the one in use.
1588/// CUDA: whether a narrow product of tensor `idx` may take the dense plane
1589/// without evicting another (see `gpu_cuda::h3_plane_fits`).
1590#[allow(unused_variables)]
1591pub fn cuda_plane_fits(model: &Arc<CmfModel>, idx: usize) -> bool {
1592    #[cfg(feature = "cuda")]
1593    {
1594        crate::gpu_cuda::h3_plane_fits(model, idx)
1595    }
1596    #[cfg(not(feature = "cuda"))]
1597    {
1598        false
1599    }
1600}
1601
1602/// CUDA: a pipeline that has the card to itself lets the per-op plane cache
1603/// grow into free memory (see `gpu_cuda::h3_planes_grow`). A no-op elsewhere.
1604#[allow(unused_variables)]
1605pub fn planes_may_grow(on: bool) {
1606    #[cfg(feature = "cuda")]
1607    crate::gpu_cuda::h3_planes_grow(on);
1608}
1609
1610/// Hy4-flash SFq calibration capture on the CUDA hybrid (see
1611/// `gpu_cuda::hy4_capture_begin`); false without a CUDA backend.
1612pub fn hy4_capture_begin(layers: usize, dim: usize, ne: usize) -> bool {
1613    #[cfg(feature = "cuda")]
1614    if backend() == Backend::Cuda {
1615        return crate::gpu_cuda::hy4_capture_begin(layers, dim, ne);
1616    }
1617    let _ = (layers, dim, ne);
1618    false
1619}
1620
1621/// The rows the capture took (and the capture disarmed).
1622pub fn hy4_capture_take() -> Option<Vec<(Vec<f32>, Vec<f32>)>> {
1623    #[cfg(feature = "cuda")]
1624    if backend() == Backend::Cuda {
1625        return crate::gpu_cuda::hy4_capture_take();
1626    }
1627    None
1628}
1629
1630/// The Metal backend is the selected one.
1631pub fn metal_active() -> bool {
1632    #[cfg(target_os = "macos")]
1633    {
1634        backend() == Backend::Metal
1635    }
1636    #[cfg(not(target_os = "macos"))]
1637    {
1638        false
1639    }
1640}
1641
1642pub fn cuda_active() -> bool {
1643    #[cfg(feature = "cuda")]
1644    {
1645        backend() == Backend::Cuda
1646    }
1647    #[cfg(not(feature = "cuda"))]
1648    {
1649        false
1650    }
1651}
1652
1653pub fn wgpu_graph_default() -> bool {
1654    // The CUDA backend serves the same two graph contracts (token, batch).
1655    #[cfg(feature = "cuda")]
1656    if backend() == Backend::Cuda {
1657        return true;
1658    }
1659    #[cfg(feature = "gpu")]
1660    {
1661        // Discrete cards always; Apple-silicon UMA on macOS too — desktop
1662        // -class GPUs where the graph measured ~2x the CPU on the Qwen3.6
1663        // family (M4: 13.3 tok/s against 7.3). Phone-class UMA (Android/
1664        // iOS builds) keeps the per-op probe path: tiled mobile GPUs have
1665        // turned the ~300-dispatch graph into seconds per token.
1666        matches!(backend(), Backend::Wgpu)
1667            && (crate::gpu_wgpu::discrete_active()
1668                || (cfg!(target_os = "macos") && crate::gpu_wgpu::adapter_up()))
1669    }
1670    #[cfg(not(feature = "gpu"))]
1671    {
1672        false
1673    }
1674}
1675
1676/// q8_row/q8_2f matvec, rows [row0, row0+rows). `xs` — prescaled by the column scale.
1677#[allow(clippy::too_many_arguments, unused_variables)]
1678pub fn q8_matvec_range(
1679    model: &Arc<CmfModel>,
1680    idx: usize,
1681    row0: usize,
1682    row_scale: &[f32],
1683    xs: &[f32],
1684    rows: usize,
1685    cols: usize,
1686    out: &mut [f32],
1687) -> bool {
1688    match backend() {
1689        #[cfg(target_os = "macos")]
1690        Backend::Metal => {
1691            crate::gpu_metal::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
1692        }
1693        #[cfg(feature = "gpu")]
1694        Backend::Wgpu => {
1695            crate::gpu_wgpu::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
1696        }
1697        Backend::None => false,
1698        #[cfg(feature = "cuda")]
1699        Backend::Cuda => false,
1700    }
1701}
1702
1703/// Decode-exact short q8_2f panel for the banked MiMo head.
1704pub(crate) fn q82_short_rows(
1705    model: &Arc<CmfModel>,
1706    idx: usize,
1707    xs: &[f32],
1708    b: usize,
1709    rows: usize,
1710    cols: usize,
1711    out: &mut [f32],
1712) -> bool {
1713    #[cfg(feature = "gpu")]
1714    if enabled_here() && backend() == Backend::Wgpu {
1715        return crate::gpu_wgpu::q82_short_rows(model, idx, xs, b, rows, cols, out);
1716    }
1717    let _ = (model, idx, xs, b, rows, cols, out);
1718    false
1719}
1720
1721/// GEMM of a prefill batch: `pre` — prescaled inputs row-major [b, cols],
1722/// out — row-major [b, rows].
1723#[allow(clippy::too_many_arguments, unused_variables)]
1724/// The two-field int8 GEMM with the column field left for the device.
1725/// wgpu only — Metal's int8 kernel takes a pre-scaled activation, so the
1726/// caller keeps that path when this returns `false`.
1727#[allow(clippy::too_many_arguments)]
1728pub fn q8_matmat_2f(
1729    model: &Arc<CmfModel>,
1730    idx: usize,
1731    row_scale: &[f32],
1732    col_field: &[f32],
1733    xs: &[f32],
1734    b: usize,
1735    rows: usize,
1736    cols: usize,
1737    out: &mut [f32],
1738) -> bool {
1739    #[allow(unreachable_patterns)]
1740    match backend() {
1741        #[cfg(feature = "gpu")]
1742        Backend::Wgpu => {
1743            crate::gpu_wgpu::q8_matmat_2f(model, idx, row_scale, col_field, xs, b, rows, cols, out)
1744        }
1745        // the codec's dense plane on the card (cached while it fits), TF32
1746        #[cfg(feature = "cuda")]
1747        Backend::Cuda => crate::gpu_cuda::h3_matmat(model, idx, xs, b, rows, cols, out),
1748        _ => false,
1749    }
1750}
1751
1752pub fn q8_matmat(
1753    model: &Arc<CmfModel>,
1754    idx: usize,
1755    row_scale: &[f32],
1756    pre: &[f32],
1757    b: usize,
1758    rows: usize,
1759    cols: usize,
1760    out: &mut [f32],
1761) -> bool {
1762    match backend() {
1763        #[cfg(target_os = "macos")]
1764        Backend::Metal => {
1765            crate::gpu_metal::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out)
1766        }
1767        #[cfg(feature = "gpu")]
1768        Backend::Wgpu => crate::gpu_wgpu::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out),
1769        Backend::None => false,
1770        #[cfg(feature = "cuda")]
1771        Backend::Cuda => false,
1772    }
1773}
1774
1775/// q1 matvec: raw f32 activations, tile-embedded scales. Metal only
1776/// for now (wgpu q1 WGSL is queued); false = CPU fallback.
1777#[allow(unused_variables)]
1778pub fn q1_matvec(
1779    model: &Arc<CmfModel>,
1780    idx: usize,
1781    xs: &[f32],
1782    rows: usize,
1783    cols: usize,
1784    out: &mut [f32],
1785) -> bool {
1786    match backend() {
1787        #[cfg(target_os = "macos")]
1788        Backend::Metal => crate::gpu_metal::q1_matvec(model, idx, xs, rows, cols, out),
1789        #[cfg(feature = "gpu")]
1790        Backend::Wgpu => crate::gpu_wgpu::q1_matvec(model, idx, xs, rows, cols, out),
1791        Backend::None => false,
1792        #[cfg(feature = "cuda")]
1793        Backend::Cuda => false,
1794    }
1795}
1796
1797/// q1g matvec (sign + scale planes, raw f32 activations); the q1 kernel's
1798/// walk and sums, so a uniform-scale repack matches `q1_matvec` bit for
1799/// bit. false = CPU fallback.
1800#[allow(unused_variables)]
1801pub fn q1g_matvec(
1802    model: &Arc<CmfModel>,
1803    idx: usize,
1804    xs: &[f32],
1805    rows: usize,
1806    cols: usize,
1807    out: &mut [f32],
1808) -> bool {
1809    match backend() {
1810        #[cfg(target_os = "macos")]
1811        Backend::Metal => crate::gpu_metal::q1g_matvec(model, idx, xs, rows, cols, out),
1812        #[cfg(feature = "gpu")]
1813        Backend::Wgpu => crate::gpu_wgpu::q1g_matvec(model, idx, xs, rows, cols, out),
1814        Backend::None => false,
1815        #[cfg(feature = "cuda")]
1816        Backend::Cuda => false,
1817    }
1818}
1819
1820/// Whole attention sub-block on the wgpu token graph (drop-in for
1821/// `qwen_attention`): normed hidden in, O-projection out, resident device
1822/// K/V mirror. false = refusal / not the wgpu backend → CPU path.
1823#[allow(clippy::too_many_arguments)]
1824pub fn attn_dropin(
1825    model: &Arc<CmfModel>,
1826    kv_id: u64,
1827    layer: usize,
1828    normed: &[f32],
1829    wq_idx: usize,
1830    wk_idx: usize,
1831    wv_idx: usize,
1832    wo_idx: usize,
1833    q_norm: Option<&[f32]>,
1834    k_norm: Option<&[f32]>,
1835    late_qk_norm: bool,
1836    invf: &[f32],
1837    nh: usize,
1838    nkv: usize,
1839    hd: usize,
1840    rd: usize,
1841    hidden: usize,
1842    pos: usize,
1843    cap: usize,
1844    gemma: bool,
1845    eps: f32,
1846    cpu_k: &[Vec<f32>],
1847    cpu_v: &[Vec<f32>],
1848    out: &mut [f32],
1849) -> bool {
1850    match backend() {
1851        #[cfg(feature = "gpu")]
1852        Backend::Wgpu => crate::gpu_wgpu::attn_dropin_gpu(
1853            model, kv_id, layer, normed, wq_idx, wk_idx, wv_idx, wo_idx, q_norm, k_norm,
1854            late_qk_norm, invf, nh, nkv, hd, rd, hidden, pos, cap, gemma, eps, cpu_k, cpu_v, out,
1855        ),
1856        #[allow(unused_variables)]
1857        _ => false,
1858    }
1859}
1860
1861/// Descriptor operation attached to a graph weight.  `None` is the default
1862/// for ordinary CMF files; Prism weights are admitted only when the token
1863/// graph carries this explicit transform contract.
1864#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1865pub enum GraphPrismOp {
1866    None,
1867    Forward,
1868    InverseEmbedding,
1869}
1870
1871/// Graph kind of a binary low-rank (`blr`, dtype 19) weight: two stage
1872/// dispatches (V, U) over the resident payload instead of one matvec. Only
1873/// the wgpu token graph builder asks for it (`QTensor::graph_weight_or_blr`).
1874pub const GRAPH_KIND_BLR: u8 = 11;
1875
1876/// One weight in the whole-token graph: tensor idx + a codec tag (0=q8_row,
1877/// 1=q1, 2=q4_tiled, 3=q1t, 4=f32, … 11=blr) + per-row scales (q8_row only) + the raw f32
1878/// data (kind 4 only — small unquantized projections like GDN in_proj_a/b).
1879pub struct GraphW<'a> {
1880    pub idx: usize,
1881    pub kind: u8,
1882    pub row_scale: &'a [f32],
1883    pub data: &'a [f32],
1884    pub prism: GraphPrismOp,
1885    pub affine: bool,
1886}
1887
1888/// A layer's token-mixing op: standard attention or a GDN (linear-attention)
1889/// block. The surrounding norms + SwiGLU FFN are common to both.
1890pub enum GraphAttn<'a> {
1891    Full {
1892        wq: GraphW<'a>,
1893        wk: GraphW<'a>,
1894        wv: GraphW<'a>,
1895        wo: GraphW<'a>,
1896        q_norm: Option<&'a [f32]>,
1897        k_norm: Option<&'a [f32]>,
1898        /// HunYuan dense: q/k norm after RoPE (rope-kernel flag bit 32).
1899        late_qk_norm: bool,
1900        /// (bq, bk, bv) attention biases (Qwen2). None ⇒ no bias.
1901        bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
1902        /// Qwen3.5 gated attention: wq emits 2·nh·hd (q||gate per head), the
1903        /// attention output is scaled by sigmoid(gate) before the O projection.
1904        output_gate: bool,
1905        cpu_k: &'a [Vec<f32>],
1906        cpu_v: &'a [Vec<f32>],
1907        /// Absolute position of `cpu_k`/`cpu_v` row 0
1908        /// (`LayerKvCache::base`): a sliding layer that keeps only its
1909        /// tail stores rows from there on. 0 for every untrimmed layer.
1910        cpu_base: usize,
1911        /// This layer's own attention geometry, when the model's layers do
1912        /// not share one (MiMo-V2: 4/8 KV heads, 128-wide V under 192-wide
1913        /// heads, sliding windows with learned sinks, two RoPE tables).
1914        /// None = the call-wide (nkv, hd, rd, invf), V as wide as K, full
1915        /// context and a plain softmax — the historical contract, whose
1916        /// kernels and dispatch are untouched.
1917        geom: Option<GraphAttnGeom<'a>>,
1918        /// Spark-X2.5 head-wise output gate: `self_attn.g_proj`
1919        /// `[num_heads, hidden]` against the attention's normed input; head
1920        /// h's output is scaled by sigmoid(g[h]) before the O projection.
1921        /// None = no such gate (every other model).
1922        head_gate: Option<GraphW<'a>>,
1923    },
1924    Gdn {
1925        qkv: GraphW<'a>,
1926        z: GraphW<'a>,
1927        a: GraphW<'a>,
1928        b: GraphW<'a>,
1929        out: GraphW<'a>,
1930        conv1d: &'a [f32],
1931        a_log: &'a [f32],
1932        dt_bias: &'a [f32],
1933        norm: &'a [f32],
1934        nv: usize,
1935        nk: usize,
1936        dk: usize,
1937        dv: usize,
1938        kk: usize,
1939        /// CPU recurrent state `[ring (kk-1)·cdim | S nv·dk·dv]` — seeds the
1940        /// device mirror when prefill ran on the host (o1 collection, CPU
1941        /// fallback): a zero-initialized device state at decode is exactly
1942        /// the "coherent but contextless" garble.
1943        cpu_state: &'a [f32],
1944        /// Block-diffusion preview weights (Clover); `None` on every
1945        /// causal model. Read only under `enter_block_preview`.
1946        preview: Option<GdnPreviewW<'a>>,
1947    },
1948    /// LFM2 gated short convolution: a fused (B, C, x) projection, a
1949    /// depthwise causal conv over a (kernel−1)-deep per-channel ring,
1950    /// C-gating, and an output projection. This mixer is what most of an
1951    /// LFM2 stack is (22 of the 2.6B's 30 layers), and before it had a
1952    /// graph arm the whole model fell to the per-op path — ~100 submits
1953    /// a token, 22 tok/s on an A100 for a 1.4 GB file.
1954    ShortConv {
1955        /// [3·hidden, hidden] fused input projection.
1956        inp: GraphW<'a>,
1957        /// [hidden, hidden] output projection.
1958        out: GraphW<'a>,
1959        /// [hidden · kernel] depthwise taps, `[channel][tap]`, tap
1960        /// kernel−1 multiplying the current position.
1961        taps: &'a [f32],
1962        kernel: usize,
1963        /// CPU conv ring `[channel][kernel−1]`, slot 0 newest — seeds
1964        /// the device mirror when prefill ran on the host, which for
1965        /// this mixer is always (the batch graph declines it).
1966        cpu_state: &'a [f32],
1967    },
1968    /// Kimi Delta Attention (Kimi-Linear): the delta rule with a decay per
1969    /// key channel, separate q / k / v short convolutions over one ring, a
1970    /// low-rank decay projection and a sigmoid-gated output norm
1971    /// (`linear_core::kda_step` has the semantics).
1972    Kda {
1973        q: GraphW<'a>,
1974        k: GraphW<'a>,
1975        v: GraphW<'a>,
1976        /// Depthwise taps `[channel][kk]` of the q, k and v convs (one ring
1977        /// of their channels on the device).
1978        conv_q: &'a [f32],
1979        conv_k: &'a [f32],
1980        conv_v: &'a [f32],
1981        /// Low-rank decay `f = f_b · (f_a · x)`: `[rank, hidden]`, `[nh·dk, rank]`.
1982        f_a: GraphW<'a>,
1983        f_b: GraphW<'a>,
1984        dt_bias: &'a [f32],
1985        /// `[nh]`, `[dk]` or `[nh·dk]` (broadcast by length).
1986        a_log: &'a [f32],
1987        /// `[nh, hidden]`: β = σ(b · x).
1988        b: GraphW<'a>,
1989        /// The output gate `g_b · (g_a · x)` (`g_b` None: `g_a` is full rank).
1990        g_a: GraphW<'a>,
1991        g_b: Option<GraphW<'a>>,
1992        /// `[dv]`, the per-head gated RMS norm.
1993        o_norm: &'a [f32],
1994        out: GraphW<'a>,
1995        nh: usize,
1996        dk: usize,
1997        dv: usize,
1998        kk: usize,
1999        /// Some(lb): log-decay = lb·σ(exp(A)·(f + bias)); None: −exp(A)·softplus(f + bias).
2000        lower_bound: Option<f32>,
2001        /// CPU state `[q ring | k ring | v ring | S]` (`KdaCfg::state_len`).
2002        cpu_state: &'a [f32],
2003    },
2004    /// DeepSeek-V2 Multi-head Latent Attention as multi-head attention
2005    /// (`pipeline::mla_attention`): q (through its low-rank stage), the
2006    /// latent and its norm, the per-head `[k_rope | k_nope]` keys and the
2007    /// values; the attention itself is `Full`'s with heads `rope + nope`
2008    /// wide and V `v_dim` wide.
2009    Mla {
2010        q_a: Option<GraphW<'a>>,
2011        q_a_norm: Option<&'a [f32]>,
2012        q: GraphW<'a>,
2013        /// `[lora + rope, hidden]`, the latent first.
2014        kv_a: GraphW<'a>,
2015        kv_a_norm: &'a [f32],
2016        /// `[nh·(nope + v), lora]`, per head `[k_nope | v]`.
2017        kv_b: GraphW<'a>,
2018        o: GraphW<'a>,
2019        nh: usize,
2020        rope: usize,
2021        nope: usize,
2022        v_dim: usize,
2023        lora: usize,
2024        scale: f32,
2025        /// Kimi-Linear: no rotation at all.
2026        no_rope: bool,
2027        cpu_k: &'a [Vec<f32>],
2028        cpu_v: &'a [Vec<f32>],
2029        cpu_base: usize,
2030        /// GLM-5.3's DSA: past `topk` positions the layer attends only to
2031        /// the positions its indexer selects (None: every position).
2032        dsa: Option<GraphDsa<'a>>,
2033        /// Hy4-flash's gated MLA: the layer's own rotary table, window,
2034        /// sinks, element-wise output gate and compressed indexer. None =
2035        /// the GLM / Kimi / DeepSeek form; a backend without the arm must
2036        /// decline a layer that carries it.
2037        hy: Option<GraphMlaHy<'a>>,
2038    },
2039}
2040
2041/// Hy4-flash's additions to MLA (`hy4::Attn`): heads `[rope | nope]` with
2042/// the rotary pairs half-split, rotated by `invf` (`rope / 2` frequencies);
2043/// a sliding window (positions a query sees, its own included) or, on the
2044/// sparse layers, the compressed indexer past `group_topk · ratio`
2045/// positions; one learned sink logit a head; the attention output scaled by
2046/// `sigmoid(gate · x)` element-wise before the O projection.
2047pub struct GraphMlaHy<'a> {
2048    /// `[nh·v, hidden]` over the layer's normed input.
2049    pub gate: GraphW<'a>,
2050    pub sinks: &'a [f32],
2051    pub window: Option<usize>,
2052    pub invf: &'a [f32],
2053    pub indexer: Option<GraphHyIndexer<'a>>,
2054}
2055
2056/// Hy4-flash's compressed indexer (`hy4::select_groups` / `pool_group`): the
2057/// index query over q_a's normed rows, the head weights and the token key
2058/// over the layer input, the token key's norm, the pooling's value and gate
2059/// projections over the token keys, the pooled key's norm, the groups'
2060/// position embedding; rotary on the last `rope` channels of each `id`-wide
2061/// head (index query at its position, a group's key at its first).
2062pub struct GraphHyIndexer<'a> {
2063    /// `[ih·id, q_rank]`.
2064    pub q: GraphW<'a>,
2065    /// `[ih, hidden]`, `[id, hidden]` f32.
2066    pub hw: &'a [f32],
2067    pub tk: &'a [f32],
2068    pub tk_norm: &'a [f32],
2069    /// `[id, id]` f32.
2070    pub kv: &'a [f32],
2071    pub kg: &'a [f32],
2072    pub k_norm: &'a [f32],
2073    /// `[ratio, id]`.
2074    pub ape: &'a [f32],
2075    pub ih: usize,
2076    pub id: usize,
2077    pub ratio: usize,
2078    pub group_topk: usize,
2079    /// kv_b `[nh·(nope + v), lora]` in f32, for the absorbed attention.
2080    pub kv_b: &'a [f32],
2081}
2082
2083/// A DSA layer's indexer (GLM-5.3, `glm5_next::dsa_forward`): the index
2084/// query over the normed low-rank query, the index key, pool gate and head
2085/// weights over the layer input, the key's LayerNorm, the pools' position
2086/// embedding, kv_b in f32 for the absorbed attention, and the geometry. The
2087/// incomplete tail is always selected.
2088pub struct GraphDsa<'a> {
2089    /// `[ih·id, q_rank]`.
2090    pub index_q: GraphW<'a>,
2091    /// `[id, hidden]`.
2092    pub index_k: GraphW<'a>,
2093    /// `[id, hidden]`.
2094    pub pool_gate: GraphW<'a>,
2095    /// `[ih, hidden]`.
2096    pub index_weights: GraphW<'a>,
2097    pub k_norm: &'a [f32],
2098    pub k_bias: &'a [f32],
2099    /// `[kpool, id]`.
2100    pub ape: &'a [f32],
2101    /// kv_b `[nh·(nope + v), lora]` in f32.
2102    pub kv_b: &'a [f32],
2103    pub ih: usize,
2104    pub id: usize,
2105    pub topk: usize,
2106    pub kpool: usize,
2107}
2108
2109/// Per-layer attention geometry for the wgpu graphs (see
2110/// `GraphAttn::Full::geom`). The layer's CPU cache keeps K rows `hd` wide
2111/// and V rows zero-padded to `hd`; the device mirror stores V `dv` wide,
2112/// and a windowed layer keeps a ring of the last positions only.
2113#[derive(Clone, Copy)]
2114pub struct GraphAttnGeom<'a> {
2115    /// KV heads of this layer (divides the Q heads).
2116    pub nkv: usize,
2117    /// Q/K head width of this layer. The call-wide `hd` for every model
2118    /// but Gemma-4, whose global layers are 512 wide over 256-wide sliding
2119    /// ones (`<= 512`, a multiple of 4).
2120    pub hd: usize,
2121    /// V head width, `4 <= dv <= hd`, a multiple of 4.
2122    pub dv: usize,
2123    /// Rotary width of this layer (NeoX half-split over `[0, rd)`).
2124    pub rd: usize,
2125    /// This layer's RoPE inverse frequencies (`rd / 2` of them).
2126    pub invf: &'a [f32],
2127    /// YaRN attention-amplitude factor applied after the rotary pair
2128    /// transform. `1.0` is ordinary RoPE; Mellum's global layers use
2129    /// `1.277258872…`. This is deliberately per-layer: local and global
2130    /// layers may have different RoPE tables and factors.
2131    pub rope_scale: f32,
2132    /// Positions a query sees, its own included (MiMo-V2 SWA: 128);
2133    /// None = the whole context.
2134    pub window: Option<usize>,
2135    /// Learned per-Q-head sink logits (gpt-oss / MiMo-V2): they join the
2136    /// softmax max and denominator and carry no value row.
2137    pub sink: Option<&'a [f32]>,
2138    /// Gemma-4's scale-less V norm: every V head is RMS-normalized (no
2139    /// weight) before it is cached, as `attention::vnorm_head` does.
2140    pub v_norm: bool,
2141    /// Unlimited-OCR's block-sparse attend. `invf` then holds this position's
2142    /// rotary angles and the rotation runs at position 1.
2143    pub dash: Option<GraphDash<'a>>,
2144    /// Ripple's value residual: this layer's blend and the embedding rows of
2145    /// the call (one row for a token, a chunk's rows for a batch). V projects
2146    /// `lerp(embedding, normed, blend)`; Q and K project the normed row.
2147    pub vres: Option<(f32, &'a [f32])>,
2148    /// Maxwell's block-sparse support. A backend without the arm must
2149    /// decline a call that reaches past the dense range (`dense_range`).
2150    pub route: Option<GraphBlockRoute<'a>>,
2151}
2152
2153/// One layer's block router (Maxwell-V1-Flash, `maxwell::route_blocks`): a
2154/// query attends to the first `prefix` blocks of `block` positions, to its
2155/// own block and the `local - 1` before it, and to at most `remote` blocks
2156/// in between, chosen for each KV group by the block's largest token score
2157/// `q_g · k_t` (ties to the lower block). `q` `[nkv·hd, hidden]` and `k`
2158/// `[hd, hidden]` project the layer's normed input; both are normed a head
2159/// (`q_norm`, `k_norm`, the layer's epsilon) and rotated as the layer's
2160/// queries and keys are. While the blocks in between do not outnumber
2161/// `remote` every position is attended and the router does not run.
2162#[derive(Clone, Copy)]
2163pub struct GraphBlockRoute<'a> {
2164    pub q: &'a [f32],
2165    pub k: &'a [f32],
2166    pub q_norm: &'a [f32],
2167    pub k_norm: &'a [f32],
2168    pub block: usize,
2169    pub prefix: usize,
2170    pub local: usize,
2171    pub remote: usize,
2172}
2173
2174impl GraphBlockRoute<'_> {
2175    /// Positions below which a query attends to its whole past.
2176    pub fn dense_range(&self) -> usize {
2177        (self.prefix + self.local + self.remote) * self.block
2178    }
2179}
2180
2181static WGPU_EXTRA_RESERVE: AtomicU64 = AtomicU64::new(0);
2182
2183/// A model's own room on a discrete card besides the wgpu backend's default
2184/// reserve (the largest ask wins): bytes its sequences keep on the card that
2185/// the default does not foresee. Read when the device is first set up, so a
2186/// loader asks before the first GPU call; `CMF_GPU_VRAM_MB` overrides it.
2187pub fn wgpu_reserve_at_least(bytes: u64) {
2188    WGPU_EXTRA_RESERVE.fetch_max(bytes, Ordering::Relaxed);
2189}
2190
2191pub(crate) fn wgpu_extra_reserve() -> u64 {
2192    WGPU_EXTRA_RESERVE.load(Ordering::Relaxed)
2193}
2194
2195static WGPU_WEIGHTS_FLOOR: AtomicU64 = AtomicU64::new(0);
2196
2197/// The weights a model's graphs need on the card whole (a stack with its own
2198/// runtime takes no device prefix: short of them every token runs on the
2199/// host). The extra reserve of [`wgpu_reserve_at_least`] does not take the
2200/// weight budget below them while the default budget holds them: on a 24 GB
2201/// card Maxwell's reserve left 17.3 GB for 19.3 GB of weights and the card
2202/// sat idle. The largest ask wins; `CMF_GPU_VRAM_MB` overrides it.
2203pub fn wgpu_keep_at_least(bytes: u64) {
2204    WGPU_WEIGHTS_FLOOR.fetch_max(bytes, Ordering::Relaxed);
2205}
2206
2207pub(crate) fn wgpu_weights_floor() -> u64 {
2208    WGPU_WEIGHTS_FLOOR.load(Ordering::Relaxed)
2209}
2210
2211static WGPU_CARD_TOTAL: AtomicU64 = AtomicU64::new(0);
2212
2213pub(crate) fn wgpu_note_card_total(bytes: u64) {
2214    WGPU_CARD_TOTAL.store(bytes, Ordering::Relaxed);
2215}
2216
2217/// A discrete card's device-local memory as the wgpu backend read it at
2218/// setup; 0 on unified memory, on a backend that does not say, and before
2219/// the device is up.
2220pub fn wgpu_card_total() -> u64 {
2221    WGPU_CARD_TOTAL.load(Ordering::Relaxed)
2222}
2223
2224/// wgpu: card bytes a position takes on the block route (`gpu_wgpu::broute`) over `layers` layers.
2225pub fn wgpu_route_position_bytes(layers: usize, nkv: usize, hd: usize) -> u64 {
2226    #[cfg(feature = "gpu")]
2227    {
2228        crate::gpu_wgpu::broute::position_bytes(layers, nkv, hd)
2229    }
2230    #[cfg(not(feature = "gpu"))]
2231    {
2232        (layers * (2 * nkv + 1) * hd * 2) as u64
2233    }
2234}
2235
2236/// wgpu: grow every K/V mirror in steps of `rows` instead of to the next power of two (a model
2237/// whose positions cost much card memory; 0 restores the power of two).
2238pub fn wgpu_kv_step(rows: usize) {
2239    #[cfg(feature = "gpu")]
2240    crate::gpu_wgpu::set_kv_step(rows);
2241    #[cfg(not(feature = "gpu"))]
2242    let _ = rows;
2243}
2244
2245static PLAN_EXTRA: std::sync::Mutex<Vec<(u64, u64)>> = std::sync::Mutex::new(Vec::new());
2246
2247/// Card room a model keeps beside its stack for weights that go on the card
2248/// later (Maxwell's MTP layer, a plan of its own built at the first draft):
2249/// the CUDA plan of the model's block-routed stack counts it in its reserve,
2250/// so the rows it fits beside the weights leave that room, and the model's
2251/// later plans take their weights from it. `model`: `CmfModel::uid`.
2252pub fn plan_extra_reserve(model: u64, bytes: u64) {
2253    let mut g = PLAN_EXTRA.lock().unwrap();
2254    match g.iter_mut().find(|e| e.0 == model) {
2255        Some(e) => e.1 = e.1.max(bytes),
2256        None => g.push((model, bytes)),
2257    }
2258}
2259
2260pub(crate) fn plan_extra(model: u64) -> u64 {
2261    PLAN_EXTRA.lock().unwrap().iter().find(|e| e.0 == model).map_or(0, |e| e.1)
2262}
2263
2264static PLAN_STREAMED: std::sync::Mutex<Vec<u64>> = std::sync::Mutex::new(Vec::new());
2265
2266pub(crate) fn note_plan_streamed(model: u64) {
2267    let mut g = PLAN_STREAMED.lock().unwrap();
2268    if !g.contains(&model) {
2269        g.push(model);
2270    }
2271}
2272
2273/// Whether a CUDA plan of this model streams its routed experts through card
2274/// slots (they did not fit beside the context's rows): every call then waits
2275/// for the host between its layers.
2276pub fn plan_streamed(model: u64) -> bool {
2277    PLAN_STREAMED.lock().unwrap().contains(&model)
2278}
2279
2280/// CUDA hybrid arm: the hyper-connection streams the next small-path call of
2281/// this thread starts from, `[row][stream][hidden]` — a stack whose first
2282/// layer does not open its range (Maxwell's MTP layer takes the main stack's
2283/// streams). Dropped by the call that reads them, or by the next one.
2284pub fn graph_streams_in(streams: Vec<f32>) {
2285    #[cfg(feature = "cuda")]
2286    crate::gpu_cuda::streams_in(streams);
2287    #[cfg(not(feature = "cuda"))]
2288    let _ = streams;
2289}
2290
2291/// CUDA hybrid arm: ask the next small-path call of this thread for its rows'
2292/// closing streams (before the fold), then take them, `[row][stream][hidden]`;
2293/// empty when the call kept none.
2294pub fn graph_streams_want() {
2295    #[cfg(feature = "cuda")]
2296    crate::gpu_cuda::streams_want();
2297}
2298
2299/// See [`graph_streams_want`].
2300pub fn graph_streams_take() -> Vec<f32> {
2301    #[cfg(feature = "cuda")]
2302    {
2303        crate::gpu_cuda::streams_take()
2304    }
2305    #[cfg(not(feature = "cuda"))]
2306    {
2307        Vec::new()
2308    }
2309}
2310
2311/// CUDA hybrid arm, a GPTQ calibration of routed experts: from now on the
2312/// prompt path keeps, for the routed FFNs of layers `[lo, hi)`, each chunk's
2313/// normed input rows with the rows' expert ids and route weights
2314/// ([`moe_tap_end`] takes them: `(layer, rows [b][hidden], ids [b][k],
2315/// weights [b][k])` in call order). This thread's calls only.
2316pub fn moe_tap_begin(lo: usize, hi: usize) {
2317    #[cfg(feature = "cuda")]
2318    crate::gpu_cuda::moe_tap_begin(lo, hi);
2319    #[cfg(not(feature = "cuda"))]
2320    let _ = (lo, hi);
2321}
2322
2323/// See [`moe_tap_begin`].
2324pub fn moe_tap_end() -> Vec<(usize, Vec<f32>, Vec<i32>, Vec<f32>)> {
2325    #[cfg(feature = "cuda")]
2326    {
2327        crate::gpu_cuda::moe_tap_end()
2328    }
2329    #[cfg(not(feature = "cuda"))]
2330    {
2331        Vec::new()
2332    }
2333}
2334
2335static ROUTE_ROWS: AtomicU64 = AtomicU64::new(0);
2336
2337/// The positions the CUDA plan of a block-routed stack keeps room for (the
2338/// context cap, or with no `CMF_MAX_SEQ` the rows that fit beside weights
2339/// that stay on the card whole).
2340pub(crate) fn note_route_rows(rows: usize) {
2341    ROUTE_ROWS.store(rows as u64, Ordering::Relaxed);
2342}
2343
2344/// See [`note_route_rows`]; 0 before a plan is built.
2345pub fn route_rows() -> usize {
2346    ROUTE_ROWS.load(Ordering::Relaxed) as usize
2347}
2348
2349/// Positions a sequence may reach: `CMF_MAX_SEQ`, else 32 768, within the
2350/// model's own limit (the loader's cap, for the code that sizes device
2351/// memory by it).
2352pub fn context_cap(model: &CmfModel) -> usize {
2353    let cap = std::env::var("CMF_MAX_SEQ").ok().and_then(|v| v.parse::<usize>().ok()).unwrap_or(32_768);
2354    model.header.arch.max_position_embeddings.min(cap).max(1)
2355}
2356
2357/// Whether the active backend's graphs carry the block router
2358/// (`GraphBlockRoute`) past the dense range: the CUDA hybrid does
2359/// (`CMF_BLOCK_ROUTE=0`: the host takes such a sequence over).
2360pub fn block_route_on() -> bool {
2361    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2362    // the CUDA hybrid's `hy_route_*` kernels, the wgpu graphs' `broute`
2363    *ON.get_or_init(|| std::env::var("CMF_BLOCK_ROUTE").as_deref() != Ok("0")) && (cuda_active() || wgpu_active())
2364}
2365
2366/// Rows of an Unlimited-OCR prompt chunk on the batch graph: every remote block
2367/// of its rows must be closed before it starts, so it spans fewer blocks than
2368/// the local window (4 of 32).
2369pub const DASH_CHUNK_MAX: usize = 64;
2370
2371/// One layer's DASH router for the token graph (`gpu_wgpu::uocr`).
2372#[derive(Clone, Copy)]
2373pub struct GraphDash<'a> {
2374    /// `[2·index_dim, hidden]`, the q rows then the k rows.
2375    pub qk_proj: &'a [f32],
2376    pub q_norm: &'a [f32],
2377    pub k_norm: &'a [f32],
2378    pub head_cls: &'a [f32],
2379    pub idx_scale: f32,
2380    pub floor: f32,
2381    pub sigma: f32,
2382    pub k: usize,
2383    pub block: usize,
2384    pub local_blocks: usize,
2385    pub nblk: usize,
2386    /// Candidate blocks of the rows, `coff[row]..coff[row + 1]` per row.
2387    pub cands: &'a [u32],
2388    pub coff: &'a [u32],
2389    /// The rows' rotation angles, `[rows][head_dim / 2]`.
2390    pub angles: &'a [f32],
2391}
2392
2393/// The wgpu graphs carry Ripple's value residual (`CMF_VRES_GRAPH=0`: the host walk).
2394pub fn vres_graph_on() -> bool {
2395    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2396    *ON.get_or_init(|| std::env::var("CMF_VRES_GRAPH").as_deref() != Ok("0"))
2397}
2398
2399/// Activation of a graph layer's dense FFN, `act(gate)·up`. The code is
2400/// the word the kernels read (`silu_mul_pre`'s `_c`, the fused gate+up
2401/// kernels' `_p1`): 0 keeps the historical SiLU expression untouched.
2402#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2403pub enum GraphAct {
2404    Silu,
2405    /// Exact erf GELU (HF `gelu`), erf by Abramowitz–Stegun 7.1.26 — the
2406    /// formula `inference::erf_f32` uses on the host.
2407    GeluErf,
2408    /// tanh-approximated GELU (HF `gelu_pytorch_tanh`, the Gemma family):
2409    /// `inference::gelu_tanh` term for term.
2410    GeluTanh,
2411    /// MiniMax M3's checked SwiGLU-OAI contract. A backend may admit this
2412    /// only through an exact matching kernel; generic SiLU must never be used
2413    /// as a substitute.
2414    SwiGluOaiM3,
2415}
2416
2417impl GraphAct {
2418    pub fn code(self) -> u32 {
2419        match self {
2420            Self::Silu => 0,
2421            Self::GeluErf => 1,
2422            Self::GeluTanh => 2,
2423            Self::SwiGluOaiM3 => 3,
2424        }
2425    }
2426}
2427
2428/// Per-layer weights for the whole-token wgpu graph.
2429/// SenseNova-Loop mHC of one graph layer (two streams, `sensenova::Mhc`):
2430/// the attention and FFN routers (`[8, 2·hidden]` f32 and their biases),
2431/// whether this layer opens the range (copies the hidden into both
2432/// streams) or closes it (hands the streams' mean on), the Sinkhorn
2433/// iterations and the branch scale.
2434#[derive(Clone, Copy)]
2435pub struct GraphMhc<'a> {
2436    pub attn_w: &'a [f32],
2437    pub attn_b: &'a [f32],
2438    pub ffn_w: &'a [f32],
2439    pub ffn_b: &'a [f32],
2440    pub enter: bool,
2441    pub leave: bool,
2442    pub iters: usize,
2443    pub pre_scale: f32,
2444    /// DeepSeek-V4's form (GLM-5.3): Some = the logits scaled per group
2445    /// (pre, post, mix) before their base is added, `pre = σ + eps`, the mix
2446    /// a row softmax plus eps then eps-floored column / row normalizations,
2447    /// and the router's RMS taken with `rms_eps`. None = SenseNova-Loop's
2448    /// log-domain Sinkhorn.
2449    pub dsv4: Option<GraphMhcDsv4>,
2450    /// The range's closing fold (`leave`): Some = Hy4-flash's head,
2451    /// `σ(l·scale + base) + eps` over `[ns, ns·hidden]` router weights;
2452    /// None = the streams' mean. A backend without the arm must decline it.
2453    pub head: Option<GraphMhcHead<'a>>,
2454}
2455
2456/// Whether a stack carries any Hy4-flash arm (identity hyper-connections,
2457/// its gated MLA, latent experts, Engram): a backend that has no kernels for
2458/// them declines the whole call rather than run the layers without them.
2459pub fn hy_layers(layers: &[GraphLayer]) -> bool {
2460    layers.iter().any(|l| {
2461        l.engram.is_some()
2462            // (a learned closing fold over the DeepSeek-V4 form is Maxwell's, not Hy4-flash's)
2463            || l.mhc.as_ref().is_some_and(|m| m.dsv4.is_some_and(|d| d.ihc.is_some()))
2464            || matches!(&l.attn, GraphAttn::Mla { hy: Some(_), .. })
2465            || matches!(&l.ffn, GraphFfn::Moe { latent: Some(_), .. } | GraphFfn::Moe { shared_limit: Some(_), .. })
2466    })
2467}
2468
2469/// Hy4-flash's closing hyper-connection fold (`hc_head`).
2470#[derive(Clone, Copy)]
2471pub struct GraphMhcHead<'a> {
2472    pub w: &'a [f32],
2473    pub base: &'a [f32],
2474    pub scale: f32,
2475}
2476
2477/// DeepSeek-V4 / GLM-5.3 mHC constants of a layer (see `GraphMhc::dsv4`):
2478/// the attention and FFN routers' three group scales, the Sinkhorn epsilon
2479/// and the router input's RMS epsilon.
2480#[derive(Clone, Copy)]
2481pub struct GraphMhcDsv4 {
2482    pub attn_scale: [f32; 3],
2483    pub ffn_scale: [f32; 3],
2484    pub eps: f32,
2485    pub rms_eps: f32,
2486    /// Hy4-flash's identity hyper-connections: Some(magnitude) = the router
2487    /// has `2·ns` logits (pre, post) and no mix, the streams are never
2488    /// mixed, `post = magnitude·σ + eps`. A backend without the arm must
2489    /// decline it.
2490    pub ihc: Option<f32>,
2491}
2492
2493pub struct GraphLayer<'a> {
2494    /// SenseNova-Loop mHC streams around both sub-layers (None: plain
2495    /// residual).
2496    pub mhc: Option<GraphMhc<'a>>,
2497    pub input_norm: &'a [f32],
2498    pub attn: GraphAttn<'a>,
2499    pub post_norm: &'a [f32],
2500    pub ffn: GraphFfn<'a>,
2501    /// Gemma sandwich norms: the token mixer's output and the FFN's output
2502    /// are RMS-normed with these weights before their residual adds.
2503    pub attn_out_norm: Option<&'a [f32]>,
2504    pub ffn_out_norm: Option<&'a [f32]>,
2505    /// Gemma-4 `layer_scalar`: the residual stream is multiplied by it at
2506    /// the end of the layer.
2507    pub layer_scale: Option<f32>,
2508    /// Hy4-flash's Engram: a residual added to the mHC streams before the
2509    /// attention's fold. A backend without the arm must decline it.
2510    pub engram: Option<GraphEngram<'a>>,
2511}
2512
2513/// One Engram layer of a graph call (`hy4::Engram::apply`): the host's
2514/// looked-up memory rows of the call, the value and per-stream key
2515/// projections over them (with biases), the norms (`eps`, torch's bf16
2516/// default) and the per-stream scales.
2517pub struct GraphEngram<'a> {
2518    /// `[rows][mem]`: a row a call position; `on[r]` false = the position
2519    /// adds nothing (an image or pad token).
2520    pub mem: &'a [f32],
2521    pub on: &'a [bool],
2522    pub mem_dim: usize,
2523    /// `[hidden, mem]`, its bias.
2524    pub value: GraphW<'a>,
2525    pub value_b: &'a [f32],
2526    /// One `[hidden, mem]` key projection, bias and two norms a stream.
2527    pub keys: Vec<GraphW<'a>>,
2528    pub key_b: Vec<&'a [f32]>,
2529    pub norm_key: Vec<&'a [f32]>,
2530    pub norm_query: Vec<&'a [f32]>,
2531    pub gamma: &'a [f32],
2532    /// `[ns, hidden]`.
2533    pub hc_scales: &'a [f32],
2534    pub eps: f32,
2535}
2536
2537/// Hy4-flash's latent MoE: the routed experts read `down · x` and their
2538/// mixture goes back through `up`; the router and the shared expert read x.
2539pub struct GraphMoeLatent<'a> {
2540    /// `[dim, hidden]`, `[hidden, dim]`.
2541    pub down: GraphW<'a>,
2542    pub up: GraphW<'a>,
2543    pub dim: usize,
2544}
2545
2546/// A SwiGLU shared MoE expert whose intermediate width or packed layout does
2547/// not match the routed expert bank.  Most MoE checkpoints put the shared
2548/// expert in the same packed bank as the routed experts, but Flint keeps its
2549/// 1024-wide shared expert beside 512-wide routed experts.  Keeping this
2550/// descriptor separate lets the graph run the existing routed-bank kernels
2551/// and add the shared expert through the ordinary dense q4tp path, rather
2552/// than silently falling all the way back to per-op execution.
2553pub struct GraphMoeDetachedShared<'a> {
2554    pub gate: GraphW<'a>,
2555    pub up: GraphW<'a>,
2556    pub down: GraphW<'a>,
2557    pub width: usize,
2558}
2559
2560/// The FFN of one graph layer: a dense SwiGLU trio, or a routed MoE —
2561/// router + top-k selection + all selected experts run ON DEVICE (the
2562/// routing decision depends on the resident hidden state, so a CPU
2563/// round-trip per layer would forfeit the one-submit design).
2564pub enum GraphFfn<'a> {
2565    /// A singleton attention-only batch graph. Returns the post-attention
2566    /// residual, allowing a dynamic expert bank to own the FFN separately.
2567    AttentionOnly,
2568    Dense {
2569        gate: GraphW<'a>,
2570        up: GraphW<'a>,
2571        down: GraphW<'a>,
2572        /// act(gate)·up. The builders refuse an activation with no arm here
2573        /// (before this field the graph computed SiLU for any dense FFN).
2574        act: GraphAct,
2575        /// Ripple's clamped SwiGLU: the gate cut from above and the up branch
2576        /// on both sides at this value before `silu(gate)·up`; 0 = none.
2577        limit: f32,
2578        /// A second triple of the same layer, added to the first one's
2579        /// output: the layer's hot neurons in their own codec (`cortiq
2580        /// hot-bake`, stored as the layer's one tube). Same activation and
2581        /// clamp as the first.
2582        hot: Option<GraphMoeDetachedShared<'a>>,
2583    },
2584    Moe {
2585        /// Router logits weight (f32, kind 4) `[n_exp, hidden]`.
2586        router: GraphW<'a>,
2587        /// Shared-expert sigmoid gate (f32) `[1, hidden]`.
2588        shared_gate: GraphW<'a>,
2589        /// Per-expert q4_tiled directory indices `(gate, up, down)`;
2590        /// the SHARED expert rides as the LAST entry — the select
2591        /// kernel pins it with the sigmoid weight.
2592        experts: Vec<(usize, usize, usize)>,
2593        /// Routed experts (shared excluded).
2594        n_exp: usize,
2595        top_k: usize,
2596        inter: usize,
2597        /// Exact gate/up activation used by every uniformly packed routed
2598        /// expert (and its in-bank shared expert, if any). The graph builder
2599        /// verifies uniformity before encoding one kernel contract for the
2600        /// layer.
2601        act: GraphAct,
2602        norm_topk: bool,
2603        /// Expert weight layout, uniform across the layer: `false` =
2604        /// q4_tiled (18 B tiles, inline f16 scale), `true` = q4tp
2605        /// (16 B nibbles + a per-row ladder plane). The two differ only
2606        /// in where the scale comes from, so they share every kernel
2607        /// but the weight-staging block.
2608        q4tp: bool,
2609        /// `true` = the gate/up experts are `q2tp` (2-bit plane) while
2610        /// `down` stays q4tp — the mixed profile a 2-bit-class checkpoint
2611        /// converts into. Only meaningful with `q4tp: true`.
2612        gu_q2: bool,
2613        /// `true` = every expert's gate, up AND down is q8_2f (int8 body,
2614        /// f16 row scales, f16 column field; Mellum2.1's quality file).
2615        /// `q4tp` and `gu_q2` are false then. Its own kernels: each
2616        /// expert's input is multiplied by THAT expert's column field.
2617        q82: bool,
2618        /// LFM2-MoE / DeepSeek-V3 `noaux_tc` routing: per-expert sigmoid
2619        /// scores instead of a softmax. `sigmoid_denom_eps` carries the
2620        /// source architecture's selected-score renormalization floor.
2621        sigmoid: bool,
2622        sigmoid_denom_eps: f32,
2623        /// Per-expert SELECTION bias: added to the score for the top-k
2624        /// choice only — the mixing weights stay unbiased (noaux_tc).
2625        bias: Option<&'a [f32]>,
2626        /// Whether a shared expert rides as the last `experts` entry.
2627        /// LFM2-MoE has none; the select kernel then leaves slot `top_k`
2628        /// unwritten and the expert loop runs `top_k` slots, not +1.
2629        has_shared: bool,
2630        /// A separately evaluated, ungated shared SwiGLU expert.  It is
2631        /// deliberately outside `experts`: those tensors cannot share the
2632        /// routed bank's stride when their intermediate width differs.
2633        detached_shared: Option<GraphMoeDetachedShared<'a>>,
2634        /// The shared expert carries a sigmoid gate (Qwen2/3-MoE). `false`
2635        /// with `has_shared`: the shared expert enters with weight 1
2636        /// (DeepSeek-V3 / HunYuan hy_v3) and `shared_gate` is a stand-in
2637        /// the select kernels ignore.
2638        shared_gated: bool,
2639        /// Multiplier on the routed mixing weights after the optional
2640        /// renormalization (`routed_scaling_factor`); 1.0 = none.
2641        route_scale: f32,
2642        /// SwiGLU clamp of every routed and shared expert (GLM-5.3: the gate
2643        /// from above, up on both sides), 0 = none. The CUDA hybrid's pair
2644        /// epilogue takes it; the wgpu graphs decline a clamped bank.
2645        limit: f32,
2646        /// The shared expert's own clamp when it differs (Hy4-flash: none
2647        /// beside clamped routed experts); None = `limit`.
2648        shared_limit: Option<f32>,
2649        /// Latent experts (Hy4-flash); None = experts at full width. A
2650        /// backend without the arm must decline it.
2651        latent: Option<GraphMoeLatent<'a>>,
2652    },
2653}
2654
2655/// Outcome of one whole-token graph attempt. A failed attempt after sealed
2656/// O(1) state was admitted must not fall through to the stale CPU state.
2657#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2658pub enum TokenGraphOutcome {
2659    /// No command was committed; the caller may use its ordinary path.
2660    Declined,
2661    /// The graph completed and its hidden/logits output is valid.
2662    Completed,
2663    /// Sealed O(1) state was admitted and a later graph operation failed.
2664    Failed,
2665}
2666
2667/// Whole-token decode graph on wgpu: the entire layer stack in ONE submit,
2668/// hidden resident, one readback. Updates `h` in place.
2669/// `loop_norm_at`: virtual layer indices after which `final_norm` is applied
2670/// (Looped Transformer mid-stack norm). Empty for standard models.
2671#[allow(clippy::too_many_arguments)]
2672pub fn forward_token_graph(
2673    model: &Arc<CmfModel>,
2674    kv_id: u64,
2675    layers: &[GraphLayer],
2676    // Per-layer sealed o1 (Nystrom) state; Some = replace this layer's
2677    // exact attention with the O(1) kernels. wgpu only.
2678    o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
2679    o1_epoch: u64,
2680    invf: &[f32],
2681    h: &mut [f32],
2682    nh: usize,
2683    nkv: usize,
2684    hd: usize,
2685    attn_scale: f32,
2686    rd: usize,
2687    hidden: usize,
2688    inter: usize,
2689    position: usize,
2690    cap: usize,
2691    gemma: bool,
2692    eps: f32,
2693    lm_head: Option<(&GraphW, usize)>,
2694    final_norm: &[f32],
2695    logits: &mut Vec<f32>,
2696    loop_norm_at: &[usize],
2697    steps: usize,
2698    embed: Option<(&GraphW, usize, f32)>,
2699    ids_out: Option<&mut Vec<u32>>,
2700    // How many leading layers the graph ran (see the wgpu twin) — smaller
2701    // than layers.len() when the expert budget ended the device prefix.
2702    layers_run: Option<&mut usize>,
2703    // Absolute index of layers[0] in the model — the KV/state mirrors key
2704    // on it, so a layer SPAN (network split segment) shares mirrors with
2705    // a full-stack run instead of colliding at slot 0.
2706    layer_base: usize,
2707    // Read the final hidden back alongside the fused head's logits.
2708    hidden_too: bool,
2709) -> TokenGraphOutcome {
2710    match backend() {
2711        #[cfg(feature = "gpu")]
2712        Backend::Wgpu => crate::gpu_wgpu::forward_token_graph(
2713            model,
2714            kv_id,
2715            layers,
2716            o1,
2717            o1_epoch,
2718            invf,
2719            h,
2720            nh,
2721            nkv,
2722            hd,
2723            attn_scale,
2724            rd,
2725            hidden,
2726            inter,
2727            position,
2728            cap,
2729            gemma,
2730            eps,
2731            lm_head,
2732            final_norm,
2733            logits,
2734            loop_norm_at,
2735            steps,
2736            embed,
2737            ids_out,
2738            layers_run,
2739            layer_base,
2740            hidden_too,
2741        ),
2742        #[cfg(feature = "cuda")]
2743        Backend::Cuda => crate::gpu_cuda::forward_token_graph(
2744            model,
2745            kv_id,
2746            layers,
2747            o1,
2748            o1_epoch,
2749            invf,
2750            h,
2751            nh,
2752            nkv,
2753            hd,
2754            attn_scale,
2755            rd,
2756            hidden,
2757            position,
2758            cap,
2759            gemma,
2760            eps,
2761            lm_head,
2762            final_norm,
2763            logits,
2764            loop_norm_at,
2765            steps,
2766            layers_run,
2767            layer_base,
2768            hidden_too,
2769        ),
2770        #[allow(unused_variables)]
2771        _ => {
2772            let _ = (
2773                attn_scale,
2774                lm_head,
2775                final_norm,
2776                logits,
2777                loop_norm_at,
2778                layers_run,
2779                layer_base,
2780                hidden_too,
2781            );
2782            TokenGraphOutcome::Declined
2783        }
2784    }
2785}
2786
2787/// Dory's forward on the selected device. `false` leaves the host to run it.
2788#[allow(clippy::too_many_arguments)]
2789pub fn dory_forward(
2790    id: u64,
2791    model: Option<&std::sync::Arc<cortiq_core::CmfModel>>,
2792    m: &crate::dory::Dory,
2793    ids: &[u32],
2794    pos: usize,
2795    loops: usize,
2796    want: crate::dory::Want,
2797    logits: &mut Vec<f32>,
2798) -> bool {
2799    #[cfg(target_os = "macos")]
2800    if backend() == Backend::Metal {
2801        return model.is_some_and(|md| crate::gpu_metal::dory::forward(id, md, m, ids, pos, loops, want, logits));
2802    }
2803    #[cfg(feature = "cuda")]
2804    if backend() == Backend::Cuda {
2805        return crate::gpu_cuda::dory_forward(id, m, ids, pos, loops, want, logits);
2806    }
2807    #[cfg(feature = "gpu")]
2808    if backend() == Backend::Wgpu {
2809        return crate::gpu_wgpu::dory::forward(id, m, ids, pos, loops, want, logits);
2810    }
2811    let _ = (id, model, m, ids, pos, loops, want, logits);
2812    false
2813}
2814
2815/// Inkling-2-Mini's call on the selected device (`ids` from `pos`; the last
2816/// row's logits when `want`, every row's when `all`). `false` leaves the host
2817/// to run it.
2818#[allow(clippy::too_many_arguments)]
2819pub fn inkling_forward(
2820    id: u64,
2821    g: &crate::inkling::Globals,
2822    layers: &[crate::inkling::Layer],
2823    cfg: &crate::inkling::Cfg,
2824    ids: &[u32],
2825    pos: usize,
2826    want: bool,
2827    all: bool,
2828    logits: &mut Vec<f32>,
2829) -> bool {
2830    #[cfg(target_os = "macos")]
2831    if backend() == Backend::Metal {
2832        return crate::gpu_metal::inkling::forward(id, g, layers, cfg, ids, pos, want, all, logits);
2833    }
2834    #[cfg(feature = "cuda")]
2835    if backend() == Backend::Cuda {
2836        return crate::gpu_cuda::inkling_forward(id, g, layers, cfg, ids, pos, want, all, logits);
2837    }
2838    #[cfg(feature = "gpu")]
2839    if backend() == Backend::Wgpu {
2840        return crate::gpu_wgpu::inkling::forward(id, g, layers, cfg, ids, pos, want, all, logits);
2841    }
2842    let _ = (id, g, layers, cfg, ids, pos, want, all, logits);
2843    false
2844}
2845
2846/// A new Inkling sequence on the device.
2847pub fn inkling_reset(id: u64) {
2848    #[cfg(target_os = "macos")]
2849    if backend() == Backend::Metal {
2850        crate::gpu_metal::inkling::reset(id);
2851        return;
2852    }
2853    #[cfg(feature = "cuda")]
2854    if backend() == Backend::Cuda {
2855        crate::gpu_cuda::inkling_reset(id);
2856    }
2857    #[cfg(feature = "gpu")]
2858    if backend() == Backend::Wgpu {
2859        crate::gpu_wgpu::inkling::reset(id);
2860    }
2861    let _ = id;
2862}
2863
2864/// Inkling's DSpark drafter on the card: up to `k` drafts from `anchor`, the
2865/// token sampled for `pos` (CUDA; `None` elsewhere: plain decoding).
2866pub fn inkling_draft(id: u64, g: &crate::inkling::Globals, cfg: &crate::inkling::Cfg, anchor: u32, pos: usize, k: usize) -> Option<Vec<u32>> {
2867    #[cfg(feature = "cuda")]
2868    if backend() == Backend::Cuda {
2869        return crate::gpu_cuda::inkling_draft(id, g, cfg, anchor, pos, k);
2870    }
2871    let _ = (id, g, cfg, anchor, pos, k);
2872    None
2873}
2874
2875/// The sequence's convolution rings saved before a draft verify.
2876pub fn inkling_ring_snap(id: u64) -> bool {
2877    #[cfg(feature = "cuda")]
2878    if backend() == Backend::Cuda {
2879        return crate::gpu_cuda::inkling_ring_snap(id);
2880    }
2881    let _ = id;
2882    false
2883}
2884
2885/// The rings put back as they stand after the verify's first `r` rows.
2886pub fn inkling_ring_back(id: u64, r: usize) -> bool {
2887    #[cfg(feature = "cuda")]
2888    if backend() == Backend::Cuda {
2889        return crate::gpu_cuda::inkling_ring_back(id, r);
2890    }
2891    let _ = (id, r);
2892    false
2893}
2894
2895/// A draft verify on the card: each row's greedy pick (the logits stay there
2896/// for `inkling_row_logits`).
2897#[allow(clippy::too_many_arguments)]
2898pub fn inkling_verify(id: u64, g: &crate::inkling::Globals, layers: &[crate::inkling::Layer], cfg: &crate::inkling::Cfg, ids: &[u32], pos: usize, picks: &mut Vec<u32>) -> bool {
2899    #[cfg(feature = "cuda")]
2900    if backend() == Backend::Cuda {
2901        return crate::gpu_cuda::inkling_verify(id, g, layers, cfg, ids, pos, picks);
2902    }
2903    let _ = (id, g, layers, cfg, ids, pos, picks);
2904    false
2905}
2906
2907/// Row `r`'s logits of the last `inkling_verify`.
2908pub fn inkling_row_logits(id: u64, r: usize, vocab: usize, out: &mut Vec<f32>) -> bool {
2909    #[cfg(feature = "cuda")]
2910    if backend() == Backend::Cuda {
2911        return crate::gpu_cuda::inkling_row_logits(id, r, vocab, out);
2912    }
2913    let _ = (id, r, vocab, out);
2914    false
2915}
2916
2917/// A new Dory sequence on the device.
2918pub fn dory_reset(id: u64) {
2919    #[cfg(target_os = "macos")]
2920    if backend() == Backend::Metal {
2921        crate::gpu_metal::dory::reset(id);
2922        return;
2923    }
2924    #[cfg(feature = "cuda")]
2925    if backend() == Backend::Cuda {
2926        crate::gpu_cuda::dory_reset(id);
2927        return;
2928    }
2929    #[cfg(feature = "gpu")]
2930    if backend() == Backend::Wgpu {
2931        crate::gpu_wgpu::dory::reset(id);
2932    }
2933    let _ = id;
2934}
2935
2936/// The KV bytes a Dory sequence holds on the device.
2937/// Has this Dory sequence gone over to the far field on the device?
2938pub fn dory_sealed(id: u64) -> bool {
2939    #[cfg(target_os = "macos")]
2940    if backend() == Backend::Metal {
2941        return crate::gpu_metal::dory::sealed(id);
2942    }
2943    #[cfg(feature = "cuda")]
2944    if backend() == Backend::Cuda {
2945        return crate::gpu_cuda::dory_sealed(id);
2946    }
2947    #[cfg(feature = "gpu")]
2948    if backend() == Backend::Wgpu {
2949        return crate::gpu_wgpu::dory::sealed(id);
2950    }
2951    let _ = id;
2952    false
2953}
2954
2955pub fn dory_kv_bytes(id: u64) -> Option<u64> {
2956    #[cfg(target_os = "macos")]
2957    if backend() == Backend::Metal {
2958        return crate::gpu_metal::dory::kv_bytes(id);
2959    }
2960    #[cfg(feature = "cuda")]
2961    if backend() == Backend::Cuda {
2962        return crate::gpu_cuda::dory_kv_bytes(id);
2963    }
2964    #[cfg(feature = "gpu")]
2965    if backend() == Backend::Wgpu {
2966        return crate::gpu_wgpu::dory::kv_bytes(id);
2967    }
2968    let _ = id;
2969    None
2970}
2971
2972/// Is the f16 token path of the resident graph there on this device?
2973pub fn embryo_wide_ready(q8: bool) -> bool {
2974    #[cfg(feature = "cuda")]
2975    if backend() == Backend::Cuda {
2976        return crate::gpu_cuda::embryo_wide_ready(q8);
2977    }
2978    #[cfg(feature = "gpu")]
2979    if backend() == Backend::Wgpu {
2980        return crate::gpu_wgpu::embryo_wide_ready(q8);
2981    }
2982    let _ = q8;
2983    false
2984}
2985
2986/// Whole-token resident graph for the Embryo working model.  Unlike the
2987/// generic graph this path accepts a packed f32 model and keeps both phase
2988/// recurrent state and the anchor KV cache on the device.  `false` is an
2989/// honest capability refusal; callers must retain the CPU executor.
2990pub fn forward_embryo_graph(
2991    model: &Arc<EmbryoGraphModel>,
2992    kv_id: u64,
2993    hidden: &[f32],
2994    position: usize,
2995    logits: &mut Vec<f32>,
2996) -> bool {
2997    #[cfg(feature = "cuda")]
2998    if backend() == Backend::Cuda {
2999        return crate::gpu_cuda::forward_embryo_graph(model, kv_id, hidden, position, logits);
3000    }
3001    #[cfg(feature = "gpu")]
3002    if backend() == Backend::Wgpu {
3003        return crate::gpu_wgpu::forward_embryo_graph(model, kv_id, hidden, position, logits);
3004    }
3005    let _ = (model, kv_id, hidden, position, logits);
3006    false
3007}
3008
3009/// Speculative-verify tail for the batched graph: fold final-norm + lm_head
3010/// over every batch position and read all k logit rows back; the batch also
3011/// snapshots the GDN state per position for `gdn_spec_restore`.
3012#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3013pub enum BatchGraphOutcome {
3014    /// The graph declined before mutating persistent device state. Callers may
3015    /// safely use the existing per-position path.
3016    Declined,
3017    /// The complete batch committed and its readback succeeded.
3018    Completed,
3019    /// A batch that had admitted sealed O(1) state failed after admission.
3020    /// Falling back to CPU would mix two state machines, so the caller must
3021    /// abort and clear the sequence instead.
3022    Failed,
3023}
3024
3025pub struct SpecTail<'a> {
3026    pub lm: GraphW<'a>,
3027    pub lm_rows: usize,
3028    pub final_norm: &'a [f32],
3029    pub logits_out: &'a mut Vec<f32>,
3030    /// Block preview, greedy: penalize and pick on the device — each row's
3031    /// argmax and its softmax probability land in the Vec (row order), and
3032    /// `logits_out` stays empty.
3033    pub pick: Option<(PreviewPick<'a>, &'a mut Vec<(u32, f32)>)>,
3034}
3035
3036/// The response penalties of a block-diffusion pass, as the host applies
3037/// them (`pipeline::clover::Penalties::apply`): per committed-token counts
3038/// the frequency, presence and repetition terms, the stop-id and
3039/// `</think>` ramps at row position `len0 + r + 1`, and `forbid` (mask,
3040/// suppressed ids) at −∞.
3041pub struct PreviewPick<'a> {
3042    pub vocab: usize,
3043    pub counts: &'a [u32],
3044    pub stop: &'a [u32],
3045    pub forbid: &'a [u32],
3046    pub think_end: Option<u32>,
3047    pub close_open: bool,
3048    pub len0: usize,
3049    pub frequency: f32,
3050    pub presence: f32,
3051    pub repetition: f32,
3052    /// (strength, start, window) of the stop-id and `</think>` ramps.
3053    pub length_ramp: (f32, f32, f32),
3054    pub think_ramp: (f32, f32, f32),
3055}
3056
3057/// Batched prefill: k contiguous positions through the whole graph in one submit
3058/// (projections/FFN as GEMMs, attention/GDN looped over scratch). `h` is
3059/// [k·hidden] in/out; `positions` len k. wgpu only.
3060#[allow(clippy::too_many_arguments)]
3061pub fn forward_batch_graph(
3062    model: &Arc<CmfModel>,
3063    kv_id: u64,
3064    layers: &[GraphLayer],
3065    invf: &[f32],
3066    h: &mut [f32],
3067    nh: usize,
3068    nkv: usize,
3069    hd: usize,
3070    rd: usize,
3071    hidden: usize,
3072    inter: usize,
3073    positions: &[usize],
3074    cap: usize,
3075    gemma: bool,
3076    eps: f32,
3077    attn_scale: f32,
3078    k: usize,
3079    // Per-layer sealed O(1) device views. An empty slice means the ordinary
3080    // exact-KV path; otherwise it must have one entry per graph layer.
3081    o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
3082    o1_epoch: u64,
3083    spec: Option<SpecTail<'_>>,
3084    // Device-prefix mode (plain prefill only): Some = when the whole stack
3085    // does not fit the weight budget, run the leading layers that do — the
3086    // same prefix rule as the token graph — leave the boundary hidden in
3087    // `h` and report the count here; the caller runs the rest on the host.
3088    // None = all layers or a decline, as before.
3089    layers_run: Option<&mut usize>,
3090) -> BatchGraphOutcome {
3091    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)
3092}
3093
3094thread_local! {
3095    static MIMO_ATTN_SCRATCH: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
3096}
3097
3098pub(crate) fn mimo_attention_scratch_enabled() -> bool {
3099    MIMO_ATTN_SCRATCH.with(std::cell::Cell::get)
3100}
3101
3102/// Scoped diagnostic A/B switch; unlike process environment mutations it
3103/// cannot race a model's background workers. Restores on panic as well.
3104#[doc(hidden)]
3105pub fn mimo_attention_scratch_scope<R>(enabled: bool, f: impl FnOnce() -> R) -> R {
3106    struct Restore(bool);
3107    impl Drop for Restore {
3108        fn drop(&mut self) {
3109            MIMO_ATTN_SCRATCH.with(|v| v.set(self.0));
3110        }
3111    }
3112    let _restore = Restore(MIMO_ATTN_SCRATCH.with(|v| v.replace(enabled)));
3113    f()
3114}
3115
3116/// Gemma-4's prompt on the batched wgpu graph (`CMF_G4_BATCH=0` keeps the
3117/// chunked host prefill it used before).
3118pub fn g4_batch_on() -> bool {
3119    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3120    *ON.get_or_init(|| std::env::var("CMF_G4_BATCH").as_deref() != Ok("0"))
3121}
3122
3123/// q8_2f MoE experts on the wgpu token and batch graphs (`CMF_MOE_Q82=0`
3124/// keeps them off the graphs: every op on its own, the 0.8.15 route).
3125pub(crate) fn moe_q82_graph_on() -> bool {
3126    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3127    *ON.get_or_init(|| std::env::var("CMF_MOE_Q82").as_deref() != Ok("0"))
3128}
3129
3130thread_local! {
3131    static MIMO_Q8_SHORT: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
3132}
3133
3134pub(crate) fn mimo_q8_short_enabled() -> bool {
3135    MIMO_Q8_SHORT.with(std::cell::Cell::get)
3136}
3137
3138/// Diagnostic A/B switch for row-exact short q8 graph kernels.
3139#[doc(hidden)]
3140pub fn mimo_q8_short_scope<R>(enabled: bool, f: impl FnOnce() -> R) -> R {
3141    struct Restore(bool);
3142    impl Drop for Restore {
3143        fn drop(&mut self) {
3144            MIMO_Q8_SHORT.with(|v| v.set(self.0));
3145        }
3146    }
3147    let _restore = Restore(MIMO_Q8_SHORT.with(|v| v.replace(enabled)));
3148    f()
3149}
3150
3151/// Batched graph over a span whose first absolute layer is `layer_base`.
3152#[allow(clippy::too_many_arguments)]
3153pub fn forward_batch_graph_at(
3154    model: &Arc<CmfModel>,
3155    kv_id: u64,
3156    layer_base: usize,
3157    layers: &[GraphLayer],
3158    invf: &[f32],
3159    h: &mut [f32],
3160    nh: usize,
3161    nkv: usize,
3162    hd: usize,
3163    rd: usize,
3164    hidden: usize,
3165    inter: usize,
3166    positions: &[usize],
3167    cap: usize,
3168    gemma: bool,
3169    eps: f32,
3170    attn_scale: f32,
3171    k: usize,
3172    // Per-layer sealed O(1) device views. An empty slice means the ordinary
3173    // exact-KV path; otherwise it must have one entry per graph layer.
3174    o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
3175    o1_epoch: u64,
3176    spec: Option<SpecTail<'_>>,
3177    // Device-prefix mode (plain prefill only): Some = when the whole stack
3178    // does not fit the weight budget, run the leading layers that do — the
3179    // same prefix rule as the token graph — leave the boundary hidden in
3180    // `h` and report the count here; the caller runs the rest on the host.
3181    // None = all layers or a decline, as before.
3182    layers_run: Option<&mut usize>,
3183) -> BatchGraphOutcome {
3184    match backend() {
3185        #[cfg(feature = "gpu")]
3186        Backend::Wgpu => crate::gpu_wgpu::forward_batch_graph_at(
3187            model, kv_id, layer_base, layers, invf, h, nh, nkv, hd, rd, hidden, inter, positions,
3188            cap, gemma, eps, attn_scale, k, o1, o1_epoch, spec, layers_run,
3189        ),
3190        #[cfg(feature = "cuda")]
3191        Backend::Cuda => crate::gpu_cuda::forward_batch_graph_at(
3192            model, kv_id, layer_base, layers, invf, h, nh, nkv, hd, rd, hidden, positions, cap,
3193            gemma, eps, attn_scale, k, o1, o1_epoch, spec, layers_run,
3194        ),
3195        #[allow(unreachable_patterns)]
3196        _ => {
3197            let _ = (o1, o1_epoch, spec, layers_run);
3198            BatchGraphOutcome::Declined
3199        }
3200    }
3201}
3202
3203/// y [n][rows] = W x [n][cols] for a graph weight on the selected device;
3204/// false leaves the caller to run it (CUDA's hybrid arm only).
3205pub fn rows_matvec(
3206    model: &Arc<CmfModel>,
3207    gw: &GraphW,
3208    rows: usize,
3209    cols: usize,
3210    x: &[f32],
3211    n: usize,
3212    y: &mut [f32],
3213) -> bool {
3214    #[cfg(feature = "cuda")]
3215    if backend() == Backend::Cuda {
3216        return crate::gpu_cuda::rows_matvec(model, gw, rows, cols, x, n, y);
3217    }
3218    let _ = (model, gw, rows, cols, x, n, y);
3219    false
3220}
3221
3222/// After a partial speculative acceptance: restore every GDN layer's device
3223/// state to the snapshot after batch position `slot`. `base_pos` is the
3224/// absolute position of the first verify row and `expected_layers` makes the
3225/// restore all-or-nothing across the model's recurrent layers. wgpu only.
3226pub fn gdn_spec_restore(kv_id: u64, slot: usize, base_pos: usize, expected_layers: usize) -> bool {
3227    #[cfg(feature = "cuda")]
3228    if backend() == Backend::Cuda {
3229        return crate::gpu_cuda::gdn_spec_restore(kv_id, slot, base_pos, expected_layers);
3230    }
3231    #[cfg(feature = "gpu")]
3232    if backend() == Backend::Wgpu {
3233        return crate::gpu_wgpu::gdn_spec_restore(kv_id, slot, base_pos, expected_layers);
3234    }
3235    #[allow(unreachable_code)]
3236    {
3237        let _ = (kv_id, slot, base_pos, expected_layers);
3238        false
3239    }
3240}
3241
3242/// CUDA hybrid arm: copy every GDN state of the sequence, all at prompt
3243/// position `pos`, to a snapshot on the card (a chat's next turn goes back
3244/// there). False on any other backend or when a layer is elsewhere.
3245pub fn gdn_snapshot(kv_id: u64, pos: usize) -> bool {
3246    #[cfg(feature = "cuda")]
3247    if backend() == Backend::Cuda {
3248        return crate::gpu_cuda::gdn_snapshot(kv_id, pos);
3249    }
3250    let _ = (kv_id, pos);
3251    false
3252}
3253
3254/// CUDA hybrid arm: every GDN state of the sequence back to its snapshot at
3255/// `pos`, all or nothing. False leaves the states untouched.
3256pub fn gdn_snapshot_restore(kv_id: u64, pos: usize) -> bool {
3257    #[cfg(feature = "cuda")]
3258    if backend() == Backend::Cuda {
3259        return crate::gpu_cuda::gdn_snapshot_restore(kv_id, pos);
3260    }
3261    let _ = (kv_id, pos);
3262    false
3263}
3264
3265/// Re-point one exact-attention device mirror after a speculative round has
3266/// discarded unaccepted rows. The rows beyond `stored` remain allocated and
3267/// are overwritten by the next append; only the logical cursor moves. This
3268/// is the wgpu twin of Metal's existing mirror cursor helper and keeps the
3269/// MTP graph's speculative/device cache coherent with its real anchor.
3270pub fn graph_kv_set_stored(kv_id: u64, layer: usize, stored: usize) -> bool {
3271    #[cfg(feature = "cuda")]
3272    if backend() == Backend::Cuda {
3273        return crate::gpu_cuda::kv_set_stored(kv_id, layer, stored);
3274    }
3275    #[cfg(feature = "gpu")]
3276    if backend() == Backend::Wgpu {
3277        return crate::gpu_wgpu::kv_mirror_set_stored(kv_id, layer, stored);
3278    }
3279    #[cfg(target_os = "macos")]
3280    if backend() == Backend::Metal {
3281        crate::gpu_metal::kv_mirror_set_stored(kv_id, layer, stored);
3282        return true;
3283    }
3284    false
3285}
3286
3287/// Rows the wgpu token graph's exact-attention mirror holds for one layer
3288/// (None: no wgpu mirror). Metal keeps its owner cache current per token
3289/// and reports None here.
3290pub fn graph_kv_stored(_kv_id: u64, _layer: usize) -> Option<usize> {
3291    #[cfg(feature = "cuda")]
3292    if backend() == Backend::Cuda {
3293        return crate::gpu_cuda::kv_stored(_kv_id, _layer);
3294    }
3295    #[cfg(feature = "gpu")]
3296    if backend() == Backend::Wgpu {
3297        return crate::gpu_wgpu::kv_mirror_stored(_kv_id, _layer);
3298    }
3299    None
3300}
3301
3302/// Does the wgpu token graph hold a device-resident recurrent state for
3303/// this layer (one the host `linear_state` has not seen)?
3304pub fn graph_state_resident(_kv_id: u64, _layer: usize) -> bool {
3305    #[cfg(feature = "cuda")]
3306    if backend() == Backend::Cuda {
3307        return crate::gpu_cuda::state_resident(_kv_id, _layer);
3308    }
3309    #[cfg(feature = "gpu")]
3310    if backend() == Backend::Wgpu {
3311        return crate::gpu_wgpu::graph_state_resident(_kv_id, _layer);
3312    }
3313    false
3314}
3315
3316/// Capture the rotated queries of `layers` in this thread's batch-graph
3317/// calls (the O(1) seal's trace for a prefix run on the device). False when
3318/// there is no wgpu batch graph to capture from.
3319pub fn o1_qcap_begin(_layers: &[usize]) -> bool {
3320    #[cfg(feature = "gpu")]
3321    if backend() == Backend::Wgpu {
3322        crate::gpu_wgpu::o1_qcap_begin(_layers);
3323        return true;
3324    }
3325    #[cfg(feature = "cuda")]
3326    if backend() == Backend::Cuda {
3327        return crate::gpu_cuda::o1_qcap_begin(_layers);
3328    }
3329    false
3330}
3331
3332/// Ask the armed capture for one row in `stride` by position, the rows a
3333/// seal's trace keeps. True: the drains hand back those rows alone; false:
3334/// every row, as before.
3335pub fn o1_qcap_stride(_stride: usize) -> bool {
3336    #[cfg(feature = "gpu")]
3337    if backend() == Backend::Wgpu {
3338        return crate::gpu_wgpu::o1_qcap_stride(_stride);
3339    }
3340    #[cfg(feature = "cuda")]
3341    if backend() == Backend::Cuda {
3342        return crate::gpu_cuda::o1_qcap_stride(_stride);
3343    }
3344    false
3345}
3346
3347/// What the capture holds so far, off the card; it stays armed.
3348pub fn o1_qcap_drain() -> Option<Vec<(usize, Vec<f32>)>> {
3349    #[cfg(feature = "gpu")]
3350    if backend() == Backend::Wgpu {
3351        return crate::gpu_wgpu::o1_qcap_drain();
3352    }
3353    #[cfg(feature = "cuda")]
3354    if backend() == Backend::Cuda {
3355        return crate::gpu_cuda::o1_qcap_drain();
3356    }
3357    None
3358}
3359
3360/// The accepted rows of a verify: the sealed layers' state moves over them.
3361pub fn o1_spec_commit(_kv_id: u64, _pos0: usize, _rows: usize) -> bool {
3362    #[cfg(feature = "cuda")]
3363    if backend() == Backend::Cuda {
3364        return crate::gpu_cuda::o1_spec_commit(_kv_id, _pos0, _rows);
3365    }
3366    #[cfg(feature = "gpu")]
3367    if backend() == Backend::Wgpu {
3368        return crate::gpu_wgpu::o1_spec_commit(_kv_id, _pos0, _rows);
3369    }
3370    #[cfg(target_os = "macos")]
3371    if backend() == Backend::Metal {
3372        return crate::gpu_metal::o1c::spec_commit(_kv_id, _rows);
3373    }
3374    false
3375}
3376
3377/// A seal's far sums go to the card (`o1_far_sums`): CUDA, unless
3378/// `CMF_O1_FAR_GPU=0`.
3379/// A finished command leaves here when the process holds both an NVIDIA
3380/// Vulkan device and a CUDA context (GPTQ: the calibration forward on the
3381/// wgpu graph, the folds and sweeps on CUDA). The driver's own exit handlers
3382/// then free something twice: glibc aborted with "corrupted size vs.
3383/// prev_size in fastbins" after `quantize-gptq` had written its file, rc 134
3384/// for a run that had succeeded (the backtrace: `free` under
3385/// libnvidia-glcore, from libGLX_nvidia's teardown). Flushes the standard
3386/// streams and exits past the handlers; a process with one of the two, or
3387/// neither, returns and exits the usual way. `CMF_EXIT_HANDLERS=1` returns always.
3388pub fn exit_past_driver_teardown(code: i32) {
3389    #[cfg(all(feature = "cuda", unix))]
3390    {
3391        if std::env::var("CMF_EXIT_HANDLERS").as_deref() != Ok("1") && crate::gpu_cuda::ctx_built() && crate::gpu_wgpu::any_ctx_built() {
3392            use std::io::Write;
3393            let _ = std::io::stdout().flush();
3394            let _ = std::io::stderr().flush();
3395            // SAFETY: `_exit` ends the process at once; every file this
3396            // process wrote was closed (or synced) by the command itself.
3397            unsafe { libc::_exit(code) }
3398        }
3399    }
3400    let _ = code;
3401}
3402
3403pub fn o1_far_sums_on() -> bool {
3404    #[cfg(feature = "cuda")]
3405    if backend() == Backend::Cuda {
3406        return std::env::var("CMF_O1_FAR_GPU").as_deref() != Ok("0") && crate::gpu_cuda::ctx_ready();
3407    }
3408    false
3409}
3410
3411/// One sealed layer's far sums on the card: `nkv` groups of `hpk` heads, `m`
3412/// landmarks each (`qt` [head][m][hd]), over the far rows `idx` (in the
3413/// replay's order) of each group's keys and values (`ks[g]`, `vs[g]`
3414/// [row][hd]). Per head, the replay's largest logits then masses
3415/// (`[head][2m]`) and numerators (`[head][m][hd]`); None when the card does
3416/// not take it.
3417#[allow(clippy::too_many_arguments)]
3418pub fn o1_far_sums(nkv: usize, hpk: usize, hd: usize, m: usize, scale: f32, qt: &[f32], idx: &[u32], ks: &[&[f32]], vs: &[&[f32]]) -> Option<(Vec<f32>, Vec<f32>)> {
3419    #[cfg(feature = "cuda")]
3420    if backend() == Backend::Cuda {
3421        return crate::gpu_cuda::o1_far_sums(nkv, hpk, hd, m, scale, qt, idx, ks, vs);
3422    }
3423    let _ = (nkv, hpk, hd, m, scale, qt, idx, ks, vs);
3424    None
3425}
3426
3427/// Copy sealed prompt chunks' rows to host memory until `o1_acap_end`. A
3428/// backend may keep one query row in `stride` by position (CUDA, wgpu), the
3429/// rows the archive's trace keeps; the others hand back every row.
3430pub fn o1_acap_begin(_stride: usize) {
3431    #[cfg(feature = "cuda")]
3432    if backend() == Backend::Cuda {
3433        crate::gpu_cuda::o1_acap_begin(_stride);
3434    }
3435    #[cfg(feature = "gpu")]
3436    if backend() == Backend::Wgpu {
3437        crate::gpu_wgpu::o1_acap_begin(_stride);
3438    }
3439    #[cfg(target_os = "macos")]
3440    if backend() == Backend::Metal {
3441        crate::gpu_metal::o1c::acap_begin();
3442    }
3443}
3444
3445pub fn o1_acap_end() {
3446    #[cfg(feature = "cuda")]
3447    if backend() == Backend::Cuda {
3448        crate::gpu_cuda::o1_acap_end();
3449    }
3450    #[cfg(feature = "gpu")]
3451    if backend() == Backend::Wgpu {
3452        crate::gpu_wgpu::o1_acap_end();
3453    }
3454    #[cfg(target_os = "macos")]
3455    if backend() == Backend::Metal {
3456        crate::gpu_metal::o1c::cap_end();
3457    }
3458}
3459
3460/// Entries the archive capture holds, not yet taken; 0 where a backend has no
3461/// such queue (`o1_acap_take_first`).
3462pub fn o1_acap_pending() -> usize {
3463    #[cfg(feature = "gpu")]
3464    if backend() == Backend::Wgpu {
3465        return crate::gpu_wgpu::o1_acap_pending();
3466    }
3467    0
3468}
3469
3470/// The oldest `n` entries of the archive capture, a chunk's rows while the chunk
3471/// after it runs (wgpu); elsewhere every row, as `o1_acap_take`.
3472pub fn o1_acap_take_first(_n: usize) -> Option<Vec<(usize, Vec<f32>, Vec<f32>, Vec<f32>)>> {
3473    #[cfg(feature = "gpu")]
3474    if backend() == Backend::Wgpu {
3475        return crate::gpu_wgpu::o1_acap_take_first(_n);
3476    }
3477    o1_acap_take()
3478}
3479
3480/// The rows captured since the last call: (layer, queries, keys, values).
3481pub fn o1_acap_take() -> Option<Vec<(usize, Vec<f32>, Vec<f32>, Vec<f32>)>> {
3482    #[cfg(feature = "cuda")]
3483    if backend() == Backend::Cuda {
3484        return crate::gpu_cuda::o1_acap_take();
3485    }
3486    #[cfg(feature = "gpu")]
3487    if backend() == Backend::Wgpu {
3488        return crate::gpu_wgpu::o1_acap_take();
3489    }
3490    #[cfg(target_os = "macos")]
3491    if backend() == Backend::Metal {
3492        return Some(crate::gpu_metal::o1c::cap_take());
3493    }
3494    None
3495}
3496
3497/// End the capture and read what is left: per layer, rows of the calls since
3498/// `o1_qcap_begin`, position-major `[rows × nh × hd]`.
3499pub fn o1_qcap_take() -> Option<Vec<(usize, Vec<f32>)>> {
3500    #[cfg(feature = "gpu")]
3501    if backend() == Backend::Wgpu {
3502        return crate::gpu_wgpu::o1_qcap_take();
3503    }
3504    #[cfg(feature = "cuda")]
3505    if backend() == Backend::Cuda {
3506        return crate::gpu_cuda::o1_qcap_take();
3507    }
3508    None
3509}
3510
3511/// One GDN layer's recurrent state as the wgpu graph holds it, in the host
3512/// `linear_state` layout ([conv ring | S]).
3513pub fn graph_gdn_state_read(_kv_id: u64, _layer: usize) -> Option<Vec<f32>> {
3514    #[cfg(feature = "cuda")]
3515    if backend() == Backend::Cuda {
3516        return crate::gpu_cuda::gdn_state_read(_kv_id, _layer);
3517    }
3518    #[cfg(feature = "gpu")]
3519    if backend() == Backend::Wgpu {
3520        return crate::gpu_wgpu::graph_gdn_state_read(_kv_id, _layer);
3521    }
3522    None
3523}
3524
3525/// Copy rows back from the wgpu token graph's K/V mirrors in one submit:
3526/// for each `(layer, from, to)` the K and V rows `[from..to)`, position-major
3527/// (`[(to − from) × nkv × hd]` each).
3528pub fn graph_kv_read_rows(
3529    _kv_id: u64,
3530    _reqs: &[(usize, usize, usize)],
3531    _nkv: usize,
3532    _hd: usize,
3533) -> Option<Vec<(Vec<f32>, Vec<f32>)>> {
3534    #[cfg(feature = "cuda")]
3535    if backend() == Backend::Cuda {
3536        return crate::gpu_cuda::kv_read_rows(_kv_id, _reqs, _nkv, _hd);
3537    }
3538    #[cfg(feature = "gpu")]
3539    if backend() == Backend::Wgpu {
3540        return crate::gpu_wgpu::kv_mirror_read_rows(_kv_id, _reqs, _nkv, _hd);
3541    }
3542    None
3543}
3544
3545/// Rows `[from, to)` of one wgpu exact-attention mirror in the host
3546/// cache's layout (V zero-padded to `hd`), whatever the mirror's geometry
3547/// (narrow V, a sliding layer's ring). The third value is the first
3548/// position actually read: a ring returns zeros below it. None: no wgpu
3549/// mirror holding those rows at (nkv, hd).
3550pub fn graph_kv_pull_host(
3551    _kv_id: u64,
3552    _layer: usize,
3553    _from: usize,
3554    _to: usize,
3555    _nkv: usize,
3556    _hd: usize,
3557) -> Option<(Vec<f32>, Vec<f32>, usize)> {
3558    #[cfg(feature = "cuda")]
3559    if backend() == Backend::Cuda {
3560        return crate::gpu_cuda::kv_pull_host(_kv_id, _layer, _from, _to, _nkv, _hd);
3561    }
3562    #[cfg(feature = "gpu")]
3563    if backend() == Backend::Wgpu {
3564        return crate::gpu_wgpu::kv_mirror_pull_host(_kv_id, _layer, _from, _to, _nkv, _hd);
3565    }
3566    None
3567}
3568
3569/// The next batch graph call on this thread submits without reading its
3570/// rows back (`gpu_wgpu::set_batch_defer`): a prompt chunk nobody reads.
3571pub fn set_batch_defer(_on: bool) {
3572    #[cfg(feature = "cuda")]
3573    if backend() == Backend::Cuda {
3574        crate::gpu_cuda::set_batch_defer(_on);
3575    }
3576    #[cfg(feature = "gpu")]
3577    if backend() == Backend::Wgpu {
3578        crate::gpu_wgpu::set_batch_defer(_on);
3579    }
3580}
3581
3582/// The prompt length the batch graph sizes its K/V mirrors for
3583/// (`gpu_wgpu::set_batch_kv_hint`); 0 clears it.
3584pub fn set_batch_kv_hint(_rows: usize) {
3585    #[cfg(feature = "cuda")]
3586    if backend() == Backend::Cuda {
3587        crate::gpu_cuda::set_batch_kv_hint(_rows);
3588    }
3589    #[cfg(feature = "gpu")]
3590    if backend() == Backend::Wgpu {
3591        crate::gpu_wgpu::set_batch_kv_hint(_rows);
3592    }
3593}
3594
3595thread_local! {
3596    /// A Looped Transformer's batch-graph call (`set_batch_loop_norm`).
3597    static BATCH_LOOP: std::cell::RefCell<Option<(Vec<usize>, std::sync::Arc<Vec<f32>>)>> = const { std::cell::RefCell::new(None) };
3598}
3599
3600/// A Looped Transformer's next batch-graph calls on this thread: the
3601/// span-relative layers after which the final norm goes on the stream
3602/// (`loop_norm_at` of the token graph), and that norm; `None` clears it. A
3603/// backend that cannot apply them declines the call.
3604pub fn set_batch_loop_norm(v: Option<(Vec<usize>, Vec<f32>)>) {
3605    BATCH_LOOP.with(|b| *b.borrow_mut() = v.map(|(at, w)| (at, std::sync::Arc::new(w))));
3606}
3607
3608/// The loop norms `set_batch_loop_norm` armed (`None`: a plain stack).
3609pub(crate) fn batch_loop_norm() -> Option<(Vec<usize>, std::sync::Arc<Vec<f32>>)> {
3610    BATCH_LOOP.with(|b| b.borrow().clone()).filter(|(at, _)| !at.is_empty())
3611}
3612
3613/// Whether a sequence's wgpu K/V mirrors may be f16 (`gpu_wgpu::kv16`):
3614/// the first note after a reset decides.
3615pub fn graph_kv16_note(_kv_id: u64, _allowed: bool) {
3616    #[cfg(feature = "gpu")]
3617    if backend() == Backend::Wgpu {
3618        crate::gpu_wgpu::kv16::note(_kv_id, _allowed);
3619    }
3620}
3621
3622/// Drop the wgpu token graph's device K/V mirror for a pipeline.
3623pub fn graph_kv_reset(_kv_id: u64) {
3624    #[cfg(feature = "cuda")]
3625    if backend() == Backend::Cuda {
3626        crate::gpu_cuda::kv_reset(_kv_id);
3627        crate::gpu_cuda::embryo_graph_reset(_kv_id);
3628    }
3629    #[cfg(feature = "gpu")]
3630    if backend() == Backend::Wgpu {
3631        crate::gpu_wgpu::kv_mirror_reset(_kv_id);
3632        crate::gpu_wgpu::embryo_graph_reset(_kv_id);
3633    }
3634}
3635
3636/// Ternary (q1t) BASE matvec on the GPU — fills `out` with the base dot; the
3637/// caller adds the sparse overlay on the CPU. Metal only for now (wgpu q1t not
3638/// yet written → CPU fallback).
3639pub fn q1t_matvec(
3640    model: &Arc<CmfModel>,
3641    idx: usize,
3642    xs: &[f32],
3643    rows: usize,
3644    cols: usize,
3645    out: &mut [f32],
3646) -> bool {
3647    match backend() {
3648        #[cfg(target_os = "macos")]
3649        Backend::Metal => {
3650            if metal_q1t_enabled() {
3651                crate::gpu_metal::q1t_matvec(model, idx, xs, rows, cols, out)
3652            } else {
3653                false
3654            }
3655        }
3656        #[cfg(feature = "gpu")]
3657        Backend::Wgpu => crate::gpu_wgpu::q1t_matvec(model, idx, xs, rows, cols, out),
3658        Backend::None => false,
3659        #[cfg(feature = "cuda")]
3660        Backend::Cuda => false,
3661    }
3662}
3663
3664/// q4_block matvec on the GPU — wgpu only (Metal drives q4_block through the
3665/// whole-token graph, not a standalone matvec).
3666#[allow(unused_variables)]
3667pub fn q4b_matvec(
3668    model: &Arc<CmfModel>,
3669    idx: usize,
3670    xs: &[f32],
3671    rows: usize,
3672    cols: usize,
3673    out: &mut [f32],
3674) -> bool {
3675    match backend() {
3676        #[cfg(target_os = "macos")]
3677        Backend::Metal => false,
3678        #[cfg(feature = "gpu")]
3679        Backend::Wgpu => crate::gpu_wgpu::q4b_matvec(model, idx, xs, rows, cols, out),
3680        Backend::None => false,
3681        #[cfg(feature = "cuda")]
3682        Backend::Cuda => false,
3683    }
3684}
3685
3686/// q1t batched GEMM (prefill) — base + overlay on-device (Metal simdgroup or
3687/// wgpu register-blocked).
3688pub fn q1t_matmat(
3689    model: &Arc<CmfModel>,
3690    idx: usize,
3691    xs: &[f32],
3692    b: usize,
3693    rows: usize,
3694    cols: usize,
3695    out: &mut [f32],
3696) -> bool {
3697    match backend() {
3698        #[cfg(target_os = "macos")]
3699        // Batched prefill and single-token decode are both enabled. On the
3700        // real 14.8B Q1T model prefill PPL was within 0.3% of CPU (7.942 vs
3701        // 7.966), and the alignment-safe decode kernel reached 3.52e-6 max_rel.
3702        Backend::Metal => crate::gpu_metal::q1t_matmat(model, idx, xs, b, rows, cols, out),
3703        #[cfg(feature = "gpu")]
3704        Backend::Wgpu => crate::gpu_wgpu::q1t_matmat(model, idx, xs, b, rows, cols, out),
3705        Backend::None => false,
3706        #[cfg(feature = "cuda")]
3707        Backend::Cuda => false,
3708    }
3709}
3710
3711/// Native Metal Q1T switch. Enabled by default after the byte-packed Q1T
3712/// fields were changed to alignment-safe loads; keep an explicit emergency
3713/// fallback for device/driver diagnostics.
3714#[cfg(target_os = "macos")]
3715pub(crate) fn metal_q1t_enabled() -> bool {
3716    std::env::var("CMF_METAL_Q1T")
3717        .map(|v| v != "0" && !v.eq_ignore_ascii_case("off"))
3718        .unwrap_or(true)
3719}
3720
3721/// Batched q1 GEMM (prefill). wgpu only — Metal has its own block path.
3722pub fn q1_matmat(
3723    model: &Arc<CmfModel>,
3724    idx: usize,
3725    xs: &[f32],
3726    b: usize,
3727    rows: usize,
3728    cols: usize,
3729    out: &mut [f32],
3730) -> bool {
3731    match backend() {
3732        #[cfg(feature = "gpu")]
3733        Backend::Wgpu => crate::gpu_wgpu::q1_matmat(model, idx, xs, b, rows, cols, out),
3734        #[allow(unused_variables)]
3735        _ => false,
3736    }
3737}
3738
3739/// Batched q1g GEMM (prefill). wgpu only, like `q1_matmat`.
3740pub fn q1g_matmat(
3741    model: &Arc<CmfModel>,
3742    idx: usize,
3743    xs: &[f32],
3744    b: usize,
3745    rows: usize,
3746    cols: usize,
3747    out: &mut [f32],
3748) -> bool {
3749    match backend() {
3750        #[cfg(feature = "gpu")]
3751        Backend::Wgpu => crate::gpu_wgpu::q1g_matmat(model, idx, xs, b, rows, cols, out),
3752        #[allow(unused_variables)]
3753        _ => false,
3754    }
3755}
3756
3757/// Contention kill for the wide imagegen GEMM/FFN paths: one grossly
3758/// slow op under a work-proportional budget (fair-device ops are
3759/// ≤~100 ms even at 1024px) means another process owns the device —
3760/// verdicts are per-process, so CPU for the rest of this one.
3761static MM_KILL: AtomicBool = AtomicBool::new(false);
3762pub(crate) fn mm_killed() -> bool {
3763    MM_KILL.load(Ordering::Relaxed)
3764}
3765pub(crate) fn mm_kill() {
3766    MM_KILL.store(true, Ordering::Relaxed);
3767}
3768
3769/// Consecutive over-budget ops. ONE slow op is not contention: on a
3770/// 24 GB Mac running the 25.7 GB fl2va file the first ops after the
3771/// prompt encode page their weights in from the SSD and take seconds —
3772/// a field report (hololabs, HF discussion #2) had to neuter the kill
3773/// to keep the denoise on the GPU, and then measured 48 s/step where the
3774/// CPU fallback took >60. Contention is persistent; a page-in is not.
3775static MM_STRIKES: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
3776const MM_STRIKES_TO_KILL: u32 = 3;
3777/// Whether the kill is armed at all. A one-shot phase whose slowness is
3778/// expected and not contention — the video prompt encoder streaming
3779/// 12 GB off the SSD on a 24 GB Mac (HF discussion #4: users had to
3780/// gut `mm_kill` to keep the denoise loop on the GPU) — disarms it and
3781/// re-arms it when the phase is over; strikes taken meanwhile are
3782/// forgotten.
3783static MM_ARMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
3784
3785/// Disarm / re-arm the contention kill around a phase whose GEMMs are
3786/// slow for reasons that are not another process (see `MM_ARMED`).
3787pub fn mm_kill_arm(on: bool) {
3788    MM_ARMED.store(on, Ordering::Relaxed);
3789    if on {
3790        MM_STRIKES.store(0, Ordering::Relaxed);
3791    }
3792}
3793
3794/// The contention verdict for one wide op: `el` against its
3795/// work-proportional `budget`. `exempt` marks ops whose time is not
3796/// evidence — the cold probe, or a weight that was not resident before
3797/// the call and rode in with it. Kills after `MM_STRIKES_TO_KILL`
3798/// consecutive strikes; a within-budget op clears the count.
3799/// `CMF_MM_KILL=0` disables the kill entirely (the device is trusted).
3800pub(crate) fn mm_budget_check(
3801    what: &str,
3802    el: std::time::Duration,
3803    budget: std::time::Duration,
3804    exempt: bool,
3805) {
3806    if el <= budget {
3807        MM_STRIKES.store(0, Ordering::Relaxed);
3808        return;
3809    }
3810    if exempt || !MM_ARMED.load(Ordering::Relaxed) {
3811        return;
3812    }
3813    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3814    let on = *ON.get_or_init(|| std::env::var("CMF_MM_KILL").as_deref() != Ok("0"));
3815    let n = MM_STRIKES.fetch_add(1, Ordering::Relaxed) + 1;
3816    if !on {
3817        tracing::info!(
3818            "gpu {what} took {el:?} (budget {budget:?}) — over budget, CMF_MM_KILL=0 keeps the device"
3819        );
3820        return;
3821    }
3822    if n >= MM_STRIKES_TO_KILL {
3823        tracing::warn!(
3824            "gpu {what} took {el:?} (budget {budget:?}), {n} in a row — \
3825             device contended, CPU for the rest of the process (CMF_MM_KILL=0 to override)"
3826        );
3827        mm_kill();
3828    } else {
3829        tracing::info!(
3830            "gpu {what} took {el:?} (budget {budget:?}) — strike {n} of {MM_STRIKES_TO_KILL}"
3831        );
3832    }
3833}
3834
3835/// Fused DiT SwiGLU FFN on the device: g=X·W1ᵀ, u=X·W3ᵀ, silu(g)·u,
3836/// Causal chunk attention on the device: `b` queries against `s0 + b`
3837/// cached keys. wgpu only — Metal's chunk graph keeps attention inside
3838/// the resident block and never calls out.
3839#[allow(unused_variables, clippy::too_many_arguments)]
3840pub fn chunk_attend(
3841    q: &[f32],
3842    k: &[&[f32]],
3843    v: &[&[f32]],
3844    b: usize,
3845    s0: usize,
3846    nh: usize,
3847    nkv: usize,
3848    hd: usize,
3849    scale: f32,
3850    out: &mut [f32],
3851) -> bool {
3852    match backend() {
3853        #[cfg(feature = "gpu")]
3854        Backend::Wgpu => crate::gpu_wgpu::chunk_attend(q, k, v, b, s0, nh, nkv, hd, scale, out),
3855        #[allow(unreachable_patterns)]
3856        _ => false,
3857    }
3858}
3859
3860/// `chunk_attend` under a sliding window (`window` keys, the query's own
3861/// included). wgpu only; see `chunk_attend_windowed`.
3862#[allow(unused_variables, clippy::too_many_arguments)]
3863pub fn chunk_attend_win(
3864    q: &[f32],
3865    k: &[&[f32]],
3866    v: &[&[f32]],
3867    b: usize,
3868    s0: usize,
3869    nh: usize,
3870    nkv: usize,
3871    hd: usize,
3872    scale: f32,
3873    window: usize,
3874    out: &mut [f32],
3875) -> bool {
3876    match backend() {
3877        #[cfg(feature = "gpu")]
3878        Backend::Wgpu => {
3879            crate::gpu_wgpu::chunk_attend_win(q, k, v, b, s0, nh, nkv, hd, scale, window, out)
3880        }
3881        #[allow(unreachable_patterns)]
3882        _ => false,
3883    }
3884}
3885
3886/// Several projections of one host activation, read back in one trip:
3887/// `out` = [P0 | P1 | …], each `idxs` entry (tensor, rows). wgpu only.
3888#[allow(unused_variables)]
3889pub fn gemm_many_keep(
3890    model: &Arc<CmfModel>,
3891    idxs: &[(usize, usize)],
3892    xs: &[f32],
3893    b: usize,
3894    cols: usize,
3895    out: &mut [f32],
3896) -> bool {
3897    match backend() {
3898        #[cfg(feature = "gpu")]
3899        Backend::Wgpu => crate::gpu_wgpu::gemm_many_keep(model, idxs, xs, b, cols, out),
3900        #[allow(unreachable_patterns)]
3901        _ => false,
3902    }
3903}
3904
3905thread_local! {
3906    /// Set by the pipeline around a layer of Spark-X2.5's batched prefill:
3907    /// its int8 matrix-unit GEMMs may take the `zi_mm` tile, and the
3908    /// projections that read one activation share its upload (wgpu).
3909    static PREFILL_FAST_GEMM: Cell<bool> = const { Cell::new(false) };
3910}
3911
3912/// Restores the previous flag on drop.
3913pub struct PrefillFastGemmGuard(bool);
3914
3915impl Drop for PrefillFastGemmGuard {
3916    fn drop(&mut self) {
3917        PREFILL_FAST_GEMM.with(|c| c.set(self.0));
3918    }
3919}
3920
3921/// Let this thread's int8 matrix-unit GEMMs take the `zi_mm` tile for the
3922/// guard's lifetime (bit-identical to the 64x64 kernel; see
3923/// `gpu_wgpu::zi_gemm_route`).
3924pub fn enter_prefill_fast_gemm() -> PrefillFastGemmGuard {
3925    PrefillFastGemmGuard(PREFILL_FAST_GEMM.with(|c| c.replace(true)))
3926}
3927
3928/// Whether `enter_prefill_fast_gemm` is in force on this thread.
3929pub fn prefill_fast_gemm() -> bool {
3930    PREFILL_FAST_GEMM.with(|c| c.get())
3931}
3932
3933/// The largest finite f16. An operand the matrix-unit attention casts to
3934/// f16 must stay within it, or the cast overflows to inf.
3935pub const F16_MAX: f32 = 65504.0;
3936
3937/// max |x| over `xs`, or +inf when an entry is inf or NaN: the value the
3938/// f16 operand guards compare with `F16_MAX`. Sixteen independent lanes
3939/// and a flag, so it vectorizes (a single `fold` chain does not).
3940pub fn abs_max_or_inf(xs: &[f32]) -> f32 {
3941    let mut acc = [0f32; 16];
3942    let mut bad = [false; 16];
3943    let mut it = xs.chunks_exact(16);
3944    for c in &mut it {
3945        for ((a, f), &v) in acc.iter_mut().zip(bad.iter_mut()).zip(c) {
3946            let v = v.abs();
3947            // NaN compares false both ways: flagged, never taken.
3948            *f |= !(v < f32::INFINITY);
3949            *a = if v > *a { v } else { *a };
3950        }
3951    }
3952    let mut m = 0f32;
3953    for &v in it.remainder() {
3954        let v = v.abs();
3955        if !(v < f32::INFINITY) {
3956            return f32::INFINITY;
3957        }
3958        m = m.max(v);
3959    }
3960    if bad.iter().any(|&f| f) {
3961        return f32::INFINITY;
3962    }
3963    acc.iter().fold(m, |m, &a| m.max(a))
3964}
3965
3966/// One GDN layer's block-preview weights (`linear_core::GdnPreviewWeights`).
3967#[derive(Clone, Copy)]
3968pub struct GdnPreviewW<'a> {
3969    /// [cdim · (kk−1)], flattened [c][distance−1].
3970    pub conv_right: &'a [f32],
3971    pub logit_scale: &'a [f32],
3972    pub history_bias: &'a [f32],
3973    pub history_c: &'a [f32],
3974}
3975
3976/// A block-diffusion preview through the batched graph (Clover): every
3977/// row attends the whole block, GDN layers run the preview operator, the
3978/// MoE routes inside the block's expert coreset, and nothing the graph
3979/// reads is advanced — the KV rows it writes past the synced count are
3980/// overwritten by the next commit.
3981#[derive(Clone, Copy, Debug, PartialEq)]
3982pub struct BlockPreview {
3983    /// `Some(top_p)`: restrict routing to the block coreset.
3984    pub coreset_top_p: Option<f32>,
3985}
3986
3987thread_local! {
3988    static BLOCK_PREVIEW: Cell<Option<BlockPreview>> = const { Cell::new(None) };
3989}
3990
3991/// Restores the previous mode on drop.
3992pub struct BlockPreviewGuard(Option<BlockPreview>);
3993
3994impl Drop for BlockPreviewGuard {
3995    fn drop(&mut self) {
3996        BLOCK_PREVIEW.with(|c| c.set(self.0));
3997    }
3998}
3999
4000/// Run the batched graph calls of this thread as block previews.
4001pub fn enter_block_preview(p: BlockPreview) -> BlockPreviewGuard {
4002    BlockPreviewGuard(BLOCK_PREVIEW.with(|c| c.replace(Some(p))))
4003}
4004
4005/// The preview mode `enter_block_preview` set on this thread, if any.
4006pub fn block_preview() -> Option<BlockPreview> {
4007    BLOCK_PREVIEW.with(|c| c.get())
4008}
4009
4010/// The decode graph's device K/V mirror a prefill chunk of one layer also
4011/// writes to (wgpu): `kv_id` is the pipeline's graph id, `layer` the
4012/// virtual layer index, `limit` the cache's `max_seq_len` — the same key
4013/// and capacity ceiling the token graph uses, so the mirror the prefill
4014/// fills is the one the first decode token reads.
4015#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4016pub struct PrefillMirror {
4017    pub kv_id: u64,
4018    pub layer: usize,
4019    pub limit: usize,
4020}
4021
4022thread_local! {
4023    /// Set by the pipeline around one layer's batched attention (see
4024    /// `enter_prefill_mirror`); every other caller of the batched
4025    /// attention (MTP heads, tests) sees None and keeps the host upload.
4026    static PREFILL_MIRROR: Cell<Option<PrefillMirror>> = const { Cell::new(None) };
4027}
4028
4029/// Restores the previous target on drop.
4030pub struct PrefillMirrorGuard(Option<PrefillMirror>);
4031
4032impl Drop for PrefillMirrorGuard {
4033    fn drop(&mut self) {
4034        PREFILL_MIRROR.with(|c| c.set(self.0));
4035    }
4036}
4037
4038/// Name the device mirror the current layer's prefill chunk appends to
4039/// and attends against, for the guard's lifetime.
4040pub fn enter_prefill_mirror(t: PrefillMirror) -> PrefillMirrorGuard {
4041    PrefillMirrorGuard(PREFILL_MIRROR.with(|c| c.replace(Some(t))))
4042}
4043
4044/// The mirror `enter_prefill_mirror` named on this thread, if any.
4045pub fn prefill_mirror() -> Option<PrefillMirror> {
4046    PREFILL_MIRROR.with(|c| c.get())
4047}
4048
4049/// `chunk_attend_win` against the decode graph's device mirror instead of
4050/// an upload of the whole prefix: the host rows the mirror lacks (the
4051/// chunk's own `b`, or more after a host-only chunk) are appended first,
4052/// then the attention binds the mirror rows in place. `s0` is the chunk's
4053/// first position and `base` the position of host row 0
4054/// (`LayerKvCache::base`: past 0 on a trimmed sliding tail). `ring` is the
4055/// layer's window as the mirror geometry (Some on every sliding layer),
4056/// `window` the window the softmax masks with (0 while it masks nothing).
4057/// `operand_max` = max |x| over `q` and every K/V row the attend reads
4058/// (`abs_max_or_inf`; +inf when unknown): past `F16_MAX` the f32 kernels
4059/// run instead of the matrix units. wgpu only; false = nothing attended
4060/// (the caller uploads as before).
4061#[allow(unused_variables, clippy::too_many_arguments)]
4062pub fn chunk_attend_mirror(
4063    t: PrefillMirror,
4064    cpu_k: &[Vec<f32>],
4065    cpu_v: &[Vec<f32>],
4066    base: usize,
4067    q: &[f32],
4068    b: usize,
4069    s0: usize,
4070    nh: usize,
4071    nkv: usize,
4072    hd: usize,
4073    scale: f32,
4074    ring: Option<usize>,
4075    window: usize,
4076    operand_max: f32,
4077    out: &mut [f32],
4078) -> bool {
4079    match backend() {
4080        #[cfg(feature = "gpu")]
4081        // QKᵀ and P·V on the matrix units where the device has them (f16
4082        // operands, f32 accumulators — not bit-identical to the f32
4083        // kernels: Spark-X2.5 4B q8_2f wiki ppl 10.677 -> 10.672);
4084        // `CMF_PREFILL_ATTN_COOP=0` keeps the f32 ones (A/B).
4085        Backend::Wgpu => crate::gpu_wgpu::chunk_attend_mirror(
4086            t.kv_id,
4087            t.layer,
4088            t.limit,
4089            cpu_k,
4090            cpu_v,
4091            base,
4092            q,
4093            b,
4094            s0,
4095            nh,
4096            nkv,
4097            hd,
4098            scale,
4099            ring,
4100            window,
4101            std::env::var("CMF_PREFILL_ATTN_COOP").as_deref() != Ok("0"),
4102            operand_max,
4103            out,
4104        ),
4105        #[allow(unreachable_patterns)]
4106        _ => false,
4107    }
4108}
4109
4110/// `chunk_attend_mirror`, then the head gate (`gains`, b × nh, computed on
4111/// the host) and the O projection `wo` on the card: the attention output
4112/// never comes home. `out` = [b][hidden]. The card scans the O operand
4113/// itself, which is the host path's product bit for bit only while max
4114/// |gated output| <= 1000: the caller vouches for that (Spark-X2.5's
4115/// prefill, max |v| <= 990). wgpu only; false = nothing written to `out`
4116/// (the caller attends and projects as before).
4117#[allow(unused_variables, clippy::too_many_arguments)]
4118pub fn chunk_attend_mirror_wo(
4119    t: PrefillMirror,
4120    cpu_k: &[Vec<f32>],
4121    cpu_v: &[Vec<f32>],
4122    base: usize,
4123    q: &[f32],
4124    b: usize,
4125    s0: usize,
4126    nh: usize,
4127    nkv: usize,
4128    hd: usize,
4129    scale: f32,
4130    ring: Option<usize>,
4131    window: usize,
4132    operand_max: f32,
4133    gains: Option<&[f32]>,
4134    wo: (&Arc<CmfModel>, usize),
4135    hidden: usize,
4136    out: &mut [f32],
4137) -> bool {
4138    match backend() {
4139        #[cfg(feature = "gpu")]
4140        Backend::Wgpu => crate::gpu_wgpu::chunk_attend_mirror_wo(
4141            t.kv_id,
4142            t.layer,
4143            t.limit,
4144            cpu_k,
4145            cpu_v,
4146            base,
4147            q,
4148            b,
4149            s0,
4150            nh,
4151            nkv,
4152            hd,
4153            scale,
4154            ring,
4155            window,
4156            std::env::var("CMF_PREFILL_ATTN_COOP").as_deref() != Ok("0"),
4157            operand_max,
4158            gains,
4159            wo,
4160            hidden,
4161            out,
4162        ),
4163        #[allow(unreachable_patterns)]
4164        _ => false,
4165    }
4166}
4167
4168/// Whether the active backend's chunk attend can apply a sliding window.
4169pub fn chunk_attend_windowed() -> bool {
4170    match backend() {
4171        #[cfg(feature = "gpu")]
4172        Backend::Wgpu => true,
4173        #[allow(unreachable_patterns)]
4174        _ => false,
4175    }
4176}
4177
4178/// Fused QKV projection: one upload of the normed chunk, three GEMMs,
4179/// one readback of Q|K|V back to back. Metal has no twin yet — its
4180/// chunk graph keeps the whole layer resident and never surfaces QKV.
4181#[allow(unused_variables, clippy::too_many_arguments)]
4182pub fn q4t_qkv(
4183    model: &Arc<CmfModel>,
4184    wq: usize,
4185    wk: usize,
4186    wv: usize,
4187    xs: &[f32],
4188    b: usize,
4189    cols: usize,
4190    rq: usize,
4191    rk: usize,
4192    rv: usize,
4193    out: &mut [f32],
4194) -> bool {
4195    match backend() {
4196        #[cfg(feature = "gpu")]
4197        Backend::Wgpu => crate::gpu_wgpu::q4t_qkv(model, wq, wk, wv, xs, b, cols, rq, rk, rv, out),
4198        #[allow(unreachable_patterns)]
4199        _ => false,
4200    }
4201}
4202
4203/// y=·W2ᵀ — one command buffer, only X and Y cross the CPU boundary.
4204#[allow(unused_variables, clippy::too_many_arguments)]
4205/// SwiGLU FFN with a row-packed [gate|up] fc1 (MiniMax-H3's DiT), run
4206/// end to end on the device. wgpu only: Metal keeps the host loop until
4207/// its own packed kernel exists.
4208#[allow(clippy::too_many_arguments, unused_variables)]
4209pub fn q4tp_ffn_packed(
4210    model: &Arc<CmfModel>,
4211    w1: usize,
4212    w2: usize,
4213    xs: &[f32],
4214    b: usize,
4215    hidden: usize,
4216    inter: usize,
4217    bias: Option<&[f32]>,
4218    out: &mut [f32],
4219) -> bool {
4220    match backend() {
4221        #[cfg(feature = "gpu")]
4222        Backend::Wgpu => {
4223            crate::gpu_wgpu::ffn_packed(model, w1, w2, xs, b, hidden, inter, bias, out)
4224        }
4225        #[allow(unreachable_patterns)]
4226        _ => false,
4227    }
4228}
4229
4230pub fn q4tp_ffn(
4231    model: &Arc<CmfModel>,
4232    w1: usize,
4233    w3: usize,
4234    w2: usize,
4235    xs: &[f32],
4236    b: usize,
4237    hidden: usize,
4238    inter: usize,
4239    out: &mut [f32],
4240) -> bool {
4241    match backend() {
4242        #[cfg(target_os = "macos")]
4243        Backend::Metal => crate::gpu_metal::q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4244        #[cfg(feature = "gpu")]
4245        Backend::Wgpu => crate::gpu_wgpu::q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4246        #[allow(unreachable_patterns)]
4247        _ => false,
4248    }
4249}
4250
4251/// `q4tp_ffn` (`q4tp` = true) / `q4t_ffn` with the activation named:
4252/// SiLU takes the plain entry points (every backend), the exact GELU of
4253/// Spark-X2.5 has a wgpu arm only — other backends decline it.
4254#[allow(clippy::too_many_arguments, unused_variables)]
4255pub fn q4_ffn_act(
4256    model: &Arc<CmfModel>,
4257    w1: usize,
4258    w3: usize,
4259    w2: usize,
4260    xs: &[f32],
4261    b: usize,
4262    hidden: usize,
4263    inter: usize,
4264    q4tp: bool,
4265    act: GraphAct,
4266    out: &mut [f32],
4267) -> bool {
4268    match act {
4269        GraphAct::Silu if q4tp => q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4270        GraphAct::Silu => q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4271        // The graph FFN's M3 OAI contract is WGPU-only.  Metal reaches its
4272        // separate direct-MoE kernel through `moe_block`; falling through to
4273        // q4tp_ffn here would silently turn it into ordinary SiLU.
4274        GraphAct::GeluErf | GraphAct::GeluTanh | GraphAct::SwiGluOaiM3 => match backend() {
4275            #[cfg(feature = "gpu")]
4276            Backend::Wgpu => crate::gpu_wgpu::q4_ffn_act(
4277                model,
4278                w1,
4279                w3,
4280                w2,
4281                xs,
4282                b,
4283                hidden,
4284                inter,
4285                q4tp,
4286                act.code(),
4287                out,
4288            ),
4289            #[allow(unreachable_patterns)]
4290            _ => false,
4291        },
4292    }
4293}
4294
4295/// The LLM prefill's dense FFN for separate gate/up/down weights in any
4296/// codec with a device GEMM (int8, q4tp, or a mix of them): the panels
4297/// stay on the card between the projections. wgpu only; other backends
4298/// decline and the caller keeps its per-GEMM path.
4299#[allow(clippy::too_many_arguments, unused_variables)]
4300pub fn ffn_act_keep(
4301    model: &Arc<CmfModel>,
4302    w1: usize,
4303    w3: usize,
4304    w2: usize,
4305    xs: &[f32],
4306    b: usize,
4307    hidden: usize,
4308    inter: usize,
4309    act: GraphAct,
4310    out: &mut [f32],
4311) -> bool {
4312    match backend() {
4313        #[cfg(feature = "gpu")]
4314        Backend::Wgpu => crate::gpu_wgpu::ffn_act_keep(
4315            model,
4316            w1,
4317            w3,
4318            w2,
4319            xs,
4320            b,
4321            hidden,
4322            inter,
4323            act.code(),
4324            out,
4325        ),
4326        #[allow(unreachable_patterns)]
4327        _ => false,
4328    }
4329}
4330
4331/// Qwen Image's exact two-projection tanh-GELU FFN.  The WGPU arm keeps the
4332/// intermediate on the device; other backends decline so the caller retains
4333/// its bounded CPU path.  `bias_in` is applied before GELU and `bias_out`
4334/// after the second projection, matching the official transformer.
4335#[allow(clippy::too_many_arguments, unused_variables)]
4336pub fn q4tp_gelu_ffn(
4337    model: &Arc<CmfModel>,
4338    w_in: usize,
4339    w_out: usize,
4340    xs: &[f32],
4341    b: usize,
4342    hidden: usize,
4343    inter: usize,
4344    bias_in: &[f32],
4345    bias_out: &[f32],
4346    out: &mut [f32],
4347) -> bool {
4348    match backend() {
4349        #[cfg(feature = "gpu")]
4350        Backend::Wgpu => crate::gpu_wgpu::q4tp_gelu_ffn(
4351            model, w_in, w_out, xs, b, hidden, inter, bias_in, bias_out, out,
4352        ),
4353        #[allow(unreachable_patterns)]
4354        _ => false,
4355    }
4356}
4357
4358pub fn q4t_ffn(
4359    model: &Arc<CmfModel>,
4360    w1: usize,
4361    w3: usize,
4362    w2: usize,
4363    xs: &[f32],
4364    b: usize,
4365    hidden: usize,
4366    inter: usize,
4367    out: &mut [f32],
4368) -> bool {
4369    match backend() {
4370        #[cfg(target_os = "macos")]
4371        Backend::Metal => crate::gpu_metal::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4372        #[cfg(feature = "gpu")]
4373        Backend::Wgpu => crate::gpu_wgpu::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4374        #[allow(unreachable_patterns)]
4375        _ => false,
4376    }
4377}
4378
4379/// One whole modulated DiT block for `dit_block`: geometry, norm
4380/// weights, AdaLN scale/gate vectors (gates pre-tanh'd), a per-token
4381/// f32 RoPE cos/sin table, and the directory indices of the seven
4382/// q4t projections. `x` is in-out `[n, hidden]`.
4383pub struct DitBlockArgs<'a> {
4384    pub n: usize,
4385    pub hidden: usize,
4386    pub inter: usize,
4387    pub nh: usize,
4388    pub nkv: usize,
4389    pub hd: usize,
4390    pub eps: f32,
4391    pub rope_cos: &'a [f32],
4392    pub rope_sin: &'a [f32],
4393    pub norm1: &'a [f32],
4394    pub norm2: &'a [f32],
4395    pub ffn_norm1: &'a [f32],
4396    pub ffn_norm2: &'a [f32],
4397    pub norm_q: &'a [f32],
4398    pub norm_k: &'a [f32],
4399    pub s_msa: &'a [f32],
4400    pub gate_msa: &'a [f32],
4401    pub s_mlp: &'a [f32],
4402    pub gate_mlp: &'a [f32],
4403    pub wq: usize,
4404    pub wk: usize,
4405    pub wv: usize,
4406    pub wo: usize,
4407    pub w1: usize,
4408    pub w3: usize,
4409    pub w2: usize,
4410    /// The projections' layout: q4tp (ladder scales) vs plain q4_tiled.
4411    /// The recommended Lumina file is q4tp, and a backend that only
4412    /// knows q4t must decline rather than decode with the wrong reader.
4413    pub q4tp: bool,
4414    /// The hidden state is already on the device from the previous block,
4415    /// so `x` need not be uploaded.
4416    pub resident_in: bool,
4417    /// Leave the result on the device instead of reading it back. The DiT
4418    /// loop does not touch `x` between blocks, so 27 of every 28 readbacks
4419    /// were moving 19 MB across PCIe and stalling on it for nothing.
4420    pub resident_out: bool,
4421}
4422
4423/// Can the selected backend keep the DiT's hidden state on the device
4424/// between blocks? Only the wgpu whole-block path; the Metal entry takes
4425/// and returns host memory every call.
4426pub fn dit_chain_supported() -> bool {
4427    #[cfg(feature = "gpu")]
4428    {
4429        return matches!(backend(), Backend::Wgpu) && fused_dit_block_available();
4430    }
4431    #[allow(unreachable_code)]
4432    false
4433}
4434
4435/// Pull the resident hidden state back to the host. For the caller that
4436/// chained blocks and then hit one the device declined.
4437pub fn dit_state_fetch(_x: &mut [f32]) -> bool {
4438    #[cfg(feature = "gpu")]
4439    {
4440        if matches!(backend(), Backend::Wgpu) {
4441            return crate::gpu_wgpu::dit_state_fetch(_x);
4442        }
4443    }
4444    false
4445}
4446
4447/// One whole modulated DiT block on the device — norms, qkv, RoPE,
4448/// attention, residuals and the SwiGLU FFN in a single command
4449/// buffer; only `x` crosses the CPU boundary (in and out).
4450#[allow(unused_variables)]
4451/// The DiT's three projections in one submission (wgpu only; the
4452/// Metal path fuses the whole block instead). False = the caller keeps
4453/// its three separate calls.
4454#[allow(unused_variables, clippy::too_many_arguments)]
4455pub fn dit_qkv(
4456    model: &Arc<CmfModel>,
4457    wq: usize,
4458    wk: usize,
4459    wv: usize,
4460    xs: &[f32],
4461    b: usize,
4462    hidden: usize,
4463    qrows: usize,
4464    kvrows: usize,
4465    q_out: &mut [f32],
4466    k_out: &mut [f32],
4467    v_out: &mut [f32],
4468) -> bool {
4469    match backend() {
4470        #[cfg(feature = "gpu")]
4471        Backend::Wgpu => crate::gpu_wgpu::q4tp_qkv(
4472            model, wq, wk, wv, xs, b, hidden, qrows, kvrows, q_out, k_out, v_out,
4473        ),
4474        #[allow(unreachable_patterns)]
4475        _ => false,
4476    }
4477}
4478
4479/// The Qwen Image double-stream attention half.  The WGPU implementation
4480/// keeps the six Q/K/V projections, the stream join, qk-norm/RoPE, joint
4481/// attention, and both output projections on the device; the caller only
4482/// supplies the two normalized streams and receives the two projected
4483/// streams.  A backend or codec that cannot satisfy the full contract
4484/// returns `false` before changing either output, so the native host path
4485/// remains the portable fallback.
4486pub struct QwenImageAttentionArgs<'a> {
4487    pub image: &'a [f32],
4488    pub text: &'a [f32],
4489    pub image_tokens: usize,
4490    pub text_tokens: usize,
4491    pub heads: usize,
4492    pub head_dim: usize,
4493    pub image_q: usize,
4494    pub image_k: usize,
4495    pub image_v: usize,
4496    pub text_q: usize,
4497    pub text_k: usize,
4498    pub text_v: usize,
4499    pub image_out: usize,
4500    pub text_out: usize,
4501    pub image_q_norm: &'a [f32],
4502    pub image_k_norm: &'a [f32],
4503    pub text_q_norm: &'a [f32],
4504    pub text_k_norm: &'a [f32],
4505    pub image_cos: &'a [f32],
4506    pub image_sin: &'a [f32],
4507    pub text_cos: &'a [f32],
4508    pub text_sin: &'a [f32],
4509    pub image_q_bias: &'a [f32],
4510    pub image_k_bias: &'a [f32],
4511    pub image_v_bias: &'a [f32],
4512    pub text_q_bias: &'a [f32],
4513    pub text_k_bias: &'a [f32],
4514    pub text_v_bias: &'a [f32],
4515    pub image_out_bias: &'a [f32],
4516    pub text_out_bias: &'a [f32],
4517    pub image_proj: &'a mut [f32],
4518    pub text_proj: &'a mut [f32],
4519}
4520
4521/// The per-layer controls and Q4TP directory indices used by the native
4522/// Qwen block.  Keeping this descriptor separate from the stream buffers
4523/// lets a whole transformer forward reuse one explicit device state without
4524/// a global scratch slot or a hidden context label.
4525#[allow(clippy::too_many_fields)]
4526pub struct QwenImageChainBlock<'a> {
4527    pub image_mod: &'a [f32],
4528    pub text_mod: &'a [f32],
4529    pub image_q: usize,
4530    pub image_k: usize,
4531    pub image_v: usize,
4532    pub text_q: usize,
4533    pub text_k: usize,
4534    pub text_v: usize,
4535    pub image_out: usize,
4536    pub text_out: usize,
4537    pub image_q_norm: &'a [f32],
4538    pub image_k_norm: &'a [f32],
4539    pub text_q_norm: &'a [f32],
4540    pub text_k_norm: &'a [f32],
4541    pub image_q_bias: &'a [f32],
4542    pub image_k_bias: &'a [f32],
4543    pub image_v_bias: &'a [f32],
4544    pub text_q_bias: &'a [f32],
4545    pub text_k_bias: &'a [f32],
4546    pub text_v_bias: &'a [f32],
4547    pub image_out_bias: &'a [f32],
4548    pub text_out_bias: &'a [f32],
4549    pub image_attn_gate: &'a [f32],
4550    pub text_attn_gate: &'a [f32],
4551    pub image_mlp_in: usize,
4552    pub image_mlp_out: usize,
4553    pub text_mlp_in: usize,
4554    pub text_mlp_out: usize,
4555    pub image_mlp_in_bias: &'a [f32],
4556    pub image_mlp_out_bias: &'a [f32],
4557    pub text_mlp_in_bias: &'a [f32],
4558    pub text_mlp_out_bias: &'a [f32],
4559}
4560
4561/// Complete Qwen Image transformer block contract. The first norm/mod
4562/// panels are supplied by the native caller; the WGPU arm keeps both streams
4563/// resident through QKV, QK/RoPE, joint attention, output projections, both
4564/// gated residuals, and the exact tanh-GELU MLPs. A backend that cannot
4565/// satisfy the whole graph returns `false` without changing either output.
4566#[allow(clippy::too_many_fields)]
4567pub struct QwenImageBlockArgs<'a> {
4568    /// Raw stream state is read for the first gated residual and overwritten
4569    /// with the block's final state after the one readback.
4570    pub image: &'a mut [f32],
4571    pub text: &'a mut [f32],
4572    pub image_norm: &'a [f32],
4573    pub text_norm: &'a [f32],
4574    pub image_tokens: usize,
4575    pub text_tokens: usize,
4576    pub heads: usize,
4577    pub head_dim: usize,
4578    pub image_cos: &'a [f32],
4579    pub image_sin: &'a [f32],
4580    pub text_cos: &'a [f32],
4581    pub text_sin: &'a [f32],
4582    pub image_q: usize,
4583    pub image_k: usize,
4584    pub image_v: usize,
4585    pub text_q: usize,
4586    pub text_k: usize,
4587    pub text_v: usize,
4588    pub image_out: usize,
4589    pub text_out: usize,
4590    pub image_q_norm: &'a [f32],
4591    pub image_k_norm: &'a [f32],
4592    pub text_q_norm: &'a [f32],
4593    pub text_k_norm: &'a [f32],
4594    pub image_q_bias: &'a [f32],
4595    pub image_k_bias: &'a [f32],
4596    pub image_v_bias: &'a [f32],
4597    pub text_q_bias: &'a [f32],
4598    pub text_k_bias: &'a [f32],
4599    pub text_v_bias: &'a [f32],
4600    pub image_out_bias: &'a [f32],
4601    pub text_out_bias: &'a [f32],
4602    pub image_attn_gate: &'a [f32],
4603    pub text_attn_gate: &'a [f32],
4604    pub image_mlp_in: usize,
4605    pub image_mlp_out: usize,
4606    pub text_mlp_in: usize,
4607    pub text_mlp_out: usize,
4608    pub image_mlp_in_bias: &'a [f32],
4609    pub image_mlp_out_bias: &'a [f32],
4610    pub text_mlp_in_bias: &'a [f32],
4611    pub text_mlp_out_bias: &'a [f32],
4612    pub image_mlp_mod: &'a [f32],
4613    pub text_mlp_mod: &'a [f32],
4614    pub image_mlp_gate: &'a [f32],
4615    pub text_mlp_gate: &'a [f32],
4616}
4617
4618/// Explicit whole-forward Qwen state contract.  The WGPU backend uploads the
4619/// two initial streams once, encodes a bounded number of complete blocks per
4620/// submission, and reads the final state once.  `blocks` is immutable for the
4621/// call, while the two stream slices receive only the final readback.
4622pub struct QwenImageChainArgs<'a> {
4623    pub image: &'a mut [f32],
4624    pub text: &'a mut [f32],
4625    pub image_tokens: usize,
4626    pub text_tokens: usize,
4627    pub heads: usize,
4628    pub head_dim: usize,
4629    pub image_cos: &'a [f32],
4630    pub image_sin: &'a [f32],
4631    pub text_cos: &'a [f32],
4632    pub text_sin: &'a [f32],
4633    pub blocks: &'a [QwenImageChainBlock<'a>],
4634}
4635
4636#[allow(unused_variables)]
4637pub fn qwen_image_attention(
4638    model: &Arc<CmfModel>,
4639    args: &mut QwenImageAttentionArgs<'_>,
4640) -> bool {
4641    match backend() {
4642        #[cfg(feature = "gpu")]
4643        Backend::Wgpu => crate::gpu_wgpu::qwen_image_attention(model, args),
4644        #[allow(unreachable_patterns)]
4645        _ => false,
4646    }
4647}
4648
4649#[allow(unused_variables)]
4650pub fn qwen_image_block(model: &Arc<CmfModel>, args: &mut QwenImageBlockArgs<'_>) -> bool {
4651    match backend() {
4652        #[cfg(feature = "gpu")]
4653        Backend::Wgpu => crate::gpu_wgpu::qwen_image_block(model, args),
4654        #[allow(unreachable_patterns)]
4655        _ => false,
4656    }
4657}
4658
4659/// Keep all Qwen transformer blocks on the selected WGPU device, with only
4660/// bounded chunk submissions and one final readback.  Other backends decline
4661/// so the native caller can use its exact portable block loop.
4662#[allow(unused_variables)]
4663pub fn qwen_image_chain(model: &Arc<CmfModel>, args: &mut QwenImageChainArgs<'_>) -> bool {
4664    match backend() {
4665        #[cfg(feature = "gpu")]
4666        Backend::Wgpu => {
4667            // the H3 parts' chain first, the original one where it declines
4668            #[cfg(not(target_os = "macos"))]
4669            if crate::gpu_wgpu::h3::qwen_chain(model, args) {
4670                return true;
4671            }
4672            crate::gpu_wgpu::qwen_image_chain(model, args)
4673        }
4674        #[cfg(feature = "cuda")]
4675        Backend::Cuda => crate::gpu_cuda::qwen_image_chain(model, args),
4676        #[allow(unreachable_patterns)]
4677        _ => false,
4678    }
4679}
4680
4681/// One MOSS-Image block for [`moss_chain`]: the norm weights and the six
4682/// projections' tensor indices.
4683pub struct MossChainBlock<'a> {
4684    pub norm1: &'a [f32],
4685    pub norm2: &'a [f32],
4686    pub q_norm: &'a [f32],
4687    pub k_norm: &'a [f32],
4688    pub q: usize,
4689    pub k: usize,
4690    pub v: usize,
4691    pub o: usize,
4692    /// `[hidden (inter) | gate (inter)]` rows of the fused feed-forward input.
4693    pub up_gate: usize,
4694    pub down: usize,
4695}
4696
4697/// A MOSS-Image forward's blocks over the joint `[image | text]` rows `x`
4698/// (`[tokens][heads · head_dim]`): one modulation `[6][dim]` for every
4699/// block, the rotation's first halves `[tokens][head_dim / 2]`.
4700pub struct MossChainArgs<'a> {
4701    pub x: &'a mut [f32],
4702    pub tokens: usize,
4703    pub heads: usize,
4704    pub head_dim: usize,
4705    pub modulation: &'a [f32],
4706    pub cos: &'a [f32],
4707    pub sin: &'a [f32],
4708    pub blocks: &'a [MossChainBlock<'a>],
4709}
4710
4711/// Every block of a MOSS-Image forward on the card in one call; `false`:
4712/// nothing was written and the caller runs its per-operation blocks.
4713#[allow(unused_variables)]
4714pub fn moss_chain(model: &Arc<CmfModel>, args: &mut MossChainArgs<'_>) -> bool {
4715    match backend() {
4716        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
4717        Backend::Wgpu => crate::gpu_wgpu::h3::moss_chain(model, args),
4718        #[cfg(feature = "cuda")]
4719        Backend::Cuda => crate::gpu_cuda::moss_chain(model, args),
4720        #[cfg(target_os = "macos")]
4721        Backend::Metal => crate::gpu_metal::h3::moss_chain(model, args),
4722        #[allow(unreachable_patterns)]
4723        _ => false,
4724    }
4725}
4726
4727/// The Qwen Image second sub-block on WGPU: affine-free LayerNorm,
4728/// shift/scale modulation, Q4TP input projection, exact tanh-GELU, output
4729/// projection, bias and gated residual.  `data` is updated in place after a
4730/// single final readback.  Backends/codecs that cannot keep this chain on the
4731/// device return `false` before changing `data`, leaving the caller's
4732/// portable per-op path intact.
4733#[allow(unused_variables, clippy::too_many_arguments)]
4734pub fn qwen_image_mlp_inplace(
4735    model: &Arc<CmfModel>,
4736    w_in: usize,
4737    w_out: usize,
4738    data: &mut [f32],
4739    batch: usize,
4740    hidden: usize,
4741    inter: usize,
4742    bias_in: &[f32],
4743    bias_out: &[f32],
4744    modulation: &[f32],
4745    gate: &[f32],
4746) -> bool {
4747    match backend() {
4748        #[cfg(feature = "gpu")]
4749        Backend::Wgpu => crate::gpu_wgpu::qwen_image_mlp_inplace(
4750            model,
4751            w_in,
4752            w_out,
4753            data,
4754            batch,
4755            hidden,
4756            inter,
4757            bias_in,
4758            bias_out,
4759            modulation,
4760            gate,
4761        ),
4762        #[allow(unreachable_patterns)]
4763        _ => false,
4764    }
4765}
4766
4767/// Is a FUSED whole-block device path on offer? The batched-CFG shape
4768/// (two sequences in one tall batch) and the fused block (one sequence,
4769/// one command buffer) are alternatives, and the caller picks.
4770pub fn fused_dit_block_available() -> bool {
4771    #[cfg(target_os = "macos")]
4772    {
4773        matches!(backend(), Backend::Metal) && fused_block_trusted()
4774    }
4775    #[cfg(not(target_os = "macos"))]
4776    {
4777        false
4778    }
4779}
4780
4781pub fn dit_block(model: &Arc<CmfModel>, a: &DitBlockArgs, x: &mut [f32]) -> bool {
4782    dit_block_seg(model, a, &[a.n], x)
4783}
4784
4785/// The same block over a CONCATENATION of independent sequences:
4786/// attention per segment, everything position-wise batched. wgpu only —
4787/// the Metal path takes the single-sequence entry above.
4788pub fn dit_block_seg(
4789    model: &Arc<CmfModel>,
4790    a: &DitBlockArgs,
4791    segs: &[usize],
4792    x: &mut [f32],
4793) -> bool {
4794    match backend() {
4795        #[cfg(target_os = "macos")]
4796        Backend::Metal if segs.len() <= 1 => crate::gpu_metal::dit_block(model, a, x),
4797        // The wgpu whole-block path. What it buys is host round trips —
4798        // six a block become one — so it defaults ON where those cost
4799        // real time (a discrete card across PCIe) and OFF on unified
4800        // memory, where the per-op path shares the same pages and the
4801        // fusion measured slightly slower on an M4. `CMF_DIT_FUSED=1`
4802        // forces it anywhere, `=0` forbids it.
4803        #[cfg(feature = "gpu")]
4804        Backend::Wgpu
4805            if match std::env::var("CMF_DIT_FUSED").ok().as_deref() {
4806                Some("0") => false,
4807                Some(_) => true,
4808                None => crate::gpu_wgpu::discrete_active(),
4809            } =>
4810        {
4811            crate::gpu_wgpu::dit_block_seg(model, a, segs, x)
4812        }
4813        // The whole block on the card, one block a call (`CMF_LUMINA_CUDA=0`
4814        // keeps the per-operation path).
4815        #[cfg(feature = "cuda")]
4816        Backend::Cuda => crate::gpu_cuda::lumina_block(model, a, segs, x),
4817        #[allow(unreachable_patterns)]
4818        _ => false,
4819    }
4820}
4821
4822/// One VAE resnet block for `vae_resnet`: norm/conv weights and the
4823/// channel/shape geometry. `shortcut` is the 1×1 projection (w, b, k)
4824/// when in/out channels differ.
4825pub struct VaeResnetArgs<'a> {
4826    pub groups: usize,
4827    pub ic: usize,
4828    pub oc: usize,
4829    pub h: usize,
4830    pub w: usize,
4831    pub n1w: &'a [f32],
4832    pub n1b: &'a [f32],
4833    pub c1w: &'a [f32],
4834    pub c1b: &'a [f32],
4835    pub c1k: usize,
4836    pub n2w: &'a [f32],
4837    pub n2b: &'a [f32],
4838    pub c2w: &'a [f32],
4839    pub c2b: &'a [f32],
4840    pub c2k: usize,
4841    pub shortcut: Option<(&'a [f32], &'a [f32], usize)>,
4842}
4843
4844/// One whole VAE resnet block on the device (norm+silu → conv ×2 →
4845/// shortcut → add, one command buffer).
4846#[allow(unused_variables)]
4847pub fn vae_resnet(a: &VaeResnetArgs, x: &[f32], out: &mut [f32]) -> bool {
4848    match backend() {
4849        #[cfg(target_os = "macos")]
4850        Backend::Metal => crate::gpu_metal::vae_resnet(a, x, out),
4851        _ => false,
4852    }
4853}
4854
4855/// Nearest-2× upsample fused with the following conv — the small
4856/// pre-upsample image is what crosses the CPU boundary.
4857#[allow(unused_variables, clippy::too_many_arguments)]
4858pub fn vae_upsample_conv(
4859    w: &[f32],
4860    bias: &[f32],
4861    x: &[f32],
4862    ic: usize,
4863    oc: usize,
4864    h: usize,
4865    w_img: usize,
4866    k: usize,
4867    out: &mut [f32],
4868) -> bool {
4869    match backend() {
4870        #[cfg(target_os = "macos")]
4871        Backend::Metal => crate::gpu_metal::vae_upsample_conv(w, bias, x, ic, oc, h, w_img, k, out),
4872        #[cfg(feature = "gpu")]
4873        Backend::Wgpu => crate::gpu_wgpu::vae_upsample_conv(w, bias, x, ic, oc, h, w_img, k, out),
4874        #[cfg(feature = "cuda")]
4875        Backend::Cuda => crate::gpu_cuda::h3_vae_conv2d(w, bias, x, ic, oc, h, w_img, k, true, out),
4876        #[allow(unreachable_patterns)]
4877        _ => false,
4878    }
4879}
4880
4881/// VAE conv2d on the device (implicit GEMM — the CPU path pays for a
4882/// multi-GB im2col matrix at high resolutions).
4883#[allow(unused_variables, clippy::too_many_arguments)]
4884pub fn vae_conv2d(
4885    w: &[f32],
4886    bias: &[f32],
4887    x: &[f32],
4888    ic: usize,
4889    oc: usize,
4890    h: usize,
4891    w_img: usize,
4892    k: usize,
4893    out: &mut [f32],
4894) -> bool {
4895    match backend() {
4896        #[cfg(target_os = "macos")]
4897        Backend::Metal => crate::gpu_metal::vae_conv2d(w, bias, x, ic, oc, h, w_img, k, out),
4898        #[cfg(feature = "gpu")]
4899        Backend::Wgpu => crate::gpu_wgpu::vae_conv2d(w, bias, x, ic, oc, h, w_img, k, out),
4900        #[cfg(feature = "cuda")]
4901        Backend::Cuda => crate::gpu_cuda::h3_vae_conv2d(w, bias, x, ic, oc, h, w_img, k, false, out),
4902        #[allow(unreachable_patterns)]
4903        _ => false,
4904    }
4905}
4906
4907/// DiT full bidirectional attention on the device (all heads:
4908/// scores GEMM → row softmax → P·V → panel unstack, one command
4909/// buffer). Head-major inputs; out is [n, nh·hd].
4910#[allow(unused_variables, clippy::too_many_arguments)]
4911/// Attention from an interleaved qkv panel, splitting into head-major
4912/// planes ON the device. wgpu only; `false` elsewhere so the caller
4913/// keeps its host repack.
4914#[allow(unused_variables)]
4915#[allow(clippy::too_many_arguments)]
4916/// qkv projection + attention with the panel never leaving the card.
4917/// wgpu only; `false` elsewhere and the caller keeps its host chain.
4918#[allow(clippy::too_many_arguments, unused_variables)]
4919pub fn dit_qkv_attention(
4920    model: &Arc<CmfModel>,
4921    qkv_idx: usize,
4922    xn: &[f32],
4923    n: usize,
4924    hidden: usize,
4925    nh: usize,
4926    hd: usize,
4927    scale: f32,
4928    nr: (&[f32], &[f32], &[f32], f32),
4929    out: &mut [f32],
4930) -> bool {
4931    match backend() {
4932        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
4933        Backend::Wgpu => crate::gpu_wgpu::dit_qkv_attention(
4934            model, qkv_idx, xn, n, hidden, nh, hd, scale, nr, out,
4935        ),
4936        #[allow(unreachable_patterns)]
4937        _ => false,
4938    }
4939}
4940
4941/// One block of a MiniMax-H3 stack for the resident chain: the four
4942/// projections by directory index, its norms, and its modulation table.
4943pub struct H3ChainBlock<'a> {
4944    pub qkv: usize,
4945    pub out: usize,
4946    pub fc1: usize,
4947    pub fc2: usize,
4948    pub norm1: &'a [f32],
4949    pub norm2: &'a [f32],
4950    pub q_norm: &'a [f32],
4951    pub k_norm: &'a [f32],
4952    /// `[modulation rows][6 · hidden]` (shift, scale, gate for attention,
4953    /// then for the MLP); empty for an unmodulated block.
4954    pub mods: &'a [f32],
4955    /// The ViT decoder's extras, each empty where a stack has none: the
4956    /// projections' biases and the per-channel scale of each residual.
4957    pub qkv_bias: &'a [f32],
4958    pub out_bias: &'a [f32],
4959    pub fc1_bias: &'a [f32],
4960    pub fc2_bias: &'a [f32],
4961    pub scale1: &'a [f32],
4962    pub scale2: &'a [f32],
4963    /// VSA's compression-branch gate `[heads·hd, hidden]` by directory index
4964    /// (`usize::MAX`: none). Read only under [`H3Chain::vsa`].
4965    pub gate: usize,
4966}
4967
4968/// A stack of MiniMax-H3 blocks over one packed sequence.
4969pub struct H3Chain<'a> {
4970    pub model: &'a Arc<CmfModel>,
4971    pub blocks: &'a [H3ChainBlock<'a>],
4972    pub n: usize,
4973    pub hidden: usize,
4974    pub heads: usize,
4975    pub head_dim: usize,
4976    pub ffn: usize,
4977    pub eps: f32,
4978    pub qk_eps: f32,
4979    /// `[n][pairs]` rotation angles; empty: no rotation.
4980    pub angles: &'a [f32],
4981    /// `[n]` modulation row of every token (unread without modulation).
4982    pub rows: &'a [u32],
4983    /// Independent sequences in the batch, `n` rows each (`h` is
4984    /// `[groups · n][hidden]`): attention stays inside a group, and the
4985    /// angles are one group's, shared by all.
4986    pub groups: usize,
4987    /// The qkv panel's row layout: `[q | k | v]` planes (false) or
4988    /// per-head `[q k v]` triples (true).
4989    pub qkv_interleaved: bool,
4990    /// Video sparse attention over the tiles of this plan instead of the
4991    /// full attention (a VSA-trained student; one group only). A backend
4992    /// without it refuses the chain.
4993    pub vsa: Option<&'a crate::mmh3::VsaPlan>,
4994}
4995
4996/// One layer of a language-model prompt encoder for the resident chain: its
4997/// seven projections by directory index and its norms.
4998pub struct TeChainLayer<'a> {
4999    pub q: usize,
5000    pub k: usize,
5001    pub v: usize,
5002    pub o: usize,
5003    pub gate: usize,
5004    pub up: usize,
5005    pub down: usize,
5006    pub input_norm: &'a [f32],
5007    pub post_norm: &'a [f32],
5008    pub q_norm: &'a [f32],
5009    pub k_norm: &'a [f32],
5010}
5011
5012/// A run of prompt-encoder layers over one causal sequence.
5013pub struct TeChain<'a> {
5014    pub model: &'a Arc<CmfModel>,
5015    pub layers: &'a [TeChainLayer<'a>],
5016    pub n: usize,
5017    pub hidden: usize,
5018    pub heads: usize,
5019    pub kv_heads: usize,
5020    pub head_dim: usize,
5021    pub inter: usize,
5022    pub eps: f32,
5023    /// `[n][head_dim / 2][2]`: (cos, sin) of every row's rotation angles.
5024    pub cs: &'a [f32],
5025}
5026
5027/// The layers over `h` `[n][hidden]`, in place, on the card. `false`: nothing
5028/// was written and the caller runs its per-op path.
5029#[allow(unused_variables)]
5030pub fn te_chain(job: &TeChain<'_>, h: &mut [f32]) -> bool {
5031    match backend() {
5032        #[cfg(feature = "cuda")]
5033        Backend::Cuda => crate::gpu_cuda::h3_te_chain(job, h),
5034        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5035        Backend::Wgpu => crate::gpu_wgpu::h3::te_chain(job, h),
5036        #[cfg(target_os = "macos")]
5037        Backend::Metal => crate::gpu_metal::h3::te_chain(job, h),
5038        #[allow(unreachable_patterns)]
5039        _ => false,
5040    }
5041}
5042
5043/// One projection of the LTX-2.5 transformer for the resident chain: a
5044/// container matrix `[rows][cols]` (q4tp or q8_2f) by directory index, or a
5045/// dense f32 one, and its bias (`[rows]`, or empty).
5046#[derive(Clone, Copy)]
5047pub struct LtxLin<'a> {
5048    pub w: Option<usize>,
5049    pub dense: &'a [f32],
5050    pub rows: usize,
5051    pub cols: usize,
5052    pub bias: &'a [f32],
5053}
5054
5055/// One attention of an LTX-2.5 block: the query reads the tokens, the keys
5056/// and values read the context (the tokens again for self-attention), q and
5057/// k take an RMS norm over the whole inner width, and every head's output
5058/// is scaled by `2 * sigmoid(gate(x))` where the block has gate logits.
5059#[derive(Clone, Copy)]
5060pub struct LtxAttn<'a> {
5061    pub q: LtxLin<'a>,
5062    pub k: LtxLin<'a>,
5063    pub v: LtxLin<'a>,
5064    pub o: LtxLin<'a>,
5065    pub q_norm: &'a [f32],
5066    pub k_norm: &'a [f32],
5067    pub gate: Option<LtxLin<'a>>,
5068    pub heads: usize,
5069    pub dh: usize,
5070}
5071
5072/// One modality's half of an LTX-2.5 block.
5073pub struct LtxStream<'a> {
5074    pub attn1: LtxAttn<'a>,
5075    pub attn2: LtxAttn<'a>,
5076    pub ff_in: LtxLin<'a>,
5077    pub ff_out: LtxLin<'a>,
5078    /// `[distinct][9][dim]`: (shift, scale, gate) of self-attention, of the
5079    /// feed-forward and of the prompt attention, for each distinct timestep
5080    /// of the stream (the block's table plus the timestep's row).
5081    pub mods: &'a [f32],
5082    /// `[2][dim]`: shift and scale of the prompt before its keys and values.
5083    pub ctx_mod: &'a [f32],
5084}
5085
5086/// One LTX-2.5 block: both streams and the two directions of their fusion.
5087pub struct LtxBlock<'a> {
5088    pub video: LtxStream<'a>,
5089    pub audio: LtxStream<'a>,
5090    pub a2v: LtxAttn<'a>,
5091    pub v2a: LtxAttn<'a>,
5092    /// `[distinct][4][dim]`: (scale, shift) of the audio-to-video attention
5093    /// and (scale, shift) of the video-to-audio one, for the video stream.
5094    pub xmods_v: &'a [f32],
5095    /// The same for the audio stream, `[distinct][4][a_dim]`.
5096    pub xmods_a: &'a [f32],
5097    /// `[dim]`: the gate of what audio adds to video.
5098    pub gate_a2v: &'a [f32],
5099    /// `[a_dim]`: the gate of what video adds to audio.
5100    pub gate_v2a: &'a [f32],
5101}
5102
5103/// What a stream brings to one denoising step besides its tokens.
5104pub struct LtxSide<'a> {
5105    pub n: usize,
5106    pub dim: usize,
5107    /// `[n]`: each token's row of `LtxStream::mods`.
5108    pub rows: &'a [u32],
5109    /// `[n]`: each token's row of the fusion tables.
5110    pub xrows: &'a [u32],
5111    /// Self-attention rotation: cos and sin `[n][dim / 2]` and the half
5112    /// width of a rotation group (pairs are `(i, i + half)` inside a group).
5113    pub pe: (&'a [f32], &'a [f32], usize),
5114    /// The same for the fusion attentions, over their inner width.
5115    pub xpe: (&'a [f32], &'a [f32], usize),
5116    /// The prompt as this stream reads it, `[ctx_len][dim]`.
5117    pub ctx: &'a [f32],
5118    pub ctx_len: usize,
5119    /// Additive per-key bias of the prompt attention; empty: none.
5120    pub mask: &'a [f32],
5121}
5122
5123/// The 48 blocks of one LTX-2.5 denoising step.
5124pub struct LtxChain<'a> {
5125    pub model: &'a Arc<CmfModel>,
5126    pub blocks: &'a [LtxBlock<'a>],
5127    pub video: LtxSide<'a>,
5128    pub audio: LtxSide<'a>,
5129}
5130
5131/// Whether this backend runs an LTX-2.5 step as one resident chain.
5132pub fn ltx_chain_available() -> bool {
5133    match backend() {
5134        #[cfg(feature = "cuda")]
5135        Backend::Cuda => true,
5136        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5137        Backend::Wgpu => crate::gpu_wgpu::h3::ltx_available(),
5138        #[allow(unreachable_patterns)]
5139        _ => false,
5140    }
5141}
5142
5143/// The blocks over both streams (`vx` `[n][dim]`, `ax` `[m][a_dim]`), in
5144/// place, with the streams on the card from the first block to the last.
5145/// `false`: nothing was written and the caller runs its per-op path.
5146#[allow(unused_variables)]
5147pub fn ltx_chain(job: &LtxChain<'_>, vx: &mut [f32], ax: &mut [f32]) -> bool {
5148    match backend() {
5149        #[cfg(feature = "cuda")]
5150        Backend::Cuda => crate::gpu_cuda::ltx_chain(job, vx, ax),
5151        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5152        Backend::Wgpu => crate::gpu_wgpu::h3::ltx_chain(job, vx, ax),
5153        #[allow(unreachable_patterns)]
5154        _ => false,
5155    }
5156}
5157
5158/// One stage of the LTX-2.5 video VAE's decode over a volume
5159/// `[c][f][h][w]`.
5160pub enum Vae3dStep<'a> {
5161    /// A 3x3x3 convolution with zero padding in space and replicated frames
5162    /// in time: `w` `[out_ch][in_ch * 27]`, `b` `[out_ch]`.
5163    Conv { w: &'a [f32], b: &'a [f32], in_ch: usize, out_ch: usize },
5164    /// The RMS over the channels at every position (`eps` under the root),
5165    /// then SiLU.
5166    NormSilu { eps: f32 },
5167    /// Keep the activation for a later `AddSaved`.
5168    Save,
5169    /// Add the kept activation.
5170    AddSaved,
5171    /// Depth to space over (frames, height, width), the channels laid out
5172    /// `(c p1 p2 p3)`; a frame stride of 2 leaves the first frame out.
5173    DepthToSpace { p: (usize, usize, usize) },
5174}
5175
5176/// The stages over `x` `[c][f][h][w]` on the card: the result and its
5177/// `(c, f, h, w)`. `None`: the caller runs its host path.
5178#[allow(unused_variables)]
5179pub fn vae3d_chain(
5180    steps: &[Vae3dStep<'_>],
5181    x: &[f32],
5182    c: usize,
5183    f: usize,
5184    h: usize,
5185    w: usize,
5186) -> Option<(Vec<f32>, usize, usize, usize, usize)> {
5187    match backend() {
5188        #[cfg(feature = "cuda")]
5189        Backend::Cuda => crate::gpu_cuda::ltx_vae_chain(steps, x, c, f, h, w),
5190        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5191        Backend::Wgpu => crate::gpu_wgpu::h3::ltx_vae_chain(steps, x, c, f, h, w),
5192        #[allow(unreachable_patterns)]
5193        _ => None,
5194    }
5195}
5196
5197/// One stage of a convolution chain over an activation `[c][h][w]`.
5198pub enum ConvStep<'a> {
5199    /// GroupNorm(32) with its affine weights, then SiLU, in place.
5200    GnSilu { w: &'a [f32], b: &'a [f32] },
5201    /// A `k`×`k` convolution `[out, in, k, k]` and its bias. `pad`: rows and
5202    /// columns of reflect padding on every side; `far`: one reflected row
5203    /// and column on the far side instead (a downsample's padding).
5204    Conv {
5205        w: &'a [f32],
5206        b: &'a [f32],
5207        out_ch: usize,
5208        in_ch: usize,
5209        k: usize,
5210        stride: usize,
5211        pad: usize,
5212        far: bool,
5213    },
5214    /// Keep the current activation as the residual branch's input.
5215    Save,
5216    /// Add the kept activation — through a 1×1 convolution (weight, bias)
5217    /// when the branch changes the channel count.
5218    AddSaved { via: Option<(&'a [f32], &'a [f32])> },
5219}
5220
5221/// The stages over `x` `[c][h][w]` on the card; `([c'][h'][w'], c', h', w')`,
5222/// or None where the backend has no such chain (the caller runs its own).
5223#[allow(unused_variables)]
5224pub fn conv_chain(steps: &[ConvStep<'_>], x: &[f32], c: usize, h: usize, w: usize) -> Option<(Vec<f32>, usize, usize, usize)> {
5225    match backend() {
5226        #[cfg(feature = "cuda")]
5227        Backend::Cuda => crate::gpu_cuda::h3_conv_chain(steps, x, c, h, w),
5228        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5229        Backend::Wgpu => crate::gpu_wgpu::h3_conv::conv_chain(steps, x, c, h, w),
5230        #[allow(unreachable_patterns)]
5231        _ => None,
5232    }
5233}
5234
5235/// Whether this backend runs a MiniMax-H3 stack as one resident chain.
5236pub fn h3_chain_available() -> bool {
5237    match backend() {
5238        #[cfg(feature = "cuda")]
5239        Backend::Cuda => true,
5240        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5241        Backend::Wgpu => crate::gpu_wgpu::h3::available(),
5242        #[cfg(target_os = "macos")]
5243        Backend::Metal => crate::gpu_metal::h3::available(),
5244        #[allow(unreachable_patterns)]
5245        _ => false,
5246    }
5247}
5248
5249/// The stack over `h` `[n][hidden]`, in place, with the stream on the card
5250/// from the first block to the last. `false`: nothing was written and the
5251/// caller runs its per-op path.
5252#[allow(unused_variables)]
5253pub fn h3_chain(job: &H3Chain<'_>, h: &mut [f32]) -> bool {
5254    match backend() {
5255        #[cfg(feature = "cuda")]
5256        Backend::Cuda => crate::gpu_cuda::h3_chain(job, h),
5257        // Metal's VSA kernels (an M4 within 0.55 % of the host reference)
5258        // are on; `CMF_H3_METAL_VSA=0` sends a sparse student's chain to the
5259        // per-op path (the host reference), never through the dense kernels.
5260        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5261        Backend::Wgpu => crate::gpu_wgpu::h3::chain(job, h),
5262        #[cfg(target_os = "macos")]
5263        Backend::Metal => (job.vsa.is_none() || std::env::var("CMF_H3_METAL_VSA").as_deref() != Ok("0")) && crate::gpu_metal::h3::chain(job, h),
5264        #[allow(unreachable_patterns)]
5265        _ => false,
5266    }
5267}
5268
5269/// The whole attention half of a DiT block on the card: qkv GEMM,
5270/// attention, output projection. Only `proj` comes home.
5271#[allow(clippy::too_many_arguments)]
5272pub fn dit_qkv_attn_out(
5273    model: &Arc<CmfModel>,
5274    qkv_idx: usize,
5275    out_idx: usize,
5276    xn: &[f32],
5277    n: usize,
5278    hidden: usize,
5279    nh: usize,
5280    hd: usize,
5281    scale: f32,
5282    nr: (&[f32], &[f32], &[f32], f32),
5283    proj: &mut [f32],
5284) -> bool {
5285    match backend() {
5286        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5287        Backend::Wgpu => crate::gpu_wgpu::dit_qkv_attn_out(
5288            model, qkv_idx, out_idx, xn, n, hidden, nh, hd, scale, nr, proj,
5289        ),
5290        #[allow(unreachable_patterns)]
5291        _ => false,
5292    }
5293}
5294
5295/// The VAE decoder's attention half on the card. Only `proj` returns.
5296#[allow(clippy::too_many_arguments)]
5297pub fn vae_qkv_attn_out(
5298    model: &Arc<CmfModel>,
5299    qkv_idx: usize,
5300    out_idx: usize,
5301    xn: &[f32],
5302    n: usize,
5303    dim: usize,
5304    nh: usize,
5305    hd: usize,
5306    scale: f32,
5307    angles: &[f32],
5308    eps: f32,
5309    qkv_bias: &[f32],
5310    proj: &mut [f32],
5311) -> bool {
5312    match backend() {
5313        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5314        Backend::Wgpu => crate::gpu_wgpu::vae_qkv_attn_out(
5315            model, qkv_idx, out_idx, xn, n, dim, nh, hd, scale, angles, eps, qkv_bias, proj,
5316        ),
5317        #[allow(unreachable_patterns)]
5318        _ => false,
5319    }
5320}
5321
5322#[allow(clippy::too_many_arguments)]
5323pub fn vae_attention_packed(
5324    qkv: &[f32],
5325    nh: usize,
5326    n: usize,
5327    hd: usize,
5328    scale: f32,
5329    angles: &[f32],
5330    eps: f32,
5331    out: &mut [f32],
5332) -> bool {
5333    vae_attention_packed_layout(qkv, nh, n, hd, scale, angles, eps, out, 1)
5334}
5335
5336#[allow(clippy::too_many_arguments)]
5337pub fn vae_attention_packed_layout(
5338    qkv: &[f32],
5339    nh: usize,
5340    n: usize,
5341    hd: usize,
5342    scale: f32,
5343    angles: &[f32],
5344    eps: f32,
5345    out: &mut [f32],
5346    layout: u32,
5347) -> bool {
5348    match backend() {
5349        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5350        Backend::Wgpu => crate::gpu_wgpu::vae_attention_packed_layout(
5351            qkv, nh, n, hd, scale, angles, eps, out, layout,
5352        ),
5353        #[allow(unreachable_patterns)]
5354        _ => false,
5355    }
5356}
5357
5358#[allow(clippy::too_many_arguments)]
5359pub fn dit_split_only(
5360    qkv: &[f32],
5361    nh: usize,
5362    n: usize,
5363    hd: usize,
5364    layout: u32,
5365    norm: Option<(&[f32], f32)>,
5366    out_q: &mut [f32],
5367) -> bool {
5368    match backend() {
5369        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5370        Backend::Wgpu => crate::gpu_wgpu::dit_split_only(qkv, nh, n, hd, layout, norm, out_q),
5371        #[allow(unreachable_patterns)]
5372        _ => false,
5373    }
5374}
5375
5376/// The backend's f32 NT GEMM: `y[n×m] = x[n×k] · wᵀ[m×k]`. Tensor
5377/// cores where the card has them. Refuses under `CMF_BAKE_GPU=0` or
5378/// strict f32, and for jobs below n·k·m = 4M, where the round trip
5379/// costs more than the arithmetic saves.
5380/// `gemm_nt_f32` whose `w` is known to change every call (an
5381/// accumulation over fresh activations, not a weight): it skips the
5382/// resident ledger and its per-call fingerprint of the whole operand.
5383pub fn gemm_nt_f32_transient(
5384    x: &[f32],
5385    w: &[f32],
5386    y: &mut [f32],
5387    n: usize,
5388    k: usize,
5389    m: usize,
5390) -> bool {
5391    match backend() {
5392        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5393        Backend::Wgpu => crate::gpu_wgpu::gemm_nt_f32_transient(x, w, y, n, k, m),
5394        #[allow(unreachable_patterns)]
5395        _ => false,
5396    }
5397}
5398
5399/// One pre-norm ViT block's f32 weights for [`vit_encode`]: LayerNorm 1,
5400/// fused qkv `[3d, d]`, proj `[d, d]`, LayerNorm 2, fc1 `[inter, d]`, fc2
5401/// `[d, inter]`, each with its bias.
5402pub struct VitLayer<'a> {
5403    pub ln1_w: &'a [f32],
5404    pub ln1_b: &'a [f32],
5405    pub qkv: &'a [f32],
5406    pub qkv_b: &'a [f32],
5407    pub proj: &'a [f32],
5408    pub proj_b: &'a [f32],
5409    pub ln2_w: &'a [f32],
5410    pub ln2_b: &'a [f32],
5411    pub fc1: &'a [f32],
5412    pub fc1_b: &'a [f32],
5413    pub fc2: &'a [f32],
5414    pub fc2_b: &'a [f32],
5415}
5416
5417/// A vision tower's encoder stack for [`vit_encode`]. `cos`/`sin` are
5418/// `[n, head_dim]` per lane; `rope_halves` pairs lane j with j ± hd/2
5419/// (Qwen-VL), else with its neighbour (OneVision's interleaved form).
5420/// `key` identifies the tower for the device weight cache.
5421pub struct VitArgs<'a> {
5422    pub key: u64,
5423    pub layers: Vec<VitLayer<'a>>,
5424    pub n: usize,
5425    pub d: usize,
5426    pub heads: usize,
5427    pub head_dim: usize,
5428    pub inter: usize,
5429    pub eps: f64,
5430    pub gelu_tanh: bool,
5431    /// CLIP's `x·σ(1.702·x)`; wins over `gelu_tanh`.
5432    pub quick_gelu: bool,
5433    pub rope_halves: bool,
5434    pub cos: &'a [f32],
5435    pub sin: &'a [f32],
5436    pub prof: bool,
5437}
5438
5439/// The encoder layers of a vision tower resident on the device, `x`
5440/// (`[n, d]`) in place. `false` = refused; the caller runs its per-op
5441/// path. `CMF_VIT_RESIDENT=0` declines.
5442#[allow(unused_variables)]
5443pub fn vit_encode(a: &VitArgs, x: &mut [f32]) -> bool {
5444    if std::env::var("CMF_VIT_RESIDENT").as_deref() == Ok("0") {
5445        return false;
5446    }
5447    match backend() {
5448        #[cfg(target_os = "macos")]
5449        Backend::Metal => crate::gpu_metal::vit::encode(a, x),
5450        #[cfg(feature = "gpu")]
5451        Backend::Wgpu => crate::gpu_wgpu::vit::encode(a, x),
5452        #[cfg(feature = "cuda")]
5453        Backend::Cuda => crate::gpu_cuda::vit_encode(a, x),
5454        #[allow(unreachable_patterns)]
5455        _ => false,
5456    }
5457}
5458
5459/// One SAM block for [`sam_encode`]. `rel` is `[2w−1, hd]` relative positions,
5460/// h then w (window blocks; the global ones take `SamArgs::rel_global`).
5461pub struct SamLayer<'a> {
5462    pub ln1_w: &'a [f32],
5463    pub ln1_b: &'a [f32],
5464    pub qkv: &'a [f32],
5465    pub qkv_b: &'a [f32],
5466    pub proj: &'a [f32],
5467    pub proj_b: &'a [f32],
5468    pub rel: &'a [f32],
5469    pub ln2_w: &'a [f32],
5470    pub ln2_b: &'a [f32],
5471    pub fc1: &'a [f32],
5472    pub fc1_b: &'a [f32],
5473    pub fc2: &'a [f32],
5474    pub fc2_b: &'a [f32],
5475    pub window: usize,
5476}
5477
5478/// One conv of SAM's neck, weights `[co, k·k, ci]`.
5479pub struct SamConv<'a> {
5480    pub w: &'a [f32],
5481    pub ci: usize,
5482    pub co: usize,
5483    pub k: usize,
5484    pub stride: usize,
5485    pub pad: usize,
5486    /// A LayerNorm2d follows (its weight and bias in `SamArgs::norms`).
5487    pub norm: bool,
5488}
5489
5490pub struct SamArgs<'a> {
5491    pub key: u64,
5492    pub layers: Vec<SamLayer<'a>>,
5493    pub convs: Vec<SamConv<'a>>,
5494    pub norms: Vec<&'a [f32]>,
5495    /// Per global block: `[2g−1, hd]` h then w, resized to this grid.
5496    pub rel_global: Vec<Vec<f32>>,
5497    pub g: usize,
5498    pub d: usize,
5499    pub heads: usize,
5500    pub head_dim: usize,
5501    pub inter: usize,
5502    pub eps: f64,
5503}
5504
5505/// SAM's blocks and neck on the device; `false` = refused.
5506#[allow(unused_variables)]
5507pub fn sam_encode(a: &SamArgs, x: &[f32], out: &mut Vec<f32>) -> bool {
5508    if std::env::var("CMF_VIT_RESIDENT").as_deref() == Ok("0") {
5509        return false;
5510    }
5511    match backend() {
5512        #[cfg(target_os = "macos")]
5513        Backend::Metal => crate::gpu_metal::vit::sam_encode(a, x, out),
5514        #[cfg(feature = "gpu")]
5515        Backend::Wgpu => crate::gpu_wgpu::vit::sam_encode(a, x, out),
5516        #[cfg(feature = "cuda")]
5517        Backend::Cuda => crate::gpu_cuda::sam_encode(a, x, out),
5518        #[allow(unreachable_patterns)]
5519        _ => false,
5520    }
5521}
5522
5523/// A Primal VAE encode or decode (`primal_vae::PvPlan`) resident on the
5524/// device: one upload, one command buffer, one readback. `false` =
5525/// refused; the caller runs the host steps.
5526pub fn primal_vae_run(
5527    key: u64,
5528    weights: &crate::primal_vae::PvWeights,
5529    plan: &crate::primal_vae::PvPlan,
5530    input: &[f32],
5531    out: &mut [f32],
5532) -> bool {
5533    match backend() {
5534        #[cfg(target_os = "macos")]
5535        Backend::Metal => crate::gpu_metal::primal_vae::run(key, weights, plan, input, out),
5536        #[cfg(feature = "gpu")]
5537        Backend::Wgpu => crate::gpu_wgpu::primal_vae::run(key, weights, plan, input, out),
5538        #[cfg(feature = "cuda")]
5539        Backend::Cuda => crate::gpu_cuda::primal_vae_run(key, weights, plan, input, out),
5540        #[allow(unreachable_patterns)]
5541        _ => false,
5542    }
5543}
5544
5545/// A vision tower's f32 NT GEMM, `y[n×m] = x[n×k] · wᵀ[m×k]`, on the
5546/// device: the encoders' f32 `eg_mm_nt` on Metal (Accelerate's sum order),
5547/// `gemm_nt_f32` on wgpu. `false` = refused (no device, a small job), the
5548/// caller runs the host GEMM.
5549pub fn vision_gemm_nt(x: &[f32], w: &[f32], y: &mut [f32], n: usize, k: usize, m: usize) -> bool {
5550    if n * k * m < (1 << 22) {
5551        return false;
5552    }
5553    match backend() {
5554        #[cfg(target_os = "macos")]
5555        Backend::Metal => crate::gpu_metal::egemma2::gemm_nt(x, w, y, n, k, m),
5556        #[cfg(feature = "gpu")]
5557        Backend::Wgpu => crate::gpu_wgpu::gemm_nt_f32(x, w, y, n, k, m),
5558        #[cfg(feature = "cuda")]
5559        Backend::Cuda => crate::gpu_cuda::h3_gemm_nt(x, w, y, n, k, m),
5560        #[allow(unreachable_patterns)]
5561        _ => false,
5562    }
5563}
5564
5565/// `y[n×m] = x[n×k] · wᵀ[m×k]`, all f32 from the host, on the device (the
5566/// audio decoder's convolutions as im2col panels). `false` = refused.
5567pub fn gemm_nt_f32(x: &[f32], w: &[f32], y: &mut [f32], n: usize, k: usize, m: usize) -> bool {
5568    match backend() {
5569        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5570        Backend::Wgpu => crate::gpu_wgpu::gemm_nt_f32(x, w, y, n, k, m),
5571        #[cfg(feature = "cuda")]
5572        Backend::Cuda => crate::gpu_cuda::h3_gemm_nt(x, w, y, n, k, m),
5573        #[allow(unreachable_patterns)]
5574        _ => false,
5575    }
5576}
5577
5578/// Music-3's FFN chain resident on the device — two GEMMs and the GLU
5579/// between them with no host round trip. `false` = refused, host runs.
5580#[allow(clippy::too_many_arguments)]
5581pub fn music3_ffn(
5582    model: &std::sync::Arc<CmfModel>,
5583    idx_in: usize,
5584    idx_out: usize,
5585    h: &[f32],
5586    bias_in: &[f32],
5587    n: usize,
5588    hs: usize,
5589    inter: usize,
5590    out: &mut [f32],
5591) -> bool {
5592    match backend() {
5593        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5594        Backend::Wgpu => {
5595            crate::gpu_wgpu::music3_ffn(model, idx_in, idx_out, h, bias_in, n, hs, inter, out)
5596        }
5597        #[cfg(feature = "cuda")]
5598        Backend::Cuda => crate::gpu_cuda::h3_music3_ffn(model, idx_in, idx_out, h, bias_in, n, hs, inter, out),
5599        #[allow(unreachable_patterns)]
5600        _ => false,
5601    }
5602}
5603
5604/// A routed FFN of one row on the card for a stack the host runs and routes
5605/// (GLM-5.3): the experts through card slots, the shared one resident (CUDA;
5606/// `false` elsewhere or refused, the caller runs the host's).
5607#[allow(clippy::too_many_arguments, unused_variables)]
5608pub fn moe_row(
5609    model: &Arc<CmfModel>,
5610    experts: &[(usize, usize, usize)],
5611    shared: Option<((usize, usize, usize), usize, f32)>,
5612    inter: usize,
5613    limit: f32,
5614    x: &[f32],
5615    picks: &[(usize, f32)],
5616    out: &mut [f32],
5617) -> bool {
5618    match backend() {
5619        #[cfg(feature = "cuda")]
5620        Backend::Cuda => crate::gpu_cuda::moe_row(model, experts, shared, inter, limit, x, picks, out),
5621        #[allow(unreachable_patterns)]
5622        _ => false,
5623    }
5624}
5625
5626/// GLM-5.3's native device state (four mHC streams, KDA rings, DSA caches):
5627/// this build runs the `glm5_next` stack on the host, so the device hooks
5628/// decline and the caller keeps the exact CPU path.
5629#[allow(clippy::too_many_arguments)]
5630pub fn glm_sequence_prepare(
5631    model_uid: u64,
5632    sequence_id: u64,
5633    layers: usize,
5634    hidden: usize,
5635    mhc_streams: usize,
5636    nh: usize,
5637    dk: usize,
5638    dv: usize,
5639    kk: usize,
5640    dsa_rank: usize,
5641    dsa_index: usize,
5642    dsa_topk: usize,
5643    dsa_kpool: usize,
5644) -> bool {
5645    let _ = (model_uid, sequence_id, layers, hidden, mhc_streams, nh, dk, dv, kk, dsa_rank, dsa_index, dsa_topk, dsa_kpool);
5646    false
5647}
5648
5649/// Grow GLM's device DSA caches (`glm_sequence_prepare`): declines here.
5650pub fn glm_sequence_reserve(model_uid: u64, sequence_id: u64, positions: usize) -> bool {
5651    let _ = (model_uid, sequence_id, positions);
5652    false
5653}
5654
5655/// Drop GLM's device state of a sequence (none in this build).
5656pub fn glm_sequence_abort(model_uid: u64, sequence_id: u64) {
5657    let _ = (model_uid, sequence_id);
5658}
5659
5660/// A 1D convolution as a GEMM whose column matrix is expanded on the
5661/// device instead of being built, transposed and uploaded by the host.
5662/// `yt` comes back `[out_n x oc]`. `false` = refused, caller runs host.
5663#[allow(clippy::too_many_arguments)]
5664pub fn conv1d_gemm(
5665    x: &[f32],
5666    w: &[f32],
5667    ic: usize,
5668    oc: usize,
5669    n: usize,
5670    k: usize,
5671    pad: usize,
5672    dil: usize,
5673    out_n: usize,
5674    yt: &mut [f32],
5675) -> bool {
5676    match backend() {
5677        #[cfg(target_os = "macos")]
5678        Backend::Metal => crate::gpu_metal::conv1d_gemm(x, w, ic, oc, n, k, pad, dil, out_n, yt),
5679        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5680        Backend::Wgpu => crate::gpu_wgpu::conv1d_gemm(x, w, ic, oc, n, k, pad, dil, out_n, yt),
5681        #[cfg(feature = "cuda")]
5682        Backend::Cuda => {
5683            // Below a few million products the round trip loses to the host.
5684            out_n * ic * k * oc >= (1 << 22) && crate::gpu_cuda::h3_conv1d(x, w, ic, oc, n, k, pad, dil, out_n, yt)
5685        }
5686        #[allow(unreachable_patterns)]
5687        _ => false,
5688    }
5689}
5690
5691/// The convolution as a GEMM on the matrix units. `false` = refused.
5692#[allow(clippy::too_many_arguments)]
5693pub fn vae_conv2d_coop(
5694    w: &[f32],
5695    bias: Option<&[f32]>,
5696    x: &[f32],
5697    ic: usize,
5698    oc: usize,
5699    h: usize,
5700    wi: usize,
5701    k: usize,
5702    out: &mut [f32],
5703) -> bool {
5704    match backend() {
5705        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5706        Backend::Wgpu => crate::gpu_wgpu::vae_conv2d_coop(w, bias, x, ic, oc, h, wi, k, out),
5707        #[allow(unreachable_patterns)]
5708        _ => false,
5709    }
5710}
5711
5712pub fn dit_attention_packed(
5713    qkv: &[f32],
5714    nh: usize,
5715    n: usize,
5716    hd: usize,
5717    scale: f32,
5718    // (rope angles, q norm weights, k norm weights, eps) when the device
5719    // should apply qk-norm and RoPE itself; None when the host already did.
5720    nr: Option<(&[f32], &[f32], &[f32], f32)>,
5721    out: &mut [f32],
5722) -> bool {
5723    match backend() {
5724        // wgpu carries the only implementation, and it is not
5725        // platform-specific: `CMF_GPU=wgpu` on macOS runs it over Metal
5726        // like anywhere else. It used to be compiled out here on macOS,
5727        // which made the call a silent `false` — and the caller's
5728        // `assert!` turned that refusal into a panic on every
5729        // `cortiq animate` this platform ever ran.
5730        #[cfg(feature = "gpu")]
5731        Backend::Wgpu => crate::gpu_wgpu::dit_attention_packed(qkv, nh, n, hd, scale, nr, out),
5732        #[allow(unreachable_patterns)]
5733        _ => false,
5734    }
5735}
5736
5737/// Whether `dit_attention_packed` has an implementation on the backend
5738/// that is actually selected.
5739///
5740/// The caller has to know BEFORE it skips the host qk-norm: deferring
5741/// the norm to a device that then refuses leaves q/k unnormalized with
5742/// no way back. Native Metal has no packed kernel, so on macOS this is
5743/// false unless `CMF_GPU=wgpu` picked the other backend.
5744pub fn dit_attention_packed_available() -> bool {
5745    #[allow(unreachable_patterns)]
5746    match backend() {
5747        #[cfg(feature = "gpu")]
5748        Backend::Wgpu => crate::gpu_wgpu::dit_attention_packed_ready(),
5749        _ => false,
5750    }
5751}
5752
5753pub fn dit_attention(
5754    qh: &[f32],
5755    kh: &[f32],
5756    vh: &[f32],
5757    nh: usize,
5758    nkv: usize,
5759    n: usize,
5760    hd: usize,
5761    scale: f32,
5762    out: &mut [f32],
5763) -> bool {
5764    match backend() {
5765        #[cfg(target_os = "macos")]
5766        Backend::Metal => crate::gpu_metal::dit_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
5767        #[cfg(feature = "gpu")]
5768        Backend::Wgpu => crate::gpu_wgpu::dit_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
5769        #[cfg(feature = "cuda")]
5770        Backend::Cuda => crate::gpu_cuda::h3_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
5771        #[allow(unreachable_patterns)]
5772        _ => false,
5773    }
5774}
5775
5776/// GPTQ calibration: a zeroed `cols × cols` Hessian accumulator on the
5777/// device (wgpu only), or None — the caller keeps the host fold then.
5778pub fn gram_alloc(cols: usize) -> Option<u64> {
5779    #[cfg(feature = "gpu")]
5780    if backend() == Backend::Wgpu {
5781        return crate::gpu_wgpu::gram::alloc(cols);
5782    }
5783    let _ = cols;
5784    None
5785}
5786
5787/// `H[id] += XᵀX` over `b` rows of `xs` (`[b·cols]`).
5788pub fn gram_add(id: u64, xs: &[f32], b: usize) -> bool {
5789    #[cfg(feature = "gpu")]
5790    if backend() == Backend::Wgpu {
5791        return crate::gpu_wgpu::gram::add(id, xs, b);
5792    }
5793    let _ = (id, xs, b);
5794    false
5795}
5796
5797/// `H[id] += XᵀX` over `b` rows of a device-resident f32 buffer.
5798#[cfg(feature = "gpu")]
5799pub fn gram_add_dev(id: u64, x: &wgpu::Buffer, b: usize) -> bool {
5800    if backend() == Backend::Wgpu {
5801        return crate::gpu_wgpu::gram::add_dev(id, x, b);
5802    }
5803    false
5804}
5805
5806/// The accumulated Hessian as a full symmetric f64 matrix (frees it).
5807pub fn gram_take(id: u64) -> Option<Vec<f64>> {
5808    #[cfg(feature = "gpu")]
5809    if backend() == Backend::Wgpu {
5810        return crate::gpu_wgpu::gram::take(id);
5811    }
5812    let _ = id;
5813    None
5814}
5815
5816/// GPTQ fold of the device Hessian `h_id` on the device: the upper Cholesky
5817/// factor of `(H + λ·mean(diag)·I)⁻¹` stays there under the returned id and
5818/// the Hessian is freed. None (no wgpu device, it does not fit, it does not
5819/// factor): the Hessian is left for `gram_take`.
5820pub fn gptq_fold_dev(h_id: u64, n: usize, lambda: f64) -> Option<u64> {
5821    #[cfg(feature = "gpu")]
5822    if backend() == Backend::Wgpu {
5823        return crate::gpu_wgpu::gptq_dev::fold(h_id, n, lambda);
5824    }
5825    let _ = (h_id, n, lambda);
5826    None
5827}
5828
5829/// (dead channels, raw H diagonal, damping used) of a device fold.
5830pub fn gptq_fold_info(id: u64) -> Option<(Vec<bool>, Vec<f32>, f64)> {
5831    #[cfg(feature = "gpu")]
5832    if backend() == Backend::Wgpu {
5833        return crate::gpu_wgpu::gptq_dev::info(id);
5834    }
5835    let _ = id;
5836    None
5837}
5838
5839/// A device fold's operator read back (n×n f32, upper).
5840pub fn gptq_fold_read(id: u64) -> Option<Vec<f32>> {
5841    #[cfg(feature = "gpu")]
5842    if backend() == Backend::Wgpu {
5843        return crate::gpu_wgpu::gptq_dev::read_u(id);
5844    }
5845    let _ = id;
5846    None
5847}
5848
5849/// Free a device fold.
5850pub fn gptq_fold_free(id: u64) {
5851    #[cfg(feature = "gpu")]
5852    if backend() == Backend::Wgpu {
5853        crate::gpu_wgpu::gptq_dev::free(id);
5854    }
5855    let _ = id;
5856}
5857
5858/// The q4tp GPTQ sweep on the device (see `gpu_wgpu::gptq_dev::sweep_q4tp`).
5859#[allow(clippy::too_many_arguments)]
5860pub fn gptq_sweep_q4tp_dev(
5861    id: u64,
5862    w: &[f32],
5863    rows: usize,
5864    tab: &[f32],
5865    lost: &[f32],
5866    nib: &mut [u8],
5867    codes: &mut [u32],
5868) -> bool {
5869    #[cfg(feature = "gpu")]
5870    if backend() == Backend::Wgpu {
5871        return crate::gpu_wgpu::gptq_dev::sweep_q4tp(id, w, rows, tab, lost, nib, codes);
5872    }
5873    let _ = (id, w, rows, tab, lost, nib, codes);
5874    false
5875}
5876
5877/// The q2tp GPTQ sweep ("placed" rule) on the device.
5878pub fn gptq_sweep_q2tp_dev(
5879    id: u64,
5880    w: &[f32],
5881    rows: usize,
5882    tab: &[f32],
5883    hw: &[f32],
5884    chunks: &mut [u8],
5885    codes: &mut [u32],
5886) -> bool {
5887    #[cfg(feature = "gpu")]
5888    if backend() == Backend::Wgpu {
5889        return crate::gpu_wgpu::gptq_dev::sweep_q2tp(id, w, rows, tab, hw, chunks, codes);
5890    }
5891    let _ = (id, w, rows, tab, hw, chunks, codes);
5892    false
5893}
5894
5895/// A device Hessian read back as a full symmetric f64 matrix, left on the
5896/// device.
5897pub fn gram_read(id: u64) -> Option<Vec<f64>> {
5898    #[cfg(feature = "gpu")]
5899    if backend() == Backend::Wgpu {
5900        return crate::gpu_wgpu::gram::read(id);
5901    }
5902    let _ = id;
5903    None
5904}
5905
5906/// Free every device Hessian (an aborted calibration pass).
5907pub fn gram_clear() {
5908    #[cfg(feature = "gpu")]
5909    if backend() == Backend::Wgpu {
5910        crate::gpu_wgpu::gram::clear();
5911    }
5912}
5913
5914/// Batched q4t GEMM on the device (imagegen DiT prefill shapes).
5915/// Metal: q4t_mul_mm decodes the mmap-resident tiles inside the
5916/// GEMM's K loop. wgpu (Vulkan/DX12 → NVIDIA/AMD/Intel/Adreno/Mali):
5917/// the register-blocked WGSL twin, weights cached in VRAM.
5918#[allow(unused_variables)]
5919pub fn q4tp_matmat(
5920    model: &Arc<CmfModel>,
5921    idx: usize,
5922    xs: &[f32],
5923    b: usize,
5924    rows: usize,
5925    cols: usize,
5926    out: &mut [f32],
5927) -> bool {
5928    match backend() {
5929        #[cfg(target_os = "macos")]
5930        Backend::Metal => crate::gpu_metal::q4tp_matmat(model, idx, xs, b, rows, cols, out),
5931        #[cfg(feature = "gpu")]
5932        Backend::Wgpu => crate::gpu_wgpu::q4tp_matmat(model, idx, xs, b, rows, cols, out),
5933        #[cfg(feature = "cuda")]
5934        Backend::Cuda => crate::gpu_cuda::h3_matmat(model, idx, xs, b, rows, cols, out),
5935        #[allow(unreachable_patterns)]
5936        _ => false,
5937    }
5938}
5939
5940/// A stage of a staged pipeline over `model` is done (the prompt encoder
5941/// before the denoiser, the denoiser before the decoder): the device drops
5942/// what it cached of that model's weights, so the next stage starts from a
5943/// card that holds one component and not their sum.
5944#[allow(unused_variables)]
5945pub fn stage_done(model: &CmfModel) {
5946    match backend() {
5947        #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5948        Backend::Wgpu => {
5949            crate::gpu_wgpu::h3::release();
5950            crate::gpu_wgpu::h3_conv::release();
5951            crate::gpu_wgpu::release_model_buffers(model)
5952        }
5953        #[cfg(feature = "cuda")]
5954        Backend::Cuda => crate::gpu_cuda::h3_release(),
5955        #[cfg(target_os = "macos")]
5956        Backend::Metal => crate::gpu_metal::h3::release(),
5957        #[allow(unreachable_patterns)]
5958        _ => {}
5959    }
5960}
5961
5962/// The resident chain's stage times, when the backend keeps them.
5963pub fn h3_prof_report() -> Option<String> {
5964    match backend() {
5965        #[cfg(feature = "cuda")]
5966        Backend::Cuda => crate::gpu_cuda::h3_prof_report(),
5967        #[allow(unreachable_patterns)]
5968        _ => None,
5969    }
5970}
5971
5972/// Ask the next whole-token or batch graph on this thread to keep the
5973/// residual stream after each of `layers` (absolute indices): a DFlash
5974/// drafter's context reads them. wgpu graphs only (the Metal graphs take
5975/// `tap` calls); an empty list disarms.
5976pub fn layer_taps_arm(layers: &[usize]) {
5977    match backend() {
5978        #[cfg(feature = "gpu")]
5979        Backend::Wgpu => crate::gpu_wgpu::layer_taps_arm(layers),
5980        #[cfg(feature = "cuda")]
5981        Backend::Cuda => crate::gpu_cuda::layer_taps_arm(layers),
5982        #[allow(unreachable_patterns)]
5983        _ => {
5984            let _ = layers;
5985        }
5986    }
5987}
5988
5989/// What the armed graph kept, `[slot][row][hidden]`; disarms. False when it
5990/// kept nothing (another backend, a span without every asked layer, a burst).
5991pub fn layer_taps_take(out: &mut Vec<f32>) -> bool {
5992    match backend() {
5993        #[cfg(feature = "gpu")]
5994        Backend::Wgpu => crate::gpu_wgpu::layer_taps_take(out),
5995        #[cfg(feature = "cuda")]
5996        Backend::Cuda => crate::gpu_cuda::layer_taps_take(out),
5997        #[allow(unreachable_patterns)]
5998        _ => {
5999            let _ = out;
6000            false
6001        }
6002    }
6003}
6004
6005/// Several four-bit GEMMs over the same rows (at most eight), `(directory
6006/// index, rows, cols, take)` each, in one submission on the narrow kernel:
6007/// `outs[i]` is `[b][take]`, the plane's first `take` rows (a head's shortlist
6008/// of the vocabulary; `take = rows` for all of it). Native Metal only: any
6009/// other backend declines and the caller runs them one by one.
6010pub fn q4tp_rows8_many(
6011    model: &Arc<CmfModel>,
6012    jobs: &[(usize, usize, usize, usize)],
6013    xs: &[f32],
6014    b: usize,
6015    outs: &mut [&mut [f32]],
6016) -> bool {
6017    match backend() {
6018        #[cfg(target_os = "macos")]
6019        Backend::Metal => {
6020            let takes: Vec<usize> = jobs.iter().map(|j| j.3).collect();
6021            let jobs: Vec<crate::gpu_metal::MmJob> = jobs
6022                .iter()
6023                .map(|&(idx, rows, cols, _)| crate::gpu_metal::MmJob { idx, rows, cols })
6024                .collect();
6025            crate::gpu_metal::q4tp_n8_many(model, &jobs, Some(&takes), xs, b, outs)
6026        }
6027        #[allow(unreachable_patterns)]
6028        _ => {
6029            let _ = (model, jobs, xs, b, outs);
6030            false
6031        }
6032    }
6033}
6034
6035/// `q4tp_ffn` over at most eight rows on the narrow kernel. Native Metal only.
6036#[allow(clippy::too_many_arguments)]
6037pub fn q4tp_rows8_ffn(
6038    model: &Arc<CmfModel>,
6039    w1: usize,
6040    w3: usize,
6041    w2: usize,
6042    xs: &[f32],
6043    b: usize,
6044    hidden: usize,
6045    inter: usize,
6046    out: &mut [f32],
6047) -> bool {
6048    match backend() {
6049        #[cfg(target_os = "macos")]
6050        Backend::Metal => crate::gpu_metal::q4tp_n8_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
6051        #[allow(unreachable_patterns)]
6052        _ => {
6053            let _ = (model, w1, w3, w2, xs, b, hidden, inter, out);
6054            false
6055        }
6056    }
6057}
6058
6059/// Several four-bit GEMMs over the same rows, `(directory index, rows, cols)`
6060/// each, in one submission (wgpu: narrow batches only). Where it declines the
6061/// caller runs them one by one.
6062pub fn q4tp_matmat_many(
6063    model: &Arc<CmfModel>,
6064    jobs: &[(usize, usize, usize)],
6065    xs: &[f32],
6066    b: usize,
6067    outs: &mut [&mut [f32]],
6068) -> bool {
6069    match backend() {
6070        #[cfg(target_os = "macos")]
6071        Backend::Metal => {
6072            let jobs: Vec<crate::gpu_metal::MmJob> = jobs
6073                .iter()
6074                .map(|&(idx, rows, cols)| crate::gpu_metal::MmJob { idx, rows, cols })
6075                .collect();
6076            crate::gpu_metal::q4tp_matmat_many(model, &jobs, xs, b, outs)
6077        }
6078        #[cfg(feature = "gpu")]
6079        Backend::Wgpu => crate::gpu_wgpu::q4tp_matmat_many(model, jobs, xs, b, outs),
6080        #[allow(unreachable_patterns)]
6081        _ => {
6082            let _ = (model, jobs, xs, b, outs);
6083            false
6084        }
6085    }
6086}
6087
6088/// The same over a two-bit weight plane. Native Metal uses the dedicated
6089/// q2tp tile; unsupported shapes return false and preserve the host fallback.
6090pub fn q2tp_matmat(
6091    model: &Arc<CmfModel>,
6092    idx: usize,
6093    xs: &[f32],
6094    b: usize,
6095    rows: usize,
6096    cols: usize,
6097    out: &mut [f32],
6098) -> bool {
6099    match backend() {
6100        #[cfg(target_os = "macos")]
6101        Backend::Metal => crate::gpu_metal::q2tp_matmat(model, idx, xs, b, rows, cols, out),
6102        #[cfg(feature = "gpu")]
6103        Backend::Wgpu => crate::gpu_wgpu::q2tp_matmat(model, idx, xs, b, rows, cols, out),
6104        #[allow(unreachable_patterns)]
6105        _ => false,
6106    }
6107}
6108
6109/// Descriptor-aware q2tp GEMM. The affine center is selected only for a
6110/// validated q2tp_affine target; the raw dtype16 payload remains unchanged.
6111pub fn q2tp_affine_matmat(
6112    model: &Arc<CmfModel>,
6113    idx: usize,
6114    xs: &[f32],
6115    b: usize,
6116    rows: usize,
6117    cols: usize,
6118    out: &mut [f32],
6119) -> bool {
6120    match backend() {
6121        #[cfg(target_os = "macos")]
6122        Backend::Metal => crate::gpu_metal::q2tp_affine_matmat(model, idx, xs, b, rows, cols, out),
6123        #[cfg(feature = "gpu")]
6124        Backend::Wgpu => crate::gpu_wgpu::q2tp_affine_matmat(model, idx, xs, b, rows, cols, out),
6125        #[allow(unreachable_patterns)]
6126        _ => false,
6127    }
6128}
6129
6130/// Binary low-rank (`blr`) product on the device: `out[b·rows] = xs[b·cols] ·
6131/// Wᵀ` through the two ±1 stages (V then U). `b = 1` is the decode GEMV.
6132/// False = not taken (no wgpu backend — Metal has no blr kernel yet — or a
6133/// shape outside the kernel's contract): the caller runs the CPU kernels.
6134pub fn blr_matmat(t: &crate::blr::BlrTensor, xs: &[f32], b: usize, out: &mut [f32]) -> bool {
6135    match backend() {
6136        #[cfg(feature = "gpu")]
6137        Backend::Wgpu => crate::gpu_wgpu::blr_matmat(t, xs, b, out),
6138        #[allow(unreachable_patterns)]
6139        _ => {
6140            let _ = (t, xs, b, out);
6141            false
6142        }
6143    }
6144}
6145
6146/// `mxfp4` matvec on the device: the wgpu kernel (`gpu_wgpu::mxfp4`).
6147/// Native Metal has no mxfp4 kernel and answers false, as does any shape or
6148/// budget the device path refuses — the CPU kernels run then.
6149pub fn mxfp4_matvec(
6150    model: &Arc<CmfModel>,
6151    idx: usize,
6152    xs: &[f32],
6153    rows: usize,
6154    cols: usize,
6155    out: &mut [f32],
6156) -> bool {
6157    mxfp4_matmat(model, idx, xs, 1, rows, cols, out)
6158}
6159
6160/// Batched `mxfp4` matvec on the device (`xs` `[b, cols]` → `out`
6161/// `[b, rows]`, up to eight tokens per workgroup). false = CPU fallback.
6162pub fn mxfp4_matmat(
6163    model: &Arc<CmfModel>,
6164    idx: usize,
6165    xs: &[f32],
6166    b: usize,
6167    rows: usize,
6168    cols: usize,
6169    out: &mut [f32],
6170) -> bool {
6171    match backend() {
6172        #[cfg(feature = "gpu")]
6173        Backend::Wgpu => crate::gpu_wgpu::mxfp4::matmat(model, idx, xs, b, rows, cols, out),
6174        #[allow(unreachable_patterns)]
6175        _ => {
6176            let _ = (model, idx, xs, b, rows, cols, out);
6177            false
6178        }
6179    }
6180}
6181
6182/// Single-token q2tp matvec through the ordinary (center=1.5) WGSL kernel.
6183pub fn q2tp_matvec(
6184    model: &Arc<CmfModel>,
6185    idx: usize,
6186    xs: &[f32],
6187    rows: usize,
6188    cols: usize,
6189    out: &mut [f32],
6190) -> bool {
6191    match backend() {
6192        #[cfg(target_os = "macos")]
6193        Backend::Metal => crate::gpu_metal::q2tp_matvec(model, idx, xs, rows, cols, out),
6194        #[cfg(feature = "gpu")]
6195        Backend::Wgpu => crate::gpu_wgpu::q2tp_matvec(model, idx, xs, rows, cols, out),
6196        #[allow(unreachable_patterns)]
6197        _ => false,
6198    }
6199}
6200
6201/// Single-token q2tp matvec with the explicit affine center=1 descriptor
6202/// operator. This is kept separate from ordinary q2tp to make accidental
6203/// center changes impossible at a call site.
6204pub fn q2tp_affine_matvec(
6205    model: &Arc<CmfModel>,
6206    idx: usize,
6207    xs: &[f32],
6208    rows: usize,
6209    cols: usize,
6210    out: &mut [f32],
6211) -> bool {
6212    match backend() {
6213        #[cfg(target_os = "macos")]
6214        Backend::Metal => crate::gpu_metal::q2tp_affine_matvec(model, idx, xs, rows, cols, out),
6215        #[cfg(feature = "gpu")]
6216        Backend::Wgpu => crate::gpu_wgpu::q2tp_affine_matvec(model, idx, xs, rows, cols, out),
6217        #[allow(unreachable_patterns)]
6218        _ => false,
6219    }
6220}
6221
6222/// Single-token q4tp matvec on the device — the lm_head class. Through the
6223/// DEDICATED matvec kernel: the batched GEMM at b=1 measured 11.73 ms
6224/// against the host's 9.51 on the release head, so the route that was
6225/// supposed to save eleven milliseconds a token lost its own probe instead.
6226pub fn q4tp_matvec(
6227    model: &Arc<CmfModel>,
6228    idx: usize,
6229    xs: &[f32],
6230    rows: usize,
6231    cols: usize,
6232    out: &mut [f32],
6233) -> bool {
6234    match backend() {
6235        #[cfg(target_os = "macos")]
6236        Backend::Metal => crate::gpu_metal::q4tp_matvec_for_test(model, idx, xs, rows, cols, out),
6237        #[cfg(feature = "gpu")]
6238        Backend::Wgpu => crate::gpu_wgpu::q4tp_matvec(model, idx, xs, rows, cols, out),
6239        #[allow(unreachable_patterns)]
6240        _ => false,
6241    }
6242}
6243
6244/// Single-token q4_tiled matvec on the device — the lm_head class (a
6245/// q4t checkpoint's head is its biggest host matvec, exactly like the
6246/// q4tp twin above). wgpu holds q4t_mv pipelines only inside the graph
6247/// encoder — the standalone arm stays an honest refusal until a
6248/// discrete-GPU q4t model reaches the bench.
6249pub fn q4t_matvec(
6250    model: &Arc<CmfModel>,
6251    idx: usize,
6252    xs: &[f32],
6253    rows: usize,
6254    cols: usize,
6255    out: &mut [f32],
6256) -> bool {
6257    match backend() {
6258        #[cfg(target_os = "macos")]
6259        Backend::Metal => crate::gpu_metal::q4t_matvec_for_test(model, idx, xs, rows, cols, out),
6260        #[allow(unreachable_patterns)]
6261        _ => false,
6262    }
6263}
6264
6265pub fn q4t_matmat(
6266    model: &Arc<CmfModel>,
6267    idx: usize,
6268    xs: &[f32],
6269    b: usize,
6270    rows: usize,
6271    cols: usize,
6272    out: &mut [f32],
6273) -> bool {
6274    match backend() {
6275        #[cfg(target_os = "macos")]
6276        Backend::Metal => crate::gpu_metal::q4t_matmat(model, idx, xs, b, rows, cols, out),
6277        #[cfg(feature = "gpu")]
6278        Backend::Wgpu => crate::gpu_wgpu::q4t_matmat(model, idx, xs, b, rows, cols, out),
6279        #[allow(unreachable_patterns)]
6280        _ => false,
6281    }
6282}
6283
6284// ── d1's one-pass `set` forward (`pipeline_masked`) ──────────────────────
6285// One LFM3 stack over a whole packed row on the device: the backends'
6286// `lfm_set` modules encode every layer in one submission.
6287
6288/// A projection of the packed row: the tensor's directory index, rows and
6289/// columns (`[rows, cols]`, applied as x·Wᵀ).
6290pub type SetW = (usize, usize, usize);
6291
6292pub enum SetMixer<'a> {
6293    Conv {
6294        in_proj: SetW,
6295        out_proj: SetW,
6296        /// `[hidden][kernel]`, tap `kernel-1` on the current position.
6297        taps: &'a [f32],
6298        kernel: usize,
6299    },
6300    Attn {
6301        wq: SetW,
6302        wk: SetW,
6303        wv: SetW,
6304        wo: SetW,
6305        q_norm: Option<&'a [f32]>,
6306        k_norm: Option<&'a [f32]>,
6307        /// The per-head sigmoid gate's f32 rows `[nh × hidden]`.
6308        head_gate: Option<&'a [f32]>,
6309        inv_freq: &'a [f32],
6310        rd: usize,
6311        nkv: usize,
6312        /// Sliding window (causal); None: d1's `set` mask.
6313        window: Option<usize>,
6314    },
6315}
6316
6317pub struct SetLayer<'a> {
6318    pub input_norm: &'a [f32],
6319    pub post_norm: &'a [f32],
6320    pub mixer: SetMixer<'a>,
6321    pub attn_out_norm: Option<&'a [f32]>,
6322    pub ffn_out_norm: Option<&'a [f32]>,
6323    /// The SiLU FFN's gate, up and down.
6324    pub gate: SetW,
6325    pub up: SetW,
6326    pub down: SetW,
6327}
6328
6329pub struct SetDims {
6330    pub hidden: usize,
6331    pub nh: usize,
6332    pub hd: usize,
6333    pub eps: f32,
6334    pub gemma: bool,
6335    pub scale: f32,
6336}
6337
6338/// The vocabulary head over chosen rows of the set forward: the head's
6339/// projection and the row indices (d1's answer slots).
6340pub struct SetHead<'a> {
6341    pub w: SetW,
6342    pub rows: &'a [usize],
6343}
6344
6345/// d1's `set` forward on the device: the final-normed hidden rows `[t,
6346/// hidden]` of the embedding rows `rows` and, with `head`, the logits
6347/// `[head.rows, vocab]` of its rows (empty without), or None when the
6348/// backend or a weight is outside the kernels (the host path answers).
6349#[allow(clippy::too_many_arguments, unused_variables)]
6350pub fn lfm_set_forward(
6351    model: &Arc<CmfModel>,
6352    layers: &[SetLayer],
6353    dims: &SetDims,
6354    final_norm: &[f32],
6355    rows: &[f32],
6356    t: usize,
6357    state: usize,
6358    group: &[i32],
6359    head: Option<&SetHead>,
6360) -> Option<(Vec<f32>, Vec<f32>)> {
6361    #[allow(unreachable_patterns)]
6362    match backend() {
6363        #[cfg(target_os = "macos")]
6364        Backend::Metal => crate::gpu_metal::lfm_set::forward(
6365            model, layers, dims, final_norm, rows, t, state, group, head,
6366        ),
6367        #[cfg(feature = "gpu")]
6368        Backend::Wgpu => crate::gpu_wgpu::lfm_set::forward(
6369            model, layers, dims, final_norm, rows, t, state, group, head,
6370        ),
6371        #[cfg(feature = "cuda")]
6372        Backend::Cuda => crate::gpu_cuda::h3_lfm_set_forward(
6373            model, layers, dims, final_norm, rows, t, state, group, head,
6374        ),
6375        _ => None,
6376    }
6377}
6378
6379/// Whole-block token-graph types re-exported from the Metal backend.
6380#[cfg(target_os = "macos")]
6381pub use crate::gpu_metal::{
6382    AttnDeviceParams, AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, GpuFlintMoe, GpuMoe, GraphDims,
6383    MetalFfn, O1AttnParams, SconvGpuLayer, TokenGraph, kv_mirror_drop, kv_mirror_read_last,
6384    kv_mirror_take_imp,
6385};
6386
6387/// A BLOCK of consecutive q1 GDN layers in one submission (Metal only).
6388#[cfg(target_os = "macos")]
6389pub fn gdn_block(
6390    model: &Arc<CmfModel>,
6391    layers: &[GdnGpuLayer],
6392    states: &mut [&mut [f32]],
6393    cfg: &GdnGpuCfg,
6394    h: &mut [f32],
6395) -> bool {
6396    match backend() {
6397        Backend::Metal => crate::gpu_metal::gdn_block(model, layers, states, cfg, h),
6398        _ => false,
6399    }
6400}
6401
6402/// A layer's MoE-FFN in one submission (amortizing the dispatch cost).
6403#[allow(unused_variables)]
6404pub fn moe_block(model: &Arc<CmfModel>, jobs: &[MoeJob], out: &mut [f32]) -> bool {
6405    match backend() {
6406        // Each backend validates its own complete activation contract.  In
6407        // particular Metal admits M3 code 3 only through its dedicated OAI
6408        // kernels and rejects every mixed/nearby variant; filtering here
6409        // would make that safe path unreachable.
6410        #[cfg(target_os = "macos")]
6411        Backend::Metal => crate::gpu_metal::moe_block(model, jobs, out),
6412        #[cfg(feature = "gpu")]
6413        Backend::Wgpu => crate::gpu_wgpu::moe_block(model, jobs, out),
6414        Backend::None => false,
6415        #[cfg(feature = "cuda")]
6416        Backend::Cuda => false,
6417    }
6418}
6419
6420/// Independent matvecs of one input in a single submission (GDN projections).
6421#[allow(unused_variables)]
6422pub fn matvec_batch(model: &Arc<CmfModel>, jobs: &[BatchJob], out: &mut [&mut [f32]]) -> bool {
6423    match backend() {
6424        #[cfg(target_os = "macos")]
6425        Backend::Metal => crate::gpu_metal::matvec_batch(model, jobs, out),
6426        #[cfg(feature = "gpu")]
6427        Backend::Wgpu => crate::gpu_wgpu::matvec_batch(model, jobs, out),
6428        Backend::None => false,
6429        #[cfg(feature = "cuda")]
6430        Backend::Cuda => false,
6431    }
6432}
6433
6434// ── Whole-token wgpu graph race (generation granularity) ─────────────
6435// On integrated/mobile adapters the graph is neither trusted nor banned
6436// a priori — it RACES the normal path: generations alternate arms (the
6437// normal path first — known-good UX — then the graph), per-token wall
6438// times accumulate per arm, and once both arms have enough steady
6439// samples the faster one wins for the process. Arm switches happen ONLY
6440// at generation boundaries (`kv_cache.clear()` resets state), so the
6441// device KV mirror and the CPU cache never diverge mid-sequence. The
6442// single exception is the first-token bail: the very first decode token
6443// of a graph generation may be discarded and recomputed on the CPU
6444// path (the prompt KV is CPU-owned at that point, so this is safe) —
6445// a tiled mobile GPU that drains its pipeline at every barrier turns
6446// the ~300-dispatch graph into seconds per token (field report: 0.2
6447// tok/s vs 15 on the CPU), and one token is all it takes to see that.
6448static GRAPH_RACE_STATE: AtomicU8 = AtomicU8::new(0); // 0 racing, 1 graph won, 2 normal won
6449static GRAPH_RACE_FLIP: AtomicU32 = AtomicU32::new(0);
6450static GRAPH_RACE_ARM_GRAPH: AtomicU8 = AtomicU8::new(0); // this generation's arm
6451static GRAPH_RACE_TOK: AtomicU32 = AtomicU32::new(0); // token index within the generation
6452static GRAPH_NS: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; // [normal, graph]
6453static GRAPH_N: [AtomicU32; 2] = [AtomicU32::new(0), AtomicU32::new(0)];
6454
6455/// Steady per-token samples per arm before the race decides.
6456const GRAPH_RACE_SAMPLES: u32 = 4;
6457
6458// A graph that cannot be built for THIS model will never build: the
6459// refusal is a property of the weights, not of the moment. Retrying it
6460// per token is not free — the builder walks every layer and asks each
6461// tensor for a graph view before giving up at layer 0 — and on an
6462// Adreno 642L that retry cost 3x: forcing the graph on a model it
6463// refuses measured 0.3 tok/s against 0.905 for the per-op path it falls
6464// back to. Remembered once, the fallback runs at its own speed.
6465//
6466// The verdict is kept PER PIPELINE (`Pipeline::graph_refused` /
6467// `mark_graph_refused`), not in a process-wide flag: several pipelines
6468// of one file share a process in `serve` (backbone slots + skill lanes
6469// loaded mid-traffic), and a refusal in one lane — or the reset a new
6470// lane used to issue — must not move another lane's running sequence
6471// between the device and the host (R4/NF-2). Callers must NOT report
6472// transient refusals (an unsealed o1 state during prefill, a softcap).
6473
6474/// Called at every generation start (fresh KV). Applies a pending
6475/// verdict and picks this generation's arm while racing.
6476/// A generation has ended: keep whatever the driver compiled during it
6477/// (`pipeline_cache_flush_if_grown`). No-op off wgpu and when nothing is new.
6478pub fn generation_end() {
6479    #[cfg(feature = "gpu")]
6480    if matches!(backend(), Backend::Wgpu) {
6481        crate::gpu_wgpu::pipeline_cache_flush_if_grown();
6482    }
6483}
6484
6485pub fn graph_race_begin_generation() {
6486    // One generation has now compiled whatever this model needs; keep it
6487    // for the next process. Once per run: the blob does not grow after
6488    // the pipelines exist, and the write is megabytes against the ~200 s
6489    // of compiling it saves on the device that needed this.
6490    #[cfg(feature = "gpu")]
6491    {
6492        // Save once, at the start of the SECOND generation: the first
6493        // has dispatched, so there is something to keep, and nothing is
6494        // saved before any work (the driver compiles at first use, not
6495        // at pipeline creation — the context comes up in 1.5 s while the
6496        // compiling costs minutes).
6497        //
6498        // Flushing again on 4, 8, 16 … was tried on the theory that a
6499        // chat turn compiles shapes the first one did not. It buys
6500        // nothing: a fresh app process still spent 49.0 s, then 58.7,
6501        // then 61.3 on its first answer with the backoff in place. One
6502        // flush it is.
6503        static FLUSHED: std::sync::Once = std::sync::Once::new();
6504        static FIRST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
6505        if FIRST.swap(false, Ordering::Relaxed) {
6506            // Nothing dispatched yet.
6507        } else {
6508            FLUSHED.call_once(crate::gpu_wgpu::pipeline_cache_flush);
6509        }
6510    }
6511    GRAPH_RACE_TOK.store(0, Ordering::Relaxed);
6512    if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
6513        return;
6514    }
6515    let (gn, cn) = (
6516        GRAPH_N[1].load(Ordering::Relaxed),
6517        GRAPH_N[0].load(Ordering::Relaxed),
6518    );
6519    if gn >= GRAPH_RACE_SAMPLES && cn >= GRAPH_RACE_SAMPLES {
6520        let g_avg = GRAPH_NS[1].load(Ordering::Relaxed) / gn as u64;
6521        let c_avg = GRAPH_NS[0].load(Ordering::Relaxed) / cn as u64;
6522        let verdict = if g_avg < c_avg { 1 } else { 2 };
6523        GRAPH_RACE_STATE.store(verdict, Ordering::Relaxed);
6524        tracing::info!(
6525            "wgpu graph race: graph {:.2} ms/tok vs normal {:.2} ms/tok -> {}",
6526            g_avg as f64 / 1e6,
6527            c_avg as f64 / 1e6,
6528            if verdict == 1 { "graph" } else { "normal path" }
6529        );
6530        return;
6531    }
6532    let flip = GRAPH_RACE_FLIP.fetch_add(1, Ordering::Relaxed);
6533    GRAPH_RACE_ARM_GRAPH.store((flip % 2 == 1) as u8, Ordering::Relaxed);
6534}
6535
6536/// Should this decode token try the graph? `trusted` (discrete adapter,
6537/// explicit env, or a GDN hybrid whose state lives on the device) skips
6538/// the race entirely.
6539pub fn graph_race_use_graph(trusted: bool) -> bool {
6540    if trusted {
6541        return true;
6542    }
6543    match GRAPH_RACE_STATE.load(Ordering::Relaxed) {
6544        1 => true,
6545        2 => false,
6546        _ => GRAPH_RACE_ARM_GRAPH.load(Ordering::Relaxed) == 1,
6547    }
6548}
6549
6550/// First decode token of a racing graph generation: hopeless already?
6551/// (>4x the normal path's per-token average AND over a second.) Settles
6552/// the race immediately; the caller discards the graph result and
6553/// recomputes this token on the normal path.
6554pub fn graph_race_first_token_hopeless(dur: std::time::Duration) -> bool {
6555    if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
6556        return false;
6557    }
6558    let first = GRAPH_RACE_TOK.load(Ordering::Relaxed) == 0;
6559    let cn = GRAPH_N[0].load(Ordering::Relaxed);
6560    if !first || cn == 0 {
6561        return false;
6562    }
6563    let c_avg = GRAPH_NS[0].load(Ordering::Relaxed) / cn as u64;
6564    let ns = dur.as_nanos() as u64;
6565    if ns > 1_000_000_000 && ns > 4 * c_avg {
6566        GRAPH_RACE_STATE.store(2, Ordering::Relaxed);
6567        tracing::info!(
6568            "wgpu graph race: first graph token {:.0} ms vs normal {:.2} ms/tok — hopeless, normal path wins",
6569            ns as f64 / 1e6,
6570            c_avg as f64 / 1e6
6571        );
6572        return true;
6573    }
6574    false
6575}
6576
6577/// Record one decode-token wall time for the racing arm. The first
6578/// token of each generation is discarded (KV-mirror upload / cold
6579/// caches on the graph arm; cold mmap on the normal arm).
6580pub fn graph_race_record(used_graph: bool, dur: std::time::Duration) {
6581    if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
6582        return;
6583    }
6584    let tok = GRAPH_RACE_TOK.fetch_add(1, Ordering::Relaxed);
6585    if tok == 0 {
6586        return;
6587    }
6588    let i = used_graph as usize;
6589    GRAPH_NS[i].fetch_add(dur.as_nanos() as u64, Ordering::Relaxed);
6590    GRAPH_N[i].fetch_add(1, Ordering::Relaxed);
6591}
6592
6593/// Bounded-cost content fingerprint for the backends' pointer-keyed device
6594/// caches: FNV over the whole slice up to 4 KiB, over 64 spread 64-byte
6595/// windows (plus the length) above. An address-keyed hit must also prove
6596/// the bytes are still the ones it uploaded — the allocator reuses heap
6597/// and mmap addresses freely, so a reloaded model or a re-dequantized
6598/// layer lands where the old bytes were — and sampling keeps that proof at
6599/// ~a microsecond even for a 126 MB matrix. Real replacements (another
6600/// model's tensor, an Adam-updated master) differ densely, so a 4 KiB
6601/// spread cannot miss them.
6602pub(crate) fn fp_bytes(data: &[u8]) -> u64 {
6603    #[inline]
6604    fn fnv(mut h: u64, bytes: &[u8]) -> u64 {
6605        let (chunks, tail) = bytes.split_at(bytes.len() & !7);
6606        for c in chunks.chunks_exact(8) {
6607            h ^= u64::from_le_bytes(c.try_into().unwrap());
6608            h = h.wrapping_mul(0x100_0000_01b3);
6609        }
6610        for &b in tail {
6611            h ^= b as u64;
6612            h = h.wrapping_mul(0x100_0000_01b3);
6613        }
6614        h
6615    }
6616    let mut h = 0xcbf2_9ce4_8422_2325u64 ^ (data.len() as u64);
6617    if data.len() <= 4096 {
6618        return fnv(h, data);
6619    }
6620    let step = (data.len() - 64) / 63;
6621    for i in 0..64 {
6622        h = fnv(h, &data[i * step..i * step + 64]);
6623    }
6624    h
6625}
6626
6627/// `fp_bytes` over an f32 slice without a bytemuck dependency (the Metal
6628/// backend builds with no GPU feature flags).
6629pub(crate) fn fp_f32(data: &[f32]) -> u64 {
6630    let bytes = unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, data.len() * 4) };
6631    fp_bytes(bytes)
6632}
6633
6634#[cfg(test)]
6635mod fp_tests {
6636    use super::fp_bytes;
6637
6638    /// The pointer-keyed caches survive on `fp_bytes` telling two different
6639    /// tensors apart at a reused address. Its sampling must therefore see a
6640    /// change ANYWHERE — head, tail, and the stretches between windows are
6641    /// the places a cheaper hash would go blind.
6642    #[test]
6643    fn fp_bytes_sees_a_change_anywhere_in_a_sampled_slice() {
6644        let n = 1 << 20; // 1 MiB — far above the 4 KiB full-hash threshold
6645        let base: Vec<u8> = (0..n).map(|i| (i * 31 + 7) as u8).collect();
6646        let h0 = fp_bytes(&base);
6647        assert_eq!(h0, fp_bytes(&base), "fingerprint must be deterministic");
6648        // A DENSE change (every requantized/redequantized tensor is one)
6649        // must flip the fingerprint no matter how the windows fall.
6650        let mut dense = base.clone();
6651        for b in dense.iter_mut() {
6652            *b = b.wrapping_add(1);
6653        }
6654        assert_ne!(
6655            h0,
6656            fp_bytes(&dense),
6657            "a fully different tensor slipped through"
6658        );
6659        // Length participates: the same prefix at a shorter length is a
6660        // different key AND a different fingerprint.
6661        assert_ne!(h0, fp_bytes(&base[..n - 64]));
6662        // Below the threshold the hash is exact: a single flipped byte in
6663        // a norm-sized vector must be seen.
6664        let mut small = vec![3u8; 4096];
6665        let hs = fp_bytes(&small);
6666        small[2048] ^= 1;
6667        assert_ne!(hs, fp_bytes(&small), "full hash missed a one-byte change");
6668        // And the sampled windows land within bounds on awkward sizes.
6669        for n in [4097usize, 5000, 64 * 64, 1 << 16] {
6670            let v = vec![9u8; n];
6671            let _ = fp_bytes(&v); // must not panic on window math
6672        }
6673    }
6674}
6675
6676/// Hand the card back after a bake: drop its resident weights, planes and
6677/// pools so the ordinary engine (the runtime gate, a serve that follows)
6678/// starts from a clean budget. No-op off the wgpu backend.
6679pub fn bake_release() {
6680    #[cfg(feature = "gpu")]
6681    crate::gpu_wgpu::bake_release();
6682}
6683
6684/// Strict-f32 for the bake's GEMMs (phase A mask training): the mask
6685/// selects neurons by a gradient signal, and f16 operand rounding on
6686/// that signal closes the wrong ones. No-op off the wgpu backend.
6687pub fn bake_precision_strict(on: bool) {
6688    #[cfg(feature = "gpu")]
6689    crate::gpu_wgpu::bake_precision_strict(on);
6690    #[cfg(not(feature = "gpu"))]
6691    let _ = on;
6692}
6693
6694/// CMF_GRAPH_HOSTPROF=1: how a graph token's wall splits between the
6695/// host encoding the command stream and the tail the GPU still owes
6696/// after encode. Fifteen GPU-side suspects measured null while the
6697/// bench counted 17.7k allocations a token — this is the instrument
6698/// that says whether the thief was on the host all along.
6699pub fn hostprof_encode_done(t0: std::time::Instant) {
6700    use std::sync::atomic::{AtomicU64, Ordering};
6701    static ENC: AtomicU64 = AtomicU64::new(0);
6702    static N: AtomicU64 = AtomicU64::new(0);
6703    if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() != Ok("1") {
6704        return;
6705    }
6706    ENC.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);
6707    let n = N.fetch_add(1, Ordering::Relaxed) + 1;
6708    if n % 100 == 0 {
6709        eprintln!(
6710            "hostprof: encode {:.2} ms/token over {n} tokens",
6711            ENC.load(Ordering::Relaxed) as f64 / n as f64 / 1e6
6712        );
6713    }
6714}
6715
6716pub fn hostprof_total(t0: std::time::Instant) {
6717    use std::sync::atomic::{AtomicU64, Ordering};
6718    static TOT: AtomicU64 = AtomicU64::new(0);
6719    static N: AtomicU64 = AtomicU64::new(0);
6720    if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() != Ok("1") {
6721        return;
6722    }
6723    TOT.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);
6724    let n = N.fetch_add(1, Ordering::Relaxed) + 1;
6725    if n % 100 == 0 {
6726        eprintln!(
6727            "hostprof: total {:.2} ms/token over {n} tokens",
6728            TOT.load(Ordering::Relaxed) as f64 / n as f64 / 1e6
6729        );
6730    }
6731}
6732
6733/// Per-stage host-encode accumulator for the Metal token loop
6734/// (CMF_GRAPH_HOSTPROF=1). Stage 0 = GDN-run encode; everything else
6735/// falls out by subtraction from hostprof's encode total.
6736pub fn stageprof(stage: u32, dt: std::time::Duration) {
6737    use std::sync::atomic::{AtomicU64, Ordering};
6738    static NS: [AtomicU64; 4] = [
6739        AtomicU64::new(0),
6740        AtomicU64::new(0),
6741        AtomicU64::new(0),
6742        AtomicU64::new(0),
6743    ];
6744    static N: AtomicU64 = AtomicU64::new(0);
6745    if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() != Ok("1") {
6746        return;
6747    }
6748    NS[stage as usize % 4].fetch_add(dt.as_nanos() as u64, Ordering::Relaxed);
6749    if stage == 1 {
6750        let n = N.fetch_add(1, Ordering::Relaxed) + 1;
6751        if n % 200 == 0 {
6752            eprintln!(
6753                "stageprof: planning {:.2} ms/tok | gdn-item {:.2} ms/tok | attn-item {:.2} ms/tok ({n} tok)",
6754                NS[1].load(Ordering::Relaxed) as f64 / n as f64 / 1e6,
6755                NS[2].load(Ordering::Relaxed) as f64 / n as f64 / 1e6,
6756                NS[3].load(Ordering::Relaxed) as f64 / n as f64 / 1e6
6757            );
6758        }
6759    }
6760}
6761
6762/// Active weight bytes dispatched so far (Metal decode path); 0 where
6763/// the backend does not count. The honest floor's numerator.
6764pub fn weight_bytes_dispatched() -> u64 {
6765    let mut total = 0u64;
6766    #[cfg(target_os = "macos")]
6767    {
6768        total += crate::gpu_metal::WEIGHT_BYTES.load(std::sync::atomic::Ordering::Relaxed);
6769    }
6770    #[cfg(feature = "gpu")]
6771    {
6772        total += crate::gpu_wgpu::WEIGHT_BYTES.load(std::sync::atomic::Ordering::Relaxed);
6773    }
6774    total
6775}
6776
6777/// The per-stage split of `weight_bytes_dispatched`:
6778/// [misc, dense-ffn, moe, attn, gdn, head].
6779pub fn weight_bytes_by() -> [u64; 6] {
6780    #[cfg(target_os = "macos")]
6781    {
6782        let mut o = [0u64; 6];
6783        for (i, a) in crate::gpu_metal::WEIGHT_BYTES_BY.iter().enumerate() {
6784            o[i] = a.load(std::sync::atomic::Ordering::Relaxed);
6785        }
6786        return o;
6787    }
6788    #[allow(unreachable_code)]
6789    [0; 6]
6790}
6791
6792#[cfg(test)]
6793mod f16_guard_tests {
6794    use super::*;
6795
6796    /// The f16 guard's maximum: the largest magnitude through the lanes and
6797    /// the remainder, +inf for an inf or a NaN anywhere.
6798    #[test]
6799    fn abs_max_or_inf_is_the_magnitude_maximum() {
6800        let mut xs: Vec<f32> = (0..37).map(|i| (i as f32 - 18.0) * 0.5).collect();
6801        assert_eq!(abs_max_or_inf(&xs), 9.0);
6802        xs[36] = -70000.0; // the remainder
6803        assert_eq!(abs_max_or_inf(&xs), 70000.0);
6804        xs[3] = f32::NAN; // a lane
6805        assert_eq!(abs_max_or_inf(&xs), f32::INFINITY);
6806        xs[3] = 0.0;
6807        xs[35] = f32::NEG_INFINITY;
6808        assert_eq!(abs_max_or_inf(&xs), f32::INFINITY);
6809        assert_eq!(abs_max_or_inf(&[]), 0.0);
6810        assert_eq!(abs_max_or_inf(&[-0.0, -1e-30]), 1e-30);
6811    }
6812}
6813
6814#[cfg(test)]
6815mod probe_warmup_tests {
6816    use super::*;
6817    use std::time::Duration;
6818
6819    fn ms(v: f64) -> Duration {
6820        Duration::from_nanos((v * 1e6) as u64)
6821    }
6822
6823    /// The bug this pins, measured on an A100: the first device call for
6824    /// a class compiles its pipeline, was timed at 117.01 ms against the
6825    /// host's 3.19, and sent `gemm-nt` to the CPU for the whole process —
6826    /// which ran a 27B bake on 2.6 cores with the card idle.
6827    #[test]
6828    fn one_cold_first_sample_does_not_lose_the_class() {
6829        let p = Probe::new();
6830        // First device sample is the pipeline build. Then the truth.
6831        probe_record_into(&p, "gemm-nt", None, true, ms(117.01));
6832        probe_record_into(&p, "gemm-nt", None, true, ms(1.1));
6833        probe_record_into(&p, "gemm-nt", None, true, ms(1.0));
6834        probe_record_into(&p, "gemm-nt", None, false, ms(3.19));
6835        probe_record_into(&p, "gemm-nt", None, false, ms(3.20));
6836        assert_eq!(
6837            p.state.load(Ordering::Relaxed),
6838            1,
6839            "the device is 3x faster once warm and must win"
6840        );
6841    }
6842
6843    /// The warm-up must not become a way to never decide, and must not
6844    /// underflow: a blind decrement at zero wraps a u32 to its maximum
6845    /// and mutes the arm for the life of the process.
6846    #[test]
6847    fn the_warmup_is_spent_once_and_never_underflows() {
6848        let p = Probe::new();
6849        for _ in 0..8 {
6850            probe_record_into(&p, "matmat", None, true, ms(10.0));
6851        }
6852        assert_eq!(p.gpu_burn.load(Ordering::Relaxed), 0, "spent, not wrapped");
6853        assert_eq!(
6854            p.gpu_n.load(Ordering::Relaxed),
6855            7,
6856            "one sample burned, the rest counted"
6857        );
6858    }
6859
6860    /// A device path that always refuses records no timing, so without
6861    /// counting the refusals the class can never reach a verdict. On an
6862    /// M4 with LFM2.5-2.6B `ffn` was still undecided after 9000 calls,
6863    /// alternating arms and paying a failed device attempt on half of
6864    /// them.
6865    #[test]
6866    fn a_class_whose_device_always_declines_settles_on_the_host() {
6867        let _probe_guard = probe_test_guard();
6868        // A class no other test in this file touches: `probe_note_decline`
6869        // works on the process-wide probes by design, and the tests in
6870        // this binary share them.
6871        let c = OpClass::MatmatWide;
6872        let p = &PROBES[c as usize];
6873        p.state.store(0, Ordering::Relaxed);
6874        p.declines.store(0, Ordering::Relaxed);
6875        for _ in 0..(PROBE_DECLINE_LIMIT - 1) {
6876            probe_note_decline(c);
6877        }
6878        assert_eq!(
6879            p.state.load(Ordering::Relaxed),
6880            0,
6881            "one short of the limit is still a question, not an answer"
6882        );
6883        probe_note_decline(c);
6884        assert_eq!(p.state.load(Ordering::Relaxed), 2, "settled on the host");
6885        assert!(matches!(probe_arm(c), ProbeArm::Cpu));
6886        p.state.store(0, Ordering::Relaxed);
6887        p.declines.store(0, Ordering::Relaxed);
6888    }
6889
6890    /// A genuinely slower device still loses — the warm-up removes an
6891    /// artefact, it does not put a thumb on the scale.
6892    #[test]
6893    fn a_slow_device_still_loses_after_the_warmup() {
6894        let p = Probe::new();
6895        for _ in 0..4 {
6896            probe_record_into(&p, "matvec", None, true, ms(40.0));
6897        }
6898        for _ in 0..4 {
6899            probe_record_into(&p, "matvec", None, false, ms(2.0));
6900        }
6901        assert_eq!(p.state.load(Ordering::Relaxed), 2, "host wins on merit");
6902    }
6903}
6904
6905/// Scratch/weight lifetime for a synchronous image-pipeline stage. Declare
6906/// this before the stage model so the model drops before cache collection.
6907pub(crate) struct ImageStageGuard {
6908    #[cfg(target_os = "macos")]
6909    metal: Option<crate::gpu_metal::ImageStageGuard>,
6910    #[cfg(feature = "gpu")]
6911    wgpu: crate::gpu_wgpu::ImageStageGuard,
6912}
6913
6914pub(crate) fn image_stage_scope() -> ImageStageGuard {
6915    ImageStageGuard {
6916        #[cfg(target_os = "macos")]
6917        metal: if matches!(backend(), Backend::Metal) {
6918            Some(crate::gpu_metal::image_stage_scope())
6919        } else {
6920            None
6921        },
6922        #[cfg(feature = "gpu")]
6923        wgpu: crate::gpu_wgpu::image_stage_scope(),
6924    }
6925}
6926
6927impl ImageStageGuard {
6928    pub(crate) fn track_model(&mut self, uid: u64) {
6929        #[cfg(target_os = "macos")]
6930        if let Some(metal) = &mut self.metal {
6931            metal.track_model(uid);
6932        }
6933        #[cfg(feature = "gpu")]
6934        self.wgpu.track_model(uid);
6935        #[cfg(not(target_os = "macos"))]
6936        let _ = uid;
6937    }
6938}
6939
6940// ════════════════════════════════════════════════════════════════════
6941// Z-Image-Turbo device contract (WP0 scaffold, plan §2.1). APPEND-ONLY.
6942//
6943// Owner of the contract: the WP1 lead. The backends implement it in their
6944// own child modules — `gpu_wgpu/zimage.rs` (WP2) and `gpu_metal/zimage.rs`
6945// (WP3) — and never edit the parent files. New fields are added only as
6946// `Option<…>` with agreed semantics; existing fields never change meaning.
6947//
6948// Convention (the same as every `gpu::*` entry): `false` = "not handled",
6949// nothing observable was changed, and the caller runs the CPU path
6950// (`zimage::ZImageDit::step_cpu` etc.), which is the bit-level reference.
6951//
6952// Sequence order everywhere is diffusers' [img rows…, cap rows…], with
6953// padded lengths n_img_p = ceil32(n_img) and n_cap_p = ceil32(L).
6954// ════════════════════════════════════════════════════════════════════
6955
6956// ───────────────────── Qwen-Image-2.1 device contract ─────────────────────
6957
6958/// Geometry of the Qwen-Image-2.1 denoiser.
6959#[derive(Clone, Copy, Debug, PartialEq)]
6960pub struct Qi21Geom {
6961    pub hidden: usize,
6962    pub nh: usize,
6963    pub hd: usize,
6964    pub inter: usize,
6965    pub in_ch: usize,
6966    pub eps: f32,
6967}
6968
6969/// One block's weights: tensor indices of `to_q, to_k, to_v, to_out.0,
6970/// gate_layer, proj (up), out (down)` and the per-head q/k norm weights.
6971pub struct Qi21BlockRef<'a> {
6972    pub w: [usize; 7],
6973    pub norm_q: &'a [f32],
6974    pub norm_k: &'a [f32],
6975}
6976
6977/// Everything the device needs to build a program and run its prefix.
6978pub struct Qi21PrefillArgs<'a> {
6979    pub model: &'a Arc<CmfModel>,
6980    pub geom: Qi21Geom,
6981    pub blocks: &'a [Qi21BlockRef<'a>],
6982    /// `img_in` [hidden, 64] and `proj_out` [64, hidden], f32.
6983    pub img_in: &'a [f32],
6984    pub proj_out: &'a [f32],
6985    pub key: u64,
6986    /// Prefix rows after `txt_in` / `img_in`, `[lp, hidden]`.
6987    pub x: &'a [f32],
6988    pub lp: usize,
6989    /// RoPE cos/sin of the prefix rows and of the target rows, `[rows, 64]`.
6990    pub rope_p: (&'a [f32], &'a [f32]),
6991    pub rope_t: (&'a [f32], &'a [f32]),
6992    /// Keys each prefix row sees (a leading run; non-decreasing).
6993    pub vis: &'a [u32],
6994    /// The t = 0 modulation `[s1|g1|s2|g2]`.
6995    pub mods0: &'a [f32],
6996    /// Target rows.
6997    pub n: usize,
6998}
6999
7000/// Build the program `a.key` and run its prefix on the device.
7001#[allow(unused_variables)]
7002pub fn qi21_prefill(a: &Qi21PrefillArgs) -> bool {
7003    match backend() {
7004        #[cfg(target_os = "macos")]
7005        Backend::Metal => crate::gpu_metal::qi21::prefill(a),
7006        #[cfg(feature = "gpu")]
7007        Backend::Wgpu => crate::gpu_wgpu::qi21::prefill(a),
7008        #[cfg(feature = "cuda")]
7009        Backend::Cuda => crate::gpu_cuda::qi21_prefill(a),
7010        #[allow(unreachable_patterns)]
7011        _ => false,
7012    }
7013}
7014
7015/// One denoiser call of program `key`: `xtok [n, 64]` → `out [n, 64]`.
7016#[allow(unused_variables)]
7017pub fn qi21_step(key: u64, xtok: &[f32], mods: &[f32], fs: &[f32], out: &mut [f32]) -> bool {
7018    match backend() {
7019        #[cfg(target_os = "macos")]
7020        Backend::Metal => crate::gpu_metal::qi21::step(key, xtok, mods, fs, out),
7021        #[cfg(feature = "gpu")]
7022        Backend::Wgpu => crate::gpu_wgpu::qi21::step(key, xtok, mods, fs, out),
7023        #[cfg(feature = "cuda")]
7024        Backend::Cuda => crate::gpu_cuda::qi21_step(key, xtok, mods, fs, out),
7025        #[allow(unreachable_patterns)]
7026        _ => false,
7027    }
7028}
7029
7030/// Drop program `key`. The wgpu module is released directly (module-local
7031/// state only), so a release never brings a device up.
7032#[allow(unused_variables)]
7033pub fn qi21_release_key(key: u64) {
7034    #[cfg(target_os = "macos")]
7035    if matches!(backend(), Backend::Metal) {
7036        crate::gpu_metal::qi21::release_key(key);
7037    }
7038    #[cfg(feature = "gpu")]
7039    crate::gpu_wgpu::qi21::release_key(key);
7040    #[cfg(feature = "cuda")]
7041    if matches!(backend(), Backend::Cuda) {
7042        crate::gpu_cuda::qi21_release_key(key);
7043    }
7044}
7045
7046/// Drop the denoiser's device state (see `qi21_release_key`), and the
7047/// resident VAE decoder's weights.
7048pub fn qi21_release() {
7049    #[cfg(target_os = "macos")]
7050    if matches!(backend(), Backend::Metal) {
7051        crate::gpu_metal::qi21::release();
7052    }
7053    #[cfg(feature = "gpu")]
7054    {
7055        crate::gpu_wgpu::qi21::release();
7056        crate::gpu_wgpu::qi21_vae::release();
7057    }
7058    #[cfg(feature = "cuda")]
7059    if matches!(backend(), Backend::Cuda) {
7060        crate::gpu_cuda::qi21_release();
7061    }
7062}
7063
7064/// One conv of the Qwen-Image-2.1 VAE decoder: host f32 weights
7065/// `[co][ci][k][k]` and bias `[co]` (k = 1 or 3, stride 1, same padding).
7066#[derive(Clone, Copy)]
7067pub struct Qi21VaeConvRef<'a> {
7068    pub w: &'a [f32],
7069    pub b: &'a [f32],
7070    pub ci: usize,
7071    pub co: usize,
7072    pub k: usize,
7073}
7074
7075/// A residual block: `conv2(φ(conv1(φ(x)))) + x` (through the 1×1
7076/// shortcut when ci ≠ co), φ = RMS_norm over channels (x/‖x‖·√C·γ), SiLU.
7077pub struct Qi21VaeResRef<'a> {
7078    pub g1: &'a [f32],
7079    pub c1: Qi21VaeConvRef<'a>,
7080    pub g2: &'a [f32],
7081    pub c2: Qi21VaeConvRef<'a>,
7082    pub shortcut: Option<Qi21VaeConvRef<'a>>,
7083}
7084
7085/// An up block: its resnets, then (all but the last block) nearest-2× +
7086/// the 3×3 conv, plus the DupUp shortcut of the block's input (`in_dim` →
7087/// `out_dim` channels, temporal factor `ft`).
7088pub struct Qi21VaeUpRef<'a> {
7089    pub resnets: Vec<Qi21VaeResRef<'a>>,
7090    pub up: Option<(Qi21VaeConvRef<'a>, usize)>,
7091    pub in_dim: usize,
7092    pub out_dim: usize,
7093}
7094
7095/// The Qwen-Image-2.1 VAE decoder (`qwen_image21_vae.rs`) for a resident
7096/// device decode.
7097pub struct Qi21VaeDecodeArgs<'a> {
7098    /// Identity of the weights: a backend caches its planes by it.
7099    pub key: u64,
7100    pub post_quant: Qi21VaeConvRef<'a>,
7101    pub conv_in: Qi21VaeConvRef<'a>,
7102    pub mid_res: [Qi21VaeResRef<'a>; 2],
7103    /// The mid attention: RMS_norm γ, `to_qkv` (1×1, 3c outputs: q, k, v),
7104    /// `proj` (1×1); single head, residual.
7105    pub attn_gamma: &'a [f32],
7106    pub attn_qkv: Qi21VaeConvRef<'a>,
7107    pub attn_proj: Qi21VaeConvRef<'a>,
7108    pub ups: Vec<Qi21VaeUpRef<'a>>,
7109    pub norm_out: &'a [f32],
7110    pub conv_out: Qi21VaeConvRef<'a>,
7111}
7112
7113/// Resident VAE decode: `z` = raw latent planes `[z_dim, h·w]` → `out`
7114/// `[out_channels, 16h·16w]` (before the clamp). `false` = not handled,
7115/// `out` untouched: the per-conv path runs.
7116#[allow(unused_variables)]
7117pub fn qi21_vae_decode(a: &Qi21VaeDecodeArgs, z: &[f32], h: usize, w: usize, out: &mut [f32]) -> bool {
7118    match backend() {
7119        #[cfg(feature = "gpu")]
7120        Backend::Wgpu => crate::gpu_wgpu::qi21_vae::decode(a, z, h, w, out),
7121        #[cfg(feature = "cuda")]
7122        Backend::Cuda => crate::gpu_cuda::qi21_vae_decode(a, z, h, w, out),
7123        #[allow(unreachable_patterns)]
7124        _ => false,
7125    }
7126}
7127
7128/// One Z-Image transformer block's device inputs (noise refiner, context
7129/// refiner or main layer — all share this shape). Weights are tensor
7130/// indices into `model.tensors` (diffusers names under `dit.`); the codec
7131/// is whatever the container holds (F16/Bf16/Q8Row/Q8_2f/Q4TiledP…), and a
7132/// backend that cannot expand a codec declines (returns `false`).
7133/// Norm vectors are f32 host slices that live as long as the caller's
7134/// `ZImageDit`; a backend may cache them by pointer (they do not change).
7135#[derive(Clone, Copy)]
7136pub struct ZBlockRef<'a> {
7137    /// `attention.to_q/to_k/to_v/to_out.0.weight`, each [hidden, hidden].
7138    pub wq: usize,
7139    pub wk: usize,
7140    pub wv: usize,
7141    pub wo: usize,
7142    /// `feed_forward.w1` (gate) / `w3` (up) [inter, hidden], `w2` (down)
7143    /// [hidden, inter]. FFN = w2(silu(w1·x) ⊙ w3·x).
7144    pub w1: usize,
7145    pub w3: usize,
7146    pub w2: usize,
7147    /// `attention_norm1` / `attention_norm2`, [hidden] (plain-w RMSNorm).
7148    pub norm1: &'a [f32],
7149    pub norm2: &'a [f32],
7150    /// `ffn_norm1` / `ffn_norm2`, [hidden].
7151    pub ffn_norm1: &'a [f32],
7152    pub ffn_norm2: &'a [f32],
7153    /// `attention.norm_q` / `norm_k`, [hd] (per-head RMSNorm before RoPE).
7154    pub norm_q: &'a [f32],
7155    pub norm_k: &'a [f32],
7156}
7157
7158/// Z-Image geometry. Turbo: hidden 3840, nh 30 (MHA, no GQA), hd 128,
7159/// inter 10240, eps 1e-5 (all RMSNorms incl. qk-norm), final_eps 1e-6
7160/// (the affine-free final LayerNorm), patch_dim 64 (2×2×16).
7161#[derive(Clone, Copy, Debug, PartialEq)]
7162pub struct ZGeom {
7163    pub hidden: usize,
7164    pub nh: usize,
7165    pub hd: usize,
7166    pub inter: usize,
7167    pub eps: f32,
7168    pub final_eps: f32,
7169    pub patch_dim: usize,
7170}
7171
7172/// Once per (prompt, resolution). The backend uploads/caches what it needs
7173/// keyed by `key`; weight planes are keyed by the MODEL (not by `key`) and
7174/// survive across prompts until `zimage_release`.
7175pub struct ZPrepareArgs<'a> {
7176    pub model: &'a Arc<CmfModel>,
7177    pub geom: ZGeom,
7178    /// Caller-chosen identity of this (prompt, resolution) state; every
7179    /// `ZStepArgs` of the same image carries the same key.
7180    pub key: u64,
7181    /// Image tokens (H/16 · W/16), padded count ceil32(n_img), caption
7182    /// padded count ceil32(L). S = n_img_p + n_cap_p.
7183    pub n_img: usize,
7184    pub n_img_p: usize,
7185    pub n_cap_p: usize,
7186    /// The patch grid (H/16, W/16); n_img = grid.0 · grid.1. Row-major
7187    /// token order `hp·grid.1 + wp`.
7188    pub grid: (usize, usize),
7189    /// [n_cap_p, hidden], ALREADY context-refined (host or device).
7190    pub cap: &'a [f32],
7191    /// Noise-refiner RoPE: [n_img_p · hd/2] cos, sin (complex-interleaved
7192    /// pairs, hd/2 angles per token).
7193    pub rope_img: (&'a [f32], &'a [f32]),
7194    /// Main-layer RoPE: [(n_img_p + n_cap_p) · hd/2], rows ordered [img, cap].
7195    pub rope_joint: (&'a [f32], &'a [f32]),
7196    /// `all_x_embedder.2-1.weight` [hidden, 64], `.bias` [hidden],
7197    /// `x_pad_token` [hidden] (replaces rows ≥ n_img after the embed).
7198    pub x_emb_w: &'a [f32],
7199    pub x_emb_b: &'a [f32],
7200    pub x_pad: &'a [f32],
7201    /// `all_final_layer.2-1.linear.weight` [64, hidden], `.bias` [64].
7202    pub final_w: &'a [f32],
7203    pub final_b: &'a [f32],
7204    /// 2 noise-refiner blocks (image rows only) and 30 main layers.
7205    pub noise_refiner: &'a [ZBlockRef<'a>],
7206    pub layers: &'a [ZBlockRef<'a>],
7207    /// OPTIONAL (backends may ignore): the modulation of EVERY step of this
7208    /// image, [steps][(2+30)·4·hidden] in the `ZStepArgs::mods` layout, and
7209    /// [steps][hidden] final scales, so a backend can upload them once per
7210    /// image and index them by `ZStepArgs::step`. `ZStepArgs::mods` is still
7211    /// always supplied and is authoritative.
7212    pub mods_all: Option<&'a [f32]>,
7213    pub final_scale_all: Option<&'a [f32]>,
7214    /// OPTIONAL (B2): the CFG negative item. When `Some`, the backend
7215    /// prepares ONE batch-2 program under `key` — item 0 is this prompt,
7216    /// item 1 the negative — and every `ZStepArgs` of that key must carry
7217    /// `out_neg`. A backend without batch 2 returns `false` (the caller
7218    /// then prepares the two items separately or runs the CPU path).
7219    pub neg: Option<ZNegArgs<'a>>,
7220}
7221
7222/// The negative (unconditional) item of a CFG pair: its own refined
7223/// caption, padded caption length and joint RoPE table (the image ids sit
7224/// at axis-0 position L_p+1, so both tables depend on the item's L_p).
7225pub struct ZNegArgs<'a> {
7226    /// [n_cap_p, hidden], context-refined.
7227    pub cap: &'a [f32],
7228    pub n_cap_p: usize,
7229    /// [n_img_p · hd/2] cos, sin (noise refiner) of this item.
7230    pub rope_img: (&'a [f32], &'a [f32]),
7231    /// [(n_img_p + n_cap_p) · hd/2] cos, sin, rows [img, cap].
7232    pub rope_joint: (&'a [f32], &'a [f32]),
7233}
7234
7235/// Once per denoising step.
7236pub struct ZStepArgs<'a> {
7237    /// The `ZPrepareArgs::key` this step belongs to. A key the backend has
7238    /// not prepared → `false`.
7239    pub key: u64,
7240    /// Step index into the schedule (0..steps); selects the row of
7241    /// `ZPrepareArgs::mods_all` when a backend uses it.
7242    pub step: usize,
7243    /// [n_img_p, 64] patchified latent, inner order (dy·2+dx)·16+c. Rows
7244    /// ≥ n_img are copies of the last row; the backend replaces them with
7245    /// `x_pad` after the embed.
7246    pub x_tok: &'a [f32],
7247    /// Per block (noise_refiner then layers) the RAW chunks
7248    /// [scale_msa, gate_msa, scale_mlp, gate_mlp] of Linear(temb) (no SiLU
7249    /// before it), [(2+30)·4·hidden]. The backend applies (1+s) and tanh(g).
7250    pub mods: &'a [f32],
7251    /// [hidden] = 1 + Linear(SiLU(temb)) — already includes the +1.
7252    pub final_scale: &'a [f32],
7253    /// [n_img, 64]: the model output v (before the pipeline's negation),
7254    /// image rows only, patchified order.
7255    pub out: &'a mut [f32],
7256    /// [n_img, 64]: the negative item's v — required (and only valid) for
7257    /// a key prepared with `ZPrepareArgs::neg`. Both items see `x_tok`.
7258    pub out_neg: Option<&'a mut [f32]>,
7259}
7260
7261/// Prepare the per-(prompt, resolution) device state. Backends: wgpu →
7262/// `gpu_wgpu::zimage::prepare` (WP2), Metal → `gpu_metal::zimage::prepare`
7263/// (WP3).
7264#[allow(unused_variables)]
7265pub fn zimage_prepare(a: &ZPrepareArgs) -> bool {
7266    match backend() {
7267        #[cfg(target_os = "macos")]
7268        Backend::Metal => crate::gpu_metal::zimage::prepare(a),
7269        #[cfg(feature = "gpu")]
7270        Backend::Wgpu => crate::gpu_wgpu::zimage::prepare(a),
7271        #[cfg(feature = "cuda")]
7272        Backend::Cuda => crate::gpu_cuda::zimage_prepare(a),
7273        #[allow(unreachable_patterns)]
7274        _ => false,
7275    }
7276}
7277
7278/// One full DiT forward on the device: x_embed → pad rows → noise refiner
7279/// ×2 → concat [img, cap] → 30 layers → final LayerNorm·scale → Linear →
7280/// image rows into `a.out`.
7281#[allow(unused_variables)]
7282pub fn zimage_step(a: &mut ZStepArgs) -> bool {
7283    match backend() {
7284        #[cfg(target_os = "macos")]
7285        Backend::Metal => crate::gpu_metal::zimage::step(a),
7286        #[cfg(feature = "gpu")]
7287        Backend::Wgpu => crate::gpu_wgpu::zimage::step(a),
7288        #[cfg(feature = "cuda")]
7289        Backend::Cuda => crate::gpu_cuda::zimage_step(a),
7290        #[allow(unreachable_patterns)]
7291        _ => false,
7292    }
7293}
7294
7295/// OPTIONAL (B2): build the backend's weight planes for the per-step blocks
7296/// and the context refiner ahead of `zimage_prepare`, so the caller can
7297/// overlap the upload with the (CPU) text encoder. `false` = not done;
7298/// `zimage_prepare` builds whatever is missing either way.
7299#[allow(unused_variables)]
7300pub fn zimage_preload(
7301    model: &Arc<CmfModel>,
7302    geom: &ZGeom,
7303    noise_refiner: &[ZBlockRef],
7304    layers: &[ZBlockRef],
7305    context_refiner: &[ZBlockRef],
7306) -> bool {
7307    match backend() {
7308        #[cfg(target_os = "macos")]
7309        Backend::Metal => {
7310            crate::gpu_metal::zimage::preload(model, geom, noise_refiner, layers, context_refiner)
7311        }
7312        #[cfg(feature = "gpu")]
7313        Backend::Wgpu => crate::gpu_wgpu::zimage::preload(model, geom, noise_refiner, layers, context_refiner),
7314        #[allow(unreachable_patterns)]
7315        _ => false,
7316    }
7317}
7318
7319/// Persist the driver's compiled pipelines after a Z-Image generation (the
7320/// chain's kernels are built at first use, after the context came up), so
7321/// the next process skips the compile. Best-effort, no-op off wgpu.
7322pub fn zimage_flush_pipelines() {
7323    #[cfg(feature = "gpu")]
7324    if matches!(backend(), Backend::Wgpu) {
7325        crate::gpu_wgpu::pipeline_cache_flush();
7326    }
7327}
7328
7329/// OPTIONAL (B2): bring the device up and compile the Z-Image kernels, on
7330/// a helper thread at the start of a generation (the context and the
7331/// compiles cost ~1 s cold, beside the host-side loading). `false` = no
7332/// device path here.
7333pub fn zimage_warmup() -> bool {
7334    match backend() {
7335        #[cfg(target_os = "macos")]
7336        Backend::Metal => crate::gpu_metal::zimage::warmup(),
7337        #[cfg(feature = "gpu")]
7338        Backend::Wgpu => crate::gpu_wgpu::zimage::warmup(),
7339        #[allow(unreachable_patterns)]
7340        _ => false,
7341    }
7342}
7343
7344/// OPTIONAL (B2): upload the resident VAE's weights and compile its
7345/// kernels ahead of `vae_decode_chain` (the caller runs it on a helper
7346/// thread while the DiT steps keep the device busy). `false` = not done.
7347#[allow(unused_variables)]
7348pub fn vae_prewarm(a: &crate::vae::VaeChainArgs) -> bool {
7349    match backend() {
7350        #[cfg(target_os = "macos")]
7351        Backend::Metal => crate::gpu_metal::zimage::vae_prewarm(a),
7352        #[cfg(feature = "gpu")]
7353        Backend::Wgpu => crate::gpu_wgpu::zimage::vae_prewarm(a),
7354        #[allow(unreachable_patterns)]
7355        _ => false,
7356    }
7357}
7358
7359/// Drop the Z-Image DiT device state (planes, prepared programs) but keep
7360/// the VAE chain (B2: the generator frees the DiT before decoding).
7361pub fn zimage_release_dit() {
7362    #[cfg(target_os = "macos")]
7363    crate::gpu_metal::zimage::release_dit();
7364    #[cfg(feature = "gpu")]
7365    crate::gpu_wgpu::zimage::release_dit();
7366    #[cfg(feature = "cuda")]
7367    if matches!(backend(), Backend::Cuda) {
7368        crate::gpu_cuda::zimage_release();
7369    }
7370}
7371
7372/// Drop every Z-Image device resource (planes, prepared states, VAE chain
7373/// buffers): stage change or process end. Calls each compiled backend's
7374/// release directly, without `backend()`, so it never brings a device up;
7375/// the child modules' `release` must touch module-local state only.
7376pub fn zimage_release() {
7377    #[cfg(target_os = "macos")]
7378    crate::gpu_metal::zimage::release();
7379    #[cfg(feature = "gpu")]
7380    crate::gpu_wgpu::zimage::release();
7381    #[cfg(feature = "cuda")]
7382    if matches!(backend(), Backend::Cuda) {
7383        crate::gpu_cuda::zimage_release();
7384    }
7385}
7386
7387/// Optional device context refiner: the same block math with scale = 0 and
7388/// gate = 1 (unmodulated): x += norm2(attn(norm1(x))); x += ffn_norm2(ffn(
7389/// ffn_norm1(x))). `cap` is [n_cap_p, hidden] in/out (the cap_embedder
7390/// output with pad rows already = cap_pad_token); `rope_cap` is
7391/// [n_cap_p · hd/2] cos, sin. `false` = untouched, run the CPU refiner.
7392#[allow(unused_variables)]
7393pub fn zimage_refine_caption(
7394    model: &Arc<CmfModel>,
7395    geom: &ZGeom,
7396    blocks: &[ZBlockRef],
7397    rope_cap: (&[f32], &[f32]),
7398    cap: &mut [f32],
7399) -> bool {
7400    match backend() {
7401        #[cfg(target_os = "macos")]
7402        Backend::Metal => {
7403            crate::gpu_metal::zimage::refine_caption(model, geom, blocks, rope_cap, cap)
7404        }
7405        #[cfg(feature = "gpu")]
7406        Backend::Wgpu => {
7407            crate::gpu_wgpu::zimage::refine_caption(model, geom, blocks, rope_cap, cap)
7408        }
7409        #[allow(unreachable_patterns)]
7410        _ => false,
7411    }
7412}
7413
7414/// Resident Flux-VAE decode (the whole decoder on the device, one latent
7415/// upload, one RGB readback). `a` comes from `VaeDecoder::chain_args()`.
7416/// `z` is [latent_channels, h, w] ALREADY de-normalised
7417/// (z/scaling_factor + shift_factor — the conv_in input); `out` is
7418/// [3, 8h, 8w], the raw decoder output (≈[-1, 1], before x/2+0.5).
7419#[allow(unused_variables)]
7420pub fn vae_decode_chain(
7421    a: &crate::vae::VaeChainArgs,
7422    z: &[f32],
7423    h: usize,
7424    w: usize,
7425    out: &mut [f32],
7426) -> bool {
7427    match backend() {
7428        #[cfg(target_os = "macos")]
7429        Backend::Metal => crate::gpu_metal::zimage::vae_decode_chain(a, z, h, w, out),
7430        #[cfg(feature = "gpu")]
7431        Backend::Wgpu => crate::gpu_wgpu::zimage::vae_decode_chain(a, z, h, w, out),
7432        #[cfg(feature = "cuda")]
7433        Backend::Cuda => crate::gpu_cuda::flux_vae_chain(a, z, h, w, out),
7434        #[allow(unreachable_patterns)]
7435        _ => false,
7436    }
7437}
7438
7439
7440// ── Kandinsky S2V device contract ──────────────────────────────────────
7441
7442/// A prepared device program for one render's geometry and conditions.
7443pub trait S2vStepper {
7444    /// One DiT forward: `x` `[T, H, W, 16]`, memory in `[1x, 2x, 4x]` order,
7445    /// returns `[T, H, W, 80]`. `step` indexes the render's timestep list and
7446    /// `chunk` the speech chunk.
7447    fn step(&mut self, step: usize, chunk: usize, x: &[f32], memory: &[Vec<f32>; 3]) -> Result<Vec<f32>, String>;
7448}
7449
7450/// The device program, or `None` to run the host path.
7451#[allow(unused_variables)]
7452pub fn s2v_prepare(
7453    dit: &crate::s2v::S2vDit,
7454    g: &crate::s2v::S2vGeom,
7455    cond: &crate::s2vgen::S2vCond,
7456    ts: &[f32],
7457    sf: [f32; 3],
7458) -> Option<Box<dyn S2vStepper>> {
7459    match backend() {
7460        #[cfg(feature = "gpu")]
7461        Backend::Wgpu => crate::gpu_wgpu::s2v::prepare(dit, g, cond, ts, sf).map(|d| Box::new(d) as Box<dyn S2vStepper>),
7462        #[cfg(target_os = "macos")]
7463        Backend::Metal => crate::gpu_metal::s2v::prepare(dit, g, cond, ts, sf).map(|d| Box::new(d) as Box<dyn S2vStepper>),
7464        #[cfg(feature = "cuda")]
7465        Backend::Cuda => crate::gpu_cuda::s2v_prepare(dit, g, cond, ts, sf).map(|d| Box::new(d) as Box<dyn S2vStepper>),
7466        #[allow(unreachable_patterns)]
7467        _ => None,
7468    }
7469}
7470
7471/// Frees what the VAE decode kept on the device.
7472pub fn s2v_release() {
7473    #[cfg(feature = "gpu")]
7474    crate::gpu_wgpu::s2v_vae::release();
7475    #[cfg(target_os = "macos")]
7476    crate::gpu_metal::s2v::release();
7477    #[cfg(feature = "cuda")]
7478    if matches!(backend(), Backend::Cuda) {
7479        crate::gpu_cuda::s2v_vae_release();
7480    }
7481}
7482
7483/// The whole temporally tiled decoder on the device, or `None`.
7484#[allow(unused_variables)]
7485pub fn s2v_vae_decode(vae: &crate::s2v_vae::S2vVae, z: &crate::ltxvae::Vol) -> Option<crate::ltxvae::Vol> {
7486    match backend() {
7487        #[cfg(feature = "gpu")]
7488        Backend::Wgpu => crate::gpu_wgpu::s2v_vae::decode(vae, z),
7489        #[cfg(target_os = "macos")]
7490        Backend::Metal => crate::gpu_metal::s2v::decode(vae, z),
7491        #[cfg(feature = "cuda")]
7492        Backend::Cuda => crate::gpu_cuda::s2v_vae_decode(vae, z),
7493        #[allow(unreachable_patterns)]
7494        _ => None,
7495    }
7496}
7497
7498/// SAM3's ViT trunk on the device: the patch rows `[5184][588]` in, the trunk
7499/// features `[5184][1024]` out, or `None` for the host trunk.
7500#[allow(unused_variables)]
7501pub fn sam3_trunk(m: &std::sync::Arc<cortiq_core::CmfModel>, pv: &[f32], pos_skip_cls: bool) -> Option<Vec<f32>> {
7502    match backend() {
7503        #[cfg(feature = "cuda")]
7504        Backend::Cuda => crate::gpu_cuda::sam3_trunk(m, pv, pos_skip_cls),
7505        #[cfg(feature = "gpu")]
7506        Backend::Wgpu => crate::gpu_wgpu::h3::sam3_trunk(m, pv, pos_skip_cls),
7507        #[allow(unreachable_patterns)]
7508        _ => None,
7509    }
7510}
7511
7512/// `out[b][rows] = xs[b][cols] · Wᵀ` for a q4tp / q8_2f container tensor on a
7513/// backend that keeps its dense plane on the card (CUDA), past the probe;
7514/// `false` elsewhere.
7515#[allow(unused_variables)]
7516pub fn plane_matmat(model: &Arc<CmfModel>, idx: usize, xs: &[f32], b: usize, rows: usize, cols: usize, out: &mut [f32]) -> bool {
7517    match backend() {
7518        #[cfg(feature = "cuda")]
7519        Backend::Cuda => crate::gpu_cuda::h3_matmat(model, idx, xs, b, rows, cols, out),
7520        #[allow(unreachable_patterns)]
7521        _ => false,
7522    }
7523}
7524
7525/// The tracker's attention core on the device: q `[n_q][dim]`, k and v
7526/// `[n_k][dim]`, softmax(q kᵀ · scale) v into `out` `[n_q][dim]`, or `false`.
7527#[allow(unused_variables, clippy::too_many_arguments)]
7528pub fn sam3_attn_sep(q: &[f32], k: &[f32], v: &[f32], n_q: usize, n_k: usize, dim: usize, heads: usize, scale: f32, out: &mut [f32]) -> bool {
7529    if !enabled_here() {
7530        return false;
7531    }
7532    match backend() {
7533        #[cfg(feature = "cuda")]
7534        Backend::Cuda => crate::gpu_cuda::sam3_attn_sep(q, k, v, n_q, n_k, dim, heads, scale, out),
7535        #[allow(unreachable_patterns)]
7536        _ => false,
7537    }
7538}
7539
7540/// `c[m][n] = a[m][k] · b[k][n]` in f32 on the device (SAM3's mask einsum), or `None`.
7541#[allow(unused_variables)]
7542pub fn sam3_mm(a: &[f32], b: &[f32], m: usize, k: usize, n: usize) -> Option<Vec<f32>> {
7543    if !enabled_here() {
7544        return None;
7545    }
7546    match backend() {
7547        #[cfg(feature = "cuda")]
7548        Backend::Cuda => crate::gpu_cuda::sam3_mm(a, b, m, k, n),
7549        #[allow(unreachable_patterns)]
7550        _ => None,
7551    }
7552}
7553
7554/// SAM3's CLIP text tower on the device: `x` the embedded tokens `[32][1024]`
7555/// in, the final LayerNorm's rows out (in place); `cm` the causal + padding
7556/// mask `[32][32]`. `false`: `x` untouched.
7557#[allow(unused_variables)]
7558pub fn sam3_text(m: &Arc<CmfModel>, x: &mut [f32], cm: &[f32]) -> bool {
7559    if !enabled_here() {
7560        return false;
7561    }
7562    match backend() {
7563        #[cfg(feature = "cuda")]
7564        Backend::Cuda => crate::gpu_cuda::sam3_text(m, x, cm),
7565        #[allow(unreachable_patterns)]
7566        _ => false,
7567    }
7568}
7569
7570/// SAM3's convolutions on the device (zero padding, `sam3::conv2d`'s shapes), or `None`.
7571#[allow(unused_variables, clippy::too_many_arguments)]
7572pub fn sam3_conv2d(w: &[f32], b: &[f32], x: &[f32], ci: usize, h: usize, wid: usize, kh: usize, kw: usize, stride: usize, pad: usize) -> Option<Vec<f32>> {
7573    if !enabled_here() {
7574        return None;
7575    }
7576    match backend() {
7577        #[cfg(feature = "cuda")]
7578        Backend::Cuda => crate::gpu_cuda::sam3_conv2d(w, b, x, ci, h, wid, kh, kw, stride, pad),
7579        #[allow(unreachable_patterns)]
7580        _ => None,
7581    }
7582}
7583
7584/// SAM3's 2 x 2 stride-2 transposed convolution on the device, or `None`.
7585#[allow(unused_variables)]
7586pub fn sam3_convt2x2(w: &[f32], b: &[f32], x: &[f32], ci: usize, h: usize, wid: usize) -> Option<Vec<f32>> {
7587    if !enabled_here() {
7588        return None;
7589    }
7590    match backend() {
7591        #[cfg(feature = "cuda")]
7592        Backend::Cuda => crate::gpu_cuda::sam3_convt2x2(w, b, x, ci, h, wid),
7593        #[allow(unreachable_patterns)]
7594        _ => None,
7595    }
7596}
7597
7598/// SAM3's attention core over fused q|k|v rows on the device (`mode`: 0 no
7599/// mask, 1 key, 2 additive, 3 per head), or `false`.
7600#[allow(unused_variables, clippy::too_many_arguments)]
7601pub fn sam3_attn_core(q: &[f32], k: &[f32], v: &[f32], n_q: usize, n_k: usize, dim: usize, heads: usize, mode: i32, mask: &[f32], scale: f32, out: &mut [f32]) -> bool {
7602    if !enabled_here() {
7603        return false;
7604    }
7605    match backend() {
7606        #[cfg(feature = "cuda")]
7607        Backend::Cuda => crate::gpu_cuda::sam3_attn_core(q, k, v, n_q, n_k, dim, heads, mode, mask, scale, out),
7608        #[allow(unreachable_patterns)]
7609        _ => false,
7610    }
7611}
7612
7613/// The reference frame through the encoder on the device, or `None`.
7614#[allow(unused_variables)]
7615pub fn s2v_vae_encode(enc: &crate::s2v_vae::S2vVaeEncoder, img: &crate::ltxvae::Vol) -> Option<(crate::ltxvae::Vol, crate::ltxvae::Vol)> {
7616    match backend() {
7617        #[cfg(feature = "gpu")]
7618        Backend::Wgpu => crate::gpu_wgpu::s2v_vae::encode(enc, img),
7619        #[cfg(target_os = "macos")]
7620        Backend::Metal => crate::gpu_metal::s2v::encode(enc, img),
7621        #[cfg(feature = "cuda")]
7622        Backend::Cuda => crate::gpu_cuda::s2v_vae_encode(enc, img),
7623        #[allow(unreachable_patterns)]
7624        _ => None,
7625    }
7626}
7627
7628/// One forward on the device for the parity gate.
7629#[allow(unused_variables)]
7630pub fn s2v_check_forward(dit: &crate::s2v::S2vDit, i: &crate::s2v::S2vInput<'_>) -> Option<Vec<f32>> {
7631    let cond = crate::s2vgen::S2vCond {
7632        text: i.text_feats.to_vec(),
7633        pooled: i.pooled.to_vec(),
7634        audio: vec![i.audio_feats.to_vec()],
7635        reference: i.reference.to_vec(),
7636        height: i.geom.lh * 8,
7637        width: i.geom.lw * 8,
7638    };
7639    let mut dev = s2v_prepare(dit, &i.geom, &cond, &[i.t], i.scale_factor)?;
7640    let memory = [i.mem1.to_vec(), i.mem2.to_vec(), i.mem4.to_vec()];
7641    dev.step(0, 0, i.x, &memory).ok()
7642}