Level 3 In-Depth AI · Transformers and Language Models
The KV Cache and Fast Inference
When a language model writes text one token at a time, it can remember the keys and values it already computed instead of recomputing them. This KV cache makes generation fast, but it eats GPU memory, which shapes how models are designed and served.
- Level
- ●●●●● Intermediate
- Reading
- 12 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 32 concepts →
- Quiz
- 5 questions ↓
This leads to
Serving LLMs at ScaleThe full path from zero — 32 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- GPT and Decoder-Only Models
- The KV Cache and Fast Inference
Read them roughly in this order. See it on the concept map →
Why it matters
A decoder-only language model generates text autoregressively: it predicts one token, appends it to the input, and runs again to predict the next. A 500-token answer means 500 forward passes. Done naively, each pass reprocesses the whole text so far, so the total work grows with the square of the length.
The KV cache removes almost all of that repetition. It is a store, kept in GPU memory, of the attention keys and values for every token processed so far. With it, each new step only has to process one new token. Every serious inference engine uses it: llama.cpp on your laptop, vLLM in a data centre, and the systems behind ChatGPT, Claude and Gemini.
But the cache is big. For a 7-billion-parameter model with standard attention it takes half a megabyte per token, so a few long conversations can need more GPU memory than the model weights themselves. That one fact explains a lot of modern LLM design and pricing:
- why newer models use grouped-query attention or other tricks to shrink the cache,
- why serving engines manage cache memory like an operating system manages RAM (Serving LLMs at Scale),
- why APIs charge less for cached prompt prefixes,
- and why long context windows are expensive.
The intuition
Imagine reading a long novel aloud and, before each new word, re-reading the entire book from the first page. That is generation without a cache. Instead, you keep notes: as you finish each sentence, you write down what matters about it. To produce the next word you consult your notes and look only at the newest word.
In Self-Attention and Multi-Head Attention, each token is turned into three vectors: a query (what am I looking for?), a key (what do I contain?) and a value (what do I pass on if chosen?). The crucial observation is that in a causal (left-to-right) model, a token's key and value never change once computed: later tokens can't affect earlier ones, because of the causal mask. So there is no reason to compute them twice. Each step:
- Compute the query, key and value for the new token only.
- Append its key and value to the cache.
- Let the new query attend over all the cached keys and values.
Key idea In a causal Transformer, keys and values of past tokens never change, so cache them. Each generation step then processes only one new token, at the price of memory that grows with every token: 2 × layers × KV heads × head size × bytes, per token.
How it works
Attention for one new token
Recall scaled dot-product attention (Self-Attention and Multi-Head Attention). For the newest token , with query vector and the stacked keys and values of tokens :
where is the head size. Only is new. The rows of and for tokens are exactly what we computed at earlier steps. The cache stores them, per layer and per head, and we append one row each step.
Prefill and decode
Generation has two phases with very different behaviour.
- Prefill. The whole prompt is processed in one forward pass, all tokens in parallel, filling the cache. This is a big batch of matrix multiplications, so the GPU's arithmetic units are busy. It determines the time to first token.
- Decode. Then tokens are produced one by one. Each step does little arithmetic (one token's worth), but must read all the model weights and the whole cache from GPU memory. Decode is memory-bandwidth bound: its speed is set by how fast bytes can be moved from memory, not by how fast they can be multiplied.
A rough rule: with a 7B model in 16-bit (14 GB of weights) on a GPU with about 2 TB/s of memory bandwidth, one decode step can't take less than s ms just to read the weights, so a single sequence tops out around 140 tokens per second. Serving many users at once helps, because one read of the weights is shared by everyone in the batch. Each user's KV cache, though, must be read separately. That is why cache size limits throughput.
The memory arithmetic
For each token, each layer stores one key vector and one value vector per KV head:
The leading 2 counts K and V. Take Llama 2 7B: 32 layers, 32 attention heads each with its own keys and values, head size 128, stored in 16-bit (2 bytes):
Its full 4,096-token context therefore needs MiB GiB per sequence. Serve 32 users at full context and the cache needs 64 GiB, several times the 13.5 GB of weights. Without a cache, though, every one of those decode steps would have to redo the work for all previous tokens.
Shrinking the cache: MQA, GQA and MLA
The formula has an obvious target: . Standard multi-head attention (MHA) gives each query head its own key and value head.
- Multi-query attention (MQA) (Shazeer, 2019) keeps many query heads but shares a single key/value head among them, cutting the cache by the number of heads (32× for a 32-head model). Quality can drop a little.
- Grouped-query attention (GQA) (Ainslie et al., 2023) is the compromise: query heads are split into groups, and each group shares one key/value head. Llama 2 70B, Llama 3 and Mistral 7B all use 8 KV heads. For Llama 3 8B (32 layers, 32 query heads, 8 KV heads, head size 128) the cache is 128 KiB per token, a quarter of Llama 2 7B's, with little loss in quality.
- Multi-head latent attention (MLA) (DeepSeek-V2, 2024) compresses keys and values into a small shared latent vector per token and reconstructs them on the fly, shrinking the cache further.
Managing the cache when serving
A server handles many requests of unknown, varying length. Reserving the maximum context's worth of cache for each one wastes most of the memory. PagedAttention (Kwon et al., 2023, the core of the vLLM engine) stores the cache in small fixed-size blocks, like an operating system's memory pages, allocated as a sequence grows. The authors reported that earlier systems wasted 60–80% of cache memory to fragmentation and over-reservation, and that vLLM cut the waste to under 4%, letting far more requests run at once.
Other standard techniques:
- Continuous batching: add new requests to the running batch as soon as others finish, instead of waiting for a whole batch to complete.
- Prefix caching: if many requests start with the same text (a long system prompt, a shared document), compute its cache once and reuse it. Commercial APIs expose this as prompt caching and bill cached input tokens at a reduced rate.
- Quantised caches: store keys and values in 8 or even 4 bits instead of 16 (Quantization).
- Sliding-window caches: models with sliding-window attention only keep the last few thousand tokens' keys and values (Long Context and Efficient Attention).
Speculative decoding
Because decode is memory-bound, checking several tokens costs about the same as generating one. Speculative decoding uses a small, fast "draft" model to guess the next few tokens, then the big model verifies them all in a single pass (like a mini-prefill), keeping the longest correct run. The output distribution is unchanged, and when the draft guesses well, generation can be two to three times faster. See Decoding: Temperature, Top-k and Top-p.
In code
First, the memory arithmetic for three real configurations (pure Python):
def kv_cache_bytes(layers, kv_heads, head_dim, tokens, batch=1, bytes_per_value=2):
return 2 * layers * kv_heads * head_dim * tokens * batch * bytes_per_value # 2 = K and V
GiB = 1024**3
configs = { # layers, KV heads, head dim
"Llama 2 7B (MHA)": (32, 32, 128),
"Llama 3 8B (GQA)": (32, 8, 128),
"Llama 2 70B (GQA)": (80, 8, 128),
}
for name, (L, H, d) in configs.items():
per_token = kv_cache_bytes(L, H, d, 1)
full = kv_cache_bytes(L, H, d, tokens=8192, batch=16) # 16 users x 8k tokens
print(f"{name:18s} {per_token/1024:6.0f} KiB/token 8k tokens x 16 users: {full/GiB:5.0f} GiB")
# Llama 2 7B (MHA) 512 KiB/token 8k tokens x 16 users: 64 GiB
# Llama 3 8B (GQA) 128 KiB/token 8k tokens x 16 users: 16 GiB
# Llama 2 70B (GQA) 320 KiB/token 8k tokens x 16 users: 40 GiB
(Llama 2's real context limit is 4,096 tokens; the 8k column just shows the scaling.) Note that the 70B model, ten times larger, has a smaller cache per token than the 7B one, thanks to GQA.
Second, a toy 4-layer attention-only model with random weights, generating 300 tokens after a 200-token prompt, with and without a cache. Both must produce identical tokens; only the speed differs.
import time, torch
torch.manual_seed(0)
V, D, L = 1000, 256, 4 # vocab, model width, layers
emb = torch.randn(V, D) / D**0.5
Wq, Wk, Wv = (torch.randn(L, D, D) / D**0.5 for _ in range(3))
out = torch.randn(D, V) / D**0.5
def layer_attn(x, l, past=None):
"""Causal single-head attention for layer l. x: (T_new, D). past: (K, V) or None."""
q, k, v = x @ Wq[l], x @ Wk[l], x @ Wv[l]
if past is not None: # reuse keys/values of earlier tokens
k, v = torch.cat([past[0], k]), torch.cat([past[1], v])
T_new, T = q.shape[0], k.shape[0]
scores = q @ k.T / D**0.5
mask = torch.ones(T_new, T).tril(T - T_new).bool() # each query sees itself + the past
att = scores.masked_fill(~mask, float("-inf")).softmax(-1)
return x + att @ v, (k, v)
def generate(prompt, n, use_cache):
tokens, cache = list(prompt), [None] * L
for step in range(n):
if use_cache and step > 0:
x = emb[tokens[-1:]] # decode: only the newest token
else:
x = emb[tokens] # prefill (or no cache): everything
for l in range(L):
x, kv = layer_attn(x, l, cache[l] if use_cache and step > 0 else None)
cache[l] = kv
tokens.append(int((x[-1] @ out).argmax()))
return tokens
prompt = torch.randint(0, V, (200,)).tolist()
for use_cache in [False, True]:
t0 = time.perf_counter()
result = generate(prompt, 300, use_cache)
print(f"cache={use_cache!s:5} {time.perf_counter() - t0:.2f} s last tokens {result[-5:]}")
# cache=False 1.02 s last tokens [903, 848, 188, 860, 57]
# cache=True 0.19 s last tokens [903, 848, 188, 860, 57]
Same tokens, about five times faster on a laptop CPU (your timings will differ). The gap widens with longer outputs, because without a cache the work per step keeps growing. In Hugging Face transformers the cache is on by default in model.generate(...); production engines such as vLLM add paging, batching and prefix caching on top.
Common pitfalls
- Forgetting the cache in long-context capacity planning. A model that "fits" on a GPU may not fit once 32 users each have 8,000 tokens of cache. Do the arithmetic above before buying hardware.
- Confusing the two phases. Prefill is compute-bound and scales with prompt length; decode is bandwidth-bound and scales with output length. Time to first token and tokens per second are different metrics with different fixes.
- Breaking prefix caching. Prefix caches match exactly. Putting a timestamp or a random ID at the start of a system prompt makes every request look different, and you pay full price every time. Put stable content first, variable content last.
- Positional encodings and cache reuse. Cached keys already include their position (for example with RoPE). You can't splice cached chunks into a different position without recomputing or correcting them.
- Batch size 1 benchmarks. Single-request speed says little about serving throughput, which depends on how many caches fit in memory.
Watch out Out-of-memory errors during generation, not during model loading, almost always mean the KV cache outgrew the GPU. Lower the maximum context length, the batch size or the number of concurrent requests, or use a model with GQA or a quantised cache.
Where it leads
- Long context: making attention itself cheaper for very long inputs, and keeping the cache manageable: Long Context and Efficient Attention.
- Serving systems: batching, paging, routing and autoscaling: Serving LLMs at Scale.
- Quantization of weights and of the cache: Quantization.
- Decoding strategies, including speculative decoding: Decoding: Temperature, Top-k and Top-p.
- Alternatives without a growing cache: State Space Models and Mamba such as Mamba keep a fixed-size state instead of a cache that grows with every token.
- Running models yourself: Running Models Locally.
A bit of history
Caching keys and values is as old as Transformer decoding itself: it was present in early implementations from the 2017 "Attention Is All You Need" codebase onwards, and it is obvious once you see that causal attention never revisits earlier tokens. It became a central design concern as models and contexts grew. In 2019 Noam Shazeer's multi-query attention paper framed decoding as limited by memory bandwidth and shrank the cache. PaLM (2022) used MQA at scale. In 2023, GQA (Joshua Ainslie and colleagues at Google) became the standard compromise, adopted by Llama 2 70B, Mistral 7B and Llama 3, and PagedAttention (Woosuk Kwon and colleagues at UC Berkeley) made the cache manageable in production through vLLM. DeepSeek-V2 introduced multi-head latent attention in 2024. In the same period, the major API providers introduced discounted prompt caching, turning a memory optimisation into a pricing feature.
Try it
- Use
kv_cache_bytesto find how many 128,000-token conversations fit in the KV cache of Llama 3 8B on an 80 GB GPU, after subtracting 16 GB for the weights.- In the toy model, raise the number of generated tokens from 300 to 600. How do the two timings change? Explain why one grows faster than the other.
- Modify
layer_attnto use a sliding window: keep only the last 64 keys and values in the cache. Do the generated tokens still match the uncached version? Why not?Hint for 2: without a cache, step costs work proportional to , so total work grows like .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints
Grouped-query attention, the middle ground between multi-head and multi-query attention used by Llama 2 70B, Llama 3, Mistral and many others.
Efficient Memory Management for Large Language Model Serving with PagedAttention (vLLM)
Stores the KV cache in fixed-size pages like an operating system's virtual memory, so many requests can share GPU memory with little waste.
vLLM documentation
A widely used open-source LLM inference engine with paged KV cache, continuous batching and prefix caching.
Fast Transformer Decoding: One Write-Head is All You Need (multi-query attention)
Shares one key and value head across all query heads, shrinking the KV cache and speeding up decoding.
Build a Large Language Model (From Scratch)
Step by step from tokenizer to pretraining to fine-tuning a GPT-like model in PyTorch. The code repository is free.
DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model
Introduced multi-head latent attention (MLA), which compresses keys and values into a small latent vector to cut the KV cache, plus the DeepSeekMoE design.
LLM Visualization
A 3D walk-through of every computation inside a GPT model, step by step.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/kv-cache.md