Modern AI Engineering

KV Cache Explained: Why LLM Inference Needs It and What It Costs

By Modern AI Engineering · · 9 min read

Ask an LLM a question and the first word takes a moment, then the rest streams out quickly. Most of that speed comes from one simple trick: the KV cache. It is also the main reason long conversations eat GPU memory.

In short: when a Transformer generates text, every new token must attend to all earlier tokens. Without a cache, the model would recompute the key and value vectors for the whole prefix at every step. The KV cache stores those keys and values once and reuses them, so each step only computes the new token's key and value. The price is memory: the cache grows with every token, every layer and every user, and on long contexts it can be larger than the model weights.

A quick refresher: what keys and values are

Inside each attention layer, every token is turned into three vectors. The new token's query is compared with every earlier key to get attention weights, and those weights mix the earlier values.

  • Query (q): what this token is looking for.
  • Key (k): what this token offers to be found by.
  • Value (v): the information it passes on if it is attended to.

Why generation repeats the same work

LLMs generate one token at a time. To produce token 101, the model needs the keys and values of tokens 1 to 100. To produce token 102, it needs the keys and values of tokens 1 to 101.

The key observation: the keys and values of old tokens never change. In a decoder-only model, token 5 cannot see token 6, so its key and value at every layer are fixed once computed. Recomputing them at every step is pure waste.

Without a cache, generating n tokens means recomputing roughly 1 + 2 + 3 + … + n key and value rows per layer, which grows with n squared. With a cache, each step computes exactly one new row per layer, so that work grows only with n.

The KV cache in 30 lines of Python

The code below runs one attention head over 10 tokens twice: once recomputing everything, once with a cache. Both give identical outputs; the cached version simply does far less work. Real inference engines do exactly this, per layer and per head, on the GPU.

import numpy as np
rng = np.random.default_rng(0)
d = 16                       # model width (one head, for clarity)
Wq, Wk, Wv = (rng.standard_normal((d, d)) / np.sqrt(d) for _ in range(3))
def softmax(x):
e = np.exp(x - x.max())
return e / e.sum()
def attend(q, K, V):
scores = K @ q / np.sqrt(d)
return softmax(scores) @ V
tokens = rng.standard_normal((10, d))   # 10 token embeddings
# 1) No cache: recompute K and V for the whole prefix at every step
out_nocache = []
for t in range(len(tokens)):
X = tokens[: t + 1]
K, V = X @ Wk, X @ Wv                 # t+1 rows recomputed every step
out_nocache.append(attend(tokens[t] @ Wq, K, V))
# 2) With a KV cache: compute K and V once per token and append
K_cache, V_cache, out_cache = [], [], []
for x in tokens:
K_cache.append(x @ Wk)                # only the new token's key
V_cache.append(x @ Wv)                # only the new token's value
out_cache.append(attend(x @ Wq, np.array(K_cache), np.array(V_cache)))
print("Same outputs:", np.allclose(out_nocache, out_cache))   # True

Prefill and decode: the two phases of inference

The cache splits inference into two very different phases. This is why a long prompt delays the first word, and why streaming speed depends more on memory bandwidth than on raw GPU compute.

PhaseWhat happensBottleneckWhat users feel
PrefillThe whole prompt is processed in one parallel pass, filling the cache for every prompt tokenComputeTime to first token
DecodeOne token per step; each step reads the whole cache and appends one rowMemory bandwidthTokens per second while streaming

How much memory does the KV cache use?

For each token, every layer stores one key and one value vector for each key/value head. In bytes: KV bytes per token = 2 × layers × KV heads × head size × bytes per value. The 2 is for K and V.

Take a typical 7B-class model with 32 layers and 32 attention heads of size 128, stored in 16-bit precision (2 bytes per value):

  • Per token: 2 × 32 × 32 × 128 × 2 = 524,288 bytes, or 512 KiB.
  • One 8,192-token conversation: 4 GiB.
  • 32 such conversations at once: 128 GiB of cache, on top of about 13 GiB of weights.
  • That last line is the whole story of LLM serving: the cache, not the weights, decides how many users fit on a GPU.

Five ways engineers shrink the KV cache

Grouped-query attention is now standard in most open models, so check a model's config for num_key_value_heads before doing the memory math. Using the number of query heads instead overestimates the cache several times over.

TechniqueWhat it changesEffect on the example above
Grouped-query attention (GQA)Several query heads share one key/value head32 → 8 KV heads cuts the cache 4×: 128 KiB per token, 1 GiB per 8k conversation
Multi-query attention (MQA)All query heads share a single K/V headUp to 32× smaller, with some quality risk
KV cache quantizationStore K and V in 8-bit or 4-bit instead of 16-bit2× to 4× smaller
Paged KV cache (PagedAttention)Store the cache in fixed-size blocks, like operating-system memory pagesSame size per token, far less wasted memory, so more users fit
Sliding windowKeep only the most recent N tokens in some layersThe cache stops growing past the window

Prefix caching: reusing the cache across requests

If many requests start with the same system prompt or the same document, the engine can compute that prefix's cache once and reuse it. This is called prefix caching or prompt caching. It cuts time to first token and cost for chatbots, RAG systems with shared instructions, and agents that resend long tool definitions on every turn.

The rule that follows: put the parts of your prompt that never change first, and the parts that change last. A single changed character early in the prompt breaks reuse for everything after it.

Common mistakes

  • Sizing a GPU from model weights alone. A model that fits can still run out of memory at your real context length and batch size because of the cache.
  • Ignoring GQA in the formula. Use the number of key/value heads, not query heads.
  • Putting variable content at the top of the prompt. It defeats prefix caching.
  • Treating long context as free. Every extra token costs cache memory and decode bandwidth on every step.

How the KV cache fits into the bigger picture

The KV cache is the foundation for nearly every serving optimization. Continuous batching, paged attention, prefix caching and speculative decoding all exist to use it or manage it better. Module 13 of the course, Serving LLMs at Scale, covers each of these with interactive labs.

Frequently asked questions

What is a KV cache in simple words?

It is a memory of the key and value vectors an LLM has already computed for earlier tokens. Reusing them means each new token needs only one new key and value per layer instead of recomputing the whole history.

Does the KV cache change the model's output?

No. It gives exactly the same result as recomputing everything; it only removes repeated work. Quantizing the cache is the exception, since lower precision can shift outputs slightly.

Why does the KV cache use so much memory?

It stores two vectors per token, per layer, per key/value head, for every active conversation. Memory grows linearly with context length and with the number of users.

Is the KV cache used during training?

Not in the usual way. Training processes whole sequences in parallel, so there is nothing to reuse across steps. The cache matters during generation.

What is the difference between the KV cache and prompt caching?

The KV cache is reused within one generation. Prompt (prefix) caching keeps the cache of a shared prompt prefix and reuses it across different requests.

Learn it properly: the AI Engineering Bootcamp

More articles