In the Transformer architecture, the Query (Q), Key (K), and Value (V) vectors are derived from the input embeddings using learned weight matrices. Here’s how they are computed:
1. Formulas for Q, K, V Vectors
Given an input embedding vector ( x ) of dimension ( d_{\text{model}} ), the Q, K, V vectors are obtained by multiplying the input with three separate weight matrices:
[
Q = x \cdot W_Q
]
[
K = x \cdot W_K
]
[
V = x \cdot W_V
]
where:
- ( W_Q \in \mathbb{R}^{d_{\text{model}} \times d_k} )
- ( W_K \in \mathbb{R}^{d_{\text{model}} \times d_k} )
- ( W_V \in \mathbb{R}^{d_{\text{model}} \times d_v} )
Here:
- ( d_k ) is the dimension of the Key and Query vectors (usually the same).
- ( d_v ) is the dimension of the Value vector (can be different from ( d_k )).
2. Attention Weights (Scaled Dot-Product Attention)
The attention weights determine how much each input token should attend to others. They are computed as:
[
\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right) V
]
- Step 1: Compute the dot product between Query and Key vectors:
[
\text{Scores} = QK^T
]
- Step 2: Scale the scores by ( \sqrt{d_k} ) to prevent large dot products from causing gradient instability:
[
\text{Scaled Scores} = \frac{QK^T}{\sqrt{d_k}}
]
- Step 3: Apply softmax to get the attention weights (probability distribution over tokens):
[
\text{Attention Weights} = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)
]
- Step 4: Multiply the attention weights by the Value vectors to get the context vector:
[
\text{Context Vector} = \text{Attention Weights} \cdot V
]
3. Context Vector
The context vector is the weighted sum of the Value vectors, where the weights are determined by the attention mechanism. It represents a refined embedding that captures relevant information from the input sequence.
Summary
- Q, K, V are linear projections of the input embeddings.
- Attention weights are computed using scaled dot-product attention.
- The context vector is the final output of the attention mechanism, used in subsequent layers.
This mechanism allows the model to dynamically focus on different parts of the input sequence, making it highly effective for tasks like machine translation, text generation, and more.