"""Turn results/*.csv into results.json (medians, min-max, raw samples, observations). python aggregate.py [--results results] [--out results.json] """ import argparse import csv import json import statistics from collections import defaultdict from pathlib import Path from common import (HERE, KV_GROUP_SIZE, KV_SETTINGS, MODELS, QUANTIZED_KV_START, arch_summary, kv_theoretical_bytes) QUESTION = ("On a 64 GB M3 Max, how much memory and speed does mlx_lm's 8-bit and 4-bit KV-cache " "quantization (kv_bits) save at 8k, 16k and 32k tokens, and does it cost needle recall or " "change model outputs versus the default fp16 cache, on Qwen3.8-27B-4bit (dense) and " "Qwen3.6-35B-A3B-4bit (MoE)?") RUN_METRICS = { # csv column -> (unit, note) "peak_gb": ("GB", "mx.get_peak_memory() over the whole run (weights + KV + activations + allocator cache)"), "peak_prefill_gb": ("GB", "peak memory from start until the first token"), "peak_decode_gb": ("GB", "peak memory after the first token (peak reset at first token)"), "peak_minus_weights_gb": ("GB", "decode-phase peak minus active memory right after model load"), "kv_cache_gb": ("GB", "measured nbytes of the full-attention KV caches at end of run (incl. 256-token allocation padding)"), "linear_state_gb": ("GB", "measured nbytes of the linear-attention (Gated DeltaNet) state; constant in context length"), "kv_theory_gb": ("GB", "full-attention layers x kv_heads x head_dim x prompt tokens x 2 x bytes/elem (quantized: bits/8 + 4/group_size)"), "prefill_tps": ("tokens/s", "prompt tokens / time to first token"), "ttft_s": ("s", "time to first token (prefill of the full prompt + first sampled token)"), "decode_tps": ("tokens/s", "(generated tokens - 1) / time from first to last token"), "n_gen_tokens": ("tokens", "generated tokens (greedy, max 128, stops at EOS)"), "recall": ("needles (of 5)", "exact-match needle values in the answer"), } def f(x): try: return float(x) except (TypeError, ValueError): return None def summary(samples, unit, note): s = [x for x in samples if x is not None] if not s: return {"value": None, "unit": unit, "samples": [], "note": note + "; no successful samples"} return {"value": round(statistics.median(s), 6), "unit": unit, "samples": [round(x, 6) for x in s], "min": round(min(s), 6), "max": round(max(s), 6), "note": f"{note}; median of n={len(s)} haystack variants, min-max {min(s):.4g}-{max(s):.4g}"} def read_csv(p): return list(csv.DictReader(open(p))) if p.exists() else [] def ctxk(ctx): return f"{int(ctx) // 1024}k" def aggregate(res: Path): runs = read_csv(res / "runs.csv") drift = read_csv(res / "drift.csv") env = json.loads((res / "env.json").read_text()) if (res / "env.json").exists() else {} models_meta = json.loads((res / "models.json").read_text()) if (res / "models.json").exists() else {} ok = [r for r in runs if not r.get("error")] failed = [r for r in runs if r.get("error")] by = defaultdict(list) # (model, ctx, kv) -> rows sorted by variant for r in ok: by[(r["model"], int(r["context"]), r["kv"])].append(r) for v in by.values(): v.sort(key=lambda r: int(r["variant"])) metrics = {} cells = sorted({(m, c) for m, c, _ in by}, key=lambda x: (x[0], x[1])) for (m, c) in cells: for kv in KV_SETTINGS: rows = by.get((m, c, kv), []) for col, (unit, note) in RUN_METRICS.items(): metrics[f"{col}__{m}__{ctxk(c)}__{kv}"] = summary([f(r[col]) for r in rows], unit, note) # paired changes vs fp16 on the same haystack variant if kv == "fp16": continue base = {r["variant"]: r for r in by.get((m, c, "fp16"), [])} for col, label in [("peak_gb", "peak memory"), ("peak_decode_gb", "decode-phase peak memory"), ("peak_prefill_gb", "prefill-phase peak memory"), ("prefill_tps", "prefill throughput"), ("decode_tps", "decode throughput"), ("ttft_s", "time to first token")]: pct = [100 * (f(r[col]) / f(base[r["variant"]][col]) - 1) for r in rows if r["variant"] in base and f(r[col]) and f(base[r["variant"]][col])] metrics[f"{col}_change_pct__{m}__{ctxk(c)}__{kv}"] = summary( pct, "%", f"{label} vs fp16 cache on the same haystack variant (negative = lower)") gb = [f(r["peak_gb"]) - f(base[r["variant"]]["peak_gb"]) for r in rows if r["variant"] in base] metrics[f"peak_gb_change__{m}__{ctxk(c)}__{kv}"] = summary( gb, "GB", "peak memory minus fp16-cache peak on the same haystack variant") gb = [f(r["peak_decode_gb"]) - f(base[r["variant"]]["peak_decode_gb"]) for r in rows if r["variant"] in base] metrics[f"peak_decode_gb_change__{m}__{ctxk(c)}__{kv}"] = summary( gb, "GB", "decode-phase peak minus fp16-cache decode-phase peak on the same haystack variant") # drift: per (model, ctx, kv), one sample per variant = mean/max KL and top-1 % over forced tokens dg = defaultdict(lambda: defaultdict(list)) for d in drift: dg[(d["model"], int(d["context"]), d["kv"])][d["variant"]].append(d) for (m, c, kv), per_v in sorted(dg.items()): means, maxes, top1, ntok = [], [], [], [] for v, rows in sorted(per_v.items()): kls = [float(r["kl_nats"]) for r in rows] means.append(statistics.fmean(kls)) maxes.append(max(kls)) top1.append(100 * statistics.fmean(int(r["top1_match"]) for r in rows)) ntok.append(len(rows)) extra = (" (self-check: fp16 cache re-forced on its own tokens, expected ~0)" if kv == "fp16" else "") metrics[f"kl_mean__{m}__{ctxk(c)}__{kv}"] = summary(means, "nats", "mean per-token KL(fp16 || this cache) over teacher-forced fp16 greedy tokens" + extra) metrics[f"kl_max__{m}__{ctxk(c)}__{kv}"] = summary(maxes, "nats", "max per-token KL(fp16 || this cache)" + extra) metrics[f"top1_agreement__{m}__{ctxk(c)}__{kv}"] = summary(top1, "%", "share of teacher-forced positions where argmax matches the fp16 cache" + extra) metrics[f"forced_tokens__{m}__{ctxk(c)}__{kv}"] = summary(ntok, "tokens", f"teacher-forced tokens per prompt (fp16 greedy continuation, <= 64; shorter if EOS came first)") for m, meta in models_meta.items(): metrics[f"weights_active_gb__{m}"] = {"value": round(meta["weights_active_gb"], 4), "unit": "GB", "samples": [meta["weights_active_gb"]], "note": "mx.get_active_memory() right after load (weights-only baseline)"} metrics[f"load_s__{m}"] = {"value": round(meta["load_s"], 2), "unit": "s", "samples": [meta["load_s"]], "note": "model load time (from local HF cache)"} for m, (repo, ctxs, _) in MODELS.items(): a = arch_summary(repo) metrics[f"full_attention_layers__{m}"] = {"value": a["full_attention_layers"], "unit": "layers", "samples": [a["full_attention_layers"]], "note": f"of {a['num_hidden_layers']} layers; the rest are linear-attention layers with a fixed-size state (from config.json)"} for c in ctxs: naive = kv_theoretical_bytes(repo, c, None, all_layers=True) / 1e9 metrics[f"kv_theory_if_all_layers_full_attention_gb__{m}__{ctxk(c)}__fp16"] = { "value": round(naive, 4), "unit": "GB", "samples": [naive], "note": "what a naive layers x kv_heads x head_dim x tokens estimate gives if every layer had a KV cache (not true for these hybrid models)"} return runs, ok, failed, metrics, env, models_meta, drift def overlap(metrics, a, b): ma, mb = metrics.get(a), metrics.get(b) if not ma or not mb or ma["value"] is None or mb["value"] is None: return None return not (ma["max"] < mb["min"] or mb["max"] < ma["min"]) def observations(metrics, ok, failed, models_meta, drift): obs = [] g = lambda k: (metrics.get(k) or {}).get("value") # noqa: E731 for m, (repo, ctxs, label) in MODELS.items(): a = arch_summary(repo) obs.append(f"{label}: {a['full_attention_layers']} of {a['num_hidden_layers']} layers are full attention " f"with {a['num_key_value_heads']} KV heads x head_dim {a['head_dim']}; only these layers have a KV cache " f"that kv_bits can quantize.") for c in ctxs: k = ctxk(c) if g(f"peak_gb__{m}__{k}__fp16") is None: continue p = {kv: g(f"peak_gb__{m}__{k}__{kv}") for kv in KV_SETTINGS} pd = {kv: g(f"peak_decode_gb__{m}__{k}__{kv}") for kv in KV_SETTINGS} kvm = {kv: g(f"kv_cache_gb__{m}__{k}__{kv}") for kv in KV_SETTINGS} obs.append(f"{label} {k}: median peak memory fp16 {p['fp16']:.2f} GB, kv8 {p['kv8'] or float('nan'):.2f} GB, " f"kv4 {p['kv4'] or float('nan'):.2f} GB (decode-phase peak {pd['fp16']:.2f} / " f"{pd['kv8'] or float('nan'):.2f} / {pd['kv4'] or float('nan'):.2f} GB); measured KV cache " f"{kvm['fp16']:.3f} / {kvm['kv8'] or float('nan'):.3f} / {kvm['kv4'] or float('nan'):.3f} GB.") for col, name in [("prefill_tps", "prefill"), ("decode_tps", "decode")]: vals = {kv: g(f"{col}__{m}__{k}__{kv}") for kv in KV_SETTINGS} if vals["fp16"] is None: continue parts = [] for kv in ("kv8", "kv4"): if vals[kv] is None: continue ov = overlap(metrics, f"{col}__{m}__{k}__fp16", f"{col}__{m}__{k}__{kv}") chg = g(f"{col}_change_pct__{m}__{k}__{kv}") chg = f"{chg:+.1f}%" if chg is not None else "n/a" parts.append(f"{kv} {vals[kv]:.1f} ({chg} paired" f"{', ranges overlap with fp16' if ov else ', ranges do not overlap'})") obs.append(f"{label} {k}: median {name} fp16 {vals['fp16']:.1f} tok/s; " + "; ".join(parts) + ".") rec = {kv: [int(float(r["recall"])) for r in ok if r["model"] == m and int(r["context"]) == c and r["kv"] == kv] for kv in KV_SETTINGS} obs.append(f"{label} {k}: needle recall (sum over variants, of 5 each) fp16 {sum(rec['fp16'])}/{5 * len(rec['fp16'])}, " f"kv8 {sum(rec['kv8'])}/{5 * len(rec['kv8'])}, kv4 {sum(rec['kv4'])}/{5 * len(rec['kv4'])}.") for kv in ("kv8", "kv4"): if g(f"kl_mean__{m}__{k}__{kv}") is not None: obs.append(f"{label} {k} {kv}: median mean KL {g(f'kl_mean__{m}__{k}__{kv}'):.4g} nats, " f"median max KL {g(f'kl_max__{m}__{k}__{kv}'):.4g} nats, top-1 agreement " f"{g(f'top1_agreement__{m}__{k}__{kv}'):.1f}% vs fp16 cache.") if g(f"kl_max__{m}__{k}__fp16") is not None: obs.append(f"{label} {k}: drift self-check (fp16 vs fp16 re-forced) max KL {g(f'kl_max__{m}__{k}__fp16'):.3g} nats.") if failed: obs.append(f"{len(failed)} planned runs did not complete: " + "; ".join(sorted({r['error'][:80] for r in failed}))) return obs def main(): ap = argparse.ArgumentParser() ap.add_argument("--results", default=str(HERE / "results")) ap.add_argument("--out", default=str(HERE / "results.json")) a = ap.parse_args() res = Path(a.results) runs, ok, failed, metrics, env, models_meta, drift = aggregate(res) variants = sorted({r["variant"] for r in ok}) thermal = [json.loads(line) for line in open(res / "thermal.jsonl")] if (res / "thermal.jsonl").exists() else [] pm_ok = any(not t["powermetrics_thermal"].startswith(("unavailable", "sudo")) and "password" not in t["powermetrics_thermal"] for t in thermal) caveats = [ "Both models are hybrid (Gated DeltaNet linear attention in 3 of every 4 layers); kv_bits only affects the full-attention layers, so savings are much smaller than for a model where every layer has a KV cache. 'Dense' refers to the MLP (no experts), not to the attention layout.", "Peak memory (mx.get_peak_memory) includes weights, activations and transient buffers, not just the KV cache; the KV cache is also reported separately (measured nbytes and theoretical size).", "mlx_lm quantized attention is implemented as quantized_matmul + softmax + quantized_matmul (scores are materialized), while the fp16 path uses fused mx.fast.scaled_dot_product_attention; prefill-phase memory and speed reflect that implementation in this mlx_lm version.", f"kv_group_size={KV_GROUP_SIZE}, quantized_kv_start={QUANTIZED_KV_START}, prefill_step_size=2048: with quantized_kv_start=0 the cache is converted after the first 2048-token prefill chunk, and all later chunks attend to quantized K/V.", "Synthetic needle retrieval in fake logs is a recall stress test, not a quality benchmark; exact-match scoring on 5 needles per prompt.", f"n={len(variants)} haystack variants per cell; differences smaller than the min-max spread should not be read as real.", "Decode throughput is measured over the model's actual answer (stops at EOS, typically well under 128 tokens), so it reflects short generations right after a long prefill.", "KL is computed from the model's bf16 logits renormalised in float64; the fp16 self-check row shows the noise floor of the measurement path.", "The linear-attention state snapshot (tens to ~150 MB) is held during decode in every run (all KV settings equally), so decode-phase peaks include it.", "Thinking disabled via the chat template (enable_thinking=False) for all runs.", ] if not pm_ok: caveats.append("powermetrics thermal sampling was not available (needs root); thermal state was logged with `pmset -g therm` only (see results/thermal.jsonl).") if failed: caveats.append(f"{len(failed)} of {len(runs)} planned runs did not complete (time budget or error); see results/runs.csv 'error' column.") st = {m: meta.get("selftest") for m, meta in models_meta.items()} out = { "question": QUESTION, "environment": env, "runs": len(variants), "metrics": metrics, "observations": observations(metrics, ok, failed, models_meta, drift), "caveats": caveats, "drift_selftest_1k_prompt": st, "raw_files": ["results/runs.csv", "results/drift.csv", "results/outputs.jsonl", "results/thermal.jsonl", "results/env.json", "results/models.json", "data/prompts_moe.json", "data/prompts_dense.json"], } Path(a.out).write_text(json.dumps(out, indent=2)) print(f"wrote {a.out}: {len(metrics)} metrics, {len(ok)} ok runs, {len(failed)} failed/skipped") if __name__ == "__main__": main()