SysDesignAtlas

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.

CoreHard10 min readaicontextattentionrope
Confidence

#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 memory

Both 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.

SchemeMechanismExtrapolates?
Learned absoluteA trainable embedding per position, added to the inputNo — position 5,000 has no embedding if you trained to 4,096
SinusoidalFixed sin/cos of position, added to the inputPoorly in practice
ALiBiAdd a distance-proportional penalty to attention scoresYes, gracefully
RoPERotate Q and K by an angle proportional to positionYes, 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" tokens

Attention 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.

Long context • Model sees everything; no relevance decision • Cross-document reasoning works naturally • Cost is superlinear in content size • TTFT grows with every token you add • Hard cap; no answer beyond the window Retrieval • Only relevant chunks enter the prompt • Cost is roughly flat in corpus size • Scales to corpora no window could hold • Adds retrieval latency and infrastructure • Quality is capped by retrieval quality
Not a rivalry — they solve different problems and are frequently combined.

#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
Attention compute grows O(n²) — doubling context is 4× the work — and KV-cache memory grows O(n). Memory limits concurrency in serving; compute sets prefill time.
What does a million-token request cost?Show answer
About 164 GB of KV cache for one request (80 layers, GQA, FP8) and ~70 seconds of prefill on an 8-GPU node before the first token.
How does RoPE encode position?Show answer
It rotates queries and keys by an angle proportional to position, so their dot product depends only on relative distance — which is what makes extending context possible.
How is a trained model's context extended?Show answer
Position interpolation (compresses local resolution), NTK-aware frequency scaling, or YaRN (the standard) — each with a short long-sequence fine-tune. None removes the quadratic cost.
What are attention sinks?Show answer
Models dump excess attention on the first few tokens; evicting them in a sliding window collapses quality. Keeping ~4 initial tokens plus the window restores it (StreamingLLM).
Long context or retrieval?Show answer
Usually retrieval into a long window. Stuffing a 2.5M-token corpus costs ~1,000× retrieving 5,000 tokens per request; long context earns its cost for one big uploaded document, whole-repo coding or agent trajectories.
What degrades before the advertised limit?Show answer
Lost in the middle (weaker recall mid-context), multi-fact reasoning failing where single-needle retrieval passes, and distraction from irrelevant content.
What did big windows actually change for retrieval?Show answer
Retrieval can be less precise — return 20 chunks instead of 3 and let the model sort them — an improvement to retrieval, not a replacement.

#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.
00:00
/ 10m