Multi-Head Attention

Multi-Head Attention (MHA) is the central computational primitive of the Transformer architecture, enabling a model to jointly attend to information from multiple representation subspaces at different positions simultaneously. It matters because virtually every state-of-the-art model in NLP, vision, and multimodal AI — from GPT-4 to Stable Diffusion — is built on it as a foundational operation. The counterintuitive fact: adding more heads does not increase the total computation budget, because each head operates on a proportionally smaller projection of the input, keeping FLOPs roughly constant.

The core insight

A single attention pass forces the model to blend all relational information into one weighted average, losing the ability to simultaneously track different kinds of relationships (syntactic, semantic, co-referential, positional). Multi-Head Attention sidesteps this by running several independent attention operations in parallel on lower-dimensional projections, then concatenating and re-projecting the results. The "aha moment" is that each head learns a distinct relational inductive bias — one head may track subject-verb agreement while another tracks coreference — without any explicit supervision telling it to do so. The final linear projection then fuses these diverse relationship signals into a single rich representation.

How It Works

Scaled Dot-Product Attention

The building block of MHA is Scaled Dot-Product Attention. Given a matrix of queries Q∈RTq×dkQ \in \mathbb{R}^{T_q \times d_k}, keys K∈RTk×dkK \in \mathbb{R}^{T_k \times d_k}, and values V∈RTk×dvV \in \mathbb{R}^{T_k \times d_v}:

1
Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\quad \text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V

Explanation: Each query vector dot-products with every key vector to produce a raw compatibility score, which is scaled to prevent vanishing gradients in the softmax, normalized to a probability distribution, and used to form a weighted sum of the value vectors. The dk\sqrt{d_k} scaling factor is critical. Without it, dot products grow with dimensionality, pushing the softmax into regions of near-zero gradient:

2
Var(q⋅k)=dk⟹Var ⁣(q⋅kdk)=1\quad \text{Var}(q \cdot k) = d_k \quad \Longrightarrow \quad \text{Var}\!\left(\frac{q \cdot k}{\sqrt{d_k}}\right) = 1

Explanation: Assuming query and key components are i.i.d. with zero mean and unit variance, dividing by dk\sqrt{d_k} normalizes the dot-product variance to 1 regardless of dimensionality, stabilizing training.

Projecting Into Multiple Subspaces

Multi-Head Attention applies hh independent learned linear projections to (Q,K,V)(Q, K, V) before computing attention:

3
headi=Attention(QWiQ,  KWiK,  VWiV)\quad \text{head}_i = \text{Attention}(Q W_i^Q,\; K W_i^K,\; V W_i^V)

Explanation: Each head ii learns its own projection matrices WiQ∈Rdmodel×dkW_i^Q \in \mathbb{R}^{d_{\text{model}} \times d_k}, WiK∈Rdmodel×dkW_i^K \in \mathbb{R}^{d_{\text{model}} \times d_k}, WiV∈Rdmodel×dvW_i^V \in \mathbb{R}^{d_{\text{model}} \times d_v} that carve out a different relational subspace of the input.

Concatenation and Output Projection

The hh head outputs are concatenated and linearly projected back to dmodeld_{\text{model}}:

4
MultiHead(Q,K,V)=Concat(head1,…,headh) WO\quad \text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h)\, W^O

Explanation: Concatenation stacks the hh value-weighted summaries into a vector of dimension h⋅dvh \cdot d_v, and the output matrix WO∈Rhdv×dmodelW^O \in \mathbb{R}^{h d_v \times d_{\text{model}}} fuses the multi-perspective information back into the model's working dimension.

Parameter Count

In the standard setting dk=dv=dmodel/hd_k = d_v = d_{\text{model}} / h, so total parameters are:

5
ParamsMHA=3 dmodel2+dmodel2=4 dmodel2\quad \text{Params}_{\text{MHA}} = 3\, d_{\text{model}}^2 + d_{\text{model}}^2 = 4\, d_{\text{model}}^2

Explanation: Three projection matrices (WQ,WK,WV)(W^Q, W^K, W^V) each of size dmodel×dmodeld_{\text{model}} \times d_{\text{model}} plus the output projection WOW^O of the same size sum to 4dmodel24 d_{\text{model}}^2 parameters, independent of the number of heads hh — confirming that heads are free in terms of parameter count but not in terms of per-head capacity.

PyTorch Implementation

```python import torch import torch.nn as nn import torch.nn.functional as F import math class MultiHeadAttention(nn.Module): def __init__(self, d_model: int, num_heads: int, dropout: float = 0.1): super().__init__() assert d_model % num_heads == 0, "d_model must be divisible by num_heads" self.d_model = d_model self.h = num_heads self.d_k = d_model // num_heads # per-head dimension

# Fused QKV projection for efficiency self.qkv_proj = nn.Linear(d_model, 3 * d_model, bias=False) self.out_proj = nn.Linear(d_model, d_model, bias=False) self.dropout = nn.Dropout(dropout) def forward( self, query: torch.Tensor, # (B, T_q, d_model) key: torch.Tensor, # (B, T_k, d_model) value: torch.Tensor, # (B, T_k, d_model) mask: torch.Tensor | None = None, # (B, 1, T_q, T_k) boolean ) -> tuple[torch.Tensor, torch.Tensor]: B, T_q, _ = query.shape T_k = key.shape[1]

# --- Project Q, K, V ---

# For self-attention query==key==value; for cross-attention they differ. Q = self.qkv_proj(query)[:, :, :self.d_model] K = self.qkv_proj(key) [:, :, self.d_model:2self.d_model] V = self.qkv_proj(value)[:, :, 2self.d_model:]

# --- Reshape to (B, h, T, d_k) --- def split_heads(x, T): return x.view(B, T, self.h, self.d_k).transpose(1, 2) Q = split_heads(Q, T_q) # (B, h, T_q, d_k) K = split_heads(K, T_k) # (B, h, T_k, d_k) V = split_heads(V, T_k) # (B, h, T_k, d_k)

# --- Scaled dot-product attention --- scale = math.sqrt(self.d_k) scores = torch.matmul(Q, K.transpose(-2, -1)) / scale # (B, h, T_q, T_k) if mask is not None: scores = scores.masked_fill(mask == 0, float('-inf')) attn_weights = F.softmax(scores, dim=-1) # (B, h, T_q, T_k) attn_weights = self.dropout(attn_weights)

# --- Weighted sum of values --- context = torch.matmul(attn_weights, V) # (B, h, T_q, d_k)

# --- Merge heads --- context = context.transpose(1, 2).contiguous().view(B, T_q, self.d_model) output = self.out_proj(context) # (B, T_q, d_model) return output, attn_weights # return weights for interpretability

# --- Quick sanity check --- if __name__ == "__main__": B, T, d = 2, 16, 512 mha = MultiHeadAttention(d_model=d, num_heads=8) x = torch.randn(B, T, d) out, attn = mha(x, x, x) # self-attention print(out.shape) # torch.Size([2, 16, 512]) print(attn.shape) # torch.Size([2, 8, 16, 16]) ``` > Note on `torch.nn.MultiheadAttention`: PyTorch ships a fused, optimized implementation. The custom version above matches its semantics exactly and is useful for learning or when you need custom masking logic. For production use `F.scaled_dot_product_attention` (PyTorch ≥ 2.0), which dispatches to FlashAttention kernels automatically.

researcher · Ashish Vaswani | b. 1985 | Inventor of the Transformer / Multi-Head Attention

Ashish Vaswani led the team at Google Brain that published "Attention Is All You Need" (2017), which introduced both the Transformer architecture and Multi-Head Attention as its core operation, replacing recurrence entirely for sequence modeling. His specific contribution was the insight that multiple parallel attention functions over projected subspaces could replace complex recurrent state, enabling massive parallelism during training. Surprisingly, Vaswani left Google shortly after the paper's publication to co-found Adept AI, and the paper — now one of the most cited in computer science history — was nearly rejected by reviewers who felt it lacked sufficient experiments on non-translation tasks.

Figure
Multi-Head Attention Architecture
Multi-Head Attention — Data Flow Q K V Linear W₁Q Linear W₁K Linear W₁V Scaled Dot-Prod head₁ ··· Linear WhQ/K/V Scaled Dot-Prod headₕ Concat(head₁, …, headₕ) Linear W (output proj) MultiHead Output ∈ ℝ^(T × d_model)
Figure
Attention Score Heatmap Concept
Two Heads, Same Sequence — Different Relational Patterns Head 1: Syntactic The cat sat mat The cat sat mat 0.6 0.7 0.8 Head 2: Positional / Local The cat sat mat The cat sat mat 0.9 0.7 0.8 0.9 High attention (blue = syntactic) High attention (amber = positional) Each head independently learns what to attend to — no supervision required.

Intuition

The Mental Model

Imagine you are a detective reading a witness statement and you need to understand it from several angles simultaneously: Who is doing what? (subject-verb) Where do pronouns point? (coreference) Which phrases are idioms? (lexical) Which words are negating others? (semantic scope). A single reading pass forces you to smear all these questions into one interpretation. Multi-Head Attention is like assigning a team of specialist analysts, each given a slightly blurred, dimensionally-reduced photocopy of the statement through different-colored filters. Analyst 1 looks only through the blue filter (trained to catch syntactic structure), analyst 2 through amber (trained on co-reference), and so on. They each write a short summary, you staple all summaries together, and a coordinator reads the stapled bundle and writes the final integrated interpretation. No one told each analyst what to specialize in — they discovered their specialty through gradient descent because it minimized prediction error.

Historical Development

Origins · 1 minhow this was discovered
History
2014
Bahdanau et al. introduce soft attention for neural machine translation, learning to align encoder states with decoder positions — the conceptual ancestor of attention mechanisms.
2015
Luong et al. propose multiplicative ("dot-product") attention variants, including the global and local attention modes that prefigure scaled dot-product attention.
2016
Cheng et al. ("Long Short-Term Memory-Networks for Machine Reading") apply self-attention within a sentence, the first clear use of a sequence attending to itself.
2017
Vaswani et al. publish "Attention Is All You Need," introducing the Transformer with Multi-Head Attention (8 heads, dmodel=512d_{\text{model}}=512) as its core operation, replacing RNNs and CNNs entirely for machine translation.
2018
Devlin et al. release BERT (12 heads × 12 layers; 24 heads × 24 layers for BERT-Large), demonstrating that masked-language-model pretraining with MHA transfers to virtually every NLP benchmark.
2019
Michel et al. ("Are Sixteen Heads Really Better than One?") prove empirically that many attention heads are redundant and can be pruned at inference time with minimal accuracy loss, prompting rethinking of head count.
2020
Brown et al. release GPT-3 with 96 heads across 96 layers, showing that scaling MHA transformers to 175B parameters yields few-shot generalization without fine-tuning.
2022
Dao et al. publish FlashAttention, a memory-efficient IO-aware exact attention algorithm that reorders the softmax + matmul computation to avoid materializing the full T×TT \times T attention matrix, enabling contexts of 4K–64K tokens.
2023–2024
Grouped-Query Attention (GQA) and Multi-Query Attention (MQA) become standard in frontier models (LLaMA 2/3, Gemini, Mistral), reducing KV-cache memory by sharing key/value heads across query heads while preserving model quality.

Why It Matters

Real-World Impact
GPT-4 (OpenAI, 2023)Estimated to use ~128 attention heads per layer across ~120 transformer layers; MHA is the mechanism by which it tracks long-range context, persona consistency, and multi-step reasoning across thousands of tokens in a prompt.
BERT / RoBERTa (Google/Meta)12 or 24 heads per layer enable probing-detectable linguistic structure (POS tags, dependency parse arcs, coreference) to emerge naturally; widely used in production search ranking at Google and Bing.
Stable Diffusion (Stability AI)Uses cross-attention layers where query comes from the noisy image latent and key/value come from the CLIP text embedding — MHA is the mechanism by which text conditions the image denoising process.
AlphaFold 2 (DeepMind, 2021)Applies MHA in the Evoformer block to simultaneously process multiple sequence alignment (MSA) representations and pairwise residue distance maps, enabling breakthrough protein structure prediction.
Vision Transformer / ViT (Google, 2020)Applies standard MHA to sequences of 16×16 image patches; attention heads learn to attend to semantically coherent image regions without convolutions, matching CNN performance at scale.
Whisper (OpenAI, 2022)Uses encoder-decoder Transformer with cross-attention MHA to align audio mel-spectrogram patches with text tokens, enabling robust multilingual speech recognition across 99 languages.
GitHub Copilot / Code LLMsMulti-Head Attention tracks long-range syntactic dependencies in code (e.g., a function call on line 300 attending to its definition on line 10) — something impossible for fixed-window RNN models.

Prerequisites