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 / autotune.py

747 lines · 30754 bytes Raw Blame History
1#!/usr/bin/env python3
2"""MojoLlama AutoTuner — finds optimal llama.cpp settings for the current hardware.
3
4Sweeps thread counts, batch sizes, parallel slots, flash attention,
5and mlock using llama-bench. Saves best config to ~/.mojollama/config.json.
6
7Tuned specifically for AMD Threadripper 3970X (32c/64t, AVX2+FMA):
8 - Physical-core-only thread count (SMT hurts gen ~25%)
9 - CPU affinity mask to pin to physical cores
10 - Flash attention ON by default (+40% pp, +5% tg)
11 - Batch=4096 ubatch=1024 baseline
12
13Usage:
14 python3 autotune.py --model /path/to/model.gguf
15 python3 autotune.py --model /tmp/tl-Q4_0.gguf --quick (faster sweep)
16"""
17
18import os
19import sys
20import json
21import time
22import re
23import subprocess
24import argparse
25import multiprocessing as mp
26import numpy as np
27from pathlib import Path
28
29CONFIG_DIR = Path.home() / ".mojollama"
30CONFIG_PATH = CONFIG_DIR / "config.json"
31BENCH_BIN = None # resolved at runtime via shutil.which()
32
33def _find_bench():
34 """Locate llama-bench: check PATH, then build tree, then common locations."""
35 global BENCH_BIN
36 if BENCH_BIN is not None:
37 return BENCH_BIN
38 import shutil
39 candidates = [
40 shutil.which("llama-bench"),
41 "/tmp/llama.cpp/build/bin/llama-bench",
42 "/usr/local/bin/llama-bench",
43 "llama-bench",
44 ]
45 for c in candidates:
46 if c and os.path.exists(c) and os.access(c, os.X_OK):
47 BENCH_BIN = c
48 return BENCH_BIN
49 return None
50
51
52def detect_cpu():
53 """Detect CPU info for display and CPU mask generation."""
54 info = {"cores": mp.cpu_count(), "name": "unknown", "physical_cores": mp.cpu_count()}
55 try:
56 core_ids = set()
57 n = mp.cpu_count() or 64
58 for i in range(n):
59 try:
60 with open(f"/sys/devices/system/cpu/cpu{i}/topology/core_id") as f:
61 core_ids.add(int(f.read().strip()))
62 except FileNotFoundError:
63 break
64 if core_ids:
65 info["physical_cores"] = len(core_ids)
66 except Exception:
67 pass
68 try:
69 with open("/proc/cpuinfo") as f:
70 for line in f:
71 if line.startswith("model name"):
72 info["name"] = line.split(":")[1].strip()
73 break
74 except Exception:
75 pass
76 return info
77
78
79def compute_cpu_mask(physical_cores):
80 """Compute CPU affinity hex mask for physical cores only.
81
82 On Threadripper 3970X: 32 physical cores → mask 0x00000000FFFFFFFF
83 This avoids SMT siblings which hurt generation throughput by ~25%.
84 """
85 if physical_cores <= 0:
86 return ""
87 mask = (1 << physical_cores) - 1
88 return f"0x{mask:016X}"
89
90
91def run_bench(model, threads, threads_batch, batch_size, ubatch_size,
92 n_parallel, mlock, flash_attn=False, n_prompt=512, n_gen=128,
93 cpu_mask=""):
94 """Run a single llama-bench test and return results."""
95 cmd = [
96 _find_bench(), "-m", str(model),
97 "-p", str(n_prompt), "-n", str(n_gen),
98 "-t", str(threads), "-b", str(batch_size), "-ub", str(ubatch_size),
99 "-r", "1", # single rep for speed during sweep
100 ]
101 if mlock:
102 cmd.append("--mlock")
103 if flash_attn:
104 cmd.extend(["-fa", "1"])
105 if cpu_mask and cpu_mask != "0x0":
106 cmd.extend(["-C", cpu_mask])
107
108 try:
109 result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
110 output = result.stdout + result.stderr
111 except subprocess.TimeoutExpired:
112 return None
113 except FileNotFoundError:
114 b = _find_bench()
115 if b is None:
116 print(f" ❌ llama-bench not found in PATH or build tree")
117 else:
118 print(f" ❌ llama-bench not found at {b}")
119 return None
120
121 # Parse results from markdown table
122 pp_speed = None
123 tg_speed = None
124 for line in output.split("\n"):
125 if "|" in line and ("pp" in line or "tg" in line):
126 parts = [p.strip() for p in line.split("|")]
127 last_col = parts[-2].strip() if len(parts) > 2 else ""
128 m = re.match(r"^([\d.]+)", last_col)
129 if m:
130 val = float(m.group(1))
131 if "pp" in line:
132 pp_speed = val
133 elif "tg" in line:
134 tg_speed = val
135
136 if pp_speed is None and tg_speed is None:
137 return None
138
139 return {
140 "threads": threads,
141 "batch": batch_size,
142 "ubatch": ubatch_size,
143 "n_parallel": n_parallel,
144 "mlock": mlock,
145 "flash_attn": flash_attn,
146 "pp_tok_s": pp_speed or 0,
147 "tg_tok_s": tg_speed or 0,
148 }
149
150
151# ═══════════════════════════════════════════════════════════════════════
152# Phase 6 — MojoLlama engine benchmark (all archs: MoE, dense, Gemma4)
153# ═══════════════════════════════════════════════════════════════════════
154
155def _detect_engine_type(model_path):
156 """Detect which MojoLlama engine class to use for a model."""
157 try:
158 import gguf
159 r = gguf.GGUFReader(model_path)
160 arch = str(r.fields.get("general.architecture", gguf.GGUFValue(b"unknown")).parts[-1]).strip().lower()
161 if any(x in arch for x in ["moe", "gpt-oss", "deepseek"]):
162 return "moe"
163 if "gemma4" in arch:
164 return "gemma4"
165 if "zaya" in arch:
166 return "zaya"
167 return "dense"
168 except Exception:
169 return "dense"
170
171
172def _load_engine(model_path, threads):
173 """Load the appropriate MojoLlama engine for the given model.
174 Returns (engine, engine_type) or raises."""
175 _md = os.path.dirname(os.path.abspath(__file__))
176 _bd = os.path.dirname(_md)
177 if _bd not in sys.path:
178 sys.path.insert(0, _bd)
179 os.environ["OMP_NUM_THREADS"] = str(threads)
180
181 engine_type = _detect_engine_type(model_path)
182
183 if engine_type in ("moe", "gemma4"):
184 from mojollama.kernels.turbo_engine_v7_moe import TurboEngineV7MoE
185 eng = TurboEngineV7MoE(model_path, n_threads=threads)
186 else:
187 from mojollama.kernels.turbo_engine_v77 import TurboEngineV77
188 eng = TurboEngineV77(model_path, n_threads=threads)
189
190 return eng, engine_type
191
192
193def bench_mojollama(model_path, threads, quick=False):
194 """Benchmark MojoLlama native engine with pp512 + tg128 measurement.
195
196 Sweeps thread counts (if threads is a list) and batch sizes.
197 Returns list of {threads, pp_tok_s, tg_tok_s, ms_per_tok} dicts.
198 """
199 try:
200 engine, etype = _load_engine(model_path, threads if isinstance(threads, int) else threads[0])
201 except Exception as exc:
202 print(f" ⚠ Engine load failed: {exc}")
203 return []
204
205 V = int(engine.vocab_size)
206 N_WARMUP = 5
207 N_MEASURED = 20
208 results = []
209
210 # Handle single thread or list
211 thread_list = [threads] if isinstance(threads, int) else threads
212
213 for nt in thread_list:
214 # Re-load engine for each thread count (OMP_NUM_THREADS must match)
215 if nt != thread_list[0]:
216 try:
217 engine, etype = _load_engine(model_path, nt)
218 except Exception as exc:
219 print(f" ⚠ Reload @{nt}t failed: {exc}")
220 continue
221
222 engine.reset()
223
224 # ── pp512: prompt processing ──
225 prompt_len = 512
226 prompt_tokens = [i % max(V, 1) for i in range(prompt_len)]
227 t0 = time.perf_counter()
228 for tok in prompt_tokens:
229 engine.forward([tok])
230 pp_elapsed = time.perf_counter() - t0
231 pp_tok_s = prompt_len / pp_elapsed
232
233 # ── tg128: token generation ──
234 token = prompt_tokens[-1]
235 # Warmup
236 for _ in range(N_WARMUP):
237 logits = engine.forward([token])
238 a = np.asarray(logits).ravel()
239 token = int(np.argmax(a)) % max(V, 1)
240 # Measured
241 t0 = time.perf_counter()
242 for _ in range(N_MEASURED):
243 logits = engine.forward([token])
244 a = np.asarray(logits).ravel()
245 token = int(np.argmax(a)) % max(V, 1)
246 tg_elapsed = time.perf_counter() - t0
247 tg_tok_s = N_MEASURED / tg_elapsed
248 tg_ms = tg_elapsed / N_MEASURED * 1000
249
250 results.append({
251 "threads": nt,
252 "pp_tok_s": round(pp_tok_s, 1),
253 "tg_tok_s": round(tg_tok_s, 1),
254 "ms_per_tok": round(tg_ms, 2),
255 "engine_type": etype,
256 })
257 print(f" {nt:3d}t → pp={pp_tok_s:.1f} tg={tg_tok_s:.1f} tok/s ({tg_ms:.1f} ms/tok)")
258
259 return results
260
261
262# ═══════════════════════════════════════════════════════════════════════
263# Phase 7 — Concurrency tuning (no server needed)
264# ═══════════════════════════════════════════════════════════════════════
265
266def bench_concurrency(model_path, quick=False):
267 """Benchmark concurrent throughput using direct engine forward() calls.
268
269 No HTTP server required. Sweeps concurrency=1,2,4,8 (or 1,4 quick).
270 Measures aggregate tok/s by spawning N concurrent forward() loops
271 via threading (GIL-released OMP matmuls run in parallel).
272 Returns dict with optimal_concurrency, max_throughput, latency.
273 """
274 try:
275 engine, etype = _load_engine(model_path, int(os.environ.get("OMP_NUM_THREADS", "8")))
276 except Exception as exc:
277 print(f" ⚠ Engine load failed for concurrency test: {exc}")
278 return None
279
280 V = int(engine.vocab_size)
281 import threading
282 from concurrent.futures import ThreadPoolExecutor
283
284 levels = [1, 2, 4, 8, 16] if not quick else [1, 4, 8]
285 n_gen = 20 # tokens per request
286 n_reqs = 3 # requests per level
287
288 def _request(engine_ref, tid):
289 """Run a short generation sequence, return tok/s."""
290 try:
291 token = int(tid) % max(V, 1)
292 t0 = time.perf_counter()
293 for _ in range(n_gen):
294 logits = engine_ref.forward([token])
295 a = np.asarray(logits).ravel()
296 token = int(np.argmax(a)) % max(V, 1)
297 elapsed = time.perf_counter() - t0
298 return n_gen / elapsed if elapsed > 0 else 0
299 except Exception:
300 return 0
301
302 results_data = []
303 for concurrency in levels:
304 t0 = time.perf_counter()
305 with ThreadPoolExecutor(max_workers=concurrency) as pool:
306 tok_s_list = list(pool.map(lambda x: _request(engine, x), range(n_reqs * concurrency)))
307 total_elapsed = time.perf_counter() - t0
308
309 valid = [t for t in tok_s_list if t > 0]
310 if not valid:
311 continue
312 avg_tok_s = sum(valid) / len(valid)
313 agg_tok_s = sum(valid)
314 latencies = [n_gen / t * 1000 for t in valid] # ms per request
315 lat_sorted = sorted(latencies)
316 p50 = lat_sorted[len(lat_sorted)//2]
317 p95 = lat_sorted[int(len(lat_sorted)*0.95)]
318
319 results_data.append({
320 "concurrency": concurrency,
321 "throughput": round(agg_tok_s, 1),
322 "avg_per_request": round(avg_tok_s, 1),
323 "p50_latency_ms": round(p50, 1),
324 "p95_latency_ms": round(p95, 1),
325 "total_time_s": round(total_elapsed, 2),
326 })
327 print(f" concurrency={concurrency:3d} → {agg_tok_s:.1f} agg tok/s p50={p50:.0f}ms p95={p95:.0f}ms")
328
329 if not results_data:
330 return None
331
332 # Find throughput plateau: first level where next step gives <10% improvement
333 plateau = results_data[-1]["concurrency"]
334 for i in range(1, len(results_data)):
335 prev_tp = results_data[i-1]["throughput"]
336 curr_tp = results_data[i]["throughput"]
337 if prev_tp > 0 and curr_tp / prev_tp < 1.10:
338 plateau = results_data[i-1]["concurrency"]
339 break
340
341 # Find latency knee: first level where p95 > 2x base p95
342 base_p95 = results_data[0]["p95_latency_ms"]
343 latency_knee = None
344 for rd in results_data[1:]:
345 if base_p95 > 0 and rd["p95_latency_ms"] > 2.0 * base_p95:
346 latency_knee = rd["concurrency"]
347 break
348
349 optimal = min(plateau, latency_knee) if latency_knee else plateau
350 best_throughput = max(rd["throughput"] for rd in results_data)
351
352 print(f"\n → Throughput plateau at concurrency={plateau}"
353 f"{' (latency knee at {latency_knee})' if latency_knee else ''}")
354 print(f" → Optimal concurrency: {optimal} (peak {best_throughput:.0f} tok/s)")
355
356 return {
357 "optimal_concurrency": optimal,
358 "throughput_plateau": plateau,
359 "latency_knee": latency_knee,
360 "max_throughput": round(best_throughput, 1),
361 "p50_latency_ms": results_data[0]["p50_latency_ms"],
362 }
363
364
365def autotune(model, quick=False, mojollama=False):
366 """Sweep configurations and find optimal settings."""
367 cpu = detect_cpu()
368 n_cores = cpu["cores"]
369 physical = cpu["physical_cores"]
370 cpu_mask = compute_cpu_mask(physical)
371 print(f"CPU: {cpu['name']} ({physical} physical, {n_cores} logical)")
372 print(f"CPU mask: {cpu_mask}")
373 print(f"Model: {model}")
374 print()
375
376 if not os.path.exists(model):
377 print(f"❌ Model not found: {model}")
378 return None
379
380 if _find_bench() is None:
381 if mojollama:
382 print("⚠ llama-bench not found — Phases 1-5 (llama.cpp tuning) will be skipped")
383 else:
384 print("❌ llama-bench not found — install llama.cpp or use --mojollama")
385 return None
386
387 skip_bench = mojollama and _find_bench() is None
388
389 # Defaults used when llama-bench phases are skipped
390 optimal_threads = physical
391 results = []
392 results_batch = []
393 results_par = []
394 r_fa_on = r_fa_off = None
395 fa_better = True
396 mlock_better = True
397 best_batch = None
398 best_par = None
399
400 # ─── Phase 1: Thread count sweep ───
401 if not skip_bench:
402 print("Phase 1: Sweeping thread counts (physical cores only)...")
403 # On Threadripper: physical cores = sweet spot, SMT hurts generation
404 thread_configs = [physical//2, physical, physical+4, n_cores] if not quick else [physical]
405 thread_configs = sorted(set(t for t in thread_configs if 1 <= t <= n_cores))
406
407 results = []
408 for t in thread_configs:
409 r = run_bench(model, threads=t, threads_batch=min(t, physical),
410 batch_size=4096, ubatch_size=1024,
411 n_parallel=4, mlock=True, flash_attn=True,
412 cpu_mask=cpu_mask)
413 if r:
414 results.append(r)
415 print(f" {t:3d} threads → pp={r['pp_tok_s']:.0f} tg={r['tg_tok_s']:.0f} tok/s")
416 else:
417 print(f" {t:3d} threads → FAILED")
418
419 if not results:
420 if not mojollama:
421 print("❌ All thread tests failed")
422 return None
423 print("⚠ All thread tests failed — using defaults, running MojoLlama phases")
424
425 if results:
426 best_all = max(results, key=lambda r: r["tg_tok_s"] + r["pp_tok_s"])
427 optimal_threads = best_all["threads"]
428 print(f"\n Best overall threads: {optimal_threads} (combined {best_all['tg_tok_s']+best_all['pp_tok_s']:.0f} tok/s)")
429
430 # ─── Phase 2: Batch size sweep ───
431 print(f"\nPhase 2: Sweeping batch sizes (threads={optimal_threads})...")
432 batch_configs = [1024, 2048, 4096, 8192] if not quick else [2048, 4096]
433
434 results_batch = []
435 for b in batch_configs:
436 ub = max(256, b // 4)
437 r = run_bench(model, threads=optimal_threads, threads_batch=min(optimal_threads, physical),
438 batch_size=b, ubatch_size=ub,
439 n_parallel=4, mlock=True, flash_attn=True,
440 cpu_mask=cpu_mask)
441 if r:
442 results_batch.append(r)
443 print(f" batch={b:5d} ub={ub:5d} → pp={r['pp_tok_s']:.0f} tg={r['tg_tok_s']:.0f} tok/s")
444
445 best_batch = max(results_batch, key=lambda r: r["tg_tok_s"] + r["pp_tok_s"]) if results_batch else None
446
447 # ─── Phase 3: Flash attention comparison ───
448 print(f"\nPhase 3: Flash attention comparison...")
449 base_args = dict(
450 model=model, threads=optimal_threads, threads_batch=min(optimal_threads, physical),
451 batch_size=best_batch["batch"] if best_batch else 4096,
452 ubatch_size=best_batch["ubatch"] if best_batch else 1024,
453 n_parallel=4, mlock=True, cpu_mask=cpu_mask,
454 )
455 r_fa_on = run_bench(flash_attn=True, **base_args)
456 r_fa_off = run_bench(flash_attn=False, **base_args)
457 fa_better = True
458 if r_fa_on and r_fa_off:
459 fa_better = r_fa_on["tg_tok_s"] + r_fa_on["pp_tok_s"] >= r_fa_off["tg_tok_s"] + r_fa_off["pp_tok_s"]
460 print(f" flash-attn ON: pp={r_fa_on['pp_tok_s']:.0f} tg={r_fa_on['tg_tok_s']:.0f}")
461 print(f" flash-attn OFF: pp={r_fa_off['pp_tok_s']:.0f} tg={r_fa_off['tg_tok_s']:.0f}")
462 delta_pp = ((r_fa_on['pp_tok_s'] / r_fa_off['pp_tok_s']) - 1) * 100 if r_fa_off['pp_tok_s'] > 0 else 0
463 delta_tg = ((r_fa_on['tg_tok_s'] / r_fa_off['tg_tok_s']) - 1) * 100 if r_fa_off['tg_tok_s'] > 0 else 0
464 print(f" → flash-attn {'ON' if fa_better else 'OFF'} wins (pp {delta_pp:+.0f}%, tg {delta_tg:+.0f}%)")
465 elif r_fa_on:
466 print(f" flash-attn ON: pp={r_fa_on['pp_tok_s']:.0f} tg={r_fa_on['tg_tok_s']:.0f} (OFF test failed)")
467
468 # ─── Phase 4: Parallel slots ───
469 print(f"\nPhase 4: Sweeping parallel slots (threads={optimal_threads})...")
470 parallel_configs = [1, 2, 4, 8] if not quick else [4]
471 parallel_configs = [p for p in parallel_configs if p <= max(4, physical // 4)]
472
473 results_par = []
474 for np_val in parallel_configs:
475 r = run_bench(model, threads=optimal_threads, threads_batch=min(optimal_threads, physical),
476 batch_size=best_batch["batch"] if best_batch else 4096,
477 ubatch_size=best_batch["ubatch"] if best_batch else 1024,
478 n_parallel=np_val, mlock=True, flash_attn=fa_better,
479 cpu_mask=cpu_mask)
480 if r:
481 results_par.append(r)
482 print(f" np={np_val:2d} → pp={r['pp_tok_s']:.0f} tg={r['tg_tok_s']:.0f} tok/s")
483
484 best_par = max(results_par, key=lambda r: r["tg_tok_s"] + r["pp_tok_s"]) if results_par else None
485
486 # ─── Phase 5: mlock comparison ───
487 print(f"\nPhase 5: mlock comparison...")
488 r_lock = run_bench(model, threads=optimal_threads, threads_batch=min(optimal_threads, physical),
489 batch_size=best_batch["batch"] if best_batch else 4096,
490 ubatch_size=best_batch["ubatch"] if best_batch else 1024,
491 n_parallel=best_par["n_parallel"] if best_par else 4,
492 mlock=True, flash_attn=fa_better, cpu_mask=cpu_mask)
493 r_nolock = run_bench(model, threads=optimal_threads, threads_batch=min(optimal_threads, physical),
494 batch_size=best_batch["batch"] if best_batch else 4096,
495 ubatch_size=best_batch["ubatch"] if best_batch else 1024,
496 n_parallel=best_par["n_parallel"] if best_par else 4,
497 mlock=False, flash_attn=fa_better, cpu_mask=cpu_mask)
498 mlock_better = True
499 if r_lock and r_nolock:
500 mlock_better = r_lock["tg_tok_s"] >= r_nolock["tg_tok_s"]
501 print(f" mlock: {r_lock['tg_tok_s']:.0f} tok/s (pp={r_lock['pp_tok_s']:.0f})")
502 print(f" no-mlock: {r_nolock['tg_tok_s']:.0f} tok/s (pp={r_nolock['pp_tok_s']:.0f})")
503 print(f" -> {'mlock ON' if mlock_better else 'mlock OFF'} wins")
504
505 # --- Phase 6: MojoLlama engine benchmark sweep ---
506 # Shared default values (used when --mojollama is not requested)
507 optimal_moe_threads = 32
508 best_moe_batch = 1
509 best_moe_tok_s = 0
510 optimal_moe_concurrency = 4
511 latency_p50_ms = 0
512
513 if mojollama:
514 print(f"\n{'='*50}")
515 print("Phase 6: MojoLlama native engine benchmark (all archs)")
516 print(f"{'='*50}")
517 moe_thread_configs = [int(physical*0.5), int(physical*0.75), physical] if not quick else [physical]
518 moe_thread_configs = sorted(set(t for t in moe_thread_configs if t >= 1))
519 all_moe_results = []
520 print(f" Thread sweep: {moe_thread_configs}")
521 r = bench_mojollama(model, moe_thread_configs, quick=quick)
522 all_moe_results.extend(r)
523
524 if all_moe_results:
525 best_moe_tg = max(all_moe_results, key=lambda x: x["tg_tok_s"])
526 best_moe_combined = max(all_moe_results, key=lambda x: x["tg_tok_s"] + x.get("pp_tok_s", 0))
527 optimal_moe_threads = best_moe_tg["threads"]
528 best_moe_tok_s = best_moe_tg["tg_tok_s"]
529 print(f"\n Best MojoLlama engine (tg): {best_moe_tg['threads']}t → {best_moe_tg['tg_tok_s']:.1f} tok/s"
530 f" pp={best_moe_tg.get('pp_tok_s', 0):.1f} tok/s")
531 print(f" Best combined: {best_moe_combined['threads']}t → "
532 f"tg={best_moe_combined['tg_tok_s']:.1f} pp={best_moe_combined.get('pp_tok_s', 0):.1f}")
533 else:
534 print(f"\n MojoLlama engine benchmark skipped -- no results")
535
536 # --- Phase 7: Concurrency tuning (direct, no server) ---
537 print(f"\n{'='*50}")
538 print("Phase 7: Concurrency tuning (direct forward calls)")
539 print(f"{'='*50}")
540 cc_result = bench_concurrency(model, quick=quick)
541 if cc_result:
542 optimal_moe_concurrency = cc_result["optimal_concurrency"]
543 latency_p50_ms = cc_result["p50_latency_ms"]
544 if cc_result["max_throughput"] > best_moe_tok_s:
545 best_moe_tok_s = cc_result["max_throughput"]
546 else:
547 print(f" Concurrency tuning skipped -- using defaults")
548
549 # --- Build final config ---
550 optimal_np = best_par["n_parallel"] if best_par else 4
551 config = {
552 "autotune_date": time.strftime("%Y-%m-%d %H:%M:%S"),
553 "cpu": cpu,
554 "model_tuned_on": str(model),
555 "llama_server": {
556 "threads": optimal_threads,
557 "threads_batch": min(optimal_threads, physical),
558 "batch_size": best_batch["batch"] if best_batch else 4096,
559 "ubatch_size": best_batch["ubatch"] if best_batch else 1024,
560 "n_parallel": optimal_np,
561 "mlock": mlock_better,
562 "cont_batching": True,
563 "flash_attn": fa_better,
564 "cpu_mask": cpu_mask,
565 },
566 "proxy_server": {
567 "max_workers": optimal_np * 8, # 8× parallel slots for headroom
568 "queue_size": optimal_np * 32, # 32× for burst absorption
569 },
570 "mojollama_engine": {
571 "threads": optimal_moe_threads,
572 "optimal_batch": best_moe_batch,
573 "optimal_concurrency": optimal_moe_concurrency,
574 "max_throughput": best_moe_tok_s,
575 "latency_p50_ms": latency_p50_ms,
576 },
577 "results": {
578 "thread_sweep": [(r["threads"], r["tg_tok_s"]) for r in results],
579 "batch_sweep": [(r["batch"], r["tg_tok_s"]) for r in results_batch],
580 "parallel_sweep": [(r["n_parallel"], r["tg_tok_s"]) for r in results_par],
581 "flash_attn_on": r_fa_on,
582 "flash_attn_off": r_fa_off,
583 "best_gen_tok_s": max(r["tg_tok_s"] for r in results) if results else 0,
584 "best_prompt_tok_s": max(r["pp_tok_s"] for r in results) if results else 0,
585 },
586 }
587
588 return config
589
590
591def save_config(config):
592 """Save config to ~/.mojollama/config.json."""
593 CONFIG_DIR.mkdir(parents=True, exist_ok=True)
594 with open(CONFIG_PATH, "w") as f:
595 json.dump(config, f, indent=2)
596 print(f"\n✅ Config saved to {CONFIG_PATH}")
597
598
599def load_config():
600 """Load saved config, or return defaults."""
601 if CONFIG_PATH.exists():
602 with open(CONFIG_PATH) as f:
603 return json.load(f)
604 return None
605
606
607def print_config(config):
608 """Pretty-print the config."""
609 s = config.get("llama_server", {})
610 p = config.get("proxy_server", {})
611 print(f"\n{'='*50}")
612 print(f" MojoLlama Server Configuration")
613 print(f" Tuned: {config.get('autotune_date', 'unknown')}")
614 cpu = config.get("cpu", {})
615 print(f" CPU: {cpu.get('name', 'unknown')} ({cpu.get('physical_cores', '?')} physical / {cpu.get('cores', '?')} logical)")
616 print(f"{'='*50}")
617 print(f" llama.cpp backend:")
618 print(f" --threads {s.get('threads', '?')}")
619 print(f" --threads-batch {s.get('threads_batch', '?')}")
620 print(f" --batch-size {s.get('batch_size', '?')}")
621 print(f" --ubatch-size {s.get('ubatch_size', '?')}")
622 print(f" --parallel-slots {s.get('n_parallel', '?')}")
623 print(f" --mlock {'yes' if s.get('mlock', True) else 'no'}")
624 print(f" --cont-batching {'yes' if s.get('cont_batching', True) else 'no'}")
625 print(f" --flash-attn {'yes' if s.get('flash_attn', True) else 'no'}")
626 print(f" -C (cpu mask) {s.get('cpu_mask', 'auto')}")
627 print(f" Proxy server:")
628 print(f" --max-workers {p.get('max_workers', '?')}")
629 print(f" --queue-size {p.get('queue_size', '?')}")
630 print()
631 r = config.get("results", {})
632 print(f" Performance (on tune model):")
633 print(f" Generation: {r.get('best_gen_tok_s', 0):.0f} tok/s")
634 print(f" Prompt: {r.get('best_prompt_tok_s', 0):.0f} tok/s")
635 print(f" Max throughput: ~{s.get('n_parallel', 4) * 12:.0f} req/s (est.)")
636 print(f"{'='*50}")
637
638
639def main():
640 parser = argparse.ArgumentParser(
641 description="MojoLlama AutoTuner — find optimal server settings"
642 )
643 parser.add_argument("--model", "-m",
644 default="/tmp/tl-Q4_0.gguf",
645 help="GGUF model to benchmark with (default: TinyLlama Q4_0)")
646 parser.add_argument("--quick", "-q", action="store_true",
647 help="Quick mode -- fewer config combos")
648 parser.add_argument("--mojollama", action="store_true",
649 help="Run MojoLlama-specific phases (6: engine bench, 7: concurrency tuning)")
650 parser.add_argument("--show", action="store_true",
651 help="Show saved config and exit")
652 parser.add_argument("--serve-cmd", action="store_true",
653 help="Print the optimized llama-server command and exit")
654 args = parser.parse_args()
655
656 if args.show:
657 config = load_config()
658 if config:
659 print_config(config)
660 else:
661 print("No saved config. Run autotune first.")
662 return
663
664 if args.serve_cmd:
665 config = load_config()
666 if not config:
667 print("# No saved config. Run autotune first.")
668 print("# Using defaults...")
669 print("llama-server -m model.gguf -c 4096 -t 32 -b 4096 -ub 1024 -np 4 --mlock --cont-batching -fa 1 -C 0x00000000FFFFFFFF")
670 return
671
672 from mojollama.backends import build_server_cmd
673 cmd = build_server_cmd("llama-server", "model.gguf", 8081, config.get("llama_server"))
674 print(" ".join(cmd))
675 return
676
677
678# ═══════════════════════════════════════════════════════════════════════
679# Auto-tune on first model load
680# ═══════════════════════════════════════════════════════════════════════
681
682_AUTO_TUNE_CACHE = {} # model_path -> config
683
684
685def auto_tune_for_model(model_path: str, quick: bool = True) -> dict:
686 """Run a fast MojoLlama engine tune for *model_path* on first load.
687
688 Caches per model path. Returns config dict with:
689 - omp_threads — optimal OMP_NUM_THREADS for this model+hardware
690 - concurrency — optimal number of parallel workers
691 - strategy — 'process' or 'thread' based on hardware topology
692
693 Only runs the MojoLlama engine phases (skips llama-bench).
694 """
695 global _AUTO_TUNE_CACHE
696 cache_key = os.path.abspath(model_path)
697 if cache_key in _AUTO_TUNE_CACHE:
698 return _AUTO_TUNE_CACHE[cache_key]
699
700 print(f"\n{'='*50}")
701 print(f" MojoLlama AutoTune — first load of {os.path.basename(model_path)}")
702 print(f" Sweeping threads + concurrency for optimal settings...")
703 print(f"{'='*50}")
704
705 config = autotune(model_path, quick=quick, mojollama=True)
706
707 if config is None:
708 # Fallback defaults
709 import multiprocessing as mp
710 n_cores = mp.cpu_count() or 32
711 config = {
712 "autotune_date": time.strftime("%Y-%m-%d %H:%M:%S"),
713 "model_tuned_on": str(model_path),
714 "mojollama_engine": {
715 "omp_threads": min(32, n_cores),
716 "concurrency": min(8, max(1, n_cores // 4)),
717 "strategy": "process",
718 },
719 "hardware": {
720 "cores": n_cores,
721 }
722 }
723
724 save_config(config)
725 _AUTO_TUNE_CACHE[cache_key] = config
726
727 print(f" ✓ Saved to {CONFIG_PATH}")
728 if "mojollama_engine" in config:
729 me = config["mojollama_engine"]
730 print(f" → {me.get('omp_threads', '?')} OMP threads, "
731 f"{me.get('concurrency', '?')} workers ({me.get('strategy', 'process')})")
732 print(f"{'='*50}\n")
733 return config
734
735
736def get_tuned_setting(model_path: str, key: str, default=None):
737 """Get a single auto-tuned setting for *model_path*.
738
739 Runs auto-tune if not cached. Example:
740 threads = get_tuned_setting('/models/model.gguf', 'omp_threads', 32)
741 """
742 config = auto_tune_for_model(model_path, quick=True)
743 return config.get("mojollama_engine", {}).get(key, default)
744
745
746if __name__ == "__main__":
747 main()