← Blog · · 13 min read

8-bit and 4-bit KV cache in MLX on an M3 Max: small memory savings and slower MoE decode on hybrid Qwen models

On this page (7 sections)
  1. TL;DR
  2. The question
  3. Setup
  4. Results
  5. Surprises and caveats
  6. How to reproduce
  7. Conclusion

TL;DR

The question

Our earlier post on context length showed that decode speed drops as context grows. The usual advice for long context on a Mac is "just use --kv-bits 4". We did not find published measurements of what that trades off on Apple Silicon: peak unified memory, prefill and decode speed, and whether recall or outputs change. Dequantizing might slow decode, and models with few KV heads might save less memory than expected, so we measured.

Setup

Hardware and software. Apple M3 Max. MLX reports memory_size as 68719476736 bytes (64 GB) and the recommended working set as 55662788608 bytes. The machine ran on AC power. Software: macOS 27.0.1 (build 26A434, Darwin 27.0.0), Python 3.13.5 (conda build), mlx 0.31.2, mlx_lm 0.31.3, numpy 2.4.2 and transformers 5.12.1.

Models. We ran both from the local Hugging Face cache:

According to config.json, both use linear attention (Gated DeltaNet) in most layers, whose state has a fixed size. Only the full-attention layers have a KV cache that grows with context:

"Dense" here describes the MLP (no experts). The attention layout is the same kind of hybrid as in the MoE.

Prompts. We built a synthetic haystack of procedurally generated fake service-log lines from a fixed seed. Each haystack hides 5 needles of the form The deploy key for service <name> is <5-digit number>., spread from near the start to near the end, and the prompt asks the model to list all five. We trimmed each prompt to the target length using each model's own tokenizer, with the chat template included and thinking disabled. There are 3 haystack variants per length. The MoE ran at 8k, 16k and 32k; the dense model at 8k and 16k only, to fit the time budget.

Settings. We used three cache settings: fp16, kv8 and kv4. fp16 is shorthand for the default unquantized cache (kv_bits=None), which stores K/V in the model's activation dtype; we did not record it, and it may be bf16. All settings used kv_group_size=64, quantized_kv_start=0 and the default prefill_step_size=2048. Decoding was greedy with max_tokens=128.

Procedure. We loaded each model once and ran one discarded warm-up per KV setting. Each block used one haystack variant and ran fp16, kv8 and kv4 in a random order, each with a fresh prompt cache. Blocks ran in variant order (all variant-0 blocks for a model, then variant 1, then variant 2), so the variant index is also the time order. We used the Python API so we could time prefill and decode separately. The snippet below is condensed from bench.py, without the deadline handling, the capture of mlx_lm's own prompt_tps/generation_tps, and the collection of cache nbytes:

import time
import mlx.core as mx
from mlx_lm import load, stream_generate
from mlx_lm.models.cache import make_prompt_cache
from mlx_lm.sample_utils import make_sampler

model, tok = load("mlx-community/Qwen3.6-35B-A3B-4bit")
greedy = make_sampler(temp=0.0)

def run(prompt_ids, kv_bits):            # None (fp16 cache), 8 or 4
    cache = make_prompt_cache(model)
    mx.reset_peak_memory()
    t0, t_first, n = time.perf_counter(), None, 0
    for _ in stream_generate(model, tok, prompt_ids, max_tokens=128,
                             sampler=greedy, prompt_cache=cache,
                             kv_bits=kv_bits, kv_group_size=64,
                             quantized_kv_start=0):
        n += 1
        if t_first is None:
            t_first = time.perf_counter()
            peak_prefill = mx.get_peak_memory()
            mx.reset_peak_memory()          # decode phase measured on its own
    t_end = time.perf_counter()
    return {"ttft_s": t_first - t0,
            "prefill_tps": len(prompt_ids) / (t_first - t0),
            "decode_tps": (n - 1) / (t_end - t_first),
            "peak_prefill_gb": peak_prefill / 1e9,
            "peak_decode_gb": mx.get_peak_memory() / 1e9}

mlx_lm queues the next token's forward pass (async_eval) before it yields the current token, so t_first and the decode-phase peak reset slightly overlap the first decode step. We expect the effect on these short decode timings to be small.

We measured KV-cache size directly as the nbytes of the cache objects at the end of each run. We also calculated a theoretical size: full-attention layers × KV heads × head_dim × tokens × 2 × bytes per element. A quantized element costs bits/8 bytes plus a bf16 scale and bias per group of 64.

Output-drift check. We took the first 64 greedy tokens from the fp16 run and teacher-forced them through the kv8 and kv4 caches, starting from the state right after prefill. For each token we recorded KL(fp16 ‖ quantized) and whether the argmax matched. As a self-check, re-forcing the fp16 cache on its own tokens gave a KL of 0 in every case. The metric:

def kl_and_top1(ref_logprobs, test_logprobs):
    p = ref_logprobs.astype(np.float64)
    q = test_logprobs.astype(np.float64)
    p = p - np.logaddexp.reduce(p, axis=-1, keepdims=True)
    q = q - np.logaddexp.reduce(q, axis=-1, keepdims=True)
    kl = np.maximum(np.sum(np.exp(p) * (p - q), axis=-1), 0.0)
    top1 = np.argmax(p, axis=-1) == np.argmax(q, axis=-1)
    return kl, top1

42 of the 45 planned runs finished in 2099 s. The three runs for the third dense variant at 16k were skipped because of the time budget, so that cell has n=2.

Results

All values are medians over haystack variants. "Δ peak" and "Decode Δ" are paired: each quantized run is compared with the fp16 run on the same variant, in the same block. Because throughput drifted over the session, use the paired Δ columns, not the absolute TTFT, prefill and decode medians, to compare settings.

Memory

Model Context KV Peak (GB) Δ peak vs fp16 Decode-phase peak (GB) KV cache, measured (GB)
MoE 8k fp16 21.88 – 19.86 0.173
MoE 8k kv8 21.80 −0.08 GB (−0.4%) 19.78 0.092
MoE 8k kv4 21.75 −0.13 GB (−0.6%) 19.74 0.049
MoE 16k fp16 22.51 – 20.08 0.341
MoE 16k kv8 22.41 −0.10 GB (−0.4%) 19.89 0.181
MoE 16k kv4 22.32 −0.19 GB (−0.9%) 19.78 0.096
MoE 32k fp16 23.96 – 20.44 0.676
MoE 32k kv8 23.67 −0.30 GB (−1.2%) 20.09 0.359
MoE 32k kv4 23.49 −0.48 GB (−2.0%) 19.89 0.190
Dense 8k fp16 19.20 – 16.14 0.554
Dense 8k kv8 18.95 −0.25 GB (−1.3%) 15.83 0.294
Dense 8k kv4 18.82 −0.38 GB (−2.0%) 15.67 0.156
Dense 16k fp16 20.47 – 16.72 1.091
Dense 16k kv8 19.97 −0.50 GB (−2.4%) 16.18 0.579
Dense 16k kv4 19.71 −0.77 GB (−3.7%) 15.86 0.307

Speed and output quality

Model Context KV TTFT (s) Prefill (tok/s) Decode (tok/s) Decode Δ Recall Mean KL (nats) Max KL (nats) Top-1 match
MoE 8k fp16 6.0 1358 90.7 – 15/15 – – –
MoE 8k kv8 6.2 1312 82.3 −9.2% 15/15 0.000011 0.0006 100%
MoE 8k kv4 6.4 1271 84.6 −6.7% 15/15 0.0024 0.154 100%
MoE 16k fp16 13.3 1227 84.7 – 15/15 – – –
MoE 16k kv8 13.6 1202 73.3 −14.0% 15/15 0.00010 0.0064 100%
MoE 16k kv4 14.0 1169 76.1 −10.5% 15/15 0.0021 0.135 100% (min 98.4%)
MoE 32k fp16 38.3 855 62.0 – 15/15 – – –
MoE 32k kv8 34.6 948 52.7 −18.3% 15/15 0.00013 0.0077 100%
MoE 32k kv4 37.2 880 55.9 −9.9% 15/15 0.00016 0.0072 100%
Dense 8k fp16 53.6 152.5 13.1 – 15/15 – – –
Dense 8k kv8 50.9 160.7 14.3 +11.9% 15/15 0.00004 0.0023 100%
Dense 8k kv4 51.8 157.9 13.6 +5.4% 15/15 0.00013 0.0062 100%
Dense 16k fp16 118.6 137.8 11.6 – 10/10 – – –
Dense 16k kv8 115.5 141.5 11.3 −2.4% 10/10 0.000019 0.0011 100%
Dense 16k kv4 118.0 138.5 11.3 −2.3% 10/10 0.00022 0.0122 100%

The recall column is the total of correct needles across all variants. The KL columns are medians of the per-prompt mean and the per-prompt max.

The cache shrinks as designed. For the MoE at 32k, the measured cache was 0.676, 0.359 and 0.190 GB. The theoretical figures are 0.671, 0.356 and 0.189 GB, and the small gap is allocation padding. A 4-bit element costs 0.5625 bytes instead of 2, which is 28% of the fp16 size.

The cache is a small part of the peak. The fp16 KV cache is 2.8% of peak memory for the MoE at 32k and 5.3% for the dense model at 16k. Right after loading, the weights alone take 19.51 GB (MoE) and 15.13 GB (dense). The usual back-of-envelope estimate assumes every layer has a KV cache. For the MoE at 32k it gives 2.68 GB, 4 times the real figure.

The peak happens during prefill. For the MoE at 32k with the fp16 cache, the prefill-phase peak was 23.96 GB and the decode-phase peak was 20.44 GB. kv_bits does nothing about that 3.5 GB gap. During decode the savings are a bit larger: −0.55 GB for the MoE at 32k with kv4 and −0.86 GB for the dense model at 16k with kv4. Even the largest configuration here peaked under 24 GB on a 64 GB machine.

Prefill speed did not change measurably. Most paired prefill differences fell inside the run-to-run spread.

Decode on the MoE was slower in every pair. At 8k and 16k the min–max ranges of the quantized runs do not overlap with fp16. At 32k, the fp16 run in the first block decoded at 75.1 tok/s, against 61.1 and 62.0 tok/s in the two later blocks, probably because that block ran earliest, before the session-wide drift. Still, all three paired comparisons at 32k were negative: −13.7% to −21.6% for kv8 and −9.9% to −14.7% for kv4. At every length, the median kv4 run decoded faster than the median kv8 run, and we saw no crossover where the quantized cache becomes faster at longer context. The kv8 penalty looks larger at 32k than at 8k, but the 32k median (−18.3%) comes from the block with the fast fp16 run, and kv4 shows no trend (−6.7%, −10.5%, −9.9%). We treat it as a possible trend, not a finding.

The dense model at 16k showed −2.4% (kv8) and −2.3% (kv4), but that cell has n=2, and a difference this size is too small for n=2 to resolve.

Hypothesis, not something we measured directly: in this mlx_lm version, quantized attention runs as quantized_matmul → softmax → quantized_matmul, while the fp16 path uses the fused mx.fast.scaled_dot_product_attention. With a cache this small next to roughly 20 GB of weights, the extra unfused work may cost more than the memory bandwidth the smaller cache saves. We did not profile kernels to check this.

Output quality held up. Every run recalled all 5 needles. The largest single-token KL we saw was 0.2555 nats (MoE, 8k, kv4, one variant), and the argmax at that position still matched fp16. Across the whole experiment, the top-1 token differed exactly once: 63 of 64 positions matched in one MoE prompt at 16k with kv4.

Surprises and caveats

How to reproduce

The code, the haystack generator (including the seed), prompts with token ids, and the raw data (runs.csv, per-token drift.csv, outputs.jsonl, thermal.jsonl, env.json) are at https://hackbig.com/blog-data/mlx-kv-cache-quantization-m3-max/.

# models must already be in ~/.cache/huggingface/hub; the run is offline
./run.sh                    # haystacks -> benchmark -> results.json
# or step by step:
python haystack.py          # data/prompts_{moe,dense}.json
python bench.py --dry-run   # check the plan and prompts without the GPU
python bench.py
python aggregate.py         # results/ -> results.json
python smoke_test.py        # CPU-only tests

run.sh hardcodes our Python interpreter path in its PY= line; change it to your own. Close other apps, plug in the charger, turn on High Power mode, and confirm that pmset -g reports powermode 2. Our run reported powermode 0 (Automatic), so High Power mode was off. Consider counterbalancing the run order within each block.

Conclusion

On our M3 Max, with these hybrid Qwen models, 4-bit and 8-bit KV caches left needle recall unchanged and output drift negligible. They saved at most 0.77 GB of peak memory and, in paired comparisons, made MoE decode 7–18% slower. On a machine with memory to spare, we would not enable them by default. On a smaller Mac, savings of this size might matter for smaller models or shorter contexts, but the models we tested peaked at 19–24 GB and we did not measure that case. This advice applies only to hybrid-attention models like these; models with full attention in every layer have larger caches, and we did not test them.

Code and raw data for this post

How this was made: an AI agent (Claude) designed and ran this experiment on our own MacBook in a sandbox; every number comes from the run's results file (linked below), checked by script before publishing.