1use std::collections::HashMap;
25use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
26use std::sync::{Arc, Mutex, OnceLock, RwLock};
27
28use fuel_ir::backend::{BackendCapabilities, SubstrateClass, TransferPath};
29use fuel_ir::dispatch::OpKind;
30use fuel_ir::probe::BackendId;
31use fuel_ir::{DType, DeviceLocation, Error, Layout, Result};
32
33#[cfg(feature = "cuda")]
34use crate::kernel::KernelCaps;
35use crate::kernel::{KernelBindingTable, MatmulM, OpParams};
36use fuel_memory::{BackendStorage, Storage};
37
38#[derive(Debug, Default)]
41pub struct CapabilityRegistry {
42 backends: Vec<BackendCapabilities>,
43}
44
45impl CapabilityRegistry {
46 pub fn new() -> Self {
48 Self {
49 backends: Vec::new(),
50 }
51 }
52
53 pub fn register(&mut self, caps: BackendCapabilities) {
58 self.backends.push(caps);
59 }
60
61 pub fn backends(&self) -> &[BackendCapabilities] {
63 &self.backends
64 }
65
66 pub fn find_backends(&self, op: OpKind, dtype: DType) -> Vec<&BackendCapabilities> {
68 self.backends
69 .iter()
70 .filter(|caps| caps.op_dtype_support.contains(&(op, dtype)))
71 .collect()
72 }
73
74 pub fn find_backend_for(&self, op: OpKind, dtype: DType) -> Result<&BackendCapabilities> {
84 for caps in &self.backends {
85 if caps.op_dtype_support.contains(&(op, dtype)) {
86 return Ok(caps);
87 }
88 }
89 Err(Error::NoBackendForOp {
94 op,
95 dtypes: vec![dtype],
96 available_backends: self.backends.iter().map(|c| c.backend_id).collect(),
97 supported_combinations: self
98 .backends
99 .iter()
100 .flat_map(|c| {
101 c.op_dtype_support
102 .iter()
103 .map(|&(o, d)| (c.backend_id, o, vec![d]))
104 })
105 .collect(),
106 }
107 .bt())
108 }
109
110 pub fn build_transfer_matrix(&self) -> TransferMatrix {
115 let mut entries = HashMap::new();
116 for caps in &self.backends {
117 for (dst, path) in &caps.transfer_paths {
118 entries.insert((caps.device_location, *dst), *path);
119 }
120 }
121 TransferMatrix { entries }
122 }
123}
124
125#[derive(Debug, Default)]
130pub struct TransferMatrix {
131 entries: HashMap<(DeviceLocation, DeviceLocation), TransferPath>,
132}
133
134impl TransferMatrix {
135 pub fn path(&self, src: DeviceLocation, dst: DeviceLocation) -> Option<TransferPath> {
140 if src == dst {
141 return Some(TransferPath::SameDevice);
142 }
143 self.entries.get(&(src, dst)).copied()
144 }
145
146 pub fn path_or_staging(&self, src: DeviceLocation, dst: DeviceLocation) -> TransferPath {
154 self.path(src, dst).unwrap_or(TransferPath::HostStaging)
155 }
156
157 pub fn entries(
159 &self,
160 ) -> impl Iterator<Item = (&(DeviceLocation, DeviceLocation), &TransferPath)> {
161 self.entries.iter()
162 }
163}
164
165pub fn resolve_target_backend(
178 registry: &CapabilityRegistry,
179 op: OpKind,
180 dtype: DType,
181) -> Result<BackendId> {
182 registry
183 .find_backend_for(op, dtype)
184 .map(|caps| caps.backend_id)
185}
186
187pub fn resolve_target_backend_residency_aware(
203 registry: &CapabilityRegistry,
204 op: OpKind,
205 dtype: DType,
206 input_locations: &[DeviceLocation],
207) -> Result<BackendId> {
208 let candidates = registry.find_backends(op, dtype);
209 if candidates.is_empty() {
210 return registry.find_backend_for(op, dtype).map(|c| c.backend_id);
212 }
213 for caps in &candidates {
216 if input_locations.contains(&caps.device_location) {
217 return Ok(caps.backend_id);
218 }
219 }
220 Ok(candidates[0].backend_id)
223}
224
225pub fn cpu_input(s: &Storage) -> Result<&fuel_cpu_backend::CpuStorageBytes> {
232 match &s.inner {
233 BackendStorage::Cpu(c) => Ok(c),
234 #[allow(unreachable_patterns)]
235 _ => Err(Error::Msg("cpu kernel wrapper called with non-CPU input".to_string()).bt()),
236 }
237}
238
239pub fn cpu_output(s: &mut Storage) -> Result<&mut fuel_cpu_backend::CpuStorageBytes> {
245 match &mut s.inner {
246 BackendStorage::Cpu(c) => Ok(c),
247 #[allow(unreachable_patterns)]
248 _ => Err(Error::Msg("cpu kernel wrapper called with non-CPU output".to_string()).bt()),
249 }
250}
251
252pub fn read_storage(arc: &Arc<RwLock<Storage>>) -> Result<std::sync::RwLockReadGuard<'_, Storage>> {
257 arc.read()
258 .map_err(|_| Error::Msg("kernel wrapper: storage RwLock poisoned (read)".to_string()).bt())
259}
260
261pub fn write_storage(
262 arc: &Arc<RwLock<Storage>>,
263) -> Result<std::sync::RwLockWriteGuard<'_, Storage>> {
264 arc.write()
265 .map_err(|_| Error::Msg("kernel wrapper: storage RwLock poisoned (write)".to_string()).bt())
266}
267
268macro_rules! cpu_binary_wrapper {
273 ($wrapper:ident, $kernel:path, $op_name:literal) => {
274 pub(crate) fn $wrapper(
277 inputs: &[Arc<RwLock<Storage>>],
278 outputs: &mut [Arc<RwLock<Storage>>],
279 _layouts: &[Layout],
280 _params: &OpParams,
281 ) -> Result<()> {
282 if inputs.len() != 2 {
283 return Err(Error::Msg(format!(
284 "{} wrapper expects 2 inputs, got {}",
285 $op_name,
286 inputs.len(),
287 ))
288 .bt());
289 }
290 if outputs.len() != 1 {
291 return Err(Error::Msg(format!(
292 "{} wrapper expects 1 output, got {}",
293 $op_name,
294 outputs.len(),
295 ))
296 .bt());
297 }
298 let lhs_guard = read_storage(&inputs[0])?;
299 let rhs_guard = read_storage(&inputs[1])?;
300 let mut out_guard = write_storage(&outputs[0])?;
301 let lhs_cpu = cpu_input(&lhs_guard)?;
302 let rhs_cpu = cpu_input(&rhs_guard)?;
303 let out_cpu = cpu_output(&mut out_guard)?;
304 $kernel(lhs_cpu, rhs_cpu, out_cpu)
305 }
306 };
307}
308
309macro_rules! cpu_unary_wrapper {
312 ($wrapper:ident, $kernel:path, $op_name:literal) => {
313 pub(crate) fn $wrapper(
316 inputs: &[Arc<RwLock<Storage>>],
317 outputs: &mut [Arc<RwLock<Storage>>],
318 _layouts: &[Layout],
319 _params: &OpParams,
320 ) -> Result<()> {
321 if inputs.len() != 1 {
322 return Err(Error::Msg(format!(
323 "{} wrapper expects 1 input, got {}",
324 $op_name,
325 inputs.len(),
326 ))
327 .bt());
328 }
329 if outputs.len() != 1 {
330 return Err(Error::Msg(format!(
331 "{} wrapper expects 1 output, got {}",
332 $op_name,
333 outputs.len(),
334 ))
335 .bt());
336 }
337 let in_guard = read_storage(&inputs[0])?;
338 let mut out_guard = write_storage(&outputs[0])?;
339 let in_cpu = cpu_input(&in_guard)?;
340 let out_cpu = cpu_output(&mut out_guard)?;
341 $kernel(in_cpu, out_cpu)
342 }
343 };
344}
345
346cpu_binary_wrapper!(
347 add_elementwise_f32_cpu_wrapper,
348 fuel_cpu_backend::byte_kernels::add_f32,
349 "add_elementwise"
350);
351cpu_binary_wrapper!(
352 sub_elementwise_f32_cpu_wrapper,
353 fuel_cpu_backend::byte_kernels::sub_f32,
354 "sub_elementwise"
355);
356cpu_binary_wrapper!(
357 mul_elementwise_f32_cpu_wrapper,
358 fuel_cpu_backend::byte_kernels::mul_f32,
359 "mul_elementwise"
360);
361cpu_binary_wrapper!(
362 div_elementwise_f32_cpu_wrapper,
363 fuel_cpu_backend::byte_kernels::div_f32,
364 "div_elementwise"
365);
366
367cpu_unary_wrapper!(
368 relu_elementwise_f32_cpu_wrapper,
369 fuel_cpu_backend::byte_kernels::relu_f32,
370 "relu_elementwise"
371);
372cpu_unary_wrapper!(
373 neg_elementwise_f32_cpu_wrapper,
374 fuel_cpu_backend::byte_kernels::neg_f32,
375 "neg_elementwise"
376);
377cpu_unary_wrapper!(
378 sqr_elementwise_f32_cpu_wrapper,
379 fuel_cpu_backend::byte_kernels::sqr_f32,
380 "sqr_elementwise"
381);
382cpu_unary_wrapper!(
383 sqrt_elementwise_f32_cpu_wrapper,
384 fuel_cpu_backend::byte_kernels::sqrt_f32,
385 "sqrt_elementwise"
386);
387cpu_unary_wrapper!(
388 recip_elementwise_f32_cpu_wrapper,
389 fuel_cpu_backend::byte_kernels::recip_f32,
390 "recip_elementwise"
391);
392cpu_unary_wrapper!(
393 abs_elementwise_f32_cpu_wrapper,
394 fuel_cpu_backend::byte_kernels::abs_f32,
395 "abs_elementwise"
396);
397cpu_unary_wrapper!(
398 tanh_elementwise_f32_cpu_wrapper,
399 fuel_cpu_backend::byte_kernels::tanh_f32,
400 "tanh_elementwise"
401);
402cpu_unary_wrapper!(
403 exp_elementwise_f32_cpu_wrapper,
404 fuel_cpu_backend::byte_kernels::exp_f32,
405 "exp_elementwise"
406);
407cpu_unary_wrapper!(
408 log_elementwise_f32_cpu_wrapper,
409 fuel_cpu_backend::byte_kernels::log_f32,
410 "log_elementwise"
411);
412cpu_unary_wrapper!(
413 sin_elementwise_f32_cpu_wrapper,
414 fuel_cpu_backend::byte_kernels::sin_f32,
415 "sin_elementwise"
416);
417cpu_unary_wrapper!(
418 cos_elementwise_f32_cpu_wrapper,
419 fuel_cpu_backend::byte_kernels::cos_f32,
420 "cos_elementwise"
421);
422cpu_unary_wrapper!(
423 sigmoid_elementwise_f32_cpu_wrapper,
424 fuel_cpu_backend::byte_kernels::sigmoid_f32,
425 "sigmoid_elementwise"
426);
427cpu_unary_wrapper!(
428 silu_elementwise_f32_cpu_wrapper,
429 fuel_cpu_backend::byte_kernels::silu_f32,
430 "silu_elementwise"
431);
432cpu_unary_wrapper!(
433 gelu_elementwise_f32_cpu_wrapper,
434 fuel_cpu_backend::byte_kernels::gelu_f32,
435 "gelu_elementwise"
436);
437cpu_unary_wrapper!(
438 step_elementwise_f32_cpu_wrapper,
439 fuel_cpu_backend::byte_kernels::step_f32,
440 "step_elementwise"
441);
442
443cpu_binary_wrapper!(
449 add_elementwise_f64_cpu_wrapper,
450 fuel_cpu_backend::byte_kernels::add_f64,
451 "add_elementwise"
452);
453cpu_binary_wrapper!(
454 sub_elementwise_f64_cpu_wrapper,
455 fuel_cpu_backend::byte_kernels::sub_f64,
456 "sub_elementwise"
457);
458cpu_binary_wrapper!(
459 mul_elementwise_f64_cpu_wrapper,
460 fuel_cpu_backend::byte_kernels::mul_f64,
461 "mul_elementwise"
462);
463cpu_binary_wrapper!(
464 div_elementwise_f64_cpu_wrapper,
465 fuel_cpu_backend::byte_kernels::div_f64,
466 "div_elementwise"
467);
468
469cpu_unary_wrapper!(
470 relu_elementwise_f64_cpu_wrapper,
471 fuel_cpu_backend::byte_kernels::relu_f64,
472 "relu_elementwise"
473);
474cpu_unary_wrapper!(
475 neg_elementwise_f64_cpu_wrapper,
476 fuel_cpu_backend::byte_kernels::neg_f64,
477 "neg_elementwise"
478);
479cpu_unary_wrapper!(
480 sqr_elementwise_f64_cpu_wrapper,
481 fuel_cpu_backend::byte_kernels::sqr_f64,
482 "sqr_elementwise"
483);
484cpu_unary_wrapper!(
485 sqrt_elementwise_f64_cpu_wrapper,
486 fuel_cpu_backend::byte_kernels::sqrt_f64,
487 "sqrt_elementwise"
488);
489cpu_unary_wrapper!(
490 recip_elementwise_f64_cpu_wrapper,
491 fuel_cpu_backend::byte_kernels::recip_f64,
492 "recip_elementwise"
493);
494cpu_unary_wrapper!(
495 abs_elementwise_f64_cpu_wrapper,
496 fuel_cpu_backend::byte_kernels::abs_f64,
497 "abs_elementwise"
498);
499cpu_unary_wrapper!(
500 tanh_elementwise_f64_cpu_wrapper,
501 fuel_cpu_backend::byte_kernels::tanh_f64,
502 "tanh_elementwise"
503);
504cpu_unary_wrapper!(
505 exp_elementwise_f64_cpu_wrapper,
506 fuel_cpu_backend::byte_kernels::exp_f64,
507 "exp_elementwise"
508);
509cpu_unary_wrapper!(
510 log_elementwise_f64_cpu_wrapper,
511 fuel_cpu_backend::byte_kernels::log_f64,
512 "log_elementwise"
513);
514cpu_unary_wrapper!(
515 sin_elementwise_f64_cpu_wrapper,
516 fuel_cpu_backend::byte_kernels::sin_f64,
517 "sin_elementwise"
518);
519cpu_unary_wrapper!(
520 cos_elementwise_f64_cpu_wrapper,
521 fuel_cpu_backend::byte_kernels::cos_f64,
522 "cos_elementwise"
523);
524cpu_unary_wrapper!(
525 sigmoid_elementwise_f64_cpu_wrapper,
526 fuel_cpu_backend::byte_kernels::sigmoid_f64,
527 "sigmoid_elementwise"
528);
529cpu_unary_wrapper!(
530 silu_elementwise_f64_cpu_wrapper,
531 fuel_cpu_backend::byte_kernels::silu_f64,
532 "silu_elementwise"
533);
534cpu_unary_wrapper!(
535 gelu_elementwise_f64_cpu_wrapper,
536 fuel_cpu_backend::byte_kernels::gelu_f64,
537 "gelu_elementwise"
538);
539cpu_unary_wrapper!(
540 step_elementwise_f64_cpu_wrapper,
541 fuel_cpu_backend::byte_kernels::step_f64,
542 "step_elementwise"
543);
544
545cpu_binary_wrapper!(
546 maximum_elementwise_f32_cpu_wrapper,
547 fuel_cpu_backend::byte_kernels::maximum_f32,
548 "maximum_elementwise"
549);
550cpu_binary_wrapper!(
551 minimum_elementwise_f32_cpu_wrapper,
552 fuel_cpu_backend::byte_kernels::minimum_f32,
553 "minimum_elementwise"
554);
555cpu_binary_wrapper!(
556 maximum_elementwise_f64_cpu_wrapper,
557 fuel_cpu_backend::byte_kernels::maximum_f64,
558 "maximum_elementwise"
559);
560cpu_binary_wrapper!(
561 minimum_elementwise_f64_cpu_wrapper,
562 fuel_cpu_backend::byte_kernels::minimum_f64,
563 "minimum_elementwise"
564);
565
566cpu_binary_wrapper!(
568 add_elementwise_bf16_cpu_wrapper,
569 fuel_cpu_backend::byte_kernels::add_bf16,
570 "add_elementwise"
571);
572cpu_binary_wrapper!(
573 sub_elementwise_bf16_cpu_wrapper,
574 fuel_cpu_backend::byte_kernels::sub_bf16,
575 "sub_elementwise"
576);
577cpu_binary_wrapper!(
578 mul_elementwise_bf16_cpu_wrapper,
579 fuel_cpu_backend::byte_kernels::mul_bf16,
580 "mul_elementwise"
581);
582cpu_binary_wrapper!(
583 div_elementwise_bf16_cpu_wrapper,
584 fuel_cpu_backend::byte_kernels::div_bf16,
585 "div_elementwise"
586);
587cpu_binary_wrapper!(
588 maximum_elementwise_bf16_cpu_wrapper,
589 fuel_cpu_backend::byte_kernels::maximum_bf16,
590 "maximum_elementwise"
591);
592cpu_binary_wrapper!(
593 minimum_elementwise_bf16_cpu_wrapper,
594 fuel_cpu_backend::byte_kernels::minimum_bf16,
595 "minimum_elementwise"
596);
597
598cpu_unary_wrapper!(
599 relu_elementwise_bf16_cpu_wrapper,
600 fuel_cpu_backend::byte_kernels::relu_bf16,
601 "relu_elementwise"
602);
603cpu_unary_wrapper!(
604 neg_elementwise_bf16_cpu_wrapper,
605 fuel_cpu_backend::byte_kernels::neg_bf16,
606 "neg_elementwise"
607);
608cpu_unary_wrapper!(
609 sqr_elementwise_bf16_cpu_wrapper,
610 fuel_cpu_backend::byte_kernels::sqr_bf16,
611 "sqr_elementwise"
612);
613cpu_unary_wrapper!(
614 sqrt_elementwise_bf16_cpu_wrapper,
615 fuel_cpu_backend::byte_kernels::sqrt_bf16,
616 "sqrt_elementwise"
617);
618cpu_unary_wrapper!(
619 recip_elementwise_bf16_cpu_wrapper,
620 fuel_cpu_backend::byte_kernels::recip_bf16,
621 "recip_elementwise"
622);
623cpu_unary_wrapper!(
624 abs_elementwise_bf16_cpu_wrapper,
625 fuel_cpu_backend::byte_kernels::abs_bf16,
626 "abs_elementwise"
627);
628cpu_unary_wrapper!(
629 tanh_elementwise_bf16_cpu_wrapper,
630 fuel_cpu_backend::byte_kernels::tanh_bf16,
631 "tanh_elementwise"
632);
633cpu_unary_wrapper!(
634 exp_elementwise_bf16_cpu_wrapper,
635 fuel_cpu_backend::byte_kernels::exp_bf16,
636 "exp_elementwise"
637);
638cpu_unary_wrapper!(
639 log_elementwise_bf16_cpu_wrapper,
640 fuel_cpu_backend::byte_kernels::log_bf16,
641 "log_elementwise"
642);
643cpu_unary_wrapper!(
644 sin_elementwise_bf16_cpu_wrapper,
645 fuel_cpu_backend::byte_kernels::sin_bf16,
646 "sin_elementwise"
647);
648cpu_unary_wrapper!(
649 cos_elementwise_bf16_cpu_wrapper,
650 fuel_cpu_backend::byte_kernels::cos_bf16,
651 "cos_elementwise"
652);
653cpu_unary_wrapper!(
654 sigmoid_elementwise_bf16_cpu_wrapper,
655 fuel_cpu_backend::byte_kernels::sigmoid_bf16,
656 "sigmoid_elementwise"
657);
658cpu_unary_wrapper!(
659 silu_elementwise_bf16_cpu_wrapper,
660 fuel_cpu_backend::byte_kernels::silu_bf16,
661 "silu_elementwise"
662);
663cpu_unary_wrapper!(
664 gelu_elementwise_bf16_cpu_wrapper,
665 fuel_cpu_backend::byte_kernels::gelu_bf16,
666 "gelu_elementwise"
667);
668cpu_unary_wrapper!(
669 step_elementwise_bf16_cpu_wrapper,
670 fuel_cpu_backend::byte_kernels::step_bf16,
671 "step_elementwise"
672);
673
674cpu_binary_wrapper!(
676 add_elementwise_f16_cpu_wrapper,
677 fuel_cpu_backend::byte_kernels::add_f16,
678 "add_elementwise"
679);
680cpu_binary_wrapper!(
681 sub_elementwise_f16_cpu_wrapper,
682 fuel_cpu_backend::byte_kernels::sub_f16,
683 "sub_elementwise"
684);
685cpu_binary_wrapper!(
686 mul_elementwise_f16_cpu_wrapper,
687 fuel_cpu_backend::byte_kernels::mul_f16,
688 "mul_elementwise"
689);
690cpu_binary_wrapper!(
691 div_elementwise_f16_cpu_wrapper,
692 fuel_cpu_backend::byte_kernels::div_f16,
693 "div_elementwise"
694);
695cpu_binary_wrapper!(
696 maximum_elementwise_f16_cpu_wrapper,
697 fuel_cpu_backend::byte_kernels::maximum_f16,
698 "maximum_elementwise"
699);
700cpu_binary_wrapper!(
701 minimum_elementwise_f16_cpu_wrapper,
702 fuel_cpu_backend::byte_kernels::minimum_f16,
703 "minimum_elementwise"
704);
705
706cpu_unary_wrapper!(
707 relu_elementwise_f16_cpu_wrapper,
708 fuel_cpu_backend::byte_kernels::relu_f16,
709 "relu_elementwise"
710);
711cpu_unary_wrapper!(
712 neg_elementwise_f16_cpu_wrapper,
713 fuel_cpu_backend::byte_kernels::neg_f16,
714 "neg_elementwise"
715);
716cpu_unary_wrapper!(
717 sqr_elementwise_f16_cpu_wrapper,
718 fuel_cpu_backend::byte_kernels::sqr_f16,
719 "sqr_elementwise"
720);
721cpu_unary_wrapper!(
722 sqrt_elementwise_f16_cpu_wrapper,
723 fuel_cpu_backend::byte_kernels::sqrt_f16,
724 "sqrt_elementwise"
725);
726cpu_unary_wrapper!(
727 recip_elementwise_f16_cpu_wrapper,
728 fuel_cpu_backend::byte_kernels::recip_f16,
729 "recip_elementwise"
730);
731cpu_unary_wrapper!(
732 abs_elementwise_f16_cpu_wrapper,
733 fuel_cpu_backend::byte_kernels::abs_f16,
734 "abs_elementwise"
735);
736cpu_unary_wrapper!(
737 tanh_elementwise_f16_cpu_wrapper,
738 fuel_cpu_backend::byte_kernels::tanh_f16,
739 "tanh_elementwise"
740);
741cpu_unary_wrapper!(
742 exp_elementwise_f16_cpu_wrapper,
743 fuel_cpu_backend::byte_kernels::exp_f16,
744 "exp_elementwise"
745);
746cpu_unary_wrapper!(
747 log_elementwise_f16_cpu_wrapper,
748 fuel_cpu_backend::byte_kernels::log_f16,
749 "log_elementwise"
750);
751cpu_unary_wrapper!(
752 sin_elementwise_f16_cpu_wrapper,
753 fuel_cpu_backend::byte_kernels::sin_f16,
754 "sin_elementwise"
755);
756cpu_unary_wrapper!(
757 cos_elementwise_f16_cpu_wrapper,
758 fuel_cpu_backend::byte_kernels::cos_f16,
759 "cos_elementwise"
760);
761cpu_unary_wrapper!(
762 sigmoid_elementwise_f16_cpu_wrapper,
763 fuel_cpu_backend::byte_kernels::sigmoid_f16,
764 "sigmoid_elementwise"
765);
766cpu_unary_wrapper!(
767 silu_elementwise_f16_cpu_wrapper,
768 fuel_cpu_backend::byte_kernels::silu_f16,
769 "silu_elementwise"
770);
771cpu_unary_wrapper!(
772 gelu_elementwise_f16_cpu_wrapper,
773 fuel_cpu_backend::byte_kernels::gelu_f16,
774 "gelu_elementwise"
775);
776cpu_unary_wrapper!(
777 step_elementwise_f16_cpu_wrapper,
778 fuel_cpu_backend::byte_kernels::step_f16,
779 "step_elementwise"
780);
781
782cpu_binary_wrapper!(
788 eq_elementwise_f32_cpu_wrapper,
789 fuel_cpu_backend::byte_kernels::eq_f32_u8,
790 "eq_elementwise"
791);
792cpu_binary_wrapper!(
793 eq_elementwise_f64_cpu_wrapper,
794 fuel_cpu_backend::byte_kernels::eq_f64_u8,
795 "eq_elementwise"
796);
797cpu_binary_wrapper!(
798 eq_elementwise_bf16_cpu_wrapper,
799 fuel_cpu_backend::byte_kernels::eq_bf16_u8,
800 "eq_elementwise"
801);
802cpu_binary_wrapper!(
803 eq_elementwise_f16_cpu_wrapper,
804 fuel_cpu_backend::byte_kernels::eq_f16_u8,
805 "eq_elementwise"
806);
807
808cpu_binary_wrapper!(
809 ne_elementwise_f32_cpu_wrapper,
810 fuel_cpu_backend::byte_kernels::ne_f32_u8,
811 "ne_elementwise"
812);
813cpu_binary_wrapper!(
814 ne_elementwise_f64_cpu_wrapper,
815 fuel_cpu_backend::byte_kernels::ne_f64_u8,
816 "ne_elementwise"
817);
818cpu_binary_wrapper!(
819 ne_elementwise_bf16_cpu_wrapper,
820 fuel_cpu_backend::byte_kernels::ne_bf16_u8,
821 "ne_elementwise"
822);
823cpu_binary_wrapper!(
824 ne_elementwise_f16_cpu_wrapper,
825 fuel_cpu_backend::byte_kernels::ne_f16_u8,
826 "ne_elementwise"
827);
828
829cpu_binary_wrapper!(
830 lt_elementwise_f32_cpu_wrapper,
831 fuel_cpu_backend::byte_kernels::lt_f32_u8,
832 "lt_elementwise"
833);
834cpu_binary_wrapper!(
835 lt_elementwise_f64_cpu_wrapper,
836 fuel_cpu_backend::byte_kernels::lt_f64_u8,
837 "lt_elementwise"
838);
839cpu_binary_wrapper!(
840 lt_elementwise_bf16_cpu_wrapper,
841 fuel_cpu_backend::byte_kernels::lt_bf16_u8,
842 "lt_elementwise"
843);
844cpu_binary_wrapper!(
845 lt_elementwise_f16_cpu_wrapper,
846 fuel_cpu_backend::byte_kernels::lt_f16_u8,
847 "lt_elementwise"
848);
849
850cpu_binary_wrapper!(
851 le_elementwise_f32_cpu_wrapper,
852 fuel_cpu_backend::byte_kernels::le_f32_u8,
853 "le_elementwise"
854);
855cpu_binary_wrapper!(
856 le_elementwise_f64_cpu_wrapper,
857 fuel_cpu_backend::byte_kernels::le_f64_u8,
858 "le_elementwise"
859);
860cpu_binary_wrapper!(
861 le_elementwise_bf16_cpu_wrapper,
862 fuel_cpu_backend::byte_kernels::le_bf16_u8,
863 "le_elementwise"
864);
865cpu_binary_wrapper!(
866 le_elementwise_f16_cpu_wrapper,
867 fuel_cpu_backend::byte_kernels::le_f16_u8,
868 "le_elementwise"
869);
870
871cpu_binary_wrapper!(
872 gt_elementwise_f32_cpu_wrapper,
873 fuel_cpu_backend::byte_kernels::gt_f32_u8,
874 "gt_elementwise"
875);
876cpu_binary_wrapper!(
877 gt_elementwise_f64_cpu_wrapper,
878 fuel_cpu_backend::byte_kernels::gt_f64_u8,
879 "gt_elementwise"
880);
881cpu_binary_wrapper!(
882 gt_elementwise_bf16_cpu_wrapper,
883 fuel_cpu_backend::byte_kernels::gt_bf16_u8,
884 "gt_elementwise"
885);
886cpu_binary_wrapper!(
887 gt_elementwise_f16_cpu_wrapper,
888 fuel_cpu_backend::byte_kernels::gt_f16_u8,
889 "gt_elementwise"
890);
891
892cpu_binary_wrapper!(
893 ge_elementwise_f32_cpu_wrapper,
894 fuel_cpu_backend::byte_kernels::ge_f32_u8,
895 "ge_elementwise"
896);
897cpu_binary_wrapper!(
898 ge_elementwise_f64_cpu_wrapper,
899 fuel_cpu_backend::byte_kernels::ge_f64_u8,
900 "ge_elementwise"
901);
902cpu_binary_wrapper!(
903 ge_elementwise_bf16_cpu_wrapper,
904 fuel_cpu_backend::byte_kernels::ge_bf16_u8,
905 "ge_elementwise"
906);
907cpu_binary_wrapper!(
908 ge_elementwise_f16_cpu_wrapper,
909 fuel_cpu_backend::byte_kernels::ge_f16_u8,
910 "ge_elementwise"
911);
912
913macro_rules! cpu_where_wrapper {
919 ($wrapper:ident, $kernel:path, $op_name:literal) => {
920 pub(crate) fn $wrapper(
923 inputs: &[Arc<RwLock<Storage>>],
924 outputs: &mut [Arc<RwLock<Storage>>],
925 _layouts: &[Layout],
926 _params: &OpParams,
927 ) -> Result<()> {
928 if inputs.len() != 3 {
929 return Err(Error::Msg(format!(
930 "{} wrapper expects 3 inputs (cond, a, b), got {}",
931 $op_name,
932 inputs.len(),
933 ))
934 .bt());
935 }
936 if outputs.len() != 1 {
937 return Err(Error::Msg(format!(
938 "{} wrapper expects 1 output, got {}",
939 $op_name,
940 outputs.len(),
941 ))
942 .bt());
943 }
944 let cond_guard = read_storage(&inputs[0])?;
945 if cond_guard.dtype != DType::Bool {
951 return Err(Error::Msg(format!(
952 "{}: cond must be Bool, got {:?} (GAP-168(c))",
953 $op_name, cond_guard.dtype,
954 ))
955 .bt());
956 }
957 let a_guard = read_storage(&inputs[1])?;
958 let b_guard = read_storage(&inputs[2])?;
959 let mut out_guard = write_storage(&outputs[0])?;
960 let cond_cpu = cpu_input(&cond_guard)?;
961 let a_cpu = cpu_input(&a_guard)?;
962 let b_cpu = cpu_input(&b_guard)?;
963 let out_cpu = cpu_output(&mut out_guard)?;
964 $kernel(cond_cpu, a_cpu, b_cpu, out_cpu)
965 }
966 };
967}
968
969cpu_where_wrapper!(
970 where_f32_cpu_wrapper,
971 fuel_cpu_backend::byte_kernels::where_f32,
972 "where"
973);
974cpu_where_wrapper!(
975 where_f64_cpu_wrapper,
976 fuel_cpu_backend::byte_kernels::where_f64,
977 "where"
978);
979cpu_where_wrapper!(
980 where_bf16_cpu_wrapper,
981 fuel_cpu_backend::byte_kernels::where_bf16,
982 "where"
983);
984cpu_where_wrapper!(
985 where_f16_cpu_wrapper,
986 fuel_cpu_backend::byte_kernels::where_f16,
987 "where"
988);
989
990cpu_unary_wrapper!(
993 floor_elementwise_f32_cpu_wrapper,
994 fuel_cpu_backend::byte_kernels::floor_f32,
995 "floor_elementwise"
996);
997cpu_unary_wrapper!(
998 floor_elementwise_f64_cpu_wrapper,
999 fuel_cpu_backend::byte_kernels::floor_f64,
1000 "floor_elementwise"
1001);
1002cpu_unary_wrapper!(
1003 floor_elementwise_bf16_cpu_wrapper,
1004 fuel_cpu_backend::byte_kernels::floor_bf16,
1005 "floor_elementwise"
1006);
1007cpu_unary_wrapper!(
1008 floor_elementwise_f16_cpu_wrapper,
1009 fuel_cpu_backend::byte_kernels::floor_f16,
1010 "floor_elementwise"
1011);
1012
1013cpu_unary_wrapper!(
1014 ceil_elementwise_f32_cpu_wrapper,
1015 fuel_cpu_backend::byte_kernels::ceil_f32,
1016 "ceil_elementwise"
1017);
1018cpu_unary_wrapper!(
1019 ceil_elementwise_f64_cpu_wrapper,
1020 fuel_cpu_backend::byte_kernels::ceil_f64,
1021 "ceil_elementwise"
1022);
1023cpu_unary_wrapper!(
1024 ceil_elementwise_bf16_cpu_wrapper,
1025 fuel_cpu_backend::byte_kernels::ceil_bf16,
1026 "ceil_elementwise"
1027);
1028cpu_unary_wrapper!(
1029 ceil_elementwise_f16_cpu_wrapper,
1030 fuel_cpu_backend::byte_kernels::ceil_f16,
1031 "ceil_elementwise"
1032);
1033
1034cpu_unary_wrapper!(
1035 round_elementwise_f32_cpu_wrapper,
1036 fuel_cpu_backend::byte_kernels::round_f32,
1037 "round_elementwise"
1038);
1039cpu_unary_wrapper!(
1040 round_elementwise_f64_cpu_wrapper,
1041 fuel_cpu_backend::byte_kernels::round_f64,
1042 "round_elementwise"
1043);
1044cpu_unary_wrapper!(
1045 round_elementwise_bf16_cpu_wrapper,
1046 fuel_cpu_backend::byte_kernels::round_bf16,
1047 "round_elementwise"
1048);
1049cpu_unary_wrapper!(
1050 round_elementwise_f16_cpu_wrapper,
1051 fuel_cpu_backend::byte_kernels::round_f16,
1052 "round_elementwise"
1053);
1054
1055cpu_unary_wrapper!(
1056 sign_elementwise_f32_cpu_wrapper,
1057 fuel_cpu_backend::byte_kernels::sign_f32,
1058 "sign_elementwise"
1059);
1060cpu_unary_wrapper!(
1061 sign_elementwise_f64_cpu_wrapper,
1062 fuel_cpu_backend::byte_kernels::sign_f64,
1063 "sign_elementwise"
1064);
1065cpu_unary_wrapper!(
1066 sign_elementwise_bf16_cpu_wrapper,
1067 fuel_cpu_backend::byte_kernels::sign_bf16,
1068 "sign_elementwise"
1069);
1070cpu_unary_wrapper!(
1071 sign_elementwise_f16_cpu_wrapper,
1072 fuel_cpu_backend::byte_kernels::sign_f16,
1073 "sign_elementwise"
1074);
1075
1076cpu_unary_wrapper!(
1077 erf_elementwise_f32_cpu_wrapper,
1078 fuel_cpu_backend::byte_kernels::erf_f32,
1079 "erf_elementwise"
1080);
1081cpu_unary_wrapper!(
1082 erf_elementwise_f64_cpu_wrapper,
1083 fuel_cpu_backend::byte_kernels::erf_f64,
1084 "erf_elementwise"
1085);
1086cpu_unary_wrapper!(
1087 erf_elementwise_bf16_cpu_wrapper,
1088 fuel_cpu_backend::byte_kernels::erf_bf16,
1089 "erf_elementwise"
1090);
1091cpu_unary_wrapper!(
1092 erf_elementwise_f16_cpu_wrapper,
1093 fuel_cpu_backend::byte_kernels::erf_f16,
1094 "erf_elementwise"
1095);
1096
1097cpu_unary_wrapper!(
1098 gelu_erf_elementwise_f32_cpu_wrapper,
1099 fuel_cpu_backend::byte_kernels::gelu_erf_f32,
1100 "gelu_erf_elementwise"
1101);
1102cpu_unary_wrapper!(
1103 gelu_erf_elementwise_f64_cpu_wrapper,
1104 fuel_cpu_backend::byte_kernels::gelu_erf_f64,
1105 "gelu_erf_elementwise"
1106);
1107cpu_unary_wrapper!(
1108 gelu_erf_elementwise_bf16_cpu_wrapper,
1109 fuel_cpu_backend::byte_kernels::gelu_erf_bf16,
1110 "gelu_erf_elementwise"
1111);
1112cpu_unary_wrapper!(
1113 gelu_erf_elementwise_f16_cpu_wrapper,
1114 fuel_cpu_backend::byte_kernels::gelu_erf_f16,
1115 "gelu_erf_elementwise"
1116);
1117
1118cpu_binary_wrapper!(
1119 pow_elementwise_f32_cpu_wrapper,
1120 fuel_cpu_backend::byte_kernels::pow_f32,
1121 "pow_elementwise"
1122);
1123cpu_binary_wrapper!(
1124 pow_elementwise_f64_cpu_wrapper,
1125 fuel_cpu_backend::byte_kernels::pow_f64,
1126 "pow_elementwise"
1127);
1128cpu_binary_wrapper!(
1129 pow_elementwise_bf16_cpu_wrapper,
1130 fuel_cpu_backend::byte_kernels::pow_bf16,
1131 "pow_elementwise"
1132);
1133cpu_binary_wrapper!(
1134 pow_elementwise_f16_cpu_wrapper,
1135 fuel_cpu_backend::byte_kernels::pow_f16,
1136 "pow_elementwise"
1137);
1138
1139cpu_unary_wrapper!(
1140 rsqrt_elementwise_f32_cpu_wrapper,
1141 fuel_cpu_backend::byte_kernels::rsqrt_f32,
1142 "rsqrt_elementwise"
1143);
1144cpu_unary_wrapper!(
1145 rsqrt_elementwise_f64_cpu_wrapper,
1146 fuel_cpu_backend::byte_kernels::rsqrt_f64,
1147 "rsqrt_elementwise"
1148);
1149cpu_unary_wrapper!(
1150 rsqrt_elementwise_bf16_cpu_wrapper,
1151 fuel_cpu_backend::byte_kernels::rsqrt_bf16,
1152 "rsqrt_elementwise"
1153);
1154cpu_unary_wrapper!(
1155 rsqrt_elementwise_f16_cpu_wrapper,
1156 fuel_cpu_backend::byte_kernels::rsqrt_f16,
1157 "rsqrt_elementwise"
1158);
1159
1160cpu_binary_wrapper!(
1161 rem_elementwise_f32_cpu_wrapper,
1162 fuel_cpu_backend::byte_kernels::rem_f32,
1163 "rem_elementwise"
1164);
1165cpu_binary_wrapper!(
1166 rem_elementwise_f64_cpu_wrapper,
1167 fuel_cpu_backend::byte_kernels::rem_f64,
1168 "rem_elementwise"
1169);
1170cpu_binary_wrapper!(
1171 rem_elementwise_bf16_cpu_wrapper,
1172 fuel_cpu_backend::byte_kernels::rem_bf16,
1173 "rem_elementwise"
1174);
1175cpu_binary_wrapper!(
1176 rem_elementwise_f16_cpu_wrapper,
1177 fuel_cpu_backend::byte_kernels::rem_f16,
1178 "rem_elementwise"
1179);
1180
1181pub(crate) fn flip_cpu_wrapper(
1186 inputs: &[Arc<RwLock<Storage>>],
1187 outputs: &mut [Arc<RwLock<Storage>>],
1188 _layouts: &[Layout],
1189 params: &OpParams,
1190) -> Result<()> {
1191 if inputs.len() != 1 || outputs.len() != 1 {
1192 return Err(Error::Msg(format!(
1193 "flip wrapper expects 1 input + 1 output, got {} + {}",
1194 inputs.len(),
1195 outputs.len(),
1196 ))
1197 .bt());
1198 }
1199 let (outer, dim_size, inner) = match params {
1200 OpParams::Flip {
1201 outer_count,
1202 dim_size,
1203 inner_count,
1204 ..
1205 } => (*outer_count, *dim_size, *inner_count),
1206 other => {
1207 return Err(Error::Msg(format!(
1208 "flip wrapper expects OpParams::Flip, got {other:?}",
1209 ))
1210 .bt());
1211 }
1212 };
1213 let in_guard = read_storage(&inputs[0])?;
1214 let mut out_guard = write_storage(&outputs[0])?;
1215 let dtype_size = out_guard.dtype.size_in_bytes();
1216 let in_cpu = cpu_input(&in_guard)?;
1217 let out_cpu = cpu_output(&mut out_guard)?;
1218 fuel_cpu_backend::byte_kernels::flip_cpu(in_cpu, out_cpu, outer, dim_size, inner, dtype_size)
1219}
1220
1221macro_rules! cpu_cumsum_wrapper {
1225 ($wrapper:ident, $kernel:path, $op_name:literal) => {
1226 pub(crate) fn $wrapper(
1227 inputs: &[Arc<RwLock<Storage>>],
1228 outputs: &mut [Arc<RwLock<Storage>>],
1229 _layouts: &[Layout],
1230 params: &OpParams,
1231 ) -> Result<()> {
1232 if inputs.len() != 1 || outputs.len() != 1 {
1233 return Err(Error::Msg(format!(
1234 "{} wrapper expects 1 input + 1 output, got {} + {}",
1235 $op_name,
1236 inputs.len(),
1237 outputs.len(),
1238 ))
1239 .bt());
1240 }
1241 let (outer, dim_size, inner) = match params {
1242 OpParams::CumSum {
1243 outer_count,
1244 dim_size,
1245 inner_count,
1246 ..
1247 } => (*outer_count, *dim_size, *inner_count),
1248 other => {
1249 return Err(Error::Msg(format!(
1250 "{} wrapper expects OpParams::CumSum, got {other:?}",
1251 $op_name,
1252 ))
1253 .bt())
1254 }
1255 };
1256 let in_guard = read_storage(&inputs[0])?;
1257 let mut out_guard = write_storage(&outputs[0])?;
1258 let in_cpu = cpu_input(&in_guard)?;
1259 let out_cpu = cpu_output(&mut out_guard)?;
1260 $kernel(in_cpu, out_cpu, outer, dim_size, inner)
1261 }
1262 };
1263}
1264
1265cpu_cumsum_wrapper!(
1266 cumsum_f32_cpu_wrapper,
1267 fuel_cpu_backend::byte_kernels::cumsum_f32,
1268 "cumsum_f32"
1269);
1270cpu_cumsum_wrapper!(
1271 cumsum_f64_cpu_wrapper,
1272 fuel_cpu_backend::byte_kernels::cumsum_f64,
1273 "cumsum_f64"
1274);
1275cpu_cumsum_wrapper!(
1276 cumsum_bf16_cpu_wrapper,
1277 fuel_cpu_backend::byte_kernels::cumsum_bf16,
1278 "cumsum_bf16"
1279);
1280cpu_cumsum_wrapper!(
1281 cumsum_f16_cpu_wrapper,
1282 fuel_cpu_backend::byte_kernels::cumsum_f16,
1283 "cumsum_f16"
1284);
1285
1286fn triu_cpu_wrapper(
1289 inputs: &[Arc<RwLock<Storage>>],
1290 outputs: &mut [Arc<RwLock<Storage>>],
1291 _layouts: &[Layout],
1292 params: &OpParams,
1293) -> Result<()> {
1294 triangular_wrapper_inner(
1295 inputs,
1296 outputs,
1297 params,
1298 true,
1299 "triu_cpu_wrapper",
1300 )
1301}
1302
1303fn tril_cpu_wrapper(
1304 inputs: &[Arc<RwLock<Storage>>],
1305 outputs: &mut [Arc<RwLock<Storage>>],
1306 _layouts: &[Layout],
1307 params: &OpParams,
1308) -> Result<()> {
1309 triangular_wrapper_inner(
1310 inputs,
1311 outputs,
1312 params,
1313 false,
1314 "tril_cpu_wrapper",
1315 )
1316}
1317
1318fn triangular_wrapper_inner(
1319 inputs: &[Arc<RwLock<Storage>>],
1320 outputs: &mut [Arc<RwLock<Storage>>],
1321 params: &OpParams,
1322 keep_upper: bool,
1323 op_name: &str,
1324) -> Result<()> {
1325 if inputs.len() != 1 || outputs.len() != 1 {
1326 return Err(Error::Msg(format!(
1327 "{op_name}: expects 1 input + 1 output, got {} + {}",
1328 inputs.len(),
1329 outputs.len(),
1330 ))
1331 .bt());
1332 }
1333 let (batch, rows, cols, diag) = match params {
1334 OpParams::Triangular {
1335 batch_count,
1336 rows,
1337 cols,
1338 diagonal,
1339 } => (*batch_count, *rows, *cols, *diagonal),
1340 other => {
1341 return Err(Error::Msg(format!(
1342 "{op_name}: expects OpParams::Triangular, got {other:?}",
1343 ))
1344 .bt());
1345 }
1346 };
1347 let in_guard = read_storage(&inputs[0])?;
1348 let mut out_guard = write_storage(&outputs[0])?;
1349 let dtype_size = out_guard.dtype.size_in_bytes();
1350 let in_cpu = cpu_input(&in_guard)?;
1351 let out_cpu = cpu_output(&mut out_guard)?;
1352 fuel_cpu_backend::byte_kernels::triangular_cpu(
1353 in_cpu, out_cpu, batch, rows, cols, diag, keep_upper, dtype_size,
1354 )
1355}
1356
1357macro_rules! cpu_log_softmax_wrapper {
1360 ($wrapper:ident, $kernel:path, $op_name:literal) => {
1361 pub(crate) fn $wrapper(
1362 inputs: &[Arc<RwLock<Storage>>],
1363 outputs: &mut [Arc<RwLock<Storage>>],
1364 _layouts: &[Layout],
1365 params: &OpParams,
1366 ) -> Result<()> {
1367 if inputs.len() != 1 || outputs.len() != 1 {
1368 return Err(Error::Msg(format!(
1369 "{} wrapper expects 1 input + 1 output, got {} + {}",
1370 $op_name,
1371 inputs.len(),
1372 outputs.len(),
1373 ))
1374 .bt());
1375 }
1376 let (outer, last_dim) = match params {
1377 OpParams::LogSoftmaxLastDim {
1378 outer_count,
1379 last_dim,
1380 } => (*outer_count, *last_dim),
1381 other => {
1382 return Err(Error::Msg(format!(
1383 "{} wrapper expects OpParams::LogSoftmaxLastDim, got {other:?}",
1384 $op_name,
1385 ))
1386 .bt());
1387 }
1388 };
1389 let in_guard = read_storage(&inputs[0])?;
1390 let mut out_guard = write_storage(&outputs[0])?;
1391 let in_cpu = cpu_input(&in_guard)?;
1392 let out_cpu = cpu_output(&mut out_guard)?;
1393 $kernel(in_cpu, out_cpu, outer, last_dim)
1394 }
1395 };
1396}
1397
1398cpu_log_softmax_wrapper!(
1399 log_softmax_f32_cpu_wrapper,
1400 fuel_cpu_backend::byte_kernels::log_softmax_last_dim_f32,
1401 "log_softmax_f32"
1402);
1403cpu_log_softmax_wrapper!(
1404 log_softmax_f64_cpu_wrapper,
1405 fuel_cpu_backend::byte_kernels::log_softmax_last_dim_f64,
1406 "log_softmax_f64"
1407);
1408cpu_log_softmax_wrapper!(
1409 log_softmax_bf16_cpu_wrapper,
1410 fuel_cpu_backend::byte_kernels::log_softmax_last_dim_bf16,
1411 "log_softmax_bf16"
1412);
1413cpu_log_softmax_wrapper!(
1414 log_softmax_f16_cpu_wrapper,
1415 fuel_cpu_backend::byte_kernels::log_softmax_last_dim_f16,
1416 "log_softmax_f16"
1417);
1418
1419macro_rules! cpu_log_softmax_backward_wrapper {
1422 ($wrapper:ident, $kernel:path, $op_name:literal) => {
1423 pub(crate) fn $wrapper(
1426 inputs: &[Arc<RwLock<Storage>>],
1427 outputs: &mut [Arc<RwLock<Storage>>],
1428 _layouts: &[Layout],
1429 params: &OpParams,
1430 ) -> Result<()> {
1431 if inputs.len() != 2 || outputs.len() != 1 {
1432 return Err(Error::Msg(format!(
1433 "{} wrapper expects 2 inputs (y, g) + 1 output, got {} + {}",
1434 $op_name,
1435 inputs.len(),
1436 outputs.len(),
1437 ))
1438 .bt());
1439 }
1440 let (outer, last_dim) = match params {
1441 OpParams::LogSoftmaxLastDim {
1442 outer_count,
1443 last_dim,
1444 } => (*outer_count, *last_dim),
1445 other => {
1446 return Err(Error::Msg(format!(
1447 "{} wrapper expects OpParams::LogSoftmaxLastDim, got {other:?}",
1448 $op_name,
1449 ))
1450 .bt());
1451 }
1452 };
1453 let y_guard = read_storage(&inputs[0])?;
1454 let g_guard = read_storage(&inputs[1])?;
1455 let mut out_guard = write_storage(&outputs[0])?;
1456 let y_cpu = cpu_input(&y_guard)?;
1457 let g_cpu = cpu_input(&g_guard)?;
1458 let out_cpu = cpu_output(&mut out_guard)?;
1459 $kernel(y_cpu, g_cpu, out_cpu, outer, last_dim)
1460 }
1461 };
1462}
1463
1464cpu_log_softmax_backward_wrapper!(
1465 log_softmax_backward_f32_cpu_wrapper,
1466 fuel_cpu_backend::byte_kernels::log_softmax_last_dim_backward_f32,
1467 "log_softmax_backward_f32"
1468);
1469cpu_log_softmax_backward_wrapper!(
1470 log_softmax_backward_f64_cpu_wrapper,
1471 fuel_cpu_backend::byte_kernels::log_softmax_last_dim_backward_f64,
1472 "log_softmax_backward_f64"
1473);
1474cpu_log_softmax_backward_wrapper!(
1475 log_softmax_backward_bf16_cpu_wrapper,
1476 fuel_cpu_backend::byte_kernels::log_softmax_last_dim_backward_bf16,
1477 "log_softmax_backward_bf16"
1478);
1479cpu_log_softmax_backward_wrapper!(
1480 log_softmax_backward_f16_cpu_wrapper,
1481 fuel_cpu_backend::byte_kernels::log_softmax_last_dim_backward_f16,
1482 "log_softmax_backward_f16"
1483);
1484
1485macro_rules! cpu_softmax_last_dim_backward_wrapper {
1489 ($wrapper:ident, $kernel:path) => {
1490 pub(crate) fn $wrapper(
1493 inputs: &[Arc<RwLock<Storage>>],
1494 outputs: &mut [Arc<RwLock<Storage>>],
1495 _layouts: &[Layout],
1496 params: &OpParams,
1497 ) -> Result<()> {
1498 if inputs.len() != 2 || outputs.len() != 1 {
1499 return Err(Error::Msg(format!(
1500 "softmax_last_dim_backward wrapper expects 2 inputs (y, g) + 1 output, got {} + {}",
1501 inputs.len(), outputs.len(),
1502 )).bt());
1503 }
1504 let (outer, last_dim) = match params {
1505 OpParams::SoftmaxLastDim { outer_count, last_dim } => (*outer_count, *last_dim),
1506 other => {
1507 return Err(Error::Msg(format!(
1508 "softmax_last_dim_backward wrapper expects OpParams::SoftmaxLastDim, got {other:?}",
1509 )).bt());
1510 }
1511 };
1512 let y_guard = read_storage(&inputs[0])?;
1513 let g_guard = read_storage(&inputs[1])?;
1514 let mut out_guard = write_storage(&outputs[0])?;
1515 let y_cpu = cpu_input(&y_guard)?;
1516 let g_cpu = cpu_input(&g_guard)?;
1517 let out_cpu = cpu_output(&mut out_guard)?;
1518 $kernel(y_cpu, g_cpu, out_cpu, outer, last_dim)
1519 }
1520 };
1521}
1522
1523cpu_softmax_last_dim_backward_wrapper!(
1524 softmax_last_dim_backward_f32_cpu_wrapper,
1525 fuel_cpu_backend::byte_kernels::softmax_last_dim_backward_f32
1526);
1527cpu_softmax_last_dim_backward_wrapper!(
1528 softmax_last_dim_backward_f64_cpu_wrapper,
1529 fuel_cpu_backend::byte_kernels::softmax_last_dim_backward_f64
1530);
1531cpu_softmax_last_dim_backward_wrapper!(
1532 softmax_last_dim_backward_bf16_cpu_wrapper,
1533 fuel_cpu_backend::byte_kernels::softmax_last_dim_backward_bf16
1534);
1535cpu_softmax_last_dim_backward_wrapper!(
1536 softmax_last_dim_backward_f16_cpu_wrapper,
1537 fuel_cpu_backend::byte_kernels::softmax_last_dim_backward_f16
1538);
1539
1540macro_rules! cpu_norm_last_dim_backward_wrapper {
1543 ($wrapper:ident, $kernel:path, $op_name:literal) => {
1544 pub(crate) fn $wrapper(
1547 inputs: &[Arc<RwLock<Storage>>],
1548 outputs: &mut [Arc<RwLock<Storage>>],
1549 _layouts: &[Layout],
1550 params: &OpParams,
1551 ) -> Result<()> {
1552 if inputs.len() != 2 || outputs.len() != 1 {
1553 return Err(Error::Msg(format!(
1554 "{} wrapper expects 2 inputs (x, g) + 1 output, got {} + {}",
1555 $op_name,
1556 inputs.len(),
1557 outputs.len(),
1558 ))
1559 .bt());
1560 }
1561 let (outer, last_dim, eps) = match params {
1562 OpParams::NormLastDim {
1563 outer_count,
1564 last_dim,
1565 eps,
1566 } => (*outer_count, *last_dim, *eps),
1567 other => {
1568 return Err(Error::Msg(format!(
1569 "{} wrapper expects OpParams::NormLastDim, got {other:?}",
1570 $op_name,
1571 ))
1572 .bt());
1573 }
1574 };
1575 let x_guard = read_storage(&inputs[0])?;
1576 let g_guard = read_storage(&inputs[1])?;
1577 let mut out_guard = write_storage(&outputs[0])?;
1578 let x_cpu = cpu_input(&x_guard)?;
1579 let g_cpu = cpu_input(&g_guard)?;
1580 let out_cpu = cpu_output(&mut out_guard)?;
1581 $kernel(x_cpu, g_cpu, out_cpu, outer, last_dim, eps)
1582 }
1583 };
1584}
1585
1586cpu_norm_last_dim_backward_wrapper!(
1587 layer_norm_last_dim_backward_f32_cpu_wrapper,
1588 fuel_cpu_backend::byte_kernels::layer_norm_last_dim_backward_f32,
1589 "layer_norm_backward_f32"
1590);
1591cpu_norm_last_dim_backward_wrapper!(
1592 layer_norm_last_dim_backward_f64_cpu_wrapper,
1593 fuel_cpu_backend::byte_kernels::layer_norm_last_dim_backward_f64,
1594 "layer_norm_backward_f64"
1595);
1596cpu_norm_last_dim_backward_wrapper!(
1597 layer_norm_last_dim_backward_bf16_cpu_wrapper,
1598 fuel_cpu_backend::byte_kernels::layer_norm_last_dim_backward_bf16,
1599 "layer_norm_backward_bf16"
1600);
1601cpu_norm_last_dim_backward_wrapper!(
1602 layer_norm_last_dim_backward_f16_cpu_wrapper,
1603 fuel_cpu_backend::byte_kernels::layer_norm_last_dim_backward_f16,
1604 "layer_norm_backward_f16"
1605);
1606
1607cpu_norm_last_dim_backward_wrapper!(
1608 rms_norm_last_dim_backward_f32_cpu_wrapper,
1609 fuel_cpu_backend::byte_kernels::rms_norm_last_dim_backward_f32,
1610 "rms_norm_backward_f32"
1611);
1612cpu_norm_last_dim_backward_wrapper!(
1613 rms_norm_last_dim_backward_f64_cpu_wrapper,
1614 fuel_cpu_backend::byte_kernels::rms_norm_last_dim_backward_f64,
1615 "rms_norm_backward_f64"
1616);
1617cpu_norm_last_dim_backward_wrapper!(
1618 rms_norm_last_dim_backward_bf16_cpu_wrapper,
1619 fuel_cpu_backend::byte_kernels::rms_norm_last_dim_backward_bf16,
1620 "rms_norm_backward_bf16"
1621);
1622cpu_norm_last_dim_backward_wrapper!(
1623 rms_norm_last_dim_backward_f16_cpu_wrapper,
1624 fuel_cpu_backend::byte_kernels::rms_norm_last_dim_backward_f16,
1625 "rms_norm_backward_f16"
1626);
1627
1628macro_rules! cpu_reduce_max_to_backward_wrapper {
1633 ($wrapper:ident, $kernel:path) => {
1634 pub(crate) fn $wrapper(
1635 inputs: &[Arc<RwLock<Storage>>],
1636 outputs: &mut [Arc<RwLock<Storage>>],
1637 _layouts: &[Layout],
1638 params: &OpParams,
1639 ) -> Result<()> {
1640 if inputs.len() != 2 || outputs.len() != 1 {
1641 return Err(Error::Msg(format!(
1642 "reduce_max_to_backward wrapper expects 2 inputs (x, upstream) + 1 output, got {} + {}",
1643 inputs.len(), outputs.len(),
1644 )).bt());
1645 }
1646 let (input_shape, output_shape) = match params {
1647 OpParams::ReduceMaxToBackward { input_shape, output_shape } => {
1648 (input_shape.as_slice(), output_shape.as_slice())
1649 }
1650 other => {
1651 return Err(Error::Msg(format!(
1652 "reduce_max_to_backward wrapper expects OpParams::ReduceMaxToBackward, got {other:?}",
1653 )).bt());
1654 }
1655 };
1656 let x_guard = read_storage(&inputs[0])?;
1657 let up_guard = read_storage(&inputs[1])?;
1658 let mut out_guard = write_storage(&outputs[0])?;
1659 let x_cpu = cpu_input(&x_guard)?;
1660 let up_cpu = cpu_input(&up_guard)?;
1661 let out_cpu = cpu_output(&mut out_guard)?;
1662 $kernel(x_cpu, up_cpu, out_cpu, input_shape, output_shape)
1663 }
1664 };
1665}
1666
1667cpu_reduce_max_to_backward_wrapper!(
1668 reduce_max_to_backward_f32_cpu_wrapper,
1669 fuel_cpu_backend::byte_kernels::reduce_max_to_backward_f32
1670);
1671cpu_reduce_max_to_backward_wrapper!(
1672 reduce_max_to_backward_f64_cpu_wrapper,
1673 fuel_cpu_backend::byte_kernels::reduce_max_to_backward_f64
1674);
1675cpu_reduce_max_to_backward_wrapper!(
1676 reduce_max_to_backward_bf16_cpu_wrapper,
1677 fuel_cpu_backend::byte_kernels::reduce_max_to_backward_bf16
1678);
1679cpu_reduce_max_to_backward_wrapper!(
1680 reduce_max_to_backward_f16_cpu_wrapper,
1681 fuel_cpu_backend::byte_kernels::reduce_max_to_backward_f16
1682);
1683
1684pub(crate) fn masked_fill_cpu_wrapper(
1687 inputs: &[Arc<RwLock<Storage>>],
1688 outputs: &mut [Arc<RwLock<Storage>>],
1689 _layouts: &[Layout],
1690 params: &OpParams,
1691) -> Result<()> {
1692 if inputs.len() != 2 || outputs.len() != 1 {
1693 return Err(Error::Msg(format!(
1694 "masked_fill_cpu_wrapper: expects 2 inputs (x, mask) + 1 output, got {} + {}",
1695 inputs.len(),
1696 outputs.len(),
1697 ))
1698 .bt());
1699 }
1700 let fill_bytes = match params {
1701 OpParams::MaskedFill { fill_bytes } => fill_bytes.clone(),
1702 other => {
1703 return Err(Error::Msg(format!(
1704 "masked_fill_cpu_wrapper: expects OpParams::MaskedFill, got {other:?}",
1705 ))
1706 .bt());
1707 }
1708 };
1709 let in_guard = read_storage(&inputs[0])?;
1710 let mask_guard = read_storage(&inputs[1])?;
1711 if mask_guard.dtype != DType::Bool {
1718 return Err(Error::Msg(format!(
1719 "masked_fill_cpu_wrapper: mask must be Bool, got {:?} (GAP-168(c))",
1720 mask_guard.dtype,
1721 ))
1722 .bt());
1723 }
1724 let mut out_guard = write_storage(&outputs[0])?;
1725 let dtype_size = out_guard.dtype.size_in_bytes();
1726 let in_cpu = cpu_input(&in_guard)?;
1727 let mask_cpu = cpu_input(&mask_guard)?;
1728 let out_cpu = cpu_output(&mut out_guard)?;
1729 fuel_cpu_backend::byte_kernels::masked_fill_cpu(
1730 in_cpu,
1731 mask_cpu,
1732 out_cpu,
1733 &fill_bytes,
1734 dtype_size,
1735 )
1736}
1737
1738pub(crate) fn pad_cpu_wrapper(
1744 inputs: &[Arc<RwLock<Storage>>],
1745 outputs: &mut [Arc<RwLock<Storage>>],
1746 _layouts: &[Layout],
1747 params: &OpParams,
1748) -> Result<()> {
1749 if inputs.len() != 1 || outputs.len() != 1 {
1750 return Err(Error::Msg(format!(
1751 "pad wrapper expects 1 input + 1 output, got {} + {}",
1752 inputs.len(),
1753 outputs.len(),
1754 ))
1755 .bt());
1756 }
1757 let (in_shape, out_shape, padding, mode_tag, fill_bytes) = match params {
1758 OpParams::Pad {
1759 in_shape,
1760 out_shape,
1761 padding,
1762 mode_tag,
1763 fill_bytes,
1764 } => (in_shape, out_shape, padding, *mode_tag, fill_bytes),
1765 other => {
1766 return Err(
1767 Error::Msg(format!("pad wrapper expects OpParams::Pad, got {other:?}",)).bt(),
1768 );
1769 }
1770 };
1771 let in_guard = read_storage(&inputs[0])?;
1772 let mut out_guard = write_storage(&outputs[0])?;
1773 let dtype_size = out_guard.dtype.size_in_bytes();
1774 let in_cpu = cpu_input(&in_guard)?;
1775 let out_cpu = cpu_output(&mut out_guard)?;
1776 match mode_tag {
1778 0 => fuel_cpu_backend::byte_kernels::pad_const_cpu(
1779 in_cpu, out_cpu, in_shape, out_shape, padding, dtype_size, fill_bytes,
1780 ),
1781 1 => {
1782 for (k, (&n, &(b, a))) in in_shape.iter().zip(padding.iter()).enumerate() {
1785 if n > 0 && (b > n - 1 || a > n - 1) {
1786 return Err(Error::Msg(format!(
1787 "pad reflect: axis {k} has dim_size {n}; before ({b}) and \
1788 after ({a}) must each be <= dim_size - 1",
1789 ))
1790 .bt());
1791 }
1792 }
1793 fuel_cpu_backend::byte_kernels::pad_reflect_cpu(
1794 in_cpu, out_cpu, in_shape, out_shape, padding, dtype_size,
1795 )
1796 }
1797 2 => fuel_cpu_backend::byte_kernels::pad_replicate_cpu(
1798 in_cpu, out_cpu, in_shape, out_shape, padding, dtype_size,
1799 ),
1800 other => Err(Error::Msg(format!("pad: unknown mode_tag {other}",)).bt()),
1801 }
1802}
1803
1804macro_rules! cpu_pad_backward_wrapper {
1808 ($wrapper:ident, $kernel:path, $op_name:literal) => {
1809 pub(crate) fn $wrapper(
1810 inputs: &[Arc<RwLock<Storage>>],
1811 outputs: &mut [Arc<RwLock<Storage>>],
1812 _layouts: &[Layout],
1813 params: &OpParams,
1814 ) -> Result<()> {
1815 if inputs.len() != 1 || outputs.len() != 1 {
1816 return Err(Error::Msg(format!(
1817 "{} wrapper expects 1 input + 1 output, got {} + {}",
1818 $op_name,
1819 inputs.len(),
1820 outputs.len(),
1821 ))
1822 .bt());
1823 }
1824 let (in_shape, out_shape, padding, mode_tag) = match params {
1825 OpParams::PadBackward {
1826 in_shape,
1827 out_shape,
1828 padding,
1829 mode_tag,
1830 } => (in_shape, out_shape, padding, *mode_tag),
1831 other => {
1832 return Err(Error::Msg(format!(
1833 "{} wrapper expects OpParams::PadBackward, got {other:?}",
1834 $op_name,
1835 ))
1836 .bt())
1837 }
1838 };
1839 let in_guard = read_storage(&inputs[0])?;
1840 let mut out_guard = write_storage(&outputs[0])?;
1841 let in_cpu = cpu_input(&in_guard)?;
1842 let out_cpu = cpu_output(&mut out_guard)?;
1843 $kernel(in_cpu, out_cpu, in_shape, out_shape, padding, mode_tag)
1844 }
1845 };
1846}
1847
1848cpu_pad_backward_wrapper!(
1849 pad_backward_f32_cpu_wrapper,
1850 fuel_cpu_backend::byte_kernels::pad_backward_f32,
1851 "pad_backward_f32"
1852);
1853cpu_pad_backward_wrapper!(
1854 pad_backward_f64_cpu_wrapper,
1855 fuel_cpu_backend::byte_kernels::pad_backward_f64,
1856 "pad_backward_f64"
1857);
1858cpu_pad_backward_wrapper!(
1859 pad_backward_bf16_cpu_wrapper,
1860 fuel_cpu_backend::byte_kernels::pad_backward_bf16,
1861 "pad_backward_bf16"
1862);
1863cpu_pad_backward_wrapper!(
1864 pad_backward_f16_cpu_wrapper,
1865 fuel_cpu_backend::byte_kernels::pad_backward_f16,
1866 "pad_backward_f16"
1867);
1868
1869pub(crate) fn roll_cpu_wrapper(
1872 inputs: &[Arc<RwLock<Storage>>],
1873 outputs: &mut [Arc<RwLock<Storage>>],
1874 _layouts: &[Layout],
1875 params: &OpParams,
1876) -> Result<()> {
1877 if inputs.len() != 1 || outputs.len() != 1 {
1878 return Err(Error::Msg(format!(
1879 "roll wrapper expects 1 input + 1 output, got {} + {}",
1880 inputs.len(),
1881 outputs.len(),
1882 ))
1883 .bt());
1884 }
1885 let (outer, dim_size, inner, shift) = match params {
1886 OpParams::Roll {
1887 outer_count,
1888 dim_size,
1889 inner_count,
1890 shift,
1891 ..
1892 } => (*outer_count, *dim_size, *inner_count, *shift),
1893 other => {
1894 return Err(Error::Msg(format!(
1895 "roll wrapper expects OpParams::Roll, got {other:?}",
1896 ))
1897 .bt());
1898 }
1899 };
1900 let in_guard = read_storage(&inputs[0])?;
1901 let mut out_guard = write_storage(&outputs[0])?;
1902 let dtype_size = out_guard.dtype.size_in_bytes();
1903 let in_cpu = cpu_input(&in_guard)?;
1904 let out_cpu = cpu_output(&mut out_guard)?;
1905 fuel_cpu_backend::byte_kernels::roll_cpu(
1906 in_cpu, out_cpu, outer, dim_size, inner, shift, dtype_size,
1907 )
1908}
1909
1910macro_rules! cpu_arg_dim_wrapper {
1914 ($wrapper:ident, $kernel:path, $op_name:literal) => {
1915 fn $wrapper(
1916 inputs: &[Arc<RwLock<Storage>>],
1917 outputs: &mut [Arc<RwLock<Storage>>],
1918 layouts: &[Layout],
1919 params: &OpParams,
1920 ) -> Result<()> {
1921 if inputs.len() != 1 || outputs.len() != 1 {
1922 return Err(Error::Msg(format!(
1923 "{} wrapper expects 1 input + 1 output, got {} + {}",
1924 $op_name,
1925 inputs.len(),
1926 outputs.len(),
1927 ))
1928 .bt());
1929 }
1930 let dims = match params {
1931 OpParams::Reduce { dims, .. } => dims,
1932 other => {
1933 return Err(Error::Msg(format!(
1934 "{} wrapper expects OpParams::Reduce, got {other:?}",
1935 $op_name,
1936 ))
1937 .bt())
1938 }
1939 };
1940 if dims.len() != 1 {
1941 return Err(Error::Msg(format!(
1942 "{} wrapper expects exactly 1 reduce dim, got {dims:?}",
1943 $op_name,
1944 ))
1945 .bt());
1946 }
1947 let dim = dims[0];
1948 let input_layout = layouts.first().ok_or_else(|| {
1949 Error::Msg(format!(
1950 "{} wrapper: layouts empty (executor must pass input layout at [0])",
1951 $op_name,
1952 ))
1953 .bt()
1954 })?;
1955 let in_guard = read_storage(&inputs[0])?;
1956 if in_guard.dtype != DType::F32 {
1957 return Err(Error::Msg(format!(
1958 "{}: only F32 input is wired today, got {:?}",
1959 $op_name, in_guard.dtype,
1960 ))
1961 .bt());
1962 }
1963 let mut out_guard = write_storage(&outputs[0])?;
1964 let in_cpu = cpu_input(&in_guard)?;
1965 let out_cpu = cpu_output(&mut out_guard)?;
1966 $kernel(in_cpu, out_cpu, input_layout.shape().dims(), dim)
1967 }
1968 };
1969}
1970
1971cpu_arg_dim_wrapper!(
1972 argmax_dim_u32_cpu_wrapper,
1973 fuel_cpu_backend::byte_kernels::argmax_dim_f32,
1974 "argmax_dim"
1975);
1976cpu_arg_dim_wrapper!(
1977 argmin_dim_u32_cpu_wrapper,
1978 fuel_cpu_backend::byte_kernels::argmin_dim_f32,
1979 "argmin_dim"
1980);
1981
1982pub(crate) fn index_add_f32_cpu_wrapper(
1987 inputs: &[Arc<RwLock<Storage>>],
1988 outputs: &mut [Arc<RwLock<Storage>>],
1989 _layouts: &[Layout],
1990 params: &OpParams,
1991) -> Result<()> {
1992 if inputs.len() != 3 || outputs.len() != 1 {
1993 return Err(Error::Msg(format!(
1994 "index_add wrapper expects 3 inputs (base, indices, src) + 1 output, got {} + {}",
1995 inputs.len(),
1996 outputs.len(),
1997 ))
1998 .bt());
1999 }
2000 let (outer_count, base_dim_size, n_indices, inner_count) = match params {
2001 OpParams::IndexAdd {
2002 outer_count,
2003 base_dim_size,
2004 n_indices,
2005 inner_count,
2006 } => (*outer_count, *base_dim_size, *n_indices, *inner_count),
2007 other => {
2008 return Err(Error::Msg(format!(
2009 "index_add wrapper expects OpParams::IndexAdd, got {other:?}",
2010 ))
2011 .bt());
2012 }
2013 };
2014 let base_guard = read_storage(&inputs[0])?;
2015 let idx_guard = read_storage(&inputs[1])?;
2016 if idx_guard.dtype != DType::U32 {
2017 return Err(Error::Msg(format!(
2018 "index_add: indices must be U32, got {:?}",
2019 idx_guard.dtype,
2020 ))
2021 .bt());
2022 }
2023 let src_guard = read_storage(&inputs[2])?;
2024 let mut out_guard = write_storage(&outputs[0])?;
2025 let base_cpu = cpu_input(&base_guard)?;
2026 let idx_cpu = cpu_input(&idx_guard)?;
2027 let src_cpu = cpu_input(&src_guard)?;
2028 let out_cpu = cpu_output(&mut out_guard)?;
2029 fuel_cpu_backend::byte_kernels::index_add_f32(
2030 base_cpu,
2031 idx_cpu,
2032 src_cpu,
2033 out_cpu,
2034 outer_count,
2035 base_dim_size,
2036 n_indices,
2037 inner_count,
2038 )
2039}
2040
2041pub(crate) fn scatter_add_f32_cpu_wrapper(
2046 inputs: &[Arc<RwLock<Storage>>],
2047 outputs: &mut [Arc<RwLock<Storage>>],
2048 _layouts: &[Layout],
2049 params: &OpParams,
2050) -> Result<()> {
2051 if inputs.len() != 3 || outputs.len() != 1 {
2052 return Err(Error::Msg(format!(
2053 "scatter_add wrapper expects 3 inputs (base, indices, src) + 1 output, got {} + {}",
2054 inputs.len(),
2055 outputs.len(),
2056 ))
2057 .bt());
2058 }
2059 let (base_shape, src_shape, dim) = match params {
2060 OpParams::ScatterAdd {
2061 base_shape,
2062 src_shape,
2063 dim,
2064 } => (base_shape, src_shape, *dim),
2065 other => {
2066 return Err(Error::Msg(format!(
2067 "scatter_add wrapper expects OpParams::ScatterAdd, got {other:?}",
2068 ))
2069 .bt());
2070 }
2071 };
2072 let base_guard = read_storage(&inputs[0])?;
2073 let idx_guard = read_storage(&inputs[1])?;
2074 if idx_guard.dtype != DType::U32 {
2075 return Err(Error::Msg(format!(
2076 "scatter_add: indices must be U32, got {:?}",
2077 idx_guard.dtype,
2078 ))
2079 .bt());
2080 }
2081 let src_guard = read_storage(&inputs[2])?;
2082 let mut out_guard = write_storage(&outputs[0])?;
2083 let base_cpu = cpu_input(&base_guard)?;
2084 let idx_cpu = cpu_input(&idx_guard)?;
2085 let src_cpu = cpu_input(&src_guard)?;
2086 let out_cpu = cpu_output(&mut out_guard)?;
2087 fuel_cpu_backend::byte_kernels::scatter_add_f32(
2088 base_cpu, idx_cpu, src_cpu, out_cpu, base_shape, src_shape, dim,
2089 )
2090}
2091
2092pub(crate) fn rope_f32_cpu_wrapper(
2097 inputs: &[Arc<RwLock<Storage>>],
2098 outputs: &mut [Arc<RwLock<Storage>>],
2099 _layouts: &[Layout],
2100 params: &OpParams,
2101) -> Result<()> {
2102 if inputs.len() != 3 || outputs.len() != 1 {
2103 return Err(Error::Msg(format!(
2104 "rope wrapper expects 3 inputs (x, cos, sin) + 1 output, got {} + {}",
2105 inputs.len(),
2106 outputs.len(),
2107 ))
2108 .bt());
2109 }
2110 let (outer_count, seq, head_dim) = match params {
2111 OpParams::Rope {
2112 outer_count,
2113 seq,
2114 head_dim,
2115 } => (*outer_count, *seq, *head_dim),
2116 other => {
2117 return Err(Error::Msg(format!(
2118 "rope wrapper expects OpParams::Rope, got {other:?}",
2119 ))
2120 .bt());
2121 }
2122 };
2123 let x_guard = read_storage(&inputs[0])?;
2124 let cos_guard = read_storage(&inputs[1])?;
2125 let sin_guard = read_storage(&inputs[2])?;
2126 let mut out_guard = write_storage(&outputs[0])?;
2127 let x_cpu = cpu_input(&x_guard)?;
2128 let cos_cpu = cpu_input(&cos_guard)?;
2129 let sin_cpu = cpu_input(&sin_guard)?;
2130 let out_cpu = cpu_output(&mut out_guard)?;
2131 fuel_cpu_backend::byte_kernels::rope_f32(
2132 x_cpu,
2133 cos_cpu,
2134 sin_cpu,
2135 out_cpu,
2136 outer_count,
2137 seq,
2138 head_dim,
2139 )
2140}
2141
2142pub(crate) fn gather_cpu_wrapper(
2147 inputs: &[Arc<RwLock<Storage>>],
2148 outputs: &mut [Arc<RwLock<Storage>>],
2149 _layouts: &[Layout],
2150 params: &OpParams,
2151) -> Result<()> {
2152 if inputs.len() != 2 || outputs.len() != 1 {
2153 return Err(Error::Msg(format!(
2154 "gather wrapper expects 2 inputs + 1 output, got {} + {}",
2155 inputs.len(),
2156 outputs.len(),
2157 ))
2158 .bt());
2159 }
2160 let (source_shape, output_shape, dim) = match params {
2161 OpParams::Gather {
2162 source_shape,
2163 output_shape,
2164 dim,
2165 } => (source_shape, output_shape, *dim),
2166 other => {
2167 return Err(Error::Msg(format!(
2168 "gather wrapper expects OpParams::Gather, got {other:?}",
2169 ))
2170 .bt());
2171 }
2172 };
2173 let src_guard = read_storage(&inputs[0])?;
2174 let idx_guard = read_storage(&inputs[1])?;
2175 if idx_guard.dtype != DType::U32 {
2176 return Err(Error::Msg(format!(
2177 "gather: indices must be U32, got {:?}",
2178 idx_guard.dtype,
2179 ))
2180 .bt());
2181 }
2182 let mut out_guard = write_storage(&outputs[0])?;
2183 let dtype_size = out_guard.dtype.size_in_bytes();
2184 let src_cpu = cpu_input(&src_guard)?;
2185 let idx_cpu = cpu_input(&idx_guard)?;
2186 let out_cpu = cpu_output(&mut out_guard)?;
2187 fuel_cpu_backend::byte_kernels::gather_cpu(
2188 src_cpu,
2189 idx_cpu,
2190 out_cpu,
2191 source_shape,
2192 output_shape,
2193 dim,
2194 dtype_size,
2195 )
2196}
2197
2198pub(crate) fn index_select_cpu_wrapper(
2204 inputs: &[Arc<RwLock<Storage>>],
2205 outputs: &mut [Arc<RwLock<Storage>>],
2206 _layouts: &[Layout],
2207 params: &OpParams,
2208) -> Result<()> {
2209 if inputs.len() != 2 {
2210 return Err(Error::Msg(format!(
2211 "index_select wrapper expects 2 inputs (source, indices), got {}",
2212 inputs.len(),
2213 ))
2214 .bt());
2215 }
2216 if outputs.len() != 1 {
2217 return Err(Error::Msg(format!(
2218 "index_select wrapper expects 1 output, got {}",
2219 outputs.len(),
2220 ))
2221 .bt());
2222 }
2223 let (outer_count, source_dim_size, n_indices, inner_count) = match params {
2224 OpParams::IndexSelect {
2225 outer_count,
2226 source_dim_size,
2227 n_indices,
2228 inner_count,
2229 } => (*outer_count, *source_dim_size, *n_indices, *inner_count),
2230 other => {
2231 return Err(Error::Msg(format!(
2232 "index_select wrapper expects OpParams::IndexSelect, got {other:?}",
2233 ))
2234 .bt());
2235 }
2236 };
2237 let src_guard = read_storage(&inputs[0])?;
2238 let idx_guard = read_storage(&inputs[1])?;
2239 if idx_guard.dtype != DType::U32 {
2240 return Err(Error::Msg(format!(
2241 "index_select: indices must be U32, got {:?}",
2242 idx_guard.dtype,
2243 ))
2244 .bt());
2245 }
2246 let mut out_guard = write_storage(&outputs[0])?;
2247 let dtype_size = out_guard.dtype.size_in_bytes();
2248 let src_cpu = cpu_input(&src_guard)?;
2249 let idx_cpu = cpu_input(&idx_guard)?;
2250 let out_cpu = cpu_output(&mut out_guard)?;
2251 fuel_cpu_backend::byte_kernels::index_select_cpu(
2252 src_cpu,
2253 idx_cpu,
2254 out_cpu,
2255 outer_count,
2256 source_dim_size,
2257 n_indices,
2258 inner_count,
2259 dtype_size,
2260 )
2261}
2262
2263macro_rules! cpu_norm_last_dim_wrapper {
2267 ($wrapper:ident, $kernel:path, $op_name:literal) => {
2268 pub(crate) fn $wrapper(
2269 inputs: &[Arc<RwLock<Storage>>],
2270 outputs: &mut [Arc<RwLock<Storage>>],
2271 _layouts: &[Layout],
2272 params: &OpParams,
2273 ) -> Result<()> {
2274 if inputs.len() != 1 || outputs.len() != 1 {
2275 return Err(Error::Msg(format!(
2276 "{} wrapper expects 1 input + 1 output, got {} + {}",
2277 $op_name,
2278 inputs.len(),
2279 outputs.len(),
2280 ))
2281 .bt());
2282 }
2283 let (outer_count, last_dim, eps) = match params {
2284 OpParams::NormLastDim {
2285 outer_count,
2286 last_dim,
2287 eps,
2288 } => (*outer_count, *last_dim, *eps),
2289 other => {
2290 return Err(Error::Msg(format!(
2291 "{} wrapper expects OpParams::NormLastDim, got {other:?}",
2292 $op_name,
2293 ))
2294 .bt())
2295 }
2296 };
2297 let in_guard = read_storage(&inputs[0])?;
2298 let mut out_guard = write_storage(&outputs[0])?;
2299 let in_cpu = cpu_input(&in_guard)?;
2300 let out_cpu = cpu_output(&mut out_guard)?;
2301 $kernel(in_cpu, out_cpu, outer_count, last_dim, eps)
2302 }
2303 };
2304}
2305
2306cpu_norm_last_dim_wrapper!(
2307 rms_norm_last_dim_f32_cpu_wrapper,
2308 fuel_cpu_backend::byte_kernels::rms_norm_last_dim_f32,
2309 "rms_norm_last_dim"
2310);
2311cpu_norm_last_dim_wrapper!(
2312 layer_norm_last_dim_f32_cpu_wrapper,
2313 fuel_cpu_backend::byte_kernels::layer_norm_last_dim_f32,
2314 "layer_norm_last_dim"
2315);
2316cpu_norm_last_dim_wrapper!(
2317 rms_norm_last_dim_bf16_cpu_wrapper,
2318 fuel_cpu_backend::byte_kernels::rms_norm_last_dim_bf16,
2319 "rms_norm_last_dim"
2320);
2321cpu_norm_last_dim_wrapper!(
2322 rms_norm_last_dim_f16_cpu_wrapper,
2323 fuel_cpu_backend::byte_kernels::rms_norm_last_dim_f16,
2324 "rms_norm_last_dim"
2325);
2326cpu_norm_last_dim_wrapper!(
2327 layer_norm_last_dim_bf16_cpu_wrapper,
2328 fuel_cpu_backend::byte_kernels::layer_norm_last_dim_bf16,
2329 "layer_norm_last_dim"
2330);
2331cpu_norm_last_dim_wrapper!(
2332 layer_norm_last_dim_f16_cpu_wrapper,
2333 fuel_cpu_backend::byte_kernels::layer_norm_last_dim_f16,
2334 "layer_norm_last_dim"
2335);
2336cpu_norm_last_dim_wrapper!(
2337 rms_norm_last_dim_f64_cpu_wrapper,
2338 fuel_cpu_backend::byte_kernels::rms_norm_last_dim_f64,
2339 "rms_norm_last_dim"
2340);
2341cpu_norm_last_dim_wrapper!(
2342 layer_norm_last_dim_f64_cpu_wrapper,
2343 fuel_cpu_backend::byte_kernels::layer_norm_last_dim_f64,
2344 "layer_norm_last_dim"
2345);
2346
2347macro_rules! cpu_softmax_last_dim_wrapper {
2354 ($wrapper:ident, $kernel:path) => {
2355 pub(crate) fn $wrapper(
2356 inputs: &[Arc<RwLock<Storage>>],
2357 outputs: &mut [Arc<RwLock<Storage>>],
2358 _layouts: &[Layout],
2359 params: &OpParams,
2360 ) -> Result<()> {
2361 if inputs.len() != 1 || outputs.len() != 1 {
2362 return Err(Error::Msg(format!(
2363 "softmax_last_dim wrapper expects 1 input + 1 output, got {} + {}",
2364 inputs.len(),
2365 outputs.len(),
2366 ))
2367 .bt());
2368 }
2369 let (outer_count, last_dim) =
2370 match params {
2371 OpParams::SoftmaxLastDim {
2372 outer_count,
2373 last_dim,
2374 } => (*outer_count, *last_dim),
2375 other => return Err(Error::Msg(format!(
2376 "softmax_last_dim wrapper expects OpParams::SoftmaxLastDim, got {other:?}",
2377 ))
2378 .bt()),
2379 };
2380 let in_guard = read_storage(&inputs[0])?;
2381 let mut out_guard = write_storage(&outputs[0])?;
2382 let in_cpu = cpu_input(&in_guard)?;
2383 let out_cpu = cpu_output(&mut out_guard)?;
2384 $kernel(in_cpu, out_cpu, outer_count, last_dim)
2385 }
2386 };
2387}
2388
2389cpu_softmax_last_dim_wrapper!(
2390 softmax_last_dim_f32_cpu_wrapper,
2391 fuel_cpu_backend::byte_kernels::softmax_last_dim_f32
2392);
2393cpu_softmax_last_dim_wrapper!(
2394 softmax_last_dim_f64_cpu_wrapper,
2395 fuel_cpu_backend::byte_kernels::softmax_last_dim_f64
2396);
2397cpu_softmax_last_dim_wrapper!(
2398 softmax_last_dim_bf16_cpu_wrapper,
2399 fuel_cpu_backend::byte_kernels::softmax_last_dim_bf16
2400);
2401cpu_softmax_last_dim_wrapper!(
2402 softmax_last_dim_f16_cpu_wrapper,
2403 fuel_cpu_backend::byte_kernels::softmax_last_dim_f16
2404);
2405
2406macro_rules! cpu_rope_wrapper {
2412 ($wrapper:ident, $kernel:path) => {
2413 pub(crate) fn $wrapper(
2414 inputs: &[Arc<RwLock<Storage>>],
2415 outputs: &mut [Arc<RwLock<Storage>>],
2416 _layouts: &[Layout],
2417 params: &OpParams,
2418 ) -> Result<()> {
2419 if inputs.len() != 3 || outputs.len() != 1 {
2420 return Err(Error::Msg(format!(
2421 "rope wrapper expects 3 inputs + 1 output, got {} + {}",
2422 inputs.len(),
2423 outputs.len(),
2424 ))
2425 .bt());
2426 }
2427 let (outer_count, seq, head_dim) = match params {
2428 OpParams::Rope {
2429 outer_count,
2430 seq,
2431 head_dim,
2432 } => (*outer_count, *seq, *head_dim),
2433 other => {
2434 return Err(Error::Msg(format!(
2435 "rope wrapper expects OpParams::Rope, got {other:?}",
2436 ))
2437 .bt())
2438 }
2439 };
2440 let x_guard = read_storage(&inputs[0])?;
2441 let cos_guard = read_storage(&inputs[1])?;
2442 let sin_guard = read_storage(&inputs[2])?;
2443 let mut out_guard = write_storage(&outputs[0])?;
2444 let x_cpu = cpu_input(&x_guard)?;
2445 let cos_cpu = cpu_input(&cos_guard)?;
2446 let sin_cpu = cpu_input(&sin_guard)?;
2447 let out_cpu = cpu_output(&mut out_guard)?;
2448 $kernel(x_cpu, cos_cpu, sin_cpu, out_cpu, outer_count, seq, head_dim)
2449 }
2450 };
2451}
2452
2453cpu_rope_wrapper!(
2454 rope_bf16_cpu_wrapper,
2455 fuel_cpu_backend::byte_kernels::rope_bf16
2456);
2457cpu_rope_wrapper!(
2458 rope_f16_cpu_wrapper,
2459 fuel_cpu_backend::byte_kernels::rope_f16
2460);
2461cpu_rope_wrapper!(
2462 rope_f64_cpu_wrapper,
2463 fuel_cpu_backend::byte_kernels::rope_f64
2464);
2465
2466#[allow(clippy::too_many_arguments)]
2469pub(crate) fn qmatmul_cpu_by_type(
2470 quant_type: fuel_graph::QuantType,
2471 act_cpu: &fuel_cpu_backend::CpuStorageBytes,
2472 w_cpu: &fuel_cpu_backend::CpuStorageBytes,
2473 out_cpu: &mut fuel_cpu_backend::CpuStorageBytes,
2474 batch_count: usize,
2475 m: usize,
2476 n: usize,
2477 k: usize,
2478) -> Result<()> {
2479 use fuel_graph::QuantType;
2480 match quant_type {
2481 QuantType::Q4_0 => fuel_cpu_backend::byte_kernels::qmatmul_q4_0_f32(
2482 act_cpu,
2483 w_cpu,
2484 out_cpu,
2485 batch_count,
2486 m,
2487 n,
2488 k,
2489 ),
2490 QuantType::Q4_1 => fuel_cpu_backend::byte_kernels::qmatmul_q4_1_f32(
2491 act_cpu,
2492 w_cpu,
2493 out_cpu,
2494 batch_count,
2495 m,
2496 n,
2497 k,
2498 ),
2499 QuantType::Q5_0 => fuel_cpu_backend::byte_kernels::qmatmul_q5_0_f32(
2500 act_cpu,
2501 w_cpu,
2502 out_cpu,
2503 batch_count,
2504 m,
2505 n,
2506 k,
2507 ),
2508 QuantType::Q5_1 => fuel_cpu_backend::byte_kernels::qmatmul_q5_1_f32(
2509 act_cpu,
2510 w_cpu,
2511 out_cpu,
2512 batch_count,
2513 m,
2514 n,
2515 k,
2516 ),
2517 QuantType::Q8_0 => fuel_cpu_backend::byte_kernels::qmatmul_q8_0_f32(
2518 act_cpu,
2519 w_cpu,
2520 out_cpu,
2521 batch_count,
2522 m,
2523 n,
2524 k,
2525 ),
2526 QuantType::Q8_1 => fuel_cpu_backend::byte_kernels::qmatmul_q8_1_f32(
2527 act_cpu,
2528 w_cpu,
2529 out_cpu,
2530 batch_count,
2531 m,
2532 n,
2533 k,
2534 ),
2535 QuantType::Q2K => fuel_cpu_backend::byte_kernels::qmatmul_q2k_f32(
2536 act_cpu,
2537 w_cpu,
2538 out_cpu,
2539 batch_count,
2540 m,
2541 n,
2542 k,
2543 ),
2544 QuantType::Q3K => fuel_cpu_backend::byte_kernels::qmatmul_q3k_f32(
2545 act_cpu,
2546 w_cpu,
2547 out_cpu,
2548 batch_count,
2549 m,
2550 n,
2551 k,
2552 ),
2553 QuantType::Q4_K_M => fuel_cpu_backend::byte_kernels::qmatmul_q4_k_m_f32(
2554 act_cpu,
2555 w_cpu,
2556 out_cpu,
2557 batch_count,
2558 m,
2559 n,
2560 k,
2561 ),
2562 QuantType::Q5K => fuel_cpu_backend::byte_kernels::qmatmul_q5k_f32(
2563 act_cpu,
2564 w_cpu,
2565 out_cpu,
2566 batch_count,
2567 m,
2568 n,
2569 k,
2570 ),
2571 QuantType::Q6K => fuel_cpu_backend::byte_kernels::qmatmul_q6k_f32(
2572 act_cpu,
2573 w_cpu,
2574 out_cpu,
2575 batch_count,
2576 m,
2577 n,
2578 k,
2579 ),
2580 }
2581}
2582
2583pub(crate) fn qmatmul_f32_cpu_wrapper(
2592 inputs: &[Arc<RwLock<Storage>>],
2593 outputs: &mut [Arc<RwLock<Storage>>],
2594 _layouts: &[Layout],
2595 params: &OpParams,
2596) -> Result<()> {
2597 if inputs.len() != 2 {
2598 return Err(Error::Msg(format!(
2599 "qmatmul wrapper expects 2 inputs (activations, weight_bytes), got {}",
2600 inputs.len(),
2601 ))
2602 .bt());
2603 }
2604 if outputs.len() != 1 {
2605 return Err(Error::Msg(format!(
2606 "qmatmul wrapper expects 1 output, got {}",
2607 outputs.len(),
2608 ))
2609 .bt());
2610 }
2611 let (quant_type, batch_count, m, n, k) = match params {
2612 OpParams::QMatMul {
2613 quant_type,
2614 batch_count,
2615 m,
2616 n,
2617 k,
2618 } => (*quant_type, *batch_count, *m, *n, *k),
2619 other => {
2620 return Err(Error::Msg(format!(
2621 "qmatmul wrapper expects OpParams::QMatMul, got {other:?}",
2622 ))
2623 .bt());
2624 }
2625 };
2626 let act_guard = read_storage(&inputs[0])?;
2627 let w_guard = read_storage(&inputs[1])?;
2628 if w_guard.dtype != DType::U32 {
2629 return Err(Error::Msg(format!(
2630 "qmatmul: weight bytes must be U32-typed (raw block stream), got {:?}",
2631 w_guard.dtype,
2632 ))
2633 .bt());
2634 }
2635 let mut out_guard = write_storage(&outputs[0])?;
2636 let act_cpu = cpu_input(&act_guard)?;
2637 let w_cpu = cpu_input(&w_guard)?;
2638 let out_cpu = cpu_output(&mut out_guard)?;
2639 qmatmul_cpu_by_type(quant_type, act_cpu, w_cpu, out_cpu, batch_count, m, n, k)
2640}
2641
2642pub(crate) fn write_slice_cpu_wrapper(
2650 inputs: &[Arc<RwLock<Storage>>],
2651 outputs: &mut [Arc<RwLock<Storage>>],
2652 _layouts: &[Layout],
2653 params: &OpParams,
2654) -> Result<()> {
2655 if inputs.len() != 1 || outputs.len() != 1 {
2656 return Err(Error::Msg(format!(
2657 "write_slice wrapper expects 1 input (source) + 1 output (dest), \
2658 got {} + {}",
2659 inputs.len(),
2660 outputs.len(),
2661 ))
2662 .bt());
2663 }
2664 let (dest_shape, ranges) = match params {
2665 OpParams::WriteSlice {
2666 dest_shape, ranges, ..
2667 } => (dest_shape, ranges),
2668 other => {
2669 return Err(Error::Msg(format!(
2670 "write_slice wrapper expects OpParams::WriteSlice, got {other:?}",
2671 ))
2672 .bt());
2673 }
2674 };
2675 let src_guard = read_storage(&inputs[0])?;
2676 let src_cpu = cpu_input(&src_guard)?;
2677 let mut dest_guard = write_storage(&outputs[0])?;
2678 let dtype_size = dest_guard.dtype.size_in_bytes();
2679 let dest_cpu = cpu_output(&mut dest_guard)?;
2680 fuel_cpu_backend::byte_kernels::write_slice_cpu(
2681 src_cpu, dest_cpu, dest_shape, ranges, dtype_size,
2682 )
2683}
2684
2685pub(crate) fn write_slice_rotating_cpu_wrapper(
2693 inputs: &[Arc<RwLock<Storage>>],
2694 outputs: &mut [Arc<RwLock<Storage>>],
2695 _layouts: &[Layout],
2696 params: &OpParams,
2697) -> Result<()> {
2698 if inputs.len() != 2 || outputs.len() != 1 {
2699 return Err(Error::Msg(format!(
2700 "write_slice_rotating wrapper expects 2 inputs (source, position) + 1 output (dest), \
2701 got {} + {}",
2702 inputs.len(),
2703 outputs.len(),
2704 ))
2705 .bt());
2706 }
2707 let (dest_shape, axis, modulus, ranges) =
2708 match params {
2709 OpParams::WriteSliceRotating {
2710 dest_shape,
2711 axis,
2712 modulus,
2713 ranges,
2714 } => (dest_shape, *axis, *modulus, ranges),
2715 other => return Err(Error::Msg(format!(
2716 "write_slice_rotating wrapper expects OpParams::WriteSliceRotating, got {other:?}",
2717 ))
2718 .bt()),
2719 };
2720 let src_guard = read_storage(&inputs[0])?;
2721 let src_cpu = cpu_input(&src_guard)?;
2722 let pos_guard = read_storage(&inputs[1])?;
2723 let pos_cpu = cpu_input(&pos_guard)?;
2724 let mut dest_guard = write_storage(&outputs[0])?;
2725 let dtype_size = dest_guard.dtype.size_in_bytes();
2726 let dest_cpu = cpu_output(&mut dest_guard)?;
2727 fuel_cpu_backend::byte_kernels::write_slice_rotating_cpu(
2728 src_cpu, pos_cpu, dest_cpu, dest_shape, axis, modulus, ranges, dtype_size,
2729 )
2730}
2731
2732pub(crate) fn write_slice_doff_cpu_wrapper(
2739 inputs: &[Arc<RwLock<Storage>>],
2740 outputs: &mut [Arc<RwLock<Storage>>],
2741 _layouts: &[Layout],
2742 params: &OpParams,
2743) -> Result<()> {
2744 if inputs.len() != 2 || outputs.len() != 1 {
2745 return Err(Error::Msg(format!(
2746 "write_slice_doff wrapper expects 2 inputs (source, offset) + 1 output (dest), \
2747 got {} + {}",
2748 inputs.len(),
2749 outputs.len(),
2750 ))
2751 .bt());
2752 }
2753 let (dest_shape, axis, ranges) = match params {
2754 OpParams::WriteSliceDoff {
2755 dest_shape,
2756 axis,
2757 ranges,
2758 } => (dest_shape, *axis, ranges),
2759 other => {
2760 return Err(Error::Msg(format!(
2761 "write_slice_doff wrapper expects OpParams::WriteSliceDoff, got {other:?}",
2762 ))
2763 .bt());
2764 }
2765 };
2766 let src_guard = read_storage(&inputs[0])?;
2767 let src_cpu = cpu_input(&src_guard)?;
2768 let off_guard = read_storage(&inputs[1])?;
2769 let off_cpu = cpu_input(&off_guard)?;
2770 let mut dest_guard = write_storage(&outputs[0])?;
2771 let dtype_size = dest_guard.dtype.size_in_bytes();
2772 let dest_cpu = cpu_output(&mut dest_guard)?;
2773 fuel_cpu_backend::byte_kernels::write_slice_doff_cpu(
2774 src_cpu, off_cpu, dest_cpu, dest_shape, axis, ranges, dtype_size,
2775 )
2776}
2777
2778pub(crate) fn concat_cpu_wrapper(
2779 inputs: &[Arc<RwLock<Storage>>],
2780 outputs: &mut [Arc<RwLock<Storage>>],
2781 _layouts: &[Layout],
2782 params: &OpParams,
2783) -> Result<()> {
2784 if inputs.is_empty() {
2785 return Err(Error::Msg("concat wrapper expects ≥ 1 input, got 0".to_string()).bt());
2786 }
2787 if outputs.len() != 1 {
2788 return Err(Error::Msg(format!(
2789 "concat wrapper expects 1 output, got {}",
2790 outputs.len(),
2791 ))
2792 .bt());
2793 }
2794 let (outer_count, input_dim_sizes, inner_count) = match params {
2795 OpParams::Concat {
2796 outer_count,
2797 input_dim_sizes,
2798 inner_count,
2799 ..
2800 } => (*outer_count, input_dim_sizes, *inner_count),
2801 other => {
2802 return Err(Error::Msg(format!(
2803 "concat wrapper expects OpParams::Concat, got {other:?}",
2804 ))
2805 .bt());
2806 }
2807 };
2808 if input_dim_sizes.len() != inputs.len() {
2809 return Err(Error::Msg(format!(
2810 "concat wrapper: OpParams declares {} inputs but the work item \
2811 carries {}",
2812 input_dim_sizes.len(),
2813 inputs.len(),
2814 ))
2815 .bt());
2816 }
2817 let in_guards: Vec<_> = inputs
2818 .iter()
2819 .map(read_storage)
2820 .collect::<Result<Vec<_>>>()?;
2821 let mut in_cpus: Vec<&fuel_cpu_backend::CpuStorageBytes> = Vec::with_capacity(in_guards.len());
2822 for g in &in_guards {
2823 in_cpus.push(cpu_input(g)?);
2824 }
2825 let mut out_guard = write_storage(&outputs[0])?;
2826 let dtype_size = out_guard.dtype.size_in_bytes();
2827 let out_cpu = cpu_output(&mut out_guard)?;
2828 fuel_cpu_backend::byte_kernels::concat_cpu(
2829 &in_cpus,
2830 out_cpu,
2831 outer_count,
2832 input_dim_sizes,
2833 inner_count,
2834 dtype_size,
2835 )
2836}
2837
2838macro_rules! cpu_index_add_wrapper {
2841 ($wrapper:ident, $kernel:path, $idx_ck:literal) => {
2842 pub(crate) fn $wrapper(
2845 inputs: &[Arc<RwLock<Storage>>],
2846 outputs: &mut [Arc<RwLock<Storage>>],
2847 _layouts: &[Layout],
2848 params: &OpParams,
2849 ) -> Result<()> {
2850 if inputs.len() != 3 || outputs.len() != 1 {
2851 return Err(Error::Msg(format!(
2852 "{}: expects 3 inputs + 1 output, got {} + {}",
2853 $idx_ck,
2854 inputs.len(),
2855 outputs.len(),
2856 ))
2857 .bt());
2858 }
2859 let (outer_count, base_dim_size, n_indices, inner_count) = match params {
2860 OpParams::IndexAdd {
2861 outer_count,
2862 base_dim_size,
2863 n_indices,
2864 inner_count,
2865 } => (*outer_count, *base_dim_size, *n_indices, *inner_count),
2866 other => {
2867 return Err(Error::Msg(format!(
2868 "{}: expects OpParams::IndexAdd, got {other:?}",
2869 $idx_ck,
2870 ))
2871 .bt())
2872 }
2873 };
2874 let base_guard = read_storage(&inputs[0])?;
2875 let idx_guard = read_storage(&inputs[1])?;
2876 if idx_guard.dtype != DType::U32 {
2877 return Err(Error::Msg(format!("{}: indices must be U32", $idx_ck,)).bt());
2878 }
2879 let src_guard = read_storage(&inputs[2])?;
2880 let mut out_guard = write_storage(&outputs[0])?;
2881 let base_cpu = cpu_input(&base_guard)?;
2882 let idx_cpu = cpu_input(&idx_guard)?;
2883 let src_cpu = cpu_input(&src_guard)?;
2884 let out_cpu = cpu_output(&mut out_guard)?;
2885 $kernel(
2886 base_cpu,
2887 idx_cpu,
2888 src_cpu,
2889 out_cpu,
2890 outer_count,
2891 base_dim_size,
2892 n_indices,
2893 inner_count,
2894 )
2895 }
2896 };
2897}
2898
2899cpu_index_add_wrapper!(
2900 index_add_f64_cpu_wrapper,
2901 fuel_cpu_backend::byte_kernels::index_add_f64,
2902 "index_add_f64"
2903);
2904cpu_index_add_wrapper!(
2905 index_add_bf16_cpu_wrapper,
2906 fuel_cpu_backend::byte_kernels::index_add_bf16,
2907 "index_add_bf16"
2908);
2909cpu_index_add_wrapper!(
2910 index_add_f16_cpu_wrapper,
2911 fuel_cpu_backend::byte_kernels::index_add_f16,
2912 "index_add_f16"
2913);
2914
2915macro_rules! cpu_scatter_add_wrapper {
2917 ($wrapper:ident, $kernel:path, $name_str:literal) => {
2918 pub(crate) fn $wrapper(
2920 inputs: &[Arc<RwLock<Storage>>],
2921 outputs: &mut [Arc<RwLock<Storage>>],
2922 _layouts: &[Layout],
2923 params: &OpParams,
2924 ) -> Result<()> {
2925 if inputs.len() != 3 || outputs.len() != 1 {
2926 return Err(Error::Msg(format!(
2927 "{}: expects 3 inputs + 1 output, got {} + {}",
2928 $name_str,
2929 inputs.len(),
2930 outputs.len(),
2931 ))
2932 .bt());
2933 }
2934 let (base_shape, src_shape, dim) = match params {
2935 OpParams::ScatterAdd {
2936 base_shape,
2937 src_shape,
2938 dim,
2939 } => (base_shape, src_shape, *dim),
2940 other => {
2941 return Err(Error::Msg(format!(
2942 "{}: expects OpParams::ScatterAdd, got {other:?}",
2943 $name_str,
2944 ))
2945 .bt())
2946 }
2947 };
2948 let base_guard = read_storage(&inputs[0])?;
2949 let idx_guard = read_storage(&inputs[1])?;
2950 if idx_guard.dtype != DType::U32 {
2951 return Err(Error::Msg(format!("{}: indices must be U32", $name_str,)).bt());
2952 }
2953 let src_guard = read_storage(&inputs[2])?;
2954 let mut out_guard = write_storage(&outputs[0])?;
2955 let base_cpu = cpu_input(&base_guard)?;
2956 let idx_cpu = cpu_input(&idx_guard)?;
2957 let src_cpu = cpu_input(&src_guard)?;
2958 let out_cpu = cpu_output(&mut out_guard)?;
2959 $kernel(
2960 base_cpu, idx_cpu, src_cpu, out_cpu, base_shape, src_shape, dim,
2961 )
2962 }
2963 };
2964}
2965
2966cpu_scatter_add_wrapper!(
2967 scatter_add_f64_cpu_wrapper,
2968 fuel_cpu_backend::byte_kernels::scatter_add_f64,
2969 "scatter_add_f64"
2970);
2971cpu_scatter_add_wrapper!(
2972 scatter_add_bf16_cpu_wrapper,
2973 fuel_cpu_backend::byte_kernels::scatter_add_bf16,
2974 "scatter_add_bf16"
2975);
2976cpu_scatter_add_wrapper!(
2977 scatter_add_f16_cpu_wrapper,
2978 fuel_cpu_backend::byte_kernels::scatter_add_f16,
2979 "scatter_add_f16"
2980);
2981
2982macro_rules! cpu_affine_wrapper_native {
2986 ($wrapper:ident, $kernel:path, $T:ty) => {
2987 pub(crate) fn $wrapper(
2990 inputs: &[Arc<RwLock<Storage>>],
2991 outputs: &mut [Arc<RwLock<Storage>>],
2992 _layouts: &[Layout],
2993 params: &OpParams,
2994 ) -> Result<()> {
2995 if inputs.len() != 1 || outputs.len() != 1 {
2996 return Err(Error::Msg("affine: 1 input + 1 output".to_string()).bt());
2997 }
2998 let (mul, add) = match params {
2999 OpParams::Affine { mul, add } => (*mul as $T, *add as $T),
3000 other => return Err(Error::Msg(format!("affine: bad params {other:?}")).bt()),
3001 };
3002 let in_guard = read_storage(&inputs[0])?;
3003 let mut out_guard = write_storage(&outputs[0])?;
3004 let in_cpu = cpu_input(&in_guard)?;
3005 let out_cpu = cpu_output(&mut out_guard)?;
3006 $kernel(in_cpu, out_cpu, mul, add)
3007 }
3008 };
3009}
3010
3011cpu_affine_wrapper_native!(
3012 affine_f64_cpu_wrapper,
3013 fuel_cpu_backend::byte_kernels::affine_f64,
3014 f64
3015);
3016
3017macro_rules! cpu_affine_wrapper_half {
3018 ($wrapper:ident, $kernel:path) => {
3019 pub(crate) fn $wrapper(
3022 inputs: &[Arc<RwLock<Storage>>],
3023 outputs: &mut [Arc<RwLock<Storage>>],
3024 _layouts: &[Layout],
3025 params: &OpParams,
3026 ) -> Result<()> {
3027 if inputs.len() != 1 || outputs.len() != 1 {
3028 return Err(Error::Msg("affine: 1 input + 1 output".to_string()).bt());
3029 }
3030 let (mul, add) = match params {
3031 OpParams::Affine { mul, add } => (*mul as f32, *add as f32),
3032 other => return Err(Error::Msg(format!("affine: bad params {other:?}")).bt()),
3033 };
3034 let in_guard = read_storage(&inputs[0])?;
3035 let mut out_guard = write_storage(&outputs[0])?;
3036 let in_cpu = cpu_input(&in_guard)?;
3037 let out_cpu = cpu_output(&mut out_guard)?;
3038 $kernel(in_cpu, out_cpu, mul, add)
3039 }
3040 };
3041}
3042
3043cpu_affine_wrapper_half!(
3044 affine_bf16_cpu_wrapper,
3045 fuel_cpu_backend::byte_kernels::affine_bf16
3046);
3047cpu_affine_wrapper_half!(
3048 affine_f16_cpu_wrapper,
3049 fuel_cpu_backend::byte_kernels::affine_f16
3050);
3051
3052macro_rules! cpu_clamp_wrapper {
3053 ($wrapper:ident, $kernel:path, $T:ty) => {
3054 pub(crate) fn $wrapper(
3057 inputs: &[Arc<RwLock<Storage>>],
3058 outputs: &mut [Arc<RwLock<Storage>>],
3059 _layouts: &[Layout],
3060 params: &OpParams,
3061 ) -> Result<()> {
3062 if inputs.len() != 1 || outputs.len() != 1 {
3063 return Err(Error::Msg("clamp: 1 input + 1 output".to_string()).bt());
3064 }
3065 let (min, max) = match params {
3066 OpParams::Clamp { min, max } => (*min as $T, *max as $T),
3067 other => return Err(Error::Msg(format!("clamp: bad params {other:?}")).bt()),
3068 };
3069 let in_guard = read_storage(&inputs[0])?;
3070 let mut out_guard = write_storage(&outputs[0])?;
3071 let in_cpu = cpu_input(&in_guard)?;
3072 let out_cpu = cpu_output(&mut out_guard)?;
3073 $kernel(in_cpu, out_cpu, min, max)
3074 }
3075 };
3076}
3077
3078cpu_clamp_wrapper!(
3079 clamp_f64_cpu_wrapper,
3080 fuel_cpu_backend::byte_kernels::clamp_f64,
3081 f64
3082);
3083cpu_clamp_wrapper!(
3084 clamp_bf16_cpu_wrapper,
3085 fuel_cpu_backend::byte_kernels::clamp_bf16,
3086 f32
3087);
3088cpu_clamp_wrapper!(
3089 clamp_f16_cpu_wrapper,
3090 fuel_cpu_backend::byte_kernels::clamp_f16,
3091 f32
3092);
3093
3094macro_rules! cpu_powi_wrapper {
3095 ($wrapper:ident, $kernel:path) => {
3096 pub(crate) fn $wrapper(
3099 inputs: &[Arc<RwLock<Storage>>],
3100 outputs: &mut [Arc<RwLock<Storage>>],
3101 _layouts: &[Layout],
3102 params: &OpParams,
3103 ) -> Result<()> {
3104 if inputs.len() != 1 || outputs.len() != 1 {
3105 return Err(Error::Msg("powi: 1 input + 1 output".to_string()).bt());
3106 }
3107 let exp = match params {
3108 OpParams::PowI { exp } => *exp,
3109 other => return Err(Error::Msg(format!("powi: bad params {other:?}")).bt()),
3110 };
3111 let in_guard = read_storage(&inputs[0])?;
3112 let mut out_guard = write_storage(&outputs[0])?;
3113 let in_cpu = cpu_input(&in_guard)?;
3114 let out_cpu = cpu_output(&mut out_guard)?;
3115 $kernel(in_cpu, out_cpu, exp)
3116 }
3117 };
3118}
3119
3120cpu_powi_wrapper!(
3121 powi_f64_cpu_wrapper,
3122 fuel_cpu_backend::byte_kernels::powi_f64
3123);
3124cpu_powi_wrapper!(
3125 powi_bf16_cpu_wrapper,
3126 fuel_cpu_backend::byte_kernels::powi_bf16
3127);
3128cpu_powi_wrapper!(
3129 powi_f16_cpu_wrapper,
3130 fuel_cpu_backend::byte_kernels::powi_f16
3131);
3132
3133macro_rules! cpu_arg_dim_wrapper_typed {
3137 ($wrapper:ident, $kernel:path, $expected_in_dtype:expr, $op_name:literal) => {
3138 fn $wrapper(
3139 inputs: &[Arc<RwLock<Storage>>],
3140 outputs: &mut [Arc<RwLock<Storage>>],
3141 layouts: &[Layout],
3142 params: &OpParams,
3143 ) -> Result<()> {
3144 if inputs.len() != 1 || outputs.len() != 1 {
3145 return Err(Error::Msg(format!("{}: 1 input + 1 output", $op_name,)).bt());
3146 }
3147 let dims = match params {
3148 OpParams::Reduce { dims, .. } => dims,
3149 other => {
3150 return Err(Error::Msg(format!(
3151 "{}: expects OpParams::Reduce, got {other:?}",
3152 $op_name,
3153 ))
3154 .bt())
3155 }
3156 };
3157 if dims.len() != 1 {
3158 return Err(Error::Msg(format!(
3159 "{}: expects exactly 1 reduce dim, got {dims:?}",
3160 $op_name,
3161 ))
3162 .bt());
3163 }
3164 let dim = dims[0];
3165 let input_layout = layouts.first().ok_or_else(|| {
3166 Error::Msg(format!(
3167 "{}: layouts empty (executor must pass input layout at [0])",
3168 $op_name,
3169 ))
3170 .bt()
3171 })?;
3172 let in_guard = read_storage(&inputs[0])?;
3173 if in_guard.dtype != $expected_in_dtype {
3174 return Err(Error::Msg(format!(
3175 "{}: expects input dtype {:?}, got {:?}",
3176 $op_name, $expected_in_dtype, in_guard.dtype,
3177 ))
3178 .bt());
3179 }
3180 let mut out_guard = write_storage(&outputs[0])?;
3181 let in_cpu = cpu_input(&in_guard)?;
3182 let out_cpu = cpu_output(&mut out_guard)?;
3183 $kernel(in_cpu, out_cpu, input_layout.shape().dims(), dim)
3184 }
3185 };
3186}
3187
3188fn argmax_dim_u32_cpu_dispatch(
3192 inputs: &[Arc<RwLock<Storage>>],
3193 outputs: &mut [Arc<RwLock<Storage>>],
3194 _layouts: &[Layout],
3195 params: &OpParams,
3196) -> Result<()> {
3197 let in_dtype = read_storage(&inputs[0])?.dtype;
3198 match in_dtype {
3199 DType::F32 => argmax_dim_u32_cpu_wrapper(inputs, outputs, _layouts, params),
3200 DType::F64 => argmax_dim_f64_only_wrapper(inputs, outputs, _layouts, params),
3201 DType::BF16 => argmax_dim_bf16_only_wrapper(inputs, outputs, _layouts, params),
3202 DType::F16 => argmax_dim_f16_only_wrapper(inputs, outputs, _layouts, params),
3203 other => Err(Error::Msg(format!("argmax_dim: unsupported input dtype {other:?}",)).bt()),
3204 }
3205}
3206
3207fn argmin_dim_u32_cpu_dispatch(
3208 inputs: &[Arc<RwLock<Storage>>],
3209 outputs: &mut [Arc<RwLock<Storage>>],
3210 _layouts: &[Layout],
3211 params: &OpParams,
3212) -> Result<()> {
3213 let in_dtype = read_storage(&inputs[0])?.dtype;
3214 match in_dtype {
3215 DType::F32 => argmin_dim_u32_cpu_wrapper(inputs, outputs, _layouts, params),
3216 DType::F64 => argmin_dim_f64_only_wrapper(inputs, outputs, _layouts, params),
3217 DType::BF16 => argmin_dim_bf16_only_wrapper(inputs, outputs, _layouts, params),
3218 DType::F16 => argmin_dim_f16_only_wrapper(inputs, outputs, _layouts, params),
3219 other => Err(Error::Msg(format!("argmin_dim: unsupported input dtype {other:?}",)).bt()),
3220 }
3221}
3222
3223cpu_arg_dim_wrapper_typed!(
3224 argmax_dim_f64_only_wrapper,
3225 fuel_cpu_backend::byte_kernels::argmax_dim_f64,
3226 DType::F64,
3227 "argmax_dim_f64"
3228);
3229cpu_arg_dim_wrapper_typed!(
3230 argmin_dim_f64_only_wrapper,
3231 fuel_cpu_backend::byte_kernels::argmin_dim_f64,
3232 DType::F64,
3233 "argmin_dim_f64"
3234);
3235cpu_arg_dim_wrapper_typed!(
3236 argmax_dim_bf16_only_wrapper,
3237 fuel_cpu_backend::byte_kernels::argmax_dim_bf16,
3238 DType::BF16,
3239 "argmax_dim_bf16"
3240);
3241cpu_arg_dim_wrapper_typed!(
3242 argmin_dim_bf16_only_wrapper,
3243 fuel_cpu_backend::byte_kernels::argmin_dim_bf16,
3244 DType::BF16,
3245 "argmin_dim_bf16"
3246);
3247cpu_arg_dim_wrapper_typed!(
3248 argmax_dim_f16_only_wrapper,
3249 fuel_cpu_backend::byte_kernels::argmax_dim_f16,
3250 DType::F16,
3251 "argmax_dim_f16"
3252);
3253cpu_arg_dim_wrapper_typed!(
3254 argmin_dim_f16_only_wrapper,
3255 fuel_cpu_backend::byte_kernels::argmin_dim_f16,
3256 DType::F16,
3257 "argmin_dim_f16"
3258);
3259
3260pub(crate) fn affine_f32_cpu_wrapper(
3263 inputs: &[Arc<RwLock<Storage>>],
3264 outputs: &mut [Arc<RwLock<Storage>>],
3265 _layouts: &[Layout],
3266 params: &OpParams,
3267) -> Result<()> {
3268 if inputs.len() != 1 || outputs.len() != 1 {
3269 return Err(Error::Msg(format!(
3270 "affine wrapper expects 1 input + 1 output, got {} + {}",
3271 inputs.len(),
3272 outputs.len(),
3273 ))
3274 .bt());
3275 }
3276 let (mul, add) = match params {
3277 OpParams::Affine { mul, add } => (*mul as f32, *add as f32),
3278 other => {
3279 return Err(Error::Msg(format!(
3280 "affine wrapper expects OpParams::Affine, got {other:?}",
3281 ))
3282 .bt());
3283 }
3284 };
3285 let in_guard = read_storage(&inputs[0])?;
3286 let mut out_guard = write_storage(&outputs[0])?;
3287 let in_cpu = cpu_input(&in_guard)?;
3288 let out_cpu = cpu_output(&mut out_guard)?;
3289 fuel_cpu_backend::byte_kernels::affine_f32(in_cpu, out_cpu, mul, add)
3290}
3291
3292macro_rules! cpu_affine_inplace_wrapper {
3297 ($name:ident, $kernel:ident, $T:ty) => {
3298 pub(crate) fn $name(
3299 inputs: &[Arc<RwLock<Storage>>],
3300 outputs: &mut [Arc<RwLock<Storage>>],
3301 _layouts: &[Layout],
3302 params: &OpParams,
3303 ) -> Result<()> {
3304 if !inputs.is_empty() || outputs.len() != 1 {
3305 return Err(Error::Msg(format!(
3306 concat!(
3307 stringify!($name),
3308 ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3309 ),
3310 inputs.len(),
3311 outputs.len(),
3312 ))
3313 .bt());
3314 }
3315 let (mul, add) = match params {
3316 OpParams::Affine { mul, add } => (*mul as $T, *add as $T),
3317 other => {
3318 return Err(Error::Msg(format!(
3319 concat!(stringify!($name), ": expected OpParams::Affine, got {:?}"),
3320 other,
3321 ))
3322 .bt())
3323 }
3324 };
3325 let mut out_guard = write_storage(&outputs[0])?;
3326 let out_cpu = cpu_output(&mut out_guard)?;
3327 fuel_cpu_backend::byte_kernels::$kernel(out_cpu, mul, add)
3328 }
3329 };
3330 ($name:ident, $kernel:ident, $T:ty, half) => {
3331 pub(crate) fn $name(
3332 inputs: &[Arc<RwLock<Storage>>],
3333 outputs: &mut [Arc<RwLock<Storage>>],
3334 _layouts: &[Layout],
3335 params: &OpParams,
3336 ) -> Result<()> {
3337 if !inputs.is_empty() || outputs.len() != 1 {
3338 return Err(Error::Msg(format!(
3339 concat!(
3340 stringify!($name),
3341 ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3342 ),
3343 inputs.len(),
3344 outputs.len(),
3345 ))
3346 .bt());
3347 }
3348 let (mul, add) = match params {
3349 OpParams::Affine { mul, add } => (*mul, *add),
3350 other => {
3351 return Err(Error::Msg(format!(
3352 concat!(stringify!($name), ": expected OpParams::Affine, got {:?}"),
3353 other,
3354 ))
3355 .bt())
3356 }
3357 };
3358 let mut out_guard = write_storage(&outputs[0])?;
3359 let out_cpu = cpu_output(&mut out_guard)?;
3360 fuel_cpu_backend::byte_kernels::$kernel(out_cpu, mul, add)
3361 }
3362 };
3363}
3364
3365cpu_affine_inplace_wrapper!(inplace_affine_f32_cpu_wrapper, affine_inplace_f32, f32);
3366cpu_affine_inplace_wrapper!(inplace_affine_f64_cpu_wrapper, affine_inplace_f64, f64);
3367cpu_affine_inplace_wrapper!(
3368 inplace_affine_bf16_cpu_wrapper,
3369 affine_inplace_bf16,
3370 f64,
3371 half
3372);
3373cpu_affine_inplace_wrapper!(
3374 inplace_affine_f16_cpu_wrapper,
3375 affine_inplace_f16,
3376 f64,
3377 half
3378);
3379
3380macro_rules! cpu_clamp_inplace_wrapper {
3384 ($name:ident, $kernel:ident, $T:ty) => {
3385 pub(crate) fn $name(
3386 inputs: &[Arc<RwLock<Storage>>],
3387 outputs: &mut [Arc<RwLock<Storage>>],
3388 _layouts: &[Layout],
3389 params: &OpParams,
3390 ) -> Result<()> {
3391 if !inputs.is_empty() || outputs.len() != 1 {
3392 return Err(Error::Msg(format!(
3393 concat!(
3394 stringify!($name),
3395 ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3396 ),
3397 inputs.len(),
3398 outputs.len(),
3399 ))
3400 .bt());
3401 }
3402 let (min, max) = match params {
3403 OpParams::Clamp { min, max } => (*min as $T, *max as $T),
3404 other => {
3405 return Err(Error::Msg(format!(
3406 concat!(stringify!($name), ": expected OpParams::Clamp, got {:?}"),
3407 other,
3408 ))
3409 .bt())
3410 }
3411 };
3412 let mut out_guard = write_storage(&outputs[0])?;
3413 let out_cpu = cpu_output(&mut out_guard)?;
3414 fuel_cpu_backend::byte_kernels::$kernel(out_cpu, min, max)
3415 }
3416 };
3417 ($name:ident, $kernel:ident, $T:ty, half) => {
3418 pub(crate) fn $name(
3419 inputs: &[Arc<RwLock<Storage>>],
3420 outputs: &mut [Arc<RwLock<Storage>>],
3421 _layouts: &[Layout],
3422 params: &OpParams,
3423 ) -> Result<()> {
3424 if !inputs.is_empty() || outputs.len() != 1 {
3425 return Err(Error::Msg(format!(
3426 concat!(
3427 stringify!($name),
3428 ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3429 ),
3430 inputs.len(),
3431 outputs.len(),
3432 ))
3433 .bt());
3434 }
3435 let (min, max) = match params {
3436 OpParams::Clamp { min, max } => (*min, *max),
3437 other => {
3438 return Err(Error::Msg(format!(
3439 concat!(stringify!($name), ": expected OpParams::Clamp, got {:?}"),
3440 other,
3441 ))
3442 .bt())
3443 }
3444 };
3445 let mut out_guard = write_storage(&outputs[0])?;
3446 let out_cpu = cpu_output(&mut out_guard)?;
3447 fuel_cpu_backend::byte_kernels::$kernel(out_cpu, min, max)
3448 }
3449 };
3450}
3451
3452cpu_clamp_inplace_wrapper!(clamp_inplace_f32_cpu_wrapper, clamp_inplace_f32, f32);
3453cpu_clamp_inplace_wrapper!(clamp_inplace_f64_cpu_wrapper, clamp_inplace_f64, f64);
3454cpu_clamp_inplace_wrapper!(
3455 clamp_inplace_bf16_cpu_wrapper,
3456 clamp_inplace_bf16,
3457 f64,
3458 half
3459);
3460cpu_clamp_inplace_wrapper!(clamp_inplace_f16_cpu_wrapper, clamp_inplace_f16, f64, half);
3461
3462macro_rules! cpu_powi_inplace_wrapper {
3465 ($name:ident, $kernel:ident) => {
3466 pub(crate) fn $name(
3467 inputs: &[Arc<RwLock<Storage>>],
3468 outputs: &mut [Arc<RwLock<Storage>>],
3469 _layouts: &[Layout],
3470 params: &OpParams,
3471 ) -> Result<()> {
3472 if !inputs.is_empty() || outputs.len() != 1 {
3473 return Err(Error::Msg(format!(
3474 concat!(
3475 stringify!($name),
3476 ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3477 ),
3478 inputs.len(),
3479 outputs.len(),
3480 ))
3481 .bt());
3482 }
3483 let exp = match params {
3484 OpParams::PowI { exp } => *exp,
3485 other => {
3486 return Err(Error::Msg(format!(
3487 concat!(stringify!($name), ": expected OpParams::PowI, got {:?}"),
3488 other,
3489 ))
3490 .bt())
3491 }
3492 };
3493 let mut out_guard = write_storage(&outputs[0])?;
3494 let out_cpu = cpu_output(&mut out_guard)?;
3495 fuel_cpu_backend::byte_kernels::$kernel(out_cpu, exp)
3496 }
3497 };
3498}
3499
3500cpu_powi_inplace_wrapper!(powi_inplace_f32_cpu_wrapper, powi_inplace_f32);
3501cpu_powi_inplace_wrapper!(powi_inplace_f64_cpu_wrapper, powi_inplace_f64);
3502cpu_powi_inplace_wrapper!(powi_inplace_bf16_cpu_wrapper, powi_inplace_bf16);
3503cpu_powi_inplace_wrapper!(powi_inplace_f16_cpu_wrapper, powi_inplace_f16);
3504
3505macro_rules! cpu_unary_inplace_wrapper {
3510 ($name:ident, $kernel:ident) => {
3511 pub(crate) fn $name(
3512 inputs: &[Arc<RwLock<Storage>>],
3513 outputs: &mut [Arc<RwLock<Storage>>],
3514 _layouts: &[Layout],
3515 _params: &OpParams,
3516 ) -> Result<()> {
3517 if !inputs.is_empty() || outputs.len() != 1 {
3518 return Err(Error::Msg(format!(
3519 concat!(
3520 stringify!($name),
3521 ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3522 ),
3523 inputs.len(),
3524 outputs.len(),
3525 ))
3526 .bt());
3527 }
3528 let mut out_guard = write_storage(&outputs[0])?;
3529 let out_cpu = cpu_output(&mut out_guard)?;
3530 fuel_cpu_backend::byte_kernels::$kernel(out_cpu)
3531 }
3532 };
3533}
3534
3535cpu_unary_inplace_wrapper!(relu_inplace_f32_cpu_wrapper, relu_inplace_f32);
3536cpu_unary_inplace_wrapper!(silu_inplace_f32_cpu_wrapper, silu_inplace_f32);
3537cpu_unary_inplace_wrapper!(gelu_inplace_f32_cpu_wrapper, gelu_inplace_f32);
3538cpu_unary_inplace_wrapper!(tanh_inplace_f32_cpu_wrapper, tanh_inplace_f32);
3539cpu_unary_inplace_wrapper!(sigmoid_inplace_f32_cpu_wrapper, sigmoid_inplace_f32);
3540
3541cpu_unary_inplace_wrapper!(relu_inplace_f64_cpu_wrapper, relu_inplace_f64);
3542cpu_unary_inplace_wrapper!(silu_inplace_f64_cpu_wrapper, silu_inplace_f64);
3543cpu_unary_inplace_wrapper!(gelu_inplace_f64_cpu_wrapper, gelu_inplace_f64);
3544cpu_unary_inplace_wrapper!(tanh_inplace_f64_cpu_wrapper, tanh_inplace_f64);
3545cpu_unary_inplace_wrapper!(sigmoid_inplace_f64_cpu_wrapper, sigmoid_inplace_f64);
3546
3547cpu_unary_inplace_wrapper!(relu_inplace_bf16_cpu_wrapper, relu_inplace_bf16);
3548cpu_unary_inplace_wrapper!(silu_inplace_bf16_cpu_wrapper, silu_inplace_bf16);
3549cpu_unary_inplace_wrapper!(gelu_inplace_bf16_cpu_wrapper, gelu_inplace_bf16);
3550cpu_unary_inplace_wrapper!(tanh_inplace_bf16_cpu_wrapper, tanh_inplace_bf16);
3551cpu_unary_inplace_wrapper!(sigmoid_inplace_bf16_cpu_wrapper, sigmoid_inplace_bf16);
3552
3553cpu_unary_inplace_wrapper!(relu_inplace_f16_cpu_wrapper, relu_inplace_f16);
3554cpu_unary_inplace_wrapper!(silu_inplace_f16_cpu_wrapper, silu_inplace_f16);
3555cpu_unary_inplace_wrapper!(gelu_inplace_f16_cpu_wrapper, gelu_inplace_f16);
3556cpu_unary_inplace_wrapper!(tanh_inplace_f16_cpu_wrapper, tanh_inplace_f16);
3557cpu_unary_inplace_wrapper!(sigmoid_inplace_f16_cpu_wrapper, sigmoid_inplace_f16);
3558
3559cpu_unary_inplace_wrapper!(neg_inplace_f32_cpu_wrapper, neg_inplace_f32);
3563cpu_unary_inplace_wrapper!(neg_inplace_f64_cpu_wrapper, neg_inplace_f64);
3564cpu_unary_inplace_wrapper!(neg_inplace_bf16_cpu_wrapper, neg_inplace_bf16);
3565cpu_unary_inplace_wrapper!(neg_inplace_f16_cpu_wrapper, neg_inplace_f16);
3566
3567cpu_unary_inplace_wrapper!(abs_inplace_f32_cpu_wrapper, abs_inplace_f32);
3568cpu_unary_inplace_wrapper!(abs_inplace_f64_cpu_wrapper, abs_inplace_f64);
3569cpu_unary_inplace_wrapper!(abs_inplace_bf16_cpu_wrapper, abs_inplace_bf16);
3570cpu_unary_inplace_wrapper!(abs_inplace_f16_cpu_wrapper, abs_inplace_f16);
3571
3572cpu_unary_inplace_wrapper!(sqr_inplace_f32_cpu_wrapper, sqr_inplace_f32);
3573cpu_unary_inplace_wrapper!(sqr_inplace_f64_cpu_wrapper, sqr_inplace_f64);
3574cpu_unary_inplace_wrapper!(sqr_inplace_bf16_cpu_wrapper, sqr_inplace_bf16);
3575cpu_unary_inplace_wrapper!(sqr_inplace_f16_cpu_wrapper, sqr_inplace_f16);
3576
3577cpu_unary_inplace_wrapper!(sqrt_inplace_f32_cpu_wrapper, sqrt_inplace_f32);
3578cpu_unary_inplace_wrapper!(sqrt_inplace_f64_cpu_wrapper, sqrt_inplace_f64);
3579cpu_unary_inplace_wrapper!(sqrt_inplace_bf16_cpu_wrapper, sqrt_inplace_bf16);
3580cpu_unary_inplace_wrapper!(sqrt_inplace_f16_cpu_wrapper, sqrt_inplace_f16);
3581
3582cpu_unary_inplace_wrapper!(rsqrt_inplace_f32_cpu_wrapper, rsqrt_inplace_f32);
3583cpu_unary_inplace_wrapper!(rsqrt_inplace_f64_cpu_wrapper, rsqrt_inplace_f64);
3584cpu_unary_inplace_wrapper!(rsqrt_inplace_bf16_cpu_wrapper, rsqrt_inplace_bf16);
3585cpu_unary_inplace_wrapper!(rsqrt_inplace_f16_cpu_wrapper, rsqrt_inplace_f16);
3586
3587cpu_unary_inplace_wrapper!(recip_inplace_f32_cpu_wrapper, recip_inplace_f32);
3588cpu_unary_inplace_wrapper!(recip_inplace_f64_cpu_wrapper, recip_inplace_f64);
3589cpu_unary_inplace_wrapper!(recip_inplace_bf16_cpu_wrapper, recip_inplace_bf16);
3590cpu_unary_inplace_wrapper!(recip_inplace_f16_cpu_wrapper, recip_inplace_f16);
3591
3592cpu_unary_inplace_wrapper!(exp_inplace_f32_cpu_wrapper, exp_inplace_f32);
3593cpu_unary_inplace_wrapper!(exp_inplace_f64_cpu_wrapper, exp_inplace_f64);
3594cpu_unary_inplace_wrapper!(exp_inplace_bf16_cpu_wrapper, exp_inplace_bf16);
3595cpu_unary_inplace_wrapper!(exp_inplace_f16_cpu_wrapper, exp_inplace_f16);
3596
3597cpu_unary_inplace_wrapper!(log_inplace_f32_cpu_wrapper, log_inplace_f32);
3598cpu_unary_inplace_wrapper!(log_inplace_f64_cpu_wrapper, log_inplace_f64);
3599cpu_unary_inplace_wrapper!(log_inplace_bf16_cpu_wrapper, log_inplace_bf16);
3600cpu_unary_inplace_wrapper!(log_inplace_f16_cpu_wrapper, log_inplace_f16);
3601
3602cpu_unary_inplace_wrapper!(sin_inplace_f32_cpu_wrapper, sin_inplace_f32);
3603cpu_unary_inplace_wrapper!(sin_inplace_f64_cpu_wrapper, sin_inplace_f64);
3604cpu_unary_inplace_wrapper!(sin_inplace_bf16_cpu_wrapper, sin_inplace_bf16);
3605cpu_unary_inplace_wrapper!(sin_inplace_f16_cpu_wrapper, sin_inplace_f16);
3606
3607cpu_unary_inplace_wrapper!(cos_inplace_f32_cpu_wrapper, cos_inplace_f32);
3608cpu_unary_inplace_wrapper!(cos_inplace_f64_cpu_wrapper, cos_inplace_f64);
3609cpu_unary_inplace_wrapper!(cos_inplace_bf16_cpu_wrapper, cos_inplace_bf16);
3610cpu_unary_inplace_wrapper!(cos_inplace_f16_cpu_wrapper, cos_inplace_f16);
3611
3612cpu_unary_inplace_wrapper!(sign_inplace_f32_cpu_wrapper, sign_inplace_f32);
3613cpu_unary_inplace_wrapper!(sign_inplace_f64_cpu_wrapper, sign_inplace_f64);
3614cpu_unary_inplace_wrapper!(sign_inplace_bf16_cpu_wrapper, sign_inplace_bf16);
3615cpu_unary_inplace_wrapper!(sign_inplace_f16_cpu_wrapper, sign_inplace_f16);
3616
3617cpu_unary_inplace_wrapper!(floor_inplace_f32_cpu_wrapper, floor_inplace_f32);
3618cpu_unary_inplace_wrapper!(floor_inplace_f64_cpu_wrapper, floor_inplace_f64);
3619cpu_unary_inplace_wrapper!(floor_inplace_bf16_cpu_wrapper, floor_inplace_bf16);
3620cpu_unary_inplace_wrapper!(floor_inplace_f16_cpu_wrapper, floor_inplace_f16);
3621
3622cpu_unary_inplace_wrapper!(ceil_inplace_f32_cpu_wrapper, ceil_inplace_f32);
3623cpu_unary_inplace_wrapper!(ceil_inplace_f64_cpu_wrapper, ceil_inplace_f64);
3624cpu_unary_inplace_wrapper!(ceil_inplace_bf16_cpu_wrapper, ceil_inplace_bf16);
3625cpu_unary_inplace_wrapper!(ceil_inplace_f16_cpu_wrapper, ceil_inplace_f16);
3626
3627cpu_unary_inplace_wrapper!(round_inplace_f32_cpu_wrapper, round_inplace_f32);
3628cpu_unary_inplace_wrapper!(round_inplace_f64_cpu_wrapper, round_inplace_f64);
3629cpu_unary_inplace_wrapper!(round_inplace_bf16_cpu_wrapper, round_inplace_bf16);
3630cpu_unary_inplace_wrapper!(round_inplace_f16_cpu_wrapper, round_inplace_f16);
3631
3632cpu_unary_inplace_wrapper!(erf_inplace_f32_cpu_wrapper, erf_inplace_f32);
3633cpu_unary_inplace_wrapper!(erf_inplace_f64_cpu_wrapper, erf_inplace_f64);
3634cpu_unary_inplace_wrapper!(erf_inplace_bf16_cpu_wrapper, erf_inplace_bf16);
3635cpu_unary_inplace_wrapper!(erf_inplace_f16_cpu_wrapper, erf_inplace_f16);
3636
3637cpu_unary_inplace_wrapper!(gelu_erf_inplace_f32_cpu_wrapper, gelu_erf_inplace_f32);
3638cpu_unary_inplace_wrapper!(gelu_erf_inplace_f64_cpu_wrapper, gelu_erf_inplace_f64);
3639cpu_unary_inplace_wrapper!(gelu_erf_inplace_bf16_cpu_wrapper, gelu_erf_inplace_bf16);
3640cpu_unary_inplace_wrapper!(gelu_erf_inplace_f16_cpu_wrapper, gelu_erf_inplace_f16);
3641
3642pub(crate) fn clamp_elementwise_f32_cpu_wrapper(
3644 inputs: &[Arc<RwLock<Storage>>],
3645 outputs: &mut [Arc<RwLock<Storage>>],
3646 _layouts: &[Layout],
3647 params: &OpParams,
3648) -> Result<()> {
3649 if inputs.len() != 1 || outputs.len() != 1 {
3650 return Err(Error::Msg(format!(
3651 "clamp wrapper expects 1 input + 1 output, got {} + {}",
3652 inputs.len(),
3653 outputs.len(),
3654 ))
3655 .bt());
3656 }
3657 let (min, max) = match params {
3658 OpParams::Clamp { min, max } => (*min as f32, *max as f32),
3659 other => {
3660 return Err(Error::Msg(format!(
3661 "clamp wrapper expects OpParams::Clamp, got {other:?}",
3662 ))
3663 .bt());
3664 }
3665 };
3666 let in_guard = read_storage(&inputs[0])?;
3667 let mut out_guard = write_storage(&outputs[0])?;
3668 let in_cpu = cpu_input(&in_guard)?;
3669 let out_cpu = cpu_output(&mut out_guard)?;
3670 fuel_cpu_backend::byte_kernels::clamp_f32(in_cpu, out_cpu, min, max)
3671}
3672
3673pub(crate) fn powi_elementwise_f32_cpu_wrapper(
3675 inputs: &[Arc<RwLock<Storage>>],
3676 outputs: &mut [Arc<RwLock<Storage>>],
3677 _layouts: &[Layout],
3678 params: &OpParams,
3679) -> Result<()> {
3680 if inputs.len() != 1 || outputs.len() != 1 {
3681 return Err(Error::Msg(format!(
3682 "powi wrapper expects 1 input + 1 output, got {} + {}",
3683 inputs.len(),
3684 outputs.len(),
3685 ))
3686 .bt());
3687 }
3688 let exp = match params {
3689 OpParams::PowI { exp } => *exp,
3690 other => {
3691 return Err(Error::Msg(format!(
3692 "powi wrapper expects OpParams::PowI, got {other:?}",
3693 ))
3694 .bt());
3695 }
3696 };
3697 let in_guard = read_storage(&inputs[0])?;
3698 let mut out_guard = write_storage(&outputs[0])?;
3699 let in_cpu = cpu_input(&in_guard)?;
3700 let out_cpu = cpu_output(&mut out_guard)?;
3701 fuel_cpu_backend::byte_kernels::powi_f32(in_cpu, out_cpu, exp)
3702}
3703
3704macro_rules! cpu_powi_backward_wrapper {
3707 ($wrapper:ident, $kernel:path, $op_name:literal) => {
3708 pub(crate) fn $wrapper(
3711 inputs: &[Arc<RwLock<Storage>>],
3712 outputs: &mut [Arc<RwLock<Storage>>],
3713 _layouts: &[Layout],
3714 params: &OpParams,
3715 ) -> Result<()> {
3716 if inputs.len() != 2 || outputs.len() != 1 {
3717 return Err(Error::Msg(format!(
3718 "{} wrapper expects 2 inputs + 1 output, got {} + {}",
3719 $op_name,
3720 inputs.len(),
3721 outputs.len(),
3722 ))
3723 .bt());
3724 }
3725 let exp = match params {
3726 OpParams::PowI { exp } => *exp,
3727 other => {
3728 return Err(Error::Msg(format!(
3729 "{} wrapper expects OpParams::PowI, got {other:?}",
3730 $op_name,
3731 ))
3732 .bt())
3733 }
3734 };
3735 let x_guard = read_storage(&inputs[0])?;
3736 let up_guard = read_storage(&inputs[1])?;
3737 let mut out_guard = write_storage(&outputs[0])?;
3738 let x_cpu = cpu_input(&x_guard)?;
3739 let up_cpu = cpu_input(&up_guard)?;
3740 let out_cpu = cpu_output(&mut out_guard)?;
3741 $kernel(x_cpu, up_cpu, out_cpu, exp)
3742 }
3743 };
3744}
3745
3746cpu_powi_backward_wrapper!(
3747 powi_backward_f32_cpu_wrapper,
3748 fuel_cpu_backend::byte_kernels::powi_backward_f32,
3749 "powi_backward_f32"
3750);
3751cpu_powi_backward_wrapper!(
3752 powi_backward_f64_cpu_wrapper,
3753 fuel_cpu_backend::byte_kernels::powi_backward_f64,
3754 "powi_backward_f64"
3755);
3756cpu_powi_backward_wrapper!(
3757 powi_backward_bf16_cpu_wrapper,
3758 fuel_cpu_backend::byte_kernels::powi_backward_bf16,
3759 "powi_backward_bf16"
3760);
3761cpu_powi_backward_wrapper!(
3762 powi_backward_f16_cpu_wrapper,
3763 fuel_cpu_backend::byte_kernels::powi_backward_f16,
3764 "powi_backward_f16"
3765);
3766
3767macro_rules! cpu_reduce_wrapper {
3772 ($wrapper:ident, $kernel:path, $op_name:literal) => {
3773 pub(crate) fn $wrapper(
3774 inputs: &[Arc<RwLock<Storage>>],
3775 outputs: &mut [Arc<RwLock<Storage>>],
3776 layouts: &[Layout],
3777 params: &OpParams,
3778 ) -> Result<()> {
3779 if inputs.len() != 1 {
3780 return Err(Error::Msg(format!(
3781 "{} wrapper expects 1 input, got {}",
3782 $op_name,
3783 inputs.len(),
3784 ))
3785 .bt());
3786 }
3787 if outputs.len() != 1 {
3788 return Err(Error::Msg(format!(
3789 "{} wrapper expects 1 output, got {}",
3790 $op_name,
3791 outputs.len(),
3792 ))
3793 .bt());
3794 }
3795 let dims = match params {
3796 OpParams::Reduce { dims, .. } => dims,
3797 other => {
3798 return Err(Error::Msg(format!(
3799 "{} wrapper expects OpParams::Reduce, got {:?}",
3800 $op_name, other,
3801 ))
3802 .bt())
3803 }
3804 };
3805 let input_layout = layouts.first().ok_or_else(|| {
3806 Error::Msg(format!(
3807 "{} wrapper: layouts empty (executor must pass input layout at [0])",
3808 $op_name,
3809 ))
3810 .bt()
3811 })?;
3812 let input_shape: &[usize] = input_layout.shape().dims();
3819 let in_guard = read_storage(&inputs[0])?;
3820 let mut out_guard = write_storage(&outputs[0])?;
3821 let in_cpu = cpu_input(&in_guard)?;
3822 let out_cpu = cpu_output(&mut out_guard)?;
3823 $kernel(in_cpu, out_cpu, input_shape, dims)
3824 }
3825 };
3826}
3827
3828cpu_reduce_wrapper!(
3829 sum_reduce_f32_cpu_wrapper,
3830 fuel_cpu_backend::byte_kernels::sum_reduce_f32,
3831 "sum_reduce"
3832);
3833cpu_reduce_wrapper!(
3834 max_reduce_f32_cpu_wrapper,
3835 fuel_cpu_backend::byte_kernels::max_reduce_f32,
3836 "max_reduce"
3837);
3838cpu_reduce_wrapper!(
3839 min_reduce_f32_cpu_wrapper,
3840 fuel_cpu_backend::byte_kernels::min_reduce_f32,
3841 "min_reduce"
3842);
3843cpu_reduce_wrapper!(
3844 mean_reduce_f32_cpu_wrapper,
3845 fuel_cpu_backend::byte_kernels::mean_reduce_f32,
3846 "mean_reduce"
3847);
3848cpu_reduce_wrapper!(
3849 sum_reduce_f64_cpu_wrapper,
3850 fuel_cpu_backend::byte_kernels::sum_reduce_f64,
3851 "sum_reduce"
3852);
3853cpu_reduce_wrapper!(
3854 max_reduce_f64_cpu_wrapper,
3855 fuel_cpu_backend::byte_kernels::max_reduce_f64,
3856 "max_reduce"
3857);
3858cpu_reduce_wrapper!(
3859 min_reduce_f64_cpu_wrapper,
3860 fuel_cpu_backend::byte_kernels::min_reduce_f64,
3861 "min_reduce"
3862);
3863cpu_reduce_wrapper!(
3864 mean_reduce_f64_cpu_wrapper,
3865 fuel_cpu_backend::byte_kernels::mean_reduce_f64,
3866 "mean_reduce"
3867);
3868
3869cpu_reduce_wrapper!(
3870 sum_reduce_bf16_cpu_wrapper,
3871 fuel_cpu_backend::byte_kernels::sum_reduce_bf16,
3872 "sum_reduce"
3873);
3874cpu_reduce_wrapper!(
3875 max_reduce_bf16_cpu_wrapper,
3876 fuel_cpu_backend::byte_kernels::max_reduce_bf16,
3877 "max_reduce"
3878);
3879cpu_reduce_wrapper!(
3880 min_reduce_bf16_cpu_wrapper,
3881 fuel_cpu_backend::byte_kernels::min_reduce_bf16,
3882 "min_reduce"
3883);
3884cpu_reduce_wrapper!(
3885 mean_reduce_bf16_cpu_wrapper,
3886 fuel_cpu_backend::byte_kernels::mean_reduce_bf16,
3887 "mean_reduce"
3888);
3889
3890cpu_reduce_wrapper!(
3891 sum_reduce_f16_cpu_wrapper,
3892 fuel_cpu_backend::byte_kernels::sum_reduce_f16,
3893 "sum_reduce"
3894);
3895cpu_reduce_wrapper!(
3896 max_reduce_f16_cpu_wrapper,
3897 fuel_cpu_backend::byte_kernels::max_reduce_f16,
3898 "max_reduce"
3899);
3900cpu_reduce_wrapper!(
3901 min_reduce_f16_cpu_wrapper,
3902 fuel_cpu_backend::byte_kernels::min_reduce_f16,
3903 "min_reduce"
3904);
3905cpu_reduce_wrapper!(
3906 mean_reduce_f16_cpu_wrapper,
3907 fuel_cpu_backend::byte_kernels::mean_reduce_f16,
3908 "mean_reduce"
3909);
3910
3911macro_rules! cpu_cast_wrapper {
3917 (
3918 $wrapper:ident,
3919 $target_dtype:expr,
3920 $target_name:literal,
3921 { $( $source:pat => $kernel:path ),+ $(,)? } $(,)?
3922 ) => {
3923 pub(crate) fn $wrapper(
3926 inputs: &[Arc<RwLock<Storage>>],
3927 outputs: &mut [Arc<RwLock<Storage>>],
3928 _layouts: &[Layout],
3929 _params: &OpParams,
3930 ) -> Result<()> {
3931 if inputs.len() != 1 {
3932 return Err(Error::Msg(format!(
3933 "cast→{} wrapper expects 1 input, got {}",
3934 $target_name,
3935 inputs.len(),
3936 ))
3937 .bt());
3938 }
3939 if outputs.len() != 1 {
3940 return Err(Error::Msg(format!(
3941 "cast→{} wrapper expects 1 output, got {}",
3942 $target_name,
3943 outputs.len(),
3944 ))
3945 .bt());
3946 }
3947 let in_guard = read_storage(&inputs[0])?;
3948 let mut out_guard = write_storage(&outputs[0])?;
3949 let source_dtype = in_guard.dtype;
3950 let in_cpu = cpu_input(&in_guard)?;
3951 let out_cpu = cpu_output(&mut out_guard)?;
3952 match source_dtype {
3953 $( $source => $kernel(in_cpu, out_cpu), )+
3954 other => Err(Error::Msg(format!(
3955 "cast→{}: source dtype {:?} not yet wired (Phase C \
3956 extends the cast matrix as needed)",
3957 $target_name, other,
3958 ))
3959 .bt()),
3960 }
3961 }
3962 };
3963}
3964
3965macro_rules! cpu_conv2d_wrapper {
3971 ($name:ident, $kernel:path) => {
3972 pub(crate) fn $name(
3973 inputs: &[Arc<RwLock<Storage>>],
3974 outputs: &mut [Arc<RwLock<Storage>>],
3975 _layouts: &[Layout],
3976 params: &OpParams,
3977 ) -> Result<()> {
3978 if inputs.len() != 2 && inputs.len() != 3 {
3979 return Err(Error::Msg(format!(
3980 "conv2d wrapper expects 2 or 3 inputs (x, weight, [bias]), got {}",
3981 inputs.len(),
3982 ))
3983 .bt());
3984 }
3985 if outputs.len() != 1 {
3986 return Err(Error::Msg(format!(
3987 "conv2d wrapper expects 1 output, got {}",
3988 outputs.len(),
3989 ))
3990 .bt());
3991 }
3992 let (x_shape, w_shape, out_shape, stride, padding, dilation, groups) = match params {
3993 OpParams::Conv2D {
3994 x_shape,
3995 w_shape,
3996 out_shape,
3997 stride,
3998 padding,
3999 dilation,
4000 groups,
4001 } => (
4002 *x_shape, *w_shape, *out_shape, *stride, *padding, *dilation, *groups,
4003 ),
4004 other => {
4005 return Err(Error::Msg(format!(
4006 "conv2d wrapper expects OpParams::Conv2D, got {other:?}",
4007 ))
4008 .bt())
4009 }
4010 };
4011 let x_guard = read_storage(&inputs[0])?;
4012 let w_guard = read_storage(&inputs[1])?;
4013 let bias_guard = match inputs.get(2) {
4014 Some(arc) => Some(read_storage(arc)?),
4015 None => None,
4016 };
4017 let mut out_guard = write_storage(&outputs[0])?;
4018 let x_cpu = cpu_input(&x_guard)?;
4019 let w_cpu = cpu_input(&w_guard)?;
4020 let bias_cpu = match &bias_guard {
4021 Some(g) => Some(cpu_input(g)?),
4022 None => None,
4023 };
4024 let out_cpu = cpu_output(&mut out_guard)?;
4025 $kernel(
4026 x_cpu, w_cpu, bias_cpu, out_cpu, x_shape, w_shape, out_shape, stride, padding,
4027 dilation, groups,
4028 )
4029 }
4030 };
4031}
4032
4033cpu_conv2d_wrapper!(
4034 conv2d_f32_cpu_wrapper,
4035 fuel_cpu_backend::byte_kernels::conv2d_f32
4036);
4037cpu_conv2d_wrapper!(
4038 conv2d_f64_cpu_wrapper,
4039 fuel_cpu_backend::byte_kernels::conv2d_f64
4040);
4041cpu_conv2d_wrapper!(
4042 conv2d_bf16_cpu_wrapper,
4043 fuel_cpu_backend::byte_kernels::conv2d_bf16
4044);
4045cpu_conv2d_wrapper!(
4046 conv2d_f16_cpu_wrapper,
4047 fuel_cpu_backend::byte_kernels::conv2d_f16
4048);
4049
4050macro_rules! cpu_conv_transpose2d_wrapper {
4056 ($name:ident, $kernel:path) => {
4057 pub(crate) fn $name(
4058 inputs: &[Arc<RwLock<Storage>>],
4059 outputs: &mut [Arc<RwLock<Storage>>],
4060 _layouts: &[Layout],
4061 params: &OpParams,
4062 ) -> Result<()> {
4063 if inputs.len() != 2 && inputs.len() != 3 {
4064 return Err(Error::Msg(format!(
4065 "conv_transpose2d wrapper expects 2 or 3 inputs (x, weight, [bias]), got {}",
4066 inputs.len(),
4067 ))
4068 .bt());
4069 }
4070 if outputs.len() != 1 {
4071 return Err(Error::Msg(format!(
4072 "conv_transpose2d wrapper expects 1 output, got {}",
4073 outputs.len(),
4074 ))
4075 .bt());
4076 }
4077 let (x_shape, w_shape, out_shape, stride, padding, dilation, groups) =
4078 match params {
4079 OpParams::ConvTranspose2D {
4080 x_shape,
4081 w_shape,
4082 out_shape,
4083 stride,
4084 padding,
4085 output_padding: _,
4086 dilation,
4087 groups,
4088 } => (
4089 *x_shape, *w_shape, *out_shape, *stride, *padding, *dilation, *groups,
4090 ),
4091 other => return Err(Error::Msg(format!(
4092 "conv_transpose2d wrapper expects OpParams::ConvTranspose2D, got {other:?}",
4093 ))
4094 .bt()),
4095 };
4096 let x_guard = read_storage(&inputs[0])?;
4097 let w_guard = read_storage(&inputs[1])?;
4098 let bias_guard = match inputs.get(2) {
4099 Some(arc) => Some(read_storage(arc)?),
4100 None => None,
4101 };
4102 let mut out_guard = write_storage(&outputs[0])?;
4103 let x_cpu = cpu_input(&x_guard)?;
4104 let w_cpu = cpu_input(&w_guard)?;
4105 let bias_cpu = match &bias_guard {
4106 Some(g) => Some(cpu_input(g)?),
4107 None => None,
4108 };
4109 let out_cpu = cpu_output(&mut out_guard)?;
4110 $kernel(
4111 x_cpu, w_cpu, bias_cpu, out_cpu, x_shape, w_shape, out_shape, stride, padding,
4112 dilation, groups,
4113 )
4114 }
4115 };
4116}
4117
4118cpu_conv_transpose2d_wrapper!(
4119 conv_transpose2d_f32_cpu_wrapper,
4120 fuel_cpu_backend::byte_kernels::conv_transpose2d_f32
4121);
4122cpu_conv_transpose2d_wrapper!(
4123 conv_transpose2d_f64_cpu_wrapper,
4124 fuel_cpu_backend::byte_kernels::conv_transpose2d_f64
4125);
4126cpu_conv_transpose2d_wrapper!(
4127 conv_transpose2d_bf16_cpu_wrapper,
4128 fuel_cpu_backend::byte_kernels::conv_transpose2d_bf16
4129);
4130cpu_conv_transpose2d_wrapper!(
4131 conv_transpose2d_f16_cpu_wrapper,
4132 fuel_cpu_backend::byte_kernels::conv_transpose2d_f16
4133);
4134
4135macro_rules! cpu_reduce_sum_to_wrapper {
4140 ($name:ident, $kernel:path) => {
4141 pub(crate) fn $name(
4142 inputs: &[Arc<RwLock<Storage>>],
4143 outputs: &mut [Arc<RwLock<Storage>>],
4144 _layouts: &[Layout],
4145 params: &OpParams,
4146 ) -> Result<()> {
4147 if inputs.len() != 1 {
4148 return Err(Error::Msg(format!(
4149 "reduce_sum_to wrapper expects 1 input, got {}",
4150 inputs.len(),
4151 ))
4152 .bt());
4153 }
4154 if outputs.len() != 1 {
4155 return Err(Error::Msg(format!(
4156 "reduce_sum_to wrapper expects 1 output, got {}",
4157 outputs.len(),
4158 ))
4159 .bt());
4160 }
4161 let (input_shape, output_shape) = match params {
4162 OpParams::ReduceSumTo {
4163 input_shape,
4164 output_shape,
4165 } => (input_shape.clone(), output_shape.clone()),
4166 other => {
4167 return Err(Error::Msg(format!(
4168 "reduce_sum_to wrapper expects OpParams::ReduceSumTo, got {other:?}",
4169 ))
4170 .bt())
4171 }
4172 };
4173 let in_guard = read_storage(&inputs[0])?;
4174 let mut out_guard = write_storage(&outputs[0])?;
4175 let in_cpu = cpu_input(&in_guard)?;
4176 let out_cpu = cpu_output(&mut out_guard)?;
4177 $kernel(in_cpu, out_cpu, &input_shape, &output_shape)
4178 }
4179 };
4180}
4181
4182cpu_reduce_sum_to_wrapper!(
4183 reduce_sum_to_f32_cpu_wrapper,
4184 fuel_cpu_backend::byte_kernels::reduce_sum_to_f32
4185);
4186cpu_reduce_sum_to_wrapper!(
4187 reduce_sum_to_f64_cpu_wrapper,
4188 fuel_cpu_backend::byte_kernels::reduce_sum_to_f64
4189);
4190cpu_reduce_sum_to_wrapper!(
4191 reduce_sum_to_bf16_cpu_wrapper,
4192 fuel_cpu_backend::byte_kernels::reduce_sum_to_bf16
4193);
4194cpu_reduce_sum_to_wrapper!(
4195 reduce_sum_to_f16_cpu_wrapper,
4196 fuel_cpu_backend::byte_kernels::reduce_sum_to_f16
4197);
4198
4199macro_rules! cpu_reduce_max_to_wrapper {
4204 ($name:ident, $kernel:path) => {
4205 pub(crate) fn $name(
4206 inputs: &[Arc<RwLock<Storage>>],
4207 outputs: &mut [Arc<RwLock<Storage>>],
4208 _layouts: &[Layout],
4209 params: &OpParams,
4210 ) -> Result<()> {
4211 if inputs.len() != 1 {
4212 return Err(Error::Msg(format!(
4213 "reduce_max_to wrapper expects 1 input, got {}",
4214 inputs.len(),
4215 ))
4216 .bt());
4217 }
4218 if outputs.len() != 1 {
4219 return Err(Error::Msg(format!(
4220 "reduce_max_to wrapper expects 1 output, got {}",
4221 outputs.len(),
4222 ))
4223 .bt());
4224 }
4225 let (input_shape, output_shape) = match params {
4226 OpParams::ReduceMaxTo {
4227 input_shape,
4228 output_shape,
4229 } => (input_shape.clone(), output_shape.clone()),
4230 other => {
4231 return Err(Error::Msg(format!(
4232 "reduce_max_to wrapper expects OpParams::ReduceMaxTo, got {other:?}",
4233 ))
4234 .bt())
4235 }
4236 };
4237 let in_guard = read_storage(&inputs[0])?;
4238 let mut out_guard = write_storage(&outputs[0])?;
4239 let in_cpu = cpu_input(&in_guard)?;
4240 let out_cpu = cpu_output(&mut out_guard)?;
4241 $kernel(in_cpu, out_cpu, &input_shape, &output_shape)
4242 }
4243 };
4244}
4245
4246cpu_reduce_max_to_wrapper!(
4247 reduce_max_to_f32_cpu_wrapper,
4248 fuel_cpu_backend::byte_kernels::reduce_max_to_f32
4249);
4250cpu_reduce_max_to_wrapper!(
4251 reduce_max_to_f64_cpu_wrapper,
4252 fuel_cpu_backend::byte_kernels::reduce_max_to_f64
4253);
4254cpu_reduce_max_to_wrapper!(
4255 reduce_max_to_bf16_cpu_wrapper,
4256 fuel_cpu_backend::byte_kernels::reduce_max_to_bf16
4257);
4258cpu_reduce_max_to_wrapper!(
4259 reduce_max_to_f16_cpu_wrapper,
4260 fuel_cpu_backend::byte_kernels::reduce_max_to_f16
4261);
4262
4263macro_rules! cpu_fused_linear_wrapper {
4266 ($wrapper:ident, $kernel:path) => {
4267 pub(crate) fn $wrapper(
4270 inputs: &[Arc<RwLock<Storage>>],
4271 outputs: &mut [Arc<RwLock<Storage>>],
4272 _layouts: &[Layout],
4273 params: &OpParams,
4274 ) -> Result<()> {
4275 if inputs.len() != 3 {
4276 return Err(Error::Msg(format!(
4277 "fused_linear wrapper expects 3 inputs (lhs, rhs, bias), got {}",
4278 inputs.len(),
4279 ))
4280 .bt());
4281 }
4282 if outputs.len() != 1 {
4283 return Err(Error::Msg(format!(
4284 "fused_linear wrapper expects 1 output, got {}",
4285 outputs.len(),
4286 ))
4287 .bt());
4288 }
4289 let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
4290 OpParams::Matmul {
4291 lhs_batch_dims,
4292 rhs_batch_dims,
4293 m,
4294 n,
4295 k,
4296 ..
4297 } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k),
4298 other => {
4299 return Err(Error::Msg(format!(
4300 "fused_linear wrapper expects OpParams::Matmul, got {other:?}",
4301 ))
4302 .bt())
4303 }
4304 };
4305 let lhs_guard = read_storage(&inputs[0])?;
4306 let rhs_guard = read_storage(&inputs[1])?;
4307 let bias_guard = read_storage(&inputs[2])?;
4308 let mut out_guard = write_storage(&outputs[0])?;
4309 let lhs_cpu = cpu_input(&lhs_guard)?;
4310 let rhs_cpu = cpu_input(&rhs_guard)?;
4311 let bias_cpu = cpu_input(&bias_guard)?;
4312 let out_cpu = cpu_output(&mut out_guard)?;
4313 $kernel(
4314 lhs_cpu,
4315 rhs_cpu,
4316 bias_cpu,
4317 out_cpu,
4318 lhs_batch_dims,
4319 rhs_batch_dims,
4320 m,
4321 n,
4322 k,
4323 )
4324 }
4325 };
4326}
4327
4328cpu_fused_linear_wrapper!(
4329 fused_linear_f32_cpu_wrapper,
4330 fuel_cpu_backend::byte_kernels::fused_linear_f32
4331);
4332cpu_fused_linear_wrapper!(
4333 fused_linear_f64_cpu_wrapper,
4334 fuel_cpu_backend::byte_kernels::fused_linear_f64
4335);
4336cpu_fused_linear_wrapper!(
4337 fused_linear_bf16_cpu_wrapper,
4338 fuel_cpu_backend::byte_kernels::fused_linear_bf16
4339);
4340cpu_fused_linear_wrapper!(
4341 fused_linear_f16_cpu_wrapper,
4342 fuel_cpu_backend::byte_kernels::fused_linear_f16
4343);
4344
4345macro_rules! cpu_fused_softmax_cross_entropy_wrapper {
4352 ($wrapper:ident, $kernel:path) => {
4353 pub(crate) fn $wrapper(
4354 inputs: &[Arc<RwLock<Storage>>],
4355 outputs: &mut [Arc<RwLock<Storage>>],
4356 _layouts: &[Layout],
4357 params: &OpParams,
4358 ) -> Result<()> {
4359 if inputs.len() != 2 {
4360 return Err(Error::Msg(format!(
4361 "fused_softmax_cross_entropy wrapper expects 2 inputs (logits, targets), got {}",
4362 inputs.len(),
4363 ))
4364 .bt());
4365 }
4366 if outputs.len() != 1 {
4367 return Err(Error::Msg(format!(
4368 "fused_softmax_cross_entropy wrapper expects 1 output, got {}",
4369 outputs.len(),
4370 ))
4371 .bt());
4372 }
4373 let (n_rows, vocab, reduction, ignore_index) = match params {
4374 OpParams::FusedSoftmaxCrossEntropy {
4375 n_rows, vocab, reduction, ignore_index,
4376 } => (*n_rows, *vocab, *reduction, *ignore_index),
4377 other => {
4378 return Err(Error::Msg(format!(
4379 "fused_softmax_cross_entropy wrapper expects \
4380 OpParams::FusedSoftmaxCrossEntropy, got {other:?}",
4381 ))
4382 .bt());
4383 }
4384 };
4385 let reduction_tag = match reduction {
4386 fuel_graph::registry::Reduction::Mean => fuel_cpu_backend::byte_kernels::REDUCTION_MEAN,
4387 fuel_graph::registry::Reduction::Sum => fuel_cpu_backend::byte_kernels::REDUCTION_SUM,
4388 fuel_graph::registry::Reduction::None => fuel_cpu_backend::byte_kernels::REDUCTION_NONE,
4389 };
4390 let logits_guard = read_storage(&inputs[0])?;
4391 let targets_guard = read_storage(&inputs[1])?;
4392 let mut out_guard = write_storage(&outputs[0])?;
4393 let logits_cpu = cpu_input(&logits_guard)?;
4394 let targets_cpu = cpu_input(&targets_guard)?;
4395 let out_cpu = cpu_output(&mut out_guard)?;
4396 $kernel(
4397 logits_cpu, targets_cpu, out_cpu,
4398 n_rows, vocab, reduction_tag, ignore_index,
4399 )
4400 }
4401 };
4402}
4403
4404cpu_fused_softmax_cross_entropy_wrapper!(
4405 fused_softmax_cross_entropy_f32_cpu_wrapper,
4406 fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_f32
4407);
4408cpu_fused_softmax_cross_entropy_wrapper!(
4409 fused_softmax_cross_entropy_f64_cpu_wrapper,
4410 fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_f64
4411);
4412cpu_fused_softmax_cross_entropy_wrapper!(
4413 fused_softmax_cross_entropy_bf16_cpu_wrapper,
4414 fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_bf16
4415);
4416cpu_fused_softmax_cross_entropy_wrapper!(
4417 fused_softmax_cross_entropy_f16_cpu_wrapper,
4418 fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_f16
4419);
4420
4421macro_rules! cpu_causal_conv1d_wrapper {
4426 ($wrapper:ident, $kernel:path) => {
4427 pub(crate) fn $wrapper(
4428 inputs: &[Arc<RwLock<Storage>>],
4429 outputs: &mut [Arc<RwLock<Storage>>],
4430 _layouts: &[Layout],
4431 params: &OpParams,
4432 ) -> Result<()> {
4433 if inputs.len() != 3 {
4434 return Err(Error::Msg(format!(
4435 "causal_conv1d wrapper expects 3 inputs (x, weight, bias), got {}",
4436 inputs.len(),
4437 ))
4438 .bt());
4439 }
4440 if outputs.len() != 1 {
4441 return Err(Error::Msg(format!(
4442 "causal_conv1d wrapper expects 1 output, got {}",
4443 outputs.len(),
4444 ))
4445 .bt());
4446 }
4447 let (batch, channels, seq_in, seq_out, kernel, use_silu) = match params {
4448 OpParams::CausalConv1d {
4449 batch,
4450 channels,
4451 seq_in,
4452 seq_out,
4453 kernel,
4454 use_silu,
4455 } => (*batch, *channels, *seq_in, *seq_out, *kernel, *use_silu),
4456 other => {
4457 return Err(Error::Msg(format!(
4458 "causal_conv1d wrapper expects OpParams::CausalConv1d, got {other:?}",
4459 ))
4460 .bt());
4461 }
4462 };
4463 let x_guard = read_storage(&inputs[0])?;
4464 let w_guard = read_storage(&inputs[1])?;
4465 let bias_guard = read_storage(&inputs[2])?;
4466 let mut out_guard = write_storage(&outputs[0])?;
4467 let x_cpu = cpu_input(&x_guard)?;
4468 let w_cpu = cpu_input(&w_guard)?;
4469 let bias_cpu = cpu_input(&bias_guard)?;
4470 let out_cpu = cpu_output(&mut out_guard)?;
4471 $kernel(
4472 x_cpu, w_cpu, bias_cpu, out_cpu, batch, channels, seq_in, seq_out, kernel, use_silu,
4473 )
4474 }
4475 };
4476}
4477
4478cpu_causal_conv1d_wrapper!(
4479 causal_conv1d_f32_cpu_wrapper,
4480 fuel_cpu_backend::byte_kernels::causal_conv1d_f32
4481);
4482cpu_causal_conv1d_wrapper!(
4483 causal_conv1d_f64_cpu_wrapper,
4484 fuel_cpu_backend::byte_kernels::causal_conv1d_f64
4485);
4486cpu_causal_conv1d_wrapper!(
4487 causal_conv1d_bf16_cpu_wrapper,
4488 fuel_cpu_backend::byte_kernels::causal_conv1d_bf16
4489);
4490cpu_causal_conv1d_wrapper!(
4491 causal_conv1d_f16_cpu_wrapper,
4492 fuel_cpu_backend::byte_kernels::causal_conv1d_f16
4493);
4494
4495macro_rules! cpu_selective_scan_wrapper {
4500 ($wrapper:ident, $kernel:path) => {
4501 pub(crate) fn $wrapper(
4502 inputs: &[Arc<RwLock<Storage>>],
4503 outputs: &mut [Arc<RwLock<Storage>>],
4504 _layouts: &[Layout],
4505 params: &OpParams,
4506 ) -> Result<()> {
4507 if inputs.len() != 5 {
4508 return Err(Error::Msg(format!(
4509 "selective_scan wrapper expects 5 inputs (u, delta, a, b, c), got {}",
4510 inputs.len(),
4511 ))
4512 .bt());
4513 }
4514 if outputs.len() != 1 {
4515 return Err(Error::Msg(format!(
4516 "selective_scan wrapper expects 1 output, got {}",
4517 outputs.len(),
4518 ))
4519 .bt());
4520 }
4521 let (batch, seqlen, dim, dstate, delta_softplus) = match params {
4522 OpParams::SelectiveScan {
4523 batch,
4524 seqlen,
4525 dim,
4526 dstate,
4527 delta_softplus,
4528 } => (*batch, *seqlen, *dim, *dstate, *delta_softplus),
4529 other => {
4530 return Err(Error::Msg(format!(
4531 "selective_scan wrapper expects OpParams::SelectiveScan, got {other:?}",
4532 ))
4533 .bt());
4534 }
4535 };
4536 let u_guard = read_storage(&inputs[0])?;
4537 let delta_guard = read_storage(&inputs[1])?;
4538 let a_guard = read_storage(&inputs[2])?;
4539 let b_guard = read_storage(&inputs[3])?;
4540 let c_guard = read_storage(&inputs[4])?;
4541 let mut out_guard = write_storage(&outputs[0])?;
4542 let u_cpu = cpu_input(&u_guard)?;
4543 let delta_cpu = cpu_input(&delta_guard)?;
4544 let a_cpu = cpu_input(&a_guard)?;
4545 let b_cpu = cpu_input(&b_guard)?;
4546 let c_cpu = cpu_input(&c_guard)?;
4547 let out_cpu = cpu_output(&mut out_guard)?;
4548 $kernel(
4549 u_cpu,
4550 delta_cpu,
4551 a_cpu,
4552 b_cpu,
4553 c_cpu,
4554 out_cpu,
4555 batch,
4556 seqlen,
4557 dim,
4558 dstate,
4559 delta_softplus,
4560 )
4561 }
4562 };
4563}
4564
4565cpu_selective_scan_wrapper!(
4566 selective_scan_f32_cpu_wrapper,
4567 fuel_cpu_backend::byte_kernels::selective_scan_f32
4568);
4569cpu_selective_scan_wrapper!(
4570 selective_scan_f64_cpu_wrapper,
4571 fuel_cpu_backend::byte_kernels::selective_scan_f64
4572);
4573cpu_selective_scan_wrapper!(
4574 selective_scan_bf16_cpu_wrapper,
4575 fuel_cpu_backend::byte_kernels::selective_scan_bf16
4576);
4577cpu_selective_scan_wrapper!(
4578 selective_scan_f16_cpu_wrapper,
4579 fuel_cpu_backend::byte_kernels::selective_scan_f16
4580);
4581
4582macro_rules! cpu_nonzero_indices_wrapper {
4589 ($wrapper:ident, $kernel:path) => {
4590 pub(crate) fn $wrapper(
4591 inputs: &[Arc<RwLock<Storage>>],
4592 outputs: &mut [Arc<RwLock<Storage>>],
4593 _layouts: &[Layout],
4594 params: &OpParams,
4595 ) -> Result<()> {
4596 if inputs.len() != 1 {
4597 return Err(Error::Msg(format!(
4598 "nonzero_indices wrapper expects 1 input, got {}",
4599 inputs.len(),
4600 ))
4601 .bt());
4602 }
4603 if outputs.len() != 1 {
4604 return Err(Error::Msg(format!(
4605 "nonzero_indices wrapper expects 1 output, got {}",
4606 outputs.len(),
4607 ))
4608 .bt());
4609 }
4610 let capacity = match params {
4611 OpParams::NonZeroIndices { capacity, .. } => *capacity,
4612 other => {
4613 return Err(Error::Msg(format!(
4614 "nonzero_indices wrapper expects OpParams::NonZeroIndices, got {other:?}",
4615 ))
4616 .bt());
4617 }
4618 };
4619 let x_guard = read_storage(&inputs[0])?;
4620 let mut out_guard = write_storage(&outputs[0])?;
4621 let x_cpu = cpu_input(&x_guard)?;
4622 let out_cpu = cpu_output(&mut out_guard)?;
4623 $kernel(x_cpu, out_cpu, capacity)
4624 }
4625 };
4626}
4627
4628cpu_nonzero_indices_wrapper!(
4629 nonzero_indices_f32_cpu_wrapper,
4630 fuel_cpu_backend::byte_kernels::nonzero_indices_f32
4631);
4632cpu_nonzero_indices_wrapper!(
4633 nonzero_indices_u32_cpu_wrapper,
4634 fuel_cpu_backend::byte_kernels::nonzero_indices_u32
4635);
4636
4637macro_rules! cpu_ssd_chunk_scan_wrapper {
4642 ($wrapper:ident, $kernel:path) => {
4643 pub(crate) fn $wrapper(
4644 inputs: &[Arc<RwLock<Storage>>],
4645 outputs: &mut [Arc<RwLock<Storage>>],
4646 _layouts: &[Layout],
4647 params: &OpParams,
4648 ) -> Result<()> {
4649 if inputs.len() != 5 {
4650 return Err(Error::Msg(format!(
4651 "ssd_chunk_scan wrapper expects 5 inputs (x, dt, a, b, c), got {}",
4652 inputs.len(),
4653 ))
4654 .bt());
4655 }
4656 if outputs.len() != 1 {
4657 return Err(Error::Msg(format!(
4658 "ssd_chunk_scan wrapper expects 1 output, got {}",
4659 outputs.len(),
4660 ))
4661 .bt());
4662 }
4663 let (batch, seqlen, heads, head_dim, state_dim, chunk_size) = match params {
4664 OpParams::SsdChunkScan {
4665 batch,
4666 seqlen,
4667 heads,
4668 head_dim,
4669 state_dim,
4670 chunk_size,
4671 } => (*batch, *seqlen, *heads, *head_dim, *state_dim, *chunk_size),
4672 other => {
4673 return Err(Error::Msg(format!(
4674 "ssd_chunk_scan wrapper expects OpParams::SsdChunkScan, got {other:?}",
4675 ))
4676 .bt());
4677 }
4678 };
4679 let x_guard = read_storage(&inputs[0])?;
4680 let dt_guard = read_storage(&inputs[1])?;
4681 let a_guard = read_storage(&inputs[2])?;
4682 let b_guard = read_storage(&inputs[3])?;
4683 let c_guard = read_storage(&inputs[4])?;
4684 let mut out_guard = write_storage(&outputs[0])?;
4685 let x_cpu = cpu_input(&x_guard)?;
4686 let dt_cpu = cpu_input(&dt_guard)?;
4687 let a_cpu = cpu_input(&a_guard)?;
4688 let b_cpu = cpu_input(&b_guard)?;
4689 let c_cpu = cpu_input(&c_guard)?;
4690 let out_cpu = cpu_output(&mut out_guard)?;
4691 $kernel(
4692 x_cpu, dt_cpu, a_cpu, b_cpu, c_cpu, out_cpu, batch, seqlen, heads, head_dim,
4693 state_dim, chunk_size,
4694 )
4695 }
4696 };
4697}
4698
4699cpu_ssd_chunk_scan_wrapper!(
4700 ssd_chunk_scan_f32_cpu_wrapper,
4701 fuel_cpu_backend::byte_kernels::ssd_chunk_scan_f32
4702);
4703cpu_ssd_chunk_scan_wrapper!(
4704 ssd_chunk_scan_f64_cpu_wrapper,
4705 fuel_cpu_backend::byte_kernels::ssd_chunk_scan_f64
4706);
4707cpu_ssd_chunk_scan_wrapper!(
4708 ssd_chunk_scan_bf16_cpu_wrapper,
4709 fuel_cpu_backend::byte_kernels::ssd_chunk_scan_bf16
4710);
4711cpu_ssd_chunk_scan_wrapper!(
4712 ssd_chunk_scan_f16_cpu_wrapper,
4713 fuel_cpu_backend::byte_kernels::ssd_chunk_scan_f16
4714);
4715
4716macro_rules! cpu_nf4_matmul_wrapper {
4720 ($wrapper:ident, $kernel:path) => {
4721 fn $wrapper(
4722 inputs: &[Arc<RwLock<Storage>>],
4723 outputs: &mut [Arc<RwLock<Storage>>],
4724 _layouts: &[Layout],
4725 params: &OpParams,
4726 ) -> Result<()> {
4727 if inputs.len() != 3 {
4728 return Err(Error::Msg(format!(
4729 "nf4_matmul wrapper expects 3 inputs (activations, w_packed, absmax), got {}",
4730 inputs.len(),
4731 ))
4732 .bt());
4733 }
4734 if outputs.len() != 1 {
4735 return Err(Error::Msg(format!(
4736 "nf4_matmul wrapper expects 1 output, got {}",
4737 outputs.len(),
4738 ))
4739 .bt());
4740 }
4741 let (batch, m, n, k, block_size) = match params {
4742 OpParams::Nf4Matmul {
4743 batch,
4744 m,
4745 n,
4746 k,
4747 block_size,
4748 } => (*batch, *m, *n, *k, *block_size),
4749 other => {
4750 return Err(Error::Msg(format!(
4751 "nf4_matmul wrapper expects OpParams::Nf4Matmul, got {other:?}",
4752 ))
4753 .bt());
4754 }
4755 };
4756 let a_guard = read_storage(&inputs[0])?;
4757 let w_guard = read_storage(&inputs[1])?;
4758 let abs_guard = read_storage(&inputs[2])?;
4759 let mut out_guard = write_storage(&outputs[0])?;
4760 let a_cpu = cpu_input(&a_guard)?;
4761 let w_cpu = cpu_input(&w_guard)?;
4762 let abs_cpu = cpu_input(&abs_guard)?;
4763 let out_cpu = cpu_output(&mut out_guard)?;
4764 $kernel(a_cpu, w_cpu, abs_cpu, out_cpu, batch, m, n, k, block_size)
4765 }
4766 };
4767}
4768
4769cpu_nf4_matmul_wrapper!(
4770 nf4_matmul_f32_cpu_wrapper,
4771 fuel_cpu_backend::byte_kernels::nf4_matmul_f32
4772);
4773cpu_nf4_matmul_wrapper!(
4774 nf4_matmul_f16_cpu_wrapper,
4775 fuel_cpu_backend::byte_kernels::nf4_matmul_f16
4776);
4777cpu_nf4_matmul_wrapper!(
4778 nf4_matmul_bf16_cpu_wrapper,
4779 fuel_cpu_backend::byte_kernels::nf4_matmul_bf16
4780);
4781
4782macro_rules! cpu_flash_attn_wrapper {
4786 ($wrapper:ident, $kernel:path) => {
4787 pub(crate) fn $wrapper(
4790 inputs: &[Arc<RwLock<Storage>>],
4791 outputs: &mut [Arc<RwLock<Storage>>],
4792 _layouts: &[Layout],
4793 params: &OpParams,
4794 ) -> Result<()> {
4795 if inputs.len() != 3 && inputs.len() != 4 {
4796 return Err(Error::Msg(format!(
4797 "flash_attn wrapper expects 3 or 4 inputs (q, k, v, [alibi]), got {}",
4798 inputs.len(),
4799 ))
4800 .bt());
4801 }
4802 if outputs.len() != 1 {
4803 return Err(Error::Msg(format!(
4804 "flash_attn wrapper expects 1 output, got {}",
4805 outputs.len(),
4806 ))
4807 .bt());
4808 }
4809 let (b, hq, hkv, sq, sk, d, k_len, scale, causal, wl, wr, softcap) = match params {
4810 OpParams::FlashAttn {
4811 b,
4812 hq,
4813 hkv,
4814 sq,
4815 sk,
4816 d,
4817 k_len,
4818 softmax_scale,
4819 causal,
4820 window_size_left,
4821 window_size_right,
4822 softcap,
4823 } => (
4824 *b,
4825 *hq,
4826 *hkv,
4827 *sq,
4828 *sk,
4829 *d,
4830 *k_len,
4831 *softmax_scale,
4832 *causal,
4833 *window_size_left,
4834 *window_size_right,
4835 *softcap,
4836 ),
4837 other => {
4838 return Err(Error::Msg(format!(
4839 "flash_attn wrapper expects OpParams::FlashAttn, got {other:?}",
4840 ))
4841 .bt())
4842 }
4843 };
4844 let q_guard = read_storage(&inputs[0])?;
4845 let k_guard = read_storage(&inputs[1])?;
4846 let v_guard = read_storage(&inputs[2])?;
4847 let alibi_guard = match inputs.get(3) {
4848 Some(arc) => Some(read_storage(arc)?),
4849 None => None,
4850 };
4851 let mut out_guard = write_storage(&outputs[0])?;
4852 let q_cpu = cpu_input(&q_guard)?;
4853 let k_cpu = cpu_input(&k_guard)?;
4854 let v_cpu = cpu_input(&v_guard)?;
4855 let alibi_cpu = match &alibi_guard {
4856 Some(g) => Some(cpu_input(g)?),
4857 None => None,
4858 };
4859 let out_cpu = cpu_output(&mut out_guard)?;
4860 $kernel(
4861 q_cpu, k_cpu, v_cpu, alibi_cpu, out_cpu, b, hq, hkv, sq, sk, d, k_len, scale,
4862 causal, wl, wr, softcap,
4863 )
4864 }
4865 };
4866}
4867
4868cpu_flash_attn_wrapper!(
4869 flash_attn_f32_cpu_wrapper,
4870 fuel_cpu_backend::byte_kernels::flash_attn_f32
4871);
4872cpu_flash_attn_wrapper!(
4873 flash_attn_f64_cpu_wrapper,
4874 fuel_cpu_backend::byte_kernels::flash_attn_f64
4875);
4876cpu_flash_attn_wrapper!(
4877 flash_attn_bf16_cpu_wrapper,
4878 fuel_cpu_backend::byte_kernels::flash_attn_bf16
4879);
4880cpu_flash_attn_wrapper!(
4881 flash_attn_f16_cpu_wrapper,
4882 fuel_cpu_backend::byte_kernels::flash_attn_f16
4883);
4884
4885macro_rules! cpu_flash_attn_backward_wrapper {
4890 ($wrapper:ident, $kernel:path, $which:expr) => {
4891 pub(crate) fn $wrapper(
4894 inputs: &[Arc<RwLock<Storage>>],
4895 outputs: &mut [Arc<RwLock<Storage>>],
4896 _layouts: &[Layout],
4897 params: &OpParams,
4898 ) -> Result<()> {
4899 if inputs.len() != 4 && inputs.len() != 5 {
4900 return Err(Error::Msg(format!(
4901 "flash_attn_backward wrapper expects 4 or 5 inputs (q, k, v, do, [alibi]), got {}",
4902 inputs.len(),
4903 ))
4904 .bt());
4905 }
4906 if outputs.len() != 1 {
4907 return Err(Error::Msg(format!(
4908 "flash_attn_backward wrapper expects 1 output, got {}",
4909 outputs.len(),
4910 ))
4911 .bt());
4912 }
4913 let (b, hq, hkv, sq, sk, d, scale, causal, wl, wr, softcap) = match params {
4914 OpParams::FlashAttn {
4915 b, hq, hkv, sq, sk, d,
4916 softmax_scale, causal,
4917 window_size_left, window_size_right, softcap,
4918 k_len: _,
4921 } => (
4922 *b, *hq, *hkv, *sq, *sk, *d,
4923 *softmax_scale, *causal,
4924 *window_size_left, *window_size_right, *softcap,
4925 ),
4926 other => {
4927 return Err(Error::Msg(format!(
4928 "flash_attn_backward wrapper expects OpParams::FlashAttn, got {other:?}",
4929 ))
4930 .bt())
4931 }
4932 };
4933 let q_guard = read_storage(&inputs[0])?;
4934 let k_guard = read_storage(&inputs[1])?;
4935 let v_guard = read_storage(&inputs[2])?;
4936 let do_guard = read_storage(&inputs[3])?;
4937 let alibi_guard = match inputs.get(4) {
4938 Some(arc) => Some(read_storage(arc)?),
4939 None => None,
4940 };
4941 let mut out_guard = write_storage(&outputs[0])?;
4942 let q_cpu = cpu_input(&q_guard)?;
4943 let k_cpu = cpu_input(&k_guard)?;
4944 let v_cpu = cpu_input(&v_guard)?;
4945 let do_cpu = cpu_input(&do_guard)?;
4946 let alibi_cpu = match &alibi_guard {
4947 Some(g) => Some(cpu_input(g)?),
4948 None => None,
4949 };
4950 let out_cpu = cpu_output(&mut out_guard)?;
4951 $kernel(
4952 q_cpu, k_cpu, v_cpu, do_cpu, alibi_cpu, out_cpu, $which,
4953 b, hq, hkv, sq, sk, d,
4954 scale, causal, wl, wr, softcap,
4955 )
4956 }
4957 };
4958}
4959
4960cpu_flash_attn_backward_wrapper!(
4961 flash_attn_backward_q_f32_cpu_wrapper,
4962 fuel_cpu_backend::byte_kernels::flash_attn_backward_f32,
4963 fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
4964);
4965cpu_flash_attn_backward_wrapper!(
4966 flash_attn_backward_k_f32_cpu_wrapper,
4967 fuel_cpu_backend::byte_kernels::flash_attn_backward_f32,
4968 fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
4969);
4970cpu_flash_attn_backward_wrapper!(
4971 flash_attn_backward_v_f32_cpu_wrapper,
4972 fuel_cpu_backend::byte_kernels::flash_attn_backward_f32,
4973 fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
4974);
4975cpu_flash_attn_backward_wrapper!(
4976 flash_attn_backward_q_f64_cpu_wrapper,
4977 fuel_cpu_backend::byte_kernels::flash_attn_backward_f64,
4978 fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
4979);
4980cpu_flash_attn_backward_wrapper!(
4981 flash_attn_backward_k_f64_cpu_wrapper,
4982 fuel_cpu_backend::byte_kernels::flash_attn_backward_f64,
4983 fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
4984);
4985cpu_flash_attn_backward_wrapper!(
4986 flash_attn_backward_v_f64_cpu_wrapper,
4987 fuel_cpu_backend::byte_kernels::flash_attn_backward_f64,
4988 fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
4989);
4990cpu_flash_attn_backward_wrapper!(
4991 flash_attn_backward_q_bf16_cpu_wrapper,
4992 fuel_cpu_backend::byte_kernels::flash_attn_backward_bf16,
4993 fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
4994);
4995cpu_flash_attn_backward_wrapper!(
4996 flash_attn_backward_k_bf16_cpu_wrapper,
4997 fuel_cpu_backend::byte_kernels::flash_attn_backward_bf16,
4998 fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
4999);
5000cpu_flash_attn_backward_wrapper!(
5001 flash_attn_backward_v_bf16_cpu_wrapper,
5002 fuel_cpu_backend::byte_kernels::flash_attn_backward_bf16,
5003 fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
5004);
5005cpu_flash_attn_backward_wrapper!(
5006 flash_attn_backward_q_f16_cpu_wrapper,
5007 fuel_cpu_backend::byte_kernels::flash_attn_backward_f16,
5008 fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
5009);
5010cpu_flash_attn_backward_wrapper!(
5011 flash_attn_backward_k_f16_cpu_wrapper,
5012 fuel_cpu_backend::byte_kernels::flash_attn_backward_f16,
5013 fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
5014);
5015cpu_flash_attn_backward_wrapper!(
5016 flash_attn_backward_v_f16_cpu_wrapper,
5017 fuel_cpu_backend::byte_kernels::flash_attn_backward_f16,
5018 fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
5019);
5020
5021macro_rules! cpu_paged_attn_wrapper {
5024 ($wrapper:ident, $kernel:path) => {
5025 pub(crate) fn $wrapper(
5029 inputs: &[Arc<RwLock<Storage>>],
5030 outputs: &mut [Arc<RwLock<Storage>>],
5031 _layouts: &[Layout],
5032 params: &OpParams,
5033 ) -> Result<()> {
5034 if inputs.len() != 5 && inputs.len() != 6 {
5035 return Err(Error::Msg(format!(
5036 "paged_attn wrapper expects 5 or 6 inputs, got {}",
5037 inputs.len(),
5038 ))
5039 .bt());
5040 }
5041 if outputs.len() != 1 {
5042 return Err(Error::Msg(format!(
5043 "paged_attn wrapper expects 1 output, got {}",
5044 outputs.len(),
5045 ))
5046 .bt());
5047 }
5048 let (b, hq, hkv, sq, d, block_size, max_blocks_per_seq, num_blocks, scale, softcap) =
5049 match params {
5050 OpParams::PagedAttn {
5051 b,
5052 hq,
5053 hkv,
5054 sq,
5055 d,
5056 block_size,
5057 max_blocks_per_seq,
5058 num_blocks,
5059 softmax_scale,
5060 softcap,
5061 } => (
5062 *b,
5063 *hq,
5064 *hkv,
5065 *sq,
5066 *d,
5067 *block_size,
5068 *max_blocks_per_seq,
5069 *num_blocks,
5070 *softmax_scale,
5071 *softcap,
5072 ),
5073 other => {
5074 return Err(Error::Msg(format!(
5075 "paged_attn wrapper expects OpParams::PagedAttn, got {other:?}",
5076 ))
5077 .bt())
5078 }
5079 };
5080 let q_g = read_storage(&inputs[0])?;
5081 let kc_g = read_storage(&inputs[1])?;
5082 let vc_g = read_storage(&inputs[2])?;
5083 let bt_g = read_storage(&inputs[3])?;
5084 let cl_g = read_storage(&inputs[4])?;
5085 let alibi_g = match inputs.get(5) {
5086 Some(arc) => Some(read_storage(arc)?),
5087 None => None,
5088 };
5089 if bt_g.dtype != DType::U32 || cl_g.dtype != DType::U32 {
5090 return Err(Error::Msg(format!(
5091 "paged_attn: block_table and context_lens must be U32, got {:?} / {:?}",
5092 bt_g.dtype, cl_g.dtype,
5093 ))
5094 .bt());
5095 }
5096 let mut out_guard = write_storage(&outputs[0])?;
5097 let q_cpu = cpu_input(&q_g)?;
5098 let kc_cpu = cpu_input(&kc_g)?;
5099 let vc_cpu = cpu_input(&vc_g)?;
5100 let bt_cpu = cpu_input(&bt_g)?;
5101 let cl_cpu = cpu_input(&cl_g)?;
5102 let alibi_cpu = match &alibi_g {
5103 Some(g) => Some(cpu_input(g)?),
5104 None => None,
5105 };
5106 let out_cpu = cpu_output(&mut out_guard)?;
5107 $kernel(
5108 q_cpu,
5109 kc_cpu,
5110 vc_cpu,
5111 bt_cpu,
5112 cl_cpu,
5113 alibi_cpu,
5114 out_cpu,
5115 b,
5116 hq,
5117 hkv,
5118 sq,
5119 d,
5120 block_size,
5121 max_blocks_per_seq,
5122 num_blocks,
5123 scale,
5124 softcap,
5125 )
5126 }
5127 };
5128}
5129
5130cpu_paged_attn_wrapper!(
5131 paged_attn_f32_cpu_wrapper,
5132 fuel_cpu_backend::byte_kernels::paged_attn_f32
5133);
5134cpu_paged_attn_wrapper!(
5135 paged_attn_f64_cpu_wrapper,
5136 fuel_cpu_backend::byte_kernels::paged_attn_f64
5137);
5138cpu_paged_attn_wrapper!(
5139 paged_attn_bf16_cpu_wrapper,
5140 fuel_cpu_backend::byte_kernels::paged_attn_bf16
5141);
5142cpu_paged_attn_wrapper!(
5143 paged_attn_f16_cpu_wrapper,
5144 fuel_cpu_backend::byte_kernels::paged_attn_f16
5145);
5146
5147cpu_cast_wrapper!(
5152 cast_to_f32_cpu_wrapper,
5153 DType::F32,
5154 "f32",
5155 {
5156 DType::F64 => fuel_cpu_backend::byte_kernels::cast_f64_to_f32,
5157 DType::F16 => fuel_cpu_backend::byte_kernels::cast_f16_to_f32,
5158 DType::BF16 => fuel_cpu_backend::byte_kernels::cast_bf16_to_f32,
5159 DType::F8E4M3 => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_f32,
5160 DType::U8 => fuel_cpu_backend::byte_kernels::cast_u8_to_f32,
5161 DType::I8 => fuel_cpu_backend::byte_kernels::cast_i8_to_f32,
5162 DType::U32 => fuel_cpu_backend::byte_kernels::cast_u32_to_f32,
5163 DType::I16 => fuel_cpu_backend::byte_kernels::cast_i16_to_f32,
5164 DType::I32 => fuel_cpu_backend::byte_kernels::cast_i32_to_f32,
5165 DType::I64 => fuel_cpu_backend::byte_kernels::cast_i64_to_f32,
5166 DType::Bool => fuel_cpu_backend::byte_kernels::cast_bool_to_f32,
5167 },
5168);
5169cpu_cast_wrapper!(
5170 cast_to_f64_cpu_wrapper,
5171 DType::F64,
5172 "f64",
5173 {
5174 DType::F32 => fuel_cpu_backend::byte_kernels::cast_f32_to_f64,
5175 DType::F16 => fuel_cpu_backend::byte_kernels::cast_f16_to_f64,
5176 DType::BF16 => fuel_cpu_backend::byte_kernels::cast_bf16_to_f64,
5177 DType::F8E4M3 => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_f64,
5178 DType::U8 => fuel_cpu_backend::byte_kernels::cast_u8_to_f64,
5179 DType::I8 => fuel_cpu_backend::byte_kernels::cast_i8_to_f64,
5180 DType::U32 => fuel_cpu_backend::byte_kernels::cast_u32_to_f64,
5181 DType::I16 => fuel_cpu_backend::byte_kernels::cast_i16_to_f64,
5182 DType::I32 => fuel_cpu_backend::byte_kernels::cast_i32_to_f64,
5183 DType::I64 => fuel_cpu_backend::byte_kernels::cast_i64_to_f64,
5184 DType::Bool => fuel_cpu_backend::byte_kernels::cast_bool_to_f64,
5185 },
5186);
5187cpu_cast_wrapper!(
5188 cast_to_bf16_cpu_wrapper,
5189 DType::BF16,
5190 "bf16",
5191 {
5192 DType::F32 => fuel_cpu_backend::byte_kernels::cast_f32_to_bf16,
5193 DType::F64 => fuel_cpu_backend::byte_kernels::cast_f64_to_bf16,
5194 DType::F16 => fuel_cpu_backend::byte_kernels::cast_f16_to_bf16,
5195 DType::F8E4M3 => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_bf16,
5196 DType::U8 => fuel_cpu_backend::byte_kernels::cast_u8_to_bf16,
5197 DType::I8 => fuel_cpu_backend::byte_kernels::cast_i8_to_bf16,
5198 DType::U32 => fuel_cpu_backend::byte_kernels::cast_u32_to_bf16,
5199 DType::I16 => fuel_cpu_backend::byte_kernels::cast_i16_to_bf16,
5200 DType::I32 => fuel_cpu_backend::byte_kernels::cast_i32_to_bf16,
5201 DType::I64 => fuel_cpu_backend::byte_kernels::cast_i64_to_bf16,
5202 DType::Bool => fuel_cpu_backend::byte_kernels::cast_bool_to_bf16,
5203 },
5204);
5205cpu_cast_wrapper!(
5206 cast_to_f16_cpu_wrapper,
5207 DType::F16,
5208 "f16",
5209 {
5210 DType::F32 => fuel_cpu_backend::byte_kernels::cast_f32_to_f16,
5211 DType::F64 => fuel_cpu_backend::byte_kernels::cast_f64_to_f16,
5212 DType::BF16 => fuel_cpu_backend::byte_kernels::cast_bf16_to_f16,
5213 DType::F8E4M3 => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_f16,
5214 DType::U8 => fuel_cpu_backend::byte_kernels::cast_u8_to_f16,
5215 DType::I8 => fuel_cpu_backend::byte_kernels::cast_i8_to_f16,
5216 DType::U32 => fuel_cpu_backend::byte_kernels::cast_u32_to_f16,
5217 DType::I16 => fuel_cpu_backend::byte_kernels::cast_i16_to_f16,
5218 DType::I32 => fuel_cpu_backend::byte_kernels::cast_i32_to_f16,
5219 DType::I64 => fuel_cpu_backend::byte_kernels::cast_i64_to_f16,
5220 DType::Bool => fuel_cpu_backend::byte_kernels::cast_bool_to_f16,
5221 },
5222);
5223cpu_cast_wrapper!(
5224 cast_to_f8e4m3_cpu_wrapper,
5225 DType::F8E4M3,
5226 "f8e4m3",
5227 {
5228 DType::F32 => fuel_cpu_backend::byte_kernels::cast_f32_to_f8e4m3,
5229 DType::F64 => fuel_cpu_backend::byte_kernels::cast_f64_to_f8e4m3,
5230 DType::F16 => fuel_cpu_backend::byte_kernels::cast_f16_to_f8e4m3,
5231 DType::BF16 => fuel_cpu_backend::byte_kernels::cast_bf16_to_f8e4m3,
5232 DType::U8 => fuel_cpu_backend::byte_kernels::cast_u8_to_f8e4m3,
5233 DType::I8 => fuel_cpu_backend::byte_kernels::cast_i8_to_f8e4m3,
5234 DType::U32 => fuel_cpu_backend::byte_kernels::cast_u32_to_f8e4m3,
5235 DType::I16 => fuel_cpu_backend::byte_kernels::cast_i16_to_f8e4m3,
5236 DType::I32 => fuel_cpu_backend::byte_kernels::cast_i32_to_f8e4m3,
5237 DType::I64 => fuel_cpu_backend::byte_kernels::cast_i64_to_f8e4m3,
5238 DType::Bool => fuel_cpu_backend::byte_kernels::cast_bool_to_f8e4m3,
5239 },
5240);
5241cpu_cast_wrapper!(
5242 cast_to_u8_cpu_wrapper,
5243 DType::U8,
5244 "u8",
5245 {
5246 DType::F32 => fuel_cpu_backend::byte_kernels::cast_f32_to_u8,
5247 DType::F64 => fuel_cpu_backend::byte_kernels::cast_f64_to_u8,
5248 DType::F16 => fuel_cpu_backend::byte_kernels::cast_f16_to_u8,
5249 DType::BF16 => fuel_cpu_backend::byte_kernels::cast_bf16_to_u8,
5250 DType::F8E4M3 => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_u8,
5251 DType::I8 => fuel_cpu_backend::byte_kernels::cast_i8_to_u8,
5252 DType::U32 => fuel_cpu_backend::byte_kernels::cast_u32_to_u8,
5253 DType::I16 => fuel_cpu_backend::byte_kernels::cast_i16_to_u8,
5254 DType::I32 => fuel_cpu_backend::byte_kernels::cast_i32_to_u8,
5255 DType::I64 => fuel_cpu_backend::byte_kernels::cast_i64_to_u8,
5256 DType::Bool => fuel_cpu_backend::byte_kernels::cast_bool_to_u8,
5257 },
5258);
5259cpu_cast_wrapper!(
5260 cast_to_i8_cpu_wrapper,
5261 DType::I8,
5262 "i8",
5263 {
5264 DType::F32 => fuel_cpu_backend::byte_kernels::cast_f32_to_i8,
5265 DType::F64 => fuel_cpu_backend::byte_kernels::cast_f64_to_i8,
5266 DType::F16 => fuel_cpu_backend::byte_kernels::cast_f16_to_i8,
5267 DType::BF16 => fuel_cpu_backend::byte_kernels::cast_bf16_to_i8,
5268 DType::F8E4M3 => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i8,
5269 DType::U8 => fuel_cpu_backend::byte_kernels::cast_u8_to_i8,
5270 DType::U32 => fuel_cpu_backend::byte_kernels::cast_u32_to_i8,
5271 DType::I16 => fuel_cpu_backend::byte_kernels::cast_i16_to_i8,
5272 DType::I32 => fuel_cpu_backend::byte_kernels::cast_i32_to_i8,
5273 DType::I64 => fuel_cpu_backend::byte_kernels::cast_i64_to_i8,
5274 DType::Bool => fuel_cpu_backend::byte_kernels::cast_bool_to_i8,
5275 },
5276);
5277cpu_cast_wrapper!(
5278 cast_to_u32_cpu_wrapper,
5279 DType::U32,
5280 "u32",
5281 {
5282 DType::F32 => fuel_cpu_backend::byte_kernels::cast_f32_to_u32,
5283 DType::F64 => fuel_cpu_backend::byte_kernels::cast_f64_to_u32,
5284 DType::F16 => fuel_cpu_backend::byte_kernels::cast_f16_to_u32,
5285 DType::BF16 => fuel_cpu_backend::byte_kernels::cast_bf16_to_u32,
5286 DType::F8E4M3 => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_u32,
5287 DType::U8 => fuel_cpu_backend::byte_kernels::cast_u8_to_u32,
5288 DType::I8 => fuel_cpu_backend::byte_kernels::cast_i8_to_u32,
5289 DType::I16 => fuel_cpu_backend::byte_kernels::cast_i16_to_u32,
5290 DType::I32 => fuel_cpu_backend::byte_kernels::cast_i32_to_u32,
5291 DType::I64 => fuel_cpu_backend::byte_kernels::cast_i64_to_u32,
5292 DType::Bool => fuel_cpu_backend::byte_kernels::cast_bool_to_u32,
5293 },
5294);
5295cpu_cast_wrapper!(
5296 cast_to_i16_cpu_wrapper,
5297 DType::I16,
5298 "i16",
5299 {
5300 DType::F32 => fuel_cpu_backend::byte_kernels::cast_f32_to_i16,
5301 DType::F64 => fuel_cpu_backend::byte_kernels::cast_f64_to_i16,
5302 DType::F16 => fuel_cpu_backend::byte_kernels::cast_f16_to_i16,
5303 DType::BF16 => fuel_cpu_backend::byte_kernels::cast_bf16_to_i16,
5304 DType::F8E4M3 => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i16,
5305 DType::U8 => fuel_cpu_backend::byte_kernels::cast_u8_to_i16,
5306 DType::I8 => fuel_cpu_backend::byte_kernels::cast_i8_to_i16,
5307 DType::U32 => fuel_cpu_backend::byte_kernels::cast_u32_to_i16,
5308 DType::I32 => fuel_cpu_backend::byte_kernels::cast_i32_to_i16,
5309 DType::I64 => fuel_cpu_backend::byte_kernels::cast_i64_to_i16,
5310 DType::Bool => fuel_cpu_backend::byte_kernels::cast_bool_to_i16,
5311 },
5312);
5313cpu_cast_wrapper!(
5314 cast_to_i32_cpu_wrapper,
5315 DType::I32,
5316 "i32",
5317 {
5318 DType::F32 => fuel_cpu_backend::byte_kernels::cast_f32_to_i32,
5319 DType::F64 => fuel_cpu_backend::byte_kernels::cast_f64_to_i32,
5320 DType::F16 => fuel_cpu_backend::byte_kernels::cast_f16_to_i32,
5321 DType::BF16 => fuel_cpu_backend::byte_kernels::cast_bf16_to_i32,
5322 DType::F8E4M3 => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i32,
5323 DType::U8 => fuel_cpu_backend::byte_kernels::cast_u8_to_i32,
5324 DType::I8 => fuel_cpu_backend::byte_kernels::cast_i8_to_i32,
5325 DType::U32 => fuel_cpu_backend::byte_kernels::cast_u32_to_i32,
5326 DType::I16 => fuel_cpu_backend::byte_kernels::cast_i16_to_i32,
5327 DType::I64 => fuel_cpu_backend::byte_kernels::cast_i64_to_i32,
5328 DType::Bool => fuel_cpu_backend::byte_kernels::cast_bool_to_i32,
5329 },
5330);
5331cpu_cast_wrapper!(
5332 cast_to_i64_cpu_wrapper,
5333 DType::I64,
5334 "i64",
5335 {
5336 DType::F32 => fuel_cpu_backend::byte_kernels::cast_f32_to_i64,
5337 DType::F64 => fuel_cpu_backend::byte_kernels::cast_f64_to_i64,
5338 DType::F16 => fuel_cpu_backend::byte_kernels::cast_f16_to_i64,
5339 DType::BF16 => fuel_cpu_backend::byte_kernels::cast_bf16_to_i64,
5340 DType::F8E4M3 => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i64,
5341 DType::U8 => fuel_cpu_backend::byte_kernels::cast_u8_to_i64,
5342 DType::I8 => fuel_cpu_backend::byte_kernels::cast_i8_to_i64,
5343 DType::U32 => fuel_cpu_backend::byte_kernels::cast_u32_to_i64,
5344 DType::I16 => fuel_cpu_backend::byte_kernels::cast_i16_to_i64,
5345 DType::I32 => fuel_cpu_backend::byte_kernels::cast_i32_to_i64,
5346 DType::Bool => fuel_cpu_backend::byte_kernels::cast_bool_to_i64,
5347 },
5348);
5349
5350cpu_cast_wrapper!(
5354 cast_to_bool_cpu_wrapper,
5355 DType::Bool,
5356 "bool",
5357 {
5358 DType::F32 => fuel_cpu_backend::byte_kernels::cast_f32_to_bool,
5359 DType::F64 => fuel_cpu_backend::byte_kernels::cast_f64_to_bool,
5360 DType::F16 => fuel_cpu_backend::byte_kernels::cast_f16_to_bool,
5361 DType::BF16 => fuel_cpu_backend::byte_kernels::cast_bf16_to_bool,
5362 DType::F8E4M3 => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_bool,
5363 DType::U8 => fuel_cpu_backend::byte_kernels::cast_u8_to_bool,
5364 DType::I8 => fuel_cpu_backend::byte_kernels::cast_i8_to_bool,
5365 DType::U32 => fuel_cpu_backend::byte_kernels::cast_u32_to_bool,
5366 DType::I16 => fuel_cpu_backend::byte_kernels::cast_i16_to_bool,
5367 DType::I32 => fuel_cpu_backend::byte_kernels::cast_i32_to_bool,
5368 DType::I64 => fuel_cpu_backend::byte_kernels::cast_i64_to_bool,
5369 },
5370);
5371
5372pub(crate) fn matmul_f32_cpu_wrapper(
5381 inputs: &[Arc<RwLock<Storage>>],
5382 outputs: &mut [Arc<RwLock<Storage>>],
5383 _layouts: &[Layout],
5384 params: &OpParams,
5385) -> Result<()> {
5386 if inputs.len() != 2 {
5387 return Err(Error::Msg(format!(
5388 "matmul wrapper expects 2 inputs, got {}",
5389 inputs.len(),
5390 ))
5391 .bt());
5392 }
5393 if outputs.len() != 1 {
5394 return Err(Error::Msg(format!(
5395 "matmul wrapper expects 1 output, got {}",
5396 outputs.len(),
5397 ))
5398 .bt());
5399 }
5400 let (lhs_batch_dims, rhs_batch_dims, m, n, k, m_compute) = match params {
5401 OpParams::Matmul {
5402 lhs_batch_dims,
5403 rhs_batch_dims,
5404 m,
5405 n,
5406 k,
5407 m_compute,
5408 } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k, m_compute),
5409 other => {
5410 return Err(Error::Msg(format!(
5411 "matmul wrapper expects OpParams::Matmul, got {other:?}",
5412 ))
5413 .bt());
5414 }
5415 };
5416 let rows = match m_compute {
5420 MatmulM::All => m,
5421 MatmulM::Rows(c) => *c,
5422 MatmulM::Deferred(d) => {
5423 return Err(Error::Msg(format!(
5424 "matmul_f32 wrapper: unresolved data-determined row count {d:?} \
5425 (must be resolved at execute before the kernel runs)",
5426 ))
5427 .bt());
5428 }
5429 };
5430 let lhs_guard = read_storage(&inputs[0])?;
5431 let rhs_guard = read_storage(&inputs[1])?;
5432 let mut out_guard = write_storage(&outputs[0])?;
5433 let lhs_cpu = cpu_input(&lhs_guard)?;
5434 let rhs_cpu = cpu_input(&rhs_guard)?;
5435 let out_cpu = cpu_output(&mut out_guard)?;
5436 fuel_cpu_backend::byte_kernels::matmul_f32_capacity(
5437 lhs_cpu,
5438 rhs_cpu,
5439 out_cpu,
5440 lhs_batch_dims,
5441 rhs_batch_dims,
5442 m,
5443 rows,
5444 n,
5445 k,
5446 )
5447}
5448
5449macro_rules! cpu_matmul_wrapper {
5454 ($wrapper:ident, $kernel:path, $type_name:literal) => {
5455 pub(crate) fn $wrapper(
5458 inputs: &[Arc<RwLock<Storage>>],
5459 outputs: &mut [Arc<RwLock<Storage>>],
5460 _layouts: &[Layout],
5461 params: &OpParams,
5462 ) -> Result<()> {
5463 if inputs.len() != 2 {
5464 return Err(Error::Msg(format!(
5465 "matmul wrapper expects 2 inputs, got {}",
5466 inputs.len(),
5467 ))
5468 .bt());
5469 }
5470 if outputs.len() != 1 {
5471 return Err(Error::Msg(format!(
5472 "matmul wrapper expects 1 output, got {}",
5473 outputs.len(),
5474 ))
5475 .bt());
5476 }
5477 let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
5478 OpParams::Matmul {
5479 lhs_batch_dims,
5480 rhs_batch_dims,
5481 m,
5482 n,
5483 k,
5484 ..
5485 } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k),
5486 other => {
5487 return Err(Error::Msg(format!(
5488 "matmul wrapper expects OpParams::Matmul, got {other:?}",
5489 ))
5490 .bt())
5491 }
5492 };
5493 let lhs_guard = read_storage(&inputs[0])?;
5494 let rhs_guard = read_storage(&inputs[1])?;
5495 let mut out_guard = write_storage(&outputs[0])?;
5496 let lhs_cpu = cpu_input(&lhs_guard)?;
5497 let rhs_cpu = cpu_input(&rhs_guard)?;
5498 let out_cpu = cpu_output(&mut out_guard)?;
5499 let _ = $type_name;
5500 $kernel(
5501 lhs_cpu,
5502 rhs_cpu,
5503 out_cpu,
5504 lhs_batch_dims,
5505 rhs_batch_dims,
5506 m,
5507 n,
5508 k,
5509 )
5510 }
5511 };
5512}
5513
5514cpu_matmul_wrapper!(
5515 matmul_bf16_cpu_wrapper,
5516 fuel_cpu_backend::byte_kernels::matmul_bf16,
5517 "matmul_bf16"
5518);
5519cpu_matmul_wrapper!(
5520 matmul_f16_cpu_wrapper,
5521 fuel_cpu_backend::byte_kernels::matmul_f16,
5522 "matmul_f16"
5523);
5524cpu_matmul_wrapper!(
5525 matmul_f32_bf16_cpu_wrapper,
5526 fuel_cpu_backend::byte_kernels::matmul_f32_bf16,
5527 "matmul_f32_bf16"
5528);
5529cpu_matmul_wrapper!(
5530 matmul_f32_f16_cpu_wrapper,
5531 fuel_cpu_backend::byte_kernels::matmul_f32_f16,
5532 "matmul_f32_f16"
5533);
5534cpu_matmul_wrapper!(
5535 matmul_i8_cpu_wrapper,
5536 fuel_cpu_backend::byte_kernels::matmul_i8,
5537 "matmul_i8"
5538);
5539cpu_matmul_wrapper!(
5540 matmul_u8_cpu_wrapper,
5541 fuel_cpu_backend::byte_kernels::matmul_u8,
5542 "matmul_u8"
5543);
5544
5545pub(crate) fn matmul_f64_cpu_wrapper(
5552 inputs: &[Arc<RwLock<Storage>>],
5553 outputs: &mut [Arc<RwLock<Storage>>],
5554 _layouts: &[Layout],
5555 params: &OpParams,
5556) -> Result<()> {
5557 if inputs.len() != 2 {
5558 return Err(Error::Msg(format!(
5559 "matmul wrapper expects 2 inputs, got {}",
5560 inputs.len(),
5561 ))
5562 .bt());
5563 }
5564 if outputs.len() != 1 {
5565 return Err(Error::Msg(format!(
5566 "matmul wrapper expects 1 output, got {}",
5567 outputs.len(),
5568 ))
5569 .bt());
5570 }
5571 let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
5572 OpParams::Matmul {
5573 lhs_batch_dims,
5574 rhs_batch_dims,
5575 m,
5576 n,
5577 k,
5578 ..
5579 } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k),
5580 other => {
5581 return Err(Error::Msg(format!(
5582 "matmul wrapper expects OpParams::Matmul, got {other:?}",
5583 ))
5584 .bt());
5585 }
5586 };
5587 let lhs_guard = read_storage(&inputs[0])?;
5588 let rhs_guard = read_storage(&inputs[1])?;
5589 let mut out_guard = write_storage(&outputs[0])?;
5590 let lhs_cpu = cpu_input(&lhs_guard)?;
5591 let rhs_cpu = cpu_input(&rhs_guard)?;
5592 let out_cpu = cpu_output(&mut out_guard)?;
5593 fuel_cpu_backend::byte_kernels::matmul_f64(
5594 lhs_cpu,
5595 rhs_cpu,
5596 out_cpu,
5597 lhs_batch_dims,
5598 rhs_batch_dims,
5599 m,
5600 n,
5601 k,
5602 )
5603}
5604
5605fn copy_from_cpu_wrapper(
5631 inputs: &[Arc<RwLock<Storage>>],
5632 outputs: &mut [Arc<RwLock<Storage>>],
5633 _layouts: &[Layout],
5634 _params: &OpParams,
5635) -> Result<()> {
5636 if inputs.len() != 1 || outputs.len() != 1 {
5637 return Err(Error::Msg(format!(
5638 "copy_from_cpu_wrapper: expected 1 input + 1 output, got {} + {}",
5639 inputs.len(),
5640 outputs.len(),
5641 ))
5642 .bt());
5643 }
5644 let in_guard = read_storage(&inputs[0])?;
5645 let src = cpu_input(&in_guard)?;
5646 let mut out_guard = write_storage(&outputs[0])?;
5647 let n_out = out_guard.inner.len_bytes();
5654 let n_src = src.len_bytes();
5655 let n = n_src.min(n_out);
5656 let src_slice = &src.bytes()[..n];
5657 match &mut out_guard.inner {
5658 BackendStorage::Cpu(dst) => {
5659 dst.bytes_mut()[..n].copy_from_slice(src_slice);
5660 }
5661 #[cfg(feature = "cuda")]
5662 BackendStorage::Cuda(dst) => {
5663 if n == n_out {
5670 dst.write_from_host(src_slice)?;
5671 } else {
5672 let mut staged = vec![0_u8; n_out];
5675 staged[..n].copy_from_slice(src_slice);
5676 dst.write_from_host(&staged)?;
5677 }
5678 }
5679 #[cfg(feature = "vulkan")]
5680 BackendStorage::Vulkan(dst) => {
5681 let backend = dst
5682 .backend()
5683 .ok_or_else(|| {
5684 Error::Msg(
5685 "copy_from_cpu_wrapper: Vulkan output has no attached \
5686 backend handle. The executor's Op::Copy arm must allocate \
5687 via VulkanBackend::alloc_bytes_handle (which attaches \
5688 the handle)."
5689 .to_string(),
5690 )
5691 .bt()
5692 })?
5693 .clone();
5694 if n == n_out {
5695 backend.write_bytes(dst, src_slice)?;
5696 } else {
5697 let mut staged = vec![0_u8; n_out];
5698 staged[..n].copy_from_slice(src_slice);
5699 backend.write_bytes(dst, &staged)?;
5700 }
5701 }
5702 #[allow(unreachable_patterns)]
5703 other => {
5704 return Err(Error::Msg(format!(
5705 "copy_from_cpu_wrapper: output backend not wired ({other:?}); \
5706 CPU + CUDA + Vulkan covered, Metal extends when its \
5707 byte-storage substrate is ready.",
5708 ))
5709 .bt());
5710 }
5711 }
5712 Ok(())
5713}
5714
5715const CPU_ELEMENTWISE_BINARY_CONTRACT: &str =
5720 include_str!("../kernel-contracts/cpu/elementwise-binary.fkc.md");
5721
5722fn register_cpu_binary_from_contract(table: &mut KernelBindingTable) {
5754 let provider = crate::fkc::import_bundle_str(
5755 CPU_ELEMENTWISE_BINARY_CONTRACT,
5756 &crate::fkc::CpuLinkRegistry,
5757 )
5758 .expect(
5759 "authored CPU elementwise-binary contract must import \
5760 (embedded via include_str!, resolved through CpuLinkRegistry)",
5761 );
5762 debug_assert!(
5763 provider.fused.is_empty(),
5764 "elementwise-binary contract declares no fused ops",
5765 );
5766 let mut fused = crate::fused::FusedKernelRegistry::new();
5767 provider
5768 .register_into(table, &mut fused)
5769 .expect("CPU elementwise-binary contract must register into the binding table");
5770}
5771
5772const CPU_AFFINE_CLAMP_POWI_CONTRACT: &str =
5776 include_str!("../kernel-contracts/cpu/affine-clamp-powi.fkc.md");
5777
5778fn register_cpu_affine_clamp_powi_from_contract(table: &mut KernelBindingTable) {
5804 let provider =
5805 crate::fkc::import_bundle_str(CPU_AFFINE_CLAMP_POWI_CONTRACT, &crate::fkc::CpuLinkRegistry)
5806 .expect(
5807 "authored CPU affine/clamp/powi contract must import \
5808 (embedded via include_str!, resolved through CpuLinkRegistry)",
5809 );
5810 debug_assert!(
5811 provider.fused.is_empty(),
5812 "affine/clamp/powi contract declares no fused ops",
5813 );
5814 let mut fused = crate::fused::FusedKernelRegistry::new();
5815 provider
5816 .register_into(table, &mut fused)
5817 .expect("CPU affine/clamp/powi contract must register into the binding table");
5818}
5819
5820const CPU_ELEMENTWISE_UNARY_CONTRACT: &str =
5824 include_str!("../kernel-contracts/cpu/elementwise-unary.fkc.md");
5825
5826fn register_cpu_unary_from_contract(table: &mut KernelBindingTable) {
5853 let provider =
5854 crate::fkc::import_bundle_str(CPU_ELEMENTWISE_UNARY_CONTRACT, &crate::fkc::CpuLinkRegistry)
5855 .expect(
5856 "authored CPU elementwise-unary contract must import \
5857 (embedded via include_str!, resolved through CpuLinkRegistry)",
5858 );
5859 debug_assert!(
5860 provider.fused.is_empty(),
5861 "elementwise-unary contract declares no fused ops",
5862 );
5863 let mut fused = crate::fused::FusedKernelRegistry::new();
5864 provider
5865 .register_into(table, &mut fused)
5866 .expect("CPU elementwise-unary contract must register into the binding table");
5867}
5868
5869const CPU_COMPARE_WHERE_CONTRACT: &str =
5873 include_str!("../kernel-contracts/cpu/compare-where.fkc.md");
5874
5875fn register_cpu_compare_where_from_contract(table: &mut KernelBindingTable) {
5904 let provider =
5905 crate::fkc::import_bundle_str(CPU_COMPARE_WHERE_CONTRACT, &crate::fkc::CpuLinkRegistry)
5906 .expect(
5907 "authored CPU compare/where contract must import \
5908 (embedded via include_str!, resolved through CpuLinkRegistry)",
5909 );
5910 debug_assert!(
5911 provider.fused.is_empty(),
5912 "compare/where contract declares no fused ops",
5913 );
5914 let mut fused = crate::fused::FusedKernelRegistry::new();
5915 provider
5916 .register_into(table, &mut fused)
5917 .expect("CPU compare/where contract must register into the binding table");
5918}
5919
5920const CPU_REDUCE_CONTRACT: &str = include_str!("../kernel-contracts/cpu/reduce.fkc.md");
5924
5925fn register_cpu_reduce_from_contract(table: &mut KernelBindingTable) {
5955 let provider = crate::fkc::import_bundle_str(CPU_REDUCE_CONTRACT, &crate::fkc::CpuLinkRegistry)
5956 .expect(
5957 "authored CPU reduce contract must import \
5958 (embedded via include_str!, resolved through CpuLinkRegistry)",
5959 );
5960 debug_assert!(
5961 provider.fused.is_empty(),
5962 "reduce contract declares no fused ops",
5963 );
5964 let mut fused = crate::fused::FusedKernelRegistry::new();
5965 provider
5966 .register_into(table, &mut fused)
5967 .expect("CPU reduce contract must register into the binding table");
5968}
5969
5970const CPU_REDUCE_TO_CONTRACT: &str = include_str!("../kernel-contracts/cpu/reduce-to.fkc.md");
5974
5975fn register_cpu_reduce_to_from_contract(table: &mut KernelBindingTable) {
6007 let provider =
6008 crate::fkc::import_bundle_str(CPU_REDUCE_TO_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6009 "authored CPU reduce-to contract must import \
6010 (embedded via include_str!, resolved through CpuLinkRegistry)",
6011 );
6012 debug_assert!(
6013 provider.fused.is_empty(),
6014 "reduce-to contract declares no fused ops",
6015 );
6016 let mut fused = crate::fused::FusedKernelRegistry::new();
6017 provider
6018 .register_into(table, &mut fused)
6019 .expect("CPU reduce-to contract must register into the binding table");
6020}
6021
6022const CPU_NORM_CONTRACT: &str = include_str!("../kernel-contracts/cpu/norm.fkc.md");
6026
6027fn register_cpu_norm_from_contract(table: &mut KernelBindingTable) {
6062 let provider = crate::fkc::import_bundle_str(CPU_NORM_CONTRACT, &crate::fkc::CpuLinkRegistry)
6063 .expect(
6064 "authored CPU norm contract must import \
6065 (embedded via include_str!, resolved through CpuLinkRegistry)",
6066 );
6067 debug_assert!(
6068 provider.fused.is_empty(),
6069 "norm forward contract declares no fused ops",
6070 );
6071 let mut fused = crate::fused::FusedKernelRegistry::new();
6072 provider
6073 .register_into(table, &mut fused)
6074 .expect("CPU norm contract must register into the binding table");
6075}
6076
6077const CPU_NORM_BACKWARD_CONTRACT: &str =
6081 include_str!("../kernel-contracts/cpu/norm-backward.fkc.md");
6082
6083fn register_cpu_norm_backward_from_contract(table: &mut KernelBindingTable) {
6117 let provider =
6118 crate::fkc::import_bundle_str(CPU_NORM_BACKWARD_CONTRACT, &crate::fkc::CpuLinkRegistry)
6119 .expect(
6120 "authored CPU norm-backward contract must import \
6121 (embedded via include_str!, resolved through CpuLinkRegistry)",
6122 );
6123 debug_assert!(
6124 provider.fused.is_empty(),
6125 "norm backward contract declares no fused ops",
6126 );
6127 let mut fused = crate::fused::FusedKernelRegistry::new();
6128 provider
6129 .register_into(table, &mut fused)
6130 .expect("CPU norm-backward contract must register into the binding table");
6131}
6132
6133const CPU_ROPE_CONTRACT: &str = include_str!("../kernel-contracts/cpu/rope.fkc.md");
6137
6138fn register_cpu_rope_from_contract(table: &mut KernelBindingTable) {
6172 let provider = crate::fkc::import_bundle_str(CPU_ROPE_CONTRACT, &crate::fkc::CpuLinkRegistry)
6173 .expect(
6174 "authored CPU rope contract must import \
6175 (embedded via include_str!, resolved through CpuLinkRegistry)",
6176 );
6177 debug_assert!(
6178 provider.fused.is_empty(),
6179 "rope contract declares no fused ops",
6180 );
6181 let mut fused = crate::fused::FusedKernelRegistry::new();
6182 provider
6183 .register_into(table, &mut fused)
6184 .expect("CPU rope contract must register into the binding table");
6185}
6186
6187const CPU_SSM_CONTRACT: &str = include_str!("../kernel-contracts/cpu/ssm.fkc.md");
6191
6192fn register_cpu_ssm_from_contract(table: &mut KernelBindingTable) {
6231 let provider = crate::fkc::import_bundle_str(CPU_SSM_CONTRACT, &crate::fkc::CpuLinkRegistry)
6232 .expect(
6233 "authored CPU ssm contract must import \
6234 (embedded via include_str!, resolved through CpuLinkRegistry)",
6235 );
6236 debug_assert!(
6237 provider.fused.is_empty(),
6238 "ssm contract declares no fused ops",
6239 );
6240 let mut fused = crate::fused::FusedKernelRegistry::new();
6241 provider
6242 .register_into(table, &mut fused)
6243 .expect("CPU ssm contract must register into the binding table");
6244}
6245
6246const CPU_CONV_CONTRACT: &str = include_str!("../kernel-contracts/cpu/conv.fkc.md");
6251
6252fn register_cpu_conv_from_contract(table: &mut KernelBindingTable) {
6292 let provider = crate::fkc::import_bundle_str(CPU_CONV_CONTRACT, &crate::fkc::CpuLinkRegistry)
6293 .expect(
6294 "authored CPU conv contract must import \
6295 (embedded via include_str!, resolved through CpuLinkRegistry)",
6296 );
6297 debug_assert!(
6298 provider.fused.is_empty(),
6299 "conv contract declares no fused ops",
6300 );
6301 let mut fused = crate::fused::FusedKernelRegistry::new();
6302 provider
6303 .register_into(table, &mut fused)
6304 .expect("CPU conv contract must register into the binding table");
6305}
6306
6307const CPU_PADDING_CONTRACT: &str = include_str!("../kernel-contracts/cpu/padding.fkc.md");
6312
6313fn register_cpu_padding_from_contract(table: &mut KernelBindingTable) {
6349 let provider =
6350 crate::fkc::import_bundle_str(CPU_PADDING_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6351 "authored CPU padding contract must import \
6352 (embedded via include_str!, resolved through CpuLinkRegistry)",
6353 );
6354 debug_assert!(
6355 provider.fused.is_empty(),
6356 "padding contract declares no fused ops",
6357 );
6358 let mut fused = crate::fused::FusedKernelRegistry::new();
6359 provider
6360 .register_into(table, &mut fused)
6361 .expect("CPU padding contract must register into the binding table");
6362}
6363
6364const CPU_SHAPE_OPS_CONTRACT: &str = include_str!("../kernel-contracts/cpu/shape-ops.fkc.md");
6368
6369fn register_cpu_shape_ops_from_contract(table: &mut KernelBindingTable) {
6410 let provider =
6411 crate::fkc::import_bundle_str(CPU_SHAPE_OPS_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6412 "authored CPU shape-ops contract must import \
6413 (embedded via include_str!, resolved through CpuLinkRegistry)",
6414 );
6415 debug_assert!(
6416 provider.fused.is_empty(),
6417 "shape-ops contract declares no fused ops",
6418 );
6419 let mut fused = crate::fused::FusedKernelRegistry::new();
6420 provider
6421 .register_into(table, &mut fused)
6422 .expect("CPU shape-ops contract must register into the binding table");
6423}
6424
6425const CPU_MATMUL_CONTRACT: &str = include_str!("../kernel-contracts/cpu/matmul.fkc.md");
6429
6430fn register_cpu_matmul_from_contract(table: &mut KernelBindingTable) {
6475 let provider = crate::fkc::import_bundle_str(CPU_MATMUL_CONTRACT, &crate::fkc::CpuLinkRegistry)
6476 .expect(
6477 "authored CPU matmul contract must import \
6478 (embedded via include_str!, resolved through CpuLinkRegistry)",
6479 );
6480 debug_assert!(
6481 provider.fused.is_empty(),
6482 "matmul contract declares no fused ops",
6483 );
6484 let mut fused = crate::fused::FusedKernelRegistry::new();
6485 provider
6486 .register_into(table, &mut fused)
6487 .expect("CPU matmul contract must register into the binding table");
6488}
6489
6490const CPU_ATTENTION_CONTRACT: &str = include_str!("../kernel-contracts/cpu/attention.fkc.md");
6495
6496fn register_cpu_attention_from_contract(table: &mut KernelBindingTable) {
6552 let provider =
6553 crate::fkc::import_bundle_str(CPU_ATTENTION_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6554 "authored CPU attention contract must import \
6555 (embedded via include_str!, resolved through CpuLinkRegistry)",
6556 );
6557 debug_assert!(
6558 provider.fused.is_empty(),
6559 "attention contract declares no fused ops (all op_kind, incl. PagedAttn)",
6560 );
6561 let mut fused = crate::fused::FusedKernelRegistry::new();
6562 provider
6563 .register_into(table, &mut fused)
6564 .expect("CPU attention contract must register into the binding table");
6565}
6566
6567const CPU_INPLACE_CONTRACT: &str =
6571 include_str!("../kernel-contracts/cpu/inplace-unary-affine.fkc.md");
6572
6573fn register_cpu_inplace_from_contract(table: &mut KernelBindingTable) {
6613 let provider =
6614 crate::fkc::import_bundle_str(CPU_INPLACE_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6615 "authored CPU in-place contract must import \
6616 (embedded via include_str!, resolved through CpuLinkRegistry)",
6617 );
6618 debug_assert!(
6619 provider.fused.is_empty(),
6620 "in-place contract declares no fused ops (all op_kind or describe-only umbrella)",
6621 );
6622 let mut fused = crate::fused::FusedKernelRegistry::new();
6623 provider
6624 .register_into(table, &mut fused)
6625 .expect("CPU in-place contract must register into the binding table");
6626}
6627
6628const CPU_CAST_CONTRACT: &str = include_str!("../kernel-contracts/cpu/cast.fkc.md");
6632
6633fn register_cpu_cast_from_contract(table: &mut KernelBindingTable) {
6663 let provider = crate::fkc::import_bundle_str(CPU_CAST_CONTRACT, &crate::fkc::CpuLinkRegistry)
6664 .expect(
6665 "authored CPU cast contract must import \
6666 (embedded via include_str!, resolved through CpuLinkRegistry)",
6667 );
6668 debug_assert!(
6669 provider.fused.is_empty(),
6670 "cast contract declares no fused ops",
6671 );
6672 let mut fused = crate::fused::FusedKernelRegistry::new();
6673 provider
6674 .register_into(table, &mut fused)
6675 .expect("CPU cast contract must register into the binding table");
6676}
6677
6678const CPU_INDEXING_CONTRACT: &str = include_str!("../kernel-contracts/cpu/indexing.fkc.md");
6683
6684fn register_cpu_indexing_from_contract(table: &mut KernelBindingTable) {
6723 let provider =
6724 crate::fkc::import_bundle_str(CPU_INDEXING_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6725 "authored CPU indexing contract must import \
6726 (embedded via include_str!, resolved through CpuLinkRegistry)",
6727 );
6728 debug_assert!(
6729 provider.fused.is_empty(),
6730 "indexing contract declares no fused ops",
6731 );
6732 let mut fused = crate::fused::FusedKernelRegistry::new();
6733 provider
6734 .register_into(table, &mut fused)
6735 .expect("CPU indexing contract must register into the binding table");
6736}
6737
6738pub fn register_cpu_kernels(table: &mut KernelBindingTable) {
6744 use OpKind::*;
6745 let cpu = BackendId::Cpu;
6746 let f32_dt = DType::F32;
6747 let f64_dt = DType::F64;
6748 let bf16_dt = DType::BF16;
6749 let f16_dt = DType::F16;
6750 let u32_dt = DType::U32;
6751
6752 let unary = |t: DType| [t, t]; let u8_dt = DType::U8;
6762 register_cpu_binary_from_contract(table);
6800
6801 register_cpu_affine_clamp_powi_from_contract(table);
6811
6812 register_cpu_unary_from_contract(table);
6825
6826 register_cpu_compare_where_from_contract(table);
6837
6838 register_cpu_reduce_from_contract(table);
6850
6851 register_cpu_reduce_to_from_contract(table);
6863
6864 register_cpu_norm_from_contract(table);
6879
6880 register_cpu_norm_backward_from_contract(table);
6896
6897 register_cpu_rope_from_contract(table);
6910
6911 register_cpu_ssm_from_contract(table);
6926
6927 table.register(
6940 NonZeroIndices,
6941 &[f32_dt, u32_dt],
6942 cpu,
6943 nonzero_indices_f32_cpu_wrapper,
6944 );
6945 table.register(
6946 NonZeroIndices,
6947 &[u32_dt, u32_dt],
6948 cpu,
6949 nonzero_indices_u32_cpu_wrapper,
6950 );
6951
6952 register_cpu_conv_from_contract(table);
6970
6971 register_cpu_padding_from_contract(table);
6987
6988 register_cpu_shape_ops_from_contract(table);
7008
7009 register_cpu_matmul_from_contract(table);
7030
7031 register_cpu_attention_from_contract(table);
7048
7049 register_cpu_inplace_from_contract(table);
7062
7063 register_cpu_cast_from_contract(table);
7083
7084 register_cpu_indexing_from_contract(table);
7100
7101 table.register(
7158 Nf4Matmul,
7159 &[DType::F32, DType::U8, DType::F32, DType::F32],
7160 cpu,
7161 nf4_matmul_f32_cpu_wrapper,
7162 );
7163 table.register(
7164 Nf4Matmul,
7165 &[DType::F16, DType::U8, DType::F32, DType::F16],
7166 cpu,
7167 nf4_matmul_f16_cpu_wrapper,
7168 );
7169 table.register(
7170 Nf4Matmul,
7171 &[DType::BF16, DType::U8, DType::F32, DType::BF16],
7172 cpu,
7173 nf4_matmul_bf16_cpu_wrapper,
7174 );
7175
7176 table.register(Triu, &unary(f32_dt), cpu, triu_cpu_wrapper);
7217 table.register(Triu, &unary(f64_dt), cpu, triu_cpu_wrapper);
7218 table.register(Triu, &unary(bf16_dt), cpu, triu_cpu_wrapper);
7219 table.register(Triu, &unary(f16_dt), cpu, triu_cpu_wrapper);
7220 table.register(Triu, &unary(u32_dt), cpu, triu_cpu_wrapper);
7221 table.register(Triu, &unary(u8_dt), cpu, triu_cpu_wrapper);
7222 table.register(Tril, &unary(f32_dt), cpu, tril_cpu_wrapper);
7223 table.register(Tril, &unary(f64_dt), cpu, tril_cpu_wrapper);
7224 table.register(Tril, &unary(bf16_dt), cpu, tril_cpu_wrapper);
7225 table.register(Tril, &unary(f16_dt), cpu, tril_cpu_wrapper);
7226 table.register(Tril, &unary(u32_dt), cpu, tril_cpu_wrapper);
7227 table.register(Tril, &unary(u8_dt), cpu, tril_cpu_wrapper);
7228
7229 table.register(
7299 QMatMul,
7300 &[f32_dt, u32_dt, f32_dt],
7301 cpu,
7302 qmatmul_f32_cpu_wrapper,
7303 );
7304
7305 for dt in [f32_dt, f64_dt, bf16_dt, f16_dt] {
7316 table.register(ArgMaxDim, &[dt, u32_dt], cpu, argmax_dim_u32_cpu_dispatch);
7317 table.register(ArgMinDim, &[dt, u32_dt], cpu, argmin_dim_u32_cpu_dispatch);
7318 }
7319
7320 let copy_dtypes = [
7335 f32_dt,
7336 f64_dt,
7337 bf16_dt,
7338 f16_dt,
7339 u32_dt,
7340 u8_dt,
7341 DType::I16,
7342 DType::I32,
7343 DType::I64,
7344 DType::Bool,
7347 ];
7348 for dt in copy_dtypes {
7349 table.register(Copy, &[dt, dt], cpu, copy_from_cpu_wrapper);
7350 }
7351 table.fill_unset_cpu_precision(crate::fused::PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU);
7373
7374 table.fill_unset_cpu_cost(crate::cost::default_cost_for_op_kind);
7391}
7392
7393#[cfg(feature = "cuda")]
7407pub(crate) fn cuda_input(s: &Storage) -> Result<&fuel_cuda_backend::CudaStorageBytes> {
7408 match &s.inner {
7409 BackendStorage::Cuda(c) => Ok(c),
7410 #[allow(unreachable_patterns)]
7411 _ => Err(Error::Msg("cuda kernel wrapper called with non-CUDA input".to_string()).bt()),
7412 }
7413}
7414
7415#[cfg(feature = "cuda")]
7417pub(crate) fn cuda_output(s: &mut Storage) -> Result<&mut fuel_cuda_backend::CudaStorageBytes> {
7418 match &mut s.inner {
7419 BackendStorage::Cuda(c) => Ok(c),
7420 #[allow(unreachable_patterns)]
7421 _ => Err(Error::Msg("cuda kernel wrapper called with non-CUDA output".to_string()).bt()),
7422 }
7423}
7424
7425#[cfg(feature = "cuda")]
7448fn copy_from_cuda_wrapper(
7449 inputs: &[Arc<RwLock<Storage>>],
7450 outputs: &mut [Arc<RwLock<Storage>>],
7451 _layouts: &[Layout],
7452 _params: &OpParams,
7453) -> Result<()> {
7454 if inputs.len() != 1 || outputs.len() != 1 {
7455 return Err(Error::Msg(format!(
7456 "copy_from_cuda_wrapper: expected 1 input + 1 output, got {} + {}",
7457 inputs.len(),
7458 outputs.len(),
7459 ))
7460 .bt());
7461 }
7462 let in_guard = read_storage(&inputs[0])?;
7463 let cuda_src = cuda_input(&in_guard)?;
7464 let mut out_guard = write_storage(&outputs[0])?;
7465 match &mut out_guard.inner {
7466 BackendStorage::Cpu(_) => {
7467 let bytes = cuda_src.to_cpu_bytes_finer()?;
7479 let dst = cpu_output(&mut out_guard)?;
7480 let n = bytes.len().min(dst.len_bytes());
7481 dst.bytes_mut()[..n].copy_from_slice(&bytes[..n]);
7482 Ok(())
7483 }
7484 BackendStorage::Cuda(_) => {
7485 let dst = cuda_output(&mut out_guard)?;
7494 dst.copy_from_device(cuda_src)?;
7495 Ok(())
7496 }
7497 #[allow(unreachable_patterns)]
7498 other => Err(Error::Msg(format!(
7499 "copy_from_cuda_wrapper: unsupported output substrate {:?} \
7500 (CUDA sources copy to CPU or CUDA outputs only; cross-vendor \
7501 GPU transfer goes through host staging as two Copy hops)",
7502 std::mem::discriminant(other),
7503 ))
7504 .bt()),
7505 }
7506}
7507
7508#[cfg(feature = "cuda")]
7527pub fn register_cuda_kernels(table: &mut KernelBindingTable) {
7528 use OpKind::*;
7529 let cuda = BackendId::Cuda;
7530
7531 let copy_dtypes = [
7536 DType::F32,
7537 DType::BF16,
7538 DType::F16,
7539 DType::U32,
7540 DType::F64,
7541 DType::U8,
7542 DType::I16,
7543 DType::I32,
7544 DType::I64,
7545 DType::Bool,
7551 ];
7552 for dt in copy_dtypes {
7553 table.register(Copy, &[dt, dt], cuda, copy_from_cuda_wrapper);
7554 }
7555}
7556
7557static GLOBAL_REGISTRY: OnceLock<RwLock<CapabilityRegistry>> = OnceLock::new();
7570
7571static TOPOLOGY_GENERATION: AtomicU64 = AtomicU64::new(0);
7583
7584pub fn topology_generation() -> u64 {
7587 TOPOLOGY_GENERATION.load(Ordering::Acquire)
7588}
7589
7590pub fn bump_topology_generation() {
7597 TOPOLOGY_GENERATION.fetch_add(1, Ordering::Release);
7598}
7599
7600static DEVICE_INFLIGHT: OnceLock<RwLock<HashMap<DeviceLocation, AtomicU32>>> = OnceLock::new();
7651
7652fn device_inflight_table() -> &'static RwLock<HashMap<DeviceLocation, AtomicU32>> {
7653 DEVICE_INFLIGHT.get_or_init(|| RwLock::new(HashMap::new()))
7654}
7655
7656pub fn inflight_inc(loc: DeviceLocation) {
7664 let table = device_inflight_table();
7665 if let Ok(guard) = table.read()
7667 && let Some(slot) = guard.get(&loc)
7668 {
7669 slot.fetch_add(1, Ordering::Relaxed);
7670 return;
7671 }
7672 if let Ok(mut guard) = table.write() {
7676 guard
7677 .entry(loc)
7678 .or_insert_with(|| AtomicU32::new(0))
7679 .fetch_add(1, Ordering::Relaxed);
7680 }
7681}
7682
7683pub fn inflight_dec(loc: DeviceLocation) {
7691 let table = device_inflight_table();
7692 if let Ok(guard) = table.read()
7693 && let Some(slot) = guard.get(&loc)
7694 {
7695 let _ = slot.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
7697 Some(v.saturating_sub(1))
7698 });
7699 }
7700}
7701
7702pub fn inflight_count(loc: DeviceLocation) -> u32 {
7707 let table = device_inflight_table();
7708 table
7709 .read()
7710 .ok()
7711 .and_then(|guard| guard.get(&loc).map(|slot| slot.load(Ordering::Relaxed)))
7712 .unwrap_or(0)
7713}
7714
7715static GLOBAL_BINDINGS: OnceLock<RwLock<Arc<KernelBindingTable>>> = OnceLock::new();
7729
7730static BINDINGS_WRITER: Mutex<()> = Mutex::new(());
7754
7755fn bindings_cell() -> &'static RwLock<Arc<KernelBindingTable>> {
7759 GLOBAL_BINDINGS.get_or_init(|| {
7760 lock_trace(" BINDINGS init: begin");
7761 let mut t = KernelBindingTable::new();
7762 register_cpu_kernels(&mut t);
7763 lock_trace(" BINDINGS init: cpu done, entering optional backends");
7764 register_optional_backends(&mut t);
7765 lock_trace(" BINDINGS init: optional backends done");
7766 t.finalize()
7772 .expect("KernelBindingTable: duplicate kernel registration at init");
7773 RwLock::new(Arc::new(t))
7774 })
7775}
7776
7777fn default_cpu_caps() -> BackendCapabilities {
7778 use OpKind::*;
7779 use std::collections::HashSet;
7780 let mut op_dtype_support = HashSet::new();
7781 let f32_dt = DType::F32;
7785 for op in [
7786 AddElementwise,
7787 SubElementwise,
7788 MulElementwise,
7789 DivElementwise,
7790 ReluElementwise,
7791 NegElementwise,
7792 SqrElementwise,
7793 SqrtElementwise,
7794 RecipElementwise,
7795 AbsElementwise,
7796 TanhElementwise,
7797 ExpElementwise,
7798 LogElementwise,
7799 SinElementwise,
7800 CosElementwise,
7801 SigmoidElementwise,
7802 SiluElementwise,
7803 GeluElementwise,
7804 StepElementwise,
7805 SumReduce,
7806 MaxReduce,
7807 MinReduce,
7808 MeanReduce,
7809 MatMul,
7810 Conv2D,
7811 ConvTranspose2D,
7812 ReduceSumTo,
7813 ReduceMaxTo,
7814 FusedLinear,
7815 FlashAttn,
7816 PagedAttn,
7817 Affine,
7818 ClampElementwise,
7819 PowIElementwise,
7820 MaximumElementwise,
7821 MinimumElementwise,
7822 Concat,
7823 SoftmaxLastDim,
7824 RmsNormLastDim,
7825 LayerNormLastDim,
7826 IndexSelect,
7827 Gather,
7828 Rope,
7829 IndexAdd,
7830 ScatterAdd,
7831 QMatMul,
7832 Copy,
7833 ] {
7834 op_dtype_support.insert((op, f32_dt));
7835 }
7836 for op in [
7840 AddElementwise,
7841 SubElementwise,
7842 MulElementwise,
7843 DivElementwise,
7844 ReluElementwise,
7845 NegElementwise,
7846 SqrElementwise,
7847 SqrtElementwise,
7848 RecipElementwise,
7849 AbsElementwise,
7850 TanhElementwise,
7851 ExpElementwise,
7852 LogElementwise,
7853 SinElementwise,
7854 CosElementwise,
7855 SigmoidElementwise,
7856 SiluElementwise,
7857 GeluElementwise,
7858 StepElementwise,
7859 MaximumElementwise,
7860 MinimumElementwise,
7861 SumReduce,
7862 MaxReduce,
7863 MinReduce,
7864 MeanReduce,
7865 MatMul,
7866 Conv2D,
7867 ConvTranspose2D,
7868 ReduceSumTo,
7869 ReduceMaxTo,
7870 FusedLinear,
7871 FlashAttn,
7872 PagedAttn,
7873 ] {
7874 op_dtype_support.insert((op, DType::F64));
7875 }
7876 let half_elementwise_ops = [
7879 AddElementwise,
7880 SubElementwise,
7881 MulElementwise,
7882 DivElementwise,
7883 MaximumElementwise,
7884 MinimumElementwise,
7885 ReluElementwise,
7886 NegElementwise,
7887 SqrElementwise,
7888 SqrtElementwise,
7889 RecipElementwise,
7890 AbsElementwise,
7891 TanhElementwise,
7892 ExpElementwise,
7893 LogElementwise,
7894 SinElementwise,
7895 CosElementwise,
7896 SigmoidElementwise,
7897 SiluElementwise,
7898 GeluElementwise,
7899 StepElementwise,
7900 ];
7901 for op in half_elementwise_ops {
7902 op_dtype_support.insert((op, DType::BF16));
7903 op_dtype_support.insert((op, DType::F16));
7904 }
7905 for op in [SumReduce, MaxReduce, MinReduce, MeanReduce, MatMul] {
7907 op_dtype_support.insert((op, DType::BF16));
7908 op_dtype_support.insert((op, DType::F16));
7909 }
7910 for op in [
7915 SoftmaxLastDim,
7916 RmsNormLastDim,
7917 LayerNormLastDim,
7918 Rope,
7919 Conv2D,
7920 ConvTranspose2D,
7921 ReduceSumTo,
7922 ReduceMaxTo,
7923 FusedLinear,
7924 FlashAttn,
7925 PagedAttn,
7926 ] {
7927 op_dtype_support.insert((op, DType::BF16));
7928 op_dtype_support.insert((op, DType::F16));
7929 }
7930 for dt in [
7933 DType::F64,
7934 DType::BF16,
7935 DType::F16,
7936 DType::U32,
7937 DType::U8,
7938 DType::I16,
7939 DType::I32,
7940 DType::I64,
7941 ] {
7942 op_dtype_support.insert((Concat, dt));
7943 op_dtype_support.insert((IndexSelect, dt));
7944 op_dtype_support.insert((Gather, dt));
7945 }
7946 for dt in [DType::F64, DType::BF16, DType::F16] {
7948 op_dtype_support.insert((IndexAdd, dt));
7949 op_dtype_support.insert((ScatterAdd, dt));
7950 op_dtype_support.insert((Affine, dt));
7951 op_dtype_support.insert((ClampElementwise, dt));
7952 op_dtype_support.insert((PowIElementwise, dt));
7953 }
7954 for op in [SoftmaxLastDim, RmsNormLastDim, LayerNormLastDim, Rope] {
7956 op_dtype_support.insert((op, DType::F64));
7957 }
7958 for op in [ArgMaxDim, ArgMinDim] {
7960 op_dtype_support.insert((op, DType::U32));
7961 }
7962 for target in [DType::F32, DType::F64, DType::BF16, DType::F16] {
7967 op_dtype_support.insert((Cast, target));
7968 }
7969 let (compute_throughput_flops_per_ns, mem_bandwidth_bytes_per_ns) =
7970 crate::ranker::default_backend_rates(BackendId::Cpu);
7971 BackendCapabilities {
7972 backend_id: BackendId::Cpu,
7973 device_location: DeviceLocation::Cpu,
7974 op_dtype_support,
7975 required_alignment: 64,
7976 access_granularity_bits: 8,
7977 transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
7978 storage_substrate: SubstrateClass::HostBytes,
7979 compute_throughput_flops_per_ns,
7980 mem_bandwidth_bytes_per_ns,
7981 }
7982}
7983
7984fn substrate_for_backend(backend: BackendId) -> SubstrateClass {
7988 match backend {
7989 BackendId::Cpu => SubstrateClass::HostBytes,
7990 BackendId::Cuda => SubstrateClass::CudaUntyped,
7991 BackendId::Vulkan => SubstrateClass::VulkanBuffer,
7992 BackendId::Metal => SubstrateClass::MetalBuffer,
7993 _ => SubstrateClass::HostBytes,
7996 }
7997}
7998
7999pub fn derive_backend_caps(
8035 backend: BackendId,
8036 device_location: DeviceLocation,
8037 table: &KernelBindingTable,
8038) -> BackendCapabilities {
8039 use std::collections::HashSet;
8040 let mut op_dtype_support: HashSet<(OpKind, DType)> = HashSet::new();
8041 for (op, dtypes, this_backend) in table.iter_keys() {
8042 if this_backend != backend {
8043 continue;
8044 }
8045 if let Some(&output_dt) = dtypes.last() {
8046 op_dtype_support.insert((op, output_dt));
8047 }
8048 }
8049 let transfer_paths = if device_location == DeviceLocation::Cpu {
8054 vec![(DeviceLocation::Cpu, TransferPath::SameDevice)]
8055 } else {
8056 vec![(DeviceLocation::Cpu, TransferPath::HostStaging)]
8057 };
8058 let (required_alignment, access_granularity_bits) = match backend {
8059 BackendId::Cpu => (64, 8),
8060 _ => (256, 8),
8064 };
8065 let (compute_throughput_flops_per_ns, mem_bandwidth_bytes_per_ns) =
8066 crate::ranker::default_backend_rates(backend);
8067 BackendCapabilities {
8068 backend_id: backend,
8069 device_location,
8070 op_dtype_support,
8071 required_alignment,
8072 access_granularity_bits,
8073 transfer_paths,
8074 storage_substrate: substrate_for_backend(backend),
8075 compute_throughput_flops_per_ns,
8076 mem_bandwidth_bytes_per_ns,
8077 }
8078}
8079
8080fn register_derived_gpu_caps(table: &KernelBindingTable) {
8100 use std::collections::HashSet;
8101 let gpu_backends: HashSet<BackendId> = table
8103 .iter_keys()
8104 .map(|(_, _, backend)| backend)
8105 .filter(|b| *b != BackendId::Cpu)
8106 .collect();
8107 for backend in gpu_backends {
8108 let device_location = backend.default_location();
8110 register_backend_capabilities(derive_backend_caps(backend, device_location, table));
8111 }
8112}
8113
8114#[inline]
8124pub(crate) fn lock_trace(what: &str) {
8125 if std::env::var_os("FUEL_LOCK_TRACE").is_some() {
8126 eprintln!("[locktrace] t={:?} {}", std::thread::current().id(), what);
8127 }
8128}
8129
8130pub fn global_registry() -> std::sync::RwLockReadGuard<'static, CapabilityRegistry> {
8131 lock_trace("want REGISTRY.oncelock+read");
8132 let l = GLOBAL_REGISTRY.get_or_init(|| {
8133 lock_trace(" REGISTRY init: begin");
8134 let mut r = CapabilityRegistry::new();
8135 r.register(default_cpu_caps());
8136 lock_trace(" REGISTRY init: end");
8137 RwLock::new(r)
8138 });
8139 let g = l.read().unwrap();
8140 lock_trace("got REGISTRY.read");
8141 g
8142}
8143
8144pub fn register_backend_capabilities(caps: BackendCapabilities) {
8151 lock_trace("want REGISTRY.oncelock+WRITE (from register_backend_capabilities)");
8152 let lock = GLOBAL_REGISTRY.get_or_init(|| {
8153 lock_trace(" REGISTRY init: begin (via register_backend_capabilities)");
8154 let mut r = CapabilityRegistry::new();
8155 r.register(default_cpu_caps());
8156 lock_trace(" REGISTRY init: end");
8157 RwLock::new(r)
8158 });
8159 lock.write().unwrap().register(caps);
8160 lock_trace("got+released REGISTRY.WRITE");
8161 bump_topology_generation();
8162}
8163
8164pub fn global_bindings() -> Arc<KernelBindingTable> {
8186 lock_trace("want BINDINGS.oncelock+snapshot");
8187 let cell = bindings_cell();
8188 let snapshot = {
8189 let guard = cell.read().unwrap_or_else(|e| e.into_inner());
8194 Arc::clone(&guard)
8195 };
8197 lock_trace("got BINDINGS snapshot (guard already released)");
8198 snapshot
8199}
8200
8201fn register_optional_backends(table: &mut KernelBindingTable) {
8205 #[cfg(feature = "cuda")]
8206 {
8207 register_cuda_kernels(table);
8208 crate::baracuda_dispatch::register_baracuda_cuda_kernels(table);
8209 table.fill_unset_cost_for_backend(BackendId::Cuda, crate::cost::default_cost_for_op_kind);
8219 }
8220 #[cfg(feature = "vulkan")]
8221 {
8222 crate::vulkan_dispatch::register_vulkan_kernels(table);
8223 }
8224
8225 register_derived_gpu_caps(table);
8235
8236 let _ = table;
8237}
8238
8239pub fn extend_global_bindings(register: impl FnOnce(&mut KernelBindingTable)) {
8252 let cell = bindings_cell();
8253 {
8254 lock_trace("want BINDINGS.WRITER (extend_global_bindings)");
8259 let _writer = BINDINGS_WRITER.lock().unwrap_or_else(|e| e.into_inner());
8260 lock_trace("got BINDINGS.WRITER -- cloning table, extender runs OFF the RwLock");
8261
8262 let mut next = {
8263 let guard = cell.read().unwrap_or_else(|e| e.into_inner());
8264 (**guard).clone()
8265 };
8266 register(&mut next);
8267 lock_trace(" extender returned");
8268 next.finalize()
8274 .expect("KernelBindingTable: duplicate kernel registration after extend");
8275
8276 {
8278 let mut guard = cell.write().unwrap_or_else(|e| e.into_inner());
8279 *guard = Arc::new(next);
8280 }
8281 lock_trace("released BINDINGS.WRITE (swap only)");
8282 }
8283 bump_topology_generation();
8284}
8285
8286const FUSED_LINEAR_QUANT_CONTRACT: &str =
8290 include_str!("../kernel-contracts/fused/linear-quant.fkc.md");
8291
8292fn register_cpu_linear_quant_fused_from_contract(r: &mut crate::fused::FusedKernelRegistry) {
8324 let provider =
8325 crate::fkc::import_bundle_str(FUSED_LINEAR_QUANT_CONTRACT, &crate::fkc::CpuLinkRegistry)
8326 .expect(
8327 "authored linear-quant fused contract must import \
8328 (embedded via include_str!, resolved through CpuLinkRegistry)",
8329 );
8330 debug_assert!(
8331 provider.primitives.is_empty(),
8332 "linear-quant bundle declares only fused ops",
8333 );
8334 let mut table = KernelBindingTable::new();
8335 provider
8336 .register_into(&mut table, r)
8337 .expect("linear-quant fused contract must register into the fused registry");
8338}
8339
8340const FUSED_NORM_SOFTMAX_CONTRACT: &str =
8344 include_str!("../kernel-contracts/fused/norm-softmax.fkc.md");
8345
8346fn register_cpu_norm_softmax_fused_from_contract(r: &mut crate::fused::FusedKernelRegistry) {
8370 let provider =
8371 crate::fkc::import_bundle_str(FUSED_NORM_SOFTMAX_CONTRACT, &crate::fkc::CpuLinkRegistry)
8372 .expect(
8373 "authored norm-softmax fused contract must import \
8374 (embedded via include_str!, resolved through CpuLinkRegistry)",
8375 );
8376 debug_assert!(
8377 provider.primitives.is_empty(),
8378 "norm-softmax bundle declares only fused ops",
8379 );
8380 let mut table = KernelBindingTable::new();
8381 provider
8382 .register_into(&mut table, r)
8383 .expect("norm-softmax fused contract must register into the fused registry");
8384}
8385
8386const FUSED_CONV_ROPE_CONTRACT: &str = include_str!("../kernel-contracts/fused/conv-rope.fkc.md");
8390
8391fn register_cpu_conv_rope_fused_from_contract(r: &mut crate::fused::FusedKernelRegistry) {
8428 let provider =
8429 crate::fkc::import_bundle_str(FUSED_CONV_ROPE_CONTRACT, &crate::fkc::CpuLinkRegistry)
8430 .expect(
8431 "authored conv-rope fused contract must import \
8432 (embedded via include_str!, resolved through CpuLinkRegistry)",
8433 );
8434 debug_assert!(
8435 provider.primitives.is_empty(),
8436 "conv-rope bundle declares only fused ops",
8437 );
8438 let mut table = KernelBindingTable::new();
8439 provider
8440 .register_into(&mut table, r)
8441 .expect("conv-rope fused contract must register into the fused registry");
8442}
8443
8444pub fn register_default_fused_kernels(r: &mut crate::fused::FusedKernelRegistry) {
8478 use crate::fused::{
8484 ATTN_BACKWARD_CPU_PRECISION, ATTN_CPU_PRECISION, NF4_MATMUL_CPU_PRECISION,
8485 cost_attn_backward_cpu, cost_attn_cpu, cost_nf4_matmul_cpu,
8486 };
8487 use crate::register_fused;
8488 use fuel_graph::registry::FusedOps;
8489
8490 const FA_F32_NOA: &[DType] = &[DType::F32, DType::F32, DType::F32, DType::F32];
8502 const FA_F32_A: &[DType] = &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32];
8503 const FA_F64_NOA: &[DType] = &[DType::F64, DType::F64, DType::F64, DType::F64];
8504 const FA_F64_A: &[DType] = &[DType::F64, DType::F64, DType::F64, DType::F64, DType::F64];
8505 const FA_BF16_NOA: &[DType] = &[DType::BF16, DType::BF16, DType::BF16, DType::BF16];
8506 const FA_BF16_A: &[DType] = &[
8507 DType::BF16,
8508 DType::BF16,
8509 DType::BF16,
8510 DType::BF16,
8511 DType::BF16,
8512 ];
8513 const FA_F16_NOA: &[DType] = &[DType::F16, DType::F16, DType::F16, DType::F16];
8514 const FA_F16_A: &[DType] = &[DType::F16, DType::F16, DType::F16, DType::F16, DType::F16];
8515
8516 const FAB_F32_NOA: &[DType] = &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32];
8520 const FAB_F32_A: &[DType] = &[
8521 DType::F32,
8522 DType::F32,
8523 DType::F32,
8524 DType::F32,
8525 DType::F32,
8526 DType::F32,
8527 ];
8528 const FAB_F64_NOA: &[DType] = &[DType::F64, DType::F64, DType::F64, DType::F64, DType::F64];
8529 const FAB_F64_A: &[DType] = &[
8530 DType::F64,
8531 DType::F64,
8532 DType::F64,
8533 DType::F64,
8534 DType::F64,
8535 DType::F64,
8536 ];
8537 const FAB_BF16_NOA: &[DType] = &[
8538 DType::BF16,
8539 DType::BF16,
8540 DType::BF16,
8541 DType::BF16,
8542 DType::BF16,
8543 ];
8544 const FAB_BF16_A: &[DType] = &[
8545 DType::BF16,
8546 DType::BF16,
8547 DType::BF16,
8548 DType::BF16,
8549 DType::BF16,
8550 DType::BF16,
8551 ];
8552 const FAB_F16_NOA: &[DType] = &[DType::F16, DType::F16, DType::F16, DType::F16, DType::F16];
8553 const FAB_F16_A: &[DType] = &[
8554 DType::F16,
8555 DType::F16,
8556 DType::F16,
8557 DType::F16,
8558 DType::F16,
8559 DType::F16,
8560 ];
8561
8562 const PA_F32_NOA: &[DType] = &[
8564 DType::F32,
8565 DType::F32,
8566 DType::F32,
8567 DType::U32,
8568 DType::U32,
8569 DType::F32,
8570 ];
8571 const PA_F32_A: &[DType] = &[
8572 DType::F32,
8573 DType::F32,
8574 DType::F32,
8575 DType::U32,
8576 DType::U32,
8577 DType::F32,
8578 DType::F32,
8579 ];
8580 const PA_F64_NOA: &[DType] = &[
8581 DType::F64,
8582 DType::F64,
8583 DType::F64,
8584 DType::U32,
8585 DType::U32,
8586 DType::F64,
8587 ];
8588 const PA_F64_A: &[DType] = &[
8589 DType::F64,
8590 DType::F64,
8591 DType::F64,
8592 DType::U32,
8593 DType::U32,
8594 DType::F64,
8595 DType::F64,
8596 ];
8597 const PA_BF16_NOA: &[DType] = &[
8598 DType::BF16,
8599 DType::BF16,
8600 DType::BF16,
8601 DType::U32,
8602 DType::U32,
8603 DType::BF16,
8604 ];
8605 const PA_BF16_A: &[DType] = &[
8606 DType::BF16,
8607 DType::BF16,
8608 DType::BF16,
8609 DType::U32,
8610 DType::U32,
8611 DType::BF16,
8612 DType::BF16,
8613 ];
8614 const PA_F16_NOA: &[DType] = &[
8615 DType::F16,
8616 DType::F16,
8617 DType::F16,
8618 DType::U32,
8619 DType::U32,
8620 DType::F16,
8621 ];
8622 const PA_F16_A: &[DType] = &[
8623 DType::F16,
8624 DType::F16,
8625 DType::F16,
8626 DType::U32,
8627 DType::U32,
8628 DType::F16,
8629 DType::F16,
8630 ];
8631
8632 let cpu = BackendId::Cpu;
8639
8640 register_cpu_linear_quant_fused_from_contract(r);
8648
8649 register_cpu_norm_softmax_fused_from_contract(r);
8656
8657 register_cpu_conv_rope_fused_from_contract(r);
8666
8667 register_fused!(
8682 r,
8683 FusedOps::FLASH_ATTN,
8684 cpu,
8685 FA_F32_NOA,
8686 flash_attn_f32_cpu_wrapper,
8687 cost = cost_attn_cpu,
8688 precision = ATTN_CPU_PRECISION
8689 );
8690 register_fused!(
8691 r,
8692 FusedOps::FLASH_ATTN,
8693 cpu,
8694 FA_F32_A,
8695 flash_attn_f32_cpu_wrapper,
8696 cost = cost_attn_cpu,
8697 precision = ATTN_CPU_PRECISION
8698 );
8699 register_fused!(
8700 r,
8701 FusedOps::FLASH_ATTN,
8702 cpu,
8703 FA_F64_NOA,
8704 flash_attn_f64_cpu_wrapper,
8705 cost = cost_attn_cpu,
8706 precision = ATTN_CPU_PRECISION
8707 );
8708 register_fused!(
8709 r,
8710 FusedOps::FLASH_ATTN,
8711 cpu,
8712 FA_F64_A,
8713 flash_attn_f64_cpu_wrapper,
8714 cost = cost_attn_cpu,
8715 precision = ATTN_CPU_PRECISION
8716 );
8717 register_fused!(
8718 r,
8719 FusedOps::FLASH_ATTN,
8720 cpu,
8721 FA_BF16_NOA,
8722 flash_attn_bf16_cpu_wrapper,
8723 cost = cost_attn_cpu,
8724 precision = ATTN_CPU_PRECISION
8725 );
8726 register_fused!(
8727 r,
8728 FusedOps::FLASH_ATTN,
8729 cpu,
8730 FA_BF16_A,
8731 flash_attn_bf16_cpu_wrapper,
8732 cost = cost_attn_cpu,
8733 precision = ATTN_CPU_PRECISION
8734 );
8735 register_fused!(
8736 r,
8737 FusedOps::FLASH_ATTN,
8738 cpu,
8739 FA_F16_NOA,
8740 flash_attn_f16_cpu_wrapper,
8741 cost = cost_attn_cpu,
8742 precision = ATTN_CPU_PRECISION
8743 );
8744 register_fused!(
8745 r,
8746 FusedOps::FLASH_ATTN,
8747 cpu,
8748 FA_F16_A,
8749 flash_attn_f16_cpu_wrapper,
8750 cost = cost_attn_cpu,
8751 precision = ATTN_CPU_PRECISION
8752 );
8753
8754 register_fused!(
8759 r,
8760 FusedOps::FLASH_ATTN_BACKWARD_Q,
8761 cpu,
8762 FAB_F32_NOA,
8763 flash_attn_backward_q_f32_cpu_wrapper,
8764 cost = cost_attn_backward_cpu,
8765 precision = ATTN_BACKWARD_CPU_PRECISION
8766 );
8767 register_fused!(
8768 r,
8769 FusedOps::FLASH_ATTN_BACKWARD_Q,
8770 cpu,
8771 FAB_F32_A,
8772 flash_attn_backward_q_f32_cpu_wrapper,
8773 cost = cost_attn_backward_cpu,
8774 precision = ATTN_BACKWARD_CPU_PRECISION
8775 );
8776 register_fused!(
8777 r,
8778 FusedOps::FLASH_ATTN_BACKWARD_Q,
8779 cpu,
8780 FAB_F64_NOA,
8781 flash_attn_backward_q_f64_cpu_wrapper,
8782 cost = cost_attn_backward_cpu,
8783 precision = ATTN_BACKWARD_CPU_PRECISION
8784 );
8785 register_fused!(
8786 r,
8787 FusedOps::FLASH_ATTN_BACKWARD_Q,
8788 cpu,
8789 FAB_F64_A,
8790 flash_attn_backward_q_f64_cpu_wrapper,
8791 cost = cost_attn_backward_cpu,
8792 precision = ATTN_BACKWARD_CPU_PRECISION
8793 );
8794 register_fused!(
8795 r,
8796 FusedOps::FLASH_ATTN_BACKWARD_Q,
8797 cpu,
8798 FAB_BF16_NOA,
8799 flash_attn_backward_q_bf16_cpu_wrapper,
8800 cost = cost_attn_backward_cpu,
8801 precision = ATTN_BACKWARD_CPU_PRECISION
8802 );
8803 register_fused!(
8804 r,
8805 FusedOps::FLASH_ATTN_BACKWARD_Q,
8806 cpu,
8807 FAB_BF16_A,
8808 flash_attn_backward_q_bf16_cpu_wrapper,
8809 cost = cost_attn_backward_cpu,
8810 precision = ATTN_BACKWARD_CPU_PRECISION
8811 );
8812 register_fused!(
8813 r,
8814 FusedOps::FLASH_ATTN_BACKWARD_Q,
8815 cpu,
8816 FAB_F16_NOA,
8817 flash_attn_backward_q_f16_cpu_wrapper,
8818 cost = cost_attn_backward_cpu,
8819 precision = ATTN_BACKWARD_CPU_PRECISION
8820 );
8821 register_fused!(
8822 r,
8823 FusedOps::FLASH_ATTN_BACKWARD_Q,
8824 cpu,
8825 FAB_F16_A,
8826 flash_attn_backward_q_f16_cpu_wrapper,
8827 cost = cost_attn_backward_cpu,
8828 precision = ATTN_BACKWARD_CPU_PRECISION
8829 );
8830
8831 register_fused!(
8832 r,
8833 FusedOps::FLASH_ATTN_BACKWARD_K,
8834 cpu,
8835 FAB_F32_NOA,
8836 flash_attn_backward_k_f32_cpu_wrapper,
8837 cost = cost_attn_backward_cpu,
8838 precision = ATTN_BACKWARD_CPU_PRECISION
8839 );
8840 register_fused!(
8841 r,
8842 FusedOps::FLASH_ATTN_BACKWARD_K,
8843 cpu,
8844 FAB_F32_A,
8845 flash_attn_backward_k_f32_cpu_wrapper,
8846 cost = cost_attn_backward_cpu,
8847 precision = ATTN_BACKWARD_CPU_PRECISION
8848 );
8849 register_fused!(
8850 r,
8851 FusedOps::FLASH_ATTN_BACKWARD_K,
8852 cpu,
8853 FAB_F64_NOA,
8854 flash_attn_backward_k_f64_cpu_wrapper,
8855 cost = cost_attn_backward_cpu,
8856 precision = ATTN_BACKWARD_CPU_PRECISION
8857 );
8858 register_fused!(
8859 r,
8860 FusedOps::FLASH_ATTN_BACKWARD_K,
8861 cpu,
8862 FAB_F64_A,
8863 flash_attn_backward_k_f64_cpu_wrapper,
8864 cost = cost_attn_backward_cpu,
8865 precision = ATTN_BACKWARD_CPU_PRECISION
8866 );
8867 register_fused!(
8868 r,
8869 FusedOps::FLASH_ATTN_BACKWARD_K,
8870 cpu,
8871 FAB_BF16_NOA,
8872 flash_attn_backward_k_bf16_cpu_wrapper,
8873 cost = cost_attn_backward_cpu,
8874 precision = ATTN_BACKWARD_CPU_PRECISION
8875 );
8876 register_fused!(
8877 r,
8878 FusedOps::FLASH_ATTN_BACKWARD_K,
8879 cpu,
8880 FAB_BF16_A,
8881 flash_attn_backward_k_bf16_cpu_wrapper,
8882 cost = cost_attn_backward_cpu,
8883 precision = ATTN_BACKWARD_CPU_PRECISION
8884 );
8885 register_fused!(
8886 r,
8887 FusedOps::FLASH_ATTN_BACKWARD_K,
8888 cpu,
8889 FAB_F16_NOA,
8890 flash_attn_backward_k_f16_cpu_wrapper,
8891 cost = cost_attn_backward_cpu,
8892 precision = ATTN_BACKWARD_CPU_PRECISION
8893 );
8894 register_fused!(
8895 r,
8896 FusedOps::FLASH_ATTN_BACKWARD_K,
8897 cpu,
8898 FAB_F16_A,
8899 flash_attn_backward_k_f16_cpu_wrapper,
8900 cost = cost_attn_backward_cpu,
8901 precision = ATTN_BACKWARD_CPU_PRECISION
8902 );
8903
8904 register_fused!(
8905 r,
8906 FusedOps::FLASH_ATTN_BACKWARD_V,
8907 cpu,
8908 FAB_F32_NOA,
8909 flash_attn_backward_v_f32_cpu_wrapper,
8910 cost = cost_attn_backward_cpu,
8911 precision = ATTN_BACKWARD_CPU_PRECISION
8912 );
8913 register_fused!(
8914 r,
8915 FusedOps::FLASH_ATTN_BACKWARD_V,
8916 cpu,
8917 FAB_F32_A,
8918 flash_attn_backward_v_f32_cpu_wrapper,
8919 cost = cost_attn_backward_cpu,
8920 precision = ATTN_BACKWARD_CPU_PRECISION
8921 );
8922 register_fused!(
8923 r,
8924 FusedOps::FLASH_ATTN_BACKWARD_V,
8925 cpu,
8926 FAB_F64_NOA,
8927 flash_attn_backward_v_f64_cpu_wrapper,
8928 cost = cost_attn_backward_cpu,
8929 precision = ATTN_BACKWARD_CPU_PRECISION
8930 );
8931 register_fused!(
8932 r,
8933 FusedOps::FLASH_ATTN_BACKWARD_V,
8934 cpu,
8935 FAB_F64_A,
8936 flash_attn_backward_v_f64_cpu_wrapper,
8937 cost = cost_attn_backward_cpu,
8938 precision = ATTN_BACKWARD_CPU_PRECISION
8939 );
8940 register_fused!(
8941 r,
8942 FusedOps::FLASH_ATTN_BACKWARD_V,
8943 cpu,
8944 FAB_BF16_NOA,
8945 flash_attn_backward_v_bf16_cpu_wrapper,
8946 cost = cost_attn_backward_cpu,
8947 precision = ATTN_BACKWARD_CPU_PRECISION
8948 );
8949 register_fused!(
8950 r,
8951 FusedOps::FLASH_ATTN_BACKWARD_V,
8952 cpu,
8953 FAB_BF16_A,
8954 flash_attn_backward_v_bf16_cpu_wrapper,
8955 cost = cost_attn_backward_cpu,
8956 precision = ATTN_BACKWARD_CPU_PRECISION
8957 );
8958 register_fused!(
8959 r,
8960 FusedOps::FLASH_ATTN_BACKWARD_V,
8961 cpu,
8962 FAB_F16_NOA,
8963 flash_attn_backward_v_f16_cpu_wrapper,
8964 cost = cost_attn_backward_cpu,
8965 precision = ATTN_BACKWARD_CPU_PRECISION
8966 );
8967 register_fused!(
8968 r,
8969 FusedOps::FLASH_ATTN_BACKWARD_V,
8970 cpu,
8971 FAB_F16_A,
8972 flash_attn_backward_v_f16_cpu_wrapper,
8973 cost = cost_attn_backward_cpu,
8974 precision = ATTN_BACKWARD_CPU_PRECISION
8975 );
8976
8977 register_fused!(
8979 r,
8980 FusedOps::PAGED_ATTN,
8981 cpu,
8982 PA_F32_NOA,
8983 paged_attn_f32_cpu_wrapper,
8984 cost = cost_attn_cpu,
8985 precision = ATTN_CPU_PRECISION
8986 );
8987 register_fused!(
8988 r,
8989 FusedOps::PAGED_ATTN,
8990 cpu,
8991 PA_F32_A,
8992 paged_attn_f32_cpu_wrapper,
8993 cost = cost_attn_cpu,
8994 precision = ATTN_CPU_PRECISION
8995 );
8996 register_fused!(
8997 r,
8998 FusedOps::PAGED_ATTN,
8999 cpu,
9000 PA_F64_NOA,
9001 paged_attn_f64_cpu_wrapper,
9002 cost = cost_attn_cpu,
9003 precision = ATTN_CPU_PRECISION
9004 );
9005 register_fused!(
9006 r,
9007 FusedOps::PAGED_ATTN,
9008 cpu,
9009 PA_F64_A,
9010 paged_attn_f64_cpu_wrapper,
9011 cost = cost_attn_cpu,
9012 precision = ATTN_CPU_PRECISION
9013 );
9014 register_fused!(
9015 r,
9016 FusedOps::PAGED_ATTN,
9017 cpu,
9018 PA_BF16_NOA,
9019 paged_attn_bf16_cpu_wrapper,
9020 cost = cost_attn_cpu,
9021 precision = ATTN_CPU_PRECISION
9022 );
9023 register_fused!(
9024 r,
9025 FusedOps::PAGED_ATTN,
9026 cpu,
9027 PA_BF16_A,
9028 paged_attn_bf16_cpu_wrapper,
9029 cost = cost_attn_cpu,
9030 precision = ATTN_CPU_PRECISION
9031 );
9032 register_fused!(
9033 r,
9034 FusedOps::PAGED_ATTN,
9035 cpu,
9036 PA_F16_NOA,
9037 paged_attn_f16_cpu_wrapper,
9038 cost = cost_attn_cpu,
9039 precision = ATTN_CPU_PRECISION
9040 );
9041 register_fused!(
9042 r,
9043 FusedOps::PAGED_ATTN,
9044 cpu,
9045 PA_F16_A,
9046 paged_attn_f16_cpu_wrapper,
9047 cost = cost_attn_cpu,
9048 precision = ATTN_CPU_PRECISION
9049 );
9050
9051 const NF4_F32: &[DType] = &[DType::F32, DType::U8, DType::F32, DType::F32];
9062 const NF4_F16: &[DType] = &[DType::F16, DType::U8, DType::F32, DType::F16];
9063 const NF4_BF16: &[DType] = &[DType::BF16, DType::U8, DType::F32, DType::BF16];
9064 register_fused!(
9065 r,
9066 FusedOps::NF4_MATMUL,
9067 cpu,
9068 NF4_F32,
9069 nf4_matmul_f32_cpu_wrapper,
9070 cost = cost_nf4_matmul_cpu,
9071 precision = NF4_MATMUL_CPU_PRECISION
9072 );
9073 register_fused!(
9074 r,
9075 FusedOps::NF4_MATMUL,
9076 cpu,
9077 NF4_F16,
9078 nf4_matmul_f16_cpu_wrapper,
9079 cost = cost_nf4_matmul_cpu,
9080 precision = NF4_MATMUL_CPU_PRECISION
9081 );
9082 register_fused!(
9083 r,
9084 FusedOps::NF4_MATMUL,
9085 cpu,
9086 NF4_BF16,
9087 nf4_matmul_bf16_cpu_wrapper,
9088 cost = cost_nf4_matmul_cpu,
9089 precision = NF4_MATMUL_CPU_PRECISION
9090 );
9091}
9092
9093#[cfg(test)]
9094mod tests {
9095 use super::*;
9096
9097 #[test]
9125 fn linear_quant_fused_family_migrated_to_fkc_contract() {
9126 use crate::fused::{FusedKernelRegistry, KernelRevisionHash};
9127 use fuel_graph::registry::FusedOps;
9128
9129 let mut r = FusedKernelRegistry::new();
9130 register_default_fused_kernels(&mut r);
9131
9132 for (dt, expected) in [
9134 (
9135 DType::F32,
9136 fused_linear_f32_cpu_wrapper as *const () as usize,
9137 ),
9138 (
9139 DType::F64,
9140 fused_linear_f64_cpu_wrapper as *const () as usize,
9141 ),
9142 (
9143 DType::BF16,
9144 fused_linear_bf16_cpu_wrapper as *const () as usize,
9145 ),
9146 (
9147 DType::F16,
9148 fused_linear_f16_cpu_wrapper as *const () as usize,
9149 ),
9150 ] {
9151 let got = r
9152 .lookup_by_dtypes(FusedOps::FUSED_LINEAR, BackendId::Cpu, &[dt, dt, dt, dt])
9153 .unwrap_or_else(|| panic!("FUSED_LINEAR {dt:?} migrated impl present"));
9154 assert_eq!(
9155 got.kernel as usize, expected,
9156 "FUSED_LINEAR {dt:?} binds its exact per-dtype production wrapper",
9157 );
9158 assert_ne!(
9159 got.revision,
9160 KernelRevisionHash::UNTRACKED,
9161 "FKC-imported FUSED_LINEAR {dt:?} carries the contract's real revision \
9162 (hand-written register_fused! stamps UNTRACKED)",
9163 );
9164 }
9165
9166 let qm = r
9168 .lookup_by_dtypes(
9169 FusedOps::QMATMUL,
9170 BackendId::Cpu,
9171 &[DType::F32, DType::U32, DType::F32],
9172 )
9173 .expect("QMATMUL migrated impl present at [F32, U32, F32]");
9174 assert_eq!(
9175 qm.kernel as usize,
9176 qmatmul_f32_cpu_wrapper as *const () as usize
9177 );
9178 assert_ne!(qm.revision, KernelRevisionHash::UNTRACKED);
9179
9180 for (dt, expected) in [
9182 (
9183 DType::F32,
9184 inplace_affine_f32_cpu_wrapper as *const () as usize,
9185 ),
9186 (
9187 DType::F64,
9188 inplace_affine_f64_cpu_wrapper as *const () as usize,
9189 ),
9190 (
9191 DType::BF16,
9192 inplace_affine_bf16_cpu_wrapper as *const () as usize,
9193 ),
9194 (
9195 DType::F16,
9196 inplace_affine_f16_cpu_wrapper as *const () as usize,
9197 ),
9198 ] {
9199 let got = r
9200 .lookup_by_dtypes(FusedOps::INPLACE_AFFINE, BackendId::Cpu, &[dt, dt])
9201 .unwrap_or_else(|| panic!("INPLACE_AFFINE {dt:?} migrated impl present"));
9202 assert_eq!(got.kernel as usize, expected);
9203 assert_ne!(got.revision, KernelRevisionHash::UNTRACKED);
9204 }
9205
9206 for (dt, expected) in [
9208 (
9209 DType::F32,
9210 fused_softmax_cross_entropy_f32_cpu_wrapper as *const () as usize,
9211 ),
9212 (
9213 DType::F64,
9214 fused_softmax_cross_entropy_f64_cpu_wrapper as *const () as usize,
9215 ),
9216 (
9217 DType::BF16,
9218 fused_softmax_cross_entropy_bf16_cpu_wrapper as *const () as usize,
9219 ),
9220 (
9221 DType::F16,
9222 fused_softmax_cross_entropy_f16_cpu_wrapper as *const () as usize,
9223 ),
9224 ] {
9225 let got = r
9226 .lookup_by_dtypes(
9227 FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
9228 BackendId::Cpu,
9229 &[dt, DType::I64, DType::F32],
9230 )
9231 .unwrap_or_else(|| panic!("FSCE {dt:?} migrated impl present"));
9232 assert_eq!(got.kernel as usize, expected);
9233 assert_ne!(got.revision, KernelRevisionHash::UNTRACKED);
9234 }
9235
9236 let fa = r
9238 .lookup_by_dtypes(
9239 FusedOps::FLASH_ATTN,
9240 BackendId::Cpu,
9241 &[DType::F32, DType::F32, DType::F32, DType::F32],
9242 )
9243 .expect("FLASH_ATTN hand-written impl present");
9244 assert_eq!(
9245 fa.kernel as usize,
9246 flash_attn_f32_cpu_wrapper as *const () as usize
9247 );
9248 assert_eq!(
9249 fa.revision,
9250 KernelRevisionHash::UNTRACKED,
9251 "unmigrated FLASH_ATTN keeps its hand-written UNTRACKED revision",
9252 );
9253
9254 let nf4 = r
9256 .lookup_by_dtypes(
9257 FusedOps::NF4_MATMUL,
9258 BackendId::Cpu,
9259 &[DType::F32, DType::U8, DType::F32, DType::F32],
9260 )
9261 .expect("NF4_MATMUL hand-written impl present (AFFINE_BLOCK deferred)");
9262 assert_eq!(
9263 nf4.kernel as usize,
9264 nf4_matmul_f32_cpu_wrapper as *const () as usize
9265 );
9266 assert_eq!(
9267 nf4.revision,
9268 KernelRevisionHash::UNTRACKED,
9269 "deferred NF4_MATMUL keeps its hand-written UNTRACKED revision",
9270 );
9271 }
9272
9273 #[test]
9298 fn norm_softmax_fused_family_migrated_to_fkc_contract() {
9299 use crate::fused::{FusedKernelRegistry, KernelRevisionHash};
9300 use fuel_graph::registry::FusedOps;
9301
9302 let mut r = FusedKernelRegistry::new();
9303 register_default_fused_kernels(&mut r);
9304
9305 let forward = [
9307 (
9308 FusedOps::SOFTMAX_LAST_DIM,
9309 [
9310 softmax_last_dim_f32_cpu_wrapper as *const () as usize,
9311 softmax_last_dim_f64_cpu_wrapper as *const () as usize,
9312 softmax_last_dim_bf16_cpu_wrapper as *const () as usize,
9313 softmax_last_dim_f16_cpu_wrapper as *const () as usize,
9314 ],
9315 ),
9316 (
9317 FusedOps::RMS_NORM_LAST_DIM,
9318 [
9319 rms_norm_last_dim_f32_cpu_wrapper as *const () as usize,
9320 rms_norm_last_dim_f64_cpu_wrapper as *const () as usize,
9321 rms_norm_last_dim_bf16_cpu_wrapper as *const () as usize,
9322 rms_norm_last_dim_f16_cpu_wrapper as *const () as usize,
9323 ],
9324 ),
9325 (
9326 FusedOps::LAYER_NORM_LAST_DIM,
9327 [
9328 layer_norm_last_dim_f32_cpu_wrapper as *const () as usize,
9329 layer_norm_last_dim_f64_cpu_wrapper as *const () as usize,
9330 layer_norm_last_dim_bf16_cpu_wrapper as *const () as usize,
9331 layer_norm_last_dim_f16_cpu_wrapper as *const () as usize,
9332 ],
9333 ),
9334 ];
9335 for (id, wrappers) in forward {
9336 for (dt, expected) in [DType::F32, DType::F64, DType::BF16, DType::F16]
9337 .iter()
9338 .zip(wrappers)
9339 {
9340 let got = r
9341 .lookup_by_dtypes(id, BackendId::Cpu, &[*dt, *dt])
9342 .unwrap_or_else(|| panic!("{id:?} {dt:?} migrated impl present"));
9343 assert_eq!(
9344 got.kernel as usize, expected,
9345 "{id:?} {dt:?} binds its exact per-dtype production wrapper",
9346 );
9347 assert_ne!(
9348 got.revision,
9349 KernelRevisionHash::UNTRACKED,
9350 "FKC-imported {id:?} {dt:?} carries the contract's real revision \
9351 (hand-written register_fused! stamps UNTRACKED)",
9352 );
9353 assert!(
9354 got.precision.bit_stable_on_same_hardware,
9355 "the 2026-07-03 audited:true flip rode through as bit-stable for {id:?} {dt:?} \
9356 (NOT the UNAUDITED an audited:false contract would have lowered to)",
9357 );
9358 }
9359 }
9360
9361 let backward = [
9364 (
9365 FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
9366 [
9367 softmax_last_dim_backward_f32_cpu_wrapper as *const () as usize,
9368 softmax_last_dim_backward_f64_cpu_wrapper as *const () as usize,
9369 softmax_last_dim_backward_bf16_cpu_wrapper as *const () as usize,
9370 softmax_last_dim_backward_f16_cpu_wrapper as *const () as usize,
9371 ],
9372 ),
9373 (
9374 FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
9375 [
9376 layer_norm_last_dim_backward_f32_cpu_wrapper as *const () as usize,
9377 layer_norm_last_dim_backward_f64_cpu_wrapper as *const () as usize,
9378 layer_norm_last_dim_backward_bf16_cpu_wrapper as *const () as usize,
9379 layer_norm_last_dim_backward_f16_cpu_wrapper as *const () as usize,
9380 ],
9381 ),
9382 (
9383 FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
9384 [
9385 rms_norm_last_dim_backward_f32_cpu_wrapper as *const () as usize,
9386 rms_norm_last_dim_backward_f64_cpu_wrapper as *const () as usize,
9387 rms_norm_last_dim_backward_bf16_cpu_wrapper as *const () as usize,
9388 rms_norm_last_dim_backward_f16_cpu_wrapper as *const () as usize,
9389 ],
9390 ),
9391 (
9392 FusedOps::REDUCE_MAX_TO_BACKWARD,
9393 [
9394 reduce_max_to_backward_f32_cpu_wrapper as *const () as usize,
9395 reduce_max_to_backward_f64_cpu_wrapper as *const () as usize,
9396 reduce_max_to_backward_bf16_cpu_wrapper as *const () as usize,
9397 reduce_max_to_backward_f16_cpu_wrapper as *const () as usize,
9398 ],
9399 ),
9400 (
9401 FusedOps::POWI_BACKWARD,
9402 [
9403 powi_backward_f32_cpu_wrapper as *const () as usize,
9404 powi_backward_f64_cpu_wrapper as *const () as usize,
9405 powi_backward_bf16_cpu_wrapper as *const () as usize,
9406 powi_backward_f16_cpu_wrapper as *const () as usize,
9407 ],
9408 ),
9409 ];
9410 for (id, wrappers) in backward {
9411 for (dt, expected) in [DType::F32, DType::F64, DType::BF16, DType::F16]
9412 .iter()
9413 .zip(wrappers)
9414 {
9415 let got = r
9416 .lookup_by_dtypes(id, BackendId::Cpu, &[*dt, *dt, *dt])
9417 .unwrap_or_else(|| panic!("{id:?} {dt:?} migrated impl present"));
9418 assert_eq!(got.kernel as usize, expected);
9419 assert_ne!(
9420 got.revision,
9421 KernelRevisionHash::UNTRACKED,
9422 "FKC-imported {id:?} {dt:?} carries the contract's real revision",
9423 );
9424 assert!(
9425 got.precision.bit_stable_on_same_hardware,
9426 "the audited:true flip rode through as bit-stable for {id:?} {dt:?}",
9427 );
9428 }
9429 }
9430
9431 let fa = r
9434 .lookup_by_dtypes(
9435 FusedOps::FLASH_ATTN,
9436 BackendId::Cpu,
9437 &[DType::F32, DType::F32, DType::F32, DType::F32],
9438 )
9439 .expect("FLASH_ATTN hand-written impl present");
9440 assert_eq!(
9441 fa.revision,
9442 KernelRevisionHash::UNTRACKED,
9443 "unmigrated FLASH_ATTN keeps its hand-written UNTRACKED revision",
9444 );
9445 }
9446
9447 #[test]
9466 fn conv_rope_fused_family_migrated_to_fkc_contract() {
9467 use crate::fused::{FusedKernelRegistry, KernelRevisionHash};
9468 use fuel_graph::registry::FusedOps;
9469
9470 let mut r = FusedKernelRegistry::new();
9471 register_default_fused_kernels(&mut r);
9472
9473 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
9474
9475 let rope_w = [
9477 rope_f32_cpu_wrapper as *const () as usize,
9478 rope_f64_cpu_wrapper as *const () as usize,
9479 rope_bf16_cpu_wrapper as *const () as usize,
9480 rope_f16_cpu_wrapper as *const () as usize,
9481 ];
9482 for (dt, expected) in dts.iter().zip(rope_w) {
9483 let got = r
9484 .lookup_by_dtypes(FusedOps::ROPE, BackendId::Cpu, &[*dt, *dt, *dt, *dt])
9485 .unwrap_or_else(|| panic!("ROPE {dt:?} migrated impl present"));
9486 assert_eq!(got.kernel as usize, expected);
9487 assert_ne!(
9488 got.revision,
9489 KernelRevisionHash::UNTRACKED,
9490 "ROPE {dt:?} real revision"
9491 );
9492 assert!(
9493 got.precision.bit_stable_on_same_hardware,
9494 "audited:true rode through bit-stable for ROPE {dt:?}",
9495 );
9496 }
9497
9498 let conv = [
9501 (
9502 FusedOps::CONV2D,
9503 [
9504 conv2d_f32_cpu_wrapper as *const () as usize,
9505 conv2d_f64_cpu_wrapper as *const () as usize,
9506 conv2d_bf16_cpu_wrapper as *const () as usize,
9507 conv2d_f16_cpu_wrapper as *const () as usize,
9508 ],
9509 ),
9510 (
9511 FusedOps::CONV_TRANSPOSE2D,
9512 [
9513 conv_transpose2d_f32_cpu_wrapper as *const () as usize,
9514 conv_transpose2d_f64_cpu_wrapper as *const () as usize,
9515 conv_transpose2d_bf16_cpu_wrapper as *const () as usize,
9516 conv_transpose2d_f16_cpu_wrapper as *const () as usize,
9517 ],
9518 ),
9519 ];
9520 for (id, wrappers) in conv {
9521 for (dt, expected) in dts.iter().zip(wrappers) {
9522 for key in [vec![*dt, *dt, *dt], vec![*dt, *dt, *dt, *dt]] {
9523 let with_bias = key.len() == 4;
9524 let got = r
9525 .lookup_by_dtypes(id, BackendId::Cpu, &key)
9526 .unwrap_or_else(|| {
9527 panic!("{id:?} {dt:?} (with_bias={with_bias}) migrated impl present")
9528 });
9529 assert_eq!(got.kernel as usize, expected);
9530 assert_ne!(
9531 got.revision,
9532 KernelRevisionHash::UNTRACKED,
9533 "{id:?} {dt:?} (with_bias={with_bias}) real revision",
9534 );
9535 assert!(
9536 got.precision.bit_stable_on_same_hardware,
9537 "audited:true rode through bit-stable for {id:?} {dt:?} (with_bias={with_bias})",
9538 );
9539 }
9540 }
9541 }
9542
9543 let cc1d_w = [
9545 causal_conv1d_f32_cpu_wrapper as *const () as usize,
9546 causal_conv1d_f64_cpu_wrapper as *const () as usize,
9547 causal_conv1d_bf16_cpu_wrapper as *const () as usize,
9548 causal_conv1d_f16_cpu_wrapper as *const () as usize,
9549 ];
9550 for (dt, expected) in dts.iter().zip(cc1d_w) {
9551 let got = r
9552 .lookup_by_dtypes(
9553 FusedOps::CAUSAL_CONV1D,
9554 BackendId::Cpu,
9555 &[*dt, *dt, *dt, *dt],
9556 )
9557 .unwrap_or_else(|| panic!("CAUSAL_CONV1D {dt:?} migrated impl present"));
9558 assert_eq!(got.kernel as usize, expected);
9559 assert_ne!(got.revision, KernelRevisionHash::UNTRACKED);
9560 assert!(got.precision.bit_stable_on_same_hardware);
9561 }
9562
9563 let scan = [
9566 (
9567 FusedOps::SELECTIVE_SCAN,
9568 [
9569 selective_scan_f32_cpu_wrapper as *const () as usize,
9570 selective_scan_f64_cpu_wrapper as *const () as usize,
9571 selective_scan_bf16_cpu_wrapper as *const () as usize,
9572 selective_scan_f16_cpu_wrapper as *const () as usize,
9573 ],
9574 ),
9575 (
9576 FusedOps::SSD_CHUNK_SCAN,
9577 [
9578 ssd_chunk_scan_f32_cpu_wrapper as *const () as usize,
9579 ssd_chunk_scan_f64_cpu_wrapper as *const () as usize,
9580 ssd_chunk_scan_bf16_cpu_wrapper as *const () as usize,
9581 ssd_chunk_scan_f16_cpu_wrapper as *const () as usize,
9582 ],
9583 ),
9584 ];
9585 for (id, wrappers) in scan {
9586 for (dt, expected) in dts.iter().zip(wrappers) {
9587 let got = r
9588 .lookup_by_dtypes(id, BackendId::Cpu, &[*dt; 6])
9589 .unwrap_or_else(|| panic!("{id:?} {dt:?} migrated impl present"));
9590 assert_eq!(got.kernel as usize, expected);
9591 assert_ne!(
9592 got.revision,
9593 KernelRevisionHash::UNTRACKED,
9594 "{id:?} {dt:?} real revision",
9595 );
9596 assert!(
9597 got.precision.bit_stable_on_same_hardware,
9598 "audited:true rode through bit-stable for {id:?} {dt:?}",
9599 );
9600 }
9601 }
9602
9603 let nf4 = r
9606 .lookup_by_dtypes(
9607 FusedOps::NF4_MATMUL,
9608 BackendId::Cpu,
9609 &[DType::F32, DType::U8, DType::F32, DType::F32],
9610 )
9611 .expect("NF4_MATMUL hand-written impl present");
9612 assert_eq!(
9613 nf4.revision,
9614 KernelRevisionHash::UNTRACKED,
9615 "deferred NF4_MATMUL keeps its hand-written UNTRACKED revision",
9616 );
9617 }
9618
9619 #[test]
9647 fn precision_guarantee_lint_bit_stable_cpu_coverage_primitives() {
9652 use fuel_ir::dispatch::OpKind;
9653 use fuel_ir::probe::BackendId;
9654
9655 const KNOWN_GAPS: &[(OpKind, &str)] = &[];
9660
9661 const ALL_OP_KINDS: &[OpKind] = &[
9667 OpKind::MatMul,
9668 OpKind::AddElementwise,
9669 OpKind::SubElementwise,
9670 OpKind::MulElementwise,
9671 OpKind::DivElementwise,
9672 OpKind::ReluElementwise,
9673 OpKind::NegElementwise,
9674 OpKind::SqrElementwise,
9675 OpKind::SqrtElementwise,
9676 OpKind::RecipElementwise,
9677 OpKind::AbsElementwise,
9678 OpKind::TanhElementwise,
9679 OpKind::ExpElementwise,
9680 OpKind::LogElementwise,
9681 OpKind::SinElementwise,
9682 OpKind::CosElementwise,
9683 OpKind::SigmoidElementwise,
9684 OpKind::SiluElementwise,
9685 OpKind::GeluTanhElementwise,
9686 OpKind::StepElementwise,
9687 OpKind::SumReduce,
9688 OpKind::MaxReduce,
9689 OpKind::MinReduce,
9690 OpKind::MeanReduce,
9691 OpKind::Cast,
9692 OpKind::Conv2D,
9693 OpKind::ConvTranspose2D,
9694 OpKind::ReduceSumTo,
9695 OpKind::ReduceMaxTo,
9696 OpKind::FusedLinear,
9697 OpKind::FlashAttn,
9698 OpKind::PagedAttn,
9699 OpKind::Affine,
9700 OpKind::ClampElementwise,
9701 OpKind::PowIElementwise,
9702 OpKind::MaximumElementwise,
9703 OpKind::MinimumElementwise,
9704 OpKind::EqualElementwise,
9705 OpKind::NotEqualElementwise,
9706 OpKind::LessElementwise,
9707 OpKind::LessEqualElementwise,
9708 OpKind::GreaterElementwise,
9709 OpKind::GreaterEqualElementwise,
9710 OpKind::Where,
9711 OpKind::FloorElementwise,
9712 OpKind::CeilElementwise,
9713 OpKind::RoundElementwise,
9714 OpKind::SignElementwise,
9715 OpKind::ErfElementwise,
9716 OpKind::GeluElementwise,
9717 OpKind::PowElementwise,
9718 OpKind::RsqrtElementwise,
9719 OpKind::RemElementwise,
9720 OpKind::Flip,
9721 OpKind::Roll,
9722 OpKind::CumSum,
9723 OpKind::Pad,
9724 OpKind::PadBackward,
9725 OpKind::Triu,
9726 OpKind::Tril,
9727 OpKind::LogSoftmaxLastDim,
9728 OpKind::LogSoftmaxLastDimBackward,
9729 OpKind::MaskedFill,
9730 OpKind::Concat,
9731 OpKind::SoftmaxLastDim,
9732 OpKind::SoftmaxLastDimBackward,
9733 OpKind::RmsNormLastDim,
9734 OpKind::RmsNormLastDimBackward,
9735 OpKind::LayerNormLastDim,
9736 OpKind::LayerNormLastDimBackward,
9737 OpKind::ReduceMaxToBackward,
9738 OpKind::IndexSelect,
9739 OpKind::Gather,
9740 OpKind::Rope,
9741 OpKind::IndexAdd,
9742 OpKind::ScatterAdd,
9743 OpKind::ArgMaxDim,
9744 OpKind::ArgMinDim,
9745 OpKind::QMatMul,
9746 OpKind::Copy,
9747 OpKind::FusedSoftmaxCrossEntropy,
9748 OpKind::CausalConv1d,
9749 OpKind::SelectiveScan,
9750 OpKind::SsdChunkScan,
9751 OpKind::Nf4Matmul,
9752 ];
9753
9754 let mut table = KernelBindingTable::new();
9758 register_cpu_kernels(&mut table);
9759
9760 let mut by_op_kind: std::collections::HashMap<
9763 OpKind,
9764 Vec<crate::fused::PrecisionGuarantee>,
9765 > = std::collections::HashMap::new();
9766 for (op, _dtypes, backend, precision) in table.iter_precision() {
9767 if backend == BackendId::Cpu {
9768 by_op_kind.entry(op).or_default().push(precision);
9769 }
9770 }
9771
9772 let mut failures: Vec<String> = Vec::new();
9773 let mut covered = 0usize;
9774 let mut allowlisted = 0usize;
9775
9776 for op in ALL_OP_KINDS.iter().copied() {
9777 if let Some((_, reason)) = KNOWN_GAPS.iter().find(|(g, _)| *g == op) {
9778 allowlisted += 1;
9779 if by_op_kind.contains_key(&op) {
9780 failures.push(format!(
9781 "OpKind::{op:?} is on the KNOWN_GAPS allowlist but DOES \
9782 have a CPU registration now. Reason given was: \
9783 {reason:?}. Remove the allowlist entry to enable the \
9784 bit-stable lint for this op.",
9785 ));
9786 }
9787 continue;
9788 }
9789 let precisions = by_op_kind.get(&op);
9790 let has_bit_stable_cpu =
9791 precisions.is_some_and(|ps| ps.iter().any(|p| p.bit_stable_on_same_hardware));
9792 if has_bit_stable_cpu {
9793 covered += 1;
9794 } else {
9795 failures.push(format!(
9796 "OpKind::{op:?} has no bit-stable CPU registration. \
9797 Architecture v1.0 §05 requires the always-built backend \
9798 (fuel-cpu-backend) to provide at least one \
9799 `bit_stable_on_same_hardware: true` kernel per primitive \
9800 op. Either add a CPU registration in \
9801 register_cpu_kernels (the fill_unset_cpu_precision pass \
9802 at the end will upgrade it to PRIMITIVE_DETERMINISTIC_CPU \
9803 automatically), or add a line to KNOWN_GAPS above with a \
9804 documented reason.",
9805 ));
9806 }
9807 }
9808
9809 assert!(
9810 failures.is_empty(),
9811 "Architecture v1.0 bit-stable CPU coverage lint (primitives) failed:\n{}",
9812 failures.join("\n"),
9813 );
9814 assert_eq!(
9815 allowlisted, 0,
9816 "KNOWN_GAPS allowlist is empty by design; saw {allowlisted} allowlisted",
9817 );
9818 assert!(covered > 0, "lint covered 0 OpKinds — table appears empty",);
9823 for op in ALL_OP_KINDS {
9827 assert!(
9828 by_op_kind.contains_key(op),
9829 "OpKind::{op:?} has no CPU registration at all — either add \
9830 one in register_cpu_kernels or document the gap in \
9831 KNOWN_GAPS.",
9832 );
9833 }
9834 }
9835
9836 #[test]
9855 fn cost_lint_per_op_kind_cpu_coverage() {
9856 use fuel_ir::dispatch::OpKind;
9857 use fuel_ir::probe::BackendId;
9858
9859 const KNOWN_GAPS: &[(OpKind, &str)] = &[];
9860
9861 const ALL_OP_KINDS: &[OpKind] = &[
9862 OpKind::MatMul,
9863 OpKind::AddElementwise,
9864 OpKind::SubElementwise,
9865 OpKind::MulElementwise,
9866 OpKind::DivElementwise,
9867 OpKind::ReluElementwise,
9868 OpKind::NegElementwise,
9869 OpKind::SqrElementwise,
9870 OpKind::SqrtElementwise,
9871 OpKind::RecipElementwise,
9872 OpKind::AbsElementwise,
9873 OpKind::TanhElementwise,
9874 OpKind::ExpElementwise,
9875 OpKind::LogElementwise,
9876 OpKind::SinElementwise,
9877 OpKind::CosElementwise,
9878 OpKind::SigmoidElementwise,
9879 OpKind::SiluElementwise,
9880 OpKind::GeluTanhElementwise,
9881 OpKind::StepElementwise,
9882 OpKind::SumReduce,
9883 OpKind::MaxReduce,
9884 OpKind::MinReduce,
9885 OpKind::MeanReduce,
9886 OpKind::Cast,
9887 OpKind::Conv2D,
9888 OpKind::ConvTranspose2D,
9889 OpKind::ReduceSumTo,
9890 OpKind::ReduceMaxTo,
9891 OpKind::FusedLinear,
9892 OpKind::FlashAttn,
9893 OpKind::PagedAttn,
9894 OpKind::Affine,
9895 OpKind::ClampElementwise,
9896 OpKind::PowIElementwise,
9897 OpKind::MaximumElementwise,
9898 OpKind::MinimumElementwise,
9899 OpKind::EqualElementwise,
9900 OpKind::NotEqualElementwise,
9901 OpKind::LessElementwise,
9902 OpKind::LessEqualElementwise,
9903 OpKind::GreaterElementwise,
9904 OpKind::GreaterEqualElementwise,
9905 OpKind::Where,
9906 OpKind::FloorElementwise,
9907 OpKind::CeilElementwise,
9908 OpKind::RoundElementwise,
9909 OpKind::SignElementwise,
9910 OpKind::ErfElementwise,
9911 OpKind::GeluElementwise,
9912 OpKind::PowElementwise,
9913 OpKind::RsqrtElementwise,
9914 OpKind::RemElementwise,
9915 OpKind::Flip,
9916 OpKind::Roll,
9917 OpKind::CumSum,
9918 OpKind::Pad,
9919 OpKind::PadBackward,
9920 OpKind::Triu,
9921 OpKind::Tril,
9922 OpKind::LogSoftmaxLastDim,
9923 OpKind::LogSoftmaxLastDimBackward,
9924 OpKind::MaskedFill,
9925 OpKind::Concat,
9926 OpKind::SoftmaxLastDim,
9927 OpKind::SoftmaxLastDimBackward,
9928 OpKind::RmsNormLastDim,
9929 OpKind::RmsNormLastDimBackward,
9930 OpKind::LayerNormLastDim,
9931 OpKind::LayerNormLastDimBackward,
9932 OpKind::ReduceMaxToBackward,
9933 OpKind::IndexSelect,
9934 OpKind::Gather,
9935 OpKind::Rope,
9936 OpKind::IndexAdd,
9937 OpKind::ScatterAdd,
9938 OpKind::ArgMaxDim,
9939 OpKind::ArgMinDim,
9940 OpKind::QMatMul,
9941 OpKind::Copy,
9942 OpKind::FusedSoftmaxCrossEntropy,
9943 OpKind::CausalConv1d,
9944 OpKind::SelectiveScan,
9945 OpKind::SsdChunkScan,
9946 OpKind::Nf4Matmul,
9947 ];
9948
9949 let mut table = KernelBindingTable::new();
9950 register_cpu_kernels(&mut table);
9951
9952 let mut by_op_kind: std::collections::HashMap<OpKind, Vec<crate::kernel::CostFn>> =
9954 std::collections::HashMap::new();
9955 for (op, _dtypes, backend, cost) in table.iter_cost() {
9956 if backend == BackendId::Cpu {
9957 by_op_kind.entry(op).or_default().push(cost);
9958 }
9959 }
9960
9961 let unknown_sentinel = crate::kernel::unknown_cost as *const () as usize;
9962
9963 let mut failures: Vec<String> = Vec::new();
9964 for op in ALL_OP_KINDS.iter().copied() {
9965 if let Some((_, reason)) = KNOWN_GAPS.iter().find(|(g, _)| *g == op) {
9966 if let Some(costs) = by_op_kind.get(&op) {
9967 let has_real = costs.iter().any(|c| (*c as usize) != unknown_sentinel);
9968 if has_real {
9969 failures.push(format!(
9970 "OpKind::{op:?} is on the cost-lint KNOWN_GAPS \
9971 allowlist but DOES have a non-default cost fn \
9972 now. Reason given: {reason:?}. Remove the \
9973 allowlist entry.",
9974 ));
9975 }
9976 }
9977 continue;
9978 }
9979 let costs = by_op_kind.get(&op);
9980 let has_real_cost =
9981 costs.is_some_and(|cs| cs.iter().any(|c| (*c as usize) != unknown_sentinel));
9982 if !has_real_cost {
9983 failures.push(format!(
9984 "OpKind::{op:?} has no non-default cost fn in any CPU \
9985 registration. Either add an arm in \
9986 `crate::cost::default_cost_for_op_kind` (the \
9987 fill_unset_cpu_cost pass at the end of \
9988 register_cpu_kernels will pick it up automatically), \
9989 register an explicit cost via `register_full(...)`, \
9990 or add a line to KNOWN_GAPS with a documented reason.",
9991 ));
9992 }
9993 }
9994
9995 assert!(
9996 failures.is_empty(),
9997 "Phase 7.6 step 8 cost-coverage lint failed:\n{}",
9998 failures.join("\n"),
9999 );
10000 for op in ALL_OP_KINDS {
10004 assert!(
10005 by_op_kind.contains_key(op),
10006 "OpKind::{op:?} has no CPU registration at all.",
10007 );
10008 }
10009 }
10010
10011 fn cpu_caps() -> BackendCapabilities {
10012 BackendCapabilities {
10013 backend_id: BackendId::Cpu,
10014 device_location: DeviceLocation::Cpu,
10015 op_dtype_support: [
10016 (OpKind::MatMul, DType::F32),
10017 (OpKind::MatMul, DType::F64),
10018 (OpKind::AddElementwise, DType::F32),
10019 (OpKind::AddElementwise, DType::F64),
10020 ]
10021 .into_iter()
10022 .collect(),
10023 required_alignment: 64,
10024 access_granularity_bits: 8,
10025 transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
10026 storage_substrate: SubstrateClass::HostBytes,
10027 compute_throughput_flops_per_ns: 1.0,
10028 mem_bandwidth_bytes_per_ns: 4.0,
10029 }
10030 }
10031
10032 fn cuda_caps() -> BackendCapabilities {
10033 BackendCapabilities {
10034 backend_id: BackendId::Cuda,
10035 device_location: DeviceLocation::Cuda { gpu_id: 0 },
10036 op_dtype_support: [
10037 (OpKind::MatMul, DType::F32),
10038 (OpKind::MatMul, DType::F16),
10039 (OpKind::AddElementwise, DType::F32),
10040 ]
10041 .into_iter()
10042 .collect(),
10043 required_alignment: 256,
10044 access_granularity_bits: 8,
10045 transfer_paths: vec![
10046 (DeviceLocation::Cpu, TransferPath::DeviceCopy),
10047 (DeviceLocation::Cuda { gpu_id: 0 }, TransferPath::SameDevice),
10048 ],
10049 storage_substrate: SubstrateClass::CudaUntyped,
10050 compute_throughput_flops_per_ns: 30.0,
10051 mem_bandwidth_bytes_per_ns: 40.0,
10052 }
10053 }
10054
10055 #[test]
10057 fn empty_registry() {
10058 let r = CapabilityRegistry::new();
10059 assert!(r.backends().is_empty());
10060 let result = r.find_backend_for(OpKind::MatMul, DType::F32);
10061 assert!(result.is_err());
10062 }
10063
10064 #[test]
10066 fn find_backends_order_preserved() {
10067 let mut r = CapabilityRegistry::new();
10068 r.register(cuda_caps()); r.register(cpu_caps());
10070
10071 let backends = r.find_backends(OpKind::MatMul, DType::F32);
10072 assert_eq!(backends.len(), 2);
10073 assert_eq!(backends[0].backend_id, BackendId::Cuda);
10074 assert_eq!(backends[1].backend_id, BackendId::Cpu);
10075 }
10076
10077 #[test]
10079 fn find_backend_first_wins() {
10080 let mut r = CapabilityRegistry::new();
10081 r.register(cuda_caps());
10082 r.register(cpu_caps());
10083
10084 let chosen = r.find_backend_for(OpKind::MatMul, DType::F32).unwrap();
10085 assert_eq!(chosen.backend_id, BackendId::Cuda);
10086 }
10087
10088 #[test]
10090 fn cpu_handles_what_gpu_doesnt() {
10091 let mut r = CapabilityRegistry::new();
10092 r.register(cuda_caps());
10093 r.register(cpu_caps());
10094
10095 let chosen = r.find_backend_for(OpKind::MatMul, DType::F64).unwrap();
10097 assert_eq!(chosen.backend_id, BackendId::Cpu);
10098 }
10099
10100 #[test]
10102 fn unsupported_combo_errors_with_diagnostic() {
10103 let mut r = CapabilityRegistry::new();
10104 r.register(cpu_caps());
10105
10106 let err = match r.find_backend_for(OpKind::MatMul, DType::BF16) {
10107 Ok(_) => panic!("expected error"),
10108 Err(e) => e,
10109 };
10110 let msg = err.to_string();
10111 assert!(
10112 msg.contains("MatMul") || msg.contains("matmul"),
10113 "error names op: {msg}"
10114 );
10115 assert!(msg.contains("BF16"), "error names dtype: {msg}");
10116 assert!(msg.contains("Cpu"), "error names available backends: {msg}");
10117 }
10118
10119 #[test]
10121 fn transfer_matrix_same_device() {
10122 let r = CapabilityRegistry::new();
10123 let m = r.build_transfer_matrix();
10124 assert_eq!(
10125 m.path(DeviceLocation::Cpu, DeviceLocation::Cpu),
10126 Some(TransferPath::SameDevice)
10127 );
10128 }
10129
10130 #[test]
10132 fn transfer_matrix_built_from_caps() {
10133 let mut r = CapabilityRegistry::new();
10134 r.register(cuda_caps());
10135 let m = r.build_transfer_matrix();
10136
10137 assert_eq!(
10139 m.path(DeviceLocation::Cuda { gpu_id: 0 }, DeviceLocation::Cpu),
10140 Some(TransferPath::DeviceCopy)
10141 );
10142 }
10143
10144 #[test]
10147 fn host_staging_fallback() {
10148 let r = CapabilityRegistry::new();
10149 let m = r.build_transfer_matrix();
10150 assert_eq!(
10152 m.path_or_staging(DeviceLocation::Cpu, DeviceLocation::Cuda { gpu_id: 0 }),
10153 TransferPath::HostStaging
10154 );
10155 }
10156
10157 #[test]
10160 fn resolve_picks_first_match() {
10161 let mut r = CapabilityRegistry::new();
10162 r.register(cuda_caps());
10163 r.register(cpu_caps());
10164 assert_eq!(
10165 resolve_target_backend(&r, OpKind::MatMul, DType::F32).unwrap(),
10166 BackendId::Cuda
10167 );
10168 }
10169
10170 #[test]
10172 fn resolve_falls_back_to_cpu() {
10173 let mut r = CapabilityRegistry::new();
10174 r.register(cuda_caps());
10175 r.register(cpu_caps());
10176 assert_eq!(
10177 resolve_target_backend(&r, OpKind::MatMul, DType::F64).unwrap(),
10178 BackendId::Cpu
10179 );
10180 }
10181
10182 #[test]
10184 fn resolve_errors_on_unsupported() {
10185 let mut r = CapabilityRegistry::new();
10186 r.register(cpu_caps());
10187 let result = resolve_target_backend(&r, OpKind::MatMul, DType::BF16);
10188 assert!(result.is_err());
10189 }
10190
10191 #[test]
10194 fn resolve_residency_aware_prefers_local() {
10195 let mut r = CapabilityRegistry::new();
10196 r.register(cuda_caps());
10198 r.register(cpu_caps());
10199
10200 let chosen = resolve_target_backend_residency_aware(
10203 &r,
10204 OpKind::MatMul,
10205 DType::F32,
10206 &[DeviceLocation::Cpu],
10207 )
10208 .unwrap();
10209 assert_eq!(chosen, BackendId::Cpu);
10210 }
10211
10212 #[test]
10215 fn resolve_residency_aware_no_local_falls_back() {
10216 let mut r = CapabilityRegistry::new();
10217 r.register(cuda_caps());
10218 r.register(cpu_caps());
10219
10220 let chosen = resolve_target_backend_residency_aware(
10223 &r,
10224 OpKind::MatMul,
10225 DType::F32,
10226 &[DeviceLocation::Vulkan { gpu_id: 0 }],
10227 )
10228 .unwrap();
10229 assert_eq!(chosen, BackendId::Cuda);
10230 }
10231
10232 #[test]
10236 fn register_cpu_kernels_populates_table() {
10237 let mut table = KernelBindingTable::new();
10238 assert!(table.is_empty());
10239 register_cpu_kernels(&mut table);
10240 assert!(!table.is_empty());
10241 let _kernel = table
10243 .lookup(
10244 OpKind::AddElementwise,
10245 &[DType::F32, DType::F32, DType::F32],
10246 BackendId::Cpu,
10247 )
10248 .expect("registered");
10249 }
10250
10251 #[test]
10269 fn global_bindings_registers_binary_family_from_contract() {
10270 let table = global_bindings();
10271
10272 let families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10274 (
10275 OpKind::AddElementwise,
10276 [
10277 add_elementwise_f32_cpu_wrapper,
10278 add_elementwise_f64_cpu_wrapper,
10279 add_elementwise_bf16_cpu_wrapper,
10280 add_elementwise_f16_cpu_wrapper,
10281 ],
10282 ),
10283 (
10284 OpKind::SubElementwise,
10285 [
10286 sub_elementwise_f32_cpu_wrapper,
10287 sub_elementwise_f64_cpu_wrapper,
10288 sub_elementwise_bf16_cpu_wrapper,
10289 sub_elementwise_f16_cpu_wrapper,
10290 ],
10291 ),
10292 (
10293 OpKind::MulElementwise,
10294 [
10295 mul_elementwise_f32_cpu_wrapper,
10296 mul_elementwise_f64_cpu_wrapper,
10297 mul_elementwise_bf16_cpu_wrapper,
10298 mul_elementwise_f16_cpu_wrapper,
10299 ],
10300 ),
10301 (
10302 OpKind::DivElementwise,
10303 [
10304 div_elementwise_f32_cpu_wrapper,
10305 div_elementwise_f64_cpu_wrapper,
10306 div_elementwise_bf16_cpu_wrapper,
10307 div_elementwise_f16_cpu_wrapper,
10308 ],
10309 ),
10310 (
10311 OpKind::MaximumElementwise,
10312 [
10313 maximum_elementwise_f32_cpu_wrapper,
10314 maximum_elementwise_f64_cpu_wrapper,
10315 maximum_elementwise_bf16_cpu_wrapper,
10316 maximum_elementwise_f16_cpu_wrapper,
10317 ],
10318 ),
10319 (
10320 OpKind::MinimumElementwise,
10321 [
10322 minimum_elementwise_f32_cpu_wrapper,
10323 minimum_elementwise_f64_cpu_wrapper,
10324 minimum_elementwise_bf16_cpu_wrapper,
10325 minimum_elementwise_f16_cpu_wrapper,
10326 ],
10327 ),
10328 (
10329 OpKind::PowElementwise,
10330 [
10331 pow_elementwise_f32_cpu_wrapper,
10332 pow_elementwise_f64_cpu_wrapper,
10333 pow_elementwise_bf16_cpu_wrapper,
10334 pow_elementwise_f16_cpu_wrapper,
10335 ],
10336 ),
10337 (
10338 OpKind::RemElementwise,
10339 [
10340 rem_elementwise_f32_cpu_wrapper,
10341 rem_elementwise_f64_cpu_wrapper,
10342 rem_elementwise_bf16_cpu_wrapper,
10343 rem_elementwise_f16_cpu_wrapper,
10344 ],
10345 ),
10346 ];
10347 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10348
10349 let mut checked = 0usize;
10350 for (op, wrappers) in families {
10351 for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10352 let alts = table.lookup_alternatives(*op, &[*dt, *dt, *dt], BackendId::Cpu);
10353 let entry = alts
10354 .iter()
10355 .find(|e| e.kernel as usize == *expected as usize)
10356 .unwrap_or_else(|| {
10357 panic!(
10358 "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10359 FROM the elementwise-binary contract in global_bindings() \
10360 — found {} alternative(s) with sources {:?}",
10361 alts.len(),
10362 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10363 )
10364 });
10365 assert_eq!(
10366 entry.kernel_source, "portable-cpu",
10367 "{op:?}/{dt:?}: binary family must be contract-sourced \
10368 (kernel_source=\"portable-cpu\"); got {:?}",
10369 entry.kernel_source,
10370 );
10371 assert!(
10372 !entry.caps.strided_input,
10373 "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10374 );
10375 assert!(
10376 entry.precision.bit_stable_on_same_hardware,
10377 "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
10378 );
10379 checked += 1;
10380 }
10381 }
10382 assert_eq!(checked, 32, "all 8 ops × 4 dtypes checked");
10383 }
10384
10385 #[test]
10395 fn global_bindings_registers_affine_clamp_powi_family_from_contract() {
10396 let table = global_bindings();
10397 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10398
10399 let forward: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10401 (
10402 OpKind::Affine,
10403 [
10404 affine_f32_cpu_wrapper,
10405 affine_f64_cpu_wrapper,
10406 affine_bf16_cpu_wrapper,
10407 affine_f16_cpu_wrapper,
10408 ],
10409 ),
10410 (
10411 OpKind::ClampElementwise,
10412 [
10413 clamp_elementwise_f32_cpu_wrapper,
10414 clamp_f64_cpu_wrapper,
10415 clamp_bf16_cpu_wrapper,
10416 clamp_f16_cpu_wrapper,
10417 ],
10418 ),
10419 (
10420 OpKind::PowIElementwise,
10421 [
10422 powi_elementwise_f32_cpu_wrapper,
10423 powi_f64_cpu_wrapper,
10424 powi_bf16_cpu_wrapper,
10425 powi_f16_cpu_wrapper,
10426 ],
10427 ),
10428 ];
10429
10430 let mut checked = 0usize;
10431 for (op, wrappers) in forward {
10432 for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10433 let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
10434 let entry = alts
10435 .iter()
10436 .find(|e| e.kernel as usize == *expected as usize)
10437 .unwrap_or_else(|| {
10438 panic!(
10439 "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10440 FROM the affine-clamp-powi contract in global_bindings() \
10441 — found {} alternative(s) with sources {:?}",
10442 alts.len(),
10443 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10444 )
10445 });
10446 assert_eq!(
10447 entry.kernel_source, "portable-cpu",
10448 "{op:?}/{dt:?}: family must be contract-sourced \
10449 (kernel_source=\"portable-cpu\"); got {:?}",
10450 entry.kernel_source,
10451 );
10452 assert!(
10453 !entry.caps.strided_input,
10454 "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10455 );
10456 assert!(
10457 entry.precision.bit_stable_on_same_hardware,
10458 "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
10459 );
10460 checked += 1;
10461 }
10462 }
10463
10464 let bw: [crate::kernel::KernelRef; 4] = [
10466 powi_backward_f32_cpu_wrapper,
10467 powi_backward_f64_cpu_wrapper,
10468 powi_backward_bf16_cpu_wrapper,
10469 powi_backward_f16_cpu_wrapper,
10470 ];
10471 for (dt, expected) in dts.iter().zip(bw.iter()) {
10472 let alts = table.lookup_alternatives(
10473 OpKind::PowIElementwiseBackward,
10474 &[*dt, *dt, *dt],
10475 BackendId::Cpu,
10476 );
10477 let entry = alts
10478 .iter()
10479 .find(|e| e.kernel as usize == *expected as usize)
10480 .unwrap_or_else(|| {
10481 panic!(
10482 "PowIElementwiseBackward/{dt:?}/Cpu: the production wrapper must \
10483 be bound FROM the affine-clamp-powi contract in global_bindings() \
10484 — found {} alternative(s) with sources {:?}",
10485 alts.len(),
10486 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10487 )
10488 });
10489 assert_eq!(
10490 entry.kernel_source, "portable-cpu",
10491 "PowIElementwiseBackward/{dt:?}: must be contract-sourced; got {:?}",
10492 entry.kernel_source,
10493 );
10494 assert!(
10495 !entry.caps.strided_input,
10496 "PowIElementwiseBackward/{dt:?}: caps preserved (contiguous-only)",
10497 );
10498 assert!(
10499 entry.precision.bit_stable_on_same_hardware,
10500 "PowIElementwiseBackward/{dt:?}: the audited bit-stable claim rode through",
10501 );
10502 checked += 1;
10503 }
10504
10505 assert_eq!(checked, 16, "3 forward ops × 4 dtypes + powi_backward × 4");
10506 }
10507
10508 #[test]
10521 fn global_bindings_registers_unary_family_from_contract() {
10522 let table = global_bindings();
10523 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10524
10525 let families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10527 (
10528 OpKind::ReluElementwise,
10529 [
10530 relu_elementwise_f32_cpu_wrapper,
10531 relu_elementwise_f64_cpu_wrapper,
10532 relu_elementwise_bf16_cpu_wrapper,
10533 relu_elementwise_f16_cpu_wrapper,
10534 ],
10535 ),
10536 (
10537 OpKind::NegElementwise,
10538 [
10539 neg_elementwise_f32_cpu_wrapper,
10540 neg_elementwise_f64_cpu_wrapper,
10541 neg_elementwise_bf16_cpu_wrapper,
10542 neg_elementwise_f16_cpu_wrapper,
10543 ],
10544 ),
10545 (
10546 OpKind::SqrElementwise,
10547 [
10548 sqr_elementwise_f32_cpu_wrapper,
10549 sqr_elementwise_f64_cpu_wrapper,
10550 sqr_elementwise_bf16_cpu_wrapper,
10551 sqr_elementwise_f16_cpu_wrapper,
10552 ],
10553 ),
10554 (
10555 OpKind::SqrtElementwise,
10556 [
10557 sqrt_elementwise_f32_cpu_wrapper,
10558 sqrt_elementwise_f64_cpu_wrapper,
10559 sqrt_elementwise_bf16_cpu_wrapper,
10560 sqrt_elementwise_f16_cpu_wrapper,
10561 ],
10562 ),
10563 (
10564 OpKind::RecipElementwise,
10565 [
10566 recip_elementwise_f32_cpu_wrapper,
10567 recip_elementwise_f64_cpu_wrapper,
10568 recip_elementwise_bf16_cpu_wrapper,
10569 recip_elementwise_f16_cpu_wrapper,
10570 ],
10571 ),
10572 (
10573 OpKind::AbsElementwise,
10574 [
10575 abs_elementwise_f32_cpu_wrapper,
10576 abs_elementwise_f64_cpu_wrapper,
10577 abs_elementwise_bf16_cpu_wrapper,
10578 abs_elementwise_f16_cpu_wrapper,
10579 ],
10580 ),
10581 (
10582 OpKind::TanhElementwise,
10583 [
10584 tanh_elementwise_f32_cpu_wrapper,
10585 tanh_elementwise_f64_cpu_wrapper,
10586 tanh_elementwise_bf16_cpu_wrapper,
10587 tanh_elementwise_f16_cpu_wrapper,
10588 ],
10589 ),
10590 (
10591 OpKind::ExpElementwise,
10592 [
10593 exp_elementwise_f32_cpu_wrapper,
10594 exp_elementwise_f64_cpu_wrapper,
10595 exp_elementwise_bf16_cpu_wrapper,
10596 exp_elementwise_f16_cpu_wrapper,
10597 ],
10598 ),
10599 (
10600 OpKind::LogElementwise,
10601 [
10602 log_elementwise_f32_cpu_wrapper,
10603 log_elementwise_f64_cpu_wrapper,
10604 log_elementwise_bf16_cpu_wrapper,
10605 log_elementwise_f16_cpu_wrapper,
10606 ],
10607 ),
10608 (
10609 OpKind::SinElementwise,
10610 [
10611 sin_elementwise_f32_cpu_wrapper,
10612 sin_elementwise_f64_cpu_wrapper,
10613 sin_elementwise_bf16_cpu_wrapper,
10614 sin_elementwise_f16_cpu_wrapper,
10615 ],
10616 ),
10617 (
10618 OpKind::CosElementwise,
10619 [
10620 cos_elementwise_f32_cpu_wrapper,
10621 cos_elementwise_f64_cpu_wrapper,
10622 cos_elementwise_bf16_cpu_wrapper,
10623 cos_elementwise_f16_cpu_wrapper,
10624 ],
10625 ),
10626 (
10627 OpKind::SigmoidElementwise,
10628 [
10629 sigmoid_elementwise_f32_cpu_wrapper,
10630 sigmoid_elementwise_f64_cpu_wrapper,
10631 sigmoid_elementwise_bf16_cpu_wrapper,
10632 sigmoid_elementwise_f16_cpu_wrapper,
10633 ],
10634 ),
10635 (
10636 OpKind::SiluElementwise,
10637 [
10638 silu_elementwise_f32_cpu_wrapper,
10639 silu_elementwise_f64_cpu_wrapper,
10640 silu_elementwise_bf16_cpu_wrapper,
10641 silu_elementwise_f16_cpu_wrapper,
10642 ],
10643 ),
10644 (
10645 OpKind::StepElementwise,
10646 [
10647 step_elementwise_f32_cpu_wrapper,
10648 step_elementwise_f64_cpu_wrapper,
10649 step_elementwise_bf16_cpu_wrapper,
10650 step_elementwise_f16_cpu_wrapper,
10651 ],
10652 ),
10653 (
10654 OpKind::GeluTanhElementwise,
10655 [
10656 gelu_elementwise_f32_cpu_wrapper,
10657 gelu_elementwise_f64_cpu_wrapper,
10658 gelu_elementwise_bf16_cpu_wrapper,
10659 gelu_elementwise_f16_cpu_wrapper,
10660 ],
10661 ),
10662 (
10663 OpKind::FloorElementwise,
10664 [
10665 floor_elementwise_f32_cpu_wrapper,
10666 floor_elementwise_f64_cpu_wrapper,
10667 floor_elementwise_bf16_cpu_wrapper,
10668 floor_elementwise_f16_cpu_wrapper,
10669 ],
10670 ),
10671 (
10672 OpKind::CeilElementwise,
10673 [
10674 ceil_elementwise_f32_cpu_wrapper,
10675 ceil_elementwise_f64_cpu_wrapper,
10676 ceil_elementwise_bf16_cpu_wrapper,
10677 ceil_elementwise_f16_cpu_wrapper,
10678 ],
10679 ),
10680 (
10681 OpKind::RoundElementwise,
10682 [
10683 round_elementwise_f32_cpu_wrapper,
10684 round_elementwise_f64_cpu_wrapper,
10685 round_elementwise_bf16_cpu_wrapper,
10686 round_elementwise_f16_cpu_wrapper,
10687 ],
10688 ),
10689 (
10690 OpKind::SignElementwise,
10691 [
10692 sign_elementwise_f32_cpu_wrapper,
10693 sign_elementwise_f64_cpu_wrapper,
10694 sign_elementwise_bf16_cpu_wrapper,
10695 sign_elementwise_f16_cpu_wrapper,
10696 ],
10697 ),
10698 (
10699 OpKind::ErfElementwise,
10700 [
10701 erf_elementwise_f32_cpu_wrapper,
10702 erf_elementwise_f64_cpu_wrapper,
10703 erf_elementwise_bf16_cpu_wrapper,
10704 erf_elementwise_f16_cpu_wrapper,
10705 ],
10706 ),
10707 (
10708 OpKind::GeluElementwise,
10709 [
10710 gelu_erf_elementwise_f32_cpu_wrapper,
10711 gelu_erf_elementwise_f64_cpu_wrapper,
10712 gelu_erf_elementwise_bf16_cpu_wrapper,
10713 gelu_erf_elementwise_f16_cpu_wrapper,
10714 ],
10715 ),
10716 (
10717 OpKind::RsqrtElementwise,
10718 [
10719 rsqrt_elementwise_f32_cpu_wrapper,
10720 rsqrt_elementwise_f64_cpu_wrapper,
10721 rsqrt_elementwise_bf16_cpu_wrapper,
10722 rsqrt_elementwise_f16_cpu_wrapper,
10723 ],
10724 ),
10725 ];
10726
10727 let mut checked = 0usize;
10728 for (op, wrappers) in families {
10729 for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10730 let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
10731 let entry = alts
10732 .iter()
10733 .find(|e| e.kernel as usize == *expected as usize)
10734 .unwrap_or_else(|| {
10735 panic!(
10736 "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10737 FROM the elementwise-unary contract in global_bindings() \
10738 — found {} alternative(s) with sources {:?}",
10739 alts.len(),
10740 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10741 )
10742 });
10743 assert_eq!(
10744 entry.kernel_source, "portable-cpu",
10745 "{op:?}/{dt:?}: unary family must be contract-sourced \
10746 (kernel_source=\"portable-cpu\"); got {:?}",
10747 entry.kernel_source,
10748 );
10749 assert!(
10750 !entry.caps.strided_input,
10751 "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10752 );
10753 assert!(
10754 entry.precision.bit_stable_on_same_hardware,
10755 "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
10756 );
10757 checked += 1;
10758 }
10759 }
10760 assert_eq!(checked, 88, "all 22 ops × 4 dtypes checked");
10761 }
10762
10763 #[test]
10783 fn global_bindings_registers_compare_where_family_from_contract() {
10784 let table = global_bindings();
10785 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10786
10787 let compare_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10789 (
10790 OpKind::EqualElementwise,
10791 [
10792 eq_elementwise_f32_cpu_wrapper,
10793 eq_elementwise_f64_cpu_wrapper,
10794 eq_elementwise_bf16_cpu_wrapper,
10795 eq_elementwise_f16_cpu_wrapper,
10796 ],
10797 ),
10798 (
10799 OpKind::NotEqualElementwise,
10800 [
10801 ne_elementwise_f32_cpu_wrapper,
10802 ne_elementwise_f64_cpu_wrapper,
10803 ne_elementwise_bf16_cpu_wrapper,
10804 ne_elementwise_f16_cpu_wrapper,
10805 ],
10806 ),
10807 (
10808 OpKind::LessElementwise,
10809 [
10810 lt_elementwise_f32_cpu_wrapper,
10811 lt_elementwise_f64_cpu_wrapper,
10812 lt_elementwise_bf16_cpu_wrapper,
10813 lt_elementwise_f16_cpu_wrapper,
10814 ],
10815 ),
10816 (
10817 OpKind::LessEqualElementwise,
10818 [
10819 le_elementwise_f32_cpu_wrapper,
10820 le_elementwise_f64_cpu_wrapper,
10821 le_elementwise_bf16_cpu_wrapper,
10822 le_elementwise_f16_cpu_wrapper,
10823 ],
10824 ),
10825 (
10826 OpKind::GreaterElementwise,
10827 [
10828 gt_elementwise_f32_cpu_wrapper,
10829 gt_elementwise_f64_cpu_wrapper,
10830 gt_elementwise_bf16_cpu_wrapper,
10831 gt_elementwise_f16_cpu_wrapper,
10832 ],
10833 ),
10834 (
10835 OpKind::GreaterEqualElementwise,
10836 [
10837 ge_elementwise_f32_cpu_wrapper,
10838 ge_elementwise_f64_cpu_wrapper,
10839 ge_elementwise_bf16_cpu_wrapper,
10840 ge_elementwise_f16_cpu_wrapper,
10841 ],
10842 ),
10843 ];
10844
10845 let mut checked = 0usize;
10846 for (op, wrappers) in compare_families {
10847 for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10848 let alts = table.lookup_alternatives(*op, &[*dt, *dt, DType::Bool], BackendId::Cpu);
10851 let entry = alts
10852 .iter()
10853 .find(|e| e.kernel as usize == *expected as usize)
10854 .unwrap_or_else(|| {
10855 panic!(
10856 "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10857 FROM the compare-where contract in global_bindings() \
10858 — found {} alternative(s) with sources {:?}",
10859 alts.len(),
10860 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10861 )
10862 });
10863 assert_eq!(
10864 entry.kernel_source, "portable-cpu",
10865 "{op:?}/{dt:?}: compare family must be contract-sourced \
10866 (kernel_source=\"portable-cpu\"); got {:?}",
10867 entry.kernel_source,
10868 );
10869 assert!(
10870 !entry.caps.strided_input,
10871 "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10872 );
10873 assert!(
10874 entry.precision.bit_stable_on_same_hardware,
10875 "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
10876 );
10877 checked += 1;
10878 }
10879 }
10880
10881 let where_wrappers: [crate::kernel::KernelRef; 4] = [
10883 where_f32_cpu_wrapper,
10884 where_f64_cpu_wrapper,
10885 where_bf16_cpu_wrapper,
10886 where_f16_cpu_wrapper,
10887 ];
10888 for (dt, expected) in dts.iter().zip(where_wrappers.iter()) {
10889 let alts = table.lookup_alternatives(
10891 OpKind::Where,
10892 &[DType::Bool, *dt, *dt, *dt],
10893 BackendId::Cpu,
10894 );
10895 let entry = alts
10896 .iter()
10897 .find(|e| e.kernel as usize == *expected as usize)
10898 .unwrap_or_else(|| {
10899 panic!(
10900 "Where/{dt:?}/Cpu: the production wrapper must be bound FROM \
10901 the compare-where contract (where fans to [U8,T,T,T]) in \
10902 global_bindings() — found {} alternative(s) with sources {:?}",
10903 alts.len(),
10904 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10905 )
10906 });
10907 assert_eq!(
10908 entry.kernel_source, "portable-cpu",
10909 "Where/{dt:?}: where must be contract-sourced \
10910 (kernel_source=\"portable-cpu\"); got {:?}",
10911 entry.kernel_source,
10912 );
10913 assert!(
10914 !entry.caps.strided_input,
10915 "Where/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10916 );
10917 checked += 1;
10918 }
10919
10920 assert_eq!(checked, 28, "24 compare (6×4) + 4 where keys checked");
10921 }
10922
10923 #[test]
10940 fn global_bindings_registers_reduce_family_from_contract() {
10941 let table = global_bindings();
10942 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10943
10944 let reduce_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10946 (
10947 OpKind::SumReduce,
10948 [
10949 sum_reduce_f32_cpu_wrapper,
10950 sum_reduce_f64_cpu_wrapper,
10951 sum_reduce_bf16_cpu_wrapper,
10952 sum_reduce_f16_cpu_wrapper,
10953 ],
10954 ),
10955 (
10956 OpKind::MeanReduce,
10957 [
10958 mean_reduce_f32_cpu_wrapper,
10959 mean_reduce_f64_cpu_wrapper,
10960 mean_reduce_bf16_cpu_wrapper,
10961 mean_reduce_f16_cpu_wrapper,
10962 ],
10963 ),
10964 (
10965 OpKind::MaxReduce,
10966 [
10967 max_reduce_f32_cpu_wrapper,
10968 max_reduce_f64_cpu_wrapper,
10969 max_reduce_bf16_cpu_wrapper,
10970 max_reduce_f16_cpu_wrapper,
10971 ],
10972 ),
10973 (
10974 OpKind::MinReduce,
10975 [
10976 min_reduce_f32_cpu_wrapper,
10977 min_reduce_f64_cpu_wrapper,
10978 min_reduce_bf16_cpu_wrapper,
10979 min_reduce_f16_cpu_wrapper,
10980 ],
10981 ),
10982 ];
10983
10984 let mut checked = 0usize;
10985 for (op, wrappers) in reduce_families {
10986 for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10987 let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
10989 let entry = alts
10990 .iter()
10991 .find(|e| e.kernel as usize == *expected as usize)
10992 .unwrap_or_else(|| {
10993 panic!(
10994 "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10995 FROM the reduce contract in global_bindings() \
10996 — found {} alternative(s) with sources {:?}",
10997 alts.len(),
10998 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10999 )
11000 });
11001 assert_eq!(
11002 entry.kernel_source, "portable-cpu",
11003 "{op:?}/{dt:?}: reduce family must be contract-sourced \
11004 (kernel_source=\"portable-cpu\"); got {:?}",
11005 entry.kernel_source,
11006 );
11007 assert!(
11008 !entry.caps.strided_input,
11009 "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11010 );
11011 assert!(
11012 entry.precision.bit_stable_on_same_hardware,
11013 "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11014 );
11015 checked += 1;
11016 }
11017 }
11018 assert_eq!(checked, 16, "4 ops × 4 dtypes checked");
11019 }
11020
11021 #[test]
11033 fn global_bindings_registers_reduce_to_family_from_contract() {
11034 let table = global_bindings();
11035 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11036
11037 let unary_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11039 (
11040 OpKind::ReduceSumTo,
11041 [
11042 reduce_sum_to_f32_cpu_wrapper,
11043 reduce_sum_to_f64_cpu_wrapper,
11044 reduce_sum_to_bf16_cpu_wrapper,
11045 reduce_sum_to_f16_cpu_wrapper,
11046 ],
11047 ),
11048 (
11049 OpKind::ReduceMaxTo,
11050 [
11051 reduce_max_to_f32_cpu_wrapper,
11052 reduce_max_to_f64_cpu_wrapper,
11053 reduce_max_to_bf16_cpu_wrapper,
11054 reduce_max_to_f16_cpu_wrapper,
11055 ],
11056 ),
11057 ];
11058 let backward_family: (OpKind, [crate::kernel::KernelRef; 4]) = (
11061 OpKind::ReduceMaxToBackward,
11062 [
11063 reduce_max_to_backward_f32_cpu_wrapper,
11064 reduce_max_to_backward_f64_cpu_wrapper,
11065 reduce_max_to_backward_bf16_cpu_wrapper,
11066 reduce_max_to_backward_f16_cpu_wrapper,
11067 ],
11068 );
11069
11070 let assert_contract_bound =
11072 |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef| {
11073 let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11074 let entry = alts
11075 .iter()
11076 .find(|e| e.kernel as usize == expected as usize)
11077 .unwrap_or_else(|| {
11078 panic!(
11079 "{op:?}/{key:?}/Cpu: the production wrapper must be bound \
11080 FROM the reduce-to contract in global_bindings() \
11081 — found {} alternative(s) with sources {:?}",
11082 alts.len(),
11083 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11084 )
11085 });
11086 assert_eq!(
11087 entry.kernel_source, "portable-cpu",
11088 "{op:?}/{key:?}: reduce-to family must be contract-sourced \
11089 (kernel_source=\"portable-cpu\"); got {:?}",
11090 entry.kernel_source,
11091 );
11092 assert!(
11093 !entry.caps.strided_input,
11094 "{op:?}/{key:?}: caps preserved (contiguous-only, strided_input=false)",
11095 );
11096 assert!(
11097 entry.precision.bit_stable_on_same_hardware,
11098 "{op:?}/{key:?}: the contract's audited bit-stable claim rode through",
11099 );
11100 };
11101
11102 let mut checked = 0usize;
11103 for (op, wrappers) in unary_families {
11104 for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11105 assert_contract_bound(*op, &[*dt, *dt], *expected);
11106 checked += 1;
11107 }
11108 }
11109 let (op, wrappers) = backward_family;
11110 for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11111 assert_contract_bound(op, &[*dt, *dt, *dt], *expected);
11112 checked += 1;
11113 }
11114 assert_eq!(checked, 12, "3 ops × 4 dtypes checked");
11115 }
11116
11117 #[test]
11130 fn global_bindings_registers_norm_family_from_contract() {
11131 let table = global_bindings();
11132 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11133
11134 let norm_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11137 (
11138 OpKind::SoftmaxLastDim,
11139 [
11140 softmax_last_dim_f32_cpu_wrapper,
11141 softmax_last_dim_f64_cpu_wrapper,
11142 softmax_last_dim_bf16_cpu_wrapper,
11143 softmax_last_dim_f16_cpu_wrapper,
11144 ],
11145 ),
11146 (
11147 OpKind::LogSoftmaxLastDim,
11148 [
11149 log_softmax_f32_cpu_wrapper,
11150 log_softmax_f64_cpu_wrapper,
11151 log_softmax_bf16_cpu_wrapper,
11152 log_softmax_f16_cpu_wrapper,
11153 ],
11154 ),
11155 (
11156 OpKind::RmsNormLastDim,
11157 [
11158 rms_norm_last_dim_f32_cpu_wrapper,
11159 rms_norm_last_dim_f64_cpu_wrapper,
11160 rms_norm_last_dim_bf16_cpu_wrapper,
11161 rms_norm_last_dim_f16_cpu_wrapper,
11162 ],
11163 ),
11164 (
11165 OpKind::LayerNormLastDim,
11166 [
11167 layer_norm_last_dim_f32_cpu_wrapper,
11168 layer_norm_last_dim_f64_cpu_wrapper,
11169 layer_norm_last_dim_bf16_cpu_wrapper,
11170 layer_norm_last_dim_f16_cpu_wrapper,
11171 ],
11172 ),
11173 ];
11174
11175 let mut checked = 0usize;
11176 for (op, wrappers) in norm_families {
11177 for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11178 let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
11180 let entry = alts
11181 .iter()
11182 .find(|e| e.kernel as usize == *expected as usize)
11183 .unwrap_or_else(|| {
11184 panic!(
11185 "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11186 FROM the norm contract in global_bindings() \
11187 — found {} alternative(s) with sources {:?}",
11188 alts.len(),
11189 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11190 )
11191 });
11192 assert_eq!(
11193 entry.kernel_source, "portable-cpu",
11194 "{op:?}/{dt:?}: norm family must be contract-sourced \
11195 (kernel_source=\"portable-cpu\"); got {:?}",
11196 entry.kernel_source,
11197 );
11198 assert!(
11199 !entry.caps.strided_input,
11200 "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11201 );
11202 assert!(
11203 entry.precision.bit_stable_on_same_hardware,
11204 "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11205 );
11206 checked += 1;
11207 }
11208 }
11209 assert_eq!(checked, 16, "4 ops × 4 dtypes checked");
11210 }
11211
11212 #[test]
11227 fn global_bindings_registers_norm_backward_family_from_contract() {
11228 let table = global_bindings();
11229 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11230
11231 let backward_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11237 (
11238 OpKind::SoftmaxLastDimBackward,
11239 [
11240 softmax_last_dim_backward_f32_cpu_wrapper,
11241 softmax_last_dim_backward_f64_cpu_wrapper,
11242 softmax_last_dim_backward_bf16_cpu_wrapper,
11243 softmax_last_dim_backward_f16_cpu_wrapper,
11244 ],
11245 ),
11246 (
11247 OpKind::LogSoftmaxLastDimBackward,
11248 [
11249 log_softmax_backward_f32_cpu_wrapper,
11250 log_softmax_backward_f64_cpu_wrapper,
11251 log_softmax_backward_bf16_cpu_wrapper,
11252 log_softmax_backward_f16_cpu_wrapper,
11253 ],
11254 ),
11255 (
11256 OpKind::LayerNormLastDimBackward,
11257 [
11258 layer_norm_last_dim_backward_f32_cpu_wrapper,
11259 layer_norm_last_dim_backward_f64_cpu_wrapper,
11260 layer_norm_last_dim_backward_bf16_cpu_wrapper,
11261 layer_norm_last_dim_backward_f16_cpu_wrapper,
11262 ],
11263 ),
11264 (
11265 OpKind::RmsNormLastDimBackward,
11266 [
11267 rms_norm_last_dim_backward_f32_cpu_wrapper,
11268 rms_norm_last_dim_backward_f64_cpu_wrapper,
11269 rms_norm_last_dim_backward_bf16_cpu_wrapper,
11270 rms_norm_last_dim_backward_f16_cpu_wrapper,
11271 ],
11272 ),
11273 ];
11274
11275 let mut checked = 0usize;
11276 for (op, wrappers) in backward_families {
11277 for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11278 let alts = table.lookup_alternatives(*op, &[*dt, *dt, *dt], BackendId::Cpu);
11280 let entry = alts
11281 .iter()
11282 .find(|e| e.kernel as usize == *expected as usize)
11283 .unwrap_or_else(|| {
11284 panic!(
11285 "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11286 FROM the norm-backward contract in global_bindings() \
11287 — found {} alternative(s) with sources {:?}",
11288 alts.len(),
11289 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11290 )
11291 });
11292 assert_eq!(
11293 entry.kernel_source, "portable-cpu",
11294 "{op:?}/{dt:?}: norm-backward family must be contract-sourced \
11295 (kernel_source=\"portable-cpu\"); got {:?}",
11296 entry.kernel_source,
11297 );
11298 assert!(
11299 !entry.caps.strided_input,
11300 "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11301 );
11302 assert!(
11303 entry.precision.bit_stable_on_same_hardware,
11304 "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11305 );
11306 checked += 1;
11307 }
11308 }
11309 assert_eq!(checked, 16, "4 ops × 4 dtypes checked");
11310 }
11311
11312 #[test]
11330 fn global_bindings_registers_rope_family_from_contract() {
11331 let table = global_bindings();
11332 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11333 let expected_wrappers: [crate::kernel::KernelRef; 4] = [
11335 rope_f32_cpu_wrapper,
11336 rope_f64_cpu_wrapper,
11337 rope_bf16_cpu_wrapper,
11338 rope_f16_cpu_wrapper,
11339 ];
11340
11341 let mut checked = 0usize;
11342 for (dt, expected) in dts.iter().zip(expected_wrappers.iter()) {
11343 let alts =
11345 table.lookup_alternatives(OpKind::Rope, &[*dt, *dt, *dt, *dt], BackendId::Cpu);
11346 let entry = alts
11347 .iter()
11348 .find(|e| e.kernel as usize == *expected as usize)
11349 .unwrap_or_else(|| {
11350 panic!(
11351 "Rope/{dt:?}/Cpu: the production wrapper must be bound \
11352 FROM the rope contract in global_bindings() \
11353 — found {} alternative(s) with sources {:?}",
11354 alts.len(),
11355 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11356 )
11357 });
11358 assert_eq!(
11359 entry.kernel_source, "portable-cpu",
11360 "Rope/{dt:?}: rope family must be contract-sourced \
11361 (kernel_source=\"portable-cpu\"); got {:?}",
11362 entry.kernel_source,
11363 );
11364 assert!(
11365 !entry.caps.strided_input,
11366 "Rope/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11367 );
11368 assert!(
11369 entry.precision.bit_stable_on_same_hardware,
11370 "Rope/{dt:?}: the contract's audited bit-stable claim rode through",
11371 );
11372 checked += 1;
11373 }
11374 assert_eq!(checked, 4, "1 op × 4 dtypes checked");
11375 }
11376
11377 #[test]
11396 fn global_bindings_registers_ssm_family_from_contract() {
11397 let table = global_bindings();
11398 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11399
11400 let check = |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
11403 let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11404 let entry = alts
11405 .iter()
11406 .find(|e| e.kernel as usize == expected as usize)
11407 .unwrap_or_else(|| {
11408 panic!(
11409 "{label}/Cpu (key {key:?}): the production wrapper must be bound \
11410 FROM the ssm contract in global_bindings() — found {} \
11411 alternative(s) with sources {:?}",
11412 alts.len(),
11413 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11414 )
11415 });
11416 assert_eq!(
11417 entry.kernel_source, "portable-cpu",
11418 "{label}: family must be contract-sourced (kernel_source=\"portable-cpu\"); \
11419 got {:?}",
11420 entry.kernel_source,
11421 );
11422 assert!(
11423 !entry.caps.strided_input,
11424 "{label}: caps preserved (contiguous-only)"
11425 );
11426 assert!(
11427 entry.precision.bit_stable_on_same_hardware,
11428 "{label}: contract's bit-stable claim rode through",
11429 );
11430 };
11431
11432 let fsce: [crate::kernel::KernelRef; 4] = [
11434 fused_softmax_cross_entropy_f32_cpu_wrapper,
11435 fused_softmax_cross_entropy_f64_cpu_wrapper,
11436 fused_softmax_cross_entropy_bf16_cpu_wrapper,
11437 fused_softmax_cross_entropy_f16_cpu_wrapper,
11438 ];
11439 let conv: [crate::kernel::KernelRef; 4] = [
11440 causal_conv1d_f32_cpu_wrapper,
11441 causal_conv1d_f64_cpu_wrapper,
11442 causal_conv1d_bf16_cpu_wrapper,
11443 causal_conv1d_f16_cpu_wrapper,
11444 ];
11445 let sscan: [crate::kernel::KernelRef; 4] = [
11446 selective_scan_f32_cpu_wrapper,
11447 selective_scan_f64_cpu_wrapper,
11448 selective_scan_bf16_cpu_wrapper,
11449 selective_scan_f16_cpu_wrapper,
11450 ];
11451 let ssd: [crate::kernel::KernelRef; 4] = [
11452 ssd_chunk_scan_f32_cpu_wrapper,
11453 ssd_chunk_scan_f64_cpu_wrapper,
11454 ssd_chunk_scan_bf16_cpu_wrapper,
11455 ssd_chunk_scan_f16_cpu_wrapper,
11456 ];
11457
11458 let mut checked = 0usize;
11459 for (i, dt) in dts.iter().enumerate() {
11460 check(
11462 OpKind::FusedSoftmaxCrossEntropy,
11463 &[*dt, DType::I64, DType::F32],
11464 fsce[i],
11465 "FusedSoftmaxCrossEntropy",
11466 );
11467 check(OpKind::CausalConv1d, &[*dt; 4], conv[i], "CausalConv1d");
11469 check(OpKind::SelectiveScan, &[*dt; 6], sscan[i], "SelectiveScan");
11472 check(OpKind::SsdChunkScan, &[*dt; 6], ssd[i], "SsdChunkScan");
11475
11476 checked += 1;
11477 }
11478 assert_eq!(
11479 checked, 4,
11480 "4 ops × 4 dtypes checked (16 contract-sourced bindings)"
11481 );
11482 }
11483
11484 #[test]
11502 fn global_bindings_registers_conv_family_from_contract() {
11503 let table = global_bindings();
11504 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11505
11506 let conv2d_wrappers: [crate::kernel::KernelRef; 4] = [
11509 conv2d_f32_cpu_wrapper,
11510 conv2d_f64_cpu_wrapper,
11511 conv2d_bf16_cpu_wrapper,
11512 conv2d_f16_cpu_wrapper,
11513 ];
11514 let convt_wrappers: [crate::kernel::KernelRef; 4] = [
11516 conv_transpose2d_f32_cpu_wrapper,
11517 conv_transpose2d_f64_cpu_wrapper,
11518 conv_transpose2d_bf16_cpu_wrapper,
11519 conv_transpose2d_f16_cpu_wrapper,
11520 ];
11521
11522 let mut checked = 0usize;
11523 for (i, dt) in dts.iter().enumerate() {
11524 for (op, expected) in [
11525 (OpKind::Conv2D, conv2d_wrappers[i]),
11526 (OpKind::ConvTranspose2D, convt_wrappers[i]),
11527 ] {
11528 let no_bias: &[DType] = &[*dt, *dt, *dt];
11532 let with_bias: &[DType] = &[*dt, *dt, *dt, *dt];
11533 for (key, label) in [(no_bias, "no-bias"), (with_bias, "with-bias")] {
11534 let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11535 let entry = alts
11536 .iter()
11537 .find(|e| e.kernel as usize == expected as usize)
11538 .unwrap_or_else(|| {
11539 panic!(
11540 "{op:?}/{dt:?}/Cpu ({label}): the production wrapper must be \
11541 bound FROM the conv contract in global_bindings() — found {} \
11542 alternative(s) with sources {:?}",
11543 alts.len(),
11544 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11545 )
11546 });
11547 assert_eq!(
11548 entry.kernel_source, "portable-cpu",
11549 "{op:?}/{dt:?} ({label}): family must be contract-sourced \
11550 (kernel_source=\"portable-cpu\"); got {:?}",
11551 entry.kernel_source,
11552 );
11553 assert!(
11554 !entry.caps.strided_input,
11555 "{op:?}/{dt:?} ({label}): caps preserved (contiguous-only)",
11556 );
11557 assert!(
11558 entry.precision.bit_stable_on_same_hardware,
11559 "{op:?}/{dt:?} ({label}): contract's bit-stable claim rode through",
11560 );
11561 checked += 1;
11562 }
11563 }
11564 }
11565 assert_eq!(
11566 checked, 16,
11567 "2 ops × 4 dtypes × 2 operand-counts checked (16 contract-sourced bindings)"
11568 );
11569 }
11570
11571 #[test]
11595 fn global_bindings_registers_padding_family_from_contract() {
11596 let table = global_bindings();
11597 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11598 let pad_backward: [crate::kernel::KernelRef; 4] = [
11600 pad_backward_f32_cpu_wrapper,
11601 pad_backward_f64_cpu_wrapper,
11602 pad_backward_bf16_cpu_wrapper,
11603 pad_backward_f16_cpu_wrapper,
11604 ];
11605
11606 let mut checked = 0usize;
11607 for (i, dt) in dts.iter().enumerate() {
11608 let key: &[DType] = &[*dt, *dt];
11610 let expected = pad_backward[i];
11611 let alts = table.lookup_alternatives(OpKind::PadBackward, key, BackendId::Cpu);
11612 let entry = alts
11613 .iter()
11614 .find(|e| e.kernel as usize == expected as usize)
11615 .unwrap_or_else(|| {
11616 panic!(
11617 "PadBackward/{dt:?}/Cpu: the production wrapper must be bound \
11618 FROM the padding contract in global_bindings() — found {} \
11619 alternative(s) with sources {:?}",
11620 alts.len(),
11621 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11622 )
11623 });
11624 assert_eq!(
11625 entry.kernel_source, "portable-cpu",
11626 "PadBackward/{dt:?}: family must be contract-sourced \
11627 (kernel_source=\"portable-cpu\"); got {:?}",
11628 entry.kernel_source,
11629 );
11630 assert!(
11631 !entry.caps.strided_input,
11632 "PadBackward/{dt:?}: caps preserved (contiguous-only)",
11633 );
11634 assert!(
11635 entry.precision.bit_stable_on_same_hardware,
11636 "PadBackward/{dt:?}: contract's bit-stable claim rode through",
11637 );
11638 checked += 1;
11639 }
11640
11641 let pad_forward_dts = [
11649 DType::U8,
11650 DType::U32,
11651 DType::BF16,
11652 DType::F16,
11653 DType::F32,
11654 DType::F64,
11655 ];
11656 for dt in pad_forward_dts {
11657 let key: &[DType] = &[dt, dt];
11658 let alts = table.lookup_alternatives(OpKind::Pad, key, BackendId::Cpu);
11659 let entry = alts
11660 .iter()
11661 .find(|e| e.kernel as usize == pad_cpu_wrapper as *const () as usize)
11662 .unwrap_or_else(|| {
11663 panic!(
11664 "Pad/{dt:?}/Cpu: the production wrapper must be bound \
11665 FROM the padding contract in global_bindings() — found {} \
11666 alternative(s) with sources {:?}",
11667 alts.len(),
11668 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11669 )
11670 });
11671 assert_eq!(
11672 entry.kernel_source, "portable-cpu",
11673 "Pad/{dt:?}: forward family must be contract-sourced \
11674 (kernel_source=\"portable-cpu\"); got {:?}",
11675 entry.kernel_source,
11676 );
11677 assert!(
11678 !entry.caps.strided_input,
11679 "Pad/{dt:?}: caps preserved (contiguous-only)",
11680 );
11681 assert!(
11682 entry.precision.bit_stable_on_same_hardware,
11683 "Pad/{dt:?}: contract's bit-stable claim rode through",
11684 );
11685 checked += 1;
11686 }
11687
11688 assert_eq!(
11689 checked, 10,
11690 "4 PadBackward + 6 forward Pad dtypes checked (contract-sourced bindings)"
11691 );
11692 }
11693
11694 #[test]
11726 fn global_bindings_registers_shape_ops_family_from_contract() {
11727 let table = global_bindings();
11728 let mut checked = 0usize;
11729
11730 let mut check =
11732 |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
11733 let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11734 let entry = alts
11735 .iter()
11736 .find(|e| e.kernel as usize == expected as usize)
11737 .unwrap_or_else(|| {
11738 panic!(
11739 "{op:?}/{label}/Cpu: the production wrapper must be bound \
11740 FROM the shape-ops contract in global_bindings() — found {} \
11741 alternative(s) with sources {:?}",
11742 alts.len(),
11743 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11744 )
11745 });
11746 assert_eq!(
11747 entry.kernel_source, "portable-cpu",
11748 "{op:?}/{label}: family must be contract-sourced \
11749 (kernel_source=\"portable-cpu\"); got {:?}",
11750 entry.kernel_source,
11751 );
11752 assert!(
11753 !entry.caps.strided_input,
11754 "{op:?}/{label}: caps preserved (contiguous-only)",
11755 );
11756 assert!(
11757 entry.precision.bit_stable_on_same_hardware,
11758 "{op:?}/{label}: contract's bit-stable claim rode through",
11759 );
11760 checked += 1;
11761 };
11762
11763 let byte_dts = [
11765 DType::F32,
11766 DType::F64,
11767 DType::BF16,
11768 DType::F16,
11769 DType::U32,
11770 DType::U8,
11771 ];
11772 for dt in byte_dts {
11773 check(OpKind::Flip, &[dt, dt], flip_cpu_wrapper, "flip");
11774 check(OpKind::Roll, &[dt, dt], roll_cpu_wrapper, "roll");
11775 check(
11777 OpKind::MaskedFill,
11778 &[dt, DType::Bool, dt], masked_fill_cpu_wrapper,
11780 "masked_fill",
11781 );
11782 }
11783
11784 let cumsum_dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11786 let cumsum_wrappers: [crate::kernel::KernelRef; 4] = [
11787 cumsum_f32_cpu_wrapper,
11788 cumsum_f64_cpu_wrapper,
11789 cumsum_bf16_cpu_wrapper,
11790 cumsum_f16_cpu_wrapper,
11791 ];
11792 for (i, dt) in cumsum_dts.iter().enumerate() {
11793 check(OpKind::CumSum, &[*dt, *dt], cumsum_wrappers[i], "cumsum");
11794 }
11795
11796 let concat_dts = [
11798 DType::F32,
11799 DType::F64,
11800 DType::BF16,
11801 DType::F16,
11802 DType::U32,
11803 DType::U8,
11804 DType::I16,
11805 DType::I32,
11806 DType::I64,
11807 ];
11808 for dt in concat_dts {
11809 check(OpKind::Concat, &[dt, dt], concat_cpu_wrapper, "concat");
11810 }
11811
11812 let scatter_dts = [
11819 DType::F32,
11820 DType::F64,
11821 DType::BF16,
11822 DType::F16,
11823 DType::U32,
11824 DType::U8,
11825 ];
11826 for dt in scatter_dts {
11827 check(
11828 OpKind::WriteSlice,
11829 &[dt, dt],
11830 write_slice_cpu_wrapper,
11831 "write_slice",
11832 );
11833 check(
11834 OpKind::WriteSliceRotating,
11835 &[dt, dt],
11836 write_slice_rotating_cpu_wrapper,
11837 "write_slice_rotating",
11838 );
11839 check(
11842 OpKind::WriteSliceDoff,
11843 &[dt, dt],
11844 write_slice_doff_cpu_wrapper,
11845 "write_slice_doff",
11846 );
11847 }
11848
11849 assert_eq!(
11850 checked,
11851 6 + 6 + 6 + 4 + 9 + 6 + 6 + 6,
11852 "flip(6) + roll(6) + masked_fill(6) + cumsum(4) + concat(9) + \
11853 write_slice(6) + write_slice_rotating(6) + write_slice_doff(6) contract-sourced bindings",
11854 );
11855 }
11856
11857 #[test]
11887 fn global_bindings_registers_indexing_family_from_contract() {
11888 let table = global_bindings();
11889 let mut checked = 0usize;
11890
11891 let mut check =
11893 |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
11894 let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11895 let entry = alts
11896 .iter()
11897 .find(|e| e.kernel as usize == expected as usize)
11898 .unwrap_or_else(|| {
11899 panic!(
11900 "{op:?}/{label}/Cpu: the production wrapper must be bound \
11901 FROM the indexing contract in global_bindings() — found {} \
11902 alternative(s) with sources {:?}",
11903 alts.len(),
11904 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11905 )
11906 });
11907 assert_eq!(
11908 entry.kernel_source, "portable-cpu",
11909 "{op:?}/{label}: family must be contract-sourced \
11910 (kernel_source=\"portable-cpu\"); got {:?}",
11911 entry.kernel_source,
11912 );
11913 assert!(
11914 !entry.caps.strided_input,
11915 "{op:?}/{label}: caps preserved (contiguous-only)",
11916 );
11917 assert!(
11918 entry.precision.bit_stable_on_same_hardware,
11919 "{op:?}/{label}: contract's bit-stable claim rode through",
11920 );
11921 checked += 1;
11922 };
11923
11924 let byte_dts = [
11927 DType::F32,
11928 DType::F64,
11929 DType::BF16,
11930 DType::F16,
11931 DType::U32,
11932 DType::U8,
11933 DType::I16,
11934 DType::I32,
11935 DType::I64,
11936 ];
11937 for dt in byte_dts {
11938 check(
11939 OpKind::IndexSelect,
11940 &[dt, DType::U32, dt],
11941 index_select_cpu_wrapper,
11942 "index_select",
11943 );
11944 check(
11945 OpKind::Gather,
11946 &[dt, DType::U32, dt],
11947 gather_cpu_wrapper,
11948 "gather",
11949 );
11950 }
11951
11952 let acc_dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11955 let index_add_wrappers: [crate::kernel::KernelRef; 4] = [
11956 index_add_f32_cpu_wrapper,
11957 index_add_f64_cpu_wrapper,
11958 index_add_bf16_cpu_wrapper,
11959 index_add_f16_cpu_wrapper,
11960 ];
11961 let scatter_add_wrappers: [crate::kernel::KernelRef; 4] = [
11962 scatter_add_f32_cpu_wrapper,
11963 scatter_add_f64_cpu_wrapper,
11964 scatter_add_bf16_cpu_wrapper,
11965 scatter_add_f16_cpu_wrapper,
11966 ];
11967 for (i, dt) in acc_dts.iter().enumerate() {
11968 check(
11969 OpKind::IndexAdd,
11970 &[*dt, DType::U32, *dt, *dt],
11971 index_add_wrappers[i],
11972 "index_add",
11973 );
11974 check(
11975 OpKind::ScatterAdd,
11976 &[*dt, DType::U32, *dt, *dt],
11977 scatter_add_wrappers[i],
11978 "scatter_add",
11979 );
11980 }
11981
11982 assert_eq!(
11983 checked,
11984 9 + 9 + 4 + 4,
11985 "index_select(9) + gather(9) + index_add(4) + scatter_add(4) \
11986 contract-sourced bindings",
11987 );
11988 }
11989
11990 #[test]
12022 fn global_bindings_registers_matmul_family_from_contract() {
12023 let table = global_bindings();
12024 let mut checked = 0usize;
12025
12026 let mut check =
12030 |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
12031 let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12032 let entry = alts
12033 .iter()
12034 .find(|e| e.kernel as usize == expected as usize)
12035 .unwrap_or_else(|| {
12036 panic!(
12037 "{op:?}/{label}/Cpu: the portable wrapper must be bound \
12038 FROM the matmul contract in global_bindings() — found {} \
12039 alternative(s) with sources {:?}",
12040 alts.len(),
12041 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12042 )
12043 });
12044 assert_eq!(
12045 entry.kernel_source, "portable-cpu",
12046 "{op:?}/{label}: portable kernel must be contract-sourced \
12047 (kernel_source=\"portable-cpu\"); got {:?}",
12048 entry.kernel_source,
12049 );
12050 assert!(
12051 !entry.caps.strided_input,
12052 "{op:?}/{label}: caps preserved (contiguous-only)",
12053 );
12054 assert!(
12055 entry.precision.bit_stable_on_same_hardware,
12056 "{op:?}/{label}: contract's bit-stable claim rode through",
12057 );
12058 checked += 1;
12059 };
12060
12061 let mm_dts = [
12063 DType::F32,
12064 DType::F64,
12065 DType::BF16,
12066 DType::F16,
12067 DType::I8,
12068 DType::U8,
12069 ];
12070 let mm_wrappers: [crate::kernel::KernelRef; 6] = [
12071 matmul_f32_cpu_wrapper,
12072 matmul_f64_cpu_wrapper,
12073 matmul_bf16_cpu_wrapper,
12074 matmul_f16_cpu_wrapper,
12075 matmul_i8_cpu_wrapper,
12076 matmul_u8_cpu_wrapper,
12077 ];
12078 for (i, dt) in mm_dts.iter().enumerate() {
12079 check(OpKind::MatMul, &[*dt, *dt, *dt], mm_wrappers[i], "matmul");
12080 }
12081
12082 let fl_dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12084 let fl_wrappers: [crate::kernel::KernelRef; 4] = [
12085 fused_linear_f32_cpu_wrapper,
12086 fused_linear_f64_cpu_wrapper,
12087 fused_linear_bf16_cpu_wrapper,
12088 fused_linear_f16_cpu_wrapper,
12089 ];
12090 for (i, dt) in fl_dts.iter().enumerate() {
12091 check(
12092 OpKind::FusedLinear,
12093 &[*dt, *dt, *dt, *dt],
12094 fl_wrappers[i],
12095 "fused_linear",
12096 );
12097 }
12098
12099 assert_eq!(
12100 checked,
12101 6 + 4,
12102 "matmul(6) + fused_linear(4) contract-sourced bindings",
12103 );
12104 }
12105
12106 #[test]
12136 fn global_bindings_registers_attention_family_from_contract() {
12137 let table = global_bindings();
12138 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12139
12140 let fa_wrappers: [crate::kernel::KernelRef; 4] = [
12143 flash_attn_f32_cpu_wrapper,
12144 flash_attn_f64_cpu_wrapper,
12145 flash_attn_bf16_cpu_wrapper,
12146 flash_attn_f16_cpu_wrapper,
12147 ];
12148 let fabq: [crate::kernel::KernelRef; 4] = [
12150 flash_attn_backward_q_f32_cpu_wrapper,
12151 flash_attn_backward_q_f64_cpu_wrapper,
12152 flash_attn_backward_q_bf16_cpu_wrapper,
12153 flash_attn_backward_q_f16_cpu_wrapper,
12154 ];
12155 let fabk: [crate::kernel::KernelRef; 4] = [
12156 flash_attn_backward_k_f32_cpu_wrapper,
12157 flash_attn_backward_k_f64_cpu_wrapper,
12158 flash_attn_backward_k_bf16_cpu_wrapper,
12159 flash_attn_backward_k_f16_cpu_wrapper,
12160 ];
12161 let fabv: [crate::kernel::KernelRef; 4] = [
12162 flash_attn_backward_v_f32_cpu_wrapper,
12163 flash_attn_backward_v_f64_cpu_wrapper,
12164 flash_attn_backward_v_bf16_cpu_wrapper,
12165 flash_attn_backward_v_f16_cpu_wrapper,
12166 ];
12167 let pa_wrappers: [crate::kernel::KernelRef; 4] = [
12170 paged_attn_f32_cpu_wrapper,
12171 paged_attn_f64_cpu_wrapper,
12172 paged_attn_bf16_cpu_wrapper,
12173 paged_attn_f16_cpu_wrapper,
12174 ];
12175
12176 let check = |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
12179 let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12180 let entry = alts
12181 .iter()
12182 .find(|e| e.kernel as usize == expected as usize)
12183 .unwrap_or_else(|| {
12184 panic!(
12185 "{op:?}/{label}/Cpu: the production wrapper must be bound \
12186 FROM the attention contract in global_bindings() — found {} \
12187 alternative(s) with sources {:?}",
12188 alts.len(),
12189 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12190 )
12191 });
12192 assert_eq!(
12193 entry.kernel_source, "portable-cpu",
12194 "{op:?}/{label}: family must be contract-sourced \
12195 (kernel_source=\"portable-cpu\"); got {:?}",
12196 entry.kernel_source,
12197 );
12198 assert!(
12199 !entry.caps.strided_input,
12200 "{op:?}/{label}: caps preserved (contiguous-only)",
12201 );
12202 assert!(
12203 entry.precision.bit_stable_on_same_hardware,
12204 "{op:?}/{label}: contract's bit-stable claim rode through",
12205 );
12206 };
12207
12208 let mut checked = 0usize;
12209 for (i, dt) in dts.iter().enumerate() {
12210 let fa_noa: &[DType] = &[*dt, *dt, *dt, *dt];
12212 let fa_a: &[DType] = &[*dt, *dt, *dt, *dt, *dt];
12213 check(OpKind::FlashAttn, fa_noa, fa_wrappers[i], "flash no-alibi");
12214 check(OpKind::FlashAttn, fa_a, fa_wrappers[i], "flash with-alibi");
12215 checked += 2;
12216
12217 let bw_noa: &[DType] = &[*dt, *dt, *dt, *dt, *dt];
12219 let bw_a: &[DType] = &[*dt, *dt, *dt, *dt, *dt, *dt];
12220 for (op, ws) in [
12221 (OpKind::FlashAttnBackwardQ, &fabq),
12222 (OpKind::FlashAttnBackwardK, &fabk),
12223 (OpKind::FlashAttnBackwardV, &fabv),
12224 ] {
12225 check(op, bw_noa, ws[i], "backward no-alibi");
12226 check(op, bw_a, ws[i], "backward with-alibi");
12227 checked += 2;
12228 }
12229
12230 let pa_noa: &[DType] = &[*dt, *dt, *dt, DType::U32, DType::U32, *dt];
12239 let pa_a: &[DType] = &[*dt, *dt, *dt, DType::U32, DType::U32, *dt, *dt];
12240 check(OpKind::PagedAttn, pa_noa, pa_wrappers[i], "paged no-alibi");
12241 check(OpKind::PagedAttn, pa_a, pa_wrappers[i], "paged with-alibi");
12242 checked += 2;
12243 }
12244 assert_eq!(
12245 checked, 40,
12246 "FlashAttn(8) + FlashAttnBackward{{Q,K,V}}(24) + PagedAttn(8) = 40 \
12247 contract-sourced bindings",
12248 );
12249 }
12250
12251 #[test]
12266 fn global_bindings_registers_inplace_family_from_contract() {
12267 let table = global_bindings();
12268 let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12269
12270 let check = |op: OpKind, dt: DType, expected: crate::kernel::KernelRef, label: &str| {
12273 let key: &[DType] = &[dt, dt];
12274 let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12275 let entry = alts
12276 .iter()
12277 .find(|e| e.kernel as usize == expected as usize)
12278 .unwrap_or_else(|| {
12279 panic!(
12280 "{op:?}/{label}/{dt:?}/Cpu: the production wrapper must be bound \
12281 FROM the in-place contract in global_bindings() — found {} \
12282 alternative(s) with sources {:?}",
12283 alts.len(),
12284 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12285 )
12286 });
12287 assert_eq!(
12288 entry.kernel_source, "portable-cpu",
12289 "{op:?}/{label}/{dt:?}: family must be contract-sourced \
12290 (kernel_source=\"portable-cpu\"); got {:?}",
12291 entry.kernel_source,
12292 );
12293 assert!(
12294 !entry.caps.strided_input,
12295 "{op:?}/{label}/{dt:?}: caps preserved (contiguous-only)",
12296 );
12297 assert!(
12298 entry.precision.bit_stable_on_same_hardware,
12299 "{op:?}/{label}/{dt:?}: contract's bit-stable claim rode through",
12300 );
12301 };
12302
12303 let unary_family: &[(OpKind, &str, [crate::kernel::KernelRef; 4])] = &[
12306 (
12307 OpKind::ReluInplace,
12308 "relu",
12309 [
12310 relu_inplace_f32_cpu_wrapper,
12311 relu_inplace_f64_cpu_wrapper,
12312 relu_inplace_bf16_cpu_wrapper,
12313 relu_inplace_f16_cpu_wrapper,
12314 ],
12315 ),
12316 (
12317 OpKind::SiluInplace,
12318 "silu",
12319 [
12320 silu_inplace_f32_cpu_wrapper,
12321 silu_inplace_f64_cpu_wrapper,
12322 silu_inplace_bf16_cpu_wrapper,
12323 silu_inplace_f16_cpu_wrapper,
12324 ],
12325 ),
12326 (
12327 OpKind::GeluTanhInplace,
12328 "gelu_tanh",
12329 [
12330 gelu_inplace_f32_cpu_wrapper,
12331 gelu_inplace_f64_cpu_wrapper,
12332 gelu_inplace_bf16_cpu_wrapper,
12333 gelu_inplace_f16_cpu_wrapper,
12334 ],
12335 ),
12336 (
12337 OpKind::TanhInplace,
12338 "tanh",
12339 [
12340 tanh_inplace_f32_cpu_wrapper,
12341 tanh_inplace_f64_cpu_wrapper,
12342 tanh_inplace_bf16_cpu_wrapper,
12343 tanh_inplace_f16_cpu_wrapper,
12344 ],
12345 ),
12346 (
12347 OpKind::SigmoidInplace,
12348 "sigmoid",
12349 [
12350 sigmoid_inplace_f32_cpu_wrapper,
12351 sigmoid_inplace_f64_cpu_wrapper,
12352 sigmoid_inplace_bf16_cpu_wrapper,
12353 sigmoid_inplace_f16_cpu_wrapper,
12354 ],
12355 ),
12356 (
12357 OpKind::NegInplace,
12358 "neg",
12359 [
12360 neg_inplace_f32_cpu_wrapper,
12361 neg_inplace_f64_cpu_wrapper,
12362 neg_inplace_bf16_cpu_wrapper,
12363 neg_inplace_f16_cpu_wrapper,
12364 ],
12365 ),
12366 (
12367 OpKind::AbsInplace,
12368 "abs",
12369 [
12370 abs_inplace_f32_cpu_wrapper,
12371 abs_inplace_f64_cpu_wrapper,
12372 abs_inplace_bf16_cpu_wrapper,
12373 abs_inplace_f16_cpu_wrapper,
12374 ],
12375 ),
12376 (
12377 OpKind::SqrInplace,
12378 "sqr",
12379 [
12380 sqr_inplace_f32_cpu_wrapper,
12381 sqr_inplace_f64_cpu_wrapper,
12382 sqr_inplace_bf16_cpu_wrapper,
12383 sqr_inplace_f16_cpu_wrapper,
12384 ],
12385 ),
12386 (
12387 OpKind::SqrtInplace,
12388 "sqrt",
12389 [
12390 sqrt_inplace_f32_cpu_wrapper,
12391 sqrt_inplace_f64_cpu_wrapper,
12392 sqrt_inplace_bf16_cpu_wrapper,
12393 sqrt_inplace_f16_cpu_wrapper,
12394 ],
12395 ),
12396 (
12397 OpKind::RsqrtInplace,
12398 "rsqrt",
12399 [
12400 rsqrt_inplace_f32_cpu_wrapper,
12401 rsqrt_inplace_f64_cpu_wrapper,
12402 rsqrt_inplace_bf16_cpu_wrapper,
12403 rsqrt_inplace_f16_cpu_wrapper,
12404 ],
12405 ),
12406 (
12407 OpKind::RecipInplace,
12408 "recip",
12409 [
12410 recip_inplace_f32_cpu_wrapper,
12411 recip_inplace_f64_cpu_wrapper,
12412 recip_inplace_bf16_cpu_wrapper,
12413 recip_inplace_f16_cpu_wrapper,
12414 ],
12415 ),
12416 (
12417 OpKind::ExpInplace,
12418 "exp",
12419 [
12420 exp_inplace_f32_cpu_wrapper,
12421 exp_inplace_f64_cpu_wrapper,
12422 exp_inplace_bf16_cpu_wrapper,
12423 exp_inplace_f16_cpu_wrapper,
12424 ],
12425 ),
12426 (
12427 OpKind::LogInplace,
12428 "log",
12429 [
12430 log_inplace_f32_cpu_wrapper,
12431 log_inplace_f64_cpu_wrapper,
12432 log_inplace_bf16_cpu_wrapper,
12433 log_inplace_f16_cpu_wrapper,
12434 ],
12435 ),
12436 (
12437 OpKind::SinInplace,
12438 "sin",
12439 [
12440 sin_inplace_f32_cpu_wrapper,
12441 sin_inplace_f64_cpu_wrapper,
12442 sin_inplace_bf16_cpu_wrapper,
12443 sin_inplace_f16_cpu_wrapper,
12444 ],
12445 ),
12446 (
12447 OpKind::CosInplace,
12448 "cos",
12449 [
12450 cos_inplace_f32_cpu_wrapper,
12451 cos_inplace_f64_cpu_wrapper,
12452 cos_inplace_bf16_cpu_wrapper,
12453 cos_inplace_f16_cpu_wrapper,
12454 ],
12455 ),
12456 (
12457 OpKind::SignInplace,
12458 "sign",
12459 [
12460 sign_inplace_f32_cpu_wrapper,
12461 sign_inplace_f64_cpu_wrapper,
12462 sign_inplace_bf16_cpu_wrapper,
12463 sign_inplace_f16_cpu_wrapper,
12464 ],
12465 ),
12466 (
12467 OpKind::FloorInplace,
12468 "floor",
12469 [
12470 floor_inplace_f32_cpu_wrapper,
12471 floor_inplace_f64_cpu_wrapper,
12472 floor_inplace_bf16_cpu_wrapper,
12473 floor_inplace_f16_cpu_wrapper,
12474 ],
12475 ),
12476 (
12477 OpKind::CeilInplace,
12478 "ceil",
12479 [
12480 ceil_inplace_f32_cpu_wrapper,
12481 ceil_inplace_f64_cpu_wrapper,
12482 ceil_inplace_bf16_cpu_wrapper,
12483 ceil_inplace_f16_cpu_wrapper,
12484 ],
12485 ),
12486 (
12487 OpKind::RoundInplace,
12488 "round",
12489 [
12490 round_inplace_f32_cpu_wrapper,
12491 round_inplace_f64_cpu_wrapper,
12492 round_inplace_bf16_cpu_wrapper,
12493 round_inplace_f16_cpu_wrapper,
12494 ],
12495 ),
12496 (
12497 OpKind::ErfInplace,
12498 "erf",
12499 [
12500 erf_inplace_f32_cpu_wrapper,
12501 erf_inplace_f64_cpu_wrapper,
12502 erf_inplace_bf16_cpu_wrapper,
12503 erf_inplace_f16_cpu_wrapper,
12504 ],
12505 ),
12506 (
12507 OpKind::GeluInplace,
12508 "gelu",
12509 [
12510 gelu_erf_inplace_f32_cpu_wrapper,
12511 gelu_erf_inplace_f64_cpu_wrapper,
12512 gelu_erf_inplace_bf16_cpu_wrapper,
12513 gelu_erf_inplace_f16_cpu_wrapper,
12514 ],
12515 ),
12516 ];
12517
12518 let scalar_family: &[(OpKind, &str, [crate::kernel::KernelRef; 4])] = &[
12522 (
12523 OpKind::InplaceAffine,
12524 "affine",
12525 [
12526 inplace_affine_f32_cpu_wrapper,
12527 inplace_affine_f64_cpu_wrapper,
12528 inplace_affine_bf16_cpu_wrapper,
12529 inplace_affine_f16_cpu_wrapper,
12530 ],
12531 ),
12532 (
12533 OpKind::ClampInplace,
12534 "clamp",
12535 [
12536 clamp_inplace_f32_cpu_wrapper,
12537 clamp_inplace_f64_cpu_wrapper,
12538 clamp_inplace_bf16_cpu_wrapper,
12539 clamp_inplace_f16_cpu_wrapper,
12540 ],
12541 ),
12542 (
12543 OpKind::PowIInplace,
12544 "powi",
12545 [
12546 powi_inplace_f32_cpu_wrapper,
12547 powi_inplace_f64_cpu_wrapper,
12548 powi_inplace_bf16_cpu_wrapper,
12549 powi_inplace_f16_cpu_wrapper,
12550 ],
12551 ),
12552 ];
12553
12554 let mut checked = 0usize;
12555 for (op, label, ws) in unary_family.iter().chain(scalar_family.iter()) {
12556 for (i, dt) in dts.iter().enumerate() {
12557 check(*op, *dt, ws[i], label);
12558 checked += 1;
12559 }
12560 }
12561 assert_eq!(
12562 checked, 96,
12563 "21 in-place unary (×4) + InplaceAffine/ClampInplace/PowIInplace (×4) = 96 \
12564 contract-sourced bindings",
12565 );
12566 }
12567
12568 #[test]
12589 fn global_bindings_registers_cast_family_from_contract() {
12590 let table = global_bindings();
12591
12592 let targets: [(DType, crate::kernel::KernelRef); 11] = [
12595 (DType::F32, cast_to_f32_cpu_wrapper),
12596 (DType::F64, cast_to_f64_cpu_wrapper),
12597 (DType::F16, cast_to_f16_cpu_wrapper),
12598 (DType::BF16, cast_to_bf16_cpu_wrapper),
12599 (DType::F8E4M3, cast_to_f8e4m3_cpu_wrapper),
12600 (DType::U8, cast_to_u8_cpu_wrapper),
12601 (DType::I8, cast_to_i8_cpu_wrapper),
12602 (DType::U32, cast_to_u32_cpu_wrapper),
12603 (DType::I16, cast_to_i16_cpu_wrapper),
12604 (DType::I32, cast_to_i32_cpu_wrapper),
12605 (DType::I64, cast_to_i64_cpu_wrapper),
12606 ];
12607 let all_dts: [DType; 11] = [
12608 DType::F32,
12609 DType::F64,
12610 DType::F16,
12611 DType::BF16,
12612 DType::F8E4M3,
12613 DType::U8,
12614 DType::I8,
12615 DType::U32,
12616 DType::I16,
12617 DType::I32,
12618 DType::I64,
12619 ];
12620
12621 let mut checked = 0usize;
12622 for (dst, expected) in targets {
12623 for src in all_dts {
12624 if src == dst {
12625 continue; }
12627 let key: &[DType] = &[src, dst];
12628 let alts = table.lookup_alternatives(OpKind::Cast, key, BackendId::Cpu);
12629 let entry = alts
12630 .iter()
12631 .find(|e| e.kernel as usize == expected as usize)
12632 .unwrap_or_else(|| {
12633 panic!(
12634 "Cast {src:?}->{dst:?}/Cpu: the production per-target wrapper must be \
12635 bound FROM the cast contract in global_bindings() — found {} \
12636 alternative(s) with sources {:?}",
12637 alts.len(),
12638 alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12639 )
12640 });
12641 assert_eq!(
12642 entry.kernel_source, "portable-cpu",
12643 "Cast {src:?}->{dst:?}: family must be contract-sourced \
12644 (kernel_source=\"portable-cpu\"); got {:?}",
12645 entry.kernel_source,
12646 );
12647 assert!(
12648 !entry.caps.strided_input,
12649 "Cast {src:?}->{dst:?}: caps preserved (contiguous-only)",
12650 );
12651 assert!(
12652 entry.precision.bit_stable_on_same_hardware,
12653 "Cast {src:?}->{dst:?}: contract's bit-stable claim rode through",
12654 );
12655 checked += 1;
12656 }
12657 }
12658 assert_eq!(
12659 checked, 110,
12660 "11 target dtypes × 10 sources each = 110 directed cast pairs (identity excluded)"
12661 );
12662 }
12663
12664 #[test]
12666 fn binding_table_lookup_miss_errors() {
12667 let mut table = KernelBindingTable::new();
12668 register_cpu_kernels(&mut table);
12669 let result = table.lookup(
12673 OpKind::AddElementwise,
12674 &[DType::I64, DType::I64, DType::I64],
12675 BackendId::Cpu,
12676 );
12677 assert!(result.is_err());
12678 }
12679
12680 #[test]
12683 fn cpu_f8e4m3_cast_pairs_registered() {
12684 let mut table = KernelBindingTable::new();
12685 register_cpu_kernels(&mut table);
12686 for other in [DType::F32, DType::F16, DType::BF16] {
12687 for (src, dst) in [(DType::F8E4M3, other), (other, DType::F8E4M3)] {
12688 table
12689 .lookup(OpKind::Cast, &[src, dst], BackendId::Cpu)
12690 .unwrap_or_else(|e| panic!("Cast {src:?} → {dst:?} (CPU) not registered: {e}"));
12691 }
12692 }
12693 }
12694
12695 #[test]
12698 fn cpu_int_matmul_registered() {
12699 let mut table = KernelBindingTable::new();
12700 register_cpu_kernels(&mut table);
12701 for t in [DType::I8, DType::U8] {
12702 table
12703 .lookup(OpKind::MatMul, &[t, t, t], BackendId::Cpu)
12704 .unwrap_or_else(|e| panic!("MatMul {t:?} (CPU) not registered: {e}"));
12705 }
12706 }
12707
12708 #[test]
12713 fn b5_end_to_end_add_elementwise_f32() {
12714 let mut registry = CapabilityRegistry::new();
12716 registry.register(cpu_caps());
12717
12718 let backend =
12720 resolve_target_backend(®istry, OpKind::AddElementwise, DType::F32).expect("resolve");
12721 assert_eq!(backend, BackendId::Cpu);
12722
12723 let mut bindings = KernelBindingTable::new();
12725 register_cpu_kernels(&mut bindings);
12726
12727 let kernel = bindings
12729 .lookup(
12730 OpKind::AddElementwise,
12731 &[DType::F32, DType::F32, DType::F32],
12732 backend,
12733 )
12734 .expect("lookup");
12735
12736 let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
12738 let rhs = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0]);
12739 let out = fuel_memory::alloc_cpu_zeroed(DType::F32, 4).expect("alloc");
12740
12741 let inputs = vec![Arc::new(RwLock::new(lhs)), Arc::new(RwLock::new(rhs))];
12742 let mut outputs = vec![Arc::new(RwLock::new(out))];
12743
12744 kernel(&inputs, &mut outputs, &[], &OpParams::None).expect("kernel");
12746
12747 let out_guard = outputs[0].read().unwrap();
12749 if let BackendStorage::Cpu(c) = &out_guard.inner {
12750 let typed: &[f32] = c.as_slice().expect("cast");
12751 assert_eq!(typed, &[11.0, 22.0, 33.0, 44.0]);
12752 } else {
12753 panic!("expected CPU output");
12754 }
12755 }
12756
12757 #[test]
12759 fn b5_wrapper_arity_check() {
12760 let mut bindings = KernelBindingTable::new();
12761 register_cpu_kernels(&mut bindings);
12762 let kernel = bindings
12763 .lookup(
12764 OpKind::AddElementwise,
12765 &[DType::F32, DType::F32, DType::F32],
12766 BackendId::Cpu,
12767 )
12768 .unwrap();
12769
12770 let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12772 let out = fuel_memory::alloc_cpu_zeroed(DType::F32, 2).unwrap();
12773 let inputs = vec![Arc::new(RwLock::new(lhs))];
12774 let mut outputs = vec![Arc::new(RwLock::new(out))];
12775
12776 let result = kernel(&inputs, &mut outputs, &[], &OpParams::None);
12777 assert!(result.is_err());
12778 }
12779
12780 #[test]
12797 fn held_snapshot_does_not_block_a_concurrent_write() {
12798 use std::sync::mpsc;
12799 use std::time::Duration;
12800
12801 let (tx, rx) = mpsc::channel();
12802 std::thread::spawn(move || {
12803 let snap = global_bindings();
12805 let before = snap
12806 .lookup(
12807 OpKind::AddElementwise,
12808 &[DType::F32, DType::F32, DType::F32],
12809 BackendId::Cpu,
12810 )
12811 .is_ok();
12812
12813 extend_global_bindings(|_t| {});
12817
12818 let _snap2 = global_bindings();
12822
12823 let after = snap
12826 .lookup(
12827 OpKind::AddElementwise,
12828 &[DType::F32, DType::F32, DType::F32],
12829 BackendId::Cpu,
12830 )
12831 .is_ok();
12832
12833 tx.send((before, after)).ok();
12834 });
12835
12836 match rx.recv_timeout(Duration::from_secs(30)) {
12837 Ok((before, after)) => {
12838 assert!(
12839 before,
12840 "CPU AddElementwise+F32 should resolve in the snapshot"
12841 );
12842 assert!(
12843 after,
12844 "snapshot must stay readable after a concurrent table swap"
12845 );
12846 }
12847 Err(_) => panic!(
12848 "GAP-015 regression: holding a binding-table snapshot across \
12849 extend_global_bindings() deadlocked (30s watchdog). The read \
12850 path must hand out an owned snapshot, not a lock guard."
12851 ),
12852 }
12853 }
12854
12855 #[test]
12857 fn global_registry_auto_registers_cpu() {
12858 let r = global_registry();
12860 assert!(!r.backends().is_empty());
12861 let cpu = r.backends().iter().find(|c| c.backend_id == BackendId::Cpu);
12863 assert!(cpu.is_some(), "CPU should be auto-registered");
12864 }
12865
12866 #[test]
12869 fn global_bindings_auto_registers_cpu_wrappers() {
12870 let b = global_bindings();
12871 let result = b.lookup(
12872 OpKind::AddElementwise,
12873 &[DType::F32, DType::F32, DType::F32],
12874 BackendId::Cpu,
12875 );
12876 assert!(
12877 result.is_ok(),
12878 "CPU AddElementwise+F32 should be registered"
12879 );
12880 }
12881
12882 #[cfg(feature = "cuda")]
12890 #[test]
12891 fn global_bindings_auto_registers_cuda_paths() {
12892 let b = global_bindings();
12893 let cublas = b.lookup(
12895 OpKind::MatMul,
12896 &[DType::F32, DType::F32, DType::F32],
12897 BackendId::Cuda,
12898 );
12899 assert!(
12900 cublas.is_ok(),
12901 "cuBLAS F32 MatMul should be auto-registered on Cuda"
12902 );
12903
12904 let baracuda_int8 = b.lookup(
12907 OpKind::MatMul,
12908 &[DType::I8, DType::I8, DType::I8],
12909 BackendId::Cuda,
12910 );
12911 assert!(
12912 baracuda_int8.is_ok(),
12913 "baracuda int8 MatMul should be auto-registered on Cuda",
12914 );
12915
12916 let alts = b.lookup_alternatives(
12921 OpKind::NegElementwise,
12922 &[DType::F32, DType::F32],
12923 BackendId::Cuda,
12924 );
12925 assert!(
12926 alts.len() == 1,
12927 "expected exactly 1 CUDA Neg F32 alternative (baracuda); got {}",
12928 alts.len(),
12929 );
12930 }
12931
12932 #[test]
12941 fn audit_multi_backend_coverage() {
12942 let b = global_bindings();
12943 assert!(
12944 !b.is_empty(),
12945 "the global binding table is empty, so this audit would report nothing"
12946 );
12947
12948 type CoverageGroup = ((OpKind, Vec<DType>), Vec<(BackendId, usize)>);
12954 let mut grouped: Vec<CoverageGroup> = Vec::new();
12955 for (op, dtypes, backend, _precision) in b.iter_precision() {
12956 let key = (op, dtypes.to_vec());
12957 if let Some((_, entry)) = grouped.iter_mut().find(|(k, _)| *k == key) {
12958 if let Some(slot) = entry.iter_mut().find(|(be, _)| *be == backend) {
12959 slot.1 += 1;
12960 } else {
12961 entry.push((backend, 1));
12962 }
12963 } else {
12964 grouped.push((key, vec![(backend, 1)]));
12965 }
12966 }
12967 grouped.sort_by(|a, b| {
12969 let oa = format!("{:?}", a.0.0);
12970 let ob = format!("{:?}", b.0.0);
12971 oa.cmp(&ob).then_with(|| {
12972 let da = format!("{:?}", a.0.1);
12973 let db = format!("{:?}", b.0.1);
12974 da.cmp(&db)
12975 })
12976 });
12977
12978 let total_keys = grouped.len();
12979 let mut multi_backend = 0;
12980 let mut multi_impl_single_backend = 0;
12981 let mut single_alt = 0;
12982
12983 println!("\n=== Picker-alternatives audit ===");
12984 println!("Total unique (op, dtypes) keys: {total_keys}");
12985 println!("Total alternatives (sum): {}", b.len());
12986 println!();
12987 println!("Keys with >1 alternative (per Judge-picking working set):");
12988 for ((op, dtypes), backends) in &grouped {
12989 let total_alts: usize = backends.iter().map(|(_, n)| *n).sum();
12990 if total_alts <= 1 {
12991 single_alt += 1;
12992 continue;
12993 }
12994 if backends.len() > 1 {
12995 multi_backend += 1;
12996 } else {
12997 multi_impl_single_backend += 1;
12998 }
12999 let backend_summary: Vec<String> = backends
13000 .iter()
13001 .map(|(be, n)| {
13002 if *n == 1 {
13003 format!("{be:?}")
13004 } else {
13005 format!("{be:?}×{n}")
13006 }
13007 })
13008 .collect();
13009 println!(
13010 " {op:?} {dtypes:?} → {} alts: [{}]",
13011 total_alts,
13012 backend_summary.join(", "),
13013 );
13014 }
13015 println!();
13016 println!("--- summary ---");
13017 println!("Single-alternative keys (no pick to make): {single_alt}");
13018 println!("Multi-backend keys (cross-backend pick): {multi_backend}");
13019 println!("Multi-impl single-backend keys: {multi_impl_single_backend}");
13020 }
13021
13022 #[test]
13036 fn inflight_inc_dec_balances_to_baseline() {
13037 let loc = DeviceLocation::Cuda { gpu_id: 99_001 };
13038 let base = inflight_count(loc);
13039
13040 const N: u32 = 7;
13042 for i in 0..N {
13043 inflight_inc(loc);
13044 assert_eq!(
13045 inflight_count(loc),
13046 base + i + 1,
13047 "inc must raise the count"
13048 );
13049 }
13050 assert_eq!(inflight_count(loc), base + N);
13051
13052 for i in 0..N {
13054 inflight_dec(loc);
13055 assert_eq!(
13056 inflight_count(loc),
13057 base + N - i - 1,
13058 "dec must lower the count",
13059 );
13060 }
13061 assert_eq!(
13062 inflight_count(loc),
13063 base,
13064 "balanced inc/dec must return the count to its pre-sequence baseline",
13065 );
13066 }
13067
13068 #[test]
13072 fn inflight_dec_is_underflow_safe() {
13073 let untouched = DeviceLocation::Vulkan { gpu_id: 99_002 };
13074 inflight_dec(untouched);
13076 assert_eq!(
13077 inflight_count(untouched),
13078 0,
13079 "dec on an untouched device stays 0"
13080 );
13081
13082 let loc = DeviceLocation::Vulkan { gpu_id: 99_003 };
13083 inflight_inc(loc);
13084 inflight_dec(loc);
13085 assert_eq!(inflight_count(loc), 0);
13086 inflight_dec(loc);
13088 assert_eq!(
13089 inflight_count(loc),
13090 0,
13091 "extra dec past zero must saturate, not wrap"
13092 );
13093 }
13094
13095 #[test]
13099 fn inflight_counts_are_per_device_independent() {
13100 let cuda = DeviceLocation::Cuda { gpu_id: 99_004 };
13101 let vulkan = DeviceLocation::Vulkan { gpu_id: 99_004 };
13102 let base_c = inflight_count(cuda);
13103 let base_v = inflight_count(vulkan);
13104
13105 inflight_inc(cuda);
13106 inflight_inc(cuda);
13107 inflight_inc(vulkan);
13108
13109 assert_eq!(inflight_count(cuda), base_c + 2);
13110 assert_eq!(inflight_count(vulkan), base_v + 1);
13111
13112 inflight_dec(cuda);
13113 inflight_dec(cuda);
13114 inflight_dec(vulkan);
13115 assert_eq!(inflight_count(cuda), base_c);
13116 assert_eq!(inflight_count(vulkan), base_v);
13117 }
13118
13119 #[test]
13128 fn derive_backend_caps_mirrors_binding_table_output_dtypes() {
13129 fn stub(
13130 _i: &[Arc<RwLock<Storage>>],
13131 _o: &mut [Arc<RwLock<Storage>>],
13132 _l: &[Layout],
13133 _p: &OpParams,
13134 ) -> Result<()> {
13135 Ok(())
13136 }
13137 fn stub_b(
13138 _i: &[Arc<RwLock<Storage>>],
13139 _o: &mut [Arc<RwLock<Storage>>],
13140 _l: &[Layout],
13141 _p: &OpParams,
13142 ) -> Result<()> {
13143 Ok(())
13144 }
13145 fn stub_c(
13146 _i: &[Arc<RwLock<Storage>>],
13147 _o: &mut [Arc<RwLock<Storage>>],
13148 _l: &[Layout],
13149 _p: &OpParams,
13150 ) -> Result<()> {
13151 Ok(())
13152 }
13153
13154 let mut table = KernelBindingTable::new();
13155 table.register(
13157 OpKind::AddElementwise,
13158 &[DType::F32, DType::F32, DType::F32],
13159 BackendId::Cpu,
13160 stub,
13161 );
13162 table.register(
13164 OpKind::MulElementwise,
13165 &[DType::F32, DType::F32, DType::F32],
13166 BackendId::Vulkan,
13167 stub_b,
13168 );
13169 table.register(
13172 OpKind::MatMul,
13173 &[DType::F16, DType::F16, DType::F32],
13174 BackendId::Vulkan,
13175 stub_c,
13176 );
13177
13178 let vk0 = DeviceLocation::Vulkan { gpu_id: 0 };
13179 let caps = derive_backend_caps(BackendId::Vulkan, vk0, &table);
13180
13181 assert_eq!(caps.backend_id, BackendId::Vulkan);
13182 assert_eq!(caps.device_location, vk0);
13183 assert_eq!(caps.storage_substrate, SubstrateClass::VulkanBuffer);
13184 assert!(
13186 caps.op_dtype_support
13187 .contains(&(OpKind::MulElementwise, DType::F32))
13188 );
13189 assert!(
13191 caps.op_dtype_support
13192 .contains(&(OpKind::MatMul, DType::F32))
13193 );
13194 assert!(
13195 !caps
13196 .op_dtype_support
13197 .contains(&(OpKind::MatMul, DType::F16))
13198 );
13199 assert!(
13201 !caps
13202 .op_dtype_support
13203 .contains(&(OpKind::AddElementwise, DType::F32))
13204 );
13205 assert!(caps
13208 .transfer_paths
13209 .iter()
13210 .any(|&(dst, path)| dst == DeviceLocation::Cpu && path == TransferPath::HostStaging));
13211 }
13212
13213 #[test]
13224 #[ignore = "requires a live CUDA device"]
13225 #[cfg(feature = "cuda")]
13226 fn copy_from_cuda_wrapper_cuda_output_write_into_matches_old_behavior() {
13227 use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
13228
13229 let Ok(dev) = CudaDevice::new(0) else {
13230 return fuel_test_support::hardware::skip(
13231 fuel_test_support::hardware::Hardware::Cuda,
13232 fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
13233 );
13234 };
13235
13236 let src_data: Vec<f32> = (0..17).map(|i| i as f32 * 1.5 - 3.0).collect();
13237 let src_bytes: Vec<u8> = src_data.iter().flat_map(|f| f.to_le_bytes()).collect();
13238 let src_cb = CudaStorageBytes::from_cpu_bytes(&dev, &src_bytes).expect("h2d src");
13239 let src_arc: Arc<RwLock<Storage>> = Arc::new(RwLock::new(Storage::new(
13240 BackendStorage::Cuda(src_cb),
13241 DType::F32,
13242 )));
13243
13244 let garbage: Vec<u8> = vec![0xAAu8; src_bytes.len()];
13248 let dst_cb = CudaStorageBytes::from_cpu_bytes(&dev, &garbage).expect("h2d garbage");
13249 let dst_arc: Arc<RwLock<Storage>> = Arc::new(RwLock::new(Storage::new(
13250 BackendStorage::Cuda(dst_cb),
13251 DType::F32,
13252 )));
13253
13254 let before_ptr = {
13256 let g = dst_arc.read().unwrap();
13257 let BackendStorage::Cuda(c) = &g.inner else {
13258 panic!("not cuda")
13259 };
13260 c.buffer() as *const _ as usize
13261 };
13262
13263 let inputs = vec![Arc::clone(&src_arc)];
13264 let mut outputs = vec![Arc::clone(&dst_arc)];
13265 copy_from_cuda_wrapper(&inputs, &mut outputs, &[], &OpParams::None)
13266 .expect("copy_from_cuda_wrapper (write-into CUDA branch)");
13267
13268 let after_ptr = {
13269 let g = dst_arc.read().unwrap();
13270 let BackendStorage::Cuda(c) = &g.inner else {
13271 panic!("not cuda")
13272 };
13273 c.buffer() as *const _ as usize
13274 };
13275 assert_eq!(
13276 before_ptr, after_ptr,
13277 "write-into must preserve the output's buffer identity (device address)"
13278 );
13279
13280 let new_bytes = {
13281 let g = dst_arc.read().unwrap();
13282 let BackendStorage::Cuda(c) = &g.inner else {
13283 panic!("not cuda")
13284 };
13285 c.to_cpu_bytes().expect("d2h new")
13286 };
13287
13288 let old_bytes = {
13291 let g = src_arc.read().unwrap();
13292 let BackendStorage::Cuda(c) = &g.inner else {
13293 panic!("not cuda")
13294 };
13295 let copied = c
13296 .slot_copy_to_new(0, c.len_bytes())
13297 .expect("slot_copy_to_new (old allocate-and-replace path)");
13298 copied.to_cpu_bytes().expect("d2h old")
13299 };
13300
13301 assert_eq!(
13302 new_bytes, old_bytes,
13303 "write-into result must byte-match the old slot_copy_to_new result"
13304 );
13305 assert_eq!(new_bytes, src_bytes, "and both must match the source bytes");
13306 }
13307}