Topic 1 of 6 · 5 min read
Rotary positions and context extension
Goal: Explain how rotary embeddings encode relative position and why extending a model's context needs scaling or extra training.
Rotary position embedding (RoPE) encodes position by rotating each query and key vector by an angle that grows with the token's index, so the attention score depends on the distance between two tokens. Almost every recent open-weight model, including Llama, Qwen, Mistral and Gemma, uses it instead of GPT-2's learned position table.
Check yourself · 1 of 3
What does a rotary position embedding rotate?
Why it matters
GPT-2 added a learned vector per position to the input. Position 1,025 had no vector if training stopped at 1,024. RoPE has no table, but it still has a limit: the model only saw rotation angles up to its training length. Past that, the angles are new and quality drops. If you plan to run a model at a longer context than it was trained for, you need to understand this.
How it works
- Split a query or key vector of size
head_diminto pairs of numbers. - Rotate pair
iby anglepos * theta_i. Low pairs rotate fast, high pairs slowly:theta_i = base ** (-2i / head_dim), withbaseoften 10,000 or much larger. - Compute attention as usual. The dot product of a rotated query at position m and a rotated key at position n depends only on m - n (see the RoFormer paper).
def rope(x, pos, base=10000.0):
# x: (head_dim,) ; rotate consecutive pairs
d = x.shape[-1]
inv_freq = base ** (-torch.arange(0, d, 2) / d)
ang = pos * inv_freq
cos, sin = ang.cos(), ang.sin()
x1, x2 = x[0::2], x[1::2]
out = torch.empty_like(x)
out[0::2] = x1 * cos - x2 * sin
out[1::2] = x1 * sin + x2 * cos
return out
RoPE is applied to queries and keys only, not to values, and inside every layer rather than once at the input.
Extending the context
Simply feeding a 4k-trained model 32k tokens produces angles it never saw. The fixes:
- Position interpolation: divide positions by a factor (32k / 4k = 8) so all angles stay in the trained range, then fine-tune briefly.
- Raise the base: a larger
baseslows every rotation. Several families train a long-context stage with a bigger base. - YaRN: scales different frequency pairs differently and adjusts attention temperature, reaching longer context with little fine-tuning (see the YaRN paper).
Before and after
Weak: "The model says 128k context in its config, so a 100k-token contract will work." The config states a limit, not quality at that length. Better: run a retrieval test (a fact placed at 10 %, 50 % and 90 % depth) at your real length, then decide.
What goes wrong
- Setting a larger
max_position_embeddingswithout a scaling entry or fine-tuning, and getting garbled text past the old limit. - Scaling factor in the serving engine that does not match the one used in training.
- Assuming a long window means long-range reasoning works equally well everywhere.
Examples
Interpolating 4k to 32k
A model trained at 4,096 tokens must serve 32,768. The factor is 32768 / 4096 = 8. With position interpolation, token 32,000 is treated as position 4,000, which is inside the trained angle range. Short-range detail gets blurrier, which is why a short fine-tune follows.
A config that asks for scaling
{
"max_position_embeddings": 131072,
"rope_theta": 500000.0,
"rope_scaling": {"rope_type": "yarn", "factor": 4.0,
"original_max_position_embeddings": 32768}
}
The model was trained at 32,768 and is stretched 4x to 131,072. A serving engine that ignores rope_scaling loads without error and degrades silently past 32k.
Key points
- RoPE rotates query and key pairs by position-dependent angles, so attention scores depend on relative distance.
- There is no learned position table, but angles beyond the training length are still unseen, so quality drops.
- Position interpolation, a larger base and YaRN all keep angles in or near the trained range.
- RoPE is applied to queries and keys inside every layer, not to values and not once at the input.
- A stated context length in a config is a ceiling; verify quality at your length with a retrieval test.
Common mistakes
- Believing RoPE removes any length limit because there is no position table.
- Raising max_position_embeddings in a config and expecting quality to follow.
- Applying RoPE to values or only once at the embedding layer when reimplementing.
- Skipping a long-context retrieval test because the model card lists a large window.
Check yourself · 2 of 3
A model trained at 8,192 tokens is asked to run at 65,536 with position interpolation. What factor divides the positions?
Check yourself · 3 of 3
A config shows max_position_embeddings 131072 but the serving engine ignores rope_scaling. What is the likely result?
Practice items, not counted towards your mastery.
Start here
- The Big LLM Architecture Comparison (Sebastian Raschka) (opens in a new tab)ArticleFree
Side-by-side walkthrough of recent open-weight designs: attention variants, MoE layouts, norm placement.
- RoFormer: Enhanced Transformer with Rotary Position Embedding (opens in a new tab)PaperFree
The original rotary embedding paper: how rotating queries and keys encodes relative position.
- YaRN: Efficient Context Window Extension of Large Language Models (opens in a new tab)PaperFree
A scaling method that stretches rotary models to longer contexts with little extra fine-tuning.