Unit 11, lesson 75

Attention, Queries, Keys, and Values

How scaled dot-product attention compares query and key vectors, turns the scores into attention weights by a row-wise softmax and averages value vectors, and what attention masks, causal masks and multi-head attention add.

  • Video 75
  • Recurrence, Attention and Transformers

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 XX in Rn×d\mathbb{R}^{n \times d} be the vector representations of the nn positions of a sequence, one row per position. Self-attention computes three matrices from XX with learned projection matrices,

Q=XWQ,K=XWK,V=XWV,\begin{gathered} Q = XW_Q, \quad K = XW_K, \\[0.4em] V = XW_V, \end{gathered}

where WQW_Q and WKW_K have shape d×dkd \times d_k and WVW_V has shape d×dvd \times d_v. Row ii of QQ is the query vector qi\mathbf{q}_i of position ii, row jj of KK is the key vector kj\mathbf{k}_j of position jj, and row jj of VV is its value vector vj\mathbf{v}_j. A key and a value with the same index belong to the same position, so KK and VV always have the same number of rows. Queries and keys must have the same width dkd_k, because they are compared by dot products, while the value width dvd_v may differ. In cross-attention the queries come from one sequence and the keys and values from another, so the number of queries nqn_q and the number of keys nkn_k can differ. In self-attention nq=nk=nn_q = n_k = n.

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 R3\mathbb{R}^3, so XX is the 3×33 \times 3 identity matrix and each projection returns its own weight matrix. The weights were chosen by hand,

Q=[200222],K=[100111],V=[200422].\begin{gathered} Q = \begin{bmatrix} \sqrt{2} & 0 \\ 0 & \sqrt{2} \\ \sqrt{2} & \sqrt{2} \end{bmatrix}, \\[0.4em] K = \begin{bmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{bmatrix}, \\[0.4em] V = \begin{bmatrix} 2 & 0 \\ 0 & 4 \\ 2 & 2 \end{bmatrix}. \end{gathered}

Here n=3n = 3, d=3d = 3 and dk=dv=2d_k = d_v = 2. Position 33, for example, has query (2,2)(\sqrt{2}, \sqrt{2}), key (1,1)(1, 1) and value (2,2)(2, 2).

Scaled dot-product attention

Definition Let QQ in Rnq×dk\mathbb{R}^{n_q \times d_k} hold nqn_q query vectors as rows, KK in Rnk×dk\mathbb{R}^{n_k \times d_k} hold nk≥1n_k \ge 1 key vectors, and VV in Rnk×dv\mathbb{R}^{n_k \times d_v} hold the matching value vectors. Scaled dot-product attention first forms the score matrix

S=QK⊤dk,S = \frac{QK^{\top}}{\sqrt{d_k}} ,

of shape nq×nkn_q \times n_k, whose entry Sij=qi⊤kj/dkS_{ij} = \mathbf{q}_i^{\top}\mathbf{k}_j / \sqrt{d_k} compares query ii with key jj. It applies the softmax to each row of SS separately, which gives the attention weight matrix AA of the same shape, and returns

Attention⁡(Q,K,V)=AV,\operatorname{Attention}(Q, K, V) = AV ,

an nq×dvn_q \times d_v matrix whose row ii is the output for query ii. In one formula the output is softmax⁡(QK⊤/dk)V\operatorname{softmax}(QK^{\top}/\sqrt{d_k})V with the softmax taken along each row, over the keys. The products are defined exactly when QQ and KK have the same number of columns and KK and VV have the same number of rows. The factor 1/dk1/\sqrt{d_k} has a specific reason. If the 2dk2d_k entries of a query q\mathbf{q} and a key k\mathbf{k} are independent random variables with mean 00 and variance 11, then q⊤k\mathbf{q}^{\top}\mathbf{k} has mean 00 and variance dkd_k, so the scaled score has variance 11. 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 11, and use those weights to average the value vectors. Without the scaling, scores spread more widely as dkd_k 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 dk=2d_k = 2 the scores of the example are

S=QK⊤2=[101011112].S = \frac{QK^{\top}}{\sqrt{2}} = \begin{bmatrix} 1 & 0 & 1 \\ 0 & 1 & 1 \\ 1 & 1 & 2 \end{bmatrix} .

The first query has dot products 2\sqrt{2}, 00 and 2\sqrt{2} with the three keys, so its scores are 11, 00 and 11. The exponentials are ee, 11 and ee with total 2e+12e + 1, so its weights are

A1,:=(e,1,e)2e+1,A_{1,:} = \frac{(e, 1, e)}{2e + 1} ,

about (0.4223,0.1554,0.4223)(0.4223, 0.1554, 0.4223). The output is the weighted sum of the value rows (2,0)(2, 0), (0,4)(0, 4) and (2,2)(2, 2),

o1=(4e2e+1,4+2e2e+1)≈(1.6893,1.4661).\begin{aligned} \mathbf{o}_1 &= \left( \frac{4e}{2e + 1}, \frac{4 + 2e}{2e + 1} \right) \\[0.4em] &\approx (1.6893, 1.4661) . \end{aligned}

Keys 11 and 33 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 3×23 \times 2 output

O=AV≈[1.68931.46611.15542.53391.57612].\begin{aligned} O &= AV \\[0.4em] &\approx \begin{bmatrix} 1.6893 & 1.4661 \\ 1.1554 & 2.5339 \\ 1.5761 & 2 \end{bmatrix} . \end{aligned}

Attention weights

Definition The attention weights are the entries of AA. Without a mask, for each query ii and key jj,

Aij=exp⁡(Sij)∑l=1nkexp⁡(Sil).A_{ij} = \frac{\exp(S_{ij})}{\sum_{l=1}^{n_k} \exp(S_{il})} .

With finite scores every weight is positive and every row adds to 11, so the output oi=∑jAijvj\mathbf{o}_i = \sum_j A_{ij}\mathbf{v}_j is a convex combination of the value vectors. Each coordinate of oi\mathbf{o}_i 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 AijA_{ij} says how much value vector jj contributes to the output of query ii in one head of one layer. It is not a measure of how much the original token at position jj 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 33 of the example has scores (1,1,2)(1, 1, 2), so its weights are

A3,:=(1,1,e)2+e,A_{3,:} = \frac{(1, 1, e)}{2 + e} ,

about (0.2119,0.2119,0.5761)(0.2119, 0.2119, 0.5761). Its output is (2(1+e)/(2+e),2)≈(1.5761,2)\bigl(2(1 + e)/(2 + e), 2\bigr) \approx (1.5761, 2), and the second coordinate is exactly 22 because 4+2e=2(2+e)4 + 2e = 2(2 + e). Every output coordinate in OO lies between the smallest and largest entries of the corresponding column of VV, as a convex combination must. Full attention also has a cost. One head computes nqnkn_q n_k scores, so self-attention over nn positions computes n2n^2 of them, whether or not an implementation stores them all at once. Doubling nn multiplies the count by 44, and n=1024n = 1024 already gives 10242=1,048,5761024^2 = 1{,}048{,}576 scores per head and layer.

Attention mask

Definition An attention mask is a matrix MM of shape nq×nkn_q \times n_k with Mij=1M_{ij} = 1 when query ii may use key jj and Mij=0M_{ij} = 0 when it may not. Masked attention sets each masked score to −∞-\infty before the row softmax, with exp⁡(−∞)=0\exp(-\infty) = 0. This is the same as taking the softmax over the allowed keys only,

Aij=Mijexp⁡(Sij)∑l=1nkMilexp⁡(Sil).A_{ij} = \frac{M_{ij}\exp(S_{ij})}{\sum_{l=1}^{n_k} M_{il}\exp(S_{il})} .

Masked weights are exactly 00, the allowed weights of each row add to 11, and output ii 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 00, 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 −∞-\infty 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 33 of the example were padding. Then every query may use keys 11 and 22 only. Query 11 keeps the scores 11 and 00, so its weights become e/(1+e)≈0.7311e/(1 + e) \approx 0.7311 and 1/(1+e)≈0.26891/(1 + e) \approx 0.2689, and its output is

o1=(2e1+e,41+e)≈(1.4621,1.0758).\begin{aligned} \mathbf{o}_1 &= \left( \frac{2e}{1 + e}, \frac{4}{1 + e} \right) \\[0.4em] &\approx (1.4621, 1.0758) . \end{aligned}

Query 33 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 1,…,n1, \dots, n, the causal mask allows key jj for query ii exactly when j≤ij \le i. Its matrix is lower triangular, with ones on and below the diagonal, so Aij=0A_{ij} = 0 for every j>ij > i. The diagonal is allowed, because the token at position ii is already known when position ii 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 ii depends only on the inputs at positions 11 to ii.

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 11 of the example may use key 11 only, so its weight is 11 and its output is exactly v1=(2,0)\mathbf{v}_1 = (2, 0). Query 22 may use keys 11 and 22, with scores 00 and 11, so

A2,:=(11+e,e1+e,0)≈(0.2689,0.7311,0),\begin{aligned} A_{2,:} &= \left( \frac{1}{1 + e}, \frac{e}{1 + e}, 0 \right) \\[0.4em] &\approx (0.2689, 0.7311, 0) , \end{aligned}

and its output is (2/(1+e),4e/(1+e))≈(0.5379,2.9242)\bigl(2/(1 + e), 4e/(1 + e)\bigr) \approx (0.5379, 2.9242). Query 33 may use every position, so its output (1.5761,2)(1.5761, 2) is unchanged. The masked entries are the three entries above the diagonal of SS.

Multi-head attention

Definition Multi-head attention with hh heads runs hh scaled dot-product attentions side by side, each with its own projections. In self-attention, head r=1,…,hr = 1, \dots, h forms Q(r)=XWQ(r)Q^{(r)} = XW_Q^{(r)}, K(r)=XWK(r)K^{(r)} = XW_K^{(r)} and V(r)=XWV(r)V^{(r)} = XW_V^{(r)} and computes

O(r)=Attention⁡(Q(r),K(r),V(r)),\begin{aligned} O^{(r)} &= \operatorname{Attention}\bigl(Q^{(r)}, \\[0.4em] &\qquad K^{(r)}, V^{(r)}\bigr), \end{aligned}

an nq×dvn_q \times d_v matrix. The head outputs are concatenated along the feature axis into an nq×hdvn_q \times hd_v matrix, which a learned output matrix WOW_O of shape hdv×douthd_v \times d_{\text{out}} maps back to one vector per query,

MultiHead⁡(X)=[ O(1)  ⋯  O(h) ]WO.\begin{aligned} & \operatorname{MultiHead}(X) \\[0.4em] &\quad = \bigl[\, O^{(1)} \; \cdots \; O^{(h)} \,\bigr] W_O . \end{aligned}

Usually every head uses the same mask, and a common choice is dk=dv=d/hd_k = d_v = d/h and dout=dd_{\text{out}} = d, 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 dv=8d_v = 8 coordinates per query concatenate to 3232 coordinates, and an output matrix of shape 32×1632 \times 16 turns them into a 1616-dimensional vector per query. The number of queries stays the same, only the feature width changes. If the model width is d=16d = 16 and each head uses dk=dv=8d_k = d_v = 8, each head has three 16×816 \times 8 projection matrices with 3⋅128=3843 \cdot 128 = 384 weights, and the layer has 4⋅384+32⋅16=20484 \cdot 384 + 32 \cdot 16 = 2048 weights without biases.

Check yourself

  1. Queries, keys and values have shapes QQ of 2×32 \times 3, KK of 4×34 \times 3 and VV of 4×54 \times 5. 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 3×53 \times 5 work?
Show the answer

The product QK⊤QK^{\top} is (2×3)(3×4)(2 \times 3)(3 \times 4), so the scores form a 2×42 \times 4 matrix, one row per query and one column per key. The row softmax keeps that shape, so the weights are 2×42 \times 4 too. The output AVAV is (2×4)(4×5)(2 \times 4)(4 \times 5), a 2×52 \times 5 matrix with one 55-dimensional output per query. The query and key width is dk=3d_k = 3, so the scores are divided by 3\sqrt{3}.

A value matrix of shape 3×53 \times 5 does not work. Each of the 44 keys needs a matching value, and the product of a 2×42 \times 4 weight matrix with a 3×53 \times 5 matrix is undefined. A value width of 55, different from dk=3d_k = 3, is no problem.

  1. One query has two allowed keys with scaled scores 00 and ln⁡3\ln 3, and the matching scalar values are 11 and 55. Find the attention weights and the output. What happens if both keys are masked?
Show the answer

The exponentials are e0=1e^0 = 1 and eln⁡3=3e^{\ln 3} = 3, with total 44, so the weights are 1/41/4 and 3/43/4. The output is

14⋅1+34⋅5=4,\tfrac14 \cdot 1 + \tfrac34 \cdot 5 = 4 ,

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 00, 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 1/41/4 and 3/43/4 again and the output 44, as if nothing were masked.

  1. Which entries of the score matrix must a causal mask exclude for a sequence of 44 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 (1,2)(1, 2), (1,3)(1, 3), (1,4)(1, 4), (2,3)(2, 3), (2,4)(2, 4) and (3,4)(3, 4). That is 4⋅3/2=64 \cdot 3 / 2 = 6 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 22 of the example has weights (1,e,e)/(2e+1)≈(0.1554,0.4223,0.4223)(1, e, e)/(2e + 1) \approx (0.1554, 0.4223, 0.4223). Zeroing the third leaves weights that add to

1+e2e+1≈0.5777,\frac{1 + e}{2e + 1} \approx 0.5777 ,

and the output becomes about (0.3107,1.6893)(0.3107, 1.6893) instead of the correct (0.5379,2.9242)(0.5379, 2.9242). Dividing the two remaining weights by their sum restores (1,e)/(1+e)(1, e)/(1 + e), which is exactly the result of masking before the softmax.

How this lesson connects