Positional encoding
A method of giving a transformer information about the order of tokens, since self-attention alone treats its input as an unordered set.
Roadmap step 1 of 4: Tokens and embeddings. Try it: Transformer Explainer: tokenization and embedding ↗
What it is
Positional encoding injects information about where each token sits in a sequence into a model. Self-attention compares all tokens with each other without any built-in notion of order, so without it 'dog bites man' and 'man bites dog' would look the same. Encodings can be fixed mathematical patterns, learned vectors, or schemes that describe the relative distance between tokens.
Why it matters
The choice of positional scheme strongly affects how well a model handles long inputs and whether it can work on sequences longer than those seen in training. Many long-context improvements come from changing or rescaling the positional method. Builders who extend context windows or fine-tune models often need to understand which scheme a model uses.
How it works
In the original approach, a vector for each position, either sinusoidal or learned, is added to the token embeddings before the first layer. Relative methods instead modify the attention computation so that the score between two tokens depends on their distance. Rotary embeddings, a popular example, rotate query and key vectors by an angle that depends on position, so their dot product reflects relative offset. Other methods add a distance-based bias directly to attention scores.