cubecl_reduce/
lib.rs

1//! This provides different implementations of the reduce algorithm which
2//! can run on multiple GPU backends using CubeCL.
3//!
4//! A reduction is a tensor operation mapping a rank `R` tensor to a rank `R - 1`
5//! by agglomerating all elements along a given axis with some binary operator.
6//! This is often also called folding.
7//!
8//! This crate provides a main entrypoint as the [`reduce`] function which allows to automatically
9//! perform a reduction for a given instruction implementing the [`ReduceInstruction`] trait and a given [`ReduceStrategy`].
10//! It also provides implementation of the [`ReduceInstruction`] trait for common operations in the [`instructions`] module.
11//! Finally, it provides many reusable primitives to perform different general reduction algorithms in the [`primitives`] module.
12
13pub mod args;
14pub mod instructions;
15pub mod primitives;
16pub mod tune_key;
17
18mod config;
19mod error;
20mod launch;
21mod shared_sum;
22mod strategy;
23
24pub use config::*;
25pub use error::*;
26pub use instructions::ReduceFamily;
27pub use instructions::ReduceInstruction;
28pub use shared_sum::*;
29pub use strategy::*;
30
31use launch::*;
32
33pub use launch::{ReduceParams, reduce_kernel};
34
35#[cfg(feature = "export_tests")]
36pub mod test;
37
38use cubecl_core::prelude::*;
39
40/// Reduce the given `axis` of the `input` tensor using the instruction `Inst` and write the result into `output`.
41///
42/// An optional [`ReduceStrategy`] can be provided to force the reduction to use a specific algorithm. If omitted, a best effort
43/// is done to try and pick the best strategy supported for the provided `client`.
44///
45/// Return an error if `strategy` is `Some(strategy)` and the specified strategy is not supported by the `client`.
46/// Also returns an error if the `axis` is larger than the `input` rank or if the shape of `output` is invalid.
47/// The shape of `output` must be the same as input except with a value of 1 for the given `axis`.
48///
49///
50/// # Example
51///
52/// This examples show how to sum the rows of a small `2 x 2` matrix into a `1 x 2` vector.
53/// For more details, see the CubeCL documentation.
54///
55/// ```ignore
56/// use cubecl_reduce::instructions::Sum;
57///
58/// let client = /* ... */;
59/// let size_f32 = std::mem::size_of::<f32>();
60/// let axis = 0; // 0 for rows, 1 for columns in the case of a matrix.
61///
62/// // Create input and output handles.
63/// let input_handle = client.create(f32::as_bytes(&[0, 1, 2, 3]));
64/// let input = unsafe {
65///     TensorHandleRef::<R>::from_raw_parts(
66///         &input_handle,
67///         &[2, 1],
68///         &[2, 2],
69///         size_f32,
70///     )
71/// };
72///
73/// let output_handle = client.empty(2 * size_f32);
74/// let output = unsafe {
75///     TensorHandleRef::<R>::from_raw_parts(
76///         &output_handle,
77///         &output_stride,
78///         &output_shape,
79///         size_f32,
80///     )
81/// };
82///
83/// // Here `R` is a `cubecl::Runtime`.
84/// let result = reduce::<R, f32, f32, Sum>(&client, input, output, axis, None);
85///
86/// if result.is_ok() {
87///        let binding = output_handle.binding();
88///        let bytes = client.read_one(binding);
89///        let output_values = f32::from_bytes(&bytes);
90///        println!("Output = {:?}", output_values); // Should print [1, 5].
91/// }
92/// ```
93pub fn reduce<R: Runtime, In: Numeric, Out: Numeric, Inst: ReduceFamily>(
94    client: &ComputeClient<R::Server, R::Channel>,
95    input: TensorHandleRef<R>,
96    output: TensorHandleRef<R>,
97    axis: usize,
98    strategy: Option<ReduceStrategy>,
99    inst_config: Inst::Config,
100) -> Result<(), ReduceError> {
101    validate_axis(input.shape.len(), axis)?;
102    valid_output_shape(input.shape, output.shape, axis)?;
103    let strategy = strategy
104        .map(|s| s.validate::<R>(client))
105        .unwrap_or(Ok(ReduceStrategy::new::<R>(client, true)))?;
106    let config = ReduceConfig::generate::<R, In>(client, &input, &output, axis, &strategy);
107
108    if let CubeCount::Static(x, y, z) = config.cube_count {
109        let (max_x, max_y, max_z) = R::max_cube_count();
110        if x > max_x || y > max_y || z > max_z {
111            return Err(ReduceError::CubeCountTooLarge);
112        }
113    }
114
115    launch_reduce::<R, In, Out, Inst>(
116        client,
117        input,
118        output,
119        axis as u32,
120        config,
121        strategy,
122        inst_config,
123    );
124    Ok(())
125}
126
127// Check that the given axis is less than the rank of the input.
128fn validate_axis(rank: usize, axis: usize) -> Result<(), ReduceError> {
129    if axis > rank {
130        return Err(ReduceError::InvalidAxis { axis, rank });
131    }
132    Ok(())
133}
134
135// Check that the output shape match the input shape with the given axis set to 1.
136fn valid_output_shape(
137    input_shape: &[usize],
138    output_shape: &[usize],
139    axis: usize,
140) -> Result<(), ReduceError> {
141    let mut expected_shape = input_shape.to_vec();
142    expected_shape[axis] = 1;
143    if output_shape != expected_shape {
144        return Err(ReduceError::MismatchShape {
145            expected_shape,
146            output_shape: output_shape.to_vec(),
147        });
148    }
149    Ok(())
150}