The Illustrated KV Cache

Open the pricing page of any large-model API and you see two things: output costs 3–5 times the input price; and for input, a cache hit is 10–50 times cheaper than a cache miss. This essay explains both.

There is one thread: the K and V inside self-attention. Store them, and that is the KV Cache. We follow the method of “The Illustrated Transformer”: first treat the model, from the outside, as an “input token → output token” interface, then take the inside apart layer by layer, put the vectors into the figures, and finally come back to the bill.

If you have not read The Illustrated Transformer, read it once first. Either way, the parts we need are explained again below.

On the pricing page, output costs several times more than input

Let’s look at the model from the outside first. You give it a prompt (the input), and it returns an answer (the output). The API bills per token. Input and output are counted separately.

Input and output are priced separately: each output token costs several times one input token.

Below are prices for a few main models, taken from the official pricing pages of three vendors (per million tokens, captured on 2026-11-24). Each row has three prices on the left and two ratios on the right.

Each row is one model. Left: the dollar price of input (cache miss), cache hit, and output. Right: how many times output costs versus input, and how many times cheaper a cache hit is than a cache miss.

Those are the two facts: the output price is 3–5 times the input price; input on a cache hit is 10–50 times cheaper than input on a cache miss. We take them one at a time. First, the inside of the model.

Inside the model is a stack of decoders

Prefill and Decode use the same stack of decoders

Unlike the original in “The Illustrated Transformer”, today’s large models (GPT, Claude, DeepSeek, and the like) keep only the decoder. They are called decoder-only. Open the model and you find a stack of decoder layers, all with the same structure.

The whole model → a stack of decoders → each decoder has two sublayers. The number of layers is not magic. It differs by model.

Each decoder splits into two sublayers. The input first flows through the self-attention layer — while the model handles one word, this layer lets it look at the other words. The self-attention output then goes into a feed-forward network. Self-attention in the decoder is masked: each word can see only itself and the words to its left. It cannot peek to the right.

One request splits into two phases. Prefill: read the whole prompt in one pass. Decode: then write one token at a time. The two facts on the bill sit in the difference between these phases.

Prefill is not an encoder. The original Transformer has two parts, an encoder and a decoder (translation is the example: the encoder reads the source, then the decoder writes the translation one word at a time). Today’s GPT, Claude, and DeepSeek models have only a decoder. They have no encoder. Prefill and Decode use the same stack of decoders and the same weights. They are two ways of running. Prefill sends every word of the prompt all at once, in parallel (masked, so each word looks only to the left), stores each word’s K and V along the way, and produces the first output word. Decode sends in 1 new word each time. So they are two phases of inference, not two modules.

Two ways to use the same Decoder. Prefill: n words enter in parallel at once, every word’s K and V are written into the KV Cache in one shot, and the first output word comes out. Decode: 1 new word enters each time, the cache is read, then that word appends its own K and V. The figure above plays on its own: Prefill first, then Decode.

What does Prefill produce? Take the prompt I love eating. After Prefill finishes, two things remain:

  1. KV Cache: the K and V of these 3 words at every layer. They stay in GPU memory, and every later Decode step reads them. This is the main product.
  2. The first output word: at the last word, eating, the model computes the probability of “what the next word is” (for example fresh at 0.62) and picks one. That pick is the first output word. The first two positions also produced a prediction, but in the prompt their next word is already known (love follows I), so those predictions are unused.

Everything else is thrown away: the intermediate results each word produces in each layer, including Q. One way to see it: K and V are “notes” kept for later lookup. Q and the intermediate results are “scratch paper”. They are thrown away after use.

Two direct consequences follow. A longer prompt means Prefill handles more words, so the user waits longer for the first character, and more “notes” are left behind, so the KV Cache is larger. Prefix caching saves money for the same reason: last time’s “notes” are still there. If this prompt starts the same way, use them directly. There is no need to run Prefill again from the start.

Each word first becomes a vector

Now look at how vectors move between these parts. As in every NLP model, we first turn each word into a vector (an embedding).

Each word becomes a vector. Drawn here as 4 cells. A real model has several thousand dimensions.

The word at each position flows through the decoder along its own path. One key property: paths depend on each other only in the self-attention layer. The feed-forward network applies the same network independently at each position, so the paths can run in parallel.

Self-attention is where the paths exchange information. Each path runs the feed-forward network on its own.

This is why Prefill is fast: the paths of every word in the prompt can be computed together. We come back to this later.

Q, K and V all come from the same vector

The first step of self-attention builds three vectors from each word’s vector: Query, Key, and Value. Each one is the embedding multiplied by one of three trained matrices.

Multiply x by three trained matrices W to get q, k, and v. k and v stay in the cache. q is thrown away after use.

Where do these three matrices W come from? WQ, WK, and WV are the model’s weights. They are learned during training and fixed once training ends. At inference every word uses the same set (each layer and each head has its own set). The formulas are simple: q=xWQ, k=xWK, v=xWV, where x is this word’s input vector at this layer (the embedding at the first layer; after that, the previous layer’s output). Because the W’s are the same set, Prefill can multiply every word in one shot. For the same word at the same layer, x and W do not change, so the k and v it produces are always the same. That is exactly why K and V can be cached.

What are they? Abstractions built so attention can be computed and understood. Picture a library: Q is the little slip in your hand (what I want to find right now), K is the category label on the shelf, and V is the book itself.

Step two is scoring: take the current word’s q and dot it with each word’s k. Step three divides by d and applies softmax, turning the scores into weights that add up to 1. Step four multiplies those weights by each word’s v. Step five adds them up, and that sum is the current word’s output z. The figure below walks through these five steps.

The current word is “eating”: its q is scored against the k of “I, love, eating”, then their v’s are mixed by those weights. The numbers inside the vectors are illustrative.

As a single formula, the current word’s output is:

z=softmax(qK⊤dk)V

Here K and V are the matrices stacked from the k and v of every visible word, and dk is the dimension of k.

Notice the difference in the figure between q and k, v: q belongs only to the current word, and only this step uses it; k and v belong to every word, and every later step uses them again. Remember that sentence. The whole secret of the KV Cache is in it.

The next word is picked from z

We have z, but what the model finally emits is one word. A few steps still sit between z and the word. (This section is the general mechanism. The video does not cover it.)

From z to the next word: after several layers we get a vector h, multiply by the vocabulary matrix to score each word, softmax turns the scores into probabilities, and one word is picked.

  1. Concatenate the z from each head, multiply by a matrix, and add this layer’s input (the residual connection).
  2. Pass through the feed-forward network, and add the residual again. This layer is done.
  3. Repeat for N layers. One layer’s output is the next layer’s input. The last layer writes a vector h at each position, the same length as the embedding.
  4. Multiply h by the “vocabulary matrix” (the LM head) to get one score per word in the vocabulary. These scores are called logits: s=hWvocab. A vocabulary usually has tens of thousands to more than a hundred thousand words.
  5. softmax: turn the scores into probabilities that add up to 1: pi=esi∑jesj.
  6. Pick a word: take the highest probability, or use Temperature and Top-P to sample among the high-probability words.
  7. The pick is an index in the vocabulary. Turn it back into text, and that is the next character you see.

When the next word is generated, only the h at the last position is used. The h at the other positions is unused at this step. That is why Prefill uses only the result at the last input word to produce the first output word.

Is z this word’s embedding? No. An embedding is the vector looked up by word index. It depends only on the word itself, so the embedding of eating is always the same. z is this word’s vector after it has seen the context. The V of earlier words is mixed in, so z differs when the words before it are I love or something else. One easy mix-up: the vector finally computed at the position eating predicts the word after it (fresh). It does not describe eating itself.

The attention figure above draws only one head, and it leaves out the residual and the feed-forward network, so it is easier to follow. In a real model, z goes through these steps before it becomes this layer’s output.

Without a cache, every step recomputes

Each decode step writes one word

After Prefill, the model has the first output word. Then Decode starts: append this new word, run again, and get the next word. Append that, run again, and so on, until the end token.

No cache: every step recomputes the K and V of every earlier word. Orange is K. Blue is V.

Look at the small K and V cells in each row. Row 2 recomputes the K and V of “I, love, eating”, and row 3 computes them again — and those K and V values match the row above exactly. A word’s K and V depend only on itself and the words to its left. If the left side has not changed, the result does not change.

Without a cache, generating the n-th word recomputes the K and V of the n words before it. In total that is 1+2+…+n≈n2/2 times (counting how many times K and V are computed). Once n reaches a few thousand, this is a huge waste.

Keep the K and V you have already computed

The fix is plain. The first time a word’s K and V are computed, store them in GPU memory. After that, each step only computes the q, k, and v of the new word. The K and V of earlier words are read straight from the cache.

With a cache: the dashed cells are read from the cache. Only the new word’s K and V are computed.

Now each step newly computes the K and V of 1 word. The total K and V computation drops from about n2/2 to n — this is “trading space for time”. The cache saves only “recomputing K and V”. Attention scoring (the new word’s q dotted with every past K) still runs every step, and one step is O(n).

This also answers a common interview question: why cache only K and V, and not Q? Q is useful only at the current step. Once it is computed, it is discarded, and the next step has a new Q. K and V are the history. Every step looks them up.

What is worth storing is what this step computes, what every later step uses again, and what will not change.

K and V are exactly that. Every new word takes its own q, scores it against the K of every past word, then mixes the V of every past word. A past word’s K and V depend only on itself and the words to its left. If the left side has not changed, they do not change.

Q belongs only to the current step. The next step has a new Q, so Q is not stored. Attention scores, weights, and the output z are all computed from the current word’s q. When q changes, they change, so every step recomputes them.

What does the cache actually store? It stores the K and V of every past word, at every layer. Not Q, and not the “result” of attention:

ThingCached?Why
KcachedEvery new word scores its own q against the K of every past word. K depends only on that word and the words to its left, and it does not change later
VcachedAfter scoring, the weights mix the V of every past word. V does not change either
Qnot cachedUseful only at the current step. The next step has a new Q
Attention scores and weightsnot cachedComputed from the current word’s q and the past K. Each new word brings a new q, so they are recomputed
Output znot cachedIt is the result of the current word’s q. Later words do not use an old word’s output directly. They read that old word’s K and V at every layer

An old word’s output becomes its own K and V in the next layer, and those were already stored the first time that layer ran. So the cache keeps one copy at every layer. That is where the GPU memory use comes from.

Output costs more because decode goes one step at a time

Now the first fact can be explained. (What follows is derived from the mechanism, not from a vendor document. The video and the pricing page do not say this directly.)

Prefill is one parallel pass. Decode is one word per step, and every step moves the weights and the whole KV out of GPU memory.

Prefill: the n words in the prompt go through the model together (remember that each feed-forward path can run in parallel?). It is large matrix multiplication, and the GPU’s compute is fully used.

Decode: each step produces only 1 word, and it has to wait for the previous word before it can compute the next. But every step moves the whole model’s weights and the KV of the whole history from GPU memory to the compute units, while the actual arithmetic is small — the bottleneck moves from “compute” to “GPU memory bandwidth”.

So output is “computed one by one”. It occupies the GPU for longer, and one card can serve fewer requests at the same time. On the pricing page, output at 3–5 times input roughly reflects this difference (the exact multiple is each vendor’s pricing decision).

The cache saves repeated computation, but GPU memory still grows

KV grows with context and with concurrency

The KV Cache is not free. The model weights have a fixed size, while KV grows with context length and the number of concurrent users. Drag the sliders below.

A sketch: the numbers are not from any real model. They only say “the weights stay fixed, and KV grows with length and concurrency”.

The estimate (the general form):

KV size≈2×L×Hkv×dhead×n×B×b

Here 2 is the two copies, K and V. L is the number of layers, Hkv is the number of KV heads, dhead is the dimension of each head, n is the sequence length, B is the concurrency, and b is the bytes per number. With long text or many users at once, the GPU memory taken by KV can far exceed the weights themselves. An 80G card runs out of memory quickly. This is the so-called “GPU memory wall”.

The KV Cache uses this much GPU memory. Does that mean the context cannot be very long? Not “cannot”. “Very expensive”. KV size grows in proportion to context length. Here is a concrete example (a public 70B-class model: 80 layers, 8 KV heads, 128 dimensions per head, 16-bit storage. I computed this from the structure myself. These numbers are not from the video): the KV for each token is about 2×80×8×128×2 bytes ≈ 0.31 MB. A context of 128K tokens is about 40 GB, and that is only one user. Serving 10 users at the same time, KV alone is about 400 GB, far past one card’s GPU memory.

Context length is limited by more than GPU memory. Prefill’s attention compute is about O(n2), and it grows with the square of the length (each word is scored against every word to its left; during Prefill there is no cache yet, and the cache does not save the scoring either), so a longer context means a slower first character. How long a context the model saw in training also sets how long it can use stably. When the context is too long, the model also tends to miss information in the middle. So a long-context model does not get there by “storing a bit more”. It compresses KV (see the next section), quantizes KV, and moves KV that is not needed right now to CPU memory or to disk.

So the whole field is looking for ways to compress it. vLLM’s PagedAttention pages KV the way an operating system pages virtual memory, which cuts fragmentation. The more fundamental fix is to make KV itself smaller.

You can make each copy thinner, or merge several copies into one

There are two directions: make each copy of KV smaller, or make the number of copies smaller.

A sketch: the width of one row stands for the same 128 tokens. Each block is one stored copy of KV. Taller means each copy is larger. Wider means more tokens were merged.

Numbers from the video: the KV Cache of V4 Flash is only about 7% of V3’s. At a context of 1 million tokens, V3 needs about 84GB of GPU memory, roughly one top-spec H100. MLA is not enough once the context reaches a million tokens — it compresses “thickness”, and 1 million words are still 1 million copies. (These numbers come from a Bilibili video and were not checked against the technical report.)

When the beginning matches, you can skip a pass

So far the KV Cache is valid only inside a single request: once the answer ends, the notes in GPU memory are cleared. But the start of each Agent turn is often the same system prompt and the same tool definitions.

Prefix caching keeps the KV of the shared prefix in a shared cache pool. If the next request starts the same way, it is read directly and Prefill is skipped. That is why “cache-hit input” is cheap on the pricing page. Time to the first character can drop from a few seconds to a few tens of milliseconds.

How do you find a reusable prefix within milliseconds? The inference engine cuts the text into fixed-size token blocks (for example, 16 tokens each), hashes each block, chains the hashes, and organizes them as a prefix tree (a radix tree). If 100 users share one system prompt of 10,000 tokens, only one trunk is stored. Each person’s question is a small branch off it. When GPU memory is tight, LRU evicts the branch that has gone unused the longest.

Click a block in the lower row to mark “this block changed”. From the first block that differs, everything after it is a cache miss (Hit = cache hit, Miss = cache miss).

There is only one rule: the match has to be exact, character by character, starting from the first token. Change one character at the start and the hash chain breaks at the root. Even if 10,000 characters after that are identical, all of them have to be recomputed.

Put what stays fixed in front, and what changes at the end

  1. Put static content first and dynamic content last. The system prompt, tool definitions, and fixed documents go in front. The user’s question, the timestamp, and the session ID go at the end.
  2. Do not write the time, the user ID, or the status at the start of the prompt. This is the most common kind of “prefix pollution”.
  3. Do not add or remove tools in the middle of a conversation. If the tool list changes, the prefix breaks.
  4. Look at the hits, then optimize. Look at the cache-hit token count in the API response (on DeepSeek this is prompt_cache_hit_tokens). Only a number that keeps rising means you are actually hitting the cache.
  5. Vendors work differently. Claude needs cache_control on the request (you can add a single top-level field and let the system manage the breakpoints). A 5-minute cache write is 1.25 times the input price, a 1-hour write is 2 times the input price, and a hit read is 0.05–0.1 times. OpenAI’s pricing page lists a cache-write price on its own (Sol as the example: 1.25 times for 30 minutes, 2.5 times for 12 hours). DeepSeek detects the prefix on its own. No code change.

Further reading: Lessons from Manus on context engineering (a note in this library) (KV Cache optimization and a 10-times difference in cost).

DeepSeek stores computed KV on disk

Automatic hits. No code change. The backend finds repeated prefixes and caches them on its own.

KV is written to disk, not only kept in GPU memory. Computed KV is moved to a distributed SSD array. Reading from disk is a bit slower than reading from GPU memory, in exchange for huge capacity at a very low cost. There are three moments when it is written out. When a request ends (the end of the input and the end of the output are each packed as one unit, so turn two of a multi-turn conversation can hit turn one). A shared prefix (when different questions share a long document or a system prompt, the backend pulls that shared prefix out and stores it on its own). A fixed token interval (a very long context is sliced at a fixed stride).

Make KV itself smaller. From MLA in V2/V3 to CSA + HCA in V4 (the figure above). Smaller KV lowers the pressure on GPU memory and lowers the storage cost.

The result shows up in the price. The video says a cache hit is 30 times cheaper, which matches the price at that time. On the official pricing page of 2026-11-24, the V4 Flash peak price is $0.006 versus $0.30, a gap of 50 times; V4 Pro is $0.044 versus $1.32, a gap of 30 times. One card can serve more requests at once, which is also why V4 can set the default context to 1 million tokens.

Think of it as a word-chain game

  1. AI writes like a word chain. It can write only 1 character at a time. Reading the question is one look (think once). Writing 6 characters takes 6 thoughts. Each thought keeps the computer busy once, so writing costs more than reading the question.
  2. Each new character means looking back over every character so far. Otherwise the writing does not hold together. Rereading every time is tiring.
  3. The fix: keep a notebook. Write down what mattered in what you read. Next time, open the notes and read only the one new character. That notebook is the KV Cache.
  4. The notes record only K and V, not Q. Picture a library. Q is your checkout slip, thrown away after you borrow the book. K is the category label on the shelf. V is the book. The label and the book are needed again next time, so they stay.
  5. The notebook keeps getting thicker, but the desk (GPU memory) is only so big. So write each page more tightly (MLA), merge a few neighboring characters into one entry (CSA, HCA), and move what does not fit into a big warehouse (disk).
  6. Why does the cache save money? If today’s opening is identical to yesterday’s homework, you can copy the notes directly. But it has to be identical starting from the first word. Change the first word and everything after it is “unrecognized”. You read it again and you pay again. So put what stays fixed in front, and put what changes (such as the time) at the end.

What to remember

Further reading