Build Multi-Head Attention in PyTorch Without Library Helpers
Machine LearningModel answerLast updated
Write a multi-head attention module from raw tensor ops: projections, head reshaping, scaled scores, masking, softmax, and output merge, plus cost and testing discussion.
You are asked to write, from scratch, a layer that performs multi-head attention. Treat it as a live coding exercise followed by a discussion.
The task
The layer takes three batched inputs:
querywith shape(batch, len_q, d_model)keywith shape(batch, len_k, d_model)valuewith shape(batch, len_k, d_model)
It must:
- Apply a learned linear projection to each of the three inputs.
- Split each projection into
num_headsheads. - Compute scaled dot-product attention separately in every head.
- Join the heads back together and pass the result through a final learned linear projection.
- Accept an optional mask that stops certain query/key pairs from interacting.
Rules
- Use NumPy or PyTorch. Matrix multiplication, reshape, transpose, softmax and linear layers are fine.
- Library attention modules (
torch.nn.MultiheadAttention,torch.nn.functional.scaled_dot_product_attention) are off limits. - You may assume
d_modelis divisible bynum_heads.
What to be ready to discuss
- Should the same code serve self-attention and cross-attention (where
len_qandlen_kdiffer)? - Which masks do you need (padding, causal, or both), and what convention does the boolean mask follow?
- Should the layer support attention dropout or return the attention weights?
- How would you check correctness, including gradients and behavior in half precision?
- How do time and memory scale with sequence length, model width and head count?
Hints
Hint 1
Project first with full-width `d_model x d_model` matrices, then reshape to `(batch, len, num_heads, d_head)` and transpose to `(batch, num_heads, len, d_head)` so one batched matmul handles all heads.
Hint 2
Scores have shape `(batch, heads, len_q, len_k)`. Divide by `sqrt(d_head)`, fill blocked positions with a large negative number (or `-inf`) before softmax, and softmax over the last (key) axis.
Hint 3
Think about edge cases: a query row where every key is masked yields NaN with `-inf`; half precision can overflow with large negative constants; and the merge step needs `contiguous()` or `reshape` after transposing back.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Do one big projection per input, reshape into heads, run batched attention over a 4D tensor, then undo the reshape and project the output.
Let d_head = d_model / num_heads.
- Project:
Q = x_q @ W_q,K = x_k @ W_k,V = x_v @ W_v, each of shape(B, L, d_model). Doing a singled_model x d_modelmatmul is equivalent tonum_headssmaller projections but much faster. - Split heads: reshape to
(B, L, H, d_head), then transpose to(B, H, L, d_head). - Scores:
scores = Q @ K.transpose(-2, -1) / sqrt(d_head)giving(B, H, len_q, len_k). - Mask: set blocked entries to a very negative value.
- Softmax over the last axis, optionally apply dropout to the weights.
- Weighted sum:
ctx = weights @ Vgiving(B, H, len_q, d_head). - Merge: transpose to
(B, len_q, H, d_head), reshape to(B, len_q, d_model), then applyW_o.
Code
import math
import torch
import torch.nn as nn
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads, dropout=0.0):
super().__init__()
assert d_model % num_heads == 0
self.h = num_heads
self.d_head = d_model // num_heads
self.wq = nn.Linear(d_model, d_model)
self.wk = nn.Linear(d_model, d_model)
self.wv = nn.Linear(d_model, d_model)
self.wo = nn.Linear(d_model, d_model)
self.drop = nn.Dropout(dropout)
def _split(self, x):
B, L, _ = x.shape
return x.view(B, L, self.h, self.d_head).transpose(1, 2)
def forward(self, q, k, v, mask=None):
# mask: bool, True = allowed, broadcastable to (B, H, Lq, Lk)
Q, K, V = self._split(self.wq(q)), self._split(self.wk(k)), self._split(self.wv(v))
scores = Q @ K.transpose(-2, -1) / math.sqrt(self.d_head)
if mask is not None:
scores = scores.masked_fill(~mask, float("-inf"))
w = torch.softmax(scores, dim=-1)
w = torch.nan_to_num(w, nan=0.0) # fully masked rows -> zeros
w = self.drop(w)
ctx = (w @ V).transpose(1, 2).reshape(q.size(0), q.size(1), -1)
return self.wo(ctx), w
Mask building examples:
- Key padding:
pad_ok[:, None, None, :]of shape(B,1,1,Lk), True where the token is real. - Causal:
torch.tril(torch.ones(Lq, Lk, dtype=torch.bool))[None, None]. - Both: combine with
&.
Why the details matter
- Scaling by
sqrt(d_head): dot products of random vectors have variance proportional tod_head. Without scaling, scores grow, softmax saturates, and gradients vanish. Used_head, notd_model. - Softmax axis: over keys (last dim), so each query's weights sum to 1.
- Mask before softmax: masking after softmax leaves weights that no longer sum to 1. Fill, then softmax.
- Fully masked rows: with
-infeverywhere, softmax returns NaN (0/0). Eithernan_to_num, or use a finite large negative (e.g.-1e9, ortorch.finfo(dtype).min), which yields a uniform distribution over masked keys instead. Decide which behavior you want and document it. - Half precision:
-1e9overflows in fp16 (max about 65504). Usefinfo(dtype).minand compute softmax in fp32 if needed. PyTorch's softmax is already max-subtracted, so large scores alone do not overflow. - Memory layout: after
transpose, the tensor is non-contiguous, soviewfails. Usereshapeor.contiguous().view.
Complexity
- Projections:
O(B * (Lq + 2Lk) * d_model^2)plus the output projectionO(B * Lq * d_model^2). - Scores and weighted sum:
O(B * H * Lq * Lk * d_head) = O(B * Lq * Lk * d_model). This is independent of head count in FLOPs. - Memory: the score tensor is
B * H * Lq * Lkelements, quadratic in sequence length and linear in heads. For example,B=8, H=16, L=4096in fp16 is about8*16*4096*4096*2 B ≈ 4.3 GBfor one layer's weights alone. This is why fused kernels (FlashAttention-style tiling) avoid materializing the full matrix.
Testing
- Compare to
torch.nn.functional.scaled_dot_product_attention(as a reference only, in tests) on random inputs withallclose. - Causal check: perturb future tokens and confirm earlier outputs do not change.
- Padding check: changing padded key/value contents must not alter outputs.
- Shape check with
len_q != len_k(cross-attention). torch.autograd.gradcheckin float64 on small sizes; confirm no NaN gradients with a fully masked row.- Run in fp16/bf16 and compare to fp32 within tolerance.
Common mistakes
- Reshaping
(B, L, d_model)directly to(B, H, L, d_head)without the transpose, which silently mixes tokens and heads. - Scaling by
sqrt(d_model)or forgetting to scale. - Softmax over the wrong axis.
- Inverting the mask convention (True meaning blocked vs. allowed).
- Applying the mask with a shape that does not broadcast across heads.
- Using
viewafter transpose.
Trade-offs and follow-ups
- Separate projections per head versus one fused matmul: the fused version is mathematically identical and faster.
- Fusing
W_q, W_k, W_vinto one matmul works for self-attention; cross-attention needs separate K/V projection from the other source. - For long sequences, consider sparse or sliding-window attention, multi-query / grouped-query attention to shrink KV cache, and KV caching for autoregressive decoding.