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 of a sequence a fixed vector of size , made of sines and cosines of at 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 to . The main property is that a shift by a fixed offset is a linear map: , with a matrix of 2 by 2 rotations that does not depend on .
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 be even and let for . Coordinates are numbered from 0, as in the paper.
SINUSOIDAL-PE(pos, d) ▷ d even- 1
for i ← 0 to d/2 - 1 do - 2
ω_i ← 10000^(-2i/d) - 3
PE[2i] ← sin(pos · ω_i) - 4
PE[2i+1] ← cos(pos · ω_i) - 5
return PE
The input of the first layer at position is , the scaled token embedding plus the encoding.
The linear shift (theorem). For every offset there is a matrix , independent of , with . By the angle-sum formulas, for each pair,
so is block diagonal with these rotation blocks. The full proof also shows the two corollaries below.
Distance in the dot product (theorem). , which depends only on , and for every . 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. per position, for a sequence; in practice the 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 the frequencies are and :
| 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. , and every pair of positions at distance 1 gives the same value. At distance 2 the value is .
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 .
- Learned absolute positions. A table of 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 , cosine at ) 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 . The formula needs pairs; with an odd size, one coordinate has no partner.
- Scale of the embeddings. The original multiplies the token embeddings by 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.
# 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
- Prove the angle-sum identity for and show that is orthogonal, , and that .
- Show that and that it is symmetric in and . What does this say about telling "before" from "after" with the dot product alone?
- For , compute the shortest and longest wavelengths . Use the pair with and the fact that is irrational to show that two different integer positions never get the same vector.
- Show that the layout in halves is for a permutation matrix , and that the shift property still holds with .
- Let and be the attention maps. Write the score of tokens at and at as four terms and show which ones depend on and separately and not only on .
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. is even, for , and the encoding is , , for any real .
Lemma 1 (the procedure). SINUSOIDAL-PE returns .
Proof. The loop at line L1 runs once for each . Line L2 sets , and lines L3 and L4 write coordinates and by the formula. The pairs for different are disjoint and together are , so every coordinate is written exactly once. Line L5 returns the vector.
For an angle let
so that is the stack of . Let be the block-diagonal matrix with blocks .
Theorem 2 (linear shift). For all real and , .
Proof. Since is block diagonal, it suffices to show for each . Write and . The angle-sum formulas give
which are the two rows of applied to . And .
depends on and on the frequencies only, not on , which is the property stated in Section 3.5 of Vaswani and colleagues.
Lemma 3 (rotation blocks). and . Hence and .
Proof. The columns of are and ; each has length and their dot product is . Multiplying out gives the entries and in the first row, and the second row follows in the same way. Block-diagonal matrices multiply block by block.
Theorem 4 (distance in the dot product). For all real and ,
Proof. For each , by the formula . Summing over gives the first claim. With each term is , so .
The dot product in Theorem 4 is the one between two encoding vectors. In a transformer the score is taken after the linear maps and of the sum of the token embedding and the encoding, and is not in general a function of the rotations , so the trained score is not a function of the offset alone. That is the gap that rotary position embedding closes.
References
- 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)
- Press, Smith and Lewis 2022, the extrapolation experiments with the sinusoidal, rotary and T5 bias methods
- 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.
| 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 D6ZPH5 Edit this page History Report an error Markdown