Paper notes

RoFormer: Writing Position into the Attention Dot Product with Rotations

RoFormer's rotary position embedding (RoPE) rotates queries and keys by position, so their dot product depends only on relative position, with no extra parameters. It later became standard in open LLMs such as LLaMA. We check its formulas, its mixed small-scale results and its properties in code.

Published Updated 10 min read

On this page
  1. Why this paper matters
  2. The method: 2D rotations and complex numbers
  3. Three things to check in code
  4. Experiments: small scale, mixed results
  5. Limits and cautions
  6. What to take away
  7. Further reading
  8. FAQ

Why this paper matters

Self-attention is blind to order, so a Transformer needs to be told who comes first. The original paper added sinusoidal vectors to the embeddings, BERT used learned absolute position vectors, and another family added relative-position biases to the attention scores. In April 2021 Jianlin Su and colleagues at Zhuiyi Technology posted rotary position embedding (RoPE) and the RoFormer model built on it.

The idea in one sentence: encode each position as a rotation, rotate the query and the key, and the dot product depends only on the position difference. It has no extra parameters and does not touch the token embeddings, so it drops easily into existing attention code. RoPE has since become the default in large models: the LLaMA paper says it removes absolute position embeddings and adds RoPE at every layer, and the Llama 2, Llama 3 and Qwen3 technical reports also use RoPE. The paper itself, though, is a small-scale proof of feasibility that did not foresee that adoption, and as we will see its experimental results are mixed.

The method: 2D rotations and complex numbers

Start in two dimensions. Treat the query and key at positions mm and nn (already multiplied by WqW_q and WkW_k) as complex numbers; the paper encodes position by multiplying with a unit complex number:

fq(xm,m)=(Wqxm) eimθ,fk(xn,n)=(Wkxn) einθf_q(x_m, m) = (W_q x_m)\, e^{i m\theta},\qquad f_k(x_n, n) = (W_k x_n)\, e^{i n\theta}

Their inner product is the real part of

g(xm,xn,m−n)=Re⁡[(Wqxm)(Wkxn)∗ ei(m−n)θ]g(x_m, x_n, m-n) = \operatorname{Re}\big[(W_q x_m)(W_k x_n)^{*}\, e^{i(m-n)\theta}\big]

and depends on m−nm-n only. Section 3.4.1 goes the other way: it requires the inner product to depend only on m−nm-n and to reduce to the plain vectors at position 0, and in two dimensions the solution is exactly this multiplication by eimθe^{im\theta}.

For dd dimensions (dd even), pair up adjacent coordinates into d/2d/2 pairs; pair ii is rotated by mθim\theta_i at position mm, with θi=10000−2(i−1)/d\theta_i = 10000^{-2(i-1)/d}. Writing the rotations as a block-diagonal orthogonal matrix RΘ,mdR^d_{\Theta,m}, the attention score is Equation 16 of the paper:

qm⊤kn=xm⊤Wq⊤RΘ, n−md Wkxn,RΘ, n−md=(RΘ,md)⊤RΘ,ndq_m^{\top} k_n = x_m^{\top} W_q^{\top} R^d_{\Theta,\,n-m}\, W_k x_n,\qquad R^d_{\Theta,\,n-m}=(R^d_{\Theta,m})^{\top}R^d_{\Theta,n}

Implementations never multiply by this sparse matrix; they apply cos⁡\cos and sin⁡\sin element-wise: each pair (x2i−1,x2i)(x_{2i-1}, x_{2i}) becomes (x2i−1cos⁡mθi−x2isin⁡mθi, x2icos⁡mθi+x2i−1sin⁡mθi)(x_{2i-1}\cos m\theta_i - x_{2i}\sin m\theta_i,\ x_{2i}\cos m\theta_i + x_{2i-1}\sin m\theta_i). The paper stresses that this is multiplicative, unlike the earlier additive schemes: position is not added in but emerges from the product of rotation matrices inside the dot product.

The paper lists three properties:

PropertyWhat it means
Flexible sequence lengthThe rotation is defined at any position, unlike a learned table with a fixed maximum
Decay with distanceWith θi=10000−2i/d\theta_i=10000^{-2i/d} an upper bound on the inner product shrinks as relative distance grows (Section 3.4.3, Figure 2)
Compatible with linear attentionRotations preserve norms, so they can be applied after the non-negative feature maps of linear attention, leaving the denominator unrotated (Equation 19)

Three things to check in code

The NumPy code below implements RoPE and verifies (1) that the dot product depends only on the position difference, (2) the decay quantity plotted in the paper’s Figure 2, 1d/2∑j∣Sj∣\tfrac{1}{d/2}\sum_j |S_j| for d=256d=256 with Sj=∑i<jei(m−n)θiS_j=\sum_{i<j}e^{i(m-n)\theta_i}, and (3) for q=kq=k, the average similarity between a vector and a copy of itself rotated by Δ\Delta positions:

import numpy as np

d, base = 256, 10000.0
theta = base ** (-2 * np.arange(d // 2) / d)  # theta_i = 10000^(-2i/d)


def rotate(x, pos):
    """Rotate every adjacent pair of x by pos * theta_i."""
    c, s = np.cos(pos * theta), np.sin(pos * theta)
    y = np.empty_like(x)
    y[0::2] = x[0::2] * c - x[1::2] * s
    y[1::2] = x[0::2] * s + x[1::2] * c
    return y


rng = np.random.default_rng(0)
q, k = rng.standard_normal(d), rng.standard_normal(d)
# 1) the score depends only on m-n (three absolute positions, m-n is 7)
for m, n in [(10, 3), (107, 100), (5000, 4993)]:
    print(m - n, round(float(rotate(q, m) @ rotate(k, n)), 6))


# 2) the quantity in the paper's Figure 2: mean_j |S_j|
def bound(rel):
    S = np.cumsum(np.exp(1j * rel * theta))
    return np.abs(S).mean()


for rel in [0, 1, 10, 50, 100, 250]:
    print(rel, round(bound(rel), 2))

# 3) q = k: average similarity of a vector with itself rel positions away
for rel in [0, 1, 4, 16, 64, 256, 1024, 8192]:
    print(rel, round(float(np.cos(rel * theta).mean()), 3))
print("wavelengths:", np.round(2 * np.pi / theta[[0, -1]]).astype(int))

Output:

7 8.324909
7 8.324909
7 8.324909
0 64.5
1 62.71
10 36.22
50 22.63
100 18.62
250 12.79
0 1.0
1 0.972
4 0.765
16 0.627
64 0.48
256 0.346
1024 0.176
8192 0.069
wavelengths: [    6 58470]

Three observations:

  • The relative-position property holds. Three different absolute positions with the same difference, 7, give exactly the same score (8.324909).
  • The quantity in Figure 2 does fall with distance, from 64.5 at distance 0 to 12.79 at distance 250. But it is a factor in an upper bound of the inner product, not a measured attention decay: real qq and kk are learned, and the paper’s limitations section admits there is no faithful explanation of why performance improves.
  • Rotation frequencies span a huge range. In the third block the average similarity for q=kq=k falls slowly with distance, while the fastest pair of dimensions completes a turn every 6 tokens and the slowest has a wavelength of about 58,470 tokens. High-frequency dimensions separate neighbours; low-frequency ones barely rotate and can keep long-range semantic links. This is also why later long-context methods retune individual frequencies; see the YaRN note.

Experiments: small scale, mixed results

All experiments ran on two servers with four V100 GPUs each, far below the scale of later models.

ExperimentSetupResult
Machine translationWMT 2014 English-German, about 4.5M sentence pairs, Transformer-baseBLEU 27.3 to 27.5 (Table 1)
BERT pretrainingReplace BERT-base’s sinusoidal encoding with RoPE; BookCorpus + WikipediaThe paper says MLM loss converges faster (Figure 3 left; curve only, no table)
GLUE fine-tuningCompared with BERT, 3 epochsSee below: three better, three worse
Performer + RoPECharacter-level language modelling on Enwik8, 12 layersFaster, lower loss (curve only)
Chinese long textCAIL2019-SCM case matching, about 34GB of Chinese pretraining dataSee below

GLUE results (Table 2):

ModelMRPCSST-2QNLISTS-BQQPMNLI (m/mm)
BERT88.993.590.585.871.284.6/83.4
RoFormer89.590.788.087.086.480.2/79.8

The paper says RoFormer significantly outperforms BERT on three of six datasets, and the table equally shows it is worse on SST-2, QNLI and MNLI, by up to about 4 points. More important is the protocol. The BERT row matches, entry by entry, the test-set numbers for BERT-BASE in Table 1 of the BERT paper (whose caption reads “GLUE Test results, scored by the evaluation server”), while the RoFormer row is, according to Section 4.3.2, the best average on the validation set after the authors’ own fine-tuning. The two rows are not on the same footing, so the 86.4 versus 71.2 gap on QQP cannot be credited to position encoding. GLUE should not be read as “RoPE improves understanding”.

Chinese long-text results (Table 5, accuracy %):

Model (cut-off length)ValidationTest
BERT-51264.1367.77
WoBERT-51264.0768.10
RoFormer-51264.1368.29
RoFormer-102466.0769.79

Raising the cut-off from 512 to 1024 improves RoFormer by 1.50 points on the test set (69.79 versus 68.29). The text says RoFormer beats WoBERT by an absolute 1.5% at 1024, but the table has no WoBERT-1024 entry; the 1.5 points is RoFormer’s own 1024-versus-512 difference. The dataset has only about 9,000 triplets split 6:2:2, so the test set is under 2,000 examples, and no confidence interval is given.

Limits and cautions

  • Limitations the authors list. The paper says that although relative position is formalised as rotations in 2D subspaces, there is no thorough explanation of why RoPE converges faster than other schemes; its long-term decay is similar to existing encodings, and the advantage on long texts has no “faithful explanation”.
  • “Long-term decay” is a bound, not a law. Item 3 of the code is just the average case for q=kq=k; real attention heads can look far away through the low-frequency dimensions.
  • Small experiments with inconsistent comparisons. Pretraining is BERT-base scale; the GLUE comparison puts test-set numbers against validation-set numbers (see above); the translation and Enwik8 experiments give one number or one curve with no variance over runs.
  • Behaviour beyond the training length is not in this paper. It only shows the benefit of a longer cut-off (1024) and does not test unseen lengths. Extrapolation is handled by later work; the wiki pages on positional encoding and long context go into it.
  • Incompatible with low-rank KV compression. The DeepSeek-V2 paper points out that RoPE is position-sensitive for both queries and keys, so applying it to compressed keys would stop the up-projection from being absorbed into the query projection; it therefore applies RoPE to a small separate set of dimensions (decoupled RoPE). That came later, but it shows that multiplying onto q and k has an engineering price.

What to take away

  1. Position encoding can be multiplicative, not just additive. Rotation makes the dot product depend only on the position difference; that is the paper’s core idea.
  2. The frequency spread decides what distances can be told apart. θi\theta_i runs from fast to slow, which is the starting point for every later RoPE scaling or extrapolation method.
  3. There are no extra parameters. That lets it replace an existing position encoding without architectural changes, and it is a practical reason for its wide adoption.
  4. The original experiments only show it is feasible. The reasons large models adopted it come from later practice, not from this paper’s GLUE table.

Further reading

FAQ

How does RoPE differ from absolute and relative position encodings?
Absolute encodings add a position vector to the token embedding, and relative encodings add a distance-dependent bias to the attention scores. RoPE does neither. It rotates each head's query and key by an angle that depends on their own positions, so the dot product of the rotated vectors automatically depends only on the position difference. It carries absolute position (in the rotation angle) and relative position (in the dot product), is multiplicative, and has no learnable parameters.
Why does RoPE act on queries and keys but not on values?
Position only has to show up in "who attends to whom", that is, in the attention scores. Values are the content being averaged and do not need to carry position. Equation 16 of the paper multiplies only q and k by rotation matrices; the transpose of one rotation times the other becomes a rotation by the position difference, and the values are left untouched.
Does RoPE let a model work beyond its training length?
The paper lists "flexibility of sequence length" as a property, but that only means the formula is defined at every position; it does not guarantee good behaviour at lengths the model never saw. The wiki pages on positional encoding and long context explain that naive extrapolation usually degrades and that scaling methods such as NTK and YaRN, or further training, are needed; see the YaRN note.
Where does the 10000 in RoPE come from?
The paper reuses the frequency schedule of the original Transformer's sinusoidal encoding, $\theta_i=10000^{-2i/d}$, so that rotation speeds spread from fast to slow across dimension pairs. Later models raise this base for longer contexts - the Llama 3 paper uses 500,000 and the Qwen3 report raises it from 10,000 to 1,000,000 - and the YaRN note covers the long-context methods in detail.