Context windows and the KV cache
A language model can only look at so much text at once. And when it writes an answer one token at a time, redoing all the earlier text at every step piles up like a staircase. Count the cells yourself and see what the KV cache saves.
Short answer. The context window is how many tokens a model can see at once. The text you send (input) and the text it writes (output) share that window. When text does not fit, you cut it, summarize it, or search it and put in only what you need. The KV cache stores the work already done on earlier tokens (their K and V) while the model writes one token at a time. With no cache, making n tokens computes n(n + 1) ÷ 2 cells. With the cache it computes n.
Each row is one step. At step t the text has t tokens, and the model makes the next one. Green cells are tokens run through the layers in that step. Gray cells are tokens only read back from the cache. This is a small toy model, not a real one: it only counts how many token positions get computed (see section 4).
Try this. ① At the start (n = 10, no cache) there are 55 green cells. Press "With cache" and only 10 are left, with 45 gray cells in their place. That is 5.5 times fewer. ② Move the slider to 100 and you get 5,050 cells against 100, or 50.5 times. ③ With n = 1 both give 1 cell. There are no earlier tokens to redo, so the cache has nothing to save.
Definitions
The text below explains with pictures and labs. These are the textbook definitions.
- context window
- The largest number of tokens a language model can handle in one call. The input tokens and the output tokens the model makes must fit in it together. It is also called the context length.
- autoregressive generation
- A way of making text where the model picks the next token, adds it to the end of the input, and picks the next token again, over and over.
- KV cache (key-value cache)
- In autoregressive generation, a store that keeps the keys (K) and values (V) of the earlier tokens for each layer, so that each step only computes K and V for the new token and adds them. Because of the causal mask, adding tokens later does not change the K and V of earlier tokens, so they can be reused.
- prefill, decode
- Prefill is the step that computes all input tokens at once and fills the KV cache. Decode is the step after it, which uses the cache and makes the output tokens one at a time.
- prompt caching
- Keeping the start (prefix) of an input that was already processed, so that when the next request starts with the same prefix, that part is not processed again and work picks up from there. Only the part that matches from the very first token can be reused.
1. What a context window is
A model does not read letters. It reads tokens (words or pieces of words). The context window is the most tokens the model can handle in one call. All of this goes inside it:
- Input: system instructions, the conversation so far, pasted documents, the current question.
- Output: the answer the model writes. Each new token is added to the end of the text and becomes input for the next one, so it uses the same window.
So the longer the document you send, the less room is left for the answer. The window size is set when the model is built, and it differs from model to model.
The window has a limit because the work grows with length. In attention, every token scores itself against every earlier token, so text twice as long gives about four times as many scores. The KV cache you will see below also takes memory in proportion to the number of tokens.
2. When it does not fit: cut, summarize, or retrieve
A model cannot take text longer than its window. An API refuses the request, and the output stops when it reaches the window or the limit you set. There are three ways to handle long text:
- Cut: drop the less important parts, such as old messages. This is the easiest, but the model knows nothing about what you dropped.
- Summarize: shrink the old parts into a short summary. The story stays, the details go.
- Retrieve: split your material into pieces (chunking) and put in only the pieces closest to the question (RAG). This works even for material far larger than the window.
The table in section 10 helps you choose.
3. The KV cache: not redoing earlier tokens
A model does not write its answer in one go. It picks the next token (sampling), adds it to the end, and picks the next one again. At each step the new token looks at the earlier tokens through attention. For that, it needs two things from each earlier token: K (the key, a label that says "this is what I am about") and V (the value, the content to take).
With no cache, every step runs the whole text through the layers again and rebuilds every K and V. But a text-writing transformer is blocked so that each token only sees the tokens before it (a causal mask). So whatever comes later, the K and V of earlier tokens never change. There is no reason to rebuild values that cannot change, so the model keeps them for each layer and only adds the K and V of the new token. That store is the KV cache.
In practice, the model first processes the whole input in one pass and fills the cache (prefill). After that it writes the answer one token at a time (decode). The lab above shows only the decode part: the text grows one token at a time from 1 token to n.
4. How the formula is built: n(n + 1) ÷ 2 and n
Use the staircase picture from the lab to count the work of generating with no cache. What we count here is a simple model: the number of token positions run through the layers. Running one token through all the layers once is one cell. The picture and the numbers follow n from the lab above.
Here is what happens with n = 100.
- Count the staircase:
1 + 2 + 3 + … + 100. At step t the model redoes all t tokens, so row t has t cells. You could add them one by one, but there is an easier way than adding 100 numbers. - Flip a copy and attach it:
2 × (1 + 2 + … + 100) = 100 × 101. Turn a second staircase upside down and put it next to the first. Row t now hast + (101 − t) = 101cells. Every row has 101 cells and there are 100 rows, so the two staircases make a rectangle of100 × 101 = 10,100cells. Why: pairing a short row with a long row makes every row the same length, so one multiplication counts them all. - Cut it in half:
1 + 2 + … + 100 = 10,100 ÷ 2 = 5,050. One staircase is half the rectangle. The same trick works for any n, so1 + 2 + … + n = n(n + 1) ÷ 2. When n doubles, the count grows about four times. - With the cache:
1 + 1 + … + 1 = 100. The model reads the K and V of earlier tokens from the cache and computes only the one new cell.5,050 ÷ 100 = 50.5times fewer. In generaln(n + 1) ÷ 2 ÷ n = (n + 1) ÷ 2, so the gap grows as the text gets longer.
What this model leaves out. The cache removes the work of running earlier tokens through the layers again. The attention work stays: the new token still scores against the K of all t earlier tokens and mixes their V, and that grows with t at every step. Reading the cache from memory also takes time. So the real difference in time is not 50.5 times.
Try this. ① At the start (n = 10), press "Next". A purple staircase is attached, every row has 11 cells, and the rectangle has 110. ② Press again and the half that is left has 55 cells. ③ In the last step only 10 green cells remain and the text says "5.5". ④ Move the slider in the first lab to 100 and step through again: you get 10,100, 5,050, 100 and 50.5.
5. Work it out by hand: 4 tokens
Start with 1 token and go up to 4, writing down the positions computed at each step.
| Step | Tokens in the text | No cache: positions computed | With cache: positions computed | Tokens in the cache after the step |
|---|---|---|---|---|
| 1 | 1 | 1 (1 of them) | 1 (1 of them) | 1 |
| 2 | 2 | 1, 2 (2 of them) | 2 (1 of them) | 2 |
| 3 | 3 | 1, 2, 3 (3 of them) | 3 (1 of them) | 3 |
| 4 | 4 | 1, 2, 3, 4 (4 of them) | 4 (1 of them) | 4 |
| Total | 10 = 4 × 5 ÷ 2 | 4 |
Now count the size of the cache. Take a made-up tiny model with 2 layers, where each K and each V is 8 numbers long. After 4 steps, each layer holds 4 × 8 numbers of K and 4 × 8 numbers of V. That is 2 × 2 × 4 × 8 = 128 numbers in all, and at 2 bytes (16 bits) per number, 256 bytes.
6. How much memory the cache takes
Written as a general formula, the hand example becomes:
cache size = 2 × layers × tokens × dimension × bytes per number
(times the number of texts being written at the same time)
The 2 is there because there are two things, K and V. The dimension is the length of one token's K (or V). The model fixes the layers and the dimension, so for one model the cache is in direct proportion to the number of tokens. For example, take a model with 32 layers, dimension 4,096 and 2 bytes per number (a made-up size). One token takes 2 × 32 × 4,096 × 2 = 524,288 bytes (about 0.5 MB), and 1,000 tokens take 524,288,000 bytes (about 0.5 GB). This memory has to sit on the same machine as the model's weights, so the longer the texts and the more requests at once, the less one machine can handle.
7. Properties to know
| Property | In plain words |
|---|---|
| Input and output share one window | A long document leaves less room for the answer |
| The K and V of earlier tokens never change, whatever comes later | Each token is blocked from seeing what comes after it (causal mask). That is why they can be stored and reused |
| The cache removes the work of redoing earlier tokens | The attention work of the new token looking at all earlier tokens stays. Each step gets a little heavier as the text grows |
| Cache memory is in direct proportion to the number of tokens | 2 × layers × tokens × dimension × bytes, times the number of requests at once |
| Prompt caching only matches up to the first token that differs | Put the parts that never change first and the parts that change last (section 8) |
8. Prompt caching in APIs: the start must be the same
You often send the same system instructions or the same long document many times. With prompt caching, the API keeps the starting part (the prefix) it has already processed. When the next request starts with the same prefix, it does not process that part again and carries on from there. Less work means a lower price and a faster first token. The stored prefix has a time limit and is dropped if not used for a while. The rules and prices differ between companies, so read the docs of the API you use.
Why it must be the start. Above the first layer, the K and V at position i depend on every token from 1 to i, because each layer mixes in the content of earlier tokens. So if token j is different, every K and V from position j onward changes, and only the part before j stays the same.
- Request A:
[instructions][document][question 1], request B:[instructions][document][question 2]. They match up to the question. - Request C:
[today's date][instructions][document][question 1]. It differs from the first token, so every day the date changes, nothing in the prefix matches.
So put what never changes (instructions, tool descriptions, long documents) first, and what changes (dates, user names, the question) last. The public docs do not say exactly what a commercial API stores inside. This page explains it with the same idea as the KV cache.
9. A weak spot of long contexts: the middle gets lost
Fitting in the window does not mean the model uses every position equally well. The "Lost in the Middle" paper (see sources) tested multi-document question answering and key-value lookup. It reported that results were often best when the needed information was at the start or end of the input, and dropped a lot when it was in the middle. This happened even with models built for long contexts. These are findings from the paper's tests, and the size of the effect can differ by model, but it is safer not to expect that more text means better use of it. That is why people put key instructions at the start or end and send only as much as they need.
10. When to use what
| Option | Good | Bad | Use it when |
|---|---|---|---|
| Put everything in the context | Nothing to build. The model sees all of the material | Costs money and time per token. Impossible if longer than the window. The middle may get lost | The material fits easily. If you ask many times about the same material, add prompt caching |
| Cut | The easiest. Cost stays flat | The model knows nothing about what you dropped | Chats where only recent messages matter |
| Summarize and put in | The story of a long exchange survives | Summaries cost extra calls. Details are lost, and a wrong summary stays wrong | Long chats and meeting notes, where the flow matters |
| Retrieve and put in (RAG) | Works for material far larger than the window. Easy to update the material. You can show which piece an answer came from | If search misses a piece, the answer misses it too. You must build pieces (chunking) and an index | Asking questions over a set of documents, material that changes often |
| Fine-tune (LoRA and others) | The model learns a tone, a format or a way of working. No need to send long instructions every time | Training takes effort and money. Retrain when the material changes. Hard to show where an answer came from | Matching a format or tone. Not a good fit for facts that change often |
Where it is used
- Long chat apps. Cut or summarize old messages so the chat stays inside the window.
- Asking questions about documents. Split the documents into pieces (chunking) and put in only the pieces you need (RAG).
- API calls that send the same instructions many times. Put the parts that never change at the start so prompt caching can match.
- Running a model yourself. Work out the KV cache memory to decide the longest text and the number of requests at once that a machine can take.
Common questions
If the window is big, isn't it best to put everything in?
Not always. Every token you send costs money and time, and research has found that models often make poor use of information in the middle of a long input. If your material fits easily and you only ask a few times, putting it all in is the simplest choice. If it is much larger than the window or changes often, search it and put in only the parts you need.
Are the KV cache and prompt caching the same thing?
Same idea, different place. The KV cache reuses the K and V of earlier tokens inside the model while it writes one answer. Prompt caching is an API feature that reuses the work on the same starting text from one request to the next. The public docs do not say exactly what a commercial API stores inside.
Does the cache really make generation (n + 1) ÷ 2 times faster?
No. This page uses a simple model that only counts token positions run through the layers. Even with the cache, the new token still has to score against the K of every earlier token and mix their V, and reading the cache from memory takes time too. The real speedup has to be measured on a given model and machine.
Words
| Words used here | Textbook term |
|---|---|
| How many tokens the model sees at once | context window, context length |
| A word or a piece of a word | token |
| The label and content of an earlier token | key (K), value (V). The new token's side is the query (Q) |
| The stored K and V | KV cache (key-value cache) |
| Letting each token see only earlier tokens | causal mask |
| Writing one token at a time, each after the last | autoregressive generation |
| Processing the input in one pass / making one token at a time | prefill / decode |
| Reusing the same starting text | prompt caching, prefix |
| Searching and putting in | retrieval-augmented generation (RAG) |
| Splitting material into pieces | chunking |
| Training the model further to fit a job | fine-tuning |
| Losing the middle | lost in the middle |
Sources
- Ashish Vaswani et al., Attention Is All You Need, arXiv:1706.03762. Q, K and V in attention, and blocking the decoder from seeing later positions.
- Nelson F. Liu et al., Lost in the Middle: How Language Models Use Long Contexts, arXiv:2307.03172. Results drop when the needed information sits in the middle of a long input.
- Hugging Face Transformers docs, KV cache. Storing the work on earlier tokens so it is not recomputed.
- Anthropic docs, Prompt caching. Reusing stored work for requests that start with the same prefix to cut cost and wait time, and how long it is kept.