interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

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."""
3import sys, os, time, json, subprocess, urllib.request, signal, numpy as np
4from concurrent.futures import ThreadPoolExecutor, as_completed
5
6MODEL = "/tmp/models/gpt-oss-20b-Q4_K_M.gguf"
7N_USERS = 10
8PROMPT_LEN = 512
9GEN_TOKENS = 20
10LLAMA_PORT = 8093
11
12# Generate a deterministic prompt of N tokens
13def make_prompt(n_tokens):
14 return "The capital of France is Paris. " * (n_tokens // 6 + 1)
15
16prompt = make_prompt(PROMPT_LEN)
17
18# ──────────────────────────────────────────────
19# 1. llama.cpp server
20# ──────────────────────────────────────────────
21print(f"\n{'='*60}")
22print(f" llama.cpp: {N_USERS} users × {PROMPT_LEN}-tok prompt + {GEN_TOKENS} gen")
23print(f"{'='*60}")
24
25cmd = ["/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
29proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
30 preexec_fn=lambda: signal.signal(signal.SIGINT, signal.SIG_IGN))
31
32url = f"http://localhost:{LLAMA_PORT}"
33for 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)
39else:
40 proc.kill(); print(" FAILED to start"); sys.exit(1)
41print(" Server ready")
42
43def 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
55wall_start = time.perf_counter()
56lats, toks = [], []
57with 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)
62wall = time.perf_counter() - wall_start
63
64proc.terminate()
65try: proc.wait(timeout=5)
66except: proc.kill()
67
68lats.sort()
69p50 = lats[len(lats)//2]*1000
70p95 = lats[int(len(lats)*0.95)]*1000 if len(lats)>1 else lats[-1]*1000
71tps = sum(toks)/wall
72
73print(f" Success: {len(lats)}/{N_USERS}")
74print(f" Wall: {wall*1000:.0f}ms")
75print(f" p50: {p50:.0f}ms p95: {p95:.0f}ms")
76print(f" Throughput: {tps:.1f} tok/s")
77
78llama_result = {"p50": p50, "p95": p95, "tps": tps, "wall": wall}
79
80# ──────────────────────────────────────────────
81# 2. MojoLlama serial engine
82# ──────────────────────────────────────────────
83print(f"\n{'='*60}")
84print(f" MojoLlama: {N_USERS} users × {PROMPT_LEN}-tok prompt + {GEN_TOKENS} gen")
85print(f"{'='*60}")
86
87sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'kernels'))
88from turbo_engine_v7_moe import TurboEngineV7MoE
89e = TurboEngineV7MoE(MODEL, 32)
90print(f" Engine loaded: {e.n_layers}L")
91
92wall_start = time.perf_counter()
93mojo_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
103for 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
122wall = time.perf_counter() - wall_start
123mojo_lats.sort()
124p50 = mojo_lats[len(mojo_lats)//2]*1000
125p95 = mojo_lats[int(len(mojo_lats)*0.95)]*1000 if len(mojo_lats)>1 else mojo_lats[-1]*1000
126tps = sum(mojo_toks)/wall
127
128print(f" Success: {len(mojo_lats)}/{N_USERS}")
129print(f" Wall: {wall*1000:.0f}ms")
130print(f" p50: {p50:.0f}ms p95: {p95:.0f}ms")
131print(f" Throughput: {tps:.1f} tok/s")
132
133mojo_result = {"p50": p50, "p95": p95, "tps": tps, "wall": wall}
134
135# ──────────────────────────────────────────────
136# COMPARISON
137# ──────────────────────────────────────────────
138print(f"\n{'='*60}")
139print(f" COMPARISON: GPT-OSS, {N_USERS} users, {PROMPT_LEN}-tok prompts")
140print(f"{'='*60}")
141print(f" {'':>25} {'llama.cpp':>15} {'MojoLlama':>15} {'Ratio':>10}")
142print(f" {'─'*25} {'─'*15} {'─'*15} {'─'*10}")
143r = mojo_result['tps'] / llama_result['tps']
144print(f" {'Throughput (tok/s)':>25} {llama_result['tps']:>15.1f} {mojo_result['tps']:>15.1f} {r:>9.2f}x")
145print(f" {'Wall time (ms)':>25} {llama_result['wall']*1000:>15.0f} {mojo_result['wall']*1000:>15.0f}")
146print(f" {'p50 latency (ms)':>25} {llama_result['p50']:>15.0f} {mojo_result['p50']:>15.0f}")
147print(f" {'p95 latency (ms)':>25} {llama_result['p95']:>15.0f} {mojo_result['p95']:>15.0f}")
148if 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)")
151else:
152 print(f"\n ⚠️ llama.cpp leads by {1/r:.2f}x")
153 print(f" (MojoLlama needs batch_forward for parallel processing)")
154print(f"{'='*60}")