Skip to main content

cubecl_core/
lib.rs

1#![no_std]
2
3#[cfg(feature = "std")]
4extern crate std;
5
6extern crate alloc;
7
8#[macro_use]
9extern crate derive_new;
10
11pub use cubecl_zspace as zspace;
12use cubecl_zspace::Shape;
13use cubecl_zspace::Strides;
14
15/// Cube Frontend Types.
16pub mod frontend;
17/// Input Output utilities.
18pub mod io;
19
20pub mod post_processing;
21
22/// Some future utilities that work across environments.
23pub use cubecl_environment as environment;
24pub use cubecl_environment::future;
25
26use cubecl_ir::VectorSize;
27use cubecl_runtime::client::ComputeClient;
28pub use cubecl_runtime::memory_management::MemoryConfiguration;
29use cubecl_runtime::server::CubeCountSelection;
30pub use frontend::cmma;
31
32/// Cube Language Internal Representation.
33pub use cubecl_ir as ir;
34
35pub mod codegen;
36pub mod compute;
37pub mod prelude;
38
39mod pod;
40
41pub use codegen::*;
42pub use cubecl_runtime::runtime::*;
43pub use pod::*;
44
45pub use cubecl_macros::*;
46pub use cubecl_runtime::benchmark;
47pub use cubecl_runtime::client;
48pub use cubecl_runtime::compiler::{CompilationError, Compiler, CubeTask};
49pub use cubecl_runtime::memory_management::MemoryUsage;
50pub use cubecl_runtime::memory_management::{
51    InstallMemoryPoolsError, MemoryPoolKind, MemoryPoolReport, MemoryReport,
52};
53pub use cubecl_runtime::server;
54pub use cubecl_runtime::throughput;
55pub use cubecl_runtime::tune;
56
57use frontend::LaunchArg;
58
59pub use cubecl_common::*;
60
61pub use prelude::CubeCount;
62pub use prelude::{CubeDim, ExecutionMode};
63
64pub use num_traits;
65
66mod id;
67pub use id::*;
68
69// Private utils for macros
70#[doc(hidden)]
71pub mod __private {
72    pub use alloc::{format, vec};
73    pub use paste::paste;
74}
75
76pub use prelude::{Assign, IntoRuntime};
77
78/// Calculate the number of cubes required to execute an operation where one cube unit is
79/// assigned to one element.
80pub fn calculate_cube_count_elemwise<R: Runtime>(
81    client: &ComputeClient<R>,
82    num_elems: usize,
83    cube_dim: CubeDim,
84) -> CubeCount {
85    if num_elems == 0 {
86        return CubeCount::Static(0, 0, 0);
87    }
88    let num_cubes = num_elems.div_ceil(cube_dim.num_elems() as usize);
89    CubeCountSelection::new(client, num_cubes as u32).cube_count()
90}
91
92pub fn tensor_vectorization_factor(
93    factors: &[VectorSize],
94    shape: &Shape,
95    strides: &Strides,
96    dim: usize,
97) -> VectorSize {
98    tensor_vector_size_parallel(factors.iter().cloned(), shape, strides, dim)
99}
100pub fn tensor_vectorization(
101    factors: &[VectorSize],
102    shape: &Shape,
103    strides: &Strides,
104    dim: usize,
105) -> VectorSize {
106    tensor_vector_size_parallel(factors.iter().cloned(), shape, strides, dim)
107}
108
109#[derive(Debug, Clone)]
110pub enum VectorizationError {
111    AxisOutOfBounds,
112    StrideMismatch,
113    NoValidVectorization,
114}
115
116/// Find the maximum vector size usable for parallel vectorization along the given axis
117/// from the supported vector sizes or return 1 if vectorization is impossible.
118///
119/// This function is designed to never return a vector size above 1 by error,
120/// but doesn't guarantee to always return the actual maximum possible vector size.
121/// That is, it may be overly strict.
122///
123/// Currently, this checks that the stride of the axis is 1, that its shape is
124/// divisible by a candidate vector size and that every non-broadcast stride outside
125/// the axis is divisible by the vector size.
126/// The last condition ensures a vectorized read on `axis` stays contiguous in the
127/// source buffer as coordinates in other dimensions change.
128pub fn tensor_vector_size_parallel(
129    optimized_vector_sizes: impl Iterator<Item = VectorSize>,
130    shape: &Shape,
131    strides: &Strides,
132    axis: usize,
133) -> VectorSize {
134    try_tensor_vector_size_parallel(optimized_vector_sizes, shape, strides, axis).unwrap_or(1)
135}
136
137/// Like `try_tensor_vector_size_parallel` but does not assume 1 is supported
138pub fn try_tensor_vector_size_parallel(
139    supported_vector_sizes: impl Iterator<Item = VectorSize>,
140    shape: &Shape,
141    strides: &Strides,
142    axis: usize,
143) -> Result<VectorSize, VectorizationError> {
144    let stride = strides
145        .get(axis)
146        .ok_or(VectorizationError::AxisOutOfBounds)?;
147    if *stride != 1 {
148        return Err(VectorizationError::StrideMismatch);
149    }
150
151    let axis_shape = shape.get(axis).ok_or(VectorizationError::AxisOutOfBounds)?;
152
153    // Smallest non-zero stride among non-axis dims. Stride 0 is a broadcast and
154    // never contributes to the source offset, so it can be ignored. Every other
155    // dim can shift the source offset when its coord changes, so its stride must
156    // be a multiple of the vector size for vectorized reads to stay aligned.
157    // Unit-size dims are included for simplicity; they only cause false negatives
158    // (vectorization disabled) rather than incorrect output.
159    let next_stride = strides
160        .iter()
161        .enumerate()
162        .filter_map(|(i, &s)| (i != axis && s != 0).then_some(s))
163        .min()
164        .unwrap_or(0);
165
166    supported_vector_sizes
167        .filter(|&vector_size| axis_shape % vector_size == 0 && next_stride % vector_size == 0)
168        .max()
169        .ok_or(VectorizationError::NoValidVectorization)
170}
171
172/// Find the maximum vector size usable for perpendicular vectorization along the given axis
173/// from the supported vector sizes or return 1 if vectorization is impossible.
174///
175/// This function is designed to never return a vector size above 1 by error,
176/// but doesn't guarantee to always return the actual maximum possible vector size.
177/// That is, it may be overly strict.
178///
179/// Currently, this checks that the stride of the axis is divisible by a candidate vector size
180/// and that the product of all shapes of axes with smaller strides is equal to the stride of the axis.
181/// The second condition ensure that elements within the stride are contiguous.
182pub fn tensor_vector_size_perpendicular(
183    supported_vector_sizes: impl Iterator<Item = VectorSize>,
184    shape: &[usize],
185    strides: &[usize],
186    axis: usize,
187) -> VectorSize {
188    try_tensor_vector_sizes_perpendicular(supported_vector_sizes, shape, strides, axis).unwrap_or(1)
189}
190
191/// Like `tensor_vector_sizes_perpendicular` but does not assume 1 is supported
192pub fn try_tensor_vector_sizes_perpendicular(
193    supported_vector_sizes: impl Iterator<Item = VectorSize>,
194    shape: &[usize],
195    strides: &[usize],
196    axis: usize,
197) -> Result<VectorSize, VectorizationError> {
198    let axis_stride = strides
199        .get(axis)
200        .ok_or(VectorizationError::AxisOutOfBounds)?;
201
202    let prod_shape_axes_smaller_strides = strides
203        .iter()
204        .zip(shape.iter())
205        .filter(|(stride, _)| **stride < *axis_stride)
206        .map(|(_, shape)| shape)
207        .product::<usize>();
208
209    if *axis_stride != prod_shape_axes_smaller_strides {
210        return Err(VectorizationError::StrideMismatch);
211    }
212
213    supported_vector_sizes
214        .filter(|&vector_size| *axis_stride % vector_size == 0)
215        .max()
216        .ok_or(VectorizationError::NoValidVectorization)
217}
218
219/// Runtime arguments to launch a kernel.
220pub type RuntimeArg<T, R> = <T as LaunchArg>::RuntimeArg<R>;
221pub type ExpandType<T> = <T as crate::prelude::CubeType>::ExpandType;
222
223#[cfg(feature = "export_tests")]
224/// Tests only useful for runtimes.
225pub mod runtime_tests;
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    fn try_parallel(
232        sizes: &[VectorSize],
233        shape: &[usize],
234        strides: &[usize],
235        axis: usize,
236    ) -> Result<VectorSize, VectorizationError> {
237        try_tensor_vector_size_parallel(
238            sizes.iter().copied(),
239            &Shape::from(shape.iter().copied()),
240            &Strides::new(strides),
241            axis,
242        )
243    }
244
245    #[test]
246    fn parallel_contiguous_picks_max_vector_size() {
247        // Contiguous [1, 9, 4], vectorize along last dim (stride 1).
248        // Outer stride 4 is a multiple of 4, so vec_size = 4 is safe.
249        let v = try_parallel(&[1, 2, 4], &[1, 9, 4], &[36, 4, 1], 2).unwrap();
250        assert_eq!(v, 4);
251    }
252
253    #[test]
254    fn parallel_unfold_step_one_rejects_vectorization() {
255        // Unfold view produced by `unfold(1, 4, 1)` on a [1, 12] contiguous tensor:
256        // shape [1, 9, 4], strides [12, 1, 1]. The frame dim has stride 1, so each
257        // step in the frame coord shifts the source offset by 1 - not a multiple
258        // of any vec_size > 1, so vectorized reads would be unaligned and return
259        // the wrong data. Must fall back to vec_size = 1.
260        let v = try_parallel(&[1, 2, 4], &[1, 9, 4], &[12, 1, 1], 2).unwrap();
261        assert_eq!(v, 1);
262    }
263
264    #[test]
265    fn parallel_unfold_step_two_allows_vectorization() {
266        // Same unfold pattern but with step=2: strides [12, 2, 1]. Frame coord
267        // shifts source by 2 (still not a multiple of 4), so vec_size = 4 must
268        // be rejected - but vec_size = 2 is fine.
269        let v = try_parallel(&[1, 2, 4], &[1, 9, 4], &[12, 2, 1], 2).unwrap();
270        assert_eq!(v, 2);
271    }
272
273    #[test]
274    fn parallel_broadcast_dim_ignored() {
275        // Broadcast dim has stride 0; it never shifts the source offset, so
276        // it should not disqualify vectorization.
277        let v = try_parallel(&[1, 2, 4], &[1, 9, 4], &[0, 4, 1], 2).unwrap();
278        assert_eq!(v, 4);
279    }
280
281    #[test]
282    fn parallel_axis_stride_not_one_is_error() {
283        let err = try_parallel(&[1, 2, 4], &[1, 9, 4], &[36, 1, 4], 2).unwrap_err();
284        assert!(matches!(err, VectorizationError::StrideMismatch));
285    }
286}