Module 0

Gradients and a tiny autograd

Every model in this course learns the same way: compute a number that says how wrong it is, find out how that number changes when each parameter changes, and nudge the parameters downhill. This module builds the machine that does the middle step.

Why it matters

A modern network has millions to billions of parameters, and training needs the derivative of one loss with respect to all of them, thousands of times over. Nobody derives those by hand. Reverse-mode automatic differentiation gets every one of them in a single backward sweep that costs about as much as computing the loss itself. Once you have written it yourself, in about 60 lines, nothing later in the course is magic: backpropagation, attention and the Jacobian lens are all this one algorithm applied to bigger graphs.

The idea

The derivative $\partial y / \partial x$ is a sensitivity: change $x$ by a small $\varepsilon$ and $y$ changes by about $\varepsilon \cdot \partial y/\partial x$. For a function of many inputs, the vector of all those sensitivities is the gradient, and it points in the direction of steepest increase.

Any formula a program can evaluate breaks down into elementary steps: an addition, a multiplication, a $\tanh$. Drawing each intermediate value as a node, with arrows from the values it was computed from, gives a computation graph. Take one neuron:

$$y = \tanh(w_1 x_1 + w_2 x_2 + b).$$

Its graph has five inputs and five intermediate values: two products, two sums and the $\tanh$. Each step is simple enough that its derivative is known by heart:

StepLocal derivatives
$v = a + b$$\partial v/\partial a = 1,\quad \partial v/\partial b = 1$
$v = a \cdot b$$\partial v/\partial a = b,\quad \partial v/\partial b = a$
$v = \tanh(a)$$\partial v/\partial a = 1 - \tanh^2(a) = 1 - v^2$

The chain rule stitches the local facts into global ones. Write $\bar v = \partial y/\partial v$ for the sensitivity of the final output to a node $v$. If $v$ feeds into nodes $u_1, \dots, u_k$, then

$$\bar v \;=\; \sum_{i=1}^{k} \bar u_i \,\frac{\partial u_i}{\partial v}.$$

That equation is the whole algorithm. Start with $\bar y = 1$. Visit the nodes in reverse order, outputs before inputs, so that by the time a node is visited every node it feeds has already reported in. At each node, multiply the incoming $\bar v$ by each local derivative and add the result to the corresponding input's total. When the sweep reaches the inputs, each one holds its gradient.

In code, each operation creates its output and attaches a small function that knows how to push the output's gradient back to its inputs. Here is addition:

def __add__(self, other):
    out = Value(self.data + other.data, (self, other), '+')
    def _backward():
        self.grad += out.grad      # local derivative is 1
        other.grad += out.grad     # local derivative is 1
    out._backward = _backward
    return out

Calling backward() on the final value sorts the graph so that every node comes after the nodes it depends on, sets the final gradient to 1, and calls each _backward in reverse.

Why backwards?

You could instead push derivatives forwards from one input at a time (forward mode), but that takes one pass per input. Going backwards from the single output takes one pass in total, whatever the number of inputs, at a small constant multiple of the cost of the forward computation. Machine learning has many parameters and one loss, so reverse mode is the right fit.

How to check a gradient

The definition of the derivative gives an independent check that needs no cleverness, the central finite difference:

$$\frac{\partial f}{\partial x} \approx \frac{f(x + h) - f(x - h)}{2h}, \qquad \text{error } O(h^2).$$

It needs two evaluations of $f$ per input, so it is far too slow for training, and with $h$ too small it drowns in rounding error ($h \approx 10^{-5}$ works well in double precision). As a test it is ideal: if your backward() disagrees with it, your backward() is wrong. Every gradient in this course, including the library behind the demos, is tested this way.

Live demo: gradients flowing back

One neuron as a computation graph

Gradient of y with respect to each input: autograd compared with finite differences
InputValue∂y/∂input, backward pass∂y/∂input, finite difference
Each box shows a value (middle line) and its gradient ∂y/∂(that value) once the backward pass has reached it. The finite-difference column is computed independently by re-running the forward pass with each input nudged by ±10⁻⁵.

Try this

  1. Set x₁ to 0 and step all the way back. What is ∂y/∂w₁, and why does it not depend on anything else in the graph?
  2. Reset, then push b up to 2. Watch what happens to every gradient. The neuron is saturated: $1 - y^2$ is close to zero, and nothing upstream can learn through it.
  3. Before stepping, predict the sign of ∂y/∂x₂. Then flip the sign of w₂ and predict again.

Exercise

Finish the Value class

Below is a complete scalar autograd engine except for two pieces: the backward step for * and the backward step for tanh. Fill in the two places marked TODO. The hidden tests build several expressions, call backward(), and compare every gradient with a finite difference.

Check yourself

Why does every _backward use += rather than =?

A value can feed into more than one later step. The chain rule says its gradient is the sum of one contribution per use. With =, each use would overwrite the previous one; a * a would report a gradient of $a$ instead of $2a$.

A function has one million inputs and one output. How many passes does forward mode need for the full gradient? Reverse mode?

Forward mode needs one pass per input: a million. Reverse mode needs one backward pass, because it propagates the sensitivity of the single output to everything at once. With many outputs and few inputs the comparison flips.

Why must nodes be visited in reverse topological order?

A node may only push its gradient to its inputs once its own gradient is final, which means every node that consumes it has already been visited. Reverse topological order guarantees exactly that.

Where this leads

You now have a way to get the gradient of any expression. Module 1 uses it for the first time in earnest: gradient descent on the two losses that the rest of the course is built on, squared error and cross-entropy.

Sources: A. G. Baydin, B. A. Pearlmutter, A. A. Radul and J. M. Siskind, “Automatic differentiation in machine learning: a survey”, Journal of Machine Learning Research 18 (2018); A. Griewank and A. Walther, Evaluating Derivatives, 2nd ed., SIAM (2008), for the cost of reverse mode. The Value class follows the design of Andrej Karpathy’s micrograd.