1use cortiq_core::CmfModel;
14use std::cell::Cell;
15use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, 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 struct Restore(bool);
37 impl Drop for Restore {
38 fn drop(&mut self) {
39 CPU_ONLY.with(|c| c.set(self.0));
40 }
41 }
42 let previous = CPU_ONLY.with(|c| c.replace(true));
43 let _restore = Restore(previous);
44 f()
45}
46
47pub(crate) fn probe_note_cold() {
50 PROBE_COLD.with(|c| c.set(true));
51}
52
53pub(crate) fn probe_was_cold() -> bool {
57 PROBE_COLD.with(|c| c.get())
58}
59
60pub fn set_layer(l: i64) {
62 CUR_LAYER.with(|c| c.set(l));
63}
64
65pub fn cur_layer() -> i64 {
67 CUR_LAYER.with(|c| c.get())
68}
69
70fn layer_ranges() -> &'static Option<Vec<(i64, i64)>> {
73 static R: OnceLock<Option<Vec<(i64, i64)>>> = OnceLock::new();
74 R.get_or_init(|| {
75 let s = std::env::var("CMF_GPU_LAYERS").ok()?;
76 let mut v = Vec::new();
77 for part in s.split(',') {
78 let part = part.trim();
79 match part.split_once('-') {
80 Some((a, b)) => v.push((a.trim().parse().ok()?, b.trim().parse().ok()?)),
81 None => {
82 let x: i64 = part.parse().ok()?;
83 v.push((x, x));
84 }
85 }
86 }
87 Some(v)
88 })
89}
90
91fn layer_allowed() -> bool {
92 match layer_ranges() {
93 None => true,
94 Some(ranges) => {
95 let cur = CUR_LAYER.with(|c| c.get());
96 cur < 0 || ranges.iter().any(|(a, b)| cur >= *a && cur <= *b)
97 }
98 }
99}
100
101pub fn enabled_here() -> bool {
105 !CPU_ONLY.with(|c| c.get()) && enabled() && layer_allowed()
106}
107
108#[derive(Clone, Copy)]
120pub enum OpClass {
121 Ffn = 0,
123 Matvec = 1,
125 Matmat = 2,
127 Batch = 3,
129 MatmatWide = 4,
135 MatvecHead = 5,
142}
143
144pub fn matvec_class(rows: usize, cols: usize) -> OpClass {
148 if rows * cols >= 67_108_864 {
149 OpClass::MatvecHead
150 } else {
151 OpClass::Matvec
152 }
153}
154
155pub enum ProbeArm {
157 Gpu,
159 CpuTimed,
161 Cpu,
163}
164
165const PROBE_SAMPLES: u32 = 6;
167
168struct Probe {
169 state: AtomicU8,
171 flip: AtomicU32,
172 gpu_ns: AtomicU64,
173 gpu_n: AtomicU32,
174 cpu_ns: AtomicU64,
175 cpu_n: AtomicU32,
176 gpu_min: AtomicU64,
183 cpu_min: AtomicU64,
184}
185
186impl Probe {
187 const fn new() -> Self {
188 Self {
189 state: AtomicU8::new(0),
190 flip: AtomicU32::new(0),
191 gpu_ns: AtomicU64::new(0),
192 gpu_n: AtomicU32::new(0),
193 cpu_ns: AtomicU64::new(0),
194 cpu_n: AtomicU32::new(0),
195 gpu_min: AtomicU64::new(u64::MAX),
196 cpu_min: AtomicU64::new(u64::MAX),
197 }
198 }
199}
200
201static PROBES: [Probe; 6] = [
202 Probe::new(),
203 Probe::new(),
204 Probe::new(),
205 Probe::new(),
206 Probe::new(),
207 Probe::new(),
208];
209
210fn probe_on() -> bool {
211 static ON: OnceLock<bool> = OnceLock::new();
212 *ON.get_or_init(|| {
213 std::env::var("CMF_GPU_PROBE")
214 .map(|v| v != "0" && v != "off")
215 .unwrap_or(true)
216 })
217}
218
219pub fn q1_force() -> bool {
224 #[cfg(target_os = "macos")]
225 {
226 backend() == Backend::Metal
227 }
228 #[cfg(not(target_os = "macos"))]
229 {
230 false
231 }
232}
233
234pub fn fused_block_trusted() -> bool {
253 #[cfg(target_os = "macos")]
254 if backend() == Backend::Metal {
255 return true;
256 }
257 wgpu_graph_default()
258}
259
260pub fn probe_arm(c: OpClass) -> ProbeArm {
264 PROBE_COLD.with(|f| f.set(false));
269 if !probe_on() {
270 return ProbeArm::Gpu;
271 }
272 let p = &PROBES[c as usize];
273 match p.state.load(Ordering::Relaxed) {
274 1 => ProbeArm::Gpu,
275 2 => ProbeArm::Cpu,
276 _ => {
277 if p.flip.fetch_add(1, Ordering::Relaxed) % 2 == 0 {
278 ProbeArm::Gpu
279 } else {
280 ProbeArm::CpuTimed
281 }
282 }
283 }
284}
285
286pub fn probe_record(c: OpClass, gpu: bool, dur: std::time::Duration) {
289 let p = &PROBES[c as usize];
290 if p.state.load(Ordering::Relaxed) != 0 {
291 return;
292 }
293 if gpu && PROBE_COLD.with(|f| f.replace(false)) {
294 return; }
296 let ns = dur.as_nanos().min(u64::MAX as u128) as u64;
297 if gpu {
298 p.gpu_ns.fetch_add(ns, Ordering::Relaxed);
299 p.gpu_n.fetch_add(1, Ordering::Relaxed);
300 p.gpu_min.fetch_min(ns, Ordering::Relaxed);
301 } else {
302 p.cpu_ns.fetch_add(ns, Ordering::Relaxed);
303 p.cpu_n.fetch_add(1, Ordering::Relaxed);
304 p.cpu_min.fetch_min(ns, Ordering::Relaxed);
305 }
306 let (gn, cn) = (
307 p.gpu_n.load(Ordering::Relaxed),
308 p.cpu_n.load(Ordering::Relaxed),
309 );
310 if gn >= 2 && cn >= 2 {
311 let g = p.gpu_min.load(Ordering::Relaxed) as f64;
315 let cp = p.cpu_min.load(Ordering::Relaxed) as f64;
316 if (gn < PROBE_SAMPLES || cn < PROBE_SAMPLES) && g < cp * 3.0 && cp < g * 3.0 {
319 return;
320 }
321 let winner = if g <= cp { 1 } else { 2 };
322 if p.state
323 .compare_exchange(0, winner, Ordering::Relaxed, Ordering::Relaxed)
324 .is_ok()
325 {
326 tracing::info!(
327 "gpu probe [{}]: gpu {:.2} ms vs cpu {:.2} ms per op → {}",
328 ["ffn", "matvec", "matmat", "qkv-batch", "matmat-wide", "lm-head"][c as usize],
329 g / 1e6,
330 cp / 1e6,
331 if winner == 1 { "gpu" } else { "cpu" },
332 );
333 }
334 }
335}
336
337pub fn probe_deciding(c: OpClass) -> bool {
340 probe_on() && PROBES[c as usize].state.load(Ordering::Relaxed) == 0
341}
342
343#[allow(unused_variables)]
353pub fn q8_resident_or_upload(model: &Arc<CmfModel>, idx: usize) -> bool {
354 static PROBE_UPLOADS: AtomicU32 = AtomicU32::new(0);
355 let may_upload = PROBE_UPLOADS.load(Ordering::Relaxed) < 4;
356 let resident = match backend() {
357 #[cfg(target_os = "macos")]
358 Backend::Metal => crate::gpu_metal::q8_resident_or_upload(model, idx, may_upload),
359 #[cfg(feature = "gpu")]
360 Backend::Wgpu => crate::gpu_wgpu::q8_resident_or_upload(model, idx, may_upload),
361 Backend::None => false,
362 };
363 if !resident && may_upload {
364 PROBE_UPLOADS.fetch_add(1, Ordering::Relaxed);
365 }
366 resident
367}
368
369#[cfg(test)]
371pub(crate) fn probe_reset() {
372 for p in &PROBES {
373 p.state.store(0, Ordering::Relaxed);
374 p.flip.store(0, Ordering::Relaxed);
375 p.gpu_ns.store(0, Ordering::Relaxed);
376 p.gpu_n.store(0, Ordering::Relaxed);
377 p.cpu_ns.store(0, Ordering::Relaxed);
378 p.cpu_n.store(0, Ordering::Relaxed);
379 }
380}
381
382#[cfg(test)]
383mod probe_tests {
384 use super::*;
385 use std::time::Duration;
386
387 #[test]
390 fn probe_alternates_discards_cold_and_decides() {
391 probe_reset();
392 assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
394 assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::CpuTimed));
395
396 probe_note_cold();
400 probe_record(OpClass::Ffn, true, Duration::from_secs(1000));
401 for _ in 0..PROBE_SAMPLES {
402 probe_record(OpClass::Ffn, true, Duration::from_millis(1));
403 probe_record(OpClass::Ffn, false, Duration::from_millis(4));
404 }
405 assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
406
407 for _ in 0..PROBE_SAMPLES {
409 probe_record(OpClass::Matmat, true, Duration::from_millis(4));
410 probe_record(OpClass::Matmat, false, Duration::from_millis(1));
411 }
412 assert!(matches!(probe_arm(OpClass::Matmat), ProbeArm::Cpu));
413
414 cpu_scope(|| CPU_ONLY.with(|c| assert!(c.get())));
416 CPU_ONLY.with(|c| assert!(!c.get()));
417 cpu_scope(|| {
418 cpu_scope(|| CPU_ONLY.with(|c| assert!(c.get())));
419 CPU_ONLY.with(|c| assert!(c.get()));
420 });
421 let _ = std::panic::catch_unwind(|| cpu_scope(|| panic!("scope test")));
422 CPU_ONLY.with(|c| assert!(!c.get()));
423 probe_reset();
424 }
425}
426
427pub const GPU_MIN_ROWS: usize = 65_536;
430
431pub fn min_rows() -> usize {
438 if let Some(v) = std::env::var("CMF_GPU_MIN_ROWS")
439 .ok()
440 .and_then(|v| v.parse().ok())
441 {
442 return v;
443 }
444 if discrete() { 4096 } else { GPU_MIN_ROWS }
445}
446
447pub fn discrete() -> bool {
449 match backend() {
450 #[cfg(feature = "gpu")]
451 Backend::Wgpu => crate::gpu_wgpu::is_discrete(),
452 #[cfg(target_os = "macos")]
453 Backend::Metal => false, Backend::None => false,
455 }
456}
457
458pub struct MoeJob<'a> {
462 pub gate: (usize, usize, usize, &'a [f32]),
463 pub up: (usize, usize, usize, &'a [f32]),
464 pub down: (usize, usize, usize, &'a [f32]),
465 pub xs_gate: Vec<f32>,
466 pub xs_up: Vec<f32>,
467 pub down_col: &'a [f32],
468 pub w: f32,
469 pub q1: bool,
472 pub q4t: bool,
475 pub q4tp: bool,
479 pub swiglu_limit: f32,
484}
485
486pub struct BatchJob<'a> {
488 pub idx: usize,
489 pub rows: usize,
490 pub cols: usize,
491 pub row_scale: &'a [f32],
492 pub xs: Vec<f32>,
493 pub layout: BatchLayout,
497}
498
499#[derive(Clone, Copy, PartialEq, Eq, Debug)]
502pub enum BatchLayout {
503 Q8,
504 Q1,
505 Q4t,
506 Q4tp,
507}
508
509#[derive(Clone, Copy, PartialEq, Eq)]
510enum Backend {
511 None,
512 #[cfg(target_os = "macos")]
513 Metal,
514 #[cfg(feature = "gpu")]
515 Wgpu,
516}
517
518fn backend() -> Backend {
519 #[cfg(feature = "gpu")]
520 if crate::gpu_wgpu::selected() {
521 return if crate::gpu_wgpu::enabled() {
522 Backend::Wgpu
523 } else {
524 Backend::None
525 };
526 }
527 #[cfg(target_os = "macos")]
528 if crate::gpu_metal::enabled() {
529 return Backend::Metal;
530 }
531 Backend::None
532}
533
534pub fn backend_available() -> bool {
540 #[cfg(target_os = "macos")]
541 {
542 true
544 }
545 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
546 {
547 static AVAIL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
548 *AVAIL.get_or_init(crate::gpu_wgpu::adapter_probe)
549 }
550 #[cfg(all(not(feature = "gpu"), not(target_os = "macos")))]
551 {
552 false
553 }
554}
555
556pub fn enabled() -> bool {
557 backend() != Backend::None
558}
559
560pub fn wgpu_active() -> bool {
574 #[cfg(feature = "gpu")]
575 {
576 matches!(backend(), Backend::Wgpu)
577 }
578 #[cfg(not(feature = "gpu"))]
579 {
580 false
581 }
582}
583
584pub fn wgpu_graph_default() -> bool {
585 #[cfg(feature = "gpu")]
586 {
587 matches!(backend(), Backend::Wgpu) && crate::gpu_wgpu::discrete_active()
588 }
589 #[cfg(not(feature = "gpu"))]
590 {
591 false
592 }
593}
594
595#[allow(clippy::too_many_arguments, unused_variables)]
597pub fn q8_matvec_range(
598 model: &Arc<CmfModel>,
599 idx: usize,
600 row0: usize,
601 row_scale: &[f32],
602 xs: &[f32],
603 rows: usize,
604 cols: usize,
605 out: &mut [f32],
606) -> bool {
607 match backend() {
608 #[cfg(target_os = "macos")]
609 Backend::Metal => {
610 crate::gpu_metal::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
611 }
612 #[cfg(feature = "gpu")]
613 Backend::Wgpu => {
614 crate::gpu_wgpu::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
615 }
616 Backend::None => false,
617 }
618}
619
620#[allow(clippy::too_many_arguments, unused_variables)]
623pub fn q8_matmat(
624 model: &Arc<CmfModel>,
625 idx: usize,
626 row_scale: &[f32],
627 pre: &[f32],
628 b: usize,
629 rows: usize,
630 cols: usize,
631 out: &mut [f32],
632) -> bool {
633 match backend() {
634 #[cfg(target_os = "macos")]
635 Backend::Metal => {
636 crate::gpu_metal::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out)
637 }
638 #[cfg(feature = "gpu")]
639 Backend::Wgpu => crate::gpu_wgpu::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out),
640 Backend::None => false,
641 }
642}
643
644#[allow(unused_variables)]
647pub fn q1_matvec(
648 model: &Arc<CmfModel>,
649 idx: usize,
650 xs: &[f32],
651 rows: usize,
652 cols: usize,
653 out: &mut [f32],
654) -> bool {
655 match backend() {
656 #[cfg(target_os = "macos")]
657 Backend::Metal => crate::gpu_metal::q1_matvec(model, idx, xs, rows, cols, out),
658 #[cfg(feature = "gpu")]
659 Backend::Wgpu => crate::gpu_wgpu::q1_matvec(model, idx, xs, rows, cols, out),
660 Backend::None => false,
661 }
662}
663
664#[allow(clippy::too_many_arguments)]
668pub fn attn_dropin(
669 model: &Arc<CmfModel>,
670 kv_id: u64,
671 layer: usize,
672 normed: &[f32],
673 wq_idx: usize,
674 wk_idx: usize,
675 wv_idx: usize,
676 wo_idx: usize,
677 q_norm: Option<&[f32]>,
678 k_norm: Option<&[f32]>,
679 invf: &[f32],
680 nh: usize,
681 nkv: usize,
682 hd: usize,
683 rd: usize,
684 hidden: usize,
685 pos: usize,
686 cap: usize,
687 gemma: bool,
688 eps: f32,
689 cpu_k: &[Vec<f32>],
690 cpu_v: &[Vec<f32>],
691 out: &mut [f32],
692) -> bool {
693 match backend() {
694 #[cfg(feature = "gpu")]
695 Backend::Wgpu => crate::gpu_wgpu::attn_dropin_gpu(
696 model, kv_id, layer, normed, wq_idx, wk_idx, wv_idx, wo_idx, q_norm, k_norm, invf, nh,
697 nkv, hd, rd, hidden, pos, cap, gemma, eps, cpu_k, cpu_v, out,
698 ),
699 #[allow(unused_variables)]
700 _ => false,
701 }
702}
703
704pub struct GraphW<'a> {
708 pub idx: usize,
709 pub kind: u8,
710 pub row_scale: &'a [f32],
711 pub data: &'a [f32],
712}
713
714pub enum GraphAttn<'a> {
717 Full {
718 wq: GraphW<'a>,
719 wk: GraphW<'a>,
720 wv: GraphW<'a>,
721 wo: GraphW<'a>,
722 q_norm: Option<&'a [f32]>,
723 k_norm: Option<&'a [f32]>,
724 bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
726 output_gate: bool,
729 cpu_k: &'a [Vec<f32>],
730 cpu_v: &'a [Vec<f32>],
731 },
732 Gdn {
733 qkv: GraphW<'a>,
734 z: GraphW<'a>,
735 a: GraphW<'a>,
736 b: GraphW<'a>,
737 out: GraphW<'a>,
738 conv1d: &'a [f32],
739 a_log: &'a [f32],
740 dt_bias: &'a [f32],
741 norm: &'a [f32],
742 nv: usize,
743 nk: usize,
744 dk: usize,
745 dv: usize,
746 kk: usize,
747 cpu_state: &'a [f32],
752 },
753}
754
755pub struct GraphLayer<'a> {
757 pub input_norm: &'a [f32],
758 pub attn: GraphAttn<'a>,
759 pub post_norm: &'a [f32],
760 pub ffn: GraphFfn<'a>,
761}
762
763pub enum GraphFfn<'a> {
768 Dense {
769 gate: GraphW<'a>,
770 up: GraphW<'a>,
771 down: GraphW<'a>,
772 },
773 Moe {
774 router: GraphW<'a>,
776 shared_gate: GraphW<'a>,
778 experts: Vec<(usize, usize, usize)>,
782 n_exp: usize,
784 top_k: usize,
785 inter: usize,
786 norm_topk: bool,
787 q4tp: bool,
793 gu_q2: bool,
797 },
798}
799
800#[allow(clippy::too_many_arguments)]
805pub fn forward_token_graph(
806 model: &Arc<CmfModel>,
807 kv_id: u64,
808 layers: &[GraphLayer],
809 o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
812 o1_epoch: u64,
813 invf: &[f32],
814 h: &mut [f32],
815 nh: usize,
816 nkv: usize,
817 hd: usize,
818 rd: usize,
819 hidden: usize,
820 inter: usize,
821 position: usize,
822 cap: usize,
823 gemma: bool,
824 eps: f32,
825 lm_head: Option<(&GraphW, usize)>,
826 final_norm: &[f32],
827 logits: &mut Vec<f32>,
828 loop_norm_at: &[usize],
829 steps: usize,
830 embed: Option<(&GraphW, usize, f32)>,
831 ids_out: Option<&mut Vec<u32>>,
832 layers_run: Option<&mut usize>,
835) -> bool {
836 match backend() {
837 #[cfg(feature = "gpu")]
838 Backend::Wgpu => crate::gpu_wgpu::forward_token_graph(
839 model,
840 kv_id,
841 layers,
842 o1,
843 o1_epoch,
844 invf,
845 h,
846 nh,
847 nkv,
848 hd,
849 rd,
850 hidden,
851 inter,
852 position,
853 cap,
854 gemma,
855 eps,
856 lm_head,
857 final_norm,
858 logits,
859 loop_norm_at,
860 steps,
861 embed,
862 ids_out,
863 layers_run,
864 ),
865 #[allow(unused_variables)]
866 _ => {
867 let _ = (lm_head, final_norm, logits, loop_norm_at, layers_run);
868 false
869 }
870 }
871}
872
873#[allow(clippy::too_many_arguments)]
877pub fn forward_batch_graph(
878 model: &Arc<CmfModel>,
879 kv_id: u64,
880 layers: &[GraphLayer],
881 invf: &[f32],
882 h: &mut [f32],
883 nh: usize,
884 nkv: usize,
885 hd: usize,
886 rd: usize,
887 hidden: usize,
888 inter: usize,
889 positions: &[usize],
890 cap: usize,
891 gemma: bool,
892 eps: f32,
893 k: usize,
894) -> bool {
895 match backend() {
896 #[cfg(feature = "gpu")]
897 Backend::Wgpu => crate::gpu_wgpu::forward_batch_graph(
898 model, kv_id, layers, invf, h, nh, nkv, hd, rd, hidden, inter, positions, cap, gemma,
899 eps, k,
900 ),
901 _ => false,
902 }
903}
904
905pub fn graph_kv_reset(_kv_id: u64) {
907 #[cfg(feature = "gpu")]
908 if backend() == Backend::Wgpu {
909 crate::gpu_wgpu::kv_mirror_reset(_kv_id);
910 }
911}
912
913pub fn q1t_matvec(
917 model: &Arc<CmfModel>,
918 idx: usize,
919 xs: &[f32],
920 rows: usize,
921 cols: usize,
922 out: &mut [f32],
923) -> bool {
924 match backend() {
925 #[cfg(target_os = "macos")]
926 Backend::Metal => {
927 if metal_q1t_enabled() {
928 crate::gpu_metal::q1t_matvec(model, idx, xs, rows, cols, out)
929 } else {
930 false
931 }
932 }
933 #[cfg(feature = "gpu")]
934 Backend::Wgpu => crate::gpu_wgpu::q1t_matvec(model, idx, xs, rows, cols, out),
935 Backend::None => false,
936 }
937}
938
939#[allow(unused_variables)]
942pub fn q4b_matvec(
943 model: &Arc<CmfModel>,
944 idx: usize,
945 xs: &[f32],
946 rows: usize,
947 cols: usize,
948 out: &mut [f32],
949) -> bool {
950 match backend() {
951 #[cfg(target_os = "macos")]
952 Backend::Metal => false,
953 #[cfg(feature = "gpu")]
954 Backend::Wgpu => crate::gpu_wgpu::q4b_matvec(model, idx, xs, rows, cols, out),
955 Backend::None => false,
956 }
957}
958
959pub fn q1t_matmat(
962 model: &Arc<CmfModel>,
963 idx: usize,
964 xs: &[f32],
965 b: usize,
966 rows: usize,
967 cols: usize,
968 out: &mut [f32],
969) -> bool {
970 match backend() {
971 #[cfg(target_os = "macos")]
972 Backend::Metal => crate::gpu_metal::q1t_matmat(model, idx, xs, b, rows, cols, out),
976 #[cfg(feature = "gpu")]
977 Backend::Wgpu => crate::gpu_wgpu::q1t_matmat(model, idx, xs, b, rows, cols, out),
978 Backend::None => false,
979 }
980}
981
982#[cfg(target_os = "macos")]
986pub(crate) fn metal_q1t_enabled() -> bool {
987 std::env::var("CMF_METAL_Q1T")
988 .map(|v| v != "0" && !v.eq_ignore_ascii_case("off"))
989 .unwrap_or(true)
990}
991
992pub fn q1_matmat(
994 model: &Arc<CmfModel>,
995 idx: usize,
996 xs: &[f32],
997 b: usize,
998 rows: usize,
999 cols: usize,
1000 out: &mut [f32],
1001) -> bool {
1002 match backend() {
1003 #[cfg(feature = "gpu")]
1004 Backend::Wgpu => crate::gpu_wgpu::q1_matmat(model, idx, xs, b, rows, cols, out),
1005 #[allow(unused_variables)]
1006 _ => false,
1007 }
1008}
1009
1010static MM_KILL: AtomicBool = AtomicBool::new(false);
1015pub(crate) fn mm_killed() -> bool {
1016 MM_KILL.load(Ordering::Relaxed)
1017}
1018pub(crate) fn mm_kill() {
1019 MM_KILL.store(true, Ordering::Relaxed);
1020}
1021
1022#[allow(unused_variables, clippy::too_many_arguments)]
1027pub fn chunk_attend(
1028 q: &[f32],
1029 k: &[&[f32]],
1030 v: &[&[f32]],
1031 b: usize,
1032 s0: usize,
1033 nh: usize,
1034 nkv: usize,
1035 hd: usize,
1036 scale: f32,
1037 out: &mut [f32],
1038) -> bool {
1039 match backend() {
1040 #[cfg(feature = "gpu")]
1041 Backend::Wgpu => crate::gpu_wgpu::chunk_attend(q, k, v, b, s0, nh, nkv, hd, scale, out),
1042 #[allow(unreachable_patterns)]
1043 _ => false,
1044 }
1045}
1046
1047#[allow(unused_variables, clippy::too_many_arguments)]
1051pub fn q4t_qkv(
1052 model: &Arc<CmfModel>,
1053 wq: usize,
1054 wk: usize,
1055 wv: usize,
1056 xs: &[f32],
1057 b: usize,
1058 cols: usize,
1059 rq: usize,
1060 rk: usize,
1061 rv: usize,
1062 out: &mut [f32],
1063) -> bool {
1064 match backend() {
1065 #[cfg(feature = "gpu")]
1066 Backend::Wgpu => crate::gpu_wgpu::q4t_qkv(model, wq, wk, wv, xs, b, cols, rq, rk, rv, out),
1067 #[allow(unreachable_patterns)]
1068 _ => false,
1069 }
1070}
1071
1072#[allow(unused_variables, clippy::too_many_arguments)]
1074pub fn q4tp_ffn(
1075 model: &Arc<CmfModel>,
1076 w1: usize,
1077 w3: usize,
1078 w2: usize,
1079 xs: &[f32],
1080 b: usize,
1081 hidden: usize,
1082 inter: usize,
1083 out: &mut [f32],
1084) -> bool {
1085 match backend() {
1086 #[cfg(target_os = "macos")]
1087 Backend::Metal => crate::gpu_metal::q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
1088 #[cfg(feature = "gpu")]
1089 Backend::Wgpu => false,
1092 #[allow(unreachable_patterns)]
1093 _ => false,
1094 }
1095}
1096
1097pub fn q4t_ffn(
1098 model: &Arc<CmfModel>,
1099 w1: usize,
1100 w3: usize,
1101 w2: usize,
1102 xs: &[f32],
1103 b: usize,
1104 hidden: usize,
1105 inter: usize,
1106 out: &mut [f32],
1107) -> bool {
1108 match backend() {
1109 #[cfg(target_os = "macos")]
1110 Backend::Metal => crate::gpu_metal::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
1111 #[cfg(feature = "gpu")]
1112 Backend::Wgpu => crate::gpu_wgpu::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
1113 #[allow(unreachable_patterns)]
1114 _ => false,
1115 }
1116}
1117
1118pub struct DitBlockArgs<'a> {
1123 pub n: usize,
1124 pub hidden: usize,
1125 pub inter: usize,
1126 pub nh: usize,
1127 pub nkv: usize,
1128 pub hd: usize,
1129 pub eps: f32,
1130 pub rope_cos: &'a [f32],
1131 pub rope_sin: &'a [f32],
1132 pub norm1: &'a [f32],
1133 pub norm2: &'a [f32],
1134 pub ffn_norm1: &'a [f32],
1135 pub ffn_norm2: &'a [f32],
1136 pub norm_q: &'a [f32],
1137 pub norm_k: &'a [f32],
1138 pub s_msa: &'a [f32],
1139 pub gate_msa: &'a [f32],
1140 pub s_mlp: &'a [f32],
1141 pub gate_mlp: &'a [f32],
1142 pub wq: usize,
1143 pub wk: usize,
1144 pub wv: usize,
1145 pub wo: usize,
1146 pub w1: usize,
1147 pub w3: usize,
1148 pub w2: usize,
1149}
1150
1151#[allow(unused_variables)]
1155pub fn dit_block(model: &Arc<CmfModel>, a: &DitBlockArgs, x: &mut [f32]) -> bool {
1156 match backend() {
1157 #[cfg(target_os = "macos")]
1158 Backend::Metal => crate::gpu_metal::dit_block(model, a, x),
1159 _ => false,
1160 }
1161}
1162
1163pub struct VaeResnetArgs<'a> {
1167 pub groups: usize,
1168 pub ic: usize,
1169 pub oc: usize,
1170 pub h: usize,
1171 pub w: usize,
1172 pub n1w: &'a [f32],
1173 pub n1b: &'a [f32],
1174 pub c1w: &'a [f32],
1175 pub c1b: &'a [f32],
1176 pub c1k: usize,
1177 pub n2w: &'a [f32],
1178 pub n2b: &'a [f32],
1179 pub c2w: &'a [f32],
1180 pub c2b: &'a [f32],
1181 pub c2k: usize,
1182 pub shortcut: Option<(&'a [f32], &'a [f32], usize)>,
1183}
1184
1185#[allow(unused_variables)]
1188pub fn vae_resnet(a: &VaeResnetArgs, x: &[f32], out: &mut [f32]) -> bool {
1189 match backend() {
1190 #[cfg(target_os = "macos")]
1191 Backend::Metal => crate::gpu_metal::vae_resnet(a, x, out),
1192 _ => false,
1193 }
1194}
1195
1196#[allow(unused_variables, clippy::too_many_arguments)]
1199pub fn vae_upsample_conv(
1200 w: &[f32],
1201 bias: &[f32],
1202 x: &[f32],
1203 ic: usize,
1204 oc: usize,
1205 h: usize,
1206 w_img: usize,
1207 k: usize,
1208 out: &mut [f32],
1209) -> bool {
1210 match backend() {
1211 #[cfg(target_os = "macos")]
1212 Backend::Metal => crate::gpu_metal::vae_upsample_conv(w, bias, x, ic, oc, h, w_img, k, out),
1213 _ => false,
1214 }
1215}
1216
1217#[allow(unused_variables, clippy::too_many_arguments)]
1220pub fn vae_conv2d(
1221 w: &[f32],
1222 bias: &[f32],
1223 x: &[f32],
1224 ic: usize,
1225 oc: usize,
1226 h: usize,
1227 w_img: usize,
1228 k: usize,
1229 out: &mut [f32],
1230) -> bool {
1231 match backend() {
1232 #[cfg(target_os = "macos")]
1233 Backend::Metal => crate::gpu_metal::vae_conv2d(w, bias, x, ic, oc, h, w_img, k, out),
1234 _ => false,
1235 }
1236}
1237
1238#[allow(unused_variables, clippy::too_many_arguments)]
1242pub fn dit_attention(
1243 qh: &[f32],
1244 kh: &[f32],
1245 vh: &[f32],
1246 nh: usize,
1247 nkv: usize,
1248 n: usize,
1249 hd: usize,
1250 scale: f32,
1251 out: &mut [f32],
1252) -> bool {
1253 match backend() {
1254 #[cfg(target_os = "macos")]
1255 Backend::Metal => crate::gpu_metal::dit_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
1256 #[cfg(feature = "gpu")]
1257 Backend::Wgpu => crate::gpu_wgpu::dit_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
1258 #[allow(unreachable_patterns)]
1259 _ => false,
1260 }
1261}
1262
1263#[allow(unused_variables)]
1268pub fn q4tp_matmat(
1269 model: &Arc<CmfModel>,
1270 idx: usize,
1271 xs: &[f32],
1272 b: usize,
1273 rows: usize,
1274 cols: usize,
1275 out: &mut [f32],
1276) -> bool {
1277 match backend() {
1278 #[cfg(target_os = "macos")]
1279 Backend::Metal => crate::gpu_metal::q4tp_matmat(model, idx, xs, b, rows, cols, out),
1280 #[cfg(feature = "gpu")]
1281 Backend::Wgpu => crate::gpu_wgpu::q4tp_matmat(model, idx, xs, b, rows, cols, out),
1282 #[allow(unreachable_patterns)]
1283 _ => false,
1284 }
1285}
1286
1287pub fn q4tp_matvec(
1292 model: &Arc<CmfModel>,
1293 idx: usize,
1294 xs: &[f32],
1295 rows: usize,
1296 cols: usize,
1297 out: &mut [f32],
1298) -> bool {
1299 match backend() {
1300 #[cfg(target_os = "macos")]
1301 Backend::Metal => crate::gpu_metal::q4tp_matvec_for_test(model, idx, xs, rows, cols, out),
1302 #[cfg(feature = "gpu")]
1303 Backend::Wgpu => crate::gpu_wgpu::q4tp_matvec(model, idx, xs, rows, cols, out),
1304 #[allow(unreachable_patterns)]
1305 _ => false,
1306 }
1307}
1308
1309pub fn q4t_matmat(
1310 model: &Arc<CmfModel>,
1311 idx: usize,
1312 xs: &[f32],
1313 b: usize,
1314 rows: usize,
1315 cols: usize,
1316 out: &mut [f32],
1317) -> bool {
1318 match backend() {
1319 #[cfg(target_os = "macos")]
1320 Backend::Metal => crate::gpu_metal::q4t_matmat(model, idx, xs, b, rows, cols, out),
1321 #[cfg(feature = "gpu")]
1322 Backend::Wgpu => crate::gpu_wgpu::q4t_matmat(model, idx, xs, b, rows, cols, out),
1323 #[allow(unreachable_patterns)]
1324 _ => false,
1325 }
1326}
1327
1328#[cfg(target_os = "macos")]
1330pub use crate::gpu_metal::{
1331 AttnDeviceParams, AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, GraphDims, TokenGraph, kv_mirror_drop,
1332 kv_mirror_read_last, kv_mirror_take_imp,
1333};
1334
1335#[cfg(target_os = "macos")]
1337pub fn gdn_block(
1338 model: &Arc<CmfModel>,
1339 layers: &[GdnGpuLayer],
1340 states: &mut [&mut [f32]],
1341 cfg: &GdnGpuCfg,
1342 h: &mut [f32],
1343) -> bool {
1344 match backend() {
1345 Backend::Metal => crate::gpu_metal::gdn_block(model, layers, states, cfg, h),
1346 _ => false,
1347 }
1348}
1349
1350#[allow(unused_variables)]
1352pub fn moe_block(model: &Arc<CmfModel>, jobs: &[MoeJob], out: &mut [f32]) -> bool {
1353 match backend() {
1354 #[cfg(target_os = "macos")]
1355 Backend::Metal => crate::gpu_metal::moe_block(model, jobs, out),
1356 #[cfg(feature = "gpu")]
1357 Backend::Wgpu => crate::gpu_wgpu::moe_block(model, jobs, out),
1358 Backend::None => false,
1359 }
1360}
1361
1362#[allow(unused_variables)]
1364pub fn matvec_batch(model: &Arc<CmfModel>, jobs: &[BatchJob], out: &mut [&mut [f32]]) -> bool {
1365 match backend() {
1366 #[cfg(target_os = "macos")]
1367 Backend::Metal => crate::gpu_metal::matvec_batch(model, jobs, out),
1368 #[cfg(feature = "gpu")]
1369 Backend::Wgpu => crate::gpu_wgpu::matvec_batch(model, jobs, out),
1370 Backend::None => false,
1371 }
1372}
1373
1374static GRAPH_RACE_STATE: AtomicU8 = AtomicU8::new(0); static GRAPH_RACE_FLIP: AtomicU32 = AtomicU32::new(0);
1390static GRAPH_RACE_ARM_GRAPH: AtomicU8 = AtomicU8::new(0); static GRAPH_RACE_TOK: AtomicU32 = AtomicU32::new(0); static GRAPH_NS: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; static GRAPH_N: [AtomicU32; 2] = [AtomicU32::new(0), AtomicU32::new(0)];
1394
1395const GRAPH_RACE_SAMPLES: u32 = 4;
1397
1398pub fn graph_race_begin_generation() {
1401 GRAPH_RACE_TOK.store(0, Ordering::Relaxed);
1402 if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
1403 return;
1404 }
1405 let (gn, cn) = (
1406 GRAPH_N[1].load(Ordering::Relaxed),
1407 GRAPH_N[0].load(Ordering::Relaxed),
1408 );
1409 if gn >= GRAPH_RACE_SAMPLES && cn >= GRAPH_RACE_SAMPLES {
1410 let g_avg = GRAPH_NS[1].load(Ordering::Relaxed) / gn as u64;
1411 let c_avg = GRAPH_NS[0].load(Ordering::Relaxed) / cn as u64;
1412 let verdict = if g_avg < c_avg { 1 } else { 2 };
1413 GRAPH_RACE_STATE.store(verdict, Ordering::Relaxed);
1414 tracing::info!(
1415 "wgpu graph race: graph {:.2} ms/tok vs normal {:.2} ms/tok -> {}",
1416 g_avg as f64 / 1e6,
1417 c_avg as f64 / 1e6,
1418 if verdict == 1 { "graph" } else { "normal path" }
1419 );
1420 return;
1421 }
1422 let flip = GRAPH_RACE_FLIP.fetch_add(1, Ordering::Relaxed);
1423 GRAPH_RACE_ARM_GRAPH.store((flip % 2 == 1) as u8, Ordering::Relaxed);
1424}
1425
1426pub fn graph_race_use_graph(trusted: bool) -> bool {
1430 if trusted {
1431 return true;
1432 }
1433 match GRAPH_RACE_STATE.load(Ordering::Relaxed) {
1434 1 => true,
1435 2 => false,
1436 _ => GRAPH_RACE_ARM_GRAPH.load(Ordering::Relaxed) == 1,
1437 }
1438}
1439
1440pub fn graph_race_first_token_hopeless(dur: std::time::Duration) -> bool {
1445 if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
1446 return false;
1447 }
1448 let first = GRAPH_RACE_TOK.load(Ordering::Relaxed) == 0;
1449 let cn = GRAPH_N[0].load(Ordering::Relaxed);
1450 if !first || cn == 0 {
1451 return false;
1452 }
1453 let c_avg = GRAPH_NS[0].load(Ordering::Relaxed) / cn as u64;
1454 let ns = dur.as_nanos() as u64;
1455 if ns > 1_000_000_000 && ns > 4 * c_avg {
1456 GRAPH_RACE_STATE.store(2, Ordering::Relaxed);
1457 tracing::info!(
1458 "wgpu graph race: first graph token {:.0} ms vs normal {:.2} ms/tok — hopeless, normal path wins",
1459 ns as f64 / 1e6,
1460 c_avg as f64 / 1e6
1461 );
1462 return true;
1463 }
1464 false
1465}
1466
1467pub fn graph_race_record(used_graph: bool, dur: std::time::Duration) {
1471 if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
1472 return;
1473 }
1474 let tok = GRAPH_RACE_TOK.fetch_add(1, Ordering::Relaxed);
1475 if tok == 0 {
1476 return;
1477 }
1478 let i = used_graph as usize;
1479 GRAPH_NS[i].fetch_add(dur.as_nanos() as u64, Ordering::Relaxed);
1480 GRAPH_N[i].fetch_add(1, Ordering::Relaxed);
1481}