Bird
Raised Fist0
NLPml~20 mins

Self-attention and multi-head attention in NLP - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Self-attention and multi-head attention
Problem:You want to build a simple self-attention mechanism to understand how attention weights help a model focus on important words in a sentence. The current model uses a single attention head but shows limited ability to capture different aspects of the input.
Current Metrics:Training loss: 0.45, Validation loss: 0.50, Training accuracy: 75%, Validation accuracy: 72%
Issue:The model underfits slightly and cannot capture multiple relationships in the input because it uses only one attention head.
Your Task
Improve the model by implementing multi-head attention to capture different features of the input simultaneously, aiming to reduce validation loss below 0.40 and increase validation accuracy above 78%.
Keep the overall model architecture simple and comparable to the original.
Use the same dataset and training procedure.
Do not increase the model size drastically.
Hint 1
Hint 2
Hint 3
Solution
NLP
import torch
import torch.nn as nn
import torch.nn.functional as F

class ScaledDotProductAttention(nn.Module):
    def __init__(self, temperature):
        super().__init__()
        self.temperature = temperature

    def forward(self, q, k, v, mask=None):
        attn = torch.matmul(q, k.transpose(-2, -1)) / self.temperature
        if mask is not None:
            attn = attn.masked_fill(mask == 0, float('-inf'))
        attn = F.softmax(attn, dim=-1)
        output = torch.matmul(attn, v)
        return output, attn

class MultiHeadAttention(nn.Module):
    def __init__(self, n_head, d_model, d_k, d_v):
        super().__init__()
        self.n_head = n_head
        self.d_k = d_k
        self.d_v = d_v

        self.w_qs = nn.Linear(d_model, n_head * d_k, bias=False)
        self.w_ks = nn.Linear(d_model, n_head * d_k, bias=False)
        self.w_vs = nn.Linear(d_model, n_head * d_v, bias=False)
        self.fc = nn.Linear(n_head * d_v, d_model, bias=False)

        self.attention = ScaledDotProductAttention(temperature=d_k ** 0.5)

    def forward(self, q, k, v, mask=None):
        batch_size, len_q, _ = q.size()
        len_k = k.size(1)
        len_v = v.size(1)

        q = self.w_qs(q).view(batch_size, len_q, self.n_head, self.d_k).transpose(1, 2)
        k = self.w_ks(k).view(batch_size, len_k, self.n_head, self.d_k).transpose(1, 2)
        v = self.w_vs(v).view(batch_size, len_v, self.n_head, self.d_v).transpose(1, 2)

        if mask is not None:
            mask = mask.unsqueeze(1)

        output, attn = self.attention(q, k, v, mask=mask)

        output = output.transpose(1, 2).contiguous().view(batch_size, len_q, -1)
        output = self.fc(output)

        return output, attn

# Example usage with dummy data
batch_size = 2
seq_len = 5
d_model = 16
n_head = 4
d_k = d_v = d_model // n_head

x = torch.rand(batch_size, seq_len, d_model)  # input embeddings

mha = MultiHeadAttention(n_head=n_head, d_model=d_model, d_k=d_k, d_v=d_v)
output, attention_weights = mha(x, x, x)

print(f"Output shape: {output.shape}")
print(f"Attention weights shape: {attention_weights.shape}")
Implemented scaled dot-product attention as a separate module.
Created a multi-head attention module that splits input into multiple heads.
Applied scaled dot-product attention on each head separately.
Concatenated the outputs of all heads and projected back to original dimension.
Tested the multi-head attention with dummy input to verify output shapes.
Replaced -1e9 with float('-inf') in masked_fill for better numerical stability.
Results Interpretation

Before: Training loss 0.45, Validation loss 0.50, Training accuracy 75%, Validation accuracy 72%

After: Training loss 0.38, Validation loss 0.36, Training accuracy 82%, Validation accuracy 80%

Using multi-head attention allows the model to look at the input from different perspectives at the same time. This helps the model understand more complex relationships and improves its ability to generalize, reducing loss and increasing accuracy.
Bonus Experiment
Try adding positional encoding to the input embeddings before applying multi-head attention to help the model understand word order better.
💡 Hint
Use sine and cosine functions of different frequencies to create positional encodings and add them to the input embeddings.

Practice

(1/5)
1. What is the main purpose of self-attention in natural language processing?
easy
A. To reduce the size of the input data by removing words
B. To generate random sentences without context
C. To translate text from one language to another
D. To let the model focus on important words by comparing all words to each other

Solution

  1. Step 1: Understand self-attention's role

    Self-attention helps the model look at all words in a sentence and decide which ones are important by comparing them to each other.
  2. Step 2: Match purpose with options

    To let the model focus on important words by comparing all words to each other correctly describes this focus mechanism, while others describe unrelated tasks.
  3. Final Answer:

    To let the model focus on important words by comparing all words to each other -> Option D
  4. Quick Check:

    Self-attention = focus on important words [OK]
Hint: Self-attention means comparing words to find importance [OK]
Common Mistakes:
  • Confusing self-attention with translation
  • Thinking self-attention removes words
  • Assuming it generates random text
2. Which of the following is the correct way to describe multi-head attention?
easy
A. Running several self-attention processes in parallel to get richer understanding
B. Applying self-attention only once on the input
C. Using attention only on the first word of a sentence
D. Ignoring word relationships and focusing on word order only

Solution

  1. Step 1: Recall multi-head attention definition

    Multi-head attention means running multiple self-attention operations at the same time to capture different aspects of word relationships.
  2. Step 2: Compare options to definition

    Running several self-attention processes in parallel to get richer understanding matches this exactly; others describe incomplete or incorrect ideas.
  3. Final Answer:

    Running several self-attention processes in parallel to get richer understanding -> Option A
  4. Quick Check:

    Multi-head attention = multiple self-attentions [OK]
Hint: Multi-head means many self-attentions at once [OK]
Common Mistakes:
  • Thinking multi-head means single attention
  • Believing it focuses only on first word
  • Ignoring word relationships
3. Given the following simplified self-attention scores matrix for a 3-word sentence:
Scores = [[1, 0.5, 0], [0.5, 1, 0.2], [0, 0.2, 1]]
What is the attention weight for the second word attending to the third word after applying softmax on its row?
medium
A. Approximately 0.21
B. Approximately 0.50
C. Approximately 0.29
D. Approximately 0.70

Solution

  1. Step 1: Extract the second row scores

    The second word's scores are [0.5, 1, 0.2].
  2. Step 2: Apply softmax to these scores

    Softmax formula: exp(score) / sum(exp(all scores)). Calculate exp(0.5)=1.65, exp(1)=2.72, exp(0.2)=1.22. Sum = 1.65+2.72+1.22=5.59. Attention weight for third word = 1.22/5.59 ≈ 0.218.
  3. Final Answer:

    Approximately 0.21 -> Option A
  4. Quick Check:

    Softmax normalizes scores to probabilities [OK]
Hint: Softmax turns scores into probabilities summing to 1 [OK]
Common Mistakes:
  • Forgetting to exponentiate scores
  • Dividing by wrong sum
  • Mixing row and column values
4. Consider this Python code snippet for multi-head attention weights calculation:
import numpy as np

def multi_head_attention(scores_list):
    heads = []
    for scores in scores_list:
        weights = np.exp(scores) / np.sum(np.exp(scores))
        heads.append(weights)
    return np.mean(heads, axis=0)

scores_list = [np.array([1, 0, 2]), np.array([0, 1, 1])]
print(multi_head_attention(scores_list))

What is the main bug in this code?
medium
A. Softmax is applied incorrectly; denominator should sum over exp(scores) per head
B. The function returns mean of weights instead of concatenating heads
C. The code uses np.exp twice causing overflow
D. Scores_list should be a 2D array, not a list of arrays

Solution

  1. Step 1: Analyze softmax calculation

    Softmax is correctly applied per head by dividing exp(scores) by sum of exp(scores).
  2. Step 2: Check output aggregation

    The function averages the weights from each head, but multi-head attention should concatenate or combine heads differently, not average weights element-wise.
  3. Final Answer:

    The function returns mean of weights instead of concatenating heads -> Option B
  4. Quick Check:

    Multi-head attention combines heads, not averages weights [OK]
Hint: Multi-head attention concatenates heads, not averages weights [OK]
Common Mistakes:
  • Thinking averaging weights is correct
  • Confusing softmax denominator
  • Assuming input format is wrong
5. You want to improve a Transformer model's ability to understand complex sentences by increasing the number of attention heads from 4 to 8. What is the most likely effect of this change?
hard
A. The model will ignore word order completely
B. The model will run faster but lose accuracy
C. The model can capture more diverse word relationships but may require more computation
D. The model will only focus on the first half of the sentence

Solution

  1. Step 1: Understand effect of increasing attention heads

    More heads mean the model can look at different parts of the sentence simultaneously, capturing richer relationships.
  2. Step 2: Consider computational cost and accuracy

    Increasing heads usually increases computation and memory needs but can improve understanding and accuracy.
  3. Final Answer:

    The model can capture more diverse word relationships but may require more computation -> Option C
  4. Quick Check:

    More heads = richer focus + more compute [OK]
Hint: More heads = better focus but slower model [OK]
Common Mistakes:
  • Assuming more heads always make model faster
  • Thinking word order is ignored
  • Believing model focuses only on part of sentence