Model cards advertise context windows of 128K, 256K, even a million tokens — yet the underlying checkpoints were pretrained on 8K-token sequences. That mismatch is not marketing padding; it is the result of a specific piece of engineering that lives almost entirely in one component: the rotary position embedding, RoPE. Nearly every modern open-weight model — Llama, Qwen, Mistral, DeepSeek, gpt-oss — uses RoPE, and nearly every long-context release is a story about how its frequencies were rescaled after pretraining. Understanding that mechanism tells you what a “128K context” claim actually means, and why some extended models hold up while others fall apart at 20K tokens.
This post builds the mechanism from scratch: why attention needs positions injected at all, how RoPE encodes them as rotations, why naive extension beyond the training length breaks, and the family of fixes — position interpolation, NTK-aware base changes, and YaRN — that modern configs use.
Attention is order-blind by construction
Self-attention computes weighted sums over value vectors, and nothing in that computation distinguishes token order. Shuffle the input tokens and the outputs shuffle in exactly the same way — the function is permutation-equivariant. “Dog bites man” and “man bites dog” produce identical representations until position information is added from the outside.
The original transformer added fixed sinusoids to token embeddings; GPT-2 learned a lookup table of absolute position vectors. Both approaches bake in a hard limit: the table has a finite number of rows, so positions past the last trained index have no representation at all. Worse, absolute encodings generalize poorly even within range, because the model must learn what position 3,047 means from scratch rather than learning relationships between distances.
RoPE: position as rotation
Rotary embeddings take a different route: instead of adding position to the embeddings, they rotate the query and key vectors. Each attention head of width d is split into d/2 two-dimensional pairs, and pair i is rotated by an angle proportional to the token position m, with a per-pair frequency θi = base−2i/d. The key property falls out of trigonometry: rotating by m and by n combine into a rotation by m − n, so when a rotated query meets a rotated key, the dot product depends only on their distance. Absolute positions enter the computation, but relative position comes out — which is exactly what language modeling wants.
The per-pair frequencies create a multi-scale clock. Fast pairs spin quickly, resolving the difference between adjacent tokens; slow pairs barely move over thousands of positions, encoding coarse document-level ordering. With the standard base of 10,000 and a 128-dimensional head, the fastest pair completes a revolution roughly every six positions, while the slowest has a wavelength of tens of thousands. A minimal implementation:
import torch
def rope_freqs(dim, max_pos, base=10000.0):
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
t = torch.arange(max_pos).float()
freqs = torch.outer(t, inv_freq) # (max_pos, dim/2)
return torch.polar(torch.ones_like(freqs), freqs) # complex e^{i*m*theta}
def apply_rope(x, freqs): # x: (batch, seq, heads, dim)
x_ = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
return torch.view_as_real(x_ * freqs).flatten(3)
Why positions past the training length break
RoPE is mathematically defined for any position, so nothing stops you from feeding it 100,000 tokens. The failure is statistical, not mechanical. Consider a pair whose wavelength is longer than the training context: during pretraining it never completed a single revolution, so every token sits at a distinct, never-repeating angle. That pair quietly functions as an absolute position marker — and every angle beyond the training length is out of distribution for it. Models degrade sharply past their trained context not because the rotations are undefined, but because the network is now reading dials it never saw during training.
Which pairs break depends on the wavelength. Pairs that completed many revolutions during training have seen essentially every angle already — for them, longer contexts change nothing. Only the slow, long-wavelength pairs are the problem. That asymmetry is the key insight behind every modern extension method: the fast pairs must be left alone, the slow pairs must be brought into distribution.
Position interpolation: shrink the positions
The simplest fix divides every position by the scale factor s = L'/L, where L is the trained length and L' the target. Feeding position m as m/s means 32K positions now produce exactly the angles the model saw up to its 2K training horizon — no new angles anywhere, guaranteed in-distribution. Extending Llama 2 from 2K to 32K this way took on the order of a thousand fine-tuning steps.
The cost is resolution. Dividing all positions by s = 16 means the fastest pair now advances 1/16 radian between adjacent tokens instead of 1 radian — the local-order signal the model relies on to distinguish neighboring tokens is compressed sixteenfold. Interpolation pressure applied uniformly hurts the pairs that were never broken. Fine-tuning recovers much of it, but at large scale factors the high-frequency loss stops being recoverable, and quality degrades.
NTK-aware scaling: raise the base instead
The next step applies the fix unevenly. Rather than scaling positions, it changes RoPE’s base so the slow pairs are slowed by the full factor while the fast pairs stay untouched:
b' = b * s^(d / (d - 2))
For a 4x extension of a 128-wide head, this turns a base of 10,000 into roughly 40,890. High frequencies keep their local resolution; low frequencies reach the new horizon without spinning into unseen territory. A useful side effect is that this works reasonably well with no fine-tuning at moderate scale factors, which made it popular for running local models past their advertised windows. Its flaw is precision: the base change is a smooth compromise, and the middle-frequency pairs — neither fully fast nor fully slow — end up slightly extrapolated, rotating past angles they never saw. With fine-tuning it underperforms plain interpolation, because those out-of-bound rotations confuse exactly the pairs that carry the most positional information.
YaRN: interpolate by rotation count, plus a temperature
YaRN makes the per-pair policy explicit. Each pair’s wavelength λ implies a rotation count r = L/λ over the training length — how many full turns it completed during pretraining. Then:
- pairs with
r < α(barely rotated — the absolute-position pairs) are interpolated by the full factors, exactly like position interpolation; - pairs with
r > β(well-practiced — the local-order pairs) are left completely untouched; - everything in between blends linearly between the two regimes.
For the Llama family, α = 1 and β = 32 work well. YaRN adds one more ingredient: attention logits are scaled by a temperature 1/t = 0.1·ln(s) + 1, compensating for the fact that attention over longer contexts spreads mass across many more tokens and becomes too diffuse. The result extends Llama 2 to 128K with roughly 400 fine-tuning steps at s = 16 plus 200 more at s = 32 — an order of magnitude less data than prior methods — and most current production models fine-tune with a YaRN-style scheme for context expansion.
Reading it in a real config
Llama 3.1’s 128K window is a worked example of the by-parts idea baked into a released checkpoint. Its configuration combines a much larger base with a ramp rule over wavelength boundaries:
{
"rope_theta": 500000,
"rope_scaling": {
"rope_type": "llama3",
"factor": 8,
"low_freq_factor": 1,
"high_freq_factor": 4,
"original_max_position_embeddings": 8192
},
"max_position_embeddings": 131072
}
The semantics: pairs whose wavelength exceeds the training length divided by high_freq_factor keep their original frequencies; pairs whose wavelength exceeds the horizon entirely are scaled by the full factor of 8; pairs in between blend. With a 500K base, a large fraction of the pairs never complete even one turn across 8K training positions, so treating the slow band separately is not optional — it is most of the spectrum. The scaling rule ships in Hugging Face transformers, and the same structure appears across the Qwen and Mistral long-context releases with different constants.
Legal positions are not the same as good ones
One caveat deserves its own paragraph. Every method above makes long contexts possible — they ensure no rotation lands outside what training covered, or covers it with fine-tuning. Whether the model can actually retrieve and combine information from 100K tokens back depends on the long-context training data, and systematic benchmarks of long-context models have repeatedly found that effective context is often a fraction of the advertised window. The RULER evaluation of seventeen models that all claimed 32K-plus windows found only about half remained satisfactory at 32K. When a release headline says “2M context,” read the configuration — base, scaling rule, fine-tuning length — and look for effective-length measurements before designing a pipeline around it.
There is also a serving-side subtlety: dynamic scaling schemes adjust the scale factor per forward pass based on the current sequence length, which means the rotation applied to each token changes as the sequence grows. Implementations must cache keys and values before RoPE is applied, or the cache silently mixes rotations computed under different scale factors. If you serve one of these models yourself, that detail lives in your inference stack, not the checkpoint.
Wrapping up
RoPE encodes position as rotation, gets relative-distance attention for free, and would extend to arbitrary lengths — if every frequency had completed its training revolutions. Long-context engineering is the art of rescaling exactly the pairs that didn’t: interpolate the slow ones, protect the fast ones, and let the middle ramp between them. Position interpolation does it bluntly, NTK-aware base changes do it cheaply, and YaRN does it explicitly with a rotation-count ramp plus an attention temperature. The full machinery is documented in the RoFormer paper and the YaRN paper, but the config-level takeaway is compact: when you see rope_scaling in a model card, you are looking at the bridge between what the model was trained on and what the marketing promises — and now you can audit it.