Build a Causal Multi-Head Attention Layer from Scratch
Machine LearningModel answerLast updated
Write a multi-head self-attention module with Q/K/V projections, scaled scores, and a causal mask so each token sees only itself and earlier tokens, then explain how it works.
Task
Build a self-attention layer for a decoder-style Transformer, written in PyTorch (NumPy is also acceptable). The layer must split its work across several heads and must be causal: the output at position i may depend only on input positions 0..i.
Interface
class MultiHeadAttention:
def __init__(self, d_model, n_heads):
# Create the layers needed for Q, K, V and the final output projection
...
def forward(self, x):
# x: (batch_size, seq_len, d_model)
# returns: (batch_size, seq_len, d_model)
...
What the layer must do
- Project. Map
xthrough three separated_model -> d_modellinear layers to obtain queries, keys and values. - Split into heads. Divide each projected tensor into
n_headschunks of sized_k = d_model // n_heads, so that each head works on its own slice. - Score. For every head compute
softmax(Q Kᵀ / sqrt(d_k) + mask) V. - Mask the future. Before the softmax, block every score where the key position is later than the query position, using
-inf(or a very large negative value). Positionimay attend to positionsj <= i, which is the lower-triangular region including the diagonal. - Merge. Concatenate the head outputs and apply a final
d_model -> d_modellinear projection.
Example
With x of shape (1, 3, 8) and n_heads = 2, each head has d_k = 4. Token 0 can only see itself, token 1 can see tokens 0 and 1, and token 2 can see tokens 0, 1 and 2. The output has shape (1, 3, 8).
Constraints
d_modelis divisible byn_heads.- The output shape equals the input shape.
What to cover in your answer
- Working code.
- Why the scores are divided by
sqrt(d_k). - How you verify that the layer is really causal.
- Time and memory complexity, and the edge cases you would guard against.
- Briefly, how you would extend the layer for padded batches and for fast autoregressive inference.
Hints
Hint 1
After projecting, reshape (B, T, d_model) into (B, T, n_heads, d_k) and swap the two middle axes, so the head dimension behaves like an extra batch dimension for the matrix multiplications.
Hint 2
The score matrix per head is T x T. The positions to block are the ones strictly above the diagonal, so torch.triu(..., diagonal=1) gives the boolean mask to pass to masked_fill. The diagonal itself must stay visible.
Hint 3
To prove causality, change only the last token of the input and check that the outputs at all earlier positions are unchanged. Also check that every attention row sums to 1 and has zeros above the diagonal.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Multi-head attention runs several smaller attentions in parallel, each on a d_k = d_model / n_heads slice of the projected representation, then recombines them. Treating the head axis as an extra batch axis lets one batched matrix multiply handle all heads at once.
Steps:
- Compute
Q = x W_q,K = x W_k,V = x W_v, each of shape(B, T, d_model). - Reshape to
(B, T, h, d_k)and transpose to(B, h, T, d_k). - Compute scores
Q Kᵀ / sqrt(d_k)of shape(B, h, T, T). - Set scores to
-infwherej > i(strictly above the diagonal). - Apply softmax over the last axis (the keys), then multiply by
Vto get(B, h, T, d_k). - Transpose back to
(B, T, h, d_k), flatten to(B, T, d_model), and applyW_o.
A point that is easy to get backwards: the allowed region is lower-triangular, but the -inf entries go in the strict upper triangle.
Code
import math
import torch
import torch.nn as nn
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
assert d_model % n_heads == 0, "d_model must be divisible by n_heads"
self.d_model = d_model
self.n_heads = n_heads
self.d_k = d_model // n_heads
self.w_q = nn.Linear(d_model, d_model)
self.w_k = nn.Linear(d_model, d_model)
self.w_v = nn.Linear(d_model, d_model)
self.w_o = nn.Linear(d_model, d_model)
def _split(self, t):
B, T, _ = t.shape
return t.view(B, T, self.n_heads, self.d_k).transpose(1, 2)
def _merge(self, t):
B, _, T, _ = t.shape
return t.transpose(1, 2).contiguous().view(B, T, self.d_model)
def forward(self, x):
B, T, _ = x.shape
q = self._split(self.w_q(x))
k = self._split(self.w_k(x))
v = self._split(self.w_v(x))
scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.d_k) # (B, h, T, T)
future = torch.triu(
torch.ones(T, T, dtype=torch.bool, device=x.device), diagonal=1
)
scores = scores.masked_fill(future, float("-inf"))
attn = torch.softmax(scores, dim=-1)
out = attn @ v # (B, h, T, d_k)
return self.w_o(self._merge(out))
Subclassing nn.Module means layer(x) calls forward, and the parameters are registered automatically.
Why it is correct
- Causality. For query
i, all keysj > iget-inf, andexp(-inf) = 0, so all probability mass falls on positions0..i. The diagonal is never masked, so no row is entirely-inf, which means softmax cannot produce NaN here. - Head independence.
view(B, T, h, d_k)cuts the last dimension into contiguous chunks, one per head. After the transpose, the batched matmul computes each head separately. - Shape. Merging reverses the split exactly and
W_oisd_model -> d_model, so the output matches the input shape.
Why divide by sqrt(d_k)
If entries of q and k are independent with mean 0 and variance 1, then q·k is a sum of d_k products with variance d_k. Unscaled logits therefore grow with head size, pushing softmax toward one-hot outputs whose gradients are close to zero, which stalls training. Dividing by sqrt(d_k) restores a logit variance of about 1 regardless of head size.
Complexity
With B batch, T sequence length, d = d_model:
- Time: projections cost
O(B·T·d²);QKᵀandattn @ VcostO(B·T²·d)across heads. TotalO(B·T·d·(d + T)). - Memory: attention scores are
O(B·h·T²)and dominate for long sequences; activations areO(B·T·d); parameters are4d² + 4d.
Verification
- Every row of
attnsums to 1, andattn[..., i, j] == 0forj > i. - The real causality test: perturb
x[:, 2]and confirmy[:, 0]andy[:, 1]are unchanged. - Compare against
torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True)using the same weights.
Edge cases and common mistakes
d_model % n_heads != 0: fail fast with an assertion.T = 1: the token attends only to itself with weight 1.n_heads = 1: reduces to ordinary single-head attention.- Masking the wrong triangle (blocking the past, or masking the diagonal) is the most common bug.
- Forgetting
.contiguous()before.viewafter a transpose (or use.reshape). - Adding
-1e9in fp16 can overflow; prefermasked_fillwith-inf, ortorch.finfo(dtype).minif a constant is required. - Softmax over the wrong axis: it must be over keys (the last dimension).
- Building the mask on the wrong device: create it on
x.device, and cache it ifTis fixed.
Extensions
Padding masks. Take a boolean key_padding_mask of shape (B, T) with True for pad tokens, broadcast it to (B, 1, 1, T), and OR it with the causal mask. With left padding, pad query rows can be fully masked, and softmax over all -inf gives NaN. Use finfo.min instead of -inf, or zero those rows with nan_to_num, and exclude pad positions from the loss.
KV cache for generation. After a prefill pass over the prompt, store each layer's K and V. At each decode step, project only the new token, append its k, v to the cache, and attend the single query over the whole cache. This costs O(T·d) per step instead of O(T²·d), and no causal mask is needed because everything cached is in the past. Cache size is about 2 · layers · h · d_k · T · bytes per sequence. It can be reduced with preallocated or paged buffers, grouped-query or multi-query attention (fewer K/V heads), int8/fp8 quantization, or sliding-window eviction.