Skip to content

Transformer Positional Encoding Worked by Hand

2026-11-13

A Transformer adds a position vector to each token embedding because attention alone does not know the order of the sequence. Vaswani et al. build that vector from sines and cosines: PE(pos, 2i) = sin(pos / 10000^(2i/d_model)) and PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model)), where pos is the position and i is the dimension pair.

Each dimension is a sinusoid, and the wavelengths form a geometric progression from 2π to 10000 · 2π. The authors chose it because they hypothesized it would let the model learn to attend by relative position: for a fixed offset k, PE(pos+k) is a linear function of PE(pos). They also tried learned positional embeddings and found nearly identical results.

Try it by hand. Use d_model = 8, far smaller than the paper's 512, so there are four sine-cosine pairs with angular frequencies 1, 0.1, 0.01 and 0.001. Position 0 gives [0, 1, 0, 1, 0, 1, 0, 1]. Position 1 gives [0.8415, 0.5403, 0.0998, 0.9950, 0.0100, 1.0000, 0.0010, 1.0000]. Position 2 gives [0.9093, −0.4161, 0.1987, 0.9801, 0.0200, 0.9998, 0.0020, 1.0000]. The first pair turns one radian per position and separates neighbors; the last changes much more gradually across positions.

The linear-function claim is a rotation. Within a pair, moving by k positions rotates (sin, cos) by the angle ω·k. Check: sin 2 = 2 · sin 1 · cos 1 = 2 · 0.8415 · 0.5403 = 0.9093.

Vaswani et al., NIPS 2017, §3.5