Neural Sync Active
Multi-Head Attention Deep Dive
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)WOwhere headi=Attention(QWiQ,KWiK,VWiV)
Parameter counts:
- Each head has 3 projection matrices: WiQ,WiK,WiV∈Rdmodel×dk
- Output projection: WO∈Rhdv×dmodel
- Total attention parameters: 3⋅h⋅dmodel⋅dk+dmodel⋅h⋅dv With dk=dv=dmodel/h:
- Per head: 3⋅dmodel⋅(dmodel/h)=3dmodel2/h
- All heads: 3dmodel2
- Output projection: dmodel2
- Total: 4dmodel2 — 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 4dmodel2:
| Component | Parameter Count |
|---|---|
| WQ (all heads combined) | dmodel2 |
| WK (all heads combined) | dmodel2 |
| WV (all heads combined) | dmodel2 |
| WO | dmodel2 |
| Total | 4dmodel2 |
This is a useful mnemonic: the attention sublayer has 4dmodel2 parameters, and the FFN sublayer has 8dmodel2 parameters (assuming inner dimension = 4dmodel).
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
Step 2: Projection for Head 1 (simplified — each W is 6×2)
W1Q,W1K,W1V transform X to Q₁, K₁, V₁ ∈ ℝ^{2×2}.
Let's say Head 1 projections yield:
Step 3: Attention in Head 1
Scale:
Softmax row 1: e0.269=1.309,e0.141=1.151, sum=2.460, weights=[0.532, 0.468] Softmax row 2: e0.354=1.425,e0.262=1.300, sum=2.725, weights=[0.523, 0.477]
Output₁ = A₁·V₁: Row 1: [0.532⋅0.8+0.468⋅0.3,0.532⋅0.2+0.468⋅0.9]=[0.566,0.528] Row 2: [0.523⋅0.8+0.477⋅0.3,0.523⋅0.2+0.477⋅0.9]=[0.562,0.534]
Step 4: Repeat for Heads 2 and 3 → head₂, head₃ ∈ ℝ^{2×2}
Step 5: Concatenate
The concatenation has shape (2, 6) — same as input.
Step 6: Output projection WO∈R6×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:
- Many heads are redundant: Pruning up to 40% of heads can maintain performance
- Head importance varies: Some heads contribute critically to certain tasks
- 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:
- Parallel pattern capture: Attend to syntax, semantics, and position simultaneously
- Robustness: Redundancy provides graceful degradation
- Interpretability: Head analysis reveals what the model learns
- Efficiency: Same parameter budget as single head, but richer representations
4. 📐 Key Formulas / Concepts
| Concept | Formula | Description |
|---|---|---|
| Multi-head output | Concat(head1,...,headh)WO | Combine all heads |
| Single head | Attention(QWiQ,KWiK,VWiV) | Per-head computation |
| Per-head dim | dk=dmodel/h | Dimension per head |
| Parameter count | 4dmodel2 | Total attention parameters |
| Head count range | h∈{8,12,16,24,32} | Typical values |
| Output shape | (n,dmodel) | 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 WO (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,WV∈Rdmodel×dmodel
- Concat has only 1 head, so Concat(head₁) = head₁
- WO∈Rdmodel×dmodel
MultiHead(Q, K, V) = head₁ · W^O = Attention(QW^Q, KW^K, VW^V)W^OSince 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 = 64Per head: 3 × 1024 × 64 = 196,608 All heads: 16 × 196,608 = 3,145,728 W^O: 1024 × 1024 = 1,048,576Total: 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:
- Underfitting: The model hasn't learned to differentiate head roles (training may be insufficient)
- Low model capacity: d_k might be too small for meaningful specialization
- Data issue: The training data may lack the diversity needed for specialization
- 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:
- Sentence boundary detection: Tracking where one sentence ends and another begins
- Next sentence prediction: The NSP task requires understanding sentence relationships
- 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
- Previous topic: Self-Attention & QKV
- Next topic: Positional Encoding
- Related: Transformer Encoder & Decoder Layers (Week 2) Join Discord PreviousSelf-Attention & QKVNextPositional Encoding