AI State of the Art
SOTA/Advanced Attention Mechanisms/20 min
Section 84

Context Window Extension: YaRN, NTK-aware Scaling

Listen as a podcast →

The central problem: RoPE doesn't scale

You train your model on 4K token sequences. Everything goes well. Then you give it a 16K token sequence at inference. Catastrophe: quality collapses completely.

Why? RoPE (previous lesson) encodes positions via rotations at specific frequencies. During training, the model learned to interpret these rotations for positions 0 to 4095. At position 16000, the rotations take values the model has never seen. It's like asking someone to read a clock that suddenly makes 40 revolutions per hour instead of 1: the hands are moving, but it no longer means anything.

The spectrum analogy

Imagine a radio trained to pick up frequencies 100-200 MHz. At 500 MHz, it receives nothing but noise. That's exactly what happens to RoPE beyond its training window: the positional frequencies become noise for the model.

Solution 1: Position Interpolation (PI)

The most direct approach: compress positions to fit them within the known range.

compressed_position=real_position×LtrainingLtarget\text{compressed\_position} = \text{real\_position} \times \frac{L_{\text{training}}}{L_{\text{target}}}

In plain terms: every position is multiplied by the ratio between the length seen in training (LtrainingL_{\text{training}}) and the targeted length (LtargetL_{\text{target}}). Trained on 4K, you test on 16K? The ratio is 1/4: position 16000 becomes 4000. All rotations stay within the range the model knows.

Advantage: it works right away, it's just a multiplicative factor on positions.

Problem: you crush the resolution. Imagine taking a ruler graduated from 0 to 100 cm and compressing it to measure from 0 to 400 cm. The markings are now 4 times closer together: you lose precision for distinguishing small distances. Concretely, neighboring tokens become artificially closer, and the model loses its ability to finely distinguish local positions.

Two stacked plots showing the value of a RoPE component as a function of position. On top, the sine wave is sampled regularly from 0 to 2048 in the blue pre-trained range, then from 2048 to 4096 in a red region labelled Unseen Range, where the red dots land on values the model has never seen. At the bottom, with position interpolation, all positions from 0 to 4096 are mapped back into the 0 to 2048 range: the dots stay inside the known region but are packed twice as densely.
On top, naive extrapolation: past 2048 the model lands in the red zone, positions whose rotation it has never seen. At the bottom, position interpolation: the position axis is squeezed by a factor of 2 so that 4096 tokens fit inside the known range. The price is immediately visible: the dots are twice as close together, so twice as hard to tell apart.Source : Aman Arora, How LLMs Scaled from 512 to 2M Context
Loss of local precision

With a 4x factor, two adjacent tokens go from "distance 1" to "distance 0.25." The high frequencies of RoPE (those encoding local relationships between neighboring tokens) suffer enormously. The model confuses consecutive tokens.

Solution 2: NTK-aware (smarter)

A word about the name first: NTK stands for Neural Tangent Kernel, the theoretical framework this trick's authors drew it from, just remember "the NTK method," the reasoning below needs none of the theory.

The key observation: in RoPE, low frequencies encode global positions (where am I in the document?) while high frequencies encode fine locality (which token is just before or after me?).

The NTK-aware idea: instead of uniformly crushing all positions (like PI), modify RoPE's base to affect frequencies differently:

base′=base×αdd−2\text{base}' = \text{base} \times \alpha^{\frac{d}{d-2}}

where α\alpha (alpha) is the extension factor (for example 4 to go from 4K to 16K), dd is the dimension of one attention head, and "base" is the number (10,000 by default) that sets the spacing of RoPE's frequencies. The new base is simply the old one, inflated by a factor slightly above α\alpha.

Increasing the base reduces all frequencies, but low frequencies (already small) are proportionally more stretched than high ones. Result: high frequencies maintain good local resolution, while low frequencies stretch to cover a longer context.

The best of both worlds

High frequencies preserve their ability to distinguish nearby tokens. Low frequencies adapt to cover more ground. You keep local precision while gaining global range. It's a much better trade-off than uniform interpolation.

Dynamic NTK: automatic adjustment

Instead of fixing the base once and for all, it's computed dynamically based on the actual length of the current context:

base′(L)=base×(LLtraining)dd−2\text{base}'(L) = \text{base} \times \left(\frac{L}{L_{\text{training}}}\right)^{\frac{d}{d-2}}

Same formula as above, but the fixed extension factor α\alpha is replaced by the ratio between the actual context length LL and the training length. For a 5K token sequence, the base adjusts slightly. For 20K, it adjusts much more. The advantage: instead of collapsing abruptly beyond the training length, the model degrades progressively. That's much more graceful.

Plot of Llama-2 7B perplexity against context length from 0 to 8000 tokens. The blue RoPE curve drops to about 4.0 then shoots vertically upward past 4200 tokens. The orange Dynamic-PI and green Dynamic-YaRN curves stay flat between 4.0 and 4.3 all the way to 8000 tokens, with the green one consistently below the orange one.
Perplexity measures how lost the model is: lower is better. In blue, plain RoPE: everything is fine up to 4096 tokens (the training length), then the curve goes vertical, which is exactly the collapse described at the top of this page. In orange and green, the dynamic variants: the degradation simply never happens, and YaRN stays below PI across the whole range.Source : YaRN paper (Peng et al., 2023), ar5iv version

Solution 3: YaRN (the modern approach)

YaRN (Yet another RoPE extensioN, the authors own the self-deprecation) intelligently combines several techniques by treating each frequency according to its needs:

YaRN: Efficient Context Window Extension of Large Language Models
  1. High frequencies (short wavelength): left untouched, they already work well
  2. Mid frequencies: progressive linear interpolation
  3. Low frequencies (long wavelength): full NTK scaling
  4. Temperature correction: without correction, attention becomes too "sharp" (concentrated on too few tokens) as the sequence gets longer. YaRN adjusts the attention scale to compensate.

It's like an audio equalizer: instead of applying the same treatment to all frequencies, you adjust each band independently based on its needs.

Plot of log-wavelength against hidden state dimension index from 0 to 64. The blue RoPE line rises steadily from 0.9 to 4.8. The orange Position Interpolation line runs parallel to it but shifted upward, starting at 2.05. The green NTK-aware line starts at the same point as RoPE and rises faster to reach 6 on the right. The red NTK-by-parts curve follows the green one exactly at first, then bends sharply up toward the orange line in the middle of the plot before converging on the same endpoint.
The equalizer, drawn out. Each line shows what a method does to each frequency band, from the fastest (left) to the slowest (right). PI in orange shifts everything uniformly, including the high frequencies it damages. NTK-aware in green respects the start but stretches the tail too much. The red curve, the one YaRN uses, leaves the first dimensions untouched, applies a gradual transition in the middle, and fully interpolates the last ones.Source : EleutherAI, Extending the RoPE (post by the YaRN authors)
YaRN results in practice

In the paper, LLaMA 2 goes from 4K to 64K, even 128K tokens, with only ~400 fine-tuning steps. Perplexity stays under control up to 32x the original length (4K × 32 = 128K). That's a remarkable effort/result ratio.

Other approaches

LongRoPE

Uses an automatic search to find the best interpolation factors per dimension. The paper reaches a 2-million-token context (a factor of ~500 from 4K) but requires more fine-tuning and compute for the search phase.

Self-Extend

No fine-tuning needed! Combines local attention (normal positions) with "grouped" attention (positions divided by a factor). Relies on the fact that the model already handles local positions well and only needs an approximation for distant positions.

Long Training (the brute force method)

Retrain directly on long sequences with a RoPE base of 500K. It's slow and expensive, but gives the best results because the model truly learns to handle long distances.

Comparison table

The orders of magnitude below are indicative, each paper measures on its own models and settings:

MethodFine-tune?Typical extensionQualityCost
Position InterpYes, shortup to ~16xGoodLow
NTK-awareNo/Yes~4-16xGoodLow-Medium
Dynamic NTKNo~4-8xDecentVery low
YaRNYes, minimalup to ~32xExcellentMedium
LongRoPEYes, short~500x (2M tokens)Very goodMedium-High
Long TrainingYes, massiveNo fixed limitOptimalVery high
Practical recommendation

In the vast majority of cases: YaRN. The quality/effort ratio is unbeatable. For extreme extensions (millions of tokens): LongRoPE. For immediate use without any fine-tuning: Dynamic NTK (acceptable for 2-4x extension).

Evaluating a context extension

Needle in a Haystack

The classic test: insert specific information at a random position in a very long text, then ask the model to retrieve it. If the model finds it regardless of position, the extension works. If not, it's a bluff: the model "accepts" the long context but doesn't really exploit it.

RULER and advanced benchmarks

More demanding tests that don't just check whether the model retrieves information, but whether it can reason about information scattered throughout a long context. Extensions through simple interpolation often fail at these more realistic tests.

Conclusion

Context extension is both a science and an art. The techniques are based on relatively simple modifications to RoPE parameters, but hyperparameter tuning is delicate. YaRN is the current sweet spot: minimal fine-tuning, excellent results.

Check your understanding0 / 5

1. Position Interpolation squashes all positions by a factor of 4 to fit 16K tokens into a 4K range. What is the price?

2. Rather than squashing all positions uniformly, the NTK method inflates RoPE's base. What does that achieve?

3. In what way does YaRN behave like an audio equalizer?

4. What is Dynamic NTK's distinctive advantage?

5. What does the « needle in a haystack » test verify?