MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / concurrency_bench.py
| 1 | """Mojo Hybrid Serve — Multi-worker concurrent server + batch benchmark. |
| 2 | Tests: multi-process, batched forward, combined. |
| 3 | """ |
| 4 | import argparse, json, os, sys, time, gc, glob |
| 5 | import numpy as np |
| 6 | import multiprocessing as mp |
| 7 | import threading |
| 8 | from pathlib import Path |
| 9 | from dataclasses import dataclass, field |
| 10 | from queue import Queue, Empty |
| 11 | from typing import Optional |
| 12 | |
| 13 | sys.path.insert(0, str(Path(__file__).resolve().parent)) |
| 14 | from src.mojollama.model.inference import LLMInference |
| 15 | |
| 16 | |
| 17 | # ─── Multi-Worker Benchmark ────────────────────────────────────────────────── |
| 18 | |
| 19 | def worker_process(model_path: str, request_queue, result_queue, worker_id: int): |
| 20 | """Worker process that handles requests sequentially with KV cache.""" |
| 21 | os.environ['MOJOLLAMA_DEVICE'] = 'cpu' |
| 22 | model = LLMInference(model_path) |
| 23 | |
| 24 | while True: |
| 25 | try: |
| 26 | req_id, prompt, max_tokens = request_queue.get(timeout=2) |
| 27 | except Empty: |
| 28 | break |
| 29 | |
| 30 | t0 = time.time() |
| 31 | try: |
| 32 | result = model.generate(prompt, max_tokens=max_tokens) |
| 33 | elapsed = time.time() - t0 |
| 34 | result_queue.put((req_id, result, elapsed)) |
| 35 | except Exception as e: |
| 36 | result_queue.put((req_id, f"[ERROR: {e}]", time.time() - t0)) |
| 37 | |
| 38 | # Reset KV cache between requests |
| 39 | model._kv_cache = None |
| 40 | model._cached_len = 0 |
| 41 | gc.collect() |
| 42 | |
| 43 | |
| 44 | def bench_multiworker(model_path: str, num_workers: list[int] = None): |
| 45 | """Benchmark multi-worker throughput.""" |
| 46 | if num_workers is None: |
| 47 | num_workers = [1, 2, 4, 8, 16, 32] |
| 48 | |
| 49 | prompt = "The capital of France is" |
| 50 | n_requests = 32 # total requests to distribute |
| 51 | gen_tokens = 10 |
| 52 | |
| 53 | print("=" * 70) |
| 54 | print("MojoLlama — Multi-Worker Benchmark") |
| 55 | print(f"Model: {model_path}") |
| 56 | print(f"Requests: {n_requests} × {gen_tokens} tokens each") |
| 57 | print(f"Prompt: '{prompt}'") |
| 58 | print(f"CPU cores: {os.cpu_count()}") |
| 59 | print("=" * 70) |
| 60 | |
| 61 | for nw in num_workers: |
| 62 | if nw > n_requests: |
| 63 | continue |
| 64 | |
| 65 | request_queue = mp.Queue() |
| 66 | result_queue = mp.Queue() |
| 67 | |
| 68 | # Enqueue requests |
| 69 | for i in range(n_requests): |
| 70 | request_queue.put((i, prompt, gen_tokens)) |
| 71 | |
| 72 | # Start workers |
| 73 | t0 = time.time() |
| 74 | workers = [] |
| 75 | for w in range(nw): |
| 76 | p = mp.Process(target=worker_process, |
| 77 | args=(model_path, request_queue, result_queue, w)) |
| 78 | p.start() |
| 79 | workers.append(p) |
| 80 | |
| 81 | # Collect results |
| 82 | results = [] |
| 83 | completed = 0 |
| 84 | timeouts = 0 |
| 85 | while completed < n_requests and timeouts < 5: |
| 86 | try: |
| 87 | rid, text, elapsed = result_queue.get(timeout=10) |
| 88 | results.append((rid, elapsed)) |
| 89 | completed += 1 |
| 90 | timeouts = 0 |
| 91 | except Empty: |
| 92 | timeouts += 1 |
| 93 | |
| 94 | total_time = time.time() - t0 |
| 95 | |
| 96 | # Wait for workers |
| 97 | for p in workers: |
| 98 | p.terminate() |
| 99 | p.join(timeout=2) |
| 100 | |
| 101 | if results: |
| 102 | times = [r[1] for r in results] |
| 103 | avg_time = sum(times) / len(times) |
| 104 | total_tokens = len(results) * gen_tokens |
| 105 | throughput = total_tokens / total_time if total_time > 0 else 0 |
| 106 | req_s = len(results) / total_time if total_time > 0 else 0 |
| 107 | |
| 108 | print(f" workers={nw:2d} | total={total_time:.1f}s | " |
| 109 | f"avg_req={avg_time:.1f}s | throughput={throughput:.1f} tok/s | " |
| 110 | f"{req_s:.1f} req/s") |
| 111 | else: |
| 112 | print(f" workers={nw:2d} | FAILED (no results)") |
| 113 | |
| 114 | # llama.cpp comparison |
| 115 | print(f"\n llama.cpp 10-concurrent: 114 tok/s, 14.3 req/s") |
| 116 | print(f" Target: match or exceed at higher worker counts") |
| 117 | |
| 118 | |
| 119 | # ─── Continuous Batching Server ────────────────────────────────────────────── |
| 120 | |
| 121 | @dataclass |
| 122 | class Request: |
| 123 | prompt: str |
| 124 | max_tokens: int = 50 |
| 125 | result: list = field(default_factory=list) |
| 126 | event: threading.Event = field(default_factory=threading.Event) |
| 127 | |
| 128 | |
| 129 | class BatchServer: |
| 130 | """Multi-worker server with request queue.""" |
| 131 | |
| 132 | def __init__(self, model_path: str, num_workers: int = 4): |
| 133 | self.model_path = model_path |
| 134 | self.num_workers = num_workers |
| 135 | self.mp_requests = mp.Queue() |
| 136 | self.mp_results = mp.Queue() |
| 137 | self.workers = [] |
| 138 | self.running = True |
| 139 | self._start_workers() |
| 140 | |
| 141 | def _start_workers(self): |
| 142 | for w in range(self.num_workers): |
| 143 | p = mp.Process(target=worker_process, |
| 144 | args=(self.model_path, self.mp_requests, |
| 145 | self.mp_results, w)) |
| 146 | p.start() |
| 147 | self.workers.append(p) |
| 148 | print(f"[BatchServer] {self.num_workers} workers started") |
| 149 | |
| 150 | def submit(self, prompt: str, max_tokens: int = 50) -> str: |
| 151 | req_id = id(prompt) + int(time.time() * 1000) |
| 152 | self.mp_requests.put((req_id, prompt, max_tokens)) |
| 153 | # Wait for result with timeout |
| 154 | deadline = time.time() + max_tokens * 60 + 30 # generous timeout |
| 155 | while time.time() < deadline: |
| 156 | try: |
| 157 | rid, text, elapsed = self.mp_results.get(timeout=1) |
| 158 | if rid == req_id: |
| 159 | return text |
| 160 | # Wrong result, put back |
| 161 | self.mp_results.put((rid, text, elapsed)) |
| 162 | except Empty: |
| 163 | continue |
| 164 | return "[timeout]" |
| 165 | |
| 166 | def submit_batch(self, prompts: list[str], max_tokens: int = 50) -> list[str]: |
| 167 | """Submit multiple prompts and wait for all results.""" |
| 168 | ids = [(id(p) + int(time.time() * 1000) + i) for i, p in enumerate(prompts)] |
| 169 | for i, p in enumerate(prompts): |
| 170 | self.mp_requests.put((ids[i], p, max_tokens)) |
| 171 | |
| 172 | results = {} |
| 173 | deadline = time.time() + max_tokens * 60 + 60 |
| 174 | while len(results) < len(prompts) and time.time() < deadline: |
| 175 | try: |
| 176 | rid, text, elapsed = self.mp_results.get(timeout=1) |
| 177 | if rid in ids: |
| 178 | results[rid] = text |
| 179 | else: |
| 180 | self.mp_results.put((rid, text, elapsed)) |
| 181 | except Empty: |
| 182 | continue |
| 183 | |
| 184 | return [results.get(rid, "[timeout]") for rid in ids] |
| 185 | |
| 186 | def shutdown(self): |
| 187 | self.running = False |
| 188 | for p in self.workers: |
| 189 | p.terminate() |
| 190 | p.join(timeout=3) |
| 191 | |
| 192 | |
| 193 | # ─── Mixed Benchmark ───────────────────────────────────────────────────────── |
| 194 | |
| 195 | def bench_continuous(model_path: str): |
| 196 | """Benchmark the continuous batching server with concurrent users.""" |
| 197 | import threading as th |
| 198 | |
| 199 | print("=" * 70) |
| 200 | print("MojoLlama — Concurrent User Benchmark") |
| 201 | print("=" * 70) |
| 202 | |
| 203 | for n_workers in [2, 4, 8]: |
| 204 | server = BatchServer(model_path, num_workers=n_workers) |
| 205 | time.sleep(5) # Wait for workers to start |
| 206 | |
| 207 | n_users = min(n_workers * 2, 16) |
| 208 | prompts = ["What is the capital of France?"] * n_users |
| 209 | |
| 210 | t0 = time.time() |
| 211 | threads = [] |
| 212 | results = [] |
| 213 | lock = th.Lock() |
| 214 | |
| 215 | def user_task(prompt): |
| 216 | r = server.submit(prompt, max_tokens=10) |
| 217 | with lock: |
| 218 | results.append(r) |
| 219 | |
| 220 | for p in prompts: |
| 221 | t = th.Thread(target=user_task, args=(p,)) |
| 222 | threads.append(t) |
| 223 | t.start() |
| 224 | |
| 225 | for t in threads: |
| 226 | t.join() |
| 227 | |
| 228 | total = time.time() - t0 |
| 229 | server.shutdown() |
| 230 | |
| 231 | tok_count = sum(len(r.split()) for r in results if r and not r.startswith('[')) |
| 232 | print(f" workers={n_workers}, users={n_users}: {total:.1f}s, " |
| 233 | f"{tok_count/total:.1f} tok/s, {n_users/total:.1f} req/s") |
| 234 | time.sleep(2) |
| 235 | |
| 236 | |
| 237 | # ─── CLI ────────────────────────────────────────────────────────────────────── |
| 238 | |
| 239 | if __name__ == '__main__': |
| 240 | parser = argparse.ArgumentParser() |
| 241 | parser.add_argument('--model', default=os.environ.get('MODEL_PATH', '')) |
| 242 | parser.add_argument('--bench', choices=['multi', 'batch', 'all'], default='all') |
| 243 | args = parser.parse_args() |
| 244 | |
| 245 | model_path = args.model |
| 246 | if not model_path: |
| 247 | files = glob.glob('*.gguf') |
| 248 | model_path = files[0] if files else 'Llama-3.2-1B-Instruct-Q4_0.gguf' |
| 249 | |
| 250 | if args.bench in ('multi', 'all'): |
| 251 | bench_multiworker(model_path) |
| 252 | if args.bench in ('all',): |
| 253 | bench_continuous(model_path) |