Positional encoding

Embedding · node type · Add

Adds a position-dependent vector to each token so attention can tell first from last.

Also called Position embedding, Sinusoidal encoding, Learned positions

Figure 1. The typed ports of Positional encoding, in the same format as every model drawing. Letters such as N or C stand for any size.

What it does

Attention by itself treats its input as an unordered set: shuffling the tokens shuffles the output in the same way. A positional encoding fixes that by adding a different vector to each position. The original transformer used fixed sine and cosine waves of different frequencies, which lets relative offsets be expressed as simple linear maps. BERT and ViT instead learn one vector per position, stored as a table and added with an Add. Vision transformers add one vector per image patch plus one for the class token.

Formula

yt = xt + ptsinusoidal: pt,2i = sin(t / 100002i/D), pt,2i+1 = cos(t / 100002i/D)

Shapes and parameters

Shapes
Input [N, T, D], table [T_max, D] (the first T rows are used); output [N, T, D].
Parameters
None for sinusoidal encodings. A learned table has T_max × D: 512 × 768 = 393,216 for BERT, 197 × 192 = 37,824 for a tiny ViT.
Used for
BERT-style text encoders, ViT and CLIP image encoders, translation models.

In WeightSpace

Read-only in WeightSpace today.

Where it appears

No model in WeightSpace uses Positional encoding yet; it is here as a reference for how the others work.