Build a Scaled Dot-Product Multi-Head Attention Block
Machine LearningModel answerLast updated
Write a PyTorch multi-head self-attention module that projects, splits into heads, attends, merges, and projects back to the input shape.
Task: Write a Multi-Head Self-Attention Module
Using PyTorch, implement a MultiHeadAttention nn.Module that takes an input tensor x of shape (batch_size, seq_len, embed_dim) and returns a tensor with the identical shape.
Your implementation must:
- Project to Q, K, V. Apply three independent linear layers (no bias sharing between them) to produce query, key, and value tensors, each of shape
(batch_size, seq_len, embed_dim). - Split into heads. Reorganize each of Q, K, V into
(batch_size, num_heads, seq_len, head_dim), wherehead_dim = embed_dim // num_heads. - Attend. Compute
softmax((Q @ K.transpose(-2, -1)) / sqrt(head_dim)) @ Vusingtorch.softmax. - Merge and project. Concatenate the per-head outputs back along the feature axis and pass the result through one final linear layer.
Required signature
import torch
import torch.nn as nn
class MultiHeadAttention(nn.Module):
def __init__(self, embed_dim, num_heads):
super().__init__()
pass
def forward(self, x):
pass
Constraints
embed_dimmust be divisible bynum_heads; otherwise raise an error.- Use
torch.softmaxfor the attention weights. - Do not hardcode batch size or sequence length — any batch size must work.
Example
mha = MultiHeadAttention(embed_dim=512, num_heads=8)
x = torch.randn(32, 10, 512)
assert mha(x).shape == (32, 10, 512)
Edge cases to reason about
seq_len == 1.batch_size == 1and other arbitrary batch sizes.- An
embed_dimthat is not divisible bynum_heads.
Discuss in your answer: the shape at each step, why the 1/sqrt(head_dim) scaling is needed, the computational cost, and how padding or causal masks would be applied.
Hints
Hint 1
The key trick is the layout `(B, H, L, d)` — with that arrangement, `torch.matmul` batches over `(B, H)` automatically, so no Python loop over heads is needed.
Hint 2
To merge heads, transpose dimensions 1 and 2 back, then flatten the last two dimensions; use `reshape` (or call `.contiguous()` before `view`) because the transposed tensor is not contiguous.
Hint 3
Softmax must be applied over the key axis (`dim=-1`), and masked positions should be filled with `-inf` *before* the softmax so they receive zero weight.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each token in the sequence produces a query, a key, and a value. A query is compared against every key to obtain similarity scores; softmax turns each row of scores into a distribution over positions, and that distribution is used to average the value vectors. "Multi-head" means running several such attention computations in parallel, each in its own d = embed_dim // num_heads dimensional subspace, then merging the results.
The whole thing is shape bookkeeping plus four linear layers.
| Step | Tensor shape |
|---|---|
Input x | (B, L, D) |
q_proj(x), k_proj(x), v_proj(x) | (B, L, D) each |
| Split heads | (B, H, L, d) each |
Scores Q @ K^T * scale | (B, H, L, L) |
| Weights (softmax over last dim) | (B, H, L, L) |
Context weights @ V | (B, H, L, d) |
| Merge heads | (B, L, D) |
out_proj(...) | (B, L, D) |
Implementation
import math
import torch
import torch.nn as nn
class MultiHeadAttention(nn.Module):
def __init__(self, embed_dim, num_heads):
super().__init__()
if embed_dim % num_heads != 0:
raise ValueError("embed_dim must be divisible by num_heads")
self.embed_dim = embed_dim
self.num_heads = num_heads
self.head_dim = embed_dim // num_heads
self.scale = 1.0 / math.sqrt(self.head_dim)
self.q_proj = nn.Linear(embed_dim, embed_dim)
self.k_proj = nn.Linear(embed_dim, embed_dim)
self.v_proj = nn.Linear(embed_dim, embed_dim)
self.out_proj = nn.Linear(embed_dim, embed_dim)
def _split_heads(self, t, batch_size, seq_len):
# (B, L, D) -> (B, L, H, d) -> (B, H, L, d)
return t.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
def forward(self, x):
# x: (B, L, D)
batch_size, seq_len, _ = x.size()
q = self._split_heads(self.q_proj(x), batch_size, seq_len)
k = self._split_heads(self.k_proj(x), batch_size, seq_len)
v = self._split_heads(self.v_proj(x), batch_size, seq_len)
# (B, H, L, d) @ (B, H, d, L) -> (B, H, L, L)
scores = torch.matmul(q, k.transpose(-2, -1)) * self.scale
weights = torch.softmax(scores, dim=-1)
# (B, H, L, L) @ (B, H, L, d) -> (B, H, L, d)
context = torch.matmul(weights, v)
# (B, H, L, d) -> (B, L, H, d) -> (B, L, D)
context = context.transpose(1, 2).contiguous().view(batch_size, seq_len, self.embed_dim)
return self.out_proj(context)
mha = MultiHeadAttention(embed_dim=512, num_heads=8)
assert mha(torch.randn(32, 10, 512)).shape == (32, 10, 512)
assert mha(torch.randn(3, 1, 512)).shape == (3, 1, 512)
Why it works
Head splitting is a reinterpretation, not extra parameters. Viewing the last axis of size D as (H, d) assigns feature slice [h*d, (h+1)*d) to head h. This is exactly equivalent to having H independent D -> d projections, but fused into one larger matmul, so it is faster in practice.
The layout does the batching. With (B, H, L, d), torch.matmul treats everything but the last two dimensions as batch dimensions, computing one L x L attention matrix per (batch, head) pair without any explicit loop.
Softmax axis matters. dim=-1 normalizes across keys: weights[b, h, i, :] is a probability distribution over which position query i attends to. Softmaxing over the query axis instead still produces valid-looking shapes but computes the wrong function.
Why scale by 1/sqrt(d). If query and key components have roughly unit variance and are near-independent, then q · k is a sum of d products, so its variance grows like d and its standard deviation like sqrt(d). Dividing by sqrt(d) restores unit-variance scores, keeping the softmax out of its saturated regime where it becomes nearly one-hot and gradients vanish.
Merging inverts the split. transpose(1, 2) returns to (B, L, H, d) and flattening the last two axes concatenates heads in the original head order. .contiguous() is needed before view; reshape would handle it automatically. The final out_proj mixes information across heads — without it each head's output would stay trapped in its own slice.
Complexity
- Projections:
O(B · L · D²). - Score computation and weighted sum:
O(B · H · L² · d) = O(B · L² · D). - Total time:
O(B · L · D² + B · L² · D). TheL²term dominates for long sequences, which is why very long inputs need sparse or linear attention variants. - Activation memory:
O(B · L · D)for the projections plusO(B · H · L²)for the score and weight matrices that backprop keeps alive. Parameters:4D² + 4D.
Edge cases
seq_len == 1: the score matrix is1 x 1, softmax returns exactly1.0, and the output equalsout_proj(v_proj(x)). No special code needed.- Any batch size: shapes are read from
x.size()at runtime, so batch size 1 and large batches work identically. - Indivisible
embed_dim: rejected in the constructor with a clear message, rather than failing later insideviewwith a confusing shape error. - Numerics:
torch.softmaxsubtracts the row maximum internally, so large scores do not overflow.
Extending with masks
For a boolean padding mask of shape (B, L) where True marks pad tokens, broadcast it to (B, 1, 1, L) and apply it to the scores before the softmax:
scores = scores.masked_fill(pad_mask[:, None, None, :], float("-inf"))
Masked keys then get exactly zero weight. A causal mask uses an upper-triangular (L, L) boolean matrix instead. Two caveats: if a whole query row is masked, softmax over all -inf yields NaN — use torch.finfo(scores.dtype).min or zero those rows out; and in mixed precision a large finite negative number is safer than a hardcoded -1e9.