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 computes attention weights by taking the dot product of queries with keys, scaling them by the square root of the key dimension, applying a softmax function, and using the resulting weights to compute a weighted sum of the values.
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
To compute the attention matrix:
- Compute the dot products of the queries and keys by calculating .
- Scale the dot products by dividing each element by to prevent extremely large values that lead to vanishing gradients in the softmax function.
- Apply the softmax function row-wise to obtain the attention weights.
- Multiply the attention weights by the values to produce the final output matrix.
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
Consider a simplified deterministic example with (so ). Let the query matrix and key matrix be:
Then, the dot product is:
Scaling by yields:
Applying the softmax (which is trivial for a single element, yielding ) and multiplying by a value vector results in:
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 of shape (d_seq, d_k) · [d_seq, d_k]
- Key matrix of shape (d_seq, d_k) · [d_seq, d_k]
- Value matrix of shape (d_seq, d_v) · [d_seq, d_v]
- Dimension of the keys · scalar
- Softmax activation function applied row-wise · function