MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / model / q4_kernels.py
| 1 | """ |
| 2 | Q4_0 quantized matmul — operates directly on raw Q4_0 blocks. |
| 3 | Never allocates the full float32 weight matrix. |
| 4 | |
| 5 | Q4_0 block format (18 bytes per 32 values): |
| 6 | bytes 0-1: float16 scale (little-endian) |
| 7 | bytes 2-17: 16 × uint8 nibble bytes |
| 8 | Position i (0-15): low nibble of byte[i] → value[i] |
| 9 | Position i+16 (16-31): high nibble of byte[i] → value[i+16] |
| 10 | dequant: value[i] = (nibble - 8) * scale |
| 11 | |
| 12 | NOTE: The nibble order is ALL LOW FIRST (16 vals), then ALL HIGH (16 vals). |
| 13 | NOT low/high interleaved. This is the GGUF v2/v3 format. |
| 14 | """ |
| 15 | |
| 16 | import numpy as np |
| 17 | |
| 18 | |
| 19 | class Q4Matmul: |
| 20 | """Compute y = x @ W or x @ W.T where W is Q4_0 quantized per-row.""" |
| 21 | |
| 22 | def __init__(self, raw_bytes: bytes, out_rows: int, in_cols: int): |
| 23 | self.out_rows = out_rows |
| 24 | self.in_cols = in_cols |
| 25 | self.blocks_per_row = (in_cols + 31) // 32 |
| 26 | self.stride = self.blocks_per_row * 18 # bytes per row of blocks |
| 27 | self.raw = np.frombuffer(raw_bytes, dtype=np.uint8) |
| 28 | |
| 29 | @classmethod |
| 30 | def from_gguf_tensor(cls, tensor) -> "Q4Matmul": |
| 31 | """Create from a GGUF reader tensor (Q4_0 type).""" |
| 32 | raw = np.array(tensor.data) |
| 33 | # GGUF shape is [cols, rows] but data is (rows, packed_cols) |
| 34 | # packed_cols = (cols / 32) * 18 |
| 35 | n_rows, row_bytes = raw.shape |
| 36 | in_cols = (row_bytes // 18) * 32 |
| 37 | return cls(raw.tobytes(), n_rows, in_cols) |
| 38 | |
| 39 | # ─── Block processing helpers ────────────────────────────────────────── |
| 40 | |
| 41 | def _process_row_blocks(self, row_idx: int) -> np.ndarray: |
| 42 | """Dequantize all blocks for one row of the weight matrix. |
| 43 | |
| 44 | Returns: |
| 45 | weight_vals: (blocks_per_row, 32) float32 — dequantized weight row |
| 46 | """ |
| 47 | offset = row_idx * self.stride |
| 48 | blocks_flat = self.raw[offset:offset + self.stride] |
| 49 | blocks = blocks_flat.reshape(-1, 18) # (n_blocks, 18) |
| 50 | |
| 51 | # Extract scales (first 2 bytes as float16) |
| 52 | scales = blocks[:, :2].view(np.float16).ravel().astype(np.float32) |
| 53 | |
| 54 | # Extract and decode nibbles — CORRECT GGUF format: |
| 55 | # Positions 0-15: low nibbles of bytes 0-15 |
| 56 | # Positions 16-31: high nibbles of bytes 0-15 |
| 57 | nibbles = blocks[:, 2:] # (n_blocks, 16) |
| 58 | lo = (nibbles & 0x0F).astype(np.float32) - 8.0 |
| 59 | hi = ((nibbles >> 4) & 0x0F).astype(np.float32) - 8.0 |
| 60 | |
| 61 | # Concatenate: all lows first, then all highs |
| 62 | weight_vals = np.empty((self.blocks_per_row, 32), dtype=np.float32) |
| 63 | weight_vals[:, :16] = lo |
| 64 | weight_vals[:, 16:] = hi |
| 65 | weight_vals *= scales[:, np.newaxis] # broadcast: (n_blocks, 32) |
| 66 | |
| 67 | return weight_vals |
| 68 | |
| 69 | def _process_row_blocks_batched(self, rows: np.ndarray) -> np.ndarray: |
| 70 | """Dequantize blocks for multiple rows at once. |
| 71 | |
| 72 | Args: |
| 73 | rows: 1D array of row indices |
| 74 | Returns: |
| 75 | (len(rows), blocks_per_row, 16) float32 tensor |
| 76 | """ |
| 77 | n_rows = len(rows) |
| 78 | result = np.empty((n_rows, self.blocks_per_row, 16), dtype=np.float32) |
| 79 | |
| 80 | for i, r in enumerate(rows): |
| 81 | result[i] = self._process_row_blocks(r) |
| 82 | |
| 83 | return result |
| 84 | |
| 85 | # ─── Forward passes ──────────────────────────────────────────────────── |
| 86 | |
| 87 | def forward(self, x: np.ndarray) -> np.ndarray: |
| 88 | """Compute y = x @ W where W is stored row-by-row as Q4_0 blocks. |
| 89 | |
| 90 | W shape: (out_rows, in_cols) |
| 91 | x shape: (batch, in_cols) or (in_cols,) |
| 92 | |
| 93 | Returns: (batch, out_rows) or (out_rows,) |
| 94 | """ |
| 95 | is_1d = x.ndim == 1 |
| 96 | if is_1d: |
| 97 | x = x.reshape(1, -1) |
| 98 | |
| 99 | batch, in_cols = x.shape |
| 100 | assert in_cols == self.in_cols, f"Input dim {in_cols} != weight dim {self.in_cols}" |
| 101 | |
| 102 | out = np.zeros((batch, self.out_rows), dtype=np.float32) |
| 103 | x_blocks = x.reshape(batch, self.blocks_per_row, 32) |
| 104 | |
| 105 | for r in range(self.out_rows): |
| 106 | w_row = self._process_row_blocks(r) # (blocks_per_row, 32) |
| 107 | # For each batch: sum over blocks of dot product |
| 108 | out[:, r] = np.sum(w_row[np.newaxis, :, :] * x_blocks, axis=(1, 2)) |
| 109 | |
| 110 | return out.reshape(-1) if is_1d else out |
| 111 | |
| 112 | def forward_t(self, x: np.ndarray) -> np.ndarray: |
| 113 | """Compute y = x @ W.T where W is (out_rows, in_cols) per-row Q4_0. |
| 114 | |
| 115 | forward() already computes y[b][r] = Σ_j x[b][j] * W[r][j] |
| 116 | which equals (x @ W.T)[b][r]. So forward() is x @ W.T. |
| 117 | |
| 118 | For x @ W, use forward() with properly shaped x. |
| 119 | """ |
| 120 | return self.forward(x) |
| 121 | |
| 122 | |
| 123 | # ─── Quantize helper (for testing) ────────────────────────────────────────── |
| 124 | |
| 125 | def pack_q4_weight(matrix: np.ndarray) -> bytes: |
| 126 | """Quantize a float32 weight matrix to Q4_0 format (byte string). |
| 127 | |
| 128 | Used for testing against float32 reference. |
| 129 | Q4_0 block: 2 bytes f16 scale + 16 bytes nibbles = 18 bytes per 32 values. |
| 130 | Nibble order: all lows first (16), then all highs (16). |
| 131 | """ |
| 132 | import struct |
| 133 | out_rows, in_cols = matrix.shape |
| 134 | blocks_per_row = (in_cols + 31) // 32 |
| 135 | stride = blocks_per_row * 18 |
| 136 | raw = bytearray(out_rows * stride) |
| 137 | |
| 138 | for r in range(out_rows): |
| 139 | row = matrix[r] |
| 140 | for b in range(blocks_per_row): |
| 141 | start = b * 32 |
| 142 | chunk = row[start:start + 32] |
| 143 | if len(chunk) < 32: |
| 144 | chunk = np.pad(chunk, (0, 32 - len(chunk))) |
| 145 | |
| 146 | # Q4_0: scale = absmax / -8 |
| 147 | amax = np.max(np.abs(chunk)) |
| 148 | scale = np.float16(amax / -8.0 if amax > 0 else -1.0) |
| 149 | s = float(scale) |
| 150 | |
| 151 | boff = (r * blocks_per_row + b) * 18 |
| 152 | struct.pack_into('<e', raw, boff, scale) |
| 153 | |
| 154 | # Pack: low nibbles first (bytes 0-15), then high nibbles packed |
| 155 | for i in range(16): |
| 156 | lo_val = max(0, min(15, int(round(chunk[i] / s) + 8))) |
| 157 | hi_val = max(0, min(15, int(round(chunk[i + 16] / s) + 8))) |
| 158 | raw[boff + 2 + i] = (hi_val << 4) | lo_val |
| 159 | |
| 160 | return bytes(raw) |
| 161 | |
| 162 | |
| 163 | # ─── Test ─────────────────────────────────────────────────────────────────── |
| 164 | |
| 165 | def test_q4_matmul(): |
| 166 | """Test Q4Matmul against float32 reference.""" |
| 167 | np.random.seed(42) |
| 168 | |
| 169 | for out_rows, in_cols in [(64, 128), (128, 256), (256, 512)]: |
| 170 | x = np.random.randn(1, in_cols).astype(np.float32) |
| 171 | W_f32 = np.random.randn(out_rows, in_cols).astype(np.float32) |
| 172 | |
| 173 | # Reference: float32 matmul |
| 174 | ref = x @ W_f32.T |
| 175 | |
| 176 | # Quantize to Q4_0 |
| 177 | raw = pack_q4_weight(W_f32) |
| 178 | q4 = Q4Matmul(raw, out_rows, in_cols) |
| 179 | result = q4.forward_t(x) |
| 180 | |
| 181 | max_err = np.max(np.abs(result - ref)) |
| 182 | rel_err = max_err / np.max(np.abs(ref)) |
| 183 | print(f" {out_rows}×{in_cols}: max_err={max_err:.4f} rel_err={rel_err:.6f}") |
| 184 | assert rel_err < 0.15, f"Q4_0 error too large: {rel_err:.4f}" |
| 185 | |
| 186 | # Test batched |
| 187 | x_batch = np.random.randn(4, 128).astype(np.float32) |
| 188 | W_f32 = np.random.randn(64, 128).astype(np.float32) |
| 189 | ref = x_batch @ W_f32.T |
| 190 | raw = pack_q4_weight(W_f32) |
| 191 | q4 = Q4Matmul(raw, 64, 128) |
| 192 | result = q4.forward_t(x_batch) |
| 193 | rel_err = np.max(np.abs(result - ref)) / np.max(np.abs(ref)) |
| 194 | print(f" batch=4 64×128: rel_err={rel_err:.6f}") |
| 195 | assert rel_err < 0.15 |
| 196 | |
| 197 | print("All tests PASS") |
| 198 | |
| 199 | |
| 200 | def benchmark_q4_matmul(): |
| 201 | """Benchmark Q4Matmul vs float32 dequant + matmul.""" |
| 202 | np.random.seed(42) |
| 203 | |
| 204 | sizes = [ |
| 205 | ("FFN gate", 2048, 8192), |
| 206 | ("FFN down", 8192, 2048), |
| 207 | ("QKV proj", 2048, 2048), |
| 208 | ("Output", 2048, 128256), |
| 209 | ] |
| 210 | |
| 211 | print(f"{'Name':<15} {'Shape':<18} {'F32 matmul':<14} {'Q4 matmul':<14} {'Speedup':<10} {'RelErr':<10}") |
| 212 | print("-" * 81) |
| 213 | |
| 214 | for name, out_r, in_c in sizes: |
| 215 | if out_r * in_c * 4 > 512 * 1024 * 1024: |
| 216 | print(f" {name:<15} {out_r}×{in_c:<10} SKIP (too large for RAM)") |
| 217 | continue |
| 218 | |
| 219 | # Reference float32 |
| 220 | W_f32 = np.random.randn(out_r, in_c).astype(np.float32) |
| 221 | x = np.random.randn(1, in_c).astype(np.float32) |
| 222 | |
| 223 | # Benchmark float32 |
| 224 | t0 = __import__('time').time() |
| 225 | for _ in range(10): |
| 226 | ref = x @ W_f32.T |
| 227 | t1 = __import__('time').time() |
| 228 | f32_ms = (t1 - t0) * 100 # ms per call |
| 229 | |
| 230 | # Q4_0 version |
| 231 | raw = pack_q4_weight(W_f32) |
| 232 | q4 = Q4Matmul(raw, out_r, in_c) |
| 233 | |
| 234 | t0 = __import__('time').time() |
| 235 | for _ in range(10): |
| 236 | result = q4.forward_t(x) |
| 237 | t1 = __import__('time').time() |
| 238 | q4_ms = (t1 - t0) * 100 |
| 239 | |
| 240 | rel_err = np.max(np.abs(result - ref)) / np.max(np.abs(ref)) |
| 241 | |
| 242 | speedup = f32_ms / q4_ms if q4_ms > 0 else float('inf') |
| 243 | print(f" {name:<15} {out_r}×{in_c:<12} {f32_ms:<12.2f} {q4_ms:<12.2f} {speedup:<8.2f}x {rel_err:.4f}") |
| 244 | |
| 245 | |
| 246 | if __name__ == "__main__": |
| 247 | import sys |
| 248 | if "--bench" in sys.argv: |
| 249 | benchmark_q4_matmul() |
| 250 | else: |
| 251 | test_q4_matmul() |