Skip to main content

neura_program/
shape.rs

1use neura_abi::MAX_RANK;
2
3const ELEMENT_LIMIT: u64 = i32::MAX as u64;
4
5#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
6pub struct Shape {
7    dims: [u32; 4],
8    elements: u32,
9}
10
11impl Shape {
12    pub const fn scalar() -> Self {
13        Self {
14            dims: [1; 4],
15            elements: 1,
16        }
17    }
18
19    pub fn vector(elements: u32) -> Self {
20        Self::of([elements])
21    }
22
23    pub fn matrix(rows: u32, columns: u32) -> Self {
24        Self::of([rows, columns])
25    }
26
27    pub fn of(dims: impl AsRef<[u32]>) -> Self {
28        let dims = dims.as_ref();
29        assert!(
30            !dims.is_empty() && dims.len() <= MAX_RANK as usize,
31            "a shape declares {} dimensions where {MAX_RANK} is the limit",
32            dims.len(),
33        );
34        let mut padded = [1u32; 4];
35        let mut elements = 1u64;
36        for (slot, dim) in padded[4 - dims.len()..].iter_mut().zip(dims) {
37            assert!(*dim > 0, "a tensor dimension must be positive");
38            *slot = *dim;
39            elements *= u64::from(*dim);
40        }
41        assert!(
42            elements <= ELEMENT_LIMIT,
43            "a tensor of {elements} elements outruns the index space the device addresses",
44        );
45        Self {
46            dims: padded,
47            elements: elements as u32,
48        }
49    }
50
51    pub const fn dims(self) -> [u32; 4] {
52        self.dims
53    }
54
55    pub const fn elements(self) -> u32 {
56        self.elements
57    }
58
59    pub fn strides(self) -> [u32; 4] {
60        let dims = self.dims;
61        let mut strides = [0u32; 4];
62        let mut stride = 1u32;
63        for axis in (0..4).rev() {
64            strides[axis] = if dims[axis] == 1 { 0 } else { stride };
65            stride *= dims[axis];
66        }
67        strides
68    }
69
70    pub fn combines_with(self, other: Self) -> bool {
71        self.dims
72            .iter()
73            .zip(other.dims)
74            .all(|(left, right)| left == &right || *left == 1 || right == 1)
75    }
76
77    pub fn combined(self, other: Self) -> Self {
78        assert!(
79            self.combines_with(other),
80            "shapes {:?} and {:?} cannot meet element by element",
81            self.dims,
82            other.dims,
83        );
84        let mut dims = [1u32; 4];
85        for (axis, dim) in dims.iter_mut().enumerate() {
86            *dim = self.dims[axis].max(other.dims[axis]);
87        }
88        Self::of(dims)
89    }
90
91    pub fn fits_within(self, other: Self) -> bool {
92        (0..4).all(|axis| self.dims[axis] == other.dims[axis] || self.dims[axis] == 1)
93    }
94
95    pub fn batch(self) -> [u32; 2] {
96        [self.dims[0], self.dims[1]]
97    }
98
99    pub fn reduced(self, axis: u32) -> Self {
100        assert!(
101            axis < MAX_RANK,
102            "a fold names one of the {MAX_RANK} axes of {:?}",
103            self.dims,
104        );
105        let mut dims = self.dims;
106        dims[axis as usize] = 1;
107        Self::of(dims)
108    }
109
110    pub fn rows(self) -> u32 {
111        self.elements / self.dims[3]
112    }
113
114    pub fn columns(self) -> u32 {
115        self.dims[3]
116    }
117
118    pub fn is_scalar(self) -> bool {
119        self.elements == 1
120    }
121}