Multihead attention
Quick answer
Multihead attention learns several projected attention operations in parallel, concatenates their outputs, and applies an output projection. Examples are static Python snippets tested locally on CPU; PyTorch is required for selected examples. ByteMind execution is unverified.
Native head shapes
import torchm=torch.nn.MultiheadAttention(12,3,batch_first=True,dropout=0.)x=torch.zeros(2,5,12)y,w=m(x,x,x,average_attn_weights=False)print(list(y.shape),list(w.shape),sum(p.numel() for p in m.parameters()))Expected output (locally tested): [2, 5, 12] [2, 3, 5, 5] 624. Three heads of width four and four biased projections.
How it works
With d_model divisible by h heads, the common equal-width layout has d_head=d_model/h. Starting with (B,L,d_model), project queries, reshape to (B,L,h,d_head) and transpose to (B,h,L,d_head); keys and values similarly use S. Score tensors have shape (B,h,L,S). Each head normalizes across S and returns (B,h,L,d_head). Transpose and concatenate back to (B,L,d_model), then multiply by W_O. Head-specific projections allow different learned interactions but no head is guaranteed to encode a human-readable concept. In standard equal-width self-attention, four d_model by d_model weight matrices and four d_model bias vectors give 4d_model^2+4d_model parameters when bias is enabled; other configurations differ. Attention score storage scales with BhL*S if materialized; optimized kernels may avoid materializing the full matrix. PyTorch MultiheadAttention with batch_first=True accepts (B,L,d_model) and can return per-head weights if average_attn_weights=False. Its Boolean masks block True, unlike functional SDPA. If weights are unnecessary, need_weights=False can enable more efficient paths.
Concatenate head features
import torchh=torch.tensor([[[[1.,2.],[3.,4.]],[[5.,6.],[7.,8.]]]])print(h.transpose(1,2).reshape(1,2,4).tolist())Expected output (locally tested): [[[1.0, 2.0, 5.0, 6.0], [3.0, 4.0, 7.0, 8.0]]]. The time axis stays intact while head features join.
Common mistakes
Do not split the time axis into heads, average head outputs in place of concatenation, or assume increasing head count increases the standard projection parameter count at fixed width.
Practice and next steps
For batch=2, length=5, width=12 and heads=3, compute head width and score shape. Compare per-head and averaged attention weight shapes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Multihead attention — knowledge check
Apply multihead attention to small examples and debugging scenarios.
What axis is divided across heads?
How combine heads before the output projection?
What is head width for d_model=12 and h=3?
What is a per-head score shape?
Are head roles guaranteed interpretable?