◆ AI All-in-One

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
↗ Plan a path here

Read first

Self-Attention and Multi-Head AttentionGPT and Decoder-Only Models

This leads to

Serving LLMs at Scale
The full path from zero — 32 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Gradient Descent
  14. Language Modeling and Next-Token Prediction
  15. Supervised Learning
  16. Linear Regression
  17. The Perceptron
  18. Logistic Regression
  19. Neural Networks
  20. Recurrent Neural Networks
  21. Backpropagation
  22. Activation Functions
  23. Vanishing and Exploding Gradients
  24. Normalization Layers: BatchNorm and LayerNorm
  25. LSTMs and GRUs
  26. Residual Connections
  27. Sequence-to-Sequence Models
  28. Attention
  29. Self-Attention and Multi-Head Attention
  30. Positional Encodings
  31. The Transformer
  32. GPT and Decoder-Only Models
  33. 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:

  1. Compute the query, key and value for the new token only.
  2. Append its key and value to the cache.
  3. Let the new query attend over all the cached keys and values.
step 1sequence length 4 tokens keys K values V The k1 v1 cat k2 v2 sat k3 v3 on k4 v4 read from the cache, not recomputed new token only:compute its q, k, v;append k, v to the cache;its q attends over all keys step 2sequence length 5 tokens keys K values V The k1 v1 cat k2 v2 sat k3 v3 on k4 v4 the k5 v5 read from the cache, not recomputed cache grows byone k and one v step 3sequence length 6 tokens keys K values V The k1 v1 cat k2 v2 sat k3 v3 on k4 v4 the k5 v5 mat k6 v6 read from the cache, not recomputed cache grows byone k and one v
Fig. 1 The KV cache growing during generation. At each step only the newest token (orange) is processed. Its key and value are appended to the cache, and its query attends over every cached key. The cache grows by one row per step in every layer.

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 tt, with query vector qt\mathbf{q}_t and the stacked keys K\mathbf{K} and values V\mathbf{V} of tokens 1…t1 \dots t:

outputt=softmax ⁣(qtK⊤d)V\text{output}_t = \mathrm{softmax}\!\left(\frac{\mathbf{q}_t \mathbf{K}^\top}{\sqrt{d}}\right) \mathbf{V}

where dd is the head size. Only qt\mathbf{q}_t is new. The rows of K\mathbf{K} and V\mathbf{V} for tokens 1…t−11 \dots t-1 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 14/200014 / 2000 s =7= 7 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:

bytes per token=2×nlayers×nkv heads×dhead×bytes per number\text{bytes per token} = 2 \times n_{\text{layers}} \times n_{\text{kv heads}} \times d_{\text{head}} \times \text{bytes per number}

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):

2×32×32×128×2=524,288 bytes=512 KiB per token2 \times 32 \times 32 \times 128 \times 2 = 524{,}288 \text{ bytes} = 512 \text{ KiB per token}

Its full 4,096-token context therefore needs 4096×0.54096 \times 0.5 MiB =2= 2 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: nkv headsn_{\text{kv heads}}. 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.
Multi-head (MHA) 8 query heads K (blue) and V (purple) heads8 K/V heads: cache × 1 Grouped-query (GQA) 8 query heads K (blue) and V (purple) heads2 K/V heads: cache ÷ 4 Multi-query (MQA) 8 query heads K (blue) and V (purple) heads1 K/V head: cache ÷ 8 only the K and V heads are cached, so fewer of them means a smaller KV cache
Fig. 2 Three ways to share keys and values among 8 query heads. Multi-head attention keeps 8 K/V heads, grouped-query attention 2, multi-query attention 1. The KV cache shrinks in proportion.

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

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

  1. Use kv_cache_bytes to 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.
  2. 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.
  3. Modify layer_attn to 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 tt costs work proportional to tt, so total work grows like n2n^2.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Why is it safe to cache the keys and values of earlier tokens in a GPT-style model?

  2. Using 2 × layers × KV heads × head size × bytes, how big is the KV cache per token for a model with 32 layers, 8 KV heads, head size 128, in 16-bit?

  3. Users complain that time to first token is slow for very long prompts, but tokens then stream quickly. Which phase is the problem?

  4. Your app puts a timestamp at the very start of a long system prompt, and API bills show no prompt-caching discount. Why?

  5. A model loads fine, but crashes with out-of-memory errors only once several long conversations are running. What is the likely cause?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

vLLM documentation

vLLM project · Intermediate · Free

A widely used open-source LLM inference engine with paged KV cache, continuous batching and prefix caching.

Book

Build a Large Language Model (From Scratch)

Sebastian Raschka · 2024 · Intermediate · code free, book paid

Step by step from tokenizer to pretraining to fine-tuning a GPT-like model in PyTorch. The code repository is free.

Interactive

LLM Visualization

Brendan Bycroft · Intermediate · Free

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