Techniqueadvanced
Rotary position embedding
Also called rotary positional encoding.
Rotate pairs of query and key coordinates by angles proportional to position, so that their dot product depends only on the relative offset.
Rotary position embedding puts word order into attention by rotating vectors instead of adding to them. The query and the key at position are cut into pairs of coordinates, and pair is rotated by the angle , with the frequencies of the sinusoidal positional encoding. Because rotations compose, the dot product of a query rotated by and a key rotated by equals the dot product of the original query with the key rotated by . So the attention score depends on the two contents and on the offset only, not on where the pair sits in the text. Su and colleagues introduced it in RoFormer, and RoPE is now the position method of many large decoder-only models, including GPT-NeoX, PaLM and LLaMA.
In plain words
Think of each query and each key as a set of clock hands. Before comparing them, turn the hands of a word at position 10 by ten steps and the hands of a word at position 7 by seven steps. Each hand has its own step size: some turn fast, some slowly.
When two hands are compared, only the angle between them matters. Turning both by the same extra amount changes nothing. So the comparison sees how far apart the two words are, not where they are in the text. A word three places back looks the same to the model at the start of a page as at its end.
Turning a hand does not make it longer or shorter, so the content of the vectors is kept. Nothing is added to the input words.
When it applies
- A transformer where attention scores should depend on the relative position of query and key, for example a decoder-only language model used on texts of very different lengths.
- Generation with a key-value cache: each key is rotated once by its own position when it is stored, and never needs to change, because the rotation of a new query alone fixes the offset.
- Dot-product attention of any kind, including grouped-query attention, since only and are changed. The values are not rotated.
The template
Let be the head size, even, and for . For a vector at position , rotate pair by :
So , where is block diagonal with these 2 by 2 rotations.
ROPE(x, pos, d) ▷ x of size d, d even- 1
for i ← 0 to d/2 - 1 do - 2
θ_i ← 10000^(-2i/d) - 3
c ← cos(pos · θ_i); s ← sin(pos · θ_i) - 4
y[2i] ← c · x[2i] - s · x[2i+1] - 5
y[2i+1] ← s · x[2i] + c · x[2i+1] - 6
return y
In each head, after the projections and of multi-head attention, replace row of by ROPE and row of by ROPE, then compute the scores as usual. The cost is per vector, small next to the score computation.
The relative property (theorem). Each block of is a rotation, so and . Hence
which depends on and only through . Also . With a pair seen as a complex number , the rotation is the product , and the score of the pair is . The full proof gives the details.
Long-term decay (heuristic). Su and colleagues show, through an upper bound and a plot of it (Section 3.4.3), that the size of the relative part of the score tends to fall as grows with these frequencies. It is a bound on a sum, not a guarantee that a trained model attends less to far tokens.
Classic examples
Two-dimensional case. With the only frequency is . Take , the query at position 3 and the key at position 1. Then , , and the score is . Moving both to positions 103 and 101 gives the same score.
Decoder-only language models. GPT-NeoX, PaLM and LLaMA apply RoPE in every head of causal language models in the style of GPT, with no position vector added to the input.
Key-value cache. In a key-value cache the stored keys are already rotated by their own positions. When the token at position is generated, only its query and its new key are rotated by ; the scores with all old keys then have the right offsets.
Translation. In Section 4.1 of the RoFormer paper, replacing the sinusoidal encoding of a base transformer by RoPE on WMT 2014 English to German gave 27.5 BLEU against 27.3 (a measurement, a small gain).
Variations
- Layout in halves. Many code bases pair coordinate with coordinate instead of and compute . This is the same method after a fixed permutation of the coordinates, but weights trained with one layout do not work with the other.
- Partial rotation. Rotate only a fraction of the coordinates of each head and leave the rest without position information.
- Longer contexts. To run a model beyond its training length, the positions can be scaled down (position interpolation) or the base 10000 raised, usually followed by a short fine-tuning.
- RoPE with linear attention. Since RoPE keeps norms and acts on queries and keys separately, it can be applied to the feature maps of linear attention (Section 3.3 of the paper).
- Other relative methods. ALiBi adds a distance penalty to the scores instead of rotating, and extrapolates better in the experiments of Press and colleagues (a measurement).
Pitfalls
- Mixing layouts. Loading weights trained with the layout in halves into code that uses interleaved pairs (or the reverse) runs without error and gives poor results. Check which pairing the model uses.
- Rotating the values. Only and are rotated. Rotating breaks the output, since the output is a sum of values and not a dot product.
- Wrong position with a cache. With a key-value cache, the new token must be rotated by its absolute position , not by 0 or by its index in the current chunk.
- Precision of the angles. For large positions, computing and its sine and cosine in half precision loses accuracy. Compute the angles in float32 or better.
- Odd head size. The method needs pairs; an odd leaves one coordinate unrotated.
- Expecting free extrapolation. The relative property does not make a model work well beyond the trained length; the high-index pairs have rotated by angles never seen in training.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rotary-position-embedding/. The authors are listed in prov/XBK70H.jsonl.
"""Rotary position embedding (RoPE) of Su et al. (RoFormer).
For an even size d and i = 0, ..., d/2 - 1, with theta_i = base^(-2i/d),
the pair (x[2i], x[2i + 1]) of a query or key at position pos is rotated by
the angle pos * theta_i:
y[2i] = cos(pos theta_i) x[2i] - sin(pos theta_i) x[2i + 1]
y[2i + 1] = sin(pos theta_i) x[2i] + cos(pos theta_i) x[2i + 1]
So y = R_pos x with a block-diagonal rotation R_pos, and
rope(q, m) . rope(k, n) = q . R_(n - m) k depends on m and n only through n - m.
rope_half is the layout in halves used by many code bases: coordinate i is
paired with coordinate i + d/2 instead of i + 1.
Precondition: d is even and positive, base > 1.
Cost: Theta(d) operations per vector, Theta(n d) for n positions.
The code takes the query and key vectors as given. It does not train a network.
"""
import math
from typing import List, Sequence
Vector = List[float]
def _check(d: int, base: float) -> None:
if d <= 0 or d % 2:
raise ValueError("the size d must be even and positive")
if not base > 1:
raise ValueError("the base must be greater than 1")
def rope(x: Sequence[float], pos: float, base: float = 10000.0) -> Vector:
"""Rotate each pair (x[2i], x[2i + 1]) by pos * base^(-2i/d)."""
d = len(x)
_check(d, base)
y = [0.0] * d
for i in range(d // 2): # @line L1
theta = base ** (-2 * i / d) # @line L2
c, s = math.cos(pos * theta), math.sin(pos * theta) # @line L3
y[2 * i] = c * x[2 * i] - s * x[2 * i + 1] # @line L4
y[2 * i + 1] = s * x[2 * i] + c * x[2 * i + 1] # @line L5
return y # @line L6
def rope_half(x: Sequence[float], pos: float, base: float = 10000.0) -> Vector:
"""The same rotations with coordinate i paired with coordinate i + d/2."""
d = len(x)
_check(d, base)
h = d // 2
y = [0.0] * d
for i in range(h):
theta = base ** (-2 * i / d)
c, s = math.cos(pos * theta), math.sin(pos * theta)
y[i] = c * x[i] - s * x[i + h]
y[i + h] = s * x[i] + c * x[i + h]
return y
def rope_score(q: Sequence[float], m: float, k: Sequence[float], n: float, base: float = 10000.0) -> float:
"""The attention score (before the 1/sqrt(d) scale) of a query at position m and a key at position n."""
if len(q) != len(k):
raise ValueError("q and k must have the same size")
return math.fsum(a * b for a, b in zip(rope(q, m, base), rope(k, n, base)))
test_rotary_position_embedding.py 94 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rotary-position-embedding/. The authors are listed in prov/XBK70H.jsonl.
import cmath
import math
import random
import pytest
from rotary_position_embedding import rope, rope_half, rope_score
def rand_vec(rng, d):
return [rng.gauss(0, 1) for _ in range(d)]
def complex_oracle(x, pos, base=10000.0):
"""Each pair as the complex number x[2i] + i x[2i+1], multiplied by exp(i pos theta_i)."""
d = len(x)
out = []
for i in range(d // 2):
z = complex(x[2 * i], x[2 * i + 1]) * cmath.exp(1j * pos * base ** (-2 * i / d))
out += [z.real, z.imag]
return out
def close(u, v, tol=1e-9):
return all(abs(a - b) <= tol * (1 + abs(b)) for a, b in zip(u, v))
def test_worked_example():
assert round(rope_score([1.0, 0.0], 3, [1.0, 0.0], 1), 6) == -0.416147
assert round(math.cos(2), 6) == -0.416147
assert close(rope([1.0, 0.0], 3), [math.cos(3), math.sin(3)])
@pytest.mark.parametrize("seed", range(10))
def test_against_complex_oracle(seed):
rng = random.Random(seed)
d = 2 * rng.randint(1, 12)
x = rand_vec(rng, d)
pos = rng.randint(-100, 3000)
assert close(rope(x, pos), complex_oracle(x, pos))
@pytest.mark.parametrize("seed", range(15))
def test_score_depends_only_on_offset(seed):
rng = random.Random(100 + seed)
d = 2 * rng.randint(1, 10)
q, k = rand_vec(rng, d), rand_vec(rng, d)
m, n = rng.randint(0, 500), rng.randint(0, 500)
t = rng.randint(-200, 200)
s = rope_score(q, m, k, n)
assert rope_score(q, m + t, k, n + t) == pytest.approx(s, abs=1e-9)
# and it equals q . R_(n - m) k
assert math.fsum(a * b for a, b in zip(q, rope(k, n - m))) == pytest.approx(s, abs=1e-9)
@pytest.mark.parametrize("seed", range(5))
def test_norm_is_kept_and_position_zero_is_identity(seed):
rng = random.Random(200 + seed)
x = rand_vec(rng, 8)
y = rope(x, rng.randint(1, 1000))
assert math.hypot(*y) == pytest.approx(math.hypot(*x))
assert rope(x, 0) == x
# rotations compose: R_a R_b = R_(a + b)
a, b = rng.randint(0, 50), rng.randint(0, 50)
assert close(rope(rope(x, a), b), rope(x, a + b))
@pytest.mark.parametrize("seed", range(5))
def test_half_layout_is_a_permutation(seed):
rng = random.Random(300 + seed)
d = 2 * rng.randint(1, 8)
h = d // 2
x = rand_vec(rng, d)
pos = rng.randint(0, 500)
# interleave the halves: (x_0, x_h, x_1, x_(h+1), ...)
perm = [v for i in range(h) for v in (i, i + h)]
inter = rope([x[p] for p in perm], pos)
half = rope_half(x, pos)
assert close([half[p] for p in perm], inter)
# mixing the layouts is a different function
if d >= 4:
assert not close(rope(x, pos + 1), rope_half(x, pos + 1), 1e-6)
def test_errors():
with pytest.raises(ValueError):
rope([1.0, 2.0, 3.0], 1)
with pytest.raises(ValueError):
rope_score([1.0, 0.0], 0, [1.0, 0.0, 0.0, 0.0], 0)
with pytest.raises(ValueError):
rope([1.0, 0.0], 1, base=0.5)
Exercises
- Prove and for the block rotations, and derive .
- With pairs as complex numbers, show that the score of pair is .
- Show that the layout in halves equals for a permutation matrix , and that it has the same relative property.
- Show that for all offsets, so RoPE cannot make a score larger than the unrotated maximum.
- Explain why adding the sinusoidal vectors to the input does not give a score that depends only on , while RoPE does.
Proof: ROPE returns R_pos x, the rotations keep norms and compose, and the score of a query at m and a key at n equals q^T R_(n-m) k, so it depends on the positions only through n - mfull
We use the notation of the page. is even, for , and for an angle
is the block-diagonal matrix with blocks , acting on the pairs . Positions and are any real numbers.
Lemma 1 (the procedure). ROPE returns .
Proof. The loop at line L1 visits each once. Line L2 sets , line L3 computes and , and lines L4 and L5 write , which is applied to the pair. The pairs are disjoint and cover all coordinates, and acts on each pair by its own block.
Lemma 2 (rotations). For all angles and , , and .
Proof. Transposing swaps the two off-diagonal entries, which gives , since cosine is even and sine is odd. For the product,
by the angle-sum formulas. Then .
Corollary 3. , , and .
Proof. Block-diagonal matrices with the same block sizes are transposed and multiplied block by block, and block of is by Lemma 2. For the norm, , since .
Theorem 4 (relative position). For all and positions ,
In particular, for every real , the score of at and at equals the score of at and at .
Proof. By Lemma 1 the left side is . By Corollary 3, . The right side depends on and only through , and .
Complex form. Identify the pair with . Then maps to , because . For two pairs and seen as complex numbers, the real dot product is . So the score is
which is Theorem 4 again in another form.
Bound. By the Cauchy-Schwarz inequality and Corollary 3, for every offset.
The theorem is about the score before the softmax and the factor; both act on the scores alone, so the attention weights of a query over keys also depend on the positions only through the offsets. With a causal mask, the mask itself depends only on the sign of , so the property holds there too.
References
- Jianlin Su, Murtadha Ahmed, Yu Lu, Shengfeng Pan, Wen Bo and Yunfeng Liu, RoFormer: enhanced transformer with rotary position embedding, Neurocomputing 568 (2024) 127063, arXiv:2104.09864, Section 3.2.1 (the 2D case, equation 12), Section 3.2.2 (the general form, equation 15), Section 3.3 (long-term decay, linear attention), Section 3.4.2 (the efficient form), Section 3.4.3 (the decay argument), Section 4.1 (WMT 2014 English to German)
- Press, Smith and Lewis 2022, the extrapolation experiments, where rotary embeddings extrapolate somewhat beyond the training length but less than ALiBi
- Vaswani et al. 2017, Section 3.5 (the frequencies that RoPE reuses)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag XBK70H Edit this page History Report an error Markdown