← 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)
TL;DR
- Both models we tested, Qwen3.6-35B-A3B-4bit (MoE) and Qwen3.8-27B-4bit (dense), are hybrids. Only 10 of 40 and 16 of 64 layers keep a KV cache, and
kv_bitsonly quantizes those layers. The cache is small to begin with: 0.676 GB for the MoE at 32k tokens and 1.091 GB for the dense model at 16k. - 4-bit KV made that cache 72% smaller, and 8-bit made it 47% smaller. Peak unified memory, though, fell by only 2.0% (−0.48 GB) for the MoE at 32k and by 3.7% (−0.77 GB) for the dense model at 16k. On our machine, the peak comes from prefill, not from the cache.
- Decode on the MoE got slower. Paired medians were −9.2% (kv8) and −6.7% (kv4) at 8k, −14.0% and −10.5% at 16k, and −18.3% and −9.9% at 32k. At 8k, kv8 ran last in all three blocks, so drift within a block may have inflated that number. On the dense model the effects were within noise: −2.4% and −2.3% at 16k, too small for n=2 to resolve, and paired kv8 changes from −5.6% to +12.3% at 8k.
- Throughput drifted down during the session: MoE 8k fp16 prefill was 29% lower in the last block than in the first, probably from thermal or power throttling. High Power mode was off during the run. The paired within-block changes are more reliable than the absolute speeds, though drift within a block can still skew them.
- Needle recall was 5/5 in every run. Measured against the fp16 cache, the median mean per-token KL was at most 0.0024 nats. The greedy top-1 token matched in every teacher-forced position except one, out of 64 positions in one prompt (MoE, 16k, kv4).
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:
mlx-community/Qwen3.6-35B-A3B-4bit@38740b847e4cb78f352aba30aa41c76e08e6eb46mlx-community/Qwen3.8-27B-4bit@10c35caafbb80f7dc6a7a432cdd11af10a6d4818
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:
- MoE: 10 of 40 layers, 2 KV heads × head_dim 256.
- Dense: 16 of 64 layers, 4 KV heads × head_dim 256.
"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
- Hybrid attention drives these results. For a model with full attention in every layer, the naive estimate would apply and the savings could be several times larger. We did not test such a model.
- What "peak memory" means here. It is MLX's
mx.get_peak_memory(), which counts weights, activations and transient buffers. It is not process RSS and not what Activity Monitor shows. - Throughput drifted down over the session. MoE fp16 prefill at 8k went 1471 → 1358 → 1045 tok/s across the three blocks (−29%), and at 16k 1264 → 1227 → 1062. All three MoE 32k runs in the first block prefilled at 1070–1124 tok/s, against 833–948 tok/s later. MoE 8k fp16 decode went 91.1 → 90.7 → 86.0 tok/s. This looks like thermal or power throttling. High Power mode was off (see below), which is a likely contributor, but we did not confirm the cause.
- Order within a block was not balanced. With n=3 blocks and a random order in each, kv8 ran last in all three MoE 8k blocks, so drift within a block could have inflated the 8k kv8 decode penalty (−9.2%). Order and drift also distort the raw medians: for the MoE at 32k, the median kv8 prefill (948 tok/s) beats fp16 (855 tok/s), yet the paired median change is −2.2%; in the second 32k block kv8 ran first and fp16 last. We did not counterbalance the order or interleave extra fp16 reference runs.
- Thermal logging and power mode.
powermetricsneeds root, so our only thermal record ispmset -g thermoutput inthermal.jsonl, published with the raw data. It records macOS thermal-warning state, not GPU clocks or temperatures, so it cannot confirm or rule out throttling.pmset -greportedpowermode 0, which is Automatic (1 is Low Power, 2 is High Power), so High Power mode was off during the run. That is a likely cause of the 29% prefill drift and the throttling, though we did not test it. - Small samples. We ran n=3 per cell, and n=2 for the dense model at 16k. At dense 8k, one fp16 run decoded at 15.0 tok/s while the others did 12.7 and 13.1, and the paired kv8 changes ranged from −5.6% to +12.3%. We do not read the +11.9% median as a real gain.
- Short generations. Decode speed is computed over the inter-token intervals of 66 to 68 generated tokens, right after a long prefill. It is not a measure of sustained long-generation throughput.
- When quantization kicks in. From our reading of
maybe_quantize_kv_cachein mlx_lm 0.31.3'sgenerate_step, withquantized_kv_start=0andprefill_step_size=2048the cache is converted after the first 2048-token prefill chunk, and later chunks attend to quantized K/V. We inferred this from the code and did not instrument it. - Easy recall test. Synthetic needles in fake logs are a recall stress test, easier than real retrieval. The KL and top-1 numbers are the more sensitive signal.
- Slow dense prefill. The dense model prefilled at 152.5 tok/s at 8k versus 1358 tok/s for the MoE. A plausible explanation, which we did not test, is compute: about 27B parameters per token against about 3B active for the A3B MoE, roughly 9× the compute, matching the roughly 9× prefill gap.
- Version-specific. These numbers hold for mlx 0.31.2 and mlx_lm 0.31.3 only.
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.