Skip to main content

strided_fused/
fused.rs

1//! Runtime-DAG fused elementwise kernels.
2
3use 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
22/// RAII owner of the initialized prefix of a stack buffer of destination
23/// views.
24///
25/// Used by the erased multi-output entry points so their stack-buffer cast stays
26/// out of the erased raw-boundary modules. Dropping the guard drops exactly the
27/// initialized prefix, so a rank above `INLINE_RANK` does not leak every
28/// destination's boxed metadata on success, error, or unwind.
29pub(crate) struct InitializedViewsMut<'a, T> {
30    storage: *mut MaybeUninit<StridedViewMut<'a, T>>,
31    len: usize,
32}
33
34impl<'a, T> InitializedViewsMut<'a, T> {
35    /// # Safety
36    /// `storage` must point to at least `OPERAND_CAP` writable slots that stay
37    /// valid until the guard is dropped.
38    pub(crate) unsafe fn new(storage: *mut MaybeUninit<StridedViewMut<'a, T>>) -> Self {
39        Self { storage, len: 0 }
40    }
41
42    /// Write the next initialized view into the prefix.
43    pub(crate) fn push(&mut self, view: StridedViewMut<'a, T>) {
44        debug_assert!(self.len < strided_basic::OPERAND_CAP);
45        // SAFETY: `storage` holds `OPERAND_CAP` writable slots by `new`'s contract
46        // (fused.rs:36), and `len < OPERAND_CAP`: both callers push at most `dests.len() <=
47        // OPERAND_CAP` views (erased.rs:448, erased.rs:551). The `debug_assert!` above checks
48        // that only in debug builds; this safe method relies on its two callers.
49        unsafe { self.storage.add(self.len).write(MaybeUninit::new(view)) };
50        self.len += 1;
51    }
52
53    /// Borrow the initialized prefix.
54    pub(crate) fn as_mut_slice(&mut self) -> &mut [StridedViewMut<'a, T>] {
55        // SAFETY: `push` (fused.rs:43) initialized every slot below `len`,
56        // `MaybeUninit<StridedViewMut>` has the layout of `StridedViewMut`, and `&mut self` makes
57        // the slice the only access while it lives.
58        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            // SAFETY: `push` (fused.rs:43) initialized every slot below `len`; `MaybeUninit` has
68            // the view's layout, and `&mut self` in `drop` drops each slot exactly once.
69            unsafe { (*self.storage.add(index)).assume_init_drop() };
70        }
71    }
72}
73
74/// A raw operand pointer that is `Default` and `Send + Sync`, so pointer lists
75/// can live in an inline operand vector and be captured by worker closures.
76///
77/// `repr(transparent)` over `*mut T`, so a slice of them can be viewed as a
78/// slice of raw pointers without copying.
79#[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
89// SAFETY: an `OperandPtr` only carries an address. Every dereference sits in an `unsafe` block
90// whose contract proves liveness and exclusivity (`interpret_inner_loop`, fused.rs:1335;
91// `replay_chunked`, chunk.rs:152), so sending or sharing the address is sound.
92unsafe impl<T> Send for OperandPtr<T> {}
93// SAFETY: as for `Send` above: sharing a reference only shares the address.
94unsafe 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/// View an inline operand vector as a `&[*mut T]` slice.
104#[inline]
105fn operand_ptrs<T>(ptrs: &[OperandPtr<T>]) -> &[*mut T] {
106    // SAFETY: `OperandPtr<T>` is `#[repr(transparent)]` over `*mut T` (fused.rs:79), so the
107    // slice reads as `ptrs.len()` raw pointers for the same borrow.
108    unsafe { core::slice::from_raw_parts(ptrs.as_ptr().cast::<*mut T>(), ptrs.len()) }
109}
110
111/// View an inline operand vector as a `&[*const T]` slice.
112#[inline]
113fn operand_const_ptrs<T>(ptrs: &[OperandPtr<T>]) -> &[*const T] {
114    // SAFETY: as in `operand_ptrs`: `OperandPtr<T>` is `#[repr(transparent)]` over `*mut T`
115    // (fused.rs:79), and `*mut T` and `*const T` have the same layout.
116    unsafe { core::slice::from_raw_parts(ptrs.as_ptr().cast::<*const T>(), ptrs.len()) }
117}
118
119/// Runtime scalar operation for a fused elementwise plan.
120#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
121pub enum FusedOp {
122    #[default]
123    Add,
124    /// `a - b` with the scalar type's own subtraction: IEEE for `f32`/`f64`,
125    /// componentwise for complex, wrapping for signed integers. It is
126    /// bit-identical to the per-element interpreter and to the unfused binary
127    /// kernel. It is not `Negate` + `Add`: a NaN operand's sign bit is not
128    /// flipped (with a NaN in both operands, which payload propagates is the
129    /// hardware's choice, as for scalar `-`). `bool` rejects it.
130    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/// One SSA instruction in a [`FusedPlan`].
180///
181/// `inputs` holds at most [`OPERAND_CAP`](strided_basic::OPERAND_CAP) value ids
182/// inline and spills above that, so a bounded program builds without touching
183/// the heap.
184#[derive(Clone, Debug, Eq, PartialEq)]
185pub struct FusedInst {
186    pub op: FusedOp,
187    pub inputs: strided_basic::OperandVec<usize>,
188}
189
190impl FusedInst {
191    /// Build an instruction from an operation and its input value ids.
192    ///
193    /// ```
194    /// use strided_fused::{FusedInst, FusedOp};
195    /// let inst = FusedInst::new(FusedOp::Add, [0, 1]);
196    /// assert_eq!(inst.inputs.as_slice(), &[0, 1]);
197    /// ```
198    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/// Topologically ordered fused elementwise SSA DAG.
216///
217/// Values are numbered in evaluation order. Input values occupy
218/// `0..input_count`; each instruction appends one value after the previous
219/// inputs/instructions. For example, with `input_count == 2`, the first
220/// instruction writes value `2`, the second writes value `3`, and so on.
221/// `outputs` contains the value ids to write to `dests` in order.
222///
223/// The program is stored inline: at most eight instructions, five outputs and
224/// [`OPERAND_CAP`](strided_basic::OPERAND_CAP) inputs per instruction, spilling
225/// to the heap only above those bounds. Build one with [`FusedPlan::new`] to
226/// keep `vec!`-based construction ergonomic; the `pub` fields accept the inline
227/// collection directly. (Changing the field type from `Vec` is a 0.6.0 breaking
228/// change.)
229///
230/// All inputs and destinations passed to [`fused_elementwise_into`] must have
231/// the same shape and scalar type. Broadcast inputs should be represented with
232/// `StridedView::broadcast` before building the plan; the fused API does not
233/// perform implicit broadcasting.
234#[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    /// Build a plan from an input count, output value ids, and instructions.
243    ///
244    /// ```
245    /// use strided_fused::{FusedInst, FusedOp, FusedPlan};
246    /// let plan = FusedPlan::new(
247    ///     2,
248    ///     vec![3],
249    ///     vec![
250    ///         FusedInst::new(FusedOp::Add, vec![0, 1]),
251    ///         FusedInst::new(FusedOp::Negate, vec![2]),
252    ///     ],
253    /// );
254    /// assert_eq!(plan.ops.len(), 2);
255    /// ```
256    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
269/// Scalar types supported by [`fused_elementwise_into`].
270pub 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                // Same select as the ordinary binary kernel; see
348                // `strided_basic::nan_propagating_maximum`.
349                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                // `minimum(hi, maximum(lo, x))`, the ordinary clamp
360                // composition; the argument order keeps signed-zero ties on
361                // the bounds and propagates NaN from any operand.
362                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    // Validate the layout once and hand the marker to the specialization, so
881    // the injectivity check does not run twice on the hot single-output path.
882    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            // Dispatch on the op once, outside the element loop, so the
1129            // specialization is monomorphized per `FusedOp` and vectorizes
1130            // (tensor4all/strided-rs#305 item 2).
1131            macro_rules! unary {
1132                ($apply:expr) => {{
1133                    // SAFETY: `map_into_validated` (strided-basic/src/execution.rs:161) needs
1134                    // three things. Every input shape equals `dest`'s: `validate_shapes` checked
1135                    // it (fused.rs:888) on the initialized path, and
1136                    // `fused_elementwise_into_uninit_multi` did (fused.rs:1845) on the
1137                    // uninitialized one. `validated` belongs to this `dest`'s geometry: here
1138                    // `dest` is `dests[0]` of a single-destination call (fused.rs:1290,
1139                    // fused.rs:1848), and the marker was made for `dests[0]` (fused.rs:882;
1140                    // uninitialized entry: erased.rs:328). Bounds and aliasing hold for the
1141                    // replay: every view keeps its construction-time bounds, `dest` is borrowed
1142                    // `&mut`, and the inputs are shared views.
1143                    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            // As above: one monomorphized kernel per `FusedOp`.
1172            macro_rules! binary {
1173                ($apply:expr) => {{
1174                    // SAFETY: as for the unary arm (fused.rs:1144): `zip_map2_into_validated`
1175                    // (strided-basic/src/execution.rs:203) has the same contract, met the same
1176                    // way.
1177                    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                // SAFETY: as for the unary arm (fused.rs:1144): `zip_map3_into_validated`
1203                // (strided-basic/src/execution.rs:251) has the same contract, met the same way.
1204                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        // SAFETY: as for the unary arm (fused.rs:1144): `zip_map2_into_validated`
1219        // (strided-basic/src/execution.rs:203) has the same contract, met the same way.
1220        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        // SAFETY: as for the unary arm (fused.rs:1144): `zip_map2_into_validated`
1231        // (strided-basic/src/execution.rs:203) has the same contract, met the same way.
1232        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        // SAFETY: as for the unary arm (fused.rs:1144): `zip_map3_into_validated`
1243        // (strided-basic/src/execution.rs:251) has the same contract, met the same way.
1244        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        // SAFETY: as for the unary arm (fused.rs:1144): `zip_map4_into_validated`
1256        // (strided-basic/src/execution.rs:305) has the same contract, met the same way.
1257        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
1281/// Take the initialized specialization with an already validated destination
1282/// layout, so the caller does not run the injectivity check twice.
1283fn 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/// Test-only thin wrapper over `validate_destination_layout_without_alloc` plus
1303/// [`try_static_specialization_initialized`], matching the helper the
1304/// specialization tests used before the layout marker was threaded through.
1305#[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
1321/// Registers the scalar interpreter keeps inline; a larger program spills to
1322/// the heap (#306 item 6).
1323const INLINE_REGS: usize = 12;
1324
1325/// Run the per-element interpreter over one generated block.
1326///
1327/// # Safety
1328/// `offsets` and `strides` hold one entry per operand, outputs first and then
1329/// inputs, as `for_each_inner_block_preordered` hands them to its callback. With
1330/// `n = dst_ptrs.len()`, for every `k < len` the element
1331/// `dst_ptrs[i] + offsets[i] + k * strides[i]` must be writable and
1332/// `input_ptrs[j] + offsets[n + j] + k * strides[n + j]` readable; no other
1333/// thread may access those destination elements during the call; and `plan`
1334/// must have passed `validate_plan` for these operand counts.
1335unsafe 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    // SAFETY: `len > 0` (checked above), and `validate_plan` admits no plan without inputs: every
1348    // output names a defined value (fused.rs:847) and instructions read only earlier values
1349    // (fused.rs:836), so with `input_count == 0` there is no value to name and the plan is
1350    // rejected. So `input_ptrs[0]` exists, and its element at `offsets[n]` (`k = 0`) is readable
1351    // under this function's contract (fused.rs:1325).
1352    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        // SAFETY: `interpret_loop_body` has this function's contract (fused.rs:1325), passed on
1356        // unchanged, plus one clause: no operand element may lie inside `regs`. That holds
1357        // because `regs` is `inline`, a local array created just above, so no operand pointer
1358        // can point into it. `regs` holds `register_count` values, one per register
1359        // `validate_plan` admits.
1360        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        // SAFETY: as for the inline register file above (fused.rs:1355): `heap` is a fresh `Vec`,
1374        // so no operand element lies inside it either.
1375        unsafe {
1376            interpret_loop_body(dst_ptrs, input_ptrs, plan, offsets, len, strides, &mut heap)
1377        };
1378    }
1379}
1380
1381/// One interpreter pass over a block, writing the register file by index so a
1382/// stack or heap file is used identically.
1383///
1384/// # Safety
1385/// As [`interpret_inner_loop`], and no input or destination element may lie
1386/// inside `regs`: the body holds `regs` as `&mut [T]` while it reads the
1387/// inputs and writes the destinations through raw pointers.
1388// Inert: `interpret_loop_body` takes 7 arguments and clippy's `too_many_arguments`
1389// fires only above 7, so this allow suppresses nothing; it is left in place.
1390#[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            // SAFETY: element `i < len` of input `input_index`, at its block offset and inner
1407            // stride, readable under the contract this body shares with `interpret_inner_loop`
1408            // (fused.rs:1325).
1409            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, &regs[..output], &inst.inputs);
1414        }
1415        for (output_index, &dst_ptr) in dst_ptrs.iter().enumerate() {
1416            let stride = inner_stride(strides, output_index);
1417            // SAFETY: element `i < len` of output `output_index`, writable under this body's
1418            // contract with `interpret_inner_loop` (fused.rs:1325); no other thread touches it.
1419            unsafe {
1420                *dst_ptr.offset(offsets[output_index] + i * stride) =
1421                    regs[plan.outputs[output_index]];
1422            }
1423        }
1424    }
1425}
1426
1427/// Seed for the chunk register file, or `None` when this scalar has no vector
1428/// kernels (or there is no input to seed from).
1429#[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    // SAFETY: both interpreters call this only after returning early for an empty `dests[0]`
1435    // (fused.rs:1500, fused.rs:1860) and after checking every input against its shape
1436    // (fused.rs:888, fused.rs:1845), so `inputs[0]` is non-empty and `ptr()` is its element at
1437    // the view offset (`base_ptr`, strided-view/src/view.rs:446). This safe helper relies on
1438    // those two callers.
1439    Some(unsafe { *inputs[0].ptr() })
1440}
1441
1442/// Register file for `seed`, or an empty one when the chunked path is declined.
1443#[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/// Inputs the chunked path reads straight from the operand, empty when it is
1453/// declined.
1454///
1455/// A stride-0 input is never direct: the register machine reads the broadcast
1456/// value from its pre-filled register chunk, not from `offset + done`. The
1457/// innermost stride of each operand (outputs first, then inputs) is read from
1458/// `ordered_strides[i].first()`.
1459#[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/// Stride of `index` along the block's innermost axis.
1486///
1487/// A rank-zero block carries no strides: its single element sits at the block
1488/// offset, which is what a stride of 0 yields.
1489#[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        // SAFETY: `build_plan_fused_small` (strided-basic/src/execution.rs:87) needs matching
1527        // rank-indexed lengths and representable shape, stride and offset arithmetic. The lengths
1528        // match: `dims` is `dests[0]`'s, and every entry of `strides_list` has that rank, because
1529        // each operand's shape was checked equal to it before this call. Construction-time
1530        // `validate_bounds` (strided-view/src/view.rs:187) establishes only that each operand's
1531        // reachable offsets lie inside its slice; it does not establish the planner's arithmetic.
1532        // This path skips the dimension ordering (strided-basic/src/kernel.rs:134), so the
1533        // importance weight never forms; the arithmetic left is `fuse_dims`'s, and it is checked
1534        // (strided-basic/src/fuse.rs:63-65, :76-79).
1535        unsafe { build_plan_fused_small(&dims, &strides_list) }
1536    } else {
1537        // SAFETY: `build_plan_fused` (strided-basic/src/execution.rs:53) needs matching
1538        // rank-indexed lengths, a valid destination index and representable shape, stride and
1539        // offset arithmetic. The lengths match: `dims` is `dests[0]`'s, and every entry of
1540        // `strides_list` has that rank, because each operand's shape was checked equal to it
1541        // before this call. Index `0` is `dests[0]`. Construction-time `validate_bounds`
1542        // (strided-view/src/view.rs:187) establishes only that each operand's reachable offsets
1543        // lie inside its slice; the planner's arithmetic is checked. The importance weight shifts
1544        // `1u64` by up to `g * rank` bits (#450), but `compute_importance` checks every shift
1545        // (strided-basic/src/fuse.rs:179-182), the weighted product (:196) and the sum (:200),
1546        // skips size-1 axes (:186-190) and narrows the width if the packing does not fit (:207-231).
1547        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                    // SAFETY: `replay_chunked` (chunk.rs:152): `block_replay_eligible` just
1565                    // checked the strides (outputs 1, inputs 0 or 1). `offsets`, `len` and
1566                    // `strides` describe one block that `for_each_inner_block_preordered`
1567                    // generated over shapes checked equal, so each stride-1 operand's `offsets[i]
1568                    // .. + len` and each stride-0 input's `offsets[i]` are elements of that
1569                    // operand, inside its bounds. `regs` is this thread's private `SCRATCH`
1570                    // buffer (chunk.rs:103), handed out only to this closure, so no operand
1571                    // overlaps it, and it holds `register_file_len(plan)` values because `seed`
1572                    // is `Some` (chunk.rs:108). `direct` came from `direct_inputs`, which starts
1573                    // from `single_use_inputs` (fused.rs:1468), which never marks an input that
1574                    // `plan.outputs` names (chunk.rs:76), and then keeps only stride-1 inputs
1575                    // (fused.rs:1475). The plan passed `validate_plan_for_scalar`, and only this
1576                    // partition writes these destination elements (see `replay_partitions`,
1577                    // fused.rs:1668).
1578                    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                // SAFETY: `interpret_inner_loop`'s contract (fused.rs:1325) holds: `offsets`,
1593                // `len` and `strides` describe one generated block over shapes checked equal, so
1594                // every element it reaches is inside each operand; only this partition writes
1595                // those destination elements (see `replay_partitions`); and the plan passed
1596                // `validate_plan_for_scalar`.
1597                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            // SAFETY: `for_each_inner_block_preordered` (strided-basic/src/execution.rs:115)
1610            // needs well-formed arrays, positive blocks, offsets that correspond to the layouts,
1611            // and valid callback accesses. `dims`, `blocks` and `strides_list` are one partition
1612            // of a `build_plan_fused*` result; `offsets` start at 0 relative to each operand's
1613            // base pointer (`initial_offsets`); and `run_block` only touches the elements of the
1614            // block it is handed (see the two calls inside it).
1615            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
1631/// Serial cost class of a fused program: `Transcendental` when any instruction is
1632/// a libm-like function, `Map` for arithmetic chains (see
1633/// `strided_basic::execution::KernelClass`).
1634fn 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
1646/// Serial cost class of one fused instruction: `Transcendental` for a libm-like
1647/// function, `Map` otherwise.
1648fn 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
1666/// Run `run_partition` over the whole region on the calling thread, or split
1667/// the region across the budget of `exec` once a fork pays for it.
1668fn 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        // SAFETY: `compute_costs` (strided-basic/src/execution.rs:467) needs well-formed
1683        // rank-indexed `ordered_strides`, here one `build_plan_fused*` result, and representable
1684        // cost arithmetic. The views' bounds checks establish only slice validity, so this proof
1685        // does not establish the cost arithmetic.
1686        let costs = unsafe { compute_costs(ordered_strides) };
1687        // SAFETY: `mapreduce_threaded` (strided-basic/src/execution.rs:496). `dims`, `blocks`,
1688        // `ordered_strides` and `initial_offsets` come from one `build_plan_fused*` result, and
1689        // `costs` from `compute_costs` over it. Partitions run concurrently, so their mutable
1690        // regions must be disjoint. Every destination layout is injective: the initialized path
1691        // checks it with `validate_destination_layout` (fused.rs:882, fused.rs:884), and the
1692        // uninitialized entry with its per-destination markers (erased.rs:328). The partitions
1693        // cover disjoint index sets, so no two of them write one destination element, and
1694        // distinct destinations are distinct exclusive borrows.
1695        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
1713/// Uninitialized-destination sibling of [`interpret_inner_loop`].
1714///
1715/// # Safety
1716/// As [`interpret_inner_loop`]; the destination elements may be uninitialized,
1717/// and each one is written, never read.
1718unsafe 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    // SAFETY: `len > 0` (checked above), and `validate_plan` admits no plan without inputs: every
1731    // output names a defined value (fused.rs:847) and instructions read only earlier values
1732    // (fused.rs:836), so with `input_count == 0` there is no value to name and the plan is
1733    // rejected. So `input_ptrs[0]` exists, and its element at `offsets[n]` (`k = 0`) is readable
1734    // under this function's contract (fused.rs:1713).
1735    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        // SAFETY: `interpret_loop_body_uninit` has this function's contract (fused.rs:1713),
1739        // passed on unchanged, plus one clause: no operand element may lie inside `regs`. That
1740        // holds because `regs` is `inline`, a local array created just above. `regs` holds
1741        // `register_count` values.
1742        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        // SAFETY: as for the inline register file above (fused.rs:1738): `heap` is a fresh `Vec`,
1756        // so no operand element lies inside it either.
1757        unsafe {
1758            interpret_loop_body_uninit(dst_ptrs, input_ptrs, plan, offsets, len, strides, &mut heap)
1759        };
1760    }
1761}
1762
1763/// Uninitialized-destination sibling of [`interpret_loop_body`].
1764///
1765/// # Safety
1766/// As [`interpret_inner_loop_uninit`], and no input or destination element may
1767/// lie inside `regs`: the body holds `regs` as `&mut [T]` while it reads the
1768/// inputs and writes the destinations through raw pointers.
1769// Inert: `interpret_loop_body_uninit` takes 7 arguments and clippy's
1770// `too_many_arguments` fires only above 7, so this allow suppresses nothing.
1771#[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            // SAFETY: element `i < len` of input `input_index`, at its block offset and inner
1788            // stride, readable under the contract this body shares with
1789            // `interpret_inner_loop_uninit` (fused.rs:1713).
1790            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, &regs[..output], &inst.inputs);
1795        }
1796        for (output_index, &dst_ptr) in dst_ptrs.iter().enumerate() {
1797            let stride = inner_stride(strides, output_index);
1798            // SAFETY: element `i < len` of output `output_index`, writable under this body's
1799            // contract with `interpret_inner_loop_uninit` (fused.rs:1713); it is never read.
1800            unsafe {
1801                *dst_ptr.offset(offsets[output_index] + i * stride) =
1802                    MaybeUninit::new(regs[plan.outputs[output_index]]);
1803            }
1804        }
1805    }
1806}
1807
1808/// Single-destination front end for [`fused_elementwise_into_uninit_multi`].
1809#[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
1826/// Evaluate a plan into one or more fully-overwritten uninitialized destinations.
1827///
1828/// `validated[i]` must come from `validate_destination_layout_without_alloc`
1829/// for `dests[i]`'s layout. A single destination keeps the static kernel
1830/// specialization; several destinations always take the interpreter or the
1831/// chunked register machine.
1832pub(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        // SAFETY: `build_plan_fused_small` (strided-basic/src/execution.rs:87) needs matching
1892        // rank-indexed lengths and representable shape, stride and offset arithmetic. The lengths
1893        // match: `dims` is `dests[0]`'s, and every entry of `strides_list` has that rank, because
1894        // each operand's shape was checked equal to it before this call. Construction-time
1895        // `validate_bounds` (strided-view/src/view.rs:187) establishes only that each operand's
1896        // reachable offsets lie inside its slice; it does not establish the planner's arithmetic.
1897        // This path skips the dimension ordering (strided-basic/src/kernel.rs:134), so the
1898        // importance weight never forms; the arithmetic left is `fuse_dims`'s, and it is checked
1899        // (strided-basic/src/fuse.rs:63-65, :76-79).
1900        unsafe { build_plan_fused_small(&dims, &strides_list) }
1901    } else {
1902        // SAFETY: `build_plan_fused` (strided-basic/src/execution.rs:53) needs matching
1903        // rank-indexed lengths, a valid destination index and representable shape, stride and
1904        // offset arithmetic. The lengths match: `dims` is `dests[0]`'s, and every entry of
1905        // `strides_list` has that rank, because each operand's shape was checked equal to it
1906        // before this call. Index `0` is `dests[0]`. Construction-time `validate_bounds`
1907        // (strided-view/src/view.rs:187) establishes only that each operand's reachable offsets
1908        // lie inside its slice; the planner's arithmetic is checked. The importance weight shifts
1909        // `1u64` by up to `g * rank` bits (#450), but `compute_importance` checks every shift
1910        // (strided-basic/src/fuse.rs:179-182), the weighted product (:196) and the sum (:200),
1911        // skips size-1 axes (:186-190) and narrows the width if the packing does not fit (:207-231).
1912        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                    // SAFETY: `replay_chunked_uninit` (chunk.rs:339): `block_replay_eligible`
1930                    // just checked the strides (outputs 1, inputs 0 or 1). `offsets`, `len` and
1931                    // `strides` describe one block that `for_each_inner_block_preordered`
1932                    // generated over shapes checked equal, so each stride-1 operand's `offsets[i]
1933                    // .. + len` and each stride-0 input's `offsets[i]` are elements of that
1934                    // operand, inside its bounds. `regs` is this thread's private `SCRATCH`
1935                    // buffer (chunk.rs:103), handed out only to this closure, so no operand
1936                    // overlaps it, and it holds `register_file_len(plan)` values because `seed`
1937                    // is `Some` (chunk.rs:108). `direct` came from `direct_inputs`, which starts
1938                    // from `single_use_inputs` (fused.rs:1468), which never marks an input that
1939                    // `plan.outputs` names (chunk.rs:76), and then keeps only stride-1 inputs
1940                    // (fused.rs:1475). The plan passed `validate_plan_for_scalar`, and only this
1941                    // partition writes these destination elements (see `replay_partitions`,
1942                    // fused.rs:1668).
1943                    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                // SAFETY: `interpret_inner_loop_uninit`'s contract (fused.rs:1713) holds:
1958                // `offsets`, `len` and `strides` describe one generated block over shapes checked
1959                // equal, so every element it reaches is inside each operand; only this partition
1960                // writes those destination elements (see `replay_partitions`); and the plan
1961                // passed `validate_plan_for_scalar`.
1962                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            // SAFETY: `for_each_inner_block_preordered` (strided-basic/src/execution.rs:115)
1975            // needs well-formed arrays, positive blocks, offsets that correspond to the layouts,
1976            // and valid callback accesses. `dims`, `blocks` and `strides_list` are one partition
1977            // of a `build_plan_fused*` result; `offsets` start at 0 relative to each operand's
1978            // base pointer (`initial_offsets`); and `run_block` only touches the elements of the
1979            // block it is handed (see the two calls inside it).
1980            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/// Returns whether `T` has the chunked vectorized replay for plans that reach
1997/// the interpreter.
1998///
1999/// Those are plans with more than one instruction or output that match no
2000/// static specialization; single-instruction plans use the ordinary unfused
2001/// kernels for every `T`. When this is `false`, such plans run element by
2002/// element and are not expected to be faster than unfused passes. When it is
2003/// `true`, a block is replayed vectorized only if every output is unit-stride
2004/// and every input is unit-stride or broadcast along the innermost axis.
2005///
2006/// This is a property of the scalar type, not a promise about one call:
2007/// contiguity is decided per block at run time.
2008///
2009/// ```
2010/// use strided_fused::has_vectorized_replay;
2011///
2012/// assert!(has_vectorized_replay::<f64>());
2013/// assert!(!has_vectorized_replay::<num_complex::Complex64>());
2014/// ```
2015#[inline]
2016pub fn has_vectorized_replay<T: FusedScalar>() -> bool {
2017    chunk::is_real_chunk_scalar::<T>()
2018}
2019
2020/// Evaluate a runtime-DAG elementwise plan into one or more destinations.
2021///
2022/// The plan is validated before any destination is written:
2023///
2024/// - `inputs.len()` must equal `plan.input_count`;
2025/// - `dests.len()` must equal `plan.outputs.len()`;
2026/// - instruction operands must reference earlier SSA values with the right
2027///   arity for their [`FusedOp`];
2028/// - every input and destination must have exactly the destination shape;
2029/// - each mutable destination layout must be injective, so two logical output
2030///   elements never map to the same memory address.
2031///
2032/// The implementation dispatches known single-output plans to existing static
2033/// `map_into`/`zip_map*_into` kernels, replays a block that is contiguous for
2034/// every operand through a chunked register machine, and falls back to a
2035/// per-element interpreter for arbitrary validated DAGs. Overlapping
2036/// source/destination memory is not supported by the strided kernels generally.
2037///
2038/// # Performance
2039///
2040/// Plans that reach the interpreter (more than one instruction or output, and
2041/// no static specialization) are replayed vectorized only for `f32` and `f64`.
2042/// For `Complex32`, `Complex64` and the integer and `bool` scalars they run the
2043/// per-element interpreter, so such a plan is not expected to beat the same
2044/// ops run as separate `zip_map2_into` passes; callers that fuse for speed
2045/// should decline multi-instruction regions of those dtypes (#528).
2046/// [`has_vectorized_replay`] reports this per scalar type.
2047///
2048/// # Numerics
2049///
2050/// The chunked replay evaluates `Exp`, `Log`, `Sin`, `Cos`, `Tanh` and `Expm1`
2051/// with the `elem-simd-math` slice kernels — the same kernels a per-instruction
2052/// dispatch through [`strided_basic::map_into_uninit_with_kernel`] uses, so the
2053/// fused and the non-fused route agree with each other. Against `std`'s scalar
2054/// functions those six instructions differ by at most one ULP of their own
2055/// output magnitude; a chain of them multiplies that difference by the output
2056/// magnitude, so an exponential chain is not bit-stable to `std`. `Log1p` and
2057/// every other instruction (`Add`, `Subtract`, `Multiply`, `Negate`, `Conj`, `Divide`,
2058/// `Abs`, `Maximum`, `Minimum`, `Clamp`, `Sqrt`, `Rsqrt`, `Pow`) keep the scalar
2059/// `FusedScalar` methods and are bit-identical to the per-element replay.
2060///
2061/// Real `Maximum`, `Minimum`, and `Clamp` share the NaN-propagating select and
2062/// signed-zero contract of `strided_basic::nan_propagating_maximum` /
2063/// `nan_propagating_minimum` (issue #315): a NaN in any operand makes the
2064/// result NaN, and a tie keeps the left operand, so `maximum(-0.0, 0.0)` and
2065/// `clamp` on equal bounds preserve the signed zero of the left/bound operand.
2066/// Complex `Abs` returns the norm in the real component; complex `Maximum`,
2067/// `Minimum`, and `Clamp` compare by squared norm. Signed integer `Add`,
2068/// `Subtract`, `Multiply`, `Negate`, and `Abs` use wrapping arithmetic. `bool` supports
2069/// only copy-like identity plans and `Conj`; ambiguous arithmetic and
2070/// transcendental op/dtype pairs are rejected before any destination is
2071/// written.
2072///
2073/// # Errors
2074///
2075/// [`StridedError::RankMismatch`] reports a disagreement about counts or ranks:
2076/// `inputs.len()` or `dests.len()` against the plan, the operand count of an
2077/// instruction against its op's arity, or the rank of an input or destination
2078/// against the destination rank. [`StridedError::ShapeMismatch`] reports an
2079/// operand or destination whose rank matches but whose extents differ.
2080/// [`StridedError::InvalidAxis`] reports an instruction
2081/// or output referencing a value the plan has not defined yet,
2082/// [`StridedError::UnsupportedOp`] reports an instruction `T` cannot evaluate,
2083/// and [`StridedError::NonInjectiveOutputLayout`] a destination layout that
2084/// cannot be proven injective (aliasing elements, or a span the check cannot
2085/// represent). Every check runs before the first destination store.
2086pub 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;