Lecture 11: Linear Algebra in Transformer Language Models
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.
How does a language model turn 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 matrix , the map takes a row of length to a row of length . It is linear since for any two such rows and scalars .
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 . A vocabulary of tokens has rows. Each row holds 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 has the same ID in and , both occurrences start with the same embedding. Training adjusts the entries of along with the maps that read these vectors. After attention incorporates the surrounding prefix, the two occurrences can have different hidden vectors.
The table lists all ten tokens our toy model can read or generate. Each ID identifies one row of the embedding table . For the prompt below, copy the three indicated rows of in reading order. Row 3 of is the embedding for , . We use 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 , the input for would be . 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 be the input to an attention head, with one row for each of the token positions. In a deeper layer, 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 At position , the three rows are the query , the key , and the value . Every query and key has width , so we can take the dot (or inner) product of a query with any key in the head. The value can have a different width .
How does a query score the keys? For a fixed query , the map is a linear functional. Its value combines the correlation 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 by summing over all coordinates: . For example, in Llama 3 8B. Changing the query changes the coefficients in this sum and can change which key scores highest. The value carries the information contributed by source . This is self-attention because all three arrays come from the same sequence.
Let and choose the three maps so that on a row they return where is the natural logarithm, as everywhere in this note. For example, the columns of select coordinates 4 and 2. The row for gives the query , the key , and the value . The factor makes the later softmax easy to compute. The prefix gives At , take the dot product of the query with each of the three keys. In prompt order the scores are Since , the maximum is , the score for . At , scores the two eligible keys and , so has the highest score. The first value coordinate carries for and for , the grammatical-number signals assigned to these nouns. The preference for is built into the example's matrices.
One matrix product computes all raw scores at once. Transposing places each key in a column, so multiplying row of by column of gives their dot product. Reading down column 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 for nonzero vectors with angle .
11.3 From scores to a contextual update
Scale, mask, and normalize. For full causal attention at position , sources are positions . After setting , convert the eligible scores to weights by softmax (11.1) The causal mask excludes future positions from the denominator. Equivalently, set their scaled scores to before softmax, using . When training on a sequence, row can then be used to predict token without reading it. With no mask, the denominator instead sums over all positions.
Each row sums to because the eligible numerators sum to the denominator. For eligible , . 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 has a variance motivation. In a simplified model where all coordinates of and are independent, each with mean and variance , each product has mean and second moment . Independence makes the variances add, giving . The scaled score then has variance . This motivates the scale used by Vaswani et al. (reference 1). Real trained activations can have different statistics.
Mix the values. Let . The matrix is the output of the attention head. Its -th row is the weighted mixture of values delivered to position . Under the softmax in (11.1), this is a convex combination of eligible value vectors, since the weights are nonnegative and sum to . Each coordinate therefore lies between the smallest and largest corresponding eligible value coordinates. For fixed , mixing is linear in . As a function of , the head also computes the weights from . Each score is a sum of products of query and key coordinates, and softmax then makes the mixing weights depend nonlinearly on the scores.
Using the queries, keys, and values in Example 11.2, compute At position 2, the allowed exponentials are . At position 3 they are , whose sum is . Then The last row contains the plural signal . 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 heads, each with value width . Head produces the head output . Here is the learned value matrix used by head . Multiplying by gives its value rows, and its attention matrix mixes those rows. To combine the heads, concatenate their outputs side by side and apply a learned output matrix . Writing for row block of height , block multiplication gives Each term is . Different heads can use different score tables and write different combinations of features into the same 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 denotes the incoming residual matrix and are row-wise normalizations, the two residual updates have the form 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 , with and for intermediate width . An entrywise activation makes the row map nonlinear in general. For example, take scalar weights and . The result sends to and to , violating linearity. The gated feed-forward network used in Llama 3 has the form Here and both have size , has size , and is entrywise multiplication. One projected branch modulates the other before the result is mapped back to width .
Readout and next-token probabilities. Let be the final row at position after any final normalization. A learned matrix maps it to vocabulary scores, called logits. Label the columns of by the token IDs in the same order as the rows of , and let be the set of these IDs. The column labeled scores token ID , and is a probability distribution on the vocabulary. In models with tied input and output weights, . 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.
Continue the toy model with one head. Let send to , and omit the MLP and the final normalization. At position 3, the residual addition gives Choose the column of to be a column with first entry and zeros below and the column to be its negative. Set the other eight columns to zero. The two verb logits are and . Their exponentials are and and the denominator is . Thus Each other token has probability . The largest probability is assigned to , which is four times as likely as . We can isolate the contribution of . In this computation only, replace its first value coordinate by and keep all keys and queries fixed. The first coordinate of the last head output falls from to . The residual at adds zero in that coordinate, so the logit for becomes and the logit for becomes . 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 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 , a standard next-token training loss is . Each term rewards assigning higher probability to the observed next token. For example, if the next token after the toy prefix is , the loss for that prediction is . Fix a position and write for its row vector of logits. Its entry is the score for vocabulary token before softmax. For example, after , scores and scores . With target ID and probabilities , the loss for this position is The derivative follows by differentiating the log of the sum. Here equals for and otherwise. In the toy example, with as the target, these derivatives are for the logit and for the 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 (11.2) It follows by substituting and . 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, and before masking. The two products apply different maps to the destination and source.
The map factors through the entries of , so . Which changes to a source row leave every score unchanged? Adding to changes the score by . This vanishes for every destination row exactly when . By the rank theorem (Theorem 7.9), the space of such source directions has dimension . For a change to the destination row, the corresponding condition is . A direction invisible in a source score can still affect the value sent by that source.
Also, since every column of is a combination of the columns of . This bound describes raw scores. In the toy example, has rank and the corresponding causal is triangular with determinant , so has rank .
Two ways to factor the same scoring rule. If is invertible of size , replacing by and by preserves the product in (11.2), since the middle factors and cancel. The query row becomes and the key row becomes . 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, likewise gives the linear map from source features to the head's contribution in the residual stream, before weighting by .
The compact SVD (Corollary 10.26) gives an orthogonal way to read the score. If and we write the left and right singular directions as unit rows and , the SVD gives . Hence 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 denote the row with a single in coordinate and zeros elsewhere. In Example 11.2, the product is . The two left vectors and the two right vectors each form an orthonormal set, so this is already a compact SVD with singular values and . The first term pairs destination coordinate 4 with source coordinate 1. The second pairs coordinate 2 with coordinate 2. The source null space is , since the two destination directions and 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 , a query from has token position and a key from has token position . The key is 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 , right multiplication by the matrix rotates that pair counterclockwise through angle . Write the query at token position as . The first index identifies the token position and the second identifies a coordinate within that query. For the first rotation block, take from this single query and from the key at position , ordering coordinates by rotation block. Use the same angle step for both pairs. Since and rotations in the plane add angles, For example, if and , this pair contributes at equal positions, one step back, and two steps back.
Now take full query and key rows of even width . Group their coordinates into matching pairs and give pair its own angle step . Thus counts tokens along the prompt, and counts coordinate pairs within one token's vector. The full rotation at position is the block diagonal matrix For , for example, there are two-dimensional blocks. The full query and key become and . Their dot product adds the contributions from all pairs. Applying the two-dimensional identity block by block gives , so the full raw score is Thus the effective bilinear matrix is . It can vary with the relative position , so the fixed in (11.2) describes the unrotated case. The raw score table still has rank at most 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 can differ from .
Normalization and orthogonal projection. LayerNorm first centers a row by subtracting its mean from every entry. In matrix form the centered row is , where and has length . Since has entry sum and is a multiple of , Theorem 9.29 shows that is the orthogonal projection onto . LayerNorm then divides by 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 . For , the LayerNorm centering gives and the RMSNorm numerator is . In the limit and before learned gains and offsets, the respective results are and . The stabilizer 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 , query heads, and keyโvalue heads (reference 7, Table 3). Each head has width , so one query head uses a query matrix. Four query heads share each keyโvalue head. For a prefix of tokens, the cache holds scalars per layer, one array each for keys and values. This is one quarter of the cache for 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 . If the eligible token scores have total exponential weight , the implementation divides each by . The token weights sum to . 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
In Example 11.3, suppose the scaled score of against increases from to , with the other scores and values held fixed. What is the new first coordinate of ?
The last row's exponentials become , giving the first coordinate .
In the toy head, increase only coordinate 3 of the input at by . What changes at position 3?
Read the three maps in Example 11.2. Only reads coordinate 3, so the first coordinate of increases by .
A bias-free head without query/key rotations has and . What is the smallest possible dimension of ?
Use the rank theorem. To attain the bound, both factors can select the first coordinates.
11.9 References and further reading
- 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).
- 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).
- 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).
- M. Phuong and M. Hutter (2022). Algorithms with explicit matrix operations and dimensions. Formal Algorithms for Transformers (arxiv.org/abs/2207.09238).
- J. Su et al. (2024). Rotary position embedding. RoFormer (arxiv.org/abs/2104.09864).
- B. Zhang and R. Sennrich (2019). Root Mean Square Layer Normalization (arxiv.org/abs/1910.07467).
- 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).
- OpenAI (2023). GPT-4 release and availability in ChatGPT Plus. GPT-4 (openai.com/index/gpt-4/).
- OpenAI (2023). Pretraining objective and scope of disclosure in Section 2. GPT-4 Technical Report (arxiv.org/abs/2303.08774).
- 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).