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