RoFormer: Enhanced Transformer with Rotary Position Embedding

Jianlin Su, Yu Lu, Shengfeng Pan, Bo Wen, Yunfeng Liu

2021 · arXiv

RoFormer: Enhanced Transformer with Rotary Position Embedding

Problem

Framing

Standard Transformer position schemes either add absolute embeddings or alter attention with relative biases, but these forms do not transfer cleanly to linear attention. RoFormer closes this gap by encoding position as a rotation in each query-key subspace, so absolute indices induce explicit relative phase differences and distance decay.

Currently Used Methods

Foundational

Proposed Method

Architecture

RoFormer keeps the standard multi-head Transformer block and only replaces positional handling inside self-attention. Each even-dimensional query and key vector is partitioned into 2D pairs, then each pair is rotated by a position-dependent angle before the inner product.

RoPE implementation diagram: 2D query-key pairs are rotated by position-dependent angles, then stacked across dimensions to form position-encoded queries and keys.

Loss / Objective

The method changes position encoding, not the task loss; training uses the baseline objective for each task while computing attention with rotated queries and keys.

f{q,k}(xm,m)=RΘ,mdW{q,k}xmf_{\{q,k\}}(\mathbf{x}_m, m) = \mathbf{R}^{d}_{\Theta,m}\,\mathbf{W}_{\{q,k\}}\,\mathbf{x}_m qmkn=(RΘ,mdWqxm)(RΘ,ndWkxn)=xmWqRΘ,nmdWkxn\mathbf{q}_m^\top \mathbf{k}_n = \left(\mathbf{R}^{d}_{\Theta,m}\mathbf{W}_q \mathbf{x}_m\right)^\top \left(\mathbf{R}^{d}_{\Theta,n}\mathbf{W}_k \mathbf{x}_n\right) = \mathbf{x}_m^\top \mathbf{W}_q^\top \mathbf{R}^{d}_{\Theta,n-m}\mathbf{W}_k\mathbf{x}_n

Sampling Rule / Algorithm

Self-attention uses the usual normalized similarity, but the similarity is computed from RoPE-transformed queries and keys.

Attention(Q,K,V)m=n=1Nsim(qm,kn)vnn=1Nsim(qm,kn)\mathrm{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V})_m = \frac{\sum_{n=1}^{N} \mathrm{sim}(\mathbf{q}_m, \mathbf{k}_n)\,\mathbf{v}_n}{\sum_{n=1}^{N} \mathrm{sim}(\mathbf{q}_m, \mathbf{k}_n)}

Training Procedure

Evaluation

Datasets

Metrics

Headline results

Results plot: the theoretical upper bound of RoPE interaction decays as relative distance increases, illustrating the built-in long-range attenuation property.

Ablations

Method Strengths and Weaknesses

Strengths

Weaknesses

Suggestions from the authors

Links

Prior Papers

Further Papers