Open the code of a modern language model and look for the linear algebra you have just learned. You will not find anything new. There is a lookup in a table of vectors, a few matrix products, a softmax, an addition, a division by a spread, and the same again, many times over. This lesson is a map: it takes the fourteen lessons of this module and shows where each one lives inside a neural network, with small numbers you can follow by hand. It teaches no new technique. Every section points to the later lesson that teaches that part properly.
The whole map
Below is one block of a transformer-style network, cut into ten steps. The steps are the ones this lesson works through. Pick a step to see what it does, the shape of each array for sizes you choose, the linear algebra it uses (with links to the lessons) and the later lesson that covers it.
Things to try:
- Select Q, K, V projections and then Scores. Change from 3 to 16 and watch the scores array. Its entry count grows with , and that square is why long inputs are costly (P7.12).
- Raise from 1 to 4 and look at Q, K, V projections again. The shape of the weights does not change: heads cut the same numbers into pieces. Only shrinks.
- Select Residual add. All three arrays have the same shape. That is the condition for adding them.
- Select Dense layer and change . With the hidden width it has about learned numbers, so it grows with the square of , while the embedding table and the output layer grow only in proportion to (they are still bigger here, because the made-up vocabulary has entries).
- Press the example button, which sets , , , . These are the sizes of the hand-worked example in this lesson.
The sections below work through the steps that matter most, in the order of the map. A word on notation first. This lesson writes a dense layer as with the weight matrix of shape (outputs, inputs), the way P1.B5 does. Papers on attention usually store the weights already transposed, with shape (inputs, outputs), and write with no transpose. It is the same operation. When you read code or a paper, check the shape of the weight first.
1. A dense layer:
A dense layer (also called a fully connected or linear layer) turns a vector of numbers into a vector of numbers. P1.B5 gave the matrix, P1.B3 gave the dot product behind each output. Take
The matrix has 2 rows and 3 columns, so it turns 3 numbers into 2. Each row is one neuron’s weight vector, and each output is one dot product plus the neuron’s bias. The first output is and the second is , so:
On a batch. Real data comes in batches. Stack the examples as the rows of (P1.B5) and the layer becomes one product (P1.B6). Take the two examples and :
and then the bias is added to every row. The shapes are and , so the product is , and the bias has shape . Broadcasting (P1.B14) stretches it down the rows:
The first row is the single-example answer . In general .
Counting the learned numbers. The layer above has weights and biases: numbers. A layer from inputs to outputs has . A layer from 784 inputs (a image, P1.B1) to 128 outputs has .
- Tools: the matrix as a map (P1.B5), matrix products (P1.B6), broadcasting (P1.B14).
- Taught later: the neuron and the layer (P4.1), the forward pass in matrix form (P4.5).
2. Why a nonlinearity sits between layers
P1.B6 showed that two layers in a row multiply their matrices. With , and :
Two layers with nothing between them are one layer, and so are ten. Put on each entry between them (P4.4): , and . That is not , so the single matrix can no longer stand in for the network.
In the map, the nonlinearity sits inside the dense layer (step 9), between its two matrices. Attention has a nonlinearity of its own: the softmax makes the weights depend on the input in a way no single matrix can copy.
- Tools: matrix composition (P1.B6).
- Taught later: multi-layer perceptrons (P4.3), activation functions (P4.4).
3. The backward pass uses
Training needs the gradient of a loss with respect to every learned number. P1.B10 showed that the gradient travels backward through by way of . Use the layer of section 1, with , so that . Suppose the loss is . This is a made-up loss, chosen so that the gradient arriving at is easy to see: . Then
Check the first one by nudging. Raise from to . The first column of is , so becomes and , down from . The change is , which is what predicts.
Each gradient has the shape of the thing it belongs to: has the shape of , and has the shape of , namely . That rule is a quick way to catch a missing transpose.
On a batch. Let the gradients arriving for the two examples be the rows of , shape . Then , the sum over examples of , again one matrix product:
The gradient for the inputs is , with rows and , and the gradient of the bias is the column sums of , .
Many layers. A gradient that passes through many layers is multiplied by many transposed matrices (and by the slopes of the nonlinearities). Take the matrix of P1.B12, whose eigenvalues are and , and start from . One multiplication gives , two give , three give , and ten give : the length grows by about a factor of per step. (This simple chain has no nonlinearity. It is the idea behind exploding and vanishing gradients, not a model of a real network.)
- Tools: the transpose and its dot-product rule (P1.B10), eigenvalues of repeated products (P1.B12).
- Taught later: backpropagation by hand (P4.8), matrix calculus (P1.C11), exploding and vanishing gradients (P4.16), initialisation (P4.12).
4. Embeddings: a lookup that is a matrix product
A model cannot multiply with a word, so every token gets a vector. The vectors are stored as the rows of a table, the embedding matrix (P1.B5), with one row per entry of the vocabulary. Make a toy vocabulary of four tokens, numbered to , with vectors of numbers (made-up values, not trained):
The token “cat” is number 1. Its one-hot vector has a 1 in place 1 and zeros elsewhere, and a product with picks out row 1 (P1.B6 reads a product as a mix of rows, with the one-hot vector as the mixing weights):
For the two tokens “cat sat”, numbers and , stack the one-hot vectors as rows and multiply:
That is rows 1 and 2 of . So a lookup is a matrix product. Real code does not build the one-hot matrix: it indexes the table, which gives the same answer without multiplying numbers by zero for every token (here is the vocabulary size). Knowing the two are equal explains how gradients behave: the lookup sends a gradient only to the rows that were used (other parts of a model, such as an output layer that reuses the table, can still reach the other rows).
Similarity between tokens is the dot product or the cosine of their vectors (P1.B3). In the toy table, , and . Trained tables are not like this toy: they have hundreds or thousands of numbers per row, and their similarities come from training data.
- Tools: a matrix as a table of rows (P1.B5), a product as a mix of rows (P1.B6), dot product and cosine (P1.B3).
- Taught later: embedding layers (P4.21), word embeddings (P6.3).
5. Attention: matrix products and one softmax
Attention lets every token collect information from the others. In the map it is steps 3 to 6: matrix products, with one softmax between them. Use the three tokens “the cat sat”. Their vectors are rows 0, 1 and 2 of the table above:
Three small matrices, which a real model would learn, turn each token vector into a query (what it looks for), a key (what it offers) and a value (what it passes on). These are made-up numbers:
Projections (shapes ).
Scores (shapes ). Entry is the dot product of the query of token with the key of token (P1.B3, P1.B10):
The scores are divided by (P7.4 explains why). To two decimals the result is
Softmax along each row. The softmax turns a row of scores into positive weights that add up to 1. Rounded to two decimals (the exact values have more digits), the weights are
Row says how much token listens to each token. The token “cat” (the second row, row 1 counting from 0) puts of its attention on itself. Each row adds to 1 up to rounding.
Weighted sum of values (shapes ). The first row is
Each output row is a linear combination of the rows of (P1.B2), with that token’s weights as the coefficients. All three rows, rounded:
The output has the same shape as the input , , and that is what lets the layers stack.
This toy leaves out several things that real models have: position information (P7.6), a mask that stops a token looking at later tokens (P7.8), and often more than one head.
A batch with heads. With sequences of tokens, has shape and the matrix products are batched (P1.B14). The numbers of each query, key and value are cut into heads of numbers (in the original transformer, and gave ). The shapes then run as
and the heads are put side by side again to give , followed by one more matrix of shape . The softmax runs over the last axis, so each row of weights sums to 1. The score array has entries, which grows with the square of the sequence length. The number of weights in , and does not depend on : more heads cut the same numbers into more, smaller pieces.
- Tools: matrix products (P1.B6), dot product (P1.B3), the transpose (P1.B10), linear combinations (P1.B2), reshape, axes and batched products (P1.B14).
- Taught later: queries, keys and values (P7.3), scaled attention (P7.4), multiple heads (P7.5), position (P7.6, P7.14), masking (P7.8).
6. Residual connections and normalisation
Residual. Many layers do not replace their input; they add something to it: . For the first token, and the attention output is , so the sum is (P1.B2). The addition needs both arrays to have the same shape. Putting the heads side by side already gives again (when , as usual), and of shape then mixes the heads without changing the shape. The backward pass benefits too: the derivative of with respect to includes the identity, so a gradient has a direct path back (P4.20).
Normalisation. Layer normalisation rescales each token’s vector. Take . Its mean is , the deviations from the mean are , and the standard deviation (the square root of the average squared deviation) is . Dividing the deviations by it gives
This vector has length : the squares are (P1.B4; real layers add a tiny constant to avoid dividing by zero and then apply a learned scale and shift). On an array of shape the mean is taken over the last axis with keepdims, giving shape (P1.B14), so every token is handled on its own. Other normalisation layers differ in which axes they average over, and in what they subtract.
- Tools: vector addition (P1.B2), norms (P1.B4), reductions over an axis (P1.B14).
- Taught later: residual connections (P4.20), normalisation layers (P4.19), how they fit together in one block (P7.7).
Which tool lives where
One line for each lesson of this module.
- P1.B1 Scalars, vectors and spaces. A token embedding, a row of weights and a data example are all vectors.
- P1.B2 Vector operations. Residual add, the gradient-descent step, and attention’s weighted sum (a linear combination).
- P1.B3 The dot product. One neuron’s output, every attention score, cosine similarity of embeddings.
- P1.B4 Norms and distances. Normalisation layers, weight decay, gradient clipping, nearest-neighbour search.
- P1.B5 Matrices as data and transformations. The data matrix, the weights of a layer, the embedding table.
- P1.B6 Matrix multiplication. A layer on a batch, stacked layers, , the product of two thin matrices in LoRA.
- P1.B7 Span, independence and rank. What a layer with a narrow middle can produce; the rank of a low-rank update.
- P1.B8 The determinant. How a map scales volume; needed by normalising flows (P8.6), not by the block in the map.
- P1.B9 Inverse and linear systems. Solving for the best weights of linear regression (P3.A2); also not in the block.
- P1.B10 Transpose, symmetric and orthogonal matrices. The backward pass, in the scores, rotations in RoPE (P7.14), orthogonal initialisation (P4.12).
- P1.B11 Projections and least squares. Linear regression (P3.A2) and PCA (P3.C3).
- P1.B12 Eigenvalues and eigenvectors. Why repeated products explode or fade, and PCA (P3.C3).
- P1.B13 The singular value decomposition. Low-rank approximation, LoRA (P10.E3), PCA and compression.
- P1.B14 Tensors, shapes and broadcasting. The and shapes, the bias broadcast, the axis a softmax or a normalisation runs over.
Two of these, the determinant and the inverse, do not appear in the block of this map. They matter elsewhere: in fitting linear models (P3.A2) and in models that must be able to undo their steps (P8.6).
Go deeper A convolution is a sparse matrix with shared weights
A convolutional layer (P5.2) slides a small kernel over its input, taking a dot product at each position. That is also a matrix product, with a special matrix. Take the input and the kernel . At each position, the output is the entry minus the next entry: . As a matrix:
Each row is the kernel, shifted one place to the right. Most entries are zero, and the two numbers that are not zero are the same in every row. So the layer has 2 learned numbers instead of . Deep-learning libraries compute this slide-and-multiply without flipping the kernel (which makes it, strictly, a cross-correlation); P5.2 explains the detail. Libraries usually do not build this matrix. They slide the kernel, which takes far less memory.
Go deeper Low rank: why LoRA stores two thin matrices
Fine-tuning a weight matrix of shape means learning a change of the same shape, which is numbers. LoRA (Hu et al., 2021) keeps the weights frozen and learns the change as a product of two thin matrices of shapes and (P1.B13). For and that is numbers instead of . A product of thin matrices has rank at most (P1.B7), so LoRA bets that the useful change is close to low rank. The layer is computed as , with shapes , so the large product is never formed. The paper applied the method mainly to attention weight matrices such as and . P10.E3 covers the method.
Try it in NumPy
This cell reproduces the numbers of the lesson: the dense layer on a batch, the collapse of two layers, the backward pass, the lookup as a product, the attention example, normalisation, and the shapes for a batch with heads.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
What to expect: the dense layer prints for one example and for the batch, with learned numbers. The two layers give both ways, and with the ReLU. The gradients are for and the matrices of section 3. The lookup prints twice. The attention scores are , the weights are the rounded matrix of section 5 with row sums , and the output rows are , and (printed to two decimals, so appears as ). The normalised vector is with squared length . The last line prints (2, 2, 3, 4) and (2, 2, 3, 3).
Where you will meet it next
- Dense layers and the forward pass (P4.1 to P4.5). The layer of section 1, one step at a time, then in matrix form with a batch.
- Backpropagation (P4.8, P1.C11, P4.10). Section 3 with real losses, then a whole network built in NumPy.
- Embeddings (P4.21, P6.3). Learned tables, and how word vectors are trained.
- Attention (P7.3 to P7.5) and the transformer block (P7.7). Section 5 with real sentences, then all the steps of the map in one block, with the residual and normalisation placed.
- Images (P5.1, P5.2). The convolution of the first Go deeper box.
- Fine-tuning (P10.E3). LoRA, the second Go deeper box.
- PCA (P3.C3) and linear regression (P3.A2). The parts of the module that this block does not use: projections, the inverse, the SVD of data.
Common mistakes
Check your understanding
A batch of examples with features goes through a dense layer with weights of shape and bias of shape . What is the shape of ?
has shape , so gives , and the bias of shape is broadcast down the 32 rows. The shape would be the input, is the transposed output, and is the shape of alone.
A layer computes with of shape . The gradient with respect to arrives. How is the gradient with respect to found?
The gradient with respect to must have 5 entries, like , and only , of shape , does. The product is not even defined for these shapes, passing on unchanged would give 3 entries, and a matrix has no inverse.
The attention scores of a sequence of tokens form a matrix for each example and head. What happens to the number of score entries when is doubled?
The count is , so doubling multiplies it by . It would only double if the count grew with alone, and it would grow eight-fold only with a third axis of size , which the scores do not have.
The one-hot vector of token number 2 is multiplied by an embedding matrix that has one row per token. What is the result?
A row vector times a matrix mixes the rows of the matrix with the vector's entries as weights. With a single 1 in place 2 and zeros elsewhere, the mix is row 2 alone. Taking a column would need the one-hot vector on the right of , and a sum of all rows would need a vector of all ones.
Two dense layers with matrices and are stacked with nothing between them. Why is that no more powerful than one layer?
by the rule for matrix products, so the pair is one matrix (and two biases also merge into one). The layers add nothing in this setting, but the second layer need not learn zeros. Training deep networks does pass gradients through many matrices.
Exercises
- For the layer of section 1 (, ) compute for .
Show answer
, and adding gives . - How many learned numbers has a dense layer from 10 inputs to 4 outputs? And from 784 inputs to 10 outputs?
Show answer
: , and . - The same layer receives the gradient at its output. Find the gradient at its input .
Show answer
. It has 3 entries, like . - Use the toy table of section 4 to embed the sequence “mat the” (numbers 3 and 0) as a product with one-hot rows. What is the result?
Show answer
: rows 3 and 0 of . - A model has , , and heads. Give , the shape of the scores and the number of score entries.
Show answer
. The scores have shape , which is entries. - A row of scores is . What are its softmax weights, and what does that token’s output equal?
Show answer
The three weights are equal, so each is . The output is the average of the three value vectors: . - Why must the output of the attention step have the same shape as the input for a residual add, and what makes it so?
Show answer
The sum adds entry by entry, so both arrays need the same shape (or shapes that broadcast). In the map, putting the heads of numbers side by side gives again, and the output matrix of shape mixes them without changing the shape. - Normalise with layer normalisation (mean, then division by the standard deviation). How does the answer compare with that of ?
Show answer
The mean is , the deviations are , the standard deviation is , and the result is : the same as for . Subtracting the mean removes a shift, and dividing by the spread removes a scale. - The dense layer of the map has . How many learned numbers does it have for ?
Show answer
. The first matrix has weights and biases, the second has weights and biases: . - Challenge: for the kernel of the convolution box, write the matrix for an input of length 5.
Show answer
It has 4 rows and 5 columns: row has in column , in column and zeros elsewhere. The first row is and the last is . The layer still has 2 learned numbers.