RoPE and length extrapolation
Part of Positional encoding.
Rotary Position Embeddings (RoPE)
- Applies a rotating transform to queries and keys that encodes positions implicitly.
- Dot products are invariant to shared rotations: if query and key vectors are both rotated by their respective positions, the attention score depends only on relative position.
- Each pair of embedding dimensions is treated as a complex number and rotated by an angle proportional to position.
- For a token at position and a feature dimension pair, the rotation is defined as: .
- In matrix form for pairs of dimensions:
- The attention score (dot product) for a 2D pair between a Query at position and a Key at position becomes: (summed over all dimension pairs, each with its own frequency ).
- The result depends only on the relative distance , not on the absolute values of or . This property, known as translation invariance, theoretically allows the model to handle sequences of arbitrary length, as the interaction mechanism is identical regardless of where in the sequence the tokens appear.
- Different dimension pairs rotate at different frequencies, creating a rich positional signal across local and global scales.
- Better generalisation to longer sequences than naive sinusoids, and adopted more widely than ALiBi.
- Extensions:
- XPos (2022/2023) extends RoPE by adding an exponential decay factor () to dampen distant tokens and stabilise length extrapolation.
The extrapolation cliff
Even with RoPE, models trained on 4K contexts failed beyond that length, as rotation angles extrapolated to untested regimes caused attention score instability. While RoPE is relative, models still failed when exceeded the maximum distance seen during training:
- The rotation frequencies decay exponentially across the dimension index .
- High-frequency dimensions complete many full cycles within the original training length, so the model has already seen every angle in for those pairs.
- Low-frequency dimensions, however, rotate so slowly that during training they only sweep a small arc of the circle. When exceeds the training length, these low-frequency dimensions enter unseen rotation angles ("phases") for the first time.
- This out-of-distribution phase shift led to high attention uncertainty and "garbage" outputs — known as the extrapolation cliff.
Related analyses: Effective Long-Context Scaling of Foundation Models (Xiong et al., 2023, introducing Adjusted Base Frequency) and Understanding the RoPE Extensions of Long-Context LLMs: An Attention Perspective (Zhong et al., 2024).
Scaling RoPE to longer contexts
Position Interpolation
- 2023 — Extending Context Window of Large Language Models via Positional Interpolation
- Rescales position indices to fit within the original training range: , where is the scale factor.
- For example, extending a 4K-context model to 32K divides all positions by 8, mapping the new 32K range into the original 0–4K range.
- Chen et al. showed you can take LLaMA (trained on 2K context with RoPE) and interpolate the RoPE angles up to 32K, then fine-tune on extended-context data — requiring only about 1,000 steps.
- Effectively "stretches" the learned positional representation to cover a longer sequence. Empirically, this works surprisingly well, with any drop in perplexity largely recovered through brief additional training on long sequences.
- Shows how much of the mechanics for long context can be achieved by adjusting positional encodings and continuing training, without redesigning the architecture.
- Drawback: reduces the "resolution" of attention. By squeezing positions together, adjacent tokens become harder to distinguish, degrading performance on tasks requiring high local precision.
Neural Tangent Kernel (NTK)-aware scaling
- NTK-Aware Scaled RoPE
- Uniform interpolation damages high-frequency positional signals — not all dimensions should be interpolated equally:
- High-frequency dimensions (local context): encode information like "token A is next to token B." Interpolating (stretching) these destroys local syntax; they should be extrapolated (kept as is).
- Low-frequency dimensions (global context): encode long-range distance. These are the ones that hit the unseen-angle limit and need to be interpolated (stretched) to fit the new length.
- Applies a non-linear transform to the RoPE base , effectively "slowing down" the rotation of low-frequency components while keeping high-frequency components fast to preserve local resolution.
YaRN (Yet another RoPE extensioN)
- 2023 — YaRN: Efficient Context Window Extension of Large Language Models
- Refined NTK-aware scaling by also addressing the entropy problem:
- As sequence length grows, the attention distribution (softmax) naturally flattens because probability mass is spread over more tokens, making the model "unsure" (high entropy).
- Introduces a temperature scaling factor (where ): By dividing by a smaller number (effectively multiplying the logits), YaRN "sharpens" the distribution, counteracting the entropy increase caused by the longer sequence.
- Combined with an "NTK-by-parts" interpolation strategy, YaRN extended Llama 2 to a 128K context with just 0.1% of pre-training data.
- Dynamic variants adjust scaling based on current sequence length, enabling zero-shot context extension without fine-tuning.
Linked from
Tags: AI