MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / benchmarks / bench_10users.py
| 1 | #!/usr/bin/env python3 |
| 2 | """GPT-OSS-20B concurrent throughput: MojoLlama engine vs llama.cpp server.""" |
| 3 | import sys, os, time, json, subprocess, urllib.request, signal |
| 4 | from concurrent.futures import ThreadPoolExecutor, as_completed |
| 5 | |
| 6 | MODEL = "/tmp/models/gpt-oss-20b-Q4_K_M.gguf" |
| 7 | LLAMA_PORT = 8092 |
| 8 | PROMPT = "What is the capital of France?" |
| 9 | MAX_TOKENS = 20 |
| 10 | N_USERS = 10 |
| 11 | N_REQUESTS = 5 # requests per user |
| 12 | |
| 13 | def send_request(url, data, timeout=120): |
| 14 | try: |
| 15 | req = urllib.request.Request(url, data=json.dumps(data).encode(), |
| 16 | headers={"Content-Type": "application/json"}) |
| 17 | t0 = time.perf_counter() |
| 18 | with urllib.request.urlopen(req, timeout=timeout) as resp: |
| 19 | result = json.loads(resp.read()) |
| 20 | elapsed = time.perf_counter() - t0 |
| 21 | tok = result.get('usage', {}).get('completion_tokens', MAX_TOKENS) |
| 22 | if not tok: tok = MAX_TOKENS |
| 23 | return elapsed, tok, True |
| 24 | except Exception as e: |
| 25 | return 0, 0, False |
| 26 | |
| 27 | def bench_llama_cpp_concurrent(): |
| 28 | """Benchmark llama.cpp server with 10 concurrent users, each sending 5 requests.""" |
| 29 | print(f"\n{'='*60}") |
| 30 | print(f" llama.cpp: 10 users × {N_REQUESTS} requests each (GPT-OSS)") |
| 31 | print(f"{'='*60}") |
| 32 | |
| 33 | cmd = ["/tmp/llama.cpp/build/bin/llama-server", "-m", MODEL, |
| 34 | "-c", "4096", "-t", "32", "--port", str(LLAMA_PORT), |
| 35 | "--cont-batching", "--no-webui", "--mlock"] |
| 36 | |
| 37 | proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, |
| 38 | preexec_fn=lambda: signal.signal(signal.SIGINT, signal.SIG_IGN)) |
| 39 | |
| 40 | url = f"http://localhost:{LLAMA_PORT}" |
| 41 | for attempt in range(60): |
| 42 | try: |
| 43 | r = urllib.request.urlopen(f"{url}/health", timeout=2) |
| 44 | if r.status == 200: break |
| 45 | except: pass |
| 46 | time.sleep(2) |
| 47 | else: |
| 48 | proc.kill(); return None |
| 49 | |
| 50 | total_latencies = [] |
| 51 | total_tokens = 0 |
| 52 | wall_start = time.perf_counter() |
| 53 | |
| 54 | def user_bench(_): |
| 55 | user_lats = [] |
| 56 | user_toks = 0 |
| 57 | for _ in range(N_REQUESTS): |
| 58 | data = {"prompt": PROMPT, "max_tokens": MAX_TOKENS, "temperature": 0} |
| 59 | lat, tok, ok = send_request(f"{url}/v1/completions", data) |
| 60 | if ok: |
| 61 | user_lats.append(lat) |
| 62 | user_toks += tok |
| 63 | return user_lats, user_toks |
| 64 | |
| 65 | with ThreadPoolExecutor(max_workers=N_USERS) as pool: |
| 66 | futures = [pool.submit(user_bench, i) for i in range(N_USERS)] |
| 67 | for f in as_completed(futures): |
| 68 | lats, toks = f.result() |
| 69 | total_latencies.extend(lats) |
| 70 | total_tokens += toks |
| 71 | |
| 72 | wall_elapsed = time.perf_counter() - wall_start |
| 73 | proc.terminate() |
| 74 | try: proc.wait(timeout=5) |
| 75 | except: proc.kill() |
| 76 | |
| 77 | total_latencies.sort() |
| 78 | n = len(total_latencies) |
| 79 | p50 = total_latencies[n//2] * 1000 |
| 80 | p95 = total_latencies[int(n*0.95)] * 1000 if n > 1 else total_latencies[-1] * 1000 |
| 81 | throughput = total_tokens / wall_elapsed |
| 82 | |
| 83 | print(f" Results:") |
| 84 | print(f" Requests: {len(total_latencies)}/{N_USERS*N_REQUESTS}") |
| 85 | print(f" Wall time: {wall_elapsed*1000:.0f} ms") |
| 86 | print(f" p50: {p50:.0f} ms p95: {p95:.0f} ms") |
| 87 | print(f" Tokens: {total_tokens}") |
| 88 | print(f" Throughput: {throughput:.1f} tok/s") |
| 89 | return {"p50": p50, "p95": p95, "throughput": throughput, "requests": len(total_latencies)} |
| 90 | |
| 91 | |
| 92 | def bench_mojollama_direct(): |
| 93 | """MojoLlama: direct engine benchmark simulating batch concurrency. |
| 94 | |
| 95 | MojoLlama's batch_forward supports B=1..N. For concurrent users, |
| 96 | we run them sequentially (since the engine is single-threaded for |
| 97 | decode). We measure how fast N individual sequential requests finish. |
| 98 | This gives us the throughput under a simple round-robin load. |
| 99 | """ |
| 100 | print(f"\n{'='*60}") |
| 101 | print(f" MojoLlama: {N_USERS} sequential requests (GPT-OSS)") |
| 102 | print(f"{'='*60}") |
| 103 | |
| 104 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'kernels')) |
| 105 | from turbo_engine_v7_moe import TurboEngineV7MoE |
| 106 | |
| 107 | e = TurboEngineV7MoE(MODEL, 32) |
| 108 | print(f" Engine loaded: {e.n_layers}L, {e.n_experts} experts") |
| 109 | |
| 110 | total_latencies = [] |
| 111 | total_tokens = 0 |
| 112 | wall_start = time.perf_counter() |
| 113 | import numpy as np |
| 114 | |
| 115 | for user in range(N_USERS): |
| 116 | for req in range(N_REQUESTS): |
| 117 | t0 = time.perf_counter() |
| 118 | tokens = np.array([[1]], dtype=np.int32) # BOS |
| 119 | tok_count = 0 |
| 120 | for _ in range(MAX_TOKENS): |
| 121 | logits = e.forward(tokens) |
| 122 | token = int(np.argmax(logits)) |
| 123 | tok_count += 1 |
| 124 | tokens = np.array([[token]], dtype=np.int32) |
| 125 | if token == 2: # EOS |
| 126 | break |
| 127 | elapsed = time.perf_counter() - t0 |
| 128 | total_latencies.append(elapsed) |
| 129 | total_tokens += tok_count |
| 130 | |
| 131 | wall_elapsed = time.perf_counter() - wall_start |
| 132 | |
| 133 | total_latencies.sort() |
| 134 | n = len(total_latencies) |
| 135 | p50 = total_latencies[n//2] * 1000 |
| 136 | p95 = total_latencies[int(n*0.95)] * 1000 if n > 1 else total_latencies[-1] * 1000 |
| 137 | throughput = total_tokens / wall_elapsed |
| 138 | |
| 139 | print(f" Results:") |
| 140 | print(f" Requests: {len(total_latencies)}/{N_USERS*N_REQUESTS}") |
| 141 | print(f" Wall time: {wall_elapsed*1000:.0f} ms") |
| 142 | print(f" p50: {p50:.0f} ms p95: {p95:.0f} ms") |
| 143 | print(f" Tokens: {total_tokens}") |
| 144 | print(f" Throughput: {throughput:.1f} tok/s") |
| 145 | return {"p50": p50, "p95": p95, "throughput": throughput, "requests": len(total_latencies)} |
| 146 | |
| 147 | |
| 148 | # Run benchmarks |
| 149 | llama = bench_llama_cpp_concurrent() |
| 150 | mojo = bench_mojollama_direct() |
| 151 | |
| 152 | print(f"\n{'='*60}") |
| 153 | print(f" COMPARISON: GPT-OSS-20B — {N_USERS} users × {N_REQUESTS} requests") |
| 154 | print(f"{'='*60}") |
| 155 | print(f" {'':>20} {'llama.cpp':>14} {'MojoLlama':>14} {'Ratio':>10}") |
| 156 | print(f" {'─'*20} {'─'*14} {'─'*14} {'─'*10}") |
| 157 | |
| 158 | if llama and mojo: |
| 159 | ratio = mojo['throughput'] / llama['throughput'] |
| 160 | print(f" {'Throughput':>20} {llama['throughput']:>14.1f} {mojo['throughput']:>14.1f} {ratio:>9.2f}x") |
| 161 | print(f" {'p50':>20} {llama['p50']:>14.0f}ms {mojo['p50']:>14.0f}ms") |
| 162 | print(f" {'p95':>20} {llama['p95']:>14.0f}ms {mojo['p95']:>14.0f}ms") |
| 163 | if ratio > 1: |
| 164 | print(f"\n ✅ MojoLlama is {ratio:.2f}x faster than llama.cpp") |
| 165 | else: |
| 166 | print(f"\n ⚠️ llama.cpp is {1/ratio:.2f}x faster than MojoLlama") |
| 167 | else: |
| 168 | if not llama: print(" llama.cpp FAILED") |
| 169 | if not mojo: print(" MojoLlama FAILED") |
| 170 | print(f"{'='*60}") |