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

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.