How do sinusoidal positional encodings convey token positions?
Last updated
Each position is mapped to a vector of sines and cosines at geometrically spaced frequencies, much like a continuous binary counter. Fast dimensions encode fine position and slow dimensions encode coarse position. The vector is added to the token embedding.
Formula:
PE(pos, 2i) = sin(pos / 10000^(2i/d))PE(pos, 2i+1) = cos(pos / 10000^(2i/d))Wavelengths range from 2π up to about 10000·2π.
Multi-scale uniqueness:
High-frequency pairs change sharply between neighbouring tokens, while low-frequency pairs change slowly across the sequence.
Together they give each position a distinct, bounded fingerprint in [-1, 1].
Relative offsets are linear:
Each (sin, cos) pair is a point on a circle, so moving by k positions is a fixed rotation that depends only on k.
This lets attention learn offset-based patterns. The dot product
PE(p)·PE(p+k)depends only on k and tends to decay as k grows.
Limitation: adding the encoding mixes position with content, so the model must disentangle the two. RoPE builds on the same frequencies but applies them as rotations instead.
[lang:python]
pos = torch.arange(L)[:, None]
i = torch.arange(0, d, 2)
angle = pos / 10000 ** (i / d)
pe = torch.zeros(L, d)
pe[:, 0::2], pe[:, 1::2] = torch.sin(angle), torch.cos(angle)
x = tok_emb + pe