cubek_test_utils/test_tensor/
strides.rs1use cubecl::zspace::{Shape, Strides};
2
3#[derive(Debug, Clone, PartialEq, Eq, Default)]
6pub enum StridedLayout {
7 #[default]
8 RowMajor,
9 ColMajor,
10 Explicit(Vec<usize>),
11}
12
13#[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 pub fn base(&self) -> &StridedLayout {
29 match self {
30 LayoutSpec::Strided(base) => base,
31 }
32 }
33
34 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
46pub 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 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 let shape = Shape::from(vec![256, 256]);
113 let strides = Strides::new(&[512, 1]);
114 assert_eq!(physical_extent(&shape, &strides), 130816);
115 assert!(physical_extent(&shape, &strides) > 256 * 256);
117 }
118
119 #[test]
120 fn physical_extent_broadcast_strides_undercount_logical() {
121 let shape = Shape::from(vec![4, 3]);
125 let strides = Strides::new(&[0, 1]);
126 assert_eq!(physical_extent(&shape, &strides), 3);
127 assert!(physical_extent(&shape, &strides) < 4 * 3);
129 }
130}