Skip to main content

cubecl_std/quant/
dequantize.rs

1use cubecl::prelude::*;
2use cubecl_common::quant::scheme::*;
3use cubecl_core as cubecl;
4use cubecl_core::ir::types::Fp8Format;
5use cubecl_core::post_processing::minifloat::fp8_bits_to_f32;
6
7/// Dequantize a vector of values, where `vector_size * num_quants` is a power of two.
8/// Unaligned values can't be dequantized in place.
9///
10/// `scale` is the effective scale for these values: how many scale levels the scheme has and how
11/// they combine is the caller's business, folded before the call. This is what keeps the
12/// primitive per-read arithmetic, serving equally a one-level read, a view multiplying the
13/// per-tensor scale in per read, or a tile handing every read one register.
14/// `table` is a lookup scheme's `2^bits`-entry table, and must be present exactly when
15/// `scheme.mode` is [`QuantMode::Lookup`].
16#[cube]
17pub fn dequantize_aligned<Q: Scalar, S: CubePrimitive, F: Numeric, NQ: Size, NF: Size>(
18    value: Vector<Q, NQ>,
19    scale: S,
20    table: ComptimeOption<Box<[f32]>>,
21    #[comptime] scheme: QuantScheme,
22) -> Vector<F, NF> {
23    comptime!(crate::quant::check_table_bindings(&scheme, table.is_some()));
24
25    let q_values = match scheme.store {
26        QuantStore::Native | QuantStore::PackedNative(_) => Vector::<F, NF>::cast_from(value),
27        QuantStore::PackedU32(_) => {
28            unpack_cast_u32::<F, NQ, NF>(Vector::cast_from(value), table.clone(), scheme)
29        }
30    };
31
32    match scheme.mode {
33        // Lookup already resolved the field to its table entry in the unpack; both modes are one
34        // scale multiply from there.
35        QuantMode::Symmetric | QuantMode::Lookup => q_values * Vector::<F, NF>::cast_from(scale),
36    }
37}
38
39/// [`dequantize_aligned`] for a scale a caller folded in f32, forming the product there too and
40/// narrowing only the result.
41///
42/// A folded scale reaches further down than what it produces: one below `F`'s smallest subnormal
43/// still scales quantized values into ordinary `F` ones. Narrowing it to `F` first rounds it to
44/// zero and takes the whole read with it, which is the failure two-level quantization exists to
45/// avoid in the first place.
46#[cube]
47pub fn dequantize_aligned_wide<Q: Scalar, F: Numeric, NQ: Size, NF: Size>(
48    value: Vector<Q, NQ>,
49    scale: f32,
50    table: ComptimeOption<Box<[f32]>>,
51    #[comptime] scheme: QuantScheme,
52) -> Vector<F, NF> {
53    Vector::<F, NF>::cast_from(dequantize_aligned::<Q, f32, f32, NQ, NF>(
54        value, scale, table, scheme,
55    ))
56}
57
58/// The effective scale of values whose per-tensor scale multiplies on top of their block scale.
59///
60/// The two multiply in f32: a block scale is normalized against the per-tensor one, so on its own
61/// it overflows a narrow compute type by orders of magnitude before the global scale can bring the
62/// product back into range.
63#[cube]
64pub fn multiply_global_scale<S: CubePrimitive>(global_scale: f32, scale: S) -> f32 {
65    global_scale * f32::cast_from(scale)
66}
67
68/// Unpack a set of values from u32, and convert to the specified floating point format.
69/// `table` decodes each field under [`QuantMode::Lookup`] and must be `None` otherwise
70/// ([`dequantize_aligned`] checks the pairing).
71#[cube]
72pub fn unpack_cast_u32<F: Numeric, NQ: Size, NF: Size>(
73    value: Vector<u32, NQ>,
74    table: ComptimeOption<Box<[f32]>>,
75    #[comptime] scheme: QuantScheme,
76) -> Vector<F, NF> {
77    let num_quants = scheme.num_quants();
78    let native_packing = scheme.native_packing();
79    let size_bits = scheme.size_bits_value();
80    let mask = comptime![packing_mask(scheme)];
81    let size!(NP) = native_packing;
82
83    let mut out = Vector::<F, NF>::empty();
84
85    #[unroll]
86    for vector_idx in 0..value.vector_size() {
87        let packed_val = value.extract(vector_idx);
88        let out_offset = vector_idx * num_quants;
89        #[unroll]
90        for packed_idx in range_stepped(0, num_quants, native_packing) {
91            let shift = packed_idx * size_bits;
92            let value = (packed_val >> shift as u32) & mask;
93
94            let float_value = cast_masked::<F, NP>(value, table.clone(), scheme);
95
96            #[unroll]
97            for native_idx in 0..native_packing {
98                let out_offset = out_offset + packed_idx + native_idx;
99                out.insert(out_offset, float_value.extract(native_idx));
100            }
101        }
102    }
103
104    out
105}
106
107/// Unpack `NF` consecutive fields of one `u32` word starting at field `first` (a runtime index),
108/// cast but **unscaled** — the caller multiplies by whatever scale its lines carry. The sub-word
109/// counterpart of [`unpack_cast_u32`], for reads whose served line is narrower than a word:
110/// `NF` may be any divisor of the packing factor, and `first` selects which slice of the word
111/// this line is. `e2m1` is refused — its native pairs cannot be split at a field boundary.
112///
113/// **The caller must keep `first + NF <= num_quants`.** `first` is runtime, so nothing here can
114/// check it, and a shift at or past 32 is not an error on most ISAs — the hardware masks the
115/// shift amount to 5 bits and the read silently lands on the wrong fields.
116#[cube]
117pub fn unpack_fields<F: Numeric, NF: Size>(
118    word: u32,
119    first: u32,
120    table: ComptimeOption<Box<[f32]>>,
121    #[comptime] scheme: QuantScheme,
122) -> Vector<F, NF> {
123    comptime!(assert!(
124        !matches!(scheme.value, QuantValue::E2M1),
125        "unpack_fields: e2m1 decodes in native pairs, which a sub-word line would split"
126    ));
127    let size_bits = scheme.size_bits_value();
128    let mask = comptime![packing_mask(scheme)];
129    let size!(N1) = 1usize;
130
131    let mut out = Vector::<F, NF>::empty();
132    #[unroll]
133    for j in 0..NF::value() {
134        let shift = (first + j as u32) * size_bits as u32;
135        let field = (word >> shift) & mask;
136        let value = cast_masked::<F, N1>(field, table.clone(), scheme);
137        out.insert(j, value.extract(0usize));
138    }
139    out
140}
141
142/// The mask required for each packed value, taking into account the native packing required for
143/// `e2m1`.
144fn packing_mask(scheme: QuantScheme) -> u32 {
145    let bits = match scheme.value {
146        QuantValue::E2M1 => 8, // Packed conversion
147        other => other.size_bits(),
148    };
149    (1u32 << bits) - 1
150}
151
152/// Cast a masked-out value in the low `n` bits of a `u32` to the specified float type.
153/// With a `table` the value is an index and the cast is its lookup; otherwise sign conversion
154/// is applied for integer quantization and minifloats are decoded in software.
155/// fp8 does not go through its type, as WGSL has no scalar fp8.
156///
157/// # Returns
158/// Two floating point numbers for `e2m1`, one for all other formats.
159#[cube]
160fn cast_masked<F: Numeric, N: Size>(
161    value: u32,
162    table: ComptimeOption<Box<[f32]>>,
163    #[comptime] scheme: QuantScheme,
164) -> Vector<F, N> {
165    #[comptime]
166    match table {
167        // The field indexes the table; the mask already bounds it to `2^bits`, the table's
168        // required length.
169        ComptimeOption::Some(t) => Vector::<F, N>::cast_from(t[value as usize]),
170        ComptimeOption::None => cast_masked_plain::<F, N>(value, scheme),
171    }
172}
173
174/// The tableless arm of [`cast_masked`]: sign conversion for the integers, software decode
175/// for the minifloats.
176#[cube]
177fn cast_masked_plain<F: Numeric, N: Size>(
178    value: u32,
179    #[comptime] scheme: QuantScheme,
180) -> Vector<F, N> {
181    match scheme.value {
182        QuantValue::E5M2 => Vector::<F, N>::cast_from(fp8_bits_to_f32::<N>(
183            Vector::<u32, N>::new(value),
184            Fp8Format::E5M2,
185        )),
186        QuantValue::E4M3 => Vector::<F, N>::cast_from(fp8_bits_to_f32::<N>(
187            Vector::<u32, N>::new(value),
188            Fp8Format::E4M3,
189        )),
190        QuantValue::E2M1 => crate::quant::fp4::e2m1_packed_bits_to_float::<F, N>(value),
191        QuantValue::Q8F
192        | QuantValue::Q4F
193        | QuantValue::Q2F
194        | QuantValue::Q8S
195        | QuantValue::Q4S
196        | QuantValue::Q2S => {
197            let size_quant = scheme.size_bits_value() as u32;
198            let sign_bit = 1u32 << (size_quant - 1);
199
200            // Branchless sign extension: `(raw ^ s) - s` with `s = 2^(n-1)` runs
201            // the identical xor/sub on every lane — two uniform vector ops on
202            // SIMD backends instead of a compare/select chain.
203            let signed_value = (value ^ sign_bit) as i32 - sign_bit as i32;
204            Vector::<F, N>::cast_from(signed_value)
205        }
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212    use cubecl_core::ir::{ElemType, Scope, UIntKind};
213    use cubecl_core::{define_size, ir::settings::Dim3};
214
215    define_size!(N1);
216
217    /// A root scope carries no typemap; the launcher normally picks the index width.
218    fn test_scope() -> Scope {
219        let scope = Scope::root(KernelSettings::new(
220            Dim3::new_single(),
221            ExecutionMode::Checked,
222            AddressType::U32,
223        ));
224        scope.register_size::<N1>(1);
225        scope.register_type::<usize>(ElemType::UInt(UIntKind::U32));
226        scope
227    }
228
229    /// The primitive is level-agnostic: it takes the effective scale for the values it unpacks,
230    /// and how many levels folded into that scale is the caller's business.
231    #[test]
232    fn expanding_takes_one_scale_whatever_the_levels() {
233        let scope = test_scope();
234        let one = f32::__expand_new(&scope, 1.0);
235        let value = Vector::<f32, N1>::__expand_new(&scope, one);
236
237        for scheme in [
238            QuantScheme::default(),
239            QuantScheme::default().per_block([32], ScaleDtype::F32),
240            QuantScheme::default()
241                .per_block([32], ScaleDtype::F32)
242                .per_tensor(ScaleDtype::F32),
243        ] {
244            dequantize_aligned::expand::<f32, f32, f32, N1, N1>(
245                &scope,
246                value,
247                one,
248                ComptimeOptionExpand::None,
249                scheme,
250            );
251        }
252    }
253}