"""KV-cache quantization benchmark (mlx_lm Python API). Needs the GPU. For each model: load once, warm up each KV setting once (discarded), then for each haystack variant ("block") and context length, run fp16 / kv8 / kv4 in a random order. Each run is a fresh prompt cache + stream_generate (greedy, max_tokens=128), timing prefill (TTFT) and decode separately and reading peak memory per phase. Drift check: the fp16 run's first 64 greedy tokens are teacher-forced through the kv8/kv4 caches, starting from the same post-prefill state (the prompt KV is kept, decode-time KV is trimmed, and the linear-attention state is restored from a snapshot taken at the end of prefill). Forcing uses mlx_lm's own generate_step with a sampler that returns the forced token, so it goes through the same decode path as normal generation. Writes results/runs.csv, results/drift.csv, results/outputs.jsonl, results/thermal.jsonl, results/env.json, results/models.json. python bench.py --dry-run # check the plan and prompts, no MLX import python bench.py --deadline # real run; stops starting runs past deadline """ import argparse import csv import gc import json import platform import random import subprocess import sys import time import numpy as np from common import (DRIFT_TOKENS, DATA, KV_GROUP_SIZE, KV_SETTINGS, MAX_TOKENS, MODELS, N_VARIANTS, QUANTIZED_KV_START, RESULTS, arch_summary, kv_theoretical_bytes, revision, snapshot_dir) from drift import kl_and_top1 from haystack import score_recall RUN_FIELDS = ["model", "context", "variant", "kv", "order_in_block", "n_prompt_tokens", "n_gen_tokens", "finish", "ttft_s", "prefill_tps", "decode_s", "decode_tps", "mlx_prompt_tps", "mlx_generation_tps", "peak_prefill_gb", "peak_decode_gb", "peak_gb", "weights_gb", "peak_minus_weights_gb", "kv_cache_gb", "linear_state_gb", "kv_theory_gb", "recall", "started_at", "error"] DRIFT_FIELDS = ["model", "context", "variant", "kv", "token_idx", "ref_token", "kl_nats", "top1_match"] GB = 1e9 mx = None # imported lazily so --dry-run works without Metal def sh(cmd, timeout=20): try: r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) return (r.stdout + r.stderr).strip() except Exception as e: # noqa: BLE001 return f"unavailable: {e}" def thermal_snapshot(tag): # powermetrics needs root; we try non-interactive sudo and record the failure if any. return {"t": time.time(), "tag": tag, "pmset_therm": sh(["pmset", "-g", "therm"]), "powermetrics_thermal": sh(["sudo", "-n", "powermetrics", "--samplers", "thermal", "-n", "1", "-i", "500"])} def environment(): import mlx_lm import transformers try: dev = {k: (v if isinstance(v, (int, str)) else str(v)) for k, v in mx.device_info().items()} except Exception as e: # noqa: BLE001 dev = {"error": str(e)} return { "machine": {"hw.model": sh(["sysctl", "-n", "hw.model"]), "cpu": sh(["sysctl", "-n", "machdep.cpu.brand_string"]), "memsize_bytes": sh(["sysctl", "-n", "hw.memsize"]), "mlx_device_info": dev}, "os": {"sw_vers": sh(["sw_vers"]), "uname": platform.uname()._asdict(), "power_settings": sh(["pmset", "-g"]), "battery": sh(["pmset", "-g", "batt"])}, "software": {"python": sys.version, "mlx": mx.__version__, "mlx_lm": mlx_lm.__version__, "numpy": np.__version__, "transformers": transformers.__version__}, "models": {k: {"repo": r, "revision": revision(r)} for k, (r, _, _) in MODELS.items()}, "settings": {"kv_group_size": KV_GROUP_SIZE, "quantized_kv_start": QUANTIZED_KV_START, "max_tokens": MAX_TOKENS, "drift_tokens": DRIFT_TOKENS, "sampler": "greedy (argmax)", "prefill_step_size": 2048, "chat_template": "enable_thinking=False"}, } # ---------------------------------------------------------------- cache helpers def cache_types(): from mlx_lm.models.cache import ArraysCache, KVCache, QuantizedKVCache return ArraysCache, KVCache, QuantizedKVCache def cache_bytes(cache): ArraysCache, _, _ = cache_types() kv = sum(c.nbytes for c in cache if not isinstance(c, ArraysCache)) lin = sum(c.nbytes for c in cache if isinstance(c, ArraysCache)) return kv, lin def rewind(cache, arrays_snapshot, n_tokens): """Return the cache to its state after prefilling n_tokens prompt tokens.""" ArraysCache, _, _ = cache_types() for i, c in enumerate(cache): if isinstance(c, ArraysCache): c.cache = list(arrays_snapshot[i]) else: c.trim(c.offset - n_tokens) def _host(x): name = str(x.dtype).split(".")[-1] if x.dtype in (mx.bfloat16, mx.float16): x = x.astype(mx.float32) # lossless; numpy has no bf16 return np.array(x), name def _device(h): a, name = h return mx.array(a).astype(getattr(mx, name)) def offload(cache): """Copy a (rewound) cache to host numpy so it does not count toward MLX memory.""" ArraysCache, KVCache, QuantizedKVCache = cache_types() out = [] for c in cache: if isinstance(c, ArraysCache): out.append(("arrays", [None if x is None else _host(x) for x in c.cache])) elif isinstance(c, QuantizedKVCache): k, v = c.state out.append(("qkv", c.group_size, c.bits, c.offset, [_host(x) for x in k], [_host(x) for x in v])) else: k, v = c.state out.append(("kv", _host(k), _host(v))) return out def restore(host): ArraysCache, KVCache, QuantizedKVCache = cache_types() cache = [] for e in host: if e[0] == "arrays": c = ArraysCache(size=len(e[1])) c.cache = [None if h is None else _device(h) for h in e[1]] elif e[0] == "qkv": _, gs, bits, off, k, v = e c = QuantizedKVCache(group_size=gs, bits=bits) c.keys, c.values, c.offset = tuple(map(_device, k)), tuple(map(_device, v)), off else: c = KVCache() c.state = (_device(e[1]), _device(e[2])) cache.append(c) mx.eval([c.state for c in cache]) return cache # ---------------------------------------------------------------- runs def free_run(model, tok, ids, kv_bits, max_tokens): """One measured generation. Returns metrics, generated tokens, their logprobs, and the cache + linear-state snapshot needed to rewind to end-of-prefill.""" from mlx_lm import stream_generate from mlx_lm.models.cache import make_prompt_cache ArraysCache, _, _ = cache_types() cache = make_prompt_cache(model) n = len(ids) snap = {} def progress(done, total): # called after each prefill chunk is evaluated; at total-1 the cache holds prompt[:-1] if done == total - 1 and not snap: snap.update({i: list(c.cache) for i, c in enumerate(cache) if isinstance(c, ArraysCache)}) gc.collect() mx.synchronize() mx.clear_cache() mx.reset_peak_memory() tokens, logprobs, last = [], [], None t0 = time.perf_counter() t_first = None peak_prefill = None for i, r in enumerate(stream_generate(model, tok, prompt=ids, max_tokens=max_tokens, prompt_cache=cache, kv_bits=kv_bits, kv_group_size=KV_GROUP_SIZE, quantized_kv_start=QUANTIZED_KV_START, prompt_progress_callback=progress)): if i == 0: t_first = time.perf_counter() peak_prefill = mx.get_peak_memory() mx.reset_peak_memory() tokens.append(r.token) if len(logprobs) < DRIFT_TOKENS: logprobs.append(r.logprobs) # keep refs only; host copy happens after timing last = r mx.synchronize() t_end = time.perf_counter() peak_decode = mx.get_peak_memory() kv_b, lin_b = cache_bytes(cache) ttft = t_first - t0 dec_s = t_end - t_first m = {"n_prompt_tokens": n, "n_gen_tokens": len(tokens), "finish": last.finish_reason, "ttft_s": ttft, "prefill_tps": n / ttft, "decode_s": dec_s, "decode_tps": (len(tokens) - 1) / dec_s if len(tokens) > 1 and dec_s > 0 else float("nan"), "mlx_prompt_tps": last.prompt_tps, "mlx_generation_tps": last.generation_tps, "peak_prefill_gb": peak_prefill / GB, "peak_decode_gb": peak_decode / GB, "peak_gb": max(peak_prefill, peak_decode) / GB, "kv_cache_gb": kv_b / GB, "linear_state_gb": lin_b / GB} lp_host = np.stack([np.array(lp.astype(mx.float32)) for lp in logprobs]) return m, tokens, lp_host, cache, snap def forced_logprobs(model, cache, last_prompt_token, forced, kv_bits): """Teacher-force `forced` from a rewound cache via generate_step; returns [T, vocab].""" from mlx_lm.generate import generate_step k = [0] def sampler(_logprobs): t = forced[min(k[0], len(forced) - 1)] k[0] += 1 return mx.array([t], dtype=mx.uint32) out = [] for tok_id, lp in generate_step(mx.array([last_prompt_token]), model, prompt_cache=cache, max_tokens=len(forced), sampler=sampler, kv_bits=kv_bits, kv_group_size=KV_GROUP_SIZE, quantized_kv_start=QUANTIZED_KV_START): out.append(np.array(lp.astype(mx.float32))) assert tok_id == forced[len(out) - 1], "forced token mismatch" return np.stack(out) def drift_selftest(model, tok, ids, n=16): """Exercise rewind / offload / restore / forcing on a short prompt (not reported as a result). fp16-forced vs fp16-free should give KL ~ 0 if the machinery is right.""" _, toks, lp, cache, snap = free_run(model, tok, ids, None, n) rewind(cache, snap, len(ids) - 1) kl_self, _ = kl_and_top1(lp, forced_logprobs(model, cache, ids[-1], toks, None)) _, _, _, cache, snap = free_run(model, tok, ids, 4, n) rewind(cache, snap, len(ids) - 1) kl4, top1 = kl_and_top1(lp, forced_logprobs(model, restore(offload(cache)), ids[-1], toks, 4)) return {"fp16_self_max_kl": float(kl_self.max()), "kv4_mean_kl": float(kl4.mean()), "kv4_top1": float(top1.mean()), "tokens": len(toks)} # ---------------------------------------------------------------- driver def load_prompts(key): return json.loads((DATA / f"prompts_{key}.json").read_text()) def plan(models, variants, seed): """Variant-major blocks so a time overrun loses whole variants, not whole contexts.""" rng = random.Random(seed) blocks = [] for key in models: for v in range(variants): runs = [] for ctx in MODELS[key][1]: order = list(KV_SETTINGS) rng.shuffle(order) runs.append((ctx, order)) blocks.append({"model": key, "variant": v, "runs": runs}) return blocks class Writer: def __init__(self, path, fields): new = not path.exists() self.f = open(path, "a", newline="") self.w = csv.DictWriter(self.f, fieldnames=fields, extrasaction="ignore") if new: self.w.writeheader() def row(self, d): self.w.writerow(d) self.f.flush() def main(): ap = argparse.ArgumentParser() ap.add_argument("--models", nargs="+", default=list(MODELS)) ap.add_argument("--variants", type=int, default=N_VARIANTS) ap.add_argument("--seed", type=int, default=7) ap.add_argument("--cooldown", type=float, default=20.0) ap.add_argument("--deadline", type=float, default=time.time() + 36 * 60, help="unix time after which no new runs are started") ap.add_argument("--dry-run", action="store_true") a = ap.parse_args() blocks = plan(a.models, a.variants, a.seed) prompts = {k: load_prompts(k) for k in a.models} index = {(p["model"], p["context"], p["variant"]): p for k in a.models for p in prompts[k]["prompts"]} for b in blocks: for ctx, order in b["runs"]: p = index[(b["model"], ctx, b["variant"])] assert ctx - 64 < p["n_tokens"] <= ctx, (ctx, p["n_tokens"]) if a.dry_run: for b in blocks: print(b["model"], "variant", b["variant"], [(c, o) for c, o in b["runs"]]) for k in a.models: r = MODELS[k][0] print(k, revision(r), arch_summary(r)) for ctx in MODELS[k][1]: print(f" {ctx}: theory KV GB fp16/kv8/kv4 =", [round(kv_theoretical_bytes(r, ctx, b) / GB, 3) for b in KV_SETTINGS.values()]) print(f"dry run OK: {sum(len(b['runs']) * 3 for b in blocks)} measured runs planned") return global mx import mlx.core as _mx mx = _mx from mlx_lm import load RESULTS.mkdir(exist_ok=True) (RESULTS / "env.json").write_text(json.dumps(environment(), indent=2)) runs_w = Writer(RESULTS / "runs.csv", RUN_FIELDS) drift_w = Writer(RESULTS / "drift.csv", DRIFT_FIELDS) outputs = open(RESULTS / "outputs.jsonl", "a") thermal = open(RESULTS / "thermal.jsonl", "a") drift_errors = open(RESULTS / "drift_errors.jsonl", "a") models_meta = {} last_dur = {} def log_thermal(tag): thermal.write(json.dumps(thermal_snapshot(tag)) + "\n") thermal.flush() def drift(key, ctx, v, kvname, ref_tokens, ref_lp, test_lp): kl, top1 = kl_and_top1(ref_lp, test_lp) for i in range(len(kl)): drift_w.row({"model": key, "context": ctx, "variant": v, "kv": kvname, "token_idx": i, "ref_token": ref_tokens[i], "kl_nats": float(kl[i]), "top1_match": int(top1[i])}) print(f" drift {kvname}: mean KL {kl.mean():.4g} max {kl.max():.4g} top1 {top1.mean():.3f}") for key in a.models: repo = MODELS[key][0] print(f"== loading {key} {repo}", flush=True) log_thermal(f"{key}:before_load") t = time.perf_counter() model, tok = load(str(snapshot_dir(repo))) mx.synchronize() mx.clear_cache() weights = mx.get_active_memory() models_meta[key] = {"repo": repo, "revision": revision(repo), "load_s": time.perf_counter() - t, "weights_active_gb": weights / GB, "arch": arch_summary(repo)} print(f" weights {weights / GB:.2f} GB", flush=True) warm = load_prompts(key)["warmup"] for kvname, bits in KV_SETTINGS.items(): # discarded: Metal kernel compile + warm-up m, *_ = free_run(model, tok, warm["ids"], bits, 16) print(f" warm-up {kvname}: ttft {m['ttft_s']:.2f}s", flush=True) _ = None try: models_meta[key]["selftest"] = drift_selftest(model, tok, warm["ids"]) except Exception as e: # noqa: BLE001 models_meta[key]["selftest"] = {"error": f"{type(e).__name__}: {e}"} print(f" drift self-test (1k prompt): {models_meta[key]['selftest']}", flush=True) gc.collect() mx.clear_cache() for b in [b for b in blocks if b["model"] == key]: v = b["variant"] log_thermal(f"{key}:v{v}:before") for ctx, order in b["runs"]: p = index[(key, ctx, v)] ids = p["ids"] ref = None # (tokens, logprobs) from the fp16 run pending = {} # kv name -> offloaded rewound cache, waiting for ref for j, kvname in enumerate(order): bits = KV_SETTINGS[kvname] row = {"model": key, "context": ctx, "variant": v, "kv": kvname, "order_in_block": j, "weights_gb": weights / GB, "kv_theory_gb": kv_theoretical_bytes(repo, len(ids), bits) / GB, "started_at": time.time()} est = last_dur.get((key, ctx), 0) if time.time() + est > a.deadline: row["error"] = "skipped: time budget" runs_w.row(row) print(f" skip {key} {ctx} v{v} {kvname} (time budget)") continue t_run = time.time() try: m, toks, lp, cache, snap = free_run(model, tok, ids, bits, MAX_TOKENS) except Exception as e: # noqa: BLE001 row["error"] = f"{type(e).__name__}: {e}" runs_w.row(row) print(f" ERROR {key} {ctx} v{v} {kvname}: {e}", flush=True) gc.collect() mx.clear_cache() continue text = tok.decode(toks, skip_special_tokens=True) rec = score_recall(text, p["needles"]) row.update(m, recall=rec["correct"], peak_minus_weights_gb=m["peak_decode_gb"] - weights / GB) runs_w.row(row) outputs.write(json.dumps({"model": key, "context": ctx, "variant": v, "kv": kvname, "tokens": toks, "text": text, "recall": rec}) + "\n") outputs.flush() print(f" {key} {ctx} v{v} {kvname}: ttft {m['ttft_s']:.1f}s " f"prefill {m['prefill_tps']:.0f} tok/s decode {m['decode_tps']:.1f} tok/s " f"peak {m['peak_gb']:.2f} GB kv {m['kv_cache_gb']:.3f} GB recall {rec['correct']}/5", flush=True) # ---- drift (not timed) try: rewind(cache, snap, len(ids) - 1) if kvname == "fp16": n_f = min(DRIFT_TOKENS, len(toks)) ref = (toks[:n_f], lp[:n_f]) # self-check: forcing through fp16 should reproduce the free run (KL ~ 0) test = forced_logprobs(model, cache, ids[-1], ref[0], None) drift(key, ctx, v, "fp16", ref[0], ref[1], test) del cache for name, host in pending.items(): c2 = restore(host) test = forced_logprobs(model, c2, ids[-1], ref[0], KV_SETTINGS[name]) drift(key, ctx, v, name, ref[0], ref[1], test) del c2 pending.clear() elif ref is not None: test = forced_logprobs(model, cache, ids[-1], ref[0], bits) drift(key, ctx, v, kvname, ref[0], ref[1], test) del cache else: pending[kvname] = offload(cache) del cache except Exception as e: # noqa: BLE001 drift_errors.write(json.dumps({"model": key, "context": ctx, "variant": v, "kv": kvname, "error": f"{type(e).__name__}: {e}"}) + "\n") drift_errors.flush() print(f" DRIFT ERROR {key} {ctx} v{v} {kvname}: {e}", flush=True) cache = snap = None gc.collect() mx.clear_cache() last_dur[(key, ctx)] = time.time() - t_run if pending: print(f" no fp16 reference for {list(pending)} at {key} {ctx} v{v}; drift not computed") log_thermal(f"{key}:v{v}:after") if time.time() + a.cooldown < a.deadline: time.sleep(a.cooldown) (RESULTS / "models.json").write_text(json.dumps(models_meta, indent=2)) del model, tok gc.collect() mx.clear_cache() (RESULTS / "models.json").write_text(json.dumps(models_meta, indent=2)) print("bench done") if __name__ == "__main__": main()