$ cat posts/neural-network-from-scratch.md

A neural network from scratch, down to the last gradient

#ml2 min read

Frameworks like PyTorch make training a network feel like magic: call loss.backward() and the gradients appear. I wanted to know exactly what happens inside that call, so I built Neural Lab, a small deep-learning engine written from scratch, and trained it on MNIST, the classic dataset of handwritten digits.

The whole trick: the chain rule

A network is a long chain of simple operations. Training needs the gradient of the loss $L$ with respect to every weight $w$, and the chain rule gives it one step at a time:

$$\frac{\partial L}{\partial w} = \frac{\partial L}{\partial y}\,\frac{\partial y}{\partial w}$$

Once you have the gradient, you nudge each weight downhill, scaled by the learning rate $\eta$:

$$w \leftarrow w - \eta\,\frac{\partial L}{\partial w}$$

Reverse-mode automatic differentiation records every operation as it runs, then walks the record backwards, applying the chain rule at each step. Here’s the core idea in a few lines of Python:

class Value:
    def __init__(self, data, parents=()):
        self.data, self.grad, self.parents = data, 0.0, parents
        self._backward = lambda: None

    def __add__(self, other):
        out = Value(self.data + other.data, (self, other))
        def _backward():
            self.grad += out.grad
            other.grad += out.grad
        out._backward = _backward
        return out

    def __mul__(self, other):
        out = Value(self.data * other.data, (self, other))
        def _backward():
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad
        out._backward = _backward
        return out

    def backward(self):
        order, seen = [], set()
        def visit(v):
            if v not in seen:
                seen.add(v)
                for p in v.parents:
                    visit(p)
                order.append(v)
        visit(self)
        self.grad = 1.0
        for v in reversed(order):
            v._backward()

x, w, b = Value(2.0), Value(-3.0), Value(1.0)
y = x * w + b
y.backward()
print(w.grad)   # 2.0, because dy/dw = x

Neural Lab does the same thing with whole tensors instead of single numbers, and adds what a real network needs: dense and convolutional layers, and the usual optimisers.

Trust, but check the gradients

A wrong gradient doesn’t crash anything. The network just learns badly, and you never find out why. So every operation is checked against a numerical estimate:

$$\frac{\partial f}{\partial x} \approx \frac{f(x+h) - f(x-h)}{2h}$$

All 49 gradient checks pass, and 24 results match an independent NumPy implementation. One check taught me something: for a deep network of sigmoids, the gradients were so tiny that I had to use a bigger step $h$. That’s the vanishing gradient problem, seen up close.

The result

A LeNet-style convolutional network reaches 98.7% accuracy on the 10,000 test digits after 3 passes over the training data, in about 13 seconds on my M1 MacBook.

My favourite part is the Draw station: write a digit with the mouse and see what the network thinks it is.