Positional Encoding
Attention cannot see order on its own. Sinusoids, rotary embeddings and biases, and why RoPE leaves only relative position in the score.
Jump to a section
Attention cannot see order on its own
Feed "dog bites man" and "man bites dog" into a self-attention layer with no positional signal and you get the same three output vectors, just listed in a different order. Each token's output depends on its own query and on the set of keys and values around it, and both sentences contain the same set.
That property is permutation equivariance: shuffle the inputs and the outputs shuffle the same way. It holds for unmasked attention. A causal mask breaks it, since position sees exactly tokens, but an encoder has no such mask.
So position has to be supplied. There are two broad routes. Absolute encodings, sinusoidal or learned, change the input vectors before the first layer. Relative methods change the attention score itself, either by rotating queries and keys (RoPE) or by adding a bias that depends on distance (ALiBi, T5).
Sinusoids at many wavelengths
The original Transformer adds a fixed vector to each token embedding. For position and pair index in a model of width :
Each pair of dimensions is one sinusoid. Its wavelength is , growing geometrically from for the first pair to just under for the last. In the base model, , the fastest pair repeats about every 6.3 positions and the slowest about every 60,600. The fast pairs locate a token precisely; the slow ones say roughly where in the sequence it is.
The paper chose this design for one property. For any fixed offset , is a linear function of : each pair rotates by an angle that depends on but not on . The authors' reasoning was that a layer could then learn to attend by relative distance with one fixed linear map, whatever the absolute positions are.
The encoding is added, not concatenated. Adding keeps the width at 512 and lets each dimension carry content and position at once; concatenating would also work, but it widens the input and every projection that reads it.
Learned absolute embeddings replace the formula with a trained table, one vector per position. BERT has 512 rows and GPT-2 has 1,024. The table is simple and works well inside its range, but position 1,025 in GPT-2 has no row at all, and extending the table means training the new rows.
Rotating queries and keys
RoPE takes the other route. Instead of adding anything to the embeddings, it rotates each query and key in every layer by an angle proportional to its position. A head of width is split into coordinate pairs, and pair at position is rotated by , with in the original paper.
Take one pair, a query at position and a key at position . Rotation matrices compose by adding angles and , so
The absolute positions cancel. Only the offset enters the score, combined with the content of and .
Llama 3 uses RoPE with a head dimension of 128, so each head has 64 rotary pairs, and it raises the base from 10,000 to 500,000. The paper ties the change to supporting longer contexts, and the arithmetic shows what it does. A larger base slows every pair except the first. With base 10,000 the slowest pair repeats every 54,000 tokens or so; with 500,000 it repeats every 2.6 million, so the slow pairs still tell apart positions far beyond a 128K context.
What the invariance does and does not say
The cancellation above is exact for one pair, with fixed unrotated vectors and fixed frequencies. Move both positions by the same amount and the rotated coordinates change, but their dot product does not. That is a clean test for a RoPE implementation: if shifting both indices changes the score, the rotation or the indexing is wrong.
It is not a statement about the whole model. Insert text before a sentence and the hidden states that produce and change, because the context, the mask and every earlier attention calculation have changed. The score is relative in its positional part, not a function of distance alone.
Nor does similarity fall steadily with distance. One pair's contribution oscillates as the offset grows. Long-context behaviour comes from many frequencies, trained representations, and any frequency scaling applied after training, and the only way to know how a model handles long inputs is to evaluate it on them.
Biases instead of rotations
ALiBi skips position vectors entirely. Each head adds a penalty to its attention scores that grows linearly with the distance between query and key, with a different slope per head. BLOOM and MPT use it. The bias is defined at any distance, and the paper was titled "Train Short, Test Long" for its extrapolation results, but generalization beyond the training length is still something to measure on your own model.
T5 also adds a bias to the scores, but a learned one: offsets are grouped into buckets, exact for small distances and logarithmic for large ones, and each bucket has a learned scalar per head. See T5 relative position bias for the bucket arithmetic.
In code
The sinusoidal table in PyTorch, added to token embeddings:
1import torch
2from torch import Tensor
3
4
5def sinusoidal_encoding(seq_len: int, d_model: int) -> Tensor:
6 if d_model <= 0 or d_model % 2:
7 raise ValueError("This paired sine/cosine implementation needs positive even d_model")
8 pos = torch.arange(seq_len).unsqueeze(1) # (seq, 1)
9 i = torch.arange(0, d_model, 2) # even indices
10 div = torch.exp(i * (-torch.log(torch.tensor(10000.0)) / d_model))
11 pe = torch.zeros(seq_len, d_model)
12 pe[:, 0::2] = torch.sin(pos * div) # even dims -> sin
13 pe[:, 1::2] = torch.cos(pos * div) # odd dims -> cos
14 return pe
15
16
17pe = sinusoidal_encoding(seq_len=50, d_model=128)
18tokens = torch.randn(50, 128)
19position_aware = tokens + pe # add, don't concat
20assert pe.shape == (50, 128)Both relative-position claims, checked in plain Python for a single pair:
1import math
2
3
4def rotate(v, angle):
5 c, s = math.cos(angle), math.sin(angle)
6 return (v[0] * c - v[1] * s, v[0] * s + v[1] * c)
7
8
9def rope_score(q, k, m, n, theta=0.25):
10 qr, kr = rotate(q, m * theta), rotate(k, n * theta)
11 return qr[0] * kr[0] + qr[1] * kr[1]
12
13
14q, k = (1.0, 0.5), (0.5, 1.0)
15base = rope_score(q, k, 3, 7)
16for shift in (1, 10, 1000):
17 assert abs(rope_score(q, k, 3 + shift, 7 + shift) - base) < 1e-9 # same offset, same score
18assert abs(rope_score(q, k, 3, 8) - base) > 1e-3 # new offset, new score
19
20# Sinusoidal: PE(pos + k) is a fixed rotation of PE(pos), whatever pos is.
21w, k_off = 1 / 10000 ** (2 * 3 / 512), 5
22for pos in (0, 17, 4000):
23 s, c = math.sin(pos * w), math.cos(pos * w)
24 shifted = (s * math.cos(k_off * w) + c * math.sin(k_off * w),
25 -s * math.sin(k_off * w) + c * math.cos(k_off * w))
26 assert abs(shifted[0] - math.sin((pos + k_off) * w)) < 1e-9
27 assert abs(shifted[1] - math.cos((pos + k_off) * w)) < 1e-9Where it goes wrong
Running past the training length. Every scheme here except a learned table can compute an encoding for position 100,000. None of them guarantees good predictions there. RoPE models extended to longer contexts usually change the frequencies and train further, rather than relying on the formula alone.
Losing the offset during decoding. With a KV cache, the new token's query and key must be rotated by its true position in the sequence, not by 0 because the input tensor has length one. The output stays fluent and slowly loses track of order, so the bug survives casual testing.
Mixing pairing conventions. The RoFormer paper rotates adjacent coordinates , while many codebases pair dimension with . Both are valid, but weights trained under one convention give wrong scores under the other, so checkpoint converters have to permute the query and key projections.
Untrained rows in a learned table. A table allocated with more rows than the training sequences ever reached has rows that never received a gradient. Those positions exist but were never trained, so check results there before relying on them.
Sources and further reading
- Vaswani et al., Attention Is All You Need, §3.5: sinusoidal positions.
- Su et al., RoFormer: relative positional dependence through rotations.
- Press et al., Train Short, Test Long (ALiBi, 2021): linear distance biases on attention scores.
- Llama Team, The Llama 3 Herd of Models (2024): RoPE with a base frequency of 500,000.
Keep going
Ask your own question about Positional Encoding, or start a guided session on it: six short pages, from the big picture to code you can run.