AI Logic

Positional Encodings

RoPE (Rotary Position Embedding)

Updated:

How RoPE works. The left shows the flow of an attention layer: nothing is added to the input, and in each layer the query q and key k are rotated according to positions m and n before the score is computed. The right is a worked example for one 2-dimensional pair: the top shows the same vector rotated by θ at each of positions 0–5, and the bottom shows position pairs (m, n) = (1, 3) and (4, 6), which have the same distance 2 and therefore the same angle between query and key and the same dot product.

What is RoPE?

RoPE (Rotary Position Embedding) injects position information by rotating the attention queries and keys by an angle proportional to the word's position. It was proposed by Su et al. in 2021 in the RoFormer paper.

The scaled dot-product attention in the Transformer does not distinguish word order on its own. The original Transformer added sinusoidal positional encoding to the input embeddings. Instead of adding, RoPE multiplies the queries and keys in every layer by a rotation matrix.

Rotation is used because when two vectors are each rotated and then their dot product is taken, the result depends only on the difference between the rotation angles. If the query at position mm is rotated by mθm\theta and the key at position nn by nθn\theta, the dot product depends only on the angle difference (n−m)θ(n-m)\theta, that is, only on the distance between the two words. The defining feature of RoPE is that although the rotation uses absolute positions, attention receives relative positions.

There are no learned parameters. LLaMA drops absolute position embeddings and applies RoPE in every layer of the network (Section 2.2 of the LLaMA paper).

The left of the figure at the top of the article shows where position information is injected. It has the same layout as the figures in the articles on learned positional embeddings, relative position representations, and ALiBi, so the injection points can be compared directly. The right is a worked example of the rotation and dot product for one 2-dimensional pair.

Theory (rotating two dimensions at a time)

The explanation follows the equations in Section 3.2 of the paper. Let xmx_m be the input for the word at position mm, Wq,WkW_q, W_k the weights of the linear layers that produce the queries and keys, and dd (even) the head size.

  1. As usual, compute the query WqxmW_q x_m and the key WkxnW_k x_n.
  2. Split the dd-dimensional vector into d/2d/2 pairs of two dimensions: dimensions 1–2, 3–4, and so on.
  3. Assign a rotation speed θi\theta_i to the ii-th pair. The speed differs per pair and follows the same geometric sequence as sinusoidal positional encoding.
  4. Rotate the ii-th pair of the query at position mm in the plane by the angle mθim\theta_i. Likewise, rotate the key at position nn by the angle nθin\theta_i.
  5. Compute the dot product (score) of the rotated query and key as usual. The values are not rotated.

First consider two dimensions (d=2d = 2). The rotation in step 4 is multiplication by the following matrix (Eq. (13) in the paper).

f{q,k}(xm,m)=(cos⁡mθ−sin⁡mθsin⁡mθcos⁡mθ)W{q,k} xmf_{\{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

In dd dimensions, the vector is multiplied by the matrix RΘ,mdR^d_{\Theta,m}, which places d/2d/2 of these 2×2 rotations along the diagonal (Eqs. (14) and (15)). The speeds in step 3 are as follows.

qm=RΘ,mdWqxm,kn=RΘ,ndWkxn,θi=10000−2(i−1)/d,i=1,2,…,d/2q_m = R^d_{\Theta,m} W_q x_m, \qquad k_n = R^d_{\Theta,n} W_k x_n, \qquad \theta_i = 10000^{-2(i-1)/d}, \quad i = 1, 2, \dots, d/2

Transposing a rotation matrix gives the rotation in the opposite direction (Rm⊤Rn=Rn−mR_m^\top R_n = R_{n-m}), so the dot product in step 5 becomes the following (Eq. (16)).

qm⊤kn=(RΘ,mdWqxm)⊤(RΘ,ndWkxn)=xm⊤Wq⊤RΘ, n−md Wkxnq_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 matrix in the middle, RΘ,n−mdR^d_{\Theta,n-m}, depends only on the distance n−mn - m. In other words, the only position information that enters the score is relative position.

Most entries of RΘ,mdR^d_{\Theta,m} are 0, so multiplying by the matrix directly is wasteful. The paper gives an equation that produces the same result with element-wise multiplication (Eq. (34)). Using xx and a vector in which the two values of each pair are swapped and one is negated, it computes x⊗cos⁡mθ+(−x2,x1,−x4,x3,… )⊗sin⁡mθx \otimes \cos m\theta + (-x_2, x_1, -x_4, x_3, \dots) \otimes \sin m\theta. The PyTorch implementation below uses this method.

Why represent position with rotation?

An analogy with the two hands of a clock helps. If the query hand is turned by "mm hours" and the key hand by "nn hours," the angle between the two hands is determined by n−mn - m hours, regardless of where on the dial they are. The dot product depends on the lengths of the two hands and the angle between them, so the score also depends only on the distance. The bottom right of the figure at the top of the article shows, computed from the equations, that the position pairs (1,3)(1, 3) and (4,6)(4, 6) have the same distance 2 and therefore the same dot product.

This mechanism has the following properties.

  • It does not change vector length: Rotation preserves length (it is an orthogonal matrix), so injecting position does not distort the magnitude of the values. The paper argues that this contributes to stable training.
  • It injects position by multiplication: Sinusoidal positional encoding and relative position representations inject position by adding vectors. RoPE injects it by multiplying, so expanding the dot product introduces no extra terms, and relative position emerges naturally as a product of rotations.
  • The dot product tends to shrink for more distant words: The paper shows that with θi\theta_i set to the geometric sequence above, the upper bound of the dot product decreases with distance (Section 3.4.3, Figure 2). This matches the intuition that connections between distant words can be weaker.
  • It also combines with linear attention: Since rotation preserves length, it can be applied to the features of linear attention (such as Performer) (Eq. (19) in Section 3.3).

The ALiBi paper also highlights that RoPE injects position information in every layer and not into the values. Since the values carry no position, the output of each layer does not directly contain position information. The ALiBi paper suspected that this separation helps extrapolation to longer sequences and adopted it in the design of ALiBi.

Experimental results

Translation (RoFormer paper, Table 1): On WMT 2014 English→German, replacing the position representation of the Transformer base model with RoPE raised BLEU from 27.3 to 27.5.

Pre-training convergence (Figure 3): When BERT was pre-trained with its position representation replaced by RoPE, the masked language modeling loss fell faster than with BERT. In an experiment adding RoPE to Performer, the loss was also lower at the same number of steps.

Downstream tasks (Table 2): Results against BERT on six GLUE tasks were mixed.

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

RoFormer was better on MRPC, STS-B, and QQP, while BERT scored higher on SST-2, QNLI, and MNLI.

Long documents (Table 5): On a task that judges the similarity of long Chinese documents (CAIL2019-SCM), RoFormer and WoBERT (a word-level BERT) were nearly equal with inputs limited to 512 characters (test accuracy 68.29% and 68.10%). RoFormer with inputs extended to 1024 characters reached 69.79%. BERT, which uses learned positional embeddings, cannot handle inputs longer than 512 as is.

Extrapolation to sequences longer than training (ALiBi paper, Table 2): Perplexity of language models trained on length-512 sequences of WikiText-103 and evaluated on longer sequences (lower is better).

Evaluation lengthSinusoidalRoPEALiBi
512 (same as training)20.0520.0719.73
101243.5421.3718.73
2512132.4131.5818.41

RoPE degrades far less than sinusoidal encoding, but its perplexity rises once the length greatly exceeds the training length.

Practical considerations

RoPE represents relative position, but accuracy is not maintained on sequences much longer than the training length. In the ALiBi paper's comparison, a RoPE model trained at length 512 improved up to about 200 tokens beyond the training length, but its perplexity rose for longer sequences. To use a context longer than in training, consider methods that adjust the rotation angles to extend the context, such as position interpolation and YaRN.

Also keep the following in mind.

  • Only queries and keys are rotated: Values and input embeddings are not rotated. There is also no need to add absolute position embeddings to the input.
  • Match the way dimensions are paired: The paper pairs adjacent dimensions (1–2, 3–4, ...). A different pairing is a different position representation, so when using a pre-trained model, match the pairing used in that model's implementation.
  • Compute it in every attention layer: Unlike methods that add position once at the input, the queries and keys of every layer are rotated. cos⁡mθi\cos m\theta_i and sin⁡mθi\sin m\theta_i depend only on position and dimension, so they can be precomputed and reused.

The RoFormer paper itself states that it cannot fully explain why RoPE converges faster than other position representations or why it is more accurate on long documents (Section 4.5.5). Its properties are shown theoretically, but the size of the effect varies by task.

Comparison with other position representations

MethodWhere position is injectedLearned parametersSequences longer than trainingMain uses
Learned positional embeddingAdded to the input embeddings (once)Yes (Lmax⁡×dL_{\max} \times d)Cannot be representedBERT, GPT
Sinusoidal positional encodingAdded to the input embeddings (once)NoneValues can be computed, but accuracy drops sharplyOriginal Transformer
Relative position representationsPer-distance vectors added to scores and values in every layerYes (2k+12k+1 distances)Computable because the distance is clippedTranslation, etc.
RoPE (this article)Queries and keys rotated by an angle proportional to position in every layerNoneOnly slightly longer (extendable with position interpolation, etc.)LLaMA, etc.
ALiBiA penalty proportional to distance subtracted from scores in every layerNoneAccuracy is easier to maintainWhen sequences longer than training are needed
  • To use relative position without adding parameters, RoPE is a good fit. The form of the score computation does not change, so it can be used simply by adding the query and key rotations to an ordinary attention implementation.
  • To handle inputs longer than in training without additional training, ALiBi has been reported to maintain accuracy better.
  • To extend the context of a RoPE model, there are methods that adjust the rotation angles, such as position interpolation, YaRN, and LongRoPE. There is also xPos, a method based on RoPE.

PyTorch example

Show code
python
import torch


def rope_cos_sin(seq_len: int, d: int, base: float = 10000.0):
    """Precompute cos(m θ_i) and sin(m θ_i) for each position m and pair i (θ_i = base^(-2(i-1)/d))"""
    theta = base ** (-torch.arange(0, d, 2).float() / d)        # [d/2]
    angle = torch.arange(seq_len).float()[:, None] * theta       # [seq_len, d/2]  m θ_i
    # Adjacent dimensions share the same angle, so repeat each value twice (Eq. (34) in the paper)
    cos = angle.cos().repeat_interleave(2, dim=-1)                # [seq_len, d]
    sin = angle.sin().repeat_interleave(2, dim=-1)
    return cos, sin


def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    """x: [..., seq_len, d]. Rotate each pair (x1, x2) by the angle m θ_i"""
    x1, x2 = x[..., 0::2], x[..., 1::2]
    rotated = torch.stack((-x2, x1), dim=-1).flatten(-2)         # (-x2, x1, -x4, x3, ...)
    return x * cos + rotated * sin


# Inside attention, rotate only the queries and keys (values are unchanged)
B, h, n, d = 2, 8, 16, 64
q, k, v = torch.randn(B, h, n, d), torch.randn(B, h, n, d), torch.randn(B, h, n, d)
cos, sin = rope_cos_sin(n, d)
q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
attn = torch.softmax(q @ k.transpose(-2, -1) / d ** 0.5, dim=-1)
out = attn @ v
print(out.shape)  # torch.Size([2, 8, 16, 64])

# Check that the dot product depends only on distance: place the same q and k at positions (1, 3) and (4, 6)
q0, k0 = torch.randn(d), torch.randn(d)
cos, sin = rope_cos_sin(8, d)
dot = lambda m, n_: apply_rope(q0, cos[m], sin[m]) @ apply_rope(k0, cos[n_], sin[n_])
print(dot(1, 3).item(), dot(4, 6).item())  # same value (both distances are 2)

FAQ

Q. How does RoPE differ from sinusoidal positional encoding?
A.

Both use the same geometric sequence of angles (θi=10000−2(i−1)/d\theta_i = 10000^{-2(i-1)/d}), but sinusoidal encoding adds sin and cos values to the input, while RoPE rotates the queries and keys. Adding introduces terms into the score that mix word content with position, whereas rotation makes the dot product depend only on the distance n−mn - m. Also, sinusoidal encoding injects position once at the input, while RoPE does so in every layer.

Q. Why are the values not rotated?
A.

Position information is needed in the score computation that decides "which words to attend to and how much," and only the queries and keys take part in it. The ALiBi paper notes that keeping position out of the values means the output of each layer does not directly contain position information, which may help extrapolation to longer sequences.

Q. How can a RoPE model be used with a context longer than in training?
A.

Feeding longer inputs as is produces large rotation angles never seen in training, and accuracy drops. Methods such as position interpolation have been proposed that adjust the rotation angles to keep them within the trained range. YaRN and LongRoPE also extend the context by adjusting the rotation angles.

References

  1. J. Su, Y. Lu, S. Pan, A. Murtadha, B. Wen, and Y. Liu, "RoFormer: Enhanced Transformer with Rotary Position Embedding," arXiv:2104.09864, 2021.
  2. H. Touvron et al., "LLaMA: Open and Efficient Foundation Language Models," arXiv:2302.13971, 2023.
  3. O. Press, N. A. Smith, and M. Lewis, "Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation," ICLR, 2022.
  4. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.