All courses

Rotary position embeddings (RoPE)

Rotate each 2D pair of query and key dimensions by an angle proportional to the position. Show that q·k then depends on the two positions only through their relative offset.

Builds on: Injecting order: absolute position embeddings, 2D rotation matrices

▶ Watch this lesson Start the whole course

What the animation says

Same pair, different slot

Attention scores a query against a key with a dot product. Absolute position embeddings add a slot number to each token, so the score can see order. But 'cat' at slot seven and 'sat' at slot eight can score differently from the same two words at one hundred seven and one hundred eight. Then the model has to relearn 'look at the previous word' for every slot. What really matters is how far back a token is. Can we make the score depend only on that gap?

Turn pairs like clock hands

Here's the trick. Split each query and key into pairs of numbers, and draw each pair as an arrow. At position t, turn the arrow by t steps of a fixed angle, like a clock hand. Turning never changes length. And the dot product of two arrows depends only on their lengths and the angle between them. The query turns by its position, the key by its own. The shared part of the turn cancels, leaving only the gap. Now slide both tokens one hundred slots later. What happens to the angle between the arrows?

Worked case: 90° per step

It stays the same. Both arrows gain the same extra turn, and it cancels out. Now some numbers. One pair turns ninety degrees per position. Query content points right, key content points up. Unturned, the score is zero. Query at four turns a full circle, back to pointing right. Key at three turns two hundred seventy degrees, also to the right. Score: one. Query at two, key at one: both point left. Score: one again. Same gap, same score. Your turn. Which of these position pairs also scores one?

Many hands, many speeds

A real attention head has many pairs, and each pair turns at its own speed. Pair zero turns fastest. Each later pair turns slower, until the last ones barely move. Fast hands tell nearby offsets apart. Slow hands tell far ones apart. Each turn is an ordinary 2D rotation: a cos minus b sin, then a sin plus b cos. It happens after the projections, in every attention layer, with no learned parameters. So which vectors actually get rotated?

Check it in numpy

Only queries and keys turn. The values are left alone. Now check it in code. This function turns each pair of a vector by its position times that pair's frequency. Take a random eight-dimensional query and key. Score them at positions five and three, then at one hundred five and one hundred three. Both have an offset of two, and the two printed numbers match up to rounding. That's RoPE: the score sees how far apart tokens are, never which slot they sit in.

Can a score see only how far apart tokens are?

Absolute position embeddings let attention see order, but they tie a token to a fixed slot. The score between 'cat' at 7 and 'sat' at 8 can differ from the same pair at 107 and 108. The model may then have to relearn 'look at the previous word' for every slot. What usually matters is how far back a token is. Can we build position into the score so that $q\cdot k$ depends only on the offset $t-s$?

Turn every pair like a clock hand

Split each query and key into $d_{head}/2$ pairs of numbers, and treat each pair as a 2D arrow. At position $t$, turn each arrow by $t$ steps of its pair's fixed angle. Turning keeps lengths fixed, and the dot product of two arrows depends only on their lengths and the angle between them. So the turning they share cancels, and only $t-s$ is left. Pairs turn at different speeds: fast hands tell nearby offsets apart, slow hands tell far ones apart.

The RoPE formula

Let $q_t$ and $k_s$ be rows $t$ and $s$ of $Q=XW_Q$ and $K=XW_K$. Write $q^{(i)}$ for pair $i$ of $q$: dims $(2i,2i{+}1)$, $i=0,\dots,d_{head}/2-1$. Pair $i$ has frequency $\omega_i=10000^{-2i/d_{head}}$. At position $t$, rotate pair $(a,b)$ by $\phi=t\omega_i$: $$(a,b)\mapsto(a\cos\phi-b\sin\phi,\;a\sin\phi+b\cos\phi)$$ With $R(\phi)$ this rotation, $R(\phi)^\top R(\psi)=R(\psi-\phi)$, so $\tilde q_t\cdot\tilde k_s=\sum_i q_t^{(i)}\cdot R((s-t)\omega_i)\,k_s^{(i)}$. Only $t-s$ appears. The values $V=XW_V$ are not rotated.

One pair, 90° per position

Take $\omega=90^\circ$, query content $(1,0)$ and key content $(0,1)$. Unrotated, the score is $0$. - $t=4,s=3$: the query turns $360^\circ$ to $(1,0)$. The key turns $270^\circ$ to $(0\cdot0-1\cdot(-1),\,0\cdot(-1)+1\cdot0)=(1,0)$. Score $=1$. - $t=2,s=1$: the query is $(-1,0)$ and the key is $(-1,0)$. Score $=1$ again. - $t=s=3$: the query is $(0,-1)$ and the key is $(1,0)$. Score $=0$. The score depends on the offset, not on the slot.

Check shift invariance in numpy

This applies RoPE to random 8-dim $q,k$ and compares the score at positions (5, 3) with the score at (105, 103). Both have offset 2, so the two printed numbers match up to rounding.
import numpy as np
def rope(x, pos, base=10000.0):
    d = x.shape[-1]; i = np.arange(d // 2)
    ang = pos * base ** (-2 * i / d)      # one angle per pair
    a, b = x[0::2], x[1::2]
    c, s = np.cos(ang), np.sin(ang)
    out = np.empty_like(x)
    out[0::2], out[1::2] = a*c - b*s, a*s + b*c
    return out
rng = np.random.default_rng(0); q, k = rng.normal(size=(2, 8))
print(rope(q, 5) @ rope(k, 3), rope(q, 105) @ rope(k, 103))

What to remember

RoPE rotates pair $i$ of a query or key at position $t$ by angle $t\omega_i$. This happens after the projections, in every attention layer. It adds nothing to the embeddings and has no learned parameters. Rotation keeps lengths fixed, so for fixed content the dot product depends only on the difference of the angles. So $q\cdot k$ sees position only through the offset $t-s$, never through the absolute slot.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.