Explain the purpose and benefits of using multi-head attention in transformer models.
Multi-head attention splits queries, keys, and values into h parallel lower-dimensional heads (d_k = d_model / h) with distinct learned projections, allowing each head to attend to different syntactic, positional, or semantic subspaces simultaneously. Because each head operates in a reduced d_k dimension, multi-head attention captures richer relational patterns at roughly the same compute cost as full-dimension single-head attention. Modern LLMs also use Multi-Query (MQA) and Grouped-Query Attention (GQA) to shrink KV-cache memory.
Study Card: Multi-Head Attention in Transformers
Direct Answer
Multi-Head Attention (MHA) (Vaswani et al., 2017) replaces a single full-dimensional attention operation with parallel attention heads operating in distinct learned representation subspaces of dimension :
where , , and .
Why MHA is so effective:
- Prevents Softmax Averaging Bottlenecks: A single attention head outputs a single convex combination of token values per position; multi-head attention lets different heads simultaneously track syntactic subject-verb links, pronoun coreference, positional neighbors, and semantic modifiers without blurring them together.
- Roughly Constant Compute Cost: Because each head shrinks projection size to , total projection parameters () and attention FLOPs stay essentially identical to single-head attention at full , while gaining independent attention matrices.
- Ensemble & Gradient Richness: Parallel subspace projections yield smoother optimization and specialization across heads (with modern LLMs extending MHA via MQA and GQA to reduce KV-cache memory during decoding).
Key Terms
- Attention Head (): Independent scaled dot-product attention module operating on a -dimensional subspace.
- Subspace Projections (): Learned matrices mapping inputs into specialized relational spaces before concatenation and mixing via .
- Constant-Compute Partitioning (): Keeps total FLOPs comparable to single-head attention while multiplying relational expressivity.
- Multi-Query (MQA) & Grouped-Query Attention (GQA): Variants that keep distinct query heads while sharing (MQA) or (GQA) key/value heads to drastically shrink autoregressive KV-cache memory bandwidth.
Example
Consider "The trophy wouldn't fit into the brown suitcase because it was too big":
- Head 1 (Syntactic): Attends from
"fit"back to"trophy"and"suitcase"(verb arguments). - Head 2 (Local Modifier): Links
"brown"directly to"suitcase". - Head 3 (Coreference / Semantic): Resolves
"it"strongly toward"trophy"using"big"context.
Concatenating all heads and mixing via preserves every distinct relationship simultaneously.
Code Implementation
import torch
import torch.nn as nn
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads):
super().__init__()
assert d_model % num_heads == 0, "d_model must be divisible by num_heads"
self.num_heads = num_heads
self.d_k = d_model // num_heads
# Joint projections across all heads (equivalent to concatenating h per-head projections)
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 scaled_dot_product_attention(self, q, k, v, mask=None):
# q: (B, H, seq_len_q, d_k), k/v: (B, H, seq_len_k, d_k)
attn_scores = torch.matmul(q, k.transpose(-2, -1)) / (self.d_k ** 0.5)
if mask is not None:
attn_scores = attn_scores.masked_fill(mask == 0, float("-inf"))
attn_weights = torch.softmax(attn_scores, dim=-1)
output = torch.matmul(attn_weights, v)
return output, attn_weights
def forward(self, q, k, v, mask=None):
batch_size = q.size(0)
# Reshape & transpose into (batch_size, num_heads, seq_len, d_k)
q = self.W_q(q).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
k = self.W_k(k).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
v = self.W_v(v).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
attn_output, attn_weights = self.scaled_dot_product_attention(q, k, v, mask)
# Concatenate heads back to (batch_size, seq_len_q, d_model) and mix via W_o
attn_output = (
attn_output.transpose(1, 2)
.contiguous()
.view(batch_size, -1, self.num_heads * self.d_k)
)
return self.W_o(attn_output), attn_weights
torch.manual_seed(0)
batch_size, seq_len, d_model, num_heads = 4, 10, 512, 8
x = torch.randn(batch_size, seq_len, d_model)
mha = MultiHeadAttention(d_model, num_heads)
output, attn_weights = mha(x, x, x)
print("Output shape:", output.shape) # (4, 10, 512)
print("Attention weights shape:", attn_weights.shape) # (4, 8, 10, 10)
Related Concepts
- Grouped-Query Attention (GQA) & Multi-Head Latent Attention (MLA): Standard in LLaMA-3, Mistral, and DeepSeek to break memory-bandwidth limits from large MHA KV caches during generation.
- Head Pruning & Induction Heads: Mechanistic interpretability shows specific heads act as induction heads supporting in-context copying and pattern completion, while some redundant heads can be pruned.
- Rotary Position Embeddings (RoPE): Applied per head on and vectors prior to dot-product scoring.
- Cross-Attention: Uses the exact same multi-head mechanism with coming from one sequence/modality and from another.