Self-Attention
In the embeddings reading, we saw how to turn text into vectors. A word gets the same embedding every time it appears, even when it means something different in a new sentence. We’d like its vector to reflect how we’re using it here.
In a convolution, each output uses the same learned weights for its local window. With self-attention, the weights come from the sentence itself, and a word can draw on any position in the sequence.
Combining Positions
What can the surrounding words tell us about a word like small? In How the Grinch Stole Christmas!, we read that “his heart was two sizes too small.” Here heart tells us what is small, and too tells us that its size is a problem. We’d like the vector for small to draw on both.
Let \(\mathbf x_1,\ldots,\mathbf x_n\in\mathbb R^d\) be the embeddings of the \(n\) tokens in our sentence. We’ll put them in the rows of \(\mathbf X\in\mathbb R^{n\times d}\). We apply the same learned linear map to each \(\mathbf x_j\) to get its value \(\mathbf v_j\). To build the output at position \(i\), we take a weighted average of these values:
\[ \mathbf y_i=\sum_{j=1}^{n}a_{ij}\mathbf v_j, \qquad a_{ij}\geq0, \qquad \sum_{j=1}^{n}a_{ij}=1. \]
In our example, small is the seventh token. Let’s build \(\mathbf y_7\) by hand. We chose a two-dimensional value for each token (the blue points) and gave each one a weight (the bars above the sentence). The green point is \(\mathbf y_7\). Try giving heart all the weight. Where does the green point end up?
Each token supplies a value vector. As the attention weight on “heart” increases, the output for “small” moves toward the value for “heart.” At full weight the two vectors coincide.
Choosing Weights
How can we learn which words small should draw on? We use two more linear maps to give each token a query \(\mathbf q_i\in\mathbb R^d\) and a key \(\mathbf k_i\in\mathbb R^d\). For small, we take its query and compare it with every key in the sentence. As in contrastive learning, we score each pair with an inner product:
\[ s_{ij}=\frac{1}{\sqrt{d}}\,\mathbf q_i^\top\mathbf k_j, \qquad i,j\in\{1,\ldots,n\}. \]
Queries and keys need the same dimension so we can take their inner product. Here, we don’t normalize them to unit length, so both their lengths and their angle affect the score.
For one query \(i\), softmax turns its scores into weights:
\[ a_{ij}=\frac{\exp(s_{ij})}{\sum_{k=1}^{n}\exp(s_{ik})}. \]
The weights are positive and sum to one. For example, if we increase the score between the query for small and the key for heart, holding the other scores fixed, softmax gives heart a larger share of the weighted average. Its value \(\mathbf v_2\) tells us what we add to \(\mathbf y_7\) with that weight.
Stacking the vectors for all \(n\) positions gives us
\[ \mathbf Q=\mathbf X\mathbf W_Q,\qquad \mathbf K=\mathbf X\mathbf W_K,\qquad \mathbf V=\mathbf X\mathbf W_V, \]
where \(\mathbf W_Q,\mathbf W_K,\mathbf W_V\in\mathbb R^{d\times d}\). The rows of \(\mathbf Q\), \(\mathbf K\), and \(\mathbf V\) are the queries, keys, and values we just defined. Each map uses the same parameters at every position.
Matrix multiplication computes every query-key comparison, then every weighted value sum:
\[ \mathbf S=\frac{1}{\sqrt{d}}\,\mathbf Q\mathbf K^\top, \qquad \mathbf A=\operatorname{softmax}_{\mathrm{rows}}(\mathbf S), \qquad \mathbf Y=\mathbf A\mathbf V. \]
Both \(\mathbf S\) and \(\mathbf A\) are \(n\times n\) matrices. Multiplying row \(i\) of \(\mathbf A\) by \(\mathbf V\) gives the weighted average \(\mathbf y_i^\top\), row \(i\) of \(\mathbf Y\in\mathbb R^{n\times d}\).
In the figure below, hover over a score to see which query and key we multiplied. You can do the same for a weight in \(\mathbf A\) or an output in \(\mathbf Y\). Blue entries are positive, orange entries are negative, and darker colors mean larger magnitudes.
Try dragging an entry of \(\mathbf Q\) up or down. Only one row of attention weights changes. Now drag an entry of \(\mathbf K^\top\). Why can this change every row?
Each row of Q is a query and each column of Kᵀ is a key. Each entry of S is the product of \(\frac{1}{\sqrt{d}}\) and the corresponding dot product. Row-wise softmax gives A, whose rows sum to one. Each entry of Y is the dot product of a row of A and a column of V. The vectors are chosen by hand, not learned word embeddings.
We train \(\mathbf W_Q\), \(\mathbf W_K\), and \(\mathbf W_V\) by backpropagating through the weighted average, the softmax, and the three linear maps. Once we’ve trained these matrices, we can use them on a new sentence. We still have to compute \(\mathbf A\) for that sentence. This is what makes self-attention nonlinear in \(\mathbf X\): changing a word can change both its value and the weights we use to combine the values.
For a sentence with \(n\) tokens, we compare each of the \(n\) queries with all \(n\) keys. That’s \(n^2\) dot products for one attention head.
Score Scaling
Why multiply the scores by \(\frac{1}{\sqrt{d}}\)? Each query-key score adds up \(d\) products. If we double the number of coordinates, what happens to the size of that sum? Let’s look at a simple model of the queries and keys before training.
Claim: Fix positions \(i\) and \(j\). Suppose the \(2d\) entries of \(\mathbf q_i,\mathbf k_j\in\mathbb R^d\) are independent standard Gaussians. Then \[ \operatorname{Var}(\mathbf q_i^\top\mathbf k_j)=d, \qquad \operatorname{Var}\!\left(\frac{1}{\sqrt{d}}\,\mathbf q_i^\top\mathbf k_j\right)=1. \]
Proof
The dot product pairs the first coordinate of \(\mathbf q_i\) with the first coordinate of \(\mathbf k_j\), the second with the second, and so on. For each coordinate \(r=1,\ldots,d\), independence gives \[ \mathbb E[q_{ir}k_{jr}]=\mathbb E[q_{ir}]\,\mathbb E[k_{jr}]=0, \qquad \mathbb E[q_{ir}^2k_{jr}^2]=\mathbb E[q_{ir}^2]\,\mathbb E[k_{jr}^2]=1. \] Each product therefore has variance one. Since different coordinates use independent entries, we can add their variances: \[ \operatorname{Var}(\mathbf q_i^\top\mathbf k_j) =\operatorname{Var}\!\left(\sum_{r=1}^{d}q_{ir}k_{jr}\right) =\sum_{r=1}^{d}\operatorname{Var}(q_{ir}k_{jr})=d. \] Multiplying the dot product by \(\frac{1}{\sqrt{d}}\) multiplies its variance by \(\frac{1}{d}\), giving variance one.
When one score is much larger than the others, its softmax weight is close to one. Recall that \(\partial a_{ij}/\partial s_{ij}=a_{ij}(1-a_{ij})\). Near zero or one, the weight changes very little in response to a small change in its score.
We drew one set of random queries and keys for both heatmaps. Move the slider to include more of their coordinates. On the left, a few positions take up most of the weight as \(d\) grows. On the right, we multiply the scores by \(\frac{1}{\sqrt{d}}\) before applying softmax. Both heatmaps use the same shade of blue for the same weight.
The two heatmaps use the same independent standard Gaussian query and key entries. Without scaling, increasing the dimension tends to concentrate each row's attention on fewer positions. Multiplying scores by \(\frac{1}{\sqrt{d}}\) keeps their variance at one.
Dimension
Each query assigns a score to each of the \(n\) tokens. How much freedom do we have in choosing those \(n\) scores? For a query \(\mathbf q\in\mathbb R^d\), the vector of scores is \[ \frac{1}{\sqrt{d}}\mathbf K\mathbf q =\frac{1}{\sqrt{d}}\sum_{r=1}^{d}q_r\,\mathbf K_{:,r}. \] Each column of \(\mathbf K\) gives one pattern of scores across the tokens. The query’s \(d\) coordinates tell us how to combine those patterns. Different queries can choose different combinations, but they all use the same \(d\) patterns. Thus every row of the score matrix lies in a common subspace of dimension at most \(d\). Equivalently, \(\operatorname{rank}(\mathbf S)\le d\).
When \(d\ll n\), the model can still produce \(n\) scores per token, but it has far fewer than \(n\) independent directions in which to vary them. Training can change which directions the keys provide. The dimension \(d\) limits how many are available at once.
Generating Tokens
Suppose we stop just after too and ask the model to predict the next word. To make that prediction, we use the output at too. If that position could already attend to small, we would be giving away the answer.
With causal attention, we take the softmax at position \(i\) over just the first \(i\) scores. The resulting output \(\mathbf y_i\) helps predict token \(i+1\):
\[ a_{ij}= \begin{cases} \displaystyle\frac{\exp(s_{ij})}{\sum_{k=1}^{i}\exp(s_{ik})},&j\leq i,\\[6pt] 0,&j>i, \end{cases} \qquad \mathbf y_i=\sum_{j=1}^{i}a_{ij}\mathbf v_j. \] Only the available positions enter the softmax denominator, so their weights still sum to one. The attention matrix is lower triangular: row \(i\) can have nonzero entries only in columns \(1,\ldots,i\).
When \(\mathbf x_{n+1}\) arrives, the earlier outputs \(\mathbf y_1,\ldots,\mathbf y_n\) stay the same because none of them uses this new input. At each layer, we compute the new token’s query, key, and value, then compare its query with the keys at positions \(1,\ldots,n+1\). We can reuse the earlier keys and values, stored in a key-value cache, to compute the new output \(\mathbf y_{n+1}\). This takes \(n+1\) new dot products, one for each entry of the new row.
Below are measured attention weights from GPT-2, layer 3, head 10, for the Grinch line above. Each head computes its own attention weights. Move the slider from too to small to see the row added for small.
Each output can use only the current and earlier input tokens. In GPT-2's measured attention matrix, all entries above the diagonal are zero. Revealing a new token adds its row without changing earlier weights, so their keys and values can be reused.
During training, the full sentence is available, so we can compute all these rows in parallel while masking the future positions.