“The dog bit the man” and “The man bit the dog” contain exactly the same words, but mean very different things. Word order matters. Self-attention, however, has a surprising blind spot: on its own, it cannot tell these two sentences apart.
This reading explains why, and how Transformers fix it by adding a positional encoding to each word vector. We will build up the classic sinusoidal positional encoding step by step: first what we want from it, then a single rotating point on a circle, then many rotations at different speeds, and finally why this design helps attention reason about distance.
1Self-attention ignores word order
Recall how self-attention computes the output for word $i$: it compares $q_i$ with every key $k_j$, turns the scores into weights $\hat\alpha_{i,j}$ with a softmax, and returns $z_i=\sum_j \hat\alpha_{i,j} v_j$. Look closely at what this depends on: the set of key and value vectors, and nothing about where each word sits. The sum $\sum_j$ gives the same answer in any order.
So if we swap two words, every word still sees exactly the same vectors. The output for each word stays the same; it just moves along with its word. To self-attention, a sentence is a bag of words.
2The fix: add a position vector
The idea is simple. For every position $pos=1,2,3,\dots$ we define a vector $PE(pos)$ with the same dimension $d$ as the word vectors, and add it to the word vector at that position:
$$x_{pos} \;\leftarrow\; x_{pos} + PE(pos).$$Now the input at position 2 is “word + position 2”. If like and cats swap places, cats receives $PE(2)$ and like receives $PE(3)$, so the inputs are different and self-attention can tell the two sentences apart.
What should $PE(pos)$ look like?
We want an encoding with these properties:
- Unique: every position gets a different vector.
- Closer positions, more similar encodings: $PE(5)$ should be more similar to $PE(6)$ than to $PE(40)$.
- Consistent steps: the relationship between neighboring positions should be the same everywhere, e.g., $PE(1)$ vs. $PE(2)$ should look like $PE(4)$ vs. $PE(5)$.
- Bounded, and independent of sentence length: values should not explode for long sentences, and position 7 should mean the same thing in a 10-word and a 100-word sentence.
Two naive ideas fail these tests:
| Idea | Problem |
|---|---|
| $PE(pos)=pos$ (add the number) | Unbounded: at position 500 the position swamps the word vector. |
| $PE(pos)=pos/n$ for an $n$-word sentence | Depends on length: position 5 is $0.5$ in a 10-word sentence but $0.05$ in a 100-word sentence. |
3One frequency: a point on a circle
Here is a bounded idea: represent each position as a point on the unit circle, rotating by a fixed angle $\omega$ per position:
$$PE(pos) = \big[\,\sin(pos\cdot\omega),\; \cos(pos\cdot\omega)\,\big].$$All values stay between $-1$ and $1$, and the encoding does not depend on sentence length. Since every vector has length 1, the cosine similarity of two positions is just the cosine of the angle between them:
$$\cos\text{-sim}\big(PE(pos), PE(pos')\big) = \cos\big((pos-pos')\,\omega\big).$$This depends only on the distance $pos-pos'$. So neighboring positions are always equally similar (consistent steps), and nearby positions are more similar than distant ones, at least for a while.
The catch is the last thing Figure 2 shows: a circle wraps around. With $\omega=30^\circ$, position 13 lands exactly on position 1, so the encoding is no longer unique. A small $\omega$ delays the wrap-around, but then neighboring positions become almost identical and hard to distinguish. One frequency cannot do both jobs.
4Many frequencies: lessons from binary
How do we write numbers so that every one is unique? Binary. Look at how the bits change as we count from 0 to 15:
- The rightmost bit flips every step: it is a fast, high-frequency signal.
- The next bit flips every 2 steps, the next every 4 steps, and the leftmost every 8 steps: slower and slower, lower-frequency signals.
Each bit alone repeats, but together, the fast bits distinguish neighbors and the slow bits distinguish far-apart positions, so every number gets a unique pattern.
Sinusoidal positional encoding uses the same trick, with smooth waves instead of bits. It stacks many (sin, cos) pairs, each rotating at a different frequency: a “soft” version of alternating bits.
5The sinusoidal formula
For a model with dimension $d$, the encoding has $d/2$ (sin, cos) pairs. Pair number $k$ (for $k=0,1,\dots,d/2-1$) rotates with frequency $\omega_k$:
$$PE(pos)_{2k} = \sin(pos\cdot\omega_k),\qquad PE(pos)_{2k+1} = \cos(pos\cdot\omega_k),\qquad \omega_k = \frac{1}{10000^{\,2k/d}}.$$Reading the formula:
- Here $pos$ is the position and $k$ indexes the dimension pair; do not confuse the two.
- For $k=0$, $\omega_0=1$: the fastest rotation, one radian per position (a full turn every $2\pi\approx 6.3$ positions).
- As $k$ grows, $\omega_k$ shrinks geometrically. The slowest pair takes about $2\pi\cdot 10000\approx 63{,}000$ positions to make a full turn, far longer than any sentence, so the full vector never repeats in practice.
- The order is the reverse of binary as we usually write it: the first dimensions are the fast ones.
6Why this helps attention
The score between two positions involves a dot product of their (projected) input vectors. Ignoring the matrices $W^Q$ and $W^K$ for simplicity, the dot product of the inputs at positions $i$ and $j$ expands into four terms:
$$\big(x_i+PE(i)\big)\cdot\big(x_j+PE(j)\big) = \underbrace{x_i\cdot x_j}_{\text{word–word}} + \underbrace{x_i\cdot PE(j) + PE(i)\cdot x_j}_{\text{word–position}} + \underbrace{PE(i)\cdot PE(j)}_{\text{position–position}}.$$The first term is about the words, as before. The middle terms mix a word with a position; they carry little useful information on their own. The last term is where position comes in, and for the sinusoidal encoding it has a neat form. Using $\sin a\sin b+\cos a\cos b=\cos(a-b)$ for every pair:
$$PE(i)\cdot PE(j) = \sum_{k=0}^{d/2-1}\cos\big((i-j)\,\omega_k\big).$$It depends only on the distance $i-j$, not on where in the sentence the two words are. It is largest ($d/2$) when $i=j$ and generally decreases as the words get farther apart. So “I like” at positions 1–2 and the same pair at positions 31–32 get exactly the same position–position term, while “I … like” at positions 1 and 4 get a different one.
Optional: shifting by $k$ positions is a rotation
The original paper gives one more reason for this design: for any fixed offset $\Delta$, $PE(pos+\Delta)$ is a linear function of $PE(pos)$. For one (sin, cos) pair with frequency $\omega$, the angle-addition formulas give
$$\begin{bmatrix}\sin((pos+\Delta)\omega)\\ \cos((pos+\Delta)\omega)\end{bmatrix} = \begin{bmatrix}\cos(\Delta\omega) & \sin(\Delta\omega)\\ -\sin(\Delta\omega) & \cos(\Delta\omega)\end{bmatrix}\begin{bmatrix}\sin(pos\,\omega)\\ \cos(pos\,\omega)\end{bmatrix}.$$The matrix depends only on $\Delta$, not on $pos$: moving $\Delta$ positions ahead is the same rotation everywhere, exactly like Figure 2. This makes it easy for a model with linear layers to learn patterns such as “attend to the word two positions back”.
7Positional encoding in the Transformer
In the Transformer, the positional encoding is added once, at the very bottom: each input token is mapped to its embedding, the positional encoding for its position is added, and the result is fed into the stack of Transformer layers. The sinusoidal encoding has no learned parameters; it is computed from the formula.
Sinusoidal encoding is not the only option. Some alternatives:
- Learned positional embeddings: treat each position like a word and learn a vector $PE(pos)$ for it. Simple and effective (used in BERT and GPT-2), but the model cannot handle positions beyond the maximum length seen in training.
- Relative position methods: instead of adding a vector to the input, change the attention score directly based on the distance $i-j$.
- Rotary position embedding (RoPE): rotates the query and key vectors by angles proportional to their positions, so their dot product depends on the distance. It builds directly on the rotation idea above and is used in many recent large language models.
8Summary
- Self-attention treats a sentence as a set: swapping words just swaps their outputs.
- The fix is to add a position vector: $x_{pos}\leftarrow x_{pos}+PE(pos)$.
- A good encoding is unique, makes nearby positions similar, treats every step the same, and is bounded and length-independent.
- One (sin, cos) pair is a point rotating on a circle; it wraps around. Many pairs at geometrically decreasing frequencies, like binary bits, make every position unique.
- $PE(i)\cdot PE(j)=\sum_k\cos((i-j)\omega_k)$ depends only on the distance, which helps attention reason about relative position.
9Practice
Exercise 1: compute an encoding
With $d=4$, compute $PE(1)$. (Use $\sin 1\approx 0.841$, $\cos 1\approx 0.540$.)
$PE(1)=[\sin 1,\ \cos 1,\ \sin 0.01,\ \cos 0.01]\approx[0.841,\ 0.540,\ 0.010,\ 1.000]$. The first pair has already rotated a lot; the second has barely moved.
Exercise 2: distance
For the one-frequency encoding $PE(pos)=[\sin(pos\,\omega),\cos(pos\,\omega)]$, show that $PE(i)\cdot PE(j)$ depends only on $i-j$.
Exercise 3: wrap-around
With a single frequency and $\omega=45^\circ$ per position, which position first lands on the same point as position 1? Why does adding more, slower frequencies fix this?
Quick quiz
10Further reading
- Kazemnejad (2019). Transformer Architecture: The Positional Encoding. (The binary analogy and the heatmaps come from here.)
- Fleetwood (2024). You Could Have Designed State of the Art Positional Encoding. Hugging Face blog. (Builds from naive ideas to sinusoidal encoding and RoPE.)
- Alammar. The Illustrated Transformer, section “Representing the Order of the Sequence Using Positional Encoding”.
- Vaswani et al. (2017). Attention Is All You Need. NeurIPS. (Section 3.5.)