5/32
Part 1 of 6 · The chain ruleLearn and do
Six rules cover every step in this network
Write dX for the gradient of the loss with respect to X. It's an array with the same shape as X.
| Forward | Backward, given dout |
|---|---|
out = a + b | da = dout, db = dout |
out = a * b (elementwise) | da = dout * b, db = dout * a |
out = np.maximum(a, 0) | da = dout * (a > 0) |
out = a @ W | da = dout @ W.T, dW = a.T @ dout |
out = a + b, with b broadcast over rows | db = dout.sum(axis=0) |
a feeds two operations | da is the sum of what each one sends back |
- An add passes the gradient through, unchanged.
- A multiply swaps: each input gets the other input times the gradient.
- ReLU is a gate. The gradient passes where the input was positive and stops everywhere else.
- A matmul is a multiply for whole arrays, so it swaps too. The shapes tell you where the transposes go.
The last row of the table needs a picture. A value that feeds two steps gets a gradient back from each:
forward, values backward, gradients
a feeds two steps: y = a × 4 = 12 and z = a + 1 = 4. Then L = y + z = 16.
That's why an autograd engine, the code that runs the backward pass for you in PyTorch, adds into each gradient instead of overwriting it.
In the editor, write grads(a, b) for L = a * b + a, where a is used twice.