interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / .hermes / plans / phase3-q4-matmul-kernel.md

281 lines · 10210 bytes Raw Blame History Rendered
1# Phase 3: Q4_0 Direct Matmul Kernel
2
3> **For Hermes:** Use subagent-driven-development skill to implement this plan task-by-task.
4
5**Goal:** Eliminate float32 weight dequantization from the inference loop. Compute matmuls directly on Q4_0 quantized data, reducing per-tensor memory from 8x to 1x and keeping working sets within available RAM (2.6 GB).
6
7**Architecture:** Python prototype with NumPy vectorized Q4_0 matmul → Mojo kernel port. The Python prototype validates the approach and provides immediate speedup from reduced memory pressure; the Mojo port adds SIMD-level performance to approach llama.cpp's 82 tok/s.
8
9**Current bottleneck per layer:**
101. `_tensor()` calls `gguf.dequantize(t.data, tt)` → expands 9 MB Q4_0 → 72 MB float32 (8x)
112. numpy `@` matmul uses the float32 version
123. gc.collect() frees it
13- For 16 layers × 7 weight tensors = ~8 GB total float32 allocated sequentially in 2.6 GB RAM → swap thrashing
14
15**Target approach:**
161. Keep weights in raw Q4_0 bytes (9 MB per tensor)
172. Compute `out[b][r] = Σ_block Σ_i dequant(block[i]) * x[b][block.start + i]`
183. Never allocate float32 weight tensors
19
20**Tech Stack:** Python 3.11 + NumPy (prototype), Mojo 0.26.2 (kernel port)
21
22---
23
24### Task 1: Create `q4_kernels.py` — Raw Q4_0 matmul
25
26**Objective:** A Python class that loads raw Q4_0 GGUF bytes and computes `x @ W` without dequantizing W to float32.
27
28**Files:**
29- Create: `src/mojollama/model/q4_kernels.py`
30- Verify: existing `q4_matmul.py` (reference, kept for comparison)
31
32**Step 1: Write `Q4Matmul` class**
33
34```python
35"""
36Q4_0 quantized matmul — operates directly on raw Q4_0 blocks.
37Never allocates the full float32 weight matrix.
38
39Q4_0 block format (10 bytes per 16 values):
40 bytes 0-1: float16 scale (little-endian)
41 bytes 2-9: 8 × uint8, each storing 2 × 4-bit values (low nibble = index 2i, high nibble = index 2i+1)
42 dequant: value[i] = (nibble - 8) * scale
43"""
44import numpy as np
45import struct
46
47class Q4Matmul:
48 """Compute y = x @ W where W is stored in Q4_0 format (per-row blocks)."""
49
50 def __init__(self, raw_bytes: bytes, out_rows: int, in_cols: int):
51 self.out_rows = out_rows
52 self.in_cols = in_cols
53 self.blocks_per_row = (in_cols + 15) // 16
54 self.stride = self.blocks_per_row * 10 # bytes per row
55 self.raw = np.frombuffer(raw_bytes, dtype=np.uint8)
56
57 @classmethod
58 def from_gguf_tensor(cls, tensor) -> "Q4Matmul":
59 """Create from a GGUF reader tensor (Q4_0 type)."""
60 raw = np.array(tensor.data)
61 out_rows, in_cols = tensor.shape[0], tensor.shape[1]
62 return cls(raw.tobytes(), out_rows, in_cols)
63
64 def forward(self, x: np.ndarray) -> np.ndarray:
65 """Compute y = x @ W (or x @ W.T depending on how W is stored).
66
67 Args:
68 x: Input (batch, in_cols) or (in_cols,)
69 Returns:
70 Output (batch, out_rows) or (out_rows,)
71 """
72 is_1d = x.ndim == 1
73 if is_1d:
74 x = x.reshape(1, -1)
75 batch = x.shape[0]
76 out = np.zeros((batch, self.out_rows), dtype=np.float32)
77
78 batch_stride = 16 # process in batches of blocks for cache efficiency
79 for r in range(self.out_rows):
80 row_start = r * self.stride
81 row_bytes = self.raw[row_start:row_start + self.stride]
82
83 for b in range(batch):
84 total = 0.0
85 # Process blocks in SIMD-friendly batches
86 for block_idx in range(self.blocks_per_row):
87 boff = block_idx * 10
88 scale = row_bytes[boff:boff+2].view(np.float16)[0]
89 nibbles = row_bytes[boff+2:boff+10]
90
91 # Decode nibbles to int4 and dequantize
92 lo = (nibbles & 0x0F).astype(np.float32) - 8.0
93 hi = ((nibbles >> 4) & 0x0F).astype(np.float32) - 8.0
94
95 # Interleave: [lo0, hi0, lo1, hi1, ...]
96 values = np.empty(16, dtype=np.float32)
97 values[0::2] = lo
98 values[1::2] = hi
99 values *= float(scale)
100
101 col_start = block_idx * 16
102 total += np.dot(values, x[b, col_start:col_start + 16])
103
104 out[b, r] = total
105
106 return out.reshape(-1) if is_1d else out
107
108 def forward_t(self, x: np.ndarray) -> np.ndarray:
109 """Compute y = x @ W.T where W is (out_rows, in_cols).
110
111 Each output row r = dot(x, W[r]) where W[r] is row r of the weight matrix.
112 Since blocks are stored per-row of W, forward() already computes x @ W.
113 For x @ W.T, we need x @ W_col where W_col is column r of W.
114 But W is stored row-major in Q4_0, so x @ W.T means:
115 out[r] = sum_j x[j] * W[r][j]
116 which is exactly what forward() gives us!
117
118 Actually wait - forward computes out[b][r] = Σ_j x[b][j] * W[r][j] = (x @ W.T)[b][r]
119 So forward() IS x @ W.T. We need a different function for x @ W.
120
121 Use forward() for x @ W.T (the common case in transformer inference).
122 """
123 return self.forward(x)
124```
125
126**Step 2: Write unit test**
127
128```python
129"""Test q4_kernels.py against float32 reference."""
130import numpy as np
131from mojollama.model.q4_kernels import Q4Matmul
132
133def test_q4_matmul():
134 np.random.seed(42)
135 out_rows, in_cols = 128, 256
136 x = np.random.randn(1, in_cols).astype(np.float32)
137
138 # Reference: float32 matmul
139 W_f32 = np.random.randn(out_rows, in_cols).astype(np.float32)
140 ref = x @ W_f32.T
141
142 # Quantize to Q4_0 manually and create Q4Matmul
143 # ... (quantization logic from q4_matmul.py)
144 blocks_per_row = (in_cols + 15) // 16
145 raw = bytearray(out_rows * blocks_per_row * 10)
146 for r in range(out_rows):
147 row = W_f32[r]
148 for b in range(blocks_per_row):
149 start = b * 16
150 chunk = row[start:start + 16]
151 if len(chunk) < 16:
152 chunk = np.pad(chunk, (0, 16 - len(chunk)))
153 amax = np.max(np.abs(chunk))
154 scale = np.float16(amax / 7.0 if amax > 0 else 1.0)
155 boff = (r * blocks_per_row + b) * 10
156 struct.pack_into('<e', raw, boff, scale)
157 s = float(scale)
158 for i in range(8):
159 lo = max(0, min(15, int(round(chunk[i*2] / s) + 8)))
160 hi = max(0, min(15, int(round(chunk[i*2+1] / s) + 8)))
161 raw[boff + 2 + i] = (hi << 4) | lo
162
163 q4 = Q4Matmul(bytes(raw), out_rows, in_cols)
164 result = q4.forward_t(x)
165
166 max_err = np.max(np.abs(result - ref))
167 rel_err = max_err / np.max(np.abs(ref))
168 print(f"Max error: {max_err:.4f}, relative: {rel_err:.4f}")
169 assert rel_err < 0.1, f"Q4_0 error too large: {rel_err:.4f}"
170 print("PASS")
171
172if __name__ == "__main__":
173 test_q4_matmul()
174```
175
176**Step 3: Run the test**
177
178Run: `cd /onedev-workspace/work && python3 -c "from mojollama.model.q4_kernels import Q4Matmul; import numpy as np, struct; <test code>"`
179
180Expected: PASS (relative error < 0.1)
181
182---
183
184### Task 2: Integrate Q4Matmul into inference.py
185
186**Objective:** Replace dequant-then-matmul with direct Q4_0 matmul for all Q4_0 weight tensors.
187
188**Files:**
189- Modify: `src/mojollama/model/inference.py`
190- Test: `src/mojollama/model/inference.py` via `python3 src/mojollama/model/inference.py <model.gguf>`
191
192**Key changes:**
193
1941. Import Q4Matmul at top:
195```python
196from mojollama.model.q4_kernels import Q4Matmul
197```
198
1992. Add `_q4_matmul` cache dict to `__init__`:
200```python
201self._q4_matmuls = {} # gguf_name -> Q4Matmul
202```
203
2043. Add method to get or create Q4Matmul:
205```python
206def _get_q4_matmul(self, gguf_name: str):
207 if gguf_name not in self._q4_matmuls:
208 t = self._tensors_by_name.get(gguf_name)
209 if t is None:
210 return None
211 self._q4_matmuls[gguf_name] = Q4Matmul.from_gguf_tensor(t)
212 return self._q4_matmuls[gguf_name]
213```
214
2154. Modify `_tensor()`: only dequantize non-Q4_0 tensors (norms, biases, embed). For Q4_0 weights, skip dequant and return None — the matmul happens via Q4Matmul.
216
217Actually, a cleaner approach: keep `_tensor()` for non-weight tensors (norms, biases, output) and create a new method for weight matmul:
218
219```python
220def _apply_weight(self, x: np.ndarray, gguf_name: str, transposed: bool = True) -> np.ndarray:
221 """Compute x @ W or x @ W.T where W is a Q4_0 weight matrix."""
222 q4 = self._get_q4_matmul(gguf_name)
223 if transposed:
224 return q4.forward_t(x)
225 return q4.forward(x)
226```
227
2285. Replace all `x @ q_w.T` with `self._apply_weight(x, f'blk.{i}.attn_q.weight')` etc.
229
230**Note on performance:** The `_tensor()` method is no longer called for weight tensors (just norms/embed), so the 8x dequant expansion is completely eliminated. Weights stay in 9 MB Q4_0 format permanently.
231
232---
233
234### Task 3: Run inference end-to-end and verify correctness
235
236**Objective:** Verify the model produces the same (approximately) output.
237
238**Files:**
239- Run: `src/mojollama/model/inference.py`
240
241**Steps:**
2421. Run with a simple prompt and compare output tokens with baseline
2432. Verify KV cache still works correctly
2443. Measure timing
245
246---
247
248### Task 4: Benchmark against baseline and llama.cpp
249
250**Objective:** Measure speedup from Q4_0 matmul.
251
252**Steps:**
2531. Time 10-token generation (prefill + generation steps)
2542. Compare with previous baseline (~57.8s for 6-token prefill + 5-token gen)
2553. Compare with llama.cpp at 82 tok/s
2564. Report results
257
258---
259
260### Task 5: Profile and optimize hot paths (within scope)
261
262**Objective:** Find and fix the slowest parts of the Q4_0 matmul.
263
264**Potential optimizations:**
2651. Pre-compute dequantized scales for each block (scale is float16, 2 bytes per block)
2662. Use `np.dot` with pre-dequantized scales to avoid Python loop per block
2673. Process multiple rows in parallel via vectorized operations
268
269---
270
271### Task 6: Mojo kernel prototype (stretch goal)
272
273**Objective:** Port the inner loop to Mojo for SIMD acceleration.
274
275**Files:**
276- Create: `src/mojollama/model/q4_kernel.mojo`
277
278**Approach:**
279- Write a Mojo function that takes raw Q4_0 block data + float32 input
280- Uses Mojo's SIMD vector types for block processing
281- Called from Python via `Python.evaluate()` or compiled to shared library