Applications of Machine Learning

Lecture 8 · Animations

PyTorch

Backpropagation is reverse-mode automatic differentiation, and the training loop is five lines around it. Two pictures: the deck's worked example swept forward and back one node at a time; and the loop itself, run one line at a time, with and without zero_grad(). Press Step to advance one unit and read what happened; press Play to let it run.

All data on this page is synthetic, generated in your browser from a fixed seed, so Reset always gives back the same picture.

1The two sweeps on a graph

The deck's example, $L = w^2$ with $w = xy + \sin x$. Each box is a node; each edge carries its local derivative. The forward sweep fills in values left to right. Then the seed $\bar L = 1$ is placed at the loss, and the reverse sweep fills in adjoints $\bar u = \partial L/\partial u$ right to left, each one a product of an adjoint already known and one local derivative. Last, a finite-difference check.

The mathematics

The local derivatives, each needing only the values of its own node:

$$\frac{\partial u}{\partial x} = y,\ \ \frac{\partial u}{\partial y} = x,\ \ \frac{\partial s}{\partial x} = \cos x,$$ $$\frac{\partial w}{\partial u} = \frac{\partial w}{\partial s} = 1,\ \ \frac{\partial L}{\partial w} = 2w.$$

The chain rule for a node $a$ whose value feeds nodes $c_1,\dots,c_k$:

$$\bar a = \sum_{i=1}^{k} \bar c_i\,\frac{\partial c_i}{\partial a},$$

a sum over outgoing edges — which is why $\bar x$ has two terms. The check is the forward difference $\bigl(L(x+h, y) - L(x, y)\bigr)/h = \partial L/\partial x + \tfrac{h}{2}\,\partial^2 L/\partial x^2(\xi)$ by Taylor's theorem, plus a rounding error of order $\epsilon L/h$ with $\epsilon \approx 1.1\times10^{-16}$.

Watch for
  • Every value is computed once in the forward sweep and then used again in the reverse one ($y$, $x$, $\cos x$, $2w$). That is why the forward values must be kept.
  • $\bar x$ is filled in two steps: once through the product, once through the sine. At the deck's point the two contributions are $41.4558$ and $-5.7506$.
  • One reverse sweep gives both $\partial L/\partial x$ and $\partial L/\partial y$. The finite difference needs a separate evaluation of $L$ for each.
Try this
  1. Play to the end at $x = 2$, $y = 3$ and compare with the deck: $L = 47.7384$, $\bar x = 35.7052$, $\bar y = 27.6372$.
  2. Move $h$ from $10^{-1}$ down to $10^{-13}$: the finite-difference error falls in proportion to $h$ until about $10^{-7}$, then rises again as cancellation takes over. No $h$ reaches the autodiff answer's accuracy.
  3. Set $x = 1.6$, where $\cos x \approx -0.03$: the edge through the sine now carries almost nothing, and $\bar x$ is nearly the product term alone.

2The training loop, one line at a time

A model $\hat y = w x + b$ trained by plain SGD (torch.optim.SGD) on 24 points in mini-batches of 6. Each Step runs one line of the loop — the highlighted box — and the side panel shows what it changed. Tick skip to delete opt.zero_grad(): the loop still runs and the loss still goes down at first. The dashed line and the green curve are the correct run, on the same batches.

The mathematics

For a batch $B$ the loss is the mean squared error $\ell = \frac{1}{|B|}\sum_{i\in B}(wx_i + b - y_i)^2$, with $\partial\ell/\partial w = \frac{2}{|B|}\sum_i r_i x_i$ and $\partial\ell/\partial b = \frac{2}{|B|}\sum_i r_i$, $r_i = wx_i+b-y_i$. backward() adds these to p.grad; step() sets $\boldsymbol\theta \leftarrow \boldsymbol\theta - \eta\,$p.grad.

Without zero_grad(), p.grad after step $t$ is $\mathbf{G}_t = \sum_{s\le t}\mathbf{g}_s$, so

$$\boldsymbol\theta_{t+1} - \boldsymbol\theta_t = (\boldsymbol\theta_t - \boldsymbol\theta_{t-1}) - \eta\,\mathbf{g}_t:$$

momentum with coefficient 1, i.e. no friction. For a quadratic loss with curvature $\lambda$ and full batches the error obeys $e_{t+1} = (2-\eta\lambda)e_t - e_{t-1}$, whose two characteristic roots have product 1; for $0 < \eta\lambda < 4$ both have modulus 1, so the oscillation never decays. With mini-batches each batch's noise is added to $\mathbf{G}_t$ and never removed, so the swings can grow.

Watch for
  • With zero_grad(), p.grad after backward() is this batch's gradient and nothing else. Without it the readout keeps the sum of every gradient so far.
  • Skipping it, the loss falls in the first iterations — at first faster than the correct run — and then swings up and down for ever instead of settling.
  • No line raises an error, and the loss is never NaN. The only evidence is the comparison with the correct curve.
Try this
  1. Step through one iteration line by line, then set Each Step runs to one iteration and play to 100. The correct loss settles near 0.05.
  2. Tick skip and play again: the red curve keeps swinging, and after 100 iterations it is still far above the green one.
  3. With skip ticked, raise $\eta$ to 0.3 and play to iteration 300: the swings grow until the loss is in the hundreds and the line leaves the data — and still nothing raises. Lowering $\eta$ to 0.02 does not cure it either: the swings are slower, and they persist.