Module 9 — Multi-Head Attention
Multi-Head Attention (MHA) is an extension of the Self-Attention mechanism introduced in the original Transformer architecture. Instead of computing attention once, the model computes multiple attention operations in parallel using different learned projections.
Each attention head focuses on different relationships within the input sequence, enabling the model to learn richer contextual representations.
Topics
- Multiple Attention Heads
- Head Projection
- Concatenation
- Output Projection
1. Input Embedding
The input embedding matrix is
where
- = Sequence length
- = Embedding dimension
2. Query Projection
Each attention head learns its own Query projection matrix.
For head
where
3. Key Projection
Each head has its own Key projection.
where
4. Value Projection
Each head has its own Value projection.
where
5. Attention Head
Each head computes Scaled Dot-Product Attention independently.
Expanding the attention function,
6. Multiple Attention Heads
Assume there are
attention heads.
The outputs are
Each head learns different semantic relationships between tokens.
7. Concatenation
The outputs of all heads are concatenated along the feature dimension.
Output Shape
where
- = Number of heads
- = Value dimension
8. Output Projection
The concatenated output is projected back to the model dimension.
where
Output Shape
9. Complete Multi-Head Attention Formula
The complete Multi-Head Attention equation is
where
10. Matrix Dimensions
Suppose
- Sequence Length =
- Model Dimension =
- Number of Heads =
- Head Dimension =
Then
Input
Each Query
Each Key
Each Value
Each Attention Output
Concatenated Output
Final Output
11. Why Multi-Head Attention?
Multiple heads allow the Transformer to learn different relationships simultaneously.
Different heads can capture
- Local context
- Long-range dependencies
- Syntax
- Semantics
- Entity relationships
- Sentence structure
This improves representation learning compared to a single attention head.
Applications
Multi-Head Attention is the core component of
- Transformer
- BERT
- RoBERTa
- ALBERT
- GPT
- GPT-2
- GPT-3
- GPT-4
- T5
- ViT
- LLaMA
- Gemma
- Qwen
- DeepSeek
- Mistral
- Phi
- Modern Large Language Models (LLMs)
Summary
| Concept | Formula |
|---|---|
| Query Projection | |
| Key Projection |