Rotary Position Embeddings (RoPE)
Notation
| Notation | Description |
| -th query vector without positional information | |
| -th key vector without positional information | |
| -th query vector with positional information | |
| -th key vector with positional information |
Motivations: We Pursue Relative Positional Embedding
To incorporate positional information into the attention mechanism, we need to transform the original query and key vectors. The functions encode the position indices and into the query and key vectors respectively, resulting in position-aware representations and .
Typically, the attention score between a query at position and a key at position can be represented as a function that depends on both the content vectors ( and ) and their absolute positions ( and ) as follows:
but we want the attention score to only depend on the relative position () rather than absolute positions and , as relative position is easier to generalize to unseen sequence lengths.
Goal of relative positional embedding: Thus our goal is to find a function which is only a function of , , and , instead of and themselves as follows:
The RoPE is a solution to this goal.
RoPE (Rotational Position Embedding)
RoPE is a positional embedding that is a function of the relative position , which rotates the query and key vectors and then computes the attention score, which is a function of the relative position .
The base idea of RoPE is to rotate the query and key vectors by a certain angle, thus their dot product is a function of the relative position . RoPE used the property of rotation matrix multiplication. When we need to rotate a 2-dimensional vector by an angle , we can multiply a rotation matrix to the vector , to get the rotated vector .
In the following, suppose the query and key vectors are 2-dimensional vectors. We can rotate the query and key:
The attention score is then:
thus we have shown that the attention score is a function of , , and their relative position , not the absolute positions and themselves.
RoPE Implementation (Half-and-Half Pairing)
This is the method used in your Python code and in many popular implementations like LLaMA. It is chosen for its extreme efficiency with vectorized operations. Instead of pairing adjacent dimensions (which is intuitive), this method pairs the first half of the dimensions with the second half.
For a vector with dim:
- Pair 0: dimension is paired with dimension .
- Pair 1: dimension is paired with dimension .
- โฆ
- Pair : dimension is paired with dimension .
In practice, the query and key vectors are not 2-dimensional vectors, but -dimensional vectors ().
we then group the query and key vectors into pairs, and rotate each pair by a different angle (). Usually we make the following pairs: .
For each pair (), we rotate by an angle , where is a base frequency (typically ), is the -th dimension , and is the dimension of the query and key vectors.
This means higher dimensions get rotated by larger angles, creating a spectrum of different frequencies in the positional encoding.
The rotated query vector becomes:
Similarly for the key vector:
When we compute the attention score between these rotated vectors, each pair contributes a term that depends on the relative position , similar to the 2D case we analyzed earlier. The different frequencies allow the model to capture position-dependent patterns at different scales.
Thus we have:
Example:
Letโs walk through how the code achieves this with a concrete example where dim . The input query vector is .
Pairing: The pairs will be: .
Frequency: There will be unique angles for a given position : . These angles are calculated based on the position and the pair index :
where is the dimension. For example,
We construct the angles for a given position as .
The final cos and sin tensors will therefore have this duplicated structure. For position m:
Now, letโs see how the rotation is applied to .
We construct half-rotated query vector as .
We then construct the query vector as:
If we let our 2D vector be and the rotation angle be , the standard 2D rotation formulas are:
As you can see, the code perfectly implements the 2D rotation for the pair . This same logic applies simultaneously to all other pairs: , , .
Extending RoPE to Longer Contexts
Vanilla RoPE is trained with a fixed maximum context length . For positions , the phase values exceed the range the model encountered during training, degrading performance. Three principal strategies address this: modifying the base frequency (ABF), interpolating positions uniformly (PI), and combining dimension-wise interpolation with temperature scaling (YaRN).
Recall that the phase (rotation angle) for dimension pair at position is:
The goal of context extension is to keep phase values at positions within the range the model learned during training (). We write for the context extension ratio throughout.
We can express all extension methods in a general interpolation framework. Given the original RoPE encoding , each method defines a modified encoding:
where transforms positions and transforms frequencies. The choice of and distinguishes the methods.
ABF (Adjusted Base Frequency)
ABF extends the context by replacing the base frequency with a larger value (), directly reducing the angular frequencies and slowing phase accumulation. In the general framework, ABF sets (positions unchanged) and (frequencies reduced).
Derivation
With the scaled base , the phase for dimension pair at position becomes:
Historical Context: From NTK Theory to Base Scaling
The idea of modifying the base frequency to extend context did not originate in a traditional research lab. In late June 2023 โ just days after Chen et al. published Position Interpolation โ a pseudonymous Reddit user, u/bloc97, posted โNTK-Aware Scaled RoPEโ on the r/LocalLLaMA forum. The post demonstrated that by changing only three lines of code (replacing with a larger base), LLaMA 7B could handle 8K+ token sequences without any fine-tuning and with minimal perplexity degradation. This sparked a rapid wave of community-driven innovation: u/emozilla proposed Dynamic NTK scaling shortly after, and bloc97 followed up in July with NTK-by-parts โ each refinement building on the last within weeks rather than months. By August, Metaโs Code Llama had adopted a base of , validating the approach at production scale. Peng et al. formalized the full method as YaRN in September 2023 (published at ICLR 2024).
The name โNTK-awareโ comes from Neural Tangent Kernel theory (Jacot et al., 2018). The key theoretical connection is this: RoPEโs position encoding is essentially a random Fourier feature mapping, and NTK theory predicts that such Fourier features must preserve a spectrum of frequencies matching the target functionโs complexity. When PI compresses all frequencies uniformly by , it narrows the entire spectral bandwidth โ destroying the high-frequency components that the network relies on for fine-grained local position discrimination. Base scaling, by contrast, distributes the interpolation pressure non-uniformly: dimensions with small (high frequency, encoding local patterns) are barely changed, while dimensions with large (low frequency, encoding global patterns) absorb most of the compression. This preserves the modelโs sensitivity to nearby token relationships while still preventing out-of-distribution phase values at long distances.
How Modifying the Base Changes Phase Growth
We can factor the ABF phase as:
Thus the phase reduction factor compared to vanilla RoPE is , which is dimension-dependent:
- For : reduction โ the highest-frequency component is unchanged.
- For : reduction โ the lowest-frequency component sees the largest reduction.
ABF primarily compresses the low-frequency (high-dimensional) pairs while leaving the high-frequency (low-dimensional) pairs nearly intact, because the exponent amplifies the effect of for larger .
Choosing : NTK-Aware Scaling
To extend from context length to , we require the lowest-frequency pair () at position to not exceed its vanilla phase at position :
The minimum value gives the NTK-aware base:
Practical Base Frequency Values
The theoretical analysis above predicts the minimum base frequency needed for a target context length. In practice, several prominent models adopt large base values that align with these bounds:
- Code Llama: (extending from 4K to 100K tokens).
- Meta long-context models: (extending LLaMA-family models to 32Kโ128K tokens).
Men et al. (2024) establish a tighter theoretical bound by requiring the cumulative rotation for effective positional discrimination. Their analysis yields minimum base requirements that grow rapidly with context length: approximately for 4K context, for 32K, and for 128K. The values used in practice (โ) sit comfortably above these theoretical minima.
A key advantage of ABF over pure position interpolation is that it preserves local positional resolution โ nearby tokens at low dimension pairs still see approximately the same phase differences as in vanilla RoPE, since the high-frequency components are nearly unchanged. The cost is that inter-dimensional phase ratios are distorted, as we will see when comparing with PI and YaRN below.
Limitations of Large Scaling Factors
While ABF successfully extends context length, increasing the scaling factor introduces growing distortions that limit its effectiveness. Recall from the stability analysis that ABF modifies the inter-dimensional phase ratio by an extra factor of . As grows large, this factor becomes substantial for dimension pairs that are far apart in index โ meaning the model encounters inter-dimensional relationships that deviate significantly from what it learned during pre-training. In the extreme, with and , the ratio between the lowest and highest frequency pairs is distorted by a factor exceeding , a regime well outside the modelโs training distribution.
Research by Liu et al. (2023) on scaling laws for RoPE-based extrapolation reveals a counterintuitive finding: the default base of actually yields the worst extrapolation performance when models are fine-tuned for longer contexts. Performance improves when the base is adjusted in either direction. Smaller bases (e.g., ) produce smooth, gradual perplexity degradation that enables nearly unlimited extrapolation potential, while larger bases (e.g., ) produce excellent performance within a well-defined range but exhibit a sharp perplexity cliff beyond it. This non-monotonic behavior arises from a critical dimension โ the dimension index beyond which wavelengths are shorter than the training context . For LLaMA 2 7B with , this critical dimension is approximately . Dimensions beyond have already completed many rotation cycles during training and can extrapolate safely, while dimensions below it have not seen a full cycle and require interpolation. The interplay between these two regimes explains why the default base sits at a local pessimum: it places too many dimensions in the ambiguous intermediate zone.
Men et al. (2024) reinforce this picture with their finding of โsuperficial long-context ability.โ Models with an insufficiently large base can achieve low perplexity on long sequences โ appearing to handle extended contexts โ while actually failing at tasks that require precise long-range retrieval. The perplexity metric masks the modelโs inability to attend to distant tokens with high specificity, because the cumulative rotation bound approaches zero before the perplexity fully degrades. This gap between perplexity and retrieval accuracy is an important caveat when evaluating any base-scaling approach.
PI (Position Interpolation)
Position Interpolation takes the simplest possible approach: instead of modifying frequencies, it scales down all positions to fit within the trained range. In the general framework, PI sets (positions compressed) and (frequencies unchanged).
Derivation
Given the context extension ratio , PI maps each position:
The frequencies remain unchanged. The phase at position becomes:
How Position Interpolation Changes Phase
We can factor the PI phase as:
The reduction factor is , which is uniform across all dimensions.
At the extended boundary :
The phase at position under PI equals the phase at position under vanilla RoPE for every dimension . The model sees the same range of phase values it was trained on, just at a finer positional granularity.
Stability of Phase Ratios
Why PI preserves inter-dimensional relationships. Under vanilla RoPE, the inter-dimensional phase ratio between pairs and is:
Under PI, this ratio is preserved exactly (the cancels):
Under ABF, the modified frequencies change this ratio to:
The extra factor distorts the learned inter-dimensional relationships. Since PI preserves these ratios exactly, it typically requires less fine-tuning and is more stable when extending context length.
Limitations of Uniform Interpolation
While PI elegantly preserves inter-dimensional phase ratios, the uniform compression has a significant drawback. High-frequency dimension pairs (small ) already have short wavelengths โ they encode fine-grained local position differences. Compressing these by reduces the modelโs ability to distinguish nearby positions, effectively losing high-frequency positional information.
Low-frequency pairs (large ), on the other hand, have wavelengths much longer than the training context . For these dimensions, the model has never seen a full rotation cycle during training, so the phase values encountered at positions up to occupy only a small arc. These dimensions genuinely need interpolation to avoid out-of-distribution phase values at positions beyond . But high-frequency dimensions already complete many full rotations within , so they can tolerate positions beyond without extrapolation problems.
This observation โ that different dimensions require different amounts of interpolation โ motivates the more sophisticated YaRN method.
YaRN (Yet Another RoPE ExtensioN)
YaRN addresses the limitations of both ABF and PI by combining dimension-wise interpolation (NTK-by-parts) with attention temperature scaling. Rather than applying a single strategy uniformly, YaRN classifies each dimension pair according to how much interpolation it needs and blends PI with identity scaling accordingly.
Wavelength Analysis
Each dimension pair has a characteristic wavelength โ the number of positions for a full rotation:
We define the ratio of the training context length to this wavelength:
This ratio tells us how many full rotation cycles dimension completes within the training window:
- High ratio (): the model has seen many full cycles during training. This dimension encodes local positional patterns and can tolerate extrapolation to positions beyond without problems. No interpolation is needed.
- Low ratio (): the model has seen only a small arc of the full rotation. Positions beyond would produce phase values the model has never encountered. Full interpolation (as in PI) is needed.
- Intermediate ratio: a blend of interpolation and identity is appropriate.
NTK-by-Parts Interpolation
YaRN uses a ramp function to smoothly transition between full interpolation and no interpolation, based on the ratio :
where and are hyperparameters controlling the transition boundaries. For the LLaMA model family, the recommended values are and .
The choice of these boundaries has a precise physical interpretation tied to rotation cycles. A dimension pair with โ that is, โ has a wavelength longer than the training context . The model has seen less than one full rotation cycle for this dimension during pre-training, so any position beyond pushes the phase into entirely uncharted territory. These dimensions are the most vulnerable to extrapolation failure and must receive full PI-style interpolation. At the other extreme, means the model has observed 32 or more complete rotation cycles during training. The positional patterns at these frequencies are thoroughly learned; the model can reliably extrapolate because the periodic structure is well established. Leaving these dimensions unchanged preserves the fine-grained local position sensitivity that PI would destroy.
This connects directly to the critical dimension concept from Liu et al. (2023): the boundary corresponds roughly to the index where dimensions transition from having seen partial rotations to having seen full cycles. YaRNโs ramp function effectively operationalizes this theoretical boundary, with marking the onset of safe extrapolation and marking the point of full confidence. The linear transition between them provides a smooth blend that avoids abrupt changes in the frequency spectrum โ a design choice validated empirically across the LLaMA model family.
The modified frequency for dimension pair is then:
We can factor this to understand the per-dimension behavior:
The three regimes are:
- When (low-frequency dimensions, ): , identical to PI โ full interpolation.
- When (high-frequency dimensions, ): , the frequency is unchanged โ no interpolation at all.
- When (transition region): , a linear blend between PI and identity.
Temperature Scaling
NTK-by-parts interpolation solves the dimension-wise frequency problem, but it introduces a subtler issue: the modified frequencies change the entropy of the attention distribution. When we interpolate some dimensions but not others, the effective magnitude of the dot-product attention scores shifts, causing the softmax to become either too sharp or too diffuse compared to the original model.
YaRN corrects this with a temperature parameter applied to the attention logits:
The temperature is derived from the extension ratio via an empirically calibrated formula:
Solving for :
Since , we have , which gives . Dividing by scales up the attention logits, sharpening the attention distribution. This counteracts the entropy increase caused by the modified frequencies, restoring the attention pattern to a distribution similar to what the model learned during training.
For example, with : , so .
The formula was found by empirical fitting, not theoretical derivation. Peng et al. applied NTK-by-parts with various scaling factors to LLaMA 7B, 13B, 33B, and 65B models without fine-tuning, sweeping over temperature values for each configuration to find the one minimizing perplexity. When they plotted against , the relationship turned out to be remarkably linear โ and consistent across all four model sizes. They validated this across 896 documents from RedPajama at different token positions, confirming that the optimal temperature depends primarily on the extension ratio rather than on model size or input content.
To understand why NTK-by-parts increases entropy in the first place, consider what happens to the dot-product attention scores. Interpolated dimensions (those with ) have their frequencies reduced by , which compresses the phase differences between tokens โ positions that were once far apart in rotated space now appear closer. These dimensions contribute smaller dot products to the attention score. Meanwhile, unchanged dimensions (those with ) contribute normal-magnitude dot products. The net effect is that the range of attention scores across different key positions shrinks: the gap between the most-attended and least-attended tokens narrows. When softmax operates on these compressed scores, it produces a flatter, more uniform distribution โ higher entropy. The model attends to everything more equally, losing its ability to focus on the most relevant tokens. Dividing by is equivalent to multiplying the attention logits by , which stretches the score range back out, restores the sharpness of the attention distribution, and brings the entropy profile closer to what the model learned during pre-training.
We note that the temperature formula is architecture-dependent. The coefficient in was fit specifically for LLaMA models. For Mistral-7B, the optimal coefficient shifts to approximately , reflecting differences in head dimension, number of attention heads, and the learned attention patterns. In the general parametric form , both and may need re-fitting when applying YaRN to a new architecture โ though the logarithmic relationship with appears to be universal.
Dynamic NTK
In practice, the extension ratio need not be fixed at inference time. Dynamic NTK computes the scaling factor on the fly based on the current sequence length :
When , we have and YaRN reduces to vanilla RoPE โ no modification is applied. As exceeds , the interpolation gradually activates. This allows a single model to handle both short and long sequences without committing to a fixed extension ratio at deployment time.
Empirical Performance
We can now examine how YaRN performs in practice relative to other extension methods. The following table summarizes perplexity results on the Proof-pile evaluation set using a sliding window of tokens, drawn from the YaRN paper (Peng et al., 2023):
| Model | Method | Perplexity (65K) | Perplexity (128K) |
| LLaMA 2 7B | YaRN () | 2.42 | โ |
| LLaMA 2 7B | YaRN () | 2.37 | |
| LLaMA 2 13B | YaRN () | โ | 2.24 |
| Code Llama 7B | ABF () | 2.55 | 2.54 |
| Together AI 7B | PI | K blow-up | โ |
YaRN achieves the lowest perplexity at 128K tokens with the 13B model, outperforming Code Llama despite the latter using a much larger base frequency of . PI, while theoretically elegant, fails catastrophically beyond its trained extension range โ perplexity explodes past 32K tokens for the Together AI model. On passkey retrieval โ a stricter test of whether the model can actually attend to a specific token at arbitrary distances โ YaRN (, 128K) achieves 99.4% accuracy, matching Code Llamaโs 100K result.
The training efficiency comparison is equally striking. NTK-aware scaling from Xiong et al. requires approximately 64,000 A100 GPU-hours of continued pre-training. PI (Chen et al.) brings this down to roughly 640 GPU-hours. YaRN requires only 384 GPU-hours total โ 256 for the initial 64K extension plus 128 for the additional 128K stage โ using approximately 0.1% of the original pre-training data and converging in just 400 optimization steps for the first stage. This makes YaRN the most compute-efficient method by a significant margin while achieving superior or comparable results.
An important caveat emerges from these results: perplexity alone is not a reliable indicator of long-context capability. YaRN with achieves similar perplexity to , yet the model scores meaningfully higher on passkey retrieval, demonstrating better ability to attend to distant tokens. This gap suggests that perplexity primarily captures local language modeling quality, while retrieval tasks probe whether the model can genuinely leverage the full extended context. When evaluating RoPE extension methods, we recommend testing with retrieval-based benchmarks (such as passkey retrieval or needle-in-a-haystack) alongside perplexity.
From a practical standpoint, YaRN incurs zero computational overhead at inference time. The modified frequencies are pre-computed and cached, just as in vanilla RoPE, and the temperature scaling amounts to a single scalar multiplication on the attention logits. YaRN is natively supported in HuggingFace Transformers via rope_type: "yarn", and has been adopted by production models including Qwen, DeepSeek, and later LLaMA variants โ making it the de facto standard for RoPE-based context extension.
Comparison of Extension Methods
| Method | Phase at position | Reduction factor | Scaling type |
| Vanilla RoPE | โ | โ | |
| Base scaling () | Dimension-dependent | ||
| ABF () | Dim.-dependent (calibrated) | ||
| PI () | Uniform | ||
| YaRN (NTK-by-parts) | , with per-dim. | Dimension-adaptive + temp. |
where is the context extension ratio and is the ramp function evaluated at each dimension.
We can summarize the key trade-offs as follows:
- Base scaling and ABF modify the frequency spectrum in a dimension-dependent way, preserving high-frequency (local) positional resolution at the cost of distorting inter-dimensional phase ratios.
- PI applies a uniform reduction that perfectly preserves phase ratios but sacrifices high-frequency resolution.
- YaRN achieves the best of both worlds: it preserves high-frequency dimensions (where the model can extrapolate) while interpolating only the low-frequency dimensions (where extrapolation would fail), and corrects the resulting entropy shift via temperature scaling.
