# KV-cache quantization in MLX on an M3 Max: memory, speed, recall, drift This benchmark asks how much memory and speed mlx_lm's 8-bit and 4-bit KV-cache quantization (`kv_bits`) saves at 8k, 16k and 32k tokens, and whether it costs needle recall or changes the model's outputs compared with the default fp16/bf16 cache. | model | HF repo @ revision | contexts | |---|---|---| | MoE | `mlx-community/Qwen3.6-35B-A3B-4bit` @ `38740b847e4c…` | 8k, 16k, 32k | | dense | `mlx-community/Qwen3.8-27B-4bit` @ `10c35caafbb8…` | 8k, 16k | KV settings: `fp16` (default cache, `kv_bits=None`), `kv8`, `kv4`. All use `kv_group_size=64`, `quantized_kv_start=0` and mlx_lm's default `prefill_step_size=2048`. ## Read this first: both models are hybrid According to `config.json`, both models use Gated DeltaNet linear attention in 3 of every 4 layers. Only the full-attention layers have a KV cache that grows with context: | | layers | full-attention layers | KV heads × head_dim | fp16 KV at 16k / 32k (theory) | |---|---|---|---|---| | MoE 35B-A3B | 40 | 10 | 2 × 256 | 0.34 / 0.67 GB | | dense 27B | 64 | 16 | 4 × 256 | 1.07 GB / – | `kv_bits` only quantizes those layers. The linear-attention state is a fixed size and is measured separately. "Dense" means the MLP has no experts; the attention layout is the same hybrid as the MoE. ## What is measured (per model × context × KV setting, 3 haystack variants) - Peak unified memory, `mx.get_peak_memory()`, over the whole run and split into a prefill phase and a decode phase. The peak counter is reset at the first token. - Peak minus a weights-only baseline (`mx.get_active_memory()` right after load). - KV-cache size: the measured `nbytes` of the cache objects, plus a theoretical figure (full-attention layers × kv_heads × head_dim × tokens × 2 × bytes/elem; quantized elements cost bits/8 + 4/64 bytes for the bf16 scale and bias). There is also the naive "all layers" figure, to show how far off the usual estimate is for these models. - Prefill throughput (prompt tokens / TTFT), TTFT, and decode throughput (tokens after the first / time from first token to last). - Needle recall: 5 needles per prompt, exact match. - Output drift: the fp16 run's first 64 greedy tokens are teacher-forced through the kv8 and kv4 caches. This gives per-token KL(fp16 ‖ quantized) in nats and top-1 agreement. A fp16-vs-fp16 re-forced row is a self-check and should be about 0. Every number goes into `results.json` as `metrics[______]`, with the median, min, max and raw samples. Raw data is in `results/`: `runs.csv`, `drift.csv` (per token), `outputs.jsonl` (model answers), `thermal.jsonl`, `env.json` and `models.json`. The prompts, including token ids, are in `data/prompts_*.json`. ## How it works - `haystack.py` generates fake service-log lines procedurally (seed `20261019`; no real data). It plants 5 needles of the form `The deploy key for service orion-17 is 48213.` at 10/30/50/70/90% depth. The full chat-templated prompt (thinking disabled) is trimmed to ≤ the target length, within 48 tokens of it, counted with each model's own tokenizer. - `bench.py` uses the mlx_lm Python API. It loads each model once and runs one discarded warm-up per KV setting plus a 1k-token drift self-test. Then come the blocks, one per haystack variant. In each block every context length runs fp16/kv8/kv4 in a seeded random order, each with a fresh prompt cache through `stream_generate` (greedy, max_tokens 128). There is a 20 s cooldown between blocks, and `pmset -g therm` (plus powermetrics, if passwordless sudo is available) is logged before and after each block. - Drift reuses each run's own prefill. The prompt KV is kept and decode-time KV is trimmed. The linear-attention state is restored from a snapshot taken at the end of prefill. Then `generate_step` runs with a sampler that returns the forced token, so the forced pass uses the same decode code path. If a quantized run comes before the fp16 run in the random order, its rewound cache is parked in host numpy until fp16 has run, so it does not inflate the fp16 run's MLX peak. - The time guard means no new run starts after the deadline (36 min). Skipped runs are recorded in `runs.csv` and listed in `results.json` caveats. - `aggregate.py` reads `results/` and writes `results.json`, including paired (same-variant) % changes against fp16 and auto-generated factual observations. ## Reproduce ```zsh # models must already be in ~/.cache/huggingface/hub (the run itself is offline) ./run.sh # ~35 min; writes results.json + results/ # pieces: python haystack.py # data/prompts_{moe,dense}.json, data/sample_*_8k_v0.txt python bench.py --dry-run # validate plan/prompts without a GPU python bench.py # GPU run python aggregate.py # results/ -> results.json python smoke_test.py # CPU-only tests (haystack, recall scoring, KL math, aggregation) ``` Python: `/opt/homebrew/Caskroom/miniconda/base/bin/python` (3.13.5). Versions this was prepared with: mlx 0.31.2, mlx-metal 0.31.2, mlx-lm 0.31.3, numpy 2.4.2, transformers 5.12.1. The run step records the versions it actually used in `results.json → environment`. Hardware: MacBook Pro, M3 Max, 64 GB, macOS 27 (Darwin 27). The exact build, chip and memory come from `sw_vers`, `sysctl` and `mx.device_info()` and are recorded at run time. Before running, close other apps, plug in the charger and enable High Power mode (`pmset -g` output is recorded). ## Caveats - Hybrid attention: see above. Savings are bounded by 10/40 or 16/64 layers' worth of KV. - Peak memory includes weights, activations and allocator transients, not just the KV cache. - In this mlx_lm version, quantized attention is `quantized_matmul` → softmax → `quantized_matmul` with materialized scores. The fp16 path uses the fused `mx.fast.scaled_dot_product_attention`. Prefill memory and speed reflect that implementation. - With `quantized_kv_start=0` the cache is quantized after the first 2048-token prefill chunk. - n = 3 variants per cell. Do not read differences smaller than the min–max spread as real. - Decode speed is measured over the actual answer, typically 30–60 tokens before EOS. - Synthetic needles are a recall stress test, not a quality benchmark. - KL is computed from bf16 logits. The fp16 self-check row shows the noise floor. - powermetrics needs root. Without passwordless sudo, thermal state comes from `pmset -g therm` only. - Thinking is disabled (`enable_thinking=False`) for all runs.