On the path Attention paperAttention alone does not know word order; the paper adds sine and cosine waves to say where each word stands.
Attention does not see order
Attention compares every position with every other, but nothing in it says which came first. Shuffle the words of a sentence and each word gets the same new vector as before, only in a different place: “dog bites man” and “man bites dog” would look alike. So the model is told the order separately: each position gets a vector of its own, and it is added to the token’s embedding before the first layer.
Waves of many lengths
One way is to learn a vector for each position, like a second embedding table. Another needs no learning: build the vector of position pos from sines and cosines of many wavelengths, two numbers per wavelength.
pos is the position, 0, 1, 2, …; i runs from 0 to d/2 − 1, so the vector has d numbers, the even ones sines and the odd ones cosines. The first pair turns fastest, with a wavelength of 2π positions; each next pair turns more slowly, up to a wavelength of 10000 · 2π.
Like the hands of a clock, the fast pairs tell neighbouring positions apart and the slow ones tell far-apart regions apart, so every position gets a different vector. And moving k positions along turns each pair by a fixed angle, the same wherever one starts, so “k places earlier” is a fixed linear map that a layer can learn.
On the path Attention paper
In the paper. The Transformer uses these sines and cosines (section 3.5), with d = 512, added to the embeddings at the bottom of both stacks; dropout (rate 0.1) is applied to the sums. The paper also tried learned position vectors and found nearly the same quality (table 3, row E: 25.7 BLEU against 25.8). It kept the sinusoids because they might let the model handle sentences longer than any it saw in training. Later models moved to other schemes, such as rotating the queries and keys by the position (RoPE).
Test yourself
Why does a Transformer need position encoding at all?
Attention treats its inputs as a set: shuffling them only shuffles its outputs. Without a position signal the model could not tell word orders apart.
Why are many wavelengths used rather than one?
A single fast wave repeats and would give distant positions the same value; a single slow wave barely changes between neighbours. Together, fast and slow waves give every position a distinct vector, like the hands of a clock.
What did the paper find when it learned the position vectors instead?
Nearly the same quality (25.7 against 25.8 BLEU); it kept the sinusoids in the hope that they would carry over to longer sentences.
Where it leads
Kept in this browser only, never sent.
Paths through it
- Attention paperstep 8 of 17Follow this path