Skip to the content

fatehi.devx2Learning

Deep learning

Position encoding

Attention alone does not see order; a vector that says where each token stands is added to its embedding.

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.

PE(pos,2i)=sin(pos100002i/d),PE(pos,2i+1)=cos(pos100002i/d)

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.

Each word’s embedding and the vector of its position, read off waves of growing wavelength, are added. “The” at position 0 and “the” at position 4 have the same embedding but different sums.

Test yourself

  1. 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.

  2. 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.

  3. 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