cubek-std 0.3.0-pre.2

CubeK: Standard Library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use cubecl::{
    cmma::MmaDefinition,
    define_size,
    ir::{DeviceProperties, MatrixIdent, StorageType},
    prelude::*,
};

use crate::{
    MatrixLayout, StageIdent, TileSize,
    tile::{
        SharedTile, Tile, TileKind, TileKindExpand, TileScope,
        variants::instruction::mma::{MmaStageWriter, mma_fill_fragment, mma_load_strided},
    },
};

// Fragment inner vector sizes for the three MMA roles. Bound at allocation time
// via `mma_register_vector_sizes` to match the hardware's `def.vector_size(...)`
// for each role — these are independent of the outer Tile enum's stage vector `V`.
define_size!(pub NL);
define_size!(pub NR);
define_size!(pub NA);

/// Single MMA tile carrier. The role (Lhs / Rhs / Acc) lives inside
/// [`MmaFragment`] because each role's fragment uses a different inner vector
/// size (`NL` / `NR` / `NA`); the outer carrier holds the shared comptime
/// metadata the tile body uses. The matmul-level configuration that produced
/// these values lives in cubek-matmul as `MmaMatmul`.
#[derive(CubeType)]
pub struct MmaTile<N: Numeric> {
    pub fragment: MmaFragment<N>,
    #[cube(comptime)]
    pub matrix_layout: MatrixLayout,
    #[cube(comptime)]
    pub tile_size: TileSize,
    #[cube(comptime)]
    pub mma_io_config: MmaIOConfig,
}

#[derive(CubeType)]
pub enum MmaFragment<N: Numeric> {
    Lhs(Array<Vector<N, NL>>),
    Rhs(Array<Vector<N, NR>>),
    Acc(Array<Vector<N, NA>>),
}

/// Hardware-capability-driven choice of load/store methods for the MMA tile.
/// Determined once per `(device, dtypes)` and carried by the tile because the
/// fragment readers/writers branch on it.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct MmaIOConfig {
    pub lhs_load_method: LoadMethod,
    pub rhs_load_method: LoadMethod,
    pub acc_load_method: LoadMethod,
    pub store_method: StoreMethod,
}

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum LoadMethod {
    Manual,
    LoadMatrix,
}

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum StoreMethod {
    Manual,
    StoreMatrix,
}

impl MmaIOConfig {
    pub fn new(
        device_props: &DeviceProperties,
        lhs_stage: StorageType,
        rhs_stage: StorageType,
        acc_stage: StorageType,
    ) -> Self {
        Self {
            lhs_load_method: load_method(device_props, lhs_stage),
            rhs_load_method: load_method(device_props, rhs_stage),
            acc_load_method: load_method(device_props, acc_stage),
            store_method: store_method(device_props, acc_stage),
        }
    }

    pub fn load_method(&self, ident: MatrixIdent) -> LoadMethod {
        match ident {
            MatrixIdent::A => self.lhs_load_method,
            MatrixIdent::B => self.rhs_load_method,
            MatrixIdent::Accumulator => self.acc_load_method,
        }
    }

    pub fn store_method(&self) -> StoreMethod {
        self.store_method
    }
}

fn load_method(device_props: &DeviceProperties, dtype: StorageType) -> LoadMethod {
    if !matches!(dtype, StorageType::Packed(_, _))
        && device_props.features.matmul.ldmatrix.contains(&dtype)
    {
        LoadMethod::LoadMatrix
    } else {
        LoadMethod::Manual
    }
}

fn store_method(device_props: &DeviceProperties, dtype: StorageType) -> StoreMethod {
    if !matches!(dtype, StorageType::Packed(_, _))
        && device_props.features.matmul.stmatrix.contains(&dtype)
    {
        StoreMethod::StoreMatrix
    } else {
        StoreMethod::Manual
    }
}

#[cube]
fn make_mma_definition<L: Numeric, R: Numeric, A: Numeric>(
    #[comptime] tile_size: TileSize,
) -> MmaDefinition<L, R, A> {
    MmaDefinition::new(
        tile_size.m() as usize,
        tile_size.n() as usize,
        tile_size.k() as usize,
    )
}

#[cube]
#[allow(unused_variables)]
pub fn mma_register_vector_sizes<L: Numeric, R: Numeric, A: Numeric>(def: MmaDefinition<L, R, A>) {
    let vector_size_a = def.vector_size(MatrixIdent::A);
    let vector_size_b = def.vector_size(MatrixIdent::B);
    let vector_size_acc = def.vector_size(MatrixIdent::Accumulator);
    intrinsic!(|scope| {
        scope.register_size::<NL>(vector_size_a);
        scope.register_size::<NR>(vector_size_b);
        scope.register_size::<NA>(vector_size_acc);
    });
}

#[cube]
pub fn mma_allocate_lhs<L: Numeric, R: Numeric, A: Numeric, Sc: TileScope>(
    #[comptime] layout: MatrixLayout,
    #[comptime] tile_size: TileSize,
    #[comptime] mma_io_config: MmaIOConfig,
) -> Tile<L, Sc> {
    let def = make_mma_definition::<L, R, A>(tile_size);
    mma_register_vector_sizes(def);
    let vector_count = def.vectors_per_lane(MatrixIdent::A);

    Tile::from_kind(TileKind::new_Mma(MmaTile::<L> {
        fragment: MmaFragment::new_Lhs(Array::new(vector_count)),
        matrix_layout: layout,
        tile_size,
        mma_io_config,
    }))
}

#[cube]
pub fn mma_allocate_rhs<R: Numeric, L: Numeric, A: Numeric, Sc: TileScope>(
    #[comptime] layout: MatrixLayout,
    #[comptime] tile_size: TileSize,
    #[comptime] mma_io_config: MmaIOConfig,
) -> Tile<R, Sc> {
    let def = make_mma_definition::<L, R, A>(tile_size);
    mma_register_vector_sizes(def);
    let vector_count = def.vectors_per_lane(MatrixIdent::B);

    Tile::from_kind(TileKind::new_Mma(MmaTile::<R> {
        fragment: MmaFragment::new_Rhs(Array::new(vector_count)),
        matrix_layout: layout,
        tile_size,
        mma_io_config,
    }))
}

#[cube]
pub fn mma_allocate_acc<A: Numeric, L: Numeric, R: Numeric, Sc: TileScope>(
    #[comptime] layout: MatrixLayout,
    #[comptime] tile_size: TileSize,
    #[comptime] mma_io_config: MmaIOConfig,
) -> Tile<A, Sc> {
    let def = make_mma_definition::<L, R, A>(tile_size);
    mma_register_vector_sizes(def);
    let vector_count = def.vectors_per_lane(MatrixIdent::Accumulator);

    Tile::from_kind(TileKind::new_Mma(MmaTile::<A> {
        fragment: MmaFragment::new_Acc(Array::new(vector_count)),
        matrix_layout: layout,
        tile_size,
        mma_io_config,
    }))
}

#[cube]
impl<A: Numeric> MmaTile<A> {
    /// Executes `lhs · rhs`, accumulating into `self`. Each operand must
    /// carry the role its position requires (`Lhs`, `Rhs`, `Acc`).
    pub fn mma<L: Numeric, R: Numeric>(&mut self, lhs: &MmaTile<L>, rhs: &MmaTile<R>) {
        match &lhs.fragment {
            MmaFragment::Lhs(lf) => match &rhs.fragment {
                MmaFragment::Rhs(rf) => match &mut self.fragment {
                    MmaFragment::Acc(af) => {
                        mma_execute(lf, rf, af, self.matrix_layout, self.tile_size);
                    }
                    MmaFragment::Lhs(_) | MmaFragment::Rhs(_) => {
                        panic!("Mma: expected Acc role for accumulator")
                    }
                },
                MmaFragment::Lhs(_) | MmaFragment::Acc(_) => {
                    panic!("Mma: expected Rhs role for rhs")
                }
            },
            MmaFragment::Rhs(_) | MmaFragment::Acc(_) => {
                panic!("Mma: expected Lhs role for lhs")
            }
        }
    }
}

#[cube]
impl<N: Numeric> MmaTile<N> {
    /// Copies into the mma fragment from `source`. Supported sources:
    /// `Shared` (per-role load) and `None` (zero-init, Acc only).
    /// `L` / `R` / `A` are the matmul triple's role types — needed by the
    /// per-role load functions. When `self` is in role X, `N` substitutes
    /// for the X type and the other two are taken from the caller's
    /// generics.
    pub fn copy_from<SE: Numeric, SS: Size, L: Numeric, R: Numeric, A: Numeric, Sc: TileScope>(
        &mut self,
        source: &Tile<SE, Sc>,
        #[comptime] _ident: StageIdent,
    ) {
        match &source.kind {
            TileKind::SharedTile(shared) => match &mut self.fragment {
                MmaFragment::Lhs(f) => mma_load_lhs_from_shared::<SE, SS, N, R, A>(
                    shared,
                    f,
                    self.matrix_layout,
                    self.tile_size,
                    self.mma_io_config,
                ),
                MmaFragment::Rhs(f) => mma_load_rhs_from_shared::<SE, SS, N, L, A>(
                    shared,
                    f,
                    self.matrix_layout,
                    self.tile_size,
                    self.mma_io_config,
                ),
                MmaFragment::Acc(f) => mma_load_acc_from_shared::<SE, SS, N, L, R>(
                    shared,
                    f,
                    self.matrix_layout,
                    self.tile_size,
                    self.mma_io_config,
                ),
            },
            TileKind::None => match &mut self.fragment {
                MmaFragment::Acc(f) => {
                    mma_load_acc_zeros::<N, L, R>(
                        f,
                        self.matrix_layout,
                        self.tile_size,
                        self.mma_io_config,
                    );
                }
                MmaFragment::Lhs(_) | MmaFragment::Rhs(_) => {
                    panic!("Mma zero-load only supported for Acc role")
                }
            },
            TileKind::Cmma(_)
            | TileKind::Mma(_)
            | TileKind::Register(_)
            | TileKind::PlaneVec(_)
            | TileKind::Interleaved(_)
            | TileKind::Unit(_)
            | TileKind::WhiteboxFragment(_)
            | TileKind::RowWise(_)
            | TileKind::Bounce(_)
            | TileKind::Stage(_)
            | TileKind::Partition(_)
            | TileKind::Pipelined(_) => panic!("MmaTile::copy_from: unsupported source variant"),
        }
    }

    /// Zero-init the mma fragment (Acc role only).
    pub fn init_zero<L: Numeric, R: Numeric>(&mut self) {
        match &mut self.fragment {
            MmaFragment::Acc(f) => {
                mma_load_acc_zeros::<N, L, R>(
                    f,
                    self.matrix_layout,
                    self.tile_size,
                    self.mma_io_config,
                );
            }
            MmaFragment::Lhs(_) | MmaFragment::Rhs(_) => {
                panic!("MmaTile::init_zero: only Acc role supported")
            }
        }
    }
}

// ===========================================================================
// Compute: matmul / load / write / zero-init
// ===========================================================================

#[cube]
pub fn mma_execute<L: Numeric, R: Numeric, A: Numeric>(
    lhs: &Array<Vector<L, NL>>,
    rhs: &Array<Vector<R, NR>>,
    acc: &mut Array<Vector<A, NA>>,
    #[comptime] _matrix_layout: MatrixLayout,
    #[comptime] tile_size: TileSize,
) {
    let def = MmaDefinition::<L, R, A>::new(
        tile_size.m() as usize,
        tile_size.n() as usize,
        tile_size.k() as usize,
    );
    let out_arr = def.execute(lhs, rhs, &*acc);
    let num_vectors = def.vectors_per_lane(MatrixIdent::Accumulator);
    #[unroll]
    for i in 0..num_vectors {
        acc[i] = out_arr[i];
    }
}

#[cube]
pub fn mma_load_lhs_from_shared<E: Numeric, ES: Size, L: Numeric, R: Numeric, A: Numeric>(
    shared: &SharedTile<E>,
    fragment: &mut Array<Vector<L, NL>>,
    #[comptime] matrix_layout: MatrixLayout,
    #[comptime] tile_size: TileSize,
    #[comptime] mma_io_config: MmaIOConfig,
) {
    let shared = shared.view::<ES>();
    let def = make_mma_definition::<L, R, A>(tile_size);
    mma_load_strided(
        &shared,
        fragment,
        &def,
        MatrixIdent::A,
        matrix_layout,
        tile_size,
        mma_io_config,
    );
}

#[cube]
pub fn mma_load_rhs_from_shared<E: Numeric, ES: Size, R: Numeric, L: Numeric, A: Numeric>(
    shared: &SharedTile<E>,
    fragment: &mut Array<Vector<R, NR>>,
    #[comptime] matrix_layout: MatrixLayout,
    #[comptime] tile_size: TileSize,
    #[comptime] mma_io_config: MmaIOConfig,
) {
    let shared = shared.view::<ES>();
    let def = make_mma_definition::<L, R, A>(tile_size);
    mma_load_strided(
        &shared,
        fragment,
        &def,
        MatrixIdent::B,
        matrix_layout,
        tile_size,
        mma_io_config,
    );
}

#[cube]
pub fn mma_load_acc_from_shared<E: Numeric, ES: Size, A: Numeric, L: Numeric, R: Numeric>(
    shared: &SharedTile<E>,
    fragment: &mut Array<Vector<A, NA>>,
    #[comptime] matrix_layout: MatrixLayout,
    #[comptime] tile_size: TileSize,
    #[comptime] mma_io_config: MmaIOConfig,
) {
    let shared = shared.view::<ES>();
    let def = make_mma_definition::<L, R, A>(tile_size);
    mma_load_strided(
        &shared,
        fragment,
        &def,
        MatrixIdent::Accumulator,
        matrix_layout,
        tile_size,
        mma_io_config,
    );
}

#[cube]
pub fn mma_load_acc_zeros<A: Numeric, L: Numeric, R: Numeric>(
    fragment: &mut Array<Vector<A, NA>>,
    #[comptime] matrix_layout: MatrixLayout,
    #[comptime] tile_size: TileSize,
    #[comptime] mma_io_config: MmaIOConfig,
) {
    let _ = (matrix_layout, mma_io_config);
    let def = make_mma_definition::<L, R, A>(tile_size);
    mma_fill_fragment::<A, NA, A, L, R, A>(
        &A::from_int(0),
        fragment,
        &def,
        MatrixIdent::Accumulator,
    );
}

#[cube]
pub fn mma_write_to_shared<E: Numeric, ES: Size, A: Numeric, L: Numeric, R: Numeric>(
    shared: &mut SharedTile<E>,
    fragment: &Array<Vector<A, NA>>,
    #[comptime] tile_size: TileSize,
    #[comptime] mma_io_config: MmaIOConfig,
) {
    let mut shared = shared.view::<ES>();
    let def = make_mma_definition::<L, R, A>(tile_size);
    let out_layout = comptime!(shared.layout);
    MmaStageWriter::store_fragment(
        &mut shared,
        fragment,
        &def,
        MatrixIdent::Accumulator,
        out_layout,
        tile_size.m(),
        mma_io_config,
    );
}