MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / kernels / legacy-engine / q4_quantize.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Vectorized Q4_0 quantizer — numpy-fast, runs once at load time.""" |
| 3 | |
| 4 | import numpy as np |
| 5 | |
| 6 | def quantize_q4_0_vectorized(data_f32: np.ndarray, n_cols: int) -> np.ndarray: |
| 7 | """Quantize F32 row-major matrix to Q4_0 format matching our C kernel. |
| 8 | |
| 9 | Q4_0 block layout (18 bytes per 32 values): |
| 10 | bytes[0:2]: f16 scale (little-endian) |
| 11 | bytes[2:18]: 16 bytes, each packing two 4-bit values |
| 12 | byte[j] = (val[2j] + 8) & 0xF | (((val[2j+1] + 8) & 0xF) << 4) |
| 13 | |
| 14 | Returns: uint8 array of shape (n_blocks * 18,) |
| 15 | """ |
| 16 | flat = data_f32.astype(np.float32).ravel() |
| 17 | n = len(flat) |
| 18 | assert n % 32 == 0, f"n={n} not divisible by 32" |
| 19 | n_blocks = n // 32 |
| 20 | |
| 21 | # Reshape to (n_blocks, 32) |
| 22 | blocks = flat.reshape(n_blocks, 32) |
| 23 | |
| 24 | # Scale per block: max(|values|) / 8 |
| 25 | amax = np.max(np.abs(blocks), axis=1) # (n_blocks,) |
| 26 | scales = np.where(amax > 0, amax / 8.0, 0.0).astype(np.float16) |
| 27 | |
| 28 | # Quantize: q = round(val / scale) + 8, clipped to [0, 15] |
| 29 | inv_scales = np.where(scales.astype(np.float32) > 0, |
| 30 | 1.0 / scales.astype(np.float32), 0.0).astype(np.float32) |
| 31 | # (n_blocks, 32) — quantized values in 0..15 |
| 32 | q = np.clip(np.round(blocks * inv_scales[:, None] + 8.0), 0, 15).astype(np.uint8) |
| 33 | |
| 34 | # Pack pairs: byte[j] = (q[2j] & 0xF) | ((q[2j+1] & 0xF) << 4) |
| 35 | q_pairs = q.reshape(n_blocks, 16, 2) |
| 36 | packed = (q_pairs[:, :, 0] & 0x0F) | ((q_pairs[:, :, 1] & 0x0F) << 4) # (n_blocks, 16) |
| 37 | |
| 38 | # Assemble output: scale (2 bytes LE) + packed nibbles (16 bytes) |
| 39 | result = np.zeros((n_blocks, 18), dtype=np.uint8) |
| 40 | # Write f16 scale as little-endian |
| 41 | scale_view = scales.view(np.uint16) # (n_blocks,) |
| 42 | result[:, 0] = (scale_view & 0xFF).astype(np.uint8) |
| 43 | result[:, 1] = ((scale_view >> 8) & 0xFF).astype(np.uint8) |
| 44 | result[:, 2:18] = packed |
| 45 | |
| 46 | return result.ravel() |
| 47 | |
| 48 | |
| 49 | if __name__ == '__main__': |
| 50 | import time |
| 51 | |
| 52 | # Correctness test |
| 53 | _so = __import__('ctypes').CDLL('/onedev-workspace/work/src/mojollama/kernels/q4_kernel_omp.so') |
| 54 | _so.q4_matmul_omp.argtypes = [ |
| 55 | __import__('ctypes').POINTER(__import__('ctypes').c_uint8), |
| 56 | __import__('ctypes').POINTER(__import__('ctypes').c_float), |
| 57 | __import__('ctypes').POINTER(__import__('ctypes').c_float), |
| 58 | __import__('ctypes').c_int, __import__('ctypes').c_int, __import__('ctypes').c_int, |
| 59 | ] |
| 60 | _so.q4_set_num_threads(32) |
| 61 | |
| 62 | # Small correctness test |
| 63 | np.random.seed(42) |
| 64 | W = np.random.randn(4, 32).astype(np.float32) * 0.5 |
| 65 | x = np.random.randn(32).astype(np.float32) |
| 66 | expected = W @ x |
| 67 | |
| 68 | W_q4 = quantize_q4_0_vectorized(W, 32) |
| 69 | w_ptr = W_q4.ctypes.data_as(__import__('ctypes').POINTER(__import__('ctypes').c_uint8)) |
| 70 | x_ptr = x.ctypes.data_as(__import__('ctypes').POINTER(__import__('ctypes').c_float)) |
| 71 | out = np.zeros(4, dtype=np.float32) |
| 72 | out_ptr = out.ctypes.data_as(__import__('ctypes').POINTER(__import__('ctypes').c_float)) |
| 73 | _so.q4_matmul_omp(w_ptr, x_ptr, out_ptr, 4, 32, 18) |
| 74 | |
| 75 | print(f"Expected: {expected}") |
| 76 | print(f"Got: {out}") |
| 77 | print(f"Max error: {np.max(np.abs(expected - out)):.4f}") |
| 78 | print(f"Mean error: {np.mean(np.abs(expected - out)):.4f}") |
| 79 | |
| 80 | # Large benchmark |
| 81 | W_big = np.random.randn(128256, 2048).astype(np.float32) |
| 82 | t0 = time.perf_counter() |
| 83 | W_q4 = quantize_q4_0_vectorized(W_big, 2048) |
| 84 | t1 = time.perf_counter() |
| 85 | print(f"\nQuantize 128K×2048: {(t1-t0):.3f}s (one-time cost)") |
| 86 | print(f"Q4_0 size: {len(W_q4)/1e6:.1f} MB vs F32: {W_big.nbytes/1e6:.1f} MB") |
| 87 | |
| 88 | # Benchmark Q4_0 matmul for output projection |
| 89 | x_big = np.random.randn(2048).astype(np.float32) |
| 90 | logits = np.zeros(128256, dtype=np.float32) |
| 91 | _so.q4_matmul_omp( |
| 92 | W_q4.ctypes.data_as(__import__('ctypes').POINTER(__import__('ctypes').c_uint8)), |
| 93 | x_big.ctypes.data_as(__import__('ctypes').POINTER(__import__('ctypes').c_float)), |
| 94 | logits.ctypes.data_as(__import__('ctypes').POINTER(__import__('ctypes').c_float)), |
| 95 | 128256, 2048, 18) |
| 96 | |
| 97 | times = [] |
| 98 | for _ in range(20): |
| 99 | t0 = time.perf_counter() |
| 100 | _so.q4_matmul_omp( |
| 101 | W_q4.ctypes.data_as(__import__('ctypes').POINTER(__import__('ctypes').c_uint8)), |
| 102 | x_big.ctypes.data_as(__import__('ctypes').POINTER(__import__('ctypes').c_float)), |
| 103 | logits.ctypes.data_as(__import__('ctypes').POINTER(__import__('ctypes').c_float)), |
| 104 | 128256, 2048, 18) |
| 105 | t1 = time.perf_counter() |
| 106 | times.append((t1-t0)*1000) |
| 107 | times.sort() |
| 108 | print(f"Q4_0 output proj (128K×2048): {times[10]:.2f} ms median") |
| 109 | |
| 110 | # Compare with F32 |
| 111 | logits_f32 = np.zeros(128256, dtype=np.float32) |
| 112 | _so.f32_matmul_omp.argtypes = [ |
| 113 | __import__('ctypes').POINTER(__import__('ctypes').c_float), |
| 114 | __import__('ctypes').POINTER(__import__('ctypes').c_float), |
| 115 | __import__('ctypes').POINTER(__import__('ctypes').c_float), |
| 116 | __import__('ctypes').c_int, __import__('ctypes').c_int, |
| 117 | ] |
| 118 | _so.f32_matmul_omp.restype = None |
| 119 | times_f32 = [] |
| 120 | for _ in range(10): |
| 121 | t0 = time.perf_counter() |
| 122 | _so.f32_matmul_omp( |
| 123 | W_big.ctypes.data_as(__import__('ctypes').POINTER(__import__('ctypes').c_float)), |
| 124 | x_big.ctypes.data_as(__import__('ctypes').POINTER(__import__('ctypes').c_float)), |
| 125 | logits_f32.ctypes.data_as(__import__('ctypes').POINTER(__import__('ctypes').c_float)), |
| 126 | 128256, 2048) |
| 127 | t1 = time.perf_counter() |
| 128 | times_f32.append((t1-t0)*1000) |
| 129 | times_f32.sort() |
| 130 | print(f"F32 output proj (128K×2048): {times_f32[5]:.2f} ms median") |
| 131 | print(f"Speedup: {times_f32[5]/times[10]:.1f}x") |