4.1.5Transformer Architecture

Multi-head attention

2,739 words12 min readdifficulty · medium6 backlinks

What Problem Does It Solve?

Single-head attention has limited representational capacity. A single set of Q,K,VQ, K, V projections can only learn one type of relationship pattern. But language (and most sequential data) has multiple simultaneous structure types:

  • Syntactic dependencies (subject agrees with verb)
  • Semantic relationships (synonym, antonyms)
  • Positional patterns (nearby words vs. distant context)
  • Co-reference (pronouns linking to earlier nouns)

Multi-head attention (MHA) learns multiple representation subspaces in parallel, each head specializing in different patterns.


Definition and Architecture

Figure — Multi-head attention

Derivation From First Principles

Step 1: Why Reduce Dimension Per Head?

Goal: Run hh attention heads in parallel without increasing computational cost.

If we have dmodel=512d_{\text{model}} = 512 and want h=8h = 8 heads:

  • Naive approach: Each head uses full512-dim → total cost 8×cost(512)8 \times \text{cost}(512)
  • Smart approach: Each head uses dk=512/8=64d_k = 512/8 = 64 → total cost cost(512)\approx \text{cost}(512)

Why this works: Attention cost is O(n2d)O(n^2 d) where nn = sequence length, dd = dimension.

  • 8 heads of 64-dim each: 8×O(n2×64)=O(n2×512)8 \times O(n^2 \times 64) = O(n^2 \times 512)
  • Same total FLOPs as one512-dim head, but we get8 different views!

Step 2: Projecting Into Head Subspaces

For head ii, we project the shared Q,K,VQ, K, V (shape [n,dmodel][n, d_{\text{model}}]) down to [n,dk][n, d_k]:

Qi=QWiQ,Ki=KWiK,Vi=VWiVQ_i = Q W_i^Q, \quad K_i = K W_i^K, \quad V_i = V W_i^V

where WiQ,WiK,WiVW_i^Q, W_i^K, W_i^V are learned, different for each head.

WHY different projections?

  • If all heads used the same WQ,WK,WVW^Q, W^K, W^V, they'd compute identical attention patterns—no benefit!
  • Different projections let each head learn to extract different features from the same input.

Intuition: Think of each WiQW_i^Q as asking different question:

  • Head 1 might project to capture "What words are grammatically related?"
  • Head 2 might project to capture "What words are semantically similar?"
  • Head 3 might project to capture "What words are nearby in position?"

Step 3: Compute Scaled Dot-Product Attention Per Head

Each head independently computes:

headi=softmax(QiKiTdk)Vi\text{head}_i = \text{softmax}\left(\frac{Q_i K_i^T}{\sqrt{d_k}}\right) V_i

This gives an output of shape [n,dv][n, d_v] for each head.

WHY the same scaled dot-product formula?

  • It works! The magic is in the different learned projections WiQ,K,VW_i^{Q,K,V}, not in the attention mechanism itself.
  • Using the same mechanism means each head is interpretable in the same way.

Step 4: Concatenate Heads

Stack the hh head outputs side-by-side:

Concat(head1,,headh)=[head1head2headh]\text{Concat}(\text{head}_1, \ldots, \text{head}_h) = [\text{head}_1 \mid \text{head}_2 \mid \cdots \mid \text{head}_h]

This produces shape [n,hdv]=[n,dmodel][n, h \cdot d_v] = [n, d_{\text{model}}] (since hdv=dmodelh \cdot d_v = d_{\text{model}}).

WHY concatenate instead of sum/average?

  • We want to preserve all information from every head.
  • Suming would merge them, losing the distinct patterns each head learned.
  • Concatenation keeps them separate, but we need one more step to blend them...

Step 5: Final Linear Projection

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

where WORdmodel×dmodelW^O \in \mathbb{R}^{d_{\text{model}} \times d_{\text{model}}} is learned.

WHY this final projection?

  • The concatenated heads are still in separate "channels"—WOW^O lets the model mix information across heads.
  • It learns how to combine different types of attention (syntactic + semantic + positional).
  • Returns output to full dmodeld_{\text{model}} dimension, ready for the next layer.

Complete Forward Pass Example



Common Mistakes


Parameter Count

Let's count parameters for multi-head attention:

Per head:

  • WiQW_i^Q: dmodel×dkd_{\text{model}} \times d_k
  • WiKW_i^K: dmodel×dkd_{\text{model}} \times d_k
  • WiVW_i^V: dmodel×dvd_{\text{model}} \times d_v
  • Total per head: 3dmodeldk3 d_{\text{model}} \cdot d_k

All heads: h3dmodeldk=3dmodel(hdk)=3dmodel2h \cdot 3 d_{\text{model}} \cdot d_k = 3 d_{\text{model}} \cdot (h \cdot d_k) = 3 d_{\text{model}}^2 (since hdk=dmodelh \cdot d_k = d_{\text{model}})

Output projection: WOW^O has dmodel×dmodel=dmodel2d_{\text{model}} \times d_{\text{model}} = d_{\text{model}}^2 parameters

Total: 3dmodel2+dmodel2==4dmodel2==3 d_{\text{model}}^2 + d_{\text{model}}^2 ==4 d_{\text{model}}^2== parameters


Computational Complexity

Per head:

  • Computing Qi,Ki,ViQ_i, K_i, V_i: O(ndmodeldk)O(n \cdot d_{\text{model}} \cdot d_k) each, total 3ndmodeldk3 n \cdot d_{\text{model}} \cdot d_k
  • Attention scores QiKiTQ_i K_i^T: O(n2dk)O(n^2 d_k)
  • Softmax: O(n2)O(n^2)
  • Weighted sum with ViV_i: O(n2dv)O(n^2 d_v)

All heads: hh times the per-head cost

Dominant term: Attention scores O(hn2dk)=O(n2dmodel)O(h \cdot n^2 d_k) = O(n^2 d_{\text{model}}) (since hdk=dmodelh \cdot d_k = d_{\text{model}})

Output projection: O(ndmodel2)O(n \cdot d_{\text{model}}^2)

For long sequences where ndmodeln \gg d_{\text{model}}, the O(n2dmodel)O(n^2 d_{\text{model}}) attention term dominates. This is why Transformers struggle with very long sequences (length 10,000+)—quadratic in sequence length!


Recall Explain to a 12-Year-Old

Imagine you're trying to understand a friend's long story. You can't focus on everything at once, so your brain does something smart: it pays attention to different parts in different ways at the same time.

  • One part of your brain listens for who did what (like "Alice threw the ball").
  • Another part listens for emotions (like "she was excited").
  • Another part tracks when things happened (like "first... then... finally..."). Multi-head attention works the same way! The computer has multiple "attention heads" (like different parts of your brain), and each one focuses on different patterns in the text:
  • Head 1 might connect words that go together grammatically ("the cat" → "sat").
  • Head 2 might connect words that mean similar things ("happy" ← "joyful").
  • Head 3 might connect words that are nearby.

Each head is like a friend with a special talent—one is great at grammar, one is great at understanding feelings, one is great at remembering order. By having all these friends work together (that's the "multi" part), the computer understands the story much better than if it only had one friend helping!

The "concatenate and project" step at the end is like having all your friends sit down and share what they noticed, so you get the full picture.



Connections Scaled Dot-Product Attention: The attention mechanism used within each head

  • Self-Attention: MHA is typically used in self-attention (Q, K, V from same source)
  • Cross-Attention: MHA can also be used for encoder-decoder attention (Q from decoder, K,V from encoder)
  • Transformer Encoder Layer: Uses MHA followed by feed-forward network
  • Positional Encoding: Provides position information that attention heads can leverage
  • Attention Visualization: Techniques to interpret what each head has learned
  • Query-Key-Value Intuition: Foundation for understanding the projections
  • Linear Projections in Neural Networks: What the WQ,WK,WVWOW^Q, W^K, W^V W^O matrices do

#flashcards/ai-ml

What is the primary advantage of multi-head attention over single-head attention? :: Multi-head attention learns multiple representation subspaces in parallel, allowing the model to capture different types of relationships (syntactic, semantic, positional) simultaneously. A single head has limited representational capacity.

In multi-head attention with hh heads and model dimension dmodeld_{\text{model}}, what is the dimension of each head?
Each head operates in dimension dk=dv=dmodel/hd_k = d_v = d_{\text{model}} / h. This keeps total computation constant while enabling parallel specialization.
Why do we use different projection matrices WiQ,WiK,WiVW_i^Q, W_i^K, W_i^V for each head?
Different projections allow each head to learn different features from the same input. If all heads used identical projections, they would compute identical attention patterns, providing no benefit.
What is the formula for multi-head attention?
MultiHead(Q,K,V)=Concat(head1,,headh)WO\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h) W^O where headi=Attention(QWiQ,KWiK,VWiV)\text{head}_i = \text{Attention}(Q W_i^Q, K W_i^K, V W_i^V)
Why do we concatenate head outputs instead of suming them?
Concatenation preserves distinct information from each head. Summing would mix the patterns, losing the specialized information each head learned. The final WOW^O projection can then learn how to optimally combine the heads.
What is the total parameter count for multi-head attention with model dimension dmodeld_{\text{model}}?
4dmodel24 d_{\text{model}}^2 parameters: 3dmodel23 d_{\text{model}}^2 for all the WQ,WK,WVW^Q, W^K, W^V projections across heads, plus dmodel2d_{\text{model}}^2 for the output projection WOW^O.
What is the computational complexity of multi-head attention?
The dominant term is O(n2dmodel)O(n^2 d_{\text{model}}) where nn is sequence length, coming from computing attention scores across all positions. This is quadratic in sequence length.
Why does the final WOW^O projection exist in multi-head attention?
WOW^O allows the model to mix information across heads. After concatenation, the heads are still in separate "channels"—WOW^O learns how to combine different types of attention (syntactic + semantic + positional) optimally for the task.

Concept Map

limited capacity

motivates

runs

each learns

specializes in

reduces dim per head

keeps constant

project via

feeds

combined by

produces

Single-head attention

One relationship type only

Multi-head attention

h parallel heads

Own representation subspace

Syntax semantics position coreference

d_k equals d_model over h

Total FLOPs and params

Learned W_Q W_K W_V

Attention per head

Concat then W_O

Richer output representation

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Multi-head attention ek bohot hi powerful idea hai jisse Transformer models itne effective bante hain. Socho tumhe ek paragraph padhna hai aur uska meaning samajhna hai. Tumara dimag sirf ek tareke se nahi soch

Go deeper — visual, from zero

Test yourself — Transformer Architecture

Connections