Lessons › Chapter 11: Transformers and LLMs
Positional encoding
“Dog bites man” is ordinary. “Man bites dog” is news. Same three words, different order, different meaning.
Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.
Start the interactive lessonStep by step
Order matters
“Move money from savings to current” is not the same request as “from current to savings”.
Order changes meaning
“Dog bites man” is ordinary. “Man bites dog” is news. Same three words, different order, different meaning.
Attention ignores order
Attention compares every token with every other token. Shuffle the words and each token still sees the same set of others. On its own, attention treats a sentence like a bag of words.
Stamp each position
positional encoding adds a unique pattern for each position: waves of different speeds, read off at that spot. Position 1 gets one pattern, position 2 another. These are added to each word’s embedding.
Now order is visible
“dog” in position 1 now looks different from “dog” in position 3, so the model can tell who bit whom. Newer models use variations (like rotating vectors by position), but the goal is the same.
In real life: following a recipe
“Whisk the eggs, then add the flour” is not the same as “add the flour, then whisk the eggs”. When an assistant reads instructions, code or directions, the order of the words carries as much meaning as the words themselves.
Quick check: Why do transformers need positional information?
- Attention on its own ignores word order (correct)
- To make tokens shorter
- To translate between languages
Without position signals, shuffling words wouldn’t change what attention sees.
Pseudocode
attention on its own sees a bag of words: order is lost "dog bites man" and "man bites dog" would look the same position_signal(p) = waves of different speeds, read at position p input(token) = embedding(word) + position_signal(position)
Key terms
- positional encoding
- Extra numbers added to each token that tell the model where it sits in the sentence.
In the news
Recent models and papers that build on this idea: