I'll break down the backpropagation process through the attention mechanism of a decoder-only Transformer, including the mathematical formulation.
Attention Mechanism Recap
The attention mechanism in a Transformer is based on the scaled dot-product attention, which computes the attention weights as follows:
- Query (Q): The query vector is obtained by linearly transforming the input sequence.
- Key (K): The key vector is obtained by linearly transforming the input sequence.
- Value (V): The value vector is obtained by linearly transforming the input sequence.
- Attention Weights: The attention weights are computed by taking the dot product of the query and key vectors, applying a softmax function, and scaling by the square root of the key vector's dimensionality.
The attention output is computed by taking the dot product of the attention weights and the value vector.
Mathematical Formulation
Let's denote the input sequence as X, the query, key, and value vectors as Q, K, and V, respectively, and the attention output as Z. The attention mechanism can be formulated as follows:
- Query, Key, and Value:
Q = X * W_Q, K = X * W_K, V = X * W_V
- Attention Weights:
A = softmax(Q * K^T / sqrt(d_k))
- Attention Output:
Z = A * V
where W_Q, W_K, and W_V are learnable weight matrices, d_k is the dimensionality of the key vector, and ^T denotes the transpose operation.
Backpropagation through Attention
To backpropagate through the attention mechanism, we need to compute the gradients of the loss with respect to the input sequence X. Let's denote the loss as L and the gradients as dL/dX.
Using the chain rule, we can write:
dL/dX = dL/dZ * dZ/dA * dA/dQ * dQ/dX + dL/dZ * dZ/dA * dA/dK * dK/dX
Backpropagation through Queries and Keys
Now, let's break down the backpropagation process through the queries and keys:
- Backpropagation through Queries:
dL/dQ = dL/dZ * dZ/dA * dA/dQ