Skip to main content
issue 2026-08-09ML Math35 minNeurocomputing / arXiv 2021interactive

RoFormer: Enhanced Transformer with Rotary Position Embedding

This research paper explains how encoding absolute position with a rotation matrix gives self-attention an explicit relative-position dependency, length flexibility, and a natural long-range decay.

Rotary position embedding rotates queries and keys by token indexLeft: additive absolute position mixes a position cube into content. Center: RoPE rotates the query and key vectors by mθ and nθ. Right: the attention score depends on the relative angle (m−n)θ while values stay unrotated.ADD PEENTER · MIXxCONTENTpPOSITIONx+pADDITIVECONTENT + ABSRoPEROTATE Q · ROTATE K · RUNq× R_mk× R_nABSOLUTE INDEX → ANGLE⟨q′,k′⟩~ (m−n)θSCORELEAVE · RELATIVEαSOFTMAXvUNROTATEDVALUES PASS THROUGHROTARY PE — ABSOLUTE ROTATIONS · RELATIVE INNER PRODUCTθᵢ = 10000^(−2i/d) · LENGTH-FLEXIBLE · LONG-RANGE DECAY BIASRoPE rotate-then-score flowThree stacked cards: additive PE mixes content and position; RoPE rotates Q and K by token index; attention scores use the relative angle while values stay unrotated.ENTER · ROTATE · SCOREENTER ABSOLUTE INDEX madditive PE would mix x + p_mROTATE Q · Kq′ = R_m q · k′ = R_n keach even/odd pair is a 2-D planeRELATIVE SCORE⟨q′, k′⟩ depends on (m − n)θvalues stay unrotatedLEAVE · SOFTMAX → Σ α vposition routed scores, not valuesABSOLUTE ROTATION · RELATIVE ATTENTION

Transformers need to know where a token sits. Absolute sinusoidal embeddings add a position vector to each token; relative schemes try to make attention depend on the offset between tokens, but many of those tricks add position into the content stream in ways that break linear / kernelized attention.

RoPE’s punchline is geometric. Treat each even/odd pair of dimensions as a 2-D plane. At position mm, rotate the query (and key) by angle mθm\theta. Then the attention score between positions mm and nn depends on the relative angle (mn)θ(m-n)\theta — absolute indices on each side, relative structure in the product.

What this paper explains

Position information in PLMs is usually injected in one of three ways:

  1. Absolute embeddings (sinusoidal or learned) added to token embeddings.
  2. Relative biases or embeddings that modify attention logits using mnm-n.
  3. Hybrids that try to keep both.

Su et al. formulate a functional constraint: after position-aware transforms fq,fkf_q, f_k, the inner product fq(xm,m),fk(xn,n)\langle f_q(x_m, m), f_k(x_n, n)\rangle should be a function of the content and the relative offset mnm-n. They then exhibit a solution: multiply WqxmW_q x_m and WkxnW_k x_n by rotation matrices indexed by mm and nn.

The paper asks:

  1. Can relative position enter self-attention through a multiplicative (rotation) path instead of an additive one?
  2. Does that form keep sequence-length flexibility and a long-term decay intuition?
  3. Can the same idea attach to linear attention, where additive relative methods struggle?
Additive absolute PE versus rotary PELeft panel shows content and position vectors added before projection. Right panel shows query and key vectors rotated by angles mθ and nθ so the inner product depends on the relative offset.Additive absolutex_m + p_m → W_q, W_kx+pposition mixed into contentRotary (RoPE)R_m q · R_n kq @ mθk @ nθ
Additive PE stacks position onto content. RoPE leaves content projection alone and turns absolute indices into rotations of Q and K.

Prior limits

  • Additive absolute PE (Vaswani et al.) works, but position and content are mixed in the same vector before Wq,WkW_q, W_k. Relative structure is only implicit.
  • Relative position methods (Shaw et al., Transformer-XL, DeBERTa-style biases, etc.) often add position-specific terms into attention. The paper notes that adding position into the context representation can make those ideas awkward for linear self-attention.
  • Complex-space or other PE variants help empirically but still commonly follow the “add position to content” pattern the authors want to avoid.
  • Practitioners want length extrapolation and decaying influence with distance — properties that need to fall out of the formulation, not only from training data.

The mechanism

Constraint: relative in the product

Write queries and keys as position-aware maps of content xx. The authors require that the attention affinity depend on xmx_m, xnx_n, and mnm-n. In the 2-D case they solve this with complex multiplication (rotation):

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}

The product then involves ei(mn)θe^{i(m-n)\theta} — relative phase — while each side only needed its own absolute index.

Matrix view (same geometry)

Equivalently, with real 2-D vectors,

fq,k(xm,m)=(cosmθsinmθsinmθcosmθ)Wq,kxmf_{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

Rotating qq by mθm\theta and kk by nθn\theta leaves the inner product equal to rotating one vector by (mn)θ(m-n)\theta against the other.

General even dimension dd

Split Rd\mathbb{R}^d into d/2d/2 planes and apply a block-diagonal rotation:

f{q,k}(xm,m)=RΘ,mdW{q,k}xmf_{\{q,k\}}(x_m, m) = R^d_{\Theta,m}\, W_{\{q,k\}} x_m

with pairwise angles θi=100002i/d\theta_i = 10000^{-2i/d} (same base as the Transformer sinusoids). Implementation never materializes the huge matrix: rotate each (x2i,x2i+1)(x_{2i}, x_{2i+1}) pair in place.

Interactive

Rotate the query by position m

Fix a key at position n = 0. Slide the query index m. RoPE rotates q by mθ; the inner product depends on the relative angle (m − n)θ.

As m moves away from n, the relative angle grows and the demo cosine falls — the geometric intuition behind RoPE’s relative product.

Properties the paper highlights

  • Relative by construction — absolute rotations compose into an mnm-n dependency in attention.
  • Length flexibility — positions are angles; you can evaluate at indices not seen in training (with the usual caveats).
  • Long-term decay — with the θi\theta_i schedule, the expected contribution of distant pairs tends to fade as mn|m-n| grows (their §3.3 / §3.4.3 intuition).
  • Linear attention compatible — because position is a rotation of qq and kk, not an additive term glued onto the value pathway the way some relative methods need.
Block-diagonal RoPE across dimension pairsA wide vector is split into even/odd pairs. Each pair lives on its own 2-D plane and is rotated by m times a frequency θ_i, forming a block-diagonal rotation matrix.R_Θ,m^d — d/2 independent 2×2 rotationsplane 0(x_0, x_1)∠ m θ_0plane 1(x_2, x_3)∠ m θ_1plane 2(x_4, x_5)∠ m θ_2plane 3(x_6, x_7)∠ m θ_3
For even head size d, RoPE is block diagonal: rotate each consecutive pair by mθ_i with θ_i = 10000^(−2i/d). Implementations rotate in place — no giant dense matrix multiply.

Algorithm walkthrough

  1. Project tokens to qm=Wqxmq_m = W_q x_m, kn=Wkxnk_n = W_k x_n as usual.
  2. Choose even head dimension dd; set θi=100002i/d\theta_i = 10000^{-2i/d} for i=0,,d/21i = 0,\ldots,d/2-1.
  3. For each position index mm and each pair ii, rotate (qm,2i,qm,2i+1)(q_{m,2i}, q_{m,2i+1}) by mθim\theta_i (same for keys with nθin\theta_i).
  4. Compute attention with the rotated q,kq', k' — e.g. softmax(qk/d)v\mathrm{softmax}(q' k'^\top / \sqrt{d})\, v (values are typically not rotated in the standard RoPE recipe).
  5. Stack as in any Transformer; the paper’s RoFormer is “Transformer + RoPE” evaluated on MT, MLM-style pretraining, GLUE, and a Performer-style linear-attention check.

The opening visual shows additive PE as a vertical stack of content+position versus RoPE as a turn of the query/key arrows. The slider above lets you change mm and watch a 2-D pair rotate while the relative angle to a fixed key updates.

What to notice when reading

  • The derivation order: constraint on fq,fk\langle f_q, f_k\rangle first, rotation solution second — not “we tried a rotation and it worked.”
  • Values are left unrotated in the usual formulation; position enters the routing (scores), not the value vectors themselves.
  • The θi\theta_i schedule is doing real work for the decay story; it is not an arbitrary constant.
  • Their linear-attention experiment is about compatibility of the PE form, not a claim that Performer+RoPE is SOTA everywhere.

Results and evidence

Numbers below are from the paper’s reported tables (arXiv:2104.09864), not independent re-runs.

Machine translation (Table 1). On WMT 2014 English→German, under their fairseq setup (joint 37k BPE, Adam β=(0.9,0.98)\beta=(0.9,0.98), beam 4, length penalty 0.6):

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

Language modeling / downstream. They replace BERT’s sinusoidal PE with RoPE during MLM pretraining (BookCorpus + Wikipedia split) and fine-tune on GLUE; the narrative claim is that RoFormer consistently overcomes the sinusoidal baseline under their settings (see paper §4.2–4.3 for per-task scores — report from the PDF rather than inventing cells here).

Linear attention. §4.4 pairs RoPE with Performer-style linear attention to argue the multiplicative PE form still applies when softmax attention is replaced.

Chinese data. §4.5 adds further classification-style checks beyond the English GLUE suite.

Limitations

Compressed from the paper’s setting and from what it does not claim:

  • Empirical lifts vs strong absolute PE can be modest on short-sequence tasks (Table 1’s +0.2 BLEU).
  • Long-context extrapolation later became a whole research area (NTK-aware scales, YaRN, ALiBi comparisons, etc.); this paper supplies the mechanism and early evidence, not the final 2024–2026 length-extrapolation cookbook.
  • Most experiments are encoder or encoder–decoder style PLMs of their period; decoder-only LLM training recipes post-date the work.
  • Theoretical decay arguments are about the PE form’s inductive bias; they are not a guarantee for every downstream metric.

How to read the paper

  1. Abstract + §1 — relative-in-the-product goal vs additive PE.
  2. §3.1–3.2 — 2-D complex/rotation derivation, then block-diagonal RΘ,mdR^d_{\Theta,m}.
  3. §3.3 properties — length flexibility, decay, linear-attention hook.
  4. §4.1 Table 1 — WMT En→De sanity check.
  5. §4.2–4.4 — pretraining/GLUE + Performer experiment.
  6. §5 — claims to keep separate from later industrial RoPE folklore.

Knowledge check

What does RoPE rotate to inject position?

Why does rotating q at m and k at n make attention depend on relative position?

Which property do the authors emphasize for the θ_i = 10000^(−2i/d) schedule?

Keep reading

  1. Original paper (arXiv:2104.09864) — §3 derivation, Figure 1, Table 1.
  2. Vaswani et al., Attention Is All You Need — sinusoidal absolute PE — arXiv:1706.03762.
  3. Press et al., ALiBi — alternative relative bias for length extrapolation — arXiv:2108.12409.
  4. Related Fanout Daily: Attention Is All You Need, GQA, FlashAttention.

Sources

  • Su, Lu, Pan, Murtadha, Wen, Liu, RoFormer: Enhanced Transformer with Rotary Position Embedding, 2021 — arXiv:2104.09864
  • Vaswani et al., Attention Is All You Need, NeurIPS 2017 — arXiv:1706.03762
  • Press, Smith, Lewis, Train Short, Test Long: Attention with Linear Biases… (ALiBi), 2021 — arXiv:2108.12409