Study the paper
Attention Is All You Need
Lessons, visuals, quizzes, flashcards, and resources—organized in teaching order.
Multi-Head Attention
Multi-Head Attention
Multi-Head Attention
Source equation
The Multi-Head Attention mechanism allows the model to jointly attend to information from different representation subspaces at different positions. Instead of performing a single attention function with -dimensional queries, keys, and values, we project them times with different, learned linear projections.
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}Each head is computed as an independent scaled dot-product attention: where the projections are parameter matrices , , , and .
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}Implementation detail
Illustrative Toy Calculation
Let us consider a simplified setup with heads, , and .
Suppose the outputs of the two heads for a single token are:
-
Concatenation:
-
Linear Projection: Let the output projection matrix be a identity matrix:
-
Final Output:
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 containing representation vectors · Matrix of shape (N, d_model)
- Key matrix containing representation vectors · Matrix of shape (M, d_model)
- Value matrix containing representation vectors · Matrix of shape (M, d_model)
- The output of the i-th attention head · Matrix of shape (N, d_v)
- Number of attention heads · Scalar integer
- Learned output projection parameter matrix · Matrix of shape (h * d_v, d_model)
- Concatenation operation along the feature dimension · Function mapping h matrices of shape (N, d_v) to a single matrix of shape (N, h * d_v)