Skip to main content

strided_perm/
fuse.rs

1//! Dimension fusion logic ported from Strided.jl/src/mapreduce.jl
2//!
3//! This module implements the core dimension fusion algorithm that merges
4//! contiguous dimensions to reduce iteration complexity.
5
6use strided_view::INLINE_RANK;
7use tinyvec::TinyVec;
8
9/// Fused axis extents, inline up to [`INLINE_RANK`].
10///
11/// Part of the public [`BilateralFusionPlan`]; a rank above the inline
12/// capacity spills to the heap instead of erroring.
13pub type FusionDimVec = TinyVec<[usize; INLINE_RANK]>;
14
15/// Fused source or destination strides, inline up to [`INLINE_RANK`].
16pub type FusionStrideVec = TinyVec<[isize; INLINE_RANK]>;
17
18/// Validated result of fusing adjacent dimensions that are contiguous in
19/// both source and destination layouts.
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct BilateralFusionPlan {
22    /// Fused non-trivial dimensions in iteration order.
23    pub dims: FusionDimVec,
24    /// Source strides corresponding to [`Self::dims`].
25    pub src_strides: FusionStrideVec,
26    /// Destination strides corresponding to [`Self::dims`].
27    pub dst_strides: FusionStrideVec,
28}
29
30/// Failure while validating or constructing a bilateral fusion plan.
31#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
32pub enum FusionPlanError {
33    /// Shape and stride ranks do not agree.
34    #[error(
35        "metadata lengths differ: dims={dims}, src_strides={src_strides}, \
36         dst_strides={dst_strides}"
37    )]
38    LengthMismatch {
39        /// Number of dimensions.
40        dims: usize,
41        /// Number of source strides.
42        src_strides: usize,
43        /// Number of destination strides.
44        dst_strides: usize,
45    },
46    /// A dimension cannot be represented for stride arithmetic, or a fused
47    /// dimension product exceeds `usize`.
48    #[error("fused dimension product overflows usize")]
49    DimensionOverflow,
50}
51
52/// Plan bilateral dimension fusion for source and destination layouts.
53///
54/// Size-one axes are removed. Two remaining adjacent axes are fused only when
55/// each layout is affine-contiguous across the boundary. Negative strides are
56/// supported; stride multiplication overflow simply prevents fusion.
57///
58/// # Errors
59///
60/// Returns [`FusionPlanError::LengthMismatch`] when the metadata ranks differ,
61/// and [`FusionPlanError::DimensionOverflow`] when a dimension cannot
62/// participate safely in `isize` stride arithmetic or a fused extent
63/// overflows `usize`.
64pub fn plan_bilateral_fusion(
65    dims: &[usize],
66    src_strides: &[isize],
67    dst_strides: &[isize],
68) -> Result<BilateralFusionPlan, FusionPlanError> {
69    if dims.len() != src_strides.len() || dims.len() != dst_strides.len() {
70        return Err(FusionPlanError::LengthMismatch {
71            dims: dims.len(),
72            src_strides: src_strides.len(),
73            dst_strides: dst_strides.len(),
74        });
75    }
76
77    let mut plan = BilateralFusionPlan {
78        dims: FusionDimVec::with_capacity(dims.len()),
79        src_strides: FusionStrideVec::with_capacity(dims.len()),
80        dst_strides: FusionStrideVec::with_capacity(dims.len()),
81    };
82
83    for ((&dim, &src_stride), &dst_stride) in dims.iter().zip(src_strides).zip(dst_strides) {
84        if dim == 1 {
85            continue;
86        }
87        isize::try_from(dim).map_err(|_| FusionPlanError::DimensionOverflow)?;
88
89        if let Some(last) = plan.dims.len().checked_sub(1) {
90            let current_dim =
91                isize::try_from(plan.dims[last]).map_err(|_| FusionPlanError::DimensionOverflow)?;
92            let src_contiguous = plan.src_strides[last]
93                .checked_mul(current_dim)
94                .is_some_and(|expected| src_stride == expected);
95            let dst_contiguous = plan.dst_strides[last]
96                .checked_mul(current_dim)
97                .is_some_and(|expected| dst_stride == expected);
98
99            if src_contiguous && dst_contiguous {
100                plan.dims[last] = plan.dims[last]
101                    .checked_mul(dim)
102                    .ok_or(FusionPlanError::DimensionOverflow)?;
103                continue;
104            }
105        }
106
107        plan.dims.push(dim);
108        plan.src_strides.push(src_stride);
109        plan.dst_strides.push(dst_stride);
110    }
111
112    Ok(plan)
113}
114
115#[cfg(test)]
116mod tests;