Skip to content
Transformers

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 TT 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 HH 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 h∈{1,…,H}h \in \{1, \ldots, H\} has its own set of learned projection matrices:

WQh∈RD×dk,WKh∈RD×dk,WVh∈RD×dv\mathbf{W}_Q^h \in \mathbb{R}^{D \times d_k}, \quad \mathbf{W}_K^h \in \mathbb{R}^{D \times d_k}, \quad \mathbf{W}_V^h \in \mathbb{R}^{D \times d_v}

Given the input X∈RT×D\mathbf{X} \in \mathbb{R}^{T \times D}, head hh computes its own query, key, and value matrices and runs scaled dot-product attention:

headh=Attention ⁣(XWQh,  XWKh,  XWVh)∈RT×dv\text{head}_h = \text{Attention}\!\left(\mathbf{X}\mathbf{W}_Q^h,\; \mathbf{X}\mathbf{W}_K^h,\; \mathbf{X}\mathbf{W}_V^h\right) \in \mathbb{R}^{T \times d_v}

The HH head outputs are concatenated along the last dimension:

Concat(head1,…,headH)∈RT×Hdv\text{Concat}(\text{head}_1, \ldots, \text{head}_H) \in \mathbb{R}^{T \times Hd_v}

A final learned projection WO∈RHdv×D\mathbf{W}_O \in \mathbb{R}^{Hd_v \times D} maps this back to dimension DD:

MHA(X)=Concat(head1,…,headH) WO∈RT×D\text{MHA}(\mathbf{X}) = \text{Concat}(\text{head}_1, \ldots, \text{head}_H)\,\mathbf{W}_O \in \mathbb{R}^{T \times D}

The standard choice dk=dv=D/Hd_k = d_v = D/H makes the concatenated output exactly T×DT \times D, so the model dimension is preserved.

X (T × D)head₁W_Q¹ W_K¹ W_V¹Attn(Q,K,V)head₂W_Q² W_K² W_V²Attn(Q,K,V)head_HW_Q^H W_K^H W_V^HAttn(Q,K,V)···Concat(head₁ | head₂ | ··· | head_H) (T × D)W_O (D × D) output projectionZ (T × D)H heads run in parallel; each attends in its own d_k = D/H subspace

Parameter Count and Efficient Computation

With dk=dv=D/Hd_k = d_v = D/H, the parameter count is:

ComponentMatricesParameters
QueriesH×WQhH \times \mathbf{W}_Q^hH×D×(D/H)=D2H \times D \times (D/H) = D^2
KeysH×WKhH \times \mathbf{W}_K^hD2D^2
ValuesH×WVhH \times \mathbf{W}_V^hD2D^2
OutputWO\mathbf{W}_OD2D^2
Total4D24D^2

The total is the same as a single attention head with dk=Dd_k = D plus an output projection — the model has not become larger, it has redistributed the same budget across HH specialized subspaces. For GPT-2 small (D=768D = 768, H=12H = 12): 4×7682≈2.364 \times 768^2 \approx 2.36 million parameters per attention layer.

Practical implementation. Computing HH separate matrix multiplications would be inefficient. In practice, all heads are computed in a single batched operation: the projection XWQ\mathbf{X}\mathbf{W}_Q (where WQ∈RD×D\mathbf{W}_Q \in \mathbb{R}^{D \times D} bundles all HH head projections) produces Q∈RT×D\mathbf{Q} \in \mathbb{R}^{T \times D}, which is then reshaped to (T,H,dk)(T, H, d_k) and transposed to (H,T,dk)(H, T, d_k). All HH 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 WQh\mathbf{W}_Q^h and WKh\mathbf{W}_K^h map the input to different dkd_k-dimensional subspaces. Head hh 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:

MHA(X)=∑h=1Hheadh⋅WO(h)\text{MHA}(\mathbf{X}) = \sum_{h=1}^{H} \text{head}_h \cdot \mathbf{W}_O^{(h)}

where WO(h)∈Rdv×D\mathbf{W}_O^{(h)} \in \mathbb{R}^{d_v \times D} is the row slice of WO\mathbf{W}_O corresponding to head hh. Each head independently computes an attention-weighted representation, then projects it to the full DD-dimensional space. The final output is the sum of HH such contributions.

This view clarifies what WO\mathbf{W}_O 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

ModelDDHHdk=D/Hd_k = D/H
Original Transformer (base)512864
BERT-base7681264
GPT-2 small7681264
GPT-2 medium1,0241664
GPT-2 large1,2802064

The per-head dimension dk=64d_k = 64 is remarkably consistent across models of very different scales. The convention dk=64d_k = 64 (equivalently, one head per 64 dimensions of DD) has proven robust and is widely adopted. Increasing HH while keeping dkd_k fixed simply increases DD.

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: HH parallel heads each compute their own attention-weighted representation, and the concatenated result is projected back to dimension DD. 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.