Paste a thirty-page contract into a chatbot and ask it, “What does Clause 7 say?”
After you hit send, the screen sits there for a second or two with nothing on it. Then the first word pops up, and the rest follow one after another at a steady pace, as if someone were typing on the other end.
Now flip through the API pricing pages of the different providers. Next to the price for input tokens, there's often one more column, labeled “cached input”. When the same prompt is sent a second time, the price in that column is only a tenth of the regular one.
The pause of a second or two after you hit send, the steady pace of the words that follow, and that discounted column on the pricing page all come from the same thing. It's called the KV cache.
This article starts with how a model says a single word and does the math on how much effort goes to waste without a cache. Then we look at what the cache stores, how big it gets, and why it slows things down, and finally at the ideas people have come up with to make it smaller. Every figure in the article is interactive, and the numbers are recomputed live as you change the settings.
A model says one word at a time
Let's start with one term. The unit a model reads and writes text in is called a token. A token is roughly a word, a single character, or part of a word. Split into tokens, “The weather is nice,” might look like this:
The | weather | is | nice | ,
The actual split is decided by each model's tokenizer; this is just an illustration. From here on, we'll use these five tokens as our prompt.
A language model does only one thing. It looks at all the tokens so far and guesses which token comes next. Once it guesses “let's”, it appends that to the end of the sentence, then looks at these six tokens and guesses the next one. It guesses “go”, appends that too, and keeps repeating until the model decides to stop:
The | weather | is | nice | , | let's
The | weather | is | nice | , | let's | go
The | weather | is | nice | , | let's | go | outside
This way of producing one token at a time, appending it, and then producing the next is called autoregressive generation. The words in the chat window pop up one at a time because the model really does produce them one at a time.
For now, hold on to one thing. Every time the model produces a new token, it has to look back at all the tokens before it. That act of looking back is called attention.
Looking back: what attention computes
When the model is producing the word after “go”, it has to decide which of the earlier words matter more. The clue for “outside” probably comes from “weather is nice” and “go”, while “The” matters much less.
Attention is what does this picking. It prepares three things for every token:
- Query (Q): the vector the new token uses to ask its question, roughly “What information do I need right now?”
- Key (K): a label every token wears, so others can judge “How relevant am I to your question?”
- Value (V): the content each token actually hands over.
The computation takes three steps. First, the new token's Q takes a dot product with every token's K, which gives a score. Softmax then turns the scores into weights that add up to 1. Finally, adding up every token's V according to those weights gives the output of this attention step.
Described in words, this is pretty abstract, so let's work through it once with tiny numbers. In the figure below, the vectors have only 2 dimensions so they can be drawn on a flat plane. There are four tokens already in place, each with one K and one V. The orange arrow is the new token's Q, and you can rotate it:
Let's start with the default angle of 30 degrees. Q is , and its dot products with the four Ks are , , , and . Each dot product is first divided by the square root of the dimension (here ) to keep the numbers from getting too large, which gives , , , and .
Softmax turns these four scores into the weights , , , and , which add up to exactly 1. The third K points closest to Q and gets the largest weight. The fourth K points almost the opposite way, and its weight is down to 0.04.
Finally, adding up the four Vs with these weights gives the output . Rotate Q, and you'll see the largest weight move to whichever token points closest to Q, with the output arrow leaning over toward it.
Written as a formula, it's that one line from the Transformer paper:
and are the matrices you get by stacking every token's K and V, and is the dimension of the vectors.
So where do Q, K, and V come from? When a token enters an attention layer, it's a vector . The model has three trained matrices, , , and , and multiplying the vector by each of them gives:
In a real model, the vectors have thousands of dimensions, dozens of attention layers are stacked on top of each other, and each layer is split into several “heads”, each with its own set of Q, K, and V. But every head does exactly what the figure above shows.
Store nothing, and every step starts from scratch
Now let's join the last two sections together. Every time the model produces a token, it has to compare the new token's Q against the K of every earlier token, then draw on their Vs.
The most direct way to write this is to feed “the whole sentence so far” back into the model at every step and compute everything from the first layer to the last. That way, the K and V of every earlier token get computed all over again at every step.
The figure below counts exactly that work. The two small squares that go with each token are its K and V. The ones recomputed in this step light up orange, and the ones simply reused are blue. First choose “Without cache”, then press play:
In step 0, reading the prompt means computing K and V for 5 tokens. After that, every new token means computing all the tokens so far once more, so it's 6 pairs, then 7, then 8… By the fifth new token, 45 pairs have been computed in total.
Look closely, though, and the K and V of “The” come out exactly the same every time, from step 0 to step 5.
Why are they the same? Because during generation, attention follows a rule that each token can look only at itself and the tokens before it, with no peeking at what comes after. “The” is the first token, so at every layer its computation uses only itself, and no matter how many new words get added after it, none of them can change it. The second token, “weather”, looks only at “The” and itself, so it doesn't change either. The same goes for the rest: every K and V of an old token, at every layer, comes out fixed.
This rule is called the causal mask. Drawn as a grid, each row is one token's Q and each column is one token's K, and only the cells on the diagonal and below it to the left get computed. Drag the slider below and watch how the grid grows with each new word:
Each extra token adds just one row at the bottom of the grid, and the rows above don't move at all.
The grid hides one more thing. Switch to “Where Q is used”, and you'll see that each row's Q is used only once, at its own step, and never again. Switch to “Where K and V are used”, and each column's K and V, by contrast, are read by the new row at every single step.
So the answer comes naturally. Compute K and V once and store them, then reuse them directly at every later step; throw Q away once it's been used. These stored Ks and Vs are the KV cache. That's why there's no Q in the name.
Go back to the generation figure, switch to “With cache” and play it again. Reading the prompt still takes 5 pairs, but after that each step computes only the 1 pair for the new token, for a total of 10 pairs, far fewer than 45.
Once K and V are stored
In code, each step of generation now looks like this:
# Each step sends only "the one new token" into the attention layer
q, k, v = x_new @ W_q, x_new @ W_k, x_new @ W_v # each is [1, d]
K = torch.cat([K_cache, k], dim=0) # [t, d]: the old K plus the new one
V = torch.cat([V_cache, v], dim=0) # [t, d]
out = torch.softmax(q @ K.T / d ** 0.5, dim=-1) @ V # [1, d]
K_cache, V_cache = K, V # store them back for the next step
Every layer and every head has its own K_cache and V_cache. The new token computes only its own Q, K, and V. Its K and V are appended to the end of the cache, and its Q is used to run attention over the whole cache.
How much does this save? The figure below plots “how many times K and V are computed in total”, with the number of generated tokens on the horizontal axis. Try dragging the slider:
With no prompt and 1,000 generated tokens, going without a cache takes computations, while with a cache it takes only 1,000, a five-hundredfold difference. Switch the scale to “Linear”, and the no-cache line bends upward, because the work per step grows with the length; the cache line is straight, since each step adds just one more. Switch back to “Log”, and both lines straighten out, but the no-cache line is steeper, and the gap keeps widening.
This also explains the pause of a second or two we started with. After you hit send, the model first has to read the entire prompt, computing K and V for every token and storing them in the cache. This stage is called prefill. The prompt's tokens can be computed together in parallel, but a thirty-page contract easily runs to ten thousand tokens or more, so it still takes a moment.
Once the cache is built, the model moves on to decode. Each step computes just one new token, which is why the words come out at such a steady pace.
The cost: a cache that keeps growing
The computation we saved doesn't come for free. The cache takes up memory, and it keeps getting bigger.
Let's work out how much a single token needs. Take Llama 3 8B. It has 32 layers, and each layer has 8 KV heads, which means it stores 8 sets of K and V (its 32 attention heads share these 8 sets; we'll see why later). Each KV head's K or V is 128 numbers, and each number is stored in BF16, taking 2 bytes:
The leading 2 is one copy each for K and V.
128 KiB per token doesn't sound like much. But a thousand tokens is 125 MiB, 128,000 tokens is 15.6 GiB, and a million tokens takes 122.1 GiB, eight times the size of the model's own weights (about 15 GiB).
The calculator below lets you change the model, the length, and the number of users served at the same time (the batch). Each person's conversation has its own cache, so the batch multiplies straight into the total:
Try these settings:
- Llama 3 8B, a million tokens, batch 1: 122.1 GiB, too much even for a single 80 GB data-center GPU.
- The same model, 8,000 tokens, batch 32: 31.3 GiB. The context isn't long, but with many people served at once, the cache still ends up bigger than the weights.
- GPT-3 175B: each of its 96 heads stores its own K and V, so a single token takes 4.5 MiB, and a million tokens come to 4.29 TiB.
- DeepSeek-V2: a token needs only about 67.5 KiB. It uses a different way of storing the cache, which we'll get to later.
Google gave a similar example in a 2022 paper. For a model with more than 500 billion parameters in which every head stores its own K and V, at batch 512 and a context of 2048, the KV cache totals 3 TB, three times the size of the model's parameters.
Why generation is always waiting on memory
A big cache isn't only a question of whether it fits. It also slows things down.
A GPU has two kinds of resources. One is its compute units, which do the multiplying and adding. The other is memory bandwidth, which carries data from the card's memory over to the compute units. Every time the model produces a token, it has to do two things:
- Read all the weights once, since every layer needs them.
- Read this conversation's entire KV cache once, since the new token has to attend to every old token.
Once all that is read in, the actual multiplication is fairly light. Generating one token takes about “parameter count × 2” operations. The figure below uses Llama 3 8B to estimate how much data one step moves and how long it takes. Memory bandwidth and compute speed are estimated from the specs of a single H100 (3.35 TB per second, and 989 trillion BF16 operations per second):
At the default batch 1 and 8,000 tokens, one step moves about 15.9 GiB, 15 GiB of which is weights. Moving it all takes 5.1 milliseconds, while the computation takes only 0.016 milliseconds. The compute units spend more than 99% of the time waiting for data.
That's why everyone says the generation phase is memory-bound, held up by memory bandwidth.
So what can be done? The most common approach is to group many people's requests into one batch and compute them together. The weights are read once and used for everyone in the batch, so the cost of moving them gets shared out.
The KV cache can't be shared out like that. Everyone's cache is different, so the bigger the batch, the more cache there is to move. Push the batch to 8 and the context to 32,000 tokens, and the cache segment of the bar is already twice as long as the weights segment.
The Google paper puts it bluntly. With a large context and batch, the time spent reading the KV cache dominates generation. For every token generated, the chip has to read the cache from memory once, and during that time its computational core “is essentially idle”.
Why repeated prompts get a discount
The KV cache has one more benefit. Since a prompt's K and V never change once computed, if two requests begin with exactly the same text, the later one can reuse the cache the earlier one already computed, skipping even the prefill.
That's where the discounted column on the pricing page comes from. Here's what each provider's official documentation says as of December 2026:
- Anthropic: requests are cached only when you mark them with
cache_control. Input read from the cache costs 0.1 times the regular price, while writing to the cache costs 1.25 times; by default the cache is kept for 5 minutes. - OpenAI: caching is automatic by default on supported models. The documentation states that the whole prefix has to match exactly before it can be reused.
- DeepSeek: on by default for all users, under the name “Context Caching on Disk”.
- Google Gemini: models from 2.5 onward have implicit caching turned on by default.
The rules differ from provider to provider, but what they have in common is that the match is made on the beginning. The three requests below share the same long system prompt. Let's see which of them gets a free ride from the cache:
Request A comes first, so the whole thing has to be computed, and the result is stored. Request B starts exactly the same way as A, so its first 12 blocks are read straight from the cache, and it computes only its own question.
Request C changes only the first word of the system prompt. Because every token's K and V are shaped by all the tokens before it, once the beginning changes, nothing after it matches, and the whole thing has to be recomputed.
So when you use an API, one simple habit saves money. Put what doesn't change first and what changes last. System prompts, tool descriptions, and long documents you'll ask about again and again go at the beginning; the user's question, timestamps, and anything else that's different every time go at the end. If the first line of your system prompt says “The current time is 14:03:27”, every request will stop matching from the very first word.
Making the cache smaller
Go back to that formula and write each term as a symbol:
is the number of layers, the number of KV heads, the dimension of each head, the number of bytes per number, and the number of tokens. Each of these terms can be tinkered with. The ideas people have come up with fall roughly into four groups: store fewer copies, keep only a slice, store smaller numbers, and manage the space well.
Store fewer copies: let attention heads share K and V
As mentioned earlier, a model's attention is split into many heads. The original design, called Multi-Head Attention (MHA), gives every head its own K and V. GPT-3 works this way, which is why each token has to store 96 copies in every layer.
In 2019, Noam Shazeer boldly proposed letting all the heads share a single K and V, with each head keeping only its own Q. This is called Multi-Query Attention (MQA). The cache suddenly shrinks by a factor of dozens; the price is some loss in model quality, and training becomes less stable.
GQA (Grouped-Query Attention), from 2023, takes the middle ground. It splits the heads into a few groups, and each group shares one K and V. Llama 3 8B's 32 heads are split into 8 groups, with every 4 heads sharing one copy. That's where the 8 KV heads in the earlier calculation come from.
Switch between the options below to see how the sharing pattern and the cache size change:
For the same single token in a single layer, a copy for every head takes 8,192 numbers, 8 groups take 2,048, and full sharing takes only 256. GQA shrinks the cache to a quarter, and in the paper's experiments its quality stays close to having a copy for every head. Llama 2 70B, Llama 3, and Mistral 7B all adopted it.
The last option, DeepSeek-V2's MLA (Multi-head Latent Attention), takes a different approach. Instead of having heads share K and V, it compresses each token's K and V into a single 512-dimensional vector for storage, and expands that back into each head's K and V when needed. To work with the positional encoding, it also stores an extra small 64-dimensional vector. At DeepSeek-V2's size, a copy for every head would take 32,768 numbers, while MLA stores only 576, less than 2%. The paper reports that compared with the team's previous model, DeepSeek 67B, the KV cache is 93.3% smaller.
Keep only a slice: windows and attention sinks
Another approach is even blunter and keeps only the most recent slice.
Mistral 7B lets each layer look at only the previous 4,096 tokens and ignores anything further back. The cache therefore becomes a fixed-size circular buffer, where token is stored in slot and each new token overwrites the oldest one. The paper says that on sequences 32K tokens long, this cuts cache memory usage by a factor of eight.
But this trick has to be designed in at training time. What happens if you take a model that saw the full text during training and forcibly throw away the earlier tokens at inference time?
StreamingLLM, from 2023, ran exactly this experiment. The authors had Llama-2-7B read a text 400,000 tokens long while the cache kept only the most recent 4,096. As soon as the very first tokens were pushed out, perplexity (lower means the model is less surprised) shot up to 3,359.95. The model was as good as broken.
Stranger still is the fix. Just keep the first 4 tokens in the cache for good, and perplexity drops back to 9.59. What those 4 tokens actually say doesn't matter at all. In a separate experiment with Llama-2-13B, the authors replaced them with newline tokens, and perplexity came out at 5.60, about the same as the 5.40 with the original content kept.
Try choosing how many of the first tokens to keep:
The authors' explanation has to do with softmax. The weights softmax outputs always add up to 1, so even when the new token doesn't really need to consult anyone, its attention still has to “go” somewhere. The very first few tokens have been seen by every token that comes after them, and during training the model learns to dump its spare attention on them. The authors call them attention sinks. Drop them, and a big chunk of softmax's denominator suddenly disappears, throwing every token's attention distribution out of shape.
What StreamingLLM solves is “reading a very long stream without breaking down”, not “remembering things from long ago”. Once something is pushed out of the window, the model really can't see it anymore.
Store smaller numbers: lower precision
The third direction is the most straightforward. Each number normally takes 2 bytes; store it in 1 byte instead, and the cache is cut in half.
The open-source inference framework vLLM supports storing the KV cache as 8-bit floating-point numbers (FP8). Its documentation says the main benefit is that the same memory can hold about twice as much cache, so more people can be served at once. How much the lower precision affects answer quality depends on the model and the calibration method. Go back to the calculator above and switch the cache precision to “FP8 (1 byte)”, and both the per-token size and the total KV cache are cut in half.
Manage the space well: PagedAttention
The last group leaves the model alone and changes how memory is allocated instead.
The trouble is that nobody knows at the start how long the answer will be. Early inference systems, on receiving a request, reserved one contiguous stretch of memory for the maximum length right away, so they wouldn't run out halfway through generating. As a result, most of the space sat reserved but unused, and because requests vary in length, they also left behind scattered gaps too small to fit anything.
The 2023 vLLM paper measured this. In the existing systems the authors tested, only 20.4% to 38.2% of the KV cache memory actually held tokens' K and V.
Their solution borrows the way operating systems manage memory, and it's called PagedAttention. The cache is cut into small fixed-size blocks, say 16 tokens per block, and a block is handed out only when it's needed, from anywhere in memory. Each request keeps a “block table” that records where in memory each of its blocks sits. This way, only the last block of each request can have empty slots.
Switch between the two allocation methods below and see how much the memory utilization differs:
Request A: reserved 32 slots (0–31), 20 in use
Request B: reserved 32 slots (38–69), 14 in use
Request C: reserved 32 slots (76–107), 26 in use
Request D: waiting: no free run of 32 slots
vLLM reaches 96.3% utilization. The same GPU can handle more requests at once, and the paper reports 2 to 4 times the throughput of the leading systems of the time at the same latency.
Splitting the cache into blocks also makes the prompt caching we saw earlier use less memory. When several requests share the same system prompt, their block tables can point to the same blocks instead of each storing its own copy.
What if you'd rather not store anything at all
All the methods above try to save space while still assuming that “the K and V of every old token are stored”. Only the sliding window stops the cache from growing, at the price of not seeing anything outside the window.
Could the model take notes some other way? Instead of holding on to every token's K and V, it would keep a fixed-size cheat sheet and update what's on it each time it reads a new token. Then no matter how long the conversation gets, what needs to be stored stays the same size.
Plenty of people are already working in this direction; Mamba and the many kinds of linear attention all belong here. How to write the cheat sheet, and when to erase it and start over, is another long story.
Wrapping up
Back to the three things we noticed at the start:
- The pause of a second or two after you hit send: the model is doing prefill, computing K and V for every token in the prompt and storing them in the cache.
- The steady pace of the words that follow: once the cache is built, each step computes only one new token, but every step has to read the weights and the entire cache from memory.
- The discounted column on the pricing page: a request that starts with exactly the same text can reuse a cache someone else already computed.
If you're using an API, put the content that doesn't change at the front of the prompt, and you'll get the cache discount. If you're hosting a model yourself, use that formula to work out the cache size first, then decide how long a context you can offer and how many people you can serve at once. When picking a model, glance at how many KV heads it has as well: at the same 8B, a copy for every head versus 8 groups makes a fourfold difference in cache size.
The idea behind the KV cache is a very plain one. Don't compute the same thing twice. It made word-by-word generation practical, and it also moved the bottleneck from compute to memory. Over the past few years, much of the talk about inference efficiency, from GQA and MLA to PagedAttention, has really been haggling with this cache. Next time you spot that cached input column on a pricing page, you'll know it's saying hey to you.
