Skip to main content

strided_basic/
kernel.rs

1//! Kernel iteration engine ported from Julia's Strided.jl/src/mapreduce.jl
2//!
3//! This module implements the core iteration engine that follows Julia's
4//! `_mapreduce_kernel!` pattern for cache-optimized strided array operations.
5
6use crate::fuse::{compress_dims, fuse_dims};
7use crate::inline::{InlineVec, OperandVec};
8use crate::{block, order, Exec, Result, StridedError};
9
10mod tile;
11
12/// Maximum total elements for the small tensor fast path.
13/// Tensors at or below this size skip `compute_order` and `compute_block_sizes`
14/// since they fit in L1 cache and blocking provides no benefit.
15pub const SMALL_TENSOR_THRESHOLD: usize = 1024;
16
17/// Blocking metadata produced by the execution planners; not a layout-validity proof.
18#[derive(Debug)]
19pub struct KernelPlan {
20    // `order` is only read by the `#[cfg(test)]` `for_each_inner_block` traversal.
21    #[cfg_attr(not(test), allow(dead_code))]
22    pub(crate) order: InlineVec<usize>, // inner -> outer
23    pub block: InlineVec<usize>,
24}
25
26/// Build an execution plan for strided iteration (used only in tests).
27///
28/// This follows Julia's `_mapreduce_order!` -> `_mapreduce_block!` pipeline
29/// without fusion:
30/// 1. Compute optimal iteration order
31/// 2. Reorder dims and strides into that order
32/// 3. Compute block sizes for cache efficiency
33#[cfg(test)]
34pub(crate) fn build_plan(
35    dims: &[usize],
36    strides_list: &[&[isize]],
37    dest_index: Option<usize>,
38    elem_sizes: &[usize],
39) -> KernelPlan {
40    let order = order::compute_order(dims, strides_list, dest_index);
41    let ordered_dims: InlineVec<usize> = order.iter().map(|&d| dims[d]).collect();
42    let ordered_strides: OperandVec<InlineVec<isize>> = strides_list
43        .iter()
44        .map(|strides| order.iter().map(|&d| strides[d]).collect())
45        .collect();
46    let ordered_strides_refs: OperandVec<&[isize]> =
47        ordered_strides.iter().map(|s| s.as_slice()).collect();
48    let block = block::compute_block_sizes(&ordered_dims, &ordered_strides_refs, elem_sizes);
49    KernelPlan { order, block }
50}
51
52/// The plan a typed pointwise operation runs: [`build_plan_fused_small`] for
53/// tensors at or below [`SMALL_TENSOR_THRESHOLD`], [`build_plan_fused`]
54/// otherwise, with `elem_sizes[k]` the element size of `strides_list[k]`.
55pub(crate) fn pointwise_plan(
56    dims: &[usize],
57    strides_list: &[&[isize]],
58    dest_index: Option<usize>,
59    elem_sizes: &[usize],
60    total: usize,
61) -> (InlineVec<usize>, OperandVec<InlineVec<isize>>, KernelPlan) {
62    debug_assert_eq!(strides_list.len(), elem_sizes.len());
63    if total <= SMALL_TENSOR_THRESHOLD {
64        build_plan_fused_small(dims, strides_list)
65    } else {
66        build_plan_fused(dims, strides_list, dest_index, elem_sizes)
67    }
68}
69
70/// Build an execution plan with dimension fusion.
71///
72/// Pipeline: order -> reorder -> fuse -> block.
73///
74/// Ordering first ensures that dimensions are sorted by stride importance
75/// (smallest stride innermost). Fusing *after* ordering catches contiguous
76/// dimensions regardless of the original memory layout (column-major,
77/// row-major, or any permutation).
78///
79/// Returns `(fused_dims, ordered_strides, KernelPlan)` where dimensions
80/// and strides are already in iteration order (plan.order is identity).
81///
82/// `elem_sizes[k]` is the element size in bytes of `strides_list[k]`; the
83/// block model forms `strides_list[k][i] * elem_sizes[k]` per operand.
84pub(crate) fn build_plan_fused(
85    dims: &[usize],
86    strides_list: &[&[isize]],
87    dest_index: Option<usize>,
88    elem_sizes: &[usize],
89) -> (InlineVec<usize>, OperandVec<InlineVec<isize>>, KernelPlan) {
90    plan_fused(dims, strides_list, dest_index, elem_sizes, dest_index)
91}
92
93/// [`pointwise_plan`] for a fold into one accumulator that orders its axes
94/// as if operand `order_by` were a destination (`dot`): the same order, fusion
95/// and model tiles, but never the L1 set fit, because a fold's tiles order its
96/// accumulation and must stay the model's (#287).
97pub(crate) fn fold_plan(
98    dims: &[usize],
99    strides_list: &[&[isize]],
100    order_by: usize,
101    elem_sizes: &[usize],
102    total: usize,
103) -> (InlineVec<usize>, OperandVec<InlineVec<isize>>, KernelPlan) {
104    debug_assert_eq!(strides_list.len(), elem_sizes.len());
105    if total <= SMALL_TENSOR_THRESHOLD {
106        build_plan_fused_small(dims, strides_list)
107    } else {
108        plan_fused(dims, strides_list, Some(order_by), elem_sizes, None)
109    }
110}
111
112/// [`build_plan_fused`] with the ordering operand and the destination the
113/// tiles are fitted for given apart; `fit_dest: None` keeps the model's tiles.
114fn plan_fused(
115    dims: &[usize],
116    strides_list: &[&[isize]],
117    dest_index: Option<usize>,
118    elem_sizes: &[usize],
119    fit_dest: Option<usize>,
120) -> (InlineVec<usize>, OperandVec<InlineVec<isize>>, KernelPlan) {
121    // 1. Compute optimal iteration order on original dims
122    let order = order::compute_order(dims, strides_list, dest_index);
123
124    // 2. Reorder dims and strides
125    let ordered_dims: InlineVec<usize> = order.iter().map(|&d| dims[d]).collect();
126    let ordered_strides: OperandVec<InlineVec<isize>> = strides_list
127        .iter()
128        .map(|strides| order.iter().map(|&d| strides[d]).collect())
129        .collect();
130    let ordered_strides_refs: OperandVec<&[isize]> =
131        ordered_strides.iter().map(|s| s.as_slice()).collect();
132
133    // 3. Fuse contiguous dimensions in ordered space
134    let fused_dims = fuse_dims(&ordered_dims, &ordered_strides_refs);
135
136    // 4. Compress: remove size-1 dimensions to reduce loop depth
137    let (compressed_dims, compressed_strides) = compress_dims(&fused_dims, &ordered_strides_refs);
138    let compressed_strides_refs: OperandVec<&[isize]> =
139        compressed_strides.iter().map(|s| s.as_slice()).collect();
140
141    // 5. Compute blocks on the already ordered axes. With a destination the
142    // tiles are also fitted to the L1 sets (#287); a fold keeps the model's
143    // tiles, which order its single accumulator.
144    let identity: InlineVec<usize> = (0..compressed_dims.len()).collect();
145    let block = match fit_dest {
146        // A small tile under one long axis is blocked on the long axis only
147        // (strided-rs#526); every other destination plan takes the model.
148        Some(dest) => tile::tile_blocks(&compressed_dims, elem_sizes).unwrap_or_else(|| {
149            block::destination_block_sizes(
150                &compressed_dims,
151                &compressed_strides_refs,
152                elem_sizes,
153                dest,
154            )
155        }),
156        None => block::compute_block_sizes(&compressed_dims, &compressed_strides_refs, elem_sizes),
157    };
158    #[cfg(feature = "bench-hooks")]
159    let block = {
160        let forced = crate::bench_hooks::FORCED_TILES.lock().unwrap();
161        if fit_dest.is_some() && forced.len() == block.len() {
162            InlineVec::from(forced.as_slice())
163        } else {
164            block
165        }
166    };
167
168    (
169        compressed_dims,
170        compressed_strides,
171        KernelPlan {
172            order: identity,
173            block,
174        },
175    )
176}
177
178/// Simplified plan for small tensors that fit in L1 cache.
179///
180/// Skips `compute_order` and `compute_block_sizes` since blocking is
181/// unnecessary for small data. Only fuses and compresses dimensions
182/// to reduce loop depth.
183///
184/// Returns `(fused_dims, fused_strides, KernelPlan)` where the plan's
185/// order is identity and block sizes equal the full dimension sizes.
186pub(crate) fn build_plan_fused_small(
187    dims: &[usize],
188    strides_list: &[&[isize]],
189) -> (InlineVec<usize>, OperandVec<InlineVec<isize>>, KernelPlan) {
190    // Single fuse + compress pass (no ordering needed)
191    let fused = fuse_dims(dims, strides_list);
192    let (fused_dims, fused_strides) = compress_dims(&fused, strides_list);
193
194    // Block = full dimension (no tiling)
195    let block = fused_dims.clone();
196    let identity: InlineVec<usize> = (0..fused_dims.len()).collect();
197
198    (
199        fused_dims,
200        fused_strides,
201        KernelPlan {
202            order: identity,
203            block,
204        },
205    )
206}
207
208// ============================================================================
209// Block-based iteration with inner stride callback
210// ============================================================================
211
212/// Iterate over blocks, calling f with (offsets, block_len, inner_strides).
213///
214/// The callback receives the current byte offsets for each array, the number
215/// of elements in the innermost block, and the innermost strides for each array.
216/// This allows the caller to implement vectorized inner loops.
217#[cfg(test)]
218#[inline]
219pub(crate) fn for_each_inner_block<F>(
220    dims: &[usize],
221    plan: &KernelPlan,
222    strides_list: &[&[isize]],
223    mut f: F,
224) -> Result<()>
225where
226    F: FnMut(&[isize], usize, &[isize]) -> Result<()>,
227{
228    let rank = dims.len();
229    if rank == 0 {
230        let offsets: OperandVec<isize> = strides_list.iter().map(|_| 0isize).collect();
231        return f(&offsets, 1, &[]);
232    }
233
234    // Reorder dimensions and strides according to plan
235    let ordered_dims: InlineVec<usize> = plan.order.iter().map(|&d| dims[d]).collect();
236    let ordered_blocks: InlineVec<usize> = plan.block.clone();
237
238    // Build stride vectors for each array, ordered by plan
239    let mut ordered_strides: OperandVec<InlineVec<isize>> = OperandVec::new();
240    for strides in strides_list {
241        ordered_strides.push(plan.order.iter().map(|&d| strides[d]).collect());
242    }
243    let ordered_strides_refs: OperandVec<&[isize]> =
244        ordered_strides.iter().map(|s| s.as_slice()).collect();
245
246    // Initial offsets (all zero)
247    let mut offsets: OperandVec<isize> = strides_list.iter().map(|_| 0isize).collect();
248
249    // Call the specialized kernel based on rank
250    match rank {
251        1 => kernel_1d_inner(
252            &ordered_dims,
253            &ordered_blocks,
254            &ordered_strides_refs,
255            &mut offsets,
256            &mut f,
257        ),
258        2 => kernel_2d_inner(
259            &ordered_dims,
260            &ordered_blocks,
261            &ordered_strides_refs,
262            &mut offsets,
263            &mut f,
264        ),
265        3 => kernel_3d_inner(
266            &ordered_dims,
267            &ordered_blocks,
268            &ordered_strides_refs,
269            &mut offsets,
270            &mut f,
271        ),
272        4 => kernel_4d_inner(
273            &ordered_dims,
274            &ordered_blocks,
275            &ordered_strides_refs,
276            &mut offsets,
277            &mut f,
278        ),
279        5 => kernel_5d_inner(
280            &ordered_dims,
281            &ordered_blocks,
282            &ordered_strides_refs,
283            &mut offsets,
284            &mut f,
285        ),
286        6 => kernel_6d_inner(
287            &ordered_dims,
288            &ordered_blocks,
289            &ordered_strides_refs,
290            &mut offsets,
291            &mut f,
292        ),
293        7 => kernel_7d_inner(
294            &ordered_dims,
295            &ordered_blocks,
296            &ordered_strides_refs,
297            &mut offsets,
298            &mut f,
299        ),
300        8 => kernel_8d_inner(
301            &ordered_dims,
302            &ordered_blocks,
303            &ordered_strides_refs,
304            &mut offsets,
305            &mut f,
306        ),
307        _ => kernel_nd_inner_iterative(
308            &ordered_dims,
309            &ordered_blocks,
310            &ordered_strides_refs,
311            &mut offsets,
312            &mut f,
313        ),
314    }
315}
316
317// ============================================================================
318// Macro-generated rank-specialized kernels (inner-block callback)
319// ============================================================================
320
321// Every loop below advances an offset only when another position along its
322// level follows, and each loop rewinds its own level on completion. Offsets
323// therefore only ever hold reachable positions of the validated layouts (plus
324// the caller's initial offsets), so no intermediate value can overflow even
325// when a layout ends within one stride of `isize::MAX` (issue #243
326// follow-up). The rewind distance is the difference of two reachable offsets,
327// so it is representable as well.
328
329/// Element-level nested loops for ranks >= 2.
330///
331/// Iterates over the element block, calling `f` at each innermost position.
332/// Levels are listed from outermost to innermost (excluding level 0 which is
333/// the callback level). For a rank-N kernel, element levels are N-1, N-2, ..., 1.
334/// Each level leaves the offsets where it found them.
335macro_rules! elem_loops {
336    // Base case: single level (innermost element level).
337    // Iterates blens[$lv] times, calling f and advancing by stride[$lv]
338    // between calls.
339    ($offsets:ident, $strides:ident, $f:ident, $blens:ident, $is:ident; $lv:literal) => {
340        for _i in 0..$blens[$lv] {
341            $f($offsets, $blens[0], &$is)?;
342            if _i + 1 < $blens[$lv] {
343                for (o, s) in $offsets.iter_mut().zip($strides.iter()) {
344                    *o += s[$lv];
345                }
346            }
347        }
348        let _back = $blens[$lv].saturating_sub(1) as isize;
349        for (o, s) in $offsets.iter_mut().zip($strides.iter()) {
350            *o -= _back * s[$lv];
351        }
352    };
353    // Recursive case: outermost level wraps inner levels, which rewind
354    // themselves; this level advances between inner passes.
355    ($offsets:ident, $strides:ident, $f:ident, $blens:ident, $is:ident;
356     $lv:literal, $next:literal $(, $rest:literal)*) => {
357        for _i in 0..$blens[$lv] {
358            elem_loops!($offsets, $strides, $f, $blens, $is; $next $(, $rest)*);
359            if _i + 1 < $blens[$lv] {
360                for (o, s) in $offsets.iter_mut().zip($strides.iter()) {
361                    *o += s[$lv];
362                }
363            }
364        }
365        let _back = $blens[$lv].saturating_sub(1) as isize;
366        for (o, s) in $offsets.iter_mut().zip($strides.iter()) {
367            *o -= _back * s[$lv];
368        }
369    };
370}
371
372/// Block-level nested while loops for ranks >= 2.
373///
374/// Each block level iterates over tiles of the corresponding dimension.
375/// At level 0 (innermost), element loops are executed. Each block level
376/// advances to the next tile only when one follows and rewinds itself on
377/// completion; inner levels rewind themselves.
378macro_rules! block_loop {
379    // Base case: single block level (the innermost).
380    ($dims:ident, $blocks:ident, $strides:ident, $offsets:ident, $f:ident,
381     $blens:ident, $is:ident; elem=[$($el:literal),+]; $lv0:literal; top=$top:literal) => {{
382        let mut _j = 0usize;
383        let mut _advanced = 0usize;
384        while _j < $dims[$lv0] {
385            $blens[$lv0] = $blocks[$lv0].max(1).min($dims[$lv0]).min($dims[$lv0] - _j);
386            elem_loops!($offsets, $strides, $f, $blens, $is; $($el),+);
387            _j += $blens[$lv0];
388            if _j < $dims[$lv0] {
389                for (o, s) in $offsets.iter_mut().zip($strides.iter()) {
390                    *o += ($blens[$lv0] as isize) * s[$lv0];
391                }
392                _advanced = _j;
393            }
394        }
395        for (o, s) in $offsets.iter_mut().zip($strides.iter()) {
396            *o -= (_advanced as isize) * s[$lv0];
397        }
398    }};
399    // Recursive case: outer block level wraps inner block levels.
400    ($dims:ident, $blocks:ident, $strides:ident, $offsets:ident, $f:ident,
401     $blens:ident, $is:ident; elem=[$($el:literal),+];
402     $lv:literal, $next:literal $(, $rest:literal)*; top=$top:literal) => {{
403        let mut _j = 0usize;
404        let mut _advanced = 0usize;
405        while _j < $dims[$lv] {
406            $blens[$lv] = $blocks[$lv].max(1).min($dims[$lv]).min($dims[$lv] - _j);
407            block_loop!($dims, $blocks, $strides, $offsets, $f, $blens, $is;
408                elem=[$($el),+]; $next $(, $rest)*; top=$top);
409            _j += $blens[$lv];
410            if _j < $dims[$lv] {
411                for (o, s) in $offsets.iter_mut().zip($strides.iter()) {
412                    *o += ($blens[$lv] as isize) * s[$lv];
413                }
414                _advanced = _j;
415            }
416        }
417        for (o, s) in $offsets.iter_mut().zip($strides.iter()) {
418            *o -= (_advanced as isize) * s[$lv];
419        }
420    }};
421}
422
423/// Generate a rank-specialized kernel function.
424///
425/// For rank 1 there are no element loops; only a single block loop on dim 0.
426/// For rank >= 2, block loops nest from outermost to innermost (dim 0), and
427/// element loops nest from dim N-1 down to dim 1 inside the innermost block.
428/// The offsets are back at their starting values on return.
429macro_rules! make_kernel {
430    // Rank 1: single block loop, no element nesting.
431    ($name:ident, rank=1) => {
432        #[inline]
433        fn $name<F>(
434            dims: &[usize],
435            blocks: &[usize],
436            strides: &[&[isize]],
437            offsets: &mut [isize],
438            f: &mut F,
439        ) -> Result<()>
440        where
441            F: FnMut(&[isize], usize, &[isize]) -> Result<()>,
442        {
443            let d0 = dims[0];
444            let b0 = blocks[0].max(1).min(d0);
445            let inner_strides: OperandVec<isize> = strides.iter().map(|s| s[0]).collect();
446
447            let mut j0 = 0usize;
448            let mut advanced = 0usize;
449            while j0 < d0 {
450                let blen0 = b0.min(d0 - j0);
451                f(offsets, blen0, &inner_strides)?;
452                j0 += blen0;
453                if j0 < d0 {
454                    for (o, s) in offsets.iter_mut().zip(strides.iter()) {
455                        *o += (blen0 as isize) * s[0];
456                    }
457                    advanced = j0;
458                }
459            }
460            for (o, s) in offsets.iter_mut().zip(strides.iter()) {
461                *o -= (advanced as isize) * s[0];
462            }
463            Ok(())
464        }
465    };
466    // Rank >= 2: nested block loops + element loops.
467    //   block=[outermost, ..., 0]  - block loop levels from outermost to innermost
468    //   elem=[N-1, ..., 1]         - element loop levels from outermost to innermost
469    //   top=N-1                    - topmost element level (= rank - 1)
470    ($name:ident, rank=$rank:literal,
471     block=[$($blk:literal),+], elem=[$($el:literal),+], top=$top:literal) => {
472        #[inline]
473        fn $name<F>(
474            dims: &[usize],
475            blocks: &[usize],
476            strides: &[&[isize]],
477            offsets: &mut [isize],
478            f: &mut F,
479        ) -> Result<()>
480        where
481            F: FnMut(&[isize], usize, &[isize]) -> Result<()>,
482        {
483            let inner_strides: OperandVec<isize> = strides.iter().map(|s| s[0]).collect();
484            let mut blens = [0usize; $rank];
485            block_loop!(dims, blocks, strides, offsets, f, blens, inner_strides;
486                elem=[$($el),+]; $($blk),+; top=$top);
487            Ok(())
488        }
489    };
490}
491
492make_kernel!(kernel_1d_inner, rank = 1);
493make_kernel!(
494    kernel_2d_inner,
495    rank = 2,
496    block = [1, 0],
497    elem = [1],
498    top = 1
499);
500make_kernel!(
501    kernel_3d_inner,
502    rank = 3,
503    block = [2, 1, 0],
504    elem = [2, 1],
505    top = 2
506);
507make_kernel!(
508    kernel_4d_inner,
509    rank = 4,
510    block = [3, 2, 1, 0],
511    elem = [3, 2, 1],
512    top = 3
513);
514make_kernel!(
515    kernel_5d_inner,
516    rank = 5,
517    block = [4, 3, 2, 1, 0],
518    elem = [4, 3, 2, 1],
519    top = 4
520);
521make_kernel!(
522    kernel_6d_inner,
523    rank = 6,
524    block = [5, 4, 3, 2, 1, 0],
525    elem = [5, 4, 3, 2, 1],
526    top = 5
527);
528make_kernel!(
529    kernel_7d_inner,
530    rank = 7,
531    block = [6, 5, 4, 3, 2, 1, 0],
532    elem = [6, 5, 4, 3, 2, 1],
533    top = 6
534);
535make_kernel!(
536    kernel_8d_inner,
537    rank = 8,
538    block = [7, 6, 5, 4, 3, 2, 1, 0],
539    elem = [7, 6, 5, 4, 3, 2, 1],
540    top = 7
541);
542
543/// N-dimensional kernel with inner block callback (iterative form).
544///
545/// Fallback for rank >= 9. Uses a carry-style increment over outer levels
546/// instead of compile-time unrolled nested loops.
547#[inline]
548fn kernel_nd_inner_iterative<F>(
549    dims: &[usize],
550    blocks: &[usize],
551    strides: &[&[isize]],
552    offsets: &mut [isize],
553    f: &mut F,
554) -> Result<()>
555where
556    F: FnMut(&[isize], usize, &[isize]) -> Result<()>,
557{
558    let rank = dims.len();
559    debug_assert!(rank >= 9);
560
561    let d0 = dims[0];
562    let b0 = blocks[0].max(1).min(d0);
563    let inner_strides: OperandVec<isize> = strides.iter().map(|s| s[0]).collect();
564
565    // Current position for each outer level (1..rank-1). Level 0 uses block loop.
566    let mut idx: Vec<usize> = vec![0usize; rank];
567
568    // As in the rank-specialized kernels, offsets advance only when another
569    // position follows and each level rewinds from its last position, so they
570    // never leave the reachable span.
571    if dims.contains(&0) {
572        return Ok(());
573    }
574    loop {
575        // Level 0: callback over contiguous block fragments.
576        let mut j0 = 0usize;
577        let mut advanced = 0usize;
578        while j0 < d0 {
579            let blen0 = b0.min(d0 - j0);
580            f(offsets, blen0, &inner_strides)?;
581            j0 += blen0;
582            if j0 < d0 {
583                for (offset, s) in offsets.iter_mut().zip(strides.iter()) {
584                    *offset += (blen0 as isize) * s[0];
585                }
586                advanced = j0;
587            }
588        }
589        for (offset, s) in offsets.iter_mut().zip(strides.iter()) {
590            *offset -= (advanced as isize) * s[0];
591        }
592
593        // Carry-style increment for outer levels.
594        let mut level = 1usize;
595        loop {
596            if idx[level] + 1 < dims[level] {
597                idx[level] += 1;
598                for (offset, s) in offsets.iter_mut().zip(strides.iter()) {
599                    *offset += s[level];
600                }
601                break;
602            }
603
604            let last = (dims[level] - 1) as isize;
605            idx[level] = 0;
606            for (offset, s) in offsets.iter_mut().zip(strides.iter()) {
607                *offset -= last * s[level];
608            }
609            level += 1;
610            if level == rank {
611                return Ok(());
612            }
613        }
614    }
615}
616
617// ============================================================================
618// Pre-ordered iteration (for threaded leaf functions)
619// ============================================================================
620
621/// Iterate over blocks with pre-ordered dimensions and initial offsets.
622///
623/// Unlike `for_each_inner_block`, this function assumes that `dims`, `blocks`,
624/// and `strides` are **already in iteration order** (i.e., identity ordering).
625/// It also accepts `initial_offsets` which are added to the starting offsets
626/// before iteration begins.
627///
628/// This avoids the redundant re-ordering and per-callback `Vec` allocation
629/// that `for_each_inner_block_with_offsets` previously incurred.
630///
631/// The block-walking machinery is compiled once (`preordered_walk`): a generic
632/// caller only instantiates its own callback, reached through one indirect call
633/// per inner block (a run of elements, never per element). Keeping the walk
634/// generic would duplicate it for every operation, dtype and element-op
635/// combination of every downstream crate.
636#[inline]
637pub(crate) fn for_each_inner_block_preordered<S: AsRef<[isize]>, F>(
638    dims: &[usize],
639    blocks: &[usize],
640    strides: &[S],
641    initial_offsets: &[isize],
642    mut f: F,
643) -> Result<()>
644where
645    F: FnMut(&[isize], usize, &[isize]) -> Result<()>,
646{
647    let refs: OperandVec<&[isize]> = strides.iter().map(|s| s.as_ref()).collect();
648    preordered_walk(dims, blocks, &refs, initial_offsets, &mut f)
649}
650
651/// [`for_each_inner_block_preordered`] for a pointwise operation: every
652/// destination element is computed from its own inputs and written once, so
653/// the order in which the runs are visited does not change the result.
654///
655/// A plan whose leading axes form a small unfusable tile under a long axis
656/// (the per-block transpose of strided-rs#526) is walked by
657/// [`tile::SmallTile`]: one callback per tile element over an L1 block of the
658/// long axis instead of one per innermost run of the tile. Every element still
659/// reaches `f` exactly once with the same per-element operands; only the order
660/// of the runs, and how the long axis is cut into runs, differs. Folds and
661/// any other order-dependent caller use [`for_each_inner_block_preordered`].
662#[inline]
663pub(crate) fn for_each_pointwise_block_preordered<S: AsRef<[isize]>, F>(
664    dims: &[usize],
665    blocks: &[usize],
666    strides: &[S],
667    initial_offsets: &[isize],
668    mut f: F,
669) -> Result<()>
670where
671    F: FnMut(&[isize], usize, &[isize]) -> Result<()>,
672{
673    let refs: OperandVec<&[isize]> = strides.iter().map(|s| s.as_ref()).collect();
674    if let Some(tile) = tile::SmallTile::of(dims, blocks, &refs) {
675        return tile.walk(dims, blocks, &refs, initial_offsets, &mut f);
676    }
677    preordered_walk(dims, blocks, &refs, initial_offsets, &mut f)
678}
679
680type BlockFn<'a> = &'a mut dyn FnMut(&[isize], usize, &[isize]) -> Result<()>;
681
682#[inline(never)]
683fn preordered_walk(
684    dims: &[usize],
685    blocks: &[usize],
686    strides: &[&[isize]],
687    initial_offsets: &[isize],
688    mut f: BlockFn<'_>,
689) -> Result<()> {
690    let rank = dims.len();
691    if rank == 0 {
692        return f(initial_offsets, 1, &[]);
693    }
694
695    // Start from initial_offsets (kernel functions reset to starting values at end)
696    let mut offsets: OperandVec<isize> = initial_offsets.iter().copied().collect();
697
698    match rank {
699        1 => kernel_1d_inner(dims, blocks, strides, &mut offsets, &mut f),
700        2 => kernel_2d_inner(dims, blocks, strides, &mut offsets, &mut f),
701        3 => kernel_3d_inner(dims, blocks, strides, &mut offsets, &mut f),
702        4 => kernel_4d_inner(dims, blocks, strides, &mut offsets, &mut f),
703        5 => kernel_5d_inner(dims, blocks, strides, &mut offsets, &mut f),
704        6 => kernel_6d_inner(dims, blocks, strides, &mut offsets, &mut f),
705        7 => kernel_7d_inner(dims, blocks, strides, &mut offsets, &mut f),
706        8 => kernel_8d_inner(dims, blocks, strides, &mut offsets, &mut f),
707        _ => kernel_nd_inner_iterative(dims, blocks, strides, &mut offsets, &mut f),
708    }
709}
710
711// ============================================================================
712// Utility functions
713// ============================================================================
714
715/// Check exact shape agreement before prevalidated replay.
716///
717/// # Examples
718///
719/// ```
720/// use strided_basic::execution::ensure_same_shape;
721/// ensure_same_shape(&[2, 3], &[2, 3]).unwrap();
722/// assert!(ensure_same_shape(&[2, 3], &[3, 2]).is_err());
723/// ```
724///
725/// # Errors
726///
727/// Returns [`StridedError::RankMismatch`] when the two shapes have different
728/// ranks, and [`StridedError::ShapeMismatch`] when their extents differ.
729pub fn ensure_same_shape(a: &[usize], b: &[usize]) -> Result<()> {
730    if a.len() != b.len() {
731        return Err(crate::StridedError::RankMismatch(a.len(), b.len()));
732    }
733    if a != b {
734        return Err(crate::StridedError::ShapeMismatch(a.to_vec(), b.to_vec()));
735    }
736    Ok(())
737}
738
739#[derive(Copy, Clone, Debug, Eq, PartialEq)]
740pub(crate) enum ContiguousLayout {
741    /// C-like layout: last axis varies fastest.
742    RowMajor,
743    /// Julia/Fortran-like layout: first axis varies fastest.
744    ColMajor,
745}
746
747/// Returns the contiguous memory layout kind for the given (dims, strides).
748///
749/// Notes:
750/// - Ignores axes with `dim <= 1` since they do not affect addressability.
751/// - Does not treat negative-stride views as contiguous for fast-path purposes.
752pub(crate) fn contiguous_layout(dims: &[usize], strides: &[isize]) -> Option<ContiguousLayout> {
753    if dims.len() != strides.len() {
754        return None;
755    }
756    if dims.is_empty() {
757        return Some(ContiguousLayout::RowMajor);
758    }
759
760    // Row-major: check from last to first.
761    let mut expected = 1isize;
762    let mut row_ok = true;
763    for (&dim, &stride) in dims.iter().rev().zip(strides.iter().rev()) {
764        if dim <= 1 {
765            continue;
766        }
767        if stride != expected {
768            row_ok = false;
769            break;
770        }
771        expected = expected.saturating_mul(dim as isize);
772    }
773    if row_ok {
774        return Some(ContiguousLayout::RowMajor);
775    }
776
777    // Col-major: check from first to last.
778    let mut expected = 1isize;
779    for (&dim, &stride) in dims.iter().zip(strides.iter()) {
780        if dim <= 1 {
781            continue;
782        }
783        if stride != expected {
784            return None;
785        }
786        expected = expected.saturating_mul(dim as isize);
787    }
788    Some(ContiguousLayout::ColMajor)
789}
790
791/// Checked element count of `dims`.
792///
793/// A shape containing a zero extent has zero elements even when the product
794/// of its other extents would overflow; such views pass
795/// `strided_view::validate_bounds`, so this must not form that product. A
796/// nonempty shape whose element count exceeds `usize::MAX` (for example a
797/// huge stride-0 broadcast) returns [`StridedError::OffsetOverflow`].
798pub(crate) fn total_len(dims: &[usize]) -> Result<usize> {
799    if dims.contains(&0) {
800        return Ok(0);
801    }
802    dims.iter()
803        .try_fold(1usize, |acc, &dim| acc.checked_mul(dim))
804        .ok_or(StridedError::OffsetOverflow)
805}
806
807/// Whether the sequential contiguous fast path should be used.
808///
809/// When a fork over `total` elements of `class` pays and `exec` has a second slot,
810/// the contiguous fast path must not be taken so that the parallel kernel path
811/// can be reached. A serial token has no threaded path to reach and the
812/// sequential slice loop is the right kernel.
813#[inline]
814pub(crate) fn use_sequential_fast_path(
815    class: crate::cost::KernelClass,
816    total: usize,
817    exec: &Exec<'_>,
818) -> bool {
819    !crate::threading::is_parallel(class, total, exec)
820}
821
822/// Returns the common contiguous layout if **all** provided stride arrays
823/// share the same contiguous layout for the given `dims`.
824///
825/// Returns `None` if `strides_list` is empty, any array is not contiguous,
826/// or any two arrays have different contiguous layouts.
827#[inline]
828pub(crate) fn same_contiguous_layout(
829    dims: &[usize],
830    strides_list: &[&[isize]],
831) -> Option<ContiguousLayout> {
832    let first = contiguous_layout(dims, strides_list.first()?)?;
833    for strides in &strides_list[1..] {
834        if contiguous_layout(dims, strides)? != first {
835            return None;
836        }
837    }
838    Some(first)
839}
840
841/// Returns the common contiguous layout only when the sequential fast path
842/// should be used (a fork over the elements does not pay for `class`, or a serial token).
843///
844/// `class` is the cost class of the kernel the caller would otherwise fork:
845/// a copy asks as `Copy`, a reduction as `Reduce`, an element map as `Map`.
846///
847/// Returns [`StridedError::OffsetOverflow`] when the element count of `dims`
848/// does not fit in `usize`.
849#[inline]
850pub(crate) fn sequential_contiguous_layout(
851    class: crate::cost::KernelClass,
852    dims: &[usize],
853    strides_list: &[&[isize]],
854    exec: &Exec<'_>,
855) -> Result<Option<ContiguousLayout>> {
856    if !use_sequential_fast_path(class, total_len(dims)?, exec) {
857        return Ok(None);
858    }
859    Ok(same_contiguous_layout(dims, strides_list))
860}
861
862#[cfg(test)]
863#[path = "kernel/tests/tests.rs"]
864mod tests;