MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / batch_server.py
| 1 | """Mojo Hybrid Serve — continuous batching server. |
| 2 | Collects requests, batches them through a single forward pass, returns results. |
| 3 | """ |
| 4 | import argparse, json, os, sys, time, threading, gc |
| 5 | import numpy as np |
| 6 | from pathlib import Path |
| 7 | from collections import deque |
| 8 | from dataclasses import dataclass, field |
| 9 | from typing import Optional |
| 10 | |
| 11 | sys.path.insert(0, str(Path(__file__).resolve().parent)) |
| 12 | from src.mojollama.model.inference import LLMInference |
| 13 | |
| 14 | |
| 15 | # ─── Batch Bench ───────────────────────────────────────────────────────────── |
| 16 | |
| 17 | def batch_bench(model_path: str, batch_sizes: list[int] = None): |
| 18 | """Benchmark batched inference across different batch sizes.""" |
| 19 | if batch_sizes is None: |
| 20 | batch_sizes = [1, 2, 4, 8, 16] |
| 21 | |
| 22 | print("=" * 70) |
| 23 | print("MojoLlama — Batch Inference Benchmark") |
| 24 | print(f"Model: {model_path}") |
| 25 | print("=" * 70) |
| 26 | |
| 27 | model = LLMInference(model_path) |
| 28 | # Short prompt for consistent timing |
| 29 | prompt = "The capital of France is" |
| 30 | prompt_ids = model.encode(prompt) |
| 31 | prompt_len = len(prompt_ids) |
| 32 | print(f"Prompt: '{prompt}' ({prompt_len} tokens)") |
| 33 | print() |
| 34 | |
| 35 | results = [] |
| 36 | for batch_size in batch_sizes: |
| 37 | # Warmup |
| 38 | _ = _run_batch(model, prompt_ids, batch_size, gen_tokens=1) |
| 39 | |
| 40 | # Benchmark prefill (forward pass with all prompts) |
| 41 | t0 = time.time() |
| 42 | logits_list = _run_batch(model, prompt_ids, batch_size, gen_tokens=1) |
| 43 | t1 = time.time() |
| 44 | elapsed = t1 - t0 |
| 45 | |
| 46 | # Benchmark generate (with KV cache, 5 tokens) |
| 47 | t2 = time.time() |
| 48 | outputs = _run_batch_generate(model, prompt_ids, batch_size, gen_tokens=5) |
| 49 | t3 = time.time() |
| 50 | gen_elapsed = t3 - t2 |
| 51 | |
| 52 | # Tokens per second |
| 53 | total_tokens_gen = batch_size * 5 # 5 tokens per sequence |
| 54 | gen_tok_s = total_tokens_gen / gen_elapsed if gen_elapsed > 0 else 0 |
| 55 | prefill_tok_s = (batch_size * prompt_len) / elapsed if elapsed > 0 else 0 |
| 56 | single_tok_s = (batch_size * 1) / elapsed if elapsed > 0 else 0 |
| 57 | |
| 58 | results.append({ |
| 59 | 'batch_size': batch_size, |
| 60 | 'prefill_s': elapsed, |
| 61 | 'gen_s': gen_elapsed, |
| 62 | 'prefill_tok_s': prefill_tok_s, |
| 63 | 'gen_tok_s': gen_tok_s, |
| 64 | 'single_step_s': elapsed, |
| 65 | }) |
| 66 | |
| 67 | print(f" batch={batch_size:2d} | prefill={elapsed:.1f}s ({prefill_tok_s:.0f} tok/s) | " |
| 68 | f"generate={gen_elapsed:.1f}s ({gen_tok_s:.1f} tok/s)") |
| 69 | |
| 70 | # Find sweet spot |
| 71 | print("\n" + "=" * 70) |
| 72 | print("Sweet Spot Analysis") |
| 73 | print("=" * 70) |
| 74 | best_tok_s = 0 |
| 75 | best_batch = 1 |
| 76 | for r in results: |
| 77 | throughput = r['gen_tok_s'] |
| 78 | print(f" batch={r['batch_size']:2d}: {r['gen_tok_s']:.1f} tok/s " |
| 79 | f"({r['gen_s']:.1f}s for {r['batch_size']*5} tokens)") |
| 80 | if throughput > best_tok_s: |
| 81 | best_tok_s = throughput |
| 82 | best_batch = r['batch_size'] |
| 83 | |
| 84 | print(f"\n 🏆 Sweet spot: batch_size={best_batch} ({best_tok_s:.1f} tok/s)") |
| 85 | print(f"\n Compare to llama.cpp 10-concurrent: 114 tok/s across all users") |
| 86 | print(f" Our 10-concurrent target at batch={best_batch}: " |
| 87 | f"{best_tok_s * 10 / best_batch:.1f} tok/s (est.)") |
| 88 | return results |
| 89 | |
| 90 | |
| 91 | def _run_batch(model, prompt_ids: list[int], batch_size: int, gen_tokens: int): |
| 92 | """Run a batch of sequences. Returns per-sequence logits.""" |
| 93 | seq_lens = [len(prompt_ids)] * batch_size |
| 94 | max_len = max(seq_lens) |
| 95 | |
| 96 | # Stack prompts into a batch |
| 97 | batch_ids = np.zeros((batch_size, max_len), dtype=np.int64) |
| 98 | attn_mask = np.zeros((batch_size, max_len), dtype=np.float32) |
| 99 | for i in range(batch_size): |
| 100 | batch_ids[i, :seq_lens[i]] = prompt_ids |
| 101 | attn_mask[i, :seq_lens[i]] = 1.0 |
| 102 | |
| 103 | # Batched embedding |
| 104 | embed = model._get_persistent('token_embd.weight') |
| 105 | x = embed[batch_ids].astype(np.float32) # (batch, seq, dim) |
| 106 | |
| 107 | head_dim = model.n_embd // model.n_head |
| 108 | n_rep = model.n_head // model.n_kv_head |
| 109 | n_layers = model.n_layers |
| 110 | |
| 111 | cos, sin = model.precompute_freqs_cis(head_dim, max_len, model.rope_theta) |
| 112 | |
| 113 | for i in range(n_layers): |
| 114 | # Load weights once for the batch |
| 115 | ln1 = model._tensor(f'blk.{i}.attn_norm.weight') |
| 116 | q_w = model._tensor(f'blk.{i}.attn_q.weight') |
| 117 | k_w = model._tensor(f'blk.{i}.attn_k.weight') |
| 118 | v_w = model._tensor(f'blk.{i}.attn_v.weight') |
| 119 | o_w = model._tensor(f'blk.{i}.attn_output.weight') |
| 120 | |
| 121 | # RMSNorm — batch-aware: (batch, seq, dim) with shared weight |
| 122 | x_flat = x.reshape(-1, model.n_embd) |
| 123 | for b in range(batch_size): |
| 124 | for s in range(seq_lens[b]): |
| 125 | x_flat[b * max_len + s] = model.rms_norm( |
| 126 | x[b:b+1, s:s+1, :], ln1, model.norm_eps)[0, 0] |
| 127 | |
| 128 | # QKV projections — batch matmul: (batch, seq, dim) @ (dim, out) |
| 129 | q = x @ q_w.T # (batch, seq, q_dim) |
| 130 | k = x @ k_w.T # (batch, seq, k_dim) |
| 131 | v = x @ v_w.T # (batch, seq, v_dim) |
| 132 | |
| 133 | q = q.reshape(batch_size, max_len, model.n_head, head_dim) |
| 134 | k = k.reshape(batch_size, max_len, model.n_kv_head, head_dim) |
| 135 | v = v.reshape(batch_size, max_len, model.n_kv_head, head_dim) |
| 136 | |
| 137 | # RoPE per sequence |
| 138 | for b in range(batch_size): |
| 139 | L = seq_lens[b] |
| 140 | q[b, :L] = model.apply_rope(q[b, :L], cos[:L], sin[:L]) |
| 141 | k[b, :L] = model.apply_rope(k[b, :L], cos[:L], sin[:L]) |
| 142 | |
| 143 | if n_rep > 1: |
| 144 | k = np.repeat(k, n_rep, axis=2) |
| 145 | v = np.repeat(v, n_rep, axis=2) |
| 146 | |
| 147 | # Attention per sequence (masked separately) |
| 148 | for b in range(batch_size): |
| 149 | L = seq_lens[b] |
| 150 | att = np.einsum('ihd,jhd->hij', q[b, :L], k[b, :L]) / np.sqrt(head_dim) |
| 151 | mask = np.triu(np.full((L, L), -np.inf, dtype=np.float32), 1) |
| 152 | att += mask |
| 153 | am = np.max(att, axis=-1, keepdims=True) |
| 154 | att = np.exp(att - am) |
| 155 | att /= np.sum(att, axis=-1, keepdims=True) |
| 156 | out = np.einsum('hij,jhd->ihd', att, v[b, :L]).reshape(L, model.n_embd) |
| 157 | out = out @ o_w.T |
| 158 | x[b, :L] = (x[b, :L] if b == 0 else model.rms_norm( |
| 159 | x[b:b+1, :L], ln1 if False else x[b:b+1, :L])[0])[:L] + out # residual |
| 160 | # Simpler: just compute for each seq |
| 161 | x[b, :L] = x[b, :L][:len(out)] + out |
| 162 | |
| 163 | # FFN |
| 164 | ln2 = model._tensor(f'blk.{i}.ffn_norm.weight') |
| 165 | gate_w = model._tensor(f'blk.{i}.ffn_gate.weight') |
| 166 | up_w = model._tensor(f'blk.{i}.ffn_up.weight') |
| 167 | down_w = model._tensor(f'blk.{i}.ffn_down.weight') |
| 168 | |
| 169 | for b in range(batch_size): |
| 170 | L = seq_lens[b] |
| 171 | r = x[b, :L].copy() |
| 172 | x_b = model.rms_norm(x[b:b+1, :L], ln2, model.norm_eps)[0] |
| 173 | gate = x_b @ gate_w.T |
| 174 | up = x_b @ up_w.T |
| 175 | x_b = (model.silu(gate) * up) @ down_w.T |
| 176 | x[b, :L] = r + x_b |
| 177 | |
| 178 | del ln1, q_w, k_w, v_w, o_w, ln2, gate_w, up_w, down_w |
| 179 | |
| 180 | # Final norm + lm_head |
| 181 | norm_w = model._tensor('output_norm.weight') |
| 182 | embed = model._get_persistent('token_embd.weight') |
| 183 | lm_w = model._tensor('output.weight') |
| 184 | if lm_w is None: |
| 185 | lm_w = embed |
| 186 | logits = [] |
| 187 | for b in range(batch_size): |
| 188 | L = seq_lens[b] |
| 189 | x_normed = model.rms_norm(x[b:b+1, :L], norm_w, model.norm_eps)[0] |
| 190 | logit = x_normed @ lm_w.T |
| 191 | logits.append(logit) |
| 192 | |
| 193 | return logits |
| 194 | |
| 195 | |
| 196 | def _run_batch_generate(model, prompt_ids, batch_size, gen_tokens): |
| 197 | """Generate tokens for a batch.""" |
| 198 | # Simple sequential generation per sequence (parallel KV not yet implemented) |
| 199 | outputs = [] |
| 200 | for b in range(batch_size): |
| 201 | model._kv_cache = None |
| 202 | model._cached_len = 0 |
| 203 | ids = prompt_ids.copy() |
| 204 | out_ids = [] |
| 205 | for _ in range(gen_tokens): |
| 206 | logits = model.forward(ids, use_cache=True) |
| 207 | nid = int(np.argmax(logits[-1])) |
| 208 | if nid == model.eos_id: |
| 209 | break |
| 210 | out_ids.append(nid) |
| 211 | ids.append(nid) |
| 212 | outputs.append(model.decode(out_ids)) |
| 213 | return outputs |
| 214 | |
| 215 | |
| 216 | # ─── Continuous Batching Server ────────────────────────────────────────────── |
| 217 | |
| 218 | @dataclass |
| 219 | class BatchRequest: |
| 220 | prompt: str |
| 221 | max_tokens: int = 50 |
| 222 | result: list = field(default_factory=list) |
| 223 | event: threading.Event = field(default_factory=threading.Event) |
| 224 | |
| 225 | |
| 226 | class ContinuousBatchServer: |
| 227 | """Collects requests and processes them in batches.""" |
| 228 | |
| 229 | def __init__(self, model_path: str, batch_size: int = 4, |
| 230 | schedule_ms: float = 100, max_queue: int = 64): |
| 231 | self.model = LLMInference(model_path) |
| 232 | self.batch_size = batch_size |
| 233 | self.schedule_s = schedule_ms / 1000.0 |
| 234 | self.max_queue = max_queue |
| 235 | self.queue = deque() |
| 236 | self.lock = threading.Lock() |
| 237 | self.running = True |
| 238 | self._thread = threading.Thread(target=self._loop, daemon=True) |
| 239 | self._thread.start() |
| 240 | print(f"[BatchServer] batch={batch_size}, schedule={schedule_ms}ms") |
| 241 | |
| 242 | def submit(self, prompt: str, max_tokens: int = 50) -> str: |
| 243 | req = BatchRequest(prompt=prompt, max_tokens=max_tokens) |
| 244 | with self.lock: |
| 245 | if len(self.queue) >= self.max_queue: |
| 246 | raise RuntimeError("Queue full") |
| 247 | self.queue.append(req) |
| 248 | req.event.wait() |
| 249 | return req.result[0] if req.result else "" |
| 250 | |
| 251 | def _loop(self): |
| 252 | while self.running: |
| 253 | # Wait for requests or timeout |
| 254 | t_start = time.time() |
| 255 | batch = [] |
| 256 | while time.time() - t_start < self.schedule_s: |
| 257 | with self.lock: |
| 258 | while len(self.queue) > 0 and len(batch) < self.batch_size: |
| 259 | batch.append(self.queue.popleft()) |
| 260 | if batch: |
| 261 | break |
| 262 | time.sleep(0.005) |
| 263 | |
| 264 | if not batch: |
| 265 | continue |
| 266 | |
| 267 | # Process batch |
| 268 | try: |
| 269 | self._process_batch(batch) |
| 270 | except Exception as e: |
| 271 | for req in batch: |
| 272 | req.result.append(f"[Error: {e}]") |
| 273 | req.event.set() |
| 274 | |
| 275 | def _process_batch(self, batch: list[BatchRequest]): |
| 276 | """Process a batch of requests through the model.""" |
| 277 | # Encode all prompts |
| 278 | prompts = [req.prompt for req in batch] |
| 279 | encoded = [self.model.encode(p) for p in prompts] |
| 280 | max_len = max(len(e) for e in encoded) |
| 281 | batch_sz = len(batch) |
| 282 | |
| 283 | # For now, process sequentially within batch (parallel KV cache pending) |
| 284 | # This still saves weight-load overhead vs independent calls |
| 285 | # via the _run_batch helper |
| 286 | logits_list = _run_batch(self.model, encoded[0], batch_sz, gen_tokens=1) |
| 287 | |
| 288 | # Generate tokens per sequence |
| 289 | for idx, req in enumerate(batch): |
| 290 | try: |
| 291 | ids = encoded[idx].copy() |
| 292 | out_ids = [] |
| 293 | for _ in range(min(req.max_tokens, 20)): # cap for speed |
| 294 | logits = self.model.forward(ids, use_cache=True) |
| 295 | nid = int(np.argmax(logits[-1])) |
| 296 | if nid == self.model.eos_id: |
| 297 | break |
| 298 | out_ids.append(nid) |
| 299 | ids.append(nid) |
| 300 | result = self.model.decode(out_ids) |
| 301 | req.result.append(result) |
| 302 | except Exception as e: |
| 303 | req.result.append(f"[Error: {e}]") |
| 304 | finally: |
| 305 | req.event.set() |
| 306 | |
| 307 | # Clean up per-sequence KV caches |
| 308 | self.model._kv_cache = None |
| 309 | self.model._cached_len = 0 |
| 310 | gc.collect() |
| 311 | |
| 312 | def shutdown(self): |
| 313 | self.running = False |
| 314 | self._thread.join(timeout=5) |
| 315 | # Release waiting requests |
| 316 | with self.lock: |
| 317 | for req in self.queue: |
| 318 | req.result.append("[shutdown]") |
| 319 | req.event.set() |
| 320 | |
| 321 | |
| 322 | # ─── CLI ────────────────────────────────────────────────────────────────────── |
| 323 | |
| 324 | if __name__ == '__main__': |
| 325 | parser = argparse.ArgumentParser() |
| 326 | parser.add_argument('--model', default=os.environ.get('MODEL_PATH', '')) |
| 327 | parser.add_argument('--bench', action='store_true', help='Run batch benchmark') |
| 328 | parser.add_argument('--batch-sizes', type=str, default='1,2,4,8', |
| 329 | help='Comma-separated batch sizes for benchmark') |
| 330 | args = parser.parse_args() |
| 331 | |
| 332 | model_path = args.model |
| 333 | if not model_path: |
| 334 | import glob |
| 335 | files = glob.glob('*.gguf') |
| 336 | model_path = files[0] if files else 'Llama-3.2-1B-Instruct-Q4_0.gguf' |
| 337 | |
| 338 | if args.bench: |
| 339 | batch_sizes = [int(x) for x in args.batch_sizes.split(',')] |
| 340 | batch_bench(model_path, batch_sizes) |
| 341 | else: |
| 342 | # Interactive continuous batching test |
| 343 | server = ContinuousBatchServer(model_path, batch_size=4, schedule_ms=100) |
| 344 | print("\nSending 4 concurrent requests...") |
| 345 | prompts = ["The capital of France is", "What is 2+2?", |
| 346 | "Hello, my name is", "The meaning of life is"] |
| 347 | t0 = time.time() |
| 348 | results = [] |
| 349 | threads = [] |
| 350 | for p in prompts: |
| 351 | t = threading.Thread(target=lambda p=p: results.append(server.submit(p, 5))) |
| 352 | threads.append(t) |
| 353 | t.start() |
| 354 | for t in threads: |
| 355 | t.join() |
| 356 | t1 = time.time() |
| 357 | print(f"All 4 completed in {t1-t0:.1f}s") |
| 358 | for p, r in zip(prompts, results): |
| 359 | print(f" {p} → {r}") |
| 360 | server.shutdown() |