Search

Search papers and lessons

Rotary Position Embedding

Level 4 · 11 min read

Rotary position embedding encodes position by rotating query and key vectors by an angle set by token position, so attention scores depend only on the gap between tokens.

On this page

  • Colour = topic mix
  • Linear algebra
  • Architectures
  • Neural network basics
  • Discrete math
  • Language & LLMs
  • Representation learning
  • Sign in to see your progress

TL;DR

Rotary position embedding, usually called RoPE, encodes position by rotating the query and key vectors inside attention. The rotation angle grows with each token's position. The dot product between a rotated query and a rotated key then depends only on how far apart the two tokens are, not on where they sit in the sequence. Nothing is added to the input, and no new parameters are learned.

Where you'll see it: the attention layers of the LLaMA family and many other open language models, and in the long-context extensions built on top of them.

Intuition

A merry-go-round

Put two riders on a merry-go-round. Each rider points in some direction. Now spin the whole ride by an unknown amount. Both riders turn by the same angle, so the angle between them is unchanged. What you can measure is how far apart they are around the ring, and that does not depend on where the ride happens to have stopped.

RoPE works the same way. Each query and each key is a vector, and the token at position mm spins its vector by an angle proportional to mm. When a query at position mm is compared with a key at position nn, the comparison sees the difference of the two angles, which is n−mn - m. The absolute positions cancel out, and only the gap survives.

Why not add a position vector

The previous lesson, positional encoding, adds a position-dependent vector to each token embedding. That works, but the position signal then gets mixed into the content vector before attention ever sees it. A query and a key each carry their own absolute position fingerprint, and the attention score has to untangle content from position on its own. Relative distance is only learned indirectly, through the query and key projections.

RoPE asks for something more direct. It wants the score between positions mm and nn to be a function of n−mn - m alone. Rotation gives exactly that, because of a property of rotation matrices that you can check with the material on rotation matrices.

flowchart LR
  A["Token embedding"] --> B["Project to query and key"]
  B --> C["Rotate by angle set by position"]
  C --> D["Dot product depends on offset"]
  D --> E["Softmax over attention scores"]

The math

Setting up the rotation

Take a query or key vector x∈Rd\mathbf{x} \in \mathbb{R}^{d} with dd even. Group its entries into d/2d/2 pairs, (x2i,x2i+1)(x_{2i}, x_{2i+1}) for i=0,1,…,d/2−1i = 0, 1, \dots, d/2 - 1. Each pair is a point in a plane, so it can be rotated with the 2D rotation matrix.

Pair ii gets its own frequency,

θi=10000−2i/d,\theta_i = 10000^{-2i/d},

so the first pair spins fastest and the last pair spins slowest. At position mm, pair ii is rotated by the angle m θim\,\theta_i.

Definition: Rotary position embedding

For a position mm, define the block-diagonal matrix Rm∈Rd×d\mathbf{R}_m \in \mathbb{R}^{d \times d} whose ii-th 2×22 \times 2 block is

(cos⁡(mθi)−sin⁡(mθi)sin⁡(mθi)cos⁡(mθi)).\begin{pmatrix} \cos(m\theta_i) & -\sin(m\theta_i) \\ \sin(m\theta_i) & \cos(m\theta_i) \end{pmatrix}.

The rotary embedding of a query at position mm is Rmq\mathbf{R}_m \mathbf{q}, and the rotary embedding of a key at position nn is Rnk\mathbf{R}_n \mathbf{k}. Both are computed from the usual projections q=WQx\mathbf{q} = W_Q \mathbf{x} and k=WKx\mathbf{k} = W_K \mathbf{x}.

Here q\mathbf{q} and k\mathbf{k} are the query and key vectors of one attention head, mm and nn are token positions, and θi\theta_i is the frequency of pair ii. The frequencies match the sinusoidal schedule from positional encoding, which is why the two ideas look alike.

The score depends only on the offset

The attention score between positions mm and nn is the dot product of the rotated vectors. Write it with transposes and use two facts about rotations from the rotation-matrix lesson: the transpose of a rotation is the rotation by the negative angle, R(a)⊤=R(−a)R(a)^\top = R(-a), and rotations compose by adding angles, R(a)R(b)=R(a+b)R(a)R(b) = R(a+b). Then

(Rmq)⊤(Rnk)=q⊤Rm⊤Rnk=q⊤Rn−mk.(\mathbf{R}_m \mathbf{q})^\top (\mathbf{R}_n \mathbf{k}) = \mathbf{q}^\top \mathbf{R}_m^\top \mathbf{R}_n \mathbf{k} = \mathbf{q}^\top \mathbf{R}_{n-m} \mathbf{k}.

The absolute positions have disappeared. Only n−mn - m remains. The same holds block by block, because Rm\mathbf{R}_m is block-diagonal.

For one pair with q=(q1,q2)\mathbf{q} = (q_1, q_2), k=(k1,k2)\mathbf{k} = (k_1, k_2) and offset φ=(n−m)θi\varphi = (n-m)\theta_i, the contribution to the score is

si=(q1k1+q2k2)cos⁡φ+(q2k1−q1k2)sin⁡φ.s_i = (q_1 k_1 + q_2 k_2)\cos\varphi + (q_2 k_1 - q_1 k_2)\sin\varphi.

The total score is the sum of sis_i over all pairs. Each pair contributes a cosine and a sine of its own offset, so the score is a sum of waves in the gap n−mn - m.

Efficient form

Multiplying by a full d×dd \times d matrix is wasteful, because the matrix is sparse. In practice each vector is rotated with two elementwise products,

Rmq=q⊙cos⁡(mθ)+rotate_half(q)⊙sin⁡(mθ),\mathbf{R}_m \mathbf{q} = \mathbf{q} \odot \cos(m\boldsymbol{\theta}) + \mathrm{rotate\_half}(\mathbf{q}) \odot \sin(m\boldsymbol{\theta}),

where ⊙\odot is elementwise multiplication and rotate_half\mathrm{rotate\_half} swaps the two members of each pair with one negated. Many codebases pair the first half of the vector with the second half instead of adjacent entries. That is a fixed permutation of the dimensions, so it gives an equivalent model, provided queries and keys use the same pairing.

Only queries and keys are rotated. Values are left alone. Rotation preserves length, so it changes which keys match a query, not how large the vectors are.

Frequencies and wavelengths

A pair with frequency θi\theta_i completes a full turn every 2π/θi2\pi / \theta_i positions. The fastest pair, θ0=1\theta_0 = 1, turns once about every 6.3 tokens. The slowest pair turns once every tens of thousands of tokens. Between them, the pairs cover a wide range of scales, so the model can tell apart both neighbouring tokens and tokens thousands of positions away.

Worked examples

Example
Scores for a tiny query and key with d = 4

Use d=4d = 4, so there are two pairs with frequencies θ0=1\theta_0 = 1 and θ1=10000−2/4=0.01\theta_1 = 10000^{-2/4} = 0.01. Let the query and key both be q=k=(1,0,1,0)\mathbf{q} = \mathbf{k} = (1, 0, 1, 0). The query sits at position m=1m = 1 and the key at position n=3n = 3.

  1. Rotate the query by m=1m = 1.
    • Pair 0 is (1,0)(1, 0) rotated by 1⋅1=11 \cdot 1 = 1 radian: (cos⁡1,sin⁡1)≈(0.5403,0.8415)(\cos 1, \sin 1) \approx (0.5403, 0.8415).
    • Pair 1 is (1,0)(1, 0) rotated by 1⋅0.01=0.011 \cdot 0.01 = 0.01 radian: (cos⁡0.01,sin⁡0.01)≈(0.99995,0.0100)(\cos 0.01, \sin 0.01) \approx (0.99995, 0.0100).
    • So R1q≈(0.5403,0.8415,0.99995,0.0100)\mathbf{R}_1 \mathbf{q} \approx (0.5403, 0.8415, 0.99995, 0.0100).
  2. Rotate the key by n=3n = 3.
    • Pair 0 is rotated by 33 radians: (cos⁡3,sin⁡3)≈(−0.98999,0.14112)(\cos 3, \sin 3) \approx (-0.98999, 0.14112).
    • Pair 1 is rotated by 0.030.03 radian: (cos⁡0.03,sin⁡0.03)≈(0.99955,0.02999)(\cos 0.03, \sin 0.03) \approx (0.99955, 0.02999).
    • So R3k≈(−0.98999,0.14112,0.99955,0.02999)\mathbf{R}_3 \mathbf{k} \approx (-0.98999, 0.14112, 0.99955, 0.02999).
  3. Take the dot product. 0.5403⋅(−0.98999)+0.8415⋅0.14112+0.99995⋅0.99955+0.0100⋅0.02999≈−0.53490+0.11875+0.99950+0.00030=0.583650.5403 \cdot (-0.98999) + 0.8415 \cdot 0.14112 + 0.99995 \cdot 0.99955 + 0.0100 \cdot 0.02999 \approx -0.53490 + 0.11875 + 0.99950 + 0.00030 = 0.58365.
  4. Check with the offset formula. The gap is n−m=2n - m = 2, so the score should be cos⁡(2⋅1)+cos⁡(2⋅0.01)=cos⁡2+cos⁡0.02≈−0.41615+0.99980=0.58365\cos(2 \cdot 1) + \cos(2 \cdot 0.01) = \cos 2 + \cos 0.02 \approx -0.41615 + 0.99980 = 0.58365. The two results agree.
  5. Interpretation: the score came out the same as it would for any pair of positions with gap 2. Taking m=5m = 5 and n=7n = 7 instead gives the identical score, even though the absolute positions are different.
Example
Frequencies for a realistic head size of 128

A head of dimension d=128d = 128 has 6464 pairs. Here are four of them, with θi=10000−2i/128\theta_i = 10000^{-2i/128}.

Pair iiFrequency θi\theta_iWavelength 2π/θi2\pi/\theta_i (tokens)Rotation after 4096 tokens
01.06.3about 4096 radians, many full turns
10.8667.3about 3547 radians
320.0162840.96 radians, about 6.5 turns
630.000115about 54,4000.47 radian, a slow drift
  1. The fast pairs cycle many times within a few tokens. They tell apart nearby words, such as a word and the one just before it.
  2. The middle pairs complete a turn every few hundred tokens. They carry medium-range structure, such as the start of a sentence or a paragraph.
  3. The slowest pair barely moves over 4096 tokens. Its cosine is close to 1 across the whole context, so it contributes a nearly constant term to the score and acts as a coarse, long-range signal.
  4. Interpretation: each pair gives the score a different view of the gap, and together they describe the offset at many scales.

Tradeoffs and failure modes

SituationProblemBetter choice
Attention should depend on relative distanceAdditive absolute encodings mix position into contentRoPE, which makes the score a function of the offset
Autoregressive generation with a key cacheRotations applied to keys must stay valid as the cache growsStore rotated keys once. Each key depends only on its own position, so the cache stays correct
Inference beyond the training lengthAngles for positions past the training range were never seenPosition interpolation, which scales positions down into the trained range, followed by a short fine-tune
Very short fixed-length inputs with plenty of dataRoPE adds machinery a learned table would avoidLearned position embeddings
Simple baseline, or a task that needs a position biasA rotation may not be the right inductive biasAdditive sinusoidal encodings or an explicit distance bias

Failure modes to watch for. The most common bug is a mismatch between the pairing used for queries and keys, or between the position indices used at training and inference. Either one silently scrambles the scores without raising an error. A second one is an off-by-one in the position counter during generation. A model can still produce fluent text while its distance sense is shifted by one token. Finally, long-context behaviour depends on the frequencies. Lowering the frequencies or rescaling positions changes what the slow pairs can represent, so these changes need a check on a long-context benchmark, not just short prompts.

History

Position signals in transformers started with the sinusoidal encoding in the 2017 transformer paper, by Vaswani and colleagues, which added a fixed vector to each input embedding. Learned position tables followed in models such as BERT, and both approaches gave positions in absolute terms.

In 2021 Jianlin Su and colleagues posted the RoFormer paper on arXiv. It introduced rotary position embedding and argued that a rotation of queries and keys gives a relative-position signal with no extra parameters and a clean dependence on the offset. Open language models adopted it over the following years, including the GPT-NeoX family and the LLaMA family, which made RoPE the default in much of the open model ecosystem. Its later use in context-extension methods is the main reason it is studied closely today.

Check yourself

QuestionRecall: which vectors does rotary position embedding rotate, and which does it leave unchanged?Show answer

RoPE rotates the query and key vectors inside each attention head, using an angle proportional to the token's position. It leaves the value vectors unchanged. The values carry the content that gets mixed together, and the rotation only affects how well each query matches each key.

QuestionComputation: a pair with frequency θ=0.5\theta = 0.5 has query (1,0)(1, 0) at position 2 and key (1,0)(1, 0) at position 6. What is their attention contribution from this pair?Show answer

The offset is n−m=6−2=4n - m = 6 - 2 = 4, so the angle is φ=4⋅0.5=2\varphi = 4 \cdot 0.5 = 2 radians. With q=k=(1,0)\mathbf{q} = \mathbf{k} = (1, 0), the formula reduces to (q1k1)cos⁡φ=cos⁡2≈−0.416(q_1 k_1)\cos\varphi = \cos 2 \approx -0.416. The contribution is negative, meaning this pair of tokens looks dissimilar through this pair of dimensions.

QuestionWhy: explain why the attention score between a query at position mm and a key at position nn depends only on n−mn - m.Show answer

The score is (Rmq)⊤(Rnk)(\mathbf{R}_m \mathbf{q})^\top (\mathbf{R}_n \mathbf{k}). Rewriting the transpose gives q⊤Rm⊤Rnk\mathbf{q}^\top \mathbf{R}_m^\top \mathbf{R}_n \mathbf{k}. A rotation's transpose is the rotation by the negative angle, and rotations compose by adding angles, so Rm⊤Rn=Rn−m\mathbf{R}_m^\top \mathbf{R}_n = \mathbf{R}_{n-m}. The absolute positions mm and nn never appear separately, only their difference.

QuestionApplied: a model was trained with a 2048-token context and is run on 8192-token inputs. Explain why plain RoPE can degrade, and name one fix.Show answer

Positions beyond 2048 produce rotation angles the model never saw during training. The fast and middle pairs in particular spin through angles outside the trained range, so their contributions to the score are unfamiliar. One fix is position interpolation: scale the positions down by the ratio of the two lengths, so the new positions fall inside the trained range, and then fine-tune briefly. Changing the frequencies is a related option, and either one should be checked on long-context tasks.

Sources