Study the paper
Attention Is All You Need
Lessons, visuals, quizzes, flashcards, and resources—organized in teaching order.
Multi-Head Attention Mechanism
Multi-Head Attention
Multi-Head Attention
Source equation
Multi-Head Attention allows the model to jointly attend to information from different representation subspaces at different positions. Instead of performing a single attention function with queries, keys, and values, the queries, keys, and values are projected multiple 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}The output of each individual attention head is concatenated along the feature dimension, and then projected using a learned parameter matrix to produce the final multi-head attention 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}Implementation detail
Illustrative Toy Calculation
Let us compute the final output of a multi-head attention layer with heads, where each head produces a 2-dimensional output for a single token, and the final output projection matrix maps the concatenated representation back to a 2-dimensional space.
-
Inputs:
-
Step 1: Concatenation
-
Step 2: Linear Projection
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 representing the queries · Matrix of shape (N, d_k)
- Key matrix representing the keys · Matrix of shape (M, d_k)
- Value matrix representing the values · Matrix of shape (M, d_v)
- The output of the i-th attention head · Matrix of shape (N, d_v)
- Number of attention heads · Scalar integer
- 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)
- Learned output projection parameter matrix · Matrix of shape (h * d_v, d_model)
- The final multi-head attention output · Matrix of shape (N, d_model)