"""raw/*.jsonl + raw/env.json -> results.json. Pure Python, no MLX needed. Metric names: ..[.] Every value is a median; samples are kept so readers can recompute. """ import argparse import glob import json import os import statistics QUESTION = ("When an agent sends the same long system prompt on every turn, how much " "time-to-first-token on an M3 Max goes away if MLX reuses a saved prompt cache " "(in-memory copy, disk file, or mlx_lm.server's automatic cache), and is the saving " "smaller on a hybrid MoE model (Qwen3.6-35B-A3B 4-bit) than on a dense " "sliding-window model (Gemma 3 12B 4-bit)? Prefixes of 2k, 8k and 16k tokens.") PATHS = ["cold", "mem", "disk_warm", "disk_cold"] def load(raw_dir): recs = [] for fn in sorted(glob.glob(os.path.join(raw_dir, "*.jsonl"))): for line in open(fn): line = line.strip() if line: recs.append(json.loads(line)) return recs def med(xs): return statistics.median(xs) if xs else None def r(x, nd=3): return None if x is None else round(x, nd) class Metrics(dict): def add(self, name, samples, unit, note=""): samples = [s for s in samples if s is not None] if not samples: return None v = med(samples) spread = f"median of n={len(samples)}, min {r(min(samples))}, max {r(max(samples))}" self[name] = {"value": r(v, 4), "unit": unit, "samples": [r(s, 4) for s in samples], "note": f"{spread}. {note}".strip()} return v def add_value(self, name, value, unit, note=""): if value is None: return None self[name] = {"value": r(value, 4), "unit": unit, "samples": [r(value, 4)], "note": note} return value def first_divergence(a, b): for i, (x, y) in enumerate(zip(a, b)): if x != y: return i return None if len(a) == len(b) else min(len(a), len(b)) def summarize(raw_dir): recs = load(raw_dir) env = json.load(open(os.path.join(raw_dir, "env.json"))) if os.path.exists( os.path.join(raw_dir, "env.json")) else {} M, obs, cav = Metrics(), [], [] labels = sorted({x["label"] for x in recs if "label" in x}) runs = [x for x in recs if x.get("phase") == "run"] reps = max([x["rep"] for x in runs], default=-1) + 1 savings = {} for m in labels: mr = [x for x in runs if x["label"] == m] for x in recs: if x.get("label") == m and x.get("phase") == "load": M.add_value(f"weights_gb.{m}", x["weights_gb"], "GB", "MLX active memory after loading weights") M.add_value(f"model_load_s.{m}", x["load_s"], "s") if x.get("label") == m and x.get("phase") == "deadline": cav.append(f"{m}: time budget hit, reps from {x['skipped_from_rep']} on were skipped " f"(target {x.get('target', 'all')}).") targets = sorted({x["target"] for x in mr}) for L in targets: cell = [x for x in mr if x["target"] == L] k = f"{m}.{L}" pt = cell[0]["prefix_tokens"] M.add_value(f"prefix_tokens.{k}", pt, "tokens", "shared prefix length, model's own tokenizer + chat template") M.add(f"suffix_tokens.{k}", [x["suffix_tokens"] for x in cell if x["path"] == "cold"], "tokens") meds = {} for p in PATHS: xs = [x for x in cell if x["path"] == p] meds[p] = M.add(f"ttft_ms.{k}.{p}", [x["ttft_ms"] for x in xs], "ms", {"cold": "full prompt, no cache", "mem": "includes deepcopy of the prefilled cache", "disk_warm": "includes load_prompt_cache from page-cached file", "disk_cold": "includes load_prompt_cache from F_NOCACHE copy (verified non-resident)"}[p]) M.add(f"peak_mem_gb.{k}.{p}", [x["peak_gb"] for x in xs], "GB", "mx.get_peak_memory, absolute (includes weights and the in-memory prefix caches held by the harness)") M.add(f"peak_mem_over_start_gb.{k}.{p}", [x["peak_over_base_gb"] for x in xs], "GB", "peak minus active memory at run start") if p != "cold": M.add(f"suffix_ttft_ms.{k}.{p}", [x["gen_ttft_ms"] for x in xs], "ms", "suffix prefill to first token only, excluding copy/load") M.add(f"prefill_tps.{k}.cold", [x["prefill_tps"] for x in cell if x["path"] == "cold"], "tokens/s", "full prompt tokens / cold TTFT") M.add(f"copy_ms.{k}", [x.get("copy_ms") for x in cell if x["path"] == "mem"], "ms", "copy.deepcopy + mx.eval") M.add(f"load_ms.{k}.warm", [x.get("load_ms") for x in cell if x["path"] == "disk_warm"], "ms", "load_prompt_cache + mx.eval, file in page cache") M.add(f"load_ms.{k}.cold", [x.get("load_ms") for x in cell if x["path"] == "disk_cold"], "ms", "load_prompt_cache + mx.eval, fresh F_NOCACHE copy") res = [x.get("resident_before") for x in cell if x["path"] == "disk_cold"] M.add(f"resident_fraction_before_cold_load.{k}", res, "fraction", "mincore() check; 0 means truly cold") if any(v is not None and v > 0.01 for v in res): cav.append(f"{k}: some 'cold disk' files were partly resident ({max(v for v in res if v is not None):.2f}).") if meds["cold"]: for p in PATHS[1:]: if meds[p]: M.add_value(f"speedup_x.{k}.{p}", meds["cold"] / meds[p], "x", "median cold TTFT / median path TTFT") M.add_value(f"ttft_saved_pct.{k}.{p}", 100 * (1 - meds[p] / meds["cold"]), "%") savings[(m, L)] = meds for x in recs: if x.get("phase") == "build" and x["label"] == m and x["target"] == L: M.add_value(f"build_cache_s.{k}", x["build_s"], "s", "one-time prefill of the prefix into make_prompt_cache (n=1)") M.add_value(f"build_cache_tps.{k}", x["build_tps"], "tokens/s") M.add_value(f"save_cache_s.{k}", x["save_s"], "s", "save_prompt_cache") M.add_value(f"cache_file_gb.{k}", x["file_bytes"] / 1e9, "GB", "safetensors file size") M.add_value(f"cache_mem_gb.{k}", x["cache_nbytes"] / 1e9, "GB", "sum of cache .nbytes in memory") M.add_value(f"cache_trimmable.{k}", 1.0 if x["trimmable"] else 0.0, "bool", "can_trim_prompt_cache; classes: " + ",".join(x["cache_classes"])) # Correctness: 64-token greedy sequences, same (rep, q) slot as the cold run. cold = {x["q"]: x["tokens"] for x in cell if x["path"] == "cold" and len(x["tokens"]) > 1} cold_first = {x["q"]: x["first_token"] for x in cell if x["path"] == "cold"} for p in PATHS[1:]: pairs = [(cold[x["q"]], x["tokens"]) for x in cell if x["path"] == p and len(x["tokens"]) > 1 and x["q"] in cold] if pairs: match = [100.0 if a == b else 0.0 for a, b in pairs] M.add_value(f"greedy64_match_pct.{k}.{p}", statistics.mean(match), "%", f"{len(pairs)} sequences of up to 64 greedy tokens vs cold run") div = [first_divergence(a, b) for a, b in pairs] div = [d for d in div if d is not None] if div: M.add(f"greedy64_first_divergence.{k}.{p}", div, "token index", "only sequences that diverged") cav.append(f"{k} {p}: {len(div)}/{len(pairs)} greedy sequences differ from cold " f"(first divergence at token {min(div)}). Flagged, not hidden.") ft = [100.0 if x["first_token"] == cold_first.get(x["q"]) else 0.0 for x in cell if x["path"] == p and x["q"] in cold_first] if ft: M.add_value(f"first_token_match_pct.{k}.{p}", statistics.mean(ft), "%", f"all {len(ft)} runs incl. 1-token repeats") # Server sv = [x for x in recs if x.get("phase") == "server" and x["label"] == m] for L in sorted({x["target"] for x in sv}): xs = sorted([x for x in sv if x["target"] == L], key=lambda x: x["request"]) k = f"{m}.{L}" first = [x["ttft_ms"] for x in xs if x["request"] == 1] rest = [x["ttft_ms"] for x in xs if x["request"] > 1] f = M.add(f"server_ttft_ms.{k}.request1", first, "ms", "client-side, streaming, first request with this system prompt (n=1)") rr = M.add(f"server_ttft_ms.{k}.requests2_10", rest, "ms", "client-side, streaming") if f and rr: M.add_value(f"server_speedup_x.{k}", f / rr, "x", "request 1 / median of requests 2-10") if savings.get((m, L), {}).get("cold") and rr: M.add_value(f"server_speedup_vs_inprocess_cold_x.{k}", savings[(m, L)]["cold"] / rr, "x") M.add(f"server_cached_tokens.{k}.request1", [x["cached_tokens"] for x in xs if x["request"] == 1], "tokens", "usage.prompt_tokens_details.cached_tokens") M.add(f"server_cached_tokens.{k}.requests2_10", [x["cached_tokens"] for x in xs if x["request"] > 1], "tokens") M.add(f"server_prompt_tokens.{k}", [x["prompt_tokens"] for x in xs], "tokens") # Text match vs in-process cold run (same question, greedy). cold_txt = {x["q"]: x.get("text") for x in runs if x["label"] == m and x["target"] == L and x["path"] == "cold" and x.get("text") is not None} tm = [100.0 if x["text"].strip() == cold_txt[x["q"]].strip() else 0.0 for x in xs if x["q"] in cold_txt] if tm: M.add_value(f"server_text_match_pct.{k}", statistics.mean(tm), "%", f"{len(tm)} server responses vs in-process cold greedy text (64 tokens)") # Observations, straight from the numbers above. for (m, L), meds in sorted(savings.items()): c = meds["cold"] parts = [f"{p} {meds[p]:.0f} ms ({c / meds[p]:.1f}x)" for p in PATHS[1:] if meds.get(p)] obs.append(f"{m} @ {L}-token target: cold TTFT {c:.0f} ms; " + ", ".join(parts) + ".") big = max((L for (_, L) in savings), default=None) if big is not None: sv = {m: 100 * (1 - meds["mem"] / meds["cold"]) for (m, L), meds in savings.items() if L == big and meds.get("mem")} if len(sv) >= 2: obs.append(f"Share of {big}-token-prefix TTFT removed by the in-memory cache: " + ", ".join(f"{m} {v:.1f}%" for m, v in sorted(sv.items())) + ".") for k, v in M.items(): if k.startswith("server_cached_tokens") and k.endswith("requests2_10"): obs.append(f"{k}: median {v['value']} cached tokens reported by the server.") ps = str(env.get("machine", {}).get("power_source", "")) if "Battery" in ps: cav.append(f"Power source at start of run was '{ps}', not AC as the method requires; " "absolute timings may be lower than on AC power.") cav += [ "Cold baseline: 5 runs per cell (one per question); cached paths: 5 questions x 5 repeats " "(disk split into 5 cold-file + 20 warm-file loads). Cold repeats were capped to fit the 40-minute budget.", "Cache build time is a single sample per cell; the cold TTFT samples measure the same prefill repeatedly.", "'Cold disk' uses a copy written with F_NOCACHE (no sudo purge); residency was checked with mincore().", "Absolute peak memory includes the harness's own in-memory prefix caches for all lengths; use the 'over_start' numbers for per-run cost.", "Server numbers are 'what you get by default' with mlx_lm.server's LRU prompt cache (one series of 10 requests per length), not a ceiling.", "The two models differ in size and architecture; compare how much caching helps each, not which is faster.", "Single machine, single session; thermal state and background load can shift absolute numbers.", ] return {"question": QUESTION, "environment": env, "runs": reps, "metrics": M, "observations": obs, "caveats": cav} if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("--raw", default="raw") ap.add_argument("--out", default="results.json") a = ap.parse_args() res = summarize(a.raw) json.dump(res, open(a.out, "w"), indent=1) print(f"wrote {a.out}: {len(res['metrics'])} metrics, {len(res['observations'])} observations")