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 over a set of values based on queries and keys. The scaling factor is introduced to prevent the dot products from growing extremely large in magnitude for high-dimensional keys, which would otherwise push the softmax function into regions with extremely small gradients.
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}}})VImplementation detail
Illustrative Toy Calculation
Let us compute the attention output for a single query vector with :
- Query vector (shape: )
- Key matrix (shape: )
- Value matrix (shape: )
Step 1: Compute the dot product
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 of shape (batch_size, sequence_length_q, d_k) · [B, S_Q, d_k]
- Key matrix of shape (batch_size, sequence_length_k, d_k) · [B, S_K, d_k]
- Value matrix of shape (batch_size, sequence_length_k, d_v) · [B, S_K, d_v]
- Dimensionality of the keys and queries · Scalar
- The resulting attention representation of shape (batch_size, sequence_length_q, d_v) · [B, S_Q, d_v]