Lecture 18 · Animations
Attention and transformers
Attention is a similarity, a softmax and a weighted average. The two widgets below compute it in front of you on short made-up sentences: one query at a time with every number shown, and what goes wrong without positions. Press Step to advance one unit and read what happened; press Play to let it run.
All data on this page is synthetic: the embeddings and the projection matrices are random draws from a fixed seed, made in your browser, and nothing here was trained. Where a pattern is designed rather than random, the widget says so. Reset always gives back the same picture.
1Scaled dot-product attention, one query at a time
Five tokens, each a random vector $\mathbf x_i \in \mathbb R^4$, projected to a query, a key and a value of width $d_k = 2$, so that they can be drawn. Left: the keys $\mathbf k_j$ and the current query $\mathbf q_i$; a key's score is its dot product with the query, so keys further along the query's direction score higher. Right: the values $\mathbf v_j$ and the output $\mathbf z_i$, their weighted average. Each step moves to the next query.
$\mathbf q_i = \mathbf W_Q\mathbf x_i$, $\mathbf k_j = \mathbf W_K\mathbf x_j$, $\mathbf v_j = \mathbf W_V\mathbf x_j$, and
$$s_{ij} = \mathbf q_i^{\mathsf T}\mathbf k_j,\qquad w_{ij} = \mathrm{softmax}_j\!\left(\frac{s_{ij}}{\sqrt{d_k}}\right),$$ $$\mathbf z_i = \sum_j w_{ij}\mathbf v_j .$$All rows at once: $\mathrm{softmax}\bigl(\mathbf Q\mathbf K^{\mathsf T}/\sqrt{d_k}\bigr)\mathbf V$. The dot product is $\mathbf q^{\mathsf T}\mathbf k = \lVert\mathbf q\rVert\,\lVert\mathbf k\rVert\cos\theta$: the length of $\mathbf q$ times the signed length of $\mathbf k$'s projection onto $\mathbf q$'s direction. The decoder's mask sets $s_{ij} = -\infty$ for $j > i$, and $e^{-\infty} = 0$.
- The weights in each row are positive and sum to 1, so $\mathbf z_i$ always lands inside the shaded region spanned by the values (their convex hull): attention averages, it never extrapolates.
- The key with the largest projection onto the query's direction gets the largest weight. A key behind the origin, relative to the query, scores negative.
- With the mask on, row 1 has a single allowed key, so $w_{11} = 1$ and $\mathbf z_1 = \mathbf v_1$ exactly; the heat map becomes lower-triangular.
- Step through all five rows and check in the table that each row of $w$ sums to 1.
- Turn on the causal mask and step again: the upper triangle of the heat map empties, and the first output sits exactly on the first value.
- Set the query scale to 4: the scores grow fourfold, the weights concentrate on one key, and $\mathbf z_i$ moves towards that key's value.
2Positions, and the permutation problem
Top: the sinusoidal positional encoding, one column per position and one row per coordinate (blue positive, gold negative). Bottom: one self-attention layer applied to the film was not good and to a shuffle of it. Under each token, its output vector drawn as eight bars. Each step draws a new shuffle. Without positions, every token's output is the same in both orders — only the order of the outputs changes.
Why order is invisible without it: shuffling the rows of $\mathbf X$ is $\mathbf P\mathbf X$ for a permutation matrix $\mathbf P$, with $\mathbf P^{\mathsf T}\mathbf P = \mathbf I$. Then $\mathbf Q\mathbf K^{\mathsf T}$ becomes $\mathbf P\mathbf Q\mathbf K^{\mathsf T}\mathbf P^{\mathsf T}$ — the same scores, rows and columns permuted alike — and a softmax along each row does not care in what order its entries come, so
$$\begin{aligned}\mathrm{Attn}(\mathbf P\mathbf X) &= \mathbf P\,\mathrm{softmax}\Bigl(\tfrac{\mathbf Q\mathbf K^{\mathsf T}}{\sqrt{d_k}}\Bigr)\mathbf P^{\mathsf T}\,\mathbf P\mathbf V\\ &= \mathbf P\,\mathrm{Attn}(\mathbf X).\end{aligned}$$A mean over positions, which a classifier head reads, is then identical for every order.
- Without positions, the largest difference between a token's output in the two orders is 0 to rounding ($10^{-16}$), shuffle after shuffle, and so is the difference of the mean-pooled vectors.
- With positions added, the same token gets a different output in a different place, and the mean-pooled vectors differ: the model can now tell the two sentences apart.
- In the heat map, the top rows oscillate fast along the positions and the bottom rows slowly: each pair of rows is a sine and cosine of one frequency.
- Step a few times with positions off and read the two differences in the side panel: both stay at rounding level.
- Tick add positional encoding and step again: both differences are now between about 0.3 and 4 — fifteen orders of magnitude above rounding.