Study the paper
Attention Is All You Need
Lessons, visuals, quizzes, flashcards, and resources—organized in teaching order.
Scaled Dot-Product Attention
Scaled Dot-Product Attention
Scaled Dot-Product Attention
Source equation
The Scaled Dot-Product Attention mechanism maps a set of query vectors, key vectors, and value vectors to an output. The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.
Sources
S3.E1
Attention(Q,K,V)=softmax(QKTdk)V\mathrm{Attention}(Q,K,V)=\mathrm{softmax}(\frac{QK^{T}}{\sqrt{d_{k}}})V (1)
\mathrm{Attention}(Q,K,V)=\mathrm{softmax}(\frac{QK^{T}}{\sqrt{d_{k}}})VSources
S3.E1
Attention(Q,K,V)=softmax(QKTdk)V\mathrm{Attention}(Q,K,V)=\mathrm{softmax}(\frac{QK^{T}}{\sqrt{d_{k}}})V (1)
\mathrm{Attention}(Q,K,V)=\mathrm{softmax}(\frac{QK^{T}}{\sqrt{d_{k}}})VDeep dive
Why scale by ?
For large values of , the dot products grow large in magnitude, pushing the softmax function into regions with extremely small gradients. To counteract this effect, the dot products are scaled by .
Sources
S3.E1
Attention(Q,K,V)=softmax(QKTdk)V\mathrm{Attention}(Q,K,V)=\mathrm{softmax}(\frac{QK^{T}}{\sqrt{d_{k}}})V (1)
\mathrm{Attention}(Q,K,V)=\mathrm{softmax}(\frac{QK^{T}}{\sqrt{d_{k}}})VImplementation detail
Let's walk through a deterministic toy example with a single query, two keys, and two values.
Let:
- (shape: , so )
- (shape: )
- (shape: )
Step 1: Compute the dot products :
Step 2: Scale by :
Step 3: Apply softmax:
Step 4: Multiply by :
Sources
S3.E1
Attention(Q,K,V)=softmax(QKTdk)V\mathrm{Attention}(Q,K,V)=\mathrm{softmax}(\frac{QK^{T}}{\sqrt{d_{k}}})V (1)
\mathrm{Attention}(Q,K,V)=\mathrm{softmax}(\frac{QK^{T}}{\sqrt{d_{k}}})V- Query matrix containing packed query vectors · matrix of shape (d_seq_q, d_k)
- Key matrix containing packed key vectors · matrix of shape (d_seq_k, d_k)
- Value matrix containing packed value vectors · matrix of shape (d_seq_k, d_v)
- Dimensionality of the key vectors · scalar
- The resulting attention representation · matrix of shape (d_seq_q, d_v)