All courses

Injecting order: absolute position embeddings

Show that unmasked attention is permutation-equivariant, so it cannot see word order; the causal mask breaks this only weakly. Add a learned or sinusoidal position vector to each token embedding, and explain the downsides: tied to fixed positions and poor extrapolation beyond the trained length.

Builds on: Scaled dot-product attention, Causal masking

▶ Watch this lesson Start the whole course

What the animation says

Same words, different news

Dog bites man. Man bites dog. Same three words, very different news. Attention scores each pair of tokens with a dot product of their two vectors. Nothing in that score mentions where either token sits. Here is dog in the first sentence, and the output vector it gets. Predict: in man bites dog, what output does dog get?

Shuffle in, shuffle out

Same vector. Each of dog's scores depends only on two vectors, and none of them changed. Reorder the input rows, and the rows and columns of the score grid reorder the same way. Each row of weights is only reshuffled, so every output follows its token to the new spot. Shuffle in, same shuffle out. That's permutation equivariance. Unmasked attention sees a set, not a sequence. This code checks it on random numbers. The last line prints True.

The mask sees a bag

Now add the causal mask: each position sees only itself and earlier tokens. The mask stays fixed when tokens move, so the clean shuffle rule breaks. But look at the last position. It learns which tokens came before, not their order. The earlier tokens reach it as an unordered bag. Tap the reordering that leaves the last output exactly the same.

Stamp the position in

The fix: stamp each token with where it sits. Each input row becomes the token's embedding plus a position vector for its slot. That vector is either learned, one row per position, or fixed sine and cosine waves. With four dimensions, one pair turns one radian per step, the other a hundredth of a radian. Now dog at position one enters differently from dog at position two. Say training used 512 positions. Predict: what happens at position 600?

Where absolute breaks

A learned table simply has no row six hundred. Sinusoids can compute one, but the slow pair lands at six radians, past the roughly five point one seen in training. There's a deeper cost too. The cat at positions three and four looks different from the cat at three hundred and three hundred one. So each pattern must be learned largely separately at every location. What matters is the distance between tokens. That's where we go next.

Can attention tell word order at all?

'dog bites man' and 'man bites dog' contain the same three tokens. Attention compares each query with each key through dot products of their vectors, and nothing in $QK^\top$ mentions *where* a token sits. So can a model built from attention tell these two sentences apart? If it cannot, what is the cheapest way to give it word order?

Attention sees a set, not a sequence

The score between two positions depends only on their two vectors. Shuffle the input rows and every score, weight and output moves along with its token. 'dog' gets the identical output in both sentences. Unmasked attention sees a **set**. The causal mask helps only a little. In one layer, position $t$ sees which tokens are in $x_{\le t}$, but as an unordered bag. The fix is to stamp each vector with its position.

Equivariance, and the absolute fix

Let $\Pi$ be a $T\times T$ permutation matrix, which reorders rows. Then $(\Pi X)W_Q=\Pi Q$, and likewise $\Pi K$ and $\Pi V$. So $$\text{softmax}\!\left(\tfrac{\Pi QK^\top\Pi^\top}{\sqrt{d_{head}}}\right)\Pi V=\Pi\,\text{softmax}\!\left(\tfrac{QK^\top}{\sqrt{d_{head}}}\right)V.$$ Reordering the rows and columns of the scores just reshuffles each row, so the softmax output is reordered the same way, and then $\Pi^\top\Pi=I$. This is **permutation equivariance**. The mask $M$ stays fixed, which is why masking breaks it. The absolute fix: row $t$ of the input $X$ becomes $W_E[x_t]+P_t$, with $P\in\mathbb{R}^{T_{max}\times d}$ ($T_{max}$ = longest trained context). $P$ is either learned, or fixed sinusoids: coordinate pair $i=0,\dots,\tfrac d2-1$ holds $(\sin\omega_i t,\cos\omega_i t)$ with frequency $\omega_i=1/10000^{2i/d}$.

Check both claims numerically

Two checks. Shuffling the rows of $X$ shuffles the unmasked output in exactly the same way. With the causal mask, reordering the earlier tokens (the prefix) leaves the last position's output unchanged.
import numpy as np; rng = np.random.default_rng(0)
T, d = 4, 8   # one head, d_head = d
X = rng.normal(size=(T, d)); Wq, Wk, Wv = rng.normal(size=(3, d, d))
def attn(X, mask=False):
    S = (X @ Wq) @ (X @ Wk).T / np.sqrt(d)
    if mask: S = S + np.triu(np.full((T, T), -np.inf), 1)
    A = np.exp(S - S.max(1, keepdims=True)); A /= A.sum(1, keepdims=True)
    return A @ (X @ Wv)
perm = [2, 0, 3, 1]
print(np.allclose(attn(X[perm]), attn(X)[perm]))              # True
p3 = [1, 0, 2, 3]  # swap first two tokens, keep last
print(np.allclose(attn(X[p3], True)[-1], attn(X, True)[-1]))  # True

Sinusoids with d = 4, and where they fail

With $d=4$ the frequencies are $\omega_0=1$ and $\omega_1=1/10000^{2/4}=1/100$, so $P_t=(\sin t,\cos t,\sin\tfrac{t}{100},\cos\tfrac{t}{100})$. That gives $P_1=(0.84,0.54,0.01,1.00)$ and $P_2=(0.91,-0.42,0.02,1.00)$. 'dog' at position 1 enters as $W_E[\text{dog}]+P_1$, and at position 2 as $W_E[\text{dog}]+P_2$, so order now changes the scores. Suppose training used $T_{max}=512$. A learned $P$ has no row 600. Sinusoids can compute $P_{600}$, but its slow pair sits at angle 6 rad, beyond anything seen in training (at most 5.12).

Remember

Attention is order-blind: permuting the tokens just permutes the outputs. The causal mask reveals only which tokens precede, not their order. Absolute embeddings add $P_t$ to each token's vector. Then 'the cat' at positions 3–4 looks different from 'the cat' at 300–301, so each pattern has to be learned largely separately at each location. Positions beyond the trained length are missing (learned) or unfamiliar (sinusoidal). This motivates encoding the distance between tokens instead.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.