Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsLinear Algebra

Linear algebra in neural nets: a map

P1.B1525 min●●○ IntermediateReviewed Nov 30, 2026

Why this matters for machine learning

A neural network is a short list of matrix operations repeated many times, so knowing which tool of linear algebra lives where tells you what a network computes, what shapes it needs and where its cost comes from.

  • A dense layer on a batch is one product, XW⊤+b\mathbf{X}\mathbf{W}^\top+\mathbf{b}, with the bias broadcast over the examples. (P4.5: The forward pass in matrix form, coming soon)
  • An embedding layer is a table with one row per token, and picking a row is the same as multiplying a one-hot vector by the table. (P4.21: Embedding layers, coming soon)
  • Attention builds queries, keys and values with three matrices and scores every pair of tokens with one product. (P7.3: Queries, keys and values step by step, coming soon)
  • Backpropagation sends gradients backward through a layer with the transpose of its weight matrix. (P4.8: Backpropagation: step by step with numbers)
  • LoRA fine-tunes a big weight matrix by learning a low-rank update, which is two thin matrices. (P10.E3: Parameter-efficient fine-tuning, coming soon)

Before this: Matrices as data and as transformations, Matrix multiplication, Transpose, symmetric and orthogonal matrices, Tensors, shapes and broadcasting

After this lesson you can

  • Say what a dense layer computes on one example and on a batch, give the shapes, and count its learned numbers
  • Explain why a nonlinearity must sit between two layers, and how the backward pass uses W⊤\mathbf{W}^\top
  • Show that an embedding lookup is a one-hot vector times a matrix, and compute attention for three tokens as a few matrix products and one softmax
  • Match each tool of the linear algebra module to the place in a network where it is used, and name the lesson that teaches that place

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.

One block of a transformer, one operation at a time

B examples 2
T tokens 3
d width 4
h heads 2
dk = d / h = 2

1 Token ids

The text has been cut into tokens, and each token is a whole number: its place in the vocabulary. A batch is a grid of such numbers.

Shapes

  • token ids (B, T) (2, 3)

Symbols, then the numbers for the sizes above.

Learned numbers: none in this step.

These are not yet vectors. The next step turns every number into a vector.

Linear algebra used

Taught in detail later

Tap a step to see it. Shapes are for a made-up vocabulary of V = 1000 entries; m is the hidden width of the dense layer, 4d. Real models are far bigger.

Concept map of one transformer-style block. Ten steps run from the token ids to the output scores. Tap a step (or use the Previous and Next buttons) to see what it does, the shape of every array in it, how many numbers it learns, the linear-algebra lessons it uses and the lesson that teaches it in full. The steppers set the batch size B, the number of tokens T, the width d of a token vector and the number of heads h; the shapes and counts update at once. The button resets the sizes to the example used in this lesson. Lessons not yet written are shown as coming soon.

Things to try:

  1. Select Q, K, V projections and then Scores. Change TT from 3 to 16 and watch the scores array. Its entry count grows with T⋅TT\cdot T, and that square is why long inputs are costly (P7.12).
  2. Raise hh from 1 to 4 and look at Q, K, V projections again. The shape of the weights does not change: heads cut the same dd numbers into pieces. Only dk=d/hd_k=d/h shrinks.
  3. Select Residual add. All three arrays have the same shape. That is the condition for adding them.
  4. Select Dense layer and change dd. With the hidden width m=4dm=4d it has about 8d28d^2 learned numbers, so it grows with the square of dd, while the embedding table and the output layer grow only in proportion to dd (they are still bigger here, because the made-up vocabulary has 10001000 entries).
  5. Press the example button, which sets B=1B=1, T=3T=3, d=2d=2, h=1h=1. 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 Wx\mathbf{W}\mathbf{x} 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 XWQ\mathbf{X}\mathbf{W}_Q 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: Wx+b\mathbf{W}\mathbf{x}+\mathbf{b}

A dense layer (also called a fully connected or linear layer) turns a vector of dd numbers into a vector of hh numbers. P1.B5 gave the matrix, P1.B3 gave the dot product behind each output. Take

W=(123456)x=(10−1)b=(1020)\begin{aligned} \mathbf{W}&=\begin{pmatrix}1&2&3\\4&5&6\end{pmatrix}\\ \mathbf{x}&=\begin{pmatrix}1\\0\\-1\end{pmatrix}\\ \mathbf{b}&=\begin{pmatrix}10\\20\end{pmatrix} \end{aligned}

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 1⋅1+2⋅0+3⋅(−1)=−21\cdot1+2\cdot0+3\cdot(-1)=-2 and the second is 4⋅1+5⋅0+6⋅(−1)=−24\cdot1+5\cdot0+6\cdot(-1)=-2, so:

Wx=(−2−2)y=Wx+b=(818)\begin{aligned} \mathbf{W}\mathbf{x}&=\begin{pmatrix}-2\\-2\end{pmatrix}\\ \mathbf{y}=\mathbf{W}\mathbf{x}+\mathbf{b}&=\begin{pmatrix}8\\18\end{pmatrix} \end{aligned}

On a batch. Real data comes in batches. Stack the examples as the rows of X\mathbf{X} (P1.B5) and the layer becomes one product (P1.B6). Take the two examples (1,0,−1)(1,0,-1) and (2,1,0)(2,1,0):

XW⊤=(10−1210)(142536)=(−2−2413)\begin{aligned} \mathbf{X}\mathbf{W}^\top&=\begin{pmatrix}1&0&-1\\2&1&0\end{pmatrix}\begin{pmatrix}1&4\\2&5\\3&6\end{pmatrix}\\ &=\begin{pmatrix}-2&-2\\4&13\end{pmatrix} \end{aligned}

and then the bias is added to every row. The shapes are (2,3)(2,3) and (3,2)(3,2), so the product is (2,2)(2,2), and the bias has shape (2,)(2,). Broadcasting (P1.B14) stretches it down the rows:

(−2−2413)+(1020)=(8181433)\begin{pmatrix}-2&-2\\4&13\end{pmatrix}+\begin{pmatrix}10&20\end{pmatrix}=\begin{pmatrix}8&18\\14&33\end{pmatrix}

The first row is the single-example answer (8,18)(8,18). In general (N,d)⋅(d,m)+(m,)→(N,m)(N,d)\cdot(d,m)+(m,)\to(N,m).

Counting the learned numbers. The layer above has 2⋅3=62\cdot3=6 weights and 22 biases: 88 numbers. A layer from dd inputs to mm outputs has md+mmd+m. A layer from 784 inputs (a 28×2828\times28 image, P1.B1) to 128 outputs has 784⋅128+128=100,480784\cdot128+128=100{,}480.

  • 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 W1=(111−101)\mathbf{W}_1=\begin{pmatrix}1&1\\1&-1\\0&1\end{pmatrix}, W2=(101011)\mathbf{W}_2=\begin{pmatrix}1&0&1\\0&1&1\end{pmatrix} and x=(1,2)\mathbf{x}=(1,2):

W2W1=(1210)W1x=(3,−1,2)W2(W1x)=(5,1)=(W2W1)x\begin{aligned} \mathbf{W}_2\mathbf{W}_1&=\begin{pmatrix}1&2\\1&0\end{pmatrix}\\ \mathbf{W}_1\mathbf{x}&=(3,-1,2)\\ \mathbf{W}_2(\mathbf{W}_1\mathbf{x})&=(5,1)=(\mathbf{W}_2\mathbf{W}_1)\mathbf{x} \end{aligned}

Two layers with nothing between them are one layer, and so are ten. Put ReLU(z)=max⁡(0,z)\mathrm{ReLU}(z)=\max(0,z) on each entry between them (P4.4): ReLU(3,−1,2)=(3,0,2)\mathrm{ReLU}(3,-1,2)=(3,0,2), and W2(3,0,2)=(5,2)\mathbf{W}_2(3,0,2)=(5,2). That is not (5,1)(5,1), so the single matrix W2W1\mathbf{W}_2\mathbf{W}_1 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 W⊤\mathbf{W}^\top

Training needs the gradient of a loss with respect to every learned number. P1.B10 showed that the gradient travels backward through y=Wx+b\mathbf{y}=\mathbf{W}\mathbf{x}+\mathbf{b} by way of W⊤\mathbf{W}^\top. Use the layer of section 1, with x=(1,0,−1)\mathbf{x}=(1,0,-1), so that y=(8,18)\mathbf{y}=(8,18). Suppose the loss is L=2y1−y2L=2y_1-y_2. This is a made-up loss, chosen so that the gradient arriving at y\mathbf{y} is easy to see: g=∇yL=(2,−1)\mathbf{g}=\nabla_{\mathbf{y}}L=(2,-1). Then

∇xL=W⊤g=(142536)(2−1)=(−2−10)∇WL=gx⊤=(20−2−101)∇bL=g=(2,−1)\begin{aligned} \nabla_{\mathbf{x}}L&=\mathbf{W}^\top\mathbf{g}\\ &=\begin{pmatrix}1&4\\2&5\\3&6\end{pmatrix}\begin{pmatrix}2\\-1\end{pmatrix}\\ &=\begin{pmatrix}-2\\-1\\0\end{pmatrix}\\ \nabla_{\mathbf{W}}L&=\mathbf{g}\mathbf{x}^\top\\ &=\begin{pmatrix}2&0&-2\\-1&0&1\end{pmatrix}\\ \nabla_{\mathbf{b}}L&=\mathbf{g}=(2,-1) \end{aligned}

Check the first one by nudging. Raise x1x_1 from 11 to 1.0011.001. The first column of W\mathbf{W} is (1,4)(1,4), so y\mathbf{y} becomes (8.001, 18.004)(8.001,\,18.004) and L=2⋅8.001−18.004=−2.002L=2\cdot8.001-18.004=-2.002, down from −2-2. The change is −0.002=−2⋅0.001-0.002=-2\cdot0.001, which is what ∂L/∂x1=−2\partial L/\partial x_1=-2 predicts.

Each gradient has the shape of the thing it belongs to: ∇xL\nabla_{\mathbf{x}}L has the shape of x\mathbf{x}, and ∇WL\nabla_{\mathbf{W}}L has the shape of W\mathbf{W}, namely (2,3)(2,3). 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 G=(2−101)\mathbf{G}=\begin{pmatrix}2&-1\\0&1\end{pmatrix}, shape (N,h)(N,h). Then ∇WL=G⊤X\nabla_{\mathbf{W}}L=\mathbf{G}^\top\mathbf{X}, the sum over examples of gx⊤\mathbf{g}\mathbf{x}^\top, again one matrix product:

G⊤X=(20−11)(10−1210)=(20−2111)\begin{aligned} \mathbf{G}^\top\mathbf{X}&=\begin{pmatrix}2&0\\-1&1\end{pmatrix}\begin{pmatrix}1&0&-1\\2&1&0\end{pmatrix}\\ &=\begin{pmatrix}2&0&-2\\1&1&1\end{pmatrix} \end{aligned}

The gradient for the inputs is GW\mathbf{G}\mathbf{W}, with rows (−2,−1,0)(-2,-1,0) and (4,5,6)(4,5,6), and the gradient of the bias is the column sums of G\mathbf{G}, (2,0)(2,0).

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 (2112)\begin{pmatrix}2&1\\1&2\end{pmatrix} of P1.B12, whose eigenvalues are 33 and 11, and start from (1,0)(1,0). One multiplication gives (2,1)(2,1), two give (5,4)(5,4), three give (14,13)(14,13), and ten give (29525, 29524)(29525,\,29524): the length grows by about a factor of 33 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 E\mathbf{E} (P1.B5), with one row per entry of the vocabulary. Make a toy vocabulary of four tokens, numbered 00 to 33, with vectors of d=2d=2 numbers (made-up values, not trained):

E=(10110112)thecatsatmat\mathbf{E}=\begin{pmatrix}1&0\\1&1\\0&1\\1&2\end{pmatrix}\begin{matrix}\text{the}\\\text{cat}\\\text{sat}\\\text{mat}\end{matrix}

The token “cat” is number 1. Its one-hot vector has a 1 in place 1 and zeros elsewhere, and a product with E\mathbf{E} picks out row 1 (P1.B6 reads a product as a mix of rows, with the one-hot vector as the mixing weights):

(0100)E=(11)\begin{pmatrix}0&1&0&0\end{pmatrix}\mathbf{E}=\begin{pmatrix}1&1\end{pmatrix}

For the two tokens “cat sat”, numbers 11 and 22, stack the one-hot vectors as rows and multiply:

(01000010)E=(1101)\begin{pmatrix}0&1&0&0\\0&0&1&0\end{pmatrix}\mathbf{E}=\begin{pmatrix}1&1\\0&1\end{pmatrix}

That is rows 1 and 2 of E\mathbf{E}. 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 VV numbers by zero for every token (here V=4V=4 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, cos⁡(cat,mat)=32 5≈0.95\cos(\text{cat},\text{mat})=\dfrac{3}{\sqrt2\,\sqrt5}\approx0.95, cos⁡(cat,sat)=12≈0.71\cos(\text{cat},\text{sat})=\dfrac1{\sqrt2}\approx0.71 and cos⁡(the,sat)=0\cos(\text{the},\text{sat})=0. 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:

X=(101101)\mathbf{X}=\begin{pmatrix}1&0\\1&1\\0&1\end{pmatrix}

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:

WQ=(1011)WK=(1101)WV=(1002)\begin{aligned} \mathbf{W}_Q&=\begin{pmatrix}1&0\\1&1\end{pmatrix}\\ \mathbf{W}_K&=\begin{pmatrix}1&1\\0&1\end{pmatrix}\\ \mathbf{W}_V&=\begin{pmatrix}1&0\\0&2\end{pmatrix} \end{aligned}

Projections (shapes (3,2)⋅(2,2)→(3,2)(3,2)\cdot(2,2)\to(3,2)).

Q=XWQ=(102111)K=XWK=(111201)V=XWV=(101202)\begin{aligned} \mathbf{Q}=\mathbf{X}\mathbf{W}_Q&=\begin{pmatrix}1&0\\2&1\\1&1\end{pmatrix}\\ \mathbf{K}=\mathbf{X}\mathbf{W}_K&=\begin{pmatrix}1&1\\1&2\\0&1\end{pmatrix}\\ \mathbf{V}=\mathbf{X}\mathbf{W}_V&=\begin{pmatrix}1&0\\1&2\\0&2\end{pmatrix} \end{aligned}

Scores (shapes (3,2)⋅(2,3)→(3,3)(3,2)\cdot(2,3)\to(3,3)). Entry (i,j)(i,j) is the dot product of the query of token ii with the key of token jj (P1.B3, P1.B10):

QK⊤=(102111)(110121)=(110341231)\begin{aligned} \mathbf{Q}\mathbf{K}^\top&=\begin{pmatrix}1&0\\2&1\\1&1\end{pmatrix}\begin{pmatrix}1&1&0\\1&2&1\end{pmatrix}\\ &=\begin{pmatrix}1&1&0\\3&4&1\\2&3&1\end{pmatrix} \end{aligned}

The scores are divided by dk=2\sqrt{d_k}=\sqrt2 (P7.4 explains why). To two decimals the result is

QK⊤2≈(0.710.7102.122.830.711.412.120.71)\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt2}\approx\begin{pmatrix}0.71&0.71&0\\2.12&2.83&0.71\\1.41&2.12&0.71\end{pmatrix}

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

A≈(0.400.400.200.310.620.070.280.580.14)\mathbf{A}\approx\begin{pmatrix}0.40&0.40&0.20\\0.31&0.62&0.07\\0.28&0.58&0.14\end{pmatrix}

Row ii says how much token ii listens to each token. The token “cat” (the second row, row 1 counting from 0) puts 0.620.62 of its attention on itself. Each row adds to 1 up to rounding.

Weighted sum of values (shapes (3,3)⋅(3,2)→(3,2)(3,3)\cdot(3,2)\to(3,2)). The first row is

0.4011⋅(1,0)+0.4011⋅(1,2)+0.1978⋅(0,2)≈(0.80, 1.20)\begin{aligned} &0.4011\cdot(1,0)+0.4011\cdot(1,2)\\ &\quad+0.1978\cdot(0,2)\approx(0.80,\,1.20) \end{aligned}

Each output row is a linear combination of the rows of V\mathbf{V} (P1.B2), with that token’s weights as the coefficients. All three rows, rounded:

AV≈(0.801.200.931.390.861.43)\mathbf{A}\mathbf{V}\approx\begin{pmatrix}0.80&1.20\\0.93&1.39\\0.86&1.43\end{pmatrix}

The output has the same shape as the input X\mathbf{X}, (3,2)(3,2), 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 BB sequences of TT tokens, X\mathbf{X} has shape (B,T,d)(B,T,d) and the matrix products are batched (P1.B14). The dd numbers of each query, key and value are cut into hh heads of dk=d/hd_k=d/h numbers (in the original transformer, d=512d=512 and h=8h=8 gave dk=64d_k=64). The shapes then run as

Q,K,V: (B,T,d)→(B,h,T,dk)QK⊤: (B,h,T,dk)⋅(B,h,dk,T)→(B,h,T,T)AV: (B,h,T,T)⋅(B,h,T,dk)→(B,h,T,dk)\begin{aligned} \mathbf{Q},\mathbf{K},\mathbf{V}&:\ (B,T,d)\to(B,h,T,d_k)\\ \mathbf{Q}\mathbf{K}^\top&:\ (B,h,T,d_k)\cdot(B,h,d_k,T)\\ &\qquad\to(B,h,T,T)\\ \mathbf{A}\mathbf{V}&:\ (B,h,T,T)\cdot(B,h,T,d_k)\\ &\qquad\to(B,h,T,d_k) \end{aligned}

and the heads are put side by side again to give (B,T,d)(B,T,d), followed by one more matrix WO\mathbf{W}_O of shape (d,d)(d,d). The softmax runs over the last axis, so each row of weights sums to 1. The score array has B⋅h⋅T⋅TB\cdot h\cdot T\cdot T entries, which grows with the square of the sequence length. The number of weights in WQ\mathbf{W}_Q, WK\mathbf{W}_K and WV\mathbf{W}_V does not depend on hh: more heads cut the same dd 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: x+f(x)\mathbf{x}+f(\mathbf{x}). For the first token, x=(1,0)\mathbf{x}=(1,0) and the attention output is (0.80,1.20)(0.80,1.20), so the sum is (1.80,1.20)(1.80,1.20) (P1.B2). The addition needs both arrays to have the same shape. Putting the heads side by side already gives (B,T,d)(B,T,d) again (when h⋅dk=dh\cdot d_k=d, as usual), and WO\mathbf{W}_O of shape (d,d)(d,d) then mixes the heads without changing the shape. The backward pass benefits too: the derivative of x+f(x)\mathbf{x}+f(\mathbf{x}) with respect to x\mathbf{x} includes the identity, so a gradient has a direct path back (P4.20).

Normalisation. Layer normalisation rescales each token’s vector. Take (1,2,3)(1,2,3). Its mean is 22, the deviations from the mean are (−1,0,1)(-1,0,1), and the standard deviation (the square root of the average squared deviation) is 2/3≈0.816\sqrt{2/3}\approx0.816. Dividing the deviations by it gives

(1,2,3)−20.816≈(−1.22, 0, 1.22)\frac{(1,2,3)-2}{0.816}\approx(-1.22,\ 0,\ 1.22)

This vector has length d=3\sqrt d=\sqrt3: the squares are 1.5+0+1.5=31.5+0+1.5=3 (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 (B,T,d)(B,T,d) the mean is taken over the last axis with keepdims, giving shape (B,T,1)(B,T,1) (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 W\mathbf{W} of a layer, the embedding table.
  • P1.B6 Matrix multiplication. A layer on a batch, stacked layers, QK⊤\mathbf{Q}\mathbf{K}^\top, 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, K⊤\mathbf{K}^\top 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 (B,T,d)(B,T,d) and (B,h,T,T)(B,h,T,T) 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 x=(3,1,4,1)\mathbf{x}=(3,1,4,1) and the kernel (1,−1)(1,-1). At each position, the output is the entry minus the next entry: (3−1, 1−4, 4−1)=(2,−3,3)(3-1,\ 1-4,\ 4-1)=(2,-3,3). As a matrix:

(1−10001−10001−1)(3141)=(2−33)\begin{aligned} &\begin{pmatrix}1&-1&0&0\\0&1&-1&0\\0&0&1&-1\end{pmatrix}\begin{pmatrix}3\\1\\4\\1\end{pmatrix}\\ &\quad=\begin{pmatrix}2\\-3\\3\end{pmatrix} \end{aligned}

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 3⋅4=123\cdot4=12. 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 d×dd\times d means learning a change of the same shape, which is d2d^2 numbers. LoRA (Hu et al., 2021) keeps the weights frozen and learns the change as a product BA\mathbf{B}\mathbf{A} of two thin matrices of shapes d×rd\times r and r×dr\times d (P1.B13). For d=1000d=1000 and r=8r=8 that is 1000⋅8+8⋅1000=16,0001000\cdot8+8\cdot1000=16{,}000 numbers instead of 1,000,0001{,}000{,}000. A product of thin matrices has rank at most rr (P1.B7), so LoRA bets that the useful change is close to low rank. The layer is computed as Wx+B(Ax)\mathbf{W}\mathbf{x}+\mathbf{B}(\mathbf{A}\mathbf{x}), with shapes (d,)→(r,)→(d,)(d,)\to(r,)\to(d,), so the large d×dd\times d product is never formed. The paper applied the method mainly to attention weight matrices such as WQ\mathbf{W}_Q and WV\mathbf{W}_V. 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.

Try it: one block, step by step

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

What to expect: the dense layer prints (8,18)(8,18) for one example and [[8,18],[14,33]][[8,18],[14,33]] for the batch, with 88 learned numbers. The two layers give (5,1)(5,1) both ways, and (5,2)(5,2) with the ReLU. The gradients are (−2,−1,0)(-2,-1,0) for x\mathbf{x} and the matrices of section 3. The lookup prints [[1,1],[0,1]][[1,1],[0,1]] twice. The attention scores are [[1,1,0],[3,4,1],[2,3,1]][[1,1,0],[3,4,1],[2,3,1]], the weights are the rounded matrix of section 5 with row sums 11, and the output rows are (0.8,1.2)(0.8,1.2), (0.93,1.39)(0.93,1.39) and (0.86,1.43)(0.86,1.43) (printed to two decimals, so 0.800.80 appears as 0.80.8). The normalised vector is (−1.22,0,1.22)(-1.22,0,1.22) with squared length 33. 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

  1. A batch X\mathbf{X} of N=32N=32 examples with d=10d=10 features goes through a dense layer with weights W\mathbf{W} of shape (m,d)=(4,10)(m,d)=(4,10) and bias b\mathbf{b} of shape (4,)(4,). What is the shape of XW⊤+b\mathbf{X}\mathbf{W}^\top+\mathbf{b}?

  2. A layer computes y=Wx+b\mathbf{y}=\mathbf{W}\mathbf{x}+\mathbf{b} with W\mathbf{W} of shape (3,5)(3,5). The gradient g\mathbf{g} with respect to y\mathbf{y} arrives. How is the gradient with respect to x\mathbf{x} found?

  3. The attention scores of a sequence of TT tokens form a T×TT\times T matrix for each example and head. What happens to the number of score entries when TT is doubled?

  4. The one-hot vector of token number 2 is multiplied by an embedding matrix E\mathbf{E} that has one row per token. What is the result?

  5. Two dense layers with matrices W1\mathbf{W}_1 and W2\mathbf{W}_2 are stacked with nothing between them. Why is that no more powerful than one layer?

Exercises

  1. For the layer of section 1 (W=(123456)\mathbf{W}=\begin{pmatrix}1&2&3\\4&5&6\end{pmatrix}, b=(10,20)\mathbf{b}=(10,20)) compute y\mathbf{y} for x=(0,1,2)\mathbf{x}=(0,1,2).
    Show answerWx=(0+2+6, 0+5+12)=(8,17)\mathbf{W}\mathbf{x}=(0+2+6,\ 0+5+12)=(8,17), and adding b\mathbf{b} gives y=(18,37)\mathbf{y}=(18,37).
  2. How many learned numbers has a dense layer from 10 inputs to 4 outputs? And from 784 inputs to 10 outputs?
    Show answermd+mmd+m: 4⋅10+4=444\cdot10+4=44, and 10⋅784+10=785010\cdot784+10=7850.
  3. The same layer receives the gradient g=(1,3)\mathbf{g}=(1,3) at its output. Find the gradient at its input x\mathbf{x}.
    Show answerW⊤g=(1⋅1+4⋅3, 2⋅1+5⋅3, 3⋅1+6⋅3)=(13,17,21)\mathbf{W}^\top\mathbf{g}=(1\cdot1+4\cdot3,\ 2\cdot1+5\cdot3,\ 3\cdot1+6\cdot3)=(13,17,21). It has 3 entries, like x\mathbf{x}.
  4. Use the toy table E\mathbf{E} 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(00011000)E=(1210)\begin{pmatrix}0&0&0&1\\1&0&0&0\end{pmatrix}\mathbf{E}=\begin{pmatrix}1&2\\1&0\end{pmatrix}: rows 3 and 0 of E\mathbf{E}.
  5. A model has B=4B=4, T=10T=10, d=64d=64 and h=8h=8 heads. Give dkd_k, the shape of the scores and the number of score entries.
    Show answerdk=64/8=8d_k=64/8=8. The scores have shape (4,8,10,10)(4,8,10,10), which is 4⋅8⋅10⋅10=32004\cdot8\cdot10\cdot10=3200 entries.
  6. A row of scores is (0,0,0)(0,0,0). What are its softmax weights, and what does that token’s output equal?
    Show answerThe three weights are equal, so each is 1/31/3. The output is the average of the three value vectors: 13(v1+v2+v3)\tfrac13(\mathbf{v}_1+\mathbf{v}_2+\mathbf{v}_3).
  7. 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 answerThe sum x+f(x)\mathbf{x}+f(\mathbf{x}) adds entry by entry, so both arrays need the same shape (or shapes that broadcast). In the map, putting the hh heads of dk=d/hd_k=d/h numbers side by side gives (B,T,d)(B,T,d) again, and the output matrix WO\mathbf{W}_O of shape (d,d)(d,d) mixes them without changing the shape.
  8. Normalise (10,20,30)(10,20,30) with layer normalisation (mean, then division by the standard deviation). How does the answer compare with that of (1,2,3)(1,2,3)?
    Show answerThe mean is 2020, the deviations are (−10,0,10)(-10,0,10), the standard deviation is 200/3≈8.16\sqrt{200/3}\approx8.16, and the result is (−1.22,0,1.22)(-1.22,0,1.22): the same as for (1,2,3)(1,2,3). Subtracting the mean removes a shift, and dividing by the spread removes a scale.
  9. The dense layer of the map has m=4dm=4d. How many learned numbers does it have for d=4d=4?
    Show answerm=16m=16. The first matrix has 4⋅16=644\cdot16=64 weights and 1616 biases, the second has 16⋅4=6416\cdot4=64 weights and 44 biases: 64+16+64+4=14864+16+64+4=148.
  10. Challenge: for the (1,−1)(1,-1) kernel of the convolution box, write the matrix for an input of length 5.
    Show answerIt has 4 rows and 5 columns: row ii has 11 in column ii, −1-1 in column i+1i+1 and zeros elsewhere. The first row is (1,−1,0,0,0)(1,-1,0,0,0) and the last is (0,0,0,1,−1)(0,0,0,1,-1). The layer still has 2 learned numbers.

Key takeaways

  • A dense layer is y=Wx+b\mathbf{y}=\mathbf{W}\mathbf{x}+\mathbf{b}; on a batch with one example per row it is XW⊤+b\mathbf{X}\mathbf{W}^\top+\mathbf{b}, with the bias broadcast over the rows. A layer from dd inputs to mm outputs has md+mmd+m learned numbers.
  • Two linear layers with nothing between them are one linear layer (W2W1\mathbf{W}_2\mathbf{W}_1), so a nonlinearity such as ReLU goes between them.
  • The backward pass sends a gradient g\mathbf{g} through y=Wx+b\mathbf{y}=\mathbf{W}\mathbf{x}+\mathbf{b} with W⊤g\mathbf{W}^\top\mathbf{g}; the gradient of W\mathbf{W} is gx⊤\mathbf{g}\mathbf{x}^\top. Every gradient has the shape of the thing it belongs to.
  • A one-hot vector times the embedding matrix E\mathbf{E} picks one row of E\mathbf{E}, so a lookup is a matrix product that code does by indexing.
  • Attention is Q=XWQ\mathbf{Q}=\mathbf{X}\mathbf{W}_Q, K=XWK\mathbf{K}=\mathbf{X}\mathbf{W}_K, V=XWV\mathbf{V}=\mathbf{X}\mathbf{W}_V, scores QK⊤/dk\mathbf{Q}\mathbf{K}^\top/\sqrt{d_k}, a softmax along each row, and one more product with V\mathbf{V}. For a batch the scores form an array of shape (B,h,T,T)(B,h,T,T).
  • A residual connection adds the input back onto a layer's output, which needs equal shapes; normalisation subtracts a mean and divides by a spread over the last axis, one token at a time.
  • Almost every tool of P1.B1 to P1.B14 appears in this picture (the determinant and the inverse live elsewhere); the map says which later lesson teaches each piece in full.
Found a mistake? Tell us