cubecl-std 0.8.1

CubeCL 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use cubecl_core::{prelude::*, unexpanded};
use std::{
    marker::PhantomData,
    ops::{Deref, DerefMut},
    sync::Arc,
};

use crate::tensor::{
    View, ViewExpand, ViewOperationsMut, VirtualViewMut, VirtualViewMutExpand,
    layout::{Coordinates, Coords1d, Layout, VirtualLayoutExpand, VirtualLayoutOperationsExpand},
    view::ViewType,
};

/// Launchable tensor view for ease of use.
#[derive(Clone)]
pub struct TypedView<E: CubePrimitive, L: LaunchLayout, IO: SliceVisibility = ReadOnly> {
    _ty: PhantomData<(E, L, IO)>,
}

impl<E: CubePrimitive, L: LaunchLayout, IO: SliceVisibility> CubeType for TypedView<E, L, IO> {
    type ExpandType = ViewExpand<E, L::Coordinates, IO>;
}

impl<E: CubePrimitive, L: LaunchLayout, IO: SliceVisibility> Deref for TypedView<E, L, IO> {
    type Target = View<E, L::Coordinates, IO>;

    fn deref(&self) -> &Self::Target {
        unexpanded!()
    }
}

impl<E: CubePrimitive, L: LaunchLayout> DerefMut for TypedView<E, L, ReadWrite> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unexpanded!()
    }
}

pub struct TypedViewLaunch<'a, L: LaunchLayout<SourceCoordinates = Coords1d>, R: Runtime> {
    buffer: ArrayArg<'a, R>,
    layout: L::RuntimeArg<'a, R>,
}
impl<'a, L: LaunchLayout<SourceCoordinates = Coords1d>, R: Runtime> TypedViewLaunch<'a, L, R> {
    #[allow(clippy::too_many_arguments)]
    pub fn new(buffer: ArrayArg<'a, R>, layout: L::RuntimeArg<'a, R>) -> Self {
        Self { buffer, layout }
    }
}
impl<'a, L: LaunchLayout<SourceCoordinates = Coords1d>, R: Runtime> ArgSettings<R>
    for TypedViewLaunch<'a, L, R>
{
    fn register(&self, launcher: &mut KernelLauncher<R>) {
        self.buffer.register(launcher);
        self.layout.register(launcher);
    }
}

pub struct TypedViewCompilationArg<L: LaunchLayout<SourceCoordinates = Coords1d>> {
    buffer: ArrayCompilationArg,
    layout: L::CompilationArg,
}
impl<L: LaunchLayout<SourceCoordinates = Coords1d>> Clone for TypedViewCompilationArg<L> {
    fn clone(&self) -> Self {
        Self {
            buffer: self.buffer.clone(),
            layout: self.layout.clone(),
        }
    }
}
impl<L: LaunchLayout<SourceCoordinates = Coords1d>> CompilationArg for TypedViewCompilationArg<L> {}

impl<L: LaunchLayout<SourceCoordinates = Coords1d>> core::hash::Hash
    for TypedViewCompilationArg<L>
{
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.buffer.hash(state);
        self.layout.hash(state);
    }
}
impl<L: LaunchLayout<SourceCoordinates = Coords1d>> PartialEq for TypedViewCompilationArg<L> {
    fn eq(&self, other: &Self) -> bool {
        self.buffer.eq(&other.buffer) && self.layout.eq(&other.layout)
    }
}
impl<L: LaunchLayout<SourceCoordinates = Coords1d>> core::fmt::Debug
    for TypedViewCompilationArg<L>
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct(stringify!(TensorViewTyped))
            .field("buffer", &self.buffer)
            .field("layout", &self.layout)
            .finish()
    }
}
impl<L: LaunchLayout<SourceCoordinates = Coords1d>> Eq for TypedViewCompilationArg<L> {}

impl<E: CubePrimitive, L: LaunchLayout<SourceCoordinates = Coords1d>, IO: SliceVisibility> LaunchArg
    for TypedView<E, L, IO>
{
    type RuntimeArg<'a, R: Runtime> = TypedViewLaunch<'a, L, R>;
    type CompilationArg = TypedViewCompilationArg<L>;

    fn compilation_arg<'a, R: Runtime>(
        runtime_arg: &Self::RuntimeArg<'a, R>,
    ) -> Self::CompilationArg {
        TypedViewCompilationArg {
            buffer: <Array<Line<E>> as LaunchArg>::compilation_arg(&runtime_arg.buffer),
            layout: L::compilation_arg(&runtime_arg.layout),
        }
    }

    fn expand(
        arg: &Self::CompilationArg,
        builder: &mut KernelBuilder,
    ) -> <Self as CubeType>::ExpandType {
        let buffer = <Array<E> as LaunchArg>::expand(&arg.buffer, builder);
        L::apply::<E, Array<E>, IO>(L::expand(&arg.layout, builder), buffer)
    }
    fn expand_output(
        arg: &Self::CompilationArg,
        builder: &mut KernelBuilder,
    ) -> <Self as CubeType>::ExpandType {
        let buffer = <Array<E> as LaunchArg>::expand_output(&arg.buffer, builder);
        L::apply::<E, Array<E>, IO>(L::expand_output(&arg.layout, builder), buffer)
    }
}

mod seal {
    pub trait Sealed {}
}

pub trait LaunchLayout: LaunchArg + seal::Sealed {
    type SourceCoordinates: Coordinates;
    type Coordinates: Coordinates;

    fn apply<
        E: CubePrimitive,
        V: ViewOperationsMut<E, Self::SourceCoordinates> + 'static,
        IO: SliceVisibility,
    >(
        value: <Self as CubeType>::ExpandType,
        view: V::ExpandType,
    ) -> ViewExpand<E, Self::Coordinates, IO>;
}

// These unfortunately need to be manually implemented due to the dependencies of each layout on
// the coordinates of the next. Just stick with two layouts for now and add more implementations as
// needed.

impl<
    L: Layout
        + CubeType<ExpandType: VirtualLayoutOperationsExpand<L::Coordinates, L::SourceCoordinates>>
        + LaunchArg,
> seal::Sealed for L
{
}
impl<
    L: Layout
        + CubeType<ExpandType: VirtualLayoutOperationsExpand<L::Coordinates, L::SourceCoordinates>>
        + LaunchArg,
> LaunchLayout for L
{
    type SourceCoordinates = L::SourceCoordinates;
    type Coordinates = L::Coordinates;

    fn apply<
        E: CubePrimitive,
        V: ViewOperationsMut<E, Self::SourceCoordinates> + 'static,
        IO: SliceVisibility,
    >(
        value: L::ExpandType,
        view: V::ExpandType,
    ) -> ViewExpand<E, Self::Coordinates, IO> {
        let l0 = value;
        let l0 = VirtualLayoutExpand::new::<L::ExpandType>(l0);
        let view =
            VirtualViewMutExpand::<E, L::Coordinates, L::SourceCoordinates, V>::new(view, l0);
        ViewExpand::<E, L::Coordinates, IO> {
            inner: ViewType::ReadWrite(Arc::new(view)),
            _io: PhantomData,
        }
    }
}

impl<
    L0: Layout
        + CubeType<ExpandType: VirtualLayoutOperationsExpand<L0::Coordinates, L0::SourceCoordinates>>
        + LaunchArg,
    L1: Layout<SourceCoordinates = L0::Coordinates>
        + CubeType<ExpandType: VirtualLayoutOperationsExpand<L1::Coordinates, L1::SourceCoordinates>>
        + LaunchArg,
> seal::Sealed for (L0, L1)
{
}
impl<
    L0: Layout
        + CubeType<ExpandType: VirtualLayoutOperationsExpand<L0::Coordinates, L0::SourceCoordinates>>
        + LaunchArg,
    L1: Layout<SourceCoordinates = L0::Coordinates>
        + CubeType<ExpandType: VirtualLayoutOperationsExpand<L1::Coordinates, L1::SourceCoordinates>>
        + LaunchArg,
> LaunchLayout for (L0, L1)
{
    type SourceCoordinates = L0::SourceCoordinates;
    type Coordinates = L1::Coordinates;

    fn apply<
        E: CubePrimitive,
        V: ViewOperationsMut<E, Self::SourceCoordinates> + 'static,
        IO: SliceVisibility,
    >(
        value: (L0::ExpandType, L1::ExpandType),
        view: V::ExpandType,
    ) -> ViewExpand<E, Self::Coordinates, IO> {
        let (l0, l1) = value;
        let l0 = VirtualLayoutExpand::new::<L0::ExpandType>(l0);
        let view =
            VirtualViewMutExpand::<E, L0::Coordinates, L0::SourceCoordinates, V>::new(view, l0);
        let l1 = VirtualLayoutExpand::new::<L1::ExpandType>(l1);
        let view = VirtualViewMutExpand::<
            E,
            L1::Coordinates,
            L1::SourceCoordinates,
            VirtualViewMut<E, L0::Coordinates, L0::SourceCoordinates, V>,
        >::new(view, l1);
        ViewExpand::<E, L1::Coordinates, IO> {
            inner: ViewType::ReadWrite(Arc::new(view)),
            _io: PhantomData,
        }
    }
}

mod dynamic {
    use cubecl_common::quant::scheme::QuantScheme;

    use crate::{
        quant,
        tensor::layout::{
            VirtualLayout, VirtualLayoutCompilationArg, VirtualLayoutLaunch,
            as_dyn::{IntoDyn, IntoDynLayout, IntoDynLayoutLaunch},
        },
    };

    use super::*;

    pub enum ViewArg<'a, C: Coordinates, R: Runtime> {
        Array(ArrayArg<'a, R>, VirtualLayoutLaunch<'a, C, Coords1d, R>),
        TensorMap(
            TensorMapArg<'a, R>,
            VirtualLayoutLaunch<'a, C, Sequence<i32>, R>,
        ),
        Quantized {
            values: Box<ViewArg<'a, C, R>>,
            scales: Box<ViewArg<'a, C, R>>,
            scheme: QuantScheme,
        },
    }
    impl<'a, C: Coordinates, R: Runtime> ViewArg<'a, C, R> {
        pub fn new<L: Layout<Coordinates = C, SourceCoordinates = Coords1d> + LaunchArg>(
            buffer: ArrayArg<'a, R>,
            layout: L::RuntimeArg<'a, R>,
        ) -> Self {
            ViewArg::Array(buffer, VirtualLayoutLaunch::new::<L>(layout))
        }

        pub fn new_tensor_map<
            L: Layout<Coordinates = C, SourceCoordinates: IntoDyn> + LaunchArg,
        >(
            buffer: TensorMapArg<'a, R>,
            layout: L::RuntimeArg<'a, R>,
        ) -> Self {
            let layout = IntoDynLayoutLaunch::new(layout);
            ViewArg::TensorMap(buffer, VirtualLayoutLaunch::new::<IntoDynLayout<L>>(layout))
        }

        /// Create a new view arg that dequantizes on read.
        /// The scales layout should take values indices and map them to the corresponding scale.
        pub fn new_quantized(values: Self, scales: Self, scheme: QuantScheme) -> Self {
            Self::Quantized {
                values: Box::new(values),
                scales: Box::new(scales),
                scheme,
            }
        }
    }
    impl<'a, C: Coordinates, R: Runtime> ArgSettings<R> for ViewArg<'a, C, R> {
        fn register(&self, launcher: &mut KernelLauncher<R>) {
            match self {
                ViewArg::Array(buffer, layout) => {
                    buffer.register(launcher);
                    layout.register(launcher);
                }
                ViewArg::TensorMap(buffer, layout) => {
                    buffer.register(launcher);
                    layout.register(launcher);
                }
                ViewArg::Quantized { values, scales, .. } => {
                    values.register(launcher);
                    scales.register(launcher);
                }
            }
        }
    }
    #[derive(Clone)]
    pub enum ViewCompilationArg<C: Coordinates> {
        Array {
            buffer: ArrayCompilationArg,
            layout: VirtualLayoutCompilationArg<C, Coords1d>,
        },
        TensorMap {
            buffer: TensorMapCompilationArg,
            layout: VirtualLayoutCompilationArg<C, Sequence<i32>>,
        },
        Quantized {
            values: Box<ViewCompilationArg<C>>,
            scales: Box<ViewCompilationArg<C>>,
            scheme: QuantScheme,
        },
    }

    impl<C: Coordinates + 'static> CompilationArg for ViewCompilationArg<C> {}
    impl<C: Coordinates> Eq for ViewCompilationArg<C> {}
    impl<C: Coordinates> PartialEq for ViewCompilationArg<C> {
        fn eq(&self, other: &Self) -> bool {
            match (self, other) {
                (
                    ViewCompilationArg::Array { buffer, layout },
                    ViewCompilationArg::Array {
                        buffer: buffer_other,
                        layout: layout_other,
                    },
                ) => buffer == buffer_other && layout == layout_other,
                (
                    ViewCompilationArg::TensorMap { buffer, layout },
                    ViewCompilationArg::TensorMap {
                        buffer: buffer_other,
                        layout: layout_other,
                    },
                ) => buffer == buffer_other && layout == layout_other,
                (
                    ViewCompilationArg::Quantized {
                        values,
                        scales,
                        scheme,
                    },
                    ViewCompilationArg::Quantized {
                        values: values_other,
                        scales: scales_other,
                        scheme: scheme_other,
                    },
                ) => values == values_other && scales == scales_other && scheme == scheme_other,
                _ => false,
            }
        }
    }
    impl<C: Coordinates> core::hash::Hash for ViewCompilationArg<C> {
        fn hash<H: core::hash::Hasher>(&self, ra_expand_state: &mut H) {
            match self {
                ViewCompilationArg::Array { buffer, layout } => {
                    buffer.hash(ra_expand_state);
                    layout.hash(ra_expand_state);
                }
                ViewCompilationArg::TensorMap { buffer, layout } => {
                    buffer.hash(ra_expand_state);
                    layout.hash(ra_expand_state);
                }
                ViewCompilationArg::Quantized {
                    values,
                    scales,
                    scheme,
                } => {
                    values.hash(ra_expand_state);
                    scales.hash(ra_expand_state);
                    scheme.hash(ra_expand_state);
                }
            }
        }
    }
    impl<C: Coordinates> core::fmt::Debug for ViewCompilationArg<C> {
        fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
            match self {
                ViewCompilationArg::Array { buffer, layout } => f
                    .debug_struct("ArrayView")
                    .field("buffer", &buffer)
                    .field("layout", &layout)
                    .finish(),
                ViewCompilationArg::TensorMap { buffer, layout } => f
                    .debug_struct("TensorMapView")
                    .field("buffer", &buffer)
                    .field("layout", &layout)
                    .finish(),
                ViewCompilationArg::Quantized {
                    values,
                    scales,
                    scheme,
                } => f
                    .debug_struct("QuantizedView")
                    .field("values", &values)
                    .field("scales", &scales)
                    .field("scheme", &scheme)
                    .finish(),
            }
        }
    }

    impl<E: CubePrimitive, C: Coordinates + 'static, IO: SliceVisibility> LaunchArg for View<E, C, IO> {
        type RuntimeArg<'a, R: Runtime> = ViewArg<'a, C, R>;
        type CompilationArg = ViewCompilationArg<C>;

        fn compilation_arg<'a, R: Runtime>(
            runtime_arg: &Self::RuntimeArg<'a, R>,
        ) -> Self::CompilationArg {
            match runtime_arg {
                ViewArg::Array(buffer, layout) => {
                    let buffer = Array::<E>::compilation_arg(buffer);
                    let layout = VirtualLayout::<C, Coords1d>::compilation_arg(layout);
                    ViewCompilationArg::Array { buffer, layout }
                }
                ViewArg::TensorMap(buffer, layout) => {
                    let buffer = TensorMap::<E>::compilation_arg(buffer);
                    let layout = VirtualLayout::<C, Sequence<i32>>::compilation_arg(layout);
                    ViewCompilationArg::TensorMap { buffer, layout }
                }
                ViewArg::Quantized {
                    values,
                    scales,
                    scheme,
                } => {
                    // Type isn't real, but doesn't matter for compilation arg
                    let values = View::<E, C, IO>::compilation_arg(values);
                    let scales = View::<E, C, IO>::compilation_arg(scales);
                    ViewCompilationArg::Quantized {
                        values: Box::new(values),
                        scales: Box::new(scales),
                        scheme: *scheme,
                    }
                }
            }
        }
        fn expand(
            arg: &Self::CompilationArg,
            builder: &mut KernelBuilder,
        ) -> <Self as CubeType>::ExpandType {
            match arg {
                ViewCompilationArg::Array { buffer, layout } => {
                    let buffer = Array::<E>::expand(buffer, builder);
                    let layout = VirtualLayout::<C, Coords1d>::expand(layout, builder);
                    let view =
                        VirtualViewMutExpand::<E, C, Coords1d, Array<E>>::new(buffer, layout);
                    ViewExpand::<E, C, IO> {
                        inner: ViewType::ReadWrite(Arc::new(view)),
                        _io: PhantomData,
                    }
                }
                ViewCompilationArg::TensorMap { buffer, layout } => {
                    let buffer = TensorMap::<E>::expand(buffer, builder);
                    let layout = VirtualLayout::<C, Sequence<i32>>::expand(layout, builder);
                    let view = VirtualViewMutExpand::<E, C, Sequence<i32>, TensorMap<E>>::new(
                        buffer, layout,
                    );
                    ViewExpand::<E, C, IO> {
                        inner: ViewType::ReadWrite(Arc::new(view)),
                        _io: PhantomData,
                    }
                }
                ViewCompilationArg::Quantized {
                    values,
                    scales,
                    scheme,
                } => quant::view::expand_dynamic(values, scales, *scheme, builder),
            }
        }
        fn expand_output(
            arg: &Self::CompilationArg,
            builder: &mut KernelBuilder,
        ) -> <Self as CubeType>::ExpandType {
            match arg {
                ViewCompilationArg::Array { buffer, layout } => {
                    let buffer = Array::<E>::expand_output(buffer, builder);
                    let layout = VirtualLayout::<C, Coords1d>::expand_output(layout, builder);
                    let view =
                        VirtualViewMutExpand::<E, C, Coords1d, Array<E>>::new(buffer, layout);
                    ViewExpand::<E, C, IO> {
                        inner: ViewType::ReadWrite(Arc::new(view)),
                        _io: PhantomData,
                    }
                }
                ViewCompilationArg::TensorMap { buffer, layout } => {
                    let buffer = TensorMap::<E>::expand_output(buffer, builder);
                    let layout = VirtualLayout::<C, Sequence<i32>>::expand_output(layout, builder);
                    let view = VirtualViewMutExpand::<E, C, Sequence<i32>, TensorMap<E>>::new(
                        buffer, layout,
                    );
                    ViewExpand::<E, C, IO> {
                        inner: ViewType::ReadWrite(Arc::new(view)),
                        _io: PhantomData,
                    }
                }
                ViewCompilationArg::Quantized { .. } => panic!("Quantized views must be readonly"),
            }
        }
    }
}

pub use dynamic::*;