Context Windows & Long Context
How position is encoded, why attention cost is quadratic and memory cost is linear, and what actually breaks when you extend a model to a million tokens.
#Two different costs, often conflated
"Context window" is quoted as a single number, but extending it stresses two separate resources with different growth rates.
Sequence length n:
ATTENTION COMPUTE O(n²) every token attends to every token
KV CACHE MEMORY O(n) one K,V per token per layer
Doubling context: 4× the attention work, 2× the memory
10× the context: 100× the attention work, 10× the memoryBoth matter, at different points. Memory is usually the first limit you hit in serving, because it caps how many concurrent requests fit on a GPU. Compute is the limit during prefill, because it sets time-to-first-token for a long prompt.
That arithmetic is why long-context pricing is superlinear (a prompt twice as long costs more than twice as much), why providers meter cached versus uncached input separately, and why "we support 1M tokens" and "you should use 1M tokens" are entirely different claims.
#How the model knows where a token is
Here's a fact that surprises people: attention has no inherent sense of order. Shuffle the words of a sentence and the raw mechanism computes exactly the same thing — "dog bites man" and "man bites dog" are identical to it. Position has to be added deliberately, and how it's added determines whether the model copes with sequences longer than anything it saw during training.
| Scheme | Mechanism | Extrapolates? |
|---|---|---|
| Learned absolute | A trainable embedding per position, added to the input | No — position 5,000 has no embedding if you trained to 4,096 |
| Sinusoidal | Fixed sin/cos of position, added to the input | Poorly in practice |
| ALiBi | Add a distance-proportional penalty to attention scores | Yes, gracefully |
| RoPE | Rotate Q and K by an angle proportional to position | Yes, with adjustment — the modern default |
RoPE (rotary position embedding) is what nearly everything uses. Rather than adding a position vector, it rotates the query and key vectors by an angle proportional to their position. Concretely, it treats each vector as a list of pairs of numbers, treats each pair as a point on a 2D plane, and rotates that point.
Rotate Q at position m by angle m·θ
Rotate K at position n by angle n·θ
Their dot product then depends on the rotation difference:
Q_m · K_n ∝ cos((m − n)·θ)
─────
RELATIVE distance only
→ The model learns "how far apart", not "which absolute slots".
Each pair rotates at a different speed θ. Fast-rotating pairs
tell apart tokens 1 vs 2 positions away; slow ones tell apart
tokens 1,000 vs 2,000 away. Together: local AND long-range.The relative property is what makes extension possible at all: a model that only ever learned relative distances has some chance of generalising to distances it hasn't seen.
#Extending a trained model's context
You rarely retrain from scratch to get longer context. Three techniques, in increasing sophistication:
- Position interpolation. Scale positions down so 8,000 tokens map into the 4,000-position range the model was trained on. Works, but compresses local resolution — the model becomes slightly worse at fine-grained nearby relationships.
- NTK-aware scaling. Change the rotation speeds rather than the positions. Leave the fast-rotating pairs (which track nearby tokens) almost alone, and slow down the slow-rotating pairs (which track long distances) so they cover the longer range. Preserves local precision while extending range.
- YaRN. A refined version of that speed-scaling, plus a temperature correction — a small rescaling of attention scores so attention doesn't spread too thinly over the much longer sequence. The current standard for extending RoPE models, and it works with a short fine-tune on long sequences rather than full retraining.
All of them need some fine-tuning on long data to work well. None of them make the quadratic attention cost go away — they change what the model can meaningfully use, not what it costs to run.
#Sparse and windowed attention
If full attention is quadratic, attend to less.
FULL SLIDING WINDOW WITH SINKS DILATED
■■■■■■■■ ■□□□□□□□ ■□□□□□□□ ■□■□■□■□
■■■■■■■■ ■■□□□□□□ ■■□□□□□□ □■□■□■□■
■■■■■■■■ ■■■□□□□□ ■■■□□□□□ ■□■□■□■□
■■■■■■■■ □■■■□□□□ ■□■■□□□□ □■□■□■□■
└ window = 3 └ always keep
O(n²) O(n·w) the first few O(n·log n)
"sink" tokensAttention sinks are the surprising and important detail. When a sliding window evicts the earliest tokens, model quality collapses — far more than the lost information should account for. The cause is softmax, which forces each token's attention weights to add up to exactly 1 — even when nothing in the context is relevant. During training the model learned to park that leftover attention on the first few tokens, which contribute almost nothing to the output: a harmless "sink". Remove those tokens and the leftover attention has to land on real tokens that don't deserve it, distorting the output.
Keeping four initial tokens permanently, plus a sliding window, restores quality almost entirely (StreamingLLM). It's an excellent example of an emergent behaviour — something nobody designed, which the model picked up in training — that ends up dictating how you must build the cache.
Hybrid layer stacks are where production models landed: alternate a few full-attention layers with many sliding-window layers. You get long-range capability from the full layers and linear-ish cost from the rest, with the KV cache for windowed layers bounded by the window rather than the sequence.
#Long context versus retrieval
The design question that actually comes up.
#What degrades before the limit does
A model advertising 200K tokens does not use all 200K equally well.
Lost in the middle. Retrieval accuracy is high for content at the start and end of a long context and measurably lower in the middle. Practical consequence: put the most important material at the beginning or the very end of the prompt, not buried at position 90,000.
Needle-in-a-haystack passes, reasoning fails. Finding one distinctive fact in a long context is much easier than combining five facts scattered across it. Benchmarks that only test retrieval overstate usable context length considerably.
Distraction. Irrelevant content in the window measurably degrades answers, even when the relevant content is present. More context does not always help — a precise 4,000-token prompt often beats a 100,000-token one containing the same information plus noise.
#Exercise
#Check yourself
Which two costs does a longer context raise?Show answer
What does a million-token request cost?Show answer
How does RoPE encode position?Show answer
How is a trained model's context extended?Show answer
What are attention sinks?Show answer
Long context or retrieval?Show answer
What degrades before the advertised limit?Show answer
What did big windows actually change for retrieval?Show answer
#What to carry forward
- Context costs O(n²) compute and O(n) memory — different resources, binding at different times.
- RoPE encodes relative position by rotation, which is what makes extension possible; YaRN is how it's done.
- Sparse and windowed attention trade range for cost; attention sinks are required for windowing to work.
- Effective context is well below advertised context, and irrelevant content degrades answers.
- Retrieval into a long window beats either alone. The deciding factor is usually cost per request, not quality.