"""Aggregate out/*/runs.jsonl into results.json, results_runs.csv and plots. Usage: python analyze.py [--out out] [--results results.json] """ import argparse import json import math from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt # noqa: E402 import pandas as pd # noqa: E402 CATS = ["code", "extract", "explain", "creative"] QUESTION = ("On an M3 Max with 64 GB, does using Qwen3.5-9B as a draft model make Qwen3.8-27B and " "Qwen3.6-27B (4-bit, MLX) decode faster? How does the speedup change with task type and " "number of draft tokens? And is a speculated dense 27B ever faster than just running the " "35B-A3B MoE?") def load_json(p): p = Path(p) return json.loads(p.read_text()) if p.exists() else None def load_runs(out): rows, tokens, metas = [], {}, {} for d in sorted(Path(out).iterdir()): if not (d / "runs.jsonl").exists(): continue metas[d.name] = load_json(d / "meta.json") rows += [json.loads(l) for l in (d / "runs.jsonl").read_text().splitlines() if l.strip()] for l in (d / "tokens.jsonl").read_text().splitlines(): t = json.loads(l) tokens[(d.name, t["order"])] = t["tokens"] return pd.DataFrame(rows), tokens, metas def r3(x): return None if x is None or (isinstance(x, float) and math.isnan(x)) else round(float(x), 3) def metric(value, unit, samples=(), note=""): return {"value": r3(value), "unit": unit, "samples": [r3(s) for s in samples], "note": note} def expected_tokens(a, k): return k + 1 if a >= 1 else (1 - a ** (k + 1)) / (1 - a) def theory_classic(a, k, c): """Leviathan et al.: verify of k+1 tokens costs one target step, no rollback cost.""" return expected_tokens(a, k) / (k * c + 1) def theory_hybrid(a, k, c, v, r): """Adds measured verify cost v[S] and hybrid rollback re-forward cost r[S] (target-step units).""" p_rej = [a ** n * (1 - a) for n in range(k)] # P(first rejection at position n+1) cost = k * c + v[k + 1] + sum(p * r[n + 1] for n, p in enumerate(p_rej)) return expected_tokens(a, k) / cost def identity(df, tokens): """Greedy runs vs the first greedy baseline run of the same prompt (same process).""" out = [] g = df[df.temp == 0] for (tag, prompt), grp in g.groupby(["tag", "prompt"]): base = grp[grp.kind == "base"].sort_values("order") if base.empty: continue ref = tokens[(tag, int(base.iloc[0].order))] for _, r in grp.iterrows(): if r.order == base.iloc[0].order or r.kind == "draft_alone": continue t = tokens[(tag, int(r.order))] div = next((i for i, (a, b) in enumerate(zip(ref, t)) if a != b), None) if div is None and len(ref) != len(t): div = min(len(ref), len(t)) out.append({"tag": tag, "prompt": prompt, "category": r.category, "config": r.config, "kind": r.kind, "rep": r.rep, "identical": div is None, "first_diff": div}) return pd.DataFrame(out) def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default="out") ap.add_argument("--results", default="results.json") args = ap.parse_args() out = Path(args.out) df, tokens, metas = load_runs(out) env, compat = load_json(out / "env.json") or {}, load_json(out / "compat.json") or {} df.drop(columns=["text_head"], errors="ignore").to_csv(out / "results_runs.csv", index=False) M, obs, cav, tables = {}, [], [], {} fake = any(m and m.get("fake") for m in metas.values()) tmeta, mmeta = metas.get("target") or {}, metas.get("moe") or {} tname = (tmeta.get("model") or "target").split("/")[-1] reps = int(df.rep.max() + 1) if len(df) else 0 # ---- compatibility + stock mlx_lm check ------------------------------------------------ for p in compat.get("pairs", []): M[f"tokenizer_compatible__{p['target'].split('/')[-1]}"] = metric( int(p["compatible"]), "bool (1=identical ids)", [], f"vocab identical={p['vocab_identical']}, special tokens identical={p['special_tokens_identical']}, " f"pre-tokenizer identical={p.get('pre_tokenizer_identical')}, sample of {p['sample_tokens']} tokens " f"identical={p['sample_ids_identical']} (first diff at {p['sample_first_diff_index']}), " f"chat-templated prompt ids identical={p['chat_template_ids_identical_all_prompts']}") if compat.get("decision"): obs.append(compat["decision"]) for p in compat.get("pairs", []): if not p["compatible"] and p.get("sample_diff_context"): obs.append(f"{p['target'].split('/')[-1]} vs draft: same vocab ({p['vocab_size_target']} entries) " f"and special tokens, but pre-tokenizer identical={p.get('pre_tokenizer_identical')}; " f"the {compat.get('sample_text_tokens')}-token sample diverges at token " f"{p['sample_first_diff_index']}: draft {p['sample_diff_context']['draft']} vs target " f"{p['sample_diff_context']['target']}.") sc = tmeta.get("stock_check") if sc: M["stock_mlx_lm_draft_model_works"] = metric(int(sc["works"]), "bool", [], f"mlx_lm {tmeta['versions'].get('mlx_lm')}: {sc['error']}") obs.append(f"Stock mlx_lm {tmeta['versions'].get('mlx_lm')} speculative decoding (the --draft-model path) " f"{'works' if sc['works'] else 'fails'} for {tname} + draft" + (f": {sc['error']}" if sc["error"] else "") + f" Cache types: {sc['cache_types']}; " f"target cache trimmable={sc['target_cache_trimmable']}, draft cache trimmable=" f"{sc['draft_cache_trimmable']}.") if df.empty: cav.append("No benchmark runs were recorded.") g = df[(df.temp == 0)] if len(df) else df tg = g[g.tag == "target"] if len(g) else g # ---- per category x config: throughput, speedup, acceptance, ttft, e2e, memory ----------- base_med = {} spec_cfgs = sorted({c for c in tg.config.unique() if c.startswith("k")}, key=lambda c: int(c[1:])) if len(tg) else [] rows = [] for cat in CATS + ["all"]: sub = tg if cat == "all" else tg[tg.category == cat] for cfg in ["base"] + spec_cfgs: s = sub[sub.config == cfg] if s.empty: continue tps = s.decode_tps key = f"{tname}__{cfg}__{cat}" M[f"decode_tps__{key}"] = metric(tps.median(), "tokens/s", tps, f"median over {len(s)} runs (3 prompts x reps); min {tps.min():.2f}, max {tps.max():.2f}") M[f"ttft_ms__{key}"] = metric(1000 * s.ttft_s.median(), "ms", 1000 * s.ttft_s, "median; includes prefill of target (+draft)") M[f"e2e_s__{key}"] = metric(s.e2e_s.median(), "s", s.e2e_s, f"wall time for {int(s.gen_tokens.median())} generated tokens incl. prefill") M[f"peak_mem_gb__{key}"] = metric(s.peak_mem_gb.max(), "GB", s.peak_mem_gb, "max of per-run MLX peak memory; weights of target AND draft are resident in every run of this process") row = {"category": cat, "config": cfg, "runs": len(s), "tps_median": tps.median(), "tps_min": tps.min(), "tps_max": tps.max(), "ttft_ms": 1000 * s.ttft_s.median(), "e2e_s": s.e2e_s.median(), "peak_gb": s.peak_mem_gb.max()} if cfg == "base": base_med[cat] = tps.median() else: sp = tps.median() / base_med[cat] per_prompt = (s.groupby("prompt").decode_tps.median() / sub[sub.config == "base"].groupby("prompt").decode_tps.median()).dropna() M[f"speedup__{key}"] = metric(sp, "x", per_prompt, "median spec tok/s / median baseline tok/s; samples = per-prompt ratios of medians") acc, prop, rej = s.spec_accepted.sum(), s.spec_proposed.sum(), s.spec_rejections.sum() M[f"acceptance_rate__{key}"] = metric(100 * acc / prop, "%", 100 * s.spec_accepted / s.spec_proposed, "accepted / proposed draft tokens (from_draft flags), pooled over runs") alpha = acc / (acc + rej) if acc + rej else float("nan") M[f"alpha_per_position__{key}"] = metric(alpha, "probability", [], "accepted / (accepted + rejections): per-position acceptance MLE used by the theory model") M[f"tokens_per_cycle__{key}"] = metric((acc + s.spec_cycles.sum()) / s.spec_cycles.sum(), "tokens", [], "tokens emitted per draft+verify cycle (approx; the last cycle may be cut at max_tokens)") M[f"rollback_reforwards_per_run__{key}"] = metric(s.spec_target_reforwards.mean(), "count", s.spec_target_reforwards, "target re-forwards needed to roll back the recurrent state after a rejection") row.update(speedup=sp, acceptance_pct=100 * acc / prop, alpha=alpha, reforwards_per_run=s.spec_target_reforwards.mean()) rows.append(row) tables["target_by_category_config"] = [{k: (r3(v) if isinstance(v, float) else v) for k, v in r.items()} for r in rows] tab = pd.DataFrame(rows) # ---- correctness: greedy token identity --------------------------------------------------- ident = identity(df, tokens) if len(df) else pd.DataFrame() if len(ident): for (kind, cfg), s in ident[ident.tag == "target"].groupby(["kind", "config"]): what = "baseline repeats vs first baseline run" if kind == "base" else f"{cfg} vs baseline" M[f"greedy_identical_pct__{tname}__{cfg}"] = metric( 100 * s.identical.mean(), "% of runs", [], f"{what}: {int(s.identical.sum())}/{len(s)} identical; " f"first differing position (non-identical runs): {sorted(s.first_diff.dropna().astype(int).tolist())}") for tag in ident.tag.unique(): if tag == "target": continue s = ident[ident.tag == tag] M[f"greedy_identical_pct__{tag}__base"] = metric(100 * s.identical.mean(), "% of runs", [], f"baseline repeats vs first run: {int(s.identical.sum())}/{len(s)}") sp = ident[(ident.tag == "target") & (ident.kind == "spec")] if len(sp): obs.append(f"Greedy speculative output was token-identical to the greedy baseline in " f"{int(sp.identical.sum())}/{len(sp)} runs ({100 * sp.identical.mean():.1f}%).") if (~sp.identical).any(): obs.append(f"Non-identical runs diverged at token positions " f"{sorted(sp.first_diff.dropna().astype(int).tolist())} (of {int(df.gen_tokens.max())}); " f"by category: {sp[~sp.identical].category.value_counts().to_dict()}.") tables["token_identity"] = ident.to_dict(orient="records") # ---- cost ratios + theory ----------------------------------------------------------------- mb = tmeta.get("microbench") or {} c_micro = mb.get("draft_verify_ms_S1", 0) / mb["target_verify_ms_S1"] if mb.get("target_verify_ms_S1") else None da = g[(g.tag == "target") & (g.kind == "draft_alone")] if len(g) else g c_runs = base_med.get("all") / da.decode_tps.median() if len(da) and base_med.get("all") else None if mb: kmax = max([int(c[1:]) for c in spec_cfgs] + [1]) t1 = mb["target_verify_ms_S1"] v = {S: mb[f"target_verify_ms_S{S}"] / t1 for S in range(1, kmax + 2) if f"target_verify_ms_S{S}" in mb} r = {S: mb[f"target_reforward_ms_S{S}"] / t1 for S in range(1, kmax + 2) if f"target_reforward_ms_S{S}" in mb} for S in v: M[f"target_forward_ms__verify_S{S}"] = metric(mb[f"target_verify_ms_S{S}"], "ms", [], f"one target forward over {S} tokens at {mb['context_tokens']}-token context, logits+cache evaluated (median of {mb['reps']})") M[f"target_forward_ms__reforward_S{S}"] = metric(mb[f"target_reforward_ms_S{S}"], "ms", [], f"same, caches only (hybrid rollback re-forward of {S} tokens)") M["draft_forward_ms__S1"] = metric(mb.get("draft_verify_ms_S1"), "ms", [], "one draft decode step") M["draft_cost_ratio_c__microbench"] = metric(c_micro, "ratio", [], "draft step time / target step time (forward microbenchmark)") if c_runs: M["draft_cost_ratio_c__runs"] = metric(c_runs, "ratio", da.decode_tps, "baseline target decode tok/s / draft-alone decode tok/s (samples: draft-alone tok/s)") M[f"decode_tps__draft_alone__{(tmeta.get('draft') or '').split('/')[-1]}"] = metric( da.decode_tps.median(), "tokens/s", da.decode_tps, "Qwen3.5-9B alone, greedy, one prompt per category") c = c_micro or c_runs if c and len(tab) and "speedup" in tab: th = [] for _, row in tab[tab.config != "base"].iterrows(): k = int(row.config[1:]) a = row.alpha cl = theory_classic(a, k, c) hy = theory_hybrid(a, k, c, v, r) if mb and k + 1 in v else None key = f"{tname}__{row.config}__{row.category}" M[f"theory_speedup_classic__{key}"] = metric(cl, "x", [], f"(1-a^(k+1))/((1-a)(kc+1)), a={a:.3f}, c={c:.3f}") if hy: M[f"theory_speedup_hybrid__{key}"] = metric(hy, "x", [], "classic + measured verify cost + rollback re-forward cost") th.append({"category": row.category, "k": k, "alpha": r3(a), "measured": r3(row.speedup), "classic": r3(cl), "hybrid_model": r3(hy)}) tables["measured_vs_theory"] = th thd = pd.DataFrame(th) if len(thd): M["theory_abs_error_classic_mean"] = metric((thd.measured - thd.classic).abs().mean(), "x", [], "mean |measured - classic theory| over category x k cells") if thd.hybrid_model.notna().all(): M["theory_abs_error_hybrid_mean"] = metric((thd.measured - thd.hybrid_model).abs().mean(), "x", [], "mean |measured - hybrid-aware theory|") # what a smaller draft would do, at the alphas we measured (classic model) grid = [] for cc in (0.05, 0.1, 0.2, round(c, 3)): for a in (0.5, 0.6, 0.7, 0.8, 0.9): for k in (2, 4, 6): grid.append({"c": cc, "alpha": a, "k": k, "speedup_classic": r3(theory_classic(a, k, cc))}) tables["theory_grid_classic"] = grid M["theory_breakeven_alpha_k4"] = metric( next((a / 100 for a in range(1, 100) if theory_classic(a / 100, 4, c) >= 1), None), "probability", [], f"smallest alpha with classic speedup >= 1 at k=4 for the measured c={c:.3f}") # ---- temp 0.7 pass --------------------------------------------------------------------------- t7 = df[(df.tag == "target") & (df.temp > 0)] if len(df) else df if len(t7): for cat in sorted(t7.category.unique()): s, b = t7[(t7.category == cat) & (t7.kind == "spec")], t7[(t7.category == cat) & (t7.kind == "base")] if s.empty or b.empty: continue key = f"{tname}__k4@0.7__{cat}" M[f"decode_tps__{key}"] = metric(s.decode_tps.median(), "tokens/s", s.decode_tps, "temp 0.7, k=4") M[f"decode_tps__{tname}__base@0.7__{cat}"] = metric(b.decode_tps.median(), "tokens/s", b.decode_tps, "temp 0.7") M[f"speedup__{key}"] = metric(s.decode_tps.median() / b.decode_tps.median(), "x", [], "vs temp-0.7 baseline") M[f"acceptance_rate__{key}"] = metric(100 * s.spec_accepted.sum() / s.spec_proposed.sum(), "%", 100 * s.spec_accepted / s.spec_proposed, "temp 0.7, k=4") gk = M.get(f"acceptance_rate__{tname}__k4__{cat}") if gk: obs.append(f"{cat}: k=4 acceptance {gk['value']:.1f}% greedy vs " f"{M[f'acceptance_rate__{key}']['value']:.1f}% at temp 0.7.") # ---- MoE reference ----------------------------------------------------------------------- mo = g[g.tag == "moe"] if len(g) else g if len(mo): mname = mo.model.iloc[0] for cat in CATS + ["all"]: s = mo if cat == "all" else mo[mo.category == cat] M[f"decode_tps__{mname}__base__{cat}"] = metric(s.decode_tps.median(), "tokens/s", s.decode_tps, f"median over {len(s)} runs; min {s.decode_tps.min():.2f}, max {s.decode_tps.max():.2f}") M[f"ttft_ms__{mname}__base__{cat}"] = metric(1000 * s.ttft_s.median(), "ms", 1000 * s.ttft_s, "median") M[f"e2e_s__{mname}__base__{cat}"] = metric(s.e2e_s.median(), "s", s.e2e_s, "median") M[f"peak_mem_gb__{mname}__base__{cat}"] = metric(s.peak_mem_gb.max(), "GB", s.peak_mem_gb, "MoE alone resident") if len(tab): best = tab[(tab.category == cat)].sort_values("tps_median").iloc[-1] ratio = s.decode_tps.median() / best.tps_median M[f"moe_vs_best_dense__{cat}"] = metric(ratio, "x", [], f"MoE median tok/s / best {tname} config ({best.config}, {best.tps_median:.2f} tok/s)") obs.append(f"{cat}: {mname} decodes at {s.decode_tps.median():.1f} tok/s vs the fastest {tname} " f"config ({best.config}) at {best.tps_median:.1f} tok/s ({ratio:.2f}x).") # ---- headline observations from the table ------------------------------------------------ if len(tab) and "speedup" in tab: sp = tab[tab.config != "base"] for cat in CATS: s = sp[sp.category == cat] if len(s): b = s.sort_values("speedup").iloc[-1] obs.append(f"{cat}: best speculative config {b.config} gives {b.speedup:.2f}x " f"({b.tps_median:.1f} vs {base_med[cat]:.1f} tok/s baseline), acceptance {b.acceptance_pct:.1f}%.") cells = sp[sp.category != "all"] obs.append(f"Speculation was slower than the baseline in {int((cells.speedup < 1).sum())} of {len(cells)} " f"category x k cells (median of runs).") # ---- drift --------------------------------------------------------------------------------- b = tg[tg.config == "base"] if len(tg) else tg if len(b) and b.rep.nunique() > 1: first, last = b[b.rep == b.rep.min()].decode_tps.median(), b[b.rep == b.rep.max()].decode_tps.median() M[f"thermal_drift_baseline_pct__{tname}"] = metric(100 * (last / first - 1), "%", [], f"median baseline tok/s, last repeat vs first repeat ({last:.2f} vs {first:.2f})") for tag, m in metas.items(): if not m: continue for role, s in (m.get("load_s") or {}).items(): M[f"load_s__{tag}__{role}"] = metric(s, "s", [], "mlx_lm.load + materialize weights") for role, gb in (m.get("weights_gb") or {}).items(): M[f"weights_gb__{tag}__{role}"] = metric(gb, "GB", [], "sum of parameter nbytes") # ---- caveats --------------------------------------------------------------------------------- cav += [ "mlx_lm's built-in speculative decoding refuses hybrid Gated-DeltaNet models (non-trimmable ArraysCache), " "so all speculative numbers come from specdec.py: mlx_lm's loop plus state snapshot/restore. On a rejection the " "target re-runs the accepted tokens to rebuild its recurrent state; this cost is included in every speculative " "number and would be lower with a kernel that exposes per-token states.", "EOS is masked (logit -inf) for every run so all runs decode exactly 256 tokens; after a natural answer end the " "model keeps writing, which may change acceptance compared with normal use.", "Thinking mode disabled via the chat template (enable_thinking=False) for every model.", "Peak memory for the dense configs is measured with target AND draft resident (one process), also for the " "no-draft baseline; weights_gb__* gives each model's weight size.", "A 9B draft is a large draft (about a third of the target). Smaller drafts (0.5-2B) would have a much lower cost " "ratio c; see tables.theory_grid_classic for what the classic model predicts.", "Acceptance at temp 0.7 uses mlx_lm's rule (accept iff the target's own sample equals the draft token), not " "Leviathan-style rejection sampling, which would accept more often.", "Results are for one machine, one draft/target pair and 12 prompts; acceptance is prompt-driven.", ] if compat.get("primary_target") and "3.6" in compat["primary_target"]: cav.append("Qwen3.8-27B was excluded from speculative runs because its tokenizer does not produce identical " "ids to the Qwen3.5-9B draft (see compat metrics).") for tag, m in metas.items(): if m and m.get("plan_notes"): cav.append(f"[{tag}] time budget forced: " + "; ".join(m["plan_notes"])) if m and m.get("runs_skipped_deadline"): cav.append(f"[{tag}] {m['runs_skipped_deadline']} scheduled runs were skipped at the hard deadline.") th = env.get("thermal", {}) if th and not th.get("powermetrics_ok"): cav.append("powermetrics needs sudo and was not available; thermal state logged with `pmset -g therm` only.") if env.get("low_power_mode") not in (None, "0"): cav.append(f"Low Power Mode was reported as {env.get('low_power_mode')!r} during the run.") if fake: cav.insert(0, "SMOKE TEST: these numbers are synthetic (FakeBackend), not measurements.") # ---- plots ---------------------------------------------------------------------------------- plots = out / "plots" plots.mkdir(exist_ok=True) if len(tab) and "speedup" in tab: sp = tab[(tab.config != "base") & (tab.category != "all")] fig, ax = plt.subplots(1, 2, figsize=(11, 4)) for cfg in spec_cfgs: s = sp[sp.config == cfg].set_index("category").reindex(CATS) ax[0].plot(CATS, s.speedup, marker="o", label=cfg) ax[1].plot(CATS, s.acceptance_pct, marker="o", label=cfg) ax[0].axhline(1, color="grey", lw=0.8) ax[0].set_ylabel("speedup vs no draft (x)") ax[1].set_ylabel("acceptance (%)") for a in ax: a.legend() fig.suptitle(f"{tname} + Qwen3.5-9B draft, greedy, 256 tokens") fig.tight_layout() fig.savefig(plots / "speedup_acceptance.png", dpi=130) if "measured_vs_theory" in tables: thd = pd.DataFrame(tables["measured_vs_theory"]) fig, ax = plt.subplots(figsize=(5, 5)) ax.scatter(thd.classic, thd.measured, label="classic theory") if thd.hybrid_model.notna().any(): ax.scatter(thd.hybrid_model, thd.measured, marker="x", label="hybrid-aware theory") lim = [0, max(thd[["measured", "classic"]].max().max(), 1.2) * 1.1] ax.plot(lim, lim, color="grey", lw=0.8) ax.set_xlabel("predicted speedup (x)") ax.set_ylabel("measured speedup (x)") ax.legend() fig.tight_layout() fig.savefig(plots / "measured_vs_theory.png", dpi=130) if len(df): fig, ax = plt.subplots(figsize=(9, 3.5)) for (tag, cfg), s in df[df.temp == 0].groupby(["tag", "config"]): ax.plot(s.wall_clock - df.wall_clock.min(), s.decode_tps, ".", label=f"{tag}:{cfg}") ax.set_xlabel("seconds since first run") ax.set_ylabel("decode tok/s") ax.legend(fontsize=7, ncol=3) fig.tight_layout() fig.savefig(plots / "tps_over_time.png", dpi=130) results = { "question": QUESTION, "environment": { "machine": env.get("machine"), "os": env.get("os"), "software": {**(env.get("software") or {}), **{f"{k}_runtime": v for k, v in (tmeta.get("versions") or {}).items() if k in ("mlx", "mlx_lm", "device")}}, "models": {**(tmeta.get("commits") or {}), **(mmeta.get("commits") or {})}, "power": {k: env.get(k) for k in ("power_source", "low_power_mode")}, "thermal": th, }, "runs": reps, "metrics": M, "observations": obs, "caveats": cav, "tables": tables, "plan": {tag: {"plan": m.get("plan"), "notes": m.get("plan_notes"), "runs_done": m.get("runs_done"), "skipped": m.get("runs_skipped_deadline"), "elapsed_s": r3(m.get("elapsed_s"))} for tag, m in metas.items() if m}, "files": {"raw_csv": str(out / "results_runs.csv"), "plots": sorted(str(p) for p in plots.glob("*.png"))}, } Path(args.results).write_text(json.dumps(results, indent=2, default=str)) print(f"wrote {args.results}: {len(M)} metrics, {len(obs)} observations") for o in obs: print(" -", o) if __name__ == "__main__": main()