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