Skip to content

Capstone 3: your own tensor autograd library

ready≈ 11.5 hoursNeeds: 3.2, 3.3, Capstone 2

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 C=AB\mathbf{C} = \mathbf{A}\mathbf{B}, the gradients are Aˉ=CˉB⊤\bar{\mathbf{A}} = \bar{\mathbf{C}}\mathbf{B}^\top and Bˉ=A⊤Cˉ\bar{\mathbf{B}} = \mathbf{A}^\top\bar{\mathbf{C}}; 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 y=log⁡softmax⁡(x)\mathbf{y} = \log\operatorname{softmax}(\mathbf{x}), the backward is xˉ=yˉ−softmax⁡(x)∑jyˉj\bar{\mathbf{x}} = \bar{\mathbf{y}} - \operatorname{softmax}(\mathbf{x})\sum_j \bar y_j. 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.

Capstone 3 stubs/cap3_tensorgrad.py

Loading 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.

Hints · unbroadcast 0/3 revealed
Hints · __mul__ 0/3 revealed
Hints · sum 0/3 revealed
Hints · log_softmax 0/3 revealed

Then train on MNIST (locally; MNIST is already cached if you did Capstone 2):

Terminal window
cd exercises && python projects/mnist_mlp_tensorgrad.py

It 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/?)
Finish the items above first.
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.