Why does a transformer need positional encodings?
Sequence models and transformers, Positional encoding
Level L1 Beginner. Length One-liner. Nature Th Theoretical.
What's being asked
Whether you know that self-attention by itself ignores word order.
Key idea
Unlike a recurrent network that reads words one by one, self-attention looks at all words (tokens) in parallel and compares them based only on what they are, not where they sit. Without positional encodings—numbers added to each word's vector to mark its slot—the transformer treats a sentence as an unordered bag of words (the formal matrix proof of this permutation property comes later).
Steps
- Core answer: self-attention compares every word with every other word using only their contents, so shuffling the input order produces the exact same representations in a shuffled order.
- Example: without positional encodings, "dog bites man" and "man bites dog" contain the same words and get the same scores between pairs of words.
- Fix: adding a positional encoding vector to each word's input embedding gives the model a signal for word order.
Common mistakes
- Saying attention cannot see other words; it sees all of them at once, just not their order.
- Saying recurrent neural networks (RNNs) need positional encodings too; reading tokens one step at a time already gives them order.
How long your answer should be
One or two sentences; under 30 seconds.
Read this
Previous in Sequence models and transformers: In attention, what do the query, keys and values stand for, and how is the output a weighted average? If the attention weights over three values are , what is the output?
Next in Sequence models and transformers: What is the difference between the skip-gram and CBOW models of word2vec, and when would you prefer each?