In one line: Rotate each query/key 2D pair by a position-proportional angle (theta_i = 10000^(-2i/d)) so the QK dot product depends only on relative offset; became the default LLM positional encoding and the substrate for the main context-extension methods (PI, NTK, YaRN, iRoPE).
How far to trust it: Believe the mathematics: the relative-offset property is exact and checkable in one line, and every major open LLM since 2023 has adopted it. Do not read the experiments as evidence that RoPE is better: they are single runs with gains of 0.2 BLEU and 1.5 to 1.7 points, the GLUE comparison sets RoFormer's validation scores against BERT's test-server scores, and the long-text result stays inside the length RoFormer was pretrained at. The evidence, point by point.
The idea in one sentence: rotate each two-dimensional pair of a token's query and key by an angle proportional to the token's position, so every attention score depends on the two tokens' content and only their relative offset, while each token is still encoded on its own, with no parameters and values untouched.
Slide two tokens 38 positions later: every arrow turns, the angle between query and key does not, so the score is unchanged. The stage beside is one 8-dimensional query and key as a tower of 4 rotation pairs, fastest at the top:
The fast pair at the top moves most, the slow pair at the bottom hardly at all. The many-pair dials below let you move both positions yourself; the one-pair picture from zero is Fig. 4 on Positional Encodings.
You need: what an attention score is (q⊤k, then a softmax) and why a Transformer needs positions at all (Positional Encodings, sections 1 and 2, which also teaches every scheme RoPE is compared with and the context-extension methods built on it; this page is the 2021 paper). New terms:
Self-attention is position-agnostic: permute the tokens and every output is permuted the same way, so position must be injected somewhere (§1). The paper writes every scheme as a choice of three functions, qm = fq(xm, m), kn = fk(xn, n) and vn = fv(xn, n), feeding the usual softmax of qm⊤kn/√d (Eqs. 1 and 2). Every prior choice is additive:
Shaw et al. add clipped trainable relative vectors to keys and values (Eq. 5); Transformer-XL swaps in a sinusoid of m − n plus two trainable vectors (Eq. 7); T5 keeps the content term and adds a trainable bias bi,j (Eq. 8); TUPE adds a separately projected position term (Eq. 9); DeBERTa keeps only the two middle, content-position terms with relative embeddings (Eq. 10).
The authors see two structural problems. First, position is entangled with content rather than stated as what attention should see, which they argue is only the relative offset. Second, the relative variants edit the expanded attention matrix, so they cannot be used with linear attention, which never materialises q⊤k for every pair (§1, §2.3).
The gap: a formulation where the query-key inner product provably depends on the two token embeddings and their offset m − n only, while each position is still encoded independently, an absolute operation per token. That last property is also what makes KV caching cheap: a key is encoded once, at its own position, and never needs recomputing.
State the requirement as an equation and solve it (Eq. 11): find fq and fk such that
Each token is encoded using only its own absolute position, yet the inner product sees only the relative offset. The answer, derived in two dimensions and then stacked, is a rotation.
The 2D case (§3.2.1, Eq. 12). Identify the plane with the complex numbers. Then
Rotate the projected query and key by an angle proportional to the position. The conjugation makes the phases subtract, so the absolute rotations by mθ and nθ leave only the relative angle (m − n)θ. As a matrix, it is a 2 × 2 rotation by mθ applied after W (Eq. 13). The one-pair picture from zero, where you shift both positions and watch the dot product stay put, is on Positional Encodings (section 3, RoPE from zero); this page goes on from there to the many pairs and the trained models.
§3.4.1 writes fq, fk and g in polar form (Eq. 23), so the constraint splits into a radial equation and an angular one (Eq. 24). Setting m = n and using the initial condition at position 0 (Eq. 25, Eq. 26) shows the angle minus its value at 0 cannot depend on the token, only on the position, φ(m) (Eq. 28); putting n = m + 1 makes φ(m + 1) − φ(m) a constant, so φ is an arithmetic progression, φ(m) = mθ + γ (Eqs. 29 and 30): rotation at constant angular speed.
The radial part is not forced in the same way: the paper takes "a straightforward solution", a norm that does not depend on position (Eq. 27), then chooses f(x, 0) = Wx to match Equation 3 and sets γ = 0 (Eqs. 32 and 33). So the angle is forced; the rest are choices, and the paper itself calls the result "a solution". (Eq. 32 also has a typo, Wqxn for Wqxm.)
The general form (§3.2.2, Eqs. 14 and 15). For even d, split the vector into d/2 independent pairs and rotate pair i by its own frequency: f(x, m) = RdΘ,m W x, with R block-diagonal, 2 × 2 rotations by mθ1, …, mθd/2 and θi = 10000−2(i−1)/d, i = 1 … d/2. Since rotations are orthogonal and (RΘ,m)⊤RΘ,n = RΘ,n−m,
which satisfies the constraint exactly (Eq. 16). Position enters multiplicatively, into q and k only: values are untouched, norms are preserved (the paper notes orthogonality "ensures stability"), there are no parameters, and it is applied in every layer rather than once at the input.
No matrix multiply needed (§3.4.2, Eq. 34). The block structure makes R·x two elementwise products: x ⊗ cos(mθ) + (−x2, x1, −x4, x3, …) ⊗ sin(mθ), with each cos and sin repeated for the two members of its pair: a few fused elementwise operations per layer. The toy models on this page use exactly this form (train.py's rotate, the page's JavaScript rotate). Much later code instead pairs dimension i with i + d/2 (Hugging Face's Llama rotate_half); it is the same rotation on a permuted layout.
Try: each dial is one of the d/2 = 8 pairs of a 16-dimensional query (solid) and key (dashed), rotated by mθi and nθi. The bar under each dial is that pair's share of qm⊤kn. Press Shift both: every dial turns, every bar stays exactly where it was. Move only m: the fast pairs on the left spin through whole turns while the slow pairs on the right barely move, so the fast ones resolve nearby offsets and the slow ones carry coarse order. The vectors are random and illustrative; the frequencies are the paper's, θi = 10000−2i/16.
The algebra says a RoPE layer's attention pattern for a stretch of text does not depend on where the stretch sits. An additive model can only learn to approximate that. Here are two real one-layer models from this page's Train short, test long tab, identical except for position (left, RoPE multiplied into q and k; right, sinusoids added to the input), both 100% correct on held-out sequences of the length they were trained on. The stage slides the same 12 digits four positions at a time and redraws the attention weights of one head of each, as bar fields: rows are the 12 queries, columns the keys they may see (the causal mask hides the upper triangle), height is weight, and each row sums to 1.
Watch the stage's steps 2 and 3. RoPE's weights are identical to the last printed digit (the largest change is floating-point noise), because every score is a function of offsets only. The sinusoidal model's weights drift as the window moves, yet it still answers correctly: it learned to work around absolute position rather than ignore it.
The head shown in each model is the one whose weight falls most on offsets 1 and 4. Weights are computed live by the page's forward pass (checked against PyTorch), and the numbers in the steps are those weights.
θi = 10000−2i/d is the same geometric spectrum as the original sinusoidal encoding, now used multiplicatively. Wavelengths run from 2π (pair 0 turns one radian per token) up to about 2π × 10000 (the slowest pair). Fast pairs resolve nearby offsets sharply; slow pairs change little over hundreds of tokens and carry coarse long-range order. This spectrum is the knob every later context-extension method turns; the Then and now tab steps through them.
It also explains the toy's main result. With 8-dimensional heads (4 pairs) trained at length 32, pair 0 turns about 5 times inside the training window, but pairs 1, 2 and 3 never complete a turn: their largest angle seen in training is 3.1, 0.31 and 0.031 radians (recompute.py). At an offset of 40 they show angles no training example ever produced. That is the mechanism behind the train short, test long failure.
The paper's second argument for RoPE: the score between distant tokens is bounded by a quantity that falls with distance (§3.4.3, Figure 2), so distant pairs get systematically weaker interaction by construction, which matches the linguistic prior and is the paper's explanation for its long-text advantage. The stage shows why the bound falls, at the head size that reproduces Figure 2 (d = 128, 64 pairs, base 10,000); the chart after it is the bound itself, and the question is whether real scores follow it.
§3.4.3 writes the RoPE inner product as a sum of complex per-pair terms, Re[Σi hi ei(m−n)θi] with hi = q[2i:2i+1]k*[2i:2i+1] (Eq. 35), and bounds it by Abel summation: with partial sums Sj = Σi<j ei(m−n)θi, the magnitude is at most maxi|hi+1 − hi| · Σj|Sj| (Eqs. 36 and 37). The paper plots the average (1/(d/2)) Σj|Sj| against distance and it falls.
The decay is a bound, not a value. It is reached when queries and keys are aligned pair by pair (the all-ones line in the chart beside); for independent Gaussian vectors the expected score is 0 at every distance and its typical size, the grey line, stays flat. Barbero et al. prove this (Proposition 3.2, 2024) and find that Gemma 7B uses the highest frequencies to build positional heads and the lowest as semantic channels, not the decay.
Try: the blue line is Figure 2 recomputed from Equation 37. Defaults reproduce Figure 2 by matching: the paper does not state d; d = 128 gives the plotted start (19.8 at distance 8) and end (about 6.5 at 256), d = 64 or 256 give half or double. Tick "show actual scores" to put real scores beside the bound, each line divided by its value at distance 0 so they share an axis: the orange line is the score for all-ones q = k (pairs perfectly aligned), which does decay; the grey line is the mean |q⊤Rk| over 200 Gaussian pairs, which does not, and the dashed line their mean, which hugs 0. Raise the base to see why long-context models do: the bound decays far more slowly.
Write attention generally as Σn sim(qm, kn) vn / Σn sim(qm, kn) (Eq. 17). Linear attention (Katharopoulos et al.; taught on Beyond attention) replaces sim with φ(q)⊤φ(k) for a non-negative feature map such as elu(x) + 1, so the key-value products can be summed first and the O(N²) cost becomes O(N) (Eq. 18). Because RoPE is a norm-preserving rotation applied to q and k rather than an edit to the attention matrix, it composes: rotate the feature-mapped vectors in the numerator, RΘ,mφ(qm) and RΘ,nφ(kn), and leave the denominator unrotated to avoid dividing by zero (Eq. 19). The paper is candid that the weights are then no longer a probability distribution (the numerator can contain negative terms) and "kindly argue[s]" they still model importance. On this basis it presents RoPE as the relative encoding that works with O(N) attention, arguing that the earlier relative schemes cannot (§1).
The toy tests this too. The same task with linear attention: see the Train short, test long tab.
All experiments ran on two cloud servers with 4 × V100 GPUs each (§4). Every number is one run. Each experiment is rebuilt in The paper's tables, rebuilt.
From Table 2, RoFormer minus BERT. The 15.2-point QQP "win" is not a model difference: BERT's row is copied from the BERT paper's GLUE test-server table (QQP F1 on the hidden test set), RoFormer's is the best validation score. More in How much of this to believe.
What holds up. The mathematics: the relative-offset property is exact, a one-line identity anyone can check (the shift test above does it on trained weights, to the last digit), and so are norm preservation, zero parameters and compatibility with KV caching. The practical claims were replicated independently and at larger scale on the day v1 appeared: EleutherAI found lower validation loss than learned absolute and T5 relative positions in GPT-NeoX on OpenWebText2 (2.759 against 2.809 and 2.801 at about 30B tokens) and at 1.5B parameters on the Pile (2.173 against 2.240 and 2.223 at about 8B tokens), about 30% faster convergence than learned absolute, a 1 to 3% overhead with fused kernels, and a large gain for Performer. Then the field adopted it (Why it matters).
What does not hold up as evidence:
Verdict: believe the mechanism, which is exact and was validated at scale by others and then by the whole field; treat the paper's tables as illustrations. Its evidence for "better than BERT" mixes test and validation splits and very different budgets, and its evidence for "long text" never leaves the trained length.
The paper's benchmark numbers were unremarkable; the formulation conquered the field anyway. Picked up first by the open-source side, in EleutherAI's codebases in April 2021 (blog) and GPT-J that year, then GPT-NeoX-20B ("based on our positive prior experiences", 2022), PaLM ("better performance on long sequence lengths", 2022) and LLaMA (2023), RoPE has been the default positional encoding of essentially every notable LLM since 2023. The properties that won: exact relative dependence with per-token absolute application (each cached key is rotated once, at cache time, so KV caching needs no recomputation), zero parameters, norm preservation, and applicability at every layer.
It also became the substrate of the whole long-context toolchain: larger bases, Position Interpolation, NTK-aware scaling, YaRN, partial and interleaved RoPE and M-RoPE each rewrite this paper's θi spectrum (or the positions it multiplies) in a model that already uses RoPE. Those methods are taught, measured and compared on Positional Encodings (sections 4 and 7); Then and now steps through them on this paper's spectrum.
Dated 2026-10-02, when this page was built; checked again 2026-10-25. The configs move; the owner page above keeps the current numbers.
Method aside, the 2D-pair rotation has become a standard reasoning tool: attention-sink analyses, length-generalisation theory and positional-encoding follow-ups are routinely phrased in RoPE's complex-exponential language (for example Barbero et al.).
The paper's selling points are that RoPE makes attention depend on relative position only, that it gives "the flexibility of sequence length", and that it works with linear attention (abstract, §3.3). This tab tests all three on real models trained offline and running in your browser. Six one-layer causal Transformers, identical except for how position enters, were trained on sequences of 32 digits and are tested here on up to 128.
Task (illustrative, built for this page): a stream of random digits 0 to 9; at every position t ≥ 4 the model must output (xt−1 + xt−4) mod 10. It needs one look exactly one back and one exactly four back, whatever t is: a pure relative-offset task, the case RoPE is designed for (§3.1). Chance is 10%.
Models: width 32, 4 heads of 8 (so 4 rotation pairs per head), one pre-LN block (attention plus a ReLU MLP of 128), a final LayerNorm and a linear readout; 13,418 parameters (17,514 with the learned table). The variants:
Training (train.py): Adam (0.9, 0.98, ε 10−9) with linear warmup over 400 steps to 3 × 10−3, then inverse square root decay, the schedule of §4.1.2; 6,000 steps of 64 fresh random sequences of length 32; seed 0. Between 33 and 52 seconds per model on a laptop CPU (2 threads). Held-out sets are drawn with separate seeds; of 500 held-out length-32 sequences, 0 occur in a 16,000-sequence sample of each training stream (1032 possible sequences). Weights are shipped at 6 bits (one base64 character per weight, one scale per row; vectors as float16); quantisation cost at most 0.3 points of held-out accuracy (the learned table, 100% to 99.7%). The JavaScript forward pass gives identical predictions to PyTorch on every one of 1,160 test sequences, logits within 5 × 10−4 and attention weights within 1.1 × 10−5 (check_forward.py).
One configuration choice, said plainly: the first run used 2 heads of 16. There the RoPE model plateaued at 84% at the trained length after 6,000 steps (97% after 20,000; 100% after 20,000 at a peak learning rate of 10−3), while sinusoidal reached 99%. Switching to 4 heads of 8 brought every softmax model to 100% at the trained length in 6,000 steps. The choice was made on in-range accuracy only, before looking at lengths past 32; the logs are in model/sweep.
Each box is the model's output at that position: shaded when it equals (xt−1 + xt−4) mod 10, outlined in orange when wrong; dashed boxes are positions 32 and later, never seen in training; the first four have no target.
Try: RoPE, length 64, query position 63. Inside the trained length the head puts its weight on offsets 1 and 4; here the weight drains to offsets past 31, angles the slow pairs never showed in training (the spectrum section says why), and the answer breaks. Now tick the sliding window: the query sees only offsets 0 to 31, all of them trained, and RoPE is right at every position up to 128, because nothing in its scores depends on absolute position. Do the same with Sinusoidal or Learned: the window does not help them, because their inputs at position 40 are themselves unseen.
Lines are each model's accuracy at every position over 500 held-out sequences, measured in PyTorch on the shipped weights (train.py export), averaged over blocks of 4 positions; the dashed line marks the trained length. "Run the test here" redraws them from 50 fresh sequences per model computed by this page's JavaScript, so the two can be compared. Position Interpolation applies only to the two RoPE models (the others are drawn as with full attention) and is used here without the fine-tuning its paper requires.
Held-out accuracy at length 32 every 100 steps, straight from the training logs (model/train_*.log), not smoothed.
Every table of §4, transcribed from the arXiv HTML (v5) with the printed precision, and every derived number recomputed in recompute.py. The two figures that carry results, Figure 3's loss curves, exist only as plots, so they are described rather than redrawn; Figure 2 is a formula and is recomputed in the Long-term decay section.
| Model | BLEU (test) |
|---|---|
| Transformer-base (Vaswani et al., 2017) | 27.3 |
| RoFormer | 27.5 |
+0.2 BLEU, one run each, both trained by the authors (§4.1). 27.3 is also exactly the Transformer paper's own base-model figure (Attention Is All You Need).
BERT's printed row equals BERT-Base in the BERT paper's Table 1, "GLUE Test results, scored by the evaluation server". RoFormer's is the best of four learning rates, averaged, on the validation set (§4.3.2). The validation-set reference is Hugging Face's run_glue example (bert-base-cased, 3 epochs at 2e-5, 5 for MRPC, one seed; its STS-B is Spearman, QQP and MRPC F1, MNLI matched and mismatched accuracy): a same-split reference, not BERT's best, and cased where the paper used uncased.
| Model | Tokenisation | Position embedding |
|---|---|---|
| BERT | char | absolute |
| WoBERT | word | absolute |
| NEZHA | char | relative |
| RoFormer | word | RoPE |
From Table 3. RoFormer is WoBERT with RoPE in place of its absolute embedding. NEZHA, the one relative-position model listed, does not appear in Table 5's results.
From Table 4, about 34 GB of Chinese text. Accuracy tracks the stage's maximum length (correlation with log2 length, recompute.py), which the paper reads as RoPE's "excellent generalizability". It is equally what any masked language model shows: with more context, masked tokens are easier to fill. The stages also differ in batch size and steps and run in sequence, so they are not a controlled comparison. The longest length seen is 1,536.
| Stage | Max length | Batch | Steps | Loss | Accuracy |
|---|
Accuracies from Table 5; splits from v1's Table 3, which v5 replaced with "8964 triplets … split … 6:2:2" (§4.5.3) while keeping the same accuracies. Whiskers are 95% intervals for each accuracy as a proportion of the test set; the gap's standard error assumes independent errors, an upper bound that a paired test on per-case results (not released) could tighten.
| v1 split | Triplets |
|---|---|
| Train | 5,102 |
| Valid | 1,500 |
| Test | 1,536 |
| Total | 8,138 |
| Position encoding | OWT2 loss | OWT2 ppl | Pile loss (1.5B) | Pile ppl |
|---|
From Rotary Embeddings: A Relative Revolution: GPT-NeoX on OpenWebText2 at 55k steps (about 30B tokens; the text says 125M-parameter models, the table caption 150M) and mesh-transformer-jax at 1.5B parameters on the Pile at 8k steps (about 8B tokens). Single runs too, but at scale, against two baselines, by a different team, on validation data.
Curves are not read off images on this page; the endpoint values above come from the printed axis ticks and are approximate.
Turns for pair i = L · θ′i / 2π on a log scale, where θ′ is the step's (possibly rescaled) frequency and L the context it runs at. Blue pairs rotate at their trained speed, orange ones are slowed by interpolation, gold ones are on YaRN's ramp, grey dimensions carry no rotation. For the per-model YaRN bands of current configs (gpt-oss, DeepSeek V3, Kimi K2), see Positional Encodings.
RoPE survived unchanged as a mechanism; what later work changed is which pairs rotate and how fast. Every long-context method of 2023 to 2025 is a rewrite of θi (or of the positions it multiplies) in a model that already uses RoPE. The animation beside steps through them on one picture: one bar per rotation pair of an attention head, its height the number of full turns that pair makes inside the context the model works at. A pair under one turn (below the dashed line) never shows its full circle in that context, so angles past what it reached in training are new to the model, the failure the toy shows.
| Then (2021) | Now | Source |
|---|---|---|
| Base 10,000, the paper's (kept by GPT-J, GPT-NeoX and LLaMA) | Larger bases trained from the start: 500,000 (Llama 3), 1,000,000 (Qwen2.5, Qwen3, Mixtral), 150,000 (gpt-oss) | Llama 3; config.json files |
| Rotate every dimension of q and k | Often only some: GPT-J 64 of 256, GPT-NeoX 25%, DeepSeek's 64-dimension decoupled key beside 128 position-free ones, Llama 4's whole layers without positions | GPT-NeoX-20B, DeepSeek-V2, Llama 4 |
| Positions 0, 1, 2, … as integers | Rescaled at extension time (PI, NTK, YaRN) and fine-tuned briefly | PI, YaRN |
| One position index per token | Three for images and video (time, height, width) | Qwen2-VL |
| Interleaved pairs (x1, x2), (x3, x4) | Commonly "rotate half", pairing i with i + d/2: the same rotation on a permuted layout | Eq. 34 against Hugging Face's rotate_half |
| Survived unchanged: the rotation itself, applied to q and k only, in every attention layer that has positions; the geometric spectrum 10000−2i/d in form; zero parameters; keys rotated once, at cache time. | ||
Every link opens in a new tab. Reading time of the resources below: 4h 30m.
Neurocomputing 2024 (arXiv preprint 2021), the paper itself (v5, the version this page links section by section); the HTML version has the anchors this page links to. abstract page, PDF.
(45 min)
the authors' code and Chinese checkpoints (repo, about 15 minutes for the README).
(15 min)
EleutherAI (Biderman, Black, Foster, Gao, Hallahan, He, Wang, Wang): the canonical English explainer; complex-number view, derivation, runnable code, and the early adoption story (GPT-NeoX, GPT-J).
(30 min)
Jianlin Su (first author), kexue.fm: the first author's original blog derivation, which predates and is more readable than the paper (Chinese).
(30 min)
Christopher Fleetwood, Hugging Face: rederives RoPE step by step from desiderata; the best intuition builder for why each design choice is forced.
(35 min)
labml.ai: line-by-line PyTorch of the efficient elementwise form.
(25 min)
Hugging Face Transformers: the model as integrated in Transformers, with the released checkpoints (docs).
(10 min)
Barbero, Vitvitskyi, Perivolaropoulos, Pascanu, Veličković (2024): argues the long-term decay is not why RoPE works: for Gaussian queries and keys the expected score does not decay at all; Gemma 7B uses the highest frequencies for positional heads and the lowest as semantic channels.
(40 min)
Press, Smith, Lewis (2021): the paper that measured how sinusoidal and rotary encodings break when tested beyond the training length; the question this page's toy asks.
(40 min)
2017: the additive sinusoidal encoding whose frequency spectrum RoPE reuses multiplicatively.
2018: the pretraining baseline RoFormer swaps its absolute position embedding out of; its GLUE test-server row is the one RoFormer's Table 2 quotes.
2024: RoPE at base 500,000 plus staged long-context extension; the mainstream deployment pattern.
2024: MLA's decoupled RoPE keys, the trick that reconciles RoPE with latent KV compression.
2024: a representative RoPE-based open-weight architecture.
2020: learned absolute position embeddings on image patches; later vision models moved to 2D RoPE.
positional encodings, long-context extension.
under Topic: llm-architecture, the owner of positional encodings: the one-pair RoPE dial from zero (shift both positions), the base and its variants from real configs, and every context-extension method with its YaRN bands per model config; this page does not repeat them.
which released model chose which positional encoding, among its other architectural deltas.
This page is one row of the Papers database; its properties (Paper, Takeaway, Topics, Year) live there.