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/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 / bench_concurrency.py` 164 lines · 5518 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """MojoLlama Concurrent Benchmark — measure throughput under load. 3 4 Tests how many concurrent requests the server can handle at various 5 concurrency levels. Reports req/s, latency, and error rates. 6 7 Usage: 8 # Start the server first: 9 python3 -m mojollama.server --model model.gguf --port 9000 10 11 # Then run benchmark: 12 python3 bench_concurrency.py --url http://127.0.0.1:9000 13 python3 bench_concurrency.py --url http://127.0.0.1:9000 --concurrency 4,8,16,32 14 """ 15 16 import json 17 import time 18 import argparse 19 import urllib.request 20 import concurrent.futures 21 from statistics import median, stdev 22 23 24 def send_request(url, prompt="What is 2+2? Answer concisely.", max_tokens=50): 25 """Send one chat completion request, return timing.""" 26 payload = json.dumps({ 27 "messages": [{"role": "user", "content": prompt}], 28 "max_tokens": max_tokens, 29 }).encode() 30 31 t0 = time.time() 32 try: 33 req = urllib.request.Request( 34 f"{url}/v1/chat/completions", 35 data=payload, 36 headers={"Content-Type": "application/json"}, 37 ) 38 with urllib.request.urlopen(req, timeout=60) as resp: 39 data = json.loads(resp.read()) 40 elapsed = time.time() - t0 41 content = data.get("choices", [{}])[0].get("message", {}).get("content", "") 42 usage = data.get("usage", {}) 43 return { 44 "ok": True, 45 "time": elapsed, 46 "len": len(content), 47 "prompt_tokens": usage.get("prompt_tokens", 0), 48 "completion_tokens": usage.get("completion_tokens", 0), 49 } 50 except Exception as e: 51 elapsed = time.time() - t0 52 return {"ok": False, "time": elapsed, "error": str(e)} 53 54 55 def bench_concurrent(url, n_requests, concurrency, prompt=None): 56 """Run benchmark at a given concurrency level.""" 57 prompts = [ 58 "What is 2+2?", 59 "Explain quantum computing.", 60 "Write a haiku about AI.", 61 "What is the capital of France?", 62 "Define machine learning.", 63 "Hello, how are you?", 64 "What is the speed of light?", 65 "Tell me a joke.", 66 ] 67 68 with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as ex: 69 futures = [ 70 ex.submit(send_request, url, prompt=prompts[i % len(prompts)]) 71 for i in range(n_requests) 72 ] 73 results = [f.result() for f in concurrent.futures.as_completed(futures)] 74 75 ok = [r for r in results if r["ok"]] 76 fail = [r for r in results if not r["ok"]] 77 times = [r["time"] for r in ok] 78 79 if not times: 80 return { 81 "concurrency": concurrency, 82 "requests": n_requests, 83 "ok": 0, 84 "fail": len(fail), 85 "throughput": 0, 86 "avg_ms": 0, 87 "p50_ms": 0, 88 "p95_ms": 0, 89 "p99_ms": 0, 90 "total_time": 0, 91 } 92 93 total_time = max(times) 94 sorted_times = sorted(times) 95 p50 = sorted_times[len(sorted_times) // 2] 96 p95 = sorted_times[int(len(sorted_times) * 0.95)] 97 p99 = sorted_times[int(len(sorted_times) * 0.99)] 98 99 return { 100 "concurrency": concurrency, 101 "requests": n_requests, 102 "ok": len(ok), 103 "fail": len(fail), 104 "throughput": len(ok) / total_time if total_time > 0 else 0, 105 "avg_ms": (sum(times) / len(times)) * 1000, 106 "p50_ms": p50 * 1000, 107 "p95_ms": p95 * 1000, 108 "p99_ms": p99 * 1000, 109 "total_time": total_time, 110 "errors": [r["error"] for r in fail[:3]] if fail else [], 111 } 112 113 114 def main(): 115 parser = argparse.ArgumentParser( 116 description="MojoLlama concurrent benchmark" 117 ) 118 parser.add_argument("--url", default="http://127.0.0.1:9000", 119 help="Server URL") 120 parser.add_argument("--concurrency", "-c", 121 default="1,2,4,8,16", 122 help="Comma-separated concurrency levels") 123 parser.add_argument("--requests", "-n", type=int, default=32, 124 help="Requests per concurrency level") 125 parser.add_argument("--prompt", default=None, 126 help="Custom prompt (optional)") 127 args = parser.parse_args() 128 129 concurrency_levels = [int(c) for c in args.concurrency.split(",")] 130 131 # Warmup 132 print("Warming up...") 133 for _ in range(3): 134 send_request(args.url, prompt=args.prompt or "Hi") 135 print() 136 137 print(f"Server: {args.url}") 138 print(f"Requests per test: {args.requests}") 139 print(f"Concurrency levels: {args.concurrency}") 140 print() 141 print(f" {'conc':>5} | {'reqs':>5} | {'ok':>5} | {'fail':>5} | " 142 f"{'avg_ms':>7} | {'p50_ms':>7} | {'p95_ms':>7} | " 143 f"{'req/s':>8} | {'total_s':>8}") 144 print("-" * 85) 145 146 for conc in concurrency_levels: 147 result = bench_concurrent( 148 args.url, args.requests, conc, prompt=args.prompt 149 ) 150 print(f" {result['concurrency']:>5} | {result['requests']:>5} | " 151 f"{result['ok']:>5} | {result['fail']:>5} | " 152 f"{result['avg_ms']:>7.1f} | {result['p50_ms']:>7.1f} | " 153 f"{result['p95_ms']:>7.1f} | " 154 f"{result['throughput']:>8.1f} | {result['total_time']:>8.2f}") 155 156 # Summary 157 print() 158 print("Tip: For best latency, use low concurrency (1-4).") 159 print(" For best throughput, use higher concurrency (8-32).") 160 print(" The 'knee' in the latency curve shows optimal concurrency.") 161 162 163 if __name__ == "__main__": 164 main()