1use cortiq_core::CmfModel;
14use std::cell::Cell;
15use std::sync::atomic::{AtomicU32, AtomicU64, AtomicU8, Ordering};
16use std::sync::{Arc, OnceLock};
17
18thread_local! {
19 static CUR_LAYER: Cell<i64> = const { Cell::new(-1) };
23 static CPU_ONLY: Cell<bool> = const { Cell::new(false) };
28 static PROBE_COLD: Cell<bool> = const { Cell::new(false) };
32}
33
34pub fn cpu_scope<R>(f: impl FnOnce() -> R) -> R {
36 CPU_ONLY.with(|c| c.set(true));
37 let r = f();
38 CPU_ONLY.with(|c| c.set(false));
39 r
40}
41
42pub(crate) fn probe_note_cold() {
45 PROBE_COLD.with(|c| c.set(true));
46}
47
48pub fn set_layer(l: i64) {
50 CUR_LAYER.with(|c| c.set(l));
51}
52
53pub fn cur_layer() -> i64 {
55 CUR_LAYER.with(|c| c.get())
56}
57
58fn layer_ranges() -> &'static Option<Vec<(i64, i64)>> {
61 static R: OnceLock<Option<Vec<(i64, i64)>>> = OnceLock::new();
62 R.get_or_init(|| {
63 let s = std::env::var("CMF_GPU_LAYERS").ok()?;
64 let mut v = Vec::new();
65 for part in s.split(',') {
66 let part = part.trim();
67 match part.split_once('-') {
68 Some((a, b)) => v.push((a.trim().parse().ok()?, b.trim().parse().ok()?)),
69 None => {
70 let x: i64 = part.parse().ok()?;
71 v.push((x, x));
72 }
73 }
74 }
75 Some(v)
76 })
77}
78
79fn layer_allowed() -> bool {
80 match layer_ranges() {
81 None => true,
82 Some(ranges) => {
83 let cur = CUR_LAYER.with(|c| c.get());
84 cur < 0 || ranges.iter().any(|(a, b)| cur >= *a && cur <= *b)
85 }
86 }
87}
88
89pub fn enabled_here() -> bool {
93 !CPU_ONLY.with(|c| c.get()) && enabled() && layer_allowed()
94}
95
96#[derive(Clone, Copy)]
108pub enum OpClass {
109 Ffn = 0,
111 Matvec = 1,
113 Matmat = 2,
115 Batch = 3,
117}
118
119pub enum ProbeArm {
121 Gpu,
123 CpuTimed,
125 Cpu,
127}
128
129const PROBE_SAMPLES: u32 = 6;
131
132struct Probe {
133 state: AtomicU8,
135 flip: AtomicU32,
136 gpu_ns: AtomicU64,
137 gpu_n: AtomicU32,
138 cpu_ns: AtomicU64,
139 cpu_n: AtomicU32,
140}
141
142impl Probe {
143 const fn new() -> Self {
144 Self {
145 state: AtomicU8::new(0),
146 flip: AtomicU32::new(0),
147 gpu_ns: AtomicU64::new(0),
148 gpu_n: AtomicU32::new(0),
149 cpu_ns: AtomicU64::new(0),
150 cpu_n: AtomicU32::new(0),
151 }
152 }
153}
154
155static PROBES: [Probe; 4] = [Probe::new(), Probe::new(), Probe::new(), Probe::new()];
156
157fn probe_on() -> bool {
158 static ON: OnceLock<bool> = OnceLock::new();
159 *ON.get_or_init(|| {
160 std::env::var("CMF_GPU_PROBE")
161 .map(|v| v != "0" && v != "off")
162 .unwrap_or(true)
163 })
164}
165
166pub fn q1_force() -> bool {
171 #[cfg(target_os = "macos")]
172 {
173 backend() == Backend::Metal
174 }
175 #[cfg(not(target_os = "macos"))]
176 {
177 false
178 }
179}
180
181pub fn probe_arm(c: OpClass) -> ProbeArm {
185 if !probe_on() {
186 return ProbeArm::Gpu;
187 }
188 let p = &PROBES[c as usize];
189 match p.state.load(Ordering::Relaxed) {
190 1 => ProbeArm::Gpu,
191 2 => ProbeArm::Cpu,
192 _ => {
193 PROBE_COLD.with(|f| f.set(false));
194 if p.flip.fetch_add(1, Ordering::Relaxed) % 2 == 0 {
195 ProbeArm::Gpu
196 } else {
197 ProbeArm::CpuTimed
198 }
199 }
200 }
201}
202
203pub fn probe_record(c: OpClass, gpu: bool, dur: std::time::Duration) {
206 let p = &PROBES[c as usize];
207 if p.state.load(Ordering::Relaxed) != 0 {
208 return;
209 }
210 if gpu && PROBE_COLD.with(|f| f.replace(false)) {
211 return; }
213 let ns = dur.as_nanos().min(u64::MAX as u128) as u64;
214 if gpu {
215 p.gpu_ns.fetch_add(ns, Ordering::Relaxed);
216 p.gpu_n.fetch_add(1, Ordering::Relaxed);
217 } else {
218 p.cpu_ns.fetch_add(ns, Ordering::Relaxed);
219 p.cpu_n.fetch_add(1, Ordering::Relaxed);
220 }
221 let (gn, cn) = (p.gpu_n.load(Ordering::Relaxed), p.cpu_n.load(Ordering::Relaxed));
222 if gn >= 2 && cn >= 2 {
223 let g = p.gpu_ns.load(Ordering::Relaxed) as f64 / gn as f64;
224 let cp = p.cpu_ns.load(Ordering::Relaxed) as f64 / cn as f64;
225 if (gn < PROBE_SAMPLES || cn < PROBE_SAMPLES) && g < cp * 3.0 && cp < g * 3.0 {
228 return;
229 }
230 let winner = if g <= cp { 1 } else { 2 };
231 if p
232 .state
233 .compare_exchange(0, winner, Ordering::Relaxed, Ordering::Relaxed)
234 .is_ok()
235 {
236 tracing::info!(
237 "gpu probe [{}]: gpu {:.2} ms vs cpu {:.2} ms per op → {}",
238 ["ffn", "matvec", "matmat", "qkv-batch"][c as usize],
239 g / 1e6,
240 cp / 1e6,
241 if winner == 1 { "gpu" } else { "cpu" },
242 );
243 }
244 }
245}
246
247pub fn probe_deciding(c: OpClass) -> bool {
250 probe_on() && PROBES[c as usize].state.load(Ordering::Relaxed) == 0
251}
252
253#[allow(unused_variables)]
263pub fn q8_resident_or_upload(model: &Arc<CmfModel>, idx: usize) -> bool {
264 static PROBE_UPLOADS: AtomicU32 = AtomicU32::new(0);
265 let may_upload = PROBE_UPLOADS.load(Ordering::Relaxed) < 4;
266 let resident = match backend() {
267 #[cfg(target_os = "macos")]
268 Backend::Metal => crate::gpu_metal::q8_resident_or_upload(model, idx, may_upload),
269 #[cfg(feature = "gpu")]
270 Backend::Wgpu => crate::gpu_wgpu::q8_resident_or_upload(model, idx, may_upload),
271 Backend::None => false,
272 };
273 if !resident && may_upload {
274 PROBE_UPLOADS.fetch_add(1, Ordering::Relaxed);
275 }
276 resident
277}
278
279#[cfg(test)]
281pub(crate) fn probe_reset() {
282 for p in &PROBES {
283 p.state.store(0, Ordering::Relaxed);
284 p.flip.store(0, Ordering::Relaxed);
285 p.gpu_ns.store(0, Ordering::Relaxed);
286 p.gpu_n.store(0, Ordering::Relaxed);
287 p.cpu_ns.store(0, Ordering::Relaxed);
288 p.cpu_n.store(0, Ordering::Relaxed);
289 }
290}
291
292#[cfg(test)]
293mod probe_tests {
294 use super::*;
295 use std::time::Duration;
296
297 #[test]
300 fn probe_alternates_discards_cold_and_decides() {
301 probe_reset();
302 assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
304 assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::CpuTimed));
305
306 probe_note_cold();
310 probe_record(OpClass::Ffn, true, Duration::from_secs(1000));
311 for _ in 0..PROBE_SAMPLES {
312 probe_record(OpClass::Ffn, true, Duration::from_millis(1));
313 probe_record(OpClass::Ffn, false, Duration::from_millis(4));
314 }
315 assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
316
317 for _ in 0..PROBE_SAMPLES {
319 probe_record(OpClass::Matmat, true, Duration::from_millis(4));
320 probe_record(OpClass::Matmat, false, Duration::from_millis(1));
321 }
322 assert!(matches!(probe_arm(OpClass::Matmat), ProbeArm::Cpu));
323
324 cpu_scope(|| CPU_ONLY.with(|c| assert!(c.get())));
326 CPU_ONLY.with(|c| assert!(!c.get()));
327 probe_reset();
328 }
329}
330
331pub const GPU_MIN_ROWS: usize = 65_536;
334
335pub fn min_rows() -> usize {
342 if let Some(v) = std::env::var("CMF_GPU_MIN_ROWS").ok().and_then(|v| v.parse().ok()) {
343 return v;
344 }
345 if discrete() {
346 4096
347 } else {
348 GPU_MIN_ROWS
349 }
350}
351
352pub fn discrete() -> bool {
354 match backend() {
355 #[cfg(feature = "gpu")]
356 Backend::Wgpu => crate::gpu_wgpu::is_discrete(),
357 #[cfg(target_os = "macos")]
358 Backend::Metal => false, Backend::None => false,
360 }
361}
362
363pub struct MoeJob<'a> {
367 pub gate: (usize, usize, usize, &'a [f32]),
368 pub up: (usize, usize, usize, &'a [f32]),
369 pub down: (usize, usize, usize, &'a [f32]),
370 pub xs_gate: Vec<f32>,
371 pub xs_up: Vec<f32>,
372 pub down_col: &'a [f32],
373 pub w: f32,
374 pub q1: bool,
377}
378
379pub struct BatchJob<'a> {
381 pub idx: usize,
382 pub rows: usize,
383 pub cols: usize,
384 pub row_scale: &'a [f32],
385 pub xs: Vec<f32>,
386 pub q1: bool,
388}
389
390#[derive(Clone, Copy, PartialEq, Eq)]
391enum Backend {
392 None,
393 #[cfg(target_os = "macos")]
394 Metal,
395 #[cfg(feature = "gpu")]
396 Wgpu,
397}
398
399fn backend() -> Backend {
400 #[cfg(feature = "gpu")]
401 if crate::gpu_wgpu::selected() {
402 return if crate::gpu_wgpu::enabled() { Backend::Wgpu } else { Backend::None };
403 }
404 #[cfg(target_os = "macos")]
405 if crate::gpu_metal::enabled() {
406 return Backend::Metal;
407 }
408 Backend::None
409}
410
411pub fn enabled() -> bool {
413 backend() != Backend::None
414}
415
416#[allow(clippy::too_many_arguments, unused_variables)]
418pub fn q8_matvec_range(
419 model: &Arc<CmfModel>,
420 idx: usize,
421 row0: usize,
422 row_scale: &[f32],
423 xs: &[f32],
424 rows: usize,
425 cols: usize,
426 out: &mut [f32],
427) -> bool {
428 match backend() {
429 #[cfg(target_os = "macos")]
430 Backend::Metal => {
431 crate::gpu_metal::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
432 }
433 #[cfg(feature = "gpu")]
434 Backend::Wgpu => {
435 crate::gpu_wgpu::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
436 }
437 Backend::None => false,
438 }
439}
440
441#[allow(clippy::too_many_arguments, unused_variables)]
444pub fn q8_matmat(
445 model: &Arc<CmfModel>,
446 idx: usize,
447 row_scale: &[f32],
448 pre: &[f32],
449 b: usize,
450 rows: usize,
451 cols: usize,
452 out: &mut [f32],
453) -> bool {
454 match backend() {
455 #[cfg(target_os = "macos")]
456 Backend::Metal => {
457 crate::gpu_metal::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out)
458 }
459 #[cfg(feature = "gpu")]
460 Backend::Wgpu => {
461 crate::gpu_wgpu::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out)
462 }
463 Backend::None => false,
464 }
465}
466
467#[allow(unused_variables)]
470pub fn q1_matvec(
471 model: &Arc<CmfModel>,
472 idx: usize,
473 xs: &[f32],
474 rows: usize,
475 cols: usize,
476 out: &mut [f32],
477) -> bool {
478 match backend() {
479 #[cfg(target_os = "macos")]
480 Backend::Metal => crate::gpu_metal::q1_matvec(model, idx, xs, rows, cols, out),
481 #[cfg(feature = "gpu")]
482 Backend::Wgpu => crate::gpu_wgpu::q1_matvec(model, idx, xs, rows, cols, out),
483 Backend::None => false,
484 }
485}
486
487#[cfg(target_os = "macos")]
489pub use crate::gpu_metal::{
490 kv_mirror_drop, kv_mirror_read_last, kv_mirror_take_imp, AttnDeviceParams, AttnGpuLayer,
491 GdnGpuCfg, GdnGpuLayer, GraphDims, TokenGraph,
492};
493
494#[cfg(target_os = "macos")]
496pub fn gdn_block(
497 model: &Arc<CmfModel>,
498 layers: &[GdnGpuLayer],
499 states: &mut [&mut [f32]],
500 cfg: &GdnGpuCfg,
501 h: &mut [f32],
502) -> bool {
503 match backend() {
504 Backend::Metal => crate::gpu_metal::gdn_block(model, layers, states, cfg, h),
505 _ => false,
506 }
507}
508
509#[allow(unused_variables)]
511pub fn moe_block(model: &Arc<CmfModel>, jobs: &[MoeJob], out: &mut [f32]) -> bool {
512 match backend() {
513 #[cfg(target_os = "macos")]
514 Backend::Metal => crate::gpu_metal::moe_block(model, jobs, out),
515 #[cfg(feature = "gpu")]
516 Backend::Wgpu => crate::gpu_wgpu::moe_block(model, jobs, out),
517 Backend::None => false,
518 }
519}
520
521#[allow(unused_variables)]
523pub fn matvec_batch(model: &Arc<CmfModel>, jobs: &[BatchJob], out: &mut [&mut [f32]]) -> bool {
524 match backend() {
525 #[cfg(target_os = "macos")]
526 Backend::Metal => crate::gpu_metal::matvec_batch(model, jobs, out),
527 #[cfg(feature = "gpu")]
528 Backend::Wgpu => crate::gpu_wgpu::matvec_batch(model, jobs, out),
529 Backend::None => false,
530 }
531}