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 has one entry for each . 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: , with of shape , one row per example, and of shape , one row per output unit, as PyTorch stores it.
Gradients of @, sum and broadcasting
Three rules cover a dense layer. Write for the gradient arriving at an operation's output.
Matrix product. For , with of shape and of shape :
The shapes check themselves: is , so is , like , and is , like . It's lesson 6.4's , 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 back to the input's shape.
Broadcast add. , with of shape and of shape , works because NumPy stretches down the 5 rows. Each number of was used 5 times, and by lesson 6.6's rule, gradients from every use add. So the gradient of is the column sums of :
Try other shapes of :
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:
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.
b.grad is 5, 5, 5, with b's own shape : each bias number was added to all 5 rows of . As in lesson 6.7, check a real gradient by nudging, here every entry of a weight matrix in a ReLU layer:
A difference of 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)makesweightof shape(n_out, n_in)andbiasof shape(n_out,), both uniform between and , PyTorch's start. Its forward pass isx @ self.weight.T + self.bias.MLP(sizes)makes oneLinearfor 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__runsforward, somodel(X)works, as in PyTorch.
The loss is softmax cross-entropy, written as one node whose backward pass is lesson 3.11's . 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:
- +data: ndarray
- +grad: ndarray
- #_op
- #_backward
- +shape
- +__init__(data, parents, op)
- +__add__(other)
- +__mul__(other)
- +__matmul__(other)
- +T()«property»
- +sum(axis)
- +relu()
- +backward()
- +parameters()
- +__call__(x)
- +lr: list
- +__init__(params, lr)
- +step()
- +zero_grad()
- +weight: Tensor
- +bias: Tensor
- +__init__(n_in, n_out, rng)
- +forward(x)
- +parameters()
- +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 for each parameter.SGD.zero_grad()sets every gradient back to 0 (lesson 6.7, step 6).
Two layers, four tensors: weights and 16 biases, then and 2, so 82 numbers. Now the whole loop, on the moons of lesson 6.5:
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 gradient:
Nothing complains yet. The gradient of a bias has 15 numbers, one for each place the bias was copied to. The step is where it breaks:
NumPy can't write a array into a 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
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.
- NumPy: Broadcasting: the rules for stretching arrays, which the backward pass undoes
- PyTorch: torch.nn.Linear: weight of shape (out, in), the forward pass x Wᵀ + b, and the U(±1/√in) start
- PyTorch: torch.nn.Module: parameters(), and calling a module to run its forward
- Karpathy, micrograd: a tiny autograd engine: the scalar engine whose idea part 2 scales up to arrays