1use cortiq_core::CmfModel;
14use std::cell::Cell;
15use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
16use std::sync::{Arc, OnceLock};
17
18pub 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 rope_freq: Vec<f32>,
42 pub max_seq: usize,
43 pub cluster_count: usize,
44 pub cluster_size: usize,
45 pub phase_state_len: usize,
46 pub state_stride: usize,
47 pub kv_stride: usize,
48 pub norm_gemma: bool,
49 pub phase_mass: f32,
50 pub weights: Vec<f32>,
51 pub meta: Vec<u32>,
52 pub lm_head: Vec<f32>,
53 pub wide: bool,
56 pub wide_q8: bool,
57 pub mats: Vec<u8>,
58 pub lm_head_packed: Vec<u8>,
59 pub clusters: Vec<f32>,
60 pub final_norm: Vec<f32>,
61 pub inv_freq: Vec<f32>,
62 pub bounded: bool,
67 pub kv_layers: usize,
71 pub state_layers: usize,
74 pub anchor_window: usize,
75 pub anchor_sink: usize,
76 pub phase_layers: usize,
78 pub gdn_layers: usize,
82 pub gdn_heads: usize,
83 pub gdn_k_heads: usize,
84 pub gdn_dk: usize,
85 pub gdn_dv: usize,
86 pub gdn_kk: usize,
87}
88
89impl EmbryoGraphModel {
90 pub fn gdn_c_dim(&self) -> usize {
92 2 * self.gdn_k_heads * self.gdn_dk + self.gdn_heads * self.gdn_dv
93 }
94}
95
96pub const EMBRYO_META_HEADER: usize = 32;
99
100pub const EMBRYO_CHUNK_MAX: usize = 64;
104
105pub fn forward_embryo_graph_chunk(
110 model: &Arc<EmbryoGraphModel>,
111 kv_id: u64,
112 rows: &[f32],
113 position: usize,
114 n: usize,
115 logits: &mut Vec<f32>,
116) -> bool {
117 #[cfg(feature = "cuda")]
118 if backend() == Backend::Cuda {
119 return crate::gpu_cuda::forward_embryo_graph_chunk(model, kv_id, rows, position, n, logits);
120 }
121 #[cfg(feature = "gpu")]
122 if backend() == Backend::Wgpu {
123 return crate::gpu_wgpu::forward_embryo_graph_chunk(model, kv_id, rows, position, n, logits);
124 }
125 let _ = (model, kv_id, rows, position, n, logits);
126 false
127}
128
129pub fn embryo_device_state_bytes(kv_id: u64) -> Option<(u64, u64)> {
135 #[cfg(feature = "cuda")]
136 if backend() == Backend::Cuda {
137 return crate::gpu_cuda::embryo_device_state_bytes(kv_id);
138 }
139 #[cfg(feature = "gpu")]
140 if backend() == Backend::Wgpu {
141 return crate::gpu_wgpu::embryo_device_state_bytes(kv_id);
142 }
143 let _ = kv_id;
144 None
145}
146
147pub fn counts_as_placement_weight(model: &CmfModel, name: &str) -> bool {
154 model.header.genome.is_none() || cortiq_core::knowledge::is_trunk_tensor(name)
155}
156
157pub fn placement_weight_bytes(model: &CmfModel) -> u64 {
161 if model.header.genome.is_none() {
162 return model.primary_bytes().len() as u64;
163 }
164 model
165 .tensors
166 .iter()
167 .filter(|t| counts_as_placement_weight(model, &t.name))
168 .map(|t| t.nbytes)
169 .sum()
170}
171
172pub fn embryo_device_next_position(kv_id: u64) -> Option<usize> {
176 #[cfg(feature = "cuda")]
177 if backend() == Backend::Cuda {
178 return crate::gpu_cuda::embryo_device_next_position(kv_id);
179 }
180 #[cfg(feature = "gpu")]
181 if backend() == Backend::Wgpu {
182 return crate::gpu_wgpu::embryo_device_next_position(kv_id);
183 }
184 let _ = kv_id;
185 None
186}
187
188thread_local! {
189 static CUR_LAYER: Cell<i64> = const { Cell::new(-1) };
193 static CPU_ONLY: Cell<bool> = const { Cell::new(false) };
198 static PROBE_COLD: Cell<bool> = const { Cell::new(false) };
202}
203
204pub struct CpuScopeGuard(bool);
210
211impl Drop for CpuScopeGuard {
212 fn drop(&mut self) {
213 CPU_ONLY.with(|c| c.set(self.0));
214 }
215}
216
217pub fn enter_cpu_scope() -> CpuScopeGuard {
218 let previous = CPU_ONLY.with(|c| c.replace(true));
219 CpuScopeGuard(previous)
220}
221
222pub fn gpu_scope<R>(f: impl FnOnce() -> R) -> R {
228 struct Restore(bool);
229 impl Drop for Restore {
230 fn drop(&mut self) {
231 CPU_ONLY.with(|c| c.set(self.0));
232 }
233 }
234 let prev = CPU_ONLY.with(|c| c.replace(false));
235 let restore = Restore(prev);
236 let out = f();
237 drop(restore);
238 out
239}
240
241pub fn cpu_scope<R>(f: impl FnOnce() -> R) -> R {
243 let _restore = enter_cpu_scope();
244 f()
245}
246
247pub(crate) fn inherit_cpu_scope() -> impl Fn() -> Option<CpuScopeGuard> + Copy {
252 let on = CPU_ONLY.get();
253 move || on.then(enter_cpu_scope)
254}
255
256pub fn probe_set_device(label: &str) {
261 let _ = DEVICE_LABEL.set(label.to_string());
262}
263
264fn device_label() -> &'static str {
265 DEVICE_LABEL.get().map(String::as_str).unwrap_or("unknown")
266}
267
268static DEVICE_LABEL: std::sync::OnceLock<String> = std::sync::OnceLock::new();
269
270static CACHE_DIR: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();
279
280pub fn set_cache_dir(dir: std::path::PathBuf) {
282 let _ = CACHE_DIR.set(dir);
283}
284
285pub fn cache_dir_pub() -> std::path::PathBuf {
287 cache_dir()
288}
289
290fn cache_dir() -> std::path::PathBuf {
291 if let Some(d) = CACHE_DIR.get() {
292 return d.clone();
293 }
294 match std::env::var_os("TMPDIR") {
295 Some(t) => std::path::PathBuf::from(t),
296 None => std::env::temp_dir(),
297 }
298}
299
300fn probe_cache_path() -> Option<std::path::PathBuf> {
303 match std::env::var("CMF_PROBE_CACHE") {
304 Ok(v) if v == "0" => None,
305 Ok(v) => Some(std::path::PathBuf::from(v)),
306 Err(_) => Some(cache_dir().join("cortiq-gpu-probe.tsv")),
307 }
308}
309
310fn probe_cache_key_named(class: &str) -> String {
314 format!(
315 "{}\t{}\t{}",
316 env!("CARGO_PKG_VERSION"),
317 device_label(),
318 class
319 )
320}
321
322const CLASS_NAMES: [&str; 8] = [
323 "ffn",
324 "matvec",
325 "matmat",
326 "qkv-batch",
327 "matmat-wide",
328 "lm-head",
329 "gemm-nt",
330 "moe",
335];
336
337fn probe_cache_load() {
346 static ONCE: std::sync::Once = std::sync::Once::new();
347 ONCE.call_once(|| {
348 let Some(path) = probe_cache_path() else {
349 return;
350 };
351 if cfg!(test) && std::env::var("CMF_PROBE_CACHE").is_err() {
356 return;
357 }
358 let Ok(text) = std::fs::read_to_string(&path) else {
359 return;
360 };
361 probe_cache_adopt(&text);
362 });
363}
364
365fn probe_cache_adopt(text: &str) {
369 for line in text.lines() {
370 let Some((key, verdict)) = line.rsplit_once('\t') else {
371 continue;
372 };
373 let winner = match verdict.trim() {
374 "gpu" => 1u8,
375 "cpu" => 2u8,
376 _ => continue,
377 };
378 for (i, name) in CLASS_NAMES.iter().enumerate() {
379 if probe_cache_key_named(name) == key {
380 let _ = PROBES[i].state.compare_exchange(
381 0,
382 winner,
383 Ordering::Relaxed,
384 Ordering::Relaxed,
385 );
386 tracing::debug!("gpu probe [{name}]: remembered → {verdict}");
387 }
388 }
389 }
390}
391
392fn probe_cache_store(c: OpClass, winner: u8) {
395 let Some(path) = probe_cache_path() else {
396 return;
397 };
398 let line = format!(
399 "{}\t{}\n",
400 probe_cache_key_named(CLASS_NAMES[c as usize]),
401 if winner == 1 { "gpu" } else { "cpu" }
402 );
403 use std::io::Write;
404 if let Ok(mut f) = std::fs::OpenOptions::new()
405 .create(true)
406 .append(true)
407 .open(&path)
408 {
409 let _ = f.write_all(line.as_bytes());
410 }
411}
412
413pub fn cold_epoch() -> u64 {
419 COLD_EPOCH.load(std::sync::atomic::Ordering::Relaxed)
420}
421static COLD_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
422
423pub(crate) fn probe_note_cold() {
424 COLD_EPOCH.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
425 PROBE_COLD.with(|c| c.set(true));
426}
427
428pub(crate) fn probe_was_cold() -> bool {
432 PROBE_COLD.with(|c| c.get())
433}
434
435pub fn set_layer(l: i64) {
437 CUR_LAYER.with(|c| c.set(l));
438}
439
440pub fn cur_layer() -> i64 {
442 CUR_LAYER.with(|c| c.get())
443}
444
445pub fn automatic_layer_prefix(
448 model: &Arc<CmfModel>,
449 num_layers: usize,
450 physical_layers: usize,
451) -> Option<usize> {
452 match backend() {
453 #[cfg(feature = "gpu")]
454 Backend::Wgpu => {
455 crate::gpu_wgpu::automatic_layer_prefix(model, num_layers, physical_layers)
456 }
457 _ => None,
458 }
459}
460
461fn layer_ranges() -> &'static Option<Vec<(i64, i64)>> {
464 static R: OnceLock<Option<Vec<(i64, i64)>>> = OnceLock::new();
465 R.get_or_init(|| {
466 let s = std::env::var("CMF_GPU_LAYERS").ok()?;
467 let mut v = Vec::new();
468 for part in s.split(',') {
469 let part = part.trim();
470 match part.split_once('-') {
471 Some((a, b)) => v.push((a.trim().parse().ok()?, b.trim().parse().ok()?)),
472 None => {
473 let x: i64 = part.parse().ok()?;
474 v.push((x, x));
475 }
476 }
477 }
478 Some(v)
479 })
480}
481
482fn layer_allowed() -> bool {
483 match layer_ranges() {
484 None => true,
485 Some(ranges) => {
486 let cur = CUR_LAYER.with(|c| c.get());
487 cur < 0 || ranges.iter().any(|(a, b)| cur >= *a && cur <= *b)
488 }
489 }
490}
491
492pub fn enabled_here() -> bool {
496 !CPU_ONLY.with(|c| c.get()) && enabled() && layer_allowed()
497}
498
499pub fn q2tp_gpu_opt_in() -> bool {
505 std::env::var("CMF_Q2TP_GPU").as_deref() == Ok("1")
506}
507
508#[derive(Clone, Copy)]
520pub enum OpClass {
521 Ffn = 0,
523 Matvec = 1,
525 Matmat = 2,
527 Batch = 3,
529 MatmatWide = 4,
535 MatvecHead = 5,
542 GemmNt = 6,
549 Moe = 7,
552}
553
554pub fn matvec_class(rows: usize, cols: usize) -> OpClass {
558 if rows * cols >= 67_108_864 {
559 OpClass::MatvecHead
560 } else {
561 OpClass::Matvec
562 }
563}
564
565pub enum ProbeArm {
567 Gpu,
569 CpuTimed,
571 Cpu,
573}
574
575const PROBE_SAMPLES: u32 = 6;
577
578const PROBE_DECLINE_LIMIT: u32 = 16;
582
583const PROBE_WARMUP: u32 = 1;
585
586struct Probe {
587 state: AtomicU8,
589 flip: AtomicU32,
590 gpu_ns: AtomicU64,
591 gpu_n: AtomicU32,
592 declines: AtomicU32,
602 gpu_burn: AtomicU32,
615 cpu_ns: AtomicU64,
616 cpu_n: AtomicU32,
617 gpu_min: AtomicU64,
624 cpu_min: AtomicU64,
625}
626
627impl Probe {
628 const fn new() -> Self {
629 Self {
630 state: AtomicU8::new(0),
631 flip: AtomicU32::new(0),
632 gpu_ns: AtomicU64::new(0),
633 gpu_n: AtomicU32::new(0),
634 declines: AtomicU32::new(0),
635 gpu_burn: AtomicU32::new(PROBE_WARMUP),
636 cpu_ns: AtomicU64::new(0),
637 cpu_n: AtomicU32::new(0),
638 gpu_min: AtomicU64::new(u64::MAX),
639 cpu_min: AtomicU64::new(u64::MAX),
640 }
641 }
642}
643
644static PROBES: [Probe; 8] = [
645 Probe::new(),
646 Probe::new(),
647 Probe::new(),
648 Probe::new(),
649 Probe::new(),
650 Probe::new(),
651 Probe::new(),
652 Probe::new(),
653];
654
655static TRUST_GPU: AtomicBool = AtomicBool::new(false);
662
663pub fn trust_gpu() -> GpuTrust {
665 let was = TRUST_GPU.swap(true, Ordering::Relaxed);
666 GpuTrust(was)
667}
668
669pub struct GpuTrust(bool);
670
671impl Drop for GpuTrust {
672 fn drop(&mut self) {
673 TRUST_GPU.store(self.0, Ordering::Relaxed);
674 }
675}
676
677fn probe_on_for(c: OpClass) -> bool {
678 if TRUST_GPU.load(Ordering::Relaxed) && matches!(c, OpClass::MatmatWide | OpClass::Ffn) {
684 return false;
685 }
686 probe_on()
687}
688
689pub fn probe_enabled() -> bool {
693 probe_on()
694}
695
696fn probe_on() -> bool {
697 static ON: OnceLock<bool> = OnceLock::new();
698 *ON.get_or_init(|| {
699 std::env::var("CMF_GPU_PROBE")
700 .map(|v| v != "0" && v != "off")
701 .unwrap_or(true)
702 })
703}
704
705pub fn q1_force() -> bool {
710 #[cfg(target_os = "macos")]
711 {
712 backend() == Backend::Metal
713 }
714 #[cfg(not(target_os = "macos"))]
715 {
716 false
717 }
718}
719
720pub fn fused_block_trusted() -> bool {
739 #[cfg(target_os = "macos")]
740 if backend() == Backend::Metal {
741 return true;
742 }
743 wgpu_graph_default()
744}
745
746pub fn weight_is_resident(model: &Arc<CmfModel>, idx: usize) -> bool {
758 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
759 {
760 return crate::gpu_wgpu::weight_is_resident(model, idx);
761 }
762 #[cfg(not(all(feature = "gpu", not(target_os = "macos"))))]
763 {
764 let _ = (model, idx);
765 true
766 }
767}
768
769pub fn probe_arm_cold_prefers_gpu(c: OpClass, weights_resident: bool) -> ProbeArm {
770 if !weights_resident && probe_deciding(c) {
771 return ProbeArm::Gpu;
772 }
773 probe_arm(c)
774}
775
776pub fn probe_arm(c: OpClass) -> ProbeArm {
777 PROBE_COLD.with(|f| f.set(false));
782 if !probe_on_for(c) {
783 return ProbeArm::Gpu;
784 }
785 probe_cache_load();
786 let p = &PROBES[c as usize];
787 match p.state.load(Ordering::Relaxed) {
788 1 => ProbeArm::Gpu,
789 2 => ProbeArm::Cpu,
790 _ => {
791 if p.flip.fetch_add(1, Ordering::Relaxed) % 2 == 0 {
792 ProbeArm::Gpu
793 } else {
794 ProbeArm::CpuTimed
795 }
796 }
797 }
798}
799
800pub fn probe_note_decline(c: OpClass) {
804 let p = &PROBES[c as usize];
805 if p.state.load(Ordering::Relaxed) != 0 {
806 return;
807 }
808 let n = p.declines.fetch_add(1, Ordering::Relaxed) + 1;
809 if n >= PROBE_DECLINE_LIMIT
810 && p.state
811 .compare_exchange(0, 2, Ordering::Relaxed, Ordering::Relaxed)
812 .is_ok()
813 {
814 tracing::info!(
815 "gpu probe [{}]: device declined {n} times → cpu",
816 CLASS_NAMES[c as usize]
817 );
818 }
819}
820
821pub fn probe_record(c: OpClass, gpu: bool, dur: std::time::Duration) {
824 probe_record_into(
825 &PROBES[c as usize],
826 CLASS_NAMES[c as usize],
827 Some(c),
828 gpu,
829 dur,
830 )
831}
832
833fn probe_record_into(
836 p: &Probe,
837 class_name: &str,
838 cache: Option<OpClass>,
839 gpu: bool,
840 dur: std::time::Duration,
841) {
842 if p.state.load(Ordering::Relaxed) != 0 {
843 return;
844 }
845 if gpu && PROBE_COLD.with(|f| f.replace(false)) {
846 return; }
848 if gpu {
849 let left = p.gpu_burn.load(Ordering::Relaxed);
853 if left > 0 {
854 p.gpu_burn.store(left - 1, Ordering::Relaxed);
855 return; }
857 }
858 let ns = dur.as_nanos().min(u64::MAX as u128) as u64;
859 if gpu {
860 p.gpu_ns.fetch_add(ns, Ordering::Relaxed);
861 p.gpu_n.fetch_add(1, Ordering::Relaxed);
862 p.gpu_min.fetch_min(ns, Ordering::Relaxed);
863 } else {
864 p.cpu_ns.fetch_add(ns, Ordering::Relaxed);
865 p.cpu_n.fetch_add(1, Ordering::Relaxed);
866 p.cpu_min.fetch_min(ns, Ordering::Relaxed);
867 }
868 let (gn, cn) = (
869 p.gpu_n.load(Ordering::Relaxed),
870 p.cpu_n.load(Ordering::Relaxed),
871 );
872 if gn >= 2 && cn >= 2 {
873 let g = p.gpu_min.load(Ordering::Relaxed) as f64;
877 let cp = p.cpu_min.load(Ordering::Relaxed) as f64;
878 if (gn < PROBE_SAMPLES || cn < PROBE_SAMPLES) && g < cp * 2.0 && cp < g * 2.0 {
888 return;
889 }
890 let winner = if g <= cp { 1 } else { 2 };
891 if p.state
892 .compare_exchange(0, winner, Ordering::Relaxed, Ordering::Relaxed)
893 .is_ok()
894 {
895 tracing::info!(
896 "gpu probe [{}]: gpu {:.2} ms vs cpu {:.2} ms per op → {}",
897 class_name,
898 g / 1e6,
899 cp / 1e6,
900 if winner == 1 { "gpu" } else { "cpu" },
901 );
902 if let Some(c) = cache {
903 probe_cache_store(c, winner);
904 }
905 }
906 }
907}
908
909pub fn probe_deciding(c: OpClass) -> bool {
912 probe_on_for(c) && PROBES[c as usize].state.load(Ordering::Relaxed) == 0
913}
914
915#[allow(unused_variables)]
925pub fn q8_resident_or_upload(model: &Arc<CmfModel>, idx: usize) -> bool {
926 static PROBE_UPLOADS: AtomicU32 = AtomicU32::new(0);
927 let may_upload = PROBE_UPLOADS.load(Ordering::Relaxed) < 4;
928 let resident = match backend() {
929 #[cfg(target_os = "macos")]
930 Backend::Metal => crate::gpu_metal::q8_resident_or_upload(model, idx, may_upload),
931 #[cfg(feature = "gpu")]
932 Backend::Wgpu => crate::gpu_wgpu::q8_resident_or_upload(model, idx, may_upload),
933 Backend::None => false,
934 #[cfg(feature = "cuda")]
935 Backend::Cuda => crate::gpu_cuda::h3_plane_ready(model, idx, may_upload),
936 };
937 if !resident && may_upload {
938 PROBE_UPLOADS.fetch_add(1, Ordering::Relaxed);
939 }
940 resident
941}
942
943#[cfg(test)]
945pub(crate) fn probe_reset() {
946 for p in &PROBES {
947 p.state.store(0, Ordering::Relaxed);
948 p.flip.store(0, Ordering::Relaxed);
949 p.gpu_ns.store(0, Ordering::Relaxed);
950 p.gpu_n.store(0, Ordering::Relaxed);
951 p.cpu_ns.store(0, Ordering::Relaxed);
952 p.cpu_n.store(0, Ordering::Relaxed);
953 }
954}
955
956#[cfg(test)]
960static PROBE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
961
962#[cfg(test)]
963fn probe_test_guard() -> std::sync::MutexGuard<'static, ()> {
964 PROBE_TEST_LOCK
965 .lock()
966 .unwrap_or_else(std::sync::PoisonError::into_inner)
967}
968
969#[cfg(test)]
970mod probe_tests {
971 use super::*;
972 use std::time::Duration;
973
974 #[test]
975 fn cpu_only_whole_operator_dispatch_inherits_and_restores_scope() {
976 let pool = crate::pool::Pool::with_spin(3, 0);
977 cpu_scope(|| {
978 let inherit = inherit_cpu_scope();
979 pool.run_rows(64, &|_, _| {
980 let _guard = inherit();
981 assert!(CPU_ONLY.get());
982 });
983 });
984 pool.run_rows(64, &|_, _| assert!(!CPU_ONLY.get()));
985 }
986
987 #[test]
990 fn probe_alternates_discards_cold_and_decides() {
991 let _probe_guard = probe_test_guard();
992 probe_reset();
993 assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
995 assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::CpuTimed));
996
997 probe_note_cold();
1001 probe_record(OpClass::Ffn, true, Duration::from_secs(1000));
1002 for _ in 0..PROBE_SAMPLES {
1003 probe_record(OpClass::Ffn, true, Duration::from_millis(1));
1004 probe_record(OpClass::Ffn, false, Duration::from_millis(4));
1005 }
1006 assert!(matches!(probe_arm(OpClass::Ffn), ProbeArm::Gpu));
1007
1008 for _ in 0..PROBE_SAMPLES {
1010 probe_record(OpClass::Matmat, true, Duration::from_millis(4));
1011 probe_record(OpClass::Matmat, false, Duration::from_millis(1));
1012 }
1013 assert!(matches!(probe_arm(OpClass::Matmat), ProbeArm::Cpu));
1014
1015 cpu_scope(|| CPU_ONLY.with(|c| assert!(c.get())));
1017 CPU_ONLY.with(|c| assert!(!c.get()));
1018 cpu_scope(|| {
1019 cpu_scope(|| CPU_ONLY.with(|c| assert!(c.get())));
1020 CPU_ONLY.with(|c| assert!(c.get()));
1021 });
1022 let _ = std::panic::catch_unwind(|| cpu_scope(|| panic!("scope test")));
1023 CPU_ONLY.with(|c| assert!(!c.get()));
1024 probe_reset();
1025 }
1026
1027 #[test]
1028 fn a_remembered_verdict_is_adopted_and_a_stranger_is_not() {
1029 let _probe_guard = probe_test_guard();
1030 let mine = probe_cache_key_named("gemm-nt");
1042 let state = || {
1043 PROBES[OpClass::GemmNt as usize]
1044 .state
1045 .load(Ordering::Relaxed)
1046 };
1047
1048 probe_cache_adopt("SomeOtherGPU/Vulkan\tgemm-nt\tgpu\n");
1050 assert_eq!(state(), 0);
1051 let older = mine.replacen(env!("CARGO_PKG_VERSION"), "0.0.0-old", 1);
1053 assert_ne!(older, mine);
1054 probe_cache_adopt(&format!("{older}\tgpu\n"));
1055 assert_eq!(state(), 0);
1056 probe_cache_adopt(&format!("{mine}\tcpu\n"));
1058 assert_eq!(state(), 2);
1059
1060 PROBES[OpClass::GemmNt as usize]
1061 .state
1062 .store(0, Ordering::Relaxed);
1063 }
1064}
1065
1066pub const GPU_MIN_ROWS: usize = 65_536;
1069
1070pub fn min_rows() -> usize {
1077 if let Some(v) = std::env::var("CMF_GPU_MIN_ROWS")
1078 .ok()
1079 .and_then(|v| v.parse().ok())
1080 {
1081 return v;
1082 }
1083 if discrete() { 4096 } else { GPU_MIN_ROWS }
1084}
1085
1086pub fn discrete() -> bool {
1088 match backend() {
1089 #[cfg(feature = "gpu")]
1090 Backend::Wgpu => crate::gpu_wgpu::is_discrete(),
1091 #[cfg(target_os = "macos")]
1092 Backend::Metal => false, Backend::None => false,
1094 #[cfg(feature = "cuda")]
1095 Backend::Cuda => true,
1096 }
1097}
1098
1099pub struct MoeJob<'a> {
1103 pub gate: (usize, usize, usize, &'a [f32]),
1104 pub up: (usize, usize, usize, &'a [f32]),
1105 pub down: (usize, usize, usize, &'a [f32]),
1106 pub xs_gate: Vec<f32>,
1107 pub xs_up: Vec<f32>,
1108 pub down_col: &'a [f32],
1109 pub w: f32,
1110 pub q1: bool,
1113 pub q4t: bool,
1116 pub q4tp: bool,
1120 pub gu_q2: bool,
1124 pub swiglu_limit: f32,
1129 pub act: u32,
1135}
1136
1137pub struct BatchJob<'a> {
1139 pub idx: usize,
1140 pub rows: usize,
1141 pub cols: usize,
1142 pub row_scale: &'a [f32],
1143 pub xs: Vec<f32>,
1144 pub layout: BatchLayout,
1148}
1149
1150#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1153pub enum BatchLayout {
1154 Q8,
1155 Q1,
1156 Q1g,
1158 Q4t,
1159 Q4tp,
1160}
1161
1162#[derive(Clone, Copy, PartialEq, Eq)]
1163enum Backend {
1164 None,
1165 #[cfg(target_os = "macos")]
1166 Metal,
1167 #[cfg(feature = "gpu")]
1168 Wgpu,
1169 #[cfg(feature = "cuda")]
1171 Cuda,
1172}
1173
1174pub fn backend_name() -> String {
1176 match backend() {
1177 #[cfg(target_os = "macos")]
1178 Backend::Metal => "metal".into(),
1179 #[cfg(feature = "gpu")]
1180 Backend::Wgpu => "wgpu".into(),
1181 Backend::None => "cpu".into(),
1182 #[cfg(feature = "cuda")]
1183 Backend::Cuda => "cuda".into(),
1184 }
1185}
1186
1187fn backend() -> Backend {
1188 #[cfg(feature = "cuda")]
1191 if crate::gpu_cuda::selected() {
1192 return if crate::gpu_cuda::enabled() {
1193 Backend::Cuda
1194 } else {
1195 Backend::None
1196 };
1197 }
1198 #[cfg(not(feature = "cuda"))]
1201 {
1202 static SAID: std::sync::Once = std::sync::Once::new();
1203 SAID.call_once(|| {
1204 if std::env::var("CMF_GPU").as_deref() == Ok("cuda") {
1205 tracing::warn!(
1206 "CMF_GPU=cuda: this build has no CUDA backend (build with `--features cuda`)"
1207 );
1208 }
1209 });
1210 }
1211 #[cfg(feature = "gpu")]
1212 if crate::gpu_wgpu::selected() {
1213 return if crate::gpu_wgpu::enabled() {
1214 Backend::Wgpu
1215 } else {
1216 Backend::None
1217 };
1218 }
1219 #[cfg(target_os = "macos")]
1220 if crate::gpu_metal::enabled() {
1221 return Backend::Metal;
1222 }
1223 Backend::None
1224}
1225
1226pub fn backend_available() -> bool {
1232 #[cfg(target_os = "macos")]
1233 {
1234 true
1236 }
1237 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
1238 {
1239 static AVAIL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1240 *AVAIL.get_or_init(crate::gpu_wgpu::adapter_probe)
1241 }
1242 #[cfg(all(not(feature = "gpu"), not(target_os = "macos")))]
1243 {
1244 false
1245 }
1246}
1247
1248static GPU_PAUSED: PauseGate = PauseGate::new();
1254
1255struct PauseGate(std::sync::atomic::AtomicUsize);
1260
1261impl PauseGate {
1262 const fn new() -> Self {
1263 Self(std::sync::atomic::AtomicUsize::new(0))
1264 }
1265
1266 fn enter(&self) {
1267 self.0.fetch_add(1, Ordering::Relaxed);
1268 }
1269
1270 fn leave(&self) {
1271 self.0.fetch_sub(1, Ordering::Relaxed);
1272 }
1273
1274 fn paused(&self) -> bool {
1275 self.0.load(Ordering::Relaxed) != 0
1276 }
1277}
1278
1279pub fn pause_gpu() -> GpuPause {
1282 GPU_PAUSED.enter();
1283 GpuPause(())
1284}
1285
1286pub struct GpuPause(());
1287
1288impl Drop for GpuPause {
1289 fn drop(&mut self) {
1290 GPU_PAUSED.leave();
1291 }
1292}
1293
1294pub fn enabled() -> bool {
1295 !GPU_LOST.load(std::sync::atomic::Ordering::Relaxed) && !GPU_PAUSED.paused() && backend() != Backend::None
1296}
1297
1298static GPU_LOST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1303
1304pub fn mark_lost(why: &str) {
1306 if !GPU_LOST.swap(true, std::sync::atomic::Ordering::Relaxed) {
1307 tracing::error!("GPU device lost ({why}): the rest of this run stays on the CPU");
1308 }
1309}
1310
1311#[cfg(test)]
1312mod pause_gate_tests {
1313 use super::PauseGate;
1314
1315 #[test]
1318 fn pause_holds_until_the_last_guard() {
1319 let g = PauseGate::new();
1320 assert!(!g.paused());
1321 g.enter();
1322 g.enter();
1323 g.leave();
1324 assert!(g.paused(), "one holder left, the other's pause was lifted");
1325 g.leave();
1326 assert!(!g.paused());
1327 }
1328}
1329
1330pub fn wgpu_active() -> bool {
1344 #[cfg(feature = "gpu")]
1345 {
1346 matches!(backend(), Backend::Wgpu)
1347 }
1348 #[cfg(not(feature = "gpu"))]
1349 {
1350 false
1351 }
1352}
1353
1354pub fn default_device() -> usize {
1361 static D: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1362 *D.get_or_init(|| {
1363 std::env::var("CMF_GPU_ADAPTER")
1364 .ok()
1365 .and_then(|v| v.trim().parse::<usize>().ok())
1366 .unwrap_or(0)
1367 })
1368}
1369
1370thread_local! {
1371 static CUR_DEV: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
1372}
1373
1374pub fn current_device() -> usize {
1376 CUR_DEV.with(|c| c.get()).unwrap_or_else(default_device)
1377}
1378
1379pub fn set_current_device(i: usize) {
1383 CUR_DEV.with(|c| c.set(Some(i)));
1384}
1385
1386pub fn with_device<R>(dev: usize, f: impl FnOnce() -> R) -> R {
1388 let prev = CUR_DEV.with(|c| c.replace(Some(dev)));
1389 let r = f();
1390 CUR_DEV.with(|c| c.set(prev));
1391 r
1392}
1393
1394pub fn device_count() -> usize {
1397 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
1398 {
1399 return crate::gpu_wgpu::adapter_count();
1400 }
1401 #[cfg(not(all(feature = "gpu", not(target_os = "macos"))))]
1402 {
1403 usize::from(backend_available())
1404 }
1405}
1406
1407pub fn vram_budget() -> u64 {
1411 #[cfg(feature = "cuda")]
1412 if backend() == Backend::Cuda {
1413 return crate::gpu_cuda::vram_budget();
1414 }
1415 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
1416 {
1417 return crate::gpu_wgpu::device_vram_budget();
1418 }
1419 #[cfg(all(feature = "gpu", target_os = "macos"))]
1422 if backend() == Backend::Wgpu {
1423 return crate::gpu_wgpu::device_vram_budget();
1424 }
1425 #[cfg(not(all(feature = "gpu", not(target_os = "macos"))))]
1426 {
1427 if backend_available() { u64::MAX } else { 0 }
1428 }
1429}
1430
1431pub fn active_device() -> Option<String> {
1436 match backend() {
1437 #[cfg(feature = "cuda")]
1438 Backend::Cuda => crate::gpu_cuda::device_name().map(|n| format!("{n} / CUDA")),
1439 #[cfg(feature = "gpu")]
1440 Backend::Wgpu => crate::gpu_wgpu::device_label(),
1441 _ => None,
1442 }
1443}
1444
1445pub fn device_bytes_in_use() -> Option<u64> {
1448 match backend() {
1449 #[cfg(feature = "cuda")]
1450 Backend::Cuda => crate::gpu_cuda::device_bytes_in_use(),
1451 #[cfg(feature = "gpu")]
1452 Backend::Wgpu => crate::gpu_wgpu::device_bytes_in_use(),
1453 _ => None,
1454 }
1455}
1456
1457pub fn resident_bytes() -> u64 {
1461 #[cfg(feature = "cuda")]
1462 if backend() == Backend::Cuda {
1463 return crate::gpu_cuda::resident_bytes();
1464 }
1465 #[cfg(feature = "gpu")]
1466 {
1467 if backend() == Backend::Wgpu {
1468 return crate::gpu_wgpu::resident_bytes();
1469 }
1470 }
1471 0
1472}
1473
1474pub fn o1_device_stats(kv_id: u64) -> (usize, u64) {
1478 #[cfg(feature = "gpu")]
1479 {
1480 if backend() == Backend::Wgpu {
1481 return crate::gpu_wgpu::o1_device_stats(kv_id);
1482 }
1483 #[cfg(feature = "cuda")]
1484 if backend() == Backend::Cuda {
1485 return crate::gpu_cuda::o1_device_stats(kv_id);
1486 }
1487 }
1488 let _ = kv_id;
1489 (0, 0)
1490}
1491
1492pub fn upload_bytes() -> u64 {
1496 #[cfg(feature = "gpu")]
1497 {
1498 return crate::gpu_wgpu::UPLOAD_BYTES.load(std::sync::atomic::Ordering::Relaxed);
1499 }
1500 #[cfg(not(feature = "gpu"))]
1501 0
1502}
1503
1504pub fn upload_bandwidth_probe(block: usize, rounds: usize) -> Option<f64> {
1508 #[cfg(feature = "gpu")]
1509 {
1510 return crate::gpu_wgpu::upload_bandwidth_probe(block, rounds);
1511 }
1512 let _ = (block, rounds);
1513 None
1514}
1515
1516#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1528pub enum GraphPhase {
1529 Prefill,
1530 Decode,
1531}
1532
1533pub fn wgpu_graph_on(phase: GraphPhase) -> bool {
1541 match std::env::var("CMF_GPU_WGPU_GRAPH").ok().as_deref() {
1542 Some("0") => false,
1543 Some("prefill") => phase == GraphPhase::Prefill,
1544 Some(_) => true,
1545 None => {
1546 if wgpu_graph_default() {
1547 return true;
1548 }
1549 let _ = phase;
1554 false
1555 }
1556 }
1557}
1558
1559pub fn batched_attend_tiled() -> bool {
1562 #[cfg(feature = "cuda")]
1564 if backend() == Backend::Cuda {
1565 return true;
1566 }
1567 #[cfg(feature = "gpu")]
1568 {
1569 crate::gpu_wgpu::batched_attend_tiled()
1570 }
1571 #[cfg(not(feature = "gpu"))]
1572 {
1573 false
1574 }
1575}
1576
1577pub fn cuda_batch_rows() -> Option<usize> {
1580 #[cfg(feature = "cuda")]
1581 if backend() == Backend::Cuda {
1582 return Some(crate::gpu_cuda::batch_rows());
1583 }
1584 None
1585}
1586
1587#[allow(unused_variables)]
1591pub fn cuda_plane_fits(model: &Arc<CmfModel>, idx: usize) -> bool {
1592 #[cfg(feature = "cuda")]
1593 {
1594 crate::gpu_cuda::h3_plane_fits(model, idx)
1595 }
1596 #[cfg(not(feature = "cuda"))]
1597 {
1598 false
1599 }
1600}
1601
1602#[allow(unused_variables)]
1605pub fn planes_may_grow(on: bool) {
1606 #[cfg(feature = "cuda")]
1607 crate::gpu_cuda::h3_planes_grow(on);
1608}
1609
1610pub fn hy4_capture_begin(layers: usize, dim: usize, ne: usize) -> bool {
1613 #[cfg(feature = "cuda")]
1614 if backend() == Backend::Cuda {
1615 return crate::gpu_cuda::hy4_capture_begin(layers, dim, ne);
1616 }
1617 let _ = (layers, dim, ne);
1618 false
1619}
1620
1621pub fn hy4_capture_take() -> Option<Vec<(Vec<f32>, Vec<f32>)>> {
1623 #[cfg(feature = "cuda")]
1624 if backend() == Backend::Cuda {
1625 return crate::gpu_cuda::hy4_capture_take();
1626 }
1627 None
1628}
1629
1630pub fn metal_active() -> bool {
1632 #[cfg(target_os = "macos")]
1633 {
1634 backend() == Backend::Metal
1635 }
1636 #[cfg(not(target_os = "macos"))]
1637 {
1638 false
1639 }
1640}
1641
1642pub fn cuda_active() -> bool {
1643 #[cfg(feature = "cuda")]
1644 {
1645 backend() == Backend::Cuda
1646 }
1647 #[cfg(not(feature = "cuda"))]
1648 {
1649 false
1650 }
1651}
1652
1653pub fn wgpu_graph_default() -> bool {
1654 #[cfg(feature = "cuda")]
1656 if backend() == Backend::Cuda {
1657 return true;
1658 }
1659 #[cfg(feature = "gpu")]
1660 {
1661 matches!(backend(), Backend::Wgpu)
1667 && (crate::gpu_wgpu::discrete_active()
1668 || (cfg!(target_os = "macos") && crate::gpu_wgpu::adapter_up()))
1669 }
1670 #[cfg(not(feature = "gpu"))]
1671 {
1672 false
1673 }
1674}
1675
1676#[allow(clippy::too_many_arguments, unused_variables)]
1678pub fn q8_matvec_range(
1679 model: &Arc<CmfModel>,
1680 idx: usize,
1681 row0: usize,
1682 row_scale: &[f32],
1683 xs: &[f32],
1684 rows: usize,
1685 cols: usize,
1686 out: &mut [f32],
1687) -> bool {
1688 match backend() {
1689 #[cfg(target_os = "macos")]
1690 Backend::Metal => {
1691 crate::gpu_metal::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
1692 }
1693 #[cfg(feature = "gpu")]
1694 Backend::Wgpu => {
1695 crate::gpu_wgpu::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
1696 }
1697 Backend::None => false,
1698 #[cfg(feature = "cuda")]
1699 Backend::Cuda => false,
1700 }
1701}
1702
1703pub(crate) fn q82_short_rows(
1705 model: &Arc<CmfModel>,
1706 idx: usize,
1707 xs: &[f32],
1708 b: usize,
1709 rows: usize,
1710 cols: usize,
1711 out: &mut [f32],
1712) -> bool {
1713 #[cfg(feature = "gpu")]
1714 if enabled_here() && backend() == Backend::Wgpu {
1715 return crate::gpu_wgpu::q82_short_rows(model, idx, xs, b, rows, cols, out);
1716 }
1717 let _ = (model, idx, xs, b, rows, cols, out);
1718 false
1719}
1720
1721#[allow(clippy::too_many_arguments, unused_variables)]
1724#[allow(clippy::too_many_arguments)]
1728pub fn q8_matmat_2f(
1729 model: &Arc<CmfModel>,
1730 idx: usize,
1731 row_scale: &[f32],
1732 col_field: &[f32],
1733 xs: &[f32],
1734 b: usize,
1735 rows: usize,
1736 cols: usize,
1737 out: &mut [f32],
1738) -> bool {
1739 #[allow(unreachable_patterns)]
1740 match backend() {
1741 #[cfg(feature = "gpu")]
1742 Backend::Wgpu => {
1743 crate::gpu_wgpu::q8_matmat_2f(model, idx, row_scale, col_field, xs, b, rows, cols, out)
1744 }
1745 #[cfg(feature = "cuda")]
1747 Backend::Cuda => crate::gpu_cuda::h3_matmat(model, idx, xs, b, rows, cols, out),
1748 _ => false,
1749 }
1750}
1751
1752pub fn q8_matmat(
1753 model: &Arc<CmfModel>,
1754 idx: usize,
1755 row_scale: &[f32],
1756 pre: &[f32],
1757 b: usize,
1758 rows: usize,
1759 cols: usize,
1760 out: &mut [f32],
1761) -> bool {
1762 match backend() {
1763 #[cfg(target_os = "macos")]
1764 Backend::Metal => {
1765 crate::gpu_metal::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out)
1766 }
1767 #[cfg(feature = "gpu")]
1768 Backend::Wgpu => crate::gpu_wgpu::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out),
1769 Backend::None => false,
1770 #[cfg(feature = "cuda")]
1771 Backend::Cuda => false,
1772 }
1773}
1774
1775#[allow(unused_variables)]
1778pub fn q1_matvec(
1779 model: &Arc<CmfModel>,
1780 idx: usize,
1781 xs: &[f32],
1782 rows: usize,
1783 cols: usize,
1784 out: &mut [f32],
1785) -> bool {
1786 match backend() {
1787 #[cfg(target_os = "macos")]
1788 Backend::Metal => crate::gpu_metal::q1_matvec(model, idx, xs, rows, cols, out),
1789 #[cfg(feature = "gpu")]
1790 Backend::Wgpu => crate::gpu_wgpu::q1_matvec(model, idx, xs, rows, cols, out),
1791 Backend::None => false,
1792 #[cfg(feature = "cuda")]
1793 Backend::Cuda => false,
1794 }
1795}
1796
1797#[allow(unused_variables)]
1801pub fn q1g_matvec(
1802 model: &Arc<CmfModel>,
1803 idx: usize,
1804 xs: &[f32],
1805 rows: usize,
1806 cols: usize,
1807 out: &mut [f32],
1808) -> bool {
1809 match backend() {
1810 #[cfg(target_os = "macos")]
1811 Backend::Metal => crate::gpu_metal::q1g_matvec(model, idx, xs, rows, cols, out),
1812 #[cfg(feature = "gpu")]
1813 Backend::Wgpu => crate::gpu_wgpu::q1g_matvec(model, idx, xs, rows, cols, out),
1814 Backend::None => false,
1815 #[cfg(feature = "cuda")]
1816 Backend::Cuda => false,
1817 }
1818}
1819
1820#[allow(clippy::too_many_arguments)]
1824pub fn attn_dropin(
1825 model: &Arc<CmfModel>,
1826 kv_id: u64,
1827 layer: usize,
1828 normed: &[f32],
1829 wq_idx: usize,
1830 wk_idx: usize,
1831 wv_idx: usize,
1832 wo_idx: usize,
1833 q_norm: Option<&[f32]>,
1834 k_norm: Option<&[f32]>,
1835 late_qk_norm: bool,
1836 invf: &[f32],
1837 nh: usize,
1838 nkv: usize,
1839 hd: usize,
1840 rd: usize,
1841 hidden: usize,
1842 pos: usize,
1843 cap: usize,
1844 gemma: bool,
1845 eps: f32,
1846 cpu_k: &[Vec<f32>],
1847 cpu_v: &[Vec<f32>],
1848 out: &mut [f32],
1849) -> bool {
1850 match backend() {
1851 #[cfg(feature = "gpu")]
1852 Backend::Wgpu => crate::gpu_wgpu::attn_dropin_gpu(
1853 model, kv_id, layer, normed, wq_idx, wk_idx, wv_idx, wo_idx, q_norm, k_norm,
1854 late_qk_norm, invf, nh, nkv, hd, rd, hidden, pos, cap, gemma, eps, cpu_k, cpu_v, out,
1855 ),
1856 #[allow(unused_variables)]
1857 _ => false,
1858 }
1859}
1860
1861#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1865pub enum GraphPrismOp {
1866 None,
1867 Forward,
1868 InverseEmbedding,
1869}
1870
1871pub const GRAPH_KIND_BLR: u8 = 11;
1875
1876pub struct GraphW<'a> {
1880 pub idx: usize,
1881 pub kind: u8,
1882 pub row_scale: &'a [f32],
1883 pub data: &'a [f32],
1884 pub prism: GraphPrismOp,
1885 pub affine: bool,
1886}
1887
1888pub enum GraphAttn<'a> {
1891 Full {
1892 wq: GraphW<'a>,
1893 wk: GraphW<'a>,
1894 wv: GraphW<'a>,
1895 wo: GraphW<'a>,
1896 q_norm: Option<&'a [f32]>,
1897 k_norm: Option<&'a [f32]>,
1898 late_qk_norm: bool,
1900 bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
1902 output_gate: bool,
1905 cpu_k: &'a [Vec<f32>],
1906 cpu_v: &'a [Vec<f32>],
1907 cpu_base: usize,
1911 geom: Option<GraphAttnGeom<'a>>,
1918 head_gate: Option<GraphW<'a>>,
1923 },
1924 Gdn {
1925 qkv: GraphW<'a>,
1926 z: GraphW<'a>,
1927 a: GraphW<'a>,
1928 b: GraphW<'a>,
1929 out: GraphW<'a>,
1930 conv1d: &'a [f32],
1931 a_log: &'a [f32],
1932 dt_bias: &'a [f32],
1933 norm: &'a [f32],
1934 nv: usize,
1935 nk: usize,
1936 dk: usize,
1937 dv: usize,
1938 kk: usize,
1939 cpu_state: &'a [f32],
1944 preview: Option<GdnPreviewW<'a>>,
1947 },
1948 ShortConv {
1955 inp: GraphW<'a>,
1957 out: GraphW<'a>,
1959 taps: &'a [f32],
1962 kernel: usize,
1963 cpu_state: &'a [f32],
1967 },
1968 Kda {
1973 q: GraphW<'a>,
1974 k: GraphW<'a>,
1975 v: GraphW<'a>,
1976 conv_q: &'a [f32],
1979 conv_k: &'a [f32],
1980 conv_v: &'a [f32],
1981 f_a: GraphW<'a>,
1983 f_b: GraphW<'a>,
1984 dt_bias: &'a [f32],
1985 a_log: &'a [f32],
1987 b: GraphW<'a>,
1989 g_a: GraphW<'a>,
1991 g_b: Option<GraphW<'a>>,
1992 o_norm: &'a [f32],
1994 out: GraphW<'a>,
1995 nh: usize,
1996 dk: usize,
1997 dv: usize,
1998 kk: usize,
1999 lower_bound: Option<f32>,
2001 cpu_state: &'a [f32],
2003 },
2004 Mla {
2010 q_a: Option<GraphW<'a>>,
2011 q_a_norm: Option<&'a [f32]>,
2012 q: GraphW<'a>,
2013 kv_a: GraphW<'a>,
2015 kv_a_norm: &'a [f32],
2016 kv_b: GraphW<'a>,
2018 o: GraphW<'a>,
2019 nh: usize,
2020 rope: usize,
2021 nope: usize,
2022 v_dim: usize,
2023 lora: usize,
2024 scale: f32,
2025 no_rope: bool,
2027 cpu_k: &'a [Vec<f32>],
2028 cpu_v: &'a [Vec<f32>],
2029 cpu_base: usize,
2030 dsa: Option<GraphDsa<'a>>,
2033 hy: Option<GraphMlaHy<'a>>,
2038 },
2039}
2040
2041pub struct GraphMlaHy<'a> {
2048 pub gate: GraphW<'a>,
2050 pub sinks: &'a [f32],
2051 pub window: Option<usize>,
2052 pub invf: &'a [f32],
2053 pub indexer: Option<GraphHyIndexer<'a>>,
2054}
2055
2056pub struct GraphHyIndexer<'a> {
2063 pub q: GraphW<'a>,
2065 pub hw: &'a [f32],
2067 pub tk: &'a [f32],
2068 pub tk_norm: &'a [f32],
2069 pub kv: &'a [f32],
2071 pub kg: &'a [f32],
2072 pub k_norm: &'a [f32],
2073 pub ape: &'a [f32],
2075 pub ih: usize,
2076 pub id: usize,
2077 pub ratio: usize,
2078 pub group_topk: usize,
2079 pub kv_b: &'a [f32],
2081}
2082
2083pub struct GraphDsa<'a> {
2089 pub index_q: GraphW<'a>,
2091 pub index_k: GraphW<'a>,
2093 pub pool_gate: GraphW<'a>,
2095 pub index_weights: GraphW<'a>,
2097 pub k_norm: &'a [f32],
2098 pub k_bias: &'a [f32],
2099 pub ape: &'a [f32],
2101 pub kv_b: &'a [f32],
2103 pub ih: usize,
2104 pub id: usize,
2105 pub topk: usize,
2106 pub kpool: usize,
2107}
2108
2109#[derive(Clone, Copy)]
2114pub struct GraphAttnGeom<'a> {
2115 pub nkv: usize,
2117 pub hd: usize,
2121 pub dv: usize,
2123 pub rd: usize,
2125 pub invf: &'a [f32],
2127 pub rope_scale: f32,
2132 pub window: Option<usize>,
2135 pub sink: Option<&'a [f32]>,
2138 pub v_norm: bool,
2141 pub dash: Option<GraphDash<'a>>,
2144 pub vres: Option<(f32, &'a [f32])>,
2148 pub route: Option<GraphBlockRoute<'a>>,
2151}
2152
2153#[derive(Clone, Copy)]
2163pub struct GraphBlockRoute<'a> {
2164 pub q: &'a [f32],
2165 pub k: &'a [f32],
2166 pub q_norm: &'a [f32],
2167 pub k_norm: &'a [f32],
2168 pub block: usize,
2169 pub prefix: usize,
2170 pub local: usize,
2171 pub remote: usize,
2172}
2173
2174impl GraphBlockRoute<'_> {
2175 pub fn dense_range(&self) -> usize {
2177 (self.prefix + self.local + self.remote) * self.block
2178 }
2179}
2180
2181static WGPU_EXTRA_RESERVE: AtomicU64 = AtomicU64::new(0);
2182
2183pub fn wgpu_reserve_at_least(bytes: u64) {
2188 WGPU_EXTRA_RESERVE.fetch_max(bytes, Ordering::Relaxed);
2189}
2190
2191pub(crate) fn wgpu_extra_reserve() -> u64 {
2192 WGPU_EXTRA_RESERVE.load(Ordering::Relaxed)
2193}
2194
2195static WGPU_WEIGHTS_FLOOR: AtomicU64 = AtomicU64::new(0);
2196
2197pub fn wgpu_keep_at_least(bytes: u64) {
2204 WGPU_WEIGHTS_FLOOR.fetch_max(bytes, Ordering::Relaxed);
2205}
2206
2207pub(crate) fn wgpu_weights_floor() -> u64 {
2208 WGPU_WEIGHTS_FLOOR.load(Ordering::Relaxed)
2209}
2210
2211static WGPU_CARD_TOTAL: AtomicU64 = AtomicU64::new(0);
2212
2213pub(crate) fn wgpu_note_card_total(bytes: u64) {
2214 WGPU_CARD_TOTAL.store(bytes, Ordering::Relaxed);
2215}
2216
2217pub fn wgpu_card_total() -> u64 {
2221 WGPU_CARD_TOTAL.load(Ordering::Relaxed)
2222}
2223
2224pub fn wgpu_route_position_bytes(layers: usize, nkv: usize, hd: usize) -> u64 {
2226 #[cfg(feature = "gpu")]
2227 {
2228 crate::gpu_wgpu::broute::position_bytes(layers, nkv, hd)
2229 }
2230 #[cfg(not(feature = "gpu"))]
2231 {
2232 (layers * (2 * nkv + 1) * hd * 2) as u64
2233 }
2234}
2235
2236pub fn wgpu_kv_step(rows: usize) {
2239 #[cfg(feature = "gpu")]
2240 crate::gpu_wgpu::set_kv_step(rows);
2241 #[cfg(not(feature = "gpu"))]
2242 let _ = rows;
2243}
2244
2245static PLAN_EXTRA: std::sync::Mutex<Vec<(u64, u64)>> = std::sync::Mutex::new(Vec::new());
2246
2247pub fn plan_extra_reserve(model: u64, bytes: u64) {
2253 let mut g = PLAN_EXTRA.lock().unwrap();
2254 match g.iter_mut().find(|e| e.0 == model) {
2255 Some(e) => e.1 = e.1.max(bytes),
2256 None => g.push((model, bytes)),
2257 }
2258}
2259
2260pub(crate) fn plan_extra(model: u64) -> u64 {
2261 PLAN_EXTRA.lock().unwrap().iter().find(|e| e.0 == model).map_or(0, |e| e.1)
2262}
2263
2264static PLAN_STREAMED: std::sync::Mutex<Vec<u64>> = std::sync::Mutex::new(Vec::new());
2265
2266pub(crate) fn note_plan_streamed(model: u64) {
2267 let mut g = PLAN_STREAMED.lock().unwrap();
2268 if !g.contains(&model) {
2269 g.push(model);
2270 }
2271}
2272
2273pub fn plan_streamed(model: u64) -> bool {
2277 PLAN_STREAMED.lock().unwrap().contains(&model)
2278}
2279
2280pub fn graph_streams_in(streams: Vec<f32>) {
2285 #[cfg(feature = "cuda")]
2286 crate::gpu_cuda::streams_in(streams);
2287 #[cfg(not(feature = "cuda"))]
2288 let _ = streams;
2289}
2290
2291pub fn graph_streams_want() {
2295 #[cfg(feature = "cuda")]
2296 crate::gpu_cuda::streams_want();
2297}
2298
2299pub fn graph_streams_take() -> Vec<f32> {
2301 #[cfg(feature = "cuda")]
2302 {
2303 crate::gpu_cuda::streams_take()
2304 }
2305 #[cfg(not(feature = "cuda"))]
2306 {
2307 Vec::new()
2308 }
2309}
2310
2311pub fn moe_tap_begin(lo: usize, hi: usize) {
2317 #[cfg(feature = "cuda")]
2318 crate::gpu_cuda::moe_tap_begin(lo, hi);
2319 #[cfg(not(feature = "cuda"))]
2320 let _ = (lo, hi);
2321}
2322
2323pub fn moe_tap_end() -> Vec<(usize, Vec<f32>, Vec<i32>, Vec<f32>)> {
2325 #[cfg(feature = "cuda")]
2326 {
2327 crate::gpu_cuda::moe_tap_end()
2328 }
2329 #[cfg(not(feature = "cuda"))]
2330 {
2331 Vec::new()
2332 }
2333}
2334
2335static ROUTE_ROWS: AtomicU64 = AtomicU64::new(0);
2336
2337pub(crate) fn note_route_rows(rows: usize) {
2341 ROUTE_ROWS.store(rows as u64, Ordering::Relaxed);
2342}
2343
2344pub fn route_rows() -> usize {
2346 ROUTE_ROWS.load(Ordering::Relaxed) as usize
2347}
2348
2349pub fn context_cap(model: &CmfModel) -> usize {
2353 let cap = std::env::var("CMF_MAX_SEQ").ok().and_then(|v| v.parse::<usize>().ok()).unwrap_or(32_768);
2354 model.header.arch.max_position_embeddings.min(cap).max(1)
2355}
2356
2357pub fn block_route_on() -> bool {
2361 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2362 *ON.get_or_init(|| std::env::var("CMF_BLOCK_ROUTE").as_deref() != Ok("0")) && (cuda_active() || wgpu_active())
2364}
2365
2366pub const DASH_CHUNK_MAX: usize = 64;
2370
2371#[derive(Clone, Copy)]
2373pub struct GraphDash<'a> {
2374 pub qk_proj: &'a [f32],
2376 pub q_norm: &'a [f32],
2377 pub k_norm: &'a [f32],
2378 pub head_cls: &'a [f32],
2379 pub idx_scale: f32,
2380 pub floor: f32,
2381 pub sigma: f32,
2382 pub k: usize,
2383 pub block: usize,
2384 pub local_blocks: usize,
2385 pub nblk: usize,
2386 pub cands: &'a [u32],
2388 pub coff: &'a [u32],
2389 pub angles: &'a [f32],
2391}
2392
2393pub fn vres_graph_on() -> bool {
2395 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2396 *ON.get_or_init(|| std::env::var("CMF_VRES_GRAPH").as_deref() != Ok("0"))
2397}
2398
2399#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2403pub enum GraphAct {
2404 Silu,
2405 GeluErf,
2408 GeluTanh,
2411 SwiGluOaiM3,
2415}
2416
2417impl GraphAct {
2418 pub fn code(self) -> u32 {
2419 match self {
2420 Self::Silu => 0,
2421 Self::GeluErf => 1,
2422 Self::GeluTanh => 2,
2423 Self::SwiGluOaiM3 => 3,
2424 }
2425 }
2426}
2427
2428#[derive(Clone, Copy)]
2435pub struct GraphMhc<'a> {
2436 pub attn_w: &'a [f32],
2437 pub attn_b: &'a [f32],
2438 pub ffn_w: &'a [f32],
2439 pub ffn_b: &'a [f32],
2440 pub enter: bool,
2441 pub leave: bool,
2442 pub iters: usize,
2443 pub pre_scale: f32,
2444 pub dsv4: Option<GraphMhcDsv4>,
2450 pub head: Option<GraphMhcHead<'a>>,
2454}
2455
2456pub fn hy_layers(layers: &[GraphLayer]) -> bool {
2460 layers.iter().any(|l| {
2461 l.engram.is_some()
2462 || l.mhc.as_ref().is_some_and(|m| m.dsv4.is_some_and(|d| d.ihc.is_some()))
2464 || matches!(&l.attn, GraphAttn::Mla { hy: Some(_), .. })
2465 || matches!(&l.ffn, GraphFfn::Moe { latent: Some(_), .. } | GraphFfn::Moe { shared_limit: Some(_), .. })
2466 })
2467}
2468
2469#[derive(Clone, Copy)]
2471pub struct GraphMhcHead<'a> {
2472 pub w: &'a [f32],
2473 pub base: &'a [f32],
2474 pub scale: f32,
2475}
2476
2477#[derive(Clone, Copy)]
2481pub struct GraphMhcDsv4 {
2482 pub attn_scale: [f32; 3],
2483 pub ffn_scale: [f32; 3],
2484 pub eps: f32,
2485 pub rms_eps: f32,
2486 pub ihc: Option<f32>,
2491}
2492
2493pub struct GraphLayer<'a> {
2494 pub mhc: Option<GraphMhc<'a>>,
2497 pub input_norm: &'a [f32],
2498 pub attn: GraphAttn<'a>,
2499 pub post_norm: &'a [f32],
2500 pub ffn: GraphFfn<'a>,
2501 pub attn_out_norm: Option<&'a [f32]>,
2504 pub ffn_out_norm: Option<&'a [f32]>,
2505 pub layer_scale: Option<f32>,
2508 pub engram: Option<GraphEngram<'a>>,
2511}
2512
2513pub struct GraphEngram<'a> {
2518 pub mem: &'a [f32],
2521 pub on: &'a [bool],
2522 pub mem_dim: usize,
2523 pub value: GraphW<'a>,
2525 pub value_b: &'a [f32],
2526 pub keys: Vec<GraphW<'a>>,
2528 pub key_b: Vec<&'a [f32]>,
2529 pub norm_key: Vec<&'a [f32]>,
2530 pub norm_query: Vec<&'a [f32]>,
2531 pub gamma: &'a [f32],
2532 pub hc_scales: &'a [f32],
2534 pub eps: f32,
2535}
2536
2537pub struct GraphMoeLatent<'a> {
2540 pub down: GraphW<'a>,
2542 pub up: GraphW<'a>,
2543 pub dim: usize,
2544}
2545
2546pub struct GraphMoeDetachedShared<'a> {
2554 pub gate: GraphW<'a>,
2555 pub up: GraphW<'a>,
2556 pub down: GraphW<'a>,
2557 pub width: usize,
2558}
2559
2560pub enum GraphFfn<'a> {
2565 AttentionOnly,
2568 Dense {
2569 gate: GraphW<'a>,
2570 up: GraphW<'a>,
2571 down: GraphW<'a>,
2572 act: GraphAct,
2575 limit: f32,
2578 hot: Option<GraphMoeDetachedShared<'a>>,
2583 },
2584 Moe {
2585 router: GraphW<'a>,
2587 shared_gate: GraphW<'a>,
2589 experts: Vec<(usize, usize, usize)>,
2593 n_exp: usize,
2595 top_k: usize,
2596 inter: usize,
2597 act: GraphAct,
2602 norm_topk: bool,
2603 q4tp: bool,
2609 gu_q2: bool,
2613 q82: bool,
2618 sigmoid: bool,
2622 sigmoid_denom_eps: f32,
2623 bias: Option<&'a [f32]>,
2626 has_shared: bool,
2630 detached_shared: Option<GraphMoeDetachedShared<'a>>,
2634 shared_gated: bool,
2639 route_scale: f32,
2642 limit: f32,
2646 shared_limit: Option<f32>,
2649 latent: Option<GraphMoeLatent<'a>>,
2652 },
2653}
2654
2655#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2658pub enum TokenGraphOutcome {
2659 Declined,
2661 Completed,
2663 Failed,
2665}
2666
2667#[allow(clippy::too_many_arguments)]
2672pub fn forward_token_graph(
2673 model: &Arc<CmfModel>,
2674 kv_id: u64,
2675 layers: &[GraphLayer],
2676 o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
2679 o1_epoch: u64,
2680 invf: &[f32],
2681 h: &mut [f32],
2682 nh: usize,
2683 nkv: usize,
2684 hd: usize,
2685 attn_scale: f32,
2686 rd: usize,
2687 hidden: usize,
2688 inter: usize,
2689 position: usize,
2690 cap: usize,
2691 gemma: bool,
2692 eps: f32,
2693 lm_head: Option<(&GraphW, usize)>,
2694 final_norm: &[f32],
2695 logits: &mut Vec<f32>,
2696 loop_norm_at: &[usize],
2697 steps: usize,
2698 embed: Option<(&GraphW, usize, f32)>,
2699 ids_out: Option<&mut Vec<u32>>,
2700 layers_run: Option<&mut usize>,
2703 layer_base: usize,
2707 hidden_too: bool,
2709) -> TokenGraphOutcome {
2710 match backend() {
2711 #[cfg(feature = "gpu")]
2712 Backend::Wgpu => crate::gpu_wgpu::forward_token_graph(
2713 model,
2714 kv_id,
2715 layers,
2716 o1,
2717 o1_epoch,
2718 invf,
2719 h,
2720 nh,
2721 nkv,
2722 hd,
2723 attn_scale,
2724 rd,
2725 hidden,
2726 inter,
2727 position,
2728 cap,
2729 gemma,
2730 eps,
2731 lm_head,
2732 final_norm,
2733 logits,
2734 loop_norm_at,
2735 steps,
2736 embed,
2737 ids_out,
2738 layers_run,
2739 layer_base,
2740 hidden_too,
2741 ),
2742 #[cfg(feature = "cuda")]
2743 Backend::Cuda => crate::gpu_cuda::forward_token_graph(
2744 model,
2745 kv_id,
2746 layers,
2747 o1,
2748 o1_epoch,
2749 invf,
2750 h,
2751 nh,
2752 nkv,
2753 hd,
2754 attn_scale,
2755 rd,
2756 hidden,
2757 position,
2758 cap,
2759 gemma,
2760 eps,
2761 lm_head,
2762 final_norm,
2763 logits,
2764 loop_norm_at,
2765 steps,
2766 layers_run,
2767 layer_base,
2768 hidden_too,
2769 ),
2770 #[allow(unused_variables)]
2771 _ => {
2772 let _ = (
2773 attn_scale,
2774 lm_head,
2775 final_norm,
2776 logits,
2777 loop_norm_at,
2778 layers_run,
2779 layer_base,
2780 hidden_too,
2781 );
2782 TokenGraphOutcome::Declined
2783 }
2784 }
2785}
2786
2787#[allow(clippy::too_many_arguments)]
2789pub fn dory_forward(
2790 id: u64,
2791 model: Option<&std::sync::Arc<cortiq_core::CmfModel>>,
2792 m: &crate::dory::Dory,
2793 ids: &[u32],
2794 pos: usize,
2795 loops: usize,
2796 want: crate::dory::Want,
2797 logits: &mut Vec<f32>,
2798) -> bool {
2799 #[cfg(target_os = "macos")]
2800 if backend() == Backend::Metal {
2801 return model.is_some_and(|md| crate::gpu_metal::dory::forward(id, md, m, ids, pos, loops, want, logits));
2802 }
2803 #[cfg(feature = "cuda")]
2804 if backend() == Backend::Cuda {
2805 return crate::gpu_cuda::dory_forward(id, m, ids, pos, loops, want, logits);
2806 }
2807 #[cfg(feature = "gpu")]
2808 if backend() == Backend::Wgpu {
2809 return crate::gpu_wgpu::dory::forward(id, m, ids, pos, loops, want, logits);
2810 }
2811 let _ = (id, model, m, ids, pos, loops, want, logits);
2812 false
2813}
2814
2815#[allow(clippy::too_many_arguments)]
2819pub fn inkling_forward(
2820 id: u64,
2821 g: &crate::inkling::Globals,
2822 layers: &[crate::inkling::Layer],
2823 cfg: &crate::inkling::Cfg,
2824 ids: &[u32],
2825 pos: usize,
2826 want: bool,
2827 all: bool,
2828 logits: &mut Vec<f32>,
2829) -> bool {
2830 #[cfg(target_os = "macos")]
2831 if backend() == Backend::Metal {
2832 return crate::gpu_metal::inkling::forward(id, g, layers, cfg, ids, pos, want, all, logits);
2833 }
2834 #[cfg(feature = "cuda")]
2835 if backend() == Backend::Cuda {
2836 return crate::gpu_cuda::inkling_forward(id, g, layers, cfg, ids, pos, want, all, logits);
2837 }
2838 #[cfg(feature = "gpu")]
2839 if backend() == Backend::Wgpu {
2840 return crate::gpu_wgpu::inkling::forward(id, g, layers, cfg, ids, pos, want, all, logits);
2841 }
2842 let _ = (id, g, layers, cfg, ids, pos, want, all, logits);
2843 false
2844}
2845
2846pub fn inkling_reset(id: u64) {
2848 #[cfg(target_os = "macos")]
2849 if backend() == Backend::Metal {
2850 crate::gpu_metal::inkling::reset(id);
2851 return;
2852 }
2853 #[cfg(feature = "cuda")]
2854 if backend() == Backend::Cuda {
2855 crate::gpu_cuda::inkling_reset(id);
2856 }
2857 #[cfg(feature = "gpu")]
2858 if backend() == Backend::Wgpu {
2859 crate::gpu_wgpu::inkling::reset(id);
2860 }
2861 let _ = id;
2862}
2863
2864pub fn inkling_draft(id: u64, g: &crate::inkling::Globals, cfg: &crate::inkling::Cfg, anchor: u32, pos: usize, k: usize) -> Option<Vec<u32>> {
2867 #[cfg(feature = "cuda")]
2868 if backend() == Backend::Cuda {
2869 return crate::gpu_cuda::inkling_draft(id, g, cfg, anchor, pos, k);
2870 }
2871 let _ = (id, g, cfg, anchor, pos, k);
2872 None
2873}
2874
2875pub fn inkling_ring_snap(id: u64) -> bool {
2877 #[cfg(feature = "cuda")]
2878 if backend() == Backend::Cuda {
2879 return crate::gpu_cuda::inkling_ring_snap(id);
2880 }
2881 let _ = id;
2882 false
2883}
2884
2885pub fn inkling_ring_back(id: u64, r: usize) -> bool {
2887 #[cfg(feature = "cuda")]
2888 if backend() == Backend::Cuda {
2889 return crate::gpu_cuda::inkling_ring_back(id, r);
2890 }
2891 let _ = (id, r);
2892 false
2893}
2894
2895#[allow(clippy::too_many_arguments)]
2898pub fn inkling_verify(id: u64, g: &crate::inkling::Globals, layers: &[crate::inkling::Layer], cfg: &crate::inkling::Cfg, ids: &[u32], pos: usize, picks: &mut Vec<u32>) -> bool {
2899 #[cfg(feature = "cuda")]
2900 if backend() == Backend::Cuda {
2901 return crate::gpu_cuda::inkling_verify(id, g, layers, cfg, ids, pos, picks);
2902 }
2903 let _ = (id, g, layers, cfg, ids, pos, picks);
2904 false
2905}
2906
2907pub fn inkling_row_logits(id: u64, r: usize, vocab: usize, out: &mut Vec<f32>) -> bool {
2909 #[cfg(feature = "cuda")]
2910 if backend() == Backend::Cuda {
2911 return crate::gpu_cuda::inkling_row_logits(id, r, vocab, out);
2912 }
2913 let _ = (id, r, vocab, out);
2914 false
2915}
2916
2917pub fn dory_reset(id: u64) {
2919 #[cfg(target_os = "macos")]
2920 if backend() == Backend::Metal {
2921 crate::gpu_metal::dory::reset(id);
2922 return;
2923 }
2924 #[cfg(feature = "cuda")]
2925 if backend() == Backend::Cuda {
2926 crate::gpu_cuda::dory_reset(id);
2927 return;
2928 }
2929 #[cfg(feature = "gpu")]
2930 if backend() == Backend::Wgpu {
2931 crate::gpu_wgpu::dory::reset(id);
2932 }
2933 let _ = id;
2934}
2935
2936pub fn dory_sealed(id: u64) -> bool {
2939 #[cfg(target_os = "macos")]
2940 if backend() == Backend::Metal {
2941 return crate::gpu_metal::dory::sealed(id);
2942 }
2943 #[cfg(feature = "cuda")]
2944 if backend() == Backend::Cuda {
2945 return crate::gpu_cuda::dory_sealed(id);
2946 }
2947 #[cfg(feature = "gpu")]
2948 if backend() == Backend::Wgpu {
2949 return crate::gpu_wgpu::dory::sealed(id);
2950 }
2951 let _ = id;
2952 false
2953}
2954
2955pub fn dory_kv_bytes(id: u64) -> Option<u64> {
2956 #[cfg(target_os = "macos")]
2957 if backend() == Backend::Metal {
2958 return crate::gpu_metal::dory::kv_bytes(id);
2959 }
2960 #[cfg(feature = "cuda")]
2961 if backend() == Backend::Cuda {
2962 return crate::gpu_cuda::dory_kv_bytes(id);
2963 }
2964 #[cfg(feature = "gpu")]
2965 if backend() == Backend::Wgpu {
2966 return crate::gpu_wgpu::dory::kv_bytes(id);
2967 }
2968 let _ = id;
2969 None
2970}
2971
2972pub fn embryo_wide_ready(q8: bool) -> bool {
2974 #[cfg(feature = "cuda")]
2975 if backend() == Backend::Cuda {
2976 return crate::gpu_cuda::embryo_wide_ready(q8);
2977 }
2978 #[cfg(feature = "gpu")]
2979 if backend() == Backend::Wgpu {
2980 return crate::gpu_wgpu::embryo_wide_ready(q8);
2981 }
2982 let _ = q8;
2983 false
2984}
2985
2986pub fn forward_embryo_graph(
2991 model: &Arc<EmbryoGraphModel>,
2992 kv_id: u64,
2993 hidden: &[f32],
2994 position: usize,
2995 logits: &mut Vec<f32>,
2996) -> bool {
2997 #[cfg(feature = "cuda")]
2998 if backend() == Backend::Cuda {
2999 return crate::gpu_cuda::forward_embryo_graph(model, kv_id, hidden, position, logits);
3000 }
3001 #[cfg(feature = "gpu")]
3002 if backend() == Backend::Wgpu {
3003 return crate::gpu_wgpu::forward_embryo_graph(model, kv_id, hidden, position, logits);
3004 }
3005 let _ = (model, kv_id, hidden, position, logits);
3006 false
3007}
3008
3009#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3013pub enum BatchGraphOutcome {
3014 Declined,
3017 Completed,
3019 Failed,
3023}
3024
3025pub struct SpecTail<'a> {
3026 pub lm: GraphW<'a>,
3027 pub lm_rows: usize,
3028 pub final_norm: &'a [f32],
3029 pub logits_out: &'a mut Vec<f32>,
3030 pub pick: Option<(PreviewPick<'a>, &'a mut Vec<(u32, f32)>)>,
3034}
3035
3036pub struct PreviewPick<'a> {
3042 pub vocab: usize,
3043 pub counts: &'a [u32],
3044 pub stop: &'a [u32],
3045 pub forbid: &'a [u32],
3046 pub think_end: Option<u32>,
3047 pub close_open: bool,
3048 pub len0: usize,
3049 pub frequency: f32,
3050 pub presence: f32,
3051 pub repetition: f32,
3052 pub length_ramp: (f32, f32, f32),
3054 pub think_ramp: (f32, f32, f32),
3055}
3056
3057#[allow(clippy::too_many_arguments)]
3061pub fn forward_batch_graph(
3062 model: &Arc<CmfModel>,
3063 kv_id: u64,
3064 layers: &[GraphLayer],
3065 invf: &[f32],
3066 h: &mut [f32],
3067 nh: usize,
3068 nkv: usize,
3069 hd: usize,
3070 rd: usize,
3071 hidden: usize,
3072 inter: usize,
3073 positions: &[usize],
3074 cap: usize,
3075 gemma: bool,
3076 eps: f32,
3077 attn_scale: f32,
3078 k: usize,
3079 o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
3082 o1_epoch: u64,
3083 spec: Option<SpecTail<'_>>,
3084 layers_run: Option<&mut usize>,
3090) -> BatchGraphOutcome {
3091 forward_batch_graph_at(model, kv_id, 0, layers, invf, h, nh, nkv, hd, rd, hidden, inter, positions, cap, gemma, eps, attn_scale, k, o1, o1_epoch, spec, layers_run)
3092}
3093
3094thread_local! {
3095 static MIMO_ATTN_SCRATCH: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
3096}
3097
3098pub(crate) fn mimo_attention_scratch_enabled() -> bool {
3099 MIMO_ATTN_SCRATCH.with(std::cell::Cell::get)
3100}
3101
3102#[doc(hidden)]
3105pub fn mimo_attention_scratch_scope<R>(enabled: bool, f: impl FnOnce() -> R) -> R {
3106 struct Restore(bool);
3107 impl Drop for Restore {
3108 fn drop(&mut self) {
3109 MIMO_ATTN_SCRATCH.with(|v| v.set(self.0));
3110 }
3111 }
3112 let _restore = Restore(MIMO_ATTN_SCRATCH.with(|v| v.replace(enabled)));
3113 f()
3114}
3115
3116pub fn g4_batch_on() -> bool {
3119 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3120 *ON.get_or_init(|| std::env::var("CMF_G4_BATCH").as_deref() != Ok("0"))
3121}
3122
3123pub(crate) fn moe_q82_graph_on() -> bool {
3126 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3127 *ON.get_or_init(|| std::env::var("CMF_MOE_Q82").as_deref() != Ok("0"))
3128}
3129
3130thread_local! {
3131 static MIMO_Q8_SHORT: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
3132}
3133
3134pub(crate) fn mimo_q8_short_enabled() -> bool {
3135 MIMO_Q8_SHORT.with(std::cell::Cell::get)
3136}
3137
3138#[doc(hidden)]
3140pub fn mimo_q8_short_scope<R>(enabled: bool, f: impl FnOnce() -> R) -> R {
3141 struct Restore(bool);
3142 impl Drop for Restore {
3143 fn drop(&mut self) {
3144 MIMO_Q8_SHORT.with(|v| v.set(self.0));
3145 }
3146 }
3147 let _restore = Restore(MIMO_Q8_SHORT.with(|v| v.replace(enabled)));
3148 f()
3149}
3150
3151#[allow(clippy::too_many_arguments)]
3153pub fn forward_batch_graph_at(
3154 model: &Arc<CmfModel>,
3155 kv_id: u64,
3156 layer_base: usize,
3157 layers: &[GraphLayer],
3158 invf: &[f32],
3159 h: &mut [f32],
3160 nh: usize,
3161 nkv: usize,
3162 hd: usize,
3163 rd: usize,
3164 hidden: usize,
3165 inter: usize,
3166 positions: &[usize],
3167 cap: usize,
3168 gemma: bool,
3169 eps: f32,
3170 attn_scale: f32,
3171 k: usize,
3172 o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
3175 o1_epoch: u64,
3176 spec: Option<SpecTail<'_>>,
3177 layers_run: Option<&mut usize>,
3183) -> BatchGraphOutcome {
3184 match backend() {
3185 #[cfg(feature = "gpu")]
3186 Backend::Wgpu => crate::gpu_wgpu::forward_batch_graph_at(
3187 model, kv_id, layer_base, layers, invf, h, nh, nkv, hd, rd, hidden, inter, positions,
3188 cap, gemma, eps, attn_scale, k, o1, o1_epoch, spec, layers_run,
3189 ),
3190 #[cfg(feature = "cuda")]
3191 Backend::Cuda => crate::gpu_cuda::forward_batch_graph_at(
3192 model, kv_id, layer_base, layers, invf, h, nh, nkv, hd, rd, hidden, positions, cap,
3193 gemma, eps, attn_scale, k, o1, o1_epoch, spec, layers_run,
3194 ),
3195 #[allow(unreachable_patterns)]
3196 _ => {
3197 let _ = (o1, o1_epoch, spec, layers_run);
3198 BatchGraphOutcome::Declined
3199 }
3200 }
3201}
3202
3203pub fn rows_matvec(
3206 model: &Arc<CmfModel>,
3207 gw: &GraphW,
3208 rows: usize,
3209 cols: usize,
3210 x: &[f32],
3211 n: usize,
3212 y: &mut [f32],
3213) -> bool {
3214 #[cfg(feature = "cuda")]
3215 if backend() == Backend::Cuda {
3216 return crate::gpu_cuda::rows_matvec(model, gw, rows, cols, x, n, y);
3217 }
3218 let _ = (model, gw, rows, cols, x, n, y);
3219 false
3220}
3221
3222pub fn gdn_spec_restore(kv_id: u64, slot: usize, base_pos: usize, expected_layers: usize) -> bool {
3227 #[cfg(feature = "cuda")]
3228 if backend() == Backend::Cuda {
3229 return crate::gpu_cuda::gdn_spec_restore(kv_id, slot, base_pos, expected_layers);
3230 }
3231 #[cfg(feature = "gpu")]
3232 if backend() == Backend::Wgpu {
3233 return crate::gpu_wgpu::gdn_spec_restore(kv_id, slot, base_pos, expected_layers);
3234 }
3235 #[allow(unreachable_code)]
3236 {
3237 let _ = (kv_id, slot, base_pos, expected_layers);
3238 false
3239 }
3240}
3241
3242pub fn gdn_snapshot(kv_id: u64, pos: usize) -> bool {
3246 #[cfg(feature = "cuda")]
3247 if backend() == Backend::Cuda {
3248 return crate::gpu_cuda::gdn_snapshot(kv_id, pos);
3249 }
3250 let _ = (kv_id, pos);
3251 false
3252}
3253
3254pub fn gdn_snapshot_restore(kv_id: u64, pos: usize) -> bool {
3257 #[cfg(feature = "cuda")]
3258 if backend() == Backend::Cuda {
3259 return crate::gpu_cuda::gdn_snapshot_restore(kv_id, pos);
3260 }
3261 let _ = (kv_id, pos);
3262 false
3263}
3264
3265pub fn graph_kv_set_stored(kv_id: u64, layer: usize, stored: usize) -> bool {
3271 #[cfg(feature = "cuda")]
3272 if backend() == Backend::Cuda {
3273 return crate::gpu_cuda::kv_set_stored(kv_id, layer, stored);
3274 }
3275 #[cfg(feature = "gpu")]
3276 if backend() == Backend::Wgpu {
3277 return crate::gpu_wgpu::kv_mirror_set_stored(kv_id, layer, stored);
3278 }
3279 #[cfg(target_os = "macos")]
3280 if backend() == Backend::Metal {
3281 crate::gpu_metal::kv_mirror_set_stored(kv_id, layer, stored);
3282 return true;
3283 }
3284 false
3285}
3286
3287pub fn graph_kv_stored(_kv_id: u64, _layer: usize) -> Option<usize> {
3291 #[cfg(feature = "cuda")]
3292 if backend() == Backend::Cuda {
3293 return crate::gpu_cuda::kv_stored(_kv_id, _layer);
3294 }
3295 #[cfg(feature = "gpu")]
3296 if backend() == Backend::Wgpu {
3297 return crate::gpu_wgpu::kv_mirror_stored(_kv_id, _layer);
3298 }
3299 None
3300}
3301
3302pub fn graph_state_resident(_kv_id: u64, _layer: usize) -> bool {
3305 #[cfg(feature = "cuda")]
3306 if backend() == Backend::Cuda {
3307 return crate::gpu_cuda::state_resident(_kv_id, _layer);
3308 }
3309 #[cfg(feature = "gpu")]
3310 if backend() == Backend::Wgpu {
3311 return crate::gpu_wgpu::graph_state_resident(_kv_id, _layer);
3312 }
3313 false
3314}
3315
3316pub fn o1_qcap_begin(_layers: &[usize]) -> bool {
3320 #[cfg(feature = "gpu")]
3321 if backend() == Backend::Wgpu {
3322 crate::gpu_wgpu::o1_qcap_begin(_layers);
3323 return true;
3324 }
3325 #[cfg(feature = "cuda")]
3326 if backend() == Backend::Cuda {
3327 return crate::gpu_cuda::o1_qcap_begin(_layers);
3328 }
3329 false
3330}
3331
3332pub fn o1_qcap_stride(_stride: usize) -> bool {
3336 #[cfg(feature = "gpu")]
3337 if backend() == Backend::Wgpu {
3338 return crate::gpu_wgpu::o1_qcap_stride(_stride);
3339 }
3340 #[cfg(feature = "cuda")]
3341 if backend() == Backend::Cuda {
3342 return crate::gpu_cuda::o1_qcap_stride(_stride);
3343 }
3344 false
3345}
3346
3347pub fn o1_qcap_drain() -> Option<Vec<(usize, Vec<f32>)>> {
3349 #[cfg(feature = "gpu")]
3350 if backend() == Backend::Wgpu {
3351 return crate::gpu_wgpu::o1_qcap_drain();
3352 }
3353 #[cfg(feature = "cuda")]
3354 if backend() == Backend::Cuda {
3355 return crate::gpu_cuda::o1_qcap_drain();
3356 }
3357 None
3358}
3359
3360pub fn o1_spec_commit(_kv_id: u64, _pos0: usize, _rows: usize) -> bool {
3362 #[cfg(feature = "cuda")]
3363 if backend() == Backend::Cuda {
3364 return crate::gpu_cuda::o1_spec_commit(_kv_id, _pos0, _rows);
3365 }
3366 #[cfg(feature = "gpu")]
3367 if backend() == Backend::Wgpu {
3368 return crate::gpu_wgpu::o1_spec_commit(_kv_id, _pos0, _rows);
3369 }
3370 #[cfg(target_os = "macos")]
3371 if backend() == Backend::Metal {
3372 return crate::gpu_metal::o1c::spec_commit(_kv_id, _rows);
3373 }
3374 false
3375}
3376
3377pub fn exit_past_driver_teardown(code: i32) {
3389 #[cfg(all(feature = "cuda", unix))]
3390 {
3391 if std::env::var("CMF_EXIT_HANDLERS").as_deref() != Ok("1") && crate::gpu_cuda::ctx_built() && crate::gpu_wgpu::any_ctx_built() {
3392 use std::io::Write;
3393 let _ = std::io::stdout().flush();
3394 let _ = std::io::stderr().flush();
3395 unsafe { libc::_exit(code) }
3398 }
3399 }
3400 let _ = code;
3401}
3402
3403pub fn o1_far_sums_on() -> bool {
3404 #[cfg(feature = "cuda")]
3405 if backend() == Backend::Cuda {
3406 return std::env::var("CMF_O1_FAR_GPU").as_deref() != Ok("0") && crate::gpu_cuda::ctx_ready();
3407 }
3408 false
3409}
3410
3411#[allow(clippy::too_many_arguments)]
3418pub fn o1_far_sums(nkv: usize, hpk: usize, hd: usize, m: usize, scale: f32, qt: &[f32], idx: &[u32], ks: &[&[f32]], vs: &[&[f32]]) -> Option<(Vec<f32>, Vec<f32>)> {
3419 #[cfg(feature = "cuda")]
3420 if backend() == Backend::Cuda {
3421 return crate::gpu_cuda::o1_far_sums(nkv, hpk, hd, m, scale, qt, idx, ks, vs);
3422 }
3423 let _ = (nkv, hpk, hd, m, scale, qt, idx, ks, vs);
3424 None
3425}
3426
3427pub fn o1_acap_begin(_stride: usize) {
3431 #[cfg(feature = "cuda")]
3432 if backend() == Backend::Cuda {
3433 crate::gpu_cuda::o1_acap_begin(_stride);
3434 }
3435 #[cfg(feature = "gpu")]
3436 if backend() == Backend::Wgpu {
3437 crate::gpu_wgpu::o1_acap_begin(_stride);
3438 }
3439 #[cfg(target_os = "macos")]
3440 if backend() == Backend::Metal {
3441 crate::gpu_metal::o1c::acap_begin();
3442 }
3443}
3444
3445pub fn o1_acap_end() {
3446 #[cfg(feature = "cuda")]
3447 if backend() == Backend::Cuda {
3448 crate::gpu_cuda::o1_acap_end();
3449 }
3450 #[cfg(feature = "gpu")]
3451 if backend() == Backend::Wgpu {
3452 crate::gpu_wgpu::o1_acap_end();
3453 }
3454 #[cfg(target_os = "macos")]
3455 if backend() == Backend::Metal {
3456 crate::gpu_metal::o1c::cap_end();
3457 }
3458}
3459
3460pub fn o1_acap_pending() -> usize {
3463 #[cfg(feature = "gpu")]
3464 if backend() == Backend::Wgpu {
3465 return crate::gpu_wgpu::o1_acap_pending();
3466 }
3467 0
3468}
3469
3470pub fn o1_acap_take_first(_n: usize) -> Option<Vec<(usize, Vec<f32>, Vec<f32>, Vec<f32>)>> {
3473 #[cfg(feature = "gpu")]
3474 if backend() == Backend::Wgpu {
3475 return crate::gpu_wgpu::o1_acap_take_first(_n);
3476 }
3477 o1_acap_take()
3478}
3479
3480pub fn o1_acap_take() -> Option<Vec<(usize, Vec<f32>, Vec<f32>, Vec<f32>)>> {
3482 #[cfg(feature = "cuda")]
3483 if backend() == Backend::Cuda {
3484 return crate::gpu_cuda::o1_acap_take();
3485 }
3486 #[cfg(feature = "gpu")]
3487 if backend() == Backend::Wgpu {
3488 return crate::gpu_wgpu::o1_acap_take();
3489 }
3490 #[cfg(target_os = "macos")]
3491 if backend() == Backend::Metal {
3492 return Some(crate::gpu_metal::o1c::cap_take());
3493 }
3494 None
3495}
3496
3497pub fn o1_qcap_take() -> Option<Vec<(usize, Vec<f32>)>> {
3500 #[cfg(feature = "gpu")]
3501 if backend() == Backend::Wgpu {
3502 return crate::gpu_wgpu::o1_qcap_take();
3503 }
3504 #[cfg(feature = "cuda")]
3505 if backend() == Backend::Cuda {
3506 return crate::gpu_cuda::o1_qcap_take();
3507 }
3508 None
3509}
3510
3511pub fn graph_gdn_state_read(_kv_id: u64, _layer: usize) -> Option<Vec<f32>> {
3514 #[cfg(feature = "cuda")]
3515 if backend() == Backend::Cuda {
3516 return crate::gpu_cuda::gdn_state_read(_kv_id, _layer);
3517 }
3518 #[cfg(feature = "gpu")]
3519 if backend() == Backend::Wgpu {
3520 return crate::gpu_wgpu::graph_gdn_state_read(_kv_id, _layer);
3521 }
3522 None
3523}
3524
3525pub fn graph_kv_read_rows(
3529 _kv_id: u64,
3530 _reqs: &[(usize, usize, usize)],
3531 _nkv: usize,
3532 _hd: usize,
3533) -> Option<Vec<(Vec<f32>, Vec<f32>)>> {
3534 #[cfg(feature = "cuda")]
3535 if backend() == Backend::Cuda {
3536 return crate::gpu_cuda::kv_read_rows(_kv_id, _reqs, _nkv, _hd);
3537 }
3538 #[cfg(feature = "gpu")]
3539 if backend() == Backend::Wgpu {
3540 return crate::gpu_wgpu::kv_mirror_read_rows(_kv_id, _reqs, _nkv, _hd);
3541 }
3542 None
3543}
3544
3545pub fn graph_kv_pull_host(
3551 _kv_id: u64,
3552 _layer: usize,
3553 _from: usize,
3554 _to: usize,
3555 _nkv: usize,
3556 _hd: usize,
3557) -> Option<(Vec<f32>, Vec<f32>, usize)> {
3558 #[cfg(feature = "cuda")]
3559 if backend() == Backend::Cuda {
3560 return crate::gpu_cuda::kv_pull_host(_kv_id, _layer, _from, _to, _nkv, _hd);
3561 }
3562 #[cfg(feature = "gpu")]
3563 if backend() == Backend::Wgpu {
3564 return crate::gpu_wgpu::kv_mirror_pull_host(_kv_id, _layer, _from, _to, _nkv, _hd);
3565 }
3566 None
3567}
3568
3569pub fn set_batch_defer(_on: bool) {
3572 #[cfg(feature = "cuda")]
3573 if backend() == Backend::Cuda {
3574 crate::gpu_cuda::set_batch_defer(_on);
3575 }
3576 #[cfg(feature = "gpu")]
3577 if backend() == Backend::Wgpu {
3578 crate::gpu_wgpu::set_batch_defer(_on);
3579 }
3580}
3581
3582pub fn set_batch_kv_hint(_rows: usize) {
3585 #[cfg(feature = "cuda")]
3586 if backend() == Backend::Cuda {
3587 crate::gpu_cuda::set_batch_kv_hint(_rows);
3588 }
3589 #[cfg(feature = "gpu")]
3590 if backend() == Backend::Wgpu {
3591 crate::gpu_wgpu::set_batch_kv_hint(_rows);
3592 }
3593}
3594
3595thread_local! {
3596 static BATCH_LOOP: std::cell::RefCell<Option<(Vec<usize>, std::sync::Arc<Vec<f32>>)>> = const { std::cell::RefCell::new(None) };
3598}
3599
3600pub fn set_batch_loop_norm(v: Option<(Vec<usize>, Vec<f32>)>) {
3605 BATCH_LOOP.with(|b| *b.borrow_mut() = v.map(|(at, w)| (at, std::sync::Arc::new(w))));
3606}
3607
3608pub(crate) fn batch_loop_norm() -> Option<(Vec<usize>, std::sync::Arc<Vec<f32>>)> {
3610 BATCH_LOOP.with(|b| b.borrow().clone()).filter(|(at, _)| !at.is_empty())
3611}
3612
3613pub fn graph_kv16_note(_kv_id: u64, _allowed: bool) {
3616 #[cfg(feature = "gpu")]
3617 if backend() == Backend::Wgpu {
3618 crate::gpu_wgpu::kv16::note(_kv_id, _allowed);
3619 }
3620}
3621
3622pub fn graph_kv_reset(_kv_id: u64) {
3624 #[cfg(feature = "cuda")]
3625 if backend() == Backend::Cuda {
3626 crate::gpu_cuda::kv_reset(_kv_id);
3627 crate::gpu_cuda::embryo_graph_reset(_kv_id);
3628 }
3629 #[cfg(feature = "gpu")]
3630 if backend() == Backend::Wgpu {
3631 crate::gpu_wgpu::kv_mirror_reset(_kv_id);
3632 crate::gpu_wgpu::embryo_graph_reset(_kv_id);
3633 }
3634}
3635
3636pub fn q1t_matvec(
3640 model: &Arc<CmfModel>,
3641 idx: usize,
3642 xs: &[f32],
3643 rows: usize,
3644 cols: usize,
3645 out: &mut [f32],
3646) -> bool {
3647 match backend() {
3648 #[cfg(target_os = "macos")]
3649 Backend::Metal => {
3650 if metal_q1t_enabled() {
3651 crate::gpu_metal::q1t_matvec(model, idx, xs, rows, cols, out)
3652 } else {
3653 false
3654 }
3655 }
3656 #[cfg(feature = "gpu")]
3657 Backend::Wgpu => crate::gpu_wgpu::q1t_matvec(model, idx, xs, rows, cols, out),
3658 Backend::None => false,
3659 #[cfg(feature = "cuda")]
3660 Backend::Cuda => false,
3661 }
3662}
3663
3664#[allow(unused_variables)]
3667pub fn q4b_matvec(
3668 model: &Arc<CmfModel>,
3669 idx: usize,
3670 xs: &[f32],
3671 rows: usize,
3672 cols: usize,
3673 out: &mut [f32],
3674) -> bool {
3675 match backend() {
3676 #[cfg(target_os = "macos")]
3677 Backend::Metal => false,
3678 #[cfg(feature = "gpu")]
3679 Backend::Wgpu => crate::gpu_wgpu::q4b_matvec(model, idx, xs, rows, cols, out),
3680 Backend::None => false,
3681 #[cfg(feature = "cuda")]
3682 Backend::Cuda => false,
3683 }
3684}
3685
3686pub fn q1t_matmat(
3689 model: &Arc<CmfModel>,
3690 idx: usize,
3691 xs: &[f32],
3692 b: usize,
3693 rows: usize,
3694 cols: usize,
3695 out: &mut [f32],
3696) -> bool {
3697 match backend() {
3698 #[cfg(target_os = "macos")]
3699 Backend::Metal => crate::gpu_metal::q1t_matmat(model, idx, xs, b, rows, cols, out),
3703 #[cfg(feature = "gpu")]
3704 Backend::Wgpu => crate::gpu_wgpu::q1t_matmat(model, idx, xs, b, rows, cols, out),
3705 Backend::None => false,
3706 #[cfg(feature = "cuda")]
3707 Backend::Cuda => false,
3708 }
3709}
3710
3711#[cfg(target_os = "macos")]
3715pub(crate) fn metal_q1t_enabled() -> bool {
3716 std::env::var("CMF_METAL_Q1T")
3717 .map(|v| v != "0" && !v.eq_ignore_ascii_case("off"))
3718 .unwrap_or(true)
3719}
3720
3721pub fn q1_matmat(
3723 model: &Arc<CmfModel>,
3724 idx: usize,
3725 xs: &[f32],
3726 b: usize,
3727 rows: usize,
3728 cols: usize,
3729 out: &mut [f32],
3730) -> bool {
3731 match backend() {
3732 #[cfg(feature = "gpu")]
3733 Backend::Wgpu => crate::gpu_wgpu::q1_matmat(model, idx, xs, b, rows, cols, out),
3734 #[allow(unused_variables)]
3735 _ => false,
3736 }
3737}
3738
3739pub fn q1g_matmat(
3741 model: &Arc<CmfModel>,
3742 idx: usize,
3743 xs: &[f32],
3744 b: usize,
3745 rows: usize,
3746 cols: usize,
3747 out: &mut [f32],
3748) -> bool {
3749 match backend() {
3750 #[cfg(feature = "gpu")]
3751 Backend::Wgpu => crate::gpu_wgpu::q1g_matmat(model, idx, xs, b, rows, cols, out),
3752 #[allow(unused_variables)]
3753 _ => false,
3754 }
3755}
3756
3757static MM_KILL: AtomicBool = AtomicBool::new(false);
3762pub(crate) fn mm_killed() -> bool {
3763 MM_KILL.load(Ordering::Relaxed)
3764}
3765pub(crate) fn mm_kill() {
3766 MM_KILL.store(true, Ordering::Relaxed);
3767}
3768
3769static MM_STRIKES: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
3776const MM_STRIKES_TO_KILL: u32 = 3;
3777static MM_ARMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
3784
3785pub fn mm_kill_arm(on: bool) {
3788 MM_ARMED.store(on, Ordering::Relaxed);
3789 if on {
3790 MM_STRIKES.store(0, Ordering::Relaxed);
3791 }
3792}
3793
3794pub(crate) fn mm_budget_check(
3801 what: &str,
3802 el: std::time::Duration,
3803 budget: std::time::Duration,
3804 exempt: bool,
3805) {
3806 if el <= budget {
3807 MM_STRIKES.store(0, Ordering::Relaxed);
3808 return;
3809 }
3810 if exempt || !MM_ARMED.load(Ordering::Relaxed) {
3811 return;
3812 }
3813 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3814 let on = *ON.get_or_init(|| std::env::var("CMF_MM_KILL").as_deref() != Ok("0"));
3815 let n = MM_STRIKES.fetch_add(1, Ordering::Relaxed) + 1;
3816 if !on {
3817 tracing::info!(
3818 "gpu {what} took {el:?} (budget {budget:?}) — over budget, CMF_MM_KILL=0 keeps the device"
3819 );
3820 return;
3821 }
3822 if n >= MM_STRIKES_TO_KILL {
3823 tracing::warn!(
3824 "gpu {what} took {el:?} (budget {budget:?}), {n} in a row — \
3825 device contended, CPU for the rest of the process (CMF_MM_KILL=0 to override)"
3826 );
3827 mm_kill();
3828 } else {
3829 tracing::info!(
3830 "gpu {what} took {el:?} (budget {budget:?}) — strike {n} of {MM_STRIKES_TO_KILL}"
3831 );
3832 }
3833}
3834
3835#[allow(unused_variables, clippy::too_many_arguments)]
3840pub fn chunk_attend(
3841 q: &[f32],
3842 k: &[&[f32]],
3843 v: &[&[f32]],
3844 b: usize,
3845 s0: usize,
3846 nh: usize,
3847 nkv: usize,
3848 hd: usize,
3849 scale: f32,
3850 out: &mut [f32],
3851) -> bool {
3852 match backend() {
3853 #[cfg(feature = "gpu")]
3854 Backend::Wgpu => crate::gpu_wgpu::chunk_attend(q, k, v, b, s0, nh, nkv, hd, scale, out),
3855 #[allow(unreachable_patterns)]
3856 _ => false,
3857 }
3858}
3859
3860#[allow(unused_variables, clippy::too_many_arguments)]
3863pub fn chunk_attend_win(
3864 q: &[f32],
3865 k: &[&[f32]],
3866 v: &[&[f32]],
3867 b: usize,
3868 s0: usize,
3869 nh: usize,
3870 nkv: usize,
3871 hd: usize,
3872 scale: f32,
3873 window: usize,
3874 out: &mut [f32],
3875) -> bool {
3876 match backend() {
3877 #[cfg(feature = "gpu")]
3878 Backend::Wgpu => {
3879 crate::gpu_wgpu::chunk_attend_win(q, k, v, b, s0, nh, nkv, hd, scale, window, out)
3880 }
3881 #[allow(unreachable_patterns)]
3882 _ => false,
3883 }
3884}
3885
3886#[allow(unused_variables)]
3889pub fn gemm_many_keep(
3890 model: &Arc<CmfModel>,
3891 idxs: &[(usize, usize)],
3892 xs: &[f32],
3893 b: usize,
3894 cols: usize,
3895 out: &mut [f32],
3896) -> bool {
3897 match backend() {
3898 #[cfg(feature = "gpu")]
3899 Backend::Wgpu => crate::gpu_wgpu::gemm_many_keep(model, idxs, xs, b, cols, out),
3900 #[allow(unreachable_patterns)]
3901 _ => false,
3902 }
3903}
3904
3905thread_local! {
3906 static PREFILL_FAST_GEMM: Cell<bool> = const { Cell::new(false) };
3910}
3911
3912pub struct PrefillFastGemmGuard(bool);
3914
3915impl Drop for PrefillFastGemmGuard {
3916 fn drop(&mut self) {
3917 PREFILL_FAST_GEMM.with(|c| c.set(self.0));
3918 }
3919}
3920
3921pub fn enter_prefill_fast_gemm() -> PrefillFastGemmGuard {
3925 PrefillFastGemmGuard(PREFILL_FAST_GEMM.with(|c| c.replace(true)))
3926}
3927
3928pub fn prefill_fast_gemm() -> bool {
3930 PREFILL_FAST_GEMM.with(|c| c.get())
3931}
3932
3933pub const F16_MAX: f32 = 65504.0;
3936
3937pub fn abs_max_or_inf(xs: &[f32]) -> f32 {
3941 let mut acc = [0f32; 16];
3942 let mut bad = [false; 16];
3943 let mut it = xs.chunks_exact(16);
3944 for c in &mut it {
3945 for ((a, f), &v) in acc.iter_mut().zip(bad.iter_mut()).zip(c) {
3946 let v = v.abs();
3947 *f |= !(v < f32::INFINITY);
3949 *a = if v > *a { v } else { *a };
3950 }
3951 }
3952 let mut m = 0f32;
3953 for &v in it.remainder() {
3954 let v = v.abs();
3955 if !(v < f32::INFINITY) {
3956 return f32::INFINITY;
3957 }
3958 m = m.max(v);
3959 }
3960 if bad.iter().any(|&f| f) {
3961 return f32::INFINITY;
3962 }
3963 acc.iter().fold(m, |m, &a| m.max(a))
3964}
3965
3966#[derive(Clone, Copy)]
3968pub struct GdnPreviewW<'a> {
3969 pub conv_right: &'a [f32],
3971 pub logit_scale: &'a [f32],
3972 pub history_bias: &'a [f32],
3973 pub history_c: &'a [f32],
3974}
3975
3976#[derive(Clone, Copy, Debug, PartialEq)]
3982pub struct BlockPreview {
3983 pub coreset_top_p: Option<f32>,
3985}
3986
3987thread_local! {
3988 static BLOCK_PREVIEW: Cell<Option<BlockPreview>> = const { Cell::new(None) };
3989}
3990
3991pub struct BlockPreviewGuard(Option<BlockPreview>);
3993
3994impl Drop for BlockPreviewGuard {
3995 fn drop(&mut self) {
3996 BLOCK_PREVIEW.with(|c| c.set(self.0));
3997 }
3998}
3999
4000pub fn enter_block_preview(p: BlockPreview) -> BlockPreviewGuard {
4002 BlockPreviewGuard(BLOCK_PREVIEW.with(|c| c.replace(Some(p))))
4003}
4004
4005pub fn block_preview() -> Option<BlockPreview> {
4007 BLOCK_PREVIEW.with(|c| c.get())
4008}
4009
4010#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4016pub struct PrefillMirror {
4017 pub kv_id: u64,
4018 pub layer: usize,
4019 pub limit: usize,
4020}
4021
4022thread_local! {
4023 static PREFILL_MIRROR: Cell<Option<PrefillMirror>> = const { Cell::new(None) };
4027}
4028
4029pub struct PrefillMirrorGuard(Option<PrefillMirror>);
4031
4032impl Drop for PrefillMirrorGuard {
4033 fn drop(&mut self) {
4034 PREFILL_MIRROR.with(|c| c.set(self.0));
4035 }
4036}
4037
4038pub fn enter_prefill_mirror(t: PrefillMirror) -> PrefillMirrorGuard {
4041 PrefillMirrorGuard(PREFILL_MIRROR.with(|c| c.replace(Some(t))))
4042}
4043
4044pub fn prefill_mirror() -> Option<PrefillMirror> {
4046 PREFILL_MIRROR.with(|c| c.get())
4047}
4048
4049#[allow(unused_variables, clippy::too_many_arguments)]
4062pub fn chunk_attend_mirror(
4063 t: PrefillMirror,
4064 cpu_k: &[Vec<f32>],
4065 cpu_v: &[Vec<f32>],
4066 base: usize,
4067 q: &[f32],
4068 b: usize,
4069 s0: usize,
4070 nh: usize,
4071 nkv: usize,
4072 hd: usize,
4073 scale: f32,
4074 ring: Option<usize>,
4075 window: usize,
4076 operand_max: f32,
4077 out: &mut [f32],
4078) -> bool {
4079 match backend() {
4080 #[cfg(feature = "gpu")]
4081 Backend::Wgpu => crate::gpu_wgpu::chunk_attend_mirror(
4086 t.kv_id,
4087 t.layer,
4088 t.limit,
4089 cpu_k,
4090 cpu_v,
4091 base,
4092 q,
4093 b,
4094 s0,
4095 nh,
4096 nkv,
4097 hd,
4098 scale,
4099 ring,
4100 window,
4101 std::env::var("CMF_PREFILL_ATTN_COOP").as_deref() != Ok("0"),
4102 operand_max,
4103 out,
4104 ),
4105 #[allow(unreachable_patterns)]
4106 _ => false,
4107 }
4108}
4109
4110#[allow(unused_variables, clippy::too_many_arguments)]
4118pub fn chunk_attend_mirror_wo(
4119 t: PrefillMirror,
4120 cpu_k: &[Vec<f32>],
4121 cpu_v: &[Vec<f32>],
4122 base: usize,
4123 q: &[f32],
4124 b: usize,
4125 s0: usize,
4126 nh: usize,
4127 nkv: usize,
4128 hd: usize,
4129 scale: f32,
4130 ring: Option<usize>,
4131 window: usize,
4132 operand_max: f32,
4133 gains: Option<&[f32]>,
4134 wo: (&Arc<CmfModel>, usize),
4135 hidden: usize,
4136 out: &mut [f32],
4137) -> bool {
4138 match backend() {
4139 #[cfg(feature = "gpu")]
4140 Backend::Wgpu => crate::gpu_wgpu::chunk_attend_mirror_wo(
4141 t.kv_id,
4142 t.layer,
4143 t.limit,
4144 cpu_k,
4145 cpu_v,
4146 base,
4147 q,
4148 b,
4149 s0,
4150 nh,
4151 nkv,
4152 hd,
4153 scale,
4154 ring,
4155 window,
4156 std::env::var("CMF_PREFILL_ATTN_COOP").as_deref() != Ok("0"),
4157 operand_max,
4158 gains,
4159 wo,
4160 hidden,
4161 out,
4162 ),
4163 #[allow(unreachable_patterns)]
4164 _ => false,
4165 }
4166}
4167
4168pub fn chunk_attend_windowed() -> bool {
4170 match backend() {
4171 #[cfg(feature = "gpu")]
4172 Backend::Wgpu => true,
4173 #[allow(unreachable_patterns)]
4174 _ => false,
4175 }
4176}
4177
4178#[allow(unused_variables, clippy::too_many_arguments)]
4182pub fn q4t_qkv(
4183 model: &Arc<CmfModel>,
4184 wq: usize,
4185 wk: usize,
4186 wv: usize,
4187 xs: &[f32],
4188 b: usize,
4189 cols: usize,
4190 rq: usize,
4191 rk: usize,
4192 rv: usize,
4193 out: &mut [f32],
4194) -> bool {
4195 match backend() {
4196 #[cfg(feature = "gpu")]
4197 Backend::Wgpu => crate::gpu_wgpu::q4t_qkv(model, wq, wk, wv, xs, b, cols, rq, rk, rv, out),
4198 #[allow(unreachable_patterns)]
4199 _ => false,
4200 }
4201}
4202
4203#[allow(unused_variables, clippy::too_many_arguments)]
4205#[allow(clippy::too_many_arguments, unused_variables)]
4209pub fn q4tp_ffn_packed(
4210 model: &Arc<CmfModel>,
4211 w1: usize,
4212 w2: usize,
4213 xs: &[f32],
4214 b: usize,
4215 hidden: usize,
4216 inter: usize,
4217 bias: Option<&[f32]>,
4218 out: &mut [f32],
4219) -> bool {
4220 match backend() {
4221 #[cfg(feature = "gpu")]
4222 Backend::Wgpu => {
4223 crate::gpu_wgpu::ffn_packed(model, w1, w2, xs, b, hidden, inter, bias, out)
4224 }
4225 #[allow(unreachable_patterns)]
4226 _ => false,
4227 }
4228}
4229
4230pub fn q4tp_ffn(
4231 model: &Arc<CmfModel>,
4232 w1: usize,
4233 w3: usize,
4234 w2: usize,
4235 xs: &[f32],
4236 b: usize,
4237 hidden: usize,
4238 inter: usize,
4239 out: &mut [f32],
4240) -> bool {
4241 match backend() {
4242 #[cfg(target_os = "macos")]
4243 Backend::Metal => crate::gpu_metal::q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4244 #[cfg(feature = "gpu")]
4245 Backend::Wgpu => crate::gpu_wgpu::q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4246 #[allow(unreachable_patterns)]
4247 _ => false,
4248 }
4249}
4250
4251#[allow(clippy::too_many_arguments, unused_variables)]
4255pub fn q4_ffn_act(
4256 model: &Arc<CmfModel>,
4257 w1: usize,
4258 w3: usize,
4259 w2: usize,
4260 xs: &[f32],
4261 b: usize,
4262 hidden: usize,
4263 inter: usize,
4264 q4tp: bool,
4265 act: GraphAct,
4266 out: &mut [f32],
4267) -> bool {
4268 match act {
4269 GraphAct::Silu if q4tp => q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4270 GraphAct::Silu => q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4271 GraphAct::GeluErf | GraphAct::GeluTanh | GraphAct::SwiGluOaiM3 => match backend() {
4275 #[cfg(feature = "gpu")]
4276 Backend::Wgpu => crate::gpu_wgpu::q4_ffn_act(
4277 model,
4278 w1,
4279 w3,
4280 w2,
4281 xs,
4282 b,
4283 hidden,
4284 inter,
4285 q4tp,
4286 act.code(),
4287 out,
4288 ),
4289 #[allow(unreachable_patterns)]
4290 _ => false,
4291 },
4292 }
4293}
4294
4295#[allow(clippy::too_many_arguments, unused_variables)]
4300pub fn ffn_act_keep(
4301 model: &Arc<CmfModel>,
4302 w1: usize,
4303 w3: usize,
4304 w2: usize,
4305 xs: &[f32],
4306 b: usize,
4307 hidden: usize,
4308 inter: usize,
4309 act: GraphAct,
4310 out: &mut [f32],
4311) -> bool {
4312 match backend() {
4313 #[cfg(feature = "gpu")]
4314 Backend::Wgpu => crate::gpu_wgpu::ffn_act_keep(
4315 model,
4316 w1,
4317 w3,
4318 w2,
4319 xs,
4320 b,
4321 hidden,
4322 inter,
4323 act.code(),
4324 out,
4325 ),
4326 #[allow(unreachable_patterns)]
4327 _ => false,
4328 }
4329}
4330
4331#[allow(clippy::too_many_arguments, unused_variables)]
4336pub fn q4tp_gelu_ffn(
4337 model: &Arc<CmfModel>,
4338 w_in: usize,
4339 w_out: usize,
4340 xs: &[f32],
4341 b: usize,
4342 hidden: usize,
4343 inter: usize,
4344 bias_in: &[f32],
4345 bias_out: &[f32],
4346 out: &mut [f32],
4347) -> bool {
4348 match backend() {
4349 #[cfg(feature = "gpu")]
4350 Backend::Wgpu => crate::gpu_wgpu::q4tp_gelu_ffn(
4351 model, w_in, w_out, xs, b, hidden, inter, bias_in, bias_out, out,
4352 ),
4353 #[allow(unreachable_patterns)]
4354 _ => false,
4355 }
4356}
4357
4358pub fn q4t_ffn(
4359 model: &Arc<CmfModel>,
4360 w1: usize,
4361 w3: usize,
4362 w2: usize,
4363 xs: &[f32],
4364 b: usize,
4365 hidden: usize,
4366 inter: usize,
4367 out: &mut [f32],
4368) -> bool {
4369 match backend() {
4370 #[cfg(target_os = "macos")]
4371 Backend::Metal => crate::gpu_metal::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4372 #[cfg(feature = "gpu")]
4373 Backend::Wgpu => crate::gpu_wgpu::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4374 #[allow(unreachable_patterns)]
4375 _ => false,
4376 }
4377}
4378
4379pub struct DitBlockArgs<'a> {
4384 pub n: usize,
4385 pub hidden: usize,
4386 pub inter: usize,
4387 pub nh: usize,
4388 pub nkv: usize,
4389 pub hd: usize,
4390 pub eps: f32,
4391 pub rope_cos: &'a [f32],
4392 pub rope_sin: &'a [f32],
4393 pub norm1: &'a [f32],
4394 pub norm2: &'a [f32],
4395 pub ffn_norm1: &'a [f32],
4396 pub ffn_norm2: &'a [f32],
4397 pub norm_q: &'a [f32],
4398 pub norm_k: &'a [f32],
4399 pub s_msa: &'a [f32],
4400 pub gate_msa: &'a [f32],
4401 pub s_mlp: &'a [f32],
4402 pub gate_mlp: &'a [f32],
4403 pub wq: usize,
4404 pub wk: usize,
4405 pub wv: usize,
4406 pub wo: usize,
4407 pub w1: usize,
4408 pub w3: usize,
4409 pub w2: usize,
4410 pub q4tp: bool,
4414 pub resident_in: bool,
4417 pub resident_out: bool,
4421}
4422
4423pub fn dit_chain_supported() -> bool {
4427 #[cfg(feature = "gpu")]
4428 {
4429 return matches!(backend(), Backend::Wgpu) && fused_dit_block_available();
4430 }
4431 #[allow(unreachable_code)]
4432 false
4433}
4434
4435pub fn dit_state_fetch(_x: &mut [f32]) -> bool {
4438 #[cfg(feature = "gpu")]
4439 {
4440 if matches!(backend(), Backend::Wgpu) {
4441 return crate::gpu_wgpu::dit_state_fetch(_x);
4442 }
4443 }
4444 false
4445}
4446
4447#[allow(unused_variables)]
4451#[allow(unused_variables, clippy::too_many_arguments)]
4455pub fn dit_qkv(
4456 model: &Arc<CmfModel>,
4457 wq: usize,
4458 wk: usize,
4459 wv: usize,
4460 xs: &[f32],
4461 b: usize,
4462 hidden: usize,
4463 qrows: usize,
4464 kvrows: usize,
4465 q_out: &mut [f32],
4466 k_out: &mut [f32],
4467 v_out: &mut [f32],
4468) -> bool {
4469 match backend() {
4470 #[cfg(feature = "gpu")]
4471 Backend::Wgpu => crate::gpu_wgpu::q4tp_qkv(
4472 model, wq, wk, wv, xs, b, hidden, qrows, kvrows, q_out, k_out, v_out,
4473 ),
4474 #[allow(unreachable_patterns)]
4475 _ => false,
4476 }
4477}
4478
4479pub struct QwenImageAttentionArgs<'a> {
4487 pub image: &'a [f32],
4488 pub text: &'a [f32],
4489 pub image_tokens: usize,
4490 pub text_tokens: usize,
4491 pub heads: usize,
4492 pub head_dim: usize,
4493 pub image_q: usize,
4494 pub image_k: usize,
4495 pub image_v: usize,
4496 pub text_q: usize,
4497 pub text_k: usize,
4498 pub text_v: usize,
4499 pub image_out: usize,
4500 pub text_out: usize,
4501 pub image_q_norm: &'a [f32],
4502 pub image_k_norm: &'a [f32],
4503 pub text_q_norm: &'a [f32],
4504 pub text_k_norm: &'a [f32],
4505 pub image_cos: &'a [f32],
4506 pub image_sin: &'a [f32],
4507 pub text_cos: &'a [f32],
4508 pub text_sin: &'a [f32],
4509 pub image_q_bias: &'a [f32],
4510 pub image_k_bias: &'a [f32],
4511 pub image_v_bias: &'a [f32],
4512 pub text_q_bias: &'a [f32],
4513 pub text_k_bias: &'a [f32],
4514 pub text_v_bias: &'a [f32],
4515 pub image_out_bias: &'a [f32],
4516 pub text_out_bias: &'a [f32],
4517 pub image_proj: &'a mut [f32],
4518 pub text_proj: &'a mut [f32],
4519}
4520
4521#[allow(clippy::too_many_fields)]
4526pub struct QwenImageChainBlock<'a> {
4527 pub image_mod: &'a [f32],
4528 pub text_mod: &'a [f32],
4529 pub image_q: usize,
4530 pub image_k: usize,
4531 pub image_v: usize,
4532 pub text_q: usize,
4533 pub text_k: usize,
4534 pub text_v: usize,
4535 pub image_out: usize,
4536 pub text_out: usize,
4537 pub image_q_norm: &'a [f32],
4538 pub image_k_norm: &'a [f32],
4539 pub text_q_norm: &'a [f32],
4540 pub text_k_norm: &'a [f32],
4541 pub image_q_bias: &'a [f32],
4542 pub image_k_bias: &'a [f32],
4543 pub image_v_bias: &'a [f32],
4544 pub text_q_bias: &'a [f32],
4545 pub text_k_bias: &'a [f32],
4546 pub text_v_bias: &'a [f32],
4547 pub image_out_bias: &'a [f32],
4548 pub text_out_bias: &'a [f32],
4549 pub image_attn_gate: &'a [f32],
4550 pub text_attn_gate: &'a [f32],
4551 pub image_mlp_in: usize,
4552 pub image_mlp_out: usize,
4553 pub text_mlp_in: usize,
4554 pub text_mlp_out: usize,
4555 pub image_mlp_in_bias: &'a [f32],
4556 pub image_mlp_out_bias: &'a [f32],
4557 pub text_mlp_in_bias: &'a [f32],
4558 pub text_mlp_out_bias: &'a [f32],
4559}
4560
4561#[allow(clippy::too_many_fields)]
4567pub struct QwenImageBlockArgs<'a> {
4568 pub image: &'a mut [f32],
4571 pub text: &'a mut [f32],
4572 pub image_norm: &'a [f32],
4573 pub text_norm: &'a [f32],
4574 pub image_tokens: usize,
4575 pub text_tokens: usize,
4576 pub heads: usize,
4577 pub head_dim: usize,
4578 pub image_cos: &'a [f32],
4579 pub image_sin: &'a [f32],
4580 pub text_cos: &'a [f32],
4581 pub text_sin: &'a [f32],
4582 pub image_q: usize,
4583 pub image_k: usize,
4584 pub image_v: usize,
4585 pub text_q: usize,
4586 pub text_k: usize,
4587 pub text_v: usize,
4588 pub image_out: usize,
4589 pub text_out: usize,
4590 pub image_q_norm: &'a [f32],
4591 pub image_k_norm: &'a [f32],
4592 pub text_q_norm: &'a [f32],
4593 pub text_k_norm: &'a [f32],
4594 pub image_q_bias: &'a [f32],
4595 pub image_k_bias: &'a [f32],
4596 pub image_v_bias: &'a [f32],
4597 pub text_q_bias: &'a [f32],
4598 pub text_k_bias: &'a [f32],
4599 pub text_v_bias: &'a [f32],
4600 pub image_out_bias: &'a [f32],
4601 pub text_out_bias: &'a [f32],
4602 pub image_attn_gate: &'a [f32],
4603 pub text_attn_gate: &'a [f32],
4604 pub image_mlp_in: usize,
4605 pub image_mlp_out: usize,
4606 pub text_mlp_in: usize,
4607 pub text_mlp_out: usize,
4608 pub image_mlp_in_bias: &'a [f32],
4609 pub image_mlp_out_bias: &'a [f32],
4610 pub text_mlp_in_bias: &'a [f32],
4611 pub text_mlp_out_bias: &'a [f32],
4612 pub image_mlp_mod: &'a [f32],
4613 pub text_mlp_mod: &'a [f32],
4614 pub image_mlp_gate: &'a [f32],
4615 pub text_mlp_gate: &'a [f32],
4616}
4617
4618pub struct QwenImageChainArgs<'a> {
4623 pub image: &'a mut [f32],
4624 pub text: &'a mut [f32],
4625 pub image_tokens: usize,
4626 pub text_tokens: usize,
4627 pub heads: usize,
4628 pub head_dim: usize,
4629 pub image_cos: &'a [f32],
4630 pub image_sin: &'a [f32],
4631 pub text_cos: &'a [f32],
4632 pub text_sin: &'a [f32],
4633 pub blocks: &'a [QwenImageChainBlock<'a>],
4634}
4635
4636#[allow(unused_variables)]
4637pub fn qwen_image_attention(
4638 model: &Arc<CmfModel>,
4639 args: &mut QwenImageAttentionArgs<'_>,
4640) -> bool {
4641 match backend() {
4642 #[cfg(feature = "gpu")]
4643 Backend::Wgpu => crate::gpu_wgpu::qwen_image_attention(model, args),
4644 #[allow(unreachable_patterns)]
4645 _ => false,
4646 }
4647}
4648
4649#[allow(unused_variables)]
4650pub fn qwen_image_block(model: &Arc<CmfModel>, args: &mut QwenImageBlockArgs<'_>) -> bool {
4651 match backend() {
4652 #[cfg(feature = "gpu")]
4653 Backend::Wgpu => crate::gpu_wgpu::qwen_image_block(model, args),
4654 #[allow(unreachable_patterns)]
4655 _ => false,
4656 }
4657}
4658
4659#[allow(unused_variables)]
4663pub fn qwen_image_chain(model: &Arc<CmfModel>, args: &mut QwenImageChainArgs<'_>) -> bool {
4664 match backend() {
4665 #[cfg(feature = "gpu")]
4666 Backend::Wgpu => {
4667 #[cfg(not(target_os = "macos"))]
4669 if crate::gpu_wgpu::h3::qwen_chain(model, args) {
4670 return true;
4671 }
4672 crate::gpu_wgpu::qwen_image_chain(model, args)
4673 }
4674 #[cfg(feature = "cuda")]
4675 Backend::Cuda => crate::gpu_cuda::qwen_image_chain(model, args),
4676 #[allow(unreachable_patterns)]
4677 _ => false,
4678 }
4679}
4680
4681pub struct MossChainBlock<'a> {
4684 pub norm1: &'a [f32],
4685 pub norm2: &'a [f32],
4686 pub q_norm: &'a [f32],
4687 pub k_norm: &'a [f32],
4688 pub q: usize,
4689 pub k: usize,
4690 pub v: usize,
4691 pub o: usize,
4692 pub up_gate: usize,
4694 pub down: usize,
4695}
4696
4697pub struct MossChainArgs<'a> {
4701 pub x: &'a mut [f32],
4702 pub tokens: usize,
4703 pub heads: usize,
4704 pub head_dim: usize,
4705 pub modulation: &'a [f32],
4706 pub cos: &'a [f32],
4707 pub sin: &'a [f32],
4708 pub blocks: &'a [MossChainBlock<'a>],
4709}
4710
4711#[allow(unused_variables)]
4714pub fn moss_chain(model: &Arc<CmfModel>, args: &mut MossChainArgs<'_>) -> bool {
4715 match backend() {
4716 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
4717 Backend::Wgpu => crate::gpu_wgpu::h3::moss_chain(model, args),
4718 #[cfg(feature = "cuda")]
4719 Backend::Cuda => crate::gpu_cuda::moss_chain(model, args),
4720 #[cfg(target_os = "macos")]
4721 Backend::Metal => crate::gpu_metal::h3::moss_chain(model, args),
4722 #[allow(unreachable_patterns)]
4723 _ => false,
4724 }
4725}
4726
4727#[allow(unused_variables, clippy::too_many_arguments)]
4734pub fn qwen_image_mlp_inplace(
4735 model: &Arc<CmfModel>,
4736 w_in: usize,
4737 w_out: usize,
4738 data: &mut [f32],
4739 batch: usize,
4740 hidden: usize,
4741 inter: usize,
4742 bias_in: &[f32],
4743 bias_out: &[f32],
4744 modulation: &[f32],
4745 gate: &[f32],
4746) -> bool {
4747 match backend() {
4748 #[cfg(feature = "gpu")]
4749 Backend::Wgpu => crate::gpu_wgpu::qwen_image_mlp_inplace(
4750 model,
4751 w_in,
4752 w_out,
4753 data,
4754 batch,
4755 hidden,
4756 inter,
4757 bias_in,
4758 bias_out,
4759 modulation,
4760 gate,
4761 ),
4762 #[allow(unreachable_patterns)]
4763 _ => false,
4764 }
4765}
4766
4767pub fn fused_dit_block_available() -> bool {
4771 #[cfg(target_os = "macos")]
4772 {
4773 matches!(backend(), Backend::Metal) && fused_block_trusted()
4774 }
4775 #[cfg(not(target_os = "macos"))]
4776 {
4777 false
4778 }
4779}
4780
4781pub fn dit_block(model: &Arc<CmfModel>, a: &DitBlockArgs, x: &mut [f32]) -> bool {
4782 dit_block_seg(model, a, &[a.n], x)
4783}
4784
4785pub fn dit_block_seg(
4789 model: &Arc<CmfModel>,
4790 a: &DitBlockArgs,
4791 segs: &[usize],
4792 x: &mut [f32],
4793) -> bool {
4794 match backend() {
4795 #[cfg(target_os = "macos")]
4796 Backend::Metal if segs.len() <= 1 => crate::gpu_metal::dit_block(model, a, x),
4797 #[cfg(feature = "gpu")]
4804 Backend::Wgpu
4805 if match std::env::var("CMF_DIT_FUSED").ok().as_deref() {
4806 Some("0") => false,
4807 Some(_) => true,
4808 None => crate::gpu_wgpu::discrete_active(),
4809 } =>
4810 {
4811 crate::gpu_wgpu::dit_block_seg(model, a, segs, x)
4812 }
4813 #[cfg(feature = "cuda")]
4816 Backend::Cuda => crate::gpu_cuda::lumina_block(model, a, segs, x),
4817 #[allow(unreachable_patterns)]
4818 _ => false,
4819 }
4820}
4821
4822pub struct VaeResnetArgs<'a> {
4826 pub groups: usize,
4827 pub ic: usize,
4828 pub oc: usize,
4829 pub h: usize,
4830 pub w: usize,
4831 pub n1w: &'a [f32],
4832 pub n1b: &'a [f32],
4833 pub c1w: &'a [f32],
4834 pub c1b: &'a [f32],
4835 pub c1k: usize,
4836 pub n2w: &'a [f32],
4837 pub n2b: &'a [f32],
4838 pub c2w: &'a [f32],
4839 pub c2b: &'a [f32],
4840 pub c2k: usize,
4841 pub shortcut: Option<(&'a [f32], &'a [f32], usize)>,
4842}
4843
4844#[allow(unused_variables)]
4847pub fn vae_resnet(a: &VaeResnetArgs, x: &[f32], out: &mut [f32]) -> bool {
4848 match backend() {
4849 #[cfg(target_os = "macos")]
4850 Backend::Metal => crate::gpu_metal::vae_resnet(a, x, out),
4851 _ => false,
4852 }
4853}
4854
4855#[allow(unused_variables, clippy::too_many_arguments)]
4858pub fn vae_upsample_conv(
4859 w: &[f32],
4860 bias: &[f32],
4861 x: &[f32],
4862 ic: usize,
4863 oc: usize,
4864 h: usize,
4865 w_img: usize,
4866 k: usize,
4867 out: &mut [f32],
4868) -> bool {
4869 match backend() {
4870 #[cfg(target_os = "macos")]
4871 Backend::Metal => crate::gpu_metal::vae_upsample_conv(w, bias, x, ic, oc, h, w_img, k, out),
4872 #[cfg(feature = "gpu")]
4873 Backend::Wgpu => crate::gpu_wgpu::vae_upsample_conv(w, bias, x, ic, oc, h, w_img, k, out),
4874 #[cfg(feature = "cuda")]
4875 Backend::Cuda => crate::gpu_cuda::h3_vae_conv2d(w, bias, x, ic, oc, h, w_img, k, true, out),
4876 #[allow(unreachable_patterns)]
4877 _ => false,
4878 }
4879}
4880
4881#[allow(unused_variables, clippy::too_many_arguments)]
4884pub fn vae_conv2d(
4885 w: &[f32],
4886 bias: &[f32],
4887 x: &[f32],
4888 ic: usize,
4889 oc: usize,
4890 h: usize,
4891 w_img: usize,
4892 k: usize,
4893 out: &mut [f32],
4894) -> bool {
4895 match backend() {
4896 #[cfg(target_os = "macos")]
4897 Backend::Metal => crate::gpu_metal::vae_conv2d(w, bias, x, ic, oc, h, w_img, k, out),
4898 #[cfg(feature = "gpu")]
4899 Backend::Wgpu => crate::gpu_wgpu::vae_conv2d(w, bias, x, ic, oc, h, w_img, k, out),
4900 #[cfg(feature = "cuda")]
4901 Backend::Cuda => crate::gpu_cuda::h3_vae_conv2d(w, bias, x, ic, oc, h, w_img, k, false, out),
4902 #[allow(unreachable_patterns)]
4903 _ => false,
4904 }
4905}
4906
4907#[allow(unused_variables, clippy::too_many_arguments)]
4911#[allow(unused_variables)]
4915#[allow(clippy::too_many_arguments)]
4916#[allow(clippy::too_many_arguments, unused_variables)]
4919pub fn dit_qkv_attention(
4920 model: &Arc<CmfModel>,
4921 qkv_idx: usize,
4922 xn: &[f32],
4923 n: usize,
4924 hidden: usize,
4925 nh: usize,
4926 hd: usize,
4927 scale: f32,
4928 nr: (&[f32], &[f32], &[f32], f32),
4929 out: &mut [f32],
4930) -> bool {
4931 match backend() {
4932 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
4933 Backend::Wgpu => crate::gpu_wgpu::dit_qkv_attention(
4934 model, qkv_idx, xn, n, hidden, nh, hd, scale, nr, out,
4935 ),
4936 #[allow(unreachable_patterns)]
4937 _ => false,
4938 }
4939}
4940
4941pub struct H3ChainBlock<'a> {
4944 pub qkv: usize,
4945 pub out: usize,
4946 pub fc1: usize,
4947 pub fc2: usize,
4948 pub norm1: &'a [f32],
4949 pub norm2: &'a [f32],
4950 pub q_norm: &'a [f32],
4951 pub k_norm: &'a [f32],
4952 pub mods: &'a [f32],
4955 pub qkv_bias: &'a [f32],
4958 pub out_bias: &'a [f32],
4959 pub fc1_bias: &'a [f32],
4960 pub fc2_bias: &'a [f32],
4961 pub scale1: &'a [f32],
4962 pub scale2: &'a [f32],
4963 pub gate: usize,
4966}
4967
4968pub struct H3Chain<'a> {
4970 pub model: &'a Arc<CmfModel>,
4971 pub blocks: &'a [H3ChainBlock<'a>],
4972 pub n: usize,
4973 pub hidden: usize,
4974 pub heads: usize,
4975 pub head_dim: usize,
4976 pub ffn: usize,
4977 pub eps: f32,
4978 pub qk_eps: f32,
4979 pub angles: &'a [f32],
4981 pub rows: &'a [u32],
4983 pub groups: usize,
4987 pub qkv_interleaved: bool,
4990 pub vsa: Option<&'a crate::mmh3::VsaPlan>,
4994}
4995
4996pub struct TeChainLayer<'a> {
4999 pub q: usize,
5000 pub k: usize,
5001 pub v: usize,
5002 pub o: usize,
5003 pub gate: usize,
5004 pub up: usize,
5005 pub down: usize,
5006 pub input_norm: &'a [f32],
5007 pub post_norm: &'a [f32],
5008 pub q_norm: &'a [f32],
5009 pub k_norm: &'a [f32],
5010}
5011
5012pub struct TeChain<'a> {
5014 pub model: &'a Arc<CmfModel>,
5015 pub layers: &'a [TeChainLayer<'a>],
5016 pub n: usize,
5017 pub hidden: usize,
5018 pub heads: usize,
5019 pub kv_heads: usize,
5020 pub head_dim: usize,
5021 pub inter: usize,
5022 pub eps: f32,
5023 pub cs: &'a [f32],
5025}
5026
5027#[allow(unused_variables)]
5030pub fn te_chain(job: &TeChain<'_>, h: &mut [f32]) -> bool {
5031 match backend() {
5032 #[cfg(feature = "cuda")]
5033 Backend::Cuda => crate::gpu_cuda::h3_te_chain(job, h),
5034 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5035 Backend::Wgpu => crate::gpu_wgpu::h3::te_chain(job, h),
5036 #[cfg(target_os = "macos")]
5037 Backend::Metal => crate::gpu_metal::h3::te_chain(job, h),
5038 #[allow(unreachable_patterns)]
5039 _ => false,
5040 }
5041}
5042
5043#[derive(Clone, Copy)]
5047pub struct LtxLin<'a> {
5048 pub w: Option<usize>,
5049 pub dense: &'a [f32],
5050 pub rows: usize,
5051 pub cols: usize,
5052 pub bias: &'a [f32],
5053}
5054
5055#[derive(Clone, Copy)]
5060pub struct LtxAttn<'a> {
5061 pub q: LtxLin<'a>,
5062 pub k: LtxLin<'a>,
5063 pub v: LtxLin<'a>,
5064 pub o: LtxLin<'a>,
5065 pub q_norm: &'a [f32],
5066 pub k_norm: &'a [f32],
5067 pub gate: Option<LtxLin<'a>>,
5068 pub heads: usize,
5069 pub dh: usize,
5070}
5071
5072pub struct LtxStream<'a> {
5074 pub attn1: LtxAttn<'a>,
5075 pub attn2: LtxAttn<'a>,
5076 pub ff_in: LtxLin<'a>,
5077 pub ff_out: LtxLin<'a>,
5078 pub mods: &'a [f32],
5082 pub ctx_mod: &'a [f32],
5084}
5085
5086pub struct LtxBlock<'a> {
5088 pub video: LtxStream<'a>,
5089 pub audio: LtxStream<'a>,
5090 pub a2v: LtxAttn<'a>,
5091 pub v2a: LtxAttn<'a>,
5092 pub xmods_v: &'a [f32],
5095 pub xmods_a: &'a [f32],
5097 pub gate_a2v: &'a [f32],
5099 pub gate_v2a: &'a [f32],
5101}
5102
5103pub struct LtxSide<'a> {
5105 pub n: usize,
5106 pub dim: usize,
5107 pub rows: &'a [u32],
5109 pub xrows: &'a [u32],
5111 pub pe: (&'a [f32], &'a [f32], usize),
5114 pub xpe: (&'a [f32], &'a [f32], usize),
5116 pub ctx: &'a [f32],
5118 pub ctx_len: usize,
5119 pub mask: &'a [f32],
5121}
5122
5123pub struct LtxChain<'a> {
5125 pub model: &'a Arc<CmfModel>,
5126 pub blocks: &'a [LtxBlock<'a>],
5127 pub video: LtxSide<'a>,
5128 pub audio: LtxSide<'a>,
5129}
5130
5131pub fn ltx_chain_available() -> bool {
5133 match backend() {
5134 #[cfg(feature = "cuda")]
5135 Backend::Cuda => true,
5136 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5137 Backend::Wgpu => crate::gpu_wgpu::h3::ltx_available(),
5138 #[allow(unreachable_patterns)]
5139 _ => false,
5140 }
5141}
5142
5143#[allow(unused_variables)]
5147pub fn ltx_chain(job: &LtxChain<'_>, vx: &mut [f32], ax: &mut [f32]) -> bool {
5148 match backend() {
5149 #[cfg(feature = "cuda")]
5150 Backend::Cuda => crate::gpu_cuda::ltx_chain(job, vx, ax),
5151 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5152 Backend::Wgpu => crate::gpu_wgpu::h3::ltx_chain(job, vx, ax),
5153 #[allow(unreachable_patterns)]
5154 _ => false,
5155 }
5156}
5157
5158pub enum Vae3dStep<'a> {
5161 Conv { w: &'a [f32], b: &'a [f32], in_ch: usize, out_ch: usize },
5164 NormSilu { eps: f32 },
5167 Save,
5169 AddSaved,
5171 DepthToSpace { p: (usize, usize, usize) },
5174}
5175
5176#[allow(unused_variables)]
5179pub fn vae3d_chain(
5180 steps: &[Vae3dStep<'_>],
5181 x: &[f32],
5182 c: usize,
5183 f: usize,
5184 h: usize,
5185 w: usize,
5186) -> Option<(Vec<f32>, usize, usize, usize, usize)> {
5187 match backend() {
5188 #[cfg(feature = "cuda")]
5189 Backend::Cuda => crate::gpu_cuda::ltx_vae_chain(steps, x, c, f, h, w),
5190 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5191 Backend::Wgpu => crate::gpu_wgpu::h3::ltx_vae_chain(steps, x, c, f, h, w),
5192 #[allow(unreachable_patterns)]
5193 _ => None,
5194 }
5195}
5196
5197pub enum ConvStep<'a> {
5199 GnSilu { w: &'a [f32], b: &'a [f32] },
5201 Conv {
5205 w: &'a [f32],
5206 b: &'a [f32],
5207 out_ch: usize,
5208 in_ch: usize,
5209 k: usize,
5210 stride: usize,
5211 pad: usize,
5212 far: bool,
5213 },
5214 Save,
5216 AddSaved { via: Option<(&'a [f32], &'a [f32])> },
5219}
5220
5221#[allow(unused_variables)]
5224pub fn conv_chain(steps: &[ConvStep<'_>], x: &[f32], c: usize, h: usize, w: usize) -> Option<(Vec<f32>, usize, usize, usize)> {
5225 match backend() {
5226 #[cfg(feature = "cuda")]
5227 Backend::Cuda => crate::gpu_cuda::h3_conv_chain(steps, x, c, h, w),
5228 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5229 Backend::Wgpu => crate::gpu_wgpu::h3_conv::conv_chain(steps, x, c, h, w),
5230 #[allow(unreachable_patterns)]
5231 _ => None,
5232 }
5233}
5234
5235pub fn h3_chain_available() -> bool {
5237 match backend() {
5238 #[cfg(feature = "cuda")]
5239 Backend::Cuda => true,
5240 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5241 Backend::Wgpu => crate::gpu_wgpu::h3::available(),
5242 #[cfg(target_os = "macos")]
5243 Backend::Metal => crate::gpu_metal::h3::available(),
5244 #[allow(unreachable_patterns)]
5245 _ => false,
5246 }
5247}
5248
5249#[allow(unused_variables)]
5253pub fn h3_chain(job: &H3Chain<'_>, h: &mut [f32]) -> bool {
5254 match backend() {
5255 #[cfg(feature = "cuda")]
5256 Backend::Cuda => crate::gpu_cuda::h3_chain(job, h),
5257 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5261 Backend::Wgpu => crate::gpu_wgpu::h3::chain(job, h),
5262 #[cfg(target_os = "macos")]
5263 Backend::Metal => (job.vsa.is_none() || std::env::var("CMF_H3_METAL_VSA").as_deref() != Ok("0")) && crate::gpu_metal::h3::chain(job, h),
5264 #[allow(unreachable_patterns)]
5265 _ => false,
5266 }
5267}
5268
5269#[allow(clippy::too_many_arguments)]
5272pub fn dit_qkv_attn_out(
5273 model: &Arc<CmfModel>,
5274 qkv_idx: usize,
5275 out_idx: usize,
5276 xn: &[f32],
5277 n: usize,
5278 hidden: usize,
5279 nh: usize,
5280 hd: usize,
5281 scale: f32,
5282 nr: (&[f32], &[f32], &[f32], f32),
5283 proj: &mut [f32],
5284) -> bool {
5285 match backend() {
5286 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5287 Backend::Wgpu => crate::gpu_wgpu::dit_qkv_attn_out(
5288 model, qkv_idx, out_idx, xn, n, hidden, nh, hd, scale, nr, proj,
5289 ),
5290 #[allow(unreachable_patterns)]
5291 _ => false,
5292 }
5293}
5294
5295#[allow(clippy::too_many_arguments)]
5297pub fn vae_qkv_attn_out(
5298 model: &Arc<CmfModel>,
5299 qkv_idx: usize,
5300 out_idx: usize,
5301 xn: &[f32],
5302 n: usize,
5303 dim: usize,
5304 nh: usize,
5305 hd: usize,
5306 scale: f32,
5307 angles: &[f32],
5308 eps: f32,
5309 qkv_bias: &[f32],
5310 proj: &mut [f32],
5311) -> bool {
5312 match backend() {
5313 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5314 Backend::Wgpu => crate::gpu_wgpu::vae_qkv_attn_out(
5315 model, qkv_idx, out_idx, xn, n, dim, nh, hd, scale, angles, eps, qkv_bias, proj,
5316 ),
5317 #[allow(unreachable_patterns)]
5318 _ => false,
5319 }
5320}
5321
5322#[allow(clippy::too_many_arguments)]
5323pub fn vae_attention_packed(
5324 qkv: &[f32],
5325 nh: usize,
5326 n: usize,
5327 hd: usize,
5328 scale: f32,
5329 angles: &[f32],
5330 eps: f32,
5331 out: &mut [f32],
5332) -> bool {
5333 vae_attention_packed_layout(qkv, nh, n, hd, scale, angles, eps, out, 1)
5334}
5335
5336#[allow(clippy::too_many_arguments)]
5337pub fn vae_attention_packed_layout(
5338 qkv: &[f32],
5339 nh: usize,
5340 n: usize,
5341 hd: usize,
5342 scale: f32,
5343 angles: &[f32],
5344 eps: f32,
5345 out: &mut [f32],
5346 layout: u32,
5347) -> bool {
5348 match backend() {
5349 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5350 Backend::Wgpu => crate::gpu_wgpu::vae_attention_packed_layout(
5351 qkv, nh, n, hd, scale, angles, eps, out, layout,
5352 ),
5353 #[allow(unreachable_patterns)]
5354 _ => false,
5355 }
5356}
5357
5358#[allow(clippy::too_many_arguments)]
5359pub fn dit_split_only(
5360 qkv: &[f32],
5361 nh: usize,
5362 n: usize,
5363 hd: usize,
5364 layout: u32,
5365 norm: Option<(&[f32], f32)>,
5366 out_q: &mut [f32],
5367) -> bool {
5368 match backend() {
5369 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5370 Backend::Wgpu => crate::gpu_wgpu::dit_split_only(qkv, nh, n, hd, layout, norm, out_q),
5371 #[allow(unreachable_patterns)]
5372 _ => false,
5373 }
5374}
5375
5376pub fn gemm_nt_f32_transient(
5384 x: &[f32],
5385 w: &[f32],
5386 y: &mut [f32],
5387 n: usize,
5388 k: usize,
5389 m: usize,
5390) -> bool {
5391 match backend() {
5392 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5393 Backend::Wgpu => crate::gpu_wgpu::gemm_nt_f32_transient(x, w, y, n, k, m),
5394 #[allow(unreachable_patterns)]
5395 _ => false,
5396 }
5397}
5398
5399pub struct VitLayer<'a> {
5403 pub ln1_w: &'a [f32],
5404 pub ln1_b: &'a [f32],
5405 pub qkv: &'a [f32],
5406 pub qkv_b: &'a [f32],
5407 pub proj: &'a [f32],
5408 pub proj_b: &'a [f32],
5409 pub ln2_w: &'a [f32],
5410 pub ln2_b: &'a [f32],
5411 pub fc1: &'a [f32],
5412 pub fc1_b: &'a [f32],
5413 pub fc2: &'a [f32],
5414 pub fc2_b: &'a [f32],
5415}
5416
5417pub struct VitArgs<'a> {
5422 pub key: u64,
5423 pub layers: Vec<VitLayer<'a>>,
5424 pub n: usize,
5425 pub d: usize,
5426 pub heads: usize,
5427 pub head_dim: usize,
5428 pub inter: usize,
5429 pub eps: f64,
5430 pub gelu_tanh: bool,
5431 pub quick_gelu: bool,
5433 pub rope_halves: bool,
5434 pub cos: &'a [f32],
5435 pub sin: &'a [f32],
5436 pub prof: bool,
5437}
5438
5439#[allow(unused_variables)]
5443pub fn vit_encode(a: &VitArgs, x: &mut [f32]) -> bool {
5444 if std::env::var("CMF_VIT_RESIDENT").as_deref() == Ok("0") {
5445 return false;
5446 }
5447 match backend() {
5448 #[cfg(target_os = "macos")]
5449 Backend::Metal => crate::gpu_metal::vit::encode(a, x),
5450 #[cfg(feature = "gpu")]
5451 Backend::Wgpu => crate::gpu_wgpu::vit::encode(a, x),
5452 #[cfg(feature = "cuda")]
5453 Backend::Cuda => crate::gpu_cuda::vit_encode(a, x),
5454 #[allow(unreachable_patterns)]
5455 _ => false,
5456 }
5457}
5458
5459pub struct SamLayer<'a> {
5462 pub ln1_w: &'a [f32],
5463 pub ln1_b: &'a [f32],
5464 pub qkv: &'a [f32],
5465 pub qkv_b: &'a [f32],
5466 pub proj: &'a [f32],
5467 pub proj_b: &'a [f32],
5468 pub rel: &'a [f32],
5469 pub ln2_w: &'a [f32],
5470 pub ln2_b: &'a [f32],
5471 pub fc1: &'a [f32],
5472 pub fc1_b: &'a [f32],
5473 pub fc2: &'a [f32],
5474 pub fc2_b: &'a [f32],
5475 pub window: usize,
5476}
5477
5478pub struct SamConv<'a> {
5480 pub w: &'a [f32],
5481 pub ci: usize,
5482 pub co: usize,
5483 pub k: usize,
5484 pub stride: usize,
5485 pub pad: usize,
5486 pub norm: bool,
5488}
5489
5490pub struct SamArgs<'a> {
5491 pub key: u64,
5492 pub layers: Vec<SamLayer<'a>>,
5493 pub convs: Vec<SamConv<'a>>,
5494 pub norms: Vec<&'a [f32]>,
5495 pub rel_global: Vec<Vec<f32>>,
5497 pub g: usize,
5498 pub d: usize,
5499 pub heads: usize,
5500 pub head_dim: usize,
5501 pub inter: usize,
5502 pub eps: f64,
5503}
5504
5505#[allow(unused_variables)]
5507pub fn sam_encode(a: &SamArgs, x: &[f32], out: &mut Vec<f32>) -> bool {
5508 if std::env::var("CMF_VIT_RESIDENT").as_deref() == Ok("0") {
5509 return false;
5510 }
5511 match backend() {
5512 #[cfg(target_os = "macos")]
5513 Backend::Metal => crate::gpu_metal::vit::sam_encode(a, x, out),
5514 #[cfg(feature = "gpu")]
5515 Backend::Wgpu => crate::gpu_wgpu::vit::sam_encode(a, x, out),
5516 #[cfg(feature = "cuda")]
5517 Backend::Cuda => crate::gpu_cuda::sam_encode(a, x, out),
5518 #[allow(unreachable_patterns)]
5519 _ => false,
5520 }
5521}
5522
5523pub fn primal_vae_run(
5527 key: u64,
5528 weights: &crate::primal_vae::PvWeights,
5529 plan: &crate::primal_vae::PvPlan,
5530 input: &[f32],
5531 out: &mut [f32],
5532) -> bool {
5533 match backend() {
5534 #[cfg(target_os = "macos")]
5535 Backend::Metal => crate::gpu_metal::primal_vae::run(key, weights, plan, input, out),
5536 #[cfg(feature = "gpu")]
5537 Backend::Wgpu => crate::gpu_wgpu::primal_vae::run(key, weights, plan, input, out),
5538 #[cfg(feature = "cuda")]
5539 Backend::Cuda => crate::gpu_cuda::primal_vae_run(key, weights, plan, input, out),
5540 #[allow(unreachable_patterns)]
5541 _ => false,
5542 }
5543}
5544
5545pub fn vision_gemm_nt(x: &[f32], w: &[f32], y: &mut [f32], n: usize, k: usize, m: usize) -> bool {
5550 if n * k * m < (1 << 22) {
5551 return false;
5552 }
5553 match backend() {
5554 #[cfg(target_os = "macos")]
5555 Backend::Metal => crate::gpu_metal::egemma2::gemm_nt(x, w, y, n, k, m),
5556 #[cfg(feature = "gpu")]
5557 Backend::Wgpu => crate::gpu_wgpu::gemm_nt_f32(x, w, y, n, k, m),
5558 #[cfg(feature = "cuda")]
5559 Backend::Cuda => crate::gpu_cuda::h3_gemm_nt(x, w, y, n, k, m),
5560 #[allow(unreachable_patterns)]
5561 _ => false,
5562 }
5563}
5564
5565pub fn gemm_nt_f32(x: &[f32], w: &[f32], y: &mut [f32], n: usize, k: usize, m: usize) -> bool {
5568 match backend() {
5569 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5570 Backend::Wgpu => crate::gpu_wgpu::gemm_nt_f32(x, w, y, n, k, m),
5571 #[cfg(feature = "cuda")]
5572 Backend::Cuda => crate::gpu_cuda::h3_gemm_nt(x, w, y, n, k, m),
5573 #[allow(unreachable_patterns)]
5574 _ => false,
5575 }
5576}
5577
5578#[allow(clippy::too_many_arguments)]
5581pub fn music3_ffn(
5582 model: &std::sync::Arc<CmfModel>,
5583 idx_in: usize,
5584 idx_out: usize,
5585 h: &[f32],
5586 bias_in: &[f32],
5587 n: usize,
5588 hs: usize,
5589 inter: usize,
5590 out: &mut [f32],
5591) -> bool {
5592 match backend() {
5593 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5594 Backend::Wgpu => {
5595 crate::gpu_wgpu::music3_ffn(model, idx_in, idx_out, h, bias_in, n, hs, inter, out)
5596 }
5597 #[cfg(feature = "cuda")]
5598 Backend::Cuda => crate::gpu_cuda::h3_music3_ffn(model, idx_in, idx_out, h, bias_in, n, hs, inter, out),
5599 #[allow(unreachable_patterns)]
5600 _ => false,
5601 }
5602}
5603
5604#[allow(clippy::too_many_arguments, unused_variables)]
5608pub fn moe_row(
5609 model: &Arc<CmfModel>,
5610 experts: &[(usize, usize, usize)],
5611 shared: Option<((usize, usize, usize), usize, f32)>,
5612 inter: usize,
5613 limit: f32,
5614 x: &[f32],
5615 picks: &[(usize, f32)],
5616 out: &mut [f32],
5617) -> bool {
5618 match backend() {
5619 #[cfg(feature = "cuda")]
5620 Backend::Cuda => crate::gpu_cuda::moe_row(model, experts, shared, inter, limit, x, picks, out),
5621 #[allow(unreachable_patterns)]
5622 _ => false,
5623 }
5624}
5625
5626#[allow(clippy::too_many_arguments)]
5630pub fn glm_sequence_prepare(
5631 model_uid: u64,
5632 sequence_id: u64,
5633 layers: usize,
5634 hidden: usize,
5635 mhc_streams: usize,
5636 nh: usize,
5637 dk: usize,
5638 dv: usize,
5639 kk: usize,
5640 dsa_rank: usize,
5641 dsa_index: usize,
5642 dsa_topk: usize,
5643 dsa_kpool: usize,
5644) -> bool {
5645 let _ = (model_uid, sequence_id, layers, hidden, mhc_streams, nh, dk, dv, kk, dsa_rank, dsa_index, dsa_topk, dsa_kpool);
5646 false
5647}
5648
5649pub fn glm_sequence_reserve(model_uid: u64, sequence_id: u64, positions: usize) -> bool {
5651 let _ = (model_uid, sequence_id, positions);
5652 false
5653}
5654
5655pub fn glm_sequence_abort(model_uid: u64, sequence_id: u64) {
5657 let _ = (model_uid, sequence_id);
5658}
5659
5660#[allow(clippy::too_many_arguments)]
5664pub fn conv1d_gemm(
5665 x: &[f32],
5666 w: &[f32],
5667 ic: usize,
5668 oc: usize,
5669 n: usize,
5670 k: usize,
5671 pad: usize,
5672 dil: usize,
5673 out_n: usize,
5674 yt: &mut [f32],
5675) -> bool {
5676 match backend() {
5677 #[cfg(target_os = "macos")]
5678 Backend::Metal => crate::gpu_metal::conv1d_gemm(x, w, ic, oc, n, k, pad, dil, out_n, yt),
5679 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5680 Backend::Wgpu => crate::gpu_wgpu::conv1d_gemm(x, w, ic, oc, n, k, pad, dil, out_n, yt),
5681 #[cfg(feature = "cuda")]
5682 Backend::Cuda => {
5683 out_n * ic * k * oc >= (1 << 22) && crate::gpu_cuda::h3_conv1d(x, w, ic, oc, n, k, pad, dil, out_n, yt)
5685 }
5686 #[allow(unreachable_patterns)]
5687 _ => false,
5688 }
5689}
5690
5691#[allow(clippy::too_many_arguments)]
5693pub fn vae_conv2d_coop(
5694 w: &[f32],
5695 bias: Option<&[f32]>,
5696 x: &[f32],
5697 ic: usize,
5698 oc: usize,
5699 h: usize,
5700 wi: usize,
5701 k: usize,
5702 out: &mut [f32],
5703) -> bool {
5704 match backend() {
5705 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5706 Backend::Wgpu => crate::gpu_wgpu::vae_conv2d_coop(w, bias, x, ic, oc, h, wi, k, out),
5707 #[allow(unreachable_patterns)]
5708 _ => false,
5709 }
5710}
5711
5712pub fn dit_attention_packed(
5713 qkv: &[f32],
5714 nh: usize,
5715 n: usize,
5716 hd: usize,
5717 scale: f32,
5718 nr: Option<(&[f32], &[f32], &[f32], f32)>,
5721 out: &mut [f32],
5722) -> bool {
5723 match backend() {
5724 #[cfg(feature = "gpu")]
5731 Backend::Wgpu => crate::gpu_wgpu::dit_attention_packed(qkv, nh, n, hd, scale, nr, out),
5732 #[allow(unreachable_patterns)]
5733 _ => false,
5734 }
5735}
5736
5737pub fn dit_attention_packed_available() -> bool {
5745 #[allow(unreachable_patterns)]
5746 match backend() {
5747 #[cfg(feature = "gpu")]
5748 Backend::Wgpu => crate::gpu_wgpu::dit_attention_packed_ready(),
5749 _ => false,
5750 }
5751}
5752
5753pub fn dit_attention(
5754 qh: &[f32],
5755 kh: &[f32],
5756 vh: &[f32],
5757 nh: usize,
5758 nkv: usize,
5759 n: usize,
5760 hd: usize,
5761 scale: f32,
5762 out: &mut [f32],
5763) -> bool {
5764 match backend() {
5765 #[cfg(target_os = "macos")]
5766 Backend::Metal => crate::gpu_metal::dit_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
5767 #[cfg(feature = "gpu")]
5768 Backend::Wgpu => crate::gpu_wgpu::dit_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
5769 #[cfg(feature = "cuda")]
5770 Backend::Cuda => crate::gpu_cuda::h3_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
5771 #[allow(unreachable_patterns)]
5772 _ => false,
5773 }
5774}
5775
5776pub fn gram_alloc(cols: usize) -> Option<u64> {
5779 #[cfg(feature = "gpu")]
5780 if backend() == Backend::Wgpu {
5781 return crate::gpu_wgpu::gram::alloc(cols);
5782 }
5783 let _ = cols;
5784 None
5785}
5786
5787pub fn gram_add(id: u64, xs: &[f32], b: usize) -> bool {
5789 #[cfg(feature = "gpu")]
5790 if backend() == Backend::Wgpu {
5791 return crate::gpu_wgpu::gram::add(id, xs, b);
5792 }
5793 let _ = (id, xs, b);
5794 false
5795}
5796
5797#[cfg(feature = "gpu")]
5799pub fn gram_add_dev(id: u64, x: &wgpu::Buffer, b: usize) -> bool {
5800 if backend() == Backend::Wgpu {
5801 return crate::gpu_wgpu::gram::add_dev(id, x, b);
5802 }
5803 false
5804}
5805
5806pub fn gram_take(id: u64) -> Option<Vec<f64>> {
5808 #[cfg(feature = "gpu")]
5809 if backend() == Backend::Wgpu {
5810 return crate::gpu_wgpu::gram::take(id);
5811 }
5812 let _ = id;
5813 None
5814}
5815
5816pub fn gptq_fold_dev(h_id: u64, n: usize, lambda: f64) -> Option<u64> {
5821 #[cfg(feature = "gpu")]
5822 if backend() == Backend::Wgpu {
5823 return crate::gpu_wgpu::gptq_dev::fold(h_id, n, lambda);
5824 }
5825 let _ = (h_id, n, lambda);
5826 None
5827}
5828
5829pub fn gptq_fold_info(id: u64) -> Option<(Vec<bool>, Vec<f32>, f64)> {
5831 #[cfg(feature = "gpu")]
5832 if backend() == Backend::Wgpu {
5833 return crate::gpu_wgpu::gptq_dev::info(id);
5834 }
5835 let _ = id;
5836 None
5837}
5838
5839pub fn gptq_fold_read(id: u64) -> Option<Vec<f32>> {
5841 #[cfg(feature = "gpu")]
5842 if backend() == Backend::Wgpu {
5843 return crate::gpu_wgpu::gptq_dev::read_u(id);
5844 }
5845 let _ = id;
5846 None
5847}
5848
5849pub fn gptq_fold_free(id: u64) {
5851 #[cfg(feature = "gpu")]
5852 if backend() == Backend::Wgpu {
5853 crate::gpu_wgpu::gptq_dev::free(id);
5854 }
5855 let _ = id;
5856}
5857
5858#[allow(clippy::too_many_arguments)]
5860pub fn gptq_sweep_q4tp_dev(
5861 id: u64,
5862 w: &[f32],
5863 rows: usize,
5864 tab: &[f32],
5865 lost: &[f32],
5866 nib: &mut [u8],
5867 codes: &mut [u32],
5868) -> bool {
5869 #[cfg(feature = "gpu")]
5870 if backend() == Backend::Wgpu {
5871 return crate::gpu_wgpu::gptq_dev::sweep_q4tp(id, w, rows, tab, lost, nib, codes);
5872 }
5873 let _ = (id, w, rows, tab, lost, nib, codes);
5874 false
5875}
5876
5877pub fn gptq_sweep_q2tp_dev(
5879 id: u64,
5880 w: &[f32],
5881 rows: usize,
5882 tab: &[f32],
5883 hw: &[f32],
5884 chunks: &mut [u8],
5885 codes: &mut [u32],
5886) -> bool {
5887 #[cfg(feature = "gpu")]
5888 if backend() == Backend::Wgpu {
5889 return crate::gpu_wgpu::gptq_dev::sweep_q2tp(id, w, rows, tab, hw, chunks, codes);
5890 }
5891 let _ = (id, w, rows, tab, hw, chunks, codes);
5892 false
5893}
5894
5895pub fn gram_read(id: u64) -> Option<Vec<f64>> {
5898 #[cfg(feature = "gpu")]
5899 if backend() == Backend::Wgpu {
5900 return crate::gpu_wgpu::gram::read(id);
5901 }
5902 let _ = id;
5903 None
5904}
5905
5906pub fn gram_clear() {
5908 #[cfg(feature = "gpu")]
5909 if backend() == Backend::Wgpu {
5910 crate::gpu_wgpu::gram::clear();
5911 }
5912}
5913
5914#[allow(unused_variables)]
5919pub fn q4tp_matmat(
5920 model: &Arc<CmfModel>,
5921 idx: usize,
5922 xs: &[f32],
5923 b: usize,
5924 rows: usize,
5925 cols: usize,
5926 out: &mut [f32],
5927) -> bool {
5928 match backend() {
5929 #[cfg(target_os = "macos")]
5930 Backend::Metal => crate::gpu_metal::q4tp_matmat(model, idx, xs, b, rows, cols, out),
5931 #[cfg(feature = "gpu")]
5932 Backend::Wgpu => crate::gpu_wgpu::q4tp_matmat(model, idx, xs, b, rows, cols, out),
5933 #[cfg(feature = "cuda")]
5934 Backend::Cuda => crate::gpu_cuda::h3_matmat(model, idx, xs, b, rows, cols, out),
5935 #[allow(unreachable_patterns)]
5936 _ => false,
5937 }
5938}
5939
5940#[allow(unused_variables)]
5945pub fn stage_done(model: &CmfModel) {
5946 match backend() {
5947 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5948 Backend::Wgpu => {
5949 crate::gpu_wgpu::h3::release();
5950 crate::gpu_wgpu::h3_conv::release();
5951 crate::gpu_wgpu::release_model_buffers(model)
5952 }
5953 #[cfg(feature = "cuda")]
5954 Backend::Cuda => crate::gpu_cuda::h3_release(),
5955 #[cfg(target_os = "macos")]
5956 Backend::Metal => crate::gpu_metal::h3::release(),
5957 #[allow(unreachable_patterns)]
5958 _ => {}
5959 }
5960}
5961
5962pub fn h3_prof_report() -> Option<String> {
5964 match backend() {
5965 #[cfg(feature = "cuda")]
5966 Backend::Cuda => crate::gpu_cuda::h3_prof_report(),
5967 #[allow(unreachable_patterns)]
5968 _ => None,
5969 }
5970}
5971
5972pub fn layer_taps_arm(layers: &[usize]) {
5977 match backend() {
5978 #[cfg(feature = "gpu")]
5979 Backend::Wgpu => crate::gpu_wgpu::layer_taps_arm(layers),
5980 #[cfg(feature = "cuda")]
5981 Backend::Cuda => crate::gpu_cuda::layer_taps_arm(layers),
5982 #[allow(unreachable_patterns)]
5983 _ => {
5984 let _ = layers;
5985 }
5986 }
5987}
5988
5989pub fn layer_taps_take(out: &mut Vec<f32>) -> bool {
5992 match backend() {
5993 #[cfg(feature = "gpu")]
5994 Backend::Wgpu => crate::gpu_wgpu::layer_taps_take(out),
5995 #[cfg(feature = "cuda")]
5996 Backend::Cuda => crate::gpu_cuda::layer_taps_take(out),
5997 #[allow(unreachable_patterns)]
5998 _ => {
5999 let _ = out;
6000 false
6001 }
6002 }
6003}
6004
6005pub fn q4tp_rows8_many(
6011 model: &Arc<CmfModel>,
6012 jobs: &[(usize, usize, usize, usize)],
6013 xs: &[f32],
6014 b: usize,
6015 outs: &mut [&mut [f32]],
6016) -> bool {
6017 match backend() {
6018 #[cfg(target_os = "macos")]
6019 Backend::Metal => {
6020 let takes: Vec<usize> = jobs.iter().map(|j| j.3).collect();
6021 let jobs: Vec<crate::gpu_metal::MmJob> = jobs
6022 .iter()
6023 .map(|&(idx, rows, cols, _)| crate::gpu_metal::MmJob { idx, rows, cols })
6024 .collect();
6025 crate::gpu_metal::q4tp_n8_many(model, &jobs, Some(&takes), xs, b, outs)
6026 }
6027 #[allow(unreachable_patterns)]
6028 _ => {
6029 let _ = (model, jobs, xs, b, outs);
6030 false
6031 }
6032 }
6033}
6034
6035#[allow(clippy::too_many_arguments)]
6037pub fn q4tp_rows8_ffn(
6038 model: &Arc<CmfModel>,
6039 w1: usize,
6040 w3: usize,
6041 w2: usize,
6042 xs: &[f32],
6043 b: usize,
6044 hidden: usize,
6045 inter: usize,
6046 out: &mut [f32],
6047) -> bool {
6048 match backend() {
6049 #[cfg(target_os = "macos")]
6050 Backend::Metal => crate::gpu_metal::q4tp_n8_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
6051 #[allow(unreachable_patterns)]
6052 _ => {
6053 let _ = (model, w1, w3, w2, xs, b, hidden, inter, out);
6054 false
6055 }
6056 }
6057}
6058
6059pub fn q4tp_matmat_many(
6063 model: &Arc<CmfModel>,
6064 jobs: &[(usize, usize, usize)],
6065 xs: &[f32],
6066 b: usize,
6067 outs: &mut [&mut [f32]],
6068) -> bool {
6069 match backend() {
6070 #[cfg(target_os = "macos")]
6071 Backend::Metal => {
6072 let jobs: Vec<crate::gpu_metal::MmJob> = jobs
6073 .iter()
6074 .map(|&(idx, rows, cols)| crate::gpu_metal::MmJob { idx, rows, cols })
6075 .collect();
6076 crate::gpu_metal::q4tp_matmat_many(model, &jobs, xs, b, outs)
6077 }
6078 #[cfg(feature = "gpu")]
6079 Backend::Wgpu => crate::gpu_wgpu::q4tp_matmat_many(model, jobs, xs, b, outs),
6080 #[allow(unreachable_patterns)]
6081 _ => {
6082 let _ = (model, jobs, xs, b, outs);
6083 false
6084 }
6085 }
6086}
6087
6088pub fn q2tp_matmat(
6091 model: &Arc<CmfModel>,
6092 idx: usize,
6093 xs: &[f32],
6094 b: usize,
6095 rows: usize,
6096 cols: usize,
6097 out: &mut [f32],
6098) -> bool {
6099 match backend() {
6100 #[cfg(target_os = "macos")]
6101 Backend::Metal => crate::gpu_metal::q2tp_matmat(model, idx, xs, b, rows, cols, out),
6102 #[cfg(feature = "gpu")]
6103 Backend::Wgpu => crate::gpu_wgpu::q2tp_matmat(model, idx, xs, b, rows, cols, out),
6104 #[allow(unreachable_patterns)]
6105 _ => false,
6106 }
6107}
6108
6109pub fn q2tp_affine_matmat(
6112 model: &Arc<CmfModel>,
6113 idx: usize,
6114 xs: &[f32],
6115 b: usize,
6116 rows: usize,
6117 cols: usize,
6118 out: &mut [f32],
6119) -> bool {
6120 match backend() {
6121 #[cfg(target_os = "macos")]
6122 Backend::Metal => crate::gpu_metal::q2tp_affine_matmat(model, idx, xs, b, rows, cols, out),
6123 #[cfg(feature = "gpu")]
6124 Backend::Wgpu => crate::gpu_wgpu::q2tp_affine_matmat(model, idx, xs, b, rows, cols, out),
6125 #[allow(unreachable_patterns)]
6126 _ => false,
6127 }
6128}
6129
6130pub fn blr_matmat(t: &crate::blr::BlrTensor, xs: &[f32], b: usize, out: &mut [f32]) -> bool {
6135 match backend() {
6136 #[cfg(feature = "gpu")]
6137 Backend::Wgpu => crate::gpu_wgpu::blr_matmat(t, xs, b, out),
6138 #[allow(unreachable_patterns)]
6139 _ => {
6140 let _ = (t, xs, b, out);
6141 false
6142 }
6143 }
6144}
6145
6146pub fn mxfp4_matvec(
6150 model: &Arc<CmfModel>,
6151 idx: usize,
6152 xs: &[f32],
6153 rows: usize,
6154 cols: usize,
6155 out: &mut [f32],
6156) -> bool {
6157 mxfp4_matmat(model, idx, xs, 1, rows, cols, out)
6158}
6159
6160pub fn mxfp4_matmat(
6163 model: &Arc<CmfModel>,
6164 idx: usize,
6165 xs: &[f32],
6166 b: usize,
6167 rows: usize,
6168 cols: usize,
6169 out: &mut [f32],
6170) -> bool {
6171 match backend() {
6172 #[cfg(feature = "gpu")]
6173 Backend::Wgpu => crate::gpu_wgpu::mxfp4::matmat(model, idx, xs, b, rows, cols, out),
6174 #[allow(unreachable_patterns)]
6175 _ => {
6176 let _ = (model, idx, xs, b, rows, cols, out);
6177 false
6178 }
6179 }
6180}
6181
6182pub fn q2tp_matvec(
6184 model: &Arc<CmfModel>,
6185 idx: usize,
6186 xs: &[f32],
6187 rows: usize,
6188 cols: usize,
6189 out: &mut [f32],
6190) -> bool {
6191 match backend() {
6192 #[cfg(target_os = "macos")]
6193 Backend::Metal => crate::gpu_metal::q2tp_matvec(model, idx, xs, rows, cols, out),
6194 #[cfg(feature = "gpu")]
6195 Backend::Wgpu => crate::gpu_wgpu::q2tp_matvec(model, idx, xs, rows, cols, out),
6196 #[allow(unreachable_patterns)]
6197 _ => false,
6198 }
6199}
6200
6201pub fn q2tp_affine_matvec(
6205 model: &Arc<CmfModel>,
6206 idx: usize,
6207 xs: &[f32],
6208 rows: usize,
6209 cols: usize,
6210 out: &mut [f32],
6211) -> bool {
6212 match backend() {
6213 #[cfg(target_os = "macos")]
6214 Backend::Metal => crate::gpu_metal::q2tp_affine_matvec(model, idx, xs, rows, cols, out),
6215 #[cfg(feature = "gpu")]
6216 Backend::Wgpu => crate::gpu_wgpu::q2tp_affine_matvec(model, idx, xs, rows, cols, out),
6217 #[allow(unreachable_patterns)]
6218 _ => false,
6219 }
6220}
6221
6222pub fn q4tp_matvec(
6227 model: &Arc<CmfModel>,
6228 idx: usize,
6229 xs: &[f32],
6230 rows: usize,
6231 cols: usize,
6232 out: &mut [f32],
6233) -> bool {
6234 match backend() {
6235 #[cfg(target_os = "macos")]
6236 Backend::Metal => crate::gpu_metal::q4tp_matvec_for_test(model, idx, xs, rows, cols, out),
6237 #[cfg(feature = "gpu")]
6238 Backend::Wgpu => crate::gpu_wgpu::q4tp_matvec(model, idx, xs, rows, cols, out),
6239 #[allow(unreachable_patterns)]
6240 _ => false,
6241 }
6242}
6243
6244pub fn q4t_matvec(
6250 model: &Arc<CmfModel>,
6251 idx: usize,
6252 xs: &[f32],
6253 rows: usize,
6254 cols: usize,
6255 out: &mut [f32],
6256) -> bool {
6257 match backend() {
6258 #[cfg(target_os = "macos")]
6259 Backend::Metal => crate::gpu_metal::q4t_matvec_for_test(model, idx, xs, rows, cols, out),
6260 #[allow(unreachable_patterns)]
6261 _ => false,
6262 }
6263}
6264
6265pub fn q4t_matmat(
6266 model: &Arc<CmfModel>,
6267 idx: usize,
6268 xs: &[f32],
6269 b: usize,
6270 rows: usize,
6271 cols: usize,
6272 out: &mut [f32],
6273) -> bool {
6274 match backend() {
6275 #[cfg(target_os = "macos")]
6276 Backend::Metal => crate::gpu_metal::q4t_matmat(model, idx, xs, b, rows, cols, out),
6277 #[cfg(feature = "gpu")]
6278 Backend::Wgpu => crate::gpu_wgpu::q4t_matmat(model, idx, xs, b, rows, cols, out),
6279 #[allow(unreachable_patterns)]
6280 _ => false,
6281 }
6282}
6283
6284pub type SetW = (usize, usize, usize);
6291
6292pub enum SetMixer<'a> {
6293 Conv {
6294 in_proj: SetW,
6295 out_proj: SetW,
6296 taps: &'a [f32],
6298 kernel: usize,
6299 },
6300 Attn {
6301 wq: SetW,
6302 wk: SetW,
6303 wv: SetW,
6304 wo: SetW,
6305 q_norm: Option<&'a [f32]>,
6306 k_norm: Option<&'a [f32]>,
6307 head_gate: Option<&'a [f32]>,
6309 inv_freq: &'a [f32],
6310 rd: usize,
6311 nkv: usize,
6312 window: Option<usize>,
6314 },
6315}
6316
6317pub struct SetLayer<'a> {
6318 pub input_norm: &'a [f32],
6319 pub post_norm: &'a [f32],
6320 pub mixer: SetMixer<'a>,
6321 pub attn_out_norm: Option<&'a [f32]>,
6322 pub ffn_out_norm: Option<&'a [f32]>,
6323 pub gate: SetW,
6325 pub up: SetW,
6326 pub down: SetW,
6327}
6328
6329pub struct SetDims {
6330 pub hidden: usize,
6331 pub nh: usize,
6332 pub hd: usize,
6333 pub eps: f32,
6334 pub gemma: bool,
6335 pub scale: f32,
6336}
6337
6338pub struct SetHead<'a> {
6341 pub w: SetW,
6342 pub rows: &'a [usize],
6343}
6344
6345#[allow(clippy::too_many_arguments, unused_variables)]
6350pub fn lfm_set_forward(
6351 model: &Arc<CmfModel>,
6352 layers: &[SetLayer],
6353 dims: &SetDims,
6354 final_norm: &[f32],
6355 rows: &[f32],
6356 t: usize,
6357 state: usize,
6358 group: &[i32],
6359 head: Option<&SetHead>,
6360) -> Option<(Vec<f32>, Vec<f32>)> {
6361 #[allow(unreachable_patterns)]
6362 match backend() {
6363 #[cfg(target_os = "macos")]
6364 Backend::Metal => crate::gpu_metal::lfm_set::forward(
6365 model, layers, dims, final_norm, rows, t, state, group, head,
6366 ),
6367 #[cfg(feature = "gpu")]
6368 Backend::Wgpu => crate::gpu_wgpu::lfm_set::forward(
6369 model, layers, dims, final_norm, rows, t, state, group, head,
6370 ),
6371 #[cfg(feature = "cuda")]
6372 Backend::Cuda => crate::gpu_cuda::h3_lfm_set_forward(
6373 model, layers, dims, final_norm, rows, t, state, group, head,
6374 ),
6375 _ => None,
6376 }
6377}
6378
6379#[cfg(target_os = "macos")]
6381pub use crate::gpu_metal::{
6382 AttnDeviceParams, AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, GpuFlintMoe, GpuMoe, GraphDims,
6383 MetalFfn, O1AttnParams, SconvGpuLayer, TokenGraph, kv_mirror_drop, kv_mirror_read_last,
6384 kv_mirror_take_imp,
6385};
6386
6387#[cfg(target_os = "macos")]
6389pub fn gdn_block(
6390 model: &Arc<CmfModel>,
6391 layers: &[GdnGpuLayer],
6392 states: &mut [&mut [f32]],
6393 cfg: &GdnGpuCfg,
6394 h: &mut [f32],
6395) -> bool {
6396 match backend() {
6397 Backend::Metal => crate::gpu_metal::gdn_block(model, layers, states, cfg, h),
6398 _ => false,
6399 }
6400}
6401
6402#[allow(unused_variables)]
6404pub fn moe_block(model: &Arc<CmfModel>, jobs: &[MoeJob], out: &mut [f32]) -> bool {
6405 match backend() {
6406 #[cfg(target_os = "macos")]
6411 Backend::Metal => crate::gpu_metal::moe_block(model, jobs, out),
6412 #[cfg(feature = "gpu")]
6413 Backend::Wgpu => crate::gpu_wgpu::moe_block(model, jobs, out),
6414 Backend::None => false,
6415 #[cfg(feature = "cuda")]
6416 Backend::Cuda => false,
6417 }
6418}
6419
6420#[allow(unused_variables)]
6422pub fn matvec_batch(model: &Arc<CmfModel>, jobs: &[BatchJob], out: &mut [&mut [f32]]) -> bool {
6423 match backend() {
6424 #[cfg(target_os = "macos")]
6425 Backend::Metal => crate::gpu_metal::matvec_batch(model, jobs, out),
6426 #[cfg(feature = "gpu")]
6427 Backend::Wgpu => crate::gpu_wgpu::matvec_batch(model, jobs, out),
6428 Backend::None => false,
6429 #[cfg(feature = "cuda")]
6430 Backend::Cuda => false,
6431 }
6432}
6433
6434static GRAPH_RACE_STATE: AtomicU8 = AtomicU8::new(0); static GRAPH_RACE_FLIP: AtomicU32 = AtomicU32::new(0);
6450static 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)];
6454
6455const GRAPH_RACE_SAMPLES: u32 = 4;
6457
6458pub fn generation_end() {
6479 #[cfg(feature = "gpu")]
6480 if matches!(backend(), Backend::Wgpu) {
6481 crate::gpu_wgpu::pipeline_cache_flush_if_grown();
6482 }
6483}
6484
6485pub fn graph_race_begin_generation() {
6486 #[cfg(feature = "gpu")]
6491 {
6492 static FLUSHED: std::sync::Once = std::sync::Once::new();
6504 static FIRST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
6505 if FIRST.swap(false, Ordering::Relaxed) {
6506 } else {
6508 FLUSHED.call_once(crate::gpu_wgpu::pipeline_cache_flush);
6509 }
6510 }
6511 GRAPH_RACE_TOK.store(0, Ordering::Relaxed);
6512 if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
6513 return;
6514 }
6515 let (gn, cn) = (
6516 GRAPH_N[1].load(Ordering::Relaxed),
6517 GRAPH_N[0].load(Ordering::Relaxed),
6518 );
6519 if gn >= GRAPH_RACE_SAMPLES && cn >= GRAPH_RACE_SAMPLES {
6520 let g_avg = GRAPH_NS[1].load(Ordering::Relaxed) / gn as u64;
6521 let c_avg = GRAPH_NS[0].load(Ordering::Relaxed) / cn as u64;
6522 let verdict = if g_avg < c_avg { 1 } else { 2 };
6523 GRAPH_RACE_STATE.store(verdict, Ordering::Relaxed);
6524 tracing::info!(
6525 "wgpu graph race: graph {:.2} ms/tok vs normal {:.2} ms/tok -> {}",
6526 g_avg as f64 / 1e6,
6527 c_avg as f64 / 1e6,
6528 if verdict == 1 { "graph" } else { "normal path" }
6529 );
6530 return;
6531 }
6532 let flip = GRAPH_RACE_FLIP.fetch_add(1, Ordering::Relaxed);
6533 GRAPH_RACE_ARM_GRAPH.store((flip % 2 == 1) as u8, Ordering::Relaxed);
6534}
6535
6536pub fn graph_race_use_graph(trusted: bool) -> bool {
6540 if trusted {
6541 return true;
6542 }
6543 match GRAPH_RACE_STATE.load(Ordering::Relaxed) {
6544 1 => true,
6545 2 => false,
6546 _ => GRAPH_RACE_ARM_GRAPH.load(Ordering::Relaxed) == 1,
6547 }
6548}
6549
6550pub fn graph_race_first_token_hopeless(dur: std::time::Duration) -> bool {
6555 if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
6556 return false;
6557 }
6558 let first = GRAPH_RACE_TOK.load(Ordering::Relaxed) == 0;
6559 let cn = GRAPH_N[0].load(Ordering::Relaxed);
6560 if !first || cn == 0 {
6561 return false;
6562 }
6563 let c_avg = GRAPH_NS[0].load(Ordering::Relaxed) / cn as u64;
6564 let ns = dur.as_nanos() as u64;
6565 if ns > 1_000_000_000 && ns > 4 * c_avg {
6566 GRAPH_RACE_STATE.store(2, Ordering::Relaxed);
6567 tracing::info!(
6568 "wgpu graph race: first graph token {:.0} ms vs normal {:.2} ms/tok — hopeless, normal path wins",
6569 ns as f64 / 1e6,
6570 c_avg as f64 / 1e6
6571 );
6572 return true;
6573 }
6574 false
6575}
6576
6577pub fn graph_race_record(used_graph: bool, dur: std::time::Duration) {
6581 if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
6582 return;
6583 }
6584 let tok = GRAPH_RACE_TOK.fetch_add(1, Ordering::Relaxed);
6585 if tok == 0 {
6586 return;
6587 }
6588 let i = used_graph as usize;
6589 GRAPH_NS[i].fetch_add(dur.as_nanos() as u64, Ordering::Relaxed);
6590 GRAPH_N[i].fetch_add(1, Ordering::Relaxed);
6591}
6592
6593pub(crate) fn fp_bytes(data: &[u8]) -> u64 {
6603 #[inline]
6604 fn fnv(mut h: u64, bytes: &[u8]) -> u64 {
6605 let (chunks, tail) = bytes.split_at(bytes.len() & !7);
6606 for c in chunks.chunks_exact(8) {
6607 h ^= u64::from_le_bytes(c.try_into().unwrap());
6608 h = h.wrapping_mul(0x100_0000_01b3);
6609 }
6610 for &b in tail {
6611 h ^= b as u64;
6612 h = h.wrapping_mul(0x100_0000_01b3);
6613 }
6614 h
6615 }
6616 let mut h = 0xcbf2_9ce4_8422_2325u64 ^ (data.len() as u64);
6617 if data.len() <= 4096 {
6618 return fnv(h, data);
6619 }
6620 let step = (data.len() - 64) / 63;
6621 for i in 0..64 {
6622 h = fnv(h, &data[i * step..i * step + 64]);
6623 }
6624 h
6625}
6626
6627pub(crate) fn fp_f32(data: &[f32]) -> u64 {
6630 let bytes = unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, data.len() * 4) };
6631 fp_bytes(bytes)
6632}
6633
6634#[cfg(test)]
6635mod fp_tests {
6636 use super::fp_bytes;
6637
6638 #[test]
6643 fn fp_bytes_sees_a_change_anywhere_in_a_sampled_slice() {
6644 let n = 1 << 20; let base: Vec<u8> = (0..n).map(|i| (i * 31 + 7) as u8).collect();
6646 let h0 = fp_bytes(&base);
6647 assert_eq!(h0, fp_bytes(&base), "fingerprint must be deterministic");
6648 let mut dense = base.clone();
6651 for b in dense.iter_mut() {
6652 *b = b.wrapping_add(1);
6653 }
6654 assert_ne!(
6655 h0,
6656 fp_bytes(&dense),
6657 "a fully different tensor slipped through"
6658 );
6659 assert_ne!(h0, fp_bytes(&base[..n - 64]));
6662 let mut small = vec![3u8; 4096];
6665 let hs = fp_bytes(&small);
6666 small[2048] ^= 1;
6667 assert_ne!(hs, fp_bytes(&small), "full hash missed a one-byte change");
6668 for n in [4097usize, 5000, 64 * 64, 1 << 16] {
6670 let v = vec![9u8; n];
6671 let _ = fp_bytes(&v); }
6673 }
6674}
6675
6676pub fn bake_release() {
6680 #[cfg(feature = "gpu")]
6681 crate::gpu_wgpu::bake_release();
6682}
6683
6684pub fn bake_precision_strict(on: bool) {
6688 #[cfg(feature = "gpu")]
6689 crate::gpu_wgpu::bake_precision_strict(on);
6690 #[cfg(not(feature = "gpu"))]
6691 let _ = on;
6692}
6693
6694pub fn hostprof_encode_done(t0: std::time::Instant) {
6700 use std::sync::atomic::{AtomicU64, Ordering};
6701 static ENC: AtomicU64 = AtomicU64::new(0);
6702 static N: AtomicU64 = AtomicU64::new(0);
6703 if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() != Ok("1") {
6704 return;
6705 }
6706 ENC.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);
6707 let n = N.fetch_add(1, Ordering::Relaxed) + 1;
6708 if n % 100 == 0 {
6709 eprintln!(
6710 "hostprof: encode {:.2} ms/token over {n} tokens",
6711 ENC.load(Ordering::Relaxed) as f64 / n as f64 / 1e6
6712 );
6713 }
6714}
6715
6716pub fn hostprof_total(t0: std::time::Instant) {
6717 use std::sync::atomic::{AtomicU64, Ordering};
6718 static TOT: AtomicU64 = AtomicU64::new(0);
6719 static N: AtomicU64 = AtomicU64::new(0);
6720 if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() != Ok("1") {
6721 return;
6722 }
6723 TOT.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);
6724 let n = N.fetch_add(1, Ordering::Relaxed) + 1;
6725 if n % 100 == 0 {
6726 eprintln!(
6727 "hostprof: total {:.2} ms/token over {n} tokens",
6728 TOT.load(Ordering::Relaxed) as f64 / n as f64 / 1e6
6729 );
6730 }
6731}
6732
6733pub fn stageprof(stage: u32, dt: std::time::Duration) {
6737 use std::sync::atomic::{AtomicU64, Ordering};
6738 static NS: [AtomicU64; 4] = [
6739 AtomicU64::new(0),
6740 AtomicU64::new(0),
6741 AtomicU64::new(0),
6742 AtomicU64::new(0),
6743 ];
6744 static N: AtomicU64 = AtomicU64::new(0);
6745 if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() != Ok("1") {
6746 return;
6747 }
6748 NS[stage as usize % 4].fetch_add(dt.as_nanos() as u64, Ordering::Relaxed);
6749 if stage == 1 {
6750 let n = N.fetch_add(1, Ordering::Relaxed) + 1;
6751 if n % 200 == 0 {
6752 eprintln!(
6753 "stageprof: planning {:.2} ms/tok | gdn-item {:.2} ms/tok | attn-item {:.2} ms/tok ({n} tok)",
6754 NS[1].load(Ordering::Relaxed) as f64 / n as f64 / 1e6,
6755 NS[2].load(Ordering::Relaxed) as f64 / n as f64 / 1e6,
6756 NS[3].load(Ordering::Relaxed) as f64 / n as f64 / 1e6
6757 );
6758 }
6759 }
6760}
6761
6762pub fn weight_bytes_dispatched() -> u64 {
6765 let mut total = 0u64;
6766 #[cfg(target_os = "macos")]
6767 {
6768 total += crate::gpu_metal::WEIGHT_BYTES.load(std::sync::atomic::Ordering::Relaxed);
6769 }
6770 #[cfg(feature = "gpu")]
6771 {
6772 total += crate::gpu_wgpu::WEIGHT_BYTES.load(std::sync::atomic::Ordering::Relaxed);
6773 }
6774 total
6775}
6776
6777pub fn weight_bytes_by() -> [u64; 6] {
6780 #[cfg(target_os = "macos")]
6781 {
6782 let mut o = [0u64; 6];
6783 for (i, a) in crate::gpu_metal::WEIGHT_BYTES_BY.iter().enumerate() {
6784 o[i] = a.load(std::sync::atomic::Ordering::Relaxed);
6785 }
6786 return o;
6787 }
6788 #[allow(unreachable_code)]
6789 [0; 6]
6790}
6791
6792#[cfg(test)]
6793mod f16_guard_tests {
6794 use super::*;
6795
6796 #[test]
6799 fn abs_max_or_inf_is_the_magnitude_maximum() {
6800 let mut xs: Vec<f32> = (0..37).map(|i| (i as f32 - 18.0) * 0.5).collect();
6801 assert_eq!(abs_max_or_inf(&xs), 9.0);
6802 xs[36] = -70000.0; assert_eq!(abs_max_or_inf(&xs), 70000.0);
6804 xs[3] = f32::NAN; assert_eq!(abs_max_or_inf(&xs), f32::INFINITY);
6806 xs[3] = 0.0;
6807 xs[35] = f32::NEG_INFINITY;
6808 assert_eq!(abs_max_or_inf(&xs), f32::INFINITY);
6809 assert_eq!(abs_max_or_inf(&[]), 0.0);
6810 assert_eq!(abs_max_or_inf(&[-0.0, -1e-30]), 1e-30);
6811 }
6812}
6813
6814#[cfg(test)]
6815mod probe_warmup_tests {
6816 use super::*;
6817 use std::time::Duration;
6818
6819 fn ms(v: f64) -> Duration {
6820 Duration::from_nanos((v * 1e6) as u64)
6821 }
6822
6823 #[test]
6828 fn one_cold_first_sample_does_not_lose_the_class() {
6829 let p = Probe::new();
6830 probe_record_into(&p, "gemm-nt", None, true, ms(117.01));
6832 probe_record_into(&p, "gemm-nt", None, true, ms(1.1));
6833 probe_record_into(&p, "gemm-nt", None, true, ms(1.0));
6834 probe_record_into(&p, "gemm-nt", None, false, ms(3.19));
6835 probe_record_into(&p, "gemm-nt", None, false, ms(3.20));
6836 assert_eq!(
6837 p.state.load(Ordering::Relaxed),
6838 1,
6839 "the device is 3x faster once warm and must win"
6840 );
6841 }
6842
6843 #[test]
6847 fn the_warmup_is_spent_once_and_never_underflows() {
6848 let p = Probe::new();
6849 for _ in 0..8 {
6850 probe_record_into(&p, "matmat", None, true, ms(10.0));
6851 }
6852 assert_eq!(p.gpu_burn.load(Ordering::Relaxed), 0, "spent, not wrapped");
6853 assert_eq!(
6854 p.gpu_n.load(Ordering::Relaxed),
6855 7,
6856 "one sample burned, the rest counted"
6857 );
6858 }
6859
6860 #[test]
6866 fn a_class_whose_device_always_declines_settles_on_the_host() {
6867 let _probe_guard = probe_test_guard();
6868 let c = OpClass::MatmatWide;
6872 let p = &PROBES[c as usize];
6873 p.state.store(0, Ordering::Relaxed);
6874 p.declines.store(0, Ordering::Relaxed);
6875 for _ in 0..(PROBE_DECLINE_LIMIT - 1) {
6876 probe_note_decline(c);
6877 }
6878 assert_eq!(
6879 p.state.load(Ordering::Relaxed),
6880 0,
6881 "one short of the limit is still a question, not an answer"
6882 );
6883 probe_note_decline(c);
6884 assert_eq!(p.state.load(Ordering::Relaxed), 2, "settled on the host");
6885 assert!(matches!(probe_arm(c), ProbeArm::Cpu));
6886 p.state.store(0, Ordering::Relaxed);
6887 p.declines.store(0, Ordering::Relaxed);
6888 }
6889
6890 #[test]
6893 fn a_slow_device_still_loses_after_the_warmup() {
6894 let p = Probe::new();
6895 for _ in 0..4 {
6896 probe_record_into(&p, "matvec", None, true, ms(40.0));
6897 }
6898 for _ in 0..4 {
6899 probe_record_into(&p, "matvec", None, false, ms(2.0));
6900 }
6901 assert_eq!(p.state.load(Ordering::Relaxed), 2, "host wins on merit");
6902 }
6903}
6904
6905pub(crate) struct ImageStageGuard {
6908 #[cfg(target_os = "macos")]
6909 metal: Option<crate::gpu_metal::ImageStageGuard>,
6910 #[cfg(feature = "gpu")]
6911 wgpu: crate::gpu_wgpu::ImageStageGuard,
6912}
6913
6914pub(crate) fn image_stage_scope() -> ImageStageGuard {
6915 ImageStageGuard {
6916 #[cfg(target_os = "macos")]
6917 metal: if matches!(backend(), Backend::Metal) {
6918 Some(crate::gpu_metal::image_stage_scope())
6919 } else {
6920 None
6921 },
6922 #[cfg(feature = "gpu")]
6923 wgpu: crate::gpu_wgpu::image_stage_scope(),
6924 }
6925}
6926
6927impl ImageStageGuard {
6928 pub(crate) fn track_model(&mut self, uid: u64) {
6929 #[cfg(target_os = "macos")]
6930 if let Some(metal) = &mut self.metal {
6931 metal.track_model(uid);
6932 }
6933 #[cfg(feature = "gpu")]
6934 self.wgpu.track_model(uid);
6935 #[cfg(not(target_os = "macos"))]
6936 let _ = uid;
6937 }
6938}
6939
6940#[derive(Clone, Copy, Debug, PartialEq)]
6960pub struct Qi21Geom {
6961 pub hidden: usize,
6962 pub nh: usize,
6963 pub hd: usize,
6964 pub inter: usize,
6965 pub in_ch: usize,
6966 pub eps: f32,
6967}
6968
6969pub struct Qi21BlockRef<'a> {
6972 pub w: [usize; 7],
6973 pub norm_q: &'a [f32],
6974 pub norm_k: &'a [f32],
6975}
6976
6977pub struct Qi21PrefillArgs<'a> {
6979 pub model: &'a Arc<CmfModel>,
6980 pub geom: Qi21Geom,
6981 pub blocks: &'a [Qi21BlockRef<'a>],
6982 pub img_in: &'a [f32],
6984 pub proj_out: &'a [f32],
6985 pub key: u64,
6986 pub x: &'a [f32],
6988 pub lp: usize,
6989 pub rope_p: (&'a [f32], &'a [f32]),
6991 pub rope_t: (&'a [f32], &'a [f32]),
6992 pub vis: &'a [u32],
6994 pub mods0: &'a [f32],
6996 pub n: usize,
6998}
6999
7000#[allow(unused_variables)]
7002pub fn qi21_prefill(a: &Qi21PrefillArgs) -> bool {
7003 match backend() {
7004 #[cfg(target_os = "macos")]
7005 Backend::Metal => crate::gpu_metal::qi21::prefill(a),
7006 #[cfg(feature = "gpu")]
7007 Backend::Wgpu => crate::gpu_wgpu::qi21::prefill(a),
7008 #[cfg(feature = "cuda")]
7009 Backend::Cuda => crate::gpu_cuda::qi21_prefill(a),
7010 #[allow(unreachable_patterns)]
7011 _ => false,
7012 }
7013}
7014
7015#[allow(unused_variables)]
7017pub fn qi21_step(key: u64, xtok: &[f32], mods: &[f32], fs: &[f32], out: &mut [f32]) -> bool {
7018 match backend() {
7019 #[cfg(target_os = "macos")]
7020 Backend::Metal => crate::gpu_metal::qi21::step(key, xtok, mods, fs, out),
7021 #[cfg(feature = "gpu")]
7022 Backend::Wgpu => crate::gpu_wgpu::qi21::step(key, xtok, mods, fs, out),
7023 #[cfg(feature = "cuda")]
7024 Backend::Cuda => crate::gpu_cuda::qi21_step(key, xtok, mods, fs, out),
7025 #[allow(unreachable_patterns)]
7026 _ => false,
7027 }
7028}
7029
7030#[allow(unused_variables)]
7033pub fn qi21_release_key(key: u64) {
7034 #[cfg(target_os = "macos")]
7035 if matches!(backend(), Backend::Metal) {
7036 crate::gpu_metal::qi21::release_key(key);
7037 }
7038 #[cfg(feature = "gpu")]
7039 crate::gpu_wgpu::qi21::release_key(key);
7040 #[cfg(feature = "cuda")]
7041 if matches!(backend(), Backend::Cuda) {
7042 crate::gpu_cuda::qi21_release_key(key);
7043 }
7044}
7045
7046pub fn qi21_release() {
7049 #[cfg(target_os = "macos")]
7050 if matches!(backend(), Backend::Metal) {
7051 crate::gpu_metal::qi21::release();
7052 }
7053 #[cfg(feature = "gpu")]
7054 {
7055 crate::gpu_wgpu::qi21::release();
7056 crate::gpu_wgpu::qi21_vae::release();
7057 }
7058 #[cfg(feature = "cuda")]
7059 if matches!(backend(), Backend::Cuda) {
7060 crate::gpu_cuda::qi21_release();
7061 }
7062}
7063
7064#[derive(Clone, Copy)]
7067pub struct Qi21VaeConvRef<'a> {
7068 pub w: &'a [f32],
7069 pub b: &'a [f32],
7070 pub ci: usize,
7071 pub co: usize,
7072 pub k: usize,
7073}
7074
7075pub struct Qi21VaeResRef<'a> {
7078 pub g1: &'a [f32],
7079 pub c1: Qi21VaeConvRef<'a>,
7080 pub g2: &'a [f32],
7081 pub c2: Qi21VaeConvRef<'a>,
7082 pub shortcut: Option<Qi21VaeConvRef<'a>>,
7083}
7084
7085pub struct Qi21VaeUpRef<'a> {
7089 pub resnets: Vec<Qi21VaeResRef<'a>>,
7090 pub up: Option<(Qi21VaeConvRef<'a>, usize)>,
7091 pub in_dim: usize,
7092 pub out_dim: usize,
7093}
7094
7095pub struct Qi21VaeDecodeArgs<'a> {
7098 pub key: u64,
7100 pub post_quant: Qi21VaeConvRef<'a>,
7101 pub conv_in: Qi21VaeConvRef<'a>,
7102 pub mid_res: [Qi21VaeResRef<'a>; 2],
7103 pub attn_gamma: &'a [f32],
7106 pub attn_qkv: Qi21VaeConvRef<'a>,
7107 pub attn_proj: Qi21VaeConvRef<'a>,
7108 pub ups: Vec<Qi21VaeUpRef<'a>>,
7109 pub norm_out: &'a [f32],
7110 pub conv_out: Qi21VaeConvRef<'a>,
7111}
7112
7113#[allow(unused_variables)]
7117pub fn qi21_vae_decode(a: &Qi21VaeDecodeArgs, z: &[f32], h: usize, w: usize, out: &mut [f32]) -> bool {
7118 match backend() {
7119 #[cfg(feature = "gpu")]
7120 Backend::Wgpu => crate::gpu_wgpu::qi21_vae::decode(a, z, h, w, out),
7121 #[cfg(feature = "cuda")]
7122 Backend::Cuda => crate::gpu_cuda::qi21_vae_decode(a, z, h, w, out),
7123 #[allow(unreachable_patterns)]
7124 _ => false,
7125 }
7126}
7127
7128#[derive(Clone, Copy)]
7136pub struct ZBlockRef<'a> {
7137 pub wq: usize,
7139 pub wk: usize,
7140 pub wv: usize,
7141 pub wo: usize,
7142 pub w1: usize,
7145 pub w3: usize,
7146 pub w2: usize,
7147 pub norm1: &'a [f32],
7149 pub norm2: &'a [f32],
7150 pub ffn_norm1: &'a [f32],
7152 pub ffn_norm2: &'a [f32],
7153 pub norm_q: &'a [f32],
7155 pub norm_k: &'a [f32],
7156}
7157
7158#[derive(Clone, Copy, Debug, PartialEq)]
7162pub struct ZGeom {
7163 pub hidden: usize,
7164 pub nh: usize,
7165 pub hd: usize,
7166 pub inter: usize,
7167 pub eps: f32,
7168 pub final_eps: f32,
7169 pub patch_dim: usize,
7170}
7171
7172pub struct ZPrepareArgs<'a> {
7176 pub model: &'a Arc<CmfModel>,
7177 pub geom: ZGeom,
7178 pub key: u64,
7181 pub n_img: usize,
7184 pub n_img_p: usize,
7185 pub n_cap_p: usize,
7186 pub grid: (usize, usize),
7189 pub cap: &'a [f32],
7191 pub rope_img: (&'a [f32], &'a [f32]),
7194 pub rope_joint: (&'a [f32], &'a [f32]),
7196 pub x_emb_w: &'a [f32],
7199 pub x_emb_b: &'a [f32],
7200 pub x_pad: &'a [f32],
7201 pub final_w: &'a [f32],
7203 pub final_b: &'a [f32],
7204 pub noise_refiner: &'a [ZBlockRef<'a>],
7206 pub layers: &'a [ZBlockRef<'a>],
7207 pub mods_all: Option<&'a [f32]>,
7213 pub final_scale_all: Option<&'a [f32]>,
7214 pub neg: Option<ZNegArgs<'a>>,
7220}
7221
7222pub struct ZNegArgs<'a> {
7226 pub cap: &'a [f32],
7228 pub n_cap_p: usize,
7229 pub rope_img: (&'a [f32], &'a [f32]),
7231 pub rope_joint: (&'a [f32], &'a [f32]),
7233}
7234
7235pub struct ZStepArgs<'a> {
7237 pub key: u64,
7240 pub step: usize,
7243 pub x_tok: &'a [f32],
7247 pub mods: &'a [f32],
7251 pub final_scale: &'a [f32],
7253 pub out: &'a mut [f32],
7256 pub out_neg: Option<&'a mut [f32]>,
7259}
7260
7261#[allow(unused_variables)]
7265pub fn zimage_prepare(a: &ZPrepareArgs) -> bool {
7266 match backend() {
7267 #[cfg(target_os = "macos")]
7268 Backend::Metal => crate::gpu_metal::zimage::prepare(a),
7269 #[cfg(feature = "gpu")]
7270 Backend::Wgpu => crate::gpu_wgpu::zimage::prepare(a),
7271 #[cfg(feature = "cuda")]
7272 Backend::Cuda => crate::gpu_cuda::zimage_prepare(a),
7273 #[allow(unreachable_patterns)]
7274 _ => false,
7275 }
7276}
7277
7278#[allow(unused_variables)]
7282pub fn zimage_step(a: &mut ZStepArgs) -> bool {
7283 match backend() {
7284 #[cfg(target_os = "macos")]
7285 Backend::Metal => crate::gpu_metal::zimage::step(a),
7286 #[cfg(feature = "gpu")]
7287 Backend::Wgpu => crate::gpu_wgpu::zimage::step(a),
7288 #[cfg(feature = "cuda")]
7289 Backend::Cuda => crate::gpu_cuda::zimage_step(a),
7290 #[allow(unreachable_patterns)]
7291 _ => false,
7292 }
7293}
7294
7295#[allow(unused_variables)]
7300pub fn zimage_preload(
7301 model: &Arc<CmfModel>,
7302 geom: &ZGeom,
7303 noise_refiner: &[ZBlockRef],
7304 layers: &[ZBlockRef],
7305 context_refiner: &[ZBlockRef],
7306) -> bool {
7307 match backend() {
7308 #[cfg(target_os = "macos")]
7309 Backend::Metal => {
7310 crate::gpu_metal::zimage::preload(model, geom, noise_refiner, layers, context_refiner)
7311 }
7312 #[cfg(feature = "gpu")]
7313 Backend::Wgpu => crate::gpu_wgpu::zimage::preload(model, geom, noise_refiner, layers, context_refiner),
7314 #[allow(unreachable_patterns)]
7315 _ => false,
7316 }
7317}
7318
7319pub fn zimage_flush_pipelines() {
7323 #[cfg(feature = "gpu")]
7324 if matches!(backend(), Backend::Wgpu) {
7325 crate::gpu_wgpu::pipeline_cache_flush();
7326 }
7327}
7328
7329pub fn zimage_warmup() -> bool {
7334 match backend() {
7335 #[cfg(target_os = "macos")]
7336 Backend::Metal => crate::gpu_metal::zimage::warmup(),
7337 #[cfg(feature = "gpu")]
7338 Backend::Wgpu => crate::gpu_wgpu::zimage::warmup(),
7339 #[allow(unreachable_patterns)]
7340 _ => false,
7341 }
7342}
7343
7344#[allow(unused_variables)]
7348pub fn vae_prewarm(a: &crate::vae::VaeChainArgs) -> bool {
7349 match backend() {
7350 #[cfg(target_os = "macos")]
7351 Backend::Metal => crate::gpu_metal::zimage::vae_prewarm(a),
7352 #[cfg(feature = "gpu")]
7353 Backend::Wgpu => crate::gpu_wgpu::zimage::vae_prewarm(a),
7354 #[allow(unreachable_patterns)]
7355 _ => false,
7356 }
7357}
7358
7359pub fn zimage_release_dit() {
7362 #[cfg(target_os = "macos")]
7363 crate::gpu_metal::zimage::release_dit();
7364 #[cfg(feature = "gpu")]
7365 crate::gpu_wgpu::zimage::release_dit();
7366 #[cfg(feature = "cuda")]
7367 if matches!(backend(), Backend::Cuda) {
7368 crate::gpu_cuda::zimage_release();
7369 }
7370}
7371
7372pub fn zimage_release() {
7377 #[cfg(target_os = "macos")]
7378 crate::gpu_metal::zimage::release();
7379 #[cfg(feature = "gpu")]
7380 crate::gpu_wgpu::zimage::release();
7381 #[cfg(feature = "cuda")]
7382 if matches!(backend(), Backend::Cuda) {
7383 crate::gpu_cuda::zimage_release();
7384 }
7385}
7386
7387#[allow(unused_variables)]
7393pub fn zimage_refine_caption(
7394 model: &Arc<CmfModel>,
7395 geom: &ZGeom,
7396 blocks: &[ZBlockRef],
7397 rope_cap: (&[f32], &[f32]),
7398 cap: &mut [f32],
7399) -> bool {
7400 match backend() {
7401 #[cfg(target_os = "macos")]
7402 Backend::Metal => {
7403 crate::gpu_metal::zimage::refine_caption(model, geom, blocks, rope_cap, cap)
7404 }
7405 #[cfg(feature = "gpu")]
7406 Backend::Wgpu => {
7407 crate::gpu_wgpu::zimage::refine_caption(model, geom, blocks, rope_cap, cap)
7408 }
7409 #[allow(unreachable_patterns)]
7410 _ => false,
7411 }
7412}
7413
7414#[allow(unused_variables)]
7420pub fn vae_decode_chain(
7421 a: &crate::vae::VaeChainArgs,
7422 z: &[f32],
7423 h: usize,
7424 w: usize,
7425 out: &mut [f32],
7426) -> bool {
7427 match backend() {
7428 #[cfg(target_os = "macos")]
7429 Backend::Metal => crate::gpu_metal::zimage::vae_decode_chain(a, z, h, w, out),
7430 #[cfg(feature = "gpu")]
7431 Backend::Wgpu => crate::gpu_wgpu::zimage::vae_decode_chain(a, z, h, w, out),
7432 #[cfg(feature = "cuda")]
7433 Backend::Cuda => crate::gpu_cuda::flux_vae_chain(a, z, h, w, out),
7434 #[allow(unreachable_patterns)]
7435 _ => false,
7436 }
7437}
7438
7439
7440pub trait S2vStepper {
7444 fn step(&mut self, step: usize, chunk: usize, x: &[f32], memory: &[Vec<f32>; 3]) -> Result<Vec<f32>, String>;
7448}
7449
7450#[allow(unused_variables)]
7452pub fn s2v_prepare(
7453 dit: &crate::s2v::S2vDit,
7454 g: &crate::s2v::S2vGeom,
7455 cond: &crate::s2vgen::S2vCond,
7456 ts: &[f32],
7457 sf: [f32; 3],
7458) -> Option<Box<dyn S2vStepper>> {
7459 match backend() {
7460 #[cfg(feature = "gpu")]
7461 Backend::Wgpu => crate::gpu_wgpu::s2v::prepare(dit, g, cond, ts, sf).map(|d| Box::new(d) as Box<dyn S2vStepper>),
7462 #[cfg(target_os = "macos")]
7463 Backend::Metal => crate::gpu_metal::s2v::prepare(dit, g, cond, ts, sf).map(|d| Box::new(d) as Box<dyn S2vStepper>),
7464 #[cfg(feature = "cuda")]
7465 Backend::Cuda => crate::gpu_cuda::s2v_prepare(dit, g, cond, ts, sf).map(|d| Box::new(d) as Box<dyn S2vStepper>),
7466 #[allow(unreachable_patterns)]
7467 _ => None,
7468 }
7469}
7470
7471pub fn s2v_release() {
7473 #[cfg(feature = "gpu")]
7474 crate::gpu_wgpu::s2v_vae::release();
7475 #[cfg(target_os = "macos")]
7476 crate::gpu_metal::s2v::release();
7477 #[cfg(feature = "cuda")]
7478 if matches!(backend(), Backend::Cuda) {
7479 crate::gpu_cuda::s2v_vae_release();
7480 }
7481}
7482
7483#[allow(unused_variables)]
7485pub fn s2v_vae_decode(vae: &crate::s2v_vae::S2vVae, z: &crate::ltxvae::Vol) -> Option<crate::ltxvae::Vol> {
7486 match backend() {
7487 #[cfg(feature = "gpu")]
7488 Backend::Wgpu => crate::gpu_wgpu::s2v_vae::decode(vae, z),
7489 #[cfg(target_os = "macos")]
7490 Backend::Metal => crate::gpu_metal::s2v::decode(vae, z),
7491 #[cfg(feature = "cuda")]
7492 Backend::Cuda => crate::gpu_cuda::s2v_vae_decode(vae, z),
7493 #[allow(unreachable_patterns)]
7494 _ => None,
7495 }
7496}
7497
7498#[allow(unused_variables)]
7501pub fn sam3_trunk(m: &std::sync::Arc<cortiq_core::CmfModel>, pv: &[f32], pos_skip_cls: bool) -> Option<Vec<f32>> {
7502 match backend() {
7503 #[cfg(feature = "cuda")]
7504 Backend::Cuda => crate::gpu_cuda::sam3_trunk(m, pv, pos_skip_cls),
7505 #[cfg(feature = "gpu")]
7506 Backend::Wgpu => crate::gpu_wgpu::h3::sam3_trunk(m, pv, pos_skip_cls),
7507 #[allow(unreachable_patterns)]
7508 _ => None,
7509 }
7510}
7511
7512#[allow(unused_variables)]
7516pub fn plane_matmat(model: &Arc<CmfModel>, idx: usize, xs: &[f32], b: usize, rows: usize, cols: usize, out: &mut [f32]) -> bool {
7517 match backend() {
7518 #[cfg(feature = "cuda")]
7519 Backend::Cuda => crate::gpu_cuda::h3_matmat(model, idx, xs, b, rows, cols, out),
7520 #[allow(unreachable_patterns)]
7521 _ => false,
7522 }
7523}
7524
7525#[allow(unused_variables, clippy::too_many_arguments)]
7528pub fn sam3_attn_sep(q: &[f32], k: &[f32], v: &[f32], n_q: usize, n_k: usize, dim: usize, heads: usize, scale: f32, out: &mut [f32]) -> bool {
7529 if !enabled_here() {
7530 return false;
7531 }
7532 match backend() {
7533 #[cfg(feature = "cuda")]
7534 Backend::Cuda => crate::gpu_cuda::sam3_attn_sep(q, k, v, n_q, n_k, dim, heads, scale, out),
7535 #[allow(unreachable_patterns)]
7536 _ => false,
7537 }
7538}
7539
7540#[allow(unused_variables)]
7542pub fn sam3_mm(a: &[f32], b: &[f32], m: usize, k: usize, n: usize) -> Option<Vec<f32>> {
7543 if !enabled_here() {
7544 return None;
7545 }
7546 match backend() {
7547 #[cfg(feature = "cuda")]
7548 Backend::Cuda => crate::gpu_cuda::sam3_mm(a, b, m, k, n),
7549 #[allow(unreachable_patterns)]
7550 _ => None,
7551 }
7552}
7553
7554#[allow(unused_variables)]
7558pub fn sam3_text(m: &Arc<CmfModel>, x: &mut [f32], cm: &[f32]) -> bool {
7559 if !enabled_here() {
7560 return false;
7561 }
7562 match backend() {
7563 #[cfg(feature = "cuda")]
7564 Backend::Cuda => crate::gpu_cuda::sam3_text(m, x, cm),
7565 #[allow(unreachable_patterns)]
7566 _ => false,
7567 }
7568}
7569
7570#[allow(unused_variables, clippy::too_many_arguments)]
7572pub fn sam3_conv2d(w: &[f32], b: &[f32], x: &[f32], ci: usize, h: usize, wid: usize, kh: usize, kw: usize, stride: usize, pad: usize) -> Option<Vec<f32>> {
7573 if !enabled_here() {
7574 return None;
7575 }
7576 match backend() {
7577 #[cfg(feature = "cuda")]
7578 Backend::Cuda => crate::gpu_cuda::sam3_conv2d(w, b, x, ci, h, wid, kh, kw, stride, pad),
7579 #[allow(unreachable_patterns)]
7580 _ => None,
7581 }
7582}
7583
7584#[allow(unused_variables)]
7586pub fn sam3_convt2x2(w: &[f32], b: &[f32], x: &[f32], ci: usize, h: usize, wid: usize) -> Option<Vec<f32>> {
7587 if !enabled_here() {
7588 return None;
7589 }
7590 match backend() {
7591 #[cfg(feature = "cuda")]
7592 Backend::Cuda => crate::gpu_cuda::sam3_convt2x2(w, b, x, ci, h, wid),
7593 #[allow(unreachable_patterns)]
7594 _ => None,
7595 }
7596}
7597
7598#[allow(unused_variables, clippy::too_many_arguments)]
7601pub fn sam3_attn_core(q: &[f32], k: &[f32], v: &[f32], n_q: usize, n_k: usize, dim: usize, heads: usize, mode: i32, mask: &[f32], scale: f32, out: &mut [f32]) -> bool {
7602 if !enabled_here() {
7603 return false;
7604 }
7605 match backend() {
7606 #[cfg(feature = "cuda")]
7607 Backend::Cuda => crate::gpu_cuda::sam3_attn_core(q, k, v, n_q, n_k, dim, heads, mode, mask, scale, out),
7608 #[allow(unreachable_patterns)]
7609 _ => false,
7610 }
7611}
7612
7613#[allow(unused_variables)]
7615pub fn s2v_vae_encode(enc: &crate::s2v_vae::S2vVaeEncoder, img: &crate::ltxvae::Vol) -> Option<(crate::ltxvae::Vol, crate::ltxvae::Vol)> {
7616 match backend() {
7617 #[cfg(feature = "gpu")]
7618 Backend::Wgpu => crate::gpu_wgpu::s2v_vae::encode(enc, img),
7619 #[cfg(target_os = "macos")]
7620 Backend::Metal => crate::gpu_metal::s2v::encode(enc, img),
7621 #[cfg(feature = "cuda")]
7622 Backend::Cuda => crate::gpu_cuda::s2v_vae_encode(enc, img),
7623 #[allow(unreachable_patterns)]
7624 _ => None,
7625 }
7626}
7627
7628#[allow(unused_variables)]
7630pub fn s2v_check_forward(dit: &crate::s2v::S2vDit, i: &crate::s2v::S2vInput<'_>) -> Option<Vec<f32>> {
7631 let cond = crate::s2vgen::S2vCond {
7632 text: i.text_feats.to_vec(),
7633 pooled: i.pooled.to_vec(),
7634 audio: vec![i.audio_feats.to_vec()],
7635 reference: i.reference.to_vec(),
7636 height: i.geom.lh * 8,
7637 width: i.geom.lw * 8,
7638 };
7639 let mut dev = s2v_prepare(dit, &i.geom, &cond, &[i.t], i.scale_factor)?;
7640 let memory = [i.mem1.to_vec(), i.mem2.to_vec(), i.mem4.to_vec()];
7641 dev.step(0, 0, i.x, &memory).ok()
7642}