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_longprompt.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_longprompt.py` 154 lines · 6439 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """GPT-OSS long-prompt benchmark: MojoLlama serial vs llama.cpp server.""" 3 import sys, os, time, json, subprocess, urllib.request, signal, numpy as np 4 from concurrent.futures import ThreadPoolExecutor, as_completed 5 6 MODEL = "/tmp/models/gpt-oss-20b-Q4_K_M.gguf" 7 N_USERS = 10 8 PROMPT_LEN = 512 9 GEN_TOKENS = 20 10 LLAMA_PORT = 8093 11 12 # Generate a deterministic prompt of N tokens 13 def make_prompt(n_tokens): 14 return "The capital of France is Paris. " * (n_tokens // 6 + 1) 15 16 prompt = make_prompt(PROMPT_LEN) 17 18 # ────────────────────────────────────────────── 19 # 1. llama.cpp server 20 # ────────────────────────────────────────────── 21 print(f"\n{'='*60}") 22 print(f" llama.cpp: {N_USERS} users × {PROMPT_LEN}-tok prompt + {GEN_TOKENS} gen") 23 print(f"{'='*60}") 24 25 cmd = ["/tmp/llama.cpp/build/bin/llama-server", "-m", MODEL, 26 "-c", "4096", "-t", "32", "--port", str(LLAMA_PORT), 27 "--cont-batching", "--no-webui", "--mlock"] 28 29 proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, 30 preexec_fn=lambda: signal.signal(signal.SIGINT, signal.SIG_IGN)) 31 32 url = f"http://localhost:{LLAMA_PORT}" 33 for attempt in range(60): 34 try: 35 r = urllib.request.urlopen(f"{url}/health", timeout=2) 36 if r.status == 200: break 37 except: pass 38 time.sleep(2) 39 else: 40 proc.kill(); print(" FAILED to start"); sys.exit(1) 41 print(" Server ready") 42 43 def send_req(p, mt): 44 data = {"prompt": p, "max_tokens": mt, "temperature": 0} 45 req = urllib.request.Request(f"{url}/v1/completions", 46 data=json.dumps(data).encode(), 47 headers={"Content-Type":"application/json"}) 48 t0 = time.perf_counter() 49 with urllib.request.urlopen(req, timeout=300) as resp: 50 r = json.loads(resp.read()) 51 elapsed = time.perf_counter() - t0 52 tok = r.get('usage',{}).get('completion_tokens',0) or GEN_TOKENS 53 return elapsed, tok 54 55 wall_start = time.perf_counter() 56 lats, toks = [], [] 57 with ThreadPoolExecutor(max_workers=N_USERS) as pool: 58 futures = [pool.submit(send_req, prompt, GEN_TOKENS) for _ in range(N_USERS)] 59 for f in as_completed(futures): 60 lat, tok = f.result() 61 lats.append(lat); toks.append(tok) 62 wall = time.perf_counter() - wall_start 63 64 proc.terminate() 65 try: proc.wait(timeout=5) 66 except: proc.kill() 67 68 lats.sort() 69 p50 = lats[len(lats)//2]*1000 70 p95 = lats[int(len(lats)*0.95)]*1000 if len(lats)>1 else lats[-1]*1000 71 tps = sum(toks)/wall 72 73 print(f" Success: {len(lats)}/{N_USERS}") 74 print(f" Wall: {wall*1000:.0f}ms") 75 print(f" p50: {p50:.0f}ms p95: {p95:.0f}ms") 76 print(f" Throughput: {tps:.1f} tok/s") 77 78 llama_result = {"p50": p50, "p95": p95, "tps": tps, "wall": wall} 79 80 # ────────────────────────────────────────────── 81 # 2. MojoLlama serial engine 82 # ────────────────────────────────────────────── 83 print(f"\n{'='*60}") 84 print(f" MojoLlama: {N_USERS} users × {PROMPT_LEN}-tok prompt + {GEN_TOKENS} gen") 85 print(f"{'='*60}") 86 87 sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'kernels')) 88 from turbo_engine_v7_moe import TurboEngineV7MoE 89 e = TurboEngineV7MoE(MODEL, 32) 90 print(f" Engine loaded: {e.n_layers}L") 91 92 wall_start = time.perf_counter() 93 mojo_lats, mojo_toks = [], [] 94 95 # For the pure Python engine version, simulate a long prompt by 96 # running forward() for PROMPT_LEN tokens of prefill, then GEN_TOKENS decode 97 # Each user gets their own KV state (the engine uses a single KV cache though) 98 # 99 # NOTE: The engine's forward() uses a single KV cache, so we can't properly 100 # interleave 10 sequences. For a fair comparison, we process them sequentially. 101 # This matches what the serial server does. 102 103 for user in range(N_USERS): 104 t0 = time.perf_counter() 105 t = 0 106 token = np.array([[1]], dtype=np.int32) # BOS 107 # Prefill: run through PROMPT_LEN tokens 108 for pos in range(PROMPT_LEN): 109 logits = e.forward(token) 110 t += 1 111 token = np.array([[100 + (pos % 50000)]], dtype=np.int32) # fake prompt token 112 # Generation: produce GEN_TOKENS 113 for pos in range(GEN_TOKENS): 114 logits = e.forward(token) 115 token_id = int(np.argmax(logits)) 116 t += 1 117 token = np.array([[token_id]], dtype=np.int32) 118 elapsed = time.perf_counter() - t0 119 mojo_lats.append(elapsed) 120 mojo_toks.append(t) 121 122 wall = time.perf_counter() - wall_start 123 mojo_lats.sort() 124 p50 = mojo_lats[len(mojo_lats)//2]*1000 125 p95 = mojo_lats[int(len(mojo_lats)*0.95)]*1000 if len(mojo_lats)>1 else mojo_lats[-1]*1000 126 tps = sum(mojo_toks)/wall 127 128 print(f" Success: {len(mojo_lats)}/{N_USERS}") 129 print(f" Wall: {wall*1000:.0f}ms") 130 print(f" p50: {p50:.0f}ms p95: {p95:.0f}ms") 131 print(f" Throughput: {tps:.1f} tok/s") 132 133 mojo_result = {"p50": p50, "p95": p95, "tps": tps, "wall": wall} 134 135 # ────────────────────────────────────────────── 136 # COMPARISON 137 # ────────────────────────────────────────────── 138 print(f"\n{'='*60}") 139 print(f" COMPARISON: GPT-OSS, {N_USERS} users, {PROMPT_LEN}-tok prompts") 140 print(f"{'='*60}") 141 print(f" {'':>25} {'llama.cpp':>15} {'MojoLlama':>15} {'Ratio':>10}") 142 print(f" {'─'*25} {'─'*15} {'─'*15} {'─'*10}") 143 r = mojo_result['tps'] / llama_result['tps'] 144 print(f" {'Throughput (tok/s)':>25} {llama_result['tps']:>15.1f} {mojo_result['tps']:>15.1f} {r:>9.2f}x") 145 print(f" {'Wall time (ms)':>25} {llama_result['wall']*1000:>15.0f} {mojo_result['wall']*1000:>15.0f}") 146 print(f" {'p50 latency (ms)':>25} {llama_result['p50']:>15.0f} {mojo_result['p50']:>15.0f}") 147 print(f" {'p95 latency (ms)':>25} {llama_result['p95']:>15.0f} {mojo_result['p95']:>15.0f}") 148 if r > 1: 149 print(f"\n ✅ MojoLlama is {r:.2f}x faster than llama.cpp") 150 print(f" (MXFP4 batch matmul beats Q4_K under load)") 151 else: 152 print(f"\n ⚠️ llama.cpp leads by {1/r:.2f}x") 153 print(f" (MojoLlama needs batch_forward for parallel processing)") 154 print(f"{'='*60}")