Capstone 3: your own tensor autograd library
In 3.2 every node of the graph held one number. Real networks push whole arrays through each operation, so here you rebuild the same engine with a NumPy array in every node. The result, tensorgrad, is a few hundred lines and works the way PyTorch’s autograd does: a Tensor records how it was made, and loss.backward() fills in .grad for everything upstream.
Same engine, bigger nodes. backward() is unchanged from 3.2: build a topological order, seed the output’s gradient with ones, and call each node’s _backward in reverse. Each operation’s backward becomes a matrix formula. For , the gradients are and ; check the shapes and there is only one way to write them. A sum sends its gradient back to every element it added. Indexing scatters the gradient back with np.add.at, as the embedding did in 3.8.
Broadcasting is the new part. Adding a bias of shape (10,) to a batch of shape (128, 10) copies the bias into all 128 rows. Each copy affects the loss, so the bias gradient is the sum of the 128 row gradients. unbroadcast(grad, shape) sums over the extra leading axes and over every axis where the input had size 1. Every binary operation runs both input gradients through it. Without it the gradient has the wrong shape, or worse, a shape that happens to fit.
Log-softmax as one node. You could build log-softmax from exp, sum and log, but one fused node is faster and numerically stable. With , the backward is . Cross-entropy is then indexing and a mean, both already written.
Gradient-check everything. The tests check every operation, including each broadcasting case, against finite differences: your Capstone 1 checker, applied to whole arrays. They also run the expression from the micrograd README and compare it with micrograd’s numbers. The modules (Linear, ReLU, Sequential) and optimizers (SGD, Adam, ported from 3.3 to work on a list of Tensors) mirror torch.nn and torch.optim, so Part 4’s PyTorch code will look familiar.
stubs/cap3_tensorgrad.pyLoading starter file…
Prefer your own editor? Edit exercises/stubs/cap3_tensorgrad.py and run mlc check cap3. The tests are identical; import the results on the progress page.
Then train on MNIST (locally; MNIST is already cached if you did Capstone 2):
cd exercises && python projects/mnist_mlp_tensorgrad.pyIt trains a 784 → 256 → 10 network with ReLU and Adam for 8 epochs and reports test accuracy. The reference solution reaches about 98% in under a minute on a laptop CPU, against 92% for Capstone 2’s linear model. Module 3.7 already used PyTorch, and from Part 4 on every task does: its autograd works the same way as yours.
- not yet: All tests pass (0/?)
Learner log: time spent and points of confusion
Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.