oxillama-quant 0.1.2

Quantization kernels for all GGUF quantization types
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
//! Q6_K reference (naive) implementation.
//!
//! Q6_K block format (210 bytes per 256 weights):
//! - 128 bytes: ql — lower 4 bits of 6-bit quants (2 per byte)
//! - 64 bytes: qh — upper 2 bits of 6-bit quants (4 per byte)
//! - 16 bytes: scales — 16 × int8 signed scales (one per 16-weight sub-block)
//! - 2 bytes: FP16 super-block scale (d)
//!
//! Q6_K is a symmetric ("type-0") format: no minimum offset.
//! Weight formula: `w = d * scale_i * (q_6bit - 32)`
//!
//! Effective: 6.5625 bits/weight.

use crate::error::{QuantError, QuantResult};
use crate::traits::QuantKernel;
use crate::types::QuantTensor;

const Q6_K_BLOCK_SIZE: usize = 256;
const Q6_K_BLOCK_BYTES: usize = 210;

/// Reference (naive scalar) Q6_K kernel.
pub struct Q6KRef;

impl QuantKernel for Q6KRef {
    fn dequant_block(&self, block: &[u8], output: &mut [f32]) -> QuantResult<()> {
        if block.len() < Q6_K_BLOCK_BYTES {
            return Err(QuantError::BufferTooSmall {
                needed: Q6_K_BLOCK_BYTES,
                available: block.len(),
            });
        }
        if output.len() < Q6_K_BLOCK_SIZE {
            return Err(QuantError::BufferTooSmall {
                needed: Q6_K_BLOCK_SIZE,
                available: output.len(),
            });
        }

        let ql = &block[0..128];
        let qh = &block[128..192];
        let scales = &block[192..208];
        let d = f16_to_f32(u16::from_le_bytes([block[208], block[209]]));

        // Process in 2 groups of 128 weights
        for group in 0..2 {
            let ql_off = group * 64;
            let qh_off = group * 32;
            let sc_off = group * 8;
            let out_off = group * 128;

            for l in 0..32 {
                let is = l / 16; // sub-block index within group: 0 or 1

                // Assemble 6-bit quants from ql (4 low bits) and qh (2 high bits)
                let q1 = ((ql[ql_off + l] & 0x0F) | ((qh[qh_off + l] & 3) << 4)) as i32 - 32;
                let q2 =
                    ((ql[ql_off + l + 32] & 0x0F) | (((qh[qh_off + l] >> 2) & 3) << 4)) as i32 - 32;
                let q3 = ((ql[ql_off + l] >> 4) | (((qh[qh_off + l] >> 4) & 3) << 4)) as i32 - 32;
                let q4 =
                    ((ql[ql_off + l + 32] >> 4) | (((qh[qh_off + l] >> 6) & 3) << 4)) as i32 - 32;

                let s0 = scales[sc_off + is] as i8 as f32;
                let s1 = scales[sc_off + is + 2] as i8 as f32;
                let s2 = scales[sc_off + is + 4] as i8 as f32;
                let s3 = scales[sc_off + is + 6] as i8 as f32;

                output[out_off + l] = d * s0 * q1 as f32;
                output[out_off + l + 32] = d * s1 * q2 as f32;
                output[out_off + l + 64] = d * s2 * q3 as f32;
                output[out_off + l + 96] = d * s3 * q4 as f32;
            }
        }

        Ok(())
    }

    fn gemv(
        &self,
        quant_matrix: &QuantTensor,
        input: &[f32],
        output: &mut [f32],
    ) -> QuantResult<()> {
        let n_rows = quant_matrix.shape[0];
        let n_cols = if quant_matrix.shape.len() > 1 {
            quant_matrix.shape[1]
        } else {
            quant_matrix.n_elements() / n_rows
        };

        if input.len() < n_cols {
            return Err(QuantError::DimensionMismatch {
                expected: n_cols,
                got: input.len(),
            });
        }
        if output.len() < n_rows {
            return Err(QuantError::DimensionMismatch {
                expected: n_rows,
                got: output.len(),
            });
        }

        let blocks_per_row = n_cols.div_ceil(Q6_K_BLOCK_SIZE);
        let row_bytes = blocks_per_row * Q6_K_BLOCK_BYTES;

        for (row, out) in output.iter_mut().enumerate().take(n_rows) {
            let row_start = row * row_bytes;
            let mut sum = 0.0f32;

            for blk in 0..blocks_per_row {
                let bo = row_start + blk * Q6_K_BLOCK_BYTES;
                let data = &quant_matrix.data;
                let ql = &data[bo..bo + 128];
                let qh = &data[bo + 128..bo + 192];
                let scales = &data[bo + 192..bo + 208];
                let d = f16_to_f32(u16::from_le_bytes([data[bo + 208], data[bo + 209]]));
                let inp = &input[blk * Q6_K_BLOCK_SIZE..];
                // Number of valid columns in this (possibly partial) block.
                let cols_in_block = (n_cols - blk * Q6_K_BLOCK_SIZE).min(Q6_K_BLOCK_SIZE);

                // Inline dot product: extract 6-bit quants on-the-fly
                for group in 0..2 {
                    let ql_off = group * 64;
                    let qh_off = group * 32;
                    let sc_off = group * 8;
                    let in_off = group * 128;

                    for l in 0..32 {
                        let is = l / 16;
                        let q1 =
                            ((ql[ql_off + l] & 0x0F) | ((qh[qh_off + l] & 3) << 4)) as i32 - 32;
                        let q2 = ((ql[ql_off + l + 32] & 0x0F) | (((qh[qh_off + l] >> 2) & 3) << 4))
                            as i32
                            - 32;
                        let q3 = ((ql[ql_off + l] >> 4) | (((qh[qh_off + l] >> 4) & 3) << 4))
                            as i32
                            - 32;
                        let q4 = ((ql[ql_off + l + 32] >> 4) | (((qh[qh_off + l] >> 6) & 3) << 4))
                            as i32
                            - 32;

                        let s0 = d * scales[sc_off + is] as i8 as f32;
                        let s1 = d * scales[sc_off + is + 2] as i8 as f32;
                        let s2 = d * scales[sc_off + is + 4] as i8 as f32;
                        let s3 = d * scales[sc_off + is + 6] as i8 as f32;

                        let c0 = in_off + l;
                        let c1 = in_off + l + 32;
                        let c2 = in_off + l + 64;
                        let c3 = in_off + l + 96;

                        if c0 < cols_in_block {
                            sum += s0 * q1 as f32 * inp[c0];
                        }
                        if c1 < cols_in_block {
                            sum += s1 * q2 as f32 * inp[c1];
                        }
                        if c2 < cols_in_block {
                            sum += s2 * q3 as f32 * inp[c2];
                        }
                        if c3 < cols_in_block {
                            sum += s3 * q4 as f32 * inp[c3];
                        }
                    }
                }
            }

            *out = sum;
        }

        Ok(())
    }

    fn gemm(
        &self,
        quant_matrix: &QuantTensor,
        input: &[f32],
        output: &mut [f32],
        m: usize,
        n: usize,
        k: usize,
    ) -> QuantResult<()> {
        for row in 0..m {
            let input_row = &input[row * k..(row + 1) * k];
            let output_row = &mut output[row * n..(row + 1) * n];
            self.gemv(quant_matrix, input_row, output_row)?;
        }
        Ok(())
    }

    fn block_size(&self) -> usize {
        Q6_K_BLOCK_SIZE
    }

    fn block_bytes(&self) -> usize {
        Q6_K_BLOCK_BYTES
    }

    fn name(&self) -> &'static str {
        "Q6_K"
    }

    /// Override of `matvec_q8_fused` required because the trait default is wrong for Q6_K.
    ///
    /// Q6_K (block_size=256) maps 1 weight super-block → 8 Q8_0 activation blocks.
    /// Sub-block `s` (0..16) with 16 weights each → Q8_0 at index `blk * 8 + s/2`.
    ///
    /// # Formula
    /// Each 256-weight block has 16 sub-blocks of 16 weights.  Pairs of sub-blocks
    /// share a Q8_0 activation block (32 activations).  Per sub-block:
    /// `contrib = d_a * d * scale_s * Σ(q6_centered * q_a)`
    fn matvec_q8_fused(
        &self,
        weights: &[u8],
        acts_q8: &[u8],
        out: &mut [f32],
        n_rows: usize,
        n_cols: usize,
    ) -> QuantResult<()> {
        if out.len() < n_rows {
            return Err(QuantError::DimensionMismatch {
                expected: n_rows,
                got: out.len(),
            });
        }

        let blocks_per_row = n_cols.div_ceil(Q6_K_BLOCK_SIZE);
        let row_bytes = blocks_per_row * Q6_K_BLOCK_BYTES;
        // Each Q6_K super-block maps to 8 Q8_0 activation blocks.
        let q8_blocks_per_row = blocks_per_row * 8;
        let acts_needed = q8_blocks_per_row * Q8_0_BLOCK_BYTES;

        if weights.len() < n_rows * row_bytes {
            return Err(QuantError::BufferTooSmall {
                needed: n_rows * row_bytes,
                available: weights.len(),
            });
        }
        if acts_q8.len() < acts_needed {
            return Err(QuantError::BufferTooSmall {
                needed: acts_needed,
                available: acts_q8.len(),
            });
        }

        for (row, out_val) in out.iter_mut().enumerate().take(n_rows) {
            let row_start = row * row_bytes;
            let mut sum = 0.0f32;

            for blk in 0..blocks_per_row {
                let bo = row_start + blk * Q6_K_BLOCK_BYTES;
                let block = &weights[bo..bo + Q6_K_BLOCK_BYTES];

                let ql = &block[0..128];
                let qh = &block[128..192];
                let scales = &block[192..208];
                let d = f16_to_f32(u16::from_le_bytes([block[208], block[209]]));

                let input_offset = blk * Q6_K_BLOCK_SIZE;
                let cols_in_block = (n_cols - input_offset).min(Q6_K_BLOCK_SIZE);

                // Q6_K has 16 sub-blocks of 16 weights each.  Pairs share one Q8_0 block (32 acts).
                // group=0..2 covers group*128 weights;  l=0..32 within a group covers 4 sub-values.
                for group in 0..2 {
                    let ql_off = group * 64;
                    let qh_off = group * 32;
                    let sc_off = group * 8;
                    let in_off = group * 128;

                    for l in 0..32 {
                        let is = l / 16; // sub-block index within group (0 or 1)

                        let q1 =
                            ((ql[ql_off + l] & 0x0F) | ((qh[qh_off + l] & 3) << 4)) as i32 - 32;
                        let q2 = ((ql[ql_off + l + 32] & 0x0F) | (((qh[qh_off + l] >> 2) & 3) << 4))
                            as i32
                            - 32;
                        let q3 = ((ql[ql_off + l] >> 4) | (((qh[qh_off + l] >> 4) & 3) << 4))
                            as i32
                            - 32;
                        let q4 = ((ql[ql_off + l + 32] >> 4) | (((qh[qh_off + l] >> 6) & 3) << 4))
                            as i32
                            - 32;

                        let s0 = d * scales[sc_off + is] as i8 as f32;
                        let s1 = d * scales[sc_off + is + 2] as i8 as f32;
                        let s2 = d * scales[sc_off + is + 4] as i8 as f32;
                        let s3 = d * scales[sc_off + is + 6] as i8 as f32;

                        // Each pair of sub-blocks (is=0 or 1) maps to Q8_0 activation block
                        // at index `blk*8 + group*4 + is*2 + (column_half)`.
                        // The column mapping is:
                        //   c0 = in_off + l        (sub-block group*2 + 0, first half)
                        //   c2 = in_off + l + 64   (sub-block group*2 + 0, second half)
                        //   c1 = in_off + l + 32   (sub-block group*2 + 1, first half)
                        //   c3 = in_off + l + 96   (sub-block group*2 + 1, second half)
                        // Sub-blocks for c0/c2 share Q8_0 block = blk*8 + group*4 + is*2
                        // Sub-blocks for c1/c3 share Q8_0 block = blk*8 + group*4 + is*2 + 1
                        // BUT c0 and c2 are in different 16-weight sub-blocks mapped to different Q8_0.
                        // Correct mapping: each 32-weight half-group uses one Q8_0 block.
                        //   c0, c1 (l in 0..32 → in_off + l, in_off + l + 32): Q8_0 at blk*8 + group*4 + 2*is
                        //                                                         and blk*8 + group*4 + 2*is + 1
                        //   c2, c3 (in_off + l + 64, in_off + l + 96):          Q8_0 at blk*8 + group*4 + 2*is + 2
                        //                                                         and blk*8 + group*4 + 2*is + 3

                        // For simplicity: use the 4-activation-block grouping.
                        // The 256 weights decompose into 8 groups of 32, one Q8_0 per group:
                        // group 0: cols 0..32     Q8_0 #0
                        // group 1: cols 32..64    Q8_0 #1
                        // ...
                        // group 7: cols 224..256  Q8_0 #7
                        // But Q6_K's layout interleaves columns differently.  We accumulate per
                        // weight-column directly, resolving the Q8_0 block from the column index.

                        let c0 = in_off + l;
                        let c1 = in_off + l + 32;
                        let c2 = in_off + l + 64;
                        let c3 = in_off + l + 96;

                        let get_q8_sample = |col: usize| -> Option<f32> {
                            if col >= cols_in_block {
                                return None;
                            }
                            // Column `col` is within the super-block; find Q8_0 block index.
                            let q8_blk = blk * 8 + col / 32;
                            let q8_lane = col % 32;
                            let ab = &acts_q8
                                [q8_blk * Q8_0_BLOCK_BYTES..(q8_blk + 1) * Q8_0_BLOCK_BYTES];
                            let d_a = f16_to_f32(u16::from_le_bytes([ab[0], ab[1]]));
                            let q_a = ab[2 + q8_lane] as i8 as f32;
                            Some(d_a * q_a)
                        };

                        if let Some(a0) = get_q8_sample(c0) {
                            sum += s0 * q1 as f32 * a0;
                        }
                        if let Some(a1) = get_q8_sample(c1) {
                            sum += s1 * q2 as f32 * a1;
                        }
                        if let Some(a2) = get_q8_sample(c2) {
                            sum += s2 * q3 as f32 * a2;
                        }
                        if let Some(a3) = get_q8_sample(c3) {
                            sum += s3 * q4 as f32 * a3;
                        }
                    }
                }
            }

            *out_val += sum;
        }

        Ok(())
    }
}

/// Q8_0 activation block byte count used in fused GEMV.
const Q8_0_BLOCK_BYTES: usize = 34;

fn f16_to_f32(bits: u16) -> f32 {
    half::f16::from_bits(bits).to_f32()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_dequant_zero_scale() {
        let block = vec![0u8; Q6_K_BLOCK_BYTES];
        let kernel = Q6KRef;
        let mut output = vec![0.0f32; 256];
        kernel.dequant_block(&block, &mut output).unwrap();

        // d=0 → all weights = 0 (q-32 doesn't matter since d=0)
        for &v in &output {
            assert!((v).abs() < 1e-5, "expected 0, got {v}");
        }
    }

    #[test]
    fn test_dequant_simple() {
        // Construct a block where all 6-bit quants = 32 (so q-32 = 0)
        // ql: lower 4 bits of 32 = 0, qh: upper 2 bits of 32 = 2 (binary: 10_0000)
        let mut block = vec![0u8; Q6_K_BLOCK_BYTES];

        // ql = all 0x00 (lower 4 bits of quant value 32 is 0)
        // qh: each byte stores 4 values' upper 2 bits
        // value 32 = 0b100000, upper 2 bits = 0b10 = 2
        // qh[l] should have bits: q1_hi=2, q2_hi=2, q3_hi=2, q4_hi=2
        // packed: (2<<0)|(2<<2)|(2<<4)|(2<<6) = 2 + 8 + 32 + 128 = 0xAA
        for i in 0..64 {
            block[128 + i] = 0xAA;
        }

        // scales = 1 for all sub-blocks
        for i in 0..16 {
            block[192 + i] = 1;
        }

        // d = 1.0
        let d_bits = half::f16::from_f32(1.0).to_bits();
        block[208] = (d_bits & 0xFF) as u8;
        block[209] = ((d_bits >> 8) & 0xFF) as u8;

        let kernel = Q6KRef;
        let mut output = vec![0.0f32; 256];
        kernel.dequant_block(&block, &mut output).unwrap();

        // All quants = 32, so q-32 = 0, weight = d * scale * 0 = 0
        for (i, &v) in output.iter().enumerate() {
            assert!((v).abs() < 0.01, "weight[{i}] = {v}, expected 0");
        }
    }

    #[test]
    fn test_gemv_q6_k() {
        // Build a 1x256 matrix: random-ish block data
        let mut block = vec![0u8; Q6_K_BLOCK_BYTES];
        // Set some ql values
        for (i, b) in block.iter_mut().enumerate().take(128) {
            *b = ((i * 7 + 3) & 0xFF) as u8;
        }
        // Set some qh values
        for i in 0..64 {
            block[128 + i] = ((i * 13 + 5) & 0xFF) as u8;
        }
        // Set scales
        for i in 0..16 {
            block[192 + i] = (i as i8 * 3 - 8) as u8;
        }
        // d = 0.5
        let d_bits = half::f16::from_f32(0.5).to_bits().to_le_bytes();
        block[208] = d_bits[0];
        block[209] = d_bits[1];

        let kernel = Q6KRef;

        // Dequant reference
        let mut dequant = vec![0.0f32; 256];
        kernel.dequant_block(&block, &mut dequant).unwrap();

        // Input vector
        let input: Vec<f32> = (0..256).map(|i| (i as f32 * 0.01) - 1.28).collect();

        // Reference: manual dot product
        let expected: f32 = dequant.iter().zip(input.iter()).map(|(w, x)| w * x).sum();

        // GEMV
        let tensor = QuantTensor::new(block, vec![1, 256], oxillama_gguf::GgufTensorType::Q6K);
        let mut output = vec![0.0f32; 1];
        kernel.gemv(&tensor, &input, &mut output).unwrap();

        assert!(
            (output[0] - expected).abs() < 0.1,
            "gemv={}, expected={}",
            output[0],
            expected
        );
    }
}