Multi-Head Attention
Running H independent attention heads in parallel so each can specialise in a different type of dependency.
Single-head attention produces one weighted combination of the value vectors. But the previous article showed that attention weights encode a specific pattern — subject-verb dependencies, modifier-noun relationships, pronoun-antecedent coreference — and a single distribution over positions cannot specialize in all of these simultaneously. When the head focuses on syntax, it may lose track of semantics; when it attends to nearby context, it may miss distant references.
Multi-head attention addresses this by running independent attention computations in parallel, each free to learn a different projection of the input and a different type of dependency.
H Parallel Heads
Each head has its own set of learned projection matrices:
Given the input , head computes its own query, key, and value matrices and runs scaled dot-product attention:
The head outputs are concatenated along the last dimension:
A final learned projection maps this back to dimension :
The standard choice makes the concatenated output exactly , so the model dimension is preserved.
Parameter Count and Efficient Computation
With , the parameter count is:
| Component | Matrices | Parameters |
|---|---|---|
| Queries | ||
| Keys | ||
| Values | ||
| Output | ||
| Total |
The total is the same as a single attention head with plus an output projection — the model has not become larger, it has redistributed the same budget across specialized subspaces. For GPT-2 small (, ): million parameters per attention layer.
Practical implementation. Computing separate matrix multiplications would be inefficient. In practice, all heads are computed in a single batched operation: the projection (where bundles all head projections) produces , which is then reshaped to and transposed to . All sets of attention scores are then computed simultaneously in a single batched matrix multiplication. This keeps the GPU fully utilised.
What Heads Learn
The projections and map the input to different -dimensional subspaces. Head computes dot-product similarities in the subspace defined by its projections. Subspaces that are useful for detecting subject-verb agreement look different from those useful for detecting coreference, so different heads can specialize.
Empirical analyses of trained transformers consistently find that heads do develop distinct patterns. Some heads attend locally (a few positions on each side), others look globally across the sequence. Some heads appear to track syntactic structure, others semantic similarity, others copying behaviour (attending to the same token type at a different position). This specialization is not enforced by the architecture — it emerges from training on a language modelling objective.
An Algebraic View
The final output can be decomposed as a sum over heads:
where is the row slice of corresponding to head . Each head independently computes an attention-weighted representation, then projects it to the full -dimensional space. The final output is the sum of such contributions.
This view clarifies what does: it mixes the heads' individual outputs into a single representation, allowing the model to combine information gathered by different specialised attention patterns.
Typical Hyperparameters
| Model | |||
|---|---|---|---|
| Original Transformer (base) | 512 | 8 | 64 |
| BERT-base | 768 | 12 | 64 |
| GPT-2 small | 768 | 12 | 64 |
| GPT-2 medium | 1,024 | 16 | 64 |
| GPT-2 large | 1,280 | 20 | 64 |
The per-head dimension is remarkably consistent across models of very different scales. The convention (equivalently, one head per 64 dimensions of ) has proven robust and is widely adopted. Increasing while keeping fixed simply increases .
In Code
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadAttention(nn.Module):
def __init__(self, d_model: int, num_heads: int):
super().__init__()
assert d_model % num_heads == 0
self.H = num_heads
self.dk = d_model // num_heads
# One projection for all heads (more efficient than H separate ones):
# the output of W_Q is later split into H chunks of size dk, one per head
self.W_Q = nn.Linear(d_model, d_model, bias=False)
self.W_K = nn.Linear(d_model, d_model, bias=False)
self.W_V = nn.Linear(d_model, d_model, bias=False)
self.W_O = nn.Linear(d_model, d_model, bias=False)
def forward(self, x: torch.Tensor, causal: bool = False) -> torch.Tensor:
B, T, D = x.shape
# Project and reshape to (B, H, T, dk)
def split_heads(t):
return t.view(B, T, self.H, self.dk).transpose(1, 2)
Q = split_heads(self.W_Q(x)) # (B, H, T, dk)
K = split_heads(self.W_K(x))
V = split_heads(self.W_V(x))
# All H heads computed in parallel
scores = Q @ K.transpose(-2, -1) / math.sqrt(self.dk) # (B, H, T, T)
if causal:
mask = torch.triu(torch.ones(T, T, dtype=torch.bool, device=x.device), diagonal=1)
scores = scores.masked_fill(mask, float("-inf"))
A = F.softmax(scores, dim=-1) # (B, H, T, T)
out = A @ V # (B, H, T, dk)
# Merge heads: (B, H, T, dk) → (B, T, H·dk) = (B, T, D)
out = out.transpose(1, 2).contiguous().view(B, T, D)
# W_O mixes what the heads found: concat(heads) @ W_O
return self.W_O(out) # (B, T, D)
# Usage
mha = MultiHeadAttention(d_model=512, num_heads=8) # dk = 64 per head
x = torch.randn(2, 10, 512) # batch=2, seq_len=10
z = mha(x, causal=True)
print(z.shape) # torch.Size([2, 10, 512]) — same shape as the input
# Parameter count: 4 × 512² = 1,048,576
print(sum(p.numel() for p in mha.parameters())) # 1048576
# Gradients flow through all projections of all heads
z.sum().backward()
print(mha.W_Q.weight.grad.shape) # torch.Size([512, 512]) — ∂L/∂W_Q, all heads at once
# PyTorch's native implementation (uses Flash Attention on GPU)
mha_torch = nn.MultiheadAttention(
embed_dim=512, num_heads=8, batch_first=True, bias=False
)
out, weights = mha_torch(x, x, x, need_weights=False)
print(out.shape) # torch.Size([2, 10, 512])
Multi-head attention is complete: parallel heads each compute their own attention-weighted representation, and the concatenated result is projected back to dimension . A full transformer layer wraps this operation in two additional components — layer normalisation to stabilise training and a position-wise feed-forward network to transform the aggregated representations. The next article assembles these into the complete transformer block.