cubecl_reduce/instructions/
max.rs1use cubecl_core as cubecl;
2use cubecl_core::prelude::*;
3
4use crate::instructions::ReduceRequirements;
5
6use super::{ReduceCoordinate, ReduceFamily, ReduceInstruction};
7
8#[derive(Debug, CubeType, Clone)]
11pub struct Max;
12
13impl ReduceFamily for Max {
14 type Instruction<In: Numeric> = Self;
15 type Config = ();
16}
17
18#[cube]
19impl<In: Numeric> ReduceInstruction<In> for Max {
20 type AccumulatorItem = Line<In>;
21 type SharedAccumulator = SharedMemory<Line<In>>;
22 type Config = ();
23
24 fn requirements(_this: &Self) -> ReduceRequirements {
25 ReduceRequirements { coordinates: false }
26 }
27
28 fn from_config(_config: Self::Config) -> Self {
29 Max {}
30 }
31
32 fn null_input(_this: &Self, #[comptime] line_size: u32) -> Line<In> {
33 Line::empty(line_size).fill(In::min_value())
34 }
35
36 fn null_accumulator(this: &Self, #[comptime] line_size: u32) -> Self::AccumulatorItem {
37 Self::null_input(this, line_size)
38 }
39
40 fn assign_accumulator(
41 _this: &Self,
42 destination: &mut Self::AccumulatorItem,
43 source: &Self::AccumulatorItem,
44 ) {
45 *destination = *source;
46 }
47
48 fn reduce(
49 _this: &Self,
50 accumulator: &Self::AccumulatorItem,
51 item: Line<In>,
52 _coordinate: ReduceCoordinate,
53 #[comptime] use_planes: bool,
54 ) -> Self::AccumulatorItem {
55 if use_planes {
56 let candidate_item = plane_max(item);
57 select_many(
58 accumulator.greater_than(candidate_item),
59 *accumulator,
60 candidate_item,
61 )
62 } else {
63 select_many(accumulator.greater_than(item), *accumulator, item)
64 }
65 }
66
67 fn fuse_accumulators(
68 _this: &Self,
69 lhs: Self::AccumulatorItem,
70 rhs: Self::AccumulatorItem,
71 ) -> Self::AccumulatorItem {
72 select_many(lhs.greater_than(rhs), lhs, rhs)
73 }
74
75 fn merge_line<Out: Numeric>(
76 _this: &Self,
77 accumulator: Self::AccumulatorItem,
78 _shape_axis_reduce: u32,
79 ) -> Out {
80 let mut max = In::min_value();
81 #[unroll]
82 for k in 0..accumulator.size() {
83 let candidate = accumulator[k];
84 max = select(candidate > max, candidate, max);
85 }
86 Out::cast_from(max)
87 }
88
89 fn to_output_perpendicular<Out: Numeric>(
90 _this: &Self,
91 accumulator: Self::AccumulatorItem,
92 _shape_axis_reduce: u32,
93 ) -> Line<Out> {
94 Line::cast_from(accumulator)
95 }
96}