DL0027 Multi-Head Attention

How does multi-head attention work in transformer architectures?

Answer

Multi-head attention runs several attention operations in parallel on different learned projections of the same input: Q, K, V are projected into h lower-dimensional subspaces (one per head), each head performs scaled dot-product attention independently, and the h outputs are concatenated and linearly re-projected by W^O. Each head can specialize in a different relationship (syntax, local neighborhoods, long-range links) so the combined representation is richer than any single attention map.

(1) Split: Project d_{model}-dim Q, K, V into h heads of dimension d_k = d_{model} / h each.
(2) Parallel Attention: Every head computes its own softmax-weighted sum; all heads run simultaneously, so total compute is comparable to one full-size head.
(3) Merge: Concatenate the head outputs and apply output projection W^O back to d_{model}.

Diagram of Q, K, V splitting into four parallel attention heads with different specializations, concatenating, and passing through an output projection to the model dimension.

Figure 1: The MHA pipeline: split → parallel attention → concat → project; each head attends in its own subspace.

Mathematical Formulation:
\mathrm{MultiHead}(Q, K, V) = \mathrm{Concat}(\mathrm{head}_1, \dots, \mathrm{head}_h)\, W^O
\mathrm{head}_i = \mathrm{Attention}(Q W_i^Q,\; K W_i^K,\; V W_i^V)

Where:

  • W_i^Q, W_i^K, W_i^V \in \mathbb{R}^{d_{model} \times d_k} are the per-head projection matrices; h is the number of heads.
  • d_k = d_{model} / h is each head’s subspace dimension (e.g., 512-dim model with 8 heads → d_k = 64).
  • W^O \in \mathbb{R}^{h d_k \times d_{model}} mixes the concatenated heads back to the model dimension.

Why Multiple Heads Help: A single softmax distribution must average every relationship into one map; separate heads let the model attend to different positions and relation types simultaneously. Empirically, heads specialize into recognizable patterns.

Five attention heatmaps over the same sentence: one single-head map and four multi-head maps showing distinct patterns such as diagonal focus, CLS-column focus, local neighbor bands, and semantic links.

Figure 2: Same input, four different attentions: heads specialize on position bands, special tokens, and semantic pairs that one head alone could not capture.


Login to view more content


Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *