Skip to content
Module 2 · Building the Model
Chapter 7 of 17
Run it in your browser

Chapter 7: Multi-Head Attention

The map with Attention highlighted Figure 7.1: We run multiple attention heads at the same time to gather richer context.

In Chapter 6, we used one attention head. You can think of this as one reader glancing over the text. Normally you would want more than one reader, because each will catch different things. In this chapter you will:

  • Run multiple attention heads in parallel.
  • Understand how different heads learn to track different patterns.
  • Concatenate their outputs into a single rich representation.

Words to Know

  • Multi-Head Attention: Running several attention heads at the same time, so the same text is read in several different ways.
  • Concatenation: Joining several lists of numbers end to end to make one longer list.
  • Projection: A final step that blends the heads' joined outputs into one list of numbers for each token.

Theory

One Reader Isn't Enough

Parallel heads looking at different features Figure 7.2: Each head reads the same input through its own filters, and their outputs are concatenated and projected.

When you read a sentence, you track multiple things at once:

  • Who is the subject?
  • What action is happening?
  • What is the tone, serious or sarcastic?

A single head is able to pick up on only one type of feature at a time. Multi-head attention addresses this by using many heads at once. As shown in Figure 7.2, there can be many heads operating in parallel. Think of it as having many people read a passage, each circling something they find interesting, then combining their notes.

How It Works

Multi-head attention repeats the mechanism from Chapter 6:

  1. Run 4 independent attention heads (each one a SingleHeadAttention from Chapter 6) on the same input.
  2. Each head produces an output of 32 numbers (head_size).
  3. Glue (concatenate) all 4 outputs together: 4 heads × 32 numbers = 128 numbers.
  4. Apply a final projection, one more step that blends them.

As each head starts with random initial weights (individually randomized Q, K, and V filters), no two heads ever view the text in exactly the same way. Training drives them further apart still.

Why Four Heads and Not One Big One

Four readers sound expensive, and people are often surprised by what they cost.

Each filter only has dimensions relative to its head's head_size, not the full 128 channels. Split the 128 channels into four heads and filters in each head are a quarter as wide. Do the math and you'll see the products are the same:

src/examples/ch07_head_budget.py
1
2
3
4
5
head_size = C // n_heads

# Every head holds three filters (query, key, value), each C by head_size
four_heads = n_heads * 3 * C * head_size
one_head = 3 * C * C
Terminal
$ python src/examples/ch07_head_budget.py
4 heads of 32: 49,152 numbers
1 head of 128  : 49,152 numbers
Same budget: True

Four viewpoints cost nothing more than one, so all models in this family have lots of heads.

Do the Heads Really Differ?

We can verify if they actually differ on the model you will train in Chapter 13.

This script loads trained weights, inputs a line of Shakespeare, and prints how much attention the last character pays to every prior character, one row per head.

src/examples/ch07_heads_differ.py (excerpt)
1
2
3
4
for h, head in enumerate(model.blocks[0].attn.heads):
    with torch.no_grad():
        scores = head.query(x) @ head.key(x).transpose(-2, -1) * head.head_size ** -0.5
        weights = F.softmax(scores, dim=-1)[0, -1]     # the last character's row
Terminal
$ python src/examples/ch07_heads_differ.py
Prompt: "JULIET: O Romeo"

Attention paid by the last character, one row per head:
              J    U    L    I    E    T    :    _    O    _    R    o    m    e    o
  head 0:  0.02 0.04 0.01 0.06 0.03 0.04 0.04 0.02 0.06 0.04 0.05 0.04 0.11 0.38 0.07
  head 1:  0.02 0.02 0.03 0.03 0.04 0.08 0.12 0.06 0.05 0.07 0.02 0.10 0.16 0.14 0.06
  head 2:  0.04 0.07 0.04 0.06 0.05 0.11 0.04 0.06 0.09 0.07 0.07 0.06 0.09 0.09 0.06
  head 3:  0.03 0.02 0.01 0.05 0.05 0.03 0.03 0.05 0.04 0.04 0.05 0.08 0.12 0.25 0.14

Sharpest focus per head: 0->'e' (0.38)  1->'m' (0.16)  2->'T' (0.11)  3->'e' (0.25)

Head 0 is paying 0.38 of its attention to the character just before the end. The rest it hardly cares about. Head 3 kind of does this as well but not as pronounced. It's splitting its attention between e and the final o. Head 1 shares its attention across the colon, the m and the e. Head 2 pays very little attention to any single character with the largest weight being 0.11 and the smallest being 0.04 which is almost uniform.

So we see that our heads are acting differently but not as nicely as you may have heard. One is sharp, one is more smooth. One is spread out and one is not doing much of anything. In a trained model, some heads do very little. No one made them act this way and we can't promise that head 1 is the "grammar head". These are just 4 different attention heads with their initial values generated by a seed.

Watch Out

You may be tempted to tell yourself a story about what each head is doing: one head is tracking nouns, another is tracking periods. Sometimes, a head really is nicely interpretable like that and researchers have found some in big models. Often it isn't, though, as head 2 makes clear. See the numbers before you weave your tale.

The Output Projection

Once the 4 heads are concatenated, we feed the 128 numbers through one last linear layer. This is called the proj layer.

Why do we have this extra layer? Each head may find duplicate information. The projection layer learns that if head 1 and head 3 both found the same pattern, it should give it more weight. And if head 2 is unsure, the projection layer learns to ignore it. This will mix the 4 separate perspectives into a single context vector of 128 numbers. Now that we have the projection in place, the "Attention" stage of our map is complete (Figure 7.1).

Another option would have been to simply take an average of the 4 heads instead of gluing them together. If we did this we would have 32 numbers instead of 128. The problem with doing this is head 0 has a sharp focus on one character while head 2 has a flat spread. If we average these they'll both have some kind of average attention to some characters. By gluing the heads together we allow each head to provide its answer and the projection will learn how much to weight each head's answer.

In Business

Different departments form a single executive summary Figure 7.3: Multi-head attention gathers different perspectives.

Suppose you wanted to train an assistant to write emails that mimic your company's house style. You wouldn't train it on just one pattern. You would teach it to watch for tone, formatting, word choice, etc. (Figure 7.3). Multi-head attention asks 4 different groups to do this before producing one consolidated report.

Code

How the code flows in multi-head attention Figure 7.4: The heads run in parallel, get concatenated, and projected.

We use src/ch06_multihead_attention.py to build the MultiHeadAttention class (Figure 7.4).

src/ch06_multihead_attention.py (excerpt)
1
2
3
4
5
6
7
8
        # Run each head in parallel
        head_outputs = [h(x) for h in self.heads]

        # Concatenate outputs along the last dimension
        out = torch.cat(head_outputs, dim=-1)

        # Apply projection and dropout
        out = self.dropout(self.proj(out))

Running the script compares one head with four:

Terminal
$ python src/ch06_multihead_attention.py
--- Comparing one head vs multi-head ---
Single head output  shape: torch.Size([2, 10, 32])  (head_size=32)
Multi-head output   shape: torch.Size([2, 10, 128])  (C=128)

Multi-head output has 4x more channels - it sees 4 perspectives at once.

Multi-head attention done! Ready for Chapter 8.

What just happened:

  • Line 2 ran 4 independent attention heads at the same time.
  • Line 2's result is that each head produced an output with 32 channels.
  • Line 5 concatenated them into 128 channels (the original embedding dimension).
  • Line 8 applied the projection, which blends the 128 channels and keeps the shape of the input. The same line also applied dropout, which Chapter 14 explains.

Shape Check: Table 7.1 lists the shapes as the data passes through the heads.

Table 7.1: Tensor shapes during the multi-head attention step.

Variable Shape Meaning
head_outputs 4 × [B, T, 32] A list of outputs from the 4 heads.
out (after cat) [B, T, 128] The 4 outputs joined end-to-end.
out (final) [B, T, 128] The blended representation, ready for the next step.

Try It

Try It

Edit src/utils/config.py to use 8 heads instead of 4. Set n_heads = 8. Run the script again. Pay attention to how head_size is now automatically set to 16 to keep the final concatenated size at 128 (8 × 16 = 128). We can have more viewpoints, but with less granularity within each one.

Watch Out

Your embedding dimension (n_embd) has to be divisible by your number of heads (n_heads) for multi-head attention to operate cleanly. Setting n_embd = 128 and n_heads = 5 will crash the program, as it won't be able to cleanly divide the channels.

Key Takeaways

  • Multi-head attention runs several single-head attention modules in parallel.
  • Splitting the channels across heads costs nothing: four heads of 32 hold the same 49,152 numbers as one head of 128.
  • The heads do end up different, but not in a tidy way. In our trained model one head is sharp, one is soft and one is close to flat.
  • The outputs are concatenated, not averaged, so that no head's answer is diluted by the others before the projection can weigh it.
  • A final linear projection blends the separate perspectives.
  • The output shape [B, T, C] is exactly the same as the input shape, so layers stack easily.

Check Your Understanding

  1. Why is one attention head not enough to understand complex text?
  2. If n_embd = 256 and n_heads = 8, what is the head_size?
  3. Four heads of 32 hold the same number of weights as one head of 128. Why does splitting cost nothing?
  4. Why do we concatenate the heads rather than average them?
  5. In the run above, head 2's attention was almost flat. What does that tell you about the claim that each head learns its own linguistic role?
  6. What is the purpose of the final projection layer?

Assignment

Assignment 7: Same heads, new word

About 15 minutes. You change one word and write no new code. Work in this chapter's Colab notebook or on your own laptop.

  1. Run it. Run src/examples/ch07_heads_differ.py unaltered. Copy the very last line printed by the program, the one that begins Sharpest focus per head.
  2. Change one word. Find the line near the top of the program that reads PROMPT = "JULIET: O Romeo". This is the line of text that we prompt the model with. Edit Romeo to read love instead, preserving the quotation marks, and run the program again.
  3. Compare. Which character is each head focused on most now? Of all the heads, which two heads had the smallest numbers for both runs? For both runs, which heads focused on the character just before the last character?
  4. Explain it. In two or three sentences that a manager could understand, describe how the four heads differ, and why experimenting with a second prompt is worthwhile before you say what job each head does.

Hand in: both Sharpest focus per head lines, your answers to step 3, and your sentences.

Further Reading

The architecture this book builds. Sequential reading (i.e. reading one step at a time) is slow, as step 500 cannot begin until step 499 is complete, and words far away from the current position remain difficult to relate. This paper eliminated sequential reading and retained only attention and positional encoding of each token. All tokens may now be processed simultaneously, allowing training on massive amounts of text to become feasible. The architecture you'll implement in Chapters 6-10 is this architecture, scaled down.

Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I. (2017). Attention is all you need (arXiv:1706.03762). arXiv. https://doi.org/10.48550/arXiv.1706.03762

Next up: Chapter 8: Feed-Forward and Norms