1use core::mem::MaybeUninit;
4use strided_basic::execution::validate_destination_layout;
5#[cfg(test)]
6use strided_basic::execution::{is_injective_layout, validate_destination_layout_without_alloc};
7
8use crate::{Result, StridedError, StridedView, StridedViewMut};
9use strided_basic::execution::{
10 build_plan_fused, build_plan_fused_small, ensure_same_shape, for_each_inner_block_preordered,
11 SMALL_TENSOR_THRESHOLD,
12};
13use strided_basic::execution::{compute_costs, mapreduce_threaded, parallel_width, KernelClass};
14use strided_basic::execution::{
15 map_into_validated, zip_map2_into_validated, zip_map3_into_validated, zip_map4_into_validated,
16 ValidatedDestinationLayout,
17};
18use strided_basic::Exec;
19
20mod chunk;
21
22pub(crate) struct InitializedViewsMut<'a, T> {
30 storage: *mut MaybeUninit<StridedViewMut<'a, T>>,
31 len: usize,
32}
33
34impl<'a, T> InitializedViewsMut<'a, T> {
35 pub(crate) unsafe fn new(storage: *mut MaybeUninit<StridedViewMut<'a, T>>) -> Self {
39 Self { storage, len: 0 }
40 }
41
42 pub(crate) fn push(&mut self, view: StridedViewMut<'a, T>) {
44 debug_assert!(self.len < strided_basic::OPERAND_CAP);
45 unsafe { self.storage.add(self.len).write(MaybeUninit::new(view)) };
50 self.len += 1;
51 }
52
53 pub(crate) fn as_mut_slice(&mut self) -> &mut [StridedViewMut<'a, T>] {
55 unsafe {
59 core::slice::from_raw_parts_mut(self.storage.cast::<StridedViewMut<'a, T>>(), self.len)
60 }
61 }
62}
63
64impl<T> Drop for InitializedViewsMut<'_, T> {
65 fn drop(&mut self) {
66 for index in 0..self.len {
67 unsafe { (*self.storage.add(index)).assume_init_drop() };
70 }
71 }
72}
73
74#[repr(transparent)]
80#[derive(Clone, Copy, Debug)]
81pub(super) struct OperandPtr<T>(*mut T);
82
83impl<T> Default for OperandPtr<T> {
84 fn default() -> Self {
85 Self(core::ptr::null_mut())
86 }
87}
88
89unsafe impl<T> Send for OperandPtr<T> {}
93unsafe impl<T> Sync for OperandPtr<T> {}
95
96impl<T> OperandPtr<T> {
97 #[inline]
98 fn new(ptr: *mut T) -> Self {
99 Self(ptr)
100 }
101}
102
103#[inline]
105fn operand_ptrs<T>(ptrs: &[OperandPtr<T>]) -> &[*mut T] {
106 unsafe { core::slice::from_raw_parts(ptrs.as_ptr().cast::<*mut T>(), ptrs.len()) }
109}
110
111#[inline]
113fn operand_const_ptrs<T>(ptrs: &[OperandPtr<T>]) -> &[*const T] {
114 unsafe { core::slice::from_raw_parts(ptrs.as_ptr().cast::<*const T>(), ptrs.len()) }
117}
118
119#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
121pub enum FusedOp {
122 #[default]
123 Add,
124 Subtract,
131 Multiply,
132 Negate,
133 Conj,
134 Divide,
135 Abs,
136 Maximum,
137 Minimum,
138 Clamp,
139 Exp,
140 Log,
141 Sin,
142 Cos,
143 Tanh,
144 Sqrt,
145 Rsqrt,
146 Pow,
147 Expm1,
148 Log1p,
149}
150
151impl FusedOp {
152 #[inline]
153 pub const fn label(self) -> &'static str {
154 match self {
155 Self::Add => "add",
156 Self::Subtract => "subtract",
157 Self::Multiply => "multiply",
158 Self::Negate => "negate",
159 Self::Conj => "conj",
160 Self::Divide => "divide",
161 Self::Abs => "abs",
162 Self::Maximum => "maximum",
163 Self::Minimum => "minimum",
164 Self::Clamp => "clamp",
165 Self::Exp => "exp",
166 Self::Log => "log",
167 Self::Sin => "sin",
168 Self::Cos => "cos",
169 Self::Tanh => "tanh",
170 Self::Sqrt => "sqrt",
171 Self::Rsqrt => "rsqrt",
172 Self::Pow => "pow",
173 Self::Expm1 => "expm1",
174 Self::Log1p => "log1p",
175 }
176 }
177}
178
179#[derive(Clone, Debug, Eq, PartialEq)]
185pub struct FusedInst {
186 pub op: FusedOp,
187 pub inputs: strided_basic::OperandVec<usize>,
188}
189
190impl FusedInst {
191 pub fn new(op: FusedOp, inputs: impl IntoIterator<Item = usize>) -> Self {
199 Self {
200 op,
201 inputs: inputs.into_iter().collect(),
202 }
203 }
204}
205
206impl Default for FusedInst {
207 fn default() -> Self {
208 Self {
209 op: FusedOp::default(),
210 inputs: strided_basic::OperandVec::new(),
211 }
212 }
213}
214
215#[derive(Clone, Debug, Eq, PartialEq)]
235pub struct FusedPlan {
236 pub input_count: usize,
237 pub outputs: strided_basic::OperandVec<usize>,
238 pub ops: strided_basic::InlineVec<FusedInst>,
239}
240
241impl FusedPlan {
242 pub fn new(
257 input_count: usize,
258 outputs: impl IntoIterator<Item = usize>,
259 ops: impl IntoIterator<Item = FusedInst>,
260 ) -> Self {
261 Self {
262 input_count,
263 outputs: outputs.into_iter().collect(),
264 ops: ops.into_iter().collect(),
265 }
266 }
267}
268
269pub trait FusedScalar: Copy + Send + Sync + 'static {
271 fn fused_dtype_label() -> &'static str {
272 core::any::type_name::<Self>()
273 }
274
275 fn supports_fused_op(_op: FusedOp) -> bool {
276 true
277 }
278
279 fn fused_add(self, rhs: Self) -> Self;
280 fn fused_subtract(self, rhs: Self) -> Self;
281 fn fused_multiply(self, rhs: Self) -> Self;
282 fn fused_negate(self) -> Self;
283 fn fused_conj(self) -> Self;
284 fn fused_divide(self, rhs: Self) -> Self;
285 fn fused_abs(self) -> Self;
286 fn fused_maximum(self, rhs: Self) -> Self;
287 fn fused_minimum(self, rhs: Self) -> Self;
288 fn fused_clamp(self, min: Self, max: Self) -> Self;
289 fn fused_exp(self) -> Self;
290 fn fused_log(self) -> Self;
291 fn fused_sin(self) -> Self;
292 fn fused_cos(self) -> Self;
293 fn fused_tanh(self) -> Self;
294 fn fused_sqrt(self) -> Self;
295 fn fused_rsqrt(self) -> Self;
296 fn fused_pow(self, rhs: Self) -> Self;
297 fn fused_expm1(self) -> Self;
298 fn fused_log1p(self) -> Self;
299}
300
301macro_rules! unsupported_fused_op {
302 ($op:literal, $ty:literal) => {
303 unreachable!("unsupported fused op {} for dtype {}", $op, $ty)
304 };
305}
306
307macro_rules! impl_real_fused_scalar {
308 ($ty:ty) => {
309 impl FusedScalar for $ty {
310 #[inline(always)]
311 fn fused_add(self, rhs: Self) -> Self {
312 self + rhs
313 }
314
315 #[inline(always)]
316 fn fused_subtract(self, rhs: Self) -> Self {
317 self - rhs
318 }
319
320 #[inline(always)]
321 fn fused_multiply(self, rhs: Self) -> Self {
322 self * rhs
323 }
324
325 #[inline(always)]
326 fn fused_negate(self) -> Self {
327 -self
328 }
329
330 #[inline(always)]
331 fn fused_conj(self) -> Self {
332 self
333 }
334
335 #[inline(always)]
336 fn fused_divide(self, rhs: Self) -> Self {
337 self / rhs
338 }
339
340 #[inline(always)]
341 fn fused_abs(self) -> Self {
342 self.abs()
343 }
344
345 #[inline(always)]
346 fn fused_maximum(self, rhs: Self) -> Self {
347 strided_basic::nan_propagating_maximum(self, rhs)
350 }
351
352 #[inline(always)]
353 fn fused_minimum(self, rhs: Self) -> Self {
354 strided_basic::nan_propagating_minimum(self, rhs)
355 }
356
357 #[inline(always)]
358 fn fused_clamp(self, min: Self, max: Self) -> Self {
359 max.fused_minimum(min.fused_maximum(self))
363 }
364
365 #[inline(always)]
366 fn fused_exp(self) -> Self {
367 self.exp()
368 }
369
370 #[inline(always)]
371 fn fused_log(self) -> Self {
372 self.ln()
373 }
374
375 #[inline(always)]
376 fn fused_sin(self) -> Self {
377 self.sin()
378 }
379
380 #[inline(always)]
381 fn fused_cos(self) -> Self {
382 self.cos()
383 }
384
385 #[inline(always)]
386 fn fused_tanh(self) -> Self {
387 self.tanh()
388 }
389
390 #[inline(always)]
391 fn fused_sqrt(self) -> Self {
392 self.sqrt()
393 }
394
395 #[inline(always)]
396 fn fused_rsqrt(self) -> Self {
397 1.0 / self.sqrt()
398 }
399
400 #[inline(always)]
401 fn fused_pow(self, rhs: Self) -> Self {
402 self.powf(rhs)
403 }
404
405 #[inline(always)]
406 fn fused_expm1(self) -> Self {
407 self.exp_m1()
408 }
409
410 #[inline(always)]
411 fn fused_log1p(self) -> Self {
412 self.ln_1p()
413 }
414 }
415 };
416}
417
418macro_rules! impl_complex_fused_scalar {
419 ($ty:ty, $div:path) => {
420 impl FusedScalar for $ty {
421 #[inline(always)]
422 fn fused_add(self, rhs: Self) -> Self {
423 self + rhs
424 }
425
426 #[inline(always)]
427 fn fused_subtract(self, rhs: Self) -> Self {
428 self - rhs
429 }
430
431 #[inline(always)]
432 fn fused_multiply(self, rhs: Self) -> Self {
433 self * rhs
434 }
435
436 #[inline(always)]
437 fn fused_negate(self) -> Self {
438 -self
439 }
440
441 #[inline(always)]
442 fn fused_conj(self) -> Self {
443 num_complex::Complex::conj(&self)
444 }
445
446 #[inline(always)]
447 fn fused_divide(self, rhs: Self) -> Self {
448 $div(self, rhs)
449 }
450
451 #[inline(always)]
452 fn fused_abs(self) -> Self {
453 Self::new(self.norm(), 0.0)
454 }
455
456 #[inline(always)]
457 fn fused_maximum(self, rhs: Self) -> Self {
458 if self.norm_sqr() >= rhs.norm_sqr() {
459 self
460 } else {
461 rhs
462 }
463 }
464
465 #[inline(always)]
466 fn fused_minimum(self, rhs: Self) -> Self {
467 if self.norm_sqr() <= rhs.norm_sqr() {
468 self
469 } else {
470 rhs
471 }
472 }
473
474 #[inline(always)]
475 fn fused_clamp(self, min: Self, max: Self) -> Self {
476 self.fused_maximum(min).fused_minimum(max)
477 }
478
479 #[inline(always)]
480 fn fused_exp(self) -> Self {
481 self.exp()
482 }
483
484 #[inline(always)]
485 fn fused_log(self) -> Self {
486 self.ln()
487 }
488
489 #[inline(always)]
490 fn fused_sin(self) -> Self {
491 self.sin()
492 }
493
494 #[inline(always)]
495 fn fused_cos(self) -> Self {
496 self.cos()
497 }
498
499 #[inline(always)]
500 fn fused_tanh(self) -> Self {
501 self.tanh()
502 }
503
504 #[inline(always)]
505 fn fused_sqrt(self) -> Self {
506 self.sqrt()
507 }
508
509 #[inline(always)]
510 fn fused_rsqrt(self) -> Self {
511 Self::new(1.0, 0.0) / self.sqrt()
512 }
513
514 #[inline(always)]
515 fn fused_pow(self, rhs: Self) -> Self {
516 self.powc(rhs)
517 }
518
519 #[inline(always)]
520 fn fused_expm1(self) -> Self {
521 self.exp() - Self::new(1.0, 0.0)
522 }
523
524 #[inline(always)]
525 fn fused_log1p(self) -> Self {
526 (self + Self::new(1.0, 0.0)).ln()
527 }
528 }
529 };
530}
531
532impl_real_fused_scalar!(f32);
533impl_real_fused_scalar!(f64);
534impl_complex_fused_scalar!(
535 num_complex::Complex32,
536 strided_basic::robust_complex_divide_f32
537);
538impl_complex_fused_scalar!(
539 num_complex::Complex64,
540 strided_basic::robust_complex_divide_f64
541);
542
543macro_rules! impl_signed_integer_fused_scalar {
544 ($ty:ty, $label:literal) => {
545 impl FusedScalar for $ty {
546 #[inline]
547 fn fused_dtype_label() -> &'static str {
548 $label
549 }
550
551 #[inline]
552 fn supports_fused_op(op: FusedOp) -> bool {
553 matches!(
554 op,
555 FusedOp::Add
556 | FusedOp::Subtract
557 | FusedOp::Multiply
558 | FusedOp::Negate
559 | FusedOp::Conj
560 | FusedOp::Abs
561 | FusedOp::Maximum
562 | FusedOp::Minimum
563 | FusedOp::Clamp
564 )
565 }
566
567 #[inline(always)]
568 fn fused_add(self, rhs: Self) -> Self {
569 self.wrapping_add(rhs)
570 }
571
572 #[inline(always)]
573 fn fused_subtract(self, rhs: Self) -> Self {
574 self.wrapping_sub(rhs)
575 }
576
577 #[inline(always)]
578 fn fused_multiply(self, rhs: Self) -> Self {
579 self.wrapping_mul(rhs)
580 }
581
582 #[inline(always)]
583 fn fused_negate(self) -> Self {
584 self.wrapping_neg()
585 }
586
587 #[inline(always)]
588 fn fused_conj(self) -> Self {
589 self
590 }
591
592 #[inline(always)]
593 fn fused_divide(self, _rhs: Self) -> Self {
594 unsupported_fused_op!("divide", $label)
595 }
596
597 #[inline(always)]
598 fn fused_abs(self) -> Self {
599 self.wrapping_abs()
600 }
601
602 #[inline(always)]
603 fn fused_maximum(self, rhs: Self) -> Self {
604 self.max(rhs)
605 }
606
607 #[inline(always)]
608 fn fused_minimum(self, rhs: Self) -> Self {
609 self.min(rhs)
610 }
611
612 #[inline(always)]
613 fn fused_clamp(self, min: Self, max: Self) -> Self {
614 self.fused_maximum(min).fused_minimum(max)
615 }
616
617 #[inline(always)]
618 fn fused_exp(self) -> Self {
619 unsupported_fused_op!("exp", $label)
620 }
621
622 #[inline(always)]
623 fn fused_log(self) -> Self {
624 unsupported_fused_op!("log", $label)
625 }
626
627 #[inline(always)]
628 fn fused_sin(self) -> Self {
629 unsupported_fused_op!("sin", $label)
630 }
631
632 #[inline(always)]
633 fn fused_cos(self) -> Self {
634 unsupported_fused_op!("cos", $label)
635 }
636
637 #[inline(always)]
638 fn fused_tanh(self) -> Self {
639 unsupported_fused_op!("tanh", $label)
640 }
641
642 #[inline(always)]
643 fn fused_sqrt(self) -> Self {
644 unsupported_fused_op!("sqrt", $label)
645 }
646
647 #[inline(always)]
648 fn fused_rsqrt(self) -> Self {
649 unsupported_fused_op!("rsqrt", $label)
650 }
651
652 #[inline(always)]
653 fn fused_pow(self, _rhs: Self) -> Self {
654 unsupported_fused_op!("pow", $label)
655 }
656
657 #[inline(always)]
658 fn fused_expm1(self) -> Self {
659 unsupported_fused_op!("expm1", $label)
660 }
661
662 #[inline(always)]
663 fn fused_log1p(self) -> Self {
664 unsupported_fused_op!("log1p", $label)
665 }
666 }
667 };
668}
669
670impl_signed_integer_fused_scalar!(i32, "i32");
671impl_signed_integer_fused_scalar!(i64, "i64");
672
673impl FusedScalar for bool {
674 #[inline]
675 fn fused_dtype_label() -> &'static str {
676 "bool"
677 }
678
679 #[inline]
680 fn supports_fused_op(op: FusedOp) -> bool {
681 matches!(op, FusedOp::Conj)
682 }
683
684 #[inline(always)]
685 fn fused_add(self, _rhs: Self) -> Self {
686 unsupported_fused_op!("add", "bool")
687 }
688
689 #[inline(always)]
690 fn fused_subtract(self, _rhs: Self) -> Self {
691 unsupported_fused_op!("subtract", "bool")
692 }
693
694 #[inline(always)]
695 fn fused_multiply(self, _rhs: Self) -> Self {
696 unsupported_fused_op!("multiply", "bool")
697 }
698
699 #[inline(always)]
700 fn fused_negate(self) -> Self {
701 unsupported_fused_op!("negate", "bool")
702 }
703
704 #[inline(always)]
705 fn fused_conj(self) -> Self {
706 self
707 }
708
709 #[inline(always)]
710 fn fused_divide(self, _rhs: Self) -> Self {
711 unsupported_fused_op!("divide", "bool")
712 }
713
714 #[inline(always)]
715 fn fused_abs(self) -> Self {
716 unsupported_fused_op!("abs", "bool")
717 }
718
719 #[inline(always)]
720 fn fused_maximum(self, _rhs: Self) -> Self {
721 unsupported_fused_op!("maximum", "bool")
722 }
723
724 #[inline(always)]
725 fn fused_minimum(self, _rhs: Self) -> Self {
726 unsupported_fused_op!("minimum", "bool")
727 }
728
729 #[inline(always)]
730 fn fused_clamp(self, _min: Self, _max: Self) -> Self {
731 unsupported_fused_op!("clamp", "bool")
732 }
733
734 #[inline(always)]
735 fn fused_exp(self) -> Self {
736 unsupported_fused_op!("exp", "bool")
737 }
738
739 #[inline(always)]
740 fn fused_log(self) -> Self {
741 unsupported_fused_op!("log", "bool")
742 }
743
744 #[inline(always)]
745 fn fused_sin(self) -> Self {
746 unsupported_fused_op!("sin", "bool")
747 }
748
749 #[inline(always)]
750 fn fused_cos(self) -> Self {
751 unsupported_fused_op!("cos", "bool")
752 }
753
754 #[inline(always)]
755 fn fused_tanh(self) -> Self {
756 unsupported_fused_op!("tanh", "bool")
757 }
758
759 #[inline(always)]
760 fn fused_sqrt(self) -> Self {
761 unsupported_fused_op!("sqrt", "bool")
762 }
763
764 #[inline(always)]
765 fn fused_rsqrt(self) -> Self {
766 unsupported_fused_op!("rsqrt", "bool")
767 }
768
769 #[inline(always)]
770 fn fused_pow(self, _rhs: Self) -> Self {
771 unsupported_fused_op!("pow", "bool")
772 }
773
774 #[inline(always)]
775 fn fused_expm1(self) -> Self {
776 unsupported_fused_op!("expm1", "bool")
777 }
778
779 #[inline(always)]
780 fn fused_log1p(self) -> Self {
781 unsupported_fused_op!("log1p", "bool")
782 }
783}
784
785#[inline]
786fn op_arity(op: FusedOp) -> usize {
787 match op {
788 FusedOp::Negate
789 | FusedOp::Conj
790 | FusedOp::Abs
791 | FusedOp::Exp
792 | FusedOp::Log
793 | FusedOp::Sin
794 | FusedOp::Cos
795 | FusedOp::Tanh
796 | FusedOp::Sqrt
797 | FusedOp::Rsqrt
798 | FusedOp::Expm1
799 | FusedOp::Log1p => 1,
800 FusedOp::Add
801 | FusedOp::Subtract
802 | FusedOp::Multiply
803 | FusedOp::Divide
804 | FusedOp::Maximum
805 | FusedOp::Minimum
806 | FusedOp::Pow => 2,
807 FusedOp::Clamp => 3,
808 }
809}
810
811pub(crate) fn validate_plan(
812 plan: &FusedPlan,
813 input_count: usize,
814 output_count: usize,
815) -> Result<()> {
816 if input_count != plan.input_count {
817 return Err(StridedError::RankMismatch(input_count, plan.input_count));
818 }
819 if output_count != plan.outputs.len() {
820 return Err(StridedError::RankMismatch(output_count, plan.outputs.len()));
821 }
822 if output_count == 0 {
823 return Err(StridedError::RankMismatch(0, 1));
824 }
825
826 let mut value_count = plan.input_count;
827 for inst in &plan.ops {
828 let expected_arity = op_arity(inst.op);
829 if inst.inputs.len() != expected_arity {
830 return Err(StridedError::RankMismatch(
831 inst.inputs.len(),
832 expected_arity,
833 ));
834 }
835 for &input in &inst.inputs {
836 if input >= value_count {
837 return Err(StridedError::InvalidAxis {
838 axis: input,
839 rank: value_count,
840 });
841 }
842 }
843 value_count += 1;
844 }
845
846 for &output in &plan.outputs {
847 if output >= value_count {
848 return Err(StridedError::InvalidAxis {
849 axis: output,
850 rank: value_count,
851 });
852 }
853 }
854
855 Ok(())
856}
857
858pub(crate) fn validate_plan_for_scalar<T: FusedScalar>(
859 plan: &FusedPlan,
860 input_count: usize,
861 output_count: usize,
862) -> Result<()> {
863 validate_plan(plan, input_count, output_count)?;
864 for inst in &plan.ops {
865 if !T::supports_fused_op(inst.op) {
866 return Err(StridedError::UnsupportedOp {
867 op: inst.op.label(),
868 dtype: T::fused_dtype_label(),
869 });
870 }
871 }
872 Ok(())
873}
874
875fn validate_shapes<T: FusedScalar>(
876 dests: &[StridedViewMut<'_, T>],
877 inputs: &[StridedView<'_, T>],
878) -> Result<ValidatedDestinationLayout> {
879 let dims = dests[0].dims();
880 let first = validate_destination_layout(dests[0].dims(), dests[0].strides())?;
883 for dest in &dests[1..] {
884 validate_destination_layout(dest.dims(), dest.strides())?;
885 ensure_same_shape(dims, dest.dims())?;
886 }
887 for input in inputs {
888 ensure_same_shape(dims, input.dims())?;
889 }
890 Ok(first)
891}
892
893#[inline(always)]
894fn eval_op<T: FusedScalar>(op: FusedOp, regs: &[T], inputs: &[usize]) -> T {
895 match op {
896 FusedOp::Negate
897 | FusedOp::Conj
898 | FusedOp::Abs
899 | FusedOp::Exp
900 | FusedOp::Log
901 | FusedOp::Sin
902 | FusedOp::Cos
903 | FusedOp::Tanh
904 | FusedOp::Sqrt
905 | FusedOp::Rsqrt
906 | FusedOp::Expm1
907 | FusedOp::Log1p => eval_unary(op, regs[inputs[0]]),
908 FusedOp::Add
909 | FusedOp::Subtract
910 | FusedOp::Multiply
911 | FusedOp::Divide
912 | FusedOp::Maximum
913 | FusedOp::Minimum
914 | FusedOp::Pow => eval_binary(op, regs[inputs[0]], regs[inputs[1]]),
915 FusedOp::Clamp => eval_ternary(op, regs[inputs[0]], regs[inputs[1]], regs[inputs[2]]),
916 }
917}
918
919#[inline(always)]
920fn eval_unary<T: FusedScalar>(op: FusedOp, x: T) -> T {
921 match op {
922 FusedOp::Negate => x.fused_negate(),
923 FusedOp::Conj => x.fused_conj(),
924 FusedOp::Abs => x.fused_abs(),
925 FusedOp::Exp => x.fused_exp(),
926 FusedOp::Log => x.fused_log(),
927 FusedOp::Sin => x.fused_sin(),
928 FusedOp::Cos => x.fused_cos(),
929 FusedOp::Tanh => x.fused_tanh(),
930 FusedOp::Sqrt => x.fused_sqrt(),
931 FusedOp::Rsqrt => x.fused_rsqrt(),
932 FusedOp::Expm1 => x.fused_expm1(),
933 FusedOp::Log1p => x.fused_log1p(),
934 _ => unreachable!("not a unary fused op: {op:?}"),
935 }
936}
937
938#[inline(always)]
939fn eval_binary<T: FusedScalar>(op: FusedOp, a: T, b: T) -> T {
940 match op {
941 FusedOp::Add => a.fused_add(b),
942 FusedOp::Subtract => a.fused_subtract(b),
943 FusedOp::Multiply => a.fused_multiply(b),
944 FusedOp::Divide => a.fused_divide(b),
945 FusedOp::Maximum => a.fused_maximum(b),
946 FusedOp::Minimum => a.fused_minimum(b),
947 FusedOp::Pow => a.fused_pow(b),
948 _ => unreachable!("not a binary fused op: {op:?}"),
949 }
950}
951
952#[inline(always)]
953fn eval_ternary<T: FusedScalar>(op: FusedOp, a: T, b: T, c: T) -> T {
954 match op {
955 FusedOp::Clamp => a.fused_clamp(b, c),
956 _ => unreachable!("not a ternary fused op: {op:?}"),
957 }
958}
959
960#[derive(Clone, Copy)]
961enum StaticFusedKind {
962 Unary(FusedOp, usize),
963 Binary(FusedOp, usize, usize),
964 Ternary(FusedOp, usize, usize, usize),
965 AddMulLeft,
966 AddMulRight,
967 MulAddExp,
968 DivClampSqrtRsqrt,
969}
970
971#[cfg(test)]
972std::thread_local! {
973 static UNINITIALIZED_STATIC_FAMILY_HITS: core::cell::Cell<[usize; 7]> =
974 const { core::cell::Cell::new([0; 7]) };
975}
976
977#[cfg(test)]
978impl StaticFusedKind {
979 fn test_index(self) -> usize {
980 match self {
981 Self::Unary(..) => 0,
982 Self::Binary(..) => 1,
983 Self::Ternary(..) => 2,
984 Self::AddMulLeft => 3,
985 Self::AddMulRight => 4,
986 Self::MulAddExp => 5,
987 Self::DivClampSqrtRsqrt => 6,
988 }
989 }
990}
991
992#[cfg(test)]
993fn reset_uninitialized_static_family_hits() {
994 UNINITIALIZED_STATIC_FAMILY_HITS.set([0; 7]);
995}
996
997#[cfg(test)]
998fn uninitialized_static_family_hits() -> [usize; 7] {
999 UNINITIALIZED_STATIC_FAMILY_HITS.get()
1000}
1001
1002#[cfg(test)]
1003fn record_uninitialized_static_family_hit(kind: StaticFusedKind) {
1004 UNINITIALIZED_STATIC_FAMILY_HITS.set({
1005 let mut hits = UNINITIALIZED_STATIC_FAMILY_HITS.get();
1006 hits[kind.test_index()] += 1;
1007 hits
1008 });
1009}
1010
1011fn classify_static_specialization(plan: &FusedPlan) -> Option<StaticFusedKind> {
1012 if plan.outputs.len() != 1 {
1013 return None;
1014 }
1015 if let [inst] = plan.ops.as_slice() {
1016 if plan.outputs[0] != plan.input_count {
1017 return None;
1018 }
1019 return match (op_arity(inst.op), inst.inputs.as_slice()) {
1020 (1, [a]) => Some(StaticFusedKind::Unary(inst.op, *a)),
1021 (2, [a, b]) => Some(StaticFusedKind::Binary(inst.op, *a, *b)),
1022 (3, [a, b, c]) => Some(StaticFusedKind::Ternary(inst.op, *a, *b, *c)),
1023 _ => None,
1024 };
1025 }
1026 if plan.input_count == 2
1027 && plan.outputs.as_slice() == [3]
1028 && plan.ops.len() == 2
1029 && plan.ops[0].op == FusedOp::Add
1030 && plan.ops[0].inputs.as_slice() == [0, 1]
1031 && plan.ops[1].op == FusedOp::Multiply
1032 {
1033 return match plan.ops[1].inputs.as_slice() {
1034 [2, 0] => Some(StaticFusedKind::AddMulLeft),
1035 [0, 2] => Some(StaticFusedKind::AddMulRight),
1036 _ => None,
1037 };
1038 }
1039 if plan.input_count == 3
1040 && plan.outputs.as_slice() == [5]
1041 && plan.ops.len() == 3
1042 && plan.ops[0].op == FusedOp::Multiply
1043 && plan.ops[0].inputs.as_slice() == [0, 1]
1044 && plan.ops[1].op == FusedOp::Add
1045 && plan.ops[1].inputs.as_slice() == [3, 2]
1046 && plan.ops[2].op == FusedOp::Exp
1047 && plan.ops[2].inputs.as_slice() == [4]
1048 {
1049 return Some(StaticFusedKind::MulAddExp);
1050 }
1051 if plan.input_count == 4
1052 && plan.outputs.as_slice() == [8]
1053 && plan.ops.len() == 5
1054 && plan.ops[0].op == FusedOp::Divide
1055 && plan.ops[0].inputs.as_slice() == [0, 1]
1056 && plan.ops[1].op == FusedOp::Maximum
1057 && plan.ops[1].inputs.as_slice() == [4, 2]
1058 && plan.ops[2].op == FusedOp::Minimum
1059 && plan.ops[2].inputs.as_slice() == [5, 3]
1060 && plan.ops[3].op == FusedOp::Sqrt
1061 && plan.ops[3].inputs.as_slice() == [6]
1062 && plan.ops[4].op == FusedOp::Rsqrt
1063 && plan.ops[4].inputs.as_slice() == [7]
1064 {
1065 return Some(StaticFusedKind::DivClampSqrtRsqrt);
1066 }
1067 None
1068}
1069
1070trait StaticOutput<T: FusedScalar> {
1071 type Value: Copy + Send + Sync;
1072
1073 #[cfg(test)]
1074 const IS_UNINITIALIZED: bool;
1075
1076 fn write(value: T) -> Self::Value;
1077}
1078
1079struct InitializedStaticOutput;
1080
1081impl<T: FusedScalar> StaticOutput<T> for InitializedStaticOutput {
1082 type Value = T;
1083
1084 #[cfg(test)]
1085 const IS_UNINITIALIZED: bool = false;
1086
1087 #[inline(always)]
1088 fn write(value: T) -> T {
1089 value
1090 }
1091}
1092
1093struct UninitializedStaticOutput;
1094
1095impl<T: FusedScalar> StaticOutput<T> for UninitializedStaticOutput {
1096 type Value = MaybeUninit<T>;
1097
1098 #[cfg(test)]
1099 const IS_UNINITIALIZED: bool = true;
1100
1101 #[inline(always)]
1102 fn write(value: T) -> MaybeUninit<T> {
1103 MaybeUninit::new(value)
1104 }
1105}
1106
1107fn try_static_specialization_validated<T, O>(
1108 dest: &mut StridedViewMut<'_, O::Value>,
1109 inputs: &[StridedView<'_, T>],
1110 plan: &FusedPlan,
1111 validated: ValidatedDestinationLayout,
1112 exec: Exec<'_>,
1113) -> Result<bool>
1114where
1115 T: FusedScalar,
1116 O: StaticOutput<T>,
1117{
1118 let Some(kind) = classify_static_specialization(plan) else {
1119 return Ok(false);
1120 };
1121 #[cfg(test)]
1122 if O::IS_UNINITIALIZED {
1123 record_uninitialized_static_family_hit(kind);
1124 }
1125
1126 match kind {
1127 StaticFusedKind::Unary(op, a) => {
1128 macro_rules! unary {
1132 ($apply:expr) => {{
1133 unsafe {
1144 map_into_validated(
1145 dest,
1146 &inputs[a],
1147 strided_basic::Classed::new(op_class(op), |x: T| O::write($apply(x))),
1148 validated,
1149 exec,
1150 )
1151 }?
1152 }};
1153 }
1154 match op {
1155 FusedOp::Negate => unary!(|x: T| x.fused_negate()),
1156 FusedOp::Conj => unary!(|x: T| x.fused_conj()),
1157 FusedOp::Abs => unary!(|x: T| x.fused_abs()),
1158 FusedOp::Exp => unary!(|x: T| x.fused_exp()),
1159 FusedOp::Log => unary!(|x: T| x.fused_log()),
1160 FusedOp::Sin => unary!(|x: T| x.fused_sin()),
1161 FusedOp::Cos => unary!(|x: T| x.fused_cos()),
1162 FusedOp::Tanh => unary!(|x: T| x.fused_tanh()),
1163 FusedOp::Sqrt => unary!(|x: T| x.fused_sqrt()),
1164 FusedOp::Rsqrt => unary!(|x: T| x.fused_rsqrt()),
1165 FusedOp::Expm1 => unary!(|x: T| x.fused_expm1()),
1166 FusedOp::Log1p => unary!(|x: T| x.fused_log1p()),
1167 _ => unreachable!("not a unary fused op: {op:?}"),
1168 }
1169 }
1170 StaticFusedKind::Binary(op, a, b) => {
1171 macro_rules! binary {
1173 ($apply:expr) => {{
1174 unsafe {
1178 zip_map2_into_validated(
1179 dest,
1180 &inputs[a],
1181 &inputs[b],
1182 |x, y| O::write($apply(x, y)),
1183 validated,
1184 exec,
1185 )
1186 }?
1187 }};
1188 }
1189 match op {
1190 FusedOp::Add => binary!(|x: T, y: T| x.fused_add(y)),
1191 FusedOp::Subtract => binary!(|x: T, y: T| x.fused_subtract(y)),
1192 FusedOp::Multiply => binary!(|x: T, y: T| x.fused_multiply(y)),
1193 FusedOp::Divide => binary!(|x: T, y: T| x.fused_divide(y)),
1194 FusedOp::Maximum => binary!(|x: T, y: T| x.fused_maximum(y)),
1195 FusedOp::Minimum => binary!(|x: T, y: T| x.fused_minimum(y)),
1196 FusedOp::Pow => binary!(|x: T, y: T| x.fused_pow(y)),
1197 _ => unreachable!("not a binary fused op: {op:?}"),
1198 }
1199 }
1200 StaticFusedKind::Ternary(op, a, b, c) => match op {
1201 FusedOp::Clamp => {
1202 unsafe {
1205 zip_map3_into_validated(
1206 dest,
1207 &inputs[a],
1208 &inputs[b],
1209 &inputs[c],
1210 |x, y, z| O::write(x.fused_clamp(y, z)),
1211 validated,
1212 exec,
1213 )
1214 }?
1215 }
1216 _ => unreachable!("not a ternary fused op: {op:?}"),
1217 },
1218 StaticFusedKind::AddMulLeft => unsafe {
1221 zip_map2_into_validated(
1222 dest,
1223 &inputs[0],
1224 &inputs[1],
1225 |a, b| O::write(a.fused_add(b).fused_multiply(a)),
1226 validated,
1227 exec,
1228 )
1229 }?,
1230 StaticFusedKind::AddMulRight => unsafe {
1233 zip_map2_into_validated(
1234 dest,
1235 &inputs[0],
1236 &inputs[1],
1237 |a, b| O::write(a.fused_multiply(a.fused_add(b))),
1238 validated,
1239 exec,
1240 )
1241 }?,
1242 StaticFusedKind::MulAddExp => unsafe {
1245 zip_map3_into_validated(
1246 dest,
1247 &inputs[0],
1248 &inputs[1],
1249 &inputs[2],
1250 |a, b, c| O::write(a.fused_multiply(b).fused_add(c).fused_exp()),
1251 validated,
1252 exec,
1253 )
1254 }?,
1255 StaticFusedKind::DivClampSqrtRsqrt => unsafe {
1258 zip_map4_into_validated(
1259 dest,
1260 &inputs[0],
1261 &inputs[1],
1262 &inputs[2],
1263 &inputs[3],
1264 |a, b, lo, hi| {
1265 O::write(
1266 a.fused_divide(b)
1267 .fused_maximum(lo)
1268 .fused_minimum(hi)
1269 .fused_sqrt()
1270 .fused_rsqrt(),
1271 )
1272 },
1273 validated,
1274 exec,
1275 )
1276 }?,
1277 }
1278 Ok(true)
1279}
1280
1281fn try_static_specialization_initialized<T: FusedScalar>(
1284 dests: &mut [StridedViewMut<'_, T>],
1285 inputs: &[StridedView<'_, T>],
1286 plan: &FusedPlan,
1287 validated: ValidatedDestinationLayout,
1288 exec: Exec<'_>,
1289) -> Result<bool> {
1290 if dests.len() != 1 {
1291 return Ok(false);
1292 }
1293 try_static_specialization_validated::<T, InitializedStaticOutput>(
1294 &mut dests[0],
1295 inputs,
1296 plan,
1297 validated,
1298 exec,
1299 )
1300}
1301
1302#[cfg(test)]
1306fn try_static_specialization<T: FusedScalar>(
1307 dests: &mut [StridedViewMut<'_, T>],
1308 inputs: &[StridedView<'_, T>],
1309 plan: &FusedPlan,
1310) -> Result<bool> {
1311 if dests.len() != 1 {
1312 return Ok(false);
1313 }
1314 let validated = strided_basic::execution::validate_destination_layout_without_alloc(
1315 dests[0].dims(),
1316 dests[0].strides(),
1317 )?;
1318 try_static_specialization_initialized(dests, inputs, plan, validated, Exec::serial())
1319}
1320
1321const INLINE_REGS: usize = 12;
1324
1325unsafe fn interpret_inner_loop<T: FusedScalar>(
1336 dst_ptrs: &[*mut T],
1337 input_ptrs: &[*const T],
1338 plan: &FusedPlan,
1339 offsets: &[isize],
1340 len: usize,
1341 strides: &[isize],
1342) {
1343 let register_count = plan.input_count + plan.ops.len();
1344 if len == 0 || register_count == 0 {
1345 return;
1346 }
1347 let init = unsafe { *input_ptrs[0].offset(offsets[dst_ptrs.len()]) };
1353 if register_count <= INLINE_REGS {
1354 let mut inline = [init; INLINE_REGS];
1355 unsafe {
1361 interpret_loop_body(
1362 dst_ptrs,
1363 input_ptrs,
1364 plan,
1365 offsets,
1366 len,
1367 strides,
1368 &mut inline[..register_count],
1369 )
1370 };
1371 } else {
1372 let mut heap = vec![init; register_count];
1373 unsafe {
1376 interpret_loop_body(dst_ptrs, input_ptrs, plan, offsets, len, strides, &mut heap)
1377 };
1378 }
1379}
1380
1381#[allow(clippy::too_many_arguments)]
1391unsafe fn interpret_loop_body<T: FusedScalar>(
1392 dst_ptrs: &[*mut T],
1393 input_ptrs: &[*const T],
1394 plan: &FusedPlan,
1395 offsets: &[isize],
1396 len: usize,
1397 strides: &[isize],
1398 regs: &mut [T],
1399) {
1400 let output_count = dst_ptrs.len();
1401 for i in 0..len {
1402 let i = i as isize;
1403 for (input_index, &input_ptr) in input_ptrs.iter().enumerate() {
1404 let stride_index = output_count + input_index;
1405 let stride = inner_stride(strides, stride_index);
1406 regs[input_index] = unsafe { *input_ptr.offset(offsets[stride_index] + i * stride) };
1410 }
1411 for (instruction, inst) in plan.ops.iter().enumerate() {
1412 let output = plan.input_count + instruction;
1413 regs[output] = eval_op(inst.op, ®s[..output], &inst.inputs);
1414 }
1415 for (output_index, &dst_ptr) in dst_ptrs.iter().enumerate() {
1416 let stride = inner_stride(strides, output_index);
1417 unsafe {
1420 *dst_ptr.offset(offsets[output_index] + i * stride) =
1421 regs[plan.outputs[output_index]];
1422 }
1423 }
1424 }
1425}
1426
1427#[inline]
1430fn chunk_seed<T: FusedScalar>(inputs: &[StridedView<'_, T>]) -> Option<T> {
1431 if inputs.is_empty() || !chunk::is_real_chunk_scalar::<T>() {
1432 return None;
1433 }
1434 Some(unsafe { *inputs[0].ptr() })
1440}
1441
1442#[inline]
1444fn register_file<T: FusedScalar, R>(
1445 plan: &FusedPlan,
1446 seed: Option<T>,
1447 f: impl FnOnce(&mut [T]) -> R,
1448) -> R {
1449 chunk::with_register_file(plan, seed, f)
1450}
1451
1452#[inline]
1460fn direct_inputs<T: FusedScalar, S: AsRef<[isize]>>(
1461 plan: &FusedPlan,
1462 seed: Option<T>,
1463 ordered_strides: &[S],
1464 output_count: usize,
1465) -> strided_basic::OperandVec<bool> {
1466 match seed {
1467 Some(_) => {
1468 let mut direct = chunk::single_use_inputs(plan);
1469 for (index, flag) in direct.iter_mut().enumerate() {
1470 let stride = ordered_strides
1471 .get(output_count + index)
1472 .and_then(|strides| strides.as_ref().first())
1473 .copied()
1474 .unwrap_or(0);
1475 if stride != 1 {
1476 *flag = false;
1477 }
1478 }
1479 direct
1480 }
1481 None => strided_basic::OperandVec::new(),
1482 }
1483}
1484
1485#[inline]
1490fn inner_stride(strides: &[isize], index: usize) -> isize {
1491 strides.get(index).copied().unwrap_or(0)
1492}
1493
1494fn interpret_fused_elementwise_into<T: FusedScalar>(
1495 dests: &mut [StridedViewMut<'_, T>],
1496 inputs: &[StridedView<'_, T>],
1497 plan: &FusedPlan,
1498 exec: Exec<'_>,
1499) -> Result<()> {
1500 if dests[0].is_empty() {
1501 return Ok(());
1502 }
1503 let dims: strided_basic::InlineVec<usize> = dests[0].dims().iter().copied().collect();
1504
1505 let dst_ptrs: strided_basic::OperandVec<OperandPtr<T>> = dests
1506 .iter_mut()
1507 .map(|dest| OperandPtr::new(dest.as_mut_ptr()))
1508 .collect();
1509 let input_ptrs: strided_basic::OperandVec<OperandPtr<T>> = inputs
1510 .iter()
1511 .map(|input| OperandPtr::new(input.ptr() as *mut T))
1512 .collect();
1513
1514 let mut strides_list: strided_basic::OperandVec<&[isize]> =
1515 strided_basic::OperandVec::with_capacity(dests.len() + inputs.len());
1516 for dest in dests.iter() {
1517 strides_list.push(dest.strides());
1518 }
1519 for input in inputs {
1520 strides_list.push(input.strides());
1521 }
1522
1523 let elem_size = std::mem::size_of::<T>();
1524 let total = dests[0].len();
1525 let (fused_dims, ordered_strides, kernel_plan) = if total <= SMALL_TENSOR_THRESHOLD {
1526 unsafe { build_plan_fused_small(&dims, &strides_list) }
1536 } else {
1537 unsafe { build_plan_fused(&dims, &strides_list, Some(0), elem_size) }
1548 };
1549
1550 let initial_offsets: strided_basic::OperandVec<isize> =
1551 ordered_strides.iter().map(|_| 0isize).collect();
1552 let seed = chunk_seed(inputs);
1553 let operands = dst_ptrs.len() + input_ptrs.len();
1554 let run_partition = |dims: &[usize],
1555 blocks: &[usize],
1556 strides_list: &[&[isize]],
1557 offsets: &[isize]|
1558 -> Result<()> {
1559 let direct = direct_inputs(plan, seed, strides_list, dst_ptrs.len());
1560 register_file(plan, seed, |regs| {
1561 let run_block = |offsets: &[isize], len: usize, strides: &[isize]| -> Result<()> {
1562 if seed.is_some() && chunk::block_replay_eligible(strides, dst_ptrs.len(), operands)
1563 {
1564 unsafe {
1579 chunk::replay_chunked(
1580 operand_ptrs(&dst_ptrs),
1581 operand_const_ptrs(&input_ptrs),
1582 plan,
1583 offsets,
1584 len,
1585 strides,
1586 &direct,
1587 regs,
1588 );
1589 }
1590 return Ok(());
1591 }
1592 unsafe {
1598 interpret_inner_loop(
1599 operand_ptrs(&dst_ptrs),
1600 operand_const_ptrs(&input_ptrs),
1601 plan,
1602 offsets,
1603 len,
1604 strides,
1605 );
1606 }
1607 Ok(())
1608 };
1609 unsafe {
1616 for_each_inner_block_preordered(dims, blocks, strides_list, offsets, run_block)
1617 }
1618 })
1619 };
1620 replay_partitions(
1621 &fused_dims,
1622 &kernel_plan.block,
1623 &ordered_strides,
1624 &initial_offsets,
1625 plan_class(plan),
1626 exec,
1627 &run_partition,
1628 )
1629}
1630
1631fn plan_class(plan: &FusedPlan) -> KernelClass {
1635 if plan
1636 .ops
1637 .iter()
1638 .any(|inst| op_class(inst.op) == KernelClass::Transcendental)
1639 {
1640 KernelClass::Transcendental
1641 } else {
1642 KernelClass::Map
1643 }
1644}
1645
1646fn op_class(op: FusedOp) -> KernelClass {
1649 if matches!(
1650 op,
1651 FusedOp::Exp
1652 | FusedOp::Log
1653 | FusedOp::Sin
1654 | FusedOp::Cos
1655 | FusedOp::Tanh
1656 | FusedOp::Pow
1657 | FusedOp::Expm1
1658 | FusedOp::Log1p
1659 ) {
1660 KernelClass::Transcendental
1661 } else {
1662 KernelClass::Map
1663 }
1664}
1665
1666fn replay_partitions<S: AsRef<[isize]>, F>(
1669 dims: &[usize],
1670 blocks: &[usize],
1671 ordered_strides: &[S],
1672 initial_offsets: &[isize],
1673 class: KernelClass,
1674 exec: Exec<'_>,
1675 run_partition: &F,
1676) -> Result<()>
1677where
1678 F: Fn(&[usize], &[usize], &[&[isize]], &[isize]) -> Result<()> + Sync,
1679{
1680 let total: usize = dims.iter().product();
1681 if parallel_width(&exec, class, total).get() > 1 {
1682 let costs = unsafe { compute_costs(ordered_strides) };
1687 return unsafe {
1696 mapreduce_threaded(
1697 dims,
1698 blocks,
1699 ordered_strides,
1700 initial_offsets,
1701 &costs,
1702 class,
1703 exec,
1704 run_partition,
1705 )
1706 };
1707 }
1708 let strides_refs: strided_basic::OperandVec<&[isize]> =
1709 ordered_strides.iter().map(|s| s.as_ref()).collect();
1710 run_partition(dims, blocks, &strides_refs, initial_offsets)
1711}
1712
1713unsafe fn interpret_inner_loop_uninit<T: FusedScalar>(
1719 dst_ptrs: &[*mut MaybeUninit<T>],
1720 input_ptrs: &[*const T],
1721 plan: &FusedPlan,
1722 offsets: &[isize],
1723 len: usize,
1724 strides: &[isize],
1725) {
1726 let register_count = plan.input_count + plan.ops.len();
1727 if len == 0 || register_count == 0 {
1728 return;
1729 }
1730 let init = unsafe { *input_ptrs[0].offset(offsets[dst_ptrs.len()]) };
1736 if register_count <= INLINE_REGS {
1737 let mut inline = [init; INLINE_REGS];
1738 unsafe {
1743 interpret_loop_body_uninit(
1744 dst_ptrs,
1745 input_ptrs,
1746 plan,
1747 offsets,
1748 len,
1749 strides,
1750 &mut inline[..register_count],
1751 )
1752 };
1753 } else {
1754 let mut heap = vec![init; register_count];
1755 unsafe {
1758 interpret_loop_body_uninit(dst_ptrs, input_ptrs, plan, offsets, len, strides, &mut heap)
1759 };
1760 }
1761}
1762
1763#[allow(clippy::too_many_arguments)]
1772unsafe fn interpret_loop_body_uninit<T: FusedScalar>(
1773 dst_ptrs: &[*mut MaybeUninit<T>],
1774 input_ptrs: &[*const T],
1775 plan: &FusedPlan,
1776 offsets: &[isize],
1777 len: usize,
1778 strides: &[isize],
1779 regs: &mut [T],
1780) {
1781 let output_count = dst_ptrs.len();
1782 for i in 0..len {
1783 let i = i as isize;
1784 for (input_index, &input_ptr) in input_ptrs.iter().enumerate() {
1785 let stride_index = output_count + input_index;
1786 let stride = inner_stride(strides, stride_index);
1787 regs[input_index] = unsafe { *input_ptr.offset(offsets[stride_index] + i * stride) };
1791 }
1792 for (instruction, inst) in plan.ops.iter().enumerate() {
1793 let output = plan.input_count + instruction;
1794 regs[output] = eval_op(inst.op, ®s[..output], &inst.inputs);
1795 }
1796 for (output_index, &dst_ptr) in dst_ptrs.iter().enumerate() {
1797 let stride = inner_stride(strides, output_index);
1798 unsafe {
1801 *dst_ptr.offset(offsets[output_index] + i * stride) =
1802 MaybeUninit::new(regs[plan.outputs[output_index]]);
1803 }
1804 }
1805 }
1806}
1807
1808#[cfg(test)]
1810pub(crate) fn fused_elementwise_into_uninit<T: FusedScalar>(
1811 dest: &mut StridedViewMut<'_, MaybeUninit<T>>,
1812 inputs: &[StridedView<'_, T>],
1813 plan: &FusedPlan,
1814 validated: ValidatedDestinationLayout,
1815 exec: Exec<'_>,
1816) -> Result<()> {
1817 fused_elementwise_into_uninit_multi(
1818 std::slice::from_mut(dest),
1819 inputs,
1820 plan,
1821 std::slice::from_ref(&validated),
1822 exec,
1823 )
1824}
1825
1826pub(crate) fn fused_elementwise_into_uninit_multi<T: FusedScalar>(
1833 dests: &mut [StridedViewMut<'_, MaybeUninit<T>>],
1834 inputs: &[StridedView<'_, T>],
1835 plan: &FusedPlan,
1836 validated: &[ValidatedDestinationLayout],
1837 mut exec: Exec<'_>,
1838) -> Result<()> {
1839 validate_plan_for_scalar::<T>(plan, inputs.len(), dests.len())?;
1840 let dims = dests[0].dims();
1841 for dest in dests.iter() {
1842 ensure_same_shape(dims, dest.dims())?;
1843 }
1844 for input in inputs {
1845 ensure_same_shape(dims, input.dims())?;
1846 }
1847
1848 if dests.len() == 1
1849 && try_static_specialization_validated::<T, UninitializedStaticOutput>(
1850 &mut dests[0],
1851 inputs,
1852 plan,
1853 validated[0],
1854 exec.reborrow(),
1855 )?
1856 {
1857 return Ok(());
1858 }
1859
1860 if dests[0].is_empty() {
1861 return Ok(());
1862 }
1863 interpret_fused_elementwise_into_uninit(dests, inputs, plan, exec)
1864}
1865
1866fn interpret_fused_elementwise_into_uninit<T: FusedScalar>(
1867 dests: &mut [StridedViewMut<'_, MaybeUninit<T>>],
1868 inputs: &[StridedView<'_, T>],
1869 plan: &FusedPlan,
1870 exec: Exec<'_>,
1871) -> Result<()> {
1872 let dims: strided_basic::InlineVec<usize> = dests[0].dims().iter().copied().collect();
1873 let dst_ptrs: strided_basic::OperandVec<OperandPtr<MaybeUninit<T>>> = dests
1874 .iter_mut()
1875 .map(|dest| OperandPtr::new(dest.as_mut_ptr()))
1876 .collect();
1877 let input_ptrs: strided_basic::OperandVec<OperandPtr<T>> = inputs
1878 .iter()
1879 .map(|input| OperandPtr::new(input.ptr() as *mut T))
1880 .collect();
1881 let mut strides_list: strided_basic::OperandVec<&[isize]> =
1882 strided_basic::OperandVec::with_capacity(dests.len() + inputs.len());
1883 for dest in dests.iter() {
1884 strides_list.push(dest.strides());
1885 }
1886 for input in inputs {
1887 strides_list.push(input.strides());
1888 }
1889 let total = dests[0].len();
1890 let (fused_dims, ordered_strides, kernel_plan) = if total <= SMALL_TENSOR_THRESHOLD {
1891 unsafe { build_plan_fused_small(&dims, &strides_list) }
1901 } else {
1902 unsafe { build_plan_fused(&dims, &strides_list, Some(0), core::mem::size_of::<T>()) }
1913 };
1914
1915 let initial_offsets: strided_basic::OperandVec<isize> =
1916 ordered_strides.iter().map(|_| 0isize).collect();
1917 let seed = chunk_seed(inputs);
1918 let operands = dst_ptrs.len() + input_ptrs.len();
1919 let run_partition = |dims: &[usize],
1920 blocks: &[usize],
1921 strides_list: &[&[isize]],
1922 offsets: &[isize]|
1923 -> Result<()> {
1924 let direct = direct_inputs(plan, seed, strides_list, dst_ptrs.len());
1925 register_file(plan, seed, |regs| {
1926 let run_block = |offsets: &[isize], len: usize, strides: &[isize]| -> Result<()> {
1927 if seed.is_some() && chunk::block_replay_eligible(strides, dst_ptrs.len(), operands)
1928 {
1929 unsafe {
1944 chunk::replay_chunked_uninit(
1945 operand_ptrs(&dst_ptrs),
1946 operand_const_ptrs(&input_ptrs),
1947 plan,
1948 offsets,
1949 len,
1950 strides,
1951 &direct,
1952 regs,
1953 );
1954 }
1955 return Ok(());
1956 }
1957 unsafe {
1963 interpret_inner_loop_uninit(
1964 operand_ptrs(&dst_ptrs),
1965 operand_const_ptrs(&input_ptrs),
1966 plan,
1967 offsets,
1968 len,
1969 strides,
1970 );
1971 }
1972 Ok(())
1973 };
1974 unsafe {
1981 for_each_inner_block_preordered(dims, blocks, strides_list, offsets, run_block)
1982 }
1983 })
1984 };
1985 replay_partitions(
1986 &fused_dims,
1987 &kernel_plan.block,
1988 &ordered_strides,
1989 &initial_offsets,
1990 plan_class(plan),
1991 exec,
1992 &run_partition,
1993 )
1994}
1995
1996#[inline]
2016pub fn has_vectorized_replay<T: FusedScalar>() -> bool {
2017 chunk::is_real_chunk_scalar::<T>()
2018}
2019
2020pub fn fused_elementwise_into<T: FusedScalar>(
2087 dests: &mut [StridedViewMut<'_, T>],
2088 inputs: &[StridedView<'_, T>],
2089 plan: &FusedPlan,
2090 mut exec: Exec<'_>,
2091) -> Result<()> {
2092 validate_plan_for_scalar::<T>(plan, inputs.len(), dests.len())?;
2093 let validated = validate_shapes(dests, inputs)?;
2094 if try_static_specialization_initialized(dests, inputs, plan, validated, exec.reborrow())? {
2095 return Ok(());
2096 }
2097 interpret_fused_elementwise_into(dests, inputs, plan, exec)
2098}
2099
2100#[cfg(test)]
2101#[path = "fused/tests/tests.rs"]
2102mod tests;