Skip to content

RoFormer: Enhanced Transformer with Rotary Position Embedding

Skip →GPT-3 (few-shot learners)
main track #4corefundamentalpaperrubric 11/122021 · ~50 min

Jianlin Su, Yu Lu, Shengfeng Pan, … Yunfeng Liu

Status

TL;DR. RoPE injects position by rotating the query and key vectors instead of adding a position vector to the input. Each 2-D slice of qq and kk is rotated by an angle proportional to the token’s position, with a different frequency per slice. Because rotations compose, the dot product qm⊤knq_m^\top k_n depends on the content and on the offset m−nm-n only. Raschka’s architecture survey describes the move from absolute embeddings to RoPE as the norm in today’s open LLMs.

Why it matters now. Long-context retrieval, RAG over long documents and agent traces all push models beyond their training length. When that fails, the failure usually shows up in RoPE’s frequencies, and fixes such as position interpolation and YaRN are edits to the formula on this page. Understanding RoPE is also needed to read modern architecture papers, which often modify it. Raschka’s comparison, for example, lists RoPE on only half the head dimension, layers with no position encoding (NoPE), and a base of 10,000,000.

Goal (Eq. 11). Find encodings fq(xm,m)f_q(x_m,m) and fk(xn,n)f_k(x_n,n) whose inner product depends only on the two contents and the offset:

⟨fq(xm,m), fk(xn,n)⟩=g(xm,xn,m−n).\langle f_q(x_m,m),\,f_k(x_n,n)\rangle = g(x_m,x_n,m-n).

2-D solution. Treat a 2-D vector as a complex number and multiply by eimθe^{im\theta}. In real form this is a rotation:

f{q,k}(xm,m)=(cos⁡mθ−sin⁡mθsin⁡mθcos⁡mθ)W{q,k} xm.f_{\{q,k\}}(x_m,m)=\begin{pmatrix}\cos m\theta & -\sin m\theta\\ \sin m\theta & \cos m\theta\end{pmatrix}W_{\{q,k\}}\,x_m .

General form (Eq. 15). Split the dd dimensions into d/2d/2 pairs. Rotate pair ii by mθim\theta_i, with

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

The full map RΘ,mdR^d_{\Theta,m} is block-diagonal with these 2×22\times 2 rotations on the diagonal. It is orthogonal, so it does not change vector norms.

Relative-position property (Eq. 16). Rotation matrices satisfy Rm⊤Rn=Rn−mR_m^\top R_n = R_{n-m}. Therefore

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

The absolute positions mm and nn cancel. Only the offset is left, and it enters through a rotation rather than an added bias. In code, the rotation is applied element-wise as x⊗cos⁡+rotate_half⁡(x)⊗sin⁡x\otimes\cos + \operatorname{rotate\_half}(x)\otimes\sin (Eq. 34), so the sparse matrix is never formed.

Long-term decay (§3.4.3). Using Abel summation, the paper bounds the magnitude of the logit by a term that tends to shrink as ∣m−n∣|m-n| grows. This gives a mild prior that far-apart tokens interact less. It is an upper bound, not a guarantee (see the questions).

Linear attention (Eq. 19). RoPE can be combined with kernelised linear attention (for example the Performer) by rotating ϕ(q)\phi(q) and ϕ(k)\phi(k) in the numerator only. The denominator is left unchanged to avoid the risk of dividing by zero.

Rotary position embedding: rotate each 2-D slice of q and k by an angle proportional to position, so their dot product depends only on the offset Left: in one 2-D plane, a query at position m is rotated by m theta and a key at position n by n theta. Their dot product depends only on the angle between them, (n minus m) theta. Shifting both positions by the same amount rotates both vectors together and leaves that angle unchanged. Right: a d-dimensional query is split into d over 2 pairs. Pair i rotates with frequency theta i equal to 10000 to the power minus 2 (i minus 1) over d. The first pair turns once every 6.3 tokens, the last pair of a 128-dimensional head needs about 54 thousand tokens for one turn. The full rotation is a block-diagonal matrix of 2 by 2 rotations. One 2-D slice: only the offset survives q rotated by mθ k rotated by nθ (n−m)θ q_mᵀ k_n = (R_m W_q x_m)ᵀ (R_n W_k x_n) = x_mᵀ W_qᵀ R_{n−m} W_k x_n since R_mᵀ R_n = R_{n−m}: rotations compose shift m and n by +100: same score d dimensions = d/2 rotating pairs x₁ x₂ x₃ x₄ … x_{d−1} x_d pair i rotates by m·θᵢ, θᵢ = 10000^(−2(i−1)/d) period of one turn, head dim d = 128 pair 12π ≈ 6.3 tokens pair 16≈ 54 tokens pair 32≈ 540 tokens pair 48≈ 5,400 tokens pair 64≈ 54k (bar length on a log scale) R_m = blockdiag( R(mθ₁), …, R(mθ_{d/2}) ) applied to q and k only, never to v
Original sketch. Left: in each 2-D slice the score depends only on the angle (n−m)θ between the rotated query and key. Right: the d/2 slices rotate at geometrically spaced frequencies, from a period of about 6 tokens to about 54k tokens for a 128-dimensional head.
  • Translation (§4.1). On WMT14 EN–DE, swapping in RoPE moves the Transformer-base from 27.3 to 27.5 BLEU.
  • Pretraining (§4.2, Fig. 3). Replacing BERT’s sinusoidal encoding with RoPE gives faster convergence of the masked-LM loss. The paper reports curves, not final numbers.
  • GLUE (§4.3, Table 2). Mixed: better on MRPC, STS-B and QQP, worse on SST-2, QNLI and MNLI.
  • Linear attention (§4.4). With the Performer, RoPE also converges faster in language-model pretraining.
  • Long Chinese documents (§4.5, Table 5). On CAIL2019-SCM, RoFormer with 1024 tokens reaches 69.79 on test against 68.10 for WoBERT at 512, a gain of about 1.5 points that the authors attribute to handling longer text.
  • The paper admits it cannot explain why RoPE converges faster than other schemes, or why it does better on long texts.
  • Extrapolation is not studied. Behaviour beyond the training length depends on the slow frequencies, which motivated position interpolation and YaRN.
  • The base 10000 is a choice. Some recent models use much larger bases; Raschka’s comparison lists one with 10,000,000. How to set it for a target length is still mostly empirical.
  • Small and mixed evaluations. The experiments are modest in scale. RoPE’s dominance comes from later adoption at scale, not from this paper’s tables.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    Use d = 4, so θ₁ = 1 and θ₂ = 10000^(−2/4) = 0.01. Let the projected query and key both be (1, 0, 1, 0) before rotation. Compute the RoPE score q_mᵀk_n for (m, n) = (5, 8) and for (m, n) = (105, 108), and compare with the score at offset 0. Show the step that removes the absolute positions.

    What a strong answer covers
    • Each 2-D block contributes ⟨R(mθ)a, R(nθ)a⟩ = aᵀR((n−m)θ)a = cos((n−m)θ) for a = (1, 0), because R(mθ)ᵀR(nθ) = R((n−m)θ).
    • Offset 3 in both cases: cos(3) + cos(0.03) ≈ −0.990 + 0.9996 ≈ 0.010. The absolute positions 5 or 105 never appear.
    • Offset 0 gives cos 0 + cos 0 = 2.
    • The fast pair (θ = 1) has already wrapped around and turned negative after 3 tokens. The slow pair (θ = 0.01) still carries almost all the similarity. Different pairs act at different distance scales.
  2. Mechanism

    Why is RoPE multiplicative rather than additive? Expand the attention logit for additive absolute embeddings, (x_m + p_m)ᵀ W_qᵀ W_k (x_n + p_n), and explain which terms leak absolute position and how a rotation avoids them.

    What a strong answer covers
    • Additive expansion gives four terms: content–content, content–position, position–content and position–position. The two mixed terms depend on p_m and p_n separately, not only on m − n.
    • RoPE multiplies the projected vectors by an orthogonal R_m. The logit becomes x_mᵀW_qᵀ R_{n−m} W_k x_n, so position enters only through the offset (Eq. 16).
    • Because rotations preserve norms, RoPE changes angles, not lengths, of q and k. Content and position are mixed in a single bilinear form.
    • Values are not rotated, so the position signal shapes only who attends to whom, not what is copied.
  3. Mechanism

    With θ_i = 10000^(−2(i−1)/d) and a head dimension of 128, compute the period (in tokens) of the fastest and the slowest rotating pair. Use this to explain why a model trained on 4k-token sequences can fail on 32k-token inputs, and why later methods rescale the frequencies rather than the positions of every pair equally.

    What a strong answer covers
    • Fastest pair: θ₁ = 1, period 2π ≈ 6.3 tokens. Slowest pair: θ₆₄ = 10000^(−126/128) ≈ 1.15e−4, period ≈ 54,000 tokens.
    • In a 4k context the slow pairs only ever see a small fraction of a turn. At 32k their angles reach values never seen in training, so the attention logits are out of distribution.
    • Fast pairs have wrapped many times in training and see nothing new at long range. The problem is concentrated in the slow, low-frequency pairs.
    • This motivates interpolating or rescaling mainly the low-frequency pairs (the approach YaRN refines). The RoPE paper itself does not test extrapolation.
  4. Critique

    Section 3.4.3 proves a long-term decay property using Abel summation. State what the bound actually controls, why it does not guarantee that a trained model attends less to distant tokens, and how you would test the claim on a real RoPE model.

    What a strong answer covers
    • The bound shows that |Σᵢ h_i e^{i(m−n)θ_i}| is at most max|h_{i+1} − h_i| times Σ|S_i|, where S_i are partial sums of the complex exponentials. The partial-sum term decays on average with distance.
    • It is an upper bound for fixed h. A trained model can make h (the products of q and k components) large on the slow pairs and keep long-range scores high.
    • So the decay is a prior, not a constraint. Retrieval-style heads in long-context models do attend far away.
    • Test: on a RoPE LLM, measure average attention mass and logit magnitude as a function of distance per head, and compare with the bound computed from the actual q and k.
  5. What if…

    The paper's GLUE results (Table 2) are mixed: RoFormer beats BERT on MRPC, STS-B and QQP but loses on SST-2, QNLI and MNLI. Which confounds stop you from attributing either gain or loss to the position encoding, and what controlled ablation would settle it?

    What a strong answer covers
    • Reported numbers: RoFormer 89.5 vs 88.9 on MRPC, 87.0 vs 85.8 on STS-B, 86.4 vs 71.2 on QQP, but 90.7 vs 93.5 on SST-2, 88.0 vs 90.5 on QNLI, 80.2/79.8 vs 84.6/83.4 on MNLI.
    • The two models differ in more than the position scheme (pretraining data, steps and fine-tuning setup are not matched one-to-one), and GLUE tasks have high run-to-run variance.
    • The 15-point QQP gap is too large to be a plausible effect of position encoding alone, which suggests a setup difference.
    • Controlled ablation: same code, data, tokens and seeds, varying only absolute, relative-bias and rotary encodings, with several fine-tuning seeds per task.
  6. Design

    You maintain a RoPE-based embedding model trained on 512-token passages and need it to embed 8k-token documents for long-document retrieval. Lay out your options and the measurements that decide between them, given a budget of a few GPU-days.

    What a strong answer covers
    • Options: chunk and pool (no change to the model); scale positions down (interpolation) with a short fine-tune; rescale only low-frequency pairs (YaRN-style); or continue pretraining at longer length.
    • Chunking avoids out-of-range angles but loses cross-chunk context, which matters when relevance depends on distant parts of the document.
    • Interpolation compresses the fast pairs too, which can blur local word order. Frequency-aware scaling keeps them intact.
    • Measure retrieval quality as a function of where the relevant span sits in the document, short-passage quality (to catch regressions), and attention entropy at long range.

Done with this page?

Status