oxillama-quant 0.1.0

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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! AVX2+FMA accelerated Q4_K quantization kernel.
//!
//! Q4_K block layout (144 bytes per 256 weights):
//! - bytes[0..2]   — FP16 super-block scale `d` (little-endian)
//! - bytes[2..4]   — FP16 super-block minimum `dmin` (little-endian)
//! - bytes[4..16]  — 12 bytes encoding 8 sub-block scales + 8 sub-block mins,
//!                   6 bits each, packed (see `decode_scales_mins`)
//! - bytes[16..144] — 128 packed nibble bytes (256 × 4-bit unsigned values)
//!
//! Block structure: 8 sub-blocks of 32 weights each (4 groups of 2 sub-blocks).
//!
//! Weight formula: `w = d * scale_i * q - dmin * min_i` where q is 4-bit (0..15).
//! The nibble layout separates lo nibbles (first 32 weights of the group) from hi
//! nibbles (second 32 weights), unlike Q4_0 which interleaves them per byte.

#![cfg(all(feature = "simd-avx2", target_arch = "x86_64"))]

use core::arch::x86_64::*;

use crate::error::{QuantError, QuantResult};
use crate::simd::avx2::util::{f16_to_f32, hsum_f32_avx};
use crate::traits::QuantKernel;
use crate::types::QuantTensor;

/// Block size for Q4_K: 256 weights per block.
pub const BLOCK_SIZE: usize = 256;
/// Bytes per Q4_K block: 2 (FP16 d) + 2 (FP16 dmin) + 12 (packed scales/mins) + 128 (nibbles).
pub const BLOCK_BYTES: usize = 144;

/// AVX2+FMA accelerated Q4_K kernel.
///
/// Requires `avx2` and `fma` CPU features.  The [`crate::dispatch::KernelDispatcher`]
/// checks for these at runtime before constructing this kernel.
#[allow(non_camel_case_types)]
pub struct Q4_KAvx2;

/// Decode the 6-bit packed scales and mins from the 12-byte header of a Q4_K block.
///
/// Returns `(scales[8], mins[8])` where each element is a 6-bit unsigned value.
/// Scale unpacking is kept scalar because the bit-manipulation pattern is irregular
/// and would not benefit from SIMD vectorization.
fn decode_scales_mins(scales_raw: &[u8]) -> ([u8; 8], [u8; 8]) {
    let mut sc = [0u8; 8];
    let mut mn = [0u8; 8];

    // Sub-blocks 0..3: straightforward 6-bit extraction from bytes 0..3 and 4..7.
    for j in 0..4 {
        sc[j] = scales_raw[j] & 0x3F;
        mn[j] = scales_raw[j + 4] & 0x3F;
    }

    // Sub-blocks 4..7: assembled from high bits of bytes 0..3/4..7 and bytes 8..11.
    for j in 4..8 {
        let lo_sc = scales_raw[j + 4] & 0x0F;
        let hi_sc = (scales_raw[j - 4] >> 6) & 0x03;
        sc[j] = lo_sc | (hi_sc << 4);

        let lo_mn = (scales_raw[j + 4] >> 4) & 0x0F;
        let hi_mn = (scales_raw[j] >> 6) & 0x03;
        mn[j] = lo_mn | (hi_mn << 4);
    }

    (sc, mn)
}

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

        // SAFETY: block.len() >= 144 and output.len() >= 256 verified above.
        // CPU avx2+fma support guaranteed by KernelDispatcher.
        unsafe { dequant_block_avx2(block, output) }
        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(BLOCK_SIZE);
        let row_bytes = blocks_per_row * BLOCK_BYTES;

        for (row, out) in output.iter_mut().enumerate().take(n_rows) {
            let row_start = row * row_bytes;
            // SAFETY: row/block bounds verified above.
            // CPU avx2+fma support guaranteed by KernelDispatcher.
            *out = unsafe {
                gemv_row_avx2(
                    &quant_matrix.data[row_start..row_start + row_bytes],
                    input,
                    blocks_per_row,
                    n_cols,
                )
            };
        }

        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 {
        BLOCK_SIZE
    }

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

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

// ---------------------------------------------------------------------------
// Internal AVX2 kernels
// ---------------------------------------------------------------------------

/// Dequantize one 144-byte Q4_K block into 256 FP32 values using AVX2.
///
/// # Safety
/// - `block.len() >= 144`
/// - `output.len() >= 256`
/// - CPU must support `avx2` and `fma`
#[target_feature(enable = "avx2,fma")]
unsafe fn dequant_block_avx2(block: &[u8], output: &mut [f32]) {
    // Read super-block FP16 scales.
    // SAFETY: block.len() >= 144 >= 4.
    let d = f16_to_f32(block);
    let dmin = f16_to_f32(&block[2..]);

    // Decode the 12-byte packed scale/min header (scalar — irregular bit layout).
    let scales_raw = &block[4..16];
    let (sc, mn) = decode_scales_mins(scales_raw);

    // nibble data: 128 bytes starting at offset 16.
    let qs = &block[16..144];
    let mask_lo = _mm_set1_epi8(0x0F_u8 as i8);

    // Process 4 groups; each group has 32 lo-nibble weights (sub-block `is`) and
    // 32 hi-nibble weights (sub-block `is+1`).  The 32 nibble bytes for each group
    // start at qs_off and supply lo nibbles for the first 32 weights and hi nibbles
    // for the second 32 weights.
    let mut is = 0usize;
    let mut qs_off = 0usize;
    let mut out_off = 0usize;

    for _group in 0..4 {
        // Pre-compute scalar per-sub-block factors.
        let a_lo = d * sc[is] as f32; // d * scale for lo sub-block
        let b_lo = dmin * mn[is] as f32; // dmin * min for lo sub-block
        let a_hi = d * sc[is + 1] as f32; // d * scale for hi sub-block
        let b_hi = dmin * mn[is + 1] as f32; // dmin * min for hi sub-block

        let va_lo = _mm256_set1_ps(a_lo);
        let vb_lo = _mm256_set1_ps(b_lo);
        let va_hi = _mm256_set1_ps(a_hi);
        let vb_hi = _mm256_set1_ps(b_hi);

        // Load the 32 nibble bytes for this group (each byte encodes 2 nibbles:
        // lo nibble → lo sub-block weight, hi nibble → hi sub-block weight).
        // We split into two 16-byte loads.
        // SAFETY: qs_off + 32 <= 128 (4 groups × 32 bytes); block ensures validity.
        let raw_lo = _mm_loadu_si128(qs.as_ptr().add(qs_off) as *const __m128i);
        let raw_hi = _mm_loadu_si128(qs.as_ptr().add(qs_off + 16) as *const __m128i);

        // Extract lo nibbles (weights 0..15 and 16..31 of the lo sub-block).
        let lo_nibbles_0 = _mm_and_si128(raw_lo, mask_lo); // bytes 0..15 low nibbles
        let lo_nibbles_1 = _mm_and_si128(raw_hi, mask_lo); // bytes 16..31 low nibbles

        // Extract hi nibbles (weights 0..15 and 16..31 of the hi sub-block).
        let hi_nibbles_0 = _mm_and_si128(_mm_srli_epi16(raw_lo, 4), mask_lo);
        let hi_nibbles_1 = _mm_and_si128(_mm_srli_epi16(raw_hi, 4), mask_lo);

        // --- Lo sub-block: 32 weights = a_lo * q - b_lo ---

        // First 8 lo nibbles → f32.
        // SAFETY: _mm256_cvtepu8_epi32 reads 8 bytes from the 128-bit source.
        let q0_i32 = _mm256_cvtepu8_epi32(lo_nibbles_0);
        let q0_f32 = _mm256_cvtepi32_ps(q0_i32);
        // w = a_lo * q - b_lo  using FMA: fmadd(a_lo, q, -b_lo)
        let w0 = _mm256_fmsub_ps(va_lo, q0_f32, vb_lo);

        // Next 8 lo nibbles (bytes 8..15 of raw_lo).
        let lo_nibbles_0_hi = _mm_srli_si128(lo_nibbles_0, 8);
        let q1_i32 = _mm256_cvtepu8_epi32(lo_nibbles_0_hi);
        let q1_f32 = _mm256_cvtepi32_ps(q1_i32);
        let w1 = _mm256_fmsub_ps(va_lo, q1_f32, vb_lo);

        // First 8 lo nibbles from second half (bytes 0..7 of raw_hi lo nibbles).
        let q2_i32 = _mm256_cvtepu8_epi32(lo_nibbles_1);
        let q2_f32 = _mm256_cvtepi32_ps(q2_i32);
        let w2 = _mm256_fmsub_ps(va_lo, q2_f32, vb_lo);

        // Last 8 lo nibbles (bytes 8..15 of raw_hi lo nibbles).
        let lo_nibbles_1_hi = _mm_srli_si128(lo_nibbles_1, 8);
        let q3_i32 = _mm256_cvtepu8_epi32(lo_nibbles_1_hi);
        let q3_f32 = _mm256_cvtepi32_ps(q3_i32);
        let w3 = _mm256_fmsub_ps(va_lo, q3_f32, vb_lo);

        // Store 32 lo-sub-block weights.
        // SAFETY: out_off + 32 <= 256; output.len() >= 256.
        let ptr = output.as_mut_ptr().add(out_off);
        _mm256_storeu_ps(ptr, w0);
        _mm256_storeu_ps(ptr.add(8), w1);
        _mm256_storeu_ps(ptr.add(16), w2);
        _mm256_storeu_ps(ptr.add(24), w3);

        // --- Hi sub-block: 32 weights = a_hi * q - b_hi ---

        let q4_i32 = _mm256_cvtepu8_epi32(hi_nibbles_0);
        let q4_f32 = _mm256_cvtepi32_ps(q4_i32);
        let w4 = _mm256_fmsub_ps(va_hi, q4_f32, vb_hi);

        let hi_nibbles_0_hi = _mm_srli_si128(hi_nibbles_0, 8);
        let q5_i32 = _mm256_cvtepu8_epi32(hi_nibbles_0_hi);
        let q5_f32 = _mm256_cvtepi32_ps(q5_i32);
        let w5 = _mm256_fmsub_ps(va_hi, q5_f32, vb_hi);

        let q6_i32 = _mm256_cvtepu8_epi32(hi_nibbles_1);
        let q6_f32 = _mm256_cvtepi32_ps(q6_i32);
        let w6 = _mm256_fmsub_ps(va_hi, q6_f32, vb_hi);

        let hi_nibbles_1_hi = _mm_srli_si128(hi_nibbles_1, 8);
        let q7_i32 = _mm256_cvtepu8_epi32(hi_nibbles_1_hi);
        let q7_f32 = _mm256_cvtepi32_ps(q7_i32);
        let w7 = _mm256_fmsub_ps(va_hi, q7_f32, vb_hi);

        // Store 32 hi-sub-block weights.
        // SAFETY: out_off + 32 + 32 <= 256; output.len() >= 256.
        let ptr2 = output.as_mut_ptr().add(out_off + 32);
        _mm256_storeu_ps(ptr2, w4);
        _mm256_storeu_ps(ptr2.add(8), w5);
        _mm256_storeu_ps(ptr2.add(16), w6);
        _mm256_storeu_ps(ptr2.add(24), w7);

        is += 2;
        qs_off += 32;
        out_off += 64;
    }
}

/// Compute the dot product of one row of a Q4_K matrix with an FP32 vector.
///
/// Returns the scalar result for this row.
///
/// # Safety
/// - `row_data.len() == blocks_per_row * BLOCK_BYTES`
/// - `input.len() >= n_cols`
/// - CPU must support `avx2` and `fma`
#[target_feature(enable = "avx2,fma")]
unsafe fn gemv_row_avx2(
    row_data: &[u8],
    input: &[f32],
    blocks_per_row: usize,
    n_cols: usize,
) -> f32 {
    let mut row_sum = 0.0f32;

    for blk in 0..blocks_per_row {
        let block_offset = blk * BLOCK_BYTES;
        // SAFETY: row_data.len() == blocks_per_row * BLOCK_BYTES; blk < blocks_per_row.
        let block = &row_data[block_offset..block_offset + BLOCK_BYTES];
        let input_offset = blk * BLOCK_SIZE;
        let remaining = n_cols.saturating_sub(input_offset);

        // Read FP16 super-block scales.
        // SAFETY: block.len() == 144 >= 4.
        let d = f16_to_f32(block);
        let dmin = f16_to_f32(&block[2..]);

        let (sc, mn) = decode_scales_mins(&block[4..16]);

        if remaining >= BLOCK_SIZE {
            // Fast path: all 256 weights in bounds — fully vectorized.
            let mask_lo = _mm_set1_epi8(0x0F_u8 as i8);
            let qs = &block[16..144];

            let mut block_acc = _mm256_setzero_ps();
            let mut is = 0usize;
            let mut qs_off = 0usize;
            let mut w_off = input_offset;

            for _group in 0..4 {
                let a_lo = d * sc[is] as f32;
                let b_lo = dmin * mn[is] as f32;
                let a_hi = d * sc[is + 1] as f32;
                let b_hi = dmin * mn[is + 1] as f32;

                let va_lo = _mm256_set1_ps(a_lo);
                let vb_lo = _mm256_set1_ps(b_lo);
                let va_hi = _mm256_set1_ps(a_hi);
                let vb_hi = _mm256_set1_ps(b_hi);

                // Load 32 nibble bytes for this group.
                // SAFETY: qs_off + 32 <= 128; qs.len() == 128.
                let raw_lo = _mm_loadu_si128(qs.as_ptr().add(qs_off) as *const __m128i);
                let raw_hi = _mm_loadu_si128(qs.as_ptr().add(qs_off + 16) as *const __m128i);

                let lo_nibbles_0 = _mm_and_si128(raw_lo, mask_lo);
                let lo_nibbles_1 = _mm_and_si128(raw_hi, mask_lo);
                let hi_nibbles_0 = _mm_and_si128(_mm_srli_epi16(raw_lo, 4), mask_lo);
                let hi_nibbles_1 = _mm_and_si128(_mm_srli_epi16(raw_hi, 4), mask_lo);

                // SAFETY: w_off + 32 <= input_offset + BLOCK_SIZE <= n_cols <= input.len().
                let inp_ptr_lo = input.as_ptr().add(w_off);
                let inp_ptr_hi = input.as_ptr().add(w_off + 32);

                // Lo sub-block: 32 weights at inp_ptr_lo.
                let q0 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(lo_nibbles_0));
                let i0 = _mm256_loadu_ps(inp_ptr_lo);
                let w0 = _mm256_fmsub_ps(va_lo, q0, vb_lo); // a_lo*q - b_lo
                block_acc = _mm256_fmadd_ps(w0, i0, block_acc);

                let lo_nibbles_0_hi = _mm_srli_si128(lo_nibbles_0, 8);
                let q1 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(lo_nibbles_0_hi));
                let i1 = _mm256_loadu_ps(inp_ptr_lo.add(8));
                let w1 = _mm256_fmsub_ps(va_lo, q1, vb_lo);
                block_acc = _mm256_fmadd_ps(w1, i1, block_acc);

                let q2 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(lo_nibbles_1));
                let i2 = _mm256_loadu_ps(inp_ptr_lo.add(16));
                let w2 = _mm256_fmsub_ps(va_lo, q2, vb_lo);
                block_acc = _mm256_fmadd_ps(w2, i2, block_acc);

                let lo_nibbles_1_hi = _mm_srli_si128(lo_nibbles_1, 8);
                let q3 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(lo_nibbles_1_hi));
                let i3 = _mm256_loadu_ps(inp_ptr_lo.add(24));
                let w3 = _mm256_fmsub_ps(va_lo, q3, vb_lo);
                block_acc = _mm256_fmadd_ps(w3, i3, block_acc);

                // Hi sub-block: 32 weights at inp_ptr_hi.
                let q4 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(hi_nibbles_0));
                let i4 = _mm256_loadu_ps(inp_ptr_hi);
                let w4 = _mm256_fmsub_ps(va_hi, q4, vb_hi);
                block_acc = _mm256_fmadd_ps(w4, i4, block_acc);

                let hi_nibbles_0_hi = _mm_srli_si128(hi_nibbles_0, 8);
                let q5 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(hi_nibbles_0_hi));
                let i5 = _mm256_loadu_ps(inp_ptr_hi.add(8));
                let w5 = _mm256_fmsub_ps(va_hi, q5, vb_hi);
                block_acc = _mm256_fmadd_ps(w5, i5, block_acc);

                let q6 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(hi_nibbles_1));
                let i6 = _mm256_loadu_ps(inp_ptr_hi.add(16));
                let w6 = _mm256_fmsub_ps(va_hi, q6, vb_hi);
                block_acc = _mm256_fmadd_ps(w6, i6, block_acc);

                let hi_nibbles_1_hi = _mm_srli_si128(hi_nibbles_1, 8);
                let q7 = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(hi_nibbles_1_hi));
                let i7 = _mm256_loadu_ps(inp_ptr_hi.add(24));
                let w7 = _mm256_fmsub_ps(va_hi, q7, vb_hi);
                block_acc = _mm256_fmadd_ps(w7, i7, block_acc);

                is += 2;
                qs_off += 32;
                w_off += 64;
            }

            row_sum += hsum_f32_avx(block_acc);
        } else if remaining > 0 {
            // Tail path: partial block — scalar fallback to avoid out-of-bounds reads.
            let qs = &block[16..144];
            let mut partial_sum = 0.0f32;
            let mut is = 0usize;
            let mut qs_off = 0usize;
            let mut w_off = input_offset;

            for _group in 0..4 {
                let d1 = d * sc[is] as f32;
                let m1 = dmin * mn[is] as f32;
                let d2 = d * sc[is + 1] as f32;
                let m2 = dmin * mn[is + 1] as f32;

                // Lo nibbles → first 32 weights of this group.
                for l in 0..32 {
                    let idx = w_off + l;
                    if idx < n_cols {
                        // SAFETY: qs_off + l < 128 because qs_off < 128 and l < 32.
                        let q = (*qs.get_unchecked(qs_off + l) & 0x0F) as f32;
                        partial_sum += (d1 * q - m1) * input[idx];
                    }
                }
                // Hi nibbles → next 32 weights.
                for l in 0..32 {
                    let idx = w_off + 32 + l;
                    if idx < n_cols {
                        // SAFETY: qs_off + l < 128.
                        let q = ((*qs.get_unchecked(qs_off + l) >> 4) & 0x0F) as f32;
                        partial_sum += (d2 * q - m2) * input[idx];
                    }
                }

                is += 2;
                qs_off += 32;
                w_off += 64;
            }

            row_sum += partial_sum;
        }
        // remaining == 0: block fully out of bounds, skip.
    }

    row_sum
}

// ---------------------------------------------------------------------------
// Tests (CI only — not executed on aarch64 Darwin build machines)
// ---------------------------------------------------------------------------

#[cfg(all(test, target_arch = "x86_64", feature = "simd-avx2"))]
mod tests {
    use super::*;
    use crate::reference::q4_k::Q4KRef;

    fn make_q4_k_block(d: f32, dmin: f32, scales: &[u8; 12], qs: &[u8; 128]) -> Vec<u8> {
        let mut block = Vec::with_capacity(BLOCK_BYTES);
        block.extend_from_slice(&half::f16::from_f32(d).to_bits().to_le_bytes());
        block.extend_from_slice(&half::f16::from_f32(dmin).to_bits().to_le_bytes());
        block.extend_from_slice(scales);
        block.extend_from_slice(qs);
        block
    }

    fn make_tensor(block: Vec<u8>, n_cols: usize) -> QuantTensor {
        QuantTensor::new(block, vec![1, n_cols], oxillama_gguf::GgufTensorType::Q4K)
    }

    #[test]
    fn test_dequant_matches_reference() {
        if !std::arch::is_x86_feature_detected!("avx2") {
            return;
        }
        let mut scales = [0u8; 12];
        scales[0] = 5;
        scales[1] = 3;
        scales[2] = 7;
        scales[3] = 2;
        scales[4] = 4; // mins 0..3
        scales[5] = 6;
        scales[6] = 1;
        scales[7] = 3;
        scales[8] = 9; // sub-blocks 4..7 lo nibbles
        scales[9] = 11;
        scales[10] = 13;
        scales[11] = 15;

        // Alternating nibble pattern: lo=5, hi=10 → byte 0xA5
        let qs = [0xA5u8; 128];

        let block = make_q4_k_block(0.5, 0.1, &scales, &qs);

        let mut out_avx2 = vec![0.0f32; 256];
        let mut out_ref = vec![0.0f32; 256];

        Q4_KAvx2.dequant_block(&block, &mut out_avx2).unwrap();
        Q4KRef.dequant_block(&block, &mut out_ref).unwrap();

        for (i, (&a, &r)) in out_avx2.iter().zip(out_ref.iter()).enumerate() {
            assert!(
                (a - r).abs() < 1e-3,
                "dequant mismatch at index {i}: avx2={a}, ref={r}"
            );
        }
    }

    #[test]
    fn test_gemv_matches_reference() {
        if !std::arch::is_x86_feature_detected!("avx2") {
            return;
        }
        let mut scales = [0u8; 12];
        scales[..4].fill(1); // sub-blocks 0..3 scale=1
        scales[8..12].fill(1); // sub-blocks 4..7 scale=1 (lo nibble of bytes 8..11)

        // All nibbles = 8: lo=8, hi=8 → byte 0x88
        let qs = [0x88u8; 128];

        let block = make_q4_k_block(1.0, 0.0, &scales, &qs);
        let tensor_avx2 = make_tensor(block.clone(), 256);
        let tensor_ref = make_tensor(block, 256);

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

        let mut out_avx2 = vec![0.0f32; 1];
        let mut out_ref = vec![0.0f32; 1];

        Q4_KAvx2.gemv(&tensor_avx2, &input, &mut out_avx2).unwrap();
        Q4KRef.gemv(&tensor_ref, &input, &mut out_ref).unwrap();

        assert!(
            (out_avx2[0] - out_ref[0]).abs() < 0.1,
            "gemv mismatch: avx2={}, ref={}",
            out_avx2[0],
            out_ref[0]
        );
    }

    #[test]
    fn test_gemv_partial_block() {
        if !std::arch::is_x86_feature_detected!("avx2") {
            return;
        }
        // 200 columns — one partial block (200 < 256).
        let mut scales = [0u8; 12];
        scales[..4].fill(1);
        scales[8..12].fill(1);
        let qs = [0x11u8; 128]; // all weights = 1 (lo=1, hi=1)

        let block = make_q4_k_block(1.0, 0.0, &scales, &qs);
        let tensor_avx2 = make_tensor(block.clone(), 200);
        let tensor_ref = make_tensor(block, 200);

        let input = vec![1.0f32; 200];
        let mut out_avx2 = vec![0.0f32; 1];
        let mut out_ref = vec![0.0f32; 1];

        Q4_KAvx2.gemv(&tensor_avx2, &input, &mut out_avx2).unwrap();
        Q4KRef.gemv(&tensor_ref, &input, &mut out_ref).unwrap();

        assert!(
            (out_avx2[0] - out_ref[0]).abs() < 0.1,
            "partial gemv mismatch: avx2={}, ref={}",
            out_avx2[0],
            out_ref[0]
        );
    }

    #[test]
    fn test_gemv_uniform_all_ones() {
        if !std::arch::is_x86_feature_detected!("avx2") {
            return;
        }
        // d=1.0, dmin=0.0, all scales=1, all nibbles=1 → weight=1.0, sum=256.0
        let mut scales = [0u8; 12];
        scales[..4].fill(1);
        scales[8..12].fill(1);
        let qs = [0x11u8; 128];

        let block = make_q4_k_block(1.0, 0.0, &scales, &qs);
        let tensor = make_tensor(block, 256);
        let input = vec![1.0f32; 256];
        let mut out = vec![0.0f32; 1];

        Q4_KAvx2.gemv(&tensor, &input, &mut out).unwrap();

        assert!(
            (out[0] - 256.0).abs() < 1.0,
            "expected ~256.0, got {}",
            out[0]
        );
    }
}