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 4: Neural Network Foundations

The forward pass in matrix form

P4.535 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

Every neural network, from a small classifier to a large language model, runs as a chain of matrix products on a whole batch of examples at once. Knowing the shape of every matrix in that chain is how you read, write and debug network code.

  • Building a network from scratch means writing each layer as X @ W.T + b with the right shapes, and getting a batch through it. (P4.10: Build an MLP from scratch (NumPy))
  • PyTorch's nn.Linear and its training loop do exactly this, and most of the errors you meet there are shape errors like the ones in this lesson. (P2.6: PyTorch tensors and autograd)
  • Backpropagation reuses the values the forward pass stored, and gives each weight matrix a gradient of the same shape as the matrix. (P4.8: Backpropagation: step by step with numbers)
  • Counting a layer's parameters and multiply-adds tells you whether a model fits in memory and roughly how long one step takes. (P10.B4: Counting compute and memory, coming soon)

Before this: Multi-layer perceptrons, Activation functions, Tensors, shapes and broadcasting

After this lesson you can

  • Write one layer as Wx+b\mathbf{W}\mathbf{x}+\mathbf{b} for one example and as XW⊤+b\mathbf{X}\mathbf{W}^\top+\mathbf{b} for a batch, with the shape of every matrix, and say which convention PyTorch and Keras use
  • Track the shapes through a stack of layers with an activation and a softmax output, and compute the loss averaged over a batch
  • Count a layer's parameters (dindout+doutd_{\text{in}}d_{\text{out}}+d_{\text{out}}) and its multiply-adds (about N dindoutN\,d_{\text{in}}d_{\text{out}}), and say why batching is faster than a loop
  • Spot the common shape bugs (transposed weights, a wrong bias shape, a missing batch axis, softmax over the wrong axis) and catch them with assertions

You have a network that works on one example. A training step needs it on 64 examples, or 1,000. The obvious code is a loop: take example 1, run the network, take example 2, run it again. It gives the right numbers, and it is slow, because it makes the computer do 64 small jobs where it could do one big one.

The fix is to stack the 64 examples into a table and write each layer as one matrix product on the whole table. This lesson shows how that works, how to keep track of the shape of every matrix on the way, and how to count what it costs. In a test on the machine used for this lesson, one matrix product on 10,000 examples ran several times faster than the loop with the same result (the numbers are in the section on batching). Most of the bugs in real network code are shape bugs, so the second half of the lesson is about finding them.

One layer, then a batch

P4.1 built one neuron, z=w⋅x+bz=\mathbf{w}\cdot\mathbf{x}+b. A layer is doutd_{\text{out}} neurons that look at the same input. Stack their weight vectors as the rows of a matrix W\mathbf{W} of shape (dout,din)(d_{\text{out}},d_{\text{in}}), and all the dot products come out of one product (P1.B5):

z=Wx+b\mathbf{z}=\mathbf{W}\mathbf{x}+\mathbf{b}

P1.B15 worked an example: W=(123456)\mathbf{W}=\begin{pmatrix}1&2&3\\4&5&6\end{pmatrix}, b=(10,20)\mathbf{b}=(10,20) and x=(1,0,−1)\mathbf{x}=(1,0,-1) give z=(8,18)\mathbf{z}=(8,18). Row 1 of W\mathbf{W} is neuron 1: 1−0−3=−21-0-3=-2, and −2+10=8-2+10=8.

For a batch, stack the examples as the rows of X\mathbf{X}, with shape (N,din)(N,d_{\text{in}}) (P1.B5; NN is the number of rows, the batch size BB of training). The same P1.B15 layer on the examples (1,0,−1)(1,0,-1) and (2,1,0)(2,1,0) is

Z=XW⊤+b=(−2−2413)+(1020)=(8181433)\begin{aligned} \mathbf{Z}&=\mathbf{X}\mathbf{W}^\top+\mathbf{b}\\ &=\begin{pmatrix}-2&-2\\4&13\end{pmatrix}+\begin{pmatrix}10&20\end{pmatrix}\\ &=\begin{pmatrix}8&18\\14&33\end{pmatrix} \end{aligned}

Entry (i,j)(i,j) of XW⊤\mathbf{X}\mathbf{W}^\top is the dot product of example ii with neuron jj (example 2, neuron 2: (2,1,0)⋅(4,5,6)=13(2,1,0)\cdot(4,5,6)=13). The transpose is there because W\mathbf{W} keeps one neuron per row and the product needs one per column. The bias of shape (dout,)(d_{\text{out}},) is broadcast down the rows (P1.B14): align the shapes from the right, and the row (10,20)(10,20) is stretched over every example. The shape rule is

(N,din)⋅(din,dout)→(N,dout)(N,dout)+(dout,)→(N,dout)\begin{aligned} (N,d_{\text{in}})\cdot(d_{\text{in}},d_{\text{out}})&\to(N,d_{\text{out}})\\ (N,d_{\text{out}})+(d_{\text{out}},)&\to(N,d_{\text{out}}) \end{aligned}

The inner sizes dind_{\text{in}} must match, and NN passes through untouched: a layer changes the number of columns, not the number of rows. And the rows do not mix: row ii of Z\mathbf{Z} is computed from row ii of X\mathbf{X} alone, so the examples in a batch do not influence each other in a dense layer.

Two conventions, and which library uses which

There are two ways to write the same layer, and mixing them up causes a lot of the shape confusion.

  • Column-vector convention. An example is a column, the layer is z=Wx+b\mathbf{z}=\mathbf{W}\mathbf{x}+\mathbf{b}, and W\mathbf{W} has shape (dout,din)(d_{\text{out}},d_{\text{in}}). This is the convention of most maths texts, of softmax regression in P3.A8, and of backpropagation by hand in P4.8. A batch of examples stacked as columns is X⊤\mathbf{X}^\top, with shape (din,N)(d_{\text{in}},N), and the layer is Z⊤=WX⊤+b\mathbf{Z}^\top=\mathbf{W}\mathbf{X}^\top+\mathbf{b}, where b\mathbf{b} is a column of shape (dout,1)(d_{\text{out}},1) stretched across the columns.
  • Row-batch convention. An example is a row, a batch is X\mathbf{X} with shape (N,din)(N,d_{\text{in}}), and the layer is Z=XW⊤+b\mathbf{Z}=\mathbf{X}\mathbf{W}^\top+\mathbf{b}. This is what code uses, because data tables, NumPy arrays and PyTorch batches have the examples along the first axis (P2.2, P2.6).

The two give the same numbers, one the transpose of the other: (XW⊤)⊤=WX⊤(\mathbf{X}\mathbf{W}^\top)^\top=\mathbf{W}\mathbf{X}^\top. The matrix W\mathbf{W} itself is the same in both, with the neurons as rows. That is why the row-batch formula has a ⊤\top: it is the price of keeping the same W\mathbf{W}.

What the libraries do:

  • PyTorch. The documentation of nn.Linear gives y=xA⊤+by=x\mathbf{A}^\top+b. The weight has shape (out_features, in_features), the bias has shape (out_features,), and the input may have any number of leading axes before the last one, which must be in_features. So the weight is (dout,din)(d_{\text{out}},d_{\text{in}}) as in the column convention, and the layer is applied to rows.
  • Keras. The documentation of Dense gives output = activation(dot(input, kernel) + bias). Its kernel has shape (input_dim, units), which is W⊤\mathbf{W}^\top of this lesson, so there is no transpose in the formula.
  • Your own NumPy code. Whatever you choose. If you copy weights between libraries, a missing or extra transpose is the first thing to check.

For a single example stored as a 1-D array x of shape (d,), W @ x + b and x @ W.T + b are the same thing, because NumPy treats a 1-D array as a row or a column as needed. The difference only shows up once you have a batch.

Activation and stacking

After the matrix product the network applies the activation function (P4.4). It acts on each entry on its own, so it needs no matrix product, and it keeps the shape: a (N,dout)(N,d_{\text{out}}) table of numbers goes in and a (N,dout)(N,d_{\text{out}}) table comes out. For ReLU it turns each negative entry into 00 and keeps the rest.

A network is these two steps repeated. The layers of P4.3, h=f(W1x+b1)\mathbf{h}=f(\mathbf{W}_1\mathbf{x}+\mathbf{b}_1) and y^=g(W2h+b2)\hat{\mathbf{y}}=g(\mathbf{W}_2\mathbf{h}+\mathbf{b}_2), become for a whole batch:

Z1=XW1⊤+b1,H=f(Z1)Z2=HW2⊤+b2,P=g(Z2)\begin{aligned} \mathbf{Z}_1&=\mathbf{X}\mathbf{W}_1^\top+\mathbf{b}_1, &\mathbf{H}&=f(\mathbf{Z}_1)\\ \mathbf{Z}_2&=\mathbf{H}\mathbf{W}_2^\top+\mathbf{b}_2, &\mathbf{P}&=g(\mathbf{Z}_2) \end{aligned}

The output of one layer is the input of the next: H\mathbf{H} has one row per example, just as X\mathbf{X} did. Each row of P\mathbf{P} is the y^\hat{\mathbf{y}} of P4.3 for that example. The chain of shapes works out like a train of coupled wagons: X\mathbf{X} is (N,d0)(N,d_0), the first weight matrix transposed is (d0,d1)(d_0,d_1), so H\mathbf{H} is (N,d1)(N,d_1); the next one is (d1,d2)(d_1,d_2), so the output is (N,d2)(N,d_2). The inner sizes always cancel, and what is left is NN and the last size.

See it: a batch flowing through the network

The widget runs the small network of this lesson on up to 4 examples: 3 inputs, 4 ReLU neurons, then 2 outputs with a softmax. The weights are made up. Press Step to move one stage at a time (or Play), and look at the strip of chips on top: it shows the shape of the matrix after each stage. Choose the batch size NN from 1 to 4 and which example to follow (its row is pink). The numbers are the forward values, in blue.

Batch size N
Convention
Follow example

1. The batch

X: (N, d) = 4×3 one example per row

X 4×3
ex1 10−1ex2 210ex3 012ex4 111

The batch has N = 4 examples, each with 3 features. In the row-batch convention an example is a row of X. In the column-vector convention it is a column of Xᵀ. Example 1 is highlighted; follow it through the network.

Blue numbers are values computed by the forward pass. The pink row is the example you follow. The weights of the network are fixed made-up numbers.

A batch of examples flowing through a 3 to 4 to 2 network. Each stage shows the matrices being multiplied, with their shapes, and the result. Choose the batch size N, follow one example (its row or column is pink), and switch between the row-batch convention (X Wᵀ + b, examples are rows) and the column-vector convention (W Xᵀ + b, examples are columns): the same numbers, transposed. In Lite Mode every stage is shown at once and nothing animates.

Things to try (the weights are fixed, so these numbers repeat):

  1. With N=4N=4 press Step once. The product Z1\mathbf{Z}_1 has shape 4×44\times4, and its second row is (1,2,2,−2)(1,2,2,-2): example 2 through the four neurons. Press Step once more. The ReLU crosses out four entries (the three −2-2s and the −1-1) and turns them into 00. The shape does not change.
  2. Choose N=1N=1, then N=2N=2. The matrices lose rows, and the weight matrices do not change at all. The weights have no NN in their shape: the same weights serve any batch size.
  3. Follow example 3 and compare the Rows and Columns buttons. The numbers are the same, the matrices are transposed, and the bias is a row of 4 in one and a column of 4 in the other.
  4. On the last stage (N=4N=4), example 2 has probabilities (0.818,0.182)(0.818,0.182) but its true class is 1, so its loss −ln⁡0.182=1.701-\ln 0.182=1.701 is much bigger than the others. The average loss is 0.45260.4526. Change NN and the average changes with it.

The worked network, with every shape

The shapes of the whole network for N=4N=4 examples, 3 inputs, 4 hidden neurons and 2 outputs. Weights and biases are the learned part; the matrices with an NN in them are made fresh for each batch.

  • X\mathbf{X}: (4,3)(4,3).
  • Layer 1: W1\mathbf{W}_1 is (4,3)(4,3) and b1\mathbf{b}_1 is (4,)(4,). The product XW1⊤\mathbf{X}\mathbf{W}_1^\top is (4,3)⋅(3,4)=(4,4)(4,3)\cdot(3,4)=(4,4), and Z1\mathbf{Z}_1 is (4,4)(4,4).
  • ReLU: H\mathbf{H} is (4,4)(4,4).
  • Layer 2: W2\mathbf{W}_2 is (2,4)(2,4) and b2\mathbf{b}_2 is (2,)(2,). The product HW2⊤\mathbf{H}\mathbf{W}_2^\top is (4,4)⋅(4,2)=(4,2)(4,4)\cdot(4,2)=(4,2), and Z2\mathbf{Z}_2 is (4,2)(4,2).
  • Softmax: P\mathbf{P} is (4,2)(4,2).

The numbers. The four examples are the rows of X\mathbf{X}, and the weights of the four hidden neurons are the rows of W1\mathbf{W}_1:

X=(10−1210012111)W1=(1−1001111−1−101)b1=(0, 1, −1, 0)\begin{aligned} \mathbf{X}&=\begin{pmatrix}1&0&-1\\2&1&0\\0&1&2\\1&1&1\end{pmatrix}\\ \mathbf{W}_1&=\begin{pmatrix}1&-1&0\\0&1&1\\1&1&-1\\-1&0&1\end{pmatrix}\\ \mathbf{b}_1&=(0,\,1,\,-1,\,0) \end{aligned}

Check one entry by hand: example 3 is (0,1,2)(0,1,2) and neuron 3 has weights (1,1,−1)(1,1,-1) and bias −1-1, so 0+1−2−1=−20+1-2-1=-2. That is the third entry of the third row of Z1\mathbf{Z}_1. The full results:

Z1=(101−2122−2−14−220300)H=(1010122004020300)\begin{aligned} \mathbf{Z}_1&=\begin{pmatrix}1&0&1&-2\\1&2&2&-2\\-1&4&-2&2\\0&3&0&0\end{pmatrix}\\ \mathbf{H}&=\begin{pmatrix}1&0&1&0\\1&2&2&0\\0&4&0&2\\0&3&0&0\end{pmatrix} \end{aligned}

The second layer has W2=(101−1−1101)\mathbf{W}_2=\begin{pmatrix}1&0&1&-1\\-1&1&0&1\end{pmatrix} and b2=(0, 0.5)\mathbf{b}_2=(0,\,0.5):

Z2=(2−0.531.5−26.503.5)\mathbf{Z}_2=\begin{pmatrix}2&-0.5\\3&1.5\\-2&6.5\\0&3.5\end{pmatrix}

The cell below runs all of it, and prints the same matrices, the probabilities and the loss.

Try it: the whole forward pass

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

What to expect: the shapes (4, 3) (4, 4) (4, 4) (4, 2) (4, 2), the matrices above, and the probabilities 0.9240.924 and 0.0760.076 for example 1, 0.8180.818 and 0.1820.182 for example 2, and so on (example 3 shows 0.0. and 1.1. because its probabilities, 0.00020.0002 and 0.99980.9998, round to those). Each row sum is 11. The losses are 0.0790.079, 1.7011.701, 00 and 0.030.03 with mean 0.45260.4526 (example 3’s loss is 0.00020.0002, which rounds to 00 at three decimals). The loop gives (3,1.5)(3,1.5) for example 2, which is the second row of Z2\mathbf{Z}_2. Changing the third example changes only the third row.

The output layer and the loss over a batch

The last layer’s job is set by the task. For classification into KK classes it computes KK scores per example, the logits (P3.A8), and applies the softmax to turn them into probabilities. In the matrix form the softmax acts on each row on its own: exponentiate the entries of the row and divide by the sum of that row. For Z2\mathbf{Z}_2 above, row 1 is (2,−0.5)(2,-0.5), whose probabilities are 0.9240.924 and 0.0760.076, and the rows of P\mathbf{P} add up to 1. In NumPy this is a sum along axis=1, with keepdims=True so that the (N,1)(N,1) column of sums broadcasts back across the row.

The loss is defined for one example, and the loss of the batch is the average of the per-example losses (P4.6 compares loss functions). For cross-entropy, example ii with true class yiy_i has Li=−ln⁡Pi,yiL_i=-\ln P_{i,y_i} (P3.A8), and

L=1N∑i=1NLi.\mathcal{L}=\frac{1}{N}\sum_{i=1}^{N}L_i .

With the true classes y=(0,1,1,1)y=(0,1,1,1) for the four examples, the four losses are 0.0790.079, 1.7011.701, 0.00020.0002 and 0.0300.030, and the average is 0.45260.4526. Example 2 is the one the network gets wrong (it gives class 0 the probability 0.8180.818), and it supplies almost all of the loss. The average, rather than the sum, keeps the loss on about the same scale when the batch size changes, so the learning rate does not have to be changed just because the batch got bigger (P1.F4 treats mini-batches).

Counting parameters and multiply-adds

A layer’s parameters are its weights and biases: dindoutd_{\text{in}}d_{\text{out}} weights and doutd_{\text{out}} biases.

parameters=din dout+dout\text{parameters}=d_{\text{in}}\,d_{\text{out}}+d_{\text{out}}

The 3→43\to4 layer has 12+4=1612+4=16, and the 4→24\to2 layer has 8+2=108+2=10, so the network has 2626 parameters. A batch has NN examples but the parameter count does not depend on NN: the same weights are used for every row. A layer from 784784 inputs (a 28×2828\times28 image, P1.B1) to 128128 neurons has 784⋅128+128=100,480784\cdot128+128=100{,}480, and a layer from 128128 to 1010 adds 1,2901{,}290, for 101,770101{,}770 parameters.

The cost of a forward pass is the arithmetic. Each of the N doutN\,d_{\text{out}} entries of Z\mathbf{Z} is a dot product of dind_{\text{in}} pairs of numbers, so the product costs about N din doutN\,d_{\text{in}}\,d_{\text{out}} multiply-adds (P1.B6 for the product, P1.G4 for cost in general). For the small network with N=4N=4 that is 4⋅3⋅4=484\cdot3\cdot4=48 for layer 1 and 4⋅4⋅2=324\cdot4\cdot2=32 for layer 2, 8080 in all. The bias addition and the activation touch each entry once, and they are small next to the products. With N=64N=64 the 784→128→10784\to128\to10 network needs 64⋅784⋅128+64⋅128⋅10=6,504,44864\cdot784\cdot128+64\cdot128\cdot10=6{,}504{,}448 multiply-adds, about 6.5 million. The cost grows in proportion to NN, and the parameter count does not.

Why batch: one product instead of a loop

A loop over the examples and a single product give the same numbers (the cell above showed it for one example). The reason to prefer the product is speed. NumPy and PyTorch hand a matrix product to code that is tuned for exactly that job, and a Python loop pays the overhead of a function call for every example. There is also a hardware reason. In a matrix product each number is used many times (each entry of X\mathbf{X} is used doutd_{\text{out}} times), so a processor can keep its arithmetic units busy instead of waiting for data; P10.B8 returns to this. How much faster depends on the machine, the sizes and the library, so treat any single timing as an example.

The cell below measures it with N=10,000N=10{,}000 examples, 784784 features and 128128 neurons. On the machine used for this lesson (CPython and NumPy, not the browser), the loop took about 0.110.11 s and the single product about 0.010.01 s, roughly 7 to 9 times faster in repeated runs. The browser will give other numbers, but the single product should still win by a clear margin.

Try it: a loop against one matrix product

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

Shape bugs, and how to catch them

A wrong shape often does not raise an error. NumPy and PyTorch are happy to broadcast, and a legal shape is not always the shape you meant. The common ones, in the order of how quietly they fail:

  • Transposed weights. Writing X @ W where W is stored as (dout,din)(d_{\text{out}},d_{\text{in}}) raises an error when din≠doutd_{\text{in}}\neq d_{\text{out}} (the inner sizes differ). When the layer is square, it runs and gives wrong numbers.
  • A bias of the wrong shape. The bias must be (dout,)(d_{\text{out}},) (or (1,dout)(1,d_{\text{out}})). If it is (dout,1)(d_{\text{out}},1) (a column), broadcasting adds the bias entry ii to row ii instead of column ii. It raises an error for most sizes, but it runs silently when N=doutN=d_{\text{out}} (as in the lesson’s 4×44\times4 example) and also when N=1N=1, where the result even has the wrong shape (dout,dout)(d_{\text{out}},d_{\text{out}}). P1.B14 showed the same trap with the loss.
  • A missing batch axis. A single example has shape (d,), and a batch of one has shape (1, d). Many functions accept both, but they return (d_out,) and (1, d_out), and code written for batches then fails: a softmax with axis=1 on a (d_out,) array raises an error, and .shape[0] is d_out where you expected the batch size. A batch of one still needs its axis.
  • Softmax over the wrong axis. On a (N,K)(N,K) array the probabilities must add to 1 along the class axis (axis=1). Along axis=0 they add to 1 across the examples, the rows no longer sum to 1, and an example’s probabilities now depend on the other examples in the batch.

The defence is to print .shape and to assert it, at least while writing the code. The cell below wraps the layer with checks and tries each bug.

Try it: a layer with shape checks

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

What to expect: the good call prints (4, 4). The first bug is a NumPy error about the inner sizes. The checked version rejects the column bias and the missing batch axis with a clear message, and accepts the batch of one with shape (1, 4). For the square layer, the right answer for example 2 is (1,10,19)(1,10,19) and the wrong one is (3,6,9)(3,6,9), with no error. In the last two lines the correct bias gives a row (1,2,3,4)(1,2,3,4) and the column bias gives (1,1,1,1)(1,1,1,1).

Go deeper Putting the bias inside the weights

The bias can be absorbed into the weight matrix by adding one input that is always 1. Append a column of ones to X\mathbf{X} (the shape becomes (N,din+1)(N,d_{\text{in}}+1)) and append b\mathbf{b} as an extra column of W\mathbf{W} (the shape becomes (dout,din+1)(d_{\text{out}},d_{\text{in}}+1)). Then one product does everything:

(X1)(Wb)⊤=XW⊤+1b⊤\begin{aligned} \begin{pmatrix}\mathbf{X}&\mathbf{1}\end{pmatrix}\begin{pmatrix}\mathbf{W}&\mathbf{b}\end{pmatrix}^\top\\ =\mathbf{X}\mathbf{W}^\top+\mathbf{1}\mathbf{b}^\top \end{aligned}

For the first example of this lesson, with X\mathbf{X} extended to (10−112101)\begin{pmatrix}1&0&-1&1\\2&1&0&1\end{pmatrix}, the product is again (8181433)\begin{pmatrix}8&18\\14&33\end{pmatrix}. This is a convenient trick for proofs and for old textbooks, because it removes the bias from the formulas. Libraries keep the bias separate, as the parameter counts above assume.

Go deeper The layer in einsum

einsum (P2.3) names every axis. With n for the example, d for the input feature and o for the output neuron:

Z = np.einsum('nd,od->no', X, W) + b       # same as X @ W.T + b

Multiply X[n, d] by W[o, d], add up over the repeated d, and keep n and o. No transpose is written, because the letters say which axis is which. For P1.B15’s example it gives (8181433)\begin{pmatrix}8&18\\14&33\end{pmatrix}.

Go deeper More leading axes: batches of sequences

A layer acts on the last axis only. If the input has shape (B,T,d)(B,T,d) (a batch of BB sequences of TT tokens, whose vectors P4.21 explains), the layer X @ W.T + b gives (B,T,dout)(B,T,d_{\text{out}}): the matrix product treats the leading axes as batch axes (P1.B14), and PyTorch’s nn.Linear accepts any number of them. The einsum is np.einsum('...d,od->...o', X, W) + b. A transformer applies layers like this to every token of every sequence at once (P7.3). The rule is the same as in this lesson: the last size changes, and the leading sizes pass through.

What the forward pass must remember

During training the forward pass is followed by the backward pass (P4.8), and the backward pass needs numbers from the forward pass. The multiply rule of P4.8 says that the gradient of a weight uses the other factor of the product. For Z=XW⊤+b\mathbf{Z}=\mathbf{X}\mathbf{W}^\top+\mathbf{b} that other factor is the layer’s input. So the gradient for W2\mathbf{W}_2 needs H\mathbf{H}, the gradient for W1\mathbf{W}_1 needs X\mathbf{X}, and the ReLU needs to know which entries of Z1\mathbf{Z}_1 were positive. A training forward pass therefore keeps X\mathbf{X}, Z1\mathbf{Z}_1, H\mathbf{H} and the probabilities, and these tables grow with NN. (P4.10 builds this by hand.) When a network is only used to predict, each table can be discarded as soon as the next layer has used it, which is one reason training needs much more memory than prediction (P10.B4).

Depth: three ways to see it

Intuition

Picture a spreadsheet with one row per example. A layer is a formula applied to the whole sheet at once, and it gives a new sheet with the same rows and a different number of columns. The picture fails for batch normalization (P4.19), where the rows do talk to each other.

Math

Write H0=X\mathbf{H}_0=\mathbf{X} with shape (N,d0)(N,d_0). Layer ℓ\ell has Wℓ\mathbf{W}_\ell of shape (dℓ,dℓ−1)(d_\ell,d_{\ell-1}) and bℓ\mathbf{b}_\ell of shape (dℓ,)(d_\ell,), and

Zℓ=Hℓ−1Wℓ⊤+1bℓ⊤Hℓ=fℓ(Zℓ)\begin{aligned} \mathbf{Z}_\ell&=\mathbf{H}_{\ell-1}\mathbf{W}_\ell^\top+\mathbf{1}\mathbf{b}_\ell^\top\\ \mathbf{H}_\ell&=f_\ell(\mathbf{Z}_\ell) \end{aligned}

where 1\mathbf{1} is a column of NN ones, which spells out the broadcast. Then Hℓ\mathbf{H}_\ell has shape (N,dℓ)(N,d_\ell). The parameters number ∑ℓdℓ(dℓ−1+1)\sum_\ell d_\ell(d_{\ell-1}+1), and the forward pass takes about N∑ℓdℓdℓ−1N\sum_\ell d_\ell d_{\ell-1} multiply-adds. For one example, take row ii: hℓ=fℓ(Wℓhℓ−1+bℓ)\mathbf{h}_\ell=f_\ell(\mathbf{W}_\ell\mathbf{h}_{\ell-1}+\mathbf{b}_\ell), the formula of P4.3.

Code

The same layer in PyTorch (run on the machine used for this lesson, PyTorch 2.9; PyTorch cannot run in the browser, so this block is shown as text):

import torch

layer = torch.nn.Linear(3, 4)               # d_in = 3, d_out = 4
print(layer.weight.shape, layer.bias.shape)
x = torch.randn(5, 3)                       # N = 5 examples
print(torch.allclose(layer(x), x @ layer.weight.T + layer.bias))
print(layer(torch.randn(3)).shape, layer(torch.randn(2, 7, 3)).shape)
torch.Size([4, 3]) torch.Size([4])
True
torch.Size([4]) torch.Size([2, 7, 4])

The weight is (dout,din)(d_{\text{out}},d_{\text{in}}), the layer equals x @ W.T + b, a single example of shape (3,) gives (4,), and extra leading axes pass through. P2.6 uses this layer in a full training loop.

Common mistakes

Quiz

Check your understanding

  1. A PyTorch layer is nn.Linear(784, 128) and the input has shape (32, 784). What are the shape of its weight and the shape of its output?

  2. A layer has 20 inputs and 30 neurons, with a bias for each neuron. How many parameters does it have, for a batch of 16 examples?

  3. A batch has N = 5 examples and a layer has 5 outputs, so Z has shape (5, 5). By mistake the bias has shape (5, 1), a column. What happens in Z + b?

  4. P holds the predicted probabilities for N examples and K classes, with shape (N, K). You compute the softmax with axis=0 instead of axis=1. What goes wrong?

  5. In a batch of 8 examples through a dense layer and a ReLU, you change only the features of example 3. Which rows of the output change?

Exercises

  1. Compute the entry of Z1\mathbf{Z}_1 for example 2, (2,1,0)(2,1,0), and neuron 4, whose weights are (−1,0,1)(-1,0,1) and whose bias is 00. Then apply the ReLU.
    Show answer(2,1,0)⋅(−1,0,1)+0=−2+0+0=−2(2,1,0)\cdot(-1,0,1)+0=-2+0+0=-2. The ReLU turns −2-2 into 00. This is the last entry of the second row of Z1\mathbf{Z}_1 and of H\mathbf{H}.
  2. A network has 10 inputs, a hidden layer of 5 neurons and 3 outputs, and it processes a batch of N=32N=32. Give the shape of X\mathbf{X}, W1\mathbf{W}_1, b1\mathbf{b}_1, Z1\mathbf{Z}_1, W2\mathbf{W}_2 and Z2\mathbf{Z}_2, and the number of parameters.
    Show answerX\mathbf{X} is (32,10)(32,10), W1\mathbf{W}_1 is (5,10)(5,10), b1\mathbf{b}_1 is (5,)(5,), Z1\mathbf{Z}_1 is (32,5)(32,5), W2\mathbf{W}_2 is (3,5)(3,5) and Z2\mathbf{Z}_2 is (32,3)(32,3). Parameters: 5⋅10+5=555\cdot10+5=55 and 3⋅5+3=183\cdot5+3=18, so 7373, whatever the batch size.
  3. A colleague writes Z1 = X @ W1 + b1 with X of shape (4,3)(4,3), and W1 of shape (4,3)(4,3) as in this lesson. What happens? What if the first layer had 3 neurons, so W1 was (3,3)(3,3)?
    Show answerWith (4,3)(4,3) and (4,3)(4,3) the inner sizes are 33 and 44, so NumPy raises an error. With a (3,3)(3,3) weight matrix the product (4,3)⋅(3,3)(4,3)\cdot(3,3) is legal and gives a (4,3)(4,3) result, but it is XW1\mathbf{X}\mathbf{W}_1 instead of XW1⊤\mathbf{X}\mathbf{W}_1^\top: the numbers are wrong (unless the matrix happens to be symmetric), and there is no error to warn you.
  4. How many multiply-adds does the forward pass of the 784→128→10784\to128\to10 network need for a batch of N=64N=64, and how many parameters does it have?
    Show answerThe two products need 64⋅784⋅128=6,422,52864\cdot784\cdot128=6{,}422{,}528 and 64⋅128⋅10=81,92064\cdot128\cdot10=81{,}920, so 6,504,4486{,}504{,}448 (about 6.5 million). The parameters are 784⋅128+128=100,480784\cdot128+128=100{,}480 and 128⋅10+10=1,290128\cdot10+10=1{,}290, so 101,770101{,}770. Doubling NN doubles the multiply-adds and leaves the parameters unchanged.
  5. The losses of the first three examples of the lesson’s batch are 0.07890.0789, 1.70141.7014 and 0.00020.0002. What is the batch loss for a batch of just these three? Why is the mean used and not the sum?
    Show answer(0.0789+1.7014+0.0002)/3=0.5935(0.0789+1.7014+0.0002)/3=0.5935. With the sum, the loss and its gradient would grow in proportion to NN, so a learning rate chosen for one batch size would be too large or too small for another. The mean keeps the scale the same.

Next: P4.6 compares loss functions, and P4.7 and P4.8 run the same network backward to find the gradient of every weight, using the matrices stored here. P4.10 builds this network from scratch in NumPy and trains it on a real data set, and P2.6 shows nn.Linear doing the same work in PyTorch.

Key takeaways

  • One layer for one example is z=Wx+b\mathbf{z}=\mathbf{W}\mathbf{x}+\mathbf{b} with W\mathbf{W} of shape (dout,din)(d_{\text{out}},d_{\text{in}}): each row of W\mathbf{W} is one neuron. For a batch, stack the examples as the rows of X\mathbf{X} with shape (N,din)(N,d_{\text{in}}) and compute Z=XW⊤+b\mathbf{Z}=\mathbf{X}\mathbf{W}^\top+\mathbf{b} with shape (N,dout)(N,d_{\text{out}}), where the bias of shape (dout,)(d_{\text{out}},) is broadcast down the rows.
  • The two conventions give the same numbers, transposed: (XW⊤)⊤=WX⊤(\mathbf{X}\mathbf{W}^\top)^\top=\mathbf{W}\mathbf{X}^\top. Most maths texts and softmax regression (P3.A8) use column vectors. NumPy and PyTorch code uses row batches, and PyTorch's nn.Linear stores its weight as (dout,din)(d_{\text{out}},d_{\text{in}}) and computes xW⊤+b\mathbf{x}\mathbf{W}^\top+\mathbf{b}, while Keras's Dense stores the kernel as (din,dout)(d_{\text{in}},d_{\text{out}}) and needs no transpose.
  • An activation acts on each entry separately and keeps the shape. A network is a chain: H=f(XW1⊤+b1)\mathbf{H}=f(\mathbf{X}\mathbf{W}_1^\top+\mathbf{b}_1) and P=softmax(HW2⊤+b2)\mathbf{P}=\mathrm{softmax}(\mathbf{H}\mathbf{W}_2^\top+\mathbf{b}_2). The batch size NN passes through unchanged; only the last size changes, from each layer's dind_{\text{in}} to its doutd_{\text{out}}, and the inner sizes of neighbouring products must match.
  • In a dense layer, row ii of the output depends only on row ii of the input: the examples do not mix. Softmax is taken along each row, and the loss is the average of the NN per-example losses. In the lesson's small network of 3→4→23\to4\to2 with N=4N=4, the loss is 0.45260.4526.
  • A layer has dindout+doutd_{\text{in}}d_{\text{out}}+d_{\text{out}} parameters, whatever the batch size, and costs about N dindoutN\,d_{\text{in}}d_{\text{out}} multiply-adds. The 3→4→23\to4\to2 network has 2626 parameters and 8080 multiply-adds for N=4N=4.
  • One product on the whole batch replaces a Python loop over examples, gives the same numbers and is typically several times faster. The forward pass must keep its layer inputs and activations, because the backward pass uses them.
  • The classic shape bugs: a missing transpose (an error, or silently wrong when the layer is square), a bias of shape (dout,1)(d_{\text{out}},1) (silently wrong when N=doutN=d_{\text{out}} or N=1N=1), a missing batch axis, and softmax over the wrong axis. Print shapes and assert them.
Found a mistake? Tell us