Part B · Chapter 7 · Attention

7. Why attention

Before 2017, translation models read a sentence one word at a time and squeezed it into a single running summary. Attention lets every word look at every other word directly, in one step.

One word at a time, or all at once
Sentence
Playback speed

Top: a recurrent network reads the sentence one word at a time, each step folding a word into one hidden state, h, while a counter shows the steps it takes. Bottom: attention. The asking word (“it”, or “She”) reaches every word of the sentence in a single step, and the arrows thicken by how much weight one head of the paper's model really gives each word.

The idea

Charles's Part 1 post starts here. Attention “is a mechanism that enables a model to selectively focus on different parts of an input sequence when making predictions.” Think of how you read “She eats apples”: to understand the action, you lean on “eats”. Attention lets a network decide, for every word, which other words matter most.

Before the paper, the best translation models were recurrent networks. They read a sentence one word at a time, like the top of the animation, and kept everything read so far in one running summary, the hidden state. To connect “it” with “dog” four words earlier, the information about the dog had to survive four steps of being folded together with everything else. And because each step needs the one before, the steps cannot run side by side.

Attention removes both problems. Every word compares itself with every other word directly, so “it” reaches “dog” in one step, however far apart they are, and all those comparisons can run at the same time. The paper's title says the rest: the authors dropped the recurrent network altogether.

A worked example: what does “it” need?

Take “Anna has a small dog . She likes it .”. With the end marker it is 11 tokens. A recurrent network reads them in 11 steps, one after another; the word “dog” reaches “it” only after passing through 4 later steps. Attention computes all 121 word-to-word scores of one head at once.

In the paper's model, head 3 of the encoder's second layer gives “it” these weights: 87.9 % on “dog”, 3.2 % on “Anna”, 0.1 % on “it” itself. One head has learned, from translation alone, that “it” needs its noun: German must choose ihn, sie or es by the noun's gender.

The formula

The paper's introduction describes the recurrent network in one line: it generates a sequence of hidden states, each “as a function of the previous hidden state and the input for position t”:

h_t = f(h_{t-1},\ x_t)

Attention, by contrast, builds each word's new vector as a weighted mix of all the words at once:

z_i = \sum_{j=1}^{n} \alpha_{ij}\, v_j, \qquad \alpha_{ij} \ge 0,\quad \sum_{j} \alpha_{ij} = 1
\(h_t\)
the recurrent network's hidden state after word t: its whole memory of the sentence so far
\(x_t\)
word t's vector
\(\alpha_{ij}\)
the attention weight: how much word i looks at word j, between 0 and 1
\(v_j\)
what word j passes on (its value, chapter 8)
\(z_i\)
word i's new vector: the mix

The weights of each word add up to 1: they come from a softmax (chapter 6). Chapters 8 and 9 show where the scores behind them come from.

Why it matters

This is why transformers could be trained on far more text than recurrent networks: the work of a whole sentence runs in parallel on a GPU instead of word by word. And it is why a model can use something said thousands of tokens earlier in your prompt: the distance between two tokens is one step of attention.

It also explains a cost you see on every invoice. Every token is compared with every other token, so the work of attention grows with the square of the length: double the prompt, four times the comparisons. That is one reason long contexts are priced and limited the way they are.

Where it fails

  • Quadratic cost. n tokens means n × n scores per head per layer. For long documents that is the dominant cost, and why context windows have limits.
  • No sense of order on its own. Attention compares words as a set; shuffle them and the scores stay the same. The paper adds positions to fix that (chapter 12).
  • A weight is not an explanation. A high weight shows where a head looked, not why the model chose its output; many heads together, and the layers after them, decide.
Remember A recurrent network passes the sentence through one hidden state, one word per step. Attention lets every word look at every word directly, in one step, so the work runs in parallel and distance does not matter, at the price of comparing every pair.

Exercises

Try each one before you open a hint. The lab's engine checks your answer against the same models the chapter uses.

How far is the first word from the last?

A recurrent network reads “Today , the old man reads a letter .” with the end marker: 10 tokens. How many steps must the first token's information pass through before the last token is read?

Your answer
A whole number

How many scores?

One attention head on a sentence of 11 tokens: how many word-to-word scores does it compute?

Your answer
A whole number

Where does “it” look?

In “Anna has a small dog . She likes it .”, which word does head 3 of the encoder's second layer look at most from “it”? Predict, then play the animation.

Why could the paper train faster?

Why can a transformer be trained much faster than a recurrent network on the same hardware?

In the paper

Section 1 of the paper explains the bottleneck: recurrent models generate hidden states one after another, and “this inherently sequential nature precludes parallelization within training examples”. Section 2 sets attention against convolutional models, where the steps needed to relate two distant words grow with their distance, while in the transformer “this is reduced to a constant number of operations”.

In the paper: section 1, 2

Open the Theory tab
An unhandled error has occurred. Reload 🗙

Reconnecting…

Your connection to the Transformers and Attention Lab dropped, probably a Wi-Fi blip. Hold on while it reconnects.

The connection could not be restored. The page will reload in a few seconds.