At one position of a sentence a model may need information from one particular earlier position, for example the noun that a pronoun refers to. A recurrent network has to carry that information forward in a hidden state of fixed size, step by step. Attention lets each position form a weighted average of vectors from every position it is allowed to see, with weights that measure how well the positions match. This lesson defines that computation with every matrix shape stated, works a three-position example by hand, and shows how masks decide which positions are visible. All vectors in the example are constructed for teaching and are dimensionless.
Key terms
Query, key and value vectors
Definition Let the rows of a matrix in be the vector representations of the positions of a sequence, one row per position. Self-attention computes three matrices from with learned projection matrices,
where and have shape and has shape . Row of is the query vector of position , row of is the key vector of position , and row of is its value vector . A key and a value with the same index belong to the same position, so and always have the same number of rows. Queries and keys must have the same width , because they are compared by dot products, while the value width may differ. In cross-attention the queries come from one sequence and the keys and values from another, so the number of queries and the number of keys can differ. In self-attention .
In plain words Every position plays three roles. Its query describes what it is looking for, its key describes how other positions can find it, and its value is the content it hands over when it is found. These are learned coordinates, not literal questions and answers. The same token gets three different vectors because the three projections differ.
Example In the example of this lesson the three input rows are the one-hot vectors of , so is the identity matrix and each projection returns its own weight matrix. The weights were chosen by hand,
Here , and . Position , for example, has query , key and value .
Scaled dot-product attention
Definition Let in hold query vectors as rows, in hold key vectors, and in hold the matching value vectors. Scaled dot-product attention first forms the score matrix
of shape , whose entry compares query with key . It applies the softmax to each row of separately, which gives the attention weight matrix of the same shape, and returns
an matrix whose row is the output for query . In one formula the output is with the softmax taken along each row, over the keys. The products are defined exactly when and have the same number of columns and and have the same number of rows. The factor has a specific reason. If the entries of a query and a key are independent random variables with mean and variance , then has mean and variance , so the scaled score has variance . Learned vectors need not satisfy these assumptions, so the scaling keeps typical scores moderate without guaranteeing any range.
In plain words Compare every query with every key by a dot product, scale, turn each query’s row of scores into weights that add to , and use those weights to average the value vectors. Without the scaling, scores spread more widely as grows, the softmax then tends to put nearly all weight on the largest score, and the gradients that reach the other scores become very small. A softmax down each column, over the queries, would normalize a different quantity and is not this definition.
Example With the scores of the example are
The first query has dot products , and with the three keys, so its scores are , and . The exponentials are , and with total , so its weights are
about . The output is the weighted sum of the value rows , and ,
Keys and get equal weight because their scores are equal, yet they contribute differently because their values differ. The keys themselves are never averaged. Doing the same for all three rows gives the output
Attention weights
Definition The attention weights are the entries of . Without a mask, for each query and key ,
With finite scores every weight is positive and every row adds to , so the output is a convex combination of the value vectors. Each coordinate of therefore lies between the smallest and the largest value of that coordinate among the value vectors. Equal scores in a row give equal weights. Adding the same constant to every score of a row changes nothing, which is why implementations subtract the row maximum before exponentiating. A weight says how much value vector contributes to the output of query in one head of one layer. It is not a measure of how much the original token at position influences the model’s final prediction.
In plain words Each query spreads one unit of weight over the keys it may use. A large weight means that position’s value dominates this particular average. The values are themselves learned projections, other heads and residual paths carry information around the attention, and later layers mix everything again, so a large weight on a token does not show that the token caused the prediction. Questions about influence need explicit comparisons, such as changing the input and measuring the effect, and even those describe the model, not causes in the world the text is about.
Example Row of the example has scores , so its weights are
about . Its output is , and the second coordinate is exactly because . Every output coordinate in lies between the smallest and largest entries of the corresponding column of , as a convex combination must. Full attention also has a cost. One head computes scores, so self-attention over positions computes of them, whether or not an implementation stores them all at once. Doubling multiplies the count by , and already gives scores per head and layer.
Attention mask
Definition An attention mask is a matrix of shape with when query may use key and when it may not. Masked attention sets each masked score to before the row softmax, with . This is the same as taking the softmax over the allowed keys only,
Masked weights are exactly , the allowed weights of each row add to , and output is a convex combination of the allowed values only. The formula needs at least one allowed key in every row. In a fully masked row the denominator is , so no probability distribution exists. The convention in this course is to reject such a row with an error. Another system might return a zero vector with a flag marking the row as invalid, but whichever convention is used must be stated and its downstream use checked. A common use is the padding mask. When sequences of different lengths are padded to one length to form a batch, the mask removes the padding keys, and the outputs at padded query positions are left out of the loss.
In plain words A mask decides which positions each query may see, and it has to act before the normalization. A row that may see nothing has no meaningful output. Implementations that use a large finite negative number in place of raise no error for such a row and silently return an average of masked values, which is worse than an explicit failure.
Example Suppose position of the example were padding. Then every query may use keys and only. Query keeps the scores and , so its weights become and , and its output is
Query is padding too, so its output is computed but excluded from the loss. If some row had no allowed key at all, this course’s implementation would stop with an error instead of inventing weights.
Causal mask
Definition For self-attention over a sequence read from left to right, with positions , the causal mask allows key for query exactly when . Its matrix is lower triangular, with ones on and below the diagonal, so for every . The diagonal is allowed, because the token at position is already known when position is used to predict the next token. Every row allows at least its own position, so a causal mask alone never produces a fully masked row. When every attention layer uses a causal mask and all other operations act on each position separately, the output at position depends only on the inputs at positions to .
In plain words No position may look ahead. During training the whole sequence is available at once, and without the mask a position could read the very token it is supposed to predict. The mask gives training exactly the information that will exist during generation, when later tokens have not been produced yet.
Example With the causal mask, query of the example may use key only, so its weight is and its output is exactly . Query may use keys and , with scores and , so
and its output is . Query may use every position, so its output is unchanged. The masked entries are the three entries above the diagonal of .
Multi-head attention
Definition Multi-head attention with heads runs scaled dot-product attentions side by side, each with its own projections. In self-attention, head forms , and and computes
an matrix. The head outputs are concatenated along the feature axis into an matrix, which a learned output matrix of shape maps back to one vector per query,
Usually every head uses the same mask, and a common choice is and , so the result has the model’s width again. Because each head has its own projections, different heads can give the same query different weights.
In plain words One softmax gives each query one way to distribute its attention. Several heads let a position combine several differently weighted averages, each computed in its own learned coordinates, and the output matrix mixes them into one vector. Heads are not independent votes, and training does not guarantee that each one has a neat, human-readable job. They can be redundant, share a role or change behavior with context. In code the head axis must stay separate from the batch, position and feature axes, since a reshape that mixes these axes can combine unrelated positions while every shape still matches.
Example Four heads that each return coordinates per query concatenate to coordinates, and an output matrix of shape turns them into a -dimensional vector per query. The number of queries stays the same, only the feature width changes. If the model width is and each head uses , each head has three projection matrices with weights, and the layer has weights without biases.
Check yourself
- Queries, keys and values have shapes of , of and of . Give the shapes of the scores, the attention weights and the output, and the number that divides the scores. Would a value matrix of shape work?
Show the answer
The product is , so the scores form a matrix, one row per query and one column per key. The row softmax keeps that shape, so the weights are too. The output is , a matrix with one -dimensional output per query. The query and key width is , so the scores are divided by .
A value matrix of shape does not work. Each of the keys needs a matching value, and the product of a weight matrix with a matrix is undefined. A value width of , different from , is no problem.
- One query has two allowed keys with scaled scores and , and the matching scalar values are and . Find the attention weights and the output. What happens if both keys are masked?
Show the answer
The exponentials are and , with total , so the weights are and . The output is
which lies between the two values, as a convex combination must.
If both keys are masked, the row has no allowed key. The masked softmax has denominator , so there is no probability distribution and no defined output, and this course’s implementation stops with an error. A caller has to supply at least one allowed key or use a separately stated convention such as a zero output with an invalid flag. Adding a large negative constant to both scores would instead return the weights and again and the output , as if nothing were masked.
- Which entries of the score matrix must a causal mask exclude for a sequence of positions? A colleague also masks the diagonal. Another applies the causal mask to the three-position example by zeroing the future weights after the softmax. What goes wrong in each case?
Show the answer
The causal mask excludes every entry with key index above the query index, the entries , , , , and . That is entries, all strictly above the diagonal.
Masking the diagonal as well leaves the first query with no allowed key at all, a fully masked row, and it denies every position its own current token, which is available when predicting the next one.
Zeroing after the softmax breaks the normalization. Without a mask, row of the example has weights . Zeroing the third leaves weights that add to
and the output becomes about instead of the correct . Dividing the two remaining weights by their sum restores , which is exactly the result of masking before the softmax.