Algorithm Search⌘K

Techniquecore

Sinusoidal positional encoding

Also called absolute positional encoding.

Add to each token vector sines and cosines of its position at geometrically spaced frequencies, so attention can use word order.

The sinusoidal positional encoding gives each position pospos of a sequence a fixed vector PE(pos)\mathrm{PE}(pos) of size dd, made of sines and cosines of pospos at d/2d/2 frequencies, and adds it to the token embedding at that position. Scaled dot-product attention does not see the order of its inputs, so without such a signal a transformer treats a sentence as a bag of words. The frequencies form a geometric sequence, so the wavelengths run from 2π2\pi to 10000⋅2π10000 \cdot 2\pi. The main property is that a shift by a fixed offset kk is a linear map: PE(pos+k)=Mk PE(pos)\mathrm{PE}(pos + k) = M_k\, \mathrm{PE}(pos), with a matrix MkM_k of 2 by 2 rotations that does not depend on pospos.

In plain words

Attention mixes words by how well they match, and it would give the same result if the words were shuffled. So each position needs a mark that tells where it is.

Think of a row of clocks with hands that turn at different speeds. The first hand turns fast, the next one slower, and the last one very slowly. At position one, all hands are turned a little; at position two, twice as much; and so on. The reading of all the hands together is a different pattern for every position, and the pattern is added to the word.

Fast hands tell nearby positions apart. Slow hands tell far positions apart. Because moving forward by a fixed number of steps turns every hand by a fixed amount, the network can learn to look a fixed number of words back.

When it applies

  • The model mixes positions with a mechanism that is blind to order: self-attention in a transformer encoder, or a decoder where the causal mask alone gives only weak order information.
  • A fixed encoding is wanted: no extra parameters, and values for any position, including positions longer than those seen in training (though the model may not use them well).
  • The model takes absolute positions as input. If only distances should matter, a relative method such as rotary position embedding or ALiBi builds that into the scores.

The template

Let dd be even and let ωi=10000−2i/d\omega_i = 10000^{-2i/d} for i=0,…,d/2−1i = 0, \ldots, d/2 - 1. Coordinates are numbered from 0, as in the paper.

PE(pos)2i=sin⁡(pos⋅ωi),PE(pos)2i+1=cos⁡(pos⋅ωi).\mathrm{PE}(pos)_{2i} = \sin(pos \cdot \omega_i), \qquad \mathrm{PE}(pos)_{2i+1} = \cos(pos \cdot \omega_i).
  1. SINUSOIDAL-PE(pos, d) ▷ d even
  2. 1for i ← 0 to d/2 - 1 do
  3. 2ω_i ← 10000^(-2i/d)
  4. 3PE[2i] ← sin(pos · ω_i)
  5. 4PE[2i+1] ← cos(pos · ω_i)
  6. 5return PE

The input of the first layer at position pospos is d Expos+PE(pos)\sqrt{d}\, E_{x_{pos}} + \mathrm{PE}(pos), the scaled token embedding plus the encoding.

The linear shift (theorem). For every offset kk there is a matrix MkM_k, independent of pospos, with PE(pos+k)=Mk PE(pos)\mathrm{PE}(pos + k) = M_k\, \mathrm{PE}(pos). By the angle-sum formulas, for each pair,

(sin⁡((pos+k)ωi)cos⁡((pos+k)ωi))=(cos⁡kωisin⁡kωi−sin⁡kωicos⁡kωi)(sin⁡pos ωicos⁡pos ωi),\begin{pmatrix} \sin((pos + k)\omega_i) \\ \cos((pos + k)\omega_i) \end{pmatrix} = \begin{pmatrix} \cos k\omega_i & \sin k\omega_i \\ -\sin k\omega_i & \cos k\omega_i \end{pmatrix} \begin{pmatrix} \sin pos\,\omega_i \\ \cos pos\,\omega_i \end{pmatrix},

so MkM_k is block diagonal with these rotation blocks. The full proof also shows the two corollaries below.

Distance in the dot product (theorem). PE(p)⋅PE(p+k)=∑icos⁡(kωi)\mathrm{PE}(p) \cdot \mathrm{PE}(p + k) = \sum_i \cos(k \omega_i), which depends only on kk, and ∥PE(p)∥=d/2\lVert \mathrm{PE}(p) \rVert = \sqrt{d/2} for every pp. The linear maps of attention act on the sum of the token embedding and the encoding, so in a trained model the score of two positions depends on both their contents and their absolute positions, not on the offset alone.

Cost. Θ(d)\Theta(d) per position, Θ(nd)\Theta(n d) for a sequence; in practice the n×dn \times d table is computed once.

Classic examples

The original transformer. Vaswani and colleagues added the encoding to the embeddings in both stacks of the transformer for translation. Learned position vectors gave nearly the same BLEU (Table 3, row E, a measurement); they chose the sinusoid because it may extrapolate to longer sequences.

A small table. With d=4d = 4 the frequencies are ω0=1\omega_0 = 1 and ω1=10000−1/2=0.01\omega_1 = 10000^{-1/2} = 0.01:

pospos sin⁡pos\sin pos cos⁡pos\cos pos sin⁡0.01pos\sin 0.01 pos cos⁡0.01pos\cos 0.01 pos
0 0 1 0 1
1 0.841471 0.540302 0.010000 0.999950
2 0.909297 -0.416147 0.019999 0.999800
3 0.141120 -0.989992 0.029996 0.999550

The first pair changes fast and the second slowly. PE(1)⋅PE(2)=cos⁡1+cos⁡0.01=1.540252\mathrm{PE}(1) \cdot \mathrm{PE}(2) = \cos 1 + \cos 0.01 = 1.540252, and every pair of positions at distance 1 gives the same value. At distance 2 the value is cos⁡2+cos⁡0.02=0.583653\cos 2 + \cos 0.02 = 0.583653.

The same rotation inside attention. Rotary position embedding uses the same frequencies and the same 2 by 2 rotations, but applies them to the queries and keys instead of adding them to the input, so that the score depends only on the offset.

Learned positions instead. BERT and GPT-2 learn one vector per position up to a maximum length. This is as cheap at run time, but gives nothing for positions beyond that length.

Relative sinusoids in speech. The Conformer speech encoder uses a relative form of the sinusoidal encoding inside its self-attention modules.

Variations

  • Halves instead of pairs. Many code bases put all sines in the first half of the vector and all cosines in the second. This is a fixed permutation of the coordinates and has the same properties.
  • Another base. The constant 10000 sets the longest wavelength. A larger base suits longer sequences.
  • Concatenation instead of addition. Appending the encoding keeps it apart from the content at the cost of a wider input.
  • Positions from 1. The paper numbers positions from 0. Starting from 1 only shifts every vector by M1M_1.
  • Learned absolute positions. A table of L×dL \times d learned vectors, as in BERT and GPT-2.
  • Relative methods. RoPE and ALiBi put the offset into the scores directly.

Pitfalls

  • Layout mismatch. Mixing the interleaved layout (sine at 2i2i, cosine at 2i+12i + 1) with the layout in halves, for example when loading weights from another code base, silently gives wrong inputs. Use the layout the model was trained with.
  • Off-by-one positions. Training with positions from 0 and running with positions from 1 shifts every encoding. Fix one convention.
  • Expecting length extrapolation. The encoding is defined for any position, but Press and colleagues measured that models trained with it get much worse soon after the training length (a measurement). Do not rely on it for inputs much longer than the training data; use ALiBi or train on longer inputs.
  • Odd dd. The formula needs pairs; with an odd size, one coordinate has no partner.
  • Scale of the embeddings. The original multiplies the token embeddings by d\sqrt{d} before the sum. Without it, small embeddings can be swamped by the encoding, whose coordinates are of size 1.

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.

sinusoidal_positional_encoding.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sinusoidal-positional-encoding/. The authors are listed in prov/D6ZPH5.jsonl.

"""The sinusoidal positional encoding of Vaswani et al. (2017).

For an even size d and i = 0, ..., d/2 - 1, with omega_i = base^(-2i/d):

    PE(pos)[2i]     = sin(pos * omega_i)
    PE(pos)[2i + 1] = cos(pos * omega_i)

Coordinates are numbered from 0, as in the paper. The paper also numbers
positions from 0; any integer or real pos is accepted here.

shift_matrix(k, d) is the d x d matrix with PE(pos + k) = shift_matrix(k, d) PE(pos)
for every pos: a block-diagonal matrix of 2 x 2 rotations by k * omega_i.

Precondition: d is even and positive, base > 1.
Cost: Theta(d) operations for one position, Theta(n d) for n positions,
Theta(d^2) to build the shift matrix (only the 2 x 2 blocks are non-zero).
"""

import math
from typing import List

Vector = List[float]
Matrix = List[List[float]]


def _check(d: int, base: float) -> None:
    if d <= 0 or d % 2:
        raise ValueError("d must be even and positive")
    if not base > 1:
        raise ValueError("the base must be greater than 1")


def frequencies(d: int, base: float = 10000.0) -> Vector:
    """The d/2 angular frequencies omega_i = base^(-2i/d), from 1 down to base^(-(d-2)/d)."""
    _check(d, base)
    return [base ** (-2 * i / d) for i in range(d // 2)]


def positional_encoding(pos: float, d: int, base: float = 10000.0) -> Vector:
    """The encoding vector PE(pos) of size d."""
    _check(d, base)
    pe = [0.0] * d
    for i in range(d // 2):  # @line L1
        omega = base ** (-2 * i / d)  # @line L2
        pe[2 * i] = math.sin(pos * omega)  # @line L3
        pe[2 * i + 1] = math.cos(pos * omega)  # @line L4
    return pe  # @line L5


def encoding_matrix(n: int, d: int, start: int = 0, base: float = 10000.0) -> Matrix:
    """The n x d matrix whose row t is PE(start + t)."""
    return [positional_encoding(start + t, d, base) for t in range(n)]


def shift_matrix(k: float, d: int, base: float = 10000.0) -> Matrix:
    """The d x d matrix M_k with PE(pos + k) = M_k PE(pos); it does not depend on pos."""
    _check(d, base)
    m = [[0.0] * d for _ in range(d)]
    for i, omega in enumerate(frequencies(d, base)):
        c, s = math.cos(k * omega), math.sin(k * omega)
        m[2 * i][2 * i], m[2 * i][2 * i + 1] = c, s
        m[2 * i + 1][2 * i], m[2 * i + 1][2 * i + 1] = -s, c
    return m
test_sinusoidal_positional_encoding.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sinusoidal-positional-encoding/. The authors are listed in prov/D6ZPH5.jsonl.

import cmath
import math
import random

import pytest

from sinusoidal_positional_encoding import encoding_matrix, frequencies, positional_encoding, shift_matrix


def matvec(m, v):
    return [sum(a * b for a, b in zip(row, v)) for row in m]


def dot(u, v):
    return sum(a * b for a, b in zip(u, v))


def test_worked_example():
    assert [round(x, 6) for x in positional_encoding(1, 4)] == [0.841471, 0.540302, 0.01, 0.99995]
    assert [round(x, 6) for x in positional_encoding(2, 4)] == [0.909297, -0.416147, 0.019999, 0.9998]
    assert positional_encoding(0, 4) == [0.0, 1.0, 0.0, 1.0]
    assert round(dot(positional_encoding(1, 4), positional_encoding(2, 4)), 6) == 1.540252


@pytest.mark.parametrize("seed", range(10))
def test_against_complex_exponential(seed):
    rng = random.Random(seed)
    d = 2 * rng.randint(1, 16)
    pos = rng.randint(0, 5000)
    pe = positional_encoding(pos, d)
    for i in range(d // 2):
        z = cmath.exp(1j * pos / 10000 ** (2 * i / d))
        assert pe[2 * i] == pytest.approx(z.imag, abs=1e-9)
        assert pe[2 * i + 1] == pytest.approx(z.real, abs=1e-9)


@pytest.mark.parametrize("seed", range(10))
def test_shift_is_linear_and_independent_of_position(seed):
    rng = random.Random(100 + seed)
    d = 2 * rng.randint(1, 10)
    k = rng.randint(-50, 50)
    mk = shift_matrix(k, d)
    for _ in range(5):
        pos = rng.randint(0, 1000)
        got = matvec(mk, positional_encoding(pos, d))
        want = positional_encoding(pos + k, d)
        assert all(abs(a - b) < 1e-9 for a, b in zip(got, want))


@pytest.mark.parametrize("seed", range(10))
def test_dot_product_depends_only_on_offset(seed):
    rng = random.Random(200 + seed)
    d = 2 * rng.randint(1, 10)
    k = rng.randint(0, 40)
    want = sum(math.cos(k * w) for w in frequencies(d))
    for _ in range(5):
        p = rng.randint(0, 2000)
        assert dot(positional_encoding(p, d), positional_encoding(p + k, d)) == pytest.approx(want, abs=1e-9)


def test_norm_and_frequencies():
    d = 16
    for p in (0, 3, 999):
        assert math.sqrt(dot(positional_encoding(p, d), positional_encoding(p, d))) == pytest.approx(math.sqrt(d / 2))
    w = frequencies(d)
    assert w[0] == 1.0
    ratios = [w[i + 1] / w[i] for i in range(len(w) - 1)]
    assert all(r == pytest.approx(10000 ** (-2 / d)) for r in ratios)
    assert 2 * math.pi / w[-1] < 10000 * 2 * math.pi


def test_matrix_and_errors():
    m = encoding_matrix(3, 4, start=1)
    assert m[0] == positional_encoding(1, 4)
    assert len(m) == 3
    with pytest.raises(ValueError):
        positional_encoding(1, 3)
    with pytest.raises(ValueError):
        positional_encoding(1, 4, base=1.0)

Exercises

  1. Prove the angle-sum identity for MkM_k and show that MkM_k is orthogonal, Mk⊤Mk=IM_k^\top M_k = I, and that MkMl=Mk+lM_{k} M_{l} = M_{k + l}.
  2. Show that PE(p)⋅PE(q)=∑icos⁡((q−p)ωi)\mathrm{PE}(p) \cdot \mathrm{PE}(q) = \sum_i \cos((q - p)\omega_i) and that it is symmetric in pp and qq. What does this say about telling "before" from "after" with the dot product alone?
  3. For d=512d = 512, compute the shortest and longest wavelengths 2π/ωi2\pi/\omega_i. Use the pair with ω0=1\omega_0 = 1 and the fact that π\pi is irrational to show that two different integer positions never get the same vector.
  4. Show that the layout in halves is P PE(pos)P\, \mathrm{PE}(pos) for a permutation matrix PP, and that the shift property still holds with PMkP⊤P M_k P^\top.
  5. Let WQW^Q and WKW^K be the attention maps. Write the score of tokens xx at pp and yy at qq as four terms and show which ones depend on pp and qq separately and not only on q−pq - p.
Proof: SINUSOIDAL-PE computes the formula, PE(pos + k) = M_k PE(pos) with a block rotation M_k that does not depend on pos, PE(p) . PE(p + k) depends only on k, and every PE vector has norm sqrt(d/2)full

We use the notation of the page. dd is even, ωi=10000−2i/d\omega_i = 10000^{-2i/d} for i=0,…,d/2−1i = 0, \ldots, d/2 - 1, and the encoding is PE(pos)2i=sin⁡(pos ωi)\mathrm{PE}(pos)_{2i} = \sin(pos\, \omega_i), PE(pos)2i+1=cos⁡(pos ωi)\mathrm{PE}(pos)_{2i+1} = \cos(pos\, \omega_i), for any real pospos.

Lemma 1 (the procedure). SINUSOIDAL-PE(pos,d)(pos, d) returns PE(pos)\mathrm{PE}(pos).

Proof. The loop at line L1 runs once for each i=0,…,d/2−1i = 0, \ldots, d/2 - 1. Line L2 sets ωi\omega_i, and lines L3 and L4 write coordinates 2i2i and 2i+12i + 1 by the formula. The pairs {2i,2i+1}\{2i, 2i + 1\} for different ii are disjoint and together are {0,…,d−1}\{0, \ldots, d - 1\}, so every coordinate is written exactly once. Line L5 returns the vector. □\square

For an angle θ\theta let

R(θ)=(cos⁡θsin⁡θ−sin⁡θcos⁡θ),ui(pos)=(sin⁡(pos ωi)cos⁡(pos ωi)),R(\theta) = \begin{pmatrix} \cos\theta & \sin\theta \\ -\sin\theta & \cos\theta \end{pmatrix}, \qquad u_i(pos) = \begin{pmatrix} \sin(pos\, \omega_i) \\ \cos(pos\, \omega_i) \end{pmatrix},

so that PE(pos)\mathrm{PE}(pos) is the stack of u0(pos),…,ud/2−1(pos)u_0(pos), \ldots, u_{d/2-1}(pos). Let MkM_k be the block-diagonal matrix with blocks R(kω0),…,R(kωd/2−1)R(k\omega_0), \ldots, R(k\omega_{d/2-1}).

Theorem 2 (linear shift). For all real pospos and kk, PE(pos+k)=Mk PE(pos)\mathrm{PE}(pos + k) = M_k\, \mathrm{PE}(pos).

Proof. Since MkM_k is block diagonal, it suffices to show ui(pos+k)=R(kωi) ui(pos)u_i(pos + k) = R(k\omega_i)\, u_i(pos) for each ii. Write a=pos ωia = pos\,\omega_i and b=kωib = k\omega_i. The angle-sum formulas give

sin⁡(a+b)=cos⁡bsin⁡a+sin⁡bcos⁡a,cos⁡(a+b)=−sin⁡bsin⁡a+cos⁡bcos⁡a,\sin(a + b) = \cos b \sin a + \sin b \cos a, \qquad \cos(a + b) = -\sin b \sin a + \cos b \cos a,

which are the two rows of R(b)R(b) applied to (sin⁡a,cos⁡a)⊤(\sin a, \cos a)^\top. And a+b=(pos+k)ωia + b = (pos + k)\omega_i. □\square

MkM_k depends on kk and on the frequencies only, not on pospos, which is the property stated in Section 3.5 of Vaswani and colleagues.

Lemma 3 (rotation blocks). R(θ)⊤R(θ)=IR(\theta)^\top R(\theta) = I and R(α)R(β)=R(α+β)R(\alpha) R(\beta) = R(\alpha + \beta). Hence Mk⊤Mk=IM_k^\top M_k = I and MkMl=Mk+lM_k M_l = M_{k+l}.

Proof. The columns of R(θ)R(\theta) are (cos⁡θ,−sin⁡θ)(\cos\theta, -\sin\theta) and (sin⁡θ,cos⁡θ)(\sin\theta, \cos\theta); each has length cos⁡2θ+sin⁡2θ=1\sqrt{\cos^2\theta + \sin^2\theta} = 1 and their dot product is cos⁡θsin⁡θ−sin⁡θcos⁡θ=0\cos\theta\sin\theta - \sin\theta\cos\theta = 0. Multiplying out R(α)R(β)R(\alpha) R(\beta) gives the entries cos⁡αcos⁡β−sin⁡αsin⁡β=cos⁡(α+β)\cos\alpha\cos\beta - \sin\alpha\sin\beta = \cos(\alpha + \beta) and cos⁡αsin⁡β+sin⁡αcos⁡β=sin⁡(α+β)\cos\alpha\sin\beta + \sin\alpha\cos\beta = \sin(\alpha + \beta) in the first row, and the second row follows in the same way. Block-diagonal matrices multiply block by block. □\square

Theorem 4 (distance in the dot product). For all real pp and kk,

PE(p)⋅PE(p+k)=∑i=0d/2−1cos⁡(kωi),∥PE(p)∥=d/2.\mathrm{PE}(p) \cdot \mathrm{PE}(p + k) = \sum_{i=0}^{d/2-1} \cos(k\omega_i), \qquad \lVert \mathrm{PE}(p) \rVert = \sqrt{d/2}.

Proof. For each ii, ui(p)⋅ui(p+k)=sin⁡(pωi)sin⁡((p+k)ωi)+cos⁡(pωi)cos⁡((p+k)ωi)=cos⁡((p+k)ωi−pωi)=cos⁡(kωi)u_i(p) \cdot u_i(p + k) = \sin(p\omega_i)\sin((p + k)\omega_i) + \cos(p\omega_i)\cos((p + k)\omega_i) = \cos((p + k)\omega_i - p\omega_i) = \cos(k\omega_i) by the formula cos⁡(x−y)=cos⁡xcos⁡y+sin⁡xsin⁡y\cos(x - y) = \cos x \cos y + \sin x \sin y. Summing over ii gives the first claim. With k=0k = 0 each term is cos⁡0=1\cos 0 = 1, so ∥PE(p)∥2=d/2\lVert \mathrm{PE}(p) \rVert^2 = d/2. ■\blacksquare

The dot product in Theorem 4 is the one between two encoding vectors. In a transformer the score is taken after the linear maps WQW^Q and WKW^K of the sum of the token embedding and the encoding, and (WQ)⊤WK(W^Q)^\top W^K is not in general a function of the rotations MkM_k, so the trained score is not a function of the offset alone. That is the gap that rotary position embedding closes.

References

  1. Vaswani et al. 2017, Section 3.5 (the formula, the geometric wavelengths from 2 pi to 10000 times 2 pi, the linear shift, learned embeddings as the alternative), Table 3 row (E)
  2. Press, Smith and Lewis 2022, the extrapolation experiments with the sinusoidal, rotary and T5 bias methods
  3. Simon J. D. Prince, Understanding Deep Learning, MIT Press 2023, Chapter 12 (Transformers)

Where this leads

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/D6ZPH5/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