Linear Algebra — Lecture 11

Lecture 11: Linear Algebra in Transformer Language Models

Shuhong Gao  ·  Clemson University

These notes are interactive: click a section title to open it, click any dotted term to unfold its exact definition or statement in place, click ▸ Proof to expand a proof, and try the exercises — answers are checked instantly.

💡 Intuition

How does a language model turn ๐–ฃ๐—ˆ๐—€๐—Œ ๐—‡๐–พ๐–บ๐—‹ ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ\textsf{Dogs near traffic} into a prediction for the next token? We follow the computation from the embedding table to the final probabilities, starting with the inner products of Remark 9.16. This note is enrichment reading beyond the course; it is not exam material.

Row-vector convention. For any dร—rd\times r matrix AA, the map ๐ฑโ†ฆ๐ฑA\mathbf x\mapsto\mathbf xA takes a row of length dd to a row of length rr. It is linear since (a๐ฑ+b๐ฒ)A=a(๐ฑA)+b(๐ฒA)(a\mathbf x+b\mathbf y)A=a(\mathbf xA)+b(\mathbf yA) for any two such rows and scalars a,ba,b.

11.1  From text to vectors

A tokenizer splits text into tokens and gives the ID of each token in the vocabulary. A token can be a whole word, part of a word, punctuation, or a piece that includes a space. The model uses each ID to look up a row in its embedding table EE. A vocabulary of nn tokens has nn rows. Each row holds dd learned numbers, the coordinates of that token's embedding. To represent a prompt, take one row for each token in the order it appears.

If ๐–ป๐–บ๐—‡๐—„\textsf{bank} has the same ID in ๐—๐—๐–พ ๐—‹๐—‚๐—๐–พ๐—‹ ๐–ป๐–บ๐—‡๐—„\textsf{the river bank} and ๐—๐—๐–พ ๐—Œ๐–บ๐—๐—‚๐—‡๐—€๐—Œ ๐–ป๐–บ๐—‡๐—„\textsf{the savings bank}, both occurrences start with the same embedding. Training adjusts the entries of EE along with the maps that read these vectors. After attention incorporates the surrounding prefix, the two occurrences can have different hidden vectors.

Example 11.1 (A ten-token vocabulary and a three-token prompt)

The table lists all ten tokens our toy model can read or generate. Each ID identifies one row of the embedding table EE. IDtokenrow of EIDtokenrow of E1.(0,0,0,1)6๐–ป๐–บ๐—‹๐—„(1,0,0,1)2๐—‡๐–พ๐–บ๐—‹(0,1,0,0)7๐—Š๐—Ž๐—‚๐–พ๐—๐—…๐—’(0,1,0,1)3๐—‰๐–บ๐—‹๐—„(0,0,1,0)8๐–ฃ๐—ˆ๐—€๐—Œ(1,0,1,0)4๐–ป๐–บ๐—‹๐—„๐—Œ(0,1,1,0)9๐—๐—๐–พ(1,1,0,0)5๐–ผ๐–บ๐—‹๐—Œ(1,1,1,0)10๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ(0,0,โˆ’1,1)\begin{array}{rllcrll} \text{ID}&\text{token}&\text{row of }E &\qquad&\text{ID}&\text{token}&\text{row of }E\\ \hline 1&\textsf{.} &(0,0,0,1) &\qquad& 6&\textsf{bark} &(1,0,0,1)\\ 2&\textsf{near} &(0,1,0,0) &\qquad& 7&\textsf{quietly} &(0,1,0,1)\\ 3&\textsf{park} &(0,0,1,0) &\qquad& 8&\textsf{Dogs} &(1,0,1,0)\\ 4&\textsf{barks} &(0,1,1,0) &\qquad& 9&\textsf{the} &(1,1,0,0)\\ 5&\textsf{cars} &(1,1,1,0) &\qquad&10&\textsf{traffic} &(0,0,-1,1) \end{array} For the prompt below, copy the three indicated rows of EE in reading order. ๐ˆ๐ง๐ฉ๐ฎ๐ญ ๐ฉ๐ซ๐จ๐ฆ๐ฉ๐ญ๐–ฃ๐—ˆ๐—€๐—Œ ๐—‡๐–พ๐–บ๐—‹ ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผToken IDs8,2,10X=(1010010000โˆ’11).\begin{array}{ll} \textbf{Input prompt} & \textsf{Dogs near traffic}\\ \text{Token IDs} & 8,\ 2,\ 10 \end{array} \qquad X=\begin{pmatrix}1&0&1&0\\ 0&1&0&0\\ 0&0&-1&1\end{pmatrix}. Row 3 of XX is the embedding for ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ\textsf{traffic}, ๐ฑ3=(0,0,โˆ’1,1)\mathbf x_3=(0,0,-1,1). We use XX directly in the toy head.

How position enters. Position is a token's place in the prompt. With additive position encoding, the third token receives the position vector for slot 3. If it were (0,1,0,0)(0,1,0,0), the input for ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ\textsf{traffic} would be (0,0,โˆ’1,1)+(0,1,0,0)=(0,1,โˆ’1,1)(0,0,-1,1)+(0,1,0,0)=(0,1,-1,1). Each slot has its own position vector, learned or computed by a fixed formula. Llama 3 uses rotary position embedding (RoPE), rotating queries and keys according to position before taking dot products (Section 11.6).

11.2  Queries, keys, and values

Let Xโˆˆโ„mร—dX\in\mathbb R^{m\times d} be the input to an attention head, with one row ๐ฑi\mathbf x_i for each of the mm token positions. In a deeper layer, XX comes from earlier computations and may already carry information about many positions. The head applies three learned linear maps to every row. Leaving out optional biases, it forms Q=XWQโˆˆโ„mร—dโ€ฒ,WQโˆˆโ„dร—dโ€ฒ,K=XWKโˆˆโ„mร—dโ€ฒ,WKโˆˆโ„dร—dโ€ฒ,V=XWVโˆˆโ„mร—dv,WVโˆˆโ„dร—dv.\begin{align*} Q &= XW_Q \in \mathbb R^{m\times d'}, & W_Q &\in \mathbb R^{d\times d'},\\ K &= XW_K \in \mathbb R^{m\times d'}, & W_K &\in \mathbb R^{d\times d'},\\ V &= XW_V \in \mathbb R^{m\times d_v}, & W_V &\in \mathbb R^{d\times d_v}. \end{align*} At position ii, the three rows are the query ๐ชi=๐ฑiWQ\mathbf q_i=\mathbf x_i W_Q, the key ๐คi=๐ฑiWK\mathbf k_i=\mathbf x_i W_K, and the value ๐ฏi=๐ฑiWV\mathbf v_i=\mathbf x_i W_V. Every query and key has width dโ€ฒd', so we can take the dot (or inner) product of a query with any key in the head. The value ๐ฏi\mathbf v_i can have a different width dvd_v.

How does a query score the keys? For a fixed query ๐ชi\mathbf q_i, the map ๐คโ†ฆ๐ชiโ‹…๐ค\mathbf k\mapsto\mathbf q_i\cdot\mathbf k is a linear functional. Its value ๐ชiโ‹…๐ค=โˆฅ๐ชiโˆฅโˆฅ๐คโˆฅฯ\mathbf q_i\cdot\mathbf k= \|\mathbf q_i\|\,\|\mathbf k\|\,\rho combines the correlation ฯ\rho of Remark 9.13, which measures alignment, with the lengths of the two vectors, in the head's learned coordinates. The query scores each eligible key ๐คj\mathbf k_j by summing over all dโ€ฒd' coordinates: ๐ชiโ‹…๐คj=โˆ‘โ„“=1dโ€ฒqiโ„“kjโ„“\mathbf q_i\cdot\mathbf k_j=\sum_{\ell=1}^{d'}q_{i\ell}k_{j\ell}. For example, dโ€ฒ=128d'=128 in Llama 3 8B. Changing the query changes the coefficients in this sum and can change which key scores highest. The value ๐ฏj\mathbf v_j carries the information contributed by source jj. This is self-attention because all three arrays come from the same sequence.

Example 11.2 (Two queries prefer different keys)

Let dโ€ฒ=dv=2d'=d_v=2 and choose the three maps so that on a row (x1,x2,x3,x4)(x_1,x_2,x_3,x_4) they return (x4,x2),c(2x1,x2),(x3,x2),c=2log2,(x_4,x_2), \qquad c(2x_1,x_2), \qquad (x_3,x_2), \qquad c=\sqrt{2}\log 2, where log\log is the natural logarithm, as everywhere in this note. For example, the columns of WQW_Q select coordinates 4 and 2. The row (0,0,โˆ’1,1)(0,0,-1,1) for ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ\textsf{traffic} gives the query (1,0)(1,0), the key (0,0)(0,0), and the value (โˆ’1,0)(-1,0). The factor cc makes the later softmax easy to compute. The prefix gives position and token๐ชi๐คi/c๐ฏi1๐–ฃ๐—ˆ๐—€๐—Œ(0,0)(2,0)(1,0)2๐—‡๐–พ๐–บ๐—‹(0,1)(0,1)(0,1)3๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ(1,0)(0,0)(โˆ’1,0)\begin{array}{c|c|c|c} \text{position and token} & \mathbf q_i & \mathbf k_i/c & \mathbf v_i\\ \hline 1\quad\textsf{Dogs} &(0,0)&(2,0)&(1,0)\\ 2\quad\textsf{near} &(0,1)&(0,1)&(0,1)\\ 3\quad\textsf{traffic} &(1,0)&(0,0)&(-1,0) \end{array} At ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ\textsf{traffic}, take the dot product of the query ๐ช3=(1,0)\mathbf q_3=(1,0) with each of the three keys. In prompt order the scores are ๐ช3โ‹…๐ค1=(1,0)โ‹…(2c,0)=2c,๐ช3โ‹…๐ค2=(1,0)โ‹…(0,c)=0,๐ช3โ‹…๐ค3=(1,0)โ‹…(0,0)=0.\mathbf q_3\cdot\mathbf k_1=(1,0)\cdot(2c,0)=2c,\qquad \mathbf q_3\cdot\mathbf k_2=(1,0)\cdot(0,c)=0,\qquad \mathbf q_3\cdot\mathbf k_3=(1,0)\cdot(0,0)=0. Since c>0c>0, the maximum is ๐ช3โ‹…๐ค1\mathbf q_3\cdot\mathbf k_1, the score for ๐–ฃ๐—ˆ๐—€๐—Œ\textsf{Dogs}. At ๐—‡๐–พ๐–บ๐—‹\textsf{near}, ๐ช2=(0,1)\mathbf q_2=(0,1) scores the two eligible keys 00 and cc, so ๐—‡๐–พ๐–บ๐—‹\textsf{near} has the highest score. The first value coordinate carries +1+1 for ๐–ฃ๐—ˆ๐—€๐—Œ\textsf{Dogs} and โˆ’1-1 for ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ\textsf{traffic}, the grammatical-number signals assigned to these nouns. The preference for ๐–ฃ๐—ˆ๐—€๐—Œ\textsf{Dogs} is built into the example's matrices.

One matrix product computes all raw scores at once. S=QKTโˆˆโ„mร—m,sij=๐ชiโ‹…๐คj=๐ชi๐คjT.S=QK^T\in\mathbb R^{m\times m}, \qquad s_{ij}=\mathbf q_i\cdot\mathbf k_j=\mathbf q_i\mathbf k_j^T. Transposing KK places each key in a column, so multiplying row ii of QQ by column jj of KTK^T gives their dot product. Reading down column jj compares how different destinations score one source. As in Remark 9.16, this is a table of dot products. Their magnitudes depend on both lengths and angles, since ๐ชโ‹…๐ค=โˆฅ๐ชโˆฅโˆฅ๐คโˆฅcosฮธ\mathbf q\cdot\mathbf k=\|\mathbf q\|\,\|\mathbf k\|\cos\theta for nonzero vectors with angle ฮธ\theta.

11.3  From scores to a contextual update

Scale, mask, and normalize. For full causal attention at position ii, sources are positions 1,โ€ฆ,i1,\ldots,i. After setting gij=sij/dโ€ฒg_{ij}=s_{ij}/\sqrt{d'}, convert the eligible scores to weights by softmax aij={exp(gij)โˆ‘k=1iexp(gik),jโ‰คi,0,j>i.a_{ij}= \begin{cases} \displaystyle\frac{\exp(g_{ij})}{\sum_{k=1}^{i}\exp(g_{ik})}, & j\le i,\\[4pt] 0, & j>i . \end{cases}(11.1) The causal mask excludes future positions from the denominator. Equivalently, set their scaled scores to โˆ’โˆž-\infty before softmax, using exp(โˆ’โˆž)=0\exp(-\infty)=0. When training on a sequence, row ii can then be used to predict token i+1i+1 without reading it. With no mask, the denominator instead sums over all mm positions.

Each row sums to 11 because the eligible numerators sum to the denominator. For eligible j,kj,k, aij/aik=exp(gijโˆ’gik)a_{ij}/a_{ik}=\exp(g_{ij}-g_{ik}). Thus score differences determine weight ratios. Adding a common constant to the eligible scores cancels in the ratios and leaves the row unchanged.

The scaling by 1/dโ€ฒ1/\sqrt{d'} has a variance motivation. In a simplified model where all coordinates of ๐ช\mathbf q and ๐ค\mathbf k are independent, each with mean 00 and variance 11, each product qโ„“kโ„“q_\ell k_\ell has mean 00 and second moment 1โ‹…1=11\cdot 1=1. Independence makes the variances add, giving Var(๐ชโ‹…๐ค)=dโ€ฒ\operatorname{Var}(\mathbf q\cdot\mathbf k)=d'. The scaled score then has variance 11. This motivates the scale used by Vaswani et al. (reference 1). Real trained activations can have different statistics.

Mix the values. Let A=(aij)A=(a_{ij}). The matrix Z=AVZ=AV is the output of the attention head. Its ii-th row ๐ณi\mathbf z_i is the weighted mixture of values delivered to position ii. Z=AVโˆˆโ„mร—dv,๐ณi=โˆ‘j=1iaij๐ฏj.Z=AV\in\mathbb R^{m\times d_v},\qquad \mathbf z_i=\sum_{j=1}^{i}a_{ij}\mathbf v_j. Under the softmax in (11.1), this is a convex combination of eligible value vectors, since the weights are nonnegative and sum to 11. Each coordinate therefore lies between the smallest and largest corresponding eligible value coordinates. For fixed AA, mixing is linear in VV. As a function of XX, the head also computes the weights from XX. Each score is a sum of products of query and key coordinates, and softmax then makes the mixing weights depend nonlinearly on the scores.

Example 11.3 (The complete causal attention calculation)

Using the queries, keys, and values in Example 11.2, compute S2=(log2)(000010200),A=(1001/32/302/31/61/6).\frac{S}{\sqrt{2}}=(\log 2) \begin{pmatrix}0&0&0\\0&1&0\\2&0&0\end{pmatrix}, \qquad A=\begin{pmatrix} 1&0&0\\[2pt] 1/3&2/3&0\\[2pt] 2/3&1/6&1/6 \end{pmatrix}. At position 2, the allowed exponentials are (1,2)(1,2). At position 3 they are (4,1,1)(4,1,1), whose sum is 66. Then V=(1001โˆ’10),Z=AV=(101/32/31/21/6).V=\begin{pmatrix}1&0\\0&1\\-1&0\end{pmatrix}, \qquad Z=AV=\begin{pmatrix}1&0\\[2pt]1/3&2/3\\[2pt]1/2&1/6\end{pmatrix}. The last row contains the plural signal (2/3)(1)+(1/6)(0)+(1/6)(โˆ’1)=1/2(2/3)(1)+(1/6)(0)+(1/6)(-1)=1/2. Changing just the value map could reverse this signal while leaving all attention weights unchanged. To understand what was sent, read both the weights and the values.

11.4  From a head to a language model

Several heads and the residual stream. Suppose there are HH heads, each with value width dvd_v. Head hh produces the head output Zh=AhXWV,hโˆˆโ„mร—dvZ_h=A_h X W_{V,h}\in\mathbb R^{m\times d_v}. Here WV,hโˆˆโ„dร—dvW_{V,h}\in\mathbb R^{d\times d_v} is the learned value matrix used by head hh. Multiplying XX by WV,hW_{V,h} gives its value rows, and its attention matrix AhA_h mixes those rows. To combine the heads, concatenate their outputs side by side and apply a learned output matrix WOโˆˆโ„Hdvร—dW_O\in\mathbb R^{Hd_v\times d}. Writing WO(h)W_O^{(h)} for row block hh of height dvd_v, block multiplication gives [Z1โ‹ฏZH]WO=โˆ‘h=1HZhWO(h)=โˆ‘h=1HAhXWV,hWO(h).[\,Z_1\ \cdots\ Z_H\,]W_O =\sum_{h=1}^{H} Z_h W_O^{(h)} =\sum_{h=1}^{H} A_h X W_{V,h} W_O^{(h)}. Each term is mร—dm\times d. Different heads can use different score tables and write different combinations of features into the same dd coordinates. The output of the attention sublayer is added to the incoming state, called the residual stream.

In one common design, a block normalizes each row before each sublayer. If RR denotes the incoming residual matrix and N1,N2N_1,N_2 are row-wise normalizations, the two residual updates have the form R1=R+Attention(N1(R)),R2=R1+MLP(N2(R1)).R_1=R+\operatorname{Attention}(N_1(R)),\qquad R_2=R_1+\operatorname{MLP}(N_2(R_1)). Attention lets one position draw on other positions. The feed-forward network, or MLP, acts separately on each row using the same weights at all positions. A simple bias-free example is MLP(Y)=ฯ•(YW1)W2\operatorname{MLP}(Y)=\phi(YW_1)W_2, with W1โˆˆโ„dร—fW_1\in\mathbb R^{d\times f} and W2โˆˆโ„fร—dW_2\in\mathbb R^{f\times d} for intermediate width ff. An entrywise activation ฯ•\phi makes the row map nonlinear in general. For example, take scalar weights W1=W2=(1)W_1=W_2=(1) and ฯ•(t)=max(t,0)\phi(t)=\max(t,0). The result sends 11 to 11 and โˆ’1-1 to 00, violating linearity. The gated feed-forward network used in Llama 3 has the form (SiLU(YWg)โŠ™(YWa))Wb,SiLU(t)=t1+eโˆ’t.\bigl(\operatorname{SiLU}(YW_g)\odot (YW_a)\bigr)W_b,\qquad \operatorname{SiLU}(t)=\frac{t}{1+e^{-t}}. Here WgW_g and WaW_a both have size dร—fd\times f, WbW_b has size fร—df\times d, and โŠ™\odot is entrywise multiplication. One projected branch modulates the other before the result is mapped back to width dd.

Readout and next-token probabilities. Let ๐กi\mathbf h_i be the final row at position ii after any final normalization. A learned matrix Uโˆˆโ„dร—nU\in\mathbb R^{d\times n} maps it to vocabulary scores, called logits. Label the columns of UU by the token IDs in the same order as the rows of EE, and let ๐’ฑ\mathcal V be the set of these IDs. โ„“i=๐กiU,pi(t)=exp(โ„“it)โˆ‘uโˆˆ๐’ฑexp(โ„“iu).\boldsymbol\ell_i=\mathbf h_i U,\qquad p_i(t)=\frac{\exp(\ell_{it})}{\sum_{u\in\mathcal V}\exp(\ell_{iu})}. The column labeled tt scores token ID tt, and pip_i is a probability distribution on the vocabulary. In models with tied input and output weights, U=ETU=E^T. In attention, softmax distributes weight across positions in the current prefix. Here it distributes probability across vocabulary IDs. During generation, the last row scores the next token. A decoding rule can sample from the distribution or choose a highest-scoring token. The chosen ID is appended, and the process repeats on the longer prefix until a stopping condition is reached.

Example 11.4 (From the attention output to a prediction)

Continue the toy model with one head. Let WOW_O send (z1,z2)(z_1,z_2) to (z1,z2,0,0)(z_1,z_2,0,0), and omit the MLP and the final normalization. At position 3, the residual addition gives ๐ก3=(0,0,โˆ’1,1)+(1/2,1/6,0,0)=(1/2,1/6,โˆ’1,1).\mathbf h_3=(0,0,-1,1)+(1/2,1/6,0,0)=(1/2,1/6,-1,1). Choose the ๐–ป๐–บ๐—‹๐—„\textsf{bark} column of UU to be a column with first entry 2log22\log 2 and zeros below and the ๐–ป๐–บ๐—‹๐—„๐—Œ\textsf{barks} column to be its negative. Set the other eight columns to zero. The two verb logits are log2\log 2 and โˆ’log2-\log 2. Their exponentials are 22 and 1/21/2 and the denominator is 8+2+1/2=21/28+2+1/2=21/2. Thus p3(๐–ป๐–บ๐—‹๐—„)=421,p3(๐–ป๐–บ๐—‹๐—„๐—Œ)=121.p_3(\textsf{bark})=\frac{4}{21},\qquad p_3(\textsf{barks})=\frac{1}{21}. Each other token has probability 2/212/21. The largest probability is assigned to ๐–ป๐–บ๐—‹๐—„\textsf{bark}, which is four times as likely as ๐–ป๐–บ๐—‹๐—„๐—Œ\textsf{barks}. We can isolate the contribution of ๐–ฃ๐—ˆ๐—€๐—Œ\textsf{Dogs}. In this computation only, replace its first value coordinate +1+1 by 00 and keep all keys and queries fixed. The first coordinate of the last head output falls from 1/21/2 to โˆ’1/6-1/6. The residual at ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ\textsf{traffic} adds zero in that coordinate, so the logit for ๐–ป๐–บ๐—‹๐—„\textsf{bark} becomes โˆ’(log2)/3-(\log 2)/3 and the logit for ๐–ป๐–บ๐—‹๐—„๐—Œ\textsf{barks} becomes (log2)/3(\log 2)/3. The verb preference reverses with exactly the same attention weights. Its direction depends on the information carried by the values and on how the readout uses it.

What happens if we exchange the first two tokens while keeping ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ\textsf{traffic} last? In this one-layer example their keys and values exchange places together. The last query stays fixed, so the same two weighted values appear in reverse order in its sum. The prediction is identical. This exposes a limitation of using this head alone to explain a word-order-sensitive phenomenon such as subject recognition.

How the weights are learned. For a training sequence with IDs t1,โ€ฆ,tmt_1,\ldots,t_m, a standard next-token training loss is โˆ’โˆ‘i=1mโˆ’1logpi(ti+1)-\sum_{i=1}^{m-1}\log p_i(t_{i+1}). Each term rewards assigning higher probability to the observed next token. For example, if the next token after the toy prefix is ๐–ป๐–บ๐—‹๐—„\textsf{bark}, the loss for that prediction is log(21/4)\log(21/4). Fix a position ii and write โ„“=โ„“i=๐กiU\boldsymbol\ell=\boldsymbol\ell_i =\mathbf h_i U for its row vector of logits. Its entry โ„“j\ell_j is the score for vocabulary token jj before softmax. For example, after ๐–ฃ๐—ˆ๐—€๐—Œ ๐—‡๐–พ๐–บ๐—‹ ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ\textsf{Dogs near traffic}, โ„“6=log2\ell_6=\log 2 scores ๐–ป๐–บ๐—‹๐—„\textsf{bark} and โ„“4=โˆ’log2\ell_4=-\log 2 scores ๐–ป๐–บ๐—‹๐—„๐—Œ\textsf{barks}. With target ID t=ti+1t=t_{i+1} and probabilities p(j)=pi(j)p(j)=p_i(j), the loss for this position is L(โ„“)=โˆ’โ„“t+log(โˆ‘uโˆˆ๐’ฑeโ„“u),โˆ‚Lโˆ‚โ„“j=p(j)โˆ’1{j=t}.L(\boldsymbol\ell)=-\ell_t+\log\!\left(\sum_{u\in\mathcal V}e^{\ell_u}\right), \qquad \frac{\partial L}{\partial\ell_j} =p(j)-\mathbf 1_{\{j=t\}}. The derivative follows by differentiating the log of the sum. Here 1{j=t}\mathbf 1_{\{j=t\}} equals 11 for j=tj=t and 00 otherwise. In the toy example, with ๐–ป๐–บ๐—‹๐—„\textsf{bark} as the target, these derivatives are โˆ’17/21-17/21 for the ๐–ป๐–บ๐—‹๐—„\textsf{bark} logit and 1/211/21 for the ๐–ป๐–บ๐—‹๐—„๐—Œ\textsf{barks} logit. If we could change the logits directly, a small gradient descent step would raise the first and lower the second. Backpropagation applies the chain rule through the readout, the layers, and the selected embedding rows. With tied weights the same table also receives gradients through the vocabulary readout. An optimizer uses the gradients to adjust the parameters. In this way, observed next tokens help shape the embeddings and the query, key, and value maps. During ordinary generation the parameters stay fixed, while the hidden vectors and attention weights depend on the input.

11.5  What the linear algebra tells us about a head

The queryโ€“key product, rank, and null spaces. In the bias-free head without query/key rotations, the raw score matrix has the factorization S=XWQKXT,WQK=WQWKTโˆˆโ„dร—d,sij=๐ฑiWQK๐ฑjT.S=XW_{QK}X^T,\qquad W_{QK}=W_QW_K^T\in\mathbb R^{d\times d},\qquad s_{ij}=\mathbf x_i W_{QK}\mathbf x_j^T .(11.2) It follows by substituting Q=XWQQ=XW_Q and KT=WKTXTK^T=W_K^TX^T. This is a bilinear form, linear in either input with the other held fixed. It can represent a directional relation. In Example 11.3, for example, s31=2cs_{31}=2c and s13=0s_{13}=0 before masking. The two products apply different maps to the destination and source.

The map ๐ฑโ†ฆ๐ฑWQK\mathbf x\mapsto\mathbf xW_{QK} factors through the dโ€ฒd' entries of ๐ฑWQ\mathbf xW_Q, so rankWQKโ‰คdโ€ฒ\operatorname{rank}W_{QK}\le d'. Which changes to a source row leave every score unchanged? Adding ๐ฎ\mathbf u to ๐ฑj\mathbf x_j changes the score by ๐ฑiWQK๐ฎT\mathbf x_iW_{QK}\mathbf u^T. This vanishes for every destination row exactly when WQK๐ฎT=0W_{QK}\mathbf u^T=0. By the rank theorem (Theorem 7.9), the space of such source directions has dimension dโˆ’rankWQKd-\operatorname{rank}W_{QK}. For a change ๐ฎ\mathbf u to the destination row, the corresponding condition is ๐ฎWQK=0\mathbf uW_{QK}=0. A direction invisible in a source score can still affect the value sent by that source.

Also, rank(S)โ‰คdโ€ฒ\operatorname{rank}(S)\le d' since every column of QKTQK^T is a combination of the dโ€ฒd' columns of QQ. This bound describes raw scores. In the toy example, SS has rank 22 and the corresponding causal AA is triangular with determinant 1โ‹…(2/3)โ‹…(1/6)=1/91\cdot(2/3)\cdot(1/6)=1/9, so AA has rank 33.

Two ways to factor the same scoring rule. If MM is invertible of size dโ€ฒร—dโ€ฒd'\times d', replacing WQW_Q by WQMW_QM and WKW_K by WK(Mโˆ’1)TW_K(M^{-1})^T preserves the product in (11.2), since the middle factors MM and Mโˆ’1M^{-1} cancel. The query row becomes ๐ชM\mathbf q M and the key row becomes ๐ค(Mโˆ’1)T\mathbf k(M^{-1})^T. For example, doubling all queries and halving all keys leaves every score unchanged. The matching between queries and keys survives this change of coordinates. At the value end, WV,hWO(h)W_{V,h}W_O^{(h)} likewise gives the linear map from source features to the head's contribution in the residual stream, before weighting by AhA_h.

The compact SVD (Corollary 10.26) gives an orthogonal way to read the score. If r=rankWQKr=\operatorname{rank}W_{QK} and we write the left and right singular directions as unit rows ๐ฎa\mathbf u_a and ๐ฐa\mathbf w_a, the SVD gives WQK=โˆ‘a=1rฯƒa๐ฎaT๐ฐaW_{QK}=\sum_{a=1}^r\sigma_a\mathbf u_a^T\mathbf w_a. Hence sij=โˆ‘a=1rฯƒa(๐ฑiโ‹…๐ฎa)(๐ฑjโ‹…๐ฐa).s_{ij}=\sum_{a=1}^r \sigma_a(\mathbf x_i\cdot\mathbf u_a)(\mathbf x_j\cdot\mathbf w_a). This follows by substituting the rank-one sum into (11.2). Each term pairs one destination direction with one source direction. Its sign depends on the two components. The SVD identifies directional pairings and their strengths. Assigning a linguistic meaning to a direction requires evidence about which inputs activate it and how its output is used.

Let ๐ža\mathbf e_a denote the row with a single 11 in coordinate aa and zeros elsewhere. In Example 11.2, the product is c(2๐ž4T๐ž1+๐ž2T๐ž2)c(2\mathbf e_4^T\mathbf e_1+\mathbf e_2^T\mathbf e_2). The two left vectors and the two right vectors each form an orthonormal set, so this is already a compact SVD with singular values 2c2c and cc. The first term pairs destination coordinate 4 with source coordinate 1. The second pairs coordinate 2 with coordinate 2. The source null space is Span(๐ž3,๐ž4)\operatorname{Span}(\mathbf e_3,\mathbf e_4), since the two destination directions ๐ž4\mathbf e_4 and ๐ž2\mathbf e_2 are independent. Source coordinate 3 supplies the number signal assigned to the two nouns in this example and contributes zero to scoring as a key.

11.6  Position, normalization, and efficient attention

Position as a rotation. Position has the same meaning as in Section 11.1. In ๐–ฃ๐—ˆ๐—€๐—Œ ๐—‡๐–พ๐–บ๐—‹ ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ\textsf{Dogs near traffic}, a query from ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ\textsf{traffic} has token position i=3i=3 and a key from ๐–ฃ๐—ˆ๐—€๐—Œ\textsf{Dogs} has token position j=1j=1. The key is iโˆ’j=2i-j=2 tokens back. Additive encoding uses the token position to select a vector to add to the embedding. Rotary position embedding (RoPE, reference 5) uses that same position to set rotation angles inside the query and key. For a row (a,b)(a,b), right multiplication by the 2ร—22\times2 matrix D(ฮฑ)=(cosฮฑsinฮฑโˆ’sinฮฑcosฮฑ)D(\alpha)=\begin{pmatrix} \cos\alpha&\sin\alpha\\ -\sin\alpha&\cos\alpha \end{pmatrix} rotates that pair counterclockwise through angle ฮฑ\alpha. Write the query at token position ii as ๐ชi=(qi,1,qi,2,โ€ฆ,qi,dโ€ฒ)\mathbf q_i=(q_{i,1},q_{i,2},\ldots,q_{i,d'}). The first index identifies the token position and the second identifies a coordinate within that query. For the first rotation block, take ๐ฎ=(qi,1,qi,2)\mathbf u=(q_{i,1},q_{i,2}) from this single query and ๐ฏ=(kj,1,kj,2)\mathbf v=(k_{j,1},k_{j,2}) from the key at position jj, ordering coordinates by rotation block. Use the same angle step ฮธ\theta for both pairs. Since D(ฮฒ)T=D(โˆ’ฮฒ)D(\beta)^T=D(-\beta) and rotations in the plane add angles, (๐ฎD(iฮธ))(๐ฏD(jฮธ))T=๐ฎD((iโˆ’j)ฮธ)๐ฏT.(\mathbf uD(i\theta))(\mathbf vD(j\theta))^T =\mathbf uD((i-j)\theta)\mathbf v^T. For example, if ๐ฎ=๐ฏ=(1,0)\mathbf u=\mathbf v=(1,0) and ฮธ=ฯ€/2\theta=\pi/2, this pair contributes 11 at equal positions, 00 one step back, and โˆ’1-1 two steps back.

Now take full query and key rows of even width dโ€ฒ=2rd'=2r. Group their coordinates into rr matching pairs and give pair aa its own angle step ฮธa\theta_a. Thus ii counts tokens along the prompt, and aa counts coordinate pairs within one token's vector. The full rotation at position ii is the dโ€ฒร—dโ€ฒd'\times d' block diagonal matrix R(i)=diag(D(iฮธ1),โ€ฆ,D(iฮธr)).R(i)=\operatorname{diag}\bigl(D(i\theta_1),\ldots,D(i\theta_r)\bigr). For dโ€ฒ=128d'=128, for example, there are 6464 two-dimensional blocks. The full query and key become ๐ชiR(i)\mathbf q_iR(i) and ๐คjR(j)\mathbf k_jR(j). Their dot product adds the contributions from all rr pairs. Applying the two-dimensional identity block by block gives R(i)R(j)T=R(iโˆ’j)R(i)R(j)^T=R(i-j), so the full raw score is (๐ชiR(i))(๐คjR(j))T=๐ชiR(iโˆ’j)๐คjT.(\mathbf q_iR(i))(\mathbf k_jR(j))^T =\mathbf q_i R(i-j)\mathbf k_j^T. Thus the effective bilinear matrix is WQR(iโˆ’j)WKTW_QR(i-j)W_K^T. It can vary with the relative position iโˆ’ji-j, so the fixed WQKW_{QK} in (11.2) describes the unrotated case. The raw score table still has rank at most dโ€ฒd' because it is the product of the rotated query matrix and the transpose of the rotated key matrix. The arbitrary change of coordinates above need not preserve these rotated scores, since MR(iโˆ’j)Mโˆ’1MR(i-j)M^{-1} can differ from R(iโˆ’j)R(i-j).

Normalization and orthogonal projection. LayerNorm first centers a row ๐ฑ\mathbf x by subtracting its mean from every entry. In matrix form the centered row is ๐ฑC\mathbf x C, where C=Idโˆ’1T1/dC=I_d-\mathbf 1^T\mathbf 1/d and 1=(1,โ€ฆ,1)\mathbf 1=(1,\ldots,1) has length dd. Since ๐ฑC\mathbf xC has entry sum 00 and ๐ฑโˆ’๐ฑC\mathbf x-\mathbf xC is a multiple of 1\mathbf 1, Theorem 9.29 shows that ๐ฑC\mathbf xC is the orthogonal projection onto 1โŠฅ\mathbf 1^\perp. LayerNorm then divides by โˆฅ๐ฑCโˆฅ2/d+ฮต\sqrt{\|\mathbf x C\|^2/d+\varepsilon} and typically applies learned coordinate-wise gains and offsets. The centering is linear. The division depends on the input and is nonlinear.

RMSNorm (reference 6) skips centering. Before the learned coordinate-wise gains it computes ๐ฑ/โˆฅ๐ฑโˆฅ2/d+ฮต\mathbf x/\sqrt{\|\mathbf x\|^2/d+\varepsilon}. For ๐ฑ=(1,3)\mathbf x=(1,3), the LayerNorm centering gives (โˆ’1,1)(-1,1) and the RMSNorm numerator is (1,3)(1,3). In the limit ฮตโ†’0+\varepsilon\to0^+ and before learned gains and offsets, the respective results are (โˆ’1,1)(-1,1) and (1,3)/5(1,3)/\sqrt5. The stabilizer ฮต>0\varepsilon>0 keeps the denominator positive, even when the numerator is zero.

Grouped-query attention and the keyโ€“value cache. In deterministic inference with the row-wise blocks above, a prefix keeps its hidden states when another token is appended, provided earlier position encodings and mask entries stay fixed. To see this, start with the unchanged input embeddings of the prefix. In each block an old row reads only old rows, and its normalization, MLP, and residual update take the same inputs as before. Inducting over the blocks shows that the keys and values for those positions can be saved in a KV cache. The new position computes its own query and compares it to the permitted stored keys and its new key. It then mixes the corresponding values.

In grouped-query attention (GQA), several query heads share one pair of key and value arrays. Their distinct query matrices can still produce distinct weight rows. For example, Meta's Llama 3 8B has width 40964096, 3232 query heads, and 88 keyโ€“value heads (reference 7, Table 3). Each head has width 4096/32=1284096/32=128, so one query head uses a 4096ร—1284096\times128 query matrix. Four query heads share each keyโ€“value head. For a prefix of mm tokens, the cache holds 2mโ‹…8โ‹…1282m\cdot8\cdot128 scalars per layer, one array each for keys and values. This is one quarter of the cache for 3232 independent keyโ€“value heads of the same width.

11.7  What public descriptions say about major models

The calculations above describe a reference text decoder. Published systems use this mathematical pattern with model-specific choices about which rows are visible, which heads share weights, and how each row's features are transformed.

  • OpenAI and ChatGPT. GPT-4 was first offered to ChatGPT Plus subscribers, in March 2023. OpenAI's technical report describes it as Transformer-style and pretrained to predict the next token. The report withholds detailed architecture specifications, including model size. OpenAI's separately released gpt-oss models give inspectable examples. Their model card documents grouped-query attention, rotary embeddings, and alternating local-window and full causal attention. Each head also has a learned scalar bb. If the eligible token scores have total exponential weight T=โˆ‘jegijT=\sum_j e^{g_{ij}}, the implementation divides each egije^{g_{ij}} by T+ebT+e^b. The token weights sum to T/(T+eb)<1T/(T+e^b)<1. The remaining weight can be assigned to a zero value, so the convex hull for this mixture includes the origin. In the feed-forward block, an affine map of each normalized token row scores the experts. Softmax over the four largest scores weights their outputs. (References 8โ€“10.)
  • Anthropic and Claude. Anthropic's public study of Claude 3.5 Haiku examined a prompt asking for the capital of the state containing Dallas. The model answered Austin. Feature interventions supported a pathway through features associated with Texas. In constructing the attribution graph, the authors held the prompt's attention weights fixed. This lets them trace what information travels along a weighted connection while leaving open how the queries and keys produced that weight. Anthropic's earlier work develops the queryโ€“key and outputโ€“value factorization used here. (References 2โ€“3.)
  • Meta and Llama. The Llama 3 report gives a concrete architecture with grouped-query attention, RoPE, and a gated feed-forward activation called SwiGLU. It specifies dimensions and head counts, so the matrix shapes in the preceding sections can be compared with those of a trained model. (Reference 7, Section 3.2.)

11.8  Practice problems

Exercise 11.1 auto-check

In Example 11.3, suppose the scaled score of ๐—๐—‹๐–บ๐–ฟ๐–ฟ๐—‚๐–ผ\textsf{traffic} against ๐–ฃ๐—ˆ๐—€๐—Œ\textsf{Dogs} increases from 2log22\log 2 to 3log23\log 2, with the other scores and values held fixed. What is the new first coordinate of ๐ณ3\mathbf z_3?

Answer:
Exercise 11.2 auto-check

In the toy head, increase only coordinate 3 of the input at ๐–ฃ๐—ˆ๐—€๐—Œ\textsf{Dogs} by 11. What changes at position 3?

Exercise 11.3 auto-check

A bias-free head without query/key rotations has d=4096d=4096 and dโ€ฒ=128d'=128. What is the smallest possible dimension of Nul(WQK)\operatorname{Nul}(W_{QK})?

Answer:

11.9  References and further reading

  1. A. Vaswani et al. (2017). Scaled dot-product attention, multi-head attention, and the original Transformer. Attention Is All You Need (arxiv.org/abs/1706.03762).
  2. N. Elhage et al., Anthropic (2021). Queryโ€“key and outputโ€“value products and the residual stream. A Mathematical Framework for Transformer Circuits (transformer-circuits.pub/2021/framework/index.html).
  3. J. Lindsey et al., Anthropic (2025). Circuit-tracing experiments on Claude 3.5 Haiku. On the Biology of a Large Language Model (transformer-circuits.pub/2025/attribution-graphs/biology.html) and the companion methods paper (transformer-circuits.pub/2025/attribution-graphs/methods.html).
  4. M. Phuong and M. Hutter (2022). Algorithms with explicit matrix operations and dimensions. Formal Algorithms for Transformers (arxiv.org/abs/2207.09238).
  5. J. Su et al. (2024). Rotary position embedding. RoFormer (arxiv.org/abs/2104.09864).
  6. B. Zhang and R. Sennrich (2019). Root Mean Square Layer Normalization (arxiv.org/abs/1910.07467).
  7. A. Grattafiori et al., Meta (2024). Architecture in Section 3.2 and Table 3. The Llama 3 Herd of Models (arxiv.org/html/2407.21783).
  8. OpenAI (2023). GPT-4 release and availability in ChatGPT Plus. GPT-4 (openai.com/index/gpt-4/).
  9. OpenAI (2023). Pretraining objective and scope of disclosure in Section 2. GPT-4 Technical Report (arxiv.org/abs/2303.08774).
  10. OpenAI (2025). Architecture in Section 2.2 and public weights. gpt-oss-120b and gpt-oss-20b Model Card (arxiv.org/abs/2508.10925) and reference implementation (github.com/openai/gpt-oss).

Index of statements