Rotary Position Embeddings (RoPE) Explained: How LLMs Encode Token Order and Stretch Their Context
Most open LLMs know where each token sits by rotating their query and key vectors. Here is how RoPE works, why it yields relative positions for free, and how Position Interpolation and YaRN reuse the same rotations to extend a model's context window.
Self-attention on its own has no sense of order. If you shuffle the tokens of a sentence, plain dot-product attention produces the same set of scores, just permuted. Every transformer therefore needs some way to tell the model where each token sits, and the choice matters more than it first appears: it determines how well the model handles long documents and whether its context window can be stretched after training.
Rotary Position Embedding, usually shortened to RoPE, is the scheme used by a large share of today's open-weight language models, including the Llama family. It was introduced in the RoFormer paper by Jianlin Su and colleagues in 2021. This guide explains what RoPE actually computes, why it gives attention a relative notion of distance without any extra parameters, how to implement it in a few lines, and how context-extension methods such as Position Interpolation and YaRN work by adjusting its rotation frequencies.
The problem with adding position vectors
The original transformer added a fixed sinusoidal vector to each token embedding before the first layer. Learned absolute embeddings, used by early GPT and BERT models, do the same with a trainable table. Both approaches encode absolute position: token 7 gets one vector and token 1,007 gets another. The model has to learn from data that the pair (7, 10) and the pair (1,007, 1,010) are related in the same way, because nothing in the arithmetic says so.
Absolute embeddings also leave no obvious path beyond the training length. A learned table simply has no row for position 5,000 if training stopped at 4,096. Relative schemes fix part of this by adding a bias that depends on the distance between tokens, but many of them require modifying the attention computation in ways that are awkward to optimize.
The core idea: rotate, don't add
RoPE leaves the token embeddings alone. Instead, inside every attention layer, it takes the query and key vectors for each head, splits each vector into pairs of dimensions, and treats every pair as a point on a 2D plane. The pair is then rotated by an angle proportional to the token's position. A token at position m has its pair number i rotated by the angle m times theta_i.
The frequencies follow a geometric schedule borrowed from the original sinusoidal encoding. For a head dimension d, pair i uses theta_i = 10000^(-2i/d), with i running from 0 to d/2 - 1. The first pair spins fast, a full radian per token. The last pair spins extremely slowly. In matrix form, the RoFormer paper writes this as a block-diagonal rotation matrix built from 2x2 blocks of cosines and sines.
Values are left untouched. Only queries and keys are rotated, because only their dot product decides how much attention each token pays to the others.
Why rotation gives you relative position
Rotation has a useful algebraic property. If you rotate one vector by angle a and another by angle b, their dot product equals the dot product of the original vectors with a single rotation of b minus a applied between them. Applied to attention, the score between a query at position m and a key at position n depends on the content of the two tokens and on n minus m, but not on m or n individually. The RoFormer paper states this as q_m^T k_n = x_m^T W_q R_(n-m) W_k x_n.
That is the main reason RoPE became popular. The model receives absolute positions as input, since each token is rotated by its own index, yet the attention scores only ever see relative offsets. There are no learned position parameters, and because rotations preserve vector length, the magnitude of each query and key is unchanged. The paper also shows that this construction produces a gradual decay in how strongly tokens can interact as the distance between them grows, which matches the intuition that nearby words usually matter more.
A minimal implementation
The following NumPy example rotates a vector using interleaved pairs and then checks the relative-position property directly. It computes the attention score for positions 10 and 7, then for positions 1,010 and 1,007. The offset is three in both cases, so the scores match to floating-point precision.
import numpy as np
def rope_freqs(dim, base=10000.0):
# theta_i = base^(-2i/dim) for i = 0 .. dim/2 - 1
return base ** (-np.arange(0, dim, 2) / dim)
def apply_rope(x, pos, base=10000.0):
# x: (dim,) vector, rotated in interleaved pairs (x0,x1), (x2,x3), ...
theta = rope_freqs(x.shape[-1], base) * pos
cos, sin = np.cos(theta), np.sin(theta)
x_even, x_odd = x[0::2], x[1::2]
out = np.empty_like(x)
out[0::2] = x_even * cos - x_odd * sin
out[1::2] = x_even * sin + x_odd * cos
return out
rng = np.random.default_rng(0)
q, k = rng.standard_normal(64), rng.standard_normal(64)
# Same relative offset (3), very different absolute positions
a = apply_rope(q, 10) @ apply_rope(k, 7)
b = apply_rope(q, 1010) @ apply_rope(k, 1007)
print(f"{a:.6f} {b:.6f}") # identical scores
print(np.allclose(np.linalg.norm(apply_rope(q, 500)), np.linalg.norm(q))) # True
Production code works on whole tensors of shape batch by heads by sequence by head dimension, precomputes the cosine and sine tables once, and fuses the operation into a kernel, but the arithmetic is exactly this.
Interleaved versus half-split layouts
The paper pairs adjacent dimensions, so dimension 0 goes with 1, 2 with 3, and so on. The Hugging Face Transformers implementation of Llama uses a different layout: its rotate_half helper splits the vector into a first half and a second half and pairs dimension i with dimension i plus d/2. Both are valid rotations and give the same relative-position behaviour, but they are not interchangeable. Loading weights trained with one layout into code that applies the other silently corrupts attention, which is why conversion scripts between frameworks sometimes permute the query and key projection weights.
Reading the frequencies as wavelengths
A helpful way to think about RoPE is in terms of wavelength, the number of tokens it takes a pair to complete one full turn, which is 2 pi divided by theta_i. For a head dimension of 128 and base 10,000, the numbers look like this:
- Pair 0: theta is 1, so the wavelength is about 6.3 tokens. This pair distinguishes neighbouring tokens precisely but wraps around constantly.
- Pair 8: theta is about 0.316, giving a wavelength of about 20 tokens.
- Pair 32: theta is 0.01, giving a wavelength of about 628 tokens.
- Pair 63: theta is about 0.000115, giving a wavelength of roughly 54,000 tokens, far longer than most training contexts.
High-frequency pairs carry fine-grained local order, while low-frequency pairs act more like a coarse sense of how far apart two tokens are. This split is the key to understanding why naive context extension fails and why the better methods treat different pairs differently.
Why models break past their training length
If a model was trained on sequences of up to 4,096 tokens, its low-frequency pairs never completed a full rotation during training. Feed it position 16,000 and those pairs reach angles the model has never seen. The Position Interpolation paper by Chen and colleagues reports that this kind of extrapolation can produce catastrophically high attention scores, and in practice perplexity rises sharply once a RoPE model runs past its trained window.
Position Interpolation
Position Interpolation takes the simplest possible approach: instead of extending positions, it squeezes them. To run a model trained on length L at a new length L', every position index is multiplied by L divided by L'. A model trained on 2,048 tokens and run at 8,192 sees position 8,000 as position 2,000, an angle it already knows. The authors extended LLaMA models from 7B to 65B parameters to context windows of up to 32,768 tokens with fewer than 1,000 fine-tuning steps.
The cost is resolution. Squeezing all positions also squeezes the fast pairs, so neighbouring tokens end up closer together in angle than the model is used to, which can blur fine local ordering.
NTK-aware scaling and YaRN
The next wave of methods kept the fast pairs mostly intact and interpolated mainly the slow ones. NTK-aware scaling, first shared by a community researcher known as bloc97, does this by enlarging the base instead of rescaling positions. With a scale factor s and head dimension D, the new base is b times s raised to D divided by D minus 2. That leaves the highest-frequency pair unchanged while stretching the lowest-frequency pair by roughly a factor of s.
YaRN, by Peng, Quesnelle, Fan and Shippole, refines this in two ways. First, its NTK-by-parts rule computes, for each pair, how many full rotations it makes across the original context. Pairs that rotate many times are left alone, pairs that rotate less than once are interpolated as in Position Interpolation, and pairs in between are blended with a linear ramp. For the Llama family the paper uses thresholds of 1 and 32 rotations. Second, YaRN applies a mild temperature to attention, implemented by scaling the rotary embeddings by 0.1 times ln(s) plus 1, which is about 1.21 for an eightfold extension. The authors report extending Llama 2 7B and 13B to a 128k context with a few hundred fine-tuning steps and roughly ten times fewer training tokens than previous methods.
Practical checklist
- Check the model config before changing context length. In Hugging Face Transformers, RoPE settings such as the base and the scaling type live in the model configuration, with built-in options that include linear, dynamic, yarn, longrope and llama3 scaling.
- Prefer a model that was already fine-tuned for the context you need. Inference-time scaling without fine-tuning works for modest extensions, but the published results for large extensions all include some training.
- Match the pair layout to the weights. Interleaved and half-split RoPE are not interchangeable, so verify that custom kernels follow the same convention as the checkpoint.
- Re-run long-context evaluations after any change. A model can keep low perplexity on short prompts while retrieval from deep inside a long prompt quietly degrades.
- Remember that position scaling does not change memory. A longer context still grows the KV cache linearly, so plan serving capacity separately.
Summary
RoPE encodes position by rotating pairs of query and key dimensions at a spread of frequencies. Because rotations compose, attention scores depend only on the distance between tokens, with no learned parameters and no change in vector length. That same frequency structure explains both the weakness and the fix: models fail beyond their training length because slow pairs reach unseen angles, and methods such as Position Interpolation, NTK-aware scaling and YaRN extend context by deciding, pair by pair, how much to slow those rotations down.
Enjoyed this?
Get the next deep dive in your inbox. No spam — just the stories worth reading.
Subscribe to the newsletter