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
1294#[cfg(test)]
1304static TEST_GPU_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());
1305
1306#[cfg(test)]
1307thread_local! {
1308 static TEST_GPU_ENV_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1309}
1310
1311#[cfg(test)]
1313pub(crate) struct TestGpuEnv {
1314 previous: Option<std::ffi::OsString>,
1315 _lock: Option<std::sync::MutexGuard<'static, ()>>,
1316}
1317
1318#[cfg(test)]
1319fn test_gpu_env_enter(value: Option<&str>) -> TestGpuEnv {
1320 let lock = (TEST_GPU_ENV_DEPTH.get() == 0)
1321 .then(|| TEST_GPU_ENV.lock().unwrap_or_else(|e| e.into_inner()));
1322 TEST_GPU_ENV_DEPTH.set(TEST_GPU_ENV_DEPTH.get() + 1);
1323 let previous = std::env::var_os("CMF_GPU");
1324 if let Some(value) = value {
1325 unsafe { std::env::set_var("CMF_GPU", value) };
1326 }
1327 TestGpuEnv { previous, _lock: lock }
1328}
1329
1330#[cfg(test)]
1332pub(crate) fn test_gpu_env(value: &str) -> TestGpuEnv {
1333 test_gpu_env_enter(Some(value))
1334}
1335
1336#[cfg(all(test, feature = "gpu"))]
1339pub(crate) fn test_gpu_env_hold() -> TestGpuEnv {
1340 test_gpu_env_enter(None)
1341}
1342
1343#[cfg(test)]
1344impl Drop for TestGpuEnv {
1345 fn drop(&mut self) {
1346 unsafe {
1347 match self.previous.take() {
1348 Some(value) => std::env::set_var("CMF_GPU", value),
1349 None => std::env::remove_var("CMF_GPU"),
1350 }
1351 }
1352 TEST_GPU_ENV_DEPTH.set(TEST_GPU_ENV_DEPTH.get() - 1);
1353 }
1354}
1355
1356pub fn enabled() -> bool {
1357 !GPU_LOST.load(std::sync::atomic::Ordering::Relaxed) && !GPU_PAUSED.paused() && backend() != Backend::None
1358}
1359
1360static GPU_LOST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1365
1366pub fn device_lost() -> bool {
1368 GPU_LOST.load(std::sync::atomic::Ordering::Relaxed)
1369}
1370
1371pub fn mark_lost(why: &str) {
1373 if !GPU_LOST.swap(true, std::sync::atomic::Ordering::Relaxed) {
1374 tracing::error!("GPU device lost ({why}): the rest of this run stays on the CPU");
1375 }
1376}
1377
1378#[cfg(test)]
1379mod pause_gate_tests {
1380 use super::PauseGate;
1381
1382 #[test]
1385 fn pause_holds_until_the_last_guard() {
1386 let g = PauseGate::new();
1387 assert!(!g.paused());
1388 g.enter();
1389 g.enter();
1390 g.leave();
1391 assert!(g.paused(), "one holder left, the other's pause was lifted");
1392 g.leave();
1393 assert!(!g.paused());
1394 }
1395}
1396
1397pub fn wgpu_active() -> bool {
1411 #[cfg(feature = "gpu")]
1412 {
1413 matches!(backend(), Backend::Wgpu)
1414 }
1415 #[cfg(not(feature = "gpu"))]
1416 {
1417 false
1418 }
1419}
1420
1421pub fn default_device() -> usize {
1428 static D: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1429 *D.get_or_init(|| {
1430 std::env::var("CMF_GPU_ADAPTER")
1431 .ok()
1432 .and_then(|v| v.trim().parse::<usize>().ok())
1433 .unwrap_or(0)
1434 })
1435}
1436
1437thread_local! {
1438 static CUR_DEV: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
1439}
1440
1441pub fn current_device() -> usize {
1443 CUR_DEV.with(|c| c.get()).unwrap_or_else(default_device)
1444}
1445
1446pub fn set_current_device(i: usize) {
1450 CUR_DEV.with(|c| c.set(Some(i)));
1451}
1452
1453pub fn with_device<R>(dev: usize, f: impl FnOnce() -> R) -> R {
1455 let prev = CUR_DEV.with(|c| c.replace(Some(dev)));
1456 let r = f();
1457 CUR_DEV.with(|c| c.set(prev));
1458 r
1459}
1460
1461pub fn device_count() -> usize {
1464 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
1465 {
1466 return crate::gpu_wgpu::adapter_count();
1467 }
1468 #[cfg(not(all(feature = "gpu", not(target_os = "macos"))))]
1469 {
1470 usize::from(backend_available())
1471 }
1472}
1473
1474pub fn vram_budget() -> u64 {
1478 #[cfg(feature = "cuda")]
1479 if backend() == Backend::Cuda {
1480 return crate::gpu_cuda::vram_budget();
1481 }
1482 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
1483 {
1484 return crate::gpu_wgpu::device_vram_budget();
1485 }
1486 #[cfg(all(feature = "gpu", target_os = "macos"))]
1489 if backend() == Backend::Wgpu {
1490 return crate::gpu_wgpu::device_vram_budget();
1491 }
1492 #[cfg(not(all(feature = "gpu", not(target_os = "macos"))))]
1493 {
1494 if backend_available() { u64::MAX } else { 0 }
1495 }
1496}
1497
1498pub fn active_device() -> Option<String> {
1503 match backend() {
1504 #[cfg(feature = "cuda")]
1505 Backend::Cuda => crate::gpu_cuda::device_name().map(|n| format!("{n} / CUDA")),
1506 #[cfg(feature = "gpu")]
1507 Backend::Wgpu => crate::gpu_wgpu::device_label(),
1508 _ => None,
1509 }
1510}
1511
1512pub fn device_bytes_in_use() -> Option<u64> {
1515 match backend() {
1516 #[cfg(feature = "cuda")]
1517 Backend::Cuda => crate::gpu_cuda::device_bytes_in_use(),
1518 #[cfg(feature = "gpu")]
1519 Backend::Wgpu => crate::gpu_wgpu::device_bytes_in_use(),
1520 _ => None,
1521 }
1522}
1523
1524pub fn resident_bytes() -> u64 {
1528 #[cfg(feature = "cuda")]
1529 if backend() == Backend::Cuda {
1530 return crate::gpu_cuda::resident_bytes();
1531 }
1532 #[cfg(feature = "gpu")]
1533 {
1534 if backend() == Backend::Wgpu {
1535 return crate::gpu_wgpu::resident_bytes();
1536 }
1537 }
1538 0
1539}
1540
1541pub fn o1_device_stats(kv_id: u64) -> (usize, u64) {
1545 #[cfg(feature = "gpu")]
1546 {
1547 if backend() == Backend::Wgpu {
1548 return crate::gpu_wgpu::o1_device_stats(kv_id);
1549 }
1550 #[cfg(feature = "cuda")]
1551 if backend() == Backend::Cuda {
1552 return crate::gpu_cuda::o1_device_stats(kv_id);
1553 }
1554 }
1555 let _ = kv_id;
1556 (0, 0)
1557}
1558
1559pub fn upload_bytes() -> u64 {
1563 #[cfg(feature = "gpu")]
1564 {
1565 return crate::gpu_wgpu::UPLOAD_BYTES.load(std::sync::atomic::Ordering::Relaxed);
1566 }
1567 #[cfg(not(feature = "gpu"))]
1568 0
1569}
1570
1571pub fn upload_bandwidth_probe(block: usize, rounds: usize) -> Option<f64> {
1575 #[cfg(feature = "gpu")]
1576 {
1577 return crate::gpu_wgpu::upload_bandwidth_probe(block, rounds);
1578 }
1579 let _ = (block, rounds);
1580 None
1581}
1582
1583#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1595pub enum GraphPhase {
1596 Prefill,
1597 Decode,
1598}
1599
1600pub fn wgpu_graph_on(phase: GraphPhase) -> bool {
1608 match std::env::var("CMF_GPU_WGPU_GRAPH").ok().as_deref() {
1609 Some("0") => false,
1610 Some("prefill") => phase == GraphPhase::Prefill,
1611 Some(_) => true,
1612 None => {
1613 if wgpu_graph_default() {
1614 return true;
1615 }
1616 let _ = phase;
1621 false
1622 }
1623 }
1624}
1625
1626pub fn batched_attend_tiled() -> bool {
1629 #[cfg(feature = "cuda")]
1631 if backend() == Backend::Cuda {
1632 return true;
1633 }
1634 #[cfg(feature = "gpu")]
1635 {
1636 crate::gpu_wgpu::batched_attend_tiled()
1637 }
1638 #[cfg(not(feature = "gpu"))]
1639 {
1640 false
1641 }
1642}
1643
1644pub fn cuda_batch_rows() -> Option<usize> {
1647 #[cfg(feature = "cuda")]
1648 if backend() == Backend::Cuda {
1649 return Some(crate::gpu_cuda::batch_rows());
1650 }
1651 None
1652}
1653
1654#[allow(unused_variables)]
1658pub fn cuda_plane_fits(model: &Arc<CmfModel>, idx: usize) -> bool {
1659 #[cfg(feature = "cuda")]
1660 {
1661 crate::gpu_cuda::h3_plane_fits(model, idx)
1662 }
1663 #[cfg(not(feature = "cuda"))]
1664 {
1665 false
1666 }
1667}
1668
1669#[allow(unused_variables)]
1672pub fn planes_may_grow(on: bool) {
1673 #[cfg(feature = "cuda")]
1674 crate::gpu_cuda::h3_planes_grow(on);
1675}
1676
1677pub fn hy4_capture_begin(layers: usize, dim: usize, ne: usize) -> bool {
1680 #[cfg(feature = "cuda")]
1681 if backend() == Backend::Cuda {
1682 return crate::gpu_cuda::hy4_capture_begin(layers, dim, ne);
1683 }
1684 let _ = (layers, dim, ne);
1685 false
1686}
1687
1688pub fn hy4_capture_take() -> Option<Vec<(Vec<f32>, Vec<f32>)>> {
1690 #[cfg(feature = "cuda")]
1691 if backend() == Backend::Cuda {
1692 return crate::gpu_cuda::hy4_capture_take();
1693 }
1694 None
1695}
1696
1697pub fn metal_active() -> bool {
1699 #[cfg(target_os = "macos")]
1700 {
1701 backend() == Backend::Metal
1702 }
1703 #[cfg(not(target_os = "macos"))]
1704 {
1705 false
1706 }
1707}
1708
1709pub fn cuda_active() -> bool {
1710 #[cfg(feature = "cuda")]
1711 {
1712 backend() == Backend::Cuda
1713 }
1714 #[cfg(not(feature = "cuda"))]
1715 {
1716 false
1717 }
1718}
1719
1720pub fn wgpu_graph_default() -> bool {
1721 #[cfg(feature = "cuda")]
1723 if backend() == Backend::Cuda {
1724 return true;
1725 }
1726 #[cfg(feature = "gpu")]
1727 {
1728 matches!(backend(), Backend::Wgpu)
1734 && (crate::gpu_wgpu::discrete_active()
1735 || (cfg!(target_os = "macos") && crate::gpu_wgpu::adapter_up()))
1736 }
1737 #[cfg(not(feature = "gpu"))]
1738 {
1739 false
1740 }
1741}
1742
1743#[allow(clippy::too_many_arguments, unused_variables)]
1745pub fn q8_matvec_range(
1746 model: &Arc<CmfModel>,
1747 idx: usize,
1748 row0: usize,
1749 row_scale: &[f32],
1750 xs: &[f32],
1751 rows: usize,
1752 cols: usize,
1753 out: &mut [f32],
1754) -> bool {
1755 match backend() {
1756 #[cfg(target_os = "macos")]
1757 Backend::Metal => {
1758 crate::gpu_metal::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
1759 }
1760 #[cfg(feature = "gpu")]
1761 Backend::Wgpu => {
1762 crate::gpu_wgpu::q8_matvec_range(model, idx, row0, row_scale, xs, rows, cols, out)
1763 }
1764 Backend::None => false,
1765 #[cfg(feature = "cuda")]
1766 Backend::Cuda => false,
1767 }
1768}
1769
1770pub(crate) fn q82_short_rows(
1772 model: &Arc<CmfModel>,
1773 idx: usize,
1774 xs: &[f32],
1775 b: usize,
1776 rows: usize,
1777 cols: usize,
1778 out: &mut [f32],
1779) -> bool {
1780 #[cfg(feature = "gpu")]
1781 if enabled_here() && backend() == Backend::Wgpu {
1782 return crate::gpu_wgpu::q82_short_rows(model, idx, xs, b, rows, cols, out);
1783 }
1784 let _ = (model, idx, xs, b, rows, cols, out);
1785 false
1786}
1787
1788#[allow(clippy::too_many_arguments, unused_variables)]
1791#[allow(clippy::too_many_arguments)]
1795pub fn q8_matmat_2f(
1796 model: &Arc<CmfModel>,
1797 idx: usize,
1798 row_scale: &[f32],
1799 col_field: &[f32],
1800 xs: &[f32],
1801 b: usize,
1802 rows: usize,
1803 cols: usize,
1804 out: &mut [f32],
1805) -> bool {
1806 #[allow(unreachable_patterns)]
1807 match backend() {
1808 #[cfg(feature = "gpu")]
1809 Backend::Wgpu => {
1810 crate::gpu_wgpu::q8_matmat_2f(model, idx, row_scale, col_field, xs, b, rows, cols, out)
1811 }
1812 #[cfg(feature = "cuda")]
1814 Backend::Cuda => crate::gpu_cuda::h3_matmat(model, idx, xs, b, rows, cols, out),
1815 _ => false,
1816 }
1817}
1818
1819pub fn q8_matmat(
1820 model: &Arc<CmfModel>,
1821 idx: usize,
1822 row_scale: &[f32],
1823 pre: &[f32],
1824 b: usize,
1825 rows: usize,
1826 cols: usize,
1827 out: &mut [f32],
1828) -> bool {
1829 match backend() {
1830 #[cfg(target_os = "macos")]
1831 Backend::Metal => {
1832 crate::gpu_metal::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out)
1833 }
1834 #[cfg(feature = "gpu")]
1835 Backend::Wgpu => crate::gpu_wgpu::q8_matmat(model, idx, row_scale, pre, b, rows, cols, out),
1836 Backend::None => false,
1837 #[cfg(feature = "cuda")]
1838 Backend::Cuda => false,
1839 }
1840}
1841
1842#[allow(unused_variables)]
1845pub fn q1_matvec(
1846 model: &Arc<CmfModel>,
1847 idx: usize,
1848 xs: &[f32],
1849 rows: usize,
1850 cols: usize,
1851 out: &mut [f32],
1852) -> bool {
1853 match backend() {
1854 #[cfg(target_os = "macos")]
1855 Backend::Metal => crate::gpu_metal::q1_matvec(model, idx, xs, rows, cols, out),
1856 #[cfg(feature = "gpu")]
1857 Backend::Wgpu => crate::gpu_wgpu::q1_matvec(model, idx, xs, rows, cols, out),
1858 Backend::None => false,
1859 #[cfg(feature = "cuda")]
1860 Backend::Cuda => false,
1861 }
1862}
1863
1864#[allow(unused_variables)]
1868pub fn q1g_matvec(
1869 model: &Arc<CmfModel>,
1870 idx: usize,
1871 xs: &[f32],
1872 rows: usize,
1873 cols: usize,
1874 out: &mut [f32],
1875) -> bool {
1876 match backend() {
1877 #[cfg(target_os = "macos")]
1878 Backend::Metal => crate::gpu_metal::q1g_matvec(model, idx, xs, rows, cols, out),
1879 #[cfg(feature = "gpu")]
1880 Backend::Wgpu => crate::gpu_wgpu::q1g_matvec(model, idx, xs, rows, cols, out),
1881 Backend::None => false,
1882 #[cfg(feature = "cuda")]
1883 Backend::Cuda => false,
1884 }
1885}
1886
1887#[allow(clippy::too_many_arguments)]
1891pub fn attn_dropin(
1892 model: &Arc<CmfModel>,
1893 kv_id: u64,
1894 layer: usize,
1895 normed: &[f32],
1896 wq_idx: usize,
1897 wk_idx: usize,
1898 wv_idx: usize,
1899 wo_idx: usize,
1900 q_norm: Option<&[f32]>,
1901 k_norm: Option<&[f32]>,
1902 late_qk_norm: bool,
1903 invf: &[f32],
1904 nh: usize,
1905 nkv: usize,
1906 hd: usize,
1907 rd: usize,
1908 hidden: usize,
1909 pos: usize,
1910 cap: usize,
1911 gemma: bool,
1912 eps: f32,
1913 cpu_k: &[Vec<f32>],
1914 cpu_v: &[Vec<f32>],
1915 out: &mut [f32],
1916) -> bool {
1917 match backend() {
1918 #[cfg(feature = "gpu")]
1919 Backend::Wgpu => crate::gpu_wgpu::attn_dropin_gpu(
1920 model, kv_id, layer, normed, wq_idx, wk_idx, wv_idx, wo_idx, q_norm, k_norm,
1921 late_qk_norm, invf, nh, nkv, hd, rd, hidden, pos, cap, gemma, eps, cpu_k, cpu_v, out,
1922 ),
1923 #[allow(unused_variables)]
1924 _ => false,
1925 }
1926}
1927
1928#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1932pub enum GraphPrismOp {
1933 None,
1934 Forward,
1935 InverseEmbedding,
1936}
1937
1938pub const GRAPH_KIND_BLR: u8 = 11;
1942
1943pub struct GraphW<'a> {
1947 pub idx: usize,
1948 pub kind: u8,
1949 pub row_scale: &'a [f32],
1950 pub data: &'a [f32],
1951 pub prism: GraphPrismOp,
1952 pub affine: bool,
1953}
1954
1955pub enum GraphAttn<'a> {
1958 Full {
1959 wq: GraphW<'a>,
1960 wk: GraphW<'a>,
1961 wv: GraphW<'a>,
1962 wo: GraphW<'a>,
1963 q_norm: Option<&'a [f32]>,
1964 k_norm: Option<&'a [f32]>,
1965 late_qk_norm: bool,
1967 bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
1969 output_gate: bool,
1972 cpu_k: &'a [Vec<f32>],
1973 cpu_v: &'a [Vec<f32>],
1974 cpu_base: usize,
1978 geom: Option<GraphAttnGeom<'a>>,
1985 head_gate: Option<GraphW<'a>>,
1990 },
1991 Gdn {
1992 qkv: GraphW<'a>,
1993 z: GraphW<'a>,
1994 a: GraphW<'a>,
1995 b: GraphW<'a>,
1996 out: GraphW<'a>,
1997 conv1d: &'a [f32],
1998 a_log: &'a [f32],
1999 dt_bias: &'a [f32],
2000 norm: &'a [f32],
2001 nv: usize,
2002 nk: usize,
2003 dk: usize,
2004 dv: usize,
2005 kk: usize,
2006 cpu_state: &'a [f32],
2011 preview: Option<GdnPreviewW<'a>>,
2014 },
2015 ShortConv {
2022 inp: GraphW<'a>,
2024 out: GraphW<'a>,
2026 taps: &'a [f32],
2029 kernel: usize,
2030 cpu_state: &'a [f32],
2034 },
2035 Kda {
2040 q: GraphW<'a>,
2041 k: GraphW<'a>,
2042 v: GraphW<'a>,
2043 conv_q: &'a [f32],
2046 conv_k: &'a [f32],
2047 conv_v: &'a [f32],
2048 f_a: GraphW<'a>,
2050 f_b: GraphW<'a>,
2051 dt_bias: &'a [f32],
2052 a_log: &'a [f32],
2054 b: GraphW<'a>,
2056 g_a: GraphW<'a>,
2058 g_b: Option<GraphW<'a>>,
2059 o_norm: &'a [f32],
2061 out: GraphW<'a>,
2062 nh: usize,
2063 dk: usize,
2064 dv: usize,
2065 kk: usize,
2066 lower_bound: Option<f32>,
2068 cpu_state: &'a [f32],
2070 },
2071 Mla {
2077 q_a: Option<GraphW<'a>>,
2078 q_a_norm: Option<&'a [f32]>,
2079 q: GraphW<'a>,
2080 kv_a: GraphW<'a>,
2082 kv_a_norm: &'a [f32],
2083 kv_b: GraphW<'a>,
2085 o: GraphW<'a>,
2086 nh: usize,
2087 rope: usize,
2088 nope: usize,
2089 v_dim: usize,
2090 lora: usize,
2091 scale: f32,
2092 no_rope: bool,
2094 cpu_k: &'a [Vec<f32>],
2095 cpu_v: &'a [Vec<f32>],
2096 cpu_base: usize,
2097 dsa: Option<GraphDsa<'a>>,
2100 hy: Option<GraphMlaHy<'a>>,
2105 },
2106}
2107
2108pub struct GraphMlaHy<'a> {
2115 pub gate: GraphW<'a>,
2117 pub sinks: &'a [f32],
2118 pub window: Option<usize>,
2119 pub invf: &'a [f32],
2120 pub indexer: Option<GraphHyIndexer<'a>>,
2121}
2122
2123pub struct GraphHyIndexer<'a> {
2130 pub q: GraphW<'a>,
2132 pub hw: &'a [f32],
2134 pub tk: &'a [f32],
2135 pub tk_norm: &'a [f32],
2136 pub kv: &'a [f32],
2138 pub kg: &'a [f32],
2139 pub k_norm: &'a [f32],
2140 pub ape: &'a [f32],
2142 pub ih: usize,
2143 pub id: usize,
2144 pub ratio: usize,
2145 pub group_topk: usize,
2146 pub kv_b: &'a [f32],
2148}
2149
2150pub struct GraphDsa<'a> {
2156 pub index_q: GraphW<'a>,
2158 pub index_k: GraphW<'a>,
2160 pub pool_gate: GraphW<'a>,
2162 pub index_weights: GraphW<'a>,
2164 pub k_norm: &'a [f32],
2165 pub k_bias: &'a [f32],
2166 pub ape: &'a [f32],
2168 pub kv_b: &'a [f32],
2170 pub ih: usize,
2171 pub id: usize,
2172 pub topk: usize,
2173 pub kpool: usize,
2174}
2175
2176#[derive(Clone, Copy)]
2181pub struct GraphAttnGeom<'a> {
2182 pub nkv: usize,
2184 pub hd: usize,
2188 pub dv: usize,
2190 pub rd: usize,
2192 pub invf: &'a [f32],
2194 pub rope_scale: f32,
2199 pub window: Option<usize>,
2202 pub sink: Option<&'a [f32]>,
2205 pub v_norm: bool,
2208 pub dash: Option<GraphDash<'a>>,
2211 pub vres: Option<(f32, &'a [f32])>,
2215 pub route: Option<GraphBlockRoute<'a>>,
2218}
2219
2220#[derive(Clone, Copy)]
2230pub struct GraphBlockRoute<'a> {
2231 pub q: &'a [f32],
2232 pub k: &'a [f32],
2233 pub q_norm: &'a [f32],
2234 pub k_norm: &'a [f32],
2235 pub block: usize,
2236 pub prefix: usize,
2237 pub local: usize,
2238 pub remote: usize,
2239}
2240
2241impl GraphBlockRoute<'_> {
2242 pub fn dense_range(&self) -> usize {
2244 (self.prefix + self.local + self.remote) * self.block
2245 }
2246}
2247
2248static WGPU_EXTRA_RESERVE: AtomicU64 = AtomicU64::new(0);
2249
2250pub fn wgpu_reserve_at_least(bytes: u64) {
2255 WGPU_EXTRA_RESERVE.fetch_max(bytes, Ordering::Relaxed);
2256}
2257
2258pub(crate) fn wgpu_extra_reserve() -> u64 {
2259 WGPU_EXTRA_RESERVE.load(Ordering::Relaxed)
2260}
2261
2262static WGPU_WEIGHTS_FLOOR: AtomicU64 = AtomicU64::new(0);
2263
2264pub fn wgpu_keep_at_least(bytes: u64) {
2271 WGPU_WEIGHTS_FLOOR.fetch_max(bytes, Ordering::Relaxed);
2272}
2273
2274pub(crate) fn wgpu_weights_floor() -> u64 {
2275 WGPU_WEIGHTS_FLOOR.load(Ordering::Relaxed)
2276}
2277
2278static WGPU_CARD_TOTAL: AtomicU64 = AtomicU64::new(0);
2279
2280pub(crate) fn wgpu_note_card_total(bytes: u64) {
2281 WGPU_CARD_TOTAL.store(bytes, Ordering::Relaxed);
2282}
2283
2284pub fn wgpu_card_total() -> u64 {
2288 WGPU_CARD_TOTAL.load(Ordering::Relaxed)
2289}
2290
2291pub fn wgpu_route_position_bytes(layers: usize, nkv: usize, hd: usize) -> u64 {
2293 #[cfg(feature = "gpu")]
2294 {
2295 crate::gpu_wgpu::broute::position_bytes(layers, nkv, hd)
2296 }
2297 #[cfg(not(feature = "gpu"))]
2298 {
2299 (layers * (2 * nkv + 1) * hd * 2) as u64
2300 }
2301}
2302
2303pub fn wgpu_kv_step(rows: usize) {
2306 #[cfg(feature = "gpu")]
2307 crate::gpu_wgpu::set_kv_step(rows);
2308 #[cfg(not(feature = "gpu"))]
2309 let _ = rows;
2310}
2311
2312static PLAN_EXTRA: std::sync::Mutex<Vec<(u64, u64)>> = std::sync::Mutex::new(Vec::new());
2313
2314pub fn plan_extra_reserve(model: u64, bytes: u64) {
2320 let mut g = PLAN_EXTRA.lock().unwrap();
2321 match g.iter_mut().find(|e| e.0 == model) {
2322 Some(e) => e.1 = e.1.max(bytes),
2323 None => g.push((model, bytes)),
2324 }
2325}
2326
2327pub(crate) fn plan_extra(model: u64) -> u64 {
2328 PLAN_EXTRA.lock().unwrap().iter().find(|e| e.0 == model).map_or(0, |e| e.1)
2329}
2330
2331static PLAN_STREAMED: std::sync::Mutex<Vec<u64>> = std::sync::Mutex::new(Vec::new());
2332
2333pub(crate) fn note_plan_streamed(model: u64) {
2334 let mut g = PLAN_STREAMED.lock().unwrap();
2335 if !g.contains(&model) {
2336 g.push(model);
2337 }
2338}
2339
2340pub fn plan_streamed(model: u64) -> bool {
2344 PLAN_STREAMED.lock().unwrap().contains(&model)
2345}
2346
2347pub fn graph_streams_in(streams: Vec<f32>) {
2352 #[cfg(feature = "cuda")]
2353 crate::gpu_cuda::streams_in(streams);
2354 #[cfg(not(feature = "cuda"))]
2355 let _ = streams;
2356}
2357
2358pub fn graph_streams_want() {
2362 #[cfg(feature = "cuda")]
2363 crate::gpu_cuda::streams_want();
2364}
2365
2366pub fn graph_streams_take() -> Vec<f32> {
2368 #[cfg(feature = "cuda")]
2369 {
2370 crate::gpu_cuda::streams_take()
2371 }
2372 #[cfg(not(feature = "cuda"))]
2373 {
2374 Vec::new()
2375 }
2376}
2377
2378pub fn moe_tap_begin(lo: usize, hi: usize) {
2384 #[cfg(feature = "cuda")]
2385 crate::gpu_cuda::moe_tap_begin(lo, hi);
2386 #[cfg(not(feature = "cuda"))]
2387 let _ = (lo, hi);
2388}
2389
2390pub fn moe_tap_end() -> Vec<(usize, Vec<f32>, Vec<i32>, Vec<f32>)> {
2392 #[cfg(feature = "cuda")]
2393 {
2394 crate::gpu_cuda::moe_tap_end()
2395 }
2396 #[cfg(not(feature = "cuda"))]
2397 {
2398 Vec::new()
2399 }
2400}
2401
2402static ROUTE_ROWS: AtomicU64 = AtomicU64::new(0);
2403
2404pub(crate) fn note_route_rows(rows: usize) {
2408 ROUTE_ROWS.store(rows as u64, Ordering::Relaxed);
2409}
2410
2411pub fn route_rows() -> usize {
2413 ROUTE_ROWS.load(Ordering::Relaxed) as usize
2414}
2415
2416pub fn context_cap(model: &CmfModel) -> usize {
2420 let cap = std::env::var("CMF_MAX_SEQ").ok().and_then(|v| v.parse::<usize>().ok()).unwrap_or(32_768);
2421 model.header.arch.max_position_embeddings.min(cap).max(1)
2422}
2423
2424pub fn block_route_on() -> bool {
2428 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2429 *ON.get_or_init(|| std::env::var("CMF_BLOCK_ROUTE").as_deref() != Ok("0")) && (cuda_active() || wgpu_active())
2431}
2432
2433pub const DASH_CHUNK_MAX: usize = 64;
2437
2438#[derive(Clone, Copy)]
2440pub struct GraphDash<'a> {
2441 pub qk_proj: &'a [f32],
2443 pub q_norm: &'a [f32],
2444 pub k_norm: &'a [f32],
2445 pub head_cls: &'a [f32],
2446 pub idx_scale: f32,
2447 pub floor: f32,
2448 pub sigma: f32,
2449 pub k: usize,
2450 pub block: usize,
2451 pub local_blocks: usize,
2452 pub nblk: usize,
2453 pub cands: &'a [u32],
2455 pub coff: &'a [u32],
2456 pub angles: &'a [f32],
2458}
2459
2460pub fn vres_graph_on() -> bool {
2462 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2463 *ON.get_or_init(|| std::env::var("CMF_VRES_GRAPH").as_deref() != Ok("0"))
2464}
2465
2466#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2470pub enum GraphAct {
2471 Silu,
2472 GeluErf,
2475 GeluTanh,
2478 SwiGluOaiM3,
2482}
2483
2484impl GraphAct {
2485 pub fn code(self) -> u32 {
2486 match self {
2487 Self::Silu => 0,
2488 Self::GeluErf => 1,
2489 Self::GeluTanh => 2,
2490 Self::SwiGluOaiM3 => 3,
2491 }
2492 }
2493}
2494
2495#[derive(Clone, Copy)]
2502pub struct GraphMhc<'a> {
2503 pub attn_w: &'a [f32],
2504 pub attn_b: &'a [f32],
2505 pub ffn_w: &'a [f32],
2506 pub ffn_b: &'a [f32],
2507 pub enter: bool,
2508 pub leave: bool,
2509 pub iters: usize,
2510 pub pre_scale: f32,
2511 pub dsv4: Option<GraphMhcDsv4>,
2517 pub head: Option<GraphMhcHead<'a>>,
2521}
2522
2523pub fn hy_layers(layers: &[GraphLayer]) -> bool {
2527 layers.iter().any(|l| {
2528 l.engram.is_some()
2529 || l.mhc.as_ref().is_some_and(|m| m.dsv4.is_some_and(|d| d.ihc.is_some()))
2531 || matches!(&l.attn, GraphAttn::Mla { hy: Some(_), .. })
2532 || matches!(&l.ffn, GraphFfn::Moe { latent: Some(_), .. } | GraphFfn::Moe { shared_limit: Some(_), .. })
2533 })
2534}
2535
2536#[derive(Clone, Copy)]
2538pub struct GraphMhcHead<'a> {
2539 pub w: &'a [f32],
2540 pub base: &'a [f32],
2541 pub scale: f32,
2542}
2543
2544#[derive(Clone, Copy)]
2548pub struct GraphMhcDsv4 {
2549 pub attn_scale: [f32; 3],
2550 pub ffn_scale: [f32; 3],
2551 pub eps: f32,
2552 pub rms_eps: f32,
2553 pub ihc: Option<f32>,
2558}
2559
2560pub struct GraphLayer<'a> {
2561 pub mhc: Option<GraphMhc<'a>>,
2564 pub input_norm: &'a [f32],
2565 pub attn: GraphAttn<'a>,
2566 pub post_norm: &'a [f32],
2567 pub ffn: GraphFfn<'a>,
2568 pub attn_out_norm: Option<&'a [f32]>,
2571 pub ffn_out_norm: Option<&'a [f32]>,
2572 pub layer_scale: Option<f32>,
2575 pub engram: Option<GraphEngram<'a>>,
2578}
2579
2580pub struct GraphEngram<'a> {
2585 pub mem: &'a [f32],
2588 pub on: &'a [bool],
2589 pub mem_dim: usize,
2590 pub value: GraphW<'a>,
2592 pub value_b: &'a [f32],
2593 pub keys: Vec<GraphW<'a>>,
2595 pub key_b: Vec<&'a [f32]>,
2596 pub norm_key: Vec<&'a [f32]>,
2597 pub norm_query: Vec<&'a [f32]>,
2598 pub gamma: &'a [f32],
2599 pub hc_scales: &'a [f32],
2601 pub eps: f32,
2602}
2603
2604pub struct GraphMoeLatent<'a> {
2607 pub down: GraphW<'a>,
2609 pub up: GraphW<'a>,
2610 pub dim: usize,
2611}
2612
2613pub struct GraphMoeDetachedShared<'a> {
2621 pub gate: GraphW<'a>,
2622 pub up: GraphW<'a>,
2623 pub down: GraphW<'a>,
2624 pub width: usize,
2625}
2626
2627pub enum GraphFfn<'a> {
2632 AttentionOnly,
2635 Dense {
2636 gate: GraphW<'a>,
2637 up: GraphW<'a>,
2638 down: GraphW<'a>,
2639 act: GraphAct,
2642 limit: f32,
2645 hot: Option<GraphMoeDetachedShared<'a>>,
2650 },
2651 Moe {
2652 router: GraphW<'a>,
2654 shared_gate: GraphW<'a>,
2656 experts: Vec<(usize, usize, usize)>,
2660 n_exp: usize,
2662 top_k: usize,
2663 inter: usize,
2664 act: GraphAct,
2669 norm_topk: bool,
2670 q4tp: bool,
2676 gu_q2: bool,
2680 q82: bool,
2685 sigmoid: bool,
2689 sigmoid_denom_eps: f32,
2690 bias: Option<&'a [f32]>,
2693 has_shared: bool,
2697 detached_shared: Option<GraphMoeDetachedShared<'a>>,
2701 shared_gated: bool,
2706 route_scale: f32,
2709 limit: f32,
2713 shared_limit: Option<f32>,
2716 latent: Option<GraphMoeLatent<'a>>,
2719 },
2720}
2721
2722#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2725pub enum TokenGraphOutcome {
2726 Declined,
2728 Completed,
2730 Failed,
2732}
2733
2734#[allow(clippy::too_many_arguments)]
2739pub fn forward_token_graph(
2740 model: &Arc<CmfModel>,
2741 kv_id: u64,
2742 layers: &[GraphLayer],
2743 o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
2746 o1_epoch: u64,
2747 invf: &[f32],
2748 h: &mut [f32],
2749 nh: usize,
2750 nkv: usize,
2751 hd: usize,
2752 attn_scale: f32,
2753 rd: usize,
2754 hidden: usize,
2755 inter: usize,
2756 position: usize,
2757 cap: usize,
2758 gemma: bool,
2759 eps: f32,
2760 lm_head: Option<(&GraphW, usize)>,
2761 final_norm: &[f32],
2762 logits: &mut Vec<f32>,
2763 loop_norm_at: &[usize],
2764 steps: usize,
2765 embed: Option<(&GraphW, usize, f32)>,
2766 ids_out: Option<&mut Vec<u32>>,
2767 layers_run: Option<&mut usize>,
2770 layer_base: usize,
2774 hidden_too: bool,
2776) -> TokenGraphOutcome {
2777 match backend() {
2778 #[cfg(feature = "gpu")]
2779 Backend::Wgpu => crate::gpu_wgpu::forward_token_graph(
2780 model,
2781 kv_id,
2782 layers,
2783 o1,
2784 o1_epoch,
2785 invf,
2786 h,
2787 nh,
2788 nkv,
2789 hd,
2790 attn_scale,
2791 rd,
2792 hidden,
2793 inter,
2794 position,
2795 cap,
2796 gemma,
2797 eps,
2798 lm_head,
2799 final_norm,
2800 logits,
2801 loop_norm_at,
2802 steps,
2803 embed,
2804 ids_out,
2805 layers_run,
2806 layer_base,
2807 hidden_too,
2808 ),
2809 #[cfg(feature = "cuda")]
2810 Backend::Cuda => crate::gpu_cuda::forward_token_graph(
2811 model,
2812 kv_id,
2813 layers,
2814 o1,
2815 o1_epoch,
2816 invf,
2817 h,
2818 nh,
2819 nkv,
2820 hd,
2821 attn_scale,
2822 rd,
2823 hidden,
2824 position,
2825 cap,
2826 gemma,
2827 eps,
2828 lm_head,
2829 final_norm,
2830 logits,
2831 loop_norm_at,
2832 steps,
2833 layers_run,
2834 layer_base,
2835 hidden_too,
2836 ),
2837 #[allow(unused_variables)]
2838 _ => {
2839 let _ = (
2840 attn_scale,
2841 lm_head,
2842 final_norm,
2843 logits,
2844 loop_norm_at,
2845 layers_run,
2846 layer_base,
2847 hidden_too,
2848 );
2849 TokenGraphOutcome::Declined
2850 }
2851 }
2852}
2853
2854#[allow(clippy::too_many_arguments)]
2856pub fn dory_forward(
2857 id: u64,
2858 model: Option<&std::sync::Arc<cortiq_core::CmfModel>>,
2859 m: &crate::dory::Dory,
2860 ids: &[u32],
2861 pos: usize,
2862 loops: usize,
2863 want: crate::dory::Want,
2864 logits: &mut Vec<f32>,
2865) -> bool {
2866 #[cfg(target_os = "macos")]
2867 if backend() == Backend::Metal {
2868 return model.is_some_and(|md| crate::gpu_metal::dory::forward(id, md, m, ids, pos, loops, want, logits));
2869 }
2870 #[cfg(feature = "cuda")]
2871 if backend() == Backend::Cuda {
2872 return crate::gpu_cuda::dory_forward(id, m, ids, pos, loops, want, logits);
2873 }
2874 #[cfg(feature = "gpu")]
2875 if backend() == Backend::Wgpu {
2876 return crate::gpu_wgpu::dory::forward(id, m, ids, pos, loops, want, logits);
2877 }
2878 let _ = (id, model, m, ids, pos, loops, want, logits);
2879 false
2880}
2881
2882#[allow(clippy::too_many_arguments)]
2886pub fn inkling_forward(
2887 id: u64,
2888 g: &crate::inkling::Globals,
2889 layers: &[crate::inkling::Layer],
2890 cfg: &crate::inkling::Cfg,
2891 ids: &[u32],
2892 pos: usize,
2893 want: bool,
2894 all: bool,
2895 logits: &mut Vec<f32>,
2896) -> bool {
2897 #[cfg(target_os = "macos")]
2898 if backend() == Backend::Metal {
2899 return crate::gpu_metal::inkling::forward(id, g, layers, cfg, ids, pos, want, all, logits);
2900 }
2901 #[cfg(feature = "cuda")]
2902 if backend() == Backend::Cuda {
2903 return crate::gpu_cuda::inkling_forward(id, g, layers, cfg, ids, pos, want, all, logits);
2904 }
2905 #[cfg(feature = "gpu")]
2906 if backend() == Backend::Wgpu {
2907 return crate::gpu_wgpu::inkling::forward(id, g, layers, cfg, ids, pos, want, all, logits);
2908 }
2909 let _ = (id, g, layers, cfg, ids, pos, want, all, logits);
2910 false
2911}
2912
2913pub fn inkling_reset(id: u64) {
2915 #[cfg(target_os = "macos")]
2916 if backend() == Backend::Metal {
2917 crate::gpu_metal::inkling::reset(id);
2918 return;
2919 }
2920 #[cfg(feature = "cuda")]
2921 if backend() == Backend::Cuda {
2922 crate::gpu_cuda::inkling_reset(id);
2923 }
2924 #[cfg(feature = "gpu")]
2925 if backend() == Backend::Wgpu {
2926 crate::gpu_wgpu::inkling::reset(id);
2927 }
2928 let _ = id;
2929}
2930
2931pub fn inkling_draft(id: u64, g: &crate::inkling::Globals, cfg: &crate::inkling::Cfg, anchor: u32, pos: usize, k: usize) -> Option<(Vec<u32>, Vec<f32>)> {
2935 #[cfg(target_os = "macos")]
2936 if backend() == Backend::Metal {
2937 return crate::gpu_metal::inkling::draft(id, g, cfg, anchor, pos, k);
2938 }
2939 #[cfg(feature = "cuda")]
2940 if backend() == Backend::Cuda {
2941 return crate::gpu_cuda::inkling_draft(id, g, cfg, anchor, pos, k).map(|v| (v, Vec::new()));
2942 }
2943 let _ = (id, g, cfg, anchor, pos, k);
2944 None
2945}
2946
2947pub fn inkling_ring_snap(id: u64) -> bool {
2949 #[cfg(target_os = "macos")]
2950 if backend() == Backend::Metal {
2951 return crate::gpu_metal::inkling::ring_snap(id);
2952 }
2953 #[cfg(feature = "cuda")]
2954 if backend() == Backend::Cuda {
2955 return crate::gpu_cuda::inkling_ring_snap(id);
2956 }
2957 let _ = id;
2958 false
2959}
2960
2961pub fn inkling_ring_back(id: u64, r: usize) -> bool {
2963 #[cfg(target_os = "macos")]
2964 if backend() == Backend::Metal {
2965 return crate::gpu_metal::inkling::ring_back(id, r);
2966 }
2967 #[cfg(feature = "cuda")]
2968 if backend() == Backend::Cuda {
2969 return crate::gpu_cuda::inkling_ring_back(id, r);
2970 }
2971 let _ = (id, r);
2972 false
2973}
2974
2975#[allow(clippy::too_many_arguments)]
2978pub fn inkling_verify(id: u64, g: &crate::inkling::Globals, layers: &[crate::inkling::Layer], cfg: &crate::inkling::Cfg, ids: &[u32], pos: usize, picks: &mut Vec<u32>) -> bool {
2979 #[cfg(target_os = "macos")]
2980 if backend() == Backend::Metal {
2981 return crate::gpu_metal::inkling::verify(id, g, layers, cfg, ids, pos, picks);
2982 }
2983 #[cfg(feature = "cuda")]
2984 if backend() == Backend::Cuda {
2985 return crate::gpu_cuda::inkling_verify(id, g, layers, cfg, ids, pos, picks);
2986 }
2987 let _ = (id, g, layers, cfg, ids, pos, picks);
2988 false
2989}
2990
2991pub fn inkling_row_logits(id: u64, r: usize, vocab: usize, out: &mut Vec<f32>) -> bool {
2993 #[cfg(target_os = "macos")]
2994 if backend() == Backend::Metal {
2995 return crate::gpu_metal::inkling::row_logits(id, r, vocab, out);
2996 }
2997 #[cfg(feature = "cuda")]
2998 if backend() == Backend::Cuda {
2999 return crate::gpu_cuda::inkling_row_logits(id, r, vocab, out);
3000 }
3001 let _ = (id, r, vocab, out);
3002 false
3003}
3004
3005pub fn dory_reset(id: u64) {
3007 #[cfg(target_os = "macos")]
3008 if backend() == Backend::Metal {
3009 crate::gpu_metal::dory::reset(id);
3010 return;
3011 }
3012 #[cfg(feature = "cuda")]
3013 if backend() == Backend::Cuda {
3014 crate::gpu_cuda::dory_reset(id);
3015 return;
3016 }
3017 #[cfg(feature = "gpu")]
3018 if backend() == Backend::Wgpu {
3019 crate::gpu_wgpu::dory::reset(id);
3020 }
3021 let _ = id;
3022}
3023
3024pub fn dory_sealed(id: u64) -> bool {
3027 #[cfg(target_os = "macos")]
3028 if backend() == Backend::Metal {
3029 return crate::gpu_metal::dory::sealed(id);
3030 }
3031 #[cfg(feature = "cuda")]
3032 if backend() == Backend::Cuda {
3033 return crate::gpu_cuda::dory_sealed(id);
3034 }
3035 #[cfg(feature = "gpu")]
3036 if backend() == Backend::Wgpu {
3037 return crate::gpu_wgpu::dory::sealed(id);
3038 }
3039 let _ = id;
3040 false
3041}
3042
3043pub fn dory_kv_bytes(id: u64) -> Option<u64> {
3044 #[cfg(target_os = "macos")]
3045 if backend() == Backend::Metal {
3046 return crate::gpu_metal::dory::kv_bytes(id);
3047 }
3048 #[cfg(feature = "cuda")]
3049 if backend() == Backend::Cuda {
3050 return crate::gpu_cuda::dory_kv_bytes(id);
3051 }
3052 #[cfg(feature = "gpu")]
3053 if backend() == Backend::Wgpu {
3054 return crate::gpu_wgpu::dory::kv_bytes(id);
3055 }
3056 let _ = id;
3057 None
3058}
3059
3060pub fn embryo_wide_ready(q8: bool) -> bool {
3062 #[cfg(feature = "cuda")]
3063 if backend() == Backend::Cuda {
3064 return crate::gpu_cuda::embryo_wide_ready(q8);
3065 }
3066 #[cfg(feature = "gpu")]
3067 if backend() == Backend::Wgpu {
3068 return crate::gpu_wgpu::embryo_wide_ready(q8);
3069 }
3070 let _ = q8;
3071 false
3072}
3073
3074pub fn forward_embryo_graph(
3079 model: &Arc<EmbryoGraphModel>,
3080 kv_id: u64,
3081 hidden: &[f32],
3082 position: usize,
3083 logits: &mut Vec<f32>,
3084) -> bool {
3085 #[cfg(feature = "cuda")]
3086 if backend() == Backend::Cuda {
3087 return crate::gpu_cuda::forward_embryo_graph(model, kv_id, hidden, position, logits);
3088 }
3089 #[cfg(feature = "gpu")]
3090 if backend() == Backend::Wgpu {
3091 return crate::gpu_wgpu::forward_embryo_graph(model, kv_id, hidden, position, logits);
3092 }
3093 let _ = (model, kv_id, hidden, position, logits);
3094 false
3095}
3096
3097#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3101pub enum BatchGraphOutcome {
3102 Declined,
3105 Completed,
3107 Failed,
3111}
3112
3113pub struct SpecTail<'a> {
3114 pub lm: GraphW<'a>,
3115 pub lm_rows: usize,
3116 pub final_norm: &'a [f32],
3117 pub logits_out: &'a mut Vec<f32>,
3118 pub pick: Option<(PreviewPick<'a>, &'a mut Vec<(u32, f32)>)>,
3122}
3123
3124pub struct PreviewPick<'a> {
3130 pub vocab: usize,
3131 pub counts: &'a [u32],
3132 pub stop: &'a [u32],
3133 pub forbid: &'a [u32],
3134 pub think_end: Option<u32>,
3135 pub close_open: bool,
3136 pub len0: usize,
3137 pub frequency: f32,
3138 pub presence: f32,
3139 pub repetition: f32,
3140 pub length_ramp: (f32, f32, f32),
3142 pub think_ramp: (f32, f32, f32),
3143}
3144
3145#[allow(clippy::too_many_arguments)]
3149pub fn forward_batch_graph(
3150 model: &Arc<CmfModel>,
3151 kv_id: u64,
3152 layers: &[GraphLayer],
3153 invf: &[f32],
3154 h: &mut [f32],
3155 nh: usize,
3156 nkv: usize,
3157 hd: usize,
3158 rd: usize,
3159 hidden: usize,
3160 inter: usize,
3161 positions: &[usize],
3162 cap: usize,
3163 gemma: bool,
3164 eps: f32,
3165 attn_scale: f32,
3166 k: usize,
3167 o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
3170 o1_epoch: u64,
3171 spec: Option<SpecTail<'_>>,
3172 layers_run: Option<&mut usize>,
3178) -> BatchGraphOutcome {
3179 forward_batch_graph_at(model, kv_id, 0, layers, invf, h, nh, nkv, hd, rd, hidden, inter, positions, cap, gemma, eps, attn_scale, k, o1, o1_epoch, spec, layers_run)
3180}
3181
3182thread_local! {
3183 static MIMO_ATTN_SCRATCH: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
3184}
3185
3186pub(crate) fn mimo_attention_scratch_enabled() -> bool {
3187 MIMO_ATTN_SCRATCH.with(std::cell::Cell::get)
3188}
3189
3190#[doc(hidden)]
3193pub fn mimo_attention_scratch_scope<R>(enabled: bool, f: impl FnOnce() -> R) -> R {
3194 struct Restore(bool);
3195 impl Drop for Restore {
3196 fn drop(&mut self) {
3197 MIMO_ATTN_SCRATCH.with(|v| v.set(self.0));
3198 }
3199 }
3200 let _restore = Restore(MIMO_ATTN_SCRATCH.with(|v| v.replace(enabled)));
3201 f()
3202}
3203
3204pub fn g4_batch_on() -> bool {
3207 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3208 *ON.get_or_init(|| std::env::var("CMF_G4_BATCH").as_deref() != Ok("0"))
3209}
3210
3211pub(crate) fn moe_q82_graph_on() -> bool {
3214 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3215 *ON.get_or_init(|| std::env::var("CMF_MOE_Q82").as_deref() != Ok("0"))
3216}
3217
3218thread_local! {
3219 static MIMO_Q8_SHORT: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
3220}
3221
3222pub(crate) fn mimo_q8_short_enabled() -> bool {
3223 MIMO_Q8_SHORT.with(std::cell::Cell::get)
3224}
3225
3226#[doc(hidden)]
3228pub fn mimo_q8_short_scope<R>(enabled: bool, f: impl FnOnce() -> R) -> R {
3229 struct Restore(bool);
3230 impl Drop for Restore {
3231 fn drop(&mut self) {
3232 MIMO_Q8_SHORT.with(|v| v.set(self.0));
3233 }
3234 }
3235 let _restore = Restore(MIMO_Q8_SHORT.with(|v| v.replace(enabled)));
3236 f()
3237}
3238
3239#[allow(clippy::too_many_arguments)]
3241pub fn forward_batch_graph_at(
3242 model: &Arc<CmfModel>,
3243 kv_id: u64,
3244 layer_base: usize,
3245 layers: &[GraphLayer],
3246 invf: &[f32],
3247 h: &mut [f32],
3248 nh: usize,
3249 nkv: usize,
3250 hd: usize,
3251 rd: usize,
3252 hidden: usize,
3253 inter: usize,
3254 positions: &[usize],
3255 cap: usize,
3256 gemma: bool,
3257 eps: f32,
3258 attn_scale: f32,
3259 k: usize,
3260 o1: &[Option<Vec<crate::nystrom::O1DeviceView<'_>>>],
3263 o1_epoch: u64,
3264 spec: Option<SpecTail<'_>>,
3265 layers_run: Option<&mut usize>,
3271) -> BatchGraphOutcome {
3272 match backend() {
3273 #[cfg(feature = "gpu")]
3274 Backend::Wgpu => crate::gpu_wgpu::forward_batch_graph_at(
3275 model, kv_id, layer_base, layers, invf, h, nh, nkv, hd, rd, hidden, inter, positions,
3276 cap, gemma, eps, attn_scale, k, o1, o1_epoch, spec, layers_run,
3277 ),
3278 #[cfg(feature = "cuda")]
3279 Backend::Cuda => crate::gpu_cuda::forward_batch_graph_at(
3280 model, kv_id, layer_base, layers, invf, h, nh, nkv, hd, rd, hidden, positions, cap,
3281 gemma, eps, attn_scale, k, o1, o1_epoch, spec, layers_run,
3282 ),
3283 #[allow(unreachable_patterns)]
3284 _ => {
3285 let _ = (o1, o1_epoch, spec, layers_run);
3286 BatchGraphOutcome::Declined
3287 }
3288 }
3289}
3290
3291pub fn rows_matvec(
3294 model: &Arc<CmfModel>,
3295 gw: &GraphW,
3296 rows: usize,
3297 cols: usize,
3298 x: &[f32],
3299 n: usize,
3300 y: &mut [f32],
3301) -> bool {
3302 #[cfg(feature = "cuda")]
3303 if backend() == Backend::Cuda {
3304 return crate::gpu_cuda::rows_matvec(model, gw, rows, cols, x, n, y);
3305 }
3306 let _ = (model, gw, rows, cols, x, n, y);
3307 false
3308}
3309
3310pub fn gdn_spec_restore(kv_id: u64, slot: usize, base_pos: usize, expected_layers: usize) -> bool {
3315 #[cfg(feature = "cuda")]
3316 if backend() == Backend::Cuda {
3317 return crate::gpu_cuda::gdn_spec_restore(kv_id, slot, base_pos, expected_layers);
3318 }
3319 #[cfg(feature = "gpu")]
3320 if backend() == Backend::Wgpu {
3321 return crate::gpu_wgpu::gdn_spec_restore(kv_id, slot, base_pos, expected_layers);
3322 }
3323 #[allow(unreachable_code)]
3324 {
3325 let _ = (kv_id, slot, base_pos, expected_layers);
3326 false
3327 }
3328}
3329
3330pub fn gdn_snapshot(kv_id: u64, pos: usize) -> bool {
3334 #[cfg(feature = "cuda")]
3335 if backend() == Backend::Cuda {
3336 return crate::gpu_cuda::gdn_snapshot(kv_id, pos);
3337 }
3338 let _ = (kv_id, pos);
3339 false
3340}
3341
3342pub fn gdn_snapshot_restore(kv_id: u64, pos: usize) -> bool {
3345 #[cfg(feature = "cuda")]
3346 if backend() == Backend::Cuda {
3347 return crate::gpu_cuda::gdn_snapshot_restore(kv_id, pos);
3348 }
3349 let _ = (kv_id, pos);
3350 false
3351}
3352
3353pub fn graph_kv_set_stored(kv_id: u64, layer: usize, stored: usize) -> bool {
3359 #[cfg(feature = "cuda")]
3360 if backend() == Backend::Cuda {
3361 return crate::gpu_cuda::kv_set_stored(kv_id, layer, stored);
3362 }
3363 #[cfg(feature = "gpu")]
3364 if backend() == Backend::Wgpu {
3365 return crate::gpu_wgpu::kv_mirror_set_stored(kv_id, layer, stored);
3366 }
3367 #[cfg(target_os = "macos")]
3368 if backend() == Backend::Metal {
3369 crate::gpu_metal::kv_mirror_set_stored(kv_id, layer, stored);
3370 return true;
3371 }
3372 false
3373}
3374
3375pub fn graph_kv_stored(_kv_id: u64, _layer: usize) -> Option<usize> {
3379 #[cfg(feature = "cuda")]
3380 if backend() == Backend::Cuda {
3381 return crate::gpu_cuda::kv_stored(_kv_id, _layer);
3382 }
3383 #[cfg(feature = "gpu")]
3384 if backend() == Backend::Wgpu {
3385 return crate::gpu_wgpu::kv_mirror_stored(_kv_id, _layer);
3386 }
3387 None
3388}
3389
3390pub fn graph_state_resident(_kv_id: u64, _layer: usize) -> bool {
3393 #[cfg(feature = "cuda")]
3394 if backend() == Backend::Cuda {
3395 return crate::gpu_cuda::state_resident(_kv_id, _layer);
3396 }
3397 #[cfg(feature = "gpu")]
3398 if backend() == Backend::Wgpu {
3399 return crate::gpu_wgpu::graph_state_resident(_kv_id, _layer);
3400 }
3401 false
3402}
3403
3404pub fn o1_qcap_begin(_layers: &[usize]) -> bool {
3408 #[cfg(feature = "gpu")]
3409 if backend() == Backend::Wgpu {
3410 crate::gpu_wgpu::o1_qcap_begin(_layers);
3411 return true;
3412 }
3413 #[cfg(feature = "cuda")]
3414 if backend() == Backend::Cuda {
3415 return crate::gpu_cuda::o1_qcap_begin(_layers);
3416 }
3417 false
3418}
3419
3420pub fn batch_graph_over_budget() -> bool {
3423 #[cfg(feature = "gpu")]
3424 if backend() == Backend::Wgpu {
3425 return crate::gpu_wgpu::batch_over_budget();
3426 }
3427 false
3428}
3429
3430pub fn mhc_streams_read(_d: usize, _rows: usize) -> Option<Vec<f32>> {
3433 #[cfg(feature = "gpu")]
3434 if backend() == Backend::Wgpu {
3435 return crate::gpu_wgpu::mhc_streams_read(_d, _rows);
3436 }
3437 None
3438}
3439
3440pub fn o1_qcap_stride(_stride: usize) -> bool {
3444 #[cfg(feature = "gpu")]
3445 if backend() == Backend::Wgpu {
3446 return crate::gpu_wgpu::o1_qcap_stride(_stride);
3447 }
3448 #[cfg(feature = "cuda")]
3449 if backend() == Backend::Cuda {
3450 return crate::gpu_cuda::o1_qcap_stride(_stride);
3451 }
3452 false
3453}
3454
3455pub fn o1_qcap_drain() -> Option<Vec<(usize, Vec<f32>)>> {
3457 #[cfg(feature = "gpu")]
3458 if backend() == Backend::Wgpu {
3459 return crate::gpu_wgpu::o1_qcap_drain();
3460 }
3461 #[cfg(feature = "cuda")]
3462 if backend() == Backend::Cuda {
3463 return crate::gpu_cuda::o1_qcap_drain();
3464 }
3465 None
3466}
3467
3468pub fn o1_spec_commit(_kv_id: u64, _pos0: usize, _rows: usize) -> bool {
3470 #[cfg(feature = "cuda")]
3471 if backend() == Backend::Cuda {
3472 return crate::gpu_cuda::o1_spec_commit(_kv_id, _pos0, _rows);
3473 }
3474 #[cfg(feature = "gpu")]
3475 if backend() == Backend::Wgpu {
3476 return crate::gpu_wgpu::o1_spec_commit(_kv_id, _pos0, _rows);
3477 }
3478 #[cfg(target_os = "macos")]
3479 if backend() == Backend::Metal {
3480 return crate::gpu_metal::o1c::spec_commit(_kv_id, _rows);
3481 }
3482 false
3483}
3484
3485pub fn exit_past_driver_teardown(code: i32) {
3497 #[cfg(all(feature = "cuda", unix))]
3498 {
3499 if std::env::var("CMF_EXIT_HANDLERS").as_deref() != Ok("1") && crate::gpu_cuda::ctx_built() && crate::gpu_wgpu::any_ctx_built() {
3500 use std::io::Write;
3501 let _ = std::io::stdout().flush();
3502 let _ = std::io::stderr().flush();
3503 unsafe { libc::_exit(code) }
3506 }
3507 }
3508 let _ = code;
3509}
3510
3511pub fn o1_far_sums_on() -> bool {
3512 #[cfg(feature = "cuda")]
3513 if backend() == Backend::Cuda {
3514 return std::env::var("CMF_O1_FAR_GPU").as_deref() != Ok("0") && crate::gpu_cuda::ctx_ready();
3515 }
3516 false
3517}
3518
3519#[allow(clippy::too_many_arguments)]
3526pub fn o1_far_sums(nkv: usize, hpk: usize, hd: usize, m: usize, scale: f32, qt: &[f32], idx: &[u32], ks: &[&[f32]], vs: &[&[f32]]) -> Option<(Vec<f32>, Vec<f32>)> {
3527 #[cfg(feature = "cuda")]
3528 if backend() == Backend::Cuda {
3529 return crate::gpu_cuda::o1_far_sums(nkv, hpk, hd, m, scale, qt, idx, ks, vs);
3530 }
3531 let _ = (nkv, hpk, hd, m, scale, qt, idx, ks, vs);
3532 None
3533}
3534
3535pub fn o1_acap_begin(_stride: usize) {
3539 #[cfg(feature = "cuda")]
3540 if backend() == Backend::Cuda {
3541 crate::gpu_cuda::o1_acap_begin(_stride);
3542 }
3543 #[cfg(feature = "gpu")]
3544 if backend() == Backend::Wgpu {
3545 crate::gpu_wgpu::o1_acap_begin(_stride);
3546 }
3547 #[cfg(target_os = "macos")]
3548 if backend() == Backend::Metal {
3549 crate::gpu_metal::o1c::acap_begin();
3550 }
3551}
3552
3553pub fn o1_acap_end() {
3554 #[cfg(feature = "cuda")]
3555 if backend() == Backend::Cuda {
3556 crate::gpu_cuda::o1_acap_end();
3557 }
3558 #[cfg(feature = "gpu")]
3559 if backend() == Backend::Wgpu {
3560 crate::gpu_wgpu::o1_acap_end();
3561 }
3562 #[cfg(target_os = "macos")]
3563 if backend() == Backend::Metal {
3564 crate::gpu_metal::o1c::cap_end();
3565 }
3566}
3567
3568pub fn o1_acap_pending() -> usize {
3571 #[cfg(feature = "gpu")]
3572 if backend() == Backend::Wgpu {
3573 return crate::gpu_wgpu::o1_acap_pending();
3574 }
3575 0
3576}
3577
3578pub fn o1_acap_take_first(_n: usize) -> Option<Vec<(usize, Vec<f32>, Vec<f32>, Vec<f32>)>> {
3581 #[cfg(feature = "gpu")]
3582 if backend() == Backend::Wgpu {
3583 return crate::gpu_wgpu::o1_acap_take_first(_n);
3584 }
3585 o1_acap_take()
3586}
3587
3588pub fn o1_acap_take() -> Option<Vec<(usize, Vec<f32>, Vec<f32>, Vec<f32>)>> {
3590 #[cfg(feature = "cuda")]
3591 if backend() == Backend::Cuda {
3592 return crate::gpu_cuda::o1_acap_take();
3593 }
3594 #[cfg(feature = "gpu")]
3595 if backend() == Backend::Wgpu {
3596 return crate::gpu_wgpu::o1_acap_take();
3597 }
3598 #[cfg(target_os = "macos")]
3599 if backend() == Backend::Metal {
3600 return Some(crate::gpu_metal::o1c::cap_take());
3601 }
3602 None
3603}
3604
3605pub fn o1_qcap_take() -> Option<Vec<(usize, Vec<f32>)>> {
3608 #[cfg(feature = "gpu")]
3609 if backend() == Backend::Wgpu {
3610 return crate::gpu_wgpu::o1_qcap_take();
3611 }
3612 #[cfg(feature = "cuda")]
3613 if backend() == Backend::Cuda {
3614 return crate::gpu_cuda::o1_qcap_take();
3615 }
3616 None
3617}
3618
3619pub fn graph_gdn_state_read(_kv_id: u64, _layer: usize) -> Option<Vec<f32>> {
3622 #[cfg(feature = "cuda")]
3623 if backend() == Backend::Cuda {
3624 return crate::gpu_cuda::gdn_state_read(_kv_id, _layer);
3625 }
3626 #[cfg(feature = "gpu")]
3627 if backend() == Backend::Wgpu {
3628 return crate::gpu_wgpu::graph_gdn_state_read(_kv_id, _layer);
3629 }
3630 None
3631}
3632
3633pub fn graph_kv_read_rows(
3637 _kv_id: u64,
3638 _reqs: &[(usize, usize, usize)],
3639 _nkv: usize,
3640 _hd: usize,
3641) -> Option<Vec<(Vec<f32>, Vec<f32>)>> {
3642 #[cfg(feature = "cuda")]
3643 if backend() == Backend::Cuda {
3644 return crate::gpu_cuda::kv_read_rows(_kv_id, _reqs, _nkv, _hd);
3645 }
3646 #[cfg(feature = "gpu")]
3647 if backend() == Backend::Wgpu {
3648 return crate::gpu_wgpu::kv_mirror_read_rows(_kv_id, _reqs, _nkv, _hd);
3649 }
3650 None
3651}
3652
3653pub fn graph_kv_pull_host(
3659 _kv_id: u64,
3660 _layer: usize,
3661 _from: usize,
3662 _to: usize,
3663 _nkv: usize,
3664 _hd: usize,
3665) -> Option<(Vec<f32>, Vec<f32>, usize)> {
3666 #[cfg(feature = "cuda")]
3667 if backend() == Backend::Cuda {
3668 return crate::gpu_cuda::kv_pull_host(_kv_id, _layer, _from, _to, _nkv, _hd);
3669 }
3670 #[cfg(feature = "gpu")]
3671 if backend() == Backend::Wgpu {
3672 return crate::gpu_wgpu::kv_mirror_pull_host(_kv_id, _layer, _from, _to, _nkv, _hd);
3673 }
3674 None
3675}
3676
3677pub fn set_batch_defer(_on: bool) {
3680 #[cfg(feature = "cuda")]
3681 if backend() == Backend::Cuda {
3682 crate::gpu_cuda::set_batch_defer(_on);
3683 }
3684 #[cfg(feature = "gpu")]
3685 if backend() == Backend::Wgpu {
3686 crate::gpu_wgpu::set_batch_defer(_on);
3687 }
3688}
3689
3690pub fn set_batch_kv_hint(_rows: usize) {
3693 #[cfg(feature = "cuda")]
3694 if backend() == Backend::Cuda {
3695 crate::gpu_cuda::set_batch_kv_hint(_rows);
3696 }
3697 #[cfg(feature = "gpu")]
3698 if backend() == Backend::Wgpu {
3699 crate::gpu_wgpu::set_batch_kv_hint(_rows);
3700 }
3701}
3702
3703thread_local! {
3704 static BATCH_LOOP: std::cell::RefCell<Option<(Vec<usize>, std::sync::Arc<Vec<f32>>)>> = const { std::cell::RefCell::new(None) };
3706}
3707
3708pub fn set_batch_loop_norm(v: Option<(Vec<usize>, Vec<f32>)>) {
3713 BATCH_LOOP.with(|b| *b.borrow_mut() = v.map(|(at, w)| (at, std::sync::Arc::new(w))));
3714}
3715
3716pub(crate) fn batch_loop_norm() -> Option<(Vec<usize>, std::sync::Arc<Vec<f32>>)> {
3718 BATCH_LOOP.with(|b| b.borrow().clone()).filter(|(at, _)| !at.is_empty())
3719}
3720
3721pub fn graph_kv16_note(_kv_id: u64, _allowed: bool) {
3724 #[cfg(feature = "gpu")]
3725 if backend() == Backend::Wgpu {
3726 crate::gpu_wgpu::kv16::note(_kv_id, _allowed);
3727 }
3728}
3729
3730pub fn graph_kv_reset(_kv_id: u64) {
3732 #[cfg(feature = "cuda")]
3733 if backend() == Backend::Cuda {
3734 crate::gpu_cuda::kv_reset(_kv_id);
3735 crate::gpu_cuda::embryo_graph_reset(_kv_id);
3736 }
3737 #[cfg(feature = "gpu")]
3738 if backend() == Backend::Wgpu {
3739 crate::gpu_wgpu::kv_mirror_reset(_kv_id);
3740 crate::gpu_wgpu::embryo_graph_reset(_kv_id);
3741 }
3742}
3743
3744pub fn q1t_matvec(
3748 model: &Arc<CmfModel>,
3749 idx: usize,
3750 xs: &[f32],
3751 rows: usize,
3752 cols: usize,
3753 out: &mut [f32],
3754) -> bool {
3755 match backend() {
3756 #[cfg(target_os = "macos")]
3757 Backend::Metal => {
3758 if metal_q1t_enabled() {
3759 crate::gpu_metal::q1t_matvec(model, idx, xs, rows, cols, out)
3760 } else {
3761 false
3762 }
3763 }
3764 #[cfg(feature = "gpu")]
3765 Backend::Wgpu => crate::gpu_wgpu::q1t_matvec(model, idx, xs, rows, cols, out),
3766 Backend::None => false,
3767 #[cfg(feature = "cuda")]
3768 Backend::Cuda => false,
3769 }
3770}
3771
3772#[allow(unused_variables)]
3775pub fn q4b_matvec(
3776 model: &Arc<CmfModel>,
3777 idx: usize,
3778 xs: &[f32],
3779 rows: usize,
3780 cols: usize,
3781 out: &mut [f32],
3782) -> bool {
3783 match backend() {
3784 #[cfg(target_os = "macos")]
3785 Backend::Metal => false,
3786 #[cfg(feature = "gpu")]
3787 Backend::Wgpu => crate::gpu_wgpu::q4b_matvec(model, idx, xs, rows, cols, out),
3788 Backend::None => false,
3789 #[cfg(feature = "cuda")]
3790 Backend::Cuda => false,
3791 }
3792}
3793
3794pub fn q1t_matmat(
3797 model: &Arc<CmfModel>,
3798 idx: usize,
3799 xs: &[f32],
3800 b: usize,
3801 rows: usize,
3802 cols: usize,
3803 out: &mut [f32],
3804) -> bool {
3805 match backend() {
3806 #[cfg(target_os = "macos")]
3807 Backend::Metal => crate::gpu_metal::q1t_matmat(model, idx, xs, b, rows, cols, out),
3811 #[cfg(feature = "gpu")]
3812 Backend::Wgpu => crate::gpu_wgpu::q1t_matmat(model, idx, xs, b, rows, cols, out),
3813 Backend::None => false,
3814 #[cfg(feature = "cuda")]
3815 Backend::Cuda => false,
3816 }
3817}
3818
3819#[cfg(target_os = "macos")]
3823pub(crate) fn metal_q1t_enabled() -> bool {
3824 std::env::var("CMF_METAL_Q1T")
3825 .map(|v| v != "0" && !v.eq_ignore_ascii_case("off"))
3826 .unwrap_or(true)
3827}
3828
3829pub fn q1_matmat(
3831 model: &Arc<CmfModel>,
3832 idx: usize,
3833 xs: &[f32],
3834 b: usize,
3835 rows: usize,
3836 cols: usize,
3837 out: &mut [f32],
3838) -> bool {
3839 match backend() {
3840 #[cfg(feature = "gpu")]
3841 Backend::Wgpu => crate::gpu_wgpu::q1_matmat(model, idx, xs, b, rows, cols, out),
3842 #[allow(unused_variables)]
3843 _ => false,
3844 }
3845}
3846
3847pub fn q1g_matmat(
3849 model: &Arc<CmfModel>,
3850 idx: usize,
3851 xs: &[f32],
3852 b: usize,
3853 rows: usize,
3854 cols: usize,
3855 out: &mut [f32],
3856) -> bool {
3857 match backend() {
3858 #[cfg(feature = "gpu")]
3859 Backend::Wgpu => crate::gpu_wgpu::q1g_matmat(model, idx, xs, b, rows, cols, out),
3860 #[allow(unused_variables)]
3861 _ => false,
3862 }
3863}
3864
3865static MM_KILL: AtomicBool = AtomicBool::new(false);
3870pub(crate) fn mm_killed() -> bool {
3871 MM_KILL.load(Ordering::Relaxed)
3872}
3873pub(crate) fn mm_kill() {
3874 MM_KILL.store(true, Ordering::Relaxed);
3875}
3876
3877static MM_STRIKES: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
3884const MM_STRIKES_TO_KILL: u32 = 3;
3885static MM_ARMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
3892
3893pub fn mm_kill_arm(on: bool) {
3896 MM_ARMED.store(on, Ordering::Relaxed);
3897 if on {
3898 MM_STRIKES.store(0, Ordering::Relaxed);
3899 }
3900}
3901
3902pub(crate) fn mm_budget_check(
3909 what: &str,
3910 el: std::time::Duration,
3911 budget: std::time::Duration,
3912 exempt: bool,
3913) {
3914 if el <= budget {
3915 MM_STRIKES.store(0, Ordering::Relaxed);
3916 return;
3917 }
3918 if exempt || !MM_ARMED.load(Ordering::Relaxed) {
3919 return;
3920 }
3921 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3922 let on = *ON.get_or_init(|| std::env::var("CMF_MM_KILL").as_deref() != Ok("0"));
3923 let n = MM_STRIKES.fetch_add(1, Ordering::Relaxed) + 1;
3924 if !on {
3925 tracing::info!(
3926 "gpu {what} took {el:?} (budget {budget:?}) — over budget, CMF_MM_KILL=0 keeps the device"
3927 );
3928 return;
3929 }
3930 if n >= MM_STRIKES_TO_KILL {
3931 tracing::warn!(
3932 "gpu {what} took {el:?} (budget {budget:?}), {n} in a row — \
3933 device contended, CPU for the rest of the process (CMF_MM_KILL=0 to override)"
3934 );
3935 mm_kill();
3936 } else {
3937 tracing::info!(
3938 "gpu {what} took {el:?} (budget {budget:?}) — strike {n} of {MM_STRIKES_TO_KILL}"
3939 );
3940 }
3941}
3942
3943#[allow(unused_variables, clippy::too_many_arguments)]
3948pub fn chunk_attend(
3949 q: &[f32],
3950 k: &[&[f32]],
3951 v: &[&[f32]],
3952 b: usize,
3953 s0: usize,
3954 nh: usize,
3955 nkv: usize,
3956 hd: usize,
3957 scale: f32,
3958 out: &mut [f32],
3959) -> bool {
3960 match backend() {
3961 #[cfg(feature = "gpu")]
3962 Backend::Wgpu => crate::gpu_wgpu::chunk_attend(q, k, v, b, s0, nh, nkv, hd, scale, out),
3963 #[allow(unreachable_patterns)]
3964 _ => false,
3965 }
3966}
3967
3968#[allow(unused_variables, clippy::too_many_arguments)]
3971pub fn chunk_attend_win(
3972 q: &[f32],
3973 k: &[&[f32]],
3974 v: &[&[f32]],
3975 b: usize,
3976 s0: usize,
3977 nh: usize,
3978 nkv: usize,
3979 hd: usize,
3980 scale: f32,
3981 window: usize,
3982 out: &mut [f32],
3983) -> bool {
3984 match backend() {
3985 #[cfg(feature = "gpu")]
3986 Backend::Wgpu => {
3987 crate::gpu_wgpu::chunk_attend_win(q, k, v, b, s0, nh, nkv, hd, scale, window, out)
3988 }
3989 #[allow(unreachable_patterns)]
3990 _ => false,
3991 }
3992}
3993
3994#[allow(unused_variables)]
3997pub fn gemm_many_keep(
3998 model: &Arc<CmfModel>,
3999 idxs: &[(usize, usize)],
4000 xs: &[f32],
4001 b: usize,
4002 cols: usize,
4003 out: &mut [f32],
4004) -> bool {
4005 match backend() {
4006 #[cfg(feature = "gpu")]
4007 Backend::Wgpu => crate::gpu_wgpu::gemm_many_keep(model, idxs, xs, b, cols, out),
4008 #[allow(unreachable_patterns)]
4009 _ => false,
4010 }
4011}
4012
4013thread_local! {
4014 static PREFILL_FAST_GEMM: Cell<bool> = const { Cell::new(false) };
4018}
4019
4020pub struct PrefillFastGemmGuard(bool);
4022
4023impl Drop for PrefillFastGemmGuard {
4024 fn drop(&mut self) {
4025 PREFILL_FAST_GEMM.with(|c| c.set(self.0));
4026 }
4027}
4028
4029pub fn enter_prefill_fast_gemm() -> PrefillFastGemmGuard {
4033 PrefillFastGemmGuard(PREFILL_FAST_GEMM.with(|c| c.replace(true)))
4034}
4035
4036pub fn prefill_fast_gemm() -> bool {
4038 PREFILL_FAST_GEMM.with(|c| c.get())
4039}
4040
4041pub const F16_MAX: f32 = 65504.0;
4044
4045pub fn abs_max_or_inf(xs: &[f32]) -> f32 {
4049 let mut acc = [0f32; 16];
4050 let mut bad = [false; 16];
4051 let mut it = xs.chunks_exact(16);
4052 for c in &mut it {
4053 for ((a, f), &v) in acc.iter_mut().zip(bad.iter_mut()).zip(c) {
4054 let v = v.abs();
4055 *f |= !(v < f32::INFINITY);
4057 *a = if v > *a { v } else { *a };
4058 }
4059 }
4060 let mut m = 0f32;
4061 for &v in it.remainder() {
4062 let v = v.abs();
4063 if !(v < f32::INFINITY) {
4064 return f32::INFINITY;
4065 }
4066 m = m.max(v);
4067 }
4068 if bad.iter().any(|&f| f) {
4069 return f32::INFINITY;
4070 }
4071 acc.iter().fold(m, |m, &a| m.max(a))
4072}
4073
4074#[derive(Clone, Copy)]
4076pub struct GdnPreviewW<'a> {
4077 pub conv_right: &'a [f32],
4079 pub logit_scale: &'a [f32],
4080 pub history_bias: &'a [f32],
4081 pub history_c: &'a [f32],
4082}
4083
4084#[derive(Clone, Copy, Debug, PartialEq)]
4090pub struct BlockPreview {
4091 pub coreset_top_p: Option<f32>,
4093}
4094
4095thread_local! {
4096 static BLOCK_PREVIEW: Cell<Option<BlockPreview>> = const { Cell::new(None) };
4097}
4098
4099pub struct BlockPreviewGuard(Option<BlockPreview>);
4101
4102impl Drop for BlockPreviewGuard {
4103 fn drop(&mut self) {
4104 BLOCK_PREVIEW.with(|c| c.set(self.0));
4105 }
4106}
4107
4108pub fn enter_block_preview(p: BlockPreview) -> BlockPreviewGuard {
4110 BlockPreviewGuard(BLOCK_PREVIEW.with(|c| c.replace(Some(p))))
4111}
4112
4113pub fn block_preview() -> Option<BlockPreview> {
4115 BLOCK_PREVIEW.with(|c| c.get())
4116}
4117
4118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4124pub struct PrefillMirror {
4125 pub kv_id: u64,
4126 pub layer: usize,
4127 pub limit: usize,
4128}
4129
4130thread_local! {
4131 static PREFILL_MIRROR: Cell<Option<PrefillMirror>> = const { Cell::new(None) };
4135}
4136
4137pub struct PrefillMirrorGuard(Option<PrefillMirror>);
4139
4140impl Drop for PrefillMirrorGuard {
4141 fn drop(&mut self) {
4142 PREFILL_MIRROR.with(|c| c.set(self.0));
4143 }
4144}
4145
4146pub fn enter_prefill_mirror(t: PrefillMirror) -> PrefillMirrorGuard {
4149 PrefillMirrorGuard(PREFILL_MIRROR.with(|c| c.replace(Some(t))))
4150}
4151
4152pub fn prefill_mirror() -> Option<PrefillMirror> {
4154 PREFILL_MIRROR.with(|c| c.get())
4155}
4156
4157#[allow(unused_variables, clippy::too_many_arguments)]
4170pub fn chunk_attend_mirror(
4171 t: PrefillMirror,
4172 cpu_k: &[Vec<f32>],
4173 cpu_v: &[Vec<f32>],
4174 base: usize,
4175 q: &[f32],
4176 b: usize,
4177 s0: usize,
4178 nh: usize,
4179 nkv: usize,
4180 hd: usize,
4181 scale: f32,
4182 ring: Option<usize>,
4183 window: usize,
4184 operand_max: f32,
4185 out: &mut [f32],
4186) -> bool {
4187 match backend() {
4188 #[cfg(feature = "gpu")]
4189 Backend::Wgpu => crate::gpu_wgpu::chunk_attend_mirror(
4194 t.kv_id,
4195 t.layer,
4196 t.limit,
4197 cpu_k,
4198 cpu_v,
4199 base,
4200 q,
4201 b,
4202 s0,
4203 nh,
4204 nkv,
4205 hd,
4206 scale,
4207 ring,
4208 window,
4209 std::env::var("CMF_PREFILL_ATTN_COOP").as_deref() != Ok("0"),
4210 operand_max,
4211 out,
4212 ),
4213 #[allow(unreachable_patterns)]
4214 _ => false,
4215 }
4216}
4217
4218#[allow(unused_variables, clippy::too_many_arguments)]
4226pub fn chunk_attend_mirror_wo(
4227 t: PrefillMirror,
4228 cpu_k: &[Vec<f32>],
4229 cpu_v: &[Vec<f32>],
4230 base: usize,
4231 q: &[f32],
4232 b: usize,
4233 s0: usize,
4234 nh: usize,
4235 nkv: usize,
4236 hd: usize,
4237 scale: f32,
4238 ring: Option<usize>,
4239 window: usize,
4240 operand_max: f32,
4241 gains: Option<&[f32]>,
4242 wo: (&Arc<CmfModel>, usize),
4243 hidden: usize,
4244 out: &mut [f32],
4245) -> bool {
4246 match backend() {
4247 #[cfg(feature = "gpu")]
4248 Backend::Wgpu => crate::gpu_wgpu::chunk_attend_mirror_wo(
4249 t.kv_id,
4250 t.layer,
4251 t.limit,
4252 cpu_k,
4253 cpu_v,
4254 base,
4255 q,
4256 b,
4257 s0,
4258 nh,
4259 nkv,
4260 hd,
4261 scale,
4262 ring,
4263 window,
4264 std::env::var("CMF_PREFILL_ATTN_COOP").as_deref() != Ok("0"),
4265 operand_max,
4266 gains,
4267 wo,
4268 hidden,
4269 out,
4270 ),
4271 #[allow(unreachable_patterns)]
4272 _ => false,
4273 }
4274}
4275
4276pub fn chunk_attend_windowed() -> bool {
4278 match backend() {
4279 #[cfg(feature = "gpu")]
4280 Backend::Wgpu => true,
4281 #[allow(unreachable_patterns)]
4282 _ => false,
4283 }
4284}
4285
4286#[allow(unused_variables, clippy::too_many_arguments)]
4290pub fn q4t_qkv(
4291 model: &Arc<CmfModel>,
4292 wq: usize,
4293 wk: usize,
4294 wv: usize,
4295 xs: &[f32],
4296 b: usize,
4297 cols: usize,
4298 rq: usize,
4299 rk: usize,
4300 rv: usize,
4301 out: &mut [f32],
4302) -> bool {
4303 match backend() {
4304 #[cfg(feature = "gpu")]
4305 Backend::Wgpu => crate::gpu_wgpu::q4t_qkv(model, wq, wk, wv, xs, b, cols, rq, rk, rv, out),
4306 #[allow(unreachable_patterns)]
4307 _ => false,
4308 }
4309}
4310
4311#[allow(unused_variables, clippy::too_many_arguments)]
4313#[allow(clippy::too_many_arguments, unused_variables)]
4317pub fn q4tp_ffn_packed(
4318 model: &Arc<CmfModel>,
4319 w1: usize,
4320 w2: usize,
4321 xs: &[f32],
4322 b: usize,
4323 hidden: usize,
4324 inter: usize,
4325 bias: Option<&[f32]>,
4326 out: &mut [f32],
4327) -> bool {
4328 match backend() {
4329 #[cfg(feature = "gpu")]
4330 Backend::Wgpu => {
4331 crate::gpu_wgpu::ffn_packed(model, w1, w2, xs, b, hidden, inter, bias, out)
4332 }
4333 #[allow(unreachable_patterns)]
4334 _ => false,
4335 }
4336}
4337
4338pub fn q4tp_ffn(
4339 model: &Arc<CmfModel>,
4340 w1: usize,
4341 w3: usize,
4342 w2: usize,
4343 xs: &[f32],
4344 b: usize,
4345 hidden: usize,
4346 inter: usize,
4347 out: &mut [f32],
4348) -> bool {
4349 match backend() {
4350 #[cfg(target_os = "macos")]
4351 Backend::Metal => crate::gpu_metal::q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4352 #[cfg(feature = "gpu")]
4353 Backend::Wgpu => crate::gpu_wgpu::q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4354 #[allow(unreachable_patterns)]
4355 _ => false,
4356 }
4357}
4358
4359#[allow(clippy::too_many_arguments, unused_variables)]
4363pub fn q4_ffn_act(
4364 model: &Arc<CmfModel>,
4365 w1: usize,
4366 w3: usize,
4367 w2: usize,
4368 xs: &[f32],
4369 b: usize,
4370 hidden: usize,
4371 inter: usize,
4372 q4tp: bool,
4373 act: GraphAct,
4374 out: &mut [f32],
4375) -> bool {
4376 match act {
4377 GraphAct::Silu if q4tp => q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4378 GraphAct::Silu => q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4379 GraphAct::GeluErf | GraphAct::GeluTanh | GraphAct::SwiGluOaiM3 => match backend() {
4383 #[cfg(feature = "gpu")]
4384 Backend::Wgpu => crate::gpu_wgpu::q4_ffn_act(
4385 model,
4386 w1,
4387 w3,
4388 w2,
4389 xs,
4390 b,
4391 hidden,
4392 inter,
4393 q4tp,
4394 act.code(),
4395 out,
4396 ),
4397 #[allow(unreachable_patterns)]
4398 _ => false,
4399 },
4400 }
4401}
4402
4403#[allow(clippy::too_many_arguments, unused_variables)]
4408pub fn ffn_act_keep(
4409 model: &Arc<CmfModel>,
4410 w1: usize,
4411 w3: usize,
4412 w2: usize,
4413 xs: &[f32],
4414 b: usize,
4415 hidden: usize,
4416 inter: usize,
4417 act: GraphAct,
4418 out: &mut [f32],
4419) -> bool {
4420 match backend() {
4421 #[cfg(feature = "gpu")]
4422 Backend::Wgpu => crate::gpu_wgpu::ffn_act_keep(
4423 model,
4424 w1,
4425 w3,
4426 w2,
4427 xs,
4428 b,
4429 hidden,
4430 inter,
4431 act.code(),
4432 out,
4433 ),
4434 #[allow(unreachable_patterns)]
4435 _ => false,
4436 }
4437}
4438
4439#[allow(clippy::too_many_arguments, unused_variables)]
4444pub fn q4tp_gelu_ffn(
4445 model: &Arc<CmfModel>,
4446 w_in: usize,
4447 w_out: usize,
4448 xs: &[f32],
4449 b: usize,
4450 hidden: usize,
4451 inter: usize,
4452 bias_in: &[f32],
4453 bias_out: &[f32],
4454 out: &mut [f32],
4455) -> bool {
4456 match backend() {
4457 #[cfg(feature = "gpu")]
4458 Backend::Wgpu => crate::gpu_wgpu::q4tp_gelu_ffn(
4459 model, w_in, w_out, xs, b, hidden, inter, bias_in, bias_out, out,
4460 ),
4461 #[allow(unreachable_patterns)]
4462 _ => false,
4463 }
4464}
4465
4466pub fn q4t_ffn(
4467 model: &Arc<CmfModel>,
4468 w1: usize,
4469 w3: usize,
4470 w2: usize,
4471 xs: &[f32],
4472 b: usize,
4473 hidden: usize,
4474 inter: usize,
4475 out: &mut [f32],
4476) -> bool {
4477 match backend() {
4478 #[cfg(target_os = "macos")]
4479 Backend::Metal => crate::gpu_metal::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4480 #[cfg(feature = "gpu")]
4481 Backend::Wgpu => crate::gpu_wgpu::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
4482 #[allow(unreachable_patterns)]
4483 _ => false,
4484 }
4485}
4486
4487pub struct DitBlockArgs<'a> {
4492 pub n: usize,
4493 pub hidden: usize,
4494 pub inter: usize,
4495 pub nh: usize,
4496 pub nkv: usize,
4497 pub hd: usize,
4498 pub eps: f32,
4499 pub rope_cos: &'a [f32],
4500 pub rope_sin: &'a [f32],
4501 pub norm1: &'a [f32],
4502 pub norm2: &'a [f32],
4503 pub ffn_norm1: &'a [f32],
4504 pub ffn_norm2: &'a [f32],
4505 pub norm_q: &'a [f32],
4506 pub norm_k: &'a [f32],
4507 pub s_msa: &'a [f32],
4508 pub gate_msa: &'a [f32],
4509 pub s_mlp: &'a [f32],
4510 pub gate_mlp: &'a [f32],
4511 pub wq: usize,
4512 pub wk: usize,
4513 pub wv: usize,
4514 pub wo: usize,
4515 pub w1: usize,
4516 pub w3: usize,
4517 pub w2: usize,
4518 pub q4tp: bool,
4522 pub resident_in: bool,
4525 pub resident_out: bool,
4529}
4530
4531pub fn dit_chain_supported() -> bool {
4535 #[cfg(feature = "gpu")]
4536 {
4537 return matches!(backend(), Backend::Wgpu) && fused_dit_block_available();
4538 }
4539 #[allow(unreachable_code)]
4540 false
4541}
4542
4543pub fn dit_state_fetch(_x: &mut [f32]) -> bool {
4546 #[cfg(feature = "gpu")]
4547 {
4548 if matches!(backend(), Backend::Wgpu) {
4549 return crate::gpu_wgpu::dit_state_fetch(_x);
4550 }
4551 }
4552 false
4553}
4554
4555#[allow(unused_variables)]
4559#[allow(unused_variables, clippy::too_many_arguments)]
4563pub fn dit_qkv(
4564 model: &Arc<CmfModel>,
4565 wq: usize,
4566 wk: usize,
4567 wv: usize,
4568 xs: &[f32],
4569 b: usize,
4570 hidden: usize,
4571 qrows: usize,
4572 kvrows: usize,
4573 q_out: &mut [f32],
4574 k_out: &mut [f32],
4575 v_out: &mut [f32],
4576) -> bool {
4577 match backend() {
4578 #[cfg(feature = "gpu")]
4579 Backend::Wgpu => crate::gpu_wgpu::q4tp_qkv(
4580 model, wq, wk, wv, xs, b, hidden, qrows, kvrows, q_out, k_out, v_out,
4581 ),
4582 #[allow(unreachable_patterns)]
4583 _ => false,
4584 }
4585}
4586
4587pub struct QwenImageAttentionArgs<'a> {
4595 pub image: &'a [f32],
4596 pub text: &'a [f32],
4597 pub image_tokens: usize,
4598 pub text_tokens: usize,
4599 pub heads: usize,
4600 pub head_dim: usize,
4601 pub image_q: usize,
4602 pub image_k: usize,
4603 pub image_v: usize,
4604 pub text_q: usize,
4605 pub text_k: usize,
4606 pub text_v: usize,
4607 pub image_out: usize,
4608 pub text_out: usize,
4609 pub image_q_norm: &'a [f32],
4610 pub image_k_norm: &'a [f32],
4611 pub text_q_norm: &'a [f32],
4612 pub text_k_norm: &'a [f32],
4613 pub image_cos: &'a [f32],
4614 pub image_sin: &'a [f32],
4615 pub text_cos: &'a [f32],
4616 pub text_sin: &'a [f32],
4617 pub image_q_bias: &'a [f32],
4618 pub image_k_bias: &'a [f32],
4619 pub image_v_bias: &'a [f32],
4620 pub text_q_bias: &'a [f32],
4621 pub text_k_bias: &'a [f32],
4622 pub text_v_bias: &'a [f32],
4623 pub image_out_bias: &'a [f32],
4624 pub text_out_bias: &'a [f32],
4625 pub image_proj: &'a mut [f32],
4626 pub text_proj: &'a mut [f32],
4627}
4628
4629#[allow(clippy::too_many_fields)]
4634pub struct QwenImageChainBlock<'a> {
4635 pub image_mod: &'a [f32],
4636 pub text_mod: &'a [f32],
4637 pub image_q: usize,
4638 pub image_k: usize,
4639 pub image_v: usize,
4640 pub text_q: usize,
4641 pub text_k: usize,
4642 pub text_v: usize,
4643 pub image_out: usize,
4644 pub text_out: usize,
4645 pub image_q_norm: &'a [f32],
4646 pub image_k_norm: &'a [f32],
4647 pub text_q_norm: &'a [f32],
4648 pub text_k_norm: &'a [f32],
4649 pub image_q_bias: &'a [f32],
4650 pub image_k_bias: &'a [f32],
4651 pub image_v_bias: &'a [f32],
4652 pub text_q_bias: &'a [f32],
4653 pub text_k_bias: &'a [f32],
4654 pub text_v_bias: &'a [f32],
4655 pub image_out_bias: &'a [f32],
4656 pub text_out_bias: &'a [f32],
4657 pub image_attn_gate: &'a [f32],
4658 pub text_attn_gate: &'a [f32],
4659 pub image_mlp_in: usize,
4660 pub image_mlp_out: usize,
4661 pub text_mlp_in: usize,
4662 pub text_mlp_out: usize,
4663 pub image_mlp_in_bias: &'a [f32],
4664 pub image_mlp_out_bias: &'a [f32],
4665 pub text_mlp_in_bias: &'a [f32],
4666 pub text_mlp_out_bias: &'a [f32],
4667}
4668
4669#[allow(clippy::too_many_fields)]
4675pub struct QwenImageBlockArgs<'a> {
4676 pub image: &'a mut [f32],
4679 pub text: &'a mut [f32],
4680 pub image_norm: &'a [f32],
4681 pub text_norm: &'a [f32],
4682 pub image_tokens: usize,
4683 pub text_tokens: usize,
4684 pub heads: usize,
4685 pub head_dim: usize,
4686 pub image_cos: &'a [f32],
4687 pub image_sin: &'a [f32],
4688 pub text_cos: &'a [f32],
4689 pub text_sin: &'a [f32],
4690 pub image_q: usize,
4691 pub image_k: usize,
4692 pub image_v: usize,
4693 pub text_q: usize,
4694 pub text_k: usize,
4695 pub text_v: usize,
4696 pub image_out: usize,
4697 pub text_out: usize,
4698 pub image_q_norm: &'a [f32],
4699 pub image_k_norm: &'a [f32],
4700 pub text_q_norm: &'a [f32],
4701 pub text_k_norm: &'a [f32],
4702 pub image_q_bias: &'a [f32],
4703 pub image_k_bias: &'a [f32],
4704 pub image_v_bias: &'a [f32],
4705 pub text_q_bias: &'a [f32],
4706 pub text_k_bias: &'a [f32],
4707 pub text_v_bias: &'a [f32],
4708 pub image_out_bias: &'a [f32],
4709 pub text_out_bias: &'a [f32],
4710 pub image_attn_gate: &'a [f32],
4711 pub text_attn_gate: &'a [f32],
4712 pub image_mlp_in: usize,
4713 pub image_mlp_out: usize,
4714 pub text_mlp_in: usize,
4715 pub text_mlp_out: usize,
4716 pub image_mlp_in_bias: &'a [f32],
4717 pub image_mlp_out_bias: &'a [f32],
4718 pub text_mlp_in_bias: &'a [f32],
4719 pub text_mlp_out_bias: &'a [f32],
4720 pub image_mlp_mod: &'a [f32],
4721 pub text_mlp_mod: &'a [f32],
4722 pub image_mlp_gate: &'a [f32],
4723 pub text_mlp_gate: &'a [f32],
4724}
4725
4726pub struct QwenImageChainArgs<'a> {
4731 pub image: &'a mut [f32],
4732 pub text: &'a mut [f32],
4733 pub image_tokens: usize,
4734 pub text_tokens: usize,
4735 pub heads: usize,
4736 pub head_dim: usize,
4737 pub image_cos: &'a [f32],
4738 pub image_sin: &'a [f32],
4739 pub text_cos: &'a [f32],
4740 pub text_sin: &'a [f32],
4741 pub blocks: &'a [QwenImageChainBlock<'a>],
4742}
4743
4744#[allow(unused_variables)]
4745pub fn qwen_image_attention(
4746 model: &Arc<CmfModel>,
4747 args: &mut QwenImageAttentionArgs<'_>,
4748) -> bool {
4749 match backend() {
4750 #[cfg(feature = "gpu")]
4751 Backend::Wgpu => crate::gpu_wgpu::qwen_image_attention(model, args),
4752 #[allow(unreachable_patterns)]
4753 _ => false,
4754 }
4755}
4756
4757#[allow(unused_variables)]
4758pub fn qwen_image_block(model: &Arc<CmfModel>, args: &mut QwenImageBlockArgs<'_>) -> bool {
4759 match backend() {
4760 #[cfg(feature = "gpu")]
4761 Backend::Wgpu => crate::gpu_wgpu::qwen_image_block(model, args),
4762 #[allow(unreachable_patterns)]
4763 _ => false,
4764 }
4765}
4766
4767#[allow(unused_variables)]
4771pub fn qwen_image_chain(model: &Arc<CmfModel>, args: &mut QwenImageChainArgs<'_>) -> bool {
4772 match backend() {
4773 #[cfg(feature = "gpu")]
4774 Backend::Wgpu => {
4775 #[cfg(not(target_os = "macos"))]
4777 if crate::gpu_wgpu::h3::qwen_chain(model, args) {
4778 return true;
4779 }
4780 crate::gpu_wgpu::qwen_image_chain(model, args)
4781 }
4782 #[cfg(feature = "cuda")]
4783 Backend::Cuda => crate::gpu_cuda::qwen_image_chain(model, args),
4784 #[allow(unreachable_patterns)]
4785 _ => false,
4786 }
4787}
4788
4789pub struct MossChainBlock<'a> {
4792 pub norm1: &'a [f32],
4793 pub norm2: &'a [f32],
4794 pub q_norm: &'a [f32],
4795 pub k_norm: &'a [f32],
4796 pub q: usize,
4797 pub k: usize,
4798 pub v: usize,
4799 pub o: usize,
4800 pub up_gate: usize,
4802 pub down: usize,
4803}
4804
4805pub struct MossChainArgs<'a> {
4809 pub x: &'a mut [f32],
4810 pub tokens: usize,
4811 pub heads: usize,
4812 pub head_dim: usize,
4813 pub modulation: &'a [f32],
4814 pub cos: &'a [f32],
4815 pub sin: &'a [f32],
4816 pub blocks: &'a [MossChainBlock<'a>],
4817}
4818
4819#[allow(unused_variables)]
4822pub fn moss_chain(model: &Arc<CmfModel>, args: &mut MossChainArgs<'_>) -> bool {
4823 match backend() {
4824 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
4825 Backend::Wgpu => crate::gpu_wgpu::h3::moss_chain(model, args),
4826 #[cfg(feature = "cuda")]
4827 Backend::Cuda => crate::gpu_cuda::moss_chain(model, args),
4828 #[cfg(target_os = "macos")]
4829 Backend::Metal => crate::gpu_metal::h3::moss_chain(model, args),
4830 #[allow(unreachable_patterns)]
4831 _ => false,
4832 }
4833}
4834
4835#[allow(unused_variables, clippy::too_many_arguments)]
4842pub fn qwen_image_mlp_inplace(
4843 model: &Arc<CmfModel>,
4844 w_in: usize,
4845 w_out: usize,
4846 data: &mut [f32],
4847 batch: usize,
4848 hidden: usize,
4849 inter: usize,
4850 bias_in: &[f32],
4851 bias_out: &[f32],
4852 modulation: &[f32],
4853 gate: &[f32],
4854) -> bool {
4855 match backend() {
4856 #[cfg(feature = "gpu")]
4857 Backend::Wgpu => crate::gpu_wgpu::qwen_image_mlp_inplace(
4858 model,
4859 w_in,
4860 w_out,
4861 data,
4862 batch,
4863 hidden,
4864 inter,
4865 bias_in,
4866 bias_out,
4867 modulation,
4868 gate,
4869 ),
4870 #[allow(unreachable_patterns)]
4871 _ => false,
4872 }
4873}
4874
4875pub fn fused_dit_block_available() -> bool {
4879 #[cfg(target_os = "macos")]
4880 {
4881 matches!(backend(), Backend::Metal) && fused_block_trusted()
4882 }
4883 #[cfg(not(target_os = "macos"))]
4884 {
4885 false
4886 }
4887}
4888
4889pub fn dit_block(model: &Arc<CmfModel>, a: &DitBlockArgs, x: &mut [f32]) -> bool {
4890 dit_block_seg(model, a, &[a.n], x)
4891}
4892
4893pub fn dit_block_seg(
4897 model: &Arc<CmfModel>,
4898 a: &DitBlockArgs,
4899 segs: &[usize],
4900 x: &mut [f32],
4901) -> bool {
4902 match backend() {
4903 #[cfg(target_os = "macos")]
4904 Backend::Metal if segs.len() <= 1 => crate::gpu_metal::dit_block(model, a, x),
4905 #[cfg(feature = "gpu")]
4912 Backend::Wgpu
4913 if match std::env::var("CMF_DIT_FUSED").ok().as_deref() {
4914 Some("0") => false,
4915 Some(_) => true,
4916 None => crate::gpu_wgpu::discrete_active(),
4917 } =>
4918 {
4919 crate::gpu_wgpu::dit_block_seg(model, a, segs, x)
4920 }
4921 #[cfg(feature = "cuda")]
4924 Backend::Cuda => crate::gpu_cuda::lumina_block(model, a, segs, x),
4925 #[allow(unreachable_patterns)]
4926 _ => false,
4927 }
4928}
4929
4930pub struct VaeResnetArgs<'a> {
4934 pub groups: usize,
4935 pub ic: usize,
4936 pub oc: usize,
4937 pub h: usize,
4938 pub w: usize,
4939 pub n1w: &'a [f32],
4940 pub n1b: &'a [f32],
4941 pub c1w: &'a [f32],
4942 pub c1b: &'a [f32],
4943 pub c1k: usize,
4944 pub n2w: &'a [f32],
4945 pub n2b: &'a [f32],
4946 pub c2w: &'a [f32],
4947 pub c2b: &'a [f32],
4948 pub c2k: usize,
4949 pub shortcut: Option<(&'a [f32], &'a [f32], usize)>,
4950}
4951
4952#[allow(unused_variables)]
4955pub fn vae_resnet(a: &VaeResnetArgs, x: &[f32], out: &mut [f32]) -> bool {
4956 match backend() {
4957 #[cfg(target_os = "macos")]
4958 Backend::Metal => crate::gpu_metal::vae_resnet(a, x, out),
4959 _ => false,
4960 }
4961}
4962
4963#[allow(unused_variables, clippy::too_many_arguments)]
4966pub fn vae_upsample_conv(
4967 w: &[f32],
4968 bias: &[f32],
4969 x: &[f32],
4970 ic: usize,
4971 oc: usize,
4972 h: usize,
4973 w_img: usize,
4974 k: usize,
4975 out: &mut [f32],
4976) -> bool {
4977 match backend() {
4978 #[cfg(target_os = "macos")]
4979 Backend::Metal => crate::gpu_metal::vae_upsample_conv(w, bias, x, ic, oc, h, w_img, k, out),
4980 #[cfg(feature = "gpu")]
4981 Backend::Wgpu => crate::gpu_wgpu::vae_upsample_conv(w, bias, x, ic, oc, h, w_img, k, out),
4982 #[cfg(feature = "cuda")]
4983 Backend::Cuda => crate::gpu_cuda::h3_vae_conv2d(w, bias, x, ic, oc, h, w_img, k, true, out),
4984 #[allow(unreachable_patterns)]
4985 _ => false,
4986 }
4987}
4988
4989#[allow(unused_variables, clippy::too_many_arguments)]
4992pub fn vae_conv2d(
4993 w: &[f32],
4994 bias: &[f32],
4995 x: &[f32],
4996 ic: usize,
4997 oc: usize,
4998 h: usize,
4999 w_img: usize,
5000 k: usize,
5001 out: &mut [f32],
5002) -> bool {
5003 match backend() {
5004 #[cfg(target_os = "macos")]
5005 Backend::Metal => crate::gpu_metal::vae_conv2d(w, bias, x, ic, oc, h, w_img, k, out),
5006 #[cfg(feature = "gpu")]
5007 Backend::Wgpu => crate::gpu_wgpu::vae_conv2d(w, bias, x, ic, oc, h, w_img, k, out),
5008 #[cfg(feature = "cuda")]
5009 Backend::Cuda => crate::gpu_cuda::h3_vae_conv2d(w, bias, x, ic, oc, h, w_img, k, false, out),
5010 #[allow(unreachable_patterns)]
5011 _ => false,
5012 }
5013}
5014
5015#[allow(unused_variables, clippy::too_many_arguments)]
5019#[allow(unused_variables)]
5023#[allow(clippy::too_many_arguments)]
5024#[allow(clippy::too_many_arguments, unused_variables)]
5027pub fn dit_qkv_attention(
5028 model: &Arc<CmfModel>,
5029 qkv_idx: usize,
5030 xn: &[f32],
5031 n: usize,
5032 hidden: usize,
5033 nh: usize,
5034 hd: usize,
5035 scale: f32,
5036 nr: (&[f32], &[f32], &[f32], f32),
5037 out: &mut [f32],
5038) -> bool {
5039 match backend() {
5040 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5041 Backend::Wgpu => crate::gpu_wgpu::dit_qkv_attention(
5042 model, qkv_idx, xn, n, hidden, nh, hd, scale, nr, out,
5043 ),
5044 #[allow(unreachable_patterns)]
5045 _ => false,
5046 }
5047}
5048
5049pub struct H3ChainBlock<'a> {
5052 pub qkv: usize,
5053 pub out: usize,
5054 pub fc1: usize,
5055 pub fc2: usize,
5056 pub norm1: &'a [f32],
5057 pub norm2: &'a [f32],
5058 pub q_norm: &'a [f32],
5059 pub k_norm: &'a [f32],
5060 pub mods: &'a [f32],
5063 pub qkv_bias: &'a [f32],
5066 pub out_bias: &'a [f32],
5067 pub fc1_bias: &'a [f32],
5068 pub fc2_bias: &'a [f32],
5069 pub scale1: &'a [f32],
5070 pub scale2: &'a [f32],
5071 pub gate: usize,
5074}
5075
5076pub struct H3Chain<'a> {
5078 pub model: &'a Arc<CmfModel>,
5079 pub blocks: &'a [H3ChainBlock<'a>],
5080 pub n: usize,
5081 pub hidden: usize,
5082 pub heads: usize,
5083 pub head_dim: usize,
5084 pub ffn: usize,
5085 pub eps: f32,
5086 pub qk_eps: f32,
5087 pub angles: &'a [f32],
5089 pub rows: &'a [u32],
5091 pub groups: usize,
5095 pub qkv_interleaved: bool,
5098 pub vsa: Option<&'a crate::mmh3::VsaPlan>,
5102}
5103
5104pub struct TeChainLayer<'a> {
5107 pub q: usize,
5108 pub k: usize,
5109 pub v: usize,
5110 pub o: usize,
5111 pub gate: usize,
5112 pub up: usize,
5113 pub down: usize,
5114 pub input_norm: &'a [f32],
5115 pub post_norm: &'a [f32],
5116 pub q_norm: &'a [f32],
5117 pub k_norm: &'a [f32],
5118}
5119
5120pub struct TeChain<'a> {
5122 pub model: &'a Arc<CmfModel>,
5123 pub layers: &'a [TeChainLayer<'a>],
5124 pub n: usize,
5125 pub hidden: usize,
5126 pub heads: usize,
5127 pub kv_heads: usize,
5128 pub head_dim: usize,
5129 pub inter: usize,
5130 pub eps: f32,
5131 pub cs: &'a [f32],
5133}
5134
5135#[allow(unused_variables)]
5138pub fn te_chain(job: &TeChain<'_>, h: &mut [f32]) -> bool {
5139 match backend() {
5140 #[cfg(feature = "cuda")]
5141 Backend::Cuda => crate::gpu_cuda::h3_te_chain(job, h),
5142 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5143 Backend::Wgpu => crate::gpu_wgpu::h3::te_chain(job, h),
5144 #[cfg(target_os = "macos")]
5145 Backend::Metal => crate::gpu_metal::h3::te_chain(job, h),
5146 #[allow(unreachable_patterns)]
5147 _ => false,
5148 }
5149}
5150
5151#[derive(Clone, Copy)]
5155pub struct LtxLin<'a> {
5156 pub w: Option<usize>,
5157 pub dense: &'a [f32],
5158 pub rows: usize,
5159 pub cols: usize,
5160 pub bias: &'a [f32],
5161}
5162
5163#[derive(Clone, Copy)]
5168pub struct LtxAttn<'a> {
5169 pub q: LtxLin<'a>,
5170 pub k: LtxLin<'a>,
5171 pub v: LtxLin<'a>,
5172 pub o: LtxLin<'a>,
5173 pub q_norm: &'a [f32],
5174 pub k_norm: &'a [f32],
5175 pub gate: Option<LtxLin<'a>>,
5176 pub heads: usize,
5177 pub dh: usize,
5178}
5179
5180pub struct LtxStream<'a> {
5182 pub attn1: LtxAttn<'a>,
5183 pub attn2: LtxAttn<'a>,
5184 pub ff_in: LtxLin<'a>,
5185 pub ff_out: LtxLin<'a>,
5186 pub mods: &'a [f32],
5190 pub ctx_mod: &'a [f32],
5192}
5193
5194pub struct LtxBlock<'a> {
5196 pub video: LtxStream<'a>,
5197 pub audio: LtxStream<'a>,
5198 pub a2v: LtxAttn<'a>,
5199 pub v2a: LtxAttn<'a>,
5200 pub xmods_v: &'a [f32],
5203 pub xmods_a: &'a [f32],
5205 pub gate_a2v: &'a [f32],
5207 pub gate_v2a: &'a [f32],
5209}
5210
5211pub struct LtxSide<'a> {
5213 pub n: usize,
5214 pub dim: usize,
5215 pub rows: &'a [u32],
5217 pub xrows: &'a [u32],
5219 pub pe: (&'a [f32], &'a [f32], usize),
5222 pub xpe: (&'a [f32], &'a [f32], usize),
5224 pub ctx: &'a [f32],
5226 pub ctx_len: usize,
5227 pub mask: &'a [f32],
5229}
5230
5231pub struct LtxChain<'a> {
5233 pub model: &'a Arc<CmfModel>,
5234 pub blocks: &'a [LtxBlock<'a>],
5235 pub video: LtxSide<'a>,
5236 pub audio: LtxSide<'a>,
5237}
5238
5239pub fn ltx_chain_available() -> bool {
5241 match backend() {
5242 #[cfg(feature = "cuda")]
5243 Backend::Cuda => true,
5244 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5245 Backend::Wgpu => crate::gpu_wgpu::h3::ltx_available(),
5246 #[allow(unreachable_patterns)]
5247 _ => false,
5248 }
5249}
5250
5251#[allow(unused_variables)]
5255pub fn ltx_chain(job: &LtxChain<'_>, vx: &mut [f32], ax: &mut [f32]) -> bool {
5256 match backend() {
5257 #[cfg(feature = "cuda")]
5258 Backend::Cuda => crate::gpu_cuda::ltx_chain(job, vx, ax),
5259 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5260 Backend::Wgpu => crate::gpu_wgpu::h3::ltx_chain(job, vx, ax),
5261 #[allow(unreachable_patterns)]
5262 _ => false,
5263 }
5264}
5265
5266pub enum Vae3dStep<'a> {
5269 Conv { w: &'a [f32], b: &'a [f32], in_ch: usize, out_ch: usize },
5272 NormSilu { eps: f32 },
5275 Save,
5277 AddSaved,
5279 DepthToSpace { p: (usize, usize, usize) },
5282}
5283
5284#[allow(unused_variables)]
5287pub fn vae3d_chain(
5288 steps: &[Vae3dStep<'_>],
5289 x: &[f32],
5290 c: usize,
5291 f: usize,
5292 h: usize,
5293 w: usize,
5294) -> Option<(Vec<f32>, usize, usize, usize, usize)> {
5295 match backend() {
5296 #[cfg(feature = "cuda")]
5297 Backend::Cuda => crate::gpu_cuda::ltx_vae_chain(steps, x, c, f, h, w),
5298 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5299 Backend::Wgpu => crate::gpu_wgpu::h3::ltx_vae_chain(steps, x, c, f, h, w),
5300 #[allow(unreachable_patterns)]
5301 _ => None,
5302 }
5303}
5304
5305pub enum ConvStep<'a> {
5307 GnSilu { w: &'a [f32], b: &'a [f32] },
5309 Conv {
5313 w: &'a [f32],
5314 b: &'a [f32],
5315 out_ch: usize,
5316 in_ch: usize,
5317 k: usize,
5318 stride: usize,
5319 pad: usize,
5320 far: bool,
5321 },
5322 Save,
5324 AddSaved { via: Option<(&'a [f32], &'a [f32])> },
5327}
5328
5329#[allow(unused_variables)]
5332pub fn conv_chain(steps: &[ConvStep<'_>], x: &[f32], c: usize, h: usize, w: usize) -> Option<(Vec<f32>, usize, usize, usize)> {
5333 match backend() {
5334 #[cfg(feature = "cuda")]
5335 Backend::Cuda => crate::gpu_cuda::h3_conv_chain(steps, x, c, h, w),
5336 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5337 Backend::Wgpu => crate::gpu_wgpu::h3_conv::conv_chain(steps, x, c, h, w),
5338 #[allow(unreachable_patterns)]
5339 _ => None,
5340 }
5341}
5342
5343pub fn h3_chain_available() -> bool {
5345 match backend() {
5346 #[cfg(feature = "cuda")]
5347 Backend::Cuda => true,
5348 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5349 Backend::Wgpu => crate::gpu_wgpu::h3::available(),
5350 #[cfg(target_os = "macos")]
5351 Backend::Metal => crate::gpu_metal::h3::available(),
5352 #[allow(unreachable_patterns)]
5353 _ => false,
5354 }
5355}
5356
5357#[allow(unused_variables)]
5361pub fn h3_chain(job: &H3Chain<'_>, h: &mut [f32]) -> bool {
5362 match backend() {
5363 #[cfg(feature = "cuda")]
5364 Backend::Cuda => crate::gpu_cuda::h3_chain(job, h),
5365 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5369 Backend::Wgpu => crate::gpu_wgpu::h3::chain(job, h),
5370 #[cfg(target_os = "macos")]
5371 Backend::Metal => (job.vsa.is_none() || std::env::var("CMF_H3_METAL_VSA").as_deref() != Ok("0")) && crate::gpu_metal::h3::chain(job, h),
5372 #[allow(unreachable_patterns)]
5373 _ => false,
5374 }
5375}
5376
5377#[allow(clippy::too_many_arguments)]
5380pub fn dit_qkv_attn_out(
5381 model: &Arc<CmfModel>,
5382 qkv_idx: usize,
5383 out_idx: usize,
5384 xn: &[f32],
5385 n: usize,
5386 hidden: usize,
5387 nh: usize,
5388 hd: usize,
5389 scale: f32,
5390 nr: (&[f32], &[f32], &[f32], f32),
5391 proj: &mut [f32],
5392) -> bool {
5393 match backend() {
5394 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5395 Backend::Wgpu => crate::gpu_wgpu::dit_qkv_attn_out(
5396 model, qkv_idx, out_idx, xn, n, hidden, nh, hd, scale, nr, proj,
5397 ),
5398 #[allow(unreachable_patterns)]
5399 _ => false,
5400 }
5401}
5402
5403#[allow(clippy::too_many_arguments)]
5405pub fn vae_qkv_attn_out(
5406 model: &Arc<CmfModel>,
5407 qkv_idx: usize,
5408 out_idx: usize,
5409 xn: &[f32],
5410 n: usize,
5411 dim: usize,
5412 nh: usize,
5413 hd: usize,
5414 scale: f32,
5415 angles: &[f32],
5416 eps: f32,
5417 qkv_bias: &[f32],
5418 proj: &mut [f32],
5419) -> bool {
5420 match backend() {
5421 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5422 Backend::Wgpu => crate::gpu_wgpu::vae_qkv_attn_out(
5423 model, qkv_idx, out_idx, xn, n, dim, nh, hd, scale, angles, eps, qkv_bias, proj,
5424 ),
5425 #[allow(unreachable_patterns)]
5426 _ => false,
5427 }
5428}
5429
5430#[allow(clippy::too_many_arguments)]
5431pub fn vae_attention_packed(
5432 qkv: &[f32],
5433 nh: usize,
5434 n: usize,
5435 hd: usize,
5436 scale: f32,
5437 angles: &[f32],
5438 eps: f32,
5439 out: &mut [f32],
5440) -> bool {
5441 vae_attention_packed_layout(qkv, nh, n, hd, scale, angles, eps, out, 1)
5442}
5443
5444#[allow(clippy::too_many_arguments)]
5445pub fn vae_attention_packed_layout(
5446 qkv: &[f32],
5447 nh: usize,
5448 n: usize,
5449 hd: usize,
5450 scale: f32,
5451 angles: &[f32],
5452 eps: f32,
5453 out: &mut [f32],
5454 layout: u32,
5455) -> bool {
5456 match backend() {
5457 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5458 Backend::Wgpu => crate::gpu_wgpu::vae_attention_packed_layout(
5459 qkv, nh, n, hd, scale, angles, eps, out, layout,
5460 ),
5461 #[allow(unreachable_patterns)]
5462 _ => false,
5463 }
5464}
5465
5466#[allow(clippy::too_many_arguments)]
5467pub fn dit_split_only(
5468 qkv: &[f32],
5469 nh: usize,
5470 n: usize,
5471 hd: usize,
5472 layout: u32,
5473 norm: Option<(&[f32], f32)>,
5474 out_q: &mut [f32],
5475) -> bool {
5476 match backend() {
5477 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5478 Backend::Wgpu => crate::gpu_wgpu::dit_split_only(qkv, nh, n, hd, layout, norm, out_q),
5479 #[allow(unreachable_patterns)]
5480 _ => false,
5481 }
5482}
5483
5484pub fn gemm_nt_f32_transient(
5492 x: &[f32],
5493 w: &[f32],
5494 y: &mut [f32],
5495 n: usize,
5496 k: usize,
5497 m: usize,
5498) -> bool {
5499 match backend() {
5500 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5501 Backend::Wgpu => crate::gpu_wgpu::gemm_nt_f32_transient(x, w, y, n, k, m),
5502 #[allow(unreachable_patterns)]
5503 _ => false,
5504 }
5505}
5506
5507pub struct VitLayer<'a> {
5511 pub ln1_w: &'a [f32],
5512 pub ln1_b: &'a [f32],
5513 pub qkv: &'a [f32],
5514 pub qkv_b: &'a [f32],
5515 pub proj: &'a [f32],
5516 pub proj_b: &'a [f32],
5517 pub ln2_w: &'a [f32],
5518 pub ln2_b: &'a [f32],
5519 pub fc1: &'a [f32],
5520 pub fc1_b: &'a [f32],
5521 pub fc2: &'a [f32],
5522 pub fc2_b: &'a [f32],
5523}
5524
5525pub struct VitArgs<'a> {
5530 pub key: u64,
5531 pub layers: Vec<VitLayer<'a>>,
5532 pub n: usize,
5533 pub d: usize,
5534 pub heads: usize,
5535 pub head_dim: usize,
5536 pub inter: usize,
5537 pub eps: f64,
5538 pub gelu_tanh: bool,
5539 pub quick_gelu: bool,
5541 pub rope_halves: bool,
5542 pub cos: &'a [f32],
5543 pub sin: &'a [f32],
5544 pub prof: bool,
5545}
5546
5547#[allow(unused_variables)]
5551pub fn vit_encode(a: &VitArgs, x: &mut [f32]) -> bool {
5552 if std::env::var("CMF_VIT_RESIDENT").as_deref() == Ok("0") {
5553 return false;
5554 }
5555 match backend() {
5556 #[cfg(target_os = "macos")]
5557 Backend::Metal => crate::gpu_metal::vit::encode(a, x),
5558 #[cfg(feature = "gpu")]
5559 Backend::Wgpu => crate::gpu_wgpu::vit::encode(a, x),
5560 #[cfg(feature = "cuda")]
5561 Backend::Cuda => crate::gpu_cuda::vit_encode(a, x),
5562 #[allow(unreachable_patterns)]
5563 _ => false,
5564 }
5565}
5566
5567pub trait GaWeight: Sync {
5570 fn fill(&self, dst: &mut [f32]);
5572}
5573
5574pub struct GaLin<'a> {
5577 pub rows: usize,
5578 pub cols: usize,
5579 pub weight: &'a dyn GaWeight,
5580 pub bias: &'a [f32],
5582}
5583
5584pub struct GaConv<'a> {
5590 pub inp: GaLin<'a>,
5591 pub taps: &'a [f32],
5592 pub bias: &'a [f32],
5593 pub kernel: usize,
5594 pub mean_w: &'a [f32],
5595 pub out: GaLin<'a>,
5596}
5597
5598pub struct GaLayer<'a> {
5608 pub ff1_in: GaLin<'a>,
5609 pub ff1_out: GaLin<'a>,
5610 pub in_norm: &'a [f32],
5611 pub qk: GaLin<'a>,
5612 pub vg: GaLin<'a>,
5613 pub attn_out: GaLin<'a>,
5614 pub conv: Option<GaConv<'a>>,
5615 pub ff2: Option<(GaLin<'a>, GaLin<'a>)>,
5616 pub norm: &'a [f32],
5617}
5618
5619pub struct GaStack<'a> {
5625 pub fold: usize,
5626 pub dim: usize,
5627 pub heads: usize,
5628 pub proj: GaLin<'a>,
5629 pub proj_t: GaLin<'a>,
5630 pub residual_scales: &'a [f32],
5631 pub input_scale: f32,
5632 pub layers: Vec<GaLayer<'a>>,
5633}
5634
5635pub struct GaFront<'a> {
5645 pub n_mel: usize,
5646 pub conv: [(&'a [f32], &'a [f32], usize); 3],
5647 pub dw: (&'a [f32], &'a [f32]),
5648 pub pw1: GaLin<'a>,
5649 pub pw2: GaLin<'a>,
5650 pub out: GaLin<'a>,
5651}
5652
5653pub struct GigaamArgs<'a> {
5658 pub key: u64,
5659 pub width: usize,
5660 pub head_dim: usize,
5661 pub stacks: Vec<GaStack<'a>>,
5662 pub cos: &'a [f32],
5663 pub sin: &'a [f32],
5664 pub out_scale: f32,
5665 pub out_eps: f32,
5666 pub prof: bool,
5667 pub front: Option<GaFront<'a>>,
5669}
5670
5671pub struct GaVadLayer<'a> {
5682 pub norm_ff1: (&'a [f32], &'a [f32]),
5683 pub ff1: (GaLin<'a>, GaLin<'a>),
5684 pub norm_att: (&'a [f32], &'a [f32]),
5685 pub q: GaLin<'a>,
5686 pub k: GaLin<'a>,
5687 pub v: GaLin<'a>,
5688 pub o: GaLin<'a>,
5689 pub norm_conv: (&'a [f32], &'a [f32]),
5690 pub pw1: GaLin<'a>,
5691 pub taps: &'a [f32],
5692 pub dw_b: &'a [f32],
5693 pub conv_norm: (&'a [f32], &'a [f32]),
5694 pub pw2: GaLin<'a>,
5695 pub norm_ff2: (&'a [f32], &'a [f32]),
5696 pub ff2: (GaLin<'a>, GaLin<'a>),
5697 pub norm_out: (&'a [f32], &'a [f32]),
5698}
5699
5700pub struct GaVadArgs<'a> {
5705 pub key: u64,
5706 pub n_mel: usize,
5707 pub dim: usize,
5708 pub heads: usize,
5709 pub kernel: usize,
5710 pub pre: [(&'a [f32], &'a [f32], usize, usize); 2],
5711 pub layers: Vec<GaVadLayer<'a>>,
5712 pub head: GaLin<'a>,
5713 pub cos: &'a [f32],
5714 pub sin: &'a [f32],
5715}
5716
5717#[allow(unused_variables)]
5723pub fn gigaam_vad(a: &GaVadArgs, feats: &[f32], windows: usize, frames: usize, out: &mut [f32]) -> bool {
5724 if std::env::var("CMF_GIGAAM_RESIDENT").as_deref() == Ok("0") || std::env::var("CMF_GIGAAM_VAD_DEV").as_deref() == Ok("0") {
5725 return false;
5726 }
5727 match backend() {
5728 #[cfg(feature = "gpu")]
5729 Backend::Wgpu => crate::gpu_wgpu::gigaam::vad(a, feats, windows, frames, out),
5730 #[cfg(feature = "cuda")]
5731 Backend::Cuda => crate::gpu_cuda::gigaam_vad(a, feats, windows, frames, out),
5732 #[allow(unreachable_patterns)]
5733 _ => false,
5734 }
5735}
5736
5737#[allow(unused_variables)]
5743pub fn gigaam_encode_feats(a: &GigaamArgs, feats: &[f32], frames: usize, out: &mut [f32]) -> bool {
5744 if a.front.is_none() || std::env::var("CMF_GIGAAM_RESIDENT").as_deref() == Ok("0") || std::env::var("CMF_GIGAAM_FRONT_DEV").as_deref() == Ok("0") {
5745 return false;
5746 }
5747 match backend() {
5748 #[cfg(feature = "gpu")]
5749 Backend::Wgpu => crate::gpu_wgpu::gigaam::encode_feats(a, feats, frames, out),
5750 #[cfg(feature = "cuda")]
5751 Backend::Cuda => crate::gpu_cuda::gigaam_encode_feats(a, feats, frames, out),
5752 #[allow(unreachable_patterns)]
5753 _ => false,
5754 }
5755}
5756
5757#[allow(unused_variables)]
5762pub fn gigaam_encode(a: &GigaamArgs, x: &mut [f32], t: usize) -> bool {
5763 if std::env::var("CMF_GIGAAM_RESIDENT").as_deref() == Ok("0") {
5764 return false;
5765 }
5766 match backend() {
5767 #[cfg(target_os = "macos")]
5768 Backend::Metal => crate::gpu_metal::gigaam::encode(a, x, t),
5769 #[cfg(feature = "gpu")]
5770 Backend::Wgpu => crate::gpu_wgpu::gigaam::encode(a, x, t),
5771 #[cfg(feature = "cuda")]
5772 Backend::Cuda => crate::gpu_cuda::gigaam_encode(a, x, t),
5773 #[allow(unreachable_patterns)]
5774 _ => false,
5775 }
5776}
5777
5778pub struct SamLayer<'a> {
5781 pub ln1_w: &'a [f32],
5782 pub ln1_b: &'a [f32],
5783 pub qkv: &'a [f32],
5784 pub qkv_b: &'a [f32],
5785 pub proj: &'a [f32],
5786 pub proj_b: &'a [f32],
5787 pub rel: &'a [f32],
5788 pub ln2_w: &'a [f32],
5789 pub ln2_b: &'a [f32],
5790 pub fc1: &'a [f32],
5791 pub fc1_b: &'a [f32],
5792 pub fc2: &'a [f32],
5793 pub fc2_b: &'a [f32],
5794 pub window: usize,
5795}
5796
5797pub struct SamConv<'a> {
5799 pub w: &'a [f32],
5800 pub ci: usize,
5801 pub co: usize,
5802 pub k: usize,
5803 pub stride: usize,
5804 pub pad: usize,
5805 pub norm: bool,
5807}
5808
5809pub struct SamArgs<'a> {
5810 pub key: u64,
5811 pub layers: Vec<SamLayer<'a>>,
5812 pub convs: Vec<SamConv<'a>>,
5813 pub norms: Vec<&'a [f32]>,
5814 pub rel_global: Vec<Vec<f32>>,
5816 pub g: usize,
5817 pub d: usize,
5818 pub heads: usize,
5819 pub head_dim: usize,
5820 pub inter: usize,
5821 pub eps: f64,
5822}
5823
5824#[allow(unused_variables)]
5826pub fn sam_encode(a: &SamArgs, x: &[f32], out: &mut Vec<f32>) -> bool {
5827 if std::env::var("CMF_VIT_RESIDENT").as_deref() == Ok("0") {
5828 return false;
5829 }
5830 match backend() {
5831 #[cfg(target_os = "macos")]
5832 Backend::Metal => crate::gpu_metal::vit::sam_encode(a, x, out),
5833 #[cfg(feature = "gpu")]
5834 Backend::Wgpu => crate::gpu_wgpu::vit::sam_encode(a, x, out),
5835 #[cfg(feature = "cuda")]
5836 Backend::Cuda => crate::gpu_cuda::sam_encode(a, x, out),
5837 #[allow(unreachable_patterns)]
5838 _ => false,
5839 }
5840}
5841
5842pub fn primal_vae_run(
5846 key: u64,
5847 weights: &crate::primal_vae::PvWeights,
5848 plan: &crate::primal_vae::PvPlan,
5849 input: &[f32],
5850 out: &mut [f32],
5851) -> bool {
5852 match backend() {
5853 #[cfg(target_os = "macos")]
5854 Backend::Metal => crate::gpu_metal::primal_vae::run(key, weights, plan, input, out),
5855 #[cfg(feature = "gpu")]
5856 Backend::Wgpu => crate::gpu_wgpu::primal_vae::run(key, weights, plan, input, out),
5857 #[cfg(feature = "cuda")]
5858 Backend::Cuda => crate::gpu_cuda::primal_vae_run(key, weights, plan, input, out),
5859 #[allow(unreachable_patterns)]
5860 _ => false,
5861 }
5862}
5863
5864pub fn vision_gemm_nt(x: &[f32], w: &[f32], y: &mut [f32], n: usize, k: usize, m: usize) -> bool {
5869 if n * k * m < (1 << 22) {
5870 return false;
5871 }
5872 match backend() {
5873 #[cfg(target_os = "macos")]
5874 Backend::Metal => crate::gpu_metal::egemma2::gemm_nt(x, w, y, n, k, m),
5875 #[cfg(feature = "gpu")]
5876 Backend::Wgpu => crate::gpu_wgpu::gemm_nt_f32(x, w, y, n, k, m),
5877 #[cfg(feature = "cuda")]
5878 Backend::Cuda => crate::gpu_cuda::h3_gemm_nt(x, w, y, n, k, m),
5879 #[allow(unreachable_patterns)]
5880 _ => false,
5881 }
5882}
5883
5884pub fn gemm_nt_f32(x: &[f32], w: &[f32], y: &mut [f32], n: usize, k: usize, m: usize) -> bool {
5887 match backend() {
5888 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5889 Backend::Wgpu => crate::gpu_wgpu::gemm_nt_f32(x, w, y, n, k, m),
5890 #[cfg(feature = "cuda")]
5891 Backend::Cuda => crate::gpu_cuda::h3_gemm_nt(x, w, y, n, k, m),
5892 #[allow(unreachable_patterns)]
5893 _ => false,
5894 }
5895}
5896
5897#[allow(clippy::too_many_arguments)]
5900pub fn music3_ffn(
5901 model: &std::sync::Arc<CmfModel>,
5902 idx_in: usize,
5903 idx_out: usize,
5904 h: &[f32],
5905 bias_in: &[f32],
5906 n: usize,
5907 hs: usize,
5908 inter: usize,
5909 out: &mut [f32],
5910) -> bool {
5911 match backend() {
5912 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5913 Backend::Wgpu => {
5914 crate::gpu_wgpu::music3_ffn(model, idx_in, idx_out, h, bias_in, n, hs, inter, out)
5915 }
5916 #[cfg(feature = "cuda")]
5917 Backend::Cuda => crate::gpu_cuda::h3_music3_ffn(model, idx_in, idx_out, h, bias_in, n, hs, inter, out),
5918 #[allow(unreachable_patterns)]
5919 _ => false,
5920 }
5921}
5922
5923#[allow(clippy::too_many_arguments, unused_variables)]
5927pub fn moe_row(
5928 model: &Arc<CmfModel>,
5929 experts: &[(usize, usize, usize)],
5930 shared: Option<((usize, usize, usize), usize, f32)>,
5931 inter: usize,
5932 limit: f32,
5933 x: &[f32],
5934 picks: &[(usize, f32)],
5935 out: &mut [f32],
5936) -> bool {
5937 match backend() {
5938 #[cfg(feature = "cuda")]
5939 Backend::Cuda => crate::gpu_cuda::moe_row(model, experts, shared, inter, limit, x, picks, out),
5940 #[allow(unreachable_patterns)]
5941 _ => false,
5942 }
5943}
5944
5945#[allow(clippy::too_many_arguments)]
5949pub fn glm_sequence_prepare(
5950 model_uid: u64,
5951 sequence_id: u64,
5952 layers: usize,
5953 hidden: usize,
5954 mhc_streams: usize,
5955 nh: usize,
5956 dk: usize,
5957 dv: usize,
5958 kk: usize,
5959 dsa_rank: usize,
5960 dsa_index: usize,
5961 dsa_topk: usize,
5962 dsa_kpool: usize,
5963) -> bool {
5964 let _ = (model_uid, sequence_id, layers, hidden, mhc_streams, nh, dk, dv, kk, dsa_rank, dsa_index, dsa_topk, dsa_kpool);
5965 false
5966}
5967
5968pub fn glm_sequence_reserve(model_uid: u64, sequence_id: u64, positions: usize) -> bool {
5970 let _ = (model_uid, sequence_id, positions);
5971 false
5972}
5973
5974pub fn glm_sequence_abort(model_uid: u64, sequence_id: u64) {
5976 let _ = (model_uid, sequence_id);
5977}
5978
5979#[allow(clippy::too_many_arguments)]
5983pub fn conv1d_gemm(
5984 x: &[f32],
5985 w: &[f32],
5986 ic: usize,
5987 oc: usize,
5988 n: usize,
5989 k: usize,
5990 pad: usize,
5991 dil: usize,
5992 out_n: usize,
5993 yt: &mut [f32],
5994) -> bool {
5995 match backend() {
5996 #[cfg(target_os = "macos")]
5997 Backend::Metal => crate::gpu_metal::conv1d_gemm(x, w, ic, oc, n, k, pad, dil, out_n, yt),
5998 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
5999 Backend::Wgpu => crate::gpu_wgpu::conv1d_gemm(x, w, ic, oc, n, k, pad, dil, out_n, yt),
6000 #[cfg(feature = "cuda")]
6001 Backend::Cuda => {
6002 out_n * ic * k * oc >= (1 << 22) && crate::gpu_cuda::h3_conv1d(x, w, ic, oc, n, k, pad, dil, out_n, yt)
6004 }
6005 #[allow(unreachable_patterns)]
6006 _ => false,
6007 }
6008}
6009
6010#[allow(clippy::too_many_arguments)]
6012pub fn vae_conv2d_coop(
6013 w: &[f32],
6014 bias: Option<&[f32]>,
6015 x: &[f32],
6016 ic: usize,
6017 oc: usize,
6018 h: usize,
6019 wi: usize,
6020 k: usize,
6021 out: &mut [f32],
6022) -> bool {
6023 match backend() {
6024 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
6025 Backend::Wgpu => crate::gpu_wgpu::vae_conv2d_coop(w, bias, x, ic, oc, h, wi, k, out),
6026 #[allow(unreachable_patterns)]
6027 _ => false,
6028 }
6029}
6030
6031pub fn dit_attention_packed(
6032 qkv: &[f32],
6033 nh: usize,
6034 n: usize,
6035 hd: usize,
6036 scale: f32,
6037 nr: Option<(&[f32], &[f32], &[f32], f32)>,
6040 out: &mut [f32],
6041) -> bool {
6042 match backend() {
6043 #[cfg(feature = "gpu")]
6050 Backend::Wgpu => crate::gpu_wgpu::dit_attention_packed(qkv, nh, n, hd, scale, nr, out),
6051 #[allow(unreachable_patterns)]
6052 _ => false,
6053 }
6054}
6055
6056pub fn dit_attention_packed_available() -> bool {
6064 #[allow(unreachable_patterns)]
6065 match backend() {
6066 #[cfg(feature = "gpu")]
6067 Backend::Wgpu => crate::gpu_wgpu::dit_attention_packed_ready(),
6068 _ => false,
6069 }
6070}
6071
6072pub fn dit_attention(
6073 qh: &[f32],
6074 kh: &[f32],
6075 vh: &[f32],
6076 nh: usize,
6077 nkv: usize,
6078 n: usize,
6079 hd: usize,
6080 scale: f32,
6081 out: &mut [f32],
6082) -> bool {
6083 match backend() {
6084 #[cfg(target_os = "macos")]
6085 Backend::Metal => crate::gpu_metal::dit_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
6086 #[cfg(feature = "gpu")]
6087 Backend::Wgpu => crate::gpu_wgpu::dit_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
6088 #[cfg(feature = "cuda")]
6089 Backend::Cuda => crate::gpu_cuda::h3_attention(qh, kh, vh, nh, nkv, n, hd, scale, out),
6090 #[allow(unreachable_patterns)]
6091 _ => false,
6092 }
6093}
6094
6095pub fn gram_alloc(cols: usize) -> Option<u64> {
6098 #[cfg(feature = "gpu")]
6099 if backend() == Backend::Wgpu {
6100 return crate::gpu_wgpu::gram::alloc(cols);
6101 }
6102 let _ = cols;
6103 None
6104}
6105
6106pub fn gram_add(id: u64, xs: &[f32], b: usize) -> bool {
6108 #[cfg(feature = "gpu")]
6109 if backend() == Backend::Wgpu {
6110 return crate::gpu_wgpu::gram::add(id, xs, b);
6111 }
6112 let _ = (id, xs, b);
6113 false
6114}
6115
6116#[cfg(feature = "gpu")]
6118pub fn gram_add_dev(id: u64, x: &wgpu::Buffer, b: usize) -> bool {
6119 if backend() == Backend::Wgpu {
6120 return crate::gpu_wgpu::gram::add_dev(id, x, b);
6121 }
6122 false
6123}
6124
6125pub fn gram_take(id: u64) -> Option<Vec<f64>> {
6127 #[cfg(feature = "gpu")]
6128 if backend() == Backend::Wgpu {
6129 return crate::gpu_wgpu::gram::take(id);
6130 }
6131 let _ = id;
6132 None
6133}
6134
6135pub fn gptq_fold_dev(h_id: u64, n: usize, lambda: f64) -> Option<u64> {
6140 #[cfg(feature = "gpu")]
6141 if backend() == Backend::Wgpu {
6142 return crate::gpu_wgpu::gptq_dev::fold(h_id, n, lambda);
6143 }
6144 let _ = (h_id, n, lambda);
6145 None
6146}
6147
6148pub fn gptq_fold_info(id: u64) -> Option<(Vec<bool>, Vec<f32>, f64)> {
6150 #[cfg(feature = "gpu")]
6151 if backend() == Backend::Wgpu {
6152 return crate::gpu_wgpu::gptq_dev::info(id);
6153 }
6154 let _ = id;
6155 None
6156}
6157
6158pub fn gptq_fold_read(id: u64) -> Option<Vec<f32>> {
6160 #[cfg(feature = "gpu")]
6161 if backend() == Backend::Wgpu {
6162 return crate::gpu_wgpu::gptq_dev::read_u(id);
6163 }
6164 let _ = id;
6165 None
6166}
6167
6168pub fn gptq_fold_free(id: u64) {
6170 #[cfg(feature = "gpu")]
6171 if backend() == Backend::Wgpu {
6172 crate::gpu_wgpu::gptq_dev::free(id);
6173 }
6174 let _ = id;
6175}
6176
6177#[allow(clippy::too_many_arguments)]
6179pub fn gptq_sweep_q4tp_dev(
6180 id: u64,
6181 w: &[f32],
6182 rows: usize,
6183 tab: &[f32],
6184 lost: &[f32],
6185 nib: &mut [u8],
6186 codes: &mut [u32],
6187) -> bool {
6188 #[cfg(feature = "gpu")]
6189 if backend() == Backend::Wgpu {
6190 return crate::gpu_wgpu::gptq_dev::sweep_q4tp(id, w, rows, tab, lost, nib, codes);
6191 }
6192 let _ = (id, w, rows, tab, lost, nib, codes);
6193 false
6194}
6195
6196pub fn gptq_sweep_q2tp_dev(
6198 id: u64,
6199 w: &[f32],
6200 rows: usize,
6201 tab: &[f32],
6202 hw: &[f32],
6203 chunks: &mut [u8],
6204 codes: &mut [u32],
6205) -> bool {
6206 #[cfg(feature = "gpu")]
6207 if backend() == Backend::Wgpu {
6208 return crate::gpu_wgpu::gptq_dev::sweep_q2tp(id, w, rows, tab, hw, chunks, codes);
6209 }
6210 let _ = (id, w, rows, tab, hw, chunks, codes);
6211 false
6212}
6213
6214pub fn gram_read(id: u64) -> Option<Vec<f64>> {
6217 #[cfg(feature = "gpu")]
6218 if backend() == Backend::Wgpu {
6219 return crate::gpu_wgpu::gram::read(id);
6220 }
6221 let _ = id;
6222 None
6223}
6224
6225pub fn gram_clear() {
6227 #[cfg(feature = "gpu")]
6228 if backend() == Backend::Wgpu {
6229 crate::gpu_wgpu::gram::clear();
6230 }
6231}
6232
6233#[allow(unused_variables)]
6238pub fn q4tp_matmat(
6239 model: &Arc<CmfModel>,
6240 idx: usize,
6241 xs: &[f32],
6242 b: usize,
6243 rows: usize,
6244 cols: usize,
6245 out: &mut [f32],
6246) -> bool {
6247 match backend() {
6248 #[cfg(target_os = "macos")]
6249 Backend::Metal => crate::gpu_metal::q4tp_matmat(model, idx, xs, b, rows, cols, out),
6250 #[cfg(feature = "gpu")]
6251 Backend::Wgpu => crate::gpu_wgpu::q4tp_matmat(model, idx, xs, b, rows, cols, out),
6252 #[cfg(feature = "cuda")]
6253 Backend::Cuda => crate::gpu_cuda::h3_matmat(model, idx, xs, b, rows, cols, out),
6254 #[allow(unreachable_patterns)]
6255 _ => false,
6256 }
6257}
6258
6259#[allow(unused_variables)]
6264pub fn stage_done(model: &CmfModel) {
6265 match backend() {
6266 #[cfg(all(feature = "gpu", not(target_os = "macos")))]
6267 Backend::Wgpu => {
6268 crate::gpu_wgpu::h3::release();
6269 crate::gpu_wgpu::h3_conv::release();
6270 crate::gpu_wgpu::release_model_buffers(model)
6271 }
6272 #[cfg(feature = "cuda")]
6273 Backend::Cuda => crate::gpu_cuda::h3_release(),
6274 #[cfg(target_os = "macos")]
6275 Backend::Metal => crate::gpu_metal::h3::release(),
6276 #[allow(unreachable_patterns)]
6277 _ => {}
6278 }
6279}
6280
6281pub fn h3_prof_report() -> Option<String> {
6283 match backend() {
6284 #[cfg(feature = "cuda")]
6285 Backend::Cuda => crate::gpu_cuda::h3_prof_report(),
6286 #[allow(unreachable_patterns)]
6287 _ => None,
6288 }
6289}
6290
6291pub fn layer_taps_arm(layers: &[usize]) {
6296 match backend() {
6297 #[cfg(feature = "gpu")]
6298 Backend::Wgpu => crate::gpu_wgpu::layer_taps_arm(layers),
6299 #[cfg(feature = "cuda")]
6300 Backend::Cuda => crate::gpu_cuda::layer_taps_arm(layers),
6301 #[allow(unreachable_patterns)]
6302 _ => {
6303 let _ = layers;
6304 }
6305 }
6306}
6307
6308pub fn layer_taps_take(out: &mut Vec<f32>) -> bool {
6311 match backend() {
6312 #[cfg(feature = "gpu")]
6313 Backend::Wgpu => crate::gpu_wgpu::layer_taps_take(out),
6314 #[cfg(feature = "cuda")]
6315 Backend::Cuda => crate::gpu_cuda::layer_taps_take(out),
6316 #[allow(unreachable_patterns)]
6317 _ => {
6318 let _ = out;
6319 false
6320 }
6321 }
6322}
6323
6324pub fn q4tp_rows8_many(
6330 model: &Arc<CmfModel>,
6331 jobs: &[(usize, usize, usize, usize)],
6332 xs: &[f32],
6333 b: usize,
6334 outs: &mut [&mut [f32]],
6335) -> bool {
6336 match backend() {
6337 #[cfg(target_os = "macos")]
6338 Backend::Metal => {
6339 let takes: Vec<usize> = jobs.iter().map(|j| j.3).collect();
6340 let jobs: Vec<crate::gpu_metal::MmJob> = jobs
6341 .iter()
6342 .map(|&(idx, rows, cols, _)| crate::gpu_metal::MmJob { idx, rows, cols })
6343 .collect();
6344 crate::gpu_metal::q4tp_n8_many(model, &jobs, Some(&takes), xs, b, outs)
6345 }
6346 #[allow(unreachable_patterns)]
6347 _ => {
6348 let _ = (model, jobs, xs, b, outs);
6349 false
6350 }
6351 }
6352}
6353
6354#[allow(clippy::too_many_arguments)]
6356pub fn q4tp_rows8_ffn(
6357 model: &Arc<CmfModel>,
6358 w1: usize,
6359 w3: usize,
6360 w2: usize,
6361 xs: &[f32],
6362 b: usize,
6363 hidden: usize,
6364 inter: usize,
6365 out: &mut [f32],
6366) -> bool {
6367 match backend() {
6368 #[cfg(target_os = "macos")]
6369 Backend::Metal => crate::gpu_metal::q4tp_n8_ffn(model, w1, w3, w2, xs, b, hidden, inter, out),
6370 #[allow(unreachable_patterns)]
6371 _ => {
6372 let _ = (model, w1, w3, w2, xs, b, hidden, inter, out);
6373 false
6374 }
6375 }
6376}
6377
6378pub fn q4tp_matmat_many(
6382 model: &Arc<CmfModel>,
6383 jobs: &[(usize, usize, usize)],
6384 xs: &[f32],
6385 b: usize,
6386 outs: &mut [&mut [f32]],
6387) -> bool {
6388 match backend() {
6389 #[cfg(target_os = "macos")]
6390 Backend::Metal => {
6391 let jobs: Vec<crate::gpu_metal::MmJob> = jobs
6392 .iter()
6393 .map(|&(idx, rows, cols)| crate::gpu_metal::MmJob { idx, rows, cols })
6394 .collect();
6395 crate::gpu_metal::q4tp_matmat_many(model, &jobs, xs, b, outs)
6396 }
6397 #[cfg(feature = "gpu")]
6398 Backend::Wgpu => crate::gpu_wgpu::q4tp_matmat_many(model, jobs, xs, b, outs),
6399 #[allow(unreachable_patterns)]
6400 _ => {
6401 let _ = (model, jobs, xs, b, outs);
6402 false
6403 }
6404 }
6405}
6406
6407pub fn q2tp_matmat(
6410 model: &Arc<CmfModel>,
6411 idx: usize,
6412 xs: &[f32],
6413 b: usize,
6414 rows: usize,
6415 cols: usize,
6416 out: &mut [f32],
6417) -> bool {
6418 match backend() {
6419 #[cfg(target_os = "macos")]
6420 Backend::Metal => crate::gpu_metal::q2tp_matmat(model, idx, xs, b, rows, cols, out),
6421 #[cfg(feature = "gpu")]
6422 Backend::Wgpu => crate::gpu_wgpu::q2tp_matmat(model, idx, xs, b, rows, cols, out),
6423 #[allow(unreachable_patterns)]
6424 _ => false,
6425 }
6426}
6427
6428pub fn q2tp_affine_matmat(
6431 model: &Arc<CmfModel>,
6432 idx: usize,
6433 xs: &[f32],
6434 b: usize,
6435 rows: usize,
6436 cols: usize,
6437 out: &mut [f32],
6438) -> bool {
6439 match backend() {
6440 #[cfg(target_os = "macos")]
6441 Backend::Metal => crate::gpu_metal::q2tp_affine_matmat(model, idx, xs, b, rows, cols, out),
6442 #[cfg(feature = "gpu")]
6443 Backend::Wgpu => crate::gpu_wgpu::q2tp_affine_matmat(model, idx, xs, b, rows, cols, out),
6444 #[allow(unreachable_patterns)]
6445 _ => false,
6446 }
6447}
6448
6449pub fn blr_matmat(t: &crate::blr::BlrTensor, xs: &[f32], b: usize, out: &mut [f32]) -> bool {
6454 match backend() {
6455 #[cfg(feature = "gpu")]
6456 Backend::Wgpu => crate::gpu_wgpu::blr_matmat(t, xs, b, out),
6457 #[allow(unreachable_patterns)]
6458 _ => {
6459 let _ = (t, xs, b, out);
6460 false
6461 }
6462 }
6463}
6464
6465pub fn mxfp4_matvec(
6469 model: &Arc<CmfModel>,
6470 idx: usize,
6471 xs: &[f32],
6472 rows: usize,
6473 cols: usize,
6474 out: &mut [f32],
6475) -> bool {
6476 mxfp4_matmat(model, idx, xs, 1, rows, cols, out)
6477}
6478
6479pub fn mxfp4_matmat(
6482 model: &Arc<CmfModel>,
6483 idx: usize,
6484 xs: &[f32],
6485 b: usize,
6486 rows: usize,
6487 cols: usize,
6488 out: &mut [f32],
6489) -> bool {
6490 match backend() {
6491 #[cfg(feature = "gpu")]
6492 Backend::Wgpu => crate::gpu_wgpu::mxfp4::matmat(model, idx, xs, b, rows, cols, out),
6493 #[allow(unreachable_patterns)]
6494 _ => {
6495 let _ = (model, idx, xs, b, rows, cols, out);
6496 false
6497 }
6498 }
6499}
6500
6501pub fn q2tp_matvec(
6503 model: &Arc<CmfModel>,
6504 idx: usize,
6505 xs: &[f32],
6506 rows: usize,
6507 cols: usize,
6508 out: &mut [f32],
6509) -> bool {
6510 match backend() {
6511 #[cfg(target_os = "macos")]
6512 Backend::Metal => crate::gpu_metal::q2tp_matvec(model, idx, xs, rows, cols, out),
6513 #[cfg(feature = "gpu")]
6514 Backend::Wgpu => crate::gpu_wgpu::q2tp_matvec(model, idx, xs, rows, cols, out),
6515 #[allow(unreachable_patterns)]
6516 _ => false,
6517 }
6518}
6519
6520pub fn q2tp_affine_matvec(
6524 model: &Arc<CmfModel>,
6525 idx: usize,
6526 xs: &[f32],
6527 rows: usize,
6528 cols: usize,
6529 out: &mut [f32],
6530) -> bool {
6531 match backend() {
6532 #[cfg(target_os = "macos")]
6533 Backend::Metal => crate::gpu_metal::q2tp_affine_matvec(model, idx, xs, rows, cols, out),
6534 #[cfg(feature = "gpu")]
6535 Backend::Wgpu => crate::gpu_wgpu::q2tp_affine_matvec(model, idx, xs, rows, cols, out),
6536 #[allow(unreachable_patterns)]
6537 _ => false,
6538 }
6539}
6540
6541pub fn q4tp_matvec(
6546 model: &Arc<CmfModel>,
6547 idx: usize,
6548 xs: &[f32],
6549 rows: usize,
6550 cols: usize,
6551 out: &mut [f32],
6552) -> bool {
6553 match backend() {
6554 #[cfg(target_os = "macos")]
6555 Backend::Metal => crate::gpu_metal::q4tp_matvec_for_test(model, idx, xs, rows, cols, out),
6556 #[cfg(feature = "gpu")]
6557 Backend::Wgpu => crate::gpu_wgpu::q4tp_matvec(model, idx, xs, rows, cols, out),
6558 #[allow(unreachable_patterns)]
6559 _ => false,
6560 }
6561}
6562
6563pub fn q4t_matvec(
6569 model: &Arc<CmfModel>,
6570 idx: usize,
6571 xs: &[f32],
6572 rows: usize,
6573 cols: usize,
6574 out: &mut [f32],
6575) -> bool {
6576 match backend() {
6577 #[cfg(target_os = "macos")]
6578 Backend::Metal => crate::gpu_metal::q4t_matvec_for_test(model, idx, xs, rows, cols, out),
6579 #[allow(unreachable_patterns)]
6580 _ => false,
6581 }
6582}
6583
6584pub fn q4t_matmat(
6585 model: &Arc<CmfModel>,
6586 idx: usize,
6587 xs: &[f32],
6588 b: usize,
6589 rows: usize,
6590 cols: usize,
6591 out: &mut [f32],
6592) -> bool {
6593 match backend() {
6594 #[cfg(target_os = "macos")]
6595 Backend::Metal => crate::gpu_metal::q4t_matmat(model, idx, xs, b, rows, cols, out),
6596 #[cfg(feature = "gpu")]
6597 Backend::Wgpu => crate::gpu_wgpu::q4t_matmat(model, idx, xs, b, rows, cols, out),
6598 #[allow(unreachable_patterns)]
6599 _ => false,
6600 }
6601}
6602
6603pub type SetW = (usize, usize, usize);
6610
6611pub enum SetMixer<'a> {
6612 Conv {
6613 in_proj: SetW,
6614 out_proj: SetW,
6615 taps: &'a [f32],
6617 kernel: usize,
6618 },
6619 Attn {
6620 wq: SetW,
6621 wk: SetW,
6622 wv: SetW,
6623 wo: SetW,
6624 q_norm: Option<&'a [f32]>,
6625 k_norm: Option<&'a [f32]>,
6626 head_gate: Option<&'a [f32]>,
6628 inv_freq: &'a [f32],
6629 rd: usize,
6630 nkv: usize,
6631 window: Option<usize>,
6633 },
6634}
6635
6636pub struct SetLayer<'a> {
6637 pub input_norm: &'a [f32],
6638 pub post_norm: &'a [f32],
6639 pub mixer: SetMixer<'a>,
6640 pub attn_out_norm: Option<&'a [f32]>,
6641 pub ffn_out_norm: Option<&'a [f32]>,
6642 pub gate: SetW,
6644 pub up: SetW,
6645 pub down: SetW,
6646}
6647
6648pub struct SetDims {
6649 pub hidden: usize,
6650 pub nh: usize,
6651 pub hd: usize,
6652 pub eps: f32,
6653 pub gemma: bool,
6654 pub scale: f32,
6655}
6656
6657pub struct SetHead<'a> {
6660 pub w: SetW,
6661 pub rows: &'a [usize],
6662}
6663
6664#[allow(clippy::too_many_arguments, unused_variables)]
6669pub fn lfm_set_forward(
6670 model: &Arc<CmfModel>,
6671 layers: &[SetLayer],
6672 dims: &SetDims,
6673 final_norm: &[f32],
6674 rows: &[f32],
6675 t: usize,
6676 state: usize,
6677 group: &[i32],
6678 head: Option<&SetHead>,
6679) -> Option<(Vec<f32>, Vec<f32>)> {
6680 #[allow(unreachable_patterns)]
6681 match backend() {
6682 #[cfg(target_os = "macos")]
6683 Backend::Metal => crate::gpu_metal::lfm_set::forward(
6684 model, layers, dims, final_norm, rows, t, state, group, head,
6685 ),
6686 #[cfg(feature = "gpu")]
6687 Backend::Wgpu => crate::gpu_wgpu::lfm_set::forward(
6688 model, layers, dims, final_norm, rows, t, state, group, head,
6689 ),
6690 #[cfg(feature = "cuda")]
6691 Backend::Cuda => crate::gpu_cuda::h3_lfm_set_forward(
6692 model, layers, dims, final_norm, rows, t, state, group, head,
6693 ),
6694 _ => None,
6695 }
6696}
6697
6698#[cfg(target_os = "macos")]
6700pub use crate::gpu_metal::{
6701 AttnDeviceParams, AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, GpuFlintMoe, GpuMoe, GraphDims,
6702 MetalFfn, O1AttnParams, SconvGpuLayer, TokenGraph, kv_mirror_drop, kv_mirror_read_last,
6703 kv_mirror_take_imp,
6704};
6705
6706#[cfg(target_os = "macos")]
6708pub fn gdn_block(
6709 model: &Arc<CmfModel>,
6710 layers: &[GdnGpuLayer],
6711 states: &mut [&mut [f32]],
6712 cfg: &GdnGpuCfg,
6713 h: &mut [f32],
6714) -> bool {
6715 match backend() {
6716 Backend::Metal => crate::gpu_metal::gdn_block(model, layers, states, cfg, h),
6717 _ => false,
6718 }
6719}
6720
6721#[allow(unused_variables)]
6723pub fn moe_block(model: &Arc<CmfModel>, jobs: &[MoeJob], out: &mut [f32]) -> bool {
6724 match backend() {
6725 #[cfg(target_os = "macos")]
6730 Backend::Metal => crate::gpu_metal::moe_block(model, jobs, out),
6731 #[cfg(feature = "gpu")]
6732 Backend::Wgpu => crate::gpu_wgpu::moe_block(model, jobs, out),
6733 Backend::None => false,
6734 #[cfg(feature = "cuda")]
6735 Backend::Cuda => false,
6736 }
6737}
6738
6739#[allow(unused_variables)]
6741pub fn matvec_batch(model: &Arc<CmfModel>, jobs: &[BatchJob], out: &mut [&mut [f32]]) -> bool {
6742 match backend() {
6743 #[cfg(target_os = "macos")]
6744 Backend::Metal => crate::gpu_metal::matvec_batch(model, jobs, out),
6745 #[cfg(feature = "gpu")]
6746 Backend::Wgpu => crate::gpu_wgpu::matvec_batch(model, jobs, out),
6747 Backend::None => false,
6748 #[cfg(feature = "cuda")]
6749 Backend::Cuda => false,
6750 }
6751}
6752
6753static GRAPH_RACE_STATE: AtomicU8 = AtomicU8::new(0); static GRAPH_RACE_FLIP: AtomicU32 = AtomicU32::new(0);
6769static 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)];
6773
6774const GRAPH_RACE_SAMPLES: u32 = 4;
6776
6777pub fn generation_end() {
6798 #[cfg(feature = "gpu")]
6799 if matches!(backend(), Backend::Wgpu) {
6800 crate::gpu_wgpu::pipeline_cache_flush_if_grown();
6801 }
6802}
6803
6804pub fn graph_race_begin_generation() {
6805 #[cfg(feature = "gpu")]
6810 {
6811 static FLUSHED: std::sync::Once = std::sync::Once::new();
6823 static FIRST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
6824 if FIRST.swap(false, Ordering::Relaxed) {
6825 } else {
6827 FLUSHED.call_once(crate::gpu_wgpu::pipeline_cache_flush);
6828 }
6829 }
6830 GRAPH_RACE_TOK.store(0, Ordering::Relaxed);
6831 if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
6832 return;
6833 }
6834 let (gn, cn) = (
6835 GRAPH_N[1].load(Ordering::Relaxed),
6836 GRAPH_N[0].load(Ordering::Relaxed),
6837 );
6838 if gn >= GRAPH_RACE_SAMPLES && cn >= GRAPH_RACE_SAMPLES {
6839 let g_avg = GRAPH_NS[1].load(Ordering::Relaxed) / gn as u64;
6840 let c_avg = GRAPH_NS[0].load(Ordering::Relaxed) / cn as u64;
6841 let verdict = if g_avg < c_avg { 1 } else { 2 };
6842 GRAPH_RACE_STATE.store(verdict, Ordering::Relaxed);
6843 tracing::info!(
6844 "wgpu graph race: graph {:.2} ms/tok vs normal {:.2} ms/tok -> {}",
6845 g_avg as f64 / 1e6,
6846 c_avg as f64 / 1e6,
6847 if verdict == 1 { "graph" } else { "normal path" }
6848 );
6849 return;
6850 }
6851 let flip = GRAPH_RACE_FLIP.fetch_add(1, Ordering::Relaxed);
6852 GRAPH_RACE_ARM_GRAPH.store((flip % 2 == 1) as u8, Ordering::Relaxed);
6853}
6854
6855pub fn graph_race_use_graph(trusted: bool) -> bool {
6859 if trusted {
6860 return true;
6861 }
6862 match GRAPH_RACE_STATE.load(Ordering::Relaxed) {
6863 1 => true,
6864 2 => false,
6865 _ => GRAPH_RACE_ARM_GRAPH.load(Ordering::Relaxed) == 1,
6866 }
6867}
6868
6869pub fn graph_race_first_token_hopeless(dur: std::time::Duration) -> bool {
6874 if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
6875 return false;
6876 }
6877 let first = GRAPH_RACE_TOK.load(Ordering::Relaxed) == 0;
6878 let cn = GRAPH_N[0].load(Ordering::Relaxed);
6879 if !first || cn == 0 {
6880 return false;
6881 }
6882 let c_avg = GRAPH_NS[0].load(Ordering::Relaxed) / cn as u64;
6883 let ns = dur.as_nanos() as u64;
6884 if ns > 1_000_000_000 && ns > 4 * c_avg {
6885 GRAPH_RACE_STATE.store(2, Ordering::Relaxed);
6886 tracing::info!(
6887 "wgpu graph race: first graph token {:.0} ms vs normal {:.2} ms/tok — hopeless, normal path wins",
6888 ns as f64 / 1e6,
6889 c_avg as f64 / 1e6
6890 );
6891 return true;
6892 }
6893 false
6894}
6895
6896pub fn graph_race_record(used_graph: bool, dur: std::time::Duration) {
6900 if GRAPH_RACE_STATE.load(Ordering::Relaxed) != 0 {
6901 return;
6902 }
6903 let tok = GRAPH_RACE_TOK.fetch_add(1, Ordering::Relaxed);
6904 if tok == 0 {
6905 return;
6906 }
6907 let i = used_graph as usize;
6908 GRAPH_NS[i].fetch_add(dur.as_nanos() as u64, Ordering::Relaxed);
6909 GRAPH_N[i].fetch_add(1, Ordering::Relaxed);
6910}
6911
6912pub(crate) fn fp_bytes(data: &[u8]) -> u64 {
6922 #[inline]
6923 fn fnv(mut h: u64, bytes: &[u8]) -> u64 {
6924 let (chunks, tail) = bytes.split_at(bytes.len() & !7);
6925 for c in chunks.chunks_exact(8) {
6926 h ^= u64::from_le_bytes(c.try_into().unwrap());
6927 h = h.wrapping_mul(0x100_0000_01b3);
6928 }
6929 for &b in tail {
6930 h ^= b as u64;
6931 h = h.wrapping_mul(0x100_0000_01b3);
6932 }
6933 h
6934 }
6935 let mut h = 0xcbf2_9ce4_8422_2325u64 ^ (data.len() as u64);
6936 if data.len() <= 4096 {
6937 return fnv(h, data);
6938 }
6939 let step = (data.len() - 64) / 63;
6940 for i in 0..64 {
6941 h = fnv(h, &data[i * step..i * step + 64]);
6942 }
6943 h
6944}
6945
6946pub(crate) fn fp_f32(data: &[f32]) -> u64 {
6949 let bytes = unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, data.len() * 4) };
6950 fp_bytes(bytes)
6951}
6952
6953#[cfg(test)]
6954mod fp_tests {
6955 use super::fp_bytes;
6956
6957 #[test]
6962 fn fp_bytes_sees_a_change_anywhere_in_a_sampled_slice() {
6963 let n = 1 << 20; let base: Vec<u8> = (0..n).map(|i| (i * 31 + 7) as u8).collect();
6965 let h0 = fp_bytes(&base);
6966 assert_eq!(h0, fp_bytes(&base), "fingerprint must be deterministic");
6967 let mut dense = base.clone();
6970 for b in dense.iter_mut() {
6971 *b = b.wrapping_add(1);
6972 }
6973 assert_ne!(
6974 h0,
6975 fp_bytes(&dense),
6976 "a fully different tensor slipped through"
6977 );
6978 assert_ne!(h0, fp_bytes(&base[..n - 64]));
6981 let mut small = vec![3u8; 4096];
6984 let hs = fp_bytes(&small);
6985 small[2048] ^= 1;
6986 assert_ne!(hs, fp_bytes(&small), "full hash missed a one-byte change");
6987 for n in [4097usize, 5000, 64 * 64, 1 << 16] {
6989 let v = vec![9u8; n];
6990 let _ = fp_bytes(&v); }
6992 }
6993}
6994
6995pub fn bake_release() {
6999 #[cfg(feature = "gpu")]
7000 crate::gpu_wgpu::bake_release();
7001}
7002
7003pub fn bake_precision_strict(on: bool) {
7007 #[cfg(feature = "gpu")]
7008 crate::gpu_wgpu::bake_precision_strict(on);
7009 #[cfg(not(feature = "gpu"))]
7010 let _ = on;
7011}
7012
7013pub fn hostprof_encode_done(t0: std::time::Instant) {
7019 use std::sync::atomic::{AtomicU64, Ordering};
7020 static ENC: AtomicU64 = AtomicU64::new(0);
7021 static N: AtomicU64 = AtomicU64::new(0);
7022 if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() != Ok("1") {
7023 return;
7024 }
7025 ENC.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);
7026 let n = N.fetch_add(1, Ordering::Relaxed) + 1;
7027 if n % 100 == 0 {
7028 eprintln!(
7029 "hostprof: encode {:.2} ms/token over {n} tokens",
7030 ENC.load(Ordering::Relaxed) as f64 / n as f64 / 1e6
7031 );
7032 }
7033}
7034
7035pub fn hostprof_total(t0: std::time::Instant) {
7036 use std::sync::atomic::{AtomicU64, Ordering};
7037 static TOT: AtomicU64 = AtomicU64::new(0);
7038 static N: AtomicU64 = AtomicU64::new(0);
7039 if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() != Ok("1") {
7040 return;
7041 }
7042 TOT.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);
7043 let n = N.fetch_add(1, Ordering::Relaxed) + 1;
7044 if n % 100 == 0 {
7045 eprintln!(
7046 "hostprof: total {:.2} ms/token over {n} tokens",
7047 TOT.load(Ordering::Relaxed) as f64 / n as f64 / 1e6
7048 );
7049 }
7050}
7051
7052pub fn stageprof(stage: u32, dt: std::time::Duration) {
7056 use std::sync::atomic::{AtomicU64, Ordering};
7057 static NS: [AtomicU64; 4] = [
7058 AtomicU64::new(0),
7059 AtomicU64::new(0),
7060 AtomicU64::new(0),
7061 AtomicU64::new(0),
7062 ];
7063 static N: AtomicU64 = AtomicU64::new(0);
7064 if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() != Ok("1") {
7065 return;
7066 }
7067 NS[stage as usize % 4].fetch_add(dt.as_nanos() as u64, Ordering::Relaxed);
7068 if stage == 1 {
7069 let n = N.fetch_add(1, Ordering::Relaxed) + 1;
7070 if n % 200 == 0 {
7071 eprintln!(
7072 "stageprof: planning {:.2} ms/tok | gdn-item {:.2} ms/tok | attn-item {:.2} ms/tok ({n} tok)",
7073 NS[1].load(Ordering::Relaxed) as f64 / n as f64 / 1e6,
7074 NS[2].load(Ordering::Relaxed) as f64 / n as f64 / 1e6,
7075 NS[3].load(Ordering::Relaxed) as f64 / n as f64 / 1e6
7076 );
7077 }
7078 }
7079}
7080
7081pub fn weight_bytes_dispatched() -> u64 {
7084 let mut total = 0u64;
7085 #[cfg(target_os = "macos")]
7086 {
7087 total += crate::gpu_metal::WEIGHT_BYTES.load(std::sync::atomic::Ordering::Relaxed);
7088 }
7089 #[cfg(feature = "gpu")]
7090 {
7091 total += crate::gpu_wgpu::WEIGHT_BYTES.load(std::sync::atomic::Ordering::Relaxed);
7092 }
7093 total
7094}
7095
7096pub fn weight_bytes_by() -> [u64; 6] {
7099 #[cfg(target_os = "macos")]
7100 {
7101 let mut o = [0u64; 6];
7102 for (i, a) in crate::gpu_metal::WEIGHT_BYTES_BY.iter().enumerate() {
7103 o[i] = a.load(std::sync::atomic::Ordering::Relaxed);
7104 }
7105 return o;
7106 }
7107 #[allow(unreachable_code)]
7108 [0; 6]
7109}
7110
7111#[cfg(test)]
7112mod f16_guard_tests {
7113 use super::*;
7114
7115 #[test]
7118 fn abs_max_or_inf_is_the_magnitude_maximum() {
7119 let mut xs: Vec<f32> = (0..37).map(|i| (i as f32 - 18.0) * 0.5).collect();
7120 assert_eq!(abs_max_or_inf(&xs), 9.0);
7121 xs[36] = -70000.0; assert_eq!(abs_max_or_inf(&xs), 70000.0);
7123 xs[3] = f32::NAN; assert_eq!(abs_max_or_inf(&xs), f32::INFINITY);
7125 xs[3] = 0.0;
7126 xs[35] = f32::NEG_INFINITY;
7127 assert_eq!(abs_max_or_inf(&xs), f32::INFINITY);
7128 assert_eq!(abs_max_or_inf(&[]), 0.0);
7129 assert_eq!(abs_max_or_inf(&[-0.0, -1e-30]), 1e-30);
7130 }
7131}
7132
7133#[cfg(test)]
7134mod probe_warmup_tests {
7135 use super::*;
7136 use std::time::Duration;
7137
7138 fn ms(v: f64) -> Duration {
7139 Duration::from_nanos((v * 1e6) as u64)
7140 }
7141
7142 #[test]
7147 fn one_cold_first_sample_does_not_lose_the_class() {
7148 let p = Probe::new();
7149 probe_record_into(&p, "gemm-nt", None, true, ms(117.01));
7151 probe_record_into(&p, "gemm-nt", None, true, ms(1.1));
7152 probe_record_into(&p, "gemm-nt", None, true, ms(1.0));
7153 probe_record_into(&p, "gemm-nt", None, false, ms(3.19));
7154 probe_record_into(&p, "gemm-nt", None, false, ms(3.20));
7155 assert_eq!(
7156 p.state.load(Ordering::Relaxed),
7157 1,
7158 "the device is 3x faster once warm and must win"
7159 );
7160 }
7161
7162 #[test]
7166 fn the_warmup_is_spent_once_and_never_underflows() {
7167 let p = Probe::new();
7168 for _ in 0..8 {
7169 probe_record_into(&p, "matmat", None, true, ms(10.0));
7170 }
7171 assert_eq!(p.gpu_burn.load(Ordering::Relaxed), 0, "spent, not wrapped");
7172 assert_eq!(
7173 p.gpu_n.load(Ordering::Relaxed),
7174 7,
7175 "one sample burned, the rest counted"
7176 );
7177 }
7178
7179 #[test]
7185 fn a_class_whose_device_always_declines_settles_on_the_host() {
7186 let _probe_guard = probe_test_guard();
7187 let c = OpClass::MatmatWide;
7191 let p = &PROBES[c as usize];
7192 p.state.store(0, Ordering::Relaxed);
7193 p.declines.store(0, Ordering::Relaxed);
7194 for _ in 0..(PROBE_DECLINE_LIMIT - 1) {
7195 probe_note_decline(c);
7196 }
7197 assert_eq!(
7198 p.state.load(Ordering::Relaxed),
7199 0,
7200 "one short of the limit is still a question, not an answer"
7201 );
7202 probe_note_decline(c);
7203 assert_eq!(p.state.load(Ordering::Relaxed), 2, "settled on the host");
7204 assert!(matches!(probe_arm(c), ProbeArm::Cpu));
7205 p.state.store(0, Ordering::Relaxed);
7206 p.declines.store(0, Ordering::Relaxed);
7207 }
7208
7209 #[test]
7212 fn a_slow_device_still_loses_after_the_warmup() {
7213 let p = Probe::new();
7214 for _ in 0..4 {
7215 probe_record_into(&p, "matvec", None, true, ms(40.0));
7216 }
7217 for _ in 0..4 {
7218 probe_record_into(&p, "matvec", None, false, ms(2.0));
7219 }
7220 assert_eq!(p.state.load(Ordering::Relaxed), 2, "host wins on merit");
7221 }
7222}
7223
7224pub(crate) struct ImageStageGuard {
7227 #[cfg(target_os = "macos")]
7228 metal: Option<crate::gpu_metal::ImageStageGuard>,
7229 #[cfg(feature = "gpu")]
7230 wgpu: crate::gpu_wgpu::ImageStageGuard,
7231}
7232
7233pub(crate) fn image_stage_scope() -> ImageStageGuard {
7234 ImageStageGuard {
7235 #[cfg(target_os = "macos")]
7236 metal: if matches!(backend(), Backend::Metal) {
7237 Some(crate::gpu_metal::image_stage_scope())
7238 } else {
7239 None
7240 },
7241 #[cfg(feature = "gpu")]
7242 wgpu: crate::gpu_wgpu::image_stage_scope(),
7243 }
7244}
7245
7246impl ImageStageGuard {
7247 pub(crate) fn track_model(&mut self, uid: u64) {
7248 #[cfg(target_os = "macos")]
7249 if let Some(metal) = &mut self.metal {
7250 metal.track_model(uid);
7251 }
7252 #[cfg(feature = "gpu")]
7253 self.wgpu.track_model(uid);
7254 #[cfg(not(target_os = "macos"))]
7255 let _ = uid;
7256 }
7257}
7258
7259#[derive(Clone, Copy, Debug, PartialEq)]
7279pub struct Qi21Geom {
7280 pub hidden: usize,
7281 pub nh: usize,
7282 pub hd: usize,
7283 pub inter: usize,
7284 pub in_ch: usize,
7285 pub eps: f32,
7286}
7287
7288pub struct Qi21BlockRef<'a> {
7291 pub w: [usize; 7],
7292 pub norm_q: &'a [f32],
7293 pub norm_k: &'a [f32],
7294}
7295
7296pub struct Qi21PrefillArgs<'a> {
7298 pub model: &'a Arc<CmfModel>,
7299 pub geom: Qi21Geom,
7300 pub blocks: &'a [Qi21BlockRef<'a>],
7301 pub img_in: &'a [f32],
7303 pub proj_out: &'a [f32],
7304 pub key: u64,
7305 pub x: &'a [f32],
7307 pub lp: usize,
7308 pub rope_p: (&'a [f32], &'a [f32]),
7310 pub rope_t: (&'a [f32], &'a [f32]),
7311 pub vis: &'a [u32],
7313 pub mods0: &'a [f32],
7315 pub n: usize,
7317}
7318
7319#[allow(unused_variables)]
7321pub fn qi21_prefill(a: &Qi21PrefillArgs) -> bool {
7322 match backend() {
7323 #[cfg(target_os = "macos")]
7324 Backend::Metal => crate::gpu_metal::qi21::prefill(a),
7325 #[cfg(feature = "gpu")]
7326 Backend::Wgpu => crate::gpu_wgpu::qi21::prefill(a),
7327 #[cfg(feature = "cuda")]
7328 Backend::Cuda => crate::gpu_cuda::qi21_prefill(a),
7329 #[allow(unreachable_patterns)]
7330 _ => false,
7331 }
7332}
7333
7334#[allow(unused_variables)]
7336pub fn qi21_step(key: u64, xtok: &[f32], mods: &[f32], fs: &[f32], out: &mut [f32]) -> bool {
7337 match backend() {
7338 #[cfg(target_os = "macos")]
7339 Backend::Metal => crate::gpu_metal::qi21::step(key, xtok, mods, fs, out),
7340 #[cfg(feature = "gpu")]
7341 Backend::Wgpu => crate::gpu_wgpu::qi21::step(key, xtok, mods, fs, out),
7342 #[cfg(feature = "cuda")]
7343 Backend::Cuda => crate::gpu_cuda::qi21_step(key, xtok, mods, fs, out),
7344 #[allow(unreachable_patterns)]
7345 _ => false,
7346 }
7347}
7348
7349#[allow(unused_variables)]
7352pub fn qi21_release_key(key: u64) {
7353 #[cfg(target_os = "macos")]
7354 if matches!(backend(), Backend::Metal) {
7355 crate::gpu_metal::qi21::release_key(key);
7356 }
7357 #[cfg(feature = "gpu")]
7358 crate::gpu_wgpu::qi21::release_key(key);
7359 #[cfg(feature = "cuda")]
7360 if matches!(backend(), Backend::Cuda) {
7361 crate::gpu_cuda::qi21_release_key(key);
7362 }
7363}
7364
7365pub fn qi21_release() {
7368 #[cfg(target_os = "macos")]
7369 if matches!(backend(), Backend::Metal) {
7370 crate::gpu_metal::qi21::release();
7371 }
7372 #[cfg(feature = "gpu")]
7373 {
7374 crate::gpu_wgpu::qi21::release();
7375 crate::gpu_wgpu::qi21_vae::release();
7376 }
7377 #[cfg(feature = "cuda")]
7378 if matches!(backend(), Backend::Cuda) {
7379 crate::gpu_cuda::qi21_release();
7380 }
7381}
7382
7383#[derive(Clone, Copy)]
7386pub struct Qi21VaeConvRef<'a> {
7387 pub w: &'a [f32],
7388 pub b: &'a [f32],
7389 pub ci: usize,
7390 pub co: usize,
7391 pub k: usize,
7392}
7393
7394pub struct Qi21VaeResRef<'a> {
7397 pub g1: &'a [f32],
7398 pub c1: Qi21VaeConvRef<'a>,
7399 pub g2: &'a [f32],
7400 pub c2: Qi21VaeConvRef<'a>,
7401 pub shortcut: Option<Qi21VaeConvRef<'a>>,
7402}
7403
7404pub struct Qi21VaeUpRef<'a> {
7408 pub resnets: Vec<Qi21VaeResRef<'a>>,
7409 pub up: Option<(Qi21VaeConvRef<'a>, usize)>,
7410 pub in_dim: usize,
7411 pub out_dim: usize,
7412}
7413
7414pub struct Qi21VaeDecodeArgs<'a> {
7417 pub key: u64,
7419 pub post_quant: Qi21VaeConvRef<'a>,
7420 pub conv_in: Qi21VaeConvRef<'a>,
7421 pub mid_res: [Qi21VaeResRef<'a>; 2],
7422 pub attn_gamma: &'a [f32],
7425 pub attn_qkv: Qi21VaeConvRef<'a>,
7426 pub attn_proj: Qi21VaeConvRef<'a>,
7427 pub ups: Vec<Qi21VaeUpRef<'a>>,
7428 pub norm_out: &'a [f32],
7429 pub conv_out: Qi21VaeConvRef<'a>,
7430}
7431
7432#[allow(unused_variables)]
7436pub fn qi21_vae_decode(a: &Qi21VaeDecodeArgs, z: &[f32], h: usize, w: usize, out: &mut [f32]) -> bool {
7437 match backend() {
7438 #[cfg(feature = "gpu")]
7439 Backend::Wgpu => crate::gpu_wgpu::qi21_vae::decode(a, z, h, w, out),
7440 #[cfg(feature = "cuda")]
7441 Backend::Cuda => crate::gpu_cuda::qi21_vae_decode(a, z, h, w, out),
7442 #[allow(unreachable_patterns)]
7443 _ => false,
7444 }
7445}
7446
7447#[derive(Clone, Copy)]
7455pub struct ZBlockRef<'a> {
7456 pub wq: usize,
7458 pub wk: usize,
7459 pub wv: usize,
7460 pub wo: usize,
7461 pub w1: usize,
7464 pub w3: usize,
7465 pub w2: usize,
7466 pub norm1: &'a [f32],
7468 pub norm2: &'a [f32],
7469 pub ffn_norm1: &'a [f32],
7471 pub ffn_norm2: &'a [f32],
7472 pub norm_q: &'a [f32],
7474 pub norm_k: &'a [f32],
7475}
7476
7477#[derive(Clone, Copy, Debug, PartialEq)]
7481pub struct ZGeom {
7482 pub hidden: usize,
7483 pub nh: usize,
7484 pub hd: usize,
7485 pub inter: usize,
7486 pub eps: f32,
7487 pub final_eps: f32,
7488 pub patch_dim: usize,
7489}
7490
7491pub struct ZPrepareArgs<'a> {
7495 pub model: &'a Arc<CmfModel>,
7496 pub geom: ZGeom,
7497 pub key: u64,
7500 pub n_img: usize,
7503 pub n_img_p: usize,
7504 pub n_cap_p: usize,
7505 pub grid: (usize, usize),
7508 pub cap: &'a [f32],
7510 pub rope_img: (&'a [f32], &'a [f32]),
7513 pub rope_joint: (&'a [f32], &'a [f32]),
7515 pub x_emb_w: &'a [f32],
7518 pub x_emb_b: &'a [f32],
7519 pub x_pad: &'a [f32],
7520 pub final_w: &'a [f32],
7522 pub final_b: &'a [f32],
7523 pub noise_refiner: &'a [ZBlockRef<'a>],
7525 pub layers: &'a [ZBlockRef<'a>],
7526 pub mods_all: Option<&'a [f32]>,
7532 pub final_scale_all: Option<&'a [f32]>,
7533 pub neg: Option<ZNegArgs<'a>>,
7539}
7540
7541pub struct ZNegArgs<'a> {
7545 pub cap: &'a [f32],
7547 pub n_cap_p: usize,
7548 pub rope_img: (&'a [f32], &'a [f32]),
7550 pub rope_joint: (&'a [f32], &'a [f32]),
7552}
7553
7554pub struct ZStepArgs<'a> {
7556 pub key: u64,
7559 pub step: usize,
7562 pub x_tok: &'a [f32],
7566 pub mods: &'a [f32],
7570 pub final_scale: &'a [f32],
7572 pub out: &'a mut [f32],
7575 pub out_neg: Option<&'a mut [f32]>,
7578}
7579
7580#[allow(unused_variables)]
7584pub fn zimage_prepare(a: &ZPrepareArgs) -> bool {
7585 match backend() {
7586 #[cfg(target_os = "macos")]
7587 Backend::Metal => crate::gpu_metal::zimage::prepare(a),
7588 #[cfg(feature = "gpu")]
7589 Backend::Wgpu => crate::gpu_wgpu::zimage::prepare(a),
7590 #[cfg(feature = "cuda")]
7591 Backend::Cuda => crate::gpu_cuda::zimage_prepare(a),
7592 #[allow(unreachable_patterns)]
7593 _ => false,
7594 }
7595}
7596
7597#[allow(unused_variables)]
7601pub fn zimage_step(a: &mut ZStepArgs) -> bool {
7602 match backend() {
7603 #[cfg(target_os = "macos")]
7604 Backend::Metal => crate::gpu_metal::zimage::step(a),
7605 #[cfg(feature = "gpu")]
7606 Backend::Wgpu => crate::gpu_wgpu::zimage::step(a),
7607 #[cfg(feature = "cuda")]
7608 Backend::Cuda => crate::gpu_cuda::zimage_step(a),
7609 #[allow(unreachable_patterns)]
7610 _ => false,
7611 }
7612}
7613
7614#[allow(unused_variables)]
7619pub fn zimage_preload(
7620 model: &Arc<CmfModel>,
7621 geom: &ZGeom,
7622 noise_refiner: &[ZBlockRef],
7623 layers: &[ZBlockRef],
7624 context_refiner: &[ZBlockRef],
7625) -> bool {
7626 match backend() {
7627 #[cfg(target_os = "macos")]
7628 Backend::Metal => {
7629 crate::gpu_metal::zimage::preload(model, geom, noise_refiner, layers, context_refiner)
7630 }
7631 #[cfg(feature = "gpu")]
7632 Backend::Wgpu => crate::gpu_wgpu::zimage::preload(model, geom, noise_refiner, layers, context_refiner),
7633 #[allow(unreachable_patterns)]
7634 _ => false,
7635 }
7636}
7637
7638pub fn zimage_flush_pipelines() {
7642 #[cfg(feature = "gpu")]
7643 if matches!(backend(), Backend::Wgpu) {
7644 crate::gpu_wgpu::pipeline_cache_flush();
7645 }
7646}
7647
7648pub fn zimage_warmup() -> bool {
7653 match backend() {
7654 #[cfg(target_os = "macos")]
7655 Backend::Metal => crate::gpu_metal::zimage::warmup(),
7656 #[cfg(feature = "gpu")]
7657 Backend::Wgpu => crate::gpu_wgpu::zimage::warmup(),
7658 #[allow(unreachable_patterns)]
7659 _ => false,
7660 }
7661}
7662
7663#[allow(unused_variables)]
7667pub fn vae_prewarm(a: &crate::vae::VaeChainArgs) -> bool {
7668 match backend() {
7669 #[cfg(target_os = "macos")]
7670 Backend::Metal => crate::gpu_metal::zimage::vae_prewarm(a),
7671 #[cfg(feature = "gpu")]
7672 Backend::Wgpu => crate::gpu_wgpu::zimage::vae_prewarm(a),
7673 #[allow(unreachable_patterns)]
7674 _ => false,
7675 }
7676}
7677
7678pub fn zimage_release_dit() {
7681 #[cfg(target_os = "macos")]
7682 crate::gpu_metal::zimage::release_dit();
7683 #[cfg(feature = "gpu")]
7684 crate::gpu_wgpu::zimage::release_dit();
7685 #[cfg(feature = "cuda")]
7686 if matches!(backend(), Backend::Cuda) {
7687 crate::gpu_cuda::zimage_release();
7688 }
7689}
7690
7691pub fn zimage_release() {
7696 #[cfg(target_os = "macos")]
7697 crate::gpu_metal::zimage::release();
7698 #[cfg(feature = "gpu")]
7699 crate::gpu_wgpu::zimage::release();
7700 #[cfg(feature = "cuda")]
7701 if matches!(backend(), Backend::Cuda) {
7702 crate::gpu_cuda::zimage_release();
7703 }
7704}
7705
7706#[allow(unused_variables)]
7712pub fn zimage_refine_caption(
7713 model: &Arc<CmfModel>,
7714 geom: &ZGeom,
7715 blocks: &[ZBlockRef],
7716 rope_cap: (&[f32], &[f32]),
7717 cap: &mut [f32],
7718) -> bool {
7719 match backend() {
7720 #[cfg(target_os = "macos")]
7721 Backend::Metal => {
7722 crate::gpu_metal::zimage::refine_caption(model, geom, blocks, rope_cap, cap)
7723 }
7724 #[cfg(feature = "gpu")]
7725 Backend::Wgpu => {
7726 crate::gpu_wgpu::zimage::refine_caption(model, geom, blocks, rope_cap, cap)
7727 }
7728 #[allow(unreachable_patterns)]
7729 _ => false,
7730 }
7731}
7732
7733#[allow(unused_variables)]
7739pub fn vae_decode_chain(
7740 a: &crate::vae::VaeChainArgs,
7741 z: &[f32],
7742 h: usize,
7743 w: usize,
7744 out: &mut [f32],
7745) -> bool {
7746 match backend() {
7747 #[cfg(target_os = "macos")]
7748 Backend::Metal => crate::gpu_metal::zimage::vae_decode_chain(a, z, h, w, out),
7749 #[cfg(feature = "gpu")]
7750 Backend::Wgpu => crate::gpu_wgpu::zimage::vae_decode_chain(a, z, h, w, out),
7751 #[cfg(feature = "cuda")]
7752 Backend::Cuda => crate::gpu_cuda::flux_vae_chain(a, z, h, w, out),
7753 #[allow(unreachable_patterns)]
7754 _ => false,
7755 }
7756}
7757
7758
7759pub trait S2vStepper {
7763 fn step(&mut self, step: usize, chunk: usize, x: &[f32], memory: &[Vec<f32>; 3]) -> Result<Vec<f32>, String>;
7767}
7768
7769#[allow(unused_variables)]
7771pub fn s2v_prepare(
7772 dit: &crate::s2v::S2vDit,
7773 g: &crate::s2v::S2vGeom,
7774 cond: &crate::s2vgen::S2vCond,
7775 ts: &[f32],
7776 sf: [f32; 3],
7777) -> Option<Box<dyn S2vStepper>> {
7778 match backend() {
7779 #[cfg(feature = "gpu")]
7780 Backend::Wgpu => crate::gpu_wgpu::s2v::prepare(dit, g, cond, ts, sf).map(|d| Box::new(d) as Box<dyn S2vStepper>),
7781 #[cfg(target_os = "macos")]
7782 Backend::Metal => crate::gpu_metal::s2v::prepare(dit, g, cond, ts, sf).map(|d| Box::new(d) as Box<dyn S2vStepper>),
7783 #[cfg(feature = "cuda")]
7784 Backend::Cuda => crate::gpu_cuda::s2v_prepare(dit, g, cond, ts, sf).map(|d| Box::new(d) as Box<dyn S2vStepper>),
7785 #[allow(unreachable_patterns)]
7786 _ => None,
7787 }
7788}
7789
7790pub fn s2v_release() {
7792 #[cfg(feature = "gpu")]
7793 crate::gpu_wgpu::s2v_vae::release();
7794 #[cfg(target_os = "macos")]
7795 crate::gpu_metal::s2v::release();
7796 #[cfg(feature = "cuda")]
7797 if matches!(backend(), Backend::Cuda) {
7798 crate::gpu_cuda::s2v_vae_release();
7799 }
7800}
7801
7802#[allow(unused_variables)]
7804pub fn s2v_vae_decode(vae: &crate::s2v_vae::S2vVae, z: &crate::ltxvae::Vol) -> Option<crate::ltxvae::Vol> {
7805 match backend() {
7806 #[cfg(feature = "gpu")]
7807 Backend::Wgpu => crate::gpu_wgpu::s2v_vae::decode(vae, z),
7808 #[cfg(target_os = "macos")]
7809 Backend::Metal => crate::gpu_metal::s2v::decode(vae, z),
7810 #[cfg(feature = "cuda")]
7811 Backend::Cuda => crate::gpu_cuda::s2v_vae_decode(vae, z),
7812 #[allow(unreachable_patterns)]
7813 _ => None,
7814 }
7815}
7816
7817#[allow(unused_variables)]
7820pub fn sam3_trunk(m: &std::sync::Arc<cortiq_core::CmfModel>, pv: &[f32], pos_skip_cls: bool) -> Option<Vec<f32>> {
7821 match backend() {
7822 #[cfg(feature = "cuda")]
7823 Backend::Cuda => crate::gpu_cuda::sam3_trunk(m, pv, pos_skip_cls),
7824 #[cfg(feature = "gpu")]
7825 Backend::Wgpu => crate::gpu_wgpu::h3::sam3_trunk(m, pv, pos_skip_cls),
7826 #[allow(unreachable_patterns)]
7827 _ => None,
7828 }
7829}
7830
7831#[allow(unused_variables)]
7835pub fn plane_matmat(model: &Arc<CmfModel>, idx: usize, xs: &[f32], b: usize, rows: usize, cols: usize, out: &mut [f32]) -> bool {
7836 match backend() {
7837 #[cfg(feature = "cuda")]
7838 Backend::Cuda => crate::gpu_cuda::h3_matmat(model, idx, xs, b, rows, cols, out),
7839 #[allow(unreachable_patterns)]
7840 _ => false,
7841 }
7842}
7843
7844#[allow(unused_variables, clippy::too_many_arguments)]
7847pub fn sam3_attn_sep(q: &[f32], k: &[f32], v: &[f32], n_q: usize, n_k: usize, dim: usize, heads: usize, scale: f32, out: &mut [f32]) -> bool {
7848 if !enabled_here() {
7849 return false;
7850 }
7851 match backend() {
7852 #[cfg(feature = "cuda")]
7853 Backend::Cuda => crate::gpu_cuda::sam3_attn_sep(q, k, v, n_q, n_k, dim, heads, scale, out),
7854 #[allow(unreachable_patterns)]
7855 _ => false,
7856 }
7857}
7858
7859#[allow(unused_variables)]
7861pub fn sam3_mm(a: &[f32], b: &[f32], m: usize, k: usize, n: usize) -> Option<Vec<f32>> {
7862 if !enabled_here() {
7863 return None;
7864 }
7865 match backend() {
7866 #[cfg(feature = "cuda")]
7867 Backend::Cuda => crate::gpu_cuda::sam3_mm(a, b, m, k, n),
7868 #[allow(unreachable_patterns)]
7869 _ => None,
7870 }
7871}
7872
7873#[allow(unused_variables)]
7877pub fn sam3_text(m: &Arc<CmfModel>, x: &mut [f32], cm: &[f32]) -> bool {
7878 if !enabled_here() {
7879 return false;
7880 }
7881 match backend() {
7882 #[cfg(feature = "cuda")]
7883 Backend::Cuda => crate::gpu_cuda::sam3_text(m, x, cm),
7884 #[allow(unreachable_patterns)]
7885 _ => false,
7886 }
7887}
7888
7889#[allow(unused_variables, clippy::too_many_arguments)]
7891pub fn sam3_conv2d(w: &[f32], b: &[f32], x: &[f32], ci: usize, h: usize, wid: usize, kh: usize, kw: usize, stride: usize, pad: usize) -> Option<Vec<f32>> {
7892 if !enabled_here() {
7893 return None;
7894 }
7895 match backend() {
7896 #[cfg(feature = "cuda")]
7897 Backend::Cuda => crate::gpu_cuda::sam3_conv2d(w, b, x, ci, h, wid, kh, kw, stride, pad),
7898 #[allow(unreachable_patterns)]
7899 _ => None,
7900 }
7901}
7902
7903#[allow(unused_variables)]
7905pub fn sam3_convt2x2(w: &[f32], b: &[f32], x: &[f32], ci: usize, h: usize, wid: usize) -> Option<Vec<f32>> {
7906 if !enabled_here() {
7907 return None;
7908 }
7909 match backend() {
7910 #[cfg(feature = "cuda")]
7911 Backend::Cuda => crate::gpu_cuda::sam3_convt2x2(w, b, x, ci, h, wid),
7912 #[allow(unreachable_patterns)]
7913 _ => None,
7914 }
7915}
7916
7917#[allow(unused_variables, clippy::too_many_arguments)]
7920pub fn sam3_attn_core(q: &[f32], k: &[f32], v: &[f32], n_q: usize, n_k: usize, dim: usize, heads: usize, mode: i32, mask: &[f32], scale: f32, out: &mut [f32]) -> bool {
7921 if !enabled_here() {
7922 return false;
7923 }
7924 match backend() {
7925 #[cfg(feature = "cuda")]
7926 Backend::Cuda => crate::gpu_cuda::sam3_attn_core(q, k, v, n_q, n_k, dim, heads, mode, mask, scale, out),
7927 #[allow(unreachable_patterns)]
7928 _ => false,
7929 }
7930}
7931
7932#[allow(unused_variables)]
7934pub fn s2v_vae_encode(enc: &crate::s2v_vae::S2vVaeEncoder, img: &crate::ltxvae::Vol) -> Option<(crate::ltxvae::Vol, crate::ltxvae::Vol)> {
7935 match backend() {
7936 #[cfg(feature = "gpu")]
7937 Backend::Wgpu => crate::gpu_wgpu::s2v_vae::encode(enc, img),
7938 #[cfg(target_os = "macos")]
7939 Backend::Metal => crate::gpu_metal::s2v::encode(enc, img),
7940 #[cfg(feature = "cuda")]
7941 Backend::Cuda => crate::gpu_cuda::s2v_vae_encode(enc, img),
7942 #[allow(unreachable_patterns)]
7943 _ => None,
7944 }
7945}
7946
7947#[allow(unused_variables)]
7949pub fn s2v_check_forward(dit: &crate::s2v::S2vDit, i: &crate::s2v::S2vInput<'_>) -> Option<Vec<f32>> {
7950 let cond = crate::s2vgen::S2vCond {
7951 text: i.text_feats.to_vec(),
7952 pooled: i.pooled.to_vec(),
7953 audio: vec![i.audio_feats.to_vec()],
7954 reference: i.reference.to_vec(),
7955 height: i.geom.lh * 8,
7956 width: i.geom.lw * 8,
7957 };
7958 let mut dev = s2v_prepare(dit, &i.geom, &cond, &[i.t], i.scale_factor)?;
7959 let memory = [i.mem1.to_vec(), i.mem2.to_vec(), i.mem4.to_vec()];
7960 dev.step(0, 0, i.x, &memory).ok()
7961}