Neural networks · lesson 8 of 10
Parts in this lesson
Aself.grad = np.zeros_like(self.data)a gradient is an array with the same shape as the data
Bself.grad += out.grad @ other.data.Tthe backward pass of @ is two more matrix products
Cother.grad += unbroadcast(out.grad, other.shape)a stretched input sums its gradient back to its own shape
Doptimizer.zero_grad(); loss.backward(); optimizer.step()the training loop, in PyTorch’s words

Build simplenet, part 2: tensors

Last updated

Value from lesson 6.7 works, but one Python object per number is far too slow for a real network: the digits network of lesson 6.5 has over a thousand weights, and every step touches each of them hundreds of times. In this lesson you’ll rebuild simplenet on NumPy arrays. A Tensor holds a whole array, its operations are whole-array operations, and their backward passes are the matrix formulas of lesson 6.4. On top of it go Linear and MLP modules, a parameters() method, and an SGD optimiser: the same pieces, with the same names, as PyTorch.

By the end of this lesson you can

  • Write a Tensor class whose gradients are arrays of the same shape as its data
  • Find the gradients of @, sum and a broadcast +, and undo broadcasting with a sum
  • Build Linear and MLP modules with a parameters() method, and an SGD optimiser
  • Train a network on the moons with the loop predict, measure, zero_grad, backward, step

From numbers to arrays

A Value holds one number. Train lesson 6.5's 64 → 16 → 10 digits network with it and every weight, every input and every product is a separate Python object with its own closure: about 2,400 objects for each example (1,210 weights and biases, each in a product or a sum), rebuilt every step. NumPy does a whole matrix product in one call, in compiled code.

So the second half of simplenet keeps lesson 6.7's design and changes one thing: a Tensor holds an array. Its grad is an array of the same shape, because ∂L/∂Wij has one entry for each Wij. Each operation still records its parents and a _backward; backward() is the same depth-first search, keyed by id.

The forward formulas are lesson 6.1's, for a batch: Z=XW⊤+b, with X of shape (n,d), one row per example, and W of shape (k,d), one row per output unit, as PyTorch stores it.

Gradients of @, sum and broadcasting

Three rules cover a dense layer. Write G=∂L/∂C for the gradient arriving at an operation's output.

Matrix product. For C=AB, with A of shape (n,d) and B of shape (d,k):

∂L∂A=GB⊤,∂L∂B=A⊤G.

The shapes check themselves: G is (n,k), so GB⊤ is (n,k)(k,d)=(n,d), like A, and A⊤G is (d,n)(n,k)=(d,k), like B. It's lesson 6.4's δa⊤, for a whole batch at once. When you forget which way round it goes, the shapes tell you.

Sum. Every element counts once in the total, so each gets the arriving gradient: copy G back to the input's shape.

Broadcast add. X+b, with X of shape (5,3) and b of shape (3,), works because NumPy stretches b down the 5 rows. Each number of b was used 5 times, and by lesson 6.6's rule, gradients from every use add. So the gradient of b is the column sums of G:

∂L∂bj=∑i=1nGij.

Try other shapes of b:

Undoing broadcastingthe gradient of Z = X + b, sent back to b
gradient at Z, shape (4, 3)0.2−0.10.50.10.3−0.2−0.40.20.10.300.4→sum(axis=0): down each columnb's gradient, shape (3,)???Each number of b was copied to every cell of its colour, so it collects all their gradients.

A bias of shape (3,) is added to every row: NumPy stretches it down the 4 rows. So each bias number gets the sum of its column.

The rule in general: sum over every axis NumPy added in front, and over every axis that was 1 and got stretched. That's unbroadcast:

simplenet.ipynb

Now the Tensor class. Every + and * passes its gradients through unbroadcast, so any shapes NumPy accepts going forward come back right. T is a node too: the gradient of a transpose is the transpose of the gradient.

simplenet.ipynb

b.grad is 5, 5, 5, with b's own shape (3,): each bias number was added to all 5 rows of X. As in lesson 6.7, check a real gradient by nudging, here every entry of a weight matrix in a ReLU layer:

simplenet.ipynb

A difference of 6×10−10 over all 12 entries: the matrix rules and the nudges agree.

Linear and MLP modules

A layer is a weight matrix, a bias, and a forward pass. Wrap them in a class:

  • Linear(n_in, n_out) makes weight of shape (n_out, n_in) and bias of shape (n_out,), both uniform between −1/nin and 1/nin, PyTorch's start. Its forward pass is x @ self.weight.T + self.bias.
  • MLP(sizes) makes one Linear for each pair of neighbouring sizes, and its forward pass puts a ReLU between them, but not after the last one: the last layer's outputs are the logits, which go to the loss.
  • Module.__call__ runs forward, so model(X) works, as in PyTorch.

The loss is softmax cross-entropy, written as one node whose backward pass is lesson 3.11's (P−Y)/n. Doing it as one node is shorter and safer than chaining exp, sum and log, which can overflow (lesson 3.11 subtracts the biggest logit first for the same reason).

As a UML class diagram:

simplenet’s classes
100%
Tensor
  • +data: ndarray
  • +grad: ndarray
  • #_op
  • #_backward
  • +shape
  • +__init__(data, parents, op)
  • +__add__(other)
  • +__mul__(other)
  • +__matmul__(other)
  • +T()«property»
  • +sum(axis)
  • +relu()
  • +backward()
Module
  • +parameters()
  • +__call__(x)
SGD
  • +lr: list
  • +__init__(params, lr)
  • +step()
  • +zero_grad()
Linear
  • +weight: Tensor
  • +bias: Tensor
  • +__init__(n_in, n_out, rng)
  • +forward(x)
  • +parameters()
MLP
  • +layers: list
  • +__init__(sizes, rng)
  • +forward(x)
  • +parameters()
  • Class Tensor; attributes: data, grad, _op, _backward, shape; methods: __init__, __add__, __mul__, __matmul__, T, sum, relu, backward.
  • Class Module; no attributes of its own; methods: parameters, __call__.
  • Class Linear; inherits from Module; attributes: weight, bias; methods: __init__, forward, parameters.
  • Class MLP; inherits from Module; attributes: layers; methods: __init__, forward, parameters.
  • Class SGD; attributes: lr; methods: __init__, step, zero_grad.
  • Linear holds one Tensor in weight.
  • Linear holds one Tensor in bias.

The hollow-headed arrows say "is a kind of": Linear and MLP are Modules. The lines with a diamond say "holds": a Linear holds two Tensors, its weight and bias, and an MLP keeps a list of Linear layers.

parameters() and an SGD optimiser

To train, the loop needs every weight and bias in the model, however deep. Each module answers parameters(): a Linear returns its two tensors, and an MLP returns all of its layers' parameters in one list. Then an optimiser can step them without knowing anything about layers:

  • SGD.step() does θ←θ−η∇θL for each parameter.
  • SGD.zero_grad() sets every gradient back to 0 (lesson 6.7, step 6).
simplenet.ipynb

Two layers, four tensors: 16×2 weights and 16 biases, then 2×16 and 2, so 82 numbers. Now the whole loop, on the moons of lesson 6.5:

simplenet.ipynb

Loss 0.618 to 0.074, and 98.3% of the training points right after 500 steps. The loop is four lines, and they're the four lines of every PyTorch training loop in Stage 7: compute the loss, optimizer.zero_grad(), loss.backward(), optimizer.step(). You've now written every one of them yourself.

Wrong way: a bias gradient of shape (n, k)

Forget unbroadcast, and + gives the bias the whole (n,k) gradient:

simplenet.ipynb

Nothing complains yet. The gradient of a (3,) bias has 15 numbers, one for each place the bias was copied to. The step is where it breaks:

simplenet.ipynb

NumPy can't write a (5,3) array into a (3,) one. The error is reported at the step, but the bug is in +, in another method of another class. The rule that catches it every time: a gradient always has the shape of its data. Check it in a test.

Check what you learned

X is (32, 10) and W is (4, 10), and Z = X @ W.T. What shape is the gradient of W?
A bias b of shape (3,) is added to a (5, 3) batch. Why is b.grad the column sums of the arriving gradient?
Why does the MLP’s forward pass leave the ReLU off the last layer?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning