Algorithm Search⌘K

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 mm are cut into pairs of coordinates, and pair ii is rotated by the angle mθim\theta_i, with the frequencies θi=10000−2i/d\theta_i = 10000^{-2i/d} of the sinusoidal positional encoding. Because rotations compose, the dot product of a query rotated by mm and a key rotated by nn equals the dot product of the original query with the key rotated by n−mn - m. So the attention score depends on the two contents and on the offset n−mn - m 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 QQ and KK are changed. The values are not rotated.

The template

Let dd be the head size, even, and θi=10000−2i/d\theta_i = 10000^{-2i/d} for i=0,…,d/2−1i = 0, \ldots, d/2 - 1. For a vector xx at position mm, rotate pair (x2i,x2i+1)(x_{2i}, x_{2i+1}) by mθim\theta_i:

(y2iy2i+1)=(cos⁡mθi−sin⁡mθisin⁡mθicos⁡mθi)(x2ix2i+1).\begin{pmatrix} y_{2i} \\ y_{2i+1} \end{pmatrix} = \begin{pmatrix} \cos m\theta_i & -\sin m\theta_i \\ \sin m\theta_i & \cos m\theta_i \end{pmatrix} \begin{pmatrix} x_{2i} \\ x_{2i+1} \end{pmatrix}.

So y=Rmxy = R_m x, where RmR_m is block diagonal with these 2 by 2 rotations.

  1. ROPE(x, pos, d) ▷ x of size d, d even
  2. 1for i ← 0 to d/2 - 1 do
  3. 2θ_i ← 10000^(-2i/d)
  4. 3c ← cos(pos · θ_i); s ← sin(pos · θ_i)
  5. 4y[2i] ← c · x[2i] - s · x[2i+1]
  6. 5y[2i+1] ← s · x[2i] + c · x[2i+1]
  7. 6return y

In each head, after the projections Qr=XWrQQ_r = X W^Q_r and Kr=XWrKK_r = X W^K_r of multi-head attention, replace row mm of QrQ_r by ROPE(Qr,m,m,dk)(Q_{r,m}, m, d_k) and row nn of KrK_r by ROPE(Kr,n,n,dk)(K_{r,n}, n, d_k), then compute the scores as usual. The cost is Θ(d)\Theta(d) per vector, small next to the score computation.

The relative property (theorem). Each block of RmR_m is a rotation, so Rm⊤=R−mR_m^\top = R_{-m} and RaRb=Ra+bR_a R_b = R_{a + b}. Hence

(Rmq)⊤(Rnk)=q⊤Rm⊤Rnk=q⊤Rn−mk,(R_m q)^\top (R_n k) = q^\top R_m^\top R_n k = q^\top R_{n - m} k,

which depends on mm and nn only through n−mn - m. Also ∥Rmx∥=∥x∥\lVert R_m x \rVert = \lVert x \rVert. With a pair seen as a complex number z=x2i+i x2i+1z = x_{2i} + \mathrm{i}\, x_{2i+1}, the rotation is the product z eimθiz\, e^{\mathrm{i} m \theta_i}, and the score of the pair is Re⁡(qiki‾ ei(m−n)θi)\operatorname{Re}\big(q_i \overline{k_i}\, e^{\mathrm{i}(m - n)\theta_i}\big). 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 ∣n−m∣|n - m| 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 d=2d = 2 the only frequency is θ0=1\theta_0 = 1. Take q=k=(1,0)q = k = (1, 0), the query at position 3 and the key at position 1. Then R3q=(cos⁡3,sin⁡3)R_3 q = (\cos 3, \sin 3), R1k=(cos⁡1,sin⁡1)R_1 k = (\cos 1, \sin 1), and the score is cos⁡3cos⁡1+sin⁡3sin⁡1=cos⁡2=−0.416147\cos 3 \cos 1 + \sin 3 \sin 1 = \cos 2 = -0.416147. 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 tt is generated, only its query and its new key are rotated by tt; 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 ii with coordinate i+d/2i + d/2 instead of i+1i + 1 and compute xcos⁡+rotate_half⁡(x)sin⁡x \cos + \operatorname{rotate\_half}(x) \sin. 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 QQ and KK are rotated. Rotating VV 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 tt, not by 0 or by its index in the current chunk.
  • Precision of the angles. For large positions, computing mθim\theta_i 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 dkd_k 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.

rotary_position_embedding.pyI0RawGitHub
# 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

  1. Prove RaRb=Ra+bR_a R_b = R_{a+b} and Ra⊤=R−aR_a^\top = R_{-a} for the block rotations, and derive (Rmq)⊤(Rnk)=q⊤Rn−mk(R_m q)^\top (R_n k) = q^\top R_{n-m} k.
  2. With pairs as complex numbers, show that the score of pair ii is Re⁡(qiki‾ei(m−n)θi)\operatorname{Re}(q_i \overline{k_i} e^{\mathrm{i}(m-n)\theta_i}).
  3. Show that the layout in halves equals P⊤RmPP^\top R_m P for a permutation matrix PP, and that it has the same relative property.
  4. Show that ∣q⊤Rn−mk∣≤∥q∥∥k∥|q^\top R_{n-m} k| \le \lVert q \rVert \lVert k \rVert for all offsets, so RoPE cannot make a score larger than the unrotated maximum.
  5. Explain why adding the sinusoidal vectors to the input does not give a score that depends only on n−mn - m, 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. dd is even, θi=10000−2i/d\theta_i = 10000^{-2i/d} for i=0,…,d/2−1i = 0, \ldots, d/2 - 1, and for an angle ϕ\phi

G(ϕ)=(cos⁡ϕ−sin⁡ϕsin⁡ϕcos⁡ϕ).G(\phi) = \begin{pmatrix} \cos\phi & -\sin\phi \\ \sin\phi & \cos\phi \end{pmatrix}.

RmR_m is the d×dd \times d block-diagonal matrix with blocks G(mθ0),…,G(mθd/2−1)G(m\theta_0), \ldots, G(m\theta_{d/2-1}), acting on the pairs (x2i,x2i+1)(x_{2i}, x_{2i+1}). Positions mm and nn are any real numbers.

Lemma 1 (the procedure). ROPE(x,pos,d)(x, pos, d) returns Rpos xR_{pos}\, x.

Proof. The loop at line L1 visits each ii once. Line L2 sets θi\theta_i, line L3 computes c=cos⁡(pos θi)c = \cos(pos\,\theta_i) and s=sin⁡(pos θi)s = \sin(pos\,\theta_i), and lines L4 and L5 write (y2i,y2i+1)=(cx2i−sx2i+1,  sx2i+cx2i+1)(y_{2i}, y_{2i+1}) = (c x_{2i} - s x_{2i+1},\; s x_{2i} + c x_{2i+1}), which is G(pos θi)G(pos\,\theta_i) applied to the pair. The pairs are disjoint and cover all coordinates, and RposR_{pos} acts on each pair by its own block. □\square

Lemma 2 (rotations). For all angles α\alpha and β\beta, G(α)⊤=G(−α)G(\alpha)^\top = G(-\alpha), G(α)⊤G(α)=IG(\alpha)^\top G(\alpha) = I and G(α)G(β)=G(α+β)G(\alpha) G(\beta) = G(\alpha + \beta).

Proof. Transposing G(α)G(\alpha) swaps the two off-diagonal entries, which gives (cos⁡αsin⁡α−sin⁡αcos⁡α)=G(−α)\begin{pmatrix} \cos\alpha & \sin\alpha \\ -\sin\alpha & \cos\alpha \end{pmatrix} = G(-\alpha), since cosine is even and sine is odd. For the product,

G(α)G(β)=(cos⁡αcos⁡β−sin⁡αsin⁡β−(cos⁡αsin⁡β+sin⁡αcos⁡β)sin⁡αcos⁡β+cos⁡αsin⁡βcos⁡αcos⁡β−sin⁡αsin⁡β)=G(α+β)G(\alpha) G(\beta) = \begin{pmatrix} \cos\alpha\cos\beta - \sin\alpha\sin\beta & -(\cos\alpha\sin\beta + \sin\alpha\cos\beta) \\ \sin\alpha\cos\beta + \cos\alpha\sin\beta & \cos\alpha\cos\beta - \sin\alpha\sin\beta \end{pmatrix} = G(\alpha + \beta)

by the angle-sum formulas. Then G(α)⊤G(α)=G(−α)G(α)=G(0)=IG(\alpha)^\top G(\alpha) = G(-\alpha) G(\alpha) = G(0) = I. □\square

Corollary 3. Rm⊤=R−mR_m^\top = R_{-m}, RaRb=Ra+bR_a R_b = R_{a+b}, and ∥Rmx∥=∥x∥\lVert R_m x \rVert = \lVert x \rVert.

Proof. Block-diagonal matrices with the same block sizes are transposed and multiplied block by block, and block ii of RaRbR_a R_b is G(aθi)G(bθi)=G((a+b)θi)G(a\theta_i) G(b\theta_i) = G((a + b)\theta_i) by Lemma 2. For the norm, ∥Rmx∥2=x⊤Rm⊤Rmx=x⊤R0x=x⊤x\lVert R_m x \rVert^2 = x^\top R_m^\top R_m x = x^\top R_0 x = x^\top x, since R0=IR_0 = I. □\square

Theorem 4 (relative position). For all q,k∈Rdq, k \in \mathbb{R}^d and positions m,nm, n,

ROPE(q,m)⋅ROPE(k,n)=q⊤Rn−m k.\mathrm{ROPE}(q, m) \cdot \mathrm{ROPE}(k, n) = q^\top R_{n - m}\, k.

In particular, for every real tt, the score of qq at m+tm + t and kk at n+tn + t equals the score of qq at mm and kk at nn.

Proof. By Lemma 1 the left side is (Rmq)⊤(Rnk)=q⊤Rm⊤Rnk(R_m q)^\top (R_n k) = q^\top R_m^\top R_n k. By Corollary 3, Rm⊤Rn=R−mRn=Rn−mR_m^\top R_n = R_{-m} R_n = R_{n - m}. The right side depends on mm and nn only through n−mn - m, and (n+t)−(m+t)=n−m(n + t) - (m + t) = n - m. □\square

Complex form. Identify the pair (x2i,x2i+1)(x_{2i}, x_{2i+1}) with zi=x2i+i x2i+1z_i = x_{2i} + \mathrm{i}\, x_{2i+1}. Then G(ϕ)G(\phi) maps ziz_i to zieiϕz_i e^{\mathrm{i}\phi}, because (a+ib)(cos⁡ϕ+isin⁡ϕ)=(acos⁡ϕ−bsin⁡ϕ)+i(asin⁡ϕ+bcos⁡ϕ)(a + \mathrm{i} b)(\cos\phi + \mathrm{i}\sin\phi) = (a\cos\phi - b\sin\phi) + \mathrm{i}(a\sin\phi + b\cos\phi). For two pairs uu and vv seen as complex numbers, the real dot product is Re⁡(uvˉ)\operatorname{Re}(u \bar v). So the score is

∑iRe⁡(qieimθi kieinθi‾)=∑iRe⁡(qiki‾ ei(m−n)θi),\sum_i \operatorname{Re}\big(q_i e^{\mathrm{i} m\theta_i}\, \overline{k_i e^{\mathrm{i} n\theta_i}}\big) = \sum_i \operatorname{Re}\big(q_i \overline{k_i}\, e^{\mathrm{i}(m - n)\theta_i}\big),

which is Theorem 4 again in another form.

Bound. By the Cauchy-Schwarz inequality and Corollary 3, ∣q⊤Rn−mk∣≤∥q∥∥Rn−mk∥=∥q∥∥k∥|q^\top R_{n-m} k| \le \lVert q \rVert \lVert R_{n-m} k \rVert = \lVert q \rVert \lVert k \rVert for every offset. ■\blacksquare

The theorem is about the score before the softmax and the 1/dk1/\sqrt{d_k} 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 n−mn - m, so the property holds there too.

References

  1. 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)
  2. Press, Smith and Lewis 2022, the extrapolation experiments, where rotary embeddings extrapolate somewhat beyond the training length but less than ALiBi
  3. 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.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/XBK70H/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples