Study the paper
Attention Is All You Need
Lessons, visuals, quizzes, flashcards, and resources—organized in teaching order.
Multi-Head Attention Mechanics
Multi-Head Attention
Multi-Head Attention
Source equation
The Multi-Head Attention mechanism projects queries, keys, and values into multiple lower-dimensional subspaces, performs attention on each subspace in parallel, and then concatenates and projects the results back to the original dimension.
Sources
equation
MultiHead(Q,K,V)\displaystyle\mathrm{MultiHead}(Q,K,V) =Concat(head1,…,headh)WO\displaystyle=\mathrm{Concat}(\mathrm{head_{1}},...,\mathrm{head_{h}})W^{O}
\displaystyle\mathrm{MultiHead}(Q,K,V)=\mathrm{Concat}(\mathrm{head_{1}},...,\mathrm{head_{h}})W^{O}Sources
equation
MultiHead(Q,K,V)\displaystyle\mathrm{MultiHead}(Q,K,V) =Concat(head1,…,headh)WO\displaystyle=\mathrm{Concat}(\mathrm{head_{1}},...,\mathrm{head_{h}})W^{O}
\displaystyle\mathrm{MultiHead}(Q,K,V)=\mathrm{Concat}(\mathrm{head_{1}},...,\mathrm{head_{h}})W^{O}Illustrative Toy Calculation
Let us consider a simplified scenario with heads, where each head output is a 1D vector of size 2:
-
Concatenation:
-
Linear Projection: Let the output projection matrix be a matrix:
-
Result:
Sources
equation
MultiHead(Q,K,V)\displaystyle\mathrm{MultiHead}(Q,K,V) =Concat(head1,…,headh)WO\displaystyle=\mathrm{Concat}(\mathrm{head_{1}},...,\mathrm{head_{h}})W^{O}
\displaystyle\mathrm{MultiHead}(Q,K,V)=\mathrm{Concat}(\mathrm{head_{1}},...,\mathrm{head_{h}})W^{O}- Query matrix · (N, d_model)
- Key matrix · (M, d_model)
- Value matrix · (M, d_model)
- Output of the i-th attention head · (N, d_v)
- Number of attention heads · scalar
- Output projection parameter matrix · (h * d_v, d_model)
- Final multi-head attention output · (N, d_model)