Search

Search papers and lessons

RoFormer: Enhanced Transformer with Rotary Position Embedding

Jianlin Su, Yu Lu, Shengfeng Pan et al. · 2021

RoFormer encodes token position by rotating query and key vectors, so attention scores depend only on the distance between tokens, and it trains faster and reads long text better than BERT's position embeddings.

On this page

  • Colour = topic mix
  • Architectures
  • Calculus
  • Linear algebra
  • Probability
  • Neural network basics
  • Discrete math
  • Sign in to see your progress

TL;DR

Transformers do not know word order on their own, so the usual fix is to add a position vector to each token embedding. RoFormer takes a different route. It rotates each query and key vector by an angle that grows with the token's position. The dot product between two rotated vectors then depends only on the distance between the tokens, so relative position is built into attention itself.

On the paper's experiments this gives faster pre-training convergence than BERT's learned absolute position embeddings, a small translation gain, and better results on long Chinese documents. The gains on GLUE are mixed.

Where you'll see it: in the attention layers of many open large language models, including the LLaMA family, which use rotary embeddings in place of absolute position embeddings.

The problem

Self-attention compares every token with every other token, but the comparison itself does not look at order. Two sentences with the same words in a different order produce the same set of attention scores unless position is injected somewhere. Before this paper the standard options were:

  • Absolute embeddings. A position vector, either fixed sinusoids or learned, is added to the token embedding before attention. BERT uses learned absolute embeddings. The model must learn a separate vector for every position it sees, so it struggles with lengths it was not trained on.
  • Relative embeddings. Position information is added inside attention, typically as a bias or as extra terms in the score. This captures distance directly, but it changes the attention formula and often adds parameters or extra computation.

The authors also point out a structural issue. Most relative schemes add position to the token representation before the query and key projections. The authors argue this makes them incompatible with linear attention, which needs the inner product to factor in a particular way. The paper wants a method that encodes relative position with no added parameters, keeps the score a function of the distance, and still works with linear attention.

Key idea

Put position into the query and key by rotating them. Rotation is a linear map that preserves length, and the inner product of two rotated vectors depends only on the difference of their rotation angles. If the angle for position mm is mθm\theta, then the comparison between positions mm and nn sees the angle (m−n)θ(m-n)\theta, and the absolute positions drop out.

flowchart LR
    X[token embedding x_m] --> WQ[W_q projection]
    WQ --> ROT1[rotate by m theta]
    ROT1 --> Q[rotated query]
    X2[token embedding x_n] --> WK[W_k projection]
    WK --> ROT2[rotate by n theta]
    ROT2 --> K[rotated key]
    Q --> DOT[dot product]
    K --> DOT
    DOT --> SCORE[score depends on m minus n]

A small example shows this. Take two-dimensional unit vectors, both pointing along the first axis, and use angle step θ=0.5\theta = 0.5 radians. Rotating the query by 3θ=1.53\theta = 1.5 and the key by 1θ=0.51\theta = 0.5, the score is cos⁡(1.5−0.5)=cos⁡(1.0)≈0.5403\cos(1.5 - 0.5) = \cos(1.0) \approx 0.5403. Shift both positions by 10, so they become 13 and 11, and the score is cos⁡(6.5−5.5)=cos⁡(1.0)≈0.5403\cos(6.5 - 5.5) = \cos(1.0) \approx 0.5403 again. The gap is 2 in both cases, so the score is the same.

The method

Formulation

The goal is an inner product of the form

⟨fq(xm,m),fk(xn,n)⟩=g(xm,xn,m−n)\langle f_q(\mathbf{x}_m, m), f_k(\mathbf{x}_n, n) \rangle = g(\mathbf{x}_m, \mathbf{x}_n, m-n)

where xm\mathbf{x}_m is the token embedding at position mm, and fqf_q and fkf_k produce the query and key. The right side depends on the two embeddings and only on their relative offset m−nm-n.

Two dimensions

For d=2d = 2, the paper writes the query and key as complex numbers. With Wq\mathbf{W}_q and Wk\mathbf{W}_k the usual projections,

f{q,k}(xm,m)=(cos⁡mθ−sin⁡mθsin⁡mθcos⁡mθ)W{q,k}xmf_{\{q,k\}}(\mathbf{x}_m, m) = \begin{pmatrix} \cos m\theta & -\sin m\theta \\ \sin m\theta & \cos m\theta \end{pmatrix} \mathbf{W}_{\{q,k\}} \mathbf{x}_m

Multiplying the projected embedding by the rotation matrix for position mm is the entire encoding step.

General dimension

For even dd, split the vector into d/2d/2 pairs of coordinates and rotate each pair with its own frequency. The block-diagonal rotation matrix is RΘ,md\mathbf{R}_{\Theta,m}^{d}, with

θi=10000−2(i−1)/d,i=1,…,d/2\theta_i = 10000^{-2(i-1)/d}, \qquad i = 1, \ldots, d/2

The attention score becomes

qm⊤kn=(RΘ,mdWqxm)⊤(RΘ,ndWkxn)=xm⊤Wq⊤RΘ,n−mdWkxn\mathbf{q}_m^{\top}\mathbf{k}_n = (\mathbf{R}_{\Theta,m}^{d}\mathbf{W}_q\mathbf{x}_m)^{\top}(\mathbf{R}_{\Theta,n}^{d}\mathbf{W}_k\mathbf{x}_n) = \mathbf{x}_m^{\top}\mathbf{W}_q^{\top}\mathbf{R}_{\Theta,n-m}^{d}\mathbf{W}_k\mathbf{x}_n

using RΘ,n−md=(RΘ,md)⊤RΘ,nd\mathbf{R}_{\Theta,n-m}^{d} = (\mathbf{R}_{\Theta,m}^{d})^{\top}\mathbf{R}_{\Theta,n}^{d}. The matrix is orthogonal, so it keeps norms unchanged, and it adds no learned parameters.

Each pair of coordinates behaves like a complex number. The inner product becomes

Re⁡[∑iq[2i:2i+1]k[2i:2i+1]∗ei(m−n)θi]\operatorname{Re}\left[\sum_{i} \mathbf{q}_{[2i:2i+1]}\mathbf{k}_{[2i:2i+1]}^{*} e^{\mathrm{i}(m-n)\theta_i}\right]

which is how the paper shows that only m−nm-n survives.

Efficient form

The full matrix is sparse, so the paper gives a cheaper form. Write x\mathbf{x} as pairs and compute the rotation as elementwise products with cosine and sine vectors, plus a pair-swapped copy with a sign flip. This costs O(d)O(d) per position instead of a dense matrix product.

Long-term decay

The paper shows that the average magnitude of the partial sums that make up the score decreases as the distance m−nm-n grows, under the frequency choice θi=10000−2(i−1)/d\theta_i = 10000^{-2(i-1)/d}. (Section 3.3 and Section 3.4.3 write the exponent as −2i/d-2i/d instead, while Section 3.2.2 uses −2(i−1)/d-2(i-1)/d. These differ only in how the index is offset; the paper does not remark on it.) The decay is shown numerically in Figure 2, not proved in closed form. The intuition is that tokens far apart should have weaker links, and the bound shows that RoPE has this property. The argument is a bound on the size of the sum, not an exact formula for the score.

Linear attention

Standard attention uses exp⁡(q⊤k/d)\exp(\mathbf{q}^{\top}\mathbf{k}/\sqrt{d}) as the similarity, which needs all pairs and costs quadratic time in sequence length. Linear attention replaces the similarity with a product of feature maps, ϕ(q)⊤φ(k)\phi(\mathbf{q})^{\top}\varphi(\mathbf{k}), so the sums can be reordered and computed in linear time. An additive position term does not fit this form cleanly. RoPE does, because the rotation can be applied to the feature-mapped query and key directly, and it keeps the norm. The paper keeps the denominator unchanged, which means the weights are not strictly normalised, a point the authors acknowledge.

Results

Machine translation

On WMT 2014 English to German, the paper trains a standard Transformer base and a RoFormer under the same settings.

ModelBLEU
Transformer base (Vaswani et al.)27.3
RoFormer27.5

The gain is 0.2 BLEU from one comparison, with no variance reported. Treat it as "no worse, slightly better" rather than a clear win.

Pre-training against BERT

The paper says it replaces the sinusoidal position encoding of its BERT baseline (bert-base-uncased) with RoPE. That description does not match BERT itself, which uses learned absolute position embeddings, as the Problem section above says; the comparison is in any case RoPE against BERT's absolute encoding. Both models are pre-trained on BookCorpus and Wikipedia, with batch size 64 and length 512 for 100,000 steps, and the metric is training masked language modelling loss. The text reports that RoFormer converges faster than BERT. The exact curves are only in Figure 3, not in a table.

Performer with RoPE

The paper also adds RoPE to a 12-layer character-level Performer (linear attention) and trains on Enwik8 with batch size 128 and length 1024. The text reports faster convergence and lower training loss than the same model without RoPE (right plot of Figure 3). Again this is a loss curve, not a table, and it is the only experiment that exercises the linear-attention claim.

GLUE fine-tuning

TaskBERTRoFormer
MRPC (F1)88.989.5
SST-2 (acc)93.590.7
QNLI (acc)90.588.0
STS-B (Spearman)85.887.0
QQP (F1)71.286.4
MNLI (m/mm)84.6/83.480.2/79.8

RoFormer wins on three of the six tasks, and the QQP gain is large. It is clearly behind on SST-2, QNLI and MNLI. The paper calls the three wins "significant" without a significance test, so read the results as encouraging rather than settled.

Long Chinese documents

On CAIL2019 similar case matching, where many inputs exceed 512 characters, the paper compares Chinese BERT, WoBERT and RoFormer, each pre-trained on the same data according to the text, at a 512-character cut-off, and RoFormer additionally at 1024. Accuracy is in percent.

ModelValidationTest
BERT, 51264.13%67.77%
WoBERT, 51264.07%68.10%
RoFormer, 51264.13%68.29%
RoFormer, 102466.07%69.79%

The text says RoFormer at 1024 beats WoBERT by an absolute 1.5%. The table disagrees with the text: against WoBERT-512 the test column gives 69.79−68.10=1.6969.79 - 68.10 = 1.69 points and the validation column gives 66.07−64.07=2.0066.07 - 64.07 = 2.00 points. The table is the primary data, so quote 1.7 (test) rather than 1.5, and note that the comparison also changes the cut-off length from 512 to 1024, not only the model. The qualitative point, that RoFormer improves when it is allowed longer input, is the one the table supports.

Worked example: comparing scores for two pairs

Use the 2D setup with θ=0.5\theta = 0.5. The score for query at position 5 and key at position 2 has gap 3, so the angle is 3×0.5=1.53 \times 0.5 = 1.5 radians. A pair at positions 9 and 6 also has gap 3. Both scores are cos⁡(1.5)=0.0707\cos(1.5) = 0.0707 for unit vectors that point the same way. A pair at positions 9 and 2 has gap 7, so its angle is 3.53.5 radians, and cos⁡(3.5)=−0.9365\cos(3.5) = -0.9365. A single frequency like this only oscillates with the gap; it does not decay. The decay the paper describes comes from summing many frequencies θi\theta_i that spread out over a wide range, so their contributions drift out of phase as the gap grows. The paper's bound is on that sum across all pairs of coordinates, and it is shown in Figure 2 rather than as a closed formula.

Why it mattered

RoPE became one of the standard position encodings for decoder language models. Its appeal is that it adds no parameters, it is applied inside attention, and the paper claims flexibility in sequence length (its evidence is the Chinese long-text result, where the authors admit they have no faithful explanation). Models using RoPE still degrade when run well past their training length, which later long-context extension methods address by rescaling the same rotation frequencies. Later open model families adopted it.

The paper also set a template: state a property you want (relative dependence, decay, compatibility with linear attention), then derive a method that has it. The derivation is short, and most of the value is in the framing. The experiments are modest by current standards, with a single translation run, one BERT-scale pre-training comparison and a small Chinese task. The authors state the main limitation themselves: they do not fully explain why it converges faster, and their theory is about the score's form rather than its training dynamics.

Reading guide

Read in this order. The lines name the prerequisites that matter for each part of the paper.

  1. Section 1 (introduction). Needs Transformer and Positional Encoding. The contrast between additive position and relative position is the main idea.
  2. Section 2.1 (preliminary). Needs Attention Mechanism and Softmax. The score qm⊤kn\mathbf{q}_m^{\top}\mathbf{k}_n is defined here.
  3. Section 2.2 and 2.3 (absolute and relative position embeddings). Needs Positional Encoding and Word Embedding. These are the baselines the paper argues against.
  4. Section 3.2 (rotary position embedding). Needs Rotary Position Embedding for the intuition, then the 2D case, then the general form. This section is the method.
  5. Section 3.3 and 3.4 (properties and derivation). Needs basic complex numbers and orthogonal matrices. Section 3.4.3 is the decay argument.
  6. Section 4.1 (translation). Needs Transformer for the baseline and Subword Tokenization for the input.
  7. Section 4.2 and 4.3 (BERT pre-training and GLUE). Needs BERT: Pre-training of Deep Bidirectional Transformers and Masked Language Modeling.
  8. Section 4.4 (Performer with RoPE). Needs Transformer and a rough idea of linear attention from Section 3.3.
  9. Section 4.5 (Chinese long text). No further prerequisites beyond the above.

Check yourself

QuestionWhy does a rotation-based score depend only on the gap between two positions, not on the absolute positions?Show answer
The score involves the product of a rotation by mθm\theta on the query and a rotation by nθn\theta on the key. Since (Rm)⊤Rn=Rn−m(\mathbf{R}_m)^{\top}\mathbf{R}_n = \mathbf{R}_{n-m}, the two absolute angles combine into the single relative angle (n−m)θ(n-m)\theta. The absolute angles cancel, so shifting both positions by the same amount leaves the score unchanged.
QuestionWith d = 2 and theta = 0.5, what is the score for positions 4 and 1, for unit vectors pointing the same way?Show answer
The gap is 3, so the angle is 3×0.5=1.53 \times 0.5 = 1.5 radians. The score is cos⁡(1.5)≈0.0707\cos(1.5) \approx 0.0707. The key point is that the answer depends only on the gap 3, so positions 10 and 7 give the same score.
QuestionWhy is it harder to combine an additive position encoding with linear attention than RoPE?Show answer
Linear attention needs the similarity to split into a product of a function of the query and a function of the key, so that sums can be reordered. Adding a position vector to the token embedding before projection mixes position into the query and key in a way that does not factor cleanly with the feature maps. RoPE applies a norm-preserving rotation after the feature map, so the factorisation still holds.
QuestionOn the GLUE results, RoFormer beats BERT on three tasks. Name them, and explain why the paper's result is weaker evidence than the summary suggests.Show answer
RoFormer wins on MRPC, STS-B and QQP. It loses on SST-2, QNLI and MNLI. The paper says the three wins are significant but reports no significance test or variance, and the losses are substantial, so the overall picture is mixed rather than a clear improvement.

Sources

Read the full paper

Jianlin Su, Yu Lu, Shengfeng Pan et al., 2021. arXiv:2104.09864