KV cache compression and quantisation: fitting more sequences on each GPU
KV cache compression shrinks the memory the model keeps for each active sequence, by using fewer bits, dropping tokens or sharing heads. Use it when GPU memory, not compute, limits how many users you can serve.
KV cache compression in 60 seconds
- What: methods that make the per-sequence KV cache smaller: fewer bits per number, fewer tokens kept, or fewer key and value heads.
- Why: the cache grows with every token and every active request, so memory often caps concurrency before compute does.
- Three levers: quantise the stored values, evict tokens the model rarely attends to, or choose a model design that shares heads.
- Cost: some loss of quality, which grows with how hard you compress and how long and precise the task is.
- Rule: measure quality on your own tasks before and after, and keep a switch to turn compression off.
Where this type fits
This is one of the three caches that live inside the model server, alongside the plain KV cache and the prefix cache. The caching hub groups them as the caches you tune with your serving stack, not with application code. Compression does not add a new cache. It changes how the existing KV cache is stored.
The problem it solves
A language model (LLM) reads text as tokens. At each layer, attention needs a key and a value for every earlier token. The server stores them so it never recomputes them. This store is the KV cache. It is fast and it works, but it takes memory in proportion to the number of tokens, the number of layers, the number of heads, and the number of bytes per number.
Now multiply by traffic. Each active request owns its own cache. A long document chat may hold tens of thousands of tokens. A hundred such chats at once can fill the GPU with cache alone, after the model weights are loaded. When memory is full, the server must refuse new requests, queue them, or evict someone else's cache and pay to rebuild it later. Latency rises and cost per request rises with it.
Without compression you have two blunt options: buy more GPUs, or cut context length and batch size. Both cost money or product quality. Compression offers a third path. Keep the same hardware and the same context, but store less per token. The price is a small, measurable loss in answer quality, so the real question is how small you can make the cache before users notice.
How it works
- Start with the full cache: by default each key and value is stored in 16-bit numbers for every token seen so far.
- Quantise: store the numbers with fewer bits, such as 8-bit or 4-bit, plus a small scale factor to recover approximate values when they are read.
- Evict: score tokens by how much attention they receive and drop the ones that matter least. Keep the first tokens and the most recent tokens as a safe core.
- Share heads: choose or train a model whose several query heads share one set of key and value heads, so there is less to store from the start.
- Serve more: the smaller cache frees memory, so the scheduler can admit more sequences or longer contexts at once.
- Verify: compare answers with and without compression on a fixed test set before turning it on for everyone.
The three levers act at different times. Quantisation is a serving setting: you can switch it on for an existing model and accept a small rounding error. Eviction is a runtime policy. The H2O paper (Zhang et al., 2023) observed that a small set of tokens, called heavy hitters, receive most of the attention. It keeps those plus recent tokens and evicts the rest. Head sharing is different, because it is part of the model itself. Grouped-query attention (Ainslie et al., 2023) shares key and value heads across groups of query heads, which shrinks the cache by design.
The levers can be combined, but errors add up. A model with shared heads, a quantised cache and eviction has three sources of loss. Test the combination, not each lever alone.
A worked example
Acme runs a contract-review assistant. Each review loads a contract of about 20,000 tokens. Suppose, for this example only, that the 16-bit cache for one such review takes 4 GB, and the GPU has 40 GB free after loading the model. At 16-bit, the server holds 10 reviews at once. The eleventh waits in a queue.
- Step 1, baseline: 10 concurrent reviews, 4 GB each. Queue time during peak hours is the problem.
- Step 2, quantise to 8-bit: the cache halves to about 2 GB per review. The server now holds about 20 reviews. Acme runs its 200-question test set: answers match the baseline on nearly all questions, with a few small wording changes.
- Step 3, try 4-bit: about 1 GB per review, so about 40 reviews. The test set now shows missed clauses on a handful of long contracts, mostly where an exact figure had to be quoted.
- Step 4, decision: Acme keeps 8-bit for all traffic and allows 4-bit only for the short-summary route, where exact figures matter less.
- Step 5, monitor: a daily sample of reviews is replayed with compression off, and the answers are compared. A rise in disagreement raises an alert.
Building it
In practice you switch compression on through your serving engine's settings. The code below shows the idea behind the two core mechanisms, so you can reason about them. It is illustrative and not a real engine.
import numpy as np
# Placeholders: a real engine does this inside GPU kernels.
def quantise(block, bits=8):
"""Store floats as small integers plus one scale per block."""
levels = 2 ** (bits - 1) - 1 # 127 for 8-bit, 7 for 4-bit
scale = np.abs(block).max() / levels # one scale keeps rounding error bounded
if scale == 0:
scale = 1.0 # avoid dividing by zero for empty blocks
q = np.round(block / scale).astype(np.int8)
return q, scale
def dequantise(q, scale):
return q.astype(np.float32) * scale # approximate original values
class CompressedKV:
def __init__(self, budget_tokens=4096, keep_first=4, keep_recent=256, bits=8):
self.budget = budget_tokens # hard cap on tokens kept per sequence
self.keep_first = keep_first # first tokens act as attention anchors
self.keep_recent = keep_recent # recent tokens matter most for the next word
self.bits = bits
self.entries = [] # each: dict(k, v, scale_k, scale_v, score)
def append(self, k, v):
qk, sk = quantise(k, self.bits)
qv, sv = quantise(v, self.bits)
self.entries.append({'k': qk, 'v': qv, 'sk': sk, 'sv': sv, 'score': 0.0})
if len(self.entries) > self.budget:
self._evict_one()
def observe_attention(self, weights):
# Add the attention each token just received to a running score.
for e, w in zip(self.entries, weights):
e['score'] += float(w)
def _evict_one(self):
# Protect the first and most recent tokens; drop the lowest-score token between them.
lo = self.keep_first
hi = len(self.entries) - self.keep_recent
if hi <= lo:
return # nothing safe to evict yet
victim = min(range(lo, hi), key=lambda i: self.entries[i]['score'])
del self.entries[victim]
Two limits matter here. The token budget puts a ceiling on memory per sequence, so one very long chat cannot starve everyone else. The protected first and recent tokens stop the policy from evicting what the next word depends on. A third guard, not shown, is a config flag that turns compression off per route, so you can compare outputs.
Design decisions
- Start with quantisation: it is the least risky lever and works on an existing model. Default to 8-bit and move to 4-bit only where tests allow.
- Treat eviction as a last resort: dropped tokens cannot come back, so a later question may need something you removed. Use it for chat, not for tasks that quote exact text.
- Choose head sharing at model selection time: you cannot add it later. Prefer models built with grouped heads if memory is your bottleneck.
- Set compression per route: a short chat and a legal-document review have different tolerance. Make it a routing setting, not a global one.
- Keep a kill switch: a single flag that restores the full cache lets you roll back within minutes if quality drops.
- Budget by memory, not by count: plan capacity as free GPU memory divided by cache size per sequence, and reserve headroom for bursts.
- Version the setting: record the compression mode with every logged answer, so you can tell later which mode produced a bad result.
Measuring it
- Quality delta: run a fixed test set with and without compression and compare scores. Report the gap per task type, not only the average.
- Agreement rate: the share of answers that match the uncompressed answer in a replayed sample. Track it daily.
- Cache bytes per sequence: total cache memory divided by active sequences, read from the server's metrics.
- Concurrency gain: peak concurrent sequences with compression divided by peak without it, on the same hardware.
- Long-context accuracy: questions whose answer sits deep in the context, such as an exact figure on page 40. This is where eviction hurts first.
- Latency: time to first token and tokens per second, since dequantising adds a little work per step.
def agreement_rate(test_set, generate_full, generate_compressed, same):
"""Share of questions where compressed output matches the baseline.
generate_* and same() are placeholders for your serving calls and a scorer."""
matches = 0
for case in test_set:
a = generate_full(case['prompt'])
b = generate_compressed(case['prompt'])
if same(a, b, case.get('expected')):
matches += 1
return matches / max(len(test_set), 1)
When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| GPU memory is full and requests queue at peak | Yes | A smaller cache admits more sequences without new hardware. |
| Very long contexts, such as whole documents | Yes, carefully | The cache is largest here, but eviction may drop key facts, so prefer quantisation. |
| Short chats with small contexts | No | The cache is small already, so the gain does not justify the risk. |
| Tasks that must quote exact figures or code | Quantise only | Eviction can remove the exact token you need. |
| Compute, not memory, is the bottleneck | No | Compression frees memory and does not speed up compute. |
| Choosing a model for a new memory-bound service | Yes, via head sharing | A model built with grouped heads starts with a smaller cache. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Small losses that grow with harder compression and longer tasks | Test on your own tasks and set compression per route. |
| Latency | Dequantising adds a little work, but fewer queued requests often lowers wait time overall | Measure time to first token under real load. |
| Cost | More sequences per GPU lowers cost per request | Track cost per request before and after. |
| Complexity | Settings interact with the model, the engine and the hardware | Change one lever at a time and keep a kill switch. |
| Failure modes | Silent quality drops, such as a missed clause in a long document | Replay a sample daily and alert on disagreement. |
Compared with related types
The plain KV cache is what compression acts on. Without it, the model would recompute every earlier token on each step. Compression only makes that cache cheaper to hold.
The prefix cache solves a different problem: reusing the cache across requests that share the start of a prompt. It saves compute, while compression saves memory. The two work together, because a smaller shared prefix is cheaper to keep resident.
What this means for your role
Common mistakes
Further reading
- Types of caching in AI systems: the hub that compares every cache type.
- H2O, Zhang et al., 2023: keeps a small set of heavy-hitter tokens that receive most attention, plus recent tokens, and evicts the rest of the KV cache.
- GQA, Ainslie et al., 2023: grouped-query attention shares key and value heads across groups of query heads, which shrinks the KV cache.
- KV cache: the cache that compression acts on.
- Inference serving: how servers schedule requests and use GPU memory.
KV cache compression trades a little quality for a lot of capacity. Use the gentlest lever that solves your memory problem, and prove it with tests on your own tasks.