Skip to main content

cubek_test_utils/test_tensor/
strides.rs

1use cubecl::zspace::{Shape, Strides};
2
3/// How the base strides of a tensor are laid out before any tile-level rank
4/// expansion is applied.
5#[derive(Debug, Clone, PartialEq, Eq, Default)]
6pub enum StridedLayout {
7    #[default]
8    RowMajor,
9    ColMajor,
10    Explicit(Vec<usize>),
11}
12
13/// The layout of a test tensor: a base [`StridedLayout`] that drives the
14/// physical strides.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum LayoutSpec {
17    Strided(StridedLayout),
18}
19
20impl Default for LayoutSpec {
21    fn default() -> Self {
22        Self::Strided(StridedLayout::default())
23    }
24}
25
26impl LayoutSpec {
27    /// The base stride layout.
28    pub fn base(&self) -> &StridedLayout {
29        match self {
30            LayoutSpec::Strided(base) => base,
31        }
32    }
33
34    /// Compute the strides of the layout for `shape`.
35    pub fn compute_strides(&self, shape: &Shape) -> Strides {
36        self.base().compute_strides(shape)
37    }
38}
39
40impl From<StridedLayout> for LayoutSpec {
41    fn from(base: StridedLayout) -> Self {
42        Self::Strided(base)
43    }
44}
45
46/// Number of elements in the physical buffer required to cover every logical
47/// index in `shape` under `strides`, assuming element 0 is at offset 0.
48///
49/// Exceeds `shape.iter().product()` for jumpy strides (e.g. a slice stepping
50/// over padding) and is less than it for broadcast strides (a stride of 0
51/// makes every index in that dim share the same physical offset).
52pub fn physical_extent(shape: &Shape, strides: &Strides) -> usize {
53    let mut max_offset = 0usize;
54    for (s, d) in strides.iter().zip(shape.iter()) {
55        if *d > 0 && *s > 0 {
56            max_offset += (d - 1) * s;
57        }
58    }
59    max_offset + 1
60}
61
62impl StridedLayout {
63    pub fn compute_strides(&self, shape: &Shape) -> Strides {
64        let n = shape.len();
65        match self {
66            StridedLayout::RowMajor => {
67                assert!(n >= 1, "RowMajor requires at least 1 dimension");
68                let mut strides = vec![0; n];
69                strides[n - 1] = 1;
70                for i in (0..n - 1).rev() {
71                    strides[i] = strides[i + 1] * shape[i + 1];
72                }
73                Strides::new(&strides)
74            }
75            StridedLayout::ColMajor => {
76                assert!(n >= 2, "ColMajor requires at least 2 dimensions");
77                let mut strides = vec![0; n];
78                strides[n - 2] = 1;
79                strides[n - 1] = shape[n - 2];
80                for i in (0..n - 2).rev() {
81                    strides[i] = strides[i + 1] * shape[i + 1];
82                }
83                Strides::new(&strides)
84            }
85            StridedLayout::Explicit(strides) => {
86                assert!(
87                    strides.len() == n,
88                    "Explicit strides must have the same rank as the shape"
89                );
90                strides.clone().into()
91            }
92        }
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn physical_extent_contiguous_row_major() {
102        // Row-major 2x3 → strides (3, 1) → 6 elements covered.
103        let shape = Shape::from(vec![2, 3]);
104        let strides = Strides::new(&[3, 1]);
105        assert_eq!(physical_extent(&shape, &strides), 6);
106    }
107
108    #[test]
109    fn physical_extent_jumpy_strides_exceed_logical() {
110        // 256x256 logical view of a wider 256x512 buffer (stride 512 on dim 0).
111        // Last reachable offset is 255*512 + 255*1 = 130815 → +1 = 130816.
112        let shape = Shape::from(vec![256, 256]);
113        let strides = Strides::new(&[512, 1]);
114        assert_eq!(physical_extent(&shape, &strides), 130816);
115        // And it strictly exceeds the logical element count.
116        assert!(physical_extent(&shape, &strides) > 256 * 256);
117    }
118
119    #[test]
120    fn physical_extent_broadcast_strides_undercount_logical() {
121        // Broadcast dim: stride 0 means every index along that dim shares the
122        // same physical offset. A 4x3 tensor broadcasting dim 0 only needs 3
123        // elements of physical storage, not 12.
124        let shape = Shape::from(vec![4, 3]);
125        let strides = Strides::new(&[0, 1]);
126        assert_eq!(physical_extent(&shape, &strides), 3);
127        // ...and it's less than the logical element count.
128        assert!(physical_extent(&shape, &strides) < 4 * 3);
129    }
130}