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/benchmarks/bench_concurrency.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 / benchmarks / bench_concurrency.py` 302 lines · 10662 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Concurrent throughput benchmark for MojoLlama server. 3 4 Starts server as a subprocess, fires concurrent requests at various 5 concurrency levels, measures latency and throughput. 6 7 Usage: 8 OMP_NUM_THREADS=32 python3 -u bench_concurrency.py 9 10 Or just: 11 python3 -u bench_concurrency.py 12 """ 13 14 import os 15 import sys 16 import time 17 import json 18 import subprocess 19 import signal 20 import socket 21 import statistics 22 import concurrent.futures 23 import urllib.request 24 import urllib.error 25 26 # ── Configuration ───────────────────────────────────────────────────────────── 27 MODEL_PATH = '/tmp/models/Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf' 28 PORT = 8080 29 SERVER_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 30 'server_moe.py') 31 OMP_THREADS = 32 32 CONCURRENCY_LEVELS = [1, 2, 4, 8] 33 NUM_REQUESTS = 10 # total requests per concurrency level 34 PROMPT = "What is the capital of France?" 35 MAX_TOKENS = 20 36 REQUEST_TIMEOUT = 120 # seconds per individual request 37 SERVER_START_TIMEOUT = 120 # seconds to wait for server to become ready 38 39 40 # ── Helpers ─────────────────────────────────────────────────────────────────── 41 42 def port_free(port: int) -> bool: 43 """Return True if *port* is not in use on all interfaces.""" 44 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: 45 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 46 try: 47 s.bind(('0.0.0.0', port)) 48 return True 49 except OSError: 50 return False 51 52 53 def free_port(port: int, timeout: float = 5.0) -> None: 54 """Wait up to *timeout* seconds for *port* to become free, then raise.""" 55 deadline = time.monotonic() + timeout 56 while time.monotonic() < deadline: 57 if port_free(port): 58 return 59 time.sleep(0.5) 60 raise RuntimeError(f"Port {port} is still in use after {timeout}s timeout") 61 62 63 def start_server() -> subprocess.Popen: 64 """Start MojoLlama server, wait until it's ready, return the Popen handle. 65 66 Readiness is detected by scanning stdout for the log line: 67 'Serving on 0.0.0.0:{PORT}' 68 """ 69 if not port_free(PORT): 70 raise RuntimeError( 71 f"Port {PORT} is already in use — cannot start server" 72 ) 73 74 env = os.environ.copy() 75 env['OMP_NUM_THREADS'] = str(OMP_THREADS) 76 77 proc = subprocess.Popen( 78 ['python3', '-u', SERVER_SCRIPT, MODEL_PATH, str(PORT)], 79 env=env, 80 stdout=subprocess.PIPE, 81 stderr=subprocess.STDOUT, 82 text=True, 83 bufsize=1, 84 ) 85 86 ready_marker = f"Serving on 0.0.0.0:{PORT}" 87 deadline = time.monotonic() + SERVER_START_TIMEOUT 88 89 while time.monotonic() < deadline: 90 # Read a line (blocking, but we have a deadline check around the loop) 91 line = proc.stdout.readline() 92 if line: 93 sys.stdout.write(f" [server] {line}") 94 sys.stdout.flush() 95 if ready_marker in line: 96 # Server is ready — short sleep to let everything settle 97 time.sleep(0.5) 98 return proc 99 100 # Did the process die? 101 if proc.poll() is not None: 102 # Drain remaining output for diagnostics 103 remaining = proc.stdout.read() 104 if remaining: 105 sys.stdout.write(f" [server] {remaining}") 106 sys.stdout.flush() 107 raise RuntimeError( 108 f"Server process exited prematurely (rc={proc.returncode})" 109 ) 110 111 # Timed out — kill and raise 112 kill_server(proc) 113 raise RuntimeError( 114 f"Server did not become ready within {SERVER_START_TIMEOUT}s" 115 ) 116 117 118 def kill_server(proc: subprocess.Popen) -> None: 119 """Send SIGTERM to *proc*; escalate to SIGKILL after 10 s.""" 120 if proc is None or proc.poll() is not None: 121 return 122 proc.terminate() # SIGTERM 123 try: 124 proc.wait(timeout=10) 125 except subprocess.TimeoutExpired: 126 proc.kill() # SIGKILL 127 proc.wait() 128 129 130 def send_request(prompt: str, max_tokens: int) -> tuple | None: 131 """Send one completion request, return (latency_ns, tokens_generated). 132 133 Returns *None* on any failure (timeout, HTTP error, connection error, …). 134 """ 135 url = f"http://localhost:{PORT}/v1/completions" 136 body = json.dumps({ 137 "prompt": prompt, 138 "max_tokens": max_tokens, 139 }).encode('utf-8') 140 141 req = urllib.request.Request( 142 url, 143 data=body, 144 headers={"Content-Type": "application/json"}, 145 method='POST', 146 ) 147 148 t0 = time.perf_counter_ns() 149 try: 150 with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp: 151 if resp.status != 200: 152 return None 153 resp_body = json.loads(resp.read()) 154 latency_ns = time.perf_counter_ns() - t0 155 usage = resp_body.get('usage', {}) 156 tokens_gen = usage.get('completion_tokens', 0) 157 return (latency_ns, tokens_gen) 158 except Exception: 159 return None 160 161 162 # ── Benchmark core ──────────────────────────────────────────────────────────── 163 164 def benchmark_concurrency( 165 concurrency_level: int, num_requests: int = 10 166 ) -> tuple[list, float]: 167 """Run *num_requests* completions with up to *concurrency_level* in-flight. 168 169 Returns (results_list, wall_clock_seconds). 170 171 Each result is a (latency_ns, tokens_generated) tuple. 172 Results only include successful (HTTP 200) responses. 173 """ 174 results: list[tuple[int, int]] = [] 175 wall_start = time.perf_counter_ns() 176 177 with concurrent.futures.ThreadPoolExecutor( 178 max_workers=concurrency_level 179 ) as pool: 180 futures = [ 181 pool.submit(send_request, PROMPT, MAX_TOKENS) 182 for _ in range(num_requests) 183 ] 184 for future in concurrent.futures.as_completed(futures): 185 r = future.result() 186 if r is not None: 187 results.append(r) 188 189 wall_ns = time.perf_counter_ns() - wall_start 190 return results, wall_ns / 1e9 191 192 193 def percentile(data: list[float], p: float) -> float: 194 """Compute the *p*-th percentile of *data* (0–100).""" 195 if not data: 196 return 0.0 197 s = sorted(data) 198 k = (p / 100.0) * (len(s) - 1) 199 f = int(k) 200 c = k - f 201 if f + 1 < len(s): 202 return s[f] + c * (s[f + 1] - s[f]) 203 return s[f] 204 205 206 # ── Main ────────────────────────────────────────────────────────────────────── 207 208 def main(): 209 print("=" * 72, flush=True) 210 print(" MojoLlama — Concurrent Throughput Benchmark") 211 print(f" Model: {MODEL_PATH}") 212 print(f" Port: {PORT}") 213 print(f" Server: {SERVER_SCRIPT}") 214 print(f" OMP_NUM_THREADS: {OMP_THREADS}") 215 print(f" Prompt: {PROMPT!r}") 216 print(f" Max tokens: {MAX_TOKENS}") 217 print(f" Requests per level: {NUM_REQUESTS}") 218 print(f" Concurrency levels: {CONCURRENCY_LEVELS}") 219 print("=" * 72, flush=True) 220 221 # Table header 222 header = ( 223 f" {'Concurrency':>12} | {'p50 lat (ms)':>13} | " 224 f"{'p95 lat (ms)':>13} | {'Throughput (tok/s)':>18}" 225 ) 226 print(header, flush=True) 227 print(" " + "-" * len(header), flush=True) 228 229 server_proc = None 230 231 for cl_idx, concurrency in enumerate(CONCURRENCY_LEVELS): 232 # ── Start a fresh server instance ──────────────────────────────── 233 # Kill previous instance (if any) 234 if server_proc is not None: 235 kill_server(server_proc) 236 server_proc = None 237 238 # Make sure port is free 239 try: 240 free_port(PORT, timeout=15) 241 except RuntimeError as e: 242 print(f" ERROR: {e}", flush=True) 243 sys.exit(1) 244 245 # Start new server 246 print(f"\n >>> Starting server for concurrency={concurrency} ...", 247 flush=True) 248 try: 249 server_proc = start_server() 250 except RuntimeError as e: 251 print(f" FAILED to start server: {e}", flush=True) 252 sys.exit(1) 253 254 print(f" >>> Server ready. Running benchmark ...", flush=True) 255 256 # ── Run the benchmark ──────────────────────────────────────────── 257 try: 258 results, wall_sec = benchmark_concurrency( 259 concurrency, num_requests=NUM_REQUESTS 260 ) 261 except Exception as e: 262 print(f" Benchmark FAILED: {e}", flush=True) 263 results, wall_sec = [], 0.0 264 265 # ── Compute metrics ────────────────────────────────────────────── 266 successful = len(results) 267 if results: 268 latencies_ms = [r[0] / 1_000_000 for r in results] 269 total_tokens = sum(r[1] for r in results) 270 p50_lat = percentile(latencies_ms, 50) 271 p95_lat = percentile(latencies_ms, 95) 272 throughput = total_tokens / wall_sec if wall_sec > 0 else 0.0 273 274 print( 275 f" {f'Results:':>12} {successful}/{NUM_REQUESTS} OK, " 276 f"total_wall={wall_sec:.2f}s, " 277 f"total_tokens={total_tokens}", flush=True 278 ) 279 else: 280 p50_lat = 0.0 281 p95_lat = 0.0 282 throughput = 0.0 283 print(f" {f'Results:':>12} 0/{NUM_REQUESTS} OK — all failed", 284 flush=True) 285 286 # ── Print table row ────────────────────────────────────────────── 287 print( 288 f" {concurrency:>12} | {p50_lat:>13.1f} | " 289 f"{p95_lat:>13.1f} | {throughput:>18.1f}", 290 flush=True 291 ) 292 293 # ── Cleanup final server ───────────────────────────────────────────── 294 if server_proc is not None: 295 kill_server(server_proc) 296 server_proc = None 297 298 print("\n Done.", flush=True) 299 300 301 if __name__ == '__main__': 302 main()