Part B · Chapter 12 · Attention

12. Positions as sine waves

Attention on its own cannot tell “the dog sees the cat” from “the cat sees the dog”. The paper adds to every word a pattern of sine and cosine waves that says where it stands.

Where a word stands, as waves
Two orders
Playback speed

First, four pairs of the paper's position waves for our model's 64 numbers, from the fastest to the slowest, over the first 20 positions. Then the whole pattern as a grid, one row per position. Then the same words in two orders: without positions the encoder gives the repeated word exactly the same vector in both sentences; with them the vectors differ and so do the model's translations. Last, one pair of waves as a point on a circle: each step of one position turns it by the same angle.

The idea

Look again at chapter 9's formula. Nothing in it knows where a word stands: shuffle the words and every query, key, score and weight stays the same, only listed in another order. To attention a sentence is a bag of words. “The dog sees the cat” and “the cat sees the dog” would mean the same thing.

The paper's fix is to add to each word's vector a second vector that depends only on its place, a positional encoding. It is made of sine and cosine waves: the first numbers change quickly from one position to the next, the last ones very slowly, so every position gets its own pattern, like the hands of a clock that together tell the time.

Why waves rather than simply the numbers 1, 2, 3? They stay between −1 and 1 however long the text, and they have a neat property: moving k places along is the same turn of every wave pair, wherever you start. The model can learn “the word two places back” once, for every position.

A worked example: two orders

Run our encoder on “The dog sees the cat .” and “The cat sees the dog .” without the position vectors. The word “dog” ends up with exactly the same 64 numbers in both: the distance between its two vectors is 0.000. Add the positions, as the model was trained, and the distance is 6.08: the model now knows who sees whom, and translates “Der Hund sieht die Katze .” and “Die Katze sieht den Hund .”.

Position 3's first four numbers are sin(3) = 0.141, cos(3) = −0.990, sin(3 / 10000^(2/64)) = 0.778 and cos(3 / 10000^(2/64)) = −0.628. Those are added to the embedding of the fourth word, after the scaling of chapter 5.

The formula

PE_{(pos,\,2i)} = \sin\!\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right), \qquad PE_{(pos,\,2i+1)} = \cos\!\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right)
\(pos\)
the word's position: 0 for the first
\(i\)
the pair of dimensions: dimensions 2i and 2i + 1 share one wave, a sine and a cosine
\(10000^{2i/d_{\text{model}}}\)
how slow the pair's wave is: from one turn every 2π ≈ 6.3 positions for the first pair to one every 2π × 10000 for the last
\(d_{\text{model}}\)
the vector's length: 64 in our model, 512 in the paper

The encoding is added, not appended: the word's vector and its position share the same 64 numbers. The paper's model, and ours, then let training work out how to read both from the sum.

Why this is true: moving k places is a rotation

Take one pair of dimensions, with ω = 1 / 10000^(2i/d_model). At position p the pair is (sin ωp, cos ωp): a point on a circle of radius 1, at angle ωp.

At position p + k the angle is ωp + ωk. The angle-sum formulas say how sine and cosine change: both new values are fixed mixtures of the old ones, with weights cos ωk and sin ωk that depend only on k.

So moving k places is multiplying by the same 2 × 2 rotation matrix wherever p is. That is the property the paper names: for any fixed offset k, the encoding of position p + k “can be represented as a linear function” of the encoding of position p.

\begin{bmatrix} \sin \omega(p+k) \\ \cos \omega(p+k) \end{bmatrix} = \begin{bmatrix} \cos \omega k & \sin \omega k \\ -\sin \omega k & \cos \omega k \end{bmatrix} \begin{bmatrix} \sin \omega p \\ \cos \omega p \end{bmatrix}

Why it matters

Positions are part of why a model has a context window. Our GPT-style model learns one position vector per place instead of using waves, and it has exactly 32 of them: one token more and it cannot read it at all. Today's large models use other position schemes, but every one of them is trained up to some length, and quality past that length is not guaranteed; a provider's context limit reflects that as well as the cost of attention.

Where it fails

Sines are not clearly better than learned positions. The paper tried learned position vectors and found “nearly identical results”. We reran that on our model over three seeds: learned positions reach 95 % of the held-out sentences at about step 193 on average, the sines at about step 187. On our task the choice hardly matters.

Longer than trained is untested. The paper chose sines partly because they “may allow the model to extrapolate to sequence lengths longer than the ones encountered during training”. Our model trained on sentences of at most ten words; beyond that, nothing promises it works.

Adding mixes position into meaning. The same 64 numbers carry both the word and its place, so each layer has to keep them apart; later designs encode positions in other ways for that reason.

Remember Attention alone sees a sentence as a bag of words. The paper adds to each word sine and cosine waves of many speeds that depend only on its position; moving k places turns every wave pair by the same angle.

Exercises

Try each one before you open a hint. The lab's engine checks your answer against the same models the chapter uses.

The first number of position 1

The first dimension of the encoding is sin(pos). What is it at position 1? Three decimals.

Your answer
Within 0.002 of the answer

The second number of position 2

The second dimension is cos(pos). What is it at position 2? Three decimals.

Your answer
Within 0.002 of the answer

The fastest wave

After how many positions does the first pair's wave repeat? Two decimals.

Your answer
Within 0.01 of the answer

Without positions

Without the position vectors, does our encoder give “dog” the same vector in “The dog sees the cat .” and “The cat sees the dog .”?

In the paper

Section 3.5 gives the formula above, says the authors chose it because “for any fixed offset k, \(PE_{pos+k}\) can be represented as a linear function of \(PE_{pos}\)”, and reports that learned positional embeddings “produced nearly identical results (see Table 3 row (E))”. The Theory tab will rerun row E with you.

In the paper: section 3.5

Open the Theory tab
An unhandled error has occurred. Reload 🗙

Reconnecting…

Your connection to the Transformers and Attention Lab dropped, probably a Wi-Fi blip. Hold on while it reconnects.

The connection could not be restored. The page will reload in a few seconds.