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, . A layer is neurons that look at the same input. Stack their weight vectors as the rows of a matrix of shape , and all the dot products come out of one product (P1.B5):
P1.B15 worked an example: , and give . Row 1 of is neuron 1: , and .
For a batch, stack the examples as the rows of , with shape (P1.B5; is the number of rows, the batch size of training). The same P1.B15 layer on the examples and is
Entry of is the dot product of example with neuron (example 2, neuron 2: ). The transpose is there because keeps one neuron per row and the product needs one per column. The bias of shape is broadcast down the rows (P1.B14): align the shapes from the right, and the row is stretched over every example. The shape rule is
The inner sizes must match, and passes through untouched: a layer changes the number of columns, not the number of rows. And the rows do not mix: row of is computed from row of 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 , and has shape . 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 , with shape , and the layer is , where is a column of shape stretched across the columns.
- Row-batch convention. An example is a row, a batch is with shape , and the layer is . 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: . The matrix itself is the same in both, with the neurons as rows. That is why the row-batch formula has a : it is the price of keeping the same .
What the libraries do:
- PyTorch. The documentation of
nn.Lineargives . 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 bein_features. So the weight is as in the column convention, and the layer is applied to rows. - Keras. The documentation of
Densegivesoutput = activation(dot(input, kernel) + bias). Its kernel has shape(input_dim, units), which is 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 table of numbers goes in and a table comes out. For ReLU it turns each negative entry into and keeps the rest.
A network is these two steps repeated. The layers of P4.3, and , become for a whole batch:
The output of one layer is the input of the next: has one row per example, just as did. Each row of is the of P4.3 for that example. The chain of shapes works out like a train of coupled wagons: is , the first weight matrix transposed is , so is ; the next one is , so the output is . The inner sizes always cancel, and what is left is 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 from 1 to 4 and which example to follow (its row is pink). The numbers are the forward values, in blue.
Things to try (the weights are fixed, so these numbers repeat):
- With press Step once. The product has shape , and its second row is : example 2 through the four neurons. Press Step once more. The ReLU crosses out four entries (the three s and the ) and turns them into . The shape does not change.
- Choose , then . The matrices lose rows, and the weight matrices do not change at all. The weights have no in their shape: the same weights serve any batch size.
- 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.
- On the last stage (), example 2 has probabilities but its true class is 1, so its loss is much bigger than the others. The average loss is . Change and the average changes with it.
The worked network, with every shape
The shapes of the whole network for examples, 3 inputs, 4 hidden neurons and 2 outputs. Weights and biases are the learned part; the matrices with an in them are made fresh for each batch.
- : .
- Layer 1: is and is . The product is , and is .
- ReLU: is .
- Layer 2: is and is . The product is , and is .
- Softmax: is .
The numbers. The four examples are the rows of , and the weights of the four hidden neurons are the rows of :
Check one entry by hand: example 3 is and neuron 3 has weights and bias , so . That is the third entry of the third row of . The full results:
The second layer has and :
The cell below runs all of it, and prints the same matrices, the probabilities and the loss.
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 and for example 1, and for example 2, and so on (example 3 shows and because its probabilities, and , round to those). Each row sum is . The losses are , , and with mean (example 3’s loss is , which rounds to at three decimals). The loop gives for example 2, which is the second row of . 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 classes it computes 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 above, row 1 is , whose probabilities are and , and the rows of add up to 1. In NumPy this is a sum along axis=1, with keepdims=True so that the 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 with true class has (P3.A8), and
With the true classes for the four examples, the four losses are , , and , and the average is . Example 2 is the one the network gets wrong (it gives class 0 the probability ), 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: weights and biases.
The layer has , and the layer has , so the network has parameters. A batch has examples but the parameter count does not depend on : the same weights are used for every row. A layer from inputs (a image, P1.B1) to neurons has , and a layer from to adds , for parameters.
The cost of a forward pass is the arithmetic. Each of the entries of is a dot product of pairs of numbers, so the product costs about multiply-adds (P1.B6 for the product, P1.G4 for cost in general). For the small network with that is for layer 1 and for layer 2, in all. The bias addition and the activation touch each entry once, and they are small next to the products. With the network needs multiply-adds, about 6.5 million. The cost grows in proportion to , 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 is used 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 examples, features and neurons. On the machine used for this lesson (CPython and NumPy, not the browser), the loop took about s and the single product about 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.
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 @ WwhereWis stored as raises an error when (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 (or ). If it is (a column), broadcasting adds the bias entry to row instead of column . It raises an error for most sizes, but it runs silently when (as in the lesson’s example) and also when , where the result even has the wrong shape . 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 withaxis=1on a(d_out,)array raises an error, and.shape[0]isd_outwhere you expected the batch size. A batch of one still needs its axis. - Softmax over the wrong axis. On a array the probabilities must add to 1 along the class axis (
axis=1). Alongaxis=0they 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.
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 and the wrong one is , with no error. In the last two lines the correct bias gives a row and the column bias gives .
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 (the shape becomes ) and append as an extra column of (the shape becomes ). Then one product does everything:
For the first example of this lesson, with extended to , the product is again . 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 + bMultiply 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 .
Go deeper More leading axes: batches of sequences
A layer acts on the last axis only. If the input has shape (a batch of sequences of tokens, whose vectors P4.21 explains), the layer X @ W.T + b gives : 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 that other factor is the layer’s input. So the gradient for needs , the gradient for needs , and the ReLU needs to know which entries of were positive. A training forward pass therefore keeps , , and the probabilities, and these tables grow with . (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 with shape . Layer has of shape and of shape , and
where is a column of ones, which spells out the broadcast. Then has shape . The parameters number , and the forward pass takes about multiply-adds. For one example, take row : , 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 , 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
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?PyTorch stores the weight as (out_features, in_features) and computes x Wᵀ + b, so the output keeps the 32 examples as rows and has 128 columns. A weight of (784, 128) is the Keras kernel layout, which is used without a transpose. An output of (128, 32) would put the examples along the columns, which the row-batch convention does not do. The weight cannot have 32 in its shape, because the batch size is not a parameter.
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?
The weights are 20 times 30 = 600 and the biases are 30, so 630, whatever the batch size. The 600 leaves out the biases. The 620 adds a bias for each input instead of each neuron. The 10,080 is 16 times 630: the parameter count does not depend on the number of examples.
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?Broadcasting stretches a column across the columns, so row i of Z gets the single number b[i] added to all of its entries, which is not what the layer means. An error only appears when the sizes differ, and here they are both 5, which is why this bug is quiet. NumPy does not transpose anything on its own. The result keeps the shape (5, 5).
P holds the predicted probabilities for N examples and K classes, with shape (N, K). You compute the softmax with
axis=0instead ofaxis=1. What goes wrong?The softmax must normalize over the classes of one example, which is the row. Along axis 0 it normalizes over the examples for each class, so the rows no longer add to 1 and each example is affected by the rest of the batch. The two axes give different numbers in general. NumPy allows any axis. The result is not uniform: the entries are still ordered by their scores, only normalized the wrong way.
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?
Each row of the output is computed from the same row of the input, so the other rows keep their values. Sharing a matrix product does not mix the rows. The order of the examples in the table has no meaning to the layer, so neither the rows after nor the rows before example 3 are affected.
Exercises
- Compute the entry of for example 2, , and neuron 4, whose weights are and whose bias is . Then apply the ReLU.
Show answer
. The ReLU turns into . This is the last entry of the second row of and of . - A network has 10 inputs, a hidden layer of 5 neurons and 3 outputs, and it processes a batch of . Give the shape of , , , , and , and the number of parameters.
Show answer
is , is , is , is , is and is . Parameters: and , so , whatever the batch size. - A colleague writes
Z1 = X @ W1 + b1withXof shape , andW1of shape as in this lesson. What happens? What if the first layer had 3 neurons, soW1was ?Show answer
With and the inner sizes are and , so NumPy raises an error. With a weight matrix the product is legal and gives a result, but it is instead of : the numbers are wrong (unless the matrix happens to be symmetric), and there is no error to warn you. - How many multiply-adds does the forward pass of the network need for a batch of , and how many parameters does it have?
Show answer
The two products need and , so (about 6.5 million). The parameters are and , so . Doubling doubles the multiply-adds and leaves the parameters unchanged. - The losses of the first three examples of the lesson’s batch are , and . What is the batch loss for a batch of just these three? Why is the mean used and not the sum?
Show answer
. With the sum, the loss and its gradient would grow in proportion to , 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.