Multi-Head Attention › How Multi-Head Attention Works

Michael BrenndoerferUpdated May 30, 20255 min read
Language AI HandbookAll chapters
Part 13 of 67Self-Attention
Chapter 94Multi-Head Attention › How Multi-Head Attention Works
Reading section 3 of 14 · How Multi-Head Attention Works · 5 minSection 3 of 14 · 5 min

Book contents

Section 3 of 14 · 5 min read

Multi-Head Attention › How Multi-Head Attention WorksOne section · Sections in this chapter3 / 14 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Multi-head attention divides the model's capacity across hh parallel attention heads. Each head operates on a reduced dimension, so the total computation remains comparable to single-head attention with the full dimension.

The process unfolds in four steps:

  1. Project the input into hh separate QKV representations
  2. Compute scaled dot-product attention independently for each head
  3. Concatenate all head outputs into a single tensor
  4. Project the concatenated output back to the model dimension

Let's trace through each step with concrete mathematics and then implement it in code.

Step 1: Parallel Projections

Given an input sequence X∈Rn×dmodel\mathbf{X} \in \mathbb{R}^{n \times d_{\text{model}}} with nn tokens and model dimension dmodeld_{\text{model}}, we project it into QKV representations for each head. If we have hh heads, we typically set the head dimension to dk=dmodel/hd_k = d_{\text{model}} / h. This division ensures that the total computation across all heads remains comparable to a single attention operation over the full dimension.

For head ii, we compute the QKV matrices through learned linear projections:

Qi=XWiQ,Ki=XWiK,Vi=XWiV\mathbf{Q}_i = \mathbf{X} \mathbf{W}^Q_i, \quad \mathbf{K}_i = \mathbf{X} \mathbf{W}^K_i, \quad \mathbf{V}_i = \mathbf{X} \mathbf{W}^V_i

where:

  • X∈Rn×dmodel\mathbf{X} \in \mathbb{R}^{n \times d_{\text{model}}}: the input sequence with nn tokens, each represented as a dmodeld_{\text{model}}-dimensional vector
  • WiQ∈Rdmodel×dk\mathbf{W}^Q_i \in \mathbb{R}^{d_{\text{model}} \times d_k}: the learned query projection matrix for head ii, transforming each token into a dkd_k-dimensional query vector
  • WiK∈Rdmodel×dk\mathbf{W}^K_i \in \mathbb{R}^{d_{\text{model}} \times d_k}: the learned key projection matrix for head ii, transforming each token into a dkd_k-dimensional key vector
  • WiV∈Rdmodel×dv\mathbf{W}^V_i \in \mathbb{R}^{d_{\text{model}} \times d_v}: the learned value projection matrix for head ii (often dv=dkd_v = d_k)
  • Qi,Ki∈Rn×dk\mathbf{Q}_i, \mathbf{K}_i \in \mathbb{R}^{n \times d_k}: the resulting query and key matrices for head ii
  • Vi∈Rn×dv\mathbf{V}_i \in \mathbb{R}^{n \times d_v}: the resulting value matrix for head ii
  • dkd_k: the per-head dimension, typically dmodel/hd_{\text{model}} / h

Each head gets its own projection matrices. This allows it to learn different transformations of the input. Head 1 might project tokens to emphasize syntactic features, while head 2 emphasizes semantic similarity. different projection matrices create different "views" of the same input, each potentially highlighting different aspects of the token relationships.

Step 2: Independent Attention Computation

Each head computes standard scaled dot-product attention using its own projections. The attention mechanism compares queries against keys to determine relevance weights, then uses those weights to aggregate values:

headi=Attention(Qi,Ki,Vi)=softmax(QiKiTdk)Vi\text{head}_i = \text{Attention}(\mathbf{Q}_i, \mathbf{K}_i, \mathbf{V}_i) = \text{softmax}\left(\frac{\mathbf{Q}_i \mathbf{K}_i^T}{\sqrt{d_k}}\right) \mathbf{V}_i

where:

  • headi∈Rn×dv\text{head}_i \in \mathbb{R}^{n \times d_v}: the output of attention head ii, containing contextual representations for all nn tokens
  • QiKiT∈Rn×n\mathbf{Q}_i \mathbf{K}_i^T \in \mathbb{R}^{n \times n}: the matrix of raw attention scores, where entry (j,k)(j, k) measures how much query at position jj matches key at position kk
  • dk\sqrt{d_k}: the scaling factor that prevents dot products from growing too large as dkd_k increases (covered in the previous chapter on scaled dot-product attention)
  • softmax(⋅)\text{softmax}(\cdot): applied row-wise to convert scores into attention weights that sum to 1 for each query position
  • Vi\mathbf{V}_i: the value matrix whose rows are aggregated according to the attention weights

This produces hh separate outputs, each of shape Rn×dv\mathbb{R}^{n \times d_v}. The heads operate completely independently at this stage; there is no information sharing between them. This independence is what allows different heads to specialize in detecting different types of relationships.

Step 3: Concatenation

After computing all heads, we concatenate their outputs along the feature dimension. Each head produces an n×dvn \times d_v matrix, and stacking these side-by-side creates a larger matrix:

Concat(head1,head2,…,headh)∈Rn×(h⋅dv)\text{Concat}(\text{head}_1, \text{head}_2, \ldots, \text{head}_h) \in \mathbb{R}^{n \times (h \cdot d_v)}

where:

  • head1,…,headh\text{head}_1, \ldots, \text{head}_h: the hh individual head outputs, each of shape Rn×dv\mathbb{R}^{n \times d_v}
  • h⋅dvh \cdot d_v: the concatenated feature dimension, combining all heads' outputs

If dv=dk=dmodel/hd_v = d_k = d_{\text{model}} / h, then h⋅dv=dmodelh \cdot d_v = d_{\text{model}}, and the concatenated output has the same dimension as the original input. This dimensional consistency is intentional: it allows multi-head attention to be used as a drop-in replacement for single-head attention. The concatenation preserves each head's contribution separately, letting the subsequent projection learn how to combine them.

Step 4: Output Projection

Finally, we apply a learned linear projection to the concatenated output. This projection maps the combined head outputs back to the model dimension:

MultiHead(X)=Concat(head1,…,headh)WO\text{MultiHead}(\mathbf{X}) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h) \mathbf{W}^O

where:

  • Concat(head1,…,headh)∈Rn×(h⋅dv)\text{Concat}(\text{head}_1, \ldots, \text{head}_h) \in \mathbb{R}^{n \times (h \cdot d_v)}: the concatenated outputs from all hh attention heads
  • WO∈R(h⋅dv)×dmodel\mathbf{W}^O \in \mathbb{R}^{(h \cdot d_v) \times d_{\text{model}}}: the learned output projection matrix
  • MultiHead(X)∈Rn×dmodel\text{MultiHead}(\mathbf{X}) \in \mathbb{R}^{n \times d_{\text{model}}}: the final output, matching the input dimension

This projection serves two purposes. First, it combines information from all heads, allowing the model to learn how to mix their contributions. A head specializing in syntax might contribute more heavily for certain tokens, while a semantic head dominates for others. Second, it ensures the output dimension matches the input dimension, enabling residual connections in the transformer architecture.