What Is the KV Cache in LLMs? Key-Value Caching Explained

By LatestLLM Editorial · Published · Facts verified · 9 min read

Also called: key-value cache, KV caching, attention cache, past key values, prefix cache

Before this: Attention, Context window

In one line

The KV cache is the stored keys and values of every earlier token, kept so a language model can generate each new token without recomputing the whole conversation.

KV cache, simply and technically

In plain English

When a model writes an answer one word at a time, each new word has to look back at everything before it. Doing that from scratch every time would repeat almost all of its earlier work. Instead, the model saves the notes it made about each earlier word the first time it read it, and reuses them. That saved set of notes is the KV cache.

The notes take up memory, and the memory grows with every word in the conversation. For long conversations the cache can become the largest thing on the graphics card besides the model itself. That is why the cache decides how many people one server can answer at once, and why model designers work so hard to shrink it.

Think of it like this: The KV cache works like a student's index cards. After reading each page of a textbook, the student writes a card with what the page is about and what it says. When answering a question, they look through the cards instead of rereading the whole book. The cards save a great deal of time but take up desk space that grows with every page read, and unlike index cards, the model has to keep a card for every page in every one of its dozens of layers.

Everyday example: Why the second word is cheaper

A model is writing “The cat sat on the mat”, one word at a time.

Input:

Writing the 6th word

Output:

Without cache: process 5 earlier words again. With cache: process 1 new word

What it shows: To write “mat”, the model needs notes on “The”, “cat”, “sat”, “on” and “the”. Without a cache it would read those five words again from scratch. With a cache the notes already exist from earlier steps, so only the newest word is processed and its notes are added to the pile. The saving grows with length: at 1,000 words the cache avoids rereading the previous 999 every step.

Technically

In attention, each token produces a key and a value vector per layer, and a new token's query is compared with the keys of all earlier tokens. Those keys and values do not change once computed, so decoding stores them: the cache holds 2 × layers × kv_heads × head_dim numbers per token, at 2 bytes each in bfloat16. Generation then costs one token's worth of projections plus an attention read over the cache, instead of recomputing all earlier tokens, turning quadratic total work into linear work per step. GPT-2 small stores 2 × 12 × 12 × 64 × 2 = 36,864 bytes per token.

Memory is the problem. The cache is read in full at every step, so decoding is bound by memory bandwidth, and its size decides how many conversations fit on a GPU: PagedAttention (Kwon et al. 2023) manages it like virtual memory pages and improves serving throughput by 2 to 4 times. Architecture reduces it directly: grouped-query attention lowers kv_heads, sliding-window layers cap tokens per layer, and DeepSeek's multi-head latent attention caches one 512-number latent plus a 64-number RoPE key per token per layer.

Technical example: Cache size of real models

Cache bytes computed from published config.json values in bfloat16: GPT-2 small, gpt-oss-120b (36 layers alternating a 128-token window with full attention) and DeepSeek-V3 (61 layers, latent attention).

Code (python):

def per_layer(kv_heads, head_dim):
    return 2 * kv_heads * head_dim * 2        # keys and values, 2 bytes each

gpt2 = 12 * per_layer(12, 64)
print("GPT-2 small:", gpt2, "bytes per token,", round(gpt2 * 1024 / 1e6, 1), "MB at 1,024 tokens")

ctx = 131072
p = per_layer(8, 64)                           # gpt-oss: 8 KV heads of 64
oss = 18 * min(ctx, 128) * p + 18 * ctx * p    # 18 windowed layers, 18 full layers
full = 36 * ctx * p
print(f"gpt-oss-120b at {ctx:,} tokens: {oss / 1e9:.2f} GB (all-full-attention: {full / 1e9:.2f} GB)")

mla = 61 * ctx * (512 + 64) * 2                # one latent + RoPE key per token per layer
mha = 61 * ctx * 128 * (192 + 128) * 2         # same shape with a KV pair per head
print(f"DeepSeek-V3 at {ctx:,} tokens: {mla / 1e9:.2f} GB (one KV pair per head: {mha / 1e9:.1f} GB)")

Output:

GPT-2 small: 36864 bytes per token, 37.7 MB at 1,024 tokens
gpt-oss-120b at 131,072 tokens: 4.84 GB (all-full-attention: 9.66 GB)
DeepSeek-V3 at 131,072 tokens: 9.21 GB (one KV pair per head: 655.0 GB)

What it shows: The cache for one 131,072-token conversation is 4.84 GB for gpt-oss-120b and 9.21 GB for DeepSeek-V3, against 655 GB if DeepSeek kept a key and value for each of its 128 heads. The same arithmetic tells a service how many simultaneous long conversations a GPU's spare memory can hold.

How big is the KV cache?. Pick a model and a conversation length. The bars compare the estimated KV cache of the real model with the same shape using full attention on every layer and one key and value per head, and the readout gives bytes per token and the share of an 80 GB GPU. Computed from the published config.json values of each model in bfloat16, the same estimate used in the LLM architecture guides.

What the cache holds

In plain English: Every time the model reads a token it writes two short lists of numbers about it, one used for matching (the key) and one that carries the content (the value). The cache is the collection of these lists for every earlier token, in every layer. A new word is matched against all of them to decide what to read.

Technically:

Per layer and token, the model stores one key and one value vector for each KV head. A query from the new token is multiplied with all cached keys to produce scores, and the softmax weights are applied to the cached values. Because the causal mask means earlier tokens never see later ones, their keys and values never change, so caching them is exact and does not alter the output.

The cache is built in two phases. In prefill, the whole prompt is processed in parallel and its keys and values are written. In decode, each new token adds one entry per layer, and the cache is read in full for attention.

What is prefill?

The first stage of a request, in which the model processes the whole prompt in parallel and fills the cache.

What is decode?

The second stage, in which tokens are produced one at a time, each reading the cache.

How big it gets

In plain English: The cache is small for a short chat and huge for a long one. Its size is the notes per word multiplied by the number of words, and the notes per word depend on how many layers the model has and how many notes each layer keeps.

Technically:

The formula is bytes per token = 2 × layers × kv_heads × head_dim × bytes per number. GPT-2 small, with 12 layers and 12 heads of 64, needs 36,864 bytes per token. Models with sliding windows count fewer tokens in local layers: at 131,072 tokens, gpt-oss-120b's 18 windowed layers hold only 128 tokens each, giving a total of 4.84 GB instead of 9.66 GB. Gemma 4 31B at 262,144 tokens needs an estimated 11.6 GB where the same shape with full attention and one KV pair per head would need about 258 GB.

These are per-conversation figures. A server handling 32 such conversations needs 32 times as much, on top of the weights, so the cache often decides the batch size and therefore the cost per token.

Everyday example: Memory for many users

A server wants to answer many long conversations at once.

What it shows: If each conversation's notes take 5 GB, a card with 20 GB to spare can hold only four of them at a time. Halving the notes per conversation doubles how many people it can serve, which is why designers shrink the cache.

Why the cache limits speed

In plain English: To write each word, the model has to read the whole cache. Reading memory is slower than calculating, so the speed of writing is set by how fast the card can move data, not by how fast it can add numbers. A smaller cache is therefore also a faster one.

Technically:

During decoding the arithmetic per token is small compared with the bytes moved: the weights of the active layers and the full cache are streamed from high-bandwidth memory every step. Multi-query attention was proposed by Shazeer (2019) precisely because the memory-bandwidth cost of repeatedly loading large key and value tensors dominates incremental decoding.

Serving systems also care about fragmentation. Pre-allocating a maximum-length cache for every request wastes memory; PagedAttention splits the cache into fixed-size blocks allocated on demand and shared across requests with a common prefix, which Kwon et al. report improves throughput by 2 to 4 times at similar latency.

Ways to shrink the cache

In plain English: Model designers attack the cache from every side: keep notes for fewer heads, keep notes for only recent words in most layers, store a compressed version, or store the notes in fewer bits. Each saves memory at some cost in complexity or quality.

Technically:

Grouped-query attention shares each KV head among several query heads (gpt-oss: 8 KV heads for 64 query heads, an 8× saving). Sliding-window layers cap cached tokens (gpt-oss: 128, Gemma 4: 1,024). Multi-head latent attention stores one compressed vector: DeepSeek-V2 reports a 93.3% smaller cache than DeepSeek 67B, and V3 stores 576 numbers per token per layer. Gemma 4 additionally reuses keys as values on global layers and shares caches across layers in its small models.

Quantising the cache itself to 8 or 4 bits, and discarding or compressing tokens that matter little, are applied by some serving stacks. Prefix caching reuses the cache of a shared prompt prefix, such as a long system prompt, across requests.

Common misconceptions

  • Myth: The KV cache stores the model's answers so it can reuse them.

    Reality: It stores intermediate keys and values of the tokens in the current conversation, not answers. It is discarded or re-created when the conversation ends.

  • Myth: Caching changes or approximates the output.

    Reality: Caching is exact: the keys and values of earlier tokens never change, so the model produces the same tokens with or without it, only faster.

  • Myth: The model weights are the only thing that needs GPU memory.

    Reality: For long conversations and many users the cache can be as large as, or larger than, the weights.

Where you'll see this

Key takeaways

  • The KV cache stores the keys and values of all earlier tokens so each new token needs only its own computation plus a read of the cache.
  • Its size is 2 × layers × KV heads × head dimension × bytes per token, and it grows linearly with conversation length.
  • For a 131,072-token conversation the estimated cache is 4.84 GB for gpt-oss-120b and 9.21 GB for DeepSeek-V3 with latent attention, against 655 GB without it.
  • Grouped-query attention, sliding windows and latent attention exist mainly to shrink this cache.

Frequently asked questions

What is the KV cache in an LLM?

It is the memory that holds the attention keys and values of all earlier tokens, so the model can generate each new token without recomputing them.

How big is the KV cache?

2 × layers × KV heads × head dimension × bytes per number, per token. For gpt-oss-120b at 131,072 tokens it is about 4.8 GB.

Why does a long conversation use so much memory?

The cache grows linearly with the number of tokens, in every layer, and must stay in GPU memory for the whole conversation.

Does the KV cache change the model's output?

No. It is an exact optimisation that avoids recomputation and gives identical results.

How can the KV cache be made smaller?

With grouped-query or latent attention, sliding windows, quantised caches and prefix sharing.

Sources

Facts last verified November 23, 2026.

Next concept: Grouped-query attention

Learn next

  • Grouped-query attention (Intermediate): Grouped-query attention lets several query heads share one set of key and value heads, cutting the KV cache by the group size at little cost in quality.
  • Sliding-window attention (Intermediate): Sliding-window attention limits each token to reading only the most recent fixed number of tokens, so attention work and cache size stop growing with the length of the text.
  • Latency and throughput (Intermediate): Latency is how quickly one request gets its tokens and throughput is how many tokens a server produces in total; for LLM decoding both are limited mainly by how fast weights can be read from memory.