Skip to main content

cubecl_attention/components/tile/tiles/
mask.rs

1use cubecl_core as cubecl;
2use cubecl_core::prelude::*;
3use cubecl_std::tensor::layout::Coords2d;
4use cubecl_std::{CubeOption, CubeOptionExpand};
5
6use crate::components::AttentionPrecision;
7use crate::components::attention_types::MSK;
8use crate::components::fragment::{AttentionMatmul, AttentionMatmulConfig};
9use crate::components::fragment::{
10    FragmentLayout, FragmentLayoutExpand, FragmentMask, FragmentMaskExpand,
11};
12use cubecl_matmul::components::tile::StridedTile;
13
14use cubecl_std::tensor::layout::Coordinates;
15
16#[derive(CubeType)]
17/// Mask tile for Tile Attention
18/// It is an additive mask, which means the result of apply should be added, not multiplied
19pub enum MaskTile<AP: AttentionPrecision, AM: AttentionMatmul<AP>> {
20    Materialized(MaterializedTileMask<AP, AM>),
21    Logical(LogicalTileMask<AM::FragmentLayout>),
22}
23
24#[cube]
25impl<AP: AttentionPrecision, AM: AttentionMatmul<AP>> MaskTile<AP, AM> {
26    pub fn new(
27        out_of_bounds: CubeOption<Coords2d>,
28        #[comptime] partition_pos: Coords2d,
29        #[comptime] config: AM::Config,
30    ) -> MaskTile<AP, AM> {
31        let logical_mask = LogicalTileMask::<AM::FragmentLayout> {
32            logical_iter_origin: LogicalIterOrigin::init(),
33            partition_pos,
34            causal: config.causal_mask(),
35            out_of_bounds,
36            fragment_layout: AM::softmax_layout(config),
37        };
38
39        if config.materialized_mask() {
40            MaskTile::new_Materialized(MaterializedTileMask::<AP, AM> {
41                fragment: AM::allocate_mask(config),
42                logical_mask,
43                config,
44            })
45        } else {
46            MaskTile::new_Logical(logical_mask)
47        }
48    }
49
50    /// Loads the mask data into the fragment, if a tile is given, otherwise only
51    /// updates the logical mask
52    pub fn update(&mut self, new_origin: Coords2d, tile: CubeOption<StridedTile<MSK<AP>>>) {
53        match self {
54            MaskTile::Materialized(materialized_tile_mask) => {
55                // TODO read the tile
56                materialized_tile_mask
57                    .logical_mask
58                    .update_origin(new_origin);
59
60                materialized_tile_mask.update_tile(tile.unwrap())
61            }
62            MaskTile::Logical(logical_tile_mask) => logical_tile_mask.update_origin(new_origin),
63        }
64    }
65}
66
67#[derive(CubeType)]
68pub struct LogicalIterOrigin {
69    row: RuntimeCell<u32>,
70    col: RuntimeCell<u32>,
71}
72
73#[cube]
74impl LogicalIterOrigin {
75    fn init() -> LogicalIterOrigin {
76        LogicalIterOrigin {
77            row: RuntimeCell::new(0),
78            col: RuntimeCell::new(0),
79        }
80    }
81
82    fn read(&self) -> Coords2d {
83        (self.row.read(), self.col.read())
84    }
85
86    fn update(&mut self, new: Coords2d) {
87        self.row.store(new.0);
88        self.col.store(new.1);
89    }
90}
91
92#[derive(CubeType)]
93pub struct LogicalTileMask<F: FragmentLayout> {
94    logical_iter_origin: LogicalIterOrigin,
95    #[cube(comptime)]
96    partition_pos: Coords2d,
97    #[cube(comptime)]
98    causal: bool,
99    out_of_bounds: CubeOption<Coords2d>,
100    fragment_layout: F,
101}
102
103#[cube]
104impl<F: FragmentLayout> LogicalTileMask<F> {
105    pub fn should_mask(&self, local_pos: Coords2d) -> bool {
106        let pos_in_tile = self.fragment_layout.absolute_pos(local_pos);
107
108        let pos = Coords2d::add(
109            self.logical_iter_origin.read(),
110            Coords2d::add(self.partition_pos.runtime(), pos_in_tile),
111        );
112
113        let causal_masked = self.causal && pos.0 < pos.1;
114
115        let oob_masked = match self.out_of_bounds {
116            CubeOption::Some(bounds) => !Coords2d::is_in_bounds(&pos, &bounds),
117            CubeOption::None => false,
118        };
119
120        causal_masked || oob_masked
121    }
122
123    pub fn update_origin(&mut self, new_origin: Coords2d) {
124        self.logical_iter_origin.update(new_origin);
125    }
126}
127
128#[derive(CubeType)]
129pub struct MaterializedTileMask<AP: AttentionPrecision, AM: AttentionMatmul<AP>> {
130    fragment: AM::Mask,
131    logical_mask: LogicalTileMask<AM::FragmentLayout>,
132    #[cube(comptime)]
133    config: AM::Config,
134}
135
136#[cube]
137impl<AP: AttentionPrecision, AM: AttentionMatmul<AP>> MaterializedTileMask<AP, AM> {
138    pub fn should_mask(&self, local_pos: Coords2d) -> bool {
139        let logical_masked = self.logical_mask.should_mask(local_pos);
140        let materialized_masked = self.fragment.should_mask(local_pos);
141
142        logical_masked || materialized_masked
143    }
144
145    pub fn update_tile(&mut self, tile: StridedTile<MSK<AP>>) {
146        AM::fill_mask(&tile, &mut self.fragment, self.config);
147    }
148}
149
150#[cube]
151impl<AP: AttentionPrecision, AM: AttentionMatmul<AP>> FragmentMask for MaskTile<AP, AM> {
152    fn should_mask(&self, local_pos: (u32, u32)) -> bool {
153        match self {
154            MaskTile::Materialized(materialized_tile_mask) => {
155                materialized_tile_mask.should_mask(local_pos)
156            }
157            MaskTile::Logical(logical_tile_mask) => logical_tile_mask.should_mask(local_pos),
158        }
159    }
160}