Skip to main content

strided_basic/
copy_plan.rs

1//! Prepared (compile-once, execute-many) copy plans over raw strided layouts.
2//!
3//! [`copy_scale_raw`](crate::copy_scale_raw) and friends rebuild the fused
4//! loop nest on every call; for prepared-replay consumers that issue many
5//! small copies with a fixed layout, that per-call planning dominates
6//! (see issue #139). [`CopyPlan`] splits the work: [`CopyPlan::compile`]
7//! validates the layout pair and builds the fused traversal once,
8//! [`CopyPlan::execute`]/[`CopyPlan::execute_scale`]/[`CopyPlan::execute_conj`]
9//! replay it with no heap allocation for fused ranks at most
10//! [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT). The only per-execute
11//! planning is the cache-block selection for the element type, which runs the
12//! shared block model on layouts of at least two non-unit axes. A layout is
13//! walked tile by tile when the tiles change the visit order and can reuse a
14//! cache line across the runs they regroup.
15
16use core::{
17    marker::PhantomData,
18    mem::{size_of, MaybeUninit},
19    ops::{Add, Mul},
20    time::Duration,
21};
22
23use num_traits::{One, Zero};
24
25use crate::cost::KernelClass;
26use crate::raw_ops::{
27    apply_fused_range, apply_spilled_range, apply_spilled_tiled_box, apply_tiled_box,
28    fuse_pair_traversal, fused_total, pair_tiles, replay_route_serial, FusedAxis, FusedPairLayout,
29    PairTiles, PairTraversal, Route, SpilledTiles,
30};
31use crate::{ElementOpApply, Exec, RawStridedMut, RawStridedRef, Result, StridedError};
32use strided_perm::HostClass;
33
34// Same pattern as map_view.rs / outer_product.rs: inline storage in both
35// feature configurations. Only `compile` touches these; `execute*` never
36// allocates for them. (A spilled fused layout replays from stack arrays bounded
37// by its moving-axis count: see `raw_ops::MAX_MOVING_AXES`.)
38type AxisVec<T> = crate::inline::InlineVec<T>;
39
40pub(crate) trait OverwriteWriter<T> {
41    fn dims(&self) -> &[usize];
42    fn strides(&self) -> &[isize];
43    fn offset(&self) -> isize;
44    /// # Safety
45    /// The caller must use the pointer only for the validated allocation and
46    /// logical layout represented by this writer.
47    unsafe fn data_ptr(&mut self) -> *mut T;
48    /// # Safety
49    /// The offset must be an in-bounds logical destination proven by layout.
50    unsafe fn write_at(&mut self, offset: isize, value: T);
51}
52
53pub(crate) trait ReadModifyWrite<T>: OverwriteWriter<T> {
54    /// # Safety
55    /// The offset must be an in-bounds initialized slot covered by the
56    /// traversal's copy and disjointness proof.
57    unsafe fn add_at<F>(&mut self, offset: isize, value: T, combine: F)
58    where
59        F: FnOnce(T, T) -> T;
60}
61
62impl<'a, T> OverwriteWriter<T> for RawStridedMut<'a, T> {
63    fn dims(&self) -> &[usize] {
64        self.dims()
65    }
66    fn strides(&self) -> &[isize] {
67        self.strides()
68    }
69    fn offset(&self) -> isize {
70        self.offset()
71    }
72    unsafe fn data_ptr(&mut self) -> *mut T {
73        self.data_mut().as_mut_ptr()
74    }
75    unsafe fn write_at(&mut self, offset: isize, value: T) {
76        // SAFETY: the prepared layout validates every logical destination.
77        unsafe { self.data_mut().as_mut_ptr().offset(offset).write(value) }
78    }
79}
80
81impl<'a, T> ReadModifyWrite<T> for RawStridedMut<'a, T> {
82    #[inline(always)]
83    unsafe fn add_at<F>(&mut self, offset: isize, value: T, combine: F)
84    where
85        F: FnOnce(T, T) -> T,
86    {
87        // SAFETY: the copy or initialized caller proves this logical slot.
88        unsafe {
89            let ptr = self.data_mut().as_mut_ptr().offset(offset);
90            ptr.write(combine(ptr.read(), value));
91        }
92    }
93}
94
95impl<'a, T> OverwriteWriter<T> for RawStridedMut<'a, MaybeUninit<T>> {
96    fn dims(&self) -> &[usize] {
97        self.dims()
98    }
99    fn strides(&self) -> &[isize] {
100        self.strides()
101    }
102    fn offset(&self) -> isize {
103        self.offset()
104    }
105    unsafe fn data_ptr(&mut self) -> *mut T {
106        self.data_mut().as_mut_ptr().cast()
107    }
108    unsafe fn write_at(&mut self, offset: isize, value: T) {
109        // SAFETY: the prepared layout validates every logical destination.
110        unsafe {
111            self.data_mut()
112                .as_mut_ptr()
113                .offset(offset)
114                .write(MaybeUninit::new(value))
115        }
116    }
117}
118
119pub(crate) struct InitializedRawDest<'a, T> {
120    ptr: *mut T,
121    extent: usize,
122    dims: &'a [usize],
123    strides: &'a [isize],
124    offset: isize,
125    _marker: PhantomData<&'a mut [MaybeUninit<T>]>,
126}
127
128impl<'a, T> OverwriteWriter<T> for InitializedRawDest<'a, T> {
129    fn dims(&self) -> &[usize] {
130        self.dims
131    }
132    fn strides(&self) -> &[isize] {
133        self.strides
134    }
135    fn offset(&self) -> isize {
136        self.offset
137    }
138    unsafe fn data_ptr(&mut self) -> *mut T {
139        self.ptr
140    }
141    unsafe fn write_at(&mut self, offset: isize, value: T) {
142        debug_assert!(offset >= 0 && (offset as usize) < self.extent);
143        // SAFETY: the copy proof and extent check cover this logical slot.
144        unsafe { self.ptr.offset(offset).write(value) }
145    }
146}
147
148impl<'a, T> ReadModifyWrite<T> for InitializedRawDest<'a, T> {
149    #[inline(always)]
150    unsafe fn add_at<F>(&mut self, offset: isize, value: T, combine: F)
151    where
152        F: FnOnce(T, T) -> T,
153    {
154        debug_assert!(offset >= 0 && (offset as usize) < self.extent);
155        // SAFETY: the copy proof and extent check cover this logical slot.
156        unsafe {
157            let ptr = self.ptr.offset(offset);
158            ptr.write(combine(ptr.read(), value));
159        }
160    }
161}
162
163/// A compiled copy traversal for one `(dims, dst_strides, src_strides)`
164/// layout pair.
165///
166/// `compile` proves the layout facts once (rank agreement, extent overflow,
167/// destination injectivity) and fuses/orders the loop nest; each `execute*`
168/// call then only re-checks the per-call facts (that the supplied views carry
169/// exactly the compiled layout) and selects the cache blocks for its element
170/// type before replaying the prepared loops. The order in which elements are
171/// visited is unspecified.
172///
173/// Overlapping `src`/`dest` memory is not supported, matching the rest of the
174/// crate.
175///
176/// Ranks above [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT) are supported by the same fused
177/// traversal, which then stores its axes in one rank-bounded allocation.
178///
179/// # Example
180///
181/// ```rust
182/// use strided_basic::{CopyPlan, Exec, RawStridedMut, RawStridedRef};
183///
184/// let dims = [2usize, 3];
185/// let src_strides = [3isize, 1];
186/// let dst_strides = [1isize, 2]; // transposed destination
187/// let plan = CopyPlan::compile(&dims, &dst_strides, &src_strides).unwrap();
188///
189/// let src = [0.0f64, 1.0, 2.0, 10.0, 11.0, 12.0];
190/// let mut dst = [0.0f64; 6];
191/// let src_ref = RawStridedRef::new(&src, &dims, &src_strides, 0).unwrap();
192/// let mut dst_mut = RawStridedMut::new(&mut dst, &dims, &dst_strides, 0).unwrap();
193/// plan.execute(&mut dst_mut, &src_ref, Exec::serial()).unwrap();
194/// assert_eq!(dst, [0.0, 10.0, 1.0, 11.0, 2.0, 12.0]);
195/// ```
196#[derive(Clone, Debug, Default)]
197pub struct CopyPlan {
198    dims: AxisVec<usize>,
199    dst_strides: AxisVec<isize>,
200    src_strides: AxisVec<isize>,
201    fused: PairTraversal,
202    /// Elements each side spans ([`span_elements`]), so that the working set in
203    /// bytes is `dst_span * size_of::<D>() + src_span * size_of::<S>()` at replay,
204    /// where the element types are known.
205    dst_span: usize,
206    src_span: usize,
207}
208
209impl CopyPlan {
210    /// `None` when the fused traversal is stored in the rank-bounded spill.
211    #[inline]
212    pub(crate) fn fused_layout(&self) -> Option<&FusedPairLayout> {
213        self.fused.inline()
214    }
215
216    /// The cache tiles [`Self::execute`] replays this plan's inline layout with
217    /// for destination element `D` and source element `S`, or `None` when it
218    /// keeps the column-major walk or the layout spilled: the one decision a
219    /// caller replaying the plan's inline traversal itself must reuse.
220    #[inline]
221    pub(crate) fn inline_tiles<D, S>(&self) -> Option<PairTiles> {
222        self.fused.inline().and_then(pair_tiles::<D, S>)
223    }
224
225    /// Whether [`Self::tiles`] can return tiles for any element types; known
226    /// at compile time ([`PairTraversal::may_tile`]).
227    #[inline]
228    pub(crate) fn may_tile(&self) -> bool {
229        self.fused.may_tile()
230    }
231
232    /// Copy into uninitialized storage, then lend the initialized destination to `f`.
233    ///
234    /// [`Self::execute_uninit`] initializes every reachable logical destination
235    /// element before `f` runs, so the [`InitializedRawDest`] receipt handed to `f`
236    /// may read and overwrite exactly those offsets. Slots outside the plan's
237    /// reachable set are not written by that copy and it makes no claim about
238    /// them: a caller that handed in a `MaybeUninit` array still owns those slots,
239    /// so they keep whatever initialization the caller left. With
240    /// `CopyPlan::compile(&[2], &[2], &[1])` the offset-1 hole keeps the caller's
241    /// value (measured `[7.0, 99.0, 8.0]` for `src = [7, 8]`) rather than
242    /// becoming uninitialized. That is why the receipt exposes
243    /// `write_at`/`add_at` (copy_plan.rs:140, :149) instead of a typed slice: their
244    /// contracts require an offset proven by this plan's layout. The receipt borrows
245    /// the destination for `f`'s lifetime, so a read-modify-write consumer (the
246    /// gather and scatter update replay in gather_plan.rs) sees the copied operand
247    /// once and cannot alias the source.
248    ///
249    /// # Errors
250    ///
251    /// Returns the [`Self::execute_uninit`] errors (`PlanLayoutMismatch`, before any
252    /// write); `f` runs only on success.
253    pub(crate) fn execute_uninit_then<'a, T, R>(
254        &self,
255        dest: &'a mut RawStridedMut<'a, MaybeUninit<T>>,
256        src: &RawStridedRef<'_, T>,
257        mut exec: Exec<'_>,
258        f: impl for<'b, 'e> FnOnce(InitializedRawDest<'b, T>, Exec<'e>) -> R,
259    ) -> Result<R>
260    where
261        T: Copy + Send + Sync,
262    {
263        self.execute_uninit(dest, src, exec.reborrow())?;
264        let data = dest.data_mut();
265        let receipt = InitializedRawDest {
266            ptr: data.as_mut_ptr().cast(),
267            extent: data.len(),
268            dims: dest.dims(),
269            strides: dest.strides(),
270            offset: dest.offset(),
271            _marker: PhantomData,
272        };
273        Ok(f(receipt, exec))
274    }
275
276    /// Compile a copy plan for the given layout pair.
277    ///
278    /// Performs the layout validation and traversal construction
279    /// (fuse + order) once.
280    ///
281    /// # Errors
282    ///
283    /// Returns [`StridedError::StrideLengthMismatch`] when `dims`,
284    /// `dst_strides`, and `src_strides` do not all have the same length,
285    /// [`StridedError::OffsetOverflow`] when the total element count does not
286    /// fit `usize`, and [`StridedError::NonInjectiveOutputLayout`] when the
287    /// destination layout cannot be proven injective (aliasing elements, or a
288    /// span the check cannot represent).
289    pub fn compile(dims: &[usize], dst_strides: &[isize], src_strides: &[isize]) -> Result<Self> {
290        if dims.len() != dst_strides.len() || dims.len() != src_strides.len() {
291            return Err(StridedError::StrideLengthMismatch);
292        }
293        // A zero-sized layout has zero elements even when its other extents
294        // overflow; only a nonempty overflowing count is rejected.
295        crate::kernel::total_len(dims)?;
296        if !crate::layout_check::is_injective_layout(dims, dst_strides) {
297            return Err(StridedError::NonInjectiveOutputLayout);
298        }
299        let fused = fuse_pair_traversal(dims, dst_strides, src_strides);
300        Ok(Self {
301            dims: dims.into(),
302            dst_strides: dst_strides.into(),
303            src_strides: src_strides.into(),
304            fused,
305            dst_span: span_elements(dims, dst_strides),
306            src_span: span_elements(dims, src_strides),
307        })
308    }
309
310    /// Serial time one replay of this plan is estimated at on this host, for
311    /// operands of `T`.
312    ///
313    /// The rate is the one the plan's own width decision uses: the `Copy` row,
314    /// plus the per-run cache-line term of its walk, plus the beyond-L2 term when
315    /// the working set does not fit the class's L2 cache (strided-rs#364). The
316    /// element type is a parameter because `compile` stores only the layout; the
317    /// working set in bytes, and so the cache level that selects the rate, needs
318    /// `size_of::<T>()`.
319    ///
320    /// A caller that composes many plans under its own outer split can compare
321    /// this duration with `Exec`'s dispatch cost without restating the model, so
322    /// the two decisions stay consistent (strided-rs#363).
323    ///
324    /// # Examples
325    ///
326    /// ```
327    /// use strided_basic::CopyPlan;
328    ///
329    /// let plan = CopyPlan::compile(&[2, 3], &[1, 2], &[3, 1]).unwrap();
330    /// let cost: core::time::Duration = plan.serial_cost::<f64>();
331    /// assert!(cost > core::time::Duration::ZERO);
332    /// ```
333    pub fn serial_cost<T>(&self) -> Duration {
334        self.serial_cost_on::<T, T>(HostClass::detect())
335    }
336
337    /// [`Self::serial_cost`] priced for host class `host`: the class is a
338    /// parameter so that the tests can pin it.
339    pub(crate) fn serial_cost_on<D, S>(&self, host: HostClass) -> Duration {
340        // `compile` already rejected an overflowing element count, so the
341        // saturation is unreachable; it is the conservative direction if it ever
342        // were reached.
343        let elements = crate::kernel::total_len(&self.dims).unwrap_or(usize::MAX);
344        Duration::from_secs_f64(elements as f64 * self.ns_per_element_on::<D, S>(host) * 1e-9)
345    }
346
347    /// Serial rate this plan prices itself at on host class `host`: the `Copy`
348    /// row while the plan is one contiguous run, the row plus one cache line per
349    /// run of its walk otherwise, the class's beyond-L2 line past its L2 cache
350    /// (strided-rs#364). [`Self::replay`] asks it for [`HostClass::detect`]; the
351    /// class is a parameter so that the tests can pin it.
352    ///
353    /// The element size is the one fact `compile` cannot know, so the footprint
354    /// in bytes is formed here from the compiled span; nothing is probed.
355    fn ns_per_element_on<D, S>(&self, host: HostClass) -> f64 {
356        plan_ns_per_element::<D, S>(host, &self.fused, self.dst_span, self.src_span)
357    }
358
359    /// Check the per-call facts: the supplied views must carry exactly the
360    /// compiled layout. Buffer bounds against that layout were already proven
361    /// by [`RawStridedRef::new`]/[`RawStridedMut::new`] (or asserted by the
362    /// caller of the `new_unchecked` constructors), so layout equality is the
363    /// complete precondition for the pointer-based fused replay below.
364    fn check_call<D, S>(
365        &self,
366        dest: &RawStridedMut<'_, D>,
367        src: &RawStridedRef<'_, S>,
368    ) -> Result<()> {
369        check_layout_pair(&self.dims, &self.dst_strides, &self.src_strides, dest, src)
370    }
371
372    /// Check the per-call facts, then replay the compiled traversal, priced for
373    /// this host's class.
374    fn replay<D, S, Apply>(
375        &self,
376        dest: &mut RawStridedMut<'_, D>,
377        src: &RawStridedRef<'_, S>,
378        apply: Apply,
379        exec: Exec<'_>,
380    ) -> Result<()>
381    where
382        D: Copy + Send + Sync,
383        S: Copy + Send + Sync,
384        Apply: Fn(&mut D, S) + Sync,
385    {
386        self.replay_on(HostClass::detect(), dest, src, apply, exec)
387    }
388
389    /// [`Self::replay`] priced for host class `host`: every scheduling decision
390    /// of the replay asks at [`Self::ns_per_element_on`] of that class. Split out
391    /// so that a test can pin the class and observe the rate reach the replay on
392    /// every host (strided-rs#364).
393    fn replay_on<D, S, Apply>(
394        &self,
395        host: HostClass,
396        dest: &mut RawStridedMut<'_, D>,
397        src: &RawStridedRef<'_, S>,
398        apply: Apply,
399        exec: Exec<'_>,
400    ) -> Result<()>
401    where
402        D: Copy + Send + Sync,
403        S: Copy + Send + Sync,
404        Apply: Fn(&mut D, S) + Sync,
405    {
406        self.check_call(dest, src)?;
407        let ns_per_element = self.ns_per_element_on::<D, S>(host);
408        self.fused.with_route::<D, S, _>(|route| {
409            // SAFETY: `check_call` proved both views carry exactly the compiled
410            // layout, and `fused` is the fusion of that layout (only `compile`
411            // and `Default`, the rank-zero layout, build it). `compile` checked
412            // the element count and proved the destination injective, so the
413            // tiles of `fused` may be replayed.
414            unsafe { replay_fused(dest, src, route, apply, ns_per_element, exec) }
415        });
416        Ok(())
417    }
418
419    /// `dest = src` into a potentially uninitialized destination.
420    ///
421    /// On success every reachable logical destination element is initialized.
422    /// Non-reachable holes in the backing allocation are not written.
423    ///
424    /// # Errors
425    ///
426    /// Returns [`StridedError::PlanLayoutMismatch`] when the views do not
427    /// carry the compiled layout, before any write.
428    pub fn execute_uninit<T>(
429        &self,
430        dest: &mut RawStridedMut<'_, MaybeUninit<T>>,
431        src: &RawStridedRef<'_, T>,
432        exec: Exec<'_>,
433    ) -> Result<()>
434    where
435        T: Copy + Send + Sync,
436    {
437        self.replay(
438            dest,
439            src,
440            |dst: &mut MaybeUninit<T>, value: T| {
441                dst.write(value);
442            },
443            exec,
444        )
445    }
446
447    /// `dest = src`. Allocation-free for fused ranks at most
448    /// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT).
449    ///
450    /// # Errors
451    ///
452    /// Returns [`StridedError::PlanLayoutMismatch`] when the views do not
453    /// carry the compiled layout, before any write.
454    pub fn execute<T>(
455        &self,
456        dest: &mut RawStridedMut<'_, T>,
457        src: &RawStridedRef<'_, T>,
458        exec: Exec<'_>,
459    ) -> Result<()>
460    where
461        T: Copy + Send + Sync,
462    {
463        self.replay(dest, src, |dst: &mut T, value: T| *dst = value, exec)
464    }
465
466    /// `dest = scale * src`. Allocation-free for fused ranks at most
467    /// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT).
468    ///
469    /// # Errors
470    ///
471    /// Returns [`StridedError::PlanLayoutMismatch`] when the views do not
472    /// carry the compiled layout, before any write.
473    pub fn execute_scale<T>(
474        &self,
475        dest: &mut RawStridedMut<'_, T>,
476        src: &RawStridedRef<'_, T>,
477        scale: T,
478        exec: Exec<'_>,
479    ) -> Result<()>
480    where
481        T: Copy + Mul<T, Output = T> + Send + Sync,
482    {
483        self.replay(
484            dest,
485            src,
486            |dst: &mut T, value: T| *dst = scale * value,
487            exec,
488        )
489    }
490
491    /// `dest = conj(src)`. Allocation-free for fused ranks at most
492    /// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT).
493    ///
494    /// # Errors
495    ///
496    /// Returns [`StridedError::PlanLayoutMismatch`] when the views do not
497    /// carry the compiled layout, before any write.
498    pub fn execute_conj<T>(
499        &self,
500        dest: &mut RawStridedMut<'_, T>,
501        src: &RawStridedRef<'_, T>,
502        exec: Exec<'_>,
503    ) -> Result<()>
504    where
505        T: Copy + ElementOpApply + Send + Sync,
506    {
507        self.replay(dest, src, |dst: &mut T, value: T| *dst = value.conj(), exec)
508    }
509}
510
511/// Whether the replay walks `fused` as one unit-stride run on each side, the
512/// layout the `Copy` row is calibrated on, and the length of the unit-stride run
513/// its walk starts with.
514///
515/// A *run* is a stretch of the walk that advances by one element on both sides;
516/// a streamed contiguous copy is one run and keeps the row at every footprint, a
517/// reversed one (`-1` on a side) streams the same way, and a transposing walk
518/// takes one run of one element per visit. The run length is the
519/// `elements / segments` ratio of strided-rs#364's
520/// `segments * per_segment + elements * per_element_inside_segment`, read off the
521/// frozen fused layout, so it is a compile-time plan property and nothing is
522/// probed.
523///
524/// The question is about the walk the replay takes, not about a walk the layout
525/// would allow: both replays walk the fused axes in their stored order with axis 0
526/// fastest (`apply_fused_range`, `apply_spilled_range`), and the tiled replay only
527/// exists for two or more moving axes. So the strides, read in that order, must be
528/// the running products of the extents with one sign per operand. Fusion already
529/// merges every such pair, so in practice a one-run walk is a fused rank of one at
530/// unit stride; a dense *reversed* buffer of rank two or more is not one run here,
531/// because fusion sorts the axes by signed destination stride and walks
532/// `[-1, -512]` over `[512, 512]` with `-512` fastest (strided-rs#364 review).
533/// That walk's runs are one element long, and it is priced as the strided walk it
534/// is.
535fn walk_runs(fused: &PairTraversal) -> (usize, bool) {
536    /// `(leading run length, that run is the whole walk)`.
537    fn runs(axes: impl Iterator<Item = (usize, isize, isize)>) -> (usize, bool) {
538        let mut len = 1usize;
539        let mut signs = None;
540        for (dim, dst, src) in axes {
541            if dim == 1 {
542                continue;
543            }
544            // A direction flip ends the run too: the walk reverses there, so the
545            // next element is a new cache line even at a unit stride.
546            let axis_signs = (dst < 0, src < 0);
547            if dst.unsigned_abs() != len
548                || src.unsigned_abs() != len
549                || *signs.get_or_insert(axis_signs) != axis_signs
550            {
551                return (len, false);
552            }
553            len = len.saturating_mul(dim);
554        }
555        (len, true)
556    }
557    match fused {
558        PairTraversal::Inline(layout) => runs(inline_axes(layout)),
559        PairTraversal::Spilled(axes) => runs(spilled_axes(axes)),
560    }
561}
562
563// shortcut: the run length is the fused axes' untiled walk. The tiled replay of
564// strided-rs#422 cuts a box, so its runs can be shorter than the leading axis run
565// (an inner extent of 8 tiled to 6 and 2 halves the run length and so doubles the
566// per-run line charge). Upgrade when a tiled plan's in-L2 pricing is measured
567// against the model: derive the charge from `PairTraversal::with_route` then.
568
569/// The axes of a fused walk in replay order (axis 0 fastest) as
570/// `(extent, destination stride, source stride)`.
571fn inline_axes(layout: &FusedPairLayout) -> impl Iterator<Item = (usize, isize, isize)> + '_ {
572    (0..layout.rank).map(move |axis| {
573        (
574            layout.dims[axis],
575            layout.dst_strides[axis],
576            layout.src_strides[axis],
577        )
578    })
579}
580
581/// [`inline_axes`] for the spilled traversal.
582fn spilled_axes(axes: &[FusedAxis]) -> impl Iterator<Item = (usize, isize, isize)> + '_ {
583    axes.iter().map(|axis| (axis.dim, axis.dst, axis.src))
584}
585
586/// Serial rate a copy-shaped plan prices itself at on `host`, from the three
587/// facts `compile` froze in its fused layout and spans: whether the whole walk is
588/// one contiguous run, the length of its runs, and the working set in bytes.
589///
590/// [`CopyPlan`] and [`UpdatePlan`] both replay [`replay_fused`], so both ask their
591/// rate here (strided-rs#364).
592fn plan_ns_per_element<D, S>(
593    host: HostClass,
594    fused: &PairTraversal,
595    dst_span: usize,
596    src_span: usize,
597) -> f64 {
598    let (run_len, one_run) = walk_runs(fused);
599    if one_run {
600        return KernelClass::Copy.ns_per_element_of(host);
601    }
602    let bytes = dst_span
603        .saturating_mul(size_of::<D>())
604        .saturating_add(src_span.saturating_mul(size_of::<S>()));
605    crate::cost::copy_ns_per_element_for_plan(host, bytes, run_len)
606}
607
608/// Elements one side of a compiled layout spans: `1 + sum((dim - 1) * |stride|)`,
609/// the reach of the side from its base offset. Summed over the two sides it is
610/// the plan's working set in elements, saturating rather than wrapping because a
611/// stride is only bounded by `isize`.
612fn span_elements(dims: &[usize], strides: &[isize]) -> usize {
613    dims.iter()
614        .zip(strides)
615        .fold(1usize, |span, (&dim, &stride)| {
616            span.saturating_add(dim.saturating_sub(1).saturating_mul(stride.unsigned_abs()))
617        })
618}
619
620/// Verify that a pair of raw views carries exactly a compiled layout.
621///
622/// Shared by [`CopyPlan`] and [`UpdatePlan`], whose `compile` methods prove the
623/// layout facts once. Buffer bounds against that layout were already proven by
624/// [`RawStridedRef::new`]/[`RawStridedMut::new`] (or asserted by the caller of
625/// the `new_unchecked` constructors), so layout equality is the complete
626/// per-call precondition for the pointer-based fused replay.
627fn check_layout_pair<D, S>(
628    dims: &[usize],
629    dst_strides: &[isize],
630    src_strides: &[isize],
631    dest: &RawStridedMut<'_, D>,
632    src: &RawStridedRef<'_, S>,
633) -> Result<()> {
634    if dest.dims() != dims
635        || src.dims() != dims
636        || dest.strides() != dst_strides
637        || src.strides() != src_strides
638    {
639        return Err(StridedError::PlanLayoutMismatch);
640    }
641    Ok(())
642}
643
644/// A compiled read-modify-write traversal for one `(dims, dst_strides,
645/// src_strides)` layout pair.
646///
647/// [`execute`](Self::execute) computes `dest = alpha * f(src) + beta * dest` by
648/// replaying the same fused pair traversal as [`CopyPlan`]: `compile` proves
649/// the layout facts once (rank agreement, extent overflow, destination
650/// injectivity) and each call only re-checks that the supplied views carry the
651/// compiled layout before running monomorphized loops. Execute is
652/// allocation-free for fused ranks at most
653/// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT), and the injective
654/// destination makes a large replay parallel-safe exactly as in [`CopyPlan`].
655///
656/// Overlapping `src`/`dest` memory is not supported, matching the rest of the
657/// crate.
658///
659/// # Example
660///
661/// ```rust
662/// use strided_basic::{Exec, RawStridedMut, RawStridedRef, UpdatePlan};
663///
664/// let dims = [2usize, 2];
665/// let dst_strides = [1isize, 2];
666/// let src_strides = [1isize, 2];
667/// let plan = UpdatePlan::compile(&dims, &dst_strides, &src_strides).unwrap();
668///
669/// let src = [1.0f64, 2.0, 3.0, 4.0];
670/// let mut dst = [10.0f64, 20.0, 30.0, 40.0];
671/// let src_ref = RawStridedRef::new(&src, &dims, &src_strides, 0).unwrap();
672/// let mut dst_mut = RawStridedMut::new(&mut dst, &dims, &dst_strides, 0).unwrap();
673/// // dst = 2 * src + 3 * dst
674/// plan.execute(&mut dst_mut, &src_ref, 2.0, 3.0, |x| x, Exec::serial()).unwrap();
675/// assert_eq!(dst, [32.0, 64.0, 96.0, 128.0]);
676/// ```
677#[derive(Clone, Debug)]
678pub struct UpdatePlan {
679    dims: AxisVec<usize>,
680    dst_strides: AxisVec<isize>,
681    src_strides: AxisVec<isize>,
682    fused: PairTraversal,
683    /// Working-set spans, as on [`CopyPlan`]: the footprint in bytes is formed at
684    /// replay, where the element types are known.
685    dst_span: usize,
686    src_span: usize,
687}
688
689impl UpdatePlan {
690    /// Compile an update plan for the given layout pair.
691    ///
692    /// Performs the same layout validation as [`CopyPlan::compile`].
693    ///
694    /// # Errors
695    ///
696    /// Returns [`StridedError::StrideLengthMismatch`] when `dims`,
697    /// `dst_strides`, and `src_strides` do not all have the same length,
698    /// [`StridedError::OffsetOverflow`] when the total element count does not
699    /// fit `usize`, and [`StridedError::NonInjectiveOutputLayout`] when the
700    /// destination layout cannot be proven injective: two logical indices name
701    /// one slot (so a parallel replay would write that slot once per index), or
702    /// the offset span cannot be represented, leaving injectivity undecided.
703    pub fn compile(dims: &[usize], dst_strides: &[isize], src_strides: &[isize]) -> Result<Self> {
704        if dims.len() != dst_strides.len() || dims.len() != src_strides.len() {
705            return Err(StridedError::StrideLengthMismatch);
706        }
707        crate::kernel::total_len(dims)?;
708        if !crate::layout_check::is_injective_layout(dims, dst_strides) {
709            return Err(StridedError::NonInjectiveOutputLayout);
710        }
711        let fused = fuse_pair_traversal(dims, dst_strides, src_strides);
712        Ok(Self {
713            dims: dims.into(),
714            dst_strides: dst_strides.into(),
715            src_strides: src_strides.into(),
716            fused,
717            dst_span: span_elements(dims, dst_strides),
718            src_span: span_elements(dims, src_strides),
719        })
720    }
721
722    /// Serial rate this plan prices itself at on host class `host`: the same
723    /// [`plan_ns_per_element`] as [`CopyPlan`], because both replay
724    /// [`replay_fused`] and a caller that paid the line per run on one would pay
725    /// it on the other (strided-rs#364).
726    fn ns_per_element_on<D, S>(&self, host: HostClass) -> f64 {
727        plan_ns_per_element::<D, S>(host, &self.fused, self.dst_span, self.src_span)
728    }
729
730    /// Check the per-call facts, then replay the compiled traversal, priced for
731    /// this host's class.
732    fn replay<D, S, Apply>(
733        &self,
734        dest: &mut RawStridedMut<'_, D>,
735        src: &RawStridedRef<'_, S>,
736        apply: Apply,
737        exec: Exec<'_>,
738    ) -> Result<()>
739    where
740        D: Copy + Send + Sync,
741        S: Copy + Send + Sync,
742        Apply: Fn(&mut D, S) + Sync,
743    {
744        self.replay_on(HostClass::detect(), dest, src, apply, exec)
745    }
746
747    /// [`Self::replay`] priced for host class `host`: split out for the same
748    /// reason as [`CopyPlan::replay_on`], so that a test can pin the class and see
749    /// the plan's rate reach the replay on every host (strided-rs#364).
750    fn replay_on<D, S, Apply>(
751        &self,
752        host: HostClass,
753        dest: &mut RawStridedMut<'_, D>,
754        src: &RawStridedRef<'_, S>,
755        apply: Apply,
756        exec: Exec<'_>,
757    ) -> Result<()>
758    where
759        D: Copy + Send + Sync,
760        S: Copy + Send + Sync,
761        Apply: Fn(&mut D, S) + Sync,
762    {
763        check_layout_pair(&self.dims, &self.dst_strides, &self.src_strides, dest, src)?;
764        let ns_per_element = self.ns_per_element_on::<D, S>(host);
765        self.fused.with_route::<D, S, _>(|route| {
766            // SAFETY: as in `CopyPlan::replay`: the views carry the compiled
767            // layout, `fused` is its fusion (built only by `compile`), and
768            // `compile` checked the count and destination injectivity.
769            unsafe { replay_fused(dest, src, route, apply, ns_per_element, exec) }
770        });
771        Ok(())
772    }
773
774    /// `dest = alpha * f(src) + beta * dest`.
775    ///
776    /// `f` is applied to the source element before scaling. When `beta` is
777    /// zero (`-0.0` included; `NaN` is not zero) the replay is write-only: the
778    /// old destination element is never read, so a NaN-filled or uninitialized
779    /// destination cannot contaminate the result, matching BLAS `beta = 0`
780    /// semantics. Otherwise the old destination element is read through the
781    /// destination layout. Allocation-free for fused ranks at most
782    /// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT).
783    ///
784    /// `f` runs once per logical element. The order in which elements are
785    /// visited is unspecified, and on a parallel replay `f` runs concurrently
786    /// on disjoint slots: the result is defined only for an `f` whose effect
787    /// depends on the supplied value alone.
788    ///
789    /// # Errors
790    ///
791    /// [`StridedError::PlanLayoutMismatch`] when the supplied views do not
792    /// carry the compiled layout, before any write.
793    pub fn execute<T, F>(
794        &self,
795        dest: &mut RawStridedMut<'_, T>,
796        src: &RawStridedRef<'_, T>,
797        alpha: T,
798        beta: T,
799        f: F,
800        exec: Exec<'_>,
801    ) -> Result<()>
802    where
803        T: Copy + Send + Sync + Add<Output = T> + Mul<Output = T> + Zero + One + PartialEq,
804        F: Fn(T) -> T + Send + Sync,
805    {
806        if beta.is_zero() {
807            // Write-only: never form a read of the old destination.
808            if alpha.is_one() {
809                self.replay(dest, src, |dst: &mut T, value: T| *dst = f(value), exec)
810            } else {
811                self.replay(
812                    dest,
813                    src,
814                    |dst: &mut T, value: T| *dst = alpha * f(value),
815                    exec,
816                )
817            }
818        } else {
819            self.replay(
820                dest,
821                src,
822                |dst: &mut T, value: T| *dst = alpha * f(value) + beta * *dst,
823                exec,
824            )
825        }
826    }
827
828    /// `dest = alpha * f(src)` into a potentially uninitialized destination.
829    ///
830    /// This is [`execute`](Self::execute) with `beta = 0`: the destination is
831    /// never read. On success every reachable logical destination element is
832    /// initialized; non-reachable holes in the backing allocation are not
833    /// written. Allocation-free for fused ranks at most
834    /// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT). The visit-order
835    /// and callback contract is that of [`execute`](Self::execute).
836    ///
837    /// # Errors
838    ///
839    /// [`StridedError::PlanLayoutMismatch`] when the supplied views do not
840    /// carry the compiled layout, before any write.
841    ///
842    /// # Examples
843    ///
844    /// ```rust
845    /// use core::mem::MaybeUninit;
846    /// use strided_basic::{Exec, RawStridedMut, RawStridedRef, UpdatePlan};
847    ///
848    /// let dims = [2usize, 2];
849    /// let strides = [1isize, 2];
850    /// let plan = UpdatePlan::compile(&dims, &strides, &strides).unwrap();
851    /// let src = [1.0f64, 2.0, 3.0, 4.0];
852    /// let mut storage = [MaybeUninit::<f64>::uninit(); 4];
853    /// let mut dst = RawStridedMut::new(&mut storage, &dims, &strides, 0).unwrap();
854    /// let source = RawStridedRef::new(&src, &dims, &strides, 0).unwrap();
855    /// // dst = 2 * src
856    /// plan.execute_uninit(&mut dst, &source, 2.0, |x| x, Exec::serial()).unwrap();
857    /// drop(dst);
858    /// // SAFETY: every reachable destination slot was initialized above.
859    /// let values: Vec<f64> = storage.iter().map(|v| unsafe { v.assume_init() }).collect();
860    /// assert_eq!(values, [2.0, 4.0, 6.0, 8.0]);
861    /// ```
862    pub fn execute_uninit<T, F>(
863        &self,
864        dest: &mut RawStridedMut<'_, MaybeUninit<T>>,
865        src: &RawStridedRef<'_, T>,
866        alpha: T,
867        f: F,
868        exec: Exec<'_>,
869    ) -> Result<()>
870    where
871        T: Copy + Send + Sync + Mul<Output = T> + One + PartialEq,
872        F: Fn(T) -> T + Send + Sync,
873    {
874        if alpha.is_one() {
875            self.replay(
876                dest,
877                src,
878                |dst: &mut MaybeUninit<T>, value: T| {
879                    dst.write(f(value));
880                },
881                exec,
882            )
883        } else {
884            self.replay(
885                dest,
886                src,
887                |dst: &mut MaybeUninit<T>, value: T| {
888                    dst.write(alpha * f(value));
889                },
890                exec,
891            )
892        }
893    }
894}
895
896/// Replay `route` over a pair of raw views, splitting it across the budget
897/// of `exec` when the repository threshold allows it.
898///
899/// A tiled route walks its cache tiles and splits the box with the dimension
900/// splitter (see [`replay_fused_raw`] and [`replay_spilled_tiled`]). An
901/// untiled one splits the logical index space `0..total`
902/// (column-major over the traversal axes) is split into contiguous worker
903/// ranges, which divides the outer axes and, when there are fewer outer
904/// positions than workers, also chunks long inner runs (for example a rank-1
905/// contiguous copy). A serial token walks the route through
906/// [`replay_route_serial`], the walk [`crate::replay_map_raw_serial`]
907/// shares.
908///
909/// # Safety
910///
911/// - `route` must replay exactly the logical index space of the two views:
912///   either their dims and strides fused by `fuse_pair_traversal`
913///   ([`PairTraversal::with_route`]), or given by them
914///   ([`crate::raw_ops::with_given_route`]). The views' own bounds proofs
915///   ([`RawStridedRef::new`], [`RawStridedMut::new`], or the caller of their
916///   `new_unchecked`) then make every replayed offset in-bounds.
917/// - The product of the route's extents must not overflow `usize` (a checked
918///   count, zero included).
919/// - The route's tiles, when present, must be the decision of the route
920///   builder for its own axes.
921/// - When the route is tiled or `exec` is not serial, the destination strides
922///   must be injective over the route.
923/// - The destination and source must not overlap.
924///
925/// `ns_per_element` is the serial rate the replay prices itself at; both plan
926/// types pass their own ([`CopyPlan::ns_per_element_on`],
927/// `UpdatePlan::ns_per_element_on`), because the pricing follows the traversal and
928/// not the entry. The plan-free `replay_*_raw` entries pass the rate of
929/// `KernelClass::Copy` ([`crate::cost::KernelClass::ns_per_element`]).
930pub(crate) unsafe fn replay_fused<D, S, Apply>(
931    dest: &mut RawStridedMut<'_, D>,
932    src: &RawStridedRef<'_, S>,
933    route: Route<'_>,
934    mut apply: Apply,
935    ns_per_element: f64,
936    exec: Exec<'_>,
937) where
938    D: Copy + Send + Sync,
939    S: Copy + Send + Sync,
940    Apply: Fn(&mut D, S) + Sync,
941{
942    let src_ptr = src.data().as_ptr();
943    let src_base = src.offset();
944    let dst_base = dest.offset();
945    let dst_ptr = dest.data_mut().as_mut_ptr();
946    if exec.is_serial() {
947        // SAFETY: forwarded caller contract, on a serial token.
948        unsafe {
949            replay_route_serial(dst_ptr, dst_base, src_ptr, src_base, route, &mut apply);
950        }
951        return;
952    }
953    // SAFETY: forwarded caller contract: every logical index of `route` maps
954    // to in-bounds slots of both views, injectivity holds whenever the replay
955    // is tiled or the token can fan out, and the borrows do not overlap. Inline
956    // tiles address exactly the slots of their layout, in the same column-major
957    // order.
958    unsafe {
959        match route {
960            Route::Inline { layout, tiles } => replay_fused_raw(
961                dst_ptr,
962                dst_base,
963                src_ptr,
964                src_base,
965                layout,
966                tiles,
967                apply,
968                ns_per_element,
969                exec,
970            ),
971            Route::Spilled {
972                tiles: Some(tiles), ..
973            } => replay_spilled_tiled(
974                dst_ptr,
975                dst_base,
976                src_ptr,
977                src_base,
978                tiles,
979                apply,
980                exec,
981                ns_per_element,
982            ),
983            Route::Spilled { axes, tiles: None } => replay_spilled_raw(
984                dst_ptr,
985                dst_base,
986                src_ptr,
987                src_base,
988                axes,
989                apply,
990                ns_per_element,
991                exec,
992            ),
993        }
994    }
995}
996
997/// Pointer-level fused replay shared by [`CopyPlan`], [`UpdatePlan`], the
998/// plan-free `replay_*_raw` entries and the dynamic slice plans, which replay
999/// a fused window layout at a runtime base offset.
1000///
1001/// Without `tiles`, splits `0..total` across the budget of `exec` when the
1002/// repository threshold allows more than one slot, otherwise runs the serial
1003/// kernel directly. With `tiles`, the box is walked tile by tile; a token on
1004/// which one fork pays splits it with the dimension splitter, and every leaf
1005/// walks its sub-box with the same tiles anchored at its origin.
1006///
1007/// # Safety
1008///
1009/// Every logical index of `layout`, mapped through its destination strides
1010/// from `dst_base` and its source strides from `src_base`, must be an
1011/// in-bounds slot of the destination and source allocations, and the product
1012/// of its extents must not overflow `usize`. `tiles`, when `Some`, must be
1013/// `pair_tiles::<D, S>(layout)`. When `tiles` is `Some` or `exec` is not
1014/// serial, the destination strides must be injective over `layout`; an
1015/// untiled serial replay updates a repeated slot once per logical index, in
1016/// order. The destination must not overlap the source, and nothing else may
1017/// access the destination slots during the call.
1018#[allow(clippy::too_many_arguments)]
1019pub(crate) unsafe fn replay_fused_raw<D, S, Apply>(
1020    dst_ptr: *mut D,
1021    dst_base: isize,
1022    src_ptr: *const S,
1023    src_base: isize,
1024    layout: &FusedPairLayout,
1025    tiles: Option<&PairTiles>,
1026    mut apply: Apply,
1027    ns_per_element: f64,
1028    exec: Exec<'_>,
1029) where
1030    D: Copy + Send + Sync,
1031    S: Copy + Send + Sync,
1032    Apply: Fn(&mut D, S) + Sync,
1033{
1034    let total = fused_total(layout);
1035    if total == 0 {
1036        return;
1037    }
1038    if let Some(tiles) = tiles {
1039        // SAFETY: forwarded caller contract; `tiles` addresses exactly the
1040        // slots of `layout` and the destination is injective over them.
1041        unsafe {
1042            replay_tiled(
1043                dst_ptr,
1044                dst_base,
1045                src_ptr,
1046                src_base,
1047                tiles,
1048                &apply,
1049                ns_per_element,
1050                exec,
1051            )
1052        };
1053        return;
1054    }
1055    let exec = crate::cost::for_len_at_rate(exec, total, ns_per_element);
1056    if !exec.is_serial() {
1057        let dst_ptr = crate::threading::SendPtr(dst_ptr);
1058        let src_ptr = crate::threading::SendPtr(src_ptr as *mut S);
1059        crate::threading::parallel_for_each(0..total, exec, &|range| {
1060            // SAFETY: the caller contract makes every index in bounds; the
1061            // token is not serial, so the destination strides are injective
1062            // and the disjoint worker ranges write disjoint slots; the source
1063            // is only read.
1064            unsafe {
1065                apply_fused_range(
1066                    dst_ptr.as_ptr(),
1067                    dst_base,
1068                    src_ptr.as_const(),
1069                    src_base,
1070                    layout,
1071                    range.start,
1072                    range.len(),
1073                    &mut &apply,
1074                );
1075            }
1076        });
1077        return;
1078    }
1079    // SAFETY: forwarded caller contract over the full range `0..total`; one
1080    // sequential walk needs no injectivity.
1081    unsafe {
1082        apply_fused_range(
1083            dst_ptr, dst_base, src_ptr, src_base, layout, 0, total, &mut apply,
1084        );
1085    }
1086}
1087
1088/// Tiled replay of [`replay_fused_raw`]: serially one [`apply_tiled_box`] over
1089/// the whole box, or, when one fork pays, the dimension splitter of the view
1090/// path with one [`apply_tiled_box`] per leaf box.
1091///
1092/// The leaves walk the model's own blocks clipped to the leaf, as Strided.jl's
1093/// leaves rerun `_mapreduce_kernel!` with the same `blocks`; the halved blocks
1094/// the splitter normalizes internally only steer where it may cut.
1095///
1096/// # Safety
1097///
1098/// The [`replay_fused_raw`] contract for `tiles.layout`, with an injective
1099/// destination.
1100#[inline(never)]
1101#[allow(clippy::too_many_arguments)]
1102unsafe fn replay_tiled<D, S, Apply>(
1103    dst_ptr: *mut D,
1104    dst_base: isize,
1105    src_ptr: *const S,
1106    src_base: isize,
1107    tiles: &PairTiles,
1108    apply: &Apply,
1109    ns_per_element: f64,
1110    exec: Exec<'_>,
1111) where
1112    D: Copy + Send + Sync,
1113    S: Copy + Send + Sync,
1114    Apply: Fn(&mut D, S) + Sync,
1115{
1116    let layout = &tiles.layout;
1117    let rank = layout.rank;
1118    let total = fused_total(layout);
1119    // The plan's rate, not the row: a footprint past the class's L2 pays here too
1120    // (strided-rs#364).
1121    if !crate::cost::is_parallel_at_rate(total, ns_per_element, &exec) {
1122        // SAFETY: forwarded caller contract over the whole box.
1123        unsafe {
1124            apply_tiled_box(
1125                dst_ptr,
1126                dst_base,
1127                src_ptr,
1128                src_base,
1129                layout,
1130                &tiles.blocks,
1131                &mut &*apply,
1132            )
1133        };
1134        return;
1135    }
1136    let strides = [&layout.dst_strides[..rank], &layout.src_strides[..rank]];
1137    let costs = crate::fuse::compute_costs(&strides);
1138    let dst_ptr = crate::threading::SendPtr(dst_ptr);
1139    let src_ptr = crate::threading::SendPtr(src_ptr as *mut S);
1140    #[cfg(test)]
1141    let leaves = std::sync::Mutex::new(Vec::new());
1142    let result = crate::threading::mapreduce_threaded_at_rate(
1143        &layout.dims[..rank],
1144        &tiles.blocks[..rank],
1145        &strides,
1146        &[dst_base, src_base],
1147        &costs,
1148        ns_per_element,
1149        exec,
1150        &|box_dims, _, _, offsets| {
1151            #[cfg(test)]
1152            if let Ok(mut leaves) = leaves.lock() {
1153                leaves.push((offsets[0], offsets[1], box_dims.to_vec()));
1154            }
1155            let mut leaf = *layout;
1156            leaf.dims[..rank].copy_from_slice(box_dims);
1157            // SAFETY: the splitter hands disjoint sub-boxes of `layout` with
1158            // the offsets of their origins, so every logical index of a leaf
1159            // is one of `layout`; the injective destination makes the leaves
1160            // write disjoint slots, and the source is only read.
1161            unsafe {
1162                apply_tiled_box(
1163                    dst_ptr.as_ptr(),
1164                    offsets[0],
1165                    src_ptr.as_const(),
1166                    offsets[1],
1167                    &leaf,
1168                    &tiles.blocks,
1169                    &mut &*apply,
1170                )
1171            };
1172            Ok(())
1173        },
1174    );
1175    // INVARIANT: the splitter fails only on an extent product beyond `usize`,
1176    // which the caller contract excludes, and the leaves never fail.
1177    debug_assert!(result.is_ok());
1178    #[cfg(test)]
1179    crate::threading::record_tiled_leaves(leaves.into_inner().unwrap_or_default());
1180}
1181
1182/// Tiled replay of a spilled axis list: serially one
1183/// [`apply_spilled_tiled_box`] over the whole box, or, when one fork pays, the
1184/// dimension splitter of the view path with one box walk per leaf box.
1185///
1186/// The spilled counterpart of [`replay_tiled`], on the slice-backed
1187/// [`SpilledTiles`]: same splitter, same per-leaf clipping of the model's own
1188/// blocks.
1189///
1190/// # Safety
1191///
1192/// The [`replay_spilled_raw`] contract for `tiles.dims`, with an injective
1193/// destination.
1194#[allow(clippy::too_many_arguments)]
1195#[inline(never)]
1196unsafe fn replay_spilled_tiled<D, S, Apply>(
1197    dst_ptr: *mut D,
1198    dst_base: isize,
1199    src_ptr: *const S,
1200    src_base: isize,
1201    tiles: &SpilledTiles,
1202    mut apply: Apply,
1203    exec: Exec<'_>,
1204    ns_per_element: f64,
1205) where
1206    D: Copy + Send + Sync,
1207    S: Copy + Send + Sync,
1208    Apply: Fn(&mut D, S) + Sync,
1209{
1210    let total = tiles.dims().iter().product::<usize>();
1211    if !crate::cost::is_parallel_at_rate(total, ns_per_element, &exec) {
1212        // SAFETY: forwarded caller contract over the whole box.
1213        unsafe {
1214            apply_spilled_tiled_box(
1215                dst_ptr,
1216                dst_base,
1217                src_ptr,
1218                src_base,
1219                tiles,
1220                tiles.dims(),
1221                &mut apply,
1222            )
1223        };
1224        return;
1225    }
1226    let strides = [tiles.dst(), tiles.src()];
1227    let costs = crate::fuse::compute_costs(&strides);
1228    let dst_ptr = crate::threading::SendPtr(dst_ptr);
1229    let src_ptr = crate::threading::SendPtr(src_ptr as *mut S);
1230    #[cfg(test)]
1231    let leaves = std::sync::Mutex::new(Vec::new());
1232    let result = crate::threading::mapreduce_threaded_at_rate(
1233        tiles.dims(),
1234        tiles.blocks(),
1235        &strides,
1236        &[dst_base, src_base],
1237        &costs,
1238        ns_per_element,
1239        exec,
1240        &|box_dims, _, _, offsets| {
1241            #[cfg(test)]
1242            if let Ok(mut leaves) = leaves.lock() {
1243                leaves.push((offsets[0], offsets[1], box_dims.to_vec()));
1244            }
1245            // SAFETY: the splitter hands disjoint sub-boxes of `tiles.dims`
1246            // with the offsets of their origins, so every logical index of a
1247            // leaf is one of the tiles' slots; the injective destination makes
1248            // the leaves write disjoint slots, and the source is only read.
1249            unsafe {
1250                apply_spilled_tiled_box(
1251                    dst_ptr.as_ptr(),
1252                    offsets[0],
1253                    src_ptr.as_const(),
1254                    offsets[1],
1255                    tiles,
1256                    box_dims,
1257                    &mut &apply,
1258                )
1259            };
1260            Ok(())
1261        },
1262    );
1263    // INVARIANT: the splitter fails only on an extent product beyond `usize`,
1264    // which the caller contract excludes, and the leaves never fail.
1265    debug_assert!(result.is_ok());
1266    #[cfg(test)]
1267    crate::threading::record_tiled_leaves(leaves.into_inner().unwrap_or_default());
1268}
1269
1270/// Pointer-level replay of a spilled axis list.
1271///
1272/// Mirrors [`replay_fused_raw`] including its worker split; kept separate so
1273/// that the inline replay keeps its fixed-rank shape.
1274///
1275/// # Safety
1276///
1277/// The [`replay_fused_raw`] contract, for `axes`.
1278#[allow(clippy::too_many_arguments)]
1279pub(crate) unsafe fn replay_spilled_raw<D, S, Apply>(
1280    dst_ptr: *mut D,
1281    dst_base: isize,
1282    src_ptr: *const S,
1283    src_base: isize,
1284    axes: &[FusedAxis],
1285    mut apply: Apply,
1286    ns_per_element: f64,
1287    exec: Exec<'_>,
1288) where
1289    D: Copy + Send + Sync,
1290    S: Copy + Send + Sync,
1291    Apply: Fn(&mut D, S) + Sync,
1292{
1293    let total = axes.iter().map(|axis| axis.dim).product::<usize>();
1294    if total == 0 {
1295        return;
1296    }
1297    let exec = crate::cost::for_len_at_rate(exec, total, ns_per_element);
1298    if !exec.is_serial() {
1299        let dst_ptr = crate::threading::SendPtr(dst_ptr);
1300        let src_ptr = crate::threading::SendPtr(src_ptr as *mut S);
1301        crate::threading::parallel_for_each(0..total, exec, &|range| {
1302            // SAFETY: as in `replay_fused_raw`: in-bounds indices, injective
1303            // destination for a non-serial token, disjoint worker ranges.
1304            unsafe {
1305                apply_spilled_range(
1306                    dst_ptr.as_ptr(),
1307                    dst_base,
1308                    src_ptr.as_const(),
1309                    src_base,
1310                    axes,
1311                    range.start,
1312                    range.len(),
1313                    &mut &apply,
1314                );
1315            }
1316        });
1317        return;
1318    }
1319    // SAFETY: forwarded caller contract over the full range `0..total`; one
1320    // sequential walk needs no injectivity.
1321    unsafe {
1322        apply_spilled_range(
1323            dst_ptr, dst_base, src_ptr, src_base, axes, 0, total, &mut apply,
1324        );
1325    }
1326}
1327
1328#[cfg(test)]
1329#[path = "copy_plan/tests/tests.rs"]
1330mod tests;
1331
1332#[cfg(test)]
1333#[path = "copy_plan/tests/parallel_tests.rs"]
1334mod parallel_tests;