Loss, gradients and autograd

Training lowers the loss by small steps against its gradient; backpropagation gives the slope for every weight at once.

Outcome: Apply the update w ← w − η ∇L and choose a learning rate; explain minibatches, Adam and learning-rate schedules; apply the chain rule through a small network and use autograd: requires_grad, backward(), zero_grad(); take gradients with respect to the inputs, not only the weights.

Builds on Neurons, layers and MLPs, Measuring error

The loss is one number that measures how far the predictions are from the data. For surrogates it is often the mean squared error of fitting a response surface. For a polynomial the best weights could be computed in one go; for a network they cannot, because the prediction is not linear in the weights. Training starts instead from random weights and improves them step by step.

The loss is a landscape over the weights: one dimension per weight, height = loss. Its slope at the current weights is the gradient.

DefinitionGradient

∇L\nabla L, the list of slopes of the loss along every weight, ∂L/∂wj\partial L / \partial w_j for each weight wjw_j. It points uphill.

Gradient descent takes a small step the other way:

w←w−η ∇L(w)w \leftarrow w - \eta \, \nabla L(w)
(4-2)
ww: all the weights. ∇L\nabla L: the gradient of the loss with respect to them. η\eta: the learning rate, the size of the step.

The learning rate η\eta is usually the first setting to tune. Too small, and progress is slow. Too large, and each step overshoots the valley floor: the weights zigzag from side to side, and beyond a limit they diverge. Figure 4-2 is the loss of a straight-line fit, y≈wx+by \approx w x + b, over six points: only two weights, so the landscape can be drawn as contours.

-10120123slope wintercept b
loss contours (MSE 0.02, 0.1, 0.3, 0.8, 1.6, 3)path of the descentminimum

Gradient descent on a two-weight loss: 25 steps from w = b = 0 at the chosen step size. They end at w = 1.39, b = 0.65, loss 0.008 (minimum 0.0010 at w = 1.51, b = 0.50).

Figure 4-2. Gradient descent on the loss of a straight-line fit over six points, drawn as contours over its two weights ww and bb; set the learning rate below the plot.

The valley is long, narrow and tilted because the two weights partly cancel: raise the slope ww, lower the intercept bb, and the line barely moves over these points. Along that direction the loss curves about eleven times less than across it. Small steps crawl along the floor; large steps bounce between the walls, and above η\eta ≈ 0.44 they diverge. Real networks have many such valleys at once, which is why the optimisers below adapt the step.

In practice

Computing the gradient over all the data for every step is slow. Stochastic gradient descent (SGD) uses a small random minibatch instead, for example 512 points: each step is cheaper and slightly noisy, and many more steps fit in the same time. One pass over all the data is an epoch. What counts as one example depends on the model: a design for a scalar model, a point for a neural field.

Adam (Kingma and Ba 2015) keeps running averages of each weight’s gradient and squared gradient and scales each weight’s step accordingly. That often helps when weights have very different sensitivities, though rescaling weights one by one does not remove a valley tilted across several of them.

A schedule lowers the learning rate during training: large steps early for fast progress, small steps late to settle into the minimum.

Example 4-2. Gradient descent on a straight-line fit, with NumPy
import numpy as np

# Six points on a line, with noise. Find w and b by
# gradient descent on the mean squared error.
x = np.array([0.0, 0.4, 0.8, 1.2, 1.6, 2.0])
y = np.array([0.52, 1.07, 1.73, 2.31, 2.86, 3.55])

w, b, lr = 0.0, 0.0, 0.11
for step in range(500):
    err = (w * x + b) - y
    loss = np.mean(err ** 2)
    # The gradient of the loss, then one step downhill.
    dw, db = 2 * np.mean(err * x), 2 * np.mean(err)2
    w, b = w - lr * dw, b - lr * db3
print(f"w = {w:.3f}, b = {b:.3f}, loss = {loss:.5f}")
  1. lr is the learning rate η\eta of Equation 4-2; the weights start at zero.
  2. The two slopes of the mean squared error: ∂L/∂w=2N∑ieixi\partial L/\partial w = \tfrac{2}{N} \sum_i e_i x_i and ∂L/∂b=2N∑iei\partial L/\partial b = \tfrac{2}{N} \sum_i e_i, with eie_i the error at point ii. Equation 4-4 derives the first.
  3. Equation 4-2 for both weights. The tuple assignment updates w and b together, from slopes computed at the old values.

Example 4-2 prints w = 1.507, b = 0.500, loss = 0.00100: after 500 steps of η\eta = 0.1 the line has settled. Here the gradient was written by hand; for a network that is impractical.

Backpropagation

The direct way to find the slope of the loss for one weight is to nudge the weight, recompute the loss, and divide. For the 4,417 weights of Example 4-1 that is 4,417 extra evaluations of the loss per step, and the result is only approximate. Networks in papers often have millions of weights.

A network is a chain of simple operations: multiply, add, activate, repeat, then compare with the data. The chain rule of calculus says that the slope of a chain is the product of the slopes of its links. For a weight ww that affects the loss LL only through the prediction y^\hat{y}:

∂L∂w=∂L∂y^ ∂y^∂w\frac{\partial L}{\partial w} = \frac{\partial L}{\partial \hat{y}} \, \frac{\partial \hat{y}}{\partial w}
(4-3)
Each factor is the local slope of one operation. For deeper weights the chain has more factors.

Backpropagation (Rumelhart et al. 1986) organises this.

DefinitionBackpropagation

A forward pass computes the prediction and stores every intermediate value. A backward pass then starts from the loss and walks back through the layers, multiplying local slopes as it goes; at each layer it reads off the gradient for that layer’s weights.

One backward pass gives every gradient, and the whole gradient costs a small multiple of one forward pass, however many weights there are: under six times in theory and typically two to three times (Baydin et al. 2018, section 3.2, after Griewank and Walther).

Backpropagation is reverse-mode differentiation, the same principle as the discrete adjoint.

By hand, for the line fit above: y^i=wxi+b\hat{y}_i = w x_i + b and L=1N∑i(y^i−yi)2L = \tfrac{1}{N} \sum_i (\hat{y}_i - y_i)^2. For point ii, ∂L/∂y^i=2(y^i−yi)/N\partial L / \partial \hat{y}_i = 2(\hat{y}_i - y_i)/N and ∂y^i/∂w=xi\partial \hat{y}_i / \partial w = x_i. Summing over the NN points gives

∂L∂w=1N∑i=1N2(y^i−yi) xi,\frac{\partial L}{\partial w} = \frac{1}{N} \sum_{i=1}^{N} 2 (\hat{y}_i - y_i) \, x_i,
(4-4)

the formula of callout 2 in Example 4-2. Example 4-3, below, checks that PyTorch gets the same number.

Autograd in PyTorch

PyTorch records the operations applied to any tensor created with requires_grad=True (model weights have it by default). Calling loss.backward() runs the backward pass and stores each gradient in the tensor’s .grad.

For prediction only, torch.no_grad() around the code stops the recording.

The same machinery gives gradients with respect to the inputs: how the predicted lift changes with the sweep, for example. These design sensitivities drive optimising on a surrogate, and derivatives of the predicted field with respect to the coordinates are what physics losses penalise.

Example 4-3. Autograd against the hand-derived gradient, in PyTorch
import torch

# Autograd records every operation, then applies the
# chain rule backwards.
x = torch.tensor([0.0, 0.4, 0.8, 1.2, 1.6, 2.0])
y = torch.tensor([0.52, 1.07, 1.73, 2.31, 2.86, 3.55])
w = torch.tensor(1.0, requires_grad=True)1
b = torch.tensor(0.0, requires_grad=True)

loss = torch.mean((w * x + b - y) ** 2)
# Fills w.grad and b.grad.
loss.backward()
err = (w * x + b - y).detach()2
# Autograd and the hand-derived gradient agree.
print(w.grad.item(), (2 * err * x).mean().item())
print(b.grad.item(), (2 * err).mean().item())

# Gradients with respect to the INPUT: how the output
# changes with the design.
torch.manual_seed(0)
net = torch.nn.Sequential(torch.nn.Linear(2, 16),
                          torch.nn.Tanh(),
                          torch.nn.Linear(16, 1))
design = torch.tensor([[0.2, -0.5]], requires_grad=True)
net(design).sum().backward()3
# One slope per design variable.
print(design.grad)4
  1. requires_grad=True tells autograd to record every operation on w and b.
  2. .detach() takes the error out of the record, so the hand formula below is plain arithmetic.
  3. backward() needs a single number to start from; .sum() turns the batch of predictions into one.
  4. design.grad has the shape of the input, (1, 2): ∂y^/∂x1\partial \hat{y} / \partial x_1 and ∂y^/∂x2\partial \hat{y} / \partial x_2, one slope per design variable.
-2.486666679382324 -2.486666440963745
-2.013333320617676 -2.013333320617676
tensor([[ 0.0589, -0.0469]])

Example 4-3 prints autograd’s gradient next to that of Equation 4-4. For w the two agree to six significant digits (−2.4866667 and −2.4866664), about the precision of 32-bit numbers, and for b exactly. The last line holds one slope per design input of this untrained network.