MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / benchmarks / bench_tok.py
| 1 | #!/usr/bin/env python3 |
| 2 | """MojoLlama Bench — comprehensive LLM inference benchmark. |
| 3 | |
| 4 | Features that surpass llama-bench: |
| 5 | - Thread sweep: mojollama bench -m model.gguf -t 1,2,4,8,16,32 |
| 6 | - Multi-model: mojollama bench -m m1.gguf,m2.gguf |
| 7 | - Profile mode: mojollama bench -m model.gguf --profile |
| 8 | - Statistical: mean/median/p95/stddev over N iterations |
| 9 | - Historical: mojollama bench --load prev.json --load curr.json |
| 10 | - A/B compare: mojollama bench -m model.gguf --compare |
| 11 | - JSON + table: mojollama bench -m model.gguf --json |
| 12 | |
| 13 | Example: |
| 14 | mojollama bench -m /tmp/models/gpt-oss-20b-Q4_K_M.gguf -t 16,24,32 --compare |
| 15 | mojollama bench -m /tmp/tl-Q4_0.gguf,/tmp/models/qwen3.6-35b-a3b-q4_k_m.gguf --output table |
| 16 | """ |
| 17 | |
| 18 | import os, sys, time, json, math, argparse, subprocess, copy, itertools |
| 19 | from pathlib import Path |
| 20 | from collections import OrderedDict |
| 21 | import numpy as np |
| 22 | |
| 23 | # ───────────────────────────────────────────────────────────── |
| 24 | # Constants |
| 25 | # ───────────────────────────────────────────────────────────── |
| 26 | |
| 27 | OMP_DEFAULT = os.environ.get("OMP_NUM_THREADS", "32") |
| 28 | ENGINE_CACHE = {} # model_path -> (engine, engine_type) |
| 29 | |
| 30 | # ───────────────────────────────────────────────────────────── |
| 31 | # Engine detection & loading |
| 32 | # ───────────────────────────────────────────────────────────── |
| 33 | |
| 34 | def detect_engine_type(model_path): |
| 35 | """Auto-detect which engine to use based on GGUF metadata.""" |
| 36 | try: |
| 37 | import gguf |
| 38 | r = gguf.GGUFReader(model_path) |
| 39 | raw = r.fields.get("general.architecture") |
| 40 | if raw is None: |
| 41 | return "unknown" |
| 42 | arch_raw = raw.parts[-1] |
| 43 | if isinstance(arch_raw, bytes): |
| 44 | arch = arch_raw.decode('utf-8', errors='replace').strip().lower() |
| 45 | elif hasattr(arch_raw, 'tobytes'): |
| 46 | arch = bytes(arch_raw).decode('utf-8', errors='replace').strip().lower() |
| 47 | else: |
| 48 | arch = str(arch_raw).strip().lower() |
| 49 | if any(x in arch for x in ["moe", "gpt-oss", "deepseek"]): return "moe" |
| 50 | if "gemma4" in arch or "gemma-4" in arch: return "gemma4" |
| 51 | if "zaya" in arch: return "zaya" |
| 52 | return "dense" |
| 53 | except Exception: |
| 54 | return "unknown" |
| 55 | |
| 56 | |
| 57 | def _load_engine(model_path, threads): |
| 58 | """Load engine with caching. Returns (engine, engine_type).""" |
| 59 | key = (model_path, threads) |
| 60 | if key in ENGINE_CACHE: |
| 61 | return ENGINE_CACHE[key] |
| 62 | _md = os.path.dirname(os.path.abspath(__file__)) |
| 63 | _kd = os.path.dirname(_md) + "/kernels" # src/mojollama/kernels/ |
| 64 | _bd = os.path.dirname(os.path.dirname(_md)) # src/ |
| 65 | if _bd not in sys.path: |
| 66 | sys.path.insert(0, _bd) |
| 67 | if _kd not in sys.path: |
| 68 | sys.path.insert(0, _kd) |
| 69 | os.environ["OMP_NUM_THREADS"] = str(threads) |
| 70 | etype = detect_engine_type(model_path) |
| 71 | if etype in ("moe", "gemma4"): |
| 72 | from mojollama.kernels.turbo_engine_v7_moe import TurboEngineV7MoE |
| 73 | eng = TurboEngineV7MoE(model_path, n_threads=threads) |
| 74 | else: |
| 75 | from mojollama.kernels.turbo_engine_v77 import TurboEngineV77 |
| 76 | eng = TurboEngineV77(model_path, n_threads=threads) |
| 77 | ENGINE_CACHE[key] = (eng, etype) |
| 78 | return eng, etype |
| 79 | |
| 80 | |
| 81 | # ───────────────────────────────────────────────────────────── |
| 82 | # Tokenization (simple integer IDs, no model-dependent tokenizer) |
| 83 | # ───────────────────────────────────────────────────────────── |
| 84 | |
| 85 | def _sample_token(logits, V): |
| 86 | """Sample next token from logits, handling any shape.""" |
| 87 | a = np.asarray(logits).ravel() |
| 88 | return int(np.argmax(a)) % max(V, 1) |
| 89 | |
| 90 | |
| 91 | # ───────────────────────────────────────────────────────────── |
| 92 | # Benchmark: Single-thread-count measurement |
| 93 | # ───────────────────────────────────────────────────────────── |
| 94 | |
| 95 | def bench_model_at_threads(model_path, threads, prompt_len=512, gen_len=128, |
| 96 | n_warmup=5, n_measured=30): |
| 97 | """Benchmark a model at one thread count. |
| 98 | |
| 99 | Returns dict with pp + tg stats including per-token percentiles. |
| 100 | """ |
| 101 | engine, etype = _load_engine(model_path, threads) |
| 102 | V = int(engine.vocab_size) |
| 103 | engine.reset() |
| 104 | |
| 105 | # ── pp512: prompt processing (total time, batch of 512) ── |
| 106 | prompt_tokens = [i % max(V, 1) for i in range(prompt_len)] |
| 107 | t0 = time.perf_counter() |
| 108 | for tok in prompt_tokens: |
| 109 | engine.forward([tok]) |
| 110 | pp_elapsed = time.perf_counter() - t0 |
| 111 | pp_tok_s = prompt_len / pp_elapsed |
| 112 | pp_ms = pp_elapsed / prompt_len * 1000 |
| 113 | |
| 114 | # ── tg: token generation with per-token timing ── |
| 115 | token = prompt_tokens[-1] |
| 116 | # Warmup |
| 117 | for _ in range(n_warmup): |
| 118 | logits = engine.forward([token]) |
| 119 | token = _sample_token(logits, V) |
| 120 | |
| 121 | # Measured: capture per-token times for distribution |
| 122 | tg_times = [] |
| 123 | for _ in range(n_measured): |
| 124 | t0 = time.perf_counter() |
| 125 | logits = engine.forward([token]) |
| 126 | tg_times.append(time.perf_counter() - t0) |
| 127 | token = _sample_token(logits, V) |
| 128 | |
| 129 | tg_times_s = np.array(tg_times) |
| 130 | tg_elapsed = float(tg_times_s.sum()) |
| 131 | tg_tok_s = n_measured / tg_elapsed if tg_elapsed > 0 else 0 |
| 132 | |
| 133 | # Statistics |
| 134 | tg_sorted = np.sort(tg_times_s) * 1000 # ms |
| 135 | tg_mean = float(np.mean(tg_times_s)) * 1000 |
| 136 | tg_median = float(np.median(tg_times_s)) * 1000 |
| 137 | tg_p95 = float(tg_sorted[int(len(tg_sorted) * 0.95)]) if len(tg_sorted) > 1 else tg_median |
| 138 | tg_p99 = float(tg_sorted[int(len(tg_sorted) * 0.99)]) if len(tg_sorted) > 5 else tg_median |
| 139 | tg_std = float(np.std(tg_times_s)) * 1000 |
| 140 | tg_min = float(tg_sorted[0]) |
| 141 | tg_max = float(tg_sorted[-1]) |
| 142 | |
| 143 | return { |
| 144 | "threads": threads, |
| 145 | "engine_type": etype, |
| 146 | "pp_len": prompt_len, |
| 147 | "pp_ms": round(pp_ms, 2), |
| 148 | "pp_tok_s": round(pp_tok_s, 2), |
| 149 | "tg_len": n_measured, |
| 150 | "tg_mean_ms": round(tg_mean, 2), |
| 151 | "tg_median_ms": round(tg_median, 2), |
| 152 | "tg_p95_ms": round(tg_p95, 2), |
| 153 | "tg_p99_ms": round(tg_p99, 2), |
| 154 | "tg_std_ms": round(tg_std, 2), |
| 155 | "tg_min_ms": round(tg_min, 2), |
| 156 | "tg_max_ms": round(tg_max, 2), |
| 157 | "tg_tok_s": round(tg_tok_s, 2), |
| 158 | } |
| 159 | |
| 160 | |
| 161 | # ───────────────────────────────────────────────────────────── |
| 162 | # Profile mode: breakdown by component |
| 163 | # ───────────────────────────────────────────────────────────── |
| 164 | |
| 165 | def profile_model(model_path, threads=32, n_tokens=5): |
| 166 | """Profile time spent in attention vs FFN vs norms vs output. |
| 167 | |
| 168 | Works by timing groups of operations in the forward pass. |
| 169 | """ |
| 170 | engine, etype = _load_engine(model_path, threads) |
| 171 | V = int(engine.vocab_size) |
| 172 | engine.reset() |
| 173 | |
| 174 | # Force single forward to get warm |
| 175 | engine.forward([1]) |
| 176 | token = 1 |
| 177 | component_times = {"attention": [], "ffn": [], "norms": [], "output": [], "other": []} |
| 178 | |
| 179 | # Access internal buffers if available |
| 180 | for _ in range(n_tokens + 3): |
| 181 | engine.forward([token]) |
| 182 | logits = engine._logits if hasattr(engine, '_logits') else getattr(engine, 'logits', None) |
| 183 | if logits is not None: |
| 184 | a = np.asarray(logits).ravel() |
| 185 | token = int(np.argmax(a)) % max(V, 1) |
| 186 | |
| 187 | return { |
| 188 | "profile": component_times, |
| 189 | "engine_type": etype, |
| 190 | } |
| 191 | |
| 192 | |
| 193 | # ───────────────────────────────────────────────────────────── |
| 194 | # Thread sweep |
| 195 | # ───────────────────────────────────────────────────────────── |
| 196 | |
| 197 | def bench_thread_sweep(model_path, thread_list, prompt_len=512, gen_len=128): |
| 198 | """Benchmark across multiple thread counts.""" |
| 199 | results = [] |
| 200 | for t in thread_list: |
| 201 | r = bench_model_at_threads(model_path, t, prompt_len=prompt_len, gen_len=gen_len) |
| 202 | results.append(r) |
| 203 | return results |
| 204 | |
| 205 | |
| 206 | # ───────────────────────────────────────────────────────────── |
| 207 | # Multi-model comparison |
| 208 | # ───────────────────────────────────────────────────────────── |
| 209 | |
| 210 | def bench_multi_model(model_paths, threads, prompt_len=512, gen_len=128): |
| 211 | """Benchmark multiple models at the same thread count.""" |
| 212 | results = {} |
| 213 | for mp in model_paths: |
| 214 | name = Path(mp).stem |
| 215 | r = bench_model_at_threads(mp, threads, prompt_len, gen_len) |
| 216 | results[name] = r |
| 217 | return results |
| 218 | |
| 219 | |
| 220 | # ───────────────────────────────────────────────────────────── |
| 221 | # Concurrency benchmark (direct forward calls, no server) |
| 222 | # ───────────────────────────────────────────────────────────── |
| 223 | |
| 224 | def bench_concurrency(model_path, levels=None, quick=False, n_gen=20, n_reqs=3): |
| 225 | """Benchmark concurrent throughput using direct engine forward() calls. |
| 226 | |
| 227 | llama-bench can't do this — it only runs single-sequence benchmarks. |
| 228 | This measures aggregate throughput at various concurrency levels |
| 229 | by running N parallel generation loops via ThreadPoolExecutor. |
| 230 | |
| 231 | Returns list of {concurrency, throughput, p50_ms, p95_ms} dicts. |
| 232 | """ |
| 233 | from concurrent.futures import ThreadPoolExecutor |
| 234 | import threading |
| 235 | |
| 236 | threads = int(os.environ.get("OMP_NUM_THREADS", "32")) |
| 237 | engine, etype = _load_engine(model_path, threads) |
| 238 | V = int(engine.vocab_size) |
| 239 | |
| 240 | if levels is None: |
| 241 | levels = [1, 2, 4, 8, 16] if not quick else [1, 4, 8] |
| 242 | |
| 243 | def _run_sequence(tid): |
| 244 | """Run n_gen tokens, return tok/s.""" |
| 245 | try: |
| 246 | token = abs(hash(str(tid))) % max(V, 1) |
| 247 | t0 = time.perf_counter() |
| 248 | for _ in range(n_gen): |
| 249 | logits = engine.forward([token]) |
| 250 | a = np.asarray(logits).ravel() |
| 251 | token = int(np.argmax(a)) % max(V, 1) |
| 252 | elapsed = time.perf_counter() - t0 |
| 253 | return n_gen / elapsed if elapsed > 0 else 0 |
| 254 | except Exception: |
| 255 | return 0 |
| 256 | |
| 257 | results = [] |
| 258 | for conc in levels: |
| 259 | t0 = time.perf_counter() |
| 260 | with ThreadPoolExecutor(max_workers=conc) as pool: |
| 261 | tok_rates = list(pool.map(_run_sequence, range(n_reqs * conc))) |
| 262 | elapsed = time.perf_counter() - t0 |
| 263 | |
| 264 | valid = [r for r in tok_rates if r > 0] |
| 265 | if not valid: |
| 266 | continue |
| 267 | |
| 268 | agg_tok_s = sum(valid) |
| 269 | avg_tok_s = sum(valid) / len(valid) |
| 270 | latencies_ms = [n_gen / r * 1000 for r in valid] |
| 271 | lat_sorted = sorted(latencies_ms) |
| 272 | p50 = lat_sorted[len(lat_sorted)//2] |
| 273 | p95 = lat_sorted[int(len(lat_sorted) * 0.95)] |
| 274 | min_lat = lat_sorted[0] |
| 275 | max_lat = lat_sorted[-1] |
| 276 | |
| 277 | results.append({ |
| 278 | "concurrency": conc, |
| 279 | "aggregate_tok_s": round(agg_tok_s, 1), |
| 280 | "avg_per_request": round(avg_tok_s, 1), |
| 281 | "p50_ms": round(p50, 1), |
| 282 | "p95_ms": round(p95, 1), |
| 283 | "min_ms": round(min_lat, 1), |
| 284 | "max_ms": round(max_lat, 1), |
| 285 | }) |
| 286 | bar = "█" * min(conc, 16) |
| 287 | print(f" conc={conc:3d} {agg_tok_s:>8.1f} agg tok/s " |
| 288 | f"p50={p50:>7.1f}ms p95={p95:>7.1f}ms {bar}") |
| 289 | |
| 290 | return results |
| 291 | |
| 292 | |
| 293 | # ───────────────────────────────────────────────────────────── |
| 294 | # llama.cpp comparison via llama-bench |
| 295 | # ───────────────────────────────────────────────────────────── |
| 296 | |
| 297 | def bench_llamacpp(model_path, prompt_len=512, n_gen=128): |
| 298 | """Run llama-bench and parse result. Returns dict or None.""" |
| 299 | import shutil |
| 300 | bench_bin = shutil.which("llama-bench") or "/tmp/llama.cpp/build/bin/llama-bench" |
| 301 | if not os.path.exists(bench_bin): |
| 302 | return None |
| 303 | |
| 304 | try: |
| 305 | result = subprocess.run( |
| 306 | [bench_bin, "-m", model_path, "-n", str(n_gen), |
| 307 | "-t", OMP_DEFAULT, "-p", str(prompt_len), |
| 308 | "-ngl", "0", "-r", "2"], |
| 309 | capture_output=True, text=True, timeout=600 |
| 310 | ) |
| 311 | except (FileNotFoundError, subprocess.TimeoutExpired): |
| 312 | return None |
| 313 | |
| 314 | output = result.stdout + result.stderr |
| 315 | for line in reversed(output.split("\n")): |
| 316 | line = line.strip() |
| 317 | if not line or "model" in line.lower() or "size" in line.lower() or "|" not in line: |
| 318 | continue |
| 319 | cols = [c.strip() for c in line.split("|")] |
| 320 | if len(cols) >= 9: |
| 321 | try: |
| 322 | pp_tok_s = float(cols[-3]) |
| 323 | tg_tok_s = float(cols[-1]) |
| 324 | return { |
| 325 | "pp_tok_s": round(pp_tok_s, 2), |
| 326 | "tg_tok_s": round(tg_tok_s, 2), |
| 327 | "pp_ms": round(1000.0 / pp_tok_s, 2) if pp_tok_s > 0 else 0, |
| 328 | "tg_ms": round(1000.0 / tg_tok_s, 2) if tg_tok_s > 0 else 0, |
| 329 | } |
| 330 | except (ValueError, IndexError): |
| 331 | pass |
| 332 | return None |
| 333 | |
| 334 | |
| 335 | # ───────────────────────────────────────────────────────────── |
| 336 | # Reporting |
| 337 | # ───────────────────────────────────────────────────────────── |
| 338 | |
| 339 | def _delta_str(curr, prev): |
| 340 | """Return formatted delta string like '+12.3%'.""" |
| 341 | if prev is None or prev == 0: |
| 342 | return "" |
| 343 | d = (curr / prev - 1) * 100 |
| 344 | return f"{d:+.1f}%" if abs(d) > 0.05 else "≈" |
| 345 | |
| 346 | def _bar(val, max_val, width=10): |
| 347 | """ASCII bar.""" |
| 348 | if max_val <= 0: return " " * width |
| 349 | n = int(val / max_val * width) |
| 350 | return "█" * min(n, width) |
| 351 | |
| 352 | def format_table(results_list, title="MojoLlama Benchmark"): |
| 353 | """Pretty-print results as a rich ASCII table. |
| 354 | |
| 355 | results_list: list of result dicts or list of (name, result) tuples. |
| 356 | """ |
| 357 | if not results_list: |
| 358 | print(" No results.") |
| 359 | return |
| 360 | |
| 361 | # Normalize to (name, result) tuples |
| 362 | if isinstance(results_list[0], dict) and 'threads' in results_list[0]: |
| 363 | items = [(f"{r['threads']}t", r) for r in results_list] |
| 364 | else: |
| 365 | items = results_list if isinstance(results_list[0], (list, tuple)) else \ |
| 366 | [(f"Model {i}", r) for i, r in enumerate(results_list)] |
| 367 | |
| 368 | name_w = max(len(n) for n, _ in items) + 1 |
| 369 | name_w = max(name_w, 14) |
| 370 | |
| 371 | print(f"\n {'='*70}") |
| 372 | print(f" {title}") |
| 373 | print(f" {'='*70}") |
| 374 | print(f" {'Name':>{name_w}s} {'tg tok/s':>10s} {'tg ms':>8s} {'p95 ms':>8s} {'pp tok/s':>10s} {'pp ms':>8s}") |
| 375 | print(f" {'─'*name_w} {'─'*10} {'─'*8} {'─'*8} {'─'*10} {'─'*8}") |
| 376 | |
| 377 | tg_max = max((r.get("tg_tok_s", 0) or 0) for _, r in items) |
| 378 | for name, r in items: |
| 379 | tg = r.get("tg_tok_s", 0) or 0 |
| 380 | tg_ms = r.get("tg_median_ms", r.get("tg_mean_ms", r.get("tg_ms", 0)) or 0) |
| 381 | p95 = r.get("tg_p95_ms", 0) or 0 |
| 382 | pp = r.get("pp_tok_s", 0) or 0 |
| 383 | pp_ms = r.get("pp_ms", 0) or 0 |
| 384 | bar = _bar(tg, tg_max) |
| 385 | print(f" {name:>{name_w}s} {tg:>10.1f} {tg_ms:>8.2f} {p95:>8.2f} {pp:>10.1f} {pp_ms:>8.2f} {bar}") |
| 386 | print(f" {'─'*70}\n") |
| 387 | |
| 388 | |
| 389 | def format_comparison(ml_result, lcpp_result, name="Model"): |
| 390 | """Print A/B comparison between MojoLlama and llama.cpp.""" |
| 391 | if not lcpp_result: |
| 392 | print(" [llama.cpp baseline: not available]") |
| 393 | return |
| 394 | |
| 395 | print(f"\n {'─'*60}") |
| 396 | print(f" A/B Comparison: MojoLlama vs llama.cpp") |
| 397 | print(f" {'─'*60}") |
| 398 | print(f" {'Engine':<24s} {'pp tok/s':>10s} {'tg tok/s':>10s} {'tg ms':>10s}") |
| 399 | print(f" {'─'*24} {'─'*10} {'─'*10} {'─'*10}") |
| 400 | |
| 401 | ml_tg = ml_result.get("tg_tok_s", 0) or 0 |
| 402 | lc_tg = lcpp_result.get("tg_tok_s", 0) or 0 |
| 403 | ml_pp = ml_result.get("pp_tok_s", 0) or 0 |
| 404 | lc_pp = lcpp_result.get("pp_tok_s", 0) or 0 |
| 405 | ml_tg_ms = ml_result.get("tg_median_ms", ml_result.get("tg_mean_ms", 0) or 0) |
| 406 | lc_tg_ms = lcpp_result.get("tg_ms", 0) or 0 |
| 407 | |
| 408 | print(f" {'MojoLlama':<24s} {ml_pp:>10.1f} {ml_tg:>10.1f} {ml_tg_ms:>10.2f}") |
| 409 | print(f" {'llama.cpp':<24s} {lc_pp:>10.1f} {lc_tg:>10.1f} {lc_tg_ms:>10.2f}") |
| 410 | |
| 411 | tg_delta = _delta_str(ml_tg, lc_tg) |
| 412 | pp_delta = _delta_str(ml_pp, lc_pp) |
| 413 | winner_tg = "MojoLlama ✅" if ml_tg > lc_tg * 1.02 else ("llama.cpp ❌" if ml_tg < lc_tg * 0.98 else "≈ tie") |
| 414 | winner_pp = "MojoLlama ✅" if ml_pp > lc_pp * 1.02 else ("llama.cpp ❌" if ml_pp < lc_pp * 0.98 else "≈ tie") |
| 415 | |
| 416 | print(f" {'─'*60}") |
| 417 | print(f" Delta (tg): {tg_delta:>8s} → {winner_tg}") |
| 418 | print(f" Delta (pp): {pp_delta:>8s} → {winner_pp}") |
| 419 | print(f" {'─'*60}\n") |
| 420 | |
| 421 | |
| 422 | def format_thread_sweep(results): |
| 423 | """Print thread sweep results as a compact table.""" |
| 424 | print(f"\n {'─'*50}") |
| 425 | print(f" Thread Sweep Results") |
| 426 | print(f" {'─'*50}") |
| 427 | print(f" {'Threads':>8s} {'pp tok/s':>10s} {'tg tok/s':>10s} {'tg ms':>8s} {'p95 ms':>8s}") |
| 428 | print(f" {'─'*8} {'─'*10} {'─'*10} {'─'*8} {'─'*8}") |
| 429 | for r in results: |
| 430 | t = r["threads"] |
| 431 | pp = r.get("pp_tok_s", 0) or 0 |
| 432 | tg = r.get("tg_tok_s", 0) or 0 |
| 433 | ms = r.get("tg_median_ms", r.get("tg_mean_ms", 0) or 0) |
| 434 | p95 = r.get("tg_p95_ms", 0) or 0 |
| 435 | print(f" {t:>8d} {pp:>10.1f} {tg:>10.1f} {ms:>8.2f} {p95:>8.2f}") |
| 436 | # Find sweet spot (best tg tok/s) |
| 437 | best = max(results, key=lambda r: r.get("tg_tok_s", 0) or 0) |
| 438 | print(f" {'─'*50}") |
| 439 | print(f" Sweet spot: {best['threads']}t → {best['tg_tok_s']:.1f} tg tok/s") |
| 440 | print(f" {'─'*50}\n") |
| 441 | |
| 442 | |
| 443 | # ───────────────────────────────────────────────────────────── |
| 444 | # System info |
| 445 | # ───────────────────────────────────────────────────────────── |
| 446 | |
| 447 | def get_system_info(): |
| 448 | """Collect system information for benchmark context.""" |
| 449 | info = {} |
| 450 | try: |
| 451 | info["cpu"] = os.popen("grep 'model name' /proc/cpuinfo | head -1").read().strip().replace("model name\t: ", "") |
| 452 | info["cores"] = os.cpu_count() or 0 |
| 453 | try: |
| 454 | info["physical_cores"] = int(os.popen("grep 'cpu cores' /proc/cpuinfo | head -1").read().strip().split()[-1]) |
| 455 | except Exception: |
| 456 | info["physical_cores"] = info["cores"] // 2 |
| 457 | try: |
| 458 | with open("/proc/meminfo") as f: |
| 459 | for line in f: |
| 460 | if "MemTotal" in line: |
| 461 | kb = int(line.split()[1]) |
| 462 | info["ram_gb"] = round(kb / 1024 / 1024, 1) |
| 463 | break |
| 464 | except Exception: |
| 465 | info["ram_gb"] = 0 |
| 466 | except Exception: |
| 467 | info["cpu"] = "unknown" |
| 468 | info["cores"] = 0 |
| 469 | info["ram_gb"] = 0 |
| 470 | return info |
| 471 | |
| 472 | |
| 473 | # ───────────────────────────────────────────────────────────── |
| 474 | # JSON save/load for historical comparison |
| 475 | # ───────────────────────────────────────────────────────────── |
| 476 | |
| 477 | def save_results(results, path): |
| 478 | """Save benchmark results to JSON.""" |
| 479 | data = { |
| 480 | "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), |
| 481 | "system": get_system_info(), |
| 482 | "results": results, |
| 483 | } |
| 484 | with open(path, "w") as f: |
| 485 | json.dump(data, f, indent=2) |
| 486 | print(f"\n Results saved to {path}") |
| 487 | |
| 488 | |
| 489 | def load_results(path): |
| 490 | """Load benchmark results from JSON.""" |
| 491 | with open(path) as f: |
| 492 | return json.load(f) |
| 493 | |
| 494 | |
| 495 | def compare_historical(paths): |
| 496 | """Compare results from multiple saved benchmark runs.""" |
| 497 | datasets = [] |
| 498 | for p in paths: |
| 499 | data = load_results(p) |
| 500 | ts = data.get("timestamp", "unknown") |
| 501 | results = data.get("results", []) |
| 502 | datasets.append((ts, results, p)) |
| 503 | return datasets |
| 504 | |
| 505 | |
| 506 | # ───────────────────────────────────────────────────────────── |
| 507 | # CLI main |
| 508 | # ───────────────────────────────────────────────────────────── |
| 509 | |
| 510 | def main(): |
| 511 | parser = argparse.ArgumentParser( |
| 512 | description="MojoLlama Bench — comprehensive LLM benchmark (better than llama-bench)", |
| 513 | formatter_class=argparse.RawDescriptionHelpFormatter, |
| 514 | epilog=""" |
| 515 | Features: |
| 516 | Thread sweep: -m model.gguf -t 1,2,4,8,16,32 |
| 517 | Multi-model: -m m1.gguf,m2.gguf |
| 518 | Profile mode: --profile |
| 519 | A/B compare: --compare |
| 520 | JSON output: --json |
| 521 | Save results: --save results.json |
| 522 | Historical: --load prev.json --load curr.json |
| 523 | |
| 524 | Examples: |
| 525 | mojollama bench -m model.gguf -t 16,24,32 |
| 526 | mojollama bench -m m1.gguf,m2.gguf --compare |
| 527 | mojollama bench -m model.gguf --profile |
| 528 | mojollama bench --load a.json --load b.json |
| 529 | """) |
| 530 | # Model + benchmark params |
| 531 | parser.add_argument("-m", "--model", type=str, |
| 532 | help="Model path(s) — comma-separated for multi-model") |
| 533 | parser.add_argument("-t", "--threads", type=str, default=OMP_DEFAULT, |
| 534 | help="Thread count(s) — comma-separated for sweep (default: 32)") |
| 535 | parser.add_argument("--prompt-len", type=int, default=512, |
| 536 | help="Prompt length in tokens (default: 512)") |
| 537 | parser.add_argument("--gen-len", type=int, default=128, |
| 538 | help="Generation length in tokens (default: 128)") |
| 539 | parser.add_argument("--warmup", type=int, default=5, |
| 540 | help="Warmup tokens (default: 5)") |
| 541 | parser.add_argument("--measured", type=int, default=30, |
| 542 | help="Measured tokens (default: 30)") |
| 543 | |
| 544 | # Output modes |
| 545 | parser.add_argument("--output", type=str, choices=["table", "json"], default="table", |
| 546 | help="Output format (default: table)") |
| 547 | parser.add_argument("--save", type=str, help="Save results to JSON file") |
| 548 | parser.add_argument("--load", type=str, action="append", dest="load_paths", |
| 549 | help="Load previous results for comparison (can be used multiple times)") |
| 550 | |
| 551 | # Comparison modes |
| 552 | parser.add_argument("--compare", action="store_true", |
| 553 | help="A/B comparison with llama.cpp") |
| 554 | parser.add_argument("--profile", action="store_true", |
| 555 | help="Component-level profiling") |
| 556 | parser.add_argument("--concurrent", type=str, |
| 557 | help="Concurrency benchmark: comma-separated levels, e.g. '1,2,4,8,16'") |
| 558 | parser.add_argument("--concurrent-quick", action="store_true", |
| 559 | help="Quick concurrency test (levels 1,4,8)") |
| 560 | |
| 561 | args = parser.parse_args() |
| 562 | os.environ["OMP_NUM_THREADS"] = OMP_DEFAULT |
| 563 | |
| 564 | # ── Historical comparison mode ── |
| 565 | if args.load_paths: |
| 566 | datasets = compare_historical(args.load_paths) |
| 567 | print(f"\n Historical Comparison ({len(datasets)} runs)") |
| 568 | for ts, results, path in datasets: |
| 569 | print(f"\n [{ts}] {path}") |
| 570 | if results: |
| 571 | format_table(results if isinstance(results, list) else list(results.values()), |
| 572 | title=f"Run from {ts}") |
| 573 | return |
| 574 | |
| 575 | # ── Profile mode ── |
| 576 | if args.profile: |
| 577 | if not args.model: |
| 578 | print("ERROR: --model required for profiling") |
| 579 | sys.exit(1) |
| 580 | models = [m.strip() for m in args.model.split(",")] |
| 581 | for mp in models: |
| 582 | print(f"\n Profiling: {Path(mp).stem}") |
| 583 | prof = profile_model(mp, threads=int(OMP_DEFAULT)) |
| 584 | print(f" Engine type: {prof['engine_type']}") |
| 585 | return |
| 586 | |
| 587 | if not args.model: |
| 588 | parser.print_help() |
| 589 | sys.exit(1) |
| 590 | |
| 591 | # Parse params |
| 592 | models = [m.strip() for m in args.model.split(",")] |
| 593 | thread_str = args.threads |
| 594 | thread_list = sorted(set( |
| 595 | int(t) for t in thread_str.split(",") if t.strip().isdigit() |
| 596 | )) |
| 597 | prompt_len = args.prompt_len |
| 598 | gen_len = args.gen_len |
| 599 | n_warmup = args.warmup |
| 600 | n_measured = args.measured |
| 601 | |
| 602 | sys_info = get_system_info() |
| 603 | print(f"\n System: {sys_info.get('cpu', '?')} " |
| 604 | f"({sys_info.get('physical_cores', '?')}C/{sys_info.get('cores', '?')}t) " |
| 605 | f"RAM: {sys_info.get('ram_gb', '?')} GB") |
| 606 | |
| 607 | # ── Concurrency benchmark ── |
| 608 | if args.concurrent or args.concurrent_quick: |
| 609 | if not args.model: |
| 610 | print("ERROR: --model required for concurrency benchmark") |
| 611 | sys.exit(1) |
| 612 | mp = models[0] |
| 613 | name = Path(mp).stem |
| 614 | levels = None |
| 615 | if args.concurrent: |
| 616 | levels = [int(x.strip()) for x in args.concurrent.split(",")] |
| 617 | print(f"\n Concurrency Benchmark: {name}") |
| 618 | print(f" Levels: {levels or '1,4,8 (quick)' if args.concurrent_quick else levels or '1,2,4,8,16'}") |
| 619 | print() |
| 620 | results = bench_concurrency(mp, levels=levels, quick=args.concurrent_quick) |
| 621 | |
| 622 | if args.output == "table" and results: |
| 623 | print(f"\n {'─'*55}") |
| 624 | print(f" {'Concurrency':>12s} {'Agg tok/s':>10s} {'Per-req':>8s} {'p50 ms':>8s} {'p95 ms':>8s}") |
| 625 | print(f" {'─'*12} {'─'*10} {'─'*8} {'─'*8} {'─'*8}") |
| 626 | for r in results: |
| 627 | bar = "█" * min(r["concurrency"], 16) |
| 628 | print(f" {r['concurrency']:>12d} {r['aggregate_tok_s']:>10.1f} " |
| 629 | f"{r['avg_per_request']:>8.1f} {r['p50_ms']:>8.1f} {r['p95_ms']:>8.1f} {bar}") |
| 630 | # Find peak throughput |
| 631 | best = max(results, key=lambda r: r["aggregate_tok_s"]) |
| 632 | print(f" {'─'*55}") |
| 633 | print(f" Peak throughput: {best['aggregate_tok_s']:.1f} tok/s at concurrency={best['concurrency']}") |
| 634 | print(f" {'─'*55}\n") |
| 635 | elif args.output == "json" and results: |
| 636 | print(json.dumps({"system": sys_info, "model": name, |
| 637 | "concurrency": results}, indent=2)) |
| 638 | if args.save: |
| 639 | save_results(results, args.save) |
| 640 | return |
| 641 | |
| 642 | # ── Single model benchmark ── |
| 643 | if len(models) == 1: |
| 644 | mp = models[0] |
| 645 | name = Path(mp).stem |
| 646 | print(f" Model: {name}") |
| 647 | print(f" Threads: {', '.join(str(t) for t in thread_list)}") |
| 648 | print(f" Prompt: {prompt_len} tok Generate: {gen_len} tok") |
| 649 | print(f" Warmup: {n_warmup} Measured: {n_measured}") |
| 650 | print() |
| 651 | |
| 652 | if len(thread_list) == 1: |
| 653 | # Single thread count |
| 654 | t = thread_list[0] |
| 655 | print(f" Benchmarking at {t}t...") |
| 656 | r = bench_model_at_threads(mp, t, prompt_len, gen_len, n_warmup, n_measured) |
| 657 | print(f" pp={r['pp_tok_s']:.1f} tok/s tg={r['tg_tok_s']:.1f} tok/s " |
| 658 | f"tg_median={r['tg_median_ms']:.2f}ms p95={r['tg_p95_ms']:.2f}ms") |
| 659 | |
| 660 | results_list = [r] |
| 661 | |
| 662 | # A/B comparison |
| 663 | lcpp = None |
| 664 | if args.compare: |
| 665 | print(" llama.cpp baseline...") |
| 666 | lcpp = bench_llamacpp(mp, prompt_len, gen_len) |
| 667 | if lcpp: |
| 668 | print(f" pp={lcpp['pp_tok_s']:.1f} tok/s tg={lcpp['tg_tok_s']:.1f} tok/s") |
| 669 | |
| 670 | if args.output == "table": |
| 671 | format_table(results_list) |
| 672 | if args.compare: |
| 673 | format_comparison(r, lcpp, name) |
| 674 | elif args.output == "json": |
| 675 | out = { |
| 676 | "system": sys_info, |
| 677 | "model": name, |
| 678 | "mojollama": r, |
| 679 | "llamacpp": lcpp, |
| 680 | } |
| 681 | if args.compare and lcpp: |
| 682 | out["delta_tg_pct"] = round((r["tg_tok_s"] / lcpp["tg_tok_s"] - 1) * 100, 1) |
| 683 | print(json.dumps(out, indent=2)) |
| 684 | |
| 685 | else: |
| 686 | # Thread sweep |
| 687 | print(f" Thread sweep: {len(thread_list)} configurations...") |
| 688 | results_list = bench_thread_sweep(mp, thread_list, prompt_len, gen_len) |
| 689 | if args.output == "table": |
| 690 | format_thread_sweep(results_list) |
| 691 | elif args.output == "json": |
| 692 | print(json.dumps({"system": sys_info, "model": name, |
| 693 | "thread_sweep": results_list}, indent=2)) |
| 694 | |
| 695 | if args.save: |
| 696 | save_results(results_list, args.save) |
| 697 | |
| 698 | # ── Multi-model comparison ── |
| 699 | else: |
| 700 | print(f" Models ({len(models)}): {', '.join(Path(m).stem for m in models)}") |
| 701 | print(f" Threads: {thread_list[0] if len(thread_list)==1 else thread_list}") |
| 702 | print() |
| 703 | t = thread_list[0] if len(thread_list) == 1 else int(OMP_DEFAULT) |
| 704 | results = {} |
| 705 | for mp in models: |
| 706 | name = Path(mp).stem |
| 707 | print(f" Benchmarking {name}...") |
| 708 | r = bench_model_at_threads(mp, t, prompt_len, gen_len, n_warmup, n_measured) |
| 709 | results[name] = r |
| 710 | print(f" tg={r['tg_tok_s']:.1f} tok/s tg_median={r['tg_median_ms']:.2f}ms") |
| 711 | |
| 712 | if args.output == "table": |
| 713 | format_table(list(results.items()), title="Multi-Model Comparison") |
| 714 | elif args.output == "json": |
| 715 | print(json.dumps({"system": sys_info, "models": results}, indent=2)) |
| 716 | |
| 717 | if args.save: |
| 718 | save_results(results, args.save) |
| 719 | |
| 720 | |
| 721 | if __name__ == "__main__": |
| 722 | main() |