Concept units

Gradient descent

Intermediate

Read these first if they are new to you

The idea in one paragraph

Gradient descent is how most models learn. Start with some weights. Compute the gradient of the loss: the direction in which the loss rises fastest. Move the weights a small step the opposite way, so the loss falls. Repeat thousands of times. The size of each step is set by a number called the learning rate. Too small, and training crawls; too large, and the weights overshoot and fly off.

The gradient points uphill, so step the other way

A loss function gives one number for how wrong a model is. It depends on the model's weights. Picture the loss as a curve over one weight w. We want the w at the bottom of the curve, but we cannot see the whole curve. We can only compute its slope at the point where we stand.

If the slope is positive, the loss rises to the right, so we move left. If it is negative, we move right. The gradient is that slope; with many weights it is a vector of slopes, one per weight. The update rule is:

wnew = w − η × g

Here g is the gradient at the current w, and η (the Greek letter eta) is the learning rate: a small positive number that scales the step. A steep slope gives a big step; a flat slope gives a small one.

Worked example: two steps on a simple curve

Let the loss be L(w) = (w − 3)2. Its lowest point is at w = 3. Its slope is g = 2(w − 3). Start at w = 0 with η = 0.1.

  1. At w = 0: g = 2(0 − 3) = −6. New w = 0 − 0.1 × (−6) = 0.6. The loss falls from 9 to (0.6 − 3)2 = 5.76.
  2. At w = 0.6: g = 2(0.6 − 3) = −4.8. New w = 0.6 + 0.48 = 1.08. The loss falls to 3.6864.

Each step closes 20% of the remaining gap to 3, because here every step multiplies the gap by 1 − 2η = 0.8.

Your turn. Start at w = 5 with η = 0.25. Where is w after one step, and what is the loss there?

Answer

g = 2(5 − 3) = 4, so w = 5 − 0.25 × 4 = 4. The loss is (4 − 3)2 = 1, down from 4.

The learning rate decides between crawling and flying off

Try it. The figure runs gradient descent on the same curve, starting at w = 0. Predict first: what happens with a learning rate above 1? Then find a learning rate that gets the loss below 0.01 within five steps.

Gradient descent on L(w) = (w − 3)2

Each dot is one step; the short line through the newest dot shows the slope there. Changing the learning rate starts again from w = 0.
Answer

Above 1, every step jumps past the bottom and lands higher than before, so the dots move outward and the loss grows: training diverges. At exactly 1 the dots bounce between 0 and 6 forever. Any rate from about 0.25 to 0.75 gets the loss below 0.01 within five steps. On this curve 0.5 lands on the bottom in one step, but that is special to this curve.

Learning rateGap multiplied by per stepWhat happens
0.020.96steady but slow: 50 steps leave 13% of the gap
0.10.8steady progress
0.75−0.5overshoots each time, but the gap still shrinks
1.0−1bounces forever
1.1−1.2diverges
Real losses are not one neat bowl

This curve has one bottom, and its slope changes at the same steady rate everywhere, so one formula predicts every step. A real network's loss depends on millions of weights. It has flat stretches, narrow valleys and many low points. Gradient descent finds a low point near where it starts, with no promise that it is the lowest. A learning rate that works is found by trying values, not by a formula.

With many weights, every weight steps at once

A network has many weights. The gradient has one entry for each: how much the loss changes when that weight alone changes a little. One step updates all weights together, each by −η times its own entry. Backpropagation computes all those entries in one pass, and PyTorch does it for you.

In practice, each step computes the loss on a small random batch of examples rather than on all of them. This is called stochastic gradient descent; the unit on minibatches explains it. Improved versions such as AdamW change how each step is sized.

gradient_descent_numpy.py

def loss(w): return (w - 3) ** 2
def grad(w): return 2 * (w - 3)

for lr in [0.1, 1.1]:
    w = 0.0
    print(f"learning rate {lr}")
    for step in range(4):
        w = w - lr * grad(w)
        print(f"  step {step + 1}: w = {w:.4f}, loss = {loss(w):.4f}")
learning rate 0.1
  step 1: w = 0.6000, loss = 5.7600
  step 2: w = 1.0800, loss = 3.6864
  step 3: w = 1.4640, loss = 2.3593
  step 4: w = 1.7712, loss = 1.5099
learning rate 1.1
  step 1: w = 6.6000, loss = 12.9600
  step 2: w = -1.3200, loss = 18.6624
  step 3: w = 8.1840, loss = 26.8739
  step 4: w = -3.2208, loss = 38.6984

The same idea fits a line y = ax + c to four points. PyTorch computes the gradient of both weights; the loop takes the steps. torch.tensor makes a tensor, PyTorch's version of an array. The unit on automatic gradients explains requires_grad, .backward(), torch.no_grad() and .item().

fit_line_torch.py

import torch

x = torch.tensor([0.0, 1.0, 2.0, 3.0])
y = torch.tensor([1.0, 3.0, 5.0, 7.0])     # y = 2x + 1
w = torch.zeros(2, requires_grad=True)     # slope and intercept, both starting at 0

lr = 0.05
for step in range(500):
    loss = ((w[0] * x + w[1] - y) ** 2).mean()
    loss.backward()                  # fills w.grad
    with torch.no_grad():
        w -= lr * w.grad             # one step downhill
        w.grad.zero_()               # clear w.grad, because backward() adds to it
# w.detach(): the numbers in w, without requires_grad=True
print(w.detach(), f"loss {loss.item():.6f}")
tensor([2.0000, 1.0000]) loss 0.000000

Check yourself

  1. On L(w) = (w − 3)2, start at w = 1 with η = 0.1. Where is w after one step?

    Answer

    g = 2(1 − 3) = −4, so w = 1 + 0.4 = 1.4.

  2. Why does the rule subtract the gradient instead of adding it?

    Answer

    The gradient points in the direction where the loss rises fastest. We want the loss to fall, so we move the other way.

  3. Your training loss jumps around and then grows to huge values. What is the first thing to change?

    Answer

    Lower the learning rate. Growing loss is the sign of steps that overshoot, as with η above 1 on the curve here.

  4. At some point the gradient is exactly zero. What does gradient descent do there, and is that point necessarily the lowest loss?

    Answer

    It stops moving, because every step is zero. The point is flat, but it may be a low point that is not the lowest, a flat stretch, a peak, or a saddle point (lowest along one direction but highest along another), rather than the true bottom.

Go further

Optional background, for readers who want more than this page.

Where this shows up

Units that build on this one