Mathematics and Statistics for AI Intermediate 12 minutes

The Chain Rule and Automatic Differentiation

How neural networks compute the gradients of millions of parameters efficiently.

Your progress in the track0%

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\):

  1. \(z = wx + b\)
  2. \(e = z – y\)
  3. \(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.5

Why reverse mode?

ModeCostSuits
ForwardOne pass per inputFew inputs and many outputs
ReverseOne pass per outputOne 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

  1. 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.

  2. 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

  1. Baydin et al. — Automatic Differentiation in Machine Learning: a Survey
  2. PyTorch — A Gentle Introduction to torch.autograd
  3. Goodfellow, Bengio & Courville — Deep Learning (Ch. 6.5)

Complete the lesson