Bird
Raised Fist0
PyTorchml~20 mins

Multi-head attention in PyTorch - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Multi-head Attention Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output shape of multi-head attention
Given the following PyTorch code snippet using multi-head attention, what is the shape of the output tensor?
PyTorch
import torch
import torch.nn as nn

batch_size = 2
seq_len = 5
embed_dim = 16
num_heads = 4

mha = nn.MultiheadAttention(embed_dim=embed_dim, num_heads=num_heads)
query = torch.rand(seq_len, batch_size, embed_dim)
key = torch.rand(seq_len, batch_size, embed_dim)
value = torch.rand(seq_len, batch_size, embed_dim)
out, _ = mha(query, key, value)
print(out.shape)
Atorch.Size([5, 2, 16])
Btorch.Size([2, 5, 16])
Ctorch.Size([5, 16, 2])
Dtorch.Size([2, 16, 5])
Attempts:
2 left
💡 Hint
Remember that PyTorch's MultiheadAttention expects input shape (sequence_length, batch_size, embedding_dim) and outputs the same shape.
❓ Model Choice
intermediate
1:30remaining
Choosing number of heads in multi-head attention
You have an embedding dimension of 64 for your model. Which choice of number of heads is valid for PyTorch's MultiheadAttention module?
A10
B7
C9
D8
Attempts:
2 left
💡 Hint
The embedding dimension must be divisible by the number of heads.
❓ Hyperparameter
advanced
2:00remaining
Effect of increasing number of heads on model capacity
What is the most accurate effect of increasing the number of heads in a multi-head attention layer while keeping the embedding dimension fixed?
AIt increases the model's ability to focus on different parts of the input simultaneously without increasing the total embedding size.
BIt increases the embedding dimension, making the model larger and slower.
CIt decreases the model's ability to learn because each head gets fewer parameters.
DIt reduces the number of parameters by sharing weights across heads.
Attempts:
2 left
💡 Hint
Think about how multi-head attention splits the embedding dimension into multiple heads.
🔧 Debug
advanced
2:00remaining
Identifying error in multi-head attention input shapes
What error will this PyTorch code raise when running the multi-head attention layer?
PyTorch
import torch
import torch.nn as nn

mha = nn.MultiheadAttention(embed_dim=32, num_heads=4)
query = torch.rand(10, 3, 32)
key = torch.rand(10, 3, 16)
value = torch.rand(10, 3, 32)
out, _ = mha(query, key, value)
ATypeError: Expected 3D tensor for query
BRuntimeError: The key and query must have the same embedding dimension
CValueError: Number of heads must divide embedding dimension
DNo error, code runs successfully
Attempts:
2 left
💡 Hint
Check the embedding dimension of key and query tensors.
🧠 Conceptual
expert
2:30remaining
Why use multi-head attention instead of single-head attention?
Which of the following best explains the main advantage of multi-head attention over single-head attention?
AMulti-head attention reduces the computational cost compared to single-head attention.
BMulti-head attention always produces smaller output tensors than single-head attention.
CMulti-head attention allows the model to jointly attend to information from different representation subspaces at different positions.
DMulti-head attention eliminates the need for positional encoding in sequence models.
Attempts:
2 left
💡 Hint
Think about how splitting into multiple heads affects the model's focus.

Practice

(1/5)
1. What is the main purpose of multi-head attention in PyTorch's MultiheadAttention layer?
easy
A. To reduce the size of the input data
B. To perform simple addition of input vectors
C. To increase the number of layers in the model
D. To allow the model to focus on different parts of the input simultaneously

Solution

  1. Step 1: Understand the concept of multi-head attention

    Multi-head attention splits the input into multiple parts (heads) to focus on different information simultaneously.
  2. Step 2: Relate to PyTorch's MultiheadAttention layer

    This layer implements this idea to improve model understanding by attending to various input features at once.
  3. Final Answer:

    To allow the model to focus on different parts of the input simultaneously -> Option D
  4. Quick Check:

    Multi-head attention = focus on multiple input parts [OK]
Hint: Multi-head means multiple focus points at once [OK]
Common Mistakes:
  • Thinking it reduces input size
  • Confusing it with adding layers
  • Assuming it just adds vectors
2. Which of the following is the correct way to create a multi-head attention layer with 8 heads and embedding dimension 64 in PyTorch?
easy
A. torch.nn.MultiheadAttention(8, 64)
B. torch.nn.MultiheadAttention(embed_dim=64, num_heads=8)
C. torch.nn.MultiheadAttention(num_heads=64, embed_dim=8)
D. torch.nn.MultiheadAttention(64)

Solution

  1. Step 1: Check PyTorch MultiheadAttention parameter order

    The constructor requires embed_dim first, then num_heads as keyword arguments.
  2. Step 2: Verify correct syntax

    torch.nn.MultiheadAttention(embed_dim=64, num_heads=8) correctly uses embed_dim=64 and num_heads=8. torch.nn.MultiheadAttention(num_heads=64, embed_dim=8) swaps parameters incorrectly, A and D use positional arguments wrongly.
  3. Final Answer:

    torch.nn.MultiheadAttention(embed_dim=64, num_heads=8) -> Option B
  4. Quick Check:

    embed_dim first, num_heads second [OK]
Hint: Remember: embed_dim first, num_heads second in constructor [OK]
Common Mistakes:
  • Swapping embed_dim and num_heads
  • Using positional args incorrectly
  • Missing one of the required parameters
3. Given the following PyTorch code, what is the shape of the output tensor attn_output?
import torch
mha = torch.nn.MultiheadAttention(embed_dim=16, num_heads=4)
query = torch.rand(5, 3, 16)  # (sequence_length, batch_size, embed_dim)
key = torch.rand(5, 3, 16)
value = torch.rand(5, 3, 16)
attn_output, attn_weights = mha(query, key, value)
medium
A. (5, 3, 16)
B. (3, 5, 16)
C. (5, 16, 3)
D. (3, 16, 5)

Solution

  1. Step 1: Understand input shapes for MultiheadAttention

    Inputs are (sequence_length, batch_size, embed_dim). Here, query shape is (5, 3, 16).
  2. Step 2: Check output shape of attn_output

    Output shape matches query shape: (5, 3, 16).
  3. Final Answer:

    (5, 3, 16) -> Option A
  4. Quick Check:

    Output shape = query shape = (5, 3, 16) [OK]
Hint: Output shape matches query input shape [OK]
Common Mistakes:
  • Mixing batch and sequence dimensions
  • Confusing embed_dim position
  • Assuming output shape changes with heads
4. Identify the error in this PyTorch multi-head attention code snippet:
import torch
mha = torch.nn.MultiheadAttention(embed_dim=32, num_heads=4)
query = torch.rand(10, 2, 32)
key = torch.rand(10, 2, 16)
value = torch.rand(10, 2, 32)
output, weights = mha(query, key, value)
medium
A. The embed_dim of key does not match embed_dim of query and value
B. The batch size is incorrect
C. The sequence length is too large
D. The number of heads is too high

Solution

  1. Step 1: Check embed_dim consistency

    MultiheadAttention requires query, key, and value to have the same embedding dimension. Here, key has embed_dim 16, while query and value have 32.
  2. Step 2: Identify the error cause

    This mismatch causes a runtime error because the attention mechanism cannot align different embedding sizes.
  3. Final Answer:

    The embed_dim of key does not match embed_dim of query and value -> Option A
  4. Quick Check:

    Embed dims must match for query, key, value [OK]
Hint: Check all embed_dims match before calling attention [OK]
Common Mistakes:
  • Ignoring embed_dim mismatch
  • Assuming batch size causes error
  • Thinking sequence length is the problem
5. You want to apply multi-head attention to a batch of sentences with varying lengths. Which PyTorch feature helps you handle padding tokens correctly during attention computation?
hard
A. Increasing the number of heads to cover padding
B. Setting batch_first=True in MultiheadAttention
C. Using the key_padding_mask argument in MultiheadAttention
D. Manually removing padding tokens before attention

Solution

  1. Step 1: Understand padding in variable-length sequences

    Sentences have different lengths, so padding tokens are added to make batch tensors uniform.
  2. Step 2: Use key_padding_mask to ignore padding

    PyTorch's MultiheadAttention accepts key_padding_mask to mask out padded positions during attention, preventing them from affecting results.
  3. Final Answer:

    Using the key_padding_mask argument in MultiheadAttention -> Option C
  4. Quick Check:

    Mask padding tokens with key_padding_mask [OK]
Hint: Use key_padding_mask to ignore padded tokens [OK]
Common Mistakes:
  • Removing padding manually (inefficient)
  • Confusing batch_first with padding handling
  • Increasing heads does not fix padding
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard