Attention
Attention is a lookup table that can be learned with gradient descent. The table stores pairs of a key and a value . A query asks for the values whose keys match it. A hash table would return the value of the one key that equals the query. Attention returns a weighted average of all the values, and keys more similar to the query get more weight:
Here is the length of queries and keys, and is the score of key . The attention weights are positive and sum to . The lecture calls this operation queryable softmax pooling. It has no parameters of its own.The learned parts produce the queries, keys and values. Stack token vectors as the rows of . Then
with , , bias vectors and the all-ones vector . Row of is the query of token , and likewise for and . All lookups then take two matrix products:
The softmax acts on each row separately. Entry of the attention matrix is the weight that query gives key .Three forms of attention differ in who fills the table and who queries it:
- Self-attention: one sequence makes the queries, the keys and the values. Every token can read every token, including itself.
- Causal (masked) self-attention: token may read only tokens . The scores for are set to before the softmax, so their weights are .
- Cross-attention: the queries come from one sequence, such as a decoder. The keys and values come from another, such as an encoder.
Rows Versus Columns
This note stores tokens as the rows of , as HW10 and PyTorch do. The lecture and Prince store them as columns, . Their queries are with , so . Their output is , with the softmax taken over each column. That softmax matrix is , so their output equals . The lecture writes for the weight that query gives key , which is here.
Intuition
The lecture reaches attention by trying to build a hash table that gradient descent can train. A decoder step forms a query, and the encoder has stored keys with values. Four ideas follow, each fixing the problem of the one before:
- Exact match. Return the value whose key equals the query. With random initial weights, no key ever matches. A small change to the query still matches nothing, so no gradient exists.
- Closest match. Return the value of the most similar key. The returned value now gets a gradient. A small change to the query or the keys usually keeps the same winner, so their gradients are .
- Several close matches. Return the average of the values of the few most similar keys. The question becomes how to weight them.
- Weighted average. Weight every value by a similarity score turned into a probability with a softmax. Each weight now changes smoothly with the query and the keys, so all three get gradients.
The fourth idea is attention. Take the decoder step that writes “book” in a translation model. It can put its weight on the encoder state for “book”, wherever that word sits. This is a skip connection, as in a U-Net, whose address is computed from the content.
The same formula appears in the Fall 2022 lecture 17 notes, which make k-means trainable by gradient descent. The hard assignment of a point to its closest center becomes soft weights . The weighted center is then a softmax-weighted average. The point plays the role of the query, and the centers play the roles of both keys and values.
Properties
(Why Scale by ) Random queries and keys give scores whose variance grows like , and the scale keeps it at .
Let the entries of and be independent with mean and variance . Then has mean and variance , as HW9 shows. With , raw scores have standard deviation . A softmax of such scores puts nearly all weight on one key, and its gradient is nearly . Dividing by brings the standard deviation back to . The Spring 2023 lecture 14 notes explain why the scale is not . That scale would give scores with standard deviation . The weights would stay close to uniform, and selecting one key would need very large vectors.
(Softmax Versus Argmax) Attention with an argmax gives zero gradient to the queries and keys, but the softmax does not.
The softmax derivative gives
Each term pulls the output toward value when the query moves toward key . An argmax picks one key, and small changes leave the winner unchanged. Its derivative with respect to the scores is wherever the maximum is unique. Only the chosen value gets a gradient, as in HW9. The same formula shows that a saturated softmax behaves like an argmax. If one weight is near , every term is near .
(Self Versus Cross) Self-attention and cross-attention run the same computation and differ only in where the queries, keys and values come from.
In self-attention the sequence that writes the table also reads it. In cross-attention, a decoder with tokens forms . An encoder with tokens forms and . The attention matrix is then , and each decoder token gets one weighted average of encoder values. The key and value maps sit in the decoder layer and are trained by the decoder’s loss. They learn how to read the encoder’s output for the decoder’s task.
(The Causal Mask Allows Parallel Training) With a causal mask, one forward pass gives every position the output it would get from its own prefix.
Under the mask, the output of a layer at position depends only on the inputs at positions . Stacked layers keep this property, so the final output at ignores all later tokens. A decoder can therefore compute all next-token predictions and their losses in one pass. Without the mask, it would have to run once for each prefix. Adding to a score gives in the softmax. In code a large negative number, such as , plays this role.
(Permutation Equivariance) If the tokens of unmasked self-attention are permuted, its outputs are permuted in the same way.
Let be a permutation matrix and replace by . Then , and become , and . The scores become . A row-wise softmax commutes with reordering rows and columns, so the output is . The words of a sentence would then carry no order. 7.4. Positional Encoding adds the order back. A causal mask breaks this symmetry, because it depends on the positions.
(Inner Product or RBF) An RBF similarity gives the same weights as the inner product whenever all keys have the same norm.
The Spring 2023 lecture 14 notes name two similarity choices, the inner product and the RBF kernel . Expanding the square gives
The factor with is the same for every key, so it cancels in the softmax. If the keys share one norm, that factor cancels too. Only remains, which is dot-product attention with scale . Practice uses the inner product, which is cheaper and fits matrix multiplication. Other similarity kernels give other forms of attention.
(A Table Instead of a State) With attention, a sequence model stores information in a table that it writes and reads, not in a state.
An RNN must carry everything it may need later in its state . With self-attention, each token writes its key and value into a table, and later tokens look them up. The Fall 2022 lecture 17 notes describe this as writing notes to yourself instead of keeping an internal memory. The weights are still shared across positions, as in an RNN. A gradient reaches an earlier token directly through the attention weight, not through a long chain of state updates. Self-attention is also a message-passing layer on the complete graph of tokens, with learned edge weights.
(Reading an Attention Map) Row of states exactly how the output at position mixes the values of all positions.
The weights in a row are nonnegative and sum to . The output is therefore a convex combination of the values. Plotting as a heat map, as in HW10, shows which tokens each token reads. A model has one map per head and per layer, and different heads often read different things. A map shows where a head reads, not what it does with the values. Later layers also mix tokens that were already mixed, so one map does not explain a prediction.
(Cost) Self-attention over tokens computes an score matrix, so its time and memory grow as .
The product takes multiply-adds, and takes . Storing takes numbers per head. A causal mask removes about half the pairs, but the growth is still quadratic. An RNN takes sequential steps, while attention computes all pairs in parallel. 7.1.2. Efficient Attention covers methods that reduce the memory or the arithmetic.
Examples
(Easy) One Lookup
A query reads a table with three keys of length : , and . The values are , and .
Compute the scores, the weights and the output. Compare the output with argmax attention. , and . Dividing by gives the scores . The exponentials are , and , with sum . The weights are The output is . Argmax attention would return . The softmax output is close to it but also contains , whose key is second most similar.
The inner products are
(Medium) A Causal Mask
Three tokens have the scaled scores below, with row for query and column for key . Their values are , and .
Apply the causal mask, compute and the three outputs, and check which outputs change if token 3 changes. The mask sets the entries above the diagonal to . Row keeps only , so . Row keeps the scores and , giving weights and . Row keeps all three scores , which give as in the Easy example: The outputs are , and . Without the mask, row would have given most of its weight to key , whose score is . With the mask, changing token changes its key, value and query, which affect only row . The outputs and stay the same.
(Hard) Gradient of a Saturating Lookup
A query reads two keys and with values and . Here .
Find from the general formula, and evaluate it at , and . What does argmax attention give? The scores are and . The first weight is , where is the logistic function. The output is . The general formula gives Differentiating directly gives , the same result.
At the weights are and the gradient is . At they are and the gradient is . At they are and the gradient is . As the query grows, the softmax approaches an argmax and the gradient falls toward . Argmax attention returns for every , so its derivative is exactly there.
See Also
- 5.3.3. Sequence-to-Sequence Models, whose bottleneck attention removes.
- 7.1.1. Multi-Head Attention, several attention lookups in parallel.
- 7.1.2. Efficient Attention, for the cost of the matrix.
- 7.2. Transformer Architecture, the network built from attention blocks.
- 7.4. Positional Encoding, which gives attention the order of the tokens.
- 6.1.1. Message Passing, attention as message passing on a complete graph.
- 6.1. K-Means, whose soft version leads to the attention formula.
- 4.3a. Softmax Regression, for the softmax and its derivative.