Skip to content
Module 2 ยท Building the Model
Chapter 6 of 17
Run it in your browser

Chapter 6: Self-Attention (Single Head)

The map with Attention highlighted Figure 6.1: Attention builds context by looking across the sequence.

In Chapter 5 we gave our tokens some meaning through the use of embeddings. We can't just analyze one word at a time. For example, to understand what "it" refers to in the sentence "the trophy didn't fit in the suitcase because it was too big", we have to be able to associate "it" with "trophy". In this chapter you will:

  • Learn how tokens "look" at each other to build context.
  • Use the Query, Key, Value (QKV) system to find relevant information.
  • See how attention is a weighted average of numbers.
  • Apply a causal mask to hide the future.

Words to Know

  • Self-Attention: The step where each token looks at the tokens before it and decides how much each one matters to its own meaning.
  • Query (Q): A list of numbers that says what a token is looking for.
  • Key (K): A list of numbers that says what a token has to offer.
  • Value (V): A list of numbers holding the information a token passes on when it is picked.
  • Causal Mask: A filter that hides the tokens that come later, so a token sees only itself and the past.

Theory

The Problem: Context Matters

If a model can only see one token at a time, it would have no memory of what it has previously seen. So it couldn't understand subject-verb or adjective-noun combinations. Every token needs to see the other tokens and figure out which ones are related to it.

The QKV System

Self-attention solves this using three vectors for every token:

  • Query (Q): What am I looking for?
  • Key (K): What do I offer?
  • Value (V): What information do I actually contain?

Think of this as a party. You want to meet with someone that knows about marketing (Query). A person walks up to you and has Marketing Director on their name tag (Key). They match so you talk to them and learn from their knowledge (Value).

In our model, each token will generate its own Q, K, and V vectors. By taking their embedding and multiplying by weight values they can be used to look for information as well as provide it.

Attention is a Weighted Average

Attention is a weighted average Figure 6.2: Token 5 blends the values of tokens 0 to 5.

Since attention is a weighted average (Figure 6.2), when calculating the final value of token 5 we take a mix of all tokens that it has access to. There isn't a "best" token chosen.

We will take all of our Queries and multiply them by all of our Keys (q @ k.transpose) to give us an attention score for each token pairing. Then we divide by sqrt(head_size) (head size being the size of our attention heads which in this case is 32). This will keep our numbers small. After this we use softmax to normalize these numbers into percentages (weights) that sum to 1.0 (or 100%).

Token 5 may produce weights that look something like this for the following example (Figure 6.3). Keep in mind these weights have been rounded for display, so they add up to about 100% (100.1%):

  • Token 0: 19.9%
  • Token 1: 20.4%
  • Token 2: 12.2%
  • Token 3: 12.1%
  • Token 4: 21.4%
  • Token 5: 14.1%

Attention weights for token 5 Figure 6.3: Token 5's attention weights from an untrained head on random input.

The final output for token 5 is 19.9% of token 0's value, plus 20.4% of token 1's value, etc. for all six tokens. Our "Numbers Machine" gets context by mixing the numbers of the most relevant previous tokens. Collecting context like this completes the "Attention" step on our map (Figure 6.1).

The Causal Mask

The causal mask hides the future Figure 6.4: A lower triangular mask lets each token see only itself and the past.

Because the model processes all tokens at once, token 5 could see token 6. When training we would not want this as token 5 would be able to cheat , because token 5 would copy the answer from the future and would not learn to predict it.

So we apply a causal mask to the scores with a triangular pattern of negative infinities (See Figure 6.4). This is done before applying the softmax function. As we know softmax will convert -infinity into exactly 0.0. Token 5 will pay 0% attention to tokens 6, 7, 8, and 9 and can only see itself and the past.

In Business

If you searched this customer support chat using keywords, you would only be able to see one word at a time. With self-attention, your model can learn that message 4's "refund" relates to the customer's earlier message about a "broken screen" in message 1. Your model can factor this in when composing its house-style response.

Code

How the code flows in self-attention Figure 6.5: Q and K produce the masked weights, which then multiply V.

We use src/ch05_self_attention.py to build the SingleHeadAttention class (Figure 6.5).

src/ch05_self_attention.py (excerpt)
        q = self.query(x)
        k = self.key(x)
        v = self.value(x)

        # Compute attention scores and scale them to keep variance stable
        scale = HEAD_SIZE ** -0.5
        scores = q @ k.transpose(-2, -1) * scale

        # Mask future tokens by setting their scores to negative infinity
        scores = scores.masked_fill(self.tril[:T, :T] == 0, float("-inf"))

        # Convert scores to probabilities and apply dropout
        weights = F.softmax(scores, dim=-1)
        weights = self.dropout(weights)

        # Compute final output by taking weighted sum of values
        out = weights @ v

Running the script prints the attention weights:

Terminal
$ python src/ch05_self_attention.py
--- Attention weights (what token 5 attends to) ---
Token 5 attends to tokens 0..5 (future tokens masked):
  token 0: 0.199  #####
  token 1: 0.204  ######
  token 2: 0.122  ###
  token 3: 0.121  ###
  token 4: 0.214  ######
  token 5: 0.141  ####
  token 6: 0.000
  token 7: 0.000
  token 8: 0.000
  token 9: 0.000

Self-attention done! Ready for Chapter 7.

What just happened:

  • Lines 1 to 3 created independent Query, Key, and Value vectors.
  • Line 7 computed the attention scores between all tokens.
  • Line 10 masked the future tokens (notice tokens 6 to 9 have exactly 0.000 weight).
  • Line 17 created the output (for example, token 5 created its output by taking a weighted average of tokens 0 through 5).

Shape Check: Table 6.1 lists the shapes of the attention variables.

Table 6.1: Tensor shapes during the self-attention calculation.

Variable Shape Meaning
q, k, v [B, T, head_size] Queries, Keys, and Values. head_size is 32.
scores [B, T, T] Attention scores between every pair of tokens.
weights [B, T, T] The softmax probabilities (summing to 1 per row).
out [B, T, head_size] The final context-aware output vectors.

Try It

Try It

Modify the demo at the bottom of src/ch05_self_attention.py to remove the division by scale. Change scale = HEAD_SIZE ** -0.5 to scale = 1.0. Execute it again. The weights become extreme: token 4 increases from 0.214 to 0.383 while tokens 2 and 3 plummet to around 0.015. Without scaling, most of the weight accrues to only a few tokens.

Terminal
$ python src/ch05_self_attention.py
...
  token 0: 0.257  #######
  token 1: 0.293  ########
  token 2: 0.016
  token 3: 0.015
  token 4: 0.383  ###########
  token 5: 0.036  #
...

Watch Out

Take note of the transpose step. We only want to swap the final two dimensions (Time and head_size) for the purposes of computing the dot product. Using .T could also flip your Batch dimension and break your shape math, so be sure to use .transpose(-2, -1).

Terminal
$ python src/ch05_self_attention.py
...
RuntimeError: The size of tensor a (2) must match the size of tensor b (32) at non-singleton dimension 0

Key Takeaways

  • Self-attention constructs context by allowing tokens to "see" other tokens.
  • Queries, Keys and Values operate like a search engine. Queries match with Keys to fetch Values.
  • Attention is a weighted average of the Values.
  • A causal mask prevents the model from cheating by setting future scores to negative infinity.

Check Your Understanding

  1. What is the difference between a Query and a Key?
  2. Why do we divide the attention scores by the square root of the head size?
  3. What happens to a score of negative infinity when passed through softmax?
  4. Why is the causal mask necessary for a language model?

Assignment

Assignment 6: New numbers, same mask

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

  1. Run it. Execute src/ch05_self_attention.py as is. Copy the ten weights printed for token 5.
  2. Change one number. Find the line torch.manual_seed(42) near the bottom of src/ch05_self_attention.py. The seed makes sure the starting random numbers are always the same, which ensures we print the same weights each time. Replace the 42 with any whole number of your choosing and execute the script again.
  3. Compare. Which of the ten weights changed? Which weights stayed the same? What do the weights across tokens 0-5 sum to now?
  4. Explain it. In two or three sentences suitable for a manager to understand, explain why four of the rows print the same value regardless of seed.

Hand in: both sets of ten weights, your answers to step 3, and your sentences.

Further Reading

The first attention. The early models of machine translation would consume all of the source sentence, squeeze it down into one fixed-size vector, then use that to write out the target sentence. If your sentence was long, you'd lose information from compressing it down to that small vector. This paper allowed the model to look back at all input words while writing each output word, deciding which words to pay more attention to. That's what attention is. The Transformer took that concept three years later and removed everything else.

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.

Bahdanau, D., Cho, K., & Bengio, Y. (2014). Neural machine translation by jointly learning to align and translate (arXiv:1409.0473). arXiv. https://doi.org/10.48550/arXiv.1409.0473

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 7: Multi-Head Attention