The Chain Rule and Automatic Differentiation
How neural networks compute the gradients of millions of parameters efficiently.
The rule
If \(y = f(u)\) and \(u = g(x)\):
$$\frac{dy}{dx} = \frac{dy}{du}\cdot\frac{du}{dx}$$
and for vectors it becomes a product of Jacobian matrices.
The computational graph
Let us take \(L = (wx + b – y)^2\):
- \(z = wx + b\)
- \(e = z – y\)
- \(L = e^2\)
Backpropagation: \(\partial L/\partial e = 2e\), then \(\partial L/\partial z = 2e\), then \(\partial L/\partial w = 2e\,x\) and \(\partial L/\partial b = 2e\).
Checking with PyTorch
import torch
x, y = torch.tensor(2.0), torch.tensor(7.0)
w = torch.tensor(1.5, requires_grad=True)
b = torch.tensor(0.5, requires_grad=True)
L = (w * x + b - y) ** 2
L.backward()
print(w.grad, b.grad) # 2e·x and 2e where e = 3.5 - 7 = -3.5Why reverse mode?
| Mode | Cost | Suits |
|---|---|---|
| Forward | One pass per input | Few inputs and many outputs |
| Reverse | One pass per output | One output and many parameters, that is, training |
Vanishing gradients result from multiplying a large number of derivatives smaller than 1 across the layers; that is why the ReLU function and residual connections helped in training deep networks.
Lesson terms
- Automatic differentiation
- Computing exact derivatives automatically from a record of the arithmetic operations, without manual differentiation or numerical approximation.
- The chain rule
- A differentiation rule for computing the derivative of a composite function as the product of the derivatives of its components.
Abstract
The chain rule computes the derivative of a composite function by multiplying local derivatives. A neural network is a long composition of simple functions, and backpropagation is a systematic application of the chain rule from the output to the input. Reverse-mode automatic differentiation computes the gradient of a single scalar output with respect to all the parameters at a cost of the same order as the forward computation itself.
Review questions
-
Why is reverse-mode automatic differentiation preferred in deep learning?
Because we have one output (the loss) and many parameters, and reverse mode computes all the gradients in a single backward pass.
-
What is the difference between automatic differentiation and numerical differentiation?
Automatic differentiation is exact up to machine precision and applies the chain rule, while numerical differentiation is an approximation by finite differences, slower and less accurate.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate