Unit 2 · Architecture
Lesson 07 · Available to read
Context Windows, Positional Encoding and Long-Context Memory
Why attention needs position information, what a context window is, and the techniques used to make it longer.
An LLM's context window is everything it can "see" at once: the system prompt, the conversation so far, any documents or tool results you've pasted in, and the answer it is writing. This lesson covers two linked questions: how a transformer knows the order of the tokens in that window, and why making the window bigger is hard.
Attention has no sense of order
Look again at the attention formula from Lesson 6. Every token is compared with every other token by dot products — and nothing in that calculation depends on where the tokens sit. Shuffle the input and each token's attention output is unchanged (just shuffled along with it).
So without extra help, "dog bites man" and "man bites dog" would look identical. Word order carries meaning, so we must inject position information.
Three ways to encode position
1. Sinusoidal encodings (original 2017 transformer). Add to each token's embedding a fixed vector of sine and cosine waves of different frequencies, unique to its position. Low-frequency waves change slowly across positions, high-frequency ones quickly — like the hands of a clock telling hours, minutes and seconds.
2. Learned absolute embeddings (e.g. GPT-2). Keep a second lookup table with one learned vector per position (1, 2, …, up to the maximum length) and add it to the token embedding. Simple, but the model has never seen positions past its training length, so it can't extend beyond it.
3. Rotary position embeddings — RoPE (most open models today). Instead of adding anything to the embedding, rotate each query and key vector by an angle proportional to its position (different pairs of dimensions rotate at different speeds). When a query at position m meets a key at position n, the rotations partially cancel and their dot product depends on the offset m − n. Attention therefore naturally sees relative distance — "three tokens back" — which generalizes better.
Other schemes exist, such as ALiBi, which simply subtracts a penalty from attention scores that grows with distance.
The context window
The context window is the maximum number of tokens — input plus output — a model can process in one go. It has grown dramatically: GPT-3 (2020) handled 2,048 tokens; many current models handle hundreds of thousands, and some advertise a million or more. Check each model's documentation for its exact limit, because it is a hard ceiling: tokens beyond it are simply not seen.
A useful mental model: the context window is working memory, not long-term memory. The model's knowledge from training lives in its weights; the context window holds this conversation's details. When a chat grows too long, applications must drop, truncate or summarise old turns.
Why long contexts are expensive
Two costs grow with sequence length n:
- Attention compute grows with n², because every token is scored against every earlier token. Going from 8K to 128K tokens is 16× longer but about 256× more attention work.
- Memory for the KV cache — the stored keys and values of every previous token, needed during generation (Lesson 20) — grows linearly with n and with the number of layers, and can exceed the size of the model weights for very long contexts.
How models stretch their context
Engineers combine several techniques:
- Train long, gradually. Pretrain mostly on shorter sequences, then continue training on long documents.
- RoPE scaling / interpolation. Rescale the rotation angles so positions beyond the original range map into the range the model learned, then fine-tune briefly.
- Efficient attention kernels. Implementations like FlashAttention compute exact attention while never materialising the full n × n matrix in slow memory — much faster and lighter, though still quadratic in compute.
- Sparse or sliding-window attention. Let most layers attend only to a local window, with a few global layers or tokens.
- Sharing keys and values across heads (multi-query or grouped-query attention) to shrink the KV cache.
Nominal vs. effective context
A model accepting 200K tokens doesn't mean it uses all of them equally well. Two common tests:
- Needle in a haystack — hide one fact in a long document and ask for it. Modern models often do well on this simple retrieval.
- Harder tasks — reasoning that combines many facts spread across the context. Here performance usually degrades with length.
Research has also found a "lost in the middle" effect in many models: information at the very beginning or end of a long prompt is used more reliably than information buried in the middle.
Practical advice
- Put the most important instructions at the start (and repeat critical ones near the end) of long prompts.
- Don't paste everything "just in case" — retrieve the relevant parts (Lesson 15). More tokens cost more, take longer and can distract.
- In long chats, summarise older history instead of letting it silently fall out of the window.
The takeaway
Attention is blind to order, so models inject position — today usually by rotating queries and keys (RoPE); the context window is the model's working memory, and making it longer fights the quadratic cost of attention and the tendency to under-use information buried in the middle.
Practice
0 of 7 attempted
- 1Explain in your own words
Explain why a transformer without positional information could not tell "dog bites man" from "man bites dog".
Saved in this browser
- 2Recall
Name three approaches to positional encoding and give one property of each.
Saved in this browser
- 3Calculate
A model has a 200,000-token context window. Your system prompt is 3,000 tokens, the attached documents total 150,000 tokens and the conversation history is 35,000 tokens. What is the most the model's answer can be? What happens if you attach another 20,000-token document?
Saved in this browser
- 4Calculate
If attention compute grows with n², how much more attention work does a 64K-token prompt need than a 4K-token prompt?
Saved in this browser
- 5Multiple choice
What does RoPE make the query–key dot product depend on?
- 6Explain in your own words
What is the difference between a model's nominal context length and its effective context length?
Saved in this browser
- 7Apply
You're building a customer-support chatbot. Conversations can last hours and customers attach long manuals. Write three design rules you'd follow to work within the context window.
Saved in this browser