"""Turn raw/*.json into results.json (stdlib only).""" import argparse import json import re import statistics import subprocess from pathlib import Path QUESTION = ( "On an M3 Max with 64 GB, how does total and per-request decode throughput grow from batch 1 to 16 for " "Qwen3.8-27B (dense, 4-bit), Qwen3.6-35B-A3B (MoE, 4-bit) and LFM2.5-24B-A2B (MoE, 4-bit) in mlx_lm, " "and at what batch size does adding requests stop helping?" ) KNEE_GAIN = 0.10 # knee: first batch size where going to the next tested size adds < 10% total throughput def sh(cmd): try: return subprocess.run(cmd, capture_output=True, text=True, timeout=10).stdout.strip() except Exception as e: return f"unavailable ({e})" def median(xs): return statistics.median(xs) if xs else None def metric(value, unit, samples=None, note=""): r = lambda x: round(x, 4) if isinstance(x, float) else x return {"value": r(value), "unit": unit, "samples": [r(s) for s in (samples or [])], "note": note} def speed_limit(pmset_text): m = re.search(r"CPU_Speed_Limit\s*=\s*(\d+)", pmset_text or "") return int(m.group(1)) if m else None def main(): ap = argparse.ArgumentParser() ap.add_argument("--raw", default="raw") ap.add_argument("--out", default="results.json") args = ap.parse_args() raw_dir = Path(args.raw) meta = json.loads((raw_dir / "meta.json").read_text()) M, obs, caveats = {}, [], [] summary = {} # name -> {batch: median total tps} versions = None for name, info in meta["models"].items(): f = raw_dir / f"{name}.json" if not f.exists(): caveats.append(f"{name}: no data (process failed or was skipped), see run.log.") continue d = json.loads(f.read_text()) versions = versions or d["versions"] kind = info["kind"] max_tokens = d["max_tokens"] M[f"{name}.load_time"] = metric(d["load_s"], "s", note="model load from local disk") M[f"{name}.prompt_tokens"] = metric(median(d["prompt_tokens"]), "tokens", d["prompt_tokens"], "median prompt length after chat template; samples = all 16 prompts") good, excluded = {}, [] for r in d["runs"]: short = min(r["generated_tokens"]) < 0.9 * max_tokens swapped = (r.get("swapouts_delta") or 0) > 0 if short or swapped: excluded.append((r["batch"], r["rep"], "short output" if short else f"swap ({r['swapouts_delta']} pages)")) else: good.setdefault(r["batch"], []).append(r) for b, rep, why in excluded: caveats.append(f"{name} batch {b} rep {rep} excluded from throughput: {why}.") for s in d["skipped"]: caveats.append(f"{name}: skipped {s} because of the time budget.") tot = {b: median([r["total_decode_tps"] for r in rs]) for b, rs in good.items()} summary[name] = {"kind": kind, "total": tot} b1 = tot.get(1) for b in sorted(good): rs = good[b] t = [r["total_decode_tps"] for r in rs] n = len(rs) spread = f"median of {n}; min {min(t):.1f}, max {max(t):.1f}" M[f"{name}.b{b}.total_decode_tps"] = metric(median(t), "tokens/s", t, spread) pr = [r["per_request_decode_tps"] for r in rs] M[f"{name}.b{b}.per_request_decode_tps"] = metric(median(pr), "tokens/s", pr, f"total / batch size; min {min(pr):.1f}, max {max(pr):.1f}") if b1: M[f"{name}.b{b}.speedup_vs_b1"] = metric(tot[b] / b1, "x", [x / b1 for x in t], "median total tps / median batch-1 total tps") M[f"{name}.b{b}.prefill_time"] = metric(median([r["prefill_s"] for r in rs]), "s", [r["prefill_s"] for r in rs], "wall time from submit until every request has its first token") M[f"{name}.b{b}.prompt_processing_time"] = metric( median([r["prompt_processing_s"] for r in rs]), "s", [r["prompt_processing_s"] for r in rs], "mlx_lm BatchGenerator prompt-only timer (excludes the first decode step)") ttft = [median(r["ttft_s"]) for r in rs] M[f"{name}.b{b}.ttft"] = metric(median(ttft), "s", ttft, "time to first token per request (static batch: equal for all requests)") mem = [r["peak_memory_gb"] for r in rs] M[f"{name}.b{b}.peak_memory"] = metric(max(mem), "GB", mem, "mx.get_peak_memory, reset before each run; value = max") e2e = [r["end_to_end_tps"] for r in rs] M[f"{name}.b{b}.end_to_end_tps"] = metric(median(e2e), "tokens/s", e2e, "all generated tokens / (prefill + decode) wall time") M[f"{name}.b{b}.generated_tokens_per_request"] = metric( min(min(r["generated_tokens"]) for r in rs), "tokens", [], "minimum over all requests (EOS disabled)") # Correctness: batched greedy vs batch-1 greedy, from all repeats. for b in sorted({r["batch"] for r in d["runs"]}): rs = [r for r in d["runs"] if r["batch"] == b] div = [x for r in rs for x in r["first_divergence"] if x != "no_reference"] if not div: continue same = sum(1 for x in div if x is None) diverged = [x for x in div if x is not None] M[f"{name}.b{b}.identical_outputs"] = metric(100.0 * same / len(div), "%", [], f"{same}/{len(div)} request outputs identical to batch-1 greedy " f"({len(rs)} repeats x {b} requests)" + ("; batch 1 = repeat-to-repeat determinism" if b == 1 else "")) if diverged: M[f"{name}.b{b}.first_divergence"] = metric(median(diverged), "token index", diverged, f"median over diverged outputs; earliest {min(diverged)}") rep_lists = {json.dumps(r["first_divergence"]) for r in rs} M[f"{name}.b{b}.repeats_consistent"] = metric(1 if len(rep_lists) == 1 else 0, "bool", [], "1 = every repeat diverged at the same positions") if d["reference_runs"]: t = [r["total_decode_tps"] for r in d["reference_runs"]] M[f"{name}.b1_all_prompts.total_decode_tps"] = metric( median(t), "tokens/s", t, f"batch-1 reference runs over prompts 1-15; min {min(t):.1f}, max {max(t):.1f}") bs = sorted(tot) if bs: best = max(bs, key=lambda b: tot[b]) M[f"{name}.max_throughput_batch"] = metric(best, "requests", [], f"batch size with the highest median total tps ({tot[best]:.1f})") knee = next((a for a, c in zip(bs, bs[1:]) if tot[c] < tot[a] * (1 + KNEE_GAIN)), bs[-1]) M[f"{name}.knee_batch"] = metric(knee, "requests", [], f"first tested batch size where the next tested size adds < {KNEE_GAIN:.0%} total throughput") pm = meta["per_model"].get(name, {}) for when in ("before", "after"): lim = speed_limit(pm.get(when, {}).get("pmset_therm")) if lim is not None: M[f"{name}.cpu_speed_limit_{when}"] = metric(lim, "%", [], "pmset -g therm CPU_Speed_Limit (100 = no throttling)") if pm.get("returncode") not in (0, None): caveats.append(f"{name}: benchmark process ended with {pm.get('returncode')}; data up to that point is used.") # Cross-model comparison: each MoE vs the dense model. dense = next((n for n, s in summary.items() if s["kind"] == "dense"), None) for n, s in summary.items(): if s["kind"] != "moe" or not dense: continue common = sorted(set(s["total"]) & set(summary[dense]["total"])) ratios = {b: s["total"][b] / summary[dense]["total"][b] for b in common} for b, x in ratios.items(): M[f"{n}_vs_{dense}.b{b}.total_tps_ratio"] = metric(x, "x", [], f"median total tps {n} / {dense}") if ratios: cross = [(a, c) for a, c in zip(common, common[1:]) if (ratios[a] > 1) != (ratios[c] > 1)] lo, hi = common[0], common[-1] obs.append(f"{n} vs {dense}: total decode throughput ratio {ratios[lo]:.2f}x at batch {lo} and " f"{ratios[hi]:.2f}x at batch {hi}; " + (f"ranking flips between batch sizes " + ", ".join(f"{a} and {c}" for a, c in cross) + "." if cross else f"no crossover within batch {lo}-{hi}.")) for n, s in summary.items(): t = s["total"] if 1 in t and max(t) > 1: hi = max(t) obs.append(f"{n} ({s['kind']}): median total decode throughput {t[1]:.1f} tok/s at batch 1 and " f"{t[hi]:.1f} tok/s at batch {hi} ({t[hi] / t[1]:.2f}x); per-request {t[hi] / hi:.1f} tok/s at batch {hi}; " f"knee at batch {M[f'{n}.knee_batch']['value']}, maximum at batch {M[f'{n}.max_throughput_batch']['value']}.") idents = [(int(m.group(1)), v["value"]) for k, v in M.items() if (m := re.fullmatch(rf"{re.escape(n)}\.b(\d+)\.identical_outputs", k))] if idents: obs.append(f"{n}: share of request outputs identical to batch-1 greedy output: " + ", ".join(f"batch {b} {v:.0f}%" for b, v in sorted(idents)) + ".") # Optional server test. sf = raw_dir / "server.json" if sf.exists(): sd = json.loads(sf.read_text()) sname = meta.get("server", {}).get("name", sd["model"]) for c in sorted({b["concurrency"] for b in sd["bursts"]}): bb = [b for b in sd["bursts"] if b["concurrency"] == c] e2e = [b["end_to_end_tps"] for b in bb] M[f"server.{sname}.c{c}.end_to_end_tps"] = metric(median(e2e), "tokens/s", e2e, "mlx_lm.server, c concurrent streaming requests: completion tokens / wall time") tt = [t for b in bb for t in b["ttft_s"] if t is not None] if tt: M[f"server.{sname}.c{c}.ttft"] = metric(median(tt), "s", tt, "per-request time to first streamed token") toks = [t for b in bb for t in b["completion_tokens"]] M[f"server.{sname}.c{c}.completion_tokens"] = metric(min(toks), "tokens", toks, "min over requests") ref = M.get(f"{sname}.b{c}.end_to_end_tps") if ref: obs.append(f"mlx_lm.server with {c} concurrent requests ({sname}): {median(e2e):.1f} tok/s end-to-end vs " f"{ref['value']:.1f} tok/s for batch_generate-style batch {c} (same metric).") if any(x for b in sd["bursts"] for x in b["cached_tokens"] if x): caveats.append("Server reported cached prompt tokens for some requests; their prefill was partly skipped.") thermal = {n: {w: meta["per_model"].get(n, {}).get(w, {}).get("pmset_therm") for w in ("before", "after")} for n in meta["models"]} environment = { "machine": {"model": sh(["sysctl", "-n", "hw.model"]), "cpu": sh(["sysctl", "-n", "machdep.cpu.brand_string"]), "memory_bytes": sh(["sysctl", "-n", "hw.memsize"])}, "os": {"product_version": sh(["sw_vers", "-productVersion"]), "build": sh(["sw_vers", "-buildVersion"])}, "software": versions or {}, "model_order": meta["order"], "order_seed": meta["seed"], "thermal_pmset": thermal, "models": meta["models"], } caveats += [ "The three 4-bit quantisations differ (group size 64 affine for all; Qwen3.6 MoE keeps router gates at 8-bit, " "LFM2.5 keeps embeddings at 6-bit). Compare scaling (speedup vs batch 1) as well as absolute speed; no quality ranking is implied.", "Static batches: all requests start together and all have the same length (EOS disabled, 256 new tokens). " "Real agents arrive at different times and stop at different lengths, which lowers the effective batch.", "Decode throughput excludes prefill: decode time runs from the moment every request has its first token to the last token.", "Prompts are about 290 tokens; with long agent contexts the KV cache and attention cost per step grow and the curves will differ.", "Greedy outputs after EOS are forced continuations; they are used only for timing and the divergence check.", "Single machine, one session; repeats are back to back in the same process.", "All three models are hybrids: the Qwen3.5-family models (Qwen3.8-27B, Qwen3.6-35B-A3B) mix gated linear-attention " "layers with full attention, LFM2.5 mixes short convolutions with attention. Only the attention layers keep a growing KV cache, " "so 'dense' here means dense FFN/weights, not a classic all-attention transformer.", "Batched prompts of different lengths are padded by mlx_lm; any divergence from batch-1 output reflects batched kernels " "and padding, not sampling (greedy everywhere).", ] if "server" in meta and "skipped" in meta["server"]: caveats.append(f"Optional mlx_lm.server test not run: {meta['server']['skipped']}.") elif meta.get("server", {}).get("returncode") not in (0, None): caveats.append(f"Optional mlx_lm.server test failed (exit {meta['server']['returncode']}); " "see raw/server.server.log. Any server numbers above are partial.") results = { "question": QUESTION, "environment": environment, "runs": max((len(v["samples"]) for k, v in M.items() if re.search(r"\.b\d+\.total_decode_tps$", k)), default=0), "metrics": M, "observations": obs, "caveats": caveats, } Path(args.out).write_text(json.dumps(results, indent=1)) print(f"wrote {args.out}: {len(M)} metrics, {len(obs)} observations") if __name__ == "__main__": main()