"""Time prefill (TTFT) and decode for one MLX model across 512/4096/16384-token prompts. Usage: python bench_mlx.py --config A --repo mlx-community/Qwen3.8-27B-4bit --deadline python bench_mlx.py --config A --dry-run # check prompts + schedule, no model load Writes raw/.json. """ import argparse import json import os import platform import time from common import MAX_TOKENS, SCHEDULE, SEED, Budget, load_prompts, output_checks, thermal PREFILL_STEP = 2048 # mlx_lm generate_step default; recorded in output def eos_ban(eos_ids): """Logits processor that bans EOS so every run decodes exactly MAX_TOKENS tokens.""" import mlx.core as mx import numpy as np bias = {} def proc(tokens, logits): if "b" not in bias: b = np.zeros(logits.shape[-1], dtype=np.float32) b[list(eos_ids)] = -np.inf bias["b"] = mx.array(b) return logits + bias["b"].astype(logits.dtype) return proc def run_once(model, tok, ids, proc): import mlx.core as mx from mlx_lm import stream_generate mx.clear_cache() mx.reset_peak_memory() stamps, pieces, last = [], [], None t0 = time.perf_counter() for r in stream_generate(model, tok, ids, max_tokens=MAX_TOKENS, logits_processors=[proc], prefill_step_size=PREFILL_STEP): stamps.append(time.perf_counter()) pieces.append(r.text) last = r t_end = time.perf_counter() n = last.generation_tokens ttft = stamps[0] - t0 decode_s = stamps[-1] - stamps[0] text = "".join(pieces) return { "prompt_tokens": int(last.prompt_tokens), "ttft_s": ttft, "prefill_tps": last.prompt_tokens / ttft, "decode_tokens": n, "decode_tps": (n - 1) / decode_s if n > 1 else None, "wall_s": t_end - t0, "peak_mem_gb": mx.get_peak_memory() / 1e9, "mlx_reported_prompt_tps": float(last.prompt_tps), "mlx_reported_generation_tps": float(last.generation_tps), "finish_reason": last.finish_reason, "text": text, "checks": output_checks(text), } def main(): ap = argparse.ArgumentParser() ap.add_argument("--config", required=True) ap.add_argument("--repo", default="") ap.add_argument("--deadline", type=float, default=time.time() + 3600) ap.add_argument("--dry-run", action="store_true") args = ap.parse_args() prompts = load_prompts(args.config) lengths = prompts["lengths"] for _, order in SCHEDULE: for ctx in order: assert all(len(v["ids"]) == ctx for v in lengths[str(ctx)]["variants"]) if args.dry_run: print(f"[dry-run] {args.config}: prompts ok, schedule={SCHEDULE}, max_tokens={MAX_TOKENS}") return import mlx.core as mx import mlx_lm from mlx_lm import load mx.random.seed(SEED) out = {"config": args.config, "backend": "mlx_lm", "repo": args.repo, "mlx_version": mx.__version__, "mlx_lm_version": mlx_lm.__version__, "python": platform.python_version(), "max_tokens": MAX_TOKENS, "prefill_step_size": PREFILL_STEP, "sampler": "argmax (temperature 0)", "eos": "banned via logits processor (forced 256 tokens)", "kv_cache": "mlx_lm default (fresh per run, not quantized)", "thermal_before": thermal(), "runs": [], "skipped": []} t = time.perf_counter() model, tok = load(args.repo) out["load_s"] = time.perf_counter() - t out["device"] = str(mx.default_device()) proc = eos_ban(tok.eos_token_ids) out["eos_ids"] = sorted(int(i) for i in tok.eos_token_ids) # Discarded warm-up (kernel compilation, page-in), 512-token prompt, nonce 0. w = run_once(model, tok, lengths["512"]["variants"][0]["ids"], proc) out["warmup"] = {k: v for k, v in w.items() if k != "text"} print(f"[{args.config}] warm-up ttft={w['ttft_s']:.2f}s decode={w['decode_tps']:.1f} tok/s") budget = Budget(args.deadline) for rep, order in SCHEDULE: for ctx in order: if not budget.allows(ctx): out["skipped"].append({"rep": rep, "ctx": ctx, "reason": "time budget"}) print(f"[{args.config}] skip rep{rep} ctx{ctx} (time budget)") continue th = thermal() r = run_once(model, tok, lengths[str(ctx)]["variants"][rep]["ids"], proc) r.update({"rep": rep, "ctx": ctx, "t_unix": time.time(), "cpu_speed_limit": th["cpu_speed_limit"]}) budget.record(ctx, r["wall_s"]) out["runs"].append(r) print(f"[{args.config}] rep{rep} ctx{ctx}: ttft={r['ttft_s']:.2f}s " f"prefill={r['prefill_tps']:.0f} tok/s decode={r['decode_tps']:.1f} tok/s " f"peak={r['peak_mem_gb']:.1f}GB") out["thermal_after"] = thermal() os.makedirs("raw", exist_ok=True) with open(f"raw/{args.config}.json", "w") as f: json.dump(out, f, indent=1) if __name__ == "__main__": main()