Visualized ML
Topics

D · Modern ideas

Attention

Each word builds its new meaning as a weighted average of every word's value, weighted by how well its query matches their keys.

Try it: D3 · Attention

Intuition

An embedding gives each word one vector, whatever sentence it is in. But meaning depends on context: in "the cat sat because it was tired", "it" means the cat. To understand a word, a model must gather information from the right other words, and which words are right depends on the sentence.

Attention lets every word look at every other word and decide, by itself, where to look. Each word asks a question (its query), and every word advertises what it offers (its key). Where a query matches a key well, the word pays a lot of attention there. It then takes a weighted average of what the words carry (their values) and uses it to update its own vector. After a few such layers, "it" carries what the model knows about the cat.

For one word at a time (top), the arcs show how much attention it pays to each word of the sentence (bottom). The weights are a softmax of its query–key scores, so they add up to 100%. "it" pays most of its attention to "cat". The word's new vector is the weighted average of all the words' values.

The math

Stack the \(n\) input vectors of a sequence as rows of \(X\). Three learned weight matrices turn them into queries, keys and values:

\[ Q = XW_Q, \qquad K = XW_K, \qquad V = XW_V \]

Scaled dot-product attention is then

\[ \operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V \]
  • \(QK^\top\) is an \(n \times n\) matrix of scores: entry \((i, j)\) is how well word \(i\)'s query matches word \(j\)'s key.
  • The softmax is taken across each row, turning word \(i\)'s scores into weights that are positive and sum to 1.
  • Multiplying by \(V\) gives each word the weighted average of the values: row \(i\) of the output is \(\sum_j a_{ij}\mathbf{v}_j\).

Why divide by \(\sqrt{d_k}\)? A dot product of two random vectors with \(d_k\) components of variance 1 has variance \(d_k\). Without scaling, scores in large dimensions would be huge, the softmax would put almost all weight on one word, and its gradients would vanish.

Multiple heads

One attention pattern can only look for one kind of relation. Multi-head attention runs \(h\) attentions in parallel, each with its own smaller \(W_Q, W_K, W_V\), concatenates the results and mixes them with one more matrix. One head may track which noun a pronoun refers to, another the previous word, another the verb's subject.

Masking and position

In a model that generates text, a word may not look at words that come after it: their scores are set to \(-\infty\) before the softmax (a causal mask). And attention itself ignores order, since shuffling the words shuffles the outputs the same way, so position information is added to the inputs (positional encodings) or to the scores.

Worked example. One query \(\mathbf{q} = (1, 1)\), three keys \((2, 0)\), \((0, 1)\), \((1, 1)\), values \((1, 0)\), \((0, 1)\), \((1, 1)\), and \(d_k = 2\).

Scores \(\mathbf{q}\cdot\mathbf{k}_j/\sqrt2\): \(1.414\), \(0.707\), \(1.414\). Exponentials 4.11, 2.03, 4.11; total 10.25; weights \(0.401\), \(0.198\), \(0.401\).

Output: \(0.401\,(1, 0) + 0.198\,(0, 1) + 0.401\,(1, 1) = (0.802, 0.599)\).

The transformer

A transformer block is multi-head self-attention followed by a small two-layer network applied to each word separately, each with a residual connection and layer normalization around it. Stack dozens of blocks and you have the architecture behind today's language models, as well as vision transformers (which attend over image patches), speech recognizers and protein-structure predictors.

Its key advantage over recurrent networks, which read one word at a time, is that every word connects to every other directly, and all positions are computed at once, which suits GPUs.

Pitfalls

  • Quadratic cost. The score matrix has \(n^2\) entries, so doubling the context quadruples the work and memory. Efficient kernels (FlashAttention), sparse and sliding-window patterns, and caching past keys and values during generation all address this.
  • Attention is not explanation. Large weights show where information flowed in one layer and head, not why the model decided something; values and later layers transform it further.
  • Forgetting the mask. Training a generator without the causal mask lets it see the answer, so it learns nothing useful and fails at generation time.
  • Softmax saturation. Without the \(\sqrt{d_k}\) scaling, or with very large activations, the weights collapse onto one word and learning stalls.

History

Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio introduced attention in 2014 so that a translation model could look back at the relevant source words instead of squeezing a whole sentence into one vector. In 2017 Ashish Vaswani and colleagues at Google showed in "Attention Is All You Need" that attention alone, without recurrence, works better and trains faster: the transformer. BERT and GPT (2018) followed, and with them the large language models.

Connections

Builds on

Further reading