cubek-quant 0.3.0-pre.3

CubeK: Quantization 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
use cubecl::{
    calculate_cube_count_elemwise,
    features::TypeUsage,
    ir::ElemType,
    prelude::*,
    std::{
        quant::{check_scale_bindings, round::round_up_to_dtype},
        tensor::{
            View, ViewMut, into_contiguous,
            layout::linear::{LinearView, LinearViewMut, linear_view},
        },
    },
    tensor_vector_size_parallel,
};

use crate::{
    layout::{ScalesLayout, ScalesViewMut, scales_view},
    scale::{GlobalScale, Scale, split_levels},
    utils::{check_block_size_compat, packed_storage_elem},
};
use crate::{
    layout::{ScalesView, scales_layout},
    scheme::{QuantMode, QuantScheme, QuantStore, QuantValue, ScaleDtype},
};

#[cube]
fn quantize_symmetric<F: Float, N: Size, FS: CubePrimitive>(
    value: Vector<F, N>,
    scale: Scale<FS>,
    range_min: F,
    range_max: F,
) -> Vector<F, N> {
    clamp(
        Vector::round(scale.quantize_symmetric::<F, N>(value)),
        Vector::new(range_min),
        Vector::new(range_max),
    )
}

#[cube]
fn quantize_symmetric_q<F: Float, N: Size, FS: CubePrimitive, Q: Scalar>(
    value: Vector<F, N>,
    scale: Scale<FS>,
    range_min: F,
    range_max: F,
) -> Vector<Q, N> {
    Vector::cast_from(quantize_symmetric::<F, N, FS>(
        value, scale, range_min, range_max,
    ))
}

#[cube]
fn quantize_packed_value<F: Float, N: Size, FS: CubePrimitive, QS: Int>(
    value: Vector<F, N>,
    scale: Scale<FS>,
    range_min: F,
    range_max: F,
    #[comptime] scheme: QuantScheme,
) -> QS {
    let value = quantize_symmetric::<F, N, FS>(value, scale, range_min, range_max);
    pack_q::<F, N, QS>(value, scheme.value)
}

/// Pack a vector of quantized floating-point values into a single integer (the stored quantization type),
/// according to the specified quantization input type.
#[allow(clippy::explicit_counter_loop)]
#[cube]
fn pack_q<F: Float, N: Size, QS: Int>(value: Vector<F, N>, #[comptime] quant: QuantValue) -> QS {
    let size_quant = quant.size_bits();

    let size_store = QS::size_bits().comptime();
    let num_quants = size_store / size_quant;

    let mask = (1 << size_quant) - 1;
    let mut packed = QS::from_int(0);

    // Shift and combine into QS (using i32 for sign extension)
    #[unroll]
    for position in 0..num_quants {
        let offset = QS::cast_from(position * size_quant);
        let shifted = QS::cast_from(i32::cast_from(value.extract(position)) & mask) << offset;
        packed |= shifted;
    }

    packed
}

#[cube]
fn write_scale<F: Float, FS: CubePrimitive>(
    in_pos: usize,
    scale: View<F, usize>,
    mut out_scale: ViewMut<FS, usize>,
    global: &GlobalScale,
    scales_layout: ScalesLayout,
    #[comptime] param: ScaleDtype,
) -> Scale<FS> {
    // Rounded up rather than cast to nearest, which can land below the scale calibration asked for
    // and clip every value at the block maximum. The CPU backends round up too, and both have to,
    // or a tensor quantized on one reconstructs differently on the other.
    let inner = FS::cast_from(round_up_to_dtype::<F>(scale.read(in_pos), param));

    // Write the scale into the output buffer
    if scales_layout.is_block_start(in_pos) {
        out_scale.write(in_pos, inner);
    }

    global.at::<FS>(inner)
}

#[cube(launch_unchecked, address_type = "dynamic")]
fn quantize_symmetric_native_kernel<F: Float, N: Size, FS: Numeric, Q: Numeric>(
    input: LinearView<'_, Vector<F, N>>,
    scale: ScalesView<'_, F>,
    global: ComptimeOption<LinearView<'_, f32>>,
    range_min: InputScalar,
    range_max: InputScalar,
    mut output: LinearViewMut<'_, Vector<Q, N>>,
    out_scale: ScalesViewMut<'_, FS>,
    out_global: ComptimeOption<LinearViewMut<'_, f32>>,
    scales_layout: ScalesLayout,
    #[comptime] param: ScaleDtype,
    #[define(F, FS, Q)] _dtypes: [ElemType; 3],
) {
    if !output.is_in_bounds(ABSOLUTE_POS) {
        terminate!();
    }

    let native_packing = Q::packing_factor();
    let in_pos = ABSOLUTE_POS * input.vector_size() * native_packing;
    let global = GlobalScale::read(global);
    global.write(out_global);
    let scale = write_scale(in_pos, scale, out_scale, &global, scales_layout, param);

    output.write(
        ABSOLUTE_POS,
        quantize_symmetric_q::<F, N, FS, Q>(
            input.read(ABSOLUTE_POS),
            scale,
            range_min.get::<F>(),
            range_max.get::<F>(),
        ),
    );
}

#[cube(launch_unchecked, address_type = "dynamic")]
fn quantize_symmetric_packed_kernel<F: Float, N: Size, FS: Numeric, QS: Int>(
    input: LinearView<'_, Vector<F, N>>,
    scale: ScalesView<'_, F>,
    global: ComptimeOption<LinearView<'_, f32>>,
    range_min: InputScalar,
    range_max: InputScalar,
    mut output: LinearViewMut<'_, QS>,
    out_scale: ScalesViewMut<'_, FS>,
    out_global: ComptimeOption<LinearViewMut<'_, f32>>,
    scales_layout: ScalesLayout,
    #[comptime] scheme: QuantScheme,
    #[define(F, FS, QS)] _dtypes: [ElemType; 3],
) {
    if !output.is_in_bounds(ABSOLUTE_POS) {
        terminate!();
    }

    let num_quants = scheme.num_quants();
    let packed_pos = ABSOLUTE_POS * num_quants;
    let global = GlobalScale::read(global);
    global.write(out_global);
    let scale = write_scale(
        packed_pos,
        scale,
        out_scale,
        &global,
        scales_layout,
        scheme.scale_dtype(),
    );

    if input.vector_size().comptime() == num_quants {
        output.write(
            ABSOLUTE_POS,
            quantize_packed_value::<F, N, FS, QS>(
                input.read(ABSOLUTE_POS),
                scale,
                range_min.get::<F>(),
                range_max.get::<F>(),
                scheme,
            ),
        );
    } else {
        // Input vector size = 1
        let size!(NQ) = num_quants;
        let mut values = Vector::<F, NQ>::empty();
        #[unroll]
        for i in 0..num_quants {
            values.insert(i, input.read(packed_pos + i).extract(0usize));
        }
        output.write(
            ABSOLUTE_POS,
            quantize_packed_value::<F, NQ, FS, QS>(
                values,
                scale,
                range_min.get::<F>(),
                range_max.get::<F>(),
                scheme,
            ),
        );
    }
}

#[allow(clippy::result_large_err)]
pub fn launch_ref<R: Runtime>(
    client: &ComputeClient<R>,
    input: TensorBinding<R>,
    output: TensorBinding<R>,
    scales: &[TensorBinding<R>],
    out_scales: &[TensorBinding<R>],
    scheme: &QuantScheme,
    input_elem: ElemType,
) -> Result<(), LaunchError> {
    check_scale_bindings(scheme, scales.len());
    check_scale_bindings(scheme, out_scales.len());
    // Refused here rather than during kernel expansion, where the caller can no longer read the
    // scheme off the error.
    assert!(
        scheme.scale_dtype().round_up(1.0).is_some(),
        "{:?} scales have no round-up rule, which quantization requires",
        scheme.scale_dtype()
    );

    let scale_dtype = ElemType::from_scale_dtype(scheme.scale_dtype());
    let (scale, global) = split_levels(scales);
    let (out_scale, out_global) = split_levels(out_scales);

    match scheme {
        QuantScheme {
            store: QuantStore::PackedU32(_),
            ..
        } => quantize_packed(
            client,
            input,
            scheme,
            scale,
            global,
            out_scale,
            out_global,
            output,
            input_elem,
            scale_dtype,
        ),
        QuantScheme {
            value: QuantValue::Q8F | QuantValue::Q8S | QuantValue::E4M3 | QuantValue::E5M2,
            store: QuantStore::Native,
            ..
        }
        | QuantScheme {
            value: QuantValue::E2M1,
            store: QuantStore::PackedNative(_),
            ..
        } => {
            if !i8::supported_uses(client).contains(TypeUsage::Conversion) {
                panic!(
                    "{:?} is not supported for native quantization",
                    scheme.value
                );
            }

            quantize_native(
                client,
                input,
                scheme,
                scale,
                global,
                out_scale,
                out_global,
                output,
                input_elem,
                scale_dtype,
            )
        }
        QuantScheme {
            store: QuantStore::Native | QuantStore::PackedNative(_),
            value,
            ..
        } => {
            panic!("{value:?} is not supported for native quantization");
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn quantize_native<R: Runtime>(
    client: &ComputeClient<R>,
    input: TensorBinding<R>,
    scheme: &QuantScheme,
    scale: TensorBinding<R>,
    global: Option<TensorBinding<R>>,
    out_scale: TensorBinding<R>,
    out_global: Option<TensorBinding<R>>,
    output: TensorBinding<R>,
    input_dtype: ElemType,
    scale_dtype: ElemType,
) -> Result<(), LaunchError> {
    let num_elems: usize = input.shape.iter().product();
    let output_dtype = ElemType::from_quant_value(scheme.value);

    let candidates = client.io_optimized_vector_sizes(input_dtype.size().max(output_dtype.size()));
    let vector_size = tensor_vector_size_parallel(
        candidates,
        &input.shape,
        &input.strides,
        input.shape.len() - 1,
    );

    let working_units = num_elems / vector_size as usize;
    let cube_dim = CubeDim::new(client, working_units);
    let cube_count = calculate_cube_count_elemwise(client, working_units, cube_dim);
    let (range_min, range_max) = scheme.value.range();

    match scheme {
        QuantScheme {
            mode: QuantMode::Symmetric,
            store: QuantStore::Native,
            ..
        } => {
            // We could use vector_size = block_size if it's in the supported vector sizes.. but let's keep it simple
            check_block_size_compat(scheme, vector_size as usize);

            let address_type = input
                .required_address_type(input_dtype.size())
                .max(scale.required_address_type(scale_dtype.size()))
                .max(output.required_address_type(output_dtype.size()));

            let scales_layout = scales_layout(&output, &scale, 1, scheme);

            unsafe {
                quantize_symmetric_native_kernel::launch_unchecked(
                    client,
                    cube_count,
                    cube_dim,
                    address_type,
                    vector_size,
                    linear_view(input),
                    // scale is computed based on input float dtype, but stored based on qparams precision
                    scales_view(output.clone(), scale, 1, scheme),
                    global.map(linear_view).into(),
                    InputScalar::new(range_min, input_dtype),
                    InputScalar::new(range_max, input_dtype),
                    linear_view(output.clone()),
                    scales_view(output, out_scale, 1, scheme),
                    out_global.map(linear_view).into(),
                    scales_layout,
                    scheme.scale_dtype(),
                    [input_dtype, scale_dtype, output_dtype],
                )
            }
        }
        _ => panic!("Unsupported quantization scheme {scheme:?}"),
    };

    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn quantize_packed<R: Runtime>(
    client: &ComputeClient<R>,
    input: TensorBinding<R>,
    scheme: &QuantScheme,
    scale: TensorBinding<R>,
    global: Option<TensorBinding<R>>,
    out_scale: TensorBinding<R>,
    out_global: Option<TensorBinding<R>>,
    output: TensorBinding<R>,
    input_dtype: ElemType,
    scale_dtype: ElemType,
) -> Result<(), LaunchError> {
    let num_elems: usize = input.shape.iter().product();

    // Determine if we can use vectorized packing
    let mut can_vectorize = match scheme {
        QuantScheme {
            mode: QuantMode::Symmetric,
            store: QuantStore::PackedU32(dim),
            ..
        } => {
            // Check if packing dim is contiguous
            let ndims = input.shape.len();
            input.strides[ndims - 1 - *dim] == 1
        }
        QuantScheme { .. } => panic!("Unsupported quantization scheme {scheme:?}"),
    };
    // For larger tensors, copying to contiguous memory should be faster than scalar reads.
    // 2048 is a conservative floor for the threshold, could be tuned.
    let num_quants = scheme.num_quants();
    let input = if !can_vectorize && num_elems >= 2048 {
        can_vectorize = true;
        into_contiguous(client, input, input_dtype).binding()
    } else {
        input
    };

    // Elements to pack are strided, require scalar reads + manual gather
    let vector_size = if can_vectorize { num_quants } else { 1 };

    let working_units = num_elems.div_ceil(vector_size);
    let cube_dim = CubeDim::new(client, working_units);
    let cube_count = calculate_cube_count_elemwise(client, working_units, cube_dim);
    let (range_min, range_max) = scheme.value.range();
    let output_dtype = packed_storage_elem(scheme);

    let address_type = input
        .required_address_type(input_dtype.size())
        .max(scale.required_address_type(scale_dtype.size()))
        .max(output.required_address_type(output_dtype.size()));

    check_block_size_compat(scheme, num_quants); // 32 / 8 = 4

    let scales_layout = scales_layout(&output, &scale, 1, scheme);

    unsafe {
        quantize_symmetric_packed_kernel::launch_unchecked(
            client,
            cube_count,
            cube_dim,
            address_type,
            vector_size,
            linear_view(input),
            // scale is computed based on input float dtype, but stored based on qparams precision
            scales_view(output.clone(), scale, 1, scheme),
            global.map(linear_view).into(),
            InputScalar::new(range_min, input_dtype),
            InputScalar::new(range_max, input_dtype),
            linear_view(output.clone()),
            scales_view(output, out_scale, 1, scheme),
            out_global.map(linear_view).into(),
            scales_layout,
            *scheme,
            [input_dtype, scale_dtype, output_dtype],
        )
    };

    Ok(())
}