Step 12 · Long context
Going from 4k to 1M tokens is not one trick. It is four, and each one costs something.
In 60 seconds
Step 12 · Long context
Going from 4k to 1M tokens is not one trick. It is four, and each one costs something.
- 1
Barrier 1 · Compute and memory
Attention is quadratic in sequence length, and the KV cache grows linearly with it. At 1M tokens, both are brutal. - 2
Barrier 2 · The model has never seen it
Position encodings trained on 4k sequences do not automatically mean anything at 100k. The model degrades into confident nonsense. - 3
Barrier 3 · It cannot use what it has
Even with a working 200k window, retrieval quality often sags in the middle of very long inputs. A big window is not the same as attention that is usefully distributed across it.
The techniques
| Technique | Fixes | Cost |
|---|---|---|
| FlashAttention | Memory of attention itself | None — always use it |
| GQA / MQA | KV cache size | Very small quality loss |
| RoPE scaling (NTK, YaRN) | Position extrapolation | Needs some continued training |
| Sliding-window attention | Quadratic cost | Loses exact long-range attention |
| Attention sinks | Streaming stability | Architectural change |
| KV cache quantisation | Serving memory | Small accuracy cost |
| Ring / sequence parallel | Training on long sequences | Complexity, interconnect pressure |
How context extension actually works
def yarn_scaled_frequencies(head_dim, orig_max, target_max, base=10000.0):
"""Interpolate low-frequency dimensions, leave high-frequency ones alone."""
scale = target_max / orig_max
inv = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
wavelen = 2 * math.pi / inv
low, high = orig_max / 32, orig_max / 4 # boundary wavelengths
# short wavelengths (local detail) keep their original frequency
# long wavelengths (global position) get interpolated by the scale factor
ratio = ((orig_max / wavelen) - low) / (high - low)
ratio = ratio.clamp(0, 1)
return inv / (scale * (1 - ratio) + ratio)
# then continue training on long documents for a few billion tokens --
# scaling the frequencies alone is not enough on its ownTest it honestly
- Needle in a haystack — hide one fact in a long document and ask for it, at many depths and lengths. Table stakes, and easy to pass.
- Multi-needle — several facts that must be combined. Much harder, and far more predictive of real use.
- Full-document reasoning — a question whose answer requires most of the input. This is where long-context claims usually fall apart.
- Latency and cost at length — a 500k-token prompt is slow and expensive to process, every single time.
Watch and read more
Lab
A context extension that actually works, tested honestly.
The problem
# Single needle passes easily. These are the tests that discriminate.
def multi_needle(doc, facts, question): ... # answer requires 3+ facts combined
def full_doc(doc, question): ... # answer requires most of the inputYou are done when
Hard questions
Try to answer before you reveal. If you can answer these, you understood the lesson.
Q1Needle-in-a-haystack is at 100% and users say long-context is broken. Reconcile.Reveal
Questions people ask
Can I just set a bigger max length?
You can set the number, and the model will produce fluent nonsense beyond what it was trained for. Real context extension requires frequency scaling plus continued training on genuinely long documents.
Why does quality dip in the middle of long inputs?
Observed repeatedly and not fully explained. Training data has far fewer examples of long-range dependencies, and position encodings behave less distinctly at extreme distances. Mitigations help; the effect has not been eliminated.
What does long context cost in serving?
The KV cache scales with context length times batch size. It is often the binding constraint on how many users one GPU can serve, which is exactly why GQA and cache quantisation matter so much.
Are state-space models better here?
They have linear-time inference and constant-size state, which is very attractive for long sequences. They currently trade away some precise recall, which is why hybrids that interleave attention layers are popular.
Lesson test
5 questions. Get 3 right (60%) to pass and complete this lesson.
Sign in with your phone number to take the test and save your progress