MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / q4_matmul.py
| 1 | """Q4_0 quantized matmul — reference implementation. |
| 2 | Demonstrates block-by-block dot product without full dequantization. |
| 3 | |
| 4 | Q4_0 block format: |
| 5 | - 1× float16 scale (2 bytes) |
| 6 | - 8× uint8 (2× 4-bit values each, 16 values total) |
| 7 | - 10 bytes per 16 values |
| 8 | |
| 9 | Usage: |
| 10 | from q4_matmul import q4_matmul, Q4Block, quantize_q4, dequantize_q4 |
| 11 | """ |
| 12 | import numpy as np |
| 13 | import struct |
| 14 | import time |
| 15 | |
| 16 | # ─── Q4_0 Block ────────────────────────────────────────────────────────────── |
| 17 | |
| 18 | class Q4Block: |
| 19 | """A single Q4_0 quantization block (16 values, 10 bytes).""" |
| 20 | |
| 21 | def __init__(self, scale: np.float16 = np.float16(0.0), quants: np.ndarray = None): |
| 22 | self.scale = scale |
| 23 | # 8 bytes, each storing 2× 4-bit values |
| 24 | self.quants = np.zeros(8, dtype=np.uint8) if quants is None else quants |
| 25 | |
| 26 | def dequantize(self) -> np.ndarray: |
| 27 | """Dequantize block to 16 float32 values.""" |
| 28 | result = np.zeros(16, dtype=np.float32) |
| 29 | for i in range(8): |
| 30 | lo = self.quants[i] & 0x0F |
| 31 | hi = (self.quants[i] >> 4) & 0x0F |
| 32 | result[i*2] = (lo - 8) * float(self.scale) |
| 33 | result[i*2+1] = (hi - 8) * float(self.scale) |
| 34 | return result |
| 35 | |
| 36 | def dot(self, vec: np.ndarray, start: int = 0) -> float: |
| 37 | """Compute dot product with 16 values starting at vec[start].""" |
| 38 | total = 0.0 |
| 39 | s = float(self.scale) |
| 40 | for i in range(8): |
| 41 | lo = (self.quants[i] & 0x0F) - 8 |
| 42 | hi = (self.quants[i] >> 4) - 8 |
| 43 | total += (lo * vec[start + i*2] + hi * vec[start + i*2 + 1]) * s |
| 44 | return total |
| 45 | |
| 46 | |
| 47 | def quantize_q4(values: np.ndarray) -> list[Q4Block]: |
| 48 | """Quantize float32 array to Q4_0 blocks. Returns list of blocks.""" |
| 49 | n = len(values) |
| 50 | n_blocks = (n + 15) // 16 |
| 51 | blocks = [] |
| 52 | for b in range(n_blocks): |
| 53 | start = b * 16 |
| 54 | end = min(start + 16, n) |
| 55 | chunk = values[start:end] |
| 56 | if len(chunk) < 16: |
| 57 | chunk = np.pad(chunk, (0, 16 - len(chunk))) |
| 58 | # Find scale (absmax) |
| 59 | amax = np.max(np.abs(chunk)) |
| 60 | scale = np.float16(amax / 7.0 if amax > 0 else 1.0) |
| 61 | s = float(scale) |
| 62 | # Quantize |
| 63 | quants = np.zeros(8, dtype=np.uint8) |
| 64 | for i in range(8): |
| 65 | lo = max(0, min(15, int(round(chunk[i*2] / s)) + 8)) |
| 66 | hi = max(0, min(15, int(round(chunk[i*2+1] / s)) + 8)) |
| 67 | quants[i] = (hi << 4) | lo |
| 68 | blocks.append(Q4Block(scale, quants)) |
| 69 | return blocks |
| 70 | |
| 71 | |
| 72 | def dequantize_q4(blocks: list[Q4Block], n: int) -> np.ndarray: |
| 73 | """Dequantize blocks back to float32 array.""" |
| 74 | result = np.zeros(n, dtype=np.float32) |
| 75 | for b_idx, block in enumerate(blocks): |
| 76 | start = b_idx * 16 |
| 77 | end = min(start + 16, n) |
| 78 | values = block.dequantize() |
| 79 | result[start:end] = values[:end-start] |
| 80 | return result |
| 81 | |
| 82 | |
| 83 | # ─── Q4_0 Matmul ───────────────────────────────────────────────────────────── |
| 84 | |
| 85 | def pack_q4_weight(matrix: np.ndarray) -> list[list[Q4Block]]: |
| 86 | """Convert float32 weight matrix to Q4_0 blocks per row. |
| 87 | Returns list of rows, each row is list of blocks. |
| 88 | """ |
| 89 | rows, cols = matrix.shape |
| 90 | packed = [] |
| 91 | for r in range(rows): |
| 92 | packed.append(quantize_q4(matrix[r])) |
| 93 | return packed |
| 94 | |
| 95 | |
| 96 | def q4_matmul(x: np.ndarray, weight_blocks: list[list[Q4Block]], |
| 97 | out: np.ndarray = None) -> np.ndarray: |
| 98 | """Compute y = x @ W where W is stored as Q4_0 blocks. |
| 99 | |
| 100 | Args: |
| 101 | x: Input vector (batch, dim) or (dim,) |
| 102 | weight_blocks: Weight matrix as packed Q4_0 blocks [rows][blocks] |
| 103 | out: Pre-allocated output (optional) |
| 104 | |
| 105 | Returns: |
| 106 | Output vector (batch, out_dim) or (out_dim,) |
| 107 | """ |
| 108 | is_vector = x.ndim == 1 |
| 109 | if is_vector: |
| 110 | x = x.reshape(1, -1) |
| 111 | |
| 112 | batch, dim = x.shape |
| 113 | n_rows = len(weight_blocks) |
| 114 | |
| 115 | if out is None: |
| 116 | out = np.zeros((batch, n_rows), dtype=np.float32) |
| 117 | |
| 118 | for b in range(batch): |
| 119 | for r in range(n_rows): |
| 120 | total = 0.0 |
| 121 | for block_idx, block in enumerate(weight_blocks[r]): |
| 122 | start = block_idx * 16 |
| 123 | total += block.dot(x[b], start) |
| 124 | out[b, r] = total |
| 125 | |
| 126 | return out.reshape(-1) if is_vector else out |
| 127 | |
| 128 | |
| 129 | def q4_matmul_transposed(x: np.ndarray, weight_blocks: list[list[Q4Block]], |
| 130 | out: np.ndarray = None) -> np.ndarray: |
| 131 | """Compute y = x @ W.T where W is stored as Q4_0 blocks (per-row). |
| 132 | This is the common case: W is (out_dim, in_dim), we want x @ W.T. |
| 133 | |
| 134 | Here weight_blocks[r] = blocks for output neuron r. |
| 135 | So W.T has columns = blocks rows, dot with x columns. |
| 136 | """ |
| 137 | # Same as q4_matmul since blocks are per-row of W |
| 138 | return q4_matmul(x, weight_blocks, out) |
| 139 | |
| 140 | |
| 141 | # ─── Benchmark ─────────────────────────────────────────────────────────────── |
| 142 | |
| 143 | def benchmark(): |
| 144 | """Benchmark Q4_0 matmul vs float32 dequant + matmul.""" |
| 145 | np.random.seed(42) |
| 146 | |
| 147 | sizes = [ |
| 148 | (2048, 8192), # FFN up/gate |
| 149 | (2048, 2048), # QKV projections |
| 150 | (8192, 2048), # FFN down |
| 151 | ] |
| 152 | |
| 153 | print("=" * 70) |
| 154 | print("Q4_0 Quantized Matmul Benchmark") |
| 155 | print("=" * 70) |
| 156 | |
| 157 | for in_dim, out_dim in sizes: |
| 158 | print(f"\n--- Matrix {out_dim}×{in_dim} ---") |
| 159 | |
| 160 | # Create float32 weight |
| 161 | W_f32 = np.random.randn(out_dim, in_dim).astype(np.float32) |
| 162 | print(f" Float32 size: {W_f32.nbytes/1024/1024:.1f} MB") |
| 163 | |
| 164 | # Pack to Q4_0 |
| 165 | t0 = time.time() |
| 166 | blocks = pack_q4_weight(W_f32) |
| 167 | t1 = time.time() |
| 168 | # Estimate Q4_0 size |
| 169 | q4_bytes = out_dim * ((in_dim + 15)//16) * 10 |
| 170 | print(f" Q4_0 size: {q4_bytes/1024/1024:.1f} MB (packing: {t1-t0:.3f}s)") |
| 171 | |
| 172 | # Input vector |
| 173 | x = np.random.randn(1, in_dim).astype(np.float32) |
| 174 | |
| 175 | # Warmup |
| 176 | _ = x @ W_f32.T |
| 177 | _ = q4_matmul(x, blocks) |
| 178 | |
| 179 | # Benchmark float32 matmul |
| 180 | t0 = time.time() |
| 181 | for _ in range(100): |
| 182 | ref = x @ W_f32.T |
| 183 | t1 = time.time() |
| 184 | ref_ms = (t1 - t0) * 10 # ms per call |
| 185 | |
| 186 | # Benchmark Q4_0 matmul |
| 187 | t0 = time.time() |
| 188 | for _ in range(100): |
| 189 | out = q4_matmul(x, blocks) |
| 190 | t1 = time.time() |
| 191 | q4_ms = (t1 - t0) * 10 |
| 192 | |
| 193 | # Verify accuracy |
| 194 | max_err = np.max(np.abs(out - ref)) |
| 195 | rel_err = max_err / np.max(np.abs(ref)) |
| 196 | |
| 197 | print(f" Float32: {ref_ms:.1f}ms") |
| 198 | print(f" Q4_0 loop: {q4_ms:.1f}ms") |
| 199 | print(f" Speedup: {ref_ms/q4_ms:.1f}x" if q4_ms > 0 else " Speedup: inf") |
| 200 | print(f" Max error: {max_err:.4f} (relative: {rel_err:.4f})") |
| 201 | |
| 202 | # Compare full forward approach too |
| 203 | print("\n\n--- Full Forward Comparison ---") |
| 204 | print("Current: dequant entire tensor → float32 matmul") |
| 205 | print("Q4_0: dequant block-by-block → float32 dot → accumulate") |
| 206 | |
| 207 | in_dim, out_dim = 2048, 8192 # FFN layer |
| 208 | W_f32 = np.random.randn(out_dim, in_dim).astype(np.float32) |
| 209 | blocks = pack_q4_weight(W_f32) |
| 210 | x = np.random.randn(1, in_dim).astype(np.float32) |
| 211 | |
| 212 | # Pre-dequant (current approach) |
| 213 | t0 = time.time() |
| 214 | for _ in range(100): |
| 215 | W_q = blocks # Simulate reading from cache |
| 216 | _ = x @ W_f32.T |
| 217 | t1 = time.time() |
| 218 | predequant_ms = (t1 - t0) * 10 |
| 219 | print(f" Pre-dequant + matmul: {predequant_ms:.1f}ms") |
| 220 | |
| 221 | # Q4_0 block-by-block (no full dequant) |
| 222 | t0 = time.time() |
| 223 | for _ in range(100): |
| 224 | _ = q4_matmul(x, blocks) |
| 225 | t1 = time.time() |
| 226 | q4_block_ms = (t1 - t0) * 10 |
| 227 | print(f" Q4_0 block-by-block: {q4_block_ms:.1f}ms") |
| 228 | print(f" Ratio: {predequant_ms/q4_block_ms:.1f}x") |
| 229 | |
| 230 | print("\nDone.") |
| 231 | |
| 232 | |
| 233 | if __name__ == '__main__': |
| 234 | benchmark() |