"""Turn raw/*.json into results.json, plots/*.png and outputs/completions.jsonl.
Usage: python analyze.py # after run.sh's benchmark steps
python analyze.py --selftest # synthetic raw data in a temp dir, checks the pipeline only
"""
import argparse
import difflib
import json
import os
import statistics as st
import tempfile
CONFIGS = {
"A": ("A_mlx_qwen3.8-27b-dense", "MLX (mlx_lm), Qwen3.8-27B dense, mlx-community 4-bit"),
"B": ("B_ollama_qwen3.8-27b-dense", "ollama/llama.cpp, Qwen3.8-27B dense, unsloth UD-Q4_K_XL GGUF"),
"C": ("C_mlx_qwen3.6-35b-a3b-moe", "MLX (mlx_lm), Qwen3.6-35B-A3B MoE (3B active), 4-bit"),
"D": ("D_mlx_lfm2.5-24b-a2b-moe", "MLX (mlx_lm), LFM2.5-24B-A2B MoE (2B active), 4-bit"),
}
CTXS = [512, 4096, 16384]
QUESTION = ("On a 64 GB M3 Max, how much do time-to-first-token and decode speed drop as the prompt "
"grows from 512 to 16k tokens? Does MLX or llama.cpp (via ollama) handle long context "
"better for the same Qwen3.8 27B model? Does a 3B-active MoE (Qwen3.6-35B-A3B) keep its "
"speed lead once the prompt gets long?")
def e2e_256(r):
"""Measured wall time if exactly 256 tokens were decoded, else TTFT + 255 / decode tok/s."""
if r["decode_tokens"] == 256:
return r["wall_s"], False
return r["ttft_s"] + 255 / r["decode_tps"], True
def summ(samples, unit, note):
s = [round(x, 4) for x in samples if x is not None]
if not s:
return None
return {"value": round(st.median(s), 4), "unit": unit, "samples": s,
"min": min(s), "max": max(s), "n": len(s), "note": note}
def pct(a, b):
return round((1 - a / b) * 100, 2)
def analyze(raw_dir, out_path, plot_dir, outputs_path):
raw = {c: json.load(open(f"{raw_dir}/{c}.json")) for c in CONFIGS
if os.path.exists(f"{raw_dir}/{c}.json")}
stats = json.load(open(f"{raw_dir}/model_stats.json")) if os.path.exists(
f"{raw_dir}/model_stats.json") else {}
env = json.load(open(f"{raw_dir}/env.json")) if os.path.exists(f"{raw_dir}/env.json") else {}
M, obs, cav = {}, [], []
med = {} # (cfg, metric, ctx) -> median
if os.path.exists(f"{raw_dir}/failures.txt"):
cav += [l.strip() for l in open(f"{raw_dir}/failures.txt") if l.strip()]
if os.path.exists(f"{raw_dir}/ollama_build_lines.txt"):
env["ollama_server_log_lines"] = [l.rstrip() for l in open(f"{raw_dir}/ollama_build_lines.txt")]
for c, d in raw.items():
name = CONFIGS[c][0]
for ctx in CTXS:
runs = [r for r in d["runs"] if r["ctx"] == ctx]
if not runs:
continue
e2e = [e2e_256(r) for r in runs]
proj = sum(p for _, p in e2e)
rows = {
"ttft_s": (summ([r["ttft_s"] for r in runs], "s",
"wall-clock from request to first streamed token (prefill + 1st token)")),
"prefill_tps": summ([r["prefill_tps"] for r in runs], "tokens/s",
"prompt tokens / TTFT (MLX); prompt_eval_count / prompt_eval_duration (ollama)"),
"decode_tps": summ([r["decode_tps"] for r in runs], "tokens/s",
"(tokens-1)/(t_last-t_first) (MLX); eval_count/eval_duration (ollama)"),
"e2e_256_s": summ([v for v, _ in e2e], "s",
"time to a 256-token answer; measured wall time" +
(f"; {proj}/{len(runs)} runs stopped early (EOS) and are projected as "
"TTFT + 255/decode tok/s" if proj else "")),
"decode_tokens": summ([r["decode_tokens"] for r in runs], "tokens",
"tokens actually generated (MLX bans EOS, so always 256)"),
"prompt_tokens_evaluated": summ([r["prompt_tokens"] for r in runs], "tokens",
"prompt tokens the backend reports it processed"),
}
if d["backend"] == "mlx_lm":
rows["peak_mem_gb"] = summ([r["peak_mem_gb"] for r in runs], "GB",
"mx.get_peak_memory() per run (weights + KV/state + activations)")
for k, v in rows.items():
if v:
M[f"{k}.{name}.ctx{ctx}"] = v
med[(c, k, ctx)] = v["value"]
if (c, "decode_tps", 512) in med and (c, "decode_tps", 16384) in med:
M[f"decode_drop_pct_16k_vs_512.{name}"] = {
"value": pct(med[(c, "decode_tps", 16384)], med[(c, "decode_tps", 512)]), "unit": "%",
"samples": [], "note": "1 - median decode tok/s @16384 / median @512"}
M[f"prefill_tps_drop_pct_16k_vs_512.{name}"] = {
"value": pct(med[(c, "prefill_tps", 16384)], med[(c, "prefill_tps", 512)]), "unit": "%",
"samples": [], "note": "1 - median prefill tok/s @16384 / median @512"}
M[f"ttft_ratio_16k_vs_512.{name}"] = {
"value": round(med[(c, "ttft_s", 16384)] / med[(c, "ttft_s", 512)], 2), "unit": "x",
"samples": [], "note": "median TTFT @16384 / median TTFT @512 (prompt is 32x longer)"}
M[f"load_s.{name}"] = {"value": round(d.get("load_s", 0), 2), "unit": "s", "samples": [],
"note": "model load (MLX: mlx_lm.load; ollama: load_duration of warm-up)"}
lim = [r.get("cpu_speed_limit") for r in d["runs"] if r.get("cpu_speed_limit") is not None]
if lim:
M[f"min_cpu_speed_limit.{name}"] = {"value": min(lim), "unit": "%", "samples": lim,
"note": "pmset -g therm CPU_Speed_Limit before each run (100 = no throttling)"}
if min(lim) < 100:
cav.append(f"{c}: pmset reported CPU_Speed_Limit {min(lim)}% before at least one run "
"(thermal/power limiting).")
if d.get("skipped"):
cav.append(f"{c}: {len(d['skipped'])} timed runs skipped by the 40-minute budget: "
+ ", ".join(f"rep{s['rep']}@{s['ctx']}" for s in d["skipped"]))
if c in stats:
s = stats[c]
M[f"file_size_gb.{name}"] = {"value": round(s["file_gb"], 3), "unit": "GB", "samples": [],
"note": f"on-disk weights ({s['format']})"}
M[f"bpw.{name}"] = {"value": round(s["bpw_all"], 3), "unit": "bits/weight", "samples": [],
"note": "file bytes*8 / logical params (incl. scales/biases)"}
if "bpw_text" in s:
M[f"bpw_text_only.{name}"] = {"value": round(s["bpw_text"], 3), "unit": "bits/weight",
"samples": [], "note": "excluding vision-tower tensors"}
M[f"params_b.{name}"] = {"value": round(s["params_all"] / 1e9, 3), "unit": "billion",
"samples": [], "note": "logical parameters in the file"}
# ollama memory and cache sanity
if "B" in raw:
b = raw["B"]
for m in b.get("ps", {}).get("models", []):
M["ollama_ps_size_gb.B"] = {"value": round(m.get("size", 0) / 1e9, 3), "unit": "GB",
"samples": [], "note": "ollama /api/ps 'size' after warm-up "
"(ollama's allocation estimate at num_ctx 20480, not a measured peak)"}
M["ollama_ps_size_vram_gb.B"] = {"value": round(m.get("size_vram", 0) / 1e9, 3), "unit": "GB",
"samples": [], "note": "ollama /api/ps 'size_vram'"}
sus = [r for r in b["runs"] if r.get("cache_suspect")]
if sus:
cav.append(f"B: {len(sus)} runs evaluated fewer prompt tokens than sent (possible prompt-cache hit): "
+ ", ".join(f"rep{r['rep']}@{r['ctx']}={r['prompt_tokens']}" for r in sus))
early = [r for r in b["runs"] if r["decode_tokens"] < 256]
if early:
cav.append(f"B: {len(early)}/{len(b['runs'])} ollama runs stopped before 256 tokens (EOS can't be "
"disabled via the API); decode tok/s is per-token so still comparable, e2e is projected.")
# cross-config ratios
def ratio(key, x, y, ctx, label, note):
if (x, key, ctx) in med and (y, key, ctx) in med:
M[f"{label}.ctx{ctx}"] = {"value": round(med[(x, key, ctx)] / med[(y, key, ctx)], 3),
"unit": "x", "samples": [], "note": note}
return M[f"{label}.ctx{ctx}"]["value"]
for ctx in CTXS:
for key in ("ttft_s", "decode_tps", "e2e_256_s", "prefill_tps"):
ratio(key, "B", "A", ctx, f"{key}_ratio_ollama_over_mlx",
f"median {key} B (ollama GGUF) / A (MLX 4-bit), same Qwen3.8-27B")
ratio(key, "C", "A", ctx, f"{key}_ratio_moe35b_over_dense27b",
f"median {key} C (Qwen3.6-35B-A3B MoE) / A (Qwen3.8-27B dense), both MLX")
ratio(key, "D", "A", ctx, f"{key}_ratio_lfm24b_over_dense27b",
f"median {key} D (LFM2.5-24B-A2B) / A (Qwen3.8-27B dense), both MLX")
# output sanity
texts = []
for c, d in raw.items():
for r in d["runs"]:
texts.append({"config": c, "rep": r["rep"], "ctx": r["ctx"], "text": r["text"],
"checks": r["checks"]})
if texts:
M["completions_with_bullets_frac"] = {
"value": round(sum(t["checks"]["has_bullets"] for t in texts) / len(texts), 3),
"unit": "fraction", "samples": [], "note": ">=3 lines starting with -, *, • or 1. across all timed runs"}
M["completions_degenerate_count"] = {
"value": sum(t["checks"]["degenerate"] for t in texts), "unit": "runs", "samples": [],
"note": "distinct-word ratio < 0.2 or >20 repeated 8-grams"}
a = [t for t in texts if t["config"] == "A" and t["ctx"] == 512]
b = [t for t in texts if t["config"] == "B" and t["ctx"] == 512]
sims = []
for ta in a:
tb = next((t for t in b if t["rep"] == ta["rep"]), None)
if tb:
n = min(len(ta["text"]), len(tb["text"]))
sims.append(difflib.SequenceMatcher(None, ta["text"][:n], tb["text"][:n]).ratio())
if sims:
M["a_vs_b_text_similarity.ctx512"] = summ(sims, "ratio",
"difflib ratio between A and B completions (same prompt/nonce), "
"compared over the shorter length; 1.0 = identical")
bad = [t for t in texts if not t["checks"]["has_bullets"] or t["checks"]["degenerate"]]
if bad:
cav.append(f"{len(bad)} completions failed the bullet/degeneracy check: "
+ ", ".join(f"{t['config']} rep{t['rep']}@{t['ctx']}" for t in bad[:12]))
os.makedirs(os.path.dirname(outputs_path) or ".", exist_ok=True)
with open(outputs_path, "w") as f:
for t in texts:
f.write(json.dumps(t) + "\n")
# observations: plain statements of measured medians
fmt = lambda c, k, x, f: format(med[(c, k, x)], f) if (c, k, x) in med else "n/a"
for c in raw:
n = CONFIGS[c][0]
if any((c, "ttft_s", x) in med for x in CTXS):
drop = M.get(f"decode_drop_pct_16k_vs_512.{n}", {}).get("value")
obs.append(f"{c} ({CONFIGS[c][1]}): median TTFT " +
" -> ".join(f"{fmt(c, 'ttft_s', x, '.2f')} s @{x}" for x in CTXS) +
" tokens; decode " +
" -> ".join(fmt(c, "decode_tps", x, ".1f") for x in CTXS) + " tok/s" +
(f" ({drop:.1f}% drop 512->16k)." if drop is not None else "."))
for ctx in CTXS:
k = f"ttft_s_ratio_ollama_over_mlx.ctx{ctx}"
if k in M:
dk = M[f"decode_tps_ratio_ollama_over_mlx.ctx{ctx}"]["value"]
obs.append(f"@{ctx} tokens, ollama/MLX median ratio: TTFT {M[k]['value']:.2f}x, decode tok/s {dk:.2f}x "
f"(>1 TTFT = ollama slower; >1 decode = ollama faster).")
for ctx in CTXS:
k = f"e2e_256_s_ratio_moe35b_over_dense27b.ctx{ctx}"
if k in M:
obs.append(f"@{ctx} tokens, MoE C vs dense A: TTFT {M[f'ttft_s_ratio_moe35b_over_dense27b.ctx{ctx}']['value']:.2f}x, "
f"decode tok/s {M[f'decode_tps_ratio_moe35b_over_dense27b.ctx{ctx}']['value']:.2f}x, "
f"256-token answer time {M[k]['value']:.2f}x.")
for c in raw:
n = CONFIGS[c][0]
pk = [M.get(f"peak_mem_gb.{n}.ctx{x}", {}).get("value") for x in CTXS]
if all(pk):
obs.append(f"{c}: MLX peak memory {pk[0]:.1f} GB @512, {pk[2]:.1f} GB @16384.")
cav += [
"Single machine (one M3 Max 64 GB laptop); numbers will differ on other chips, RAM sizes and macOS builds.",
"A vs B is a 'closest available 4-bit' comparison, not a pure engine-vs-engine result: the MLX file is "
"affine 4-bit, group size 64 (~4.5 bpw on text weights) while the only local GGUF is unsloth UD-Q4_K_XL "
"(mixed Q4_K/Q5_K/Q6_K/IQ4, ~5.1 bpw), so llama.cpp reads more bytes per decoded token.",
"Qwen3.8-27B and Qwen3.6-35B-A3B are hybrid models (3 of every 4 layers are linear-attention/DeltaNet "
"with fixed-size state; only every 4th layer has a growing KV cache), so their long-context slowdown is "
"not representative of pure full-attention models. LFM2.5 similarly uses conv layers with 10/40 attention layers.",
"n=3 timed runs per point (after one discarded 512-token warm-up per config); medians with min-max are "
"reported, no significance testing.",
"MLX runs ban EOS to force exactly 256 decoded tokens; ollama cannot, so its token counts are reported per run.",
"Each prompt starts with a unique 4-digit nonce, so at most the first ~3 template tokens could ever be "
"reused from a previous request's cache; MLX uses a fresh cache per call.",
"Thinking disabled: Qwen via enable_thinking=False (empty block); LFM2.5 has no switch, "
"so an empty think block is appended after its template's opening .",
"High Power mode cannot be set from a script; the recorded pmset power-mode lines show what was active.",
"mlx_lm prefill uses prefill_step_size=2048; ollama uses its default batch size. Both are defaults, not tuned.",
"Config B is labelled ollama/llama.cpp, but ollama runs some newer architectures on its own ggml-based "
"Go engine rather than the llama.cpp runner; environment.ollama_server_log_lines records which runner "
"loaded the model, and the post should name it accordingly.",
]
results = {"question": QUESTION, "environment": env | {
"configs": {c: {"key": CONFIGS[c][0], "description": CONFIGS[c][1],
**({"backend_version": raw[c].get("server_version") or raw[c].get("mlx_lm_version"),
"settings": {k: raw[c].get(k) for k in ("options", "server_env", "prefill_step_size",
"sampler", "eos", "kv_cache", "create")
if k in raw[c]},
"thermal_before": raw[c].get("thermal_before", {}).get("raw"),
"thermal_after": raw[c].get("thermal_after", {}).get("raw")}
if c in raw else {"status": "not run"})}
for c in CONFIGS}},
"runs": 3, "metrics": M, "observations": obs, "caveats": cav}
with open(out_path, "w") as f:
json.dump(results, f, indent=1)
plot(raw, med, M, plot_dir)
return results
def plot(raw, med, M, plot_dir):
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
os.makedirs(plot_dir, exist_ok=True)
fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))
panels = [("ttft_s", "Time to first token (s)", True), ("decode_tps", "Decode speed (tok/s)", False),
("e2e_256_s", "Time to a 256-token answer (s)", True)]
for ax, (key, title, logy) in zip(axes, panels):
for c in raw:
name = CONFIGS[c][0]
xs, ys, lo, hi = [], [], [], []
for ctx in CTXS:
m = M.get(f"{key}.{name}.ctx{ctx}")
if m:
xs.append(ctx); ys.append(m["value"])
lo.append(m["value"] - m["min"]); hi.append(m["max"] - m["value"])
if xs:
ax.errorbar(xs, ys, yerr=[lo, hi], marker="o", capsize=3, label=name)
ax.set_xscale("log", base=2)
ax.set_xticks(CTXS, [str(x) for x in CTXS])
if logy:
ax.set_yscale("log")
ax.set_xlabel("prompt length (tokens)")
ax.set_title(title)
ax.grid(alpha=0.3)
axes[0].legend(fontsize=8)
fig.suptitle("M3 Max 64 GB: speed vs context length (median, bars = min-max, n=3)")
fig.tight_layout()
fig.savefig(os.path.join(plot_dir, "speed_vs_context.png"), dpi=150)
def selftest():
"""Feed synthetic numbers through the pipeline. Output is NOT a result; it's deleted after."""
import random
d = tempfile.mkdtemp()
rnd = random.Random(0)
for c, backend in (("A", "mlx_lm"), ("B", "ollama"), ("C", "mlx_lm")):
runs = []
for rep in (1, 2, 3):
for ctx in CTXS:
ttft = ctx / 300 * rnd.uniform(0.95, 1.05)
runs.append({"rep": rep, "ctx": ctx, "ttft_s": ttft, "prefill_tps": ctx / ttft,
"decode_tps": 20 - ctx / 4096, "decode_tokens": 256 if backend == "mlx_lm" else 200,
"wall_s": ttft + 13, "peak_mem_gb": 16 + ctx / 8192, "prompt_tokens": ctx,
"cpu_speed_limit": 100, "text": "- a b c\n- d e\n- f g h", "cache_suspect": False,
"checks": {"has_bullets": True, "degenerate": False}})
json.dump({"backend": backend, "runs": runs, "load_s": 5, "skipped": [],
"ps": {"models": [{"size": 2e10, "size_vram": 2e10}]}}, open(f"{d}/{c}.json", "w"))
r = analyze(d, f"{d}/results.json", f"{d}/plots", f"{d}/completions.jsonl")
assert r["metrics"]["ttft_s.A_mlx_qwen3.8-27b-dense.ctx16384"]["n"] == 3
assert "decode_drop_pct_16k_vs_512.B_ollama_qwen3.8-27b-dense" in r["metrics"]
assert os.path.exists(f"{d}/plots/speed_vs_context.png")
print(f"selftest ok: {len(r['metrics'])} metrics, {len(r['observations'])} observations "
f"(synthetic, in {d})")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--selftest", action="store_true")
args = ap.parse_args()
if args.selftest:
return selftest()
r = analyze("raw", "results.json", "plots", "outputs/completions.jsonl")
print("\n".join(r["observations"]))
print(f"results.json: {len(r['metrics'])} metrics")
if __name__ == "__main__":
main()