Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/src/mojollama/hybrid.py # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / src / mojollama / hybrid.py` 413 lines · 16110 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """MojoLlama Hybrid Inference Engine — Mojo SIMD + Python multiprocessing. 3 4 Architecture: 5 - Weights pre-loaded into shared memory (numpy memmap via /dev/shm/) 6 - Forward pass orchestrated in Python (layer loop, norms, attention) 7 - Q4_0 matmuls dispatched to Mojo SIMD worker processes 8 - Workers run in parallel across all physical CPU cores 9 - Workers communicate via pipes (stdin/stdout binary protocol) 10 11 This avoids all Mojo 1.0.0b1 compiler limitations: 12 ✓ No unsafe_from_address needed (workers read weights from files) 13 ✓ No PythonObject→Int conversion needed (CLI args as strings) 14 ✓ No free() import needed (process exits cleanly after work) 15 ✓ Multi-threading via multiprocessing (not Mojo threads) 16 17 Usage: 18 python3 mojollama_hybrid.py --model model.gguf --prompt "Hello" 19 """ 20 21 import os 22 import sys 23 import json 24 import time 25 import math 26 import struct 27 import subprocess 28 import multiprocessing as mp 29 import numpy as np 30 from pathlib import Path 31 32 # ─── Q4_0 Constants ────────────────────────────────────────────────── 33 34 Q4_BLOCK_SIZE = 32 # values per block 35 Q4_TYPE_SIZE = 18 # bytes per block (2 scale + 16 nibbles) 36 37 # Path to compiled Mojo worker binary 38 MOJO_WORKER = os.path.join( 39 os.path.dirname(__file__), "mojollama_q4_pipe" 40 ) 41 42 43 # ─── Weight Manager ─────────────────────────────────────────────────── 44 45 class WeightStore: 46 """Manages Q4_0 weights in shared memory for parallel access.""" 47 48 def __init__(self, gguf_path: str): 49 import gguf 50 from gguf.constants import GGMLQuantizationType 51 52 self.path = gguf_path 53 self.reader = gguf.GGUFReader(gguf_path) 54 self.tensors = {t.name: t for t in self.reader.tensors} 55 self._load_config() 56 57 # Load and extract Q4_0 weights into raw block format 58 self.raw_weights = {} # name -> (n_rows, n_cols, raw_bytes) 59 self.f32_weights = {} # name -> np.ndarray (for norms, embed) 60 61 for name, t in self.tensors.items(): 62 tt = t.tensor_type if hasattr(t, 'tensor_type') else None 63 if tt == GGMLQuantizationType.Q4_0: 64 raw = np.asarray(t.data) 65 n_rows, row_bytes = raw.shape 66 n_cols = (row_bytes // Q4_TYPE_SIZE) * Q4_BLOCK_SIZE 67 self.raw_weights[name] = (n_rows, n_cols, raw.tobytes()) 68 else: 69 arr = gguf.dequantize(t.data, tt) if tt else np.array(t.data, dtype=np.float32) 70 self.f32_weights[name] = arr 71 72 def _load_config(self): 73 f = self.reader.get_field 74 arch = f('general.architecture') 75 self.arch = str(arch.parts[-1]) if arch else 'unknown' 76 prefix = f'{self.arch}.' 77 self.n_layers = self._int(f(f'{prefix}block_count')) 78 self.n_embd = self._int(f(f'{prefix}embedding_length')) 79 self.n_head = self._int(f(f'{prefix}attention.head_count')) 80 self.n_kv_head = self._int(f(f'{prefix}attention.head_count_kv')) 81 self.n_ff = self._int(f(f'{prefix}feed_forward_length')) 82 self.norm_eps = self._float(f(f'{prefix}attention.layer_norm_rms_epsilon')) 83 84 def _int(self, f): return int(f.parts[-1].item()) if f and hasattr(f.parts[-1], 'item') else (int(f.parts[-1]) if f else 0) 85 def _float(self, f): return float(f.parts[-1].item()) if f and hasattr(f.parts[-1], 'item') else (float(f.parts[-1]) if f else 0.0) 86 87 def get_q4(self, name): 88 """Get Q4_0 weight info for a tensor.""" 89 return self.raw_weights.get(name) 90 91 def get_f32(self, name): 92 """Get float32 weight for norms, embed.""" 93 return self.f32_weights.get(name) 94 95 96 # ─── Mojo Worker Pool ──────────────────────────────────────────────── 97 98 class MojoWorkerPool: 99 """Pool of Mojo subprocess workers for parallel Q4_0 matmul.""" 100 101 def __init__(self, weight_store: WeightStore, n_workers=None): 102 self.ws = weight_store 103 self.n_workers = n_workers or mp.cpu_count() 104 self._worker_bin = MOJO_WORKER 105 106 if not os.path.exists(self._worker_bin): 107 print(f"⚠️ Mojo worker not found at {self._worker_bin}") 108 print(" Fallback: using numpy dequant + BLAS") 109 self._fallback = True 110 else: 111 self._fallback = False 112 113 def matmul(self, weight_name, x): 114 """Compute x @ W.T for a Q4_0 weight using parallel Mojo workers.""" 115 info = self.ws.get_q4(weight_name) 116 if info is None or self._fallback: 117 # Fallback to numpy 118 w = self.ws.get_f32(weight_name) 119 if w is None: 120 raise ValueError(f"Weight not found: {weight_name}") 121 # w might be gguf shape [cols, rows] → we need x @ w.T 122 if w.ndim == 2: 123 return x @ w.T 124 return x @ w 125 126 n_rows, n_cols, raw_bytes = info 127 batch = x.shape[0] if x.ndim > 1 else 1 128 129 # For small batches, use single worker 130 if batch == 1 and n_rows <= 2048: 131 return self._single_worker(raw_bytes, n_rows, n_cols, x) 132 133 # Parallel: split rows across workers 134 return self._parallel_matmul(raw_bytes, n_rows, n_cols, x) 135 136 def _single_worker(self, raw_bytes, n_rows, n_cols, x): 137 """Single Mojo worker (no parallel overhead for small jobs).""" 138 import tempfile 139 with tempfile.NamedTemporaryFile(delete=False, suffix='.bin') as f: 140 f.write(raw_bytes) 141 wpath = f.name 142 143 inp = x.flatten().astype(np.float32).tobytes() 144 145 try: 146 proc = subprocess.run( 147 [self._worker_bin, wpath, str(n_rows), str(n_cols), "0", str(n_rows)], 148 input=inp, capture_output=True, timeout=60 149 ) 150 if proc.returncode == 0: 151 result = np.frombuffer(proc.stdout, dtype=np.float32) 152 return result.reshape(x.shape[:-1] + (n_rows,)) 153 else: 154 raise RuntimeError(f"Worker failed: {proc.stderr.decode()[:200]}") 155 finally: 156 os.unlink(wpath) 157 158 def _parallel_matmul(self, raw_bytes, n_rows, n_cols, x): 159 """Parallel Mojo workers via file-based weight sharing.""" 160 # Write weights to shared memory once 161 wpath = "/dev/shm/mojo_weights.bin" 162 if not os.path.exists(wpath): 163 with open(wpath, 'wb') as f: 164 f.write(raw_bytes) 165 166 batch = x.shape[0] if x.ndim > 1 else 1 167 x_2d = x.reshape(-1, n_cols) if x.ndim == 1 else x 168 169 # Split rows across workers 170 chunk_size = max(1, n_rows // self.n_workers) 171 chunks = [] 172 start = 0 173 while start < n_rows: 174 end = min(start + chunk_size, n_rows) 175 chunks.append((start, end)) 176 start = end 177 178 # Launch workers 179 with mp.Pool(min(self.n_workers, len(chunks))) as pool: 180 results = pool.starmap( 181 self._run_worker, 182 [(wpath, n_rows, n_cols, s, e, x_2d[b % batch].tobytes()) 183 for b in range(batch) for i, (s, e) in enumerate(chunks)] 184 ) 185 186 # Combine results 187 out = np.zeros((batch, n_rows), dtype=np.float32) 188 idx = 0 189 for b in range(batch): 190 for s, e in chunks: 191 n_chunk = e - s 192 out[b, s:e] = np.frombuffer(results[idx], dtype=np.float32)[:n_chunk] 193 idx += 1 194 195 return out.reshape(x.shape[:-1] + (n_rows,)) 196 197 def _run_worker(self, wpath, n_rows, n_cols, start, end, inp_bytes): 198 """Run a single Mojo worker subprocess.""" 199 proc = subprocess.run( 200 [self._worker_bin, wpath, str(n_rows), str(n_cols), 201 str(start), str(end)], 202 input=inp_bytes, capture_output=True, timeout=30 203 ) 204 if proc.returncode != 0: 205 raise RuntimeError(f"Worker [{start},{end}): {proc.stderr.decode()[:100]}") 206 return proc.stdout 207 208 209 # ─── Hybrid Forward Engine ─────────────────────────────────────────── 210 211 class HybridEngine: 212 """Mojo + Python hybrid forward pass engine.""" 213 214 def __init__(self, gguf_path: str): 215 self.ws = WeightStore(gguf_path) 216 self.pool = MojoWorkerPool(self.ws) 217 self._kv_cache = None 218 self._cached_len = 0 219 self._timing = {} 220 221 def embed(self, input_ids): 222 w = self.ws.get_f32('token_embd.weight') 223 if w is None: 224 raise ValueError("token_embd.weight not found") 225 if w.ndim == 2 and w.shape[0] == self.ws.n_embd: 226 w = w.T 227 return w[input_ids].astype(np.float32) 228 229 def rms_norm(self, x, weight_name): 230 w = self.ws.get_f32(weight_name) 231 ss = np.mean(x ** 2, axis=-1, keepdims=True) 232 return x / np.sqrt(ss + self.ws.norm_eps) * w 233 234 def rope(self, x, cos, sin): 235 n, h, d = x.shape 236 x2 = x.reshape(n, h, d // 2, 2) 237 xr = np.stack([-x2[..., 1], x2[..., 0]], axis=-1) 238 c = cos[:n, np.newaxis, :d // 2, np.newaxis] 239 s = sin[:n, np.newaxis, :d // 2, np.newaxis] 240 return (x2 * c + xr * s).reshape(n, h, d) 241 242 def silu(self, x): 243 return x / (1 + np.exp(-x)) 244 245 def attention(self, q, k, v, mask): 246 d = q.shape[-1] 247 scores = (q @ k.swapaxes(-1, -2)) / math.sqrt(d) + mask 248 att = np.exp(scores - np.max(scores, axis=-1, keepdims=True)) 249 att = att / np.sum(att, axis=-1, keepdims=True) 250 return att @ v 251 252 def _precompute_freqs(self, dim, end, theta=500000.0): 253 freqs = 1.0 / (theta ** (np.arange(0, dim, 2).astype(np.float32) / dim)) 254 t = np.arange(end).astype(np.float32) 255 f = np.outer(t, freqs) 256 return np.cos(f), np.sin(f) 257 258 def forward(self, input_ids): 259 """Full forward pass.""" 260 seq_len = len(input_ids) 261 head_dim = self.ws.n_embd // self.ws.n_head 262 n_rep = self.ws.n_head // self.ws.n_kv_head 263 cos, sin = self._precompute_freqs(head_dim, seq_len) 264 265 # KV cache mode 266 if self._kv_cache is not None: 267 cached_len = self._cached_len 268 new_ids = np.array(input_ids[cached_len:]) 269 if len(new_ids) == 0: 270 return None 271 h = self.embed(new_ids) 272 return self._forward_step(h, cos, sin, head_dim, n_rep, cached_len) 273 274 # Full prefill 275 h = self.embed(np.array(input_ids)) 276 mask = np.triu(np.full((seq_len, seq_len), -np.inf, dtype=np.float32), 1) 277 return self._forward_full(h, cos, sin, mask, head_dim, n_rep) 278 279 def _forward_full(self, h, cos, sin, mask, head_dim, n_rep): 280 seq_len = h.shape[0] 281 self._kv_cache = [] 282 283 for i in range(self.ws.n_layers): 284 t0 = time.time() 285 r = h 286 h = self.rms_norm(h, f'blk.{i}.attn_norm.weight') 287 t1 = time.time() 288 289 # Q4_0 matmuls (dispatched to Mojo workers) 290 q = self.pool.matmul(f'blk.{i}.attn_q.weight', h) 291 k = self.pool.matmul(f'blk.{i}.attn_k.weight', h) 292 v = self.pool.matmul(f'blk.{i}.attn_v.weight', h) 293 t2 = time.time() 294 295 q = q.reshape(seq_len, self.ws.n_head, head_dim) 296 k = k.reshape(seq_len, self.ws.n_kv_head, head_dim) 297 v = v.reshape(seq_len, self.ws.n_kv_head, head_dim) 298 q = self.rope(q, cos, sin) 299 k = self.rope(k, cos, sin) 300 self._kv_cache.append((k.copy(), v.copy())) 301 302 if n_rep > 1: 303 k = np.repeat(k, n_rep, axis=1) 304 v = np.repeat(v, n_rep, axis=1) 305 306 q_t = q.transpose(1, 0, 2) 307 k_t = k.transpose(1, 0, 2) 308 v_t = v.transpose(1, 0, 2) 309 att = self.attention(q_t, k_t, v_t, mask) 310 att = att.transpose(1, 0, 2).reshape(seq_len, self.ws.n_embd) 311 h = r + self.pool.matmul(f'blk.{i}.attn_output.weight', att) 312 t3 = time.time() 313 314 # FFN 315 r = h 316 h = self.rms_norm(h, f'blk.{i}.ffn_norm.weight') 317 gate = self.silu(self.pool.matmul(f'blk.{i}.ffn_gate.weight', h)) 318 up = self.pool.matmul(f'blk.{i}.ffn_up.weight', h) 319 h = r + self.pool.matmul(f'blk.{i}.ffn_down.weight', gate * up) 320 t4 = time.time() 321 322 self._timing[i] = { 323 "norm": t1 - t0, 324 "matmul_qkv": t2 - t1, 325 "attn_proj": t3 - t2, 326 "ffn": t4 - t3, 327 "total": t4 - t0, 328 } 329 330 h = self.rms_norm(h, 'output_norm.weight') 331 logits = self.pool.matmul('output.weight', h) if 'output.weight' in self.ws.raw_weights else h @ self.ws.get_f32('token_embd.weight')[1].T 332 self._cached_len = seq_len 333 return logits 334 335 def generate(self, prompt_ids, max_tokens=50): 336 """Generate tokens.""" 337 ids = list(prompt_ids) 338 out = [] 339 self._kv_cache = None 340 self._cached_len = 0 341 342 for step in range(max_tokens): 343 t0 = time.time() 344 logits = self.forward(ids) 345 if logits is None: 346 break 347 nid = int(np.argmax(logits[-1])) 348 elapsed = time.time() - t0 349 out.append(nid) 350 ids.append(nid) 351 if step == 0: 352 print(f" Step 0: {nid} ({elapsed*1000:.0f}ms)") 353 if step % 5 == 0 and step > 0: 354 tok_s = 5 / (time.time() - t0 + 0.001) 355 print(f" ... {step} tokens ({tok_s:.1f} tok/s)") 356 357 return out 358 359 360 # ─── Quick Benchmark ───────────────────────────────────────────────── 361 362 def benchmark(): 363 """Quick end-to-end benchmark.""" 364 path = sys.argv[1] if len(sys.argv) > 1 else "Llama-3.2-1B-Instruct-Q4_0.gguf" 365 366 # Check Mojo worker 367 if not os.path.exists(MOJO_WORKER): 368 print(f"❌ Mojo worker not compiled at {MOJO_WORKER}") 369 print(" Run: mojo build q4_pipe.mojo -o mojollama_q4_pipe") 370 sys.exit(1) 371 372 print(f"Loading model: {path}") 373 t0 = time.time() 374 engine = HybridEngine(path) 375 print(f" Loaded: {time.time()-t0:.1f}s") 376 print(f" Architecture: {engine.ws.arch}, {engine.ws.n_layers} layers") 377 print(f" Mojo workers: {engine.pool.n_workers}") 378 print() 379 380 # Quick forward pass 381 ids = [128000, 9906, 1492, 12, 7888, 0] 382 print(f"Forward pass ({len(ids)} tokens)...") 383 t0 = time.time() 384 logits = engine.forward(ids) 385 elapsed = time.time() - t0 386 print(f" {elapsed*1000:.0f}ms ({len(ids)/elapsed:.1f} tok/s)") 387 print(f" Logits: {logits.shape}, argmax={np.argmax(logits[-1])}") 388 389 # Timing breakdown 390 print() 391 print("Per-layer timing (layer 0):") 392 if 0 in engine._timing: 393 t = engine._timing[0] 394 print(f" RMSNorm: {t['norm']*1000:.1f}ms") 395 print(f" QKV matmul: {t['matmul_qkv']*1000:.1f}ms") 396 print(f" Attn proj: {t['attn_proj']*1000:.1f}ms") 397 print(f" FFN: {t['ffn']*1000:.1f}ms") 398 print(f" Total: {t['total']*1000:.1f}ms") 399 400 # Generation 401 print() 402 print(f"Generating {10} tokens...") 403 ids = [128000, 9906, 1492, 12, 7888, 0] 404 engine._kv_cache = None 405 engine._cached_len = 0 406 t0 = time.time() 407 tokens = engine.generate(ids, max_tokens=10) 408 total = time.time() - t0 409 print(f" {len(tokens)} tokens in {total:.2f}s ({len(tokens)/total:.1f} tok/s)") 410 411 412 if __name__ == "__main__": 413 benchmark()