Quiz 2
Registry Synced

Multi-Head Attention Deep Dive

2041 words
10 min read

Reading compass

Now · 🎯 Learning Objectives

Multi-Head Attention Deep Dive

🎯 Learning Objectives

  • Explain why multiple attention heads are beneficial over a single head
  • Understand how different heads specialize in different linguistic patterns
  • Compute multi-head attention outputs through the full pipeline
  • Analyze head importance and redundancy

📋 Prerequisites

  • Self-Attention & QKV (previous topic)
  • Matrix concatenation and linear algebra

1. 📖 Core Content

1.1 Intuition: Why Multiple Heads?

Imagine you're analyzing a complex scene. One person might focus on colors, another on shapes, another on movement. By combining their observations, you get a richer understanding than any single observer could provide. Similarly, multi-head attention allows the model to simultaneously attend to different aspects of the input:
  • Head 1: Might focus on syntactic dependencies (subject-verb relationships)
  • Head 2: Might focus on semantic similarity (related concepts)
  • Head 3: Might focus on positional proximity (nearby words)
  • Head 4: Might focus on coreference (pronouns and their antecedents) Each head sees a different projected version of the input and computes attention independently.

1.2 Formal Definition

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}(QW_i^Q, KW_i^K, VW_i^V) Parameter counts:
  • Each head has 3 projection matrices: WiQ,WiK,WiVRdmodel×dkW_i^Q, W_i^K, W_i^V \in \mathbb{R}^{d_{model} \times d_k}
  • Output projection: WORhdv×dmodelW^O \in \mathbb{R}^{h d_v \times d_{model}}
  • Total attention parameters: 3hdmodeldk+dmodelhdv3 \cdot h \cdot d_{model} \cdot d_k + d_{model} \cdot h \cdot d_v With dk=dv=dmodel/hd_k = d_v = d_{model}/h:
  • Per head: 3dmodel(dmodel/h)=3dmodel2/h3 \cdot d_{model} \cdot (d_{model}/h) = 3d_{model}^2/h
  • All heads: 3dmodel23d_{model}^2
  • Output projection: dmodel2d_{model}^2
  • Total: 4dmodel24d_{model}^2 — same as a single head with d_model dimension! Key insight: Multi-head attention doesn't increase the total parameter count compared to a single large head. It just distributes the capacity across multiple subspaces.

1.3 Multiplication by 4 Rule

In Transformer attention, the total parameter count equals 4dmodel24d_{model}^2:
ComponentParameter Count
WQW^Q (all heads combined)dmodel2d_{model}^2
WKW^K (all heads combined)dmodel2d_{model}^2
WVW^V (all heads combined)dmodel2d_{model}^2
WOW^Odmodel2d_{model}^2
Total4dmodel2\mathbf{4d_{model}^2}
This is a useful mnemonic: the attention sublayer has 4dmodel24d_{model}^2 parameters, and the FFN sublayer has 8dmodel28d_{model}^2 parameters (assuming inner dimension = 4dmodel4d_{model}).

1.4 Complete Multi-Head Worked Example

Let's trace through a complete multi-head attention computation with:
  • 2 tokens, d_model = 6, h = 3 heads, d_k = d_v = 2 Step 1: Input
X=[123456654321]X = \begin{bmatrix} 1 & 2 & 3 & 4 & 5 & 6 \\ 6 & 5 & 4 & 3 & 2 & 1 \end{bmatrix}
Step 2: Projection for Head 1 (simplified — each W is 6×2) W1Q,W1K,W1VW^Q_1, W^K_1, W^V_1 transform X to Q₁, K₁, V₁ ∈ ℝ^{2×2}. Let's say Head 1 projections yield:
Q1=[0.50.30.20.7],K1=[0.40.10.60.5],V1=[0.80.20.30.9]Q_1 = \begin{bmatrix} 0.5 & 0.3 \\ 0.2 & 0.7 \end{bmatrix}, K_1 = \begin{bmatrix} 0.4 & 0.1 \\ 0.6 & 0.5 \end{bmatrix}, V_1 = \begin{bmatrix} 0.8 & 0.2 \\ 0.3 & 0.9 \end{bmatrix}
Step 3: Attention in Head 1
S1=Q1K1T=[0.50.4+0.30.60.50.1+0.30.50.20.4+0.70.60.20.1+0.70.5]S_1 = Q_1 K_1^T = \begin{bmatrix} 0.5\cdot0.4 + 0.3\cdot0.6 & 0.5\cdot0.1 + 0.3\cdot0.5 \\ 0.2\cdot0.4 + 0.7\cdot0.6 & 0.2\cdot0.1 + 0.7\cdot0.5 \end{bmatrix} S1=[0.380.200.500.37]S_1 = \begin{bmatrix} 0.38 & 0.20 \\ 0.50 & 0.37 \end{bmatrix}
Scale:
S1/2=[0.2690.1410.3540.262]S_1/\sqrt{2} = \begin{bmatrix} 0.269 & 0.141 \\ 0.354 & 0.262 \end{bmatrix}
Softmax row 1: e0.269=1.309,e0.141=1.151e^{0.269}=1.309, e^{0.141}=1.151, sum=2.460, weights=[0.532, 0.468] Softmax row 2: e0.354=1.425,e0.262=1.300e^{0.354}=1.425, e^{0.262}=1.300, sum=2.725, weights=[0.523, 0.477]
A1=[0.5320.4680.5230.477]A_1 = \begin{bmatrix} 0.532 & 0.468 \\ 0.523 & 0.477 \end{bmatrix}
Output₁ = A₁·V₁: Row 1: [0.5320.8+0.4680.3,0.5320.2+0.4680.9]=[0.566,0.528][0.532\cdot0.8 + 0.468\cdot0.3, 0.532\cdot0.2 + 0.468\cdot0.9] = [0.566, 0.528] Row 2: [0.5230.8+0.4770.3,0.5230.2+0.4770.9]=[0.562,0.534][0.523\cdot0.8 + 0.477\cdot0.3, 0.523\cdot0.2 + 0.477\cdot0.9] = [0.562, 0.534]
head1=[0.5660.5280.5620.534]\text{head}_1 = \begin{bmatrix} 0.566 & 0.528 \\ 0.562 & 0.534 \end{bmatrix}
Step 4: Repeat for Heads 2 and 3 → head₂, head₃ ∈ ℝ^{2×2} Step 5: Concatenate
Concat(head1,head2,head3)=[0.5660.528h2,1h2,2h3,1h3,20.5620.534h2,3h2,4h3,3h3,4]\text{Concat(head}_1, \text{head}_2, \text{head}_3) = \begin{bmatrix} 0.566 & 0.528 & h_{2,1} & h_{2,2} & h_{3,1} & h_{3,2} \\ 0.562 & 0.534 & h_{2,3} & h_{2,4} & h_{3,3} & h_{3,4} \end{bmatrix}
The concatenation has shape (2, 6) — same as input. Step 6: Output projection WOR6×6W^O \in \mathbb{R}^{6 \times 6} transforms back to (2, 6).

1.5 Head Specialization

Research has shown that different attention heads learn different functions: (Diagram) Evidence from BERT analysis:
  • Lower layers: Heads focus on positional relationships and surface features
  • Middle layers: Heads capture syntactic relationships
  • Higher layers: Heads capture semantic relationships

1.6 Head Redundancy and Pruning

Not all heads are equally important. Research shows:
  1. Many heads are redundant: Pruning up to 40% of heads can maintain performance
  2. Head importance varies: Some heads contribute critically to certain tasks
  3. Task-specific heads: Different tasks rely on different subsets of heads
python
# runnable
import numpy as np
def compute_head_importance(scores_before, scores_after, baseline_performance):
    """
    Estimate head importance by measuring performance drop when head is masked
    Args:
        scores_before: Performance with all heads
        scores_after: Performance with one head ablated
        baseline_performance: Initial performance metric
    Returns:
        importance: Relative importance of each head
    """
    num_heads = len(scores_after)
    importance = np.zeros(num_heads)
    for i in range(num_heads):
        # Larger drop = more important
        importance[i] = (baseline_performance - scores_after[i]) / baseline_performance
    return importance
# Hypothetical example: 8 heads
baseline = 0.92  # F1 score
scores_with_ablation = [0.91, 0.88, 0.90, 0.85, 0.91, 0.89, 0.92, 0.91]
importance = compute_head_importance([], scores_with_ablation, baseline)
print("Head importance scores:")
for i, imp in enumerate(importance):
    print(f"Head {i+1}: {imp:.3f} (ablated score: {scores_with_ablation[i]:.3f})")
# Heads with low importance could potentially be pruned
threshold = 0.02
prunable = [i for i, imp in enumerate(importance) if imp < threshold]
print(f"\nPrunable heads (importance < {threshold}): {[h+1 for h in prunable]}")

1.7 Why This Matters

Multi-head attention is what gives Transformers their representational power. Multiple heads allow the model to:
  1. Parallel pattern capture: Attend to syntax, semantics, and position simultaneously
  2. Robustness: Redundancy provides graceful degradation
  3. Interpretability: Head analysis reveals what the model learns
  4. Efficiency: Same parameter budget as single head, but richer representations

4. 📐 Key Formulas / Concepts

ConceptFormulaDescription
Multi-head outputConcat(head1,...,headh)WO\text{Concat(head}_1, ..., \text{head}_h)W^OCombine all heads
Single headAttention(QWiQ,KWiK,VWiV)\text{Attention}(QW_i^Q, KW_i^K, VW_i^V)Per-head computation
Per-head dimdk=dmodel/hd_k = d_{model} / hDimension per head
Parameter count4dmodel24d_{model}^2Total attention parameters
Head count rangeh{8,12,16,24,32}h \in \{8, 12, 16, 24, 32\}Typical values
Output shape(n,dmodel)(n, d_{model})Same as input

5. ⚠️ Common Pitfalls

Pitfall 1: Assuming all heads learn unique functions

The mistake: Thinking each of the 8/12/16 heads learns a completely distinct pattern. Why it happens: The "multiple perspectives" analogy suggests complete diversity. Correction: In practice, many heads learn similar patterns (redundancy). Studies show that randomly re-initializing 30-40% of heads doesn't significantly hurt performance. The redundancy is a feature, not a bug — it provides robustness.

Pitfall 2: Forgetting the output projection W^O

The mistake: Computing heads and concatenating, then assuming the output is complete. Why it happens: The concatenation naturally gives a d_model-dimensional vector. Correction: After concatenation, the output must go through WOW^O (a learned linear projection). This projection is crucial because it allows the model to mix information across heads. Without it, each head's contribution would be independent in the output.

Pitfall 3: Thinking more heads is always better

The mistake: Increasing h always improves performance. Why it happens: Intuitively, more parallel analyses should be better. Correction: With fixed d_model, increasing h decreases d_k. When d_k becomes very small (e.g., < 16), each head has too few dimensions to capture meaningful patterns. There's a sweet spot based on model size and task.

6. 📝 Practice Questions

Q1: For GPT-3 (d_model=12288, h=96), what is d_k?
d_k = 12288 / 96 = 128. Each head operates in 128-dimensional space.
Total attention parameters = 4 × 12288² ≈ 604 million parameters (out of 175B total). Q2: If we have d_model=512 and h=16, what's d_k? Is this reasonable?
d_k = 512/16 = 32. This is at the lower end of typical values. With only 32 dimensions per head, each head has limited representational capacity. This might still work but is less common than h=8 (d_k=64) or h=12 (d_k≈43). Q3: Show that multi-head attention with h=1 is equivalent to single-head attention.
With h=1:
  • d_k = d_model (since d_model/1 = d_model)
  • WQ,WK,WVRdmodel×dmodelW^Q, W^K, W^V \in \mathbb{R}^{d_{model} \times d_{model}}
  • Concat has only 1 head, so Concat(head₁) = head₁
  • WORdmodel×dmodelW^O \in \mathbb{R}^{d_{model} \times d_{model}}
MultiHead(Q, K, V) = head₁ · W^O = Attention(QW^Q, KW^K, VW^V)W^O
Since W^O is a learned square matrix, this is equivalent to single-head attention with an additional linear transform. In practice, the two W^O's can be absorbed into the projections. Q4: Compute the number of attention parameters for d_model=1024, h=16.
d_k = 1024/16 = 64
Per head: 3 × 1024 × 64 = 196,608 All heads: 16 × 196,608 = 3,145,728 W^O: 1024 × 1024 = 1,048,576
Total: 3,145,728 + 1,048,576 = 4,194,304 = 4 × 1024² ✓ Q5: Why is the FFN dimension typically 4× d_model?
This is an architectural choice from the original Transformer paper that has proven effective. The expansion factor 4 provides enough capacity for non-linear transformations. Common dimensions: 512→2048, 768→3072, 1024→4096. The FFN has 8d_model² parameters (two layers: d_model → 4d_model → d_model).
FFN params = d_model × 4d_model + 4d_model × d_model = 8d_model² Q6: If a model's attention patterns show that all heads have almost identical attention distributions, what might this indicate?
This could indicate:
  1. Underfitting: The model hasn't learned to differentiate head roles (training may be insufficient)
  2. Low model capacity: d_k might be too small for meaningful specialization
  3. Data issue: The training data may lack the diversity needed for specialization
  4. Over-regularization: Strong regularization might be pushing heads toward uniformity
In well-trained models, heads typically show distinct attention patterns. Q7: What happens to multi-head attention if we remove the output projection W^O?
Without W^O, each head's output is simply concatenated. This means:
  • The output has h independent "blocks" of information
  • No mixing occurs between heads
  • The model can't weight heads differently
  • Performance typically degrades because the model can't integrate information across heads Q8: In a Transformer with 6 encoder layers, each with 8 heads, how many unique attention mechanisms process the input?
6 layers × 1 self-attention sublayer × 8 heads = 48 total attention mechanisms. Each of these 48 heads learns a different attention pattern. In the decoder, there are 2 attention sublayers per layer (masked self-attention + cross-attention), so 6 × 2 × 8 = 96 additional mechanisms. Q9: A paper finds that Head 5 in layer 3 consistently attends to the [SEP] token. What might this head's role be?
The [SEP] token in BERT separates sentences. A head that always attends to [SEP] might be involved in:
  1. Sentence boundary detection: Tracking where one sentence ends and another begins
  2. Next sentence prediction: The NSP task requires understanding sentence relationships
  3. Global aggregation: Accumulating information from both sentences before classification
This is an example of head specialization — certain heads develop consistent, interpretable functions. Q10: Derive why multi-head attention doesn't increase the parameter count relative to a single large head.
Single head (d_k = d_model):
  • W^Q: d_model² params
  • W^K: d_model² params
  • W^V: d_model² params
  • Total: 3d_model² params
Multi-head (h heads, d_k = d_model/h):
  • Per head: 3 × d_model × (d_model/h) = 3d_model²/h params
  • All heads: h × 3d_model²/h = 3d_model² params
  • W^O: h × (d_model/h) × d_model = d_model² params
  • Total: 4d_model² params
Multi-head adds the output projection W^O (d_model² params) but doesn't change the QKV projection total. So it adds d_model² parameters (33% increase), not a factor of h increase.

7. 🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.