Attention Is All You Need · Section 3.5

3.5 Positional encoding

Attention cannot see word order, so the paper adds to every embedding a pattern of sine and cosine waves that says where the token 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.

What this section says

Attention compares every word with every word, and nothing in that comparison depends on where the words stand: shuffle the sentence and each word gets the same vector as before. Recurrent networks know the order because they read it step by step; convolutions know it because their windows slide along it. The Transformer has neither, so it must be told. It adds a positional encoding, a vector of d_model numbers that depends only on the position, to each token's embedding, at the bottom of both stacks.

PE_{(pos,\,2i)} = \sin\!\left(pos / 10000^{2i/d_{\text{model}}}\right), \qquad PE_{(pos,\,2i+1)} = \cos\!\left(pos / 10000^{2i/d_{\text{model}}}\right)

Each pair of numbers, 2i and 2i + 1, is a sine and a cosine wave over the positions. The first pair repeats every 2π ≈ 6.3 positions, and each further pair is slower, up to 10000 · 2π positions for the last: like the hands of a clock, the fast pairs tell neighbouring positions apart and the slow ones tell far-apart positions apart.

The paper chose waves for a reason it states as a hope: moving k positions further turns every pair by the same angle, so PE of pos + k is a fixed linear function of PE of pos, which should make attending by relative position easy to learn (the last scene of the clip). It also tried positions the model learns, one vector per position, and found nearly identical results; it kept the waves because they might work for sentences longer than any seen in training.

In the paper's words

“Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence.”

Section 3.5 In plain words: Attention alone cannot see word order, so the model must be told where each token stands.

“We also experimented with using learned positional embeddings [9] instead, and found that the two versions produced nearly identical results (see Table 3 row (E)).”

Section 3.5 In plain words: Positions the model learns for itself worked about as well as the sine waves (Table 3, row E).

“We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.”

Section 3.5 In plain words: The sine waves were chosen because they might work for sentences longer than any seen in training.

Quoted from Vaswani et al., Attention Is All You Need, arXiv:1706.03762v7(opens in a new tab). The figures on this page are redrawn, not copied.

The notation

The symbols of this section, in the paper and in our model
Symbol Meaning In the paper Our miniature
\(pos\) the token's position in the sentence, from 0 any 0 to 31
\(i\) which pair of numbers: dimensions 2i and 2i + 1 0 to 255 0 to 31
\(d_{\text{model}}\) numbers in the encoding, the same as the embedding, so the two can be added 512 64
\(10000\) sets the slowest wave: wavelengths run from 2π to 10000 · 2π 10000 10000
\(k\) an offset: PE of pos + k is a linear function of PE of pos any any

Try it

The positional encoding explorer

Attention treats a sentence as a set of words: shuffle them and every score stays the same. So the paper adds to each word a pattern that says where it stands, made of sine and cosine waves of many speeds. Here is that pattern, wave by wave.

The sinusoidal positional encoding for positions 0 to 50 minus one (rows) and 64 dimensions (columns): orange for positive values, blue for negative; the left columns change quickly from row to row, the right ones slowly.
Rows: positions 0 to 49, top to bottom. Columns: the 64 dimensions, left to right. Orange is positive, blue negative, dark is near 0.

One pair of dimensions

Dimensions 4 (sine) and 5 (cosine) over positions 0 to 49 One full wave takes 11.2 positions. −1 −0.5 0 0.5 1 0 10 20 30 40 position value
  • sin · 4
  • cos · 5

One full wave takes 11.2 positions.

Two positions compared

Cosine similarity of position 10 with every position Positions 10 and 14: dot product 23.93, cosine similarity 0.748. 0 0.2 0.4 0.6 0.8 1 0 10 20 30 40 position similarity 14

Positions 10 and 14: dot product 23.93, cosine similarity 0.748.

How to read it

Each row of the grid is one position, each column one of the vector's dimensions; orange is positive, blue negative. The first columns change colour at every row: fast waves that tell neighbours apart. The columns further right change slowly: waves that tell the start of a long text from its end. Together they give every position its own pattern.

Compare two positions: their similarity depends only on how far apart they are, not on where they sit, and it falls as they move apart. That is the property the paper chose the sines for: a fixed offset is the same rotation wherever it happens, so the model can learn “the word two places back” once.

In the paper (3.5)

PE(pos, 2i) = sin(pos / 10000^(2i/d_model)), PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))

pos is the position, i the pair of dimensions, d_model the vector's length (512 in the paper, 64 in our model). The paper also tried positions learned in training instead, and found nearly identical results (its Table 3, row E). We reran that on our model: learned positions reach 95 % of held-out sentences at about the same step as the sines, and end at the same quality. Table 3 explorer

On its own page: Positional encoding explorer

The waves as a grid of colours, one row per position and one column per dimension, for d_model 64 or 512; pick a wave to see it on its own, and two positions to see how alike their encodings are as they move apart.

How our miniature differs

We reran the paper's Table 3 row E on our miniature, three seeds each: with learned positions the model first translated 95 % of the held-out sentences at step 193 on average, with sines at step 187. About the same, as the paper found. Our training sentences have at most 10 tokens, and we have not tested either kind of position on longer ones.

Prepared in the Course by

Check yourself

Three questions a reader of this section should now be able to answer. The lab checks your answer against the paper and our models.

Why positions

Why does the Transformer need positional encodings at all?

Position 0

What is the value of dimension 1 of the positional encoding at position 0, \(\cos(0)\)?

Your answer
A whole number

Our row E

On our miniature, how did learned positions compare with sines, measured by the step at which each first translated 95 % of the held-out sentences?

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.