Gradients: Which Way to Change Every Weight

A loss tells you how wrong a model is, but not what to do about it. Training needs one more piece of information for every weight and bias: should this number go up or down, and how much does it matter? That information is called the gradient. This page explains what a gradient means using nothing more than arithmetic, how PyTorch works out the gradients of a loss for you, and how you can use them to lower the loss one small step at a time.

A gradient: what happens when you nudge one weight

Start with the smallest model possible: one weight w. Given the input 2, it predicts w × 2, and the correct answer is 6. To keep the arithmetic easy, this example measures how wrong the prediction is with a simple loss: take the difference between the prediction and the answer, and square it. Squaring makes every miss positive and makes big misses count more. With w = 1 the prediction is 2, the difference is 2 − 6 = −4, and the loss is (−4)² = 16.

Now ask a plain question: if you nudge w up by a tiny amount, say 0.01, what happens to the loss? You can simply try it. With w = 1.01 the prediction is 2.02, the difference is −3.98, and the loss is 15.8404. The loss went down by 0.1596. Divide that change by the size of the nudge and you get the change per unit of w: about −16. That number is the gradient of the loss for this weight.

Nudging w up by 0.01 at three starting points
wloss at wloss at w + 0.01changechange per unit of w
11615.8404−0.1596about −16
300.0004+0.0004about 0
444.0804+0.0804about +8

The gradient carries two pieces of information. Its sign gives the direction: a negative gradient means that raising the weight lowers the loss, a positive one means that raising it makes the loss worse. Its size says how strongly the loss reacts: at w = 1 the loss reacts twice as strongly as at w = 4. At w = 3 the prediction is exactly right, the loss is at its lowest, and a small nudge barely changes it, so the gradient is about 0. The smaller the nudge you try, the closer the result gets to the exact gradient (here exactly −16, 0 and +8).

The loss for every value of w

loss against w

  • loss

On the curve, the gradient is how steeply the loss rises or falls where you stand. A real model has thousands of weights and biases, and a gradient exists for each one: how the loss changes when that one parameter is nudged up while all the others stay where they are. So the gradients of a weight tensor form a tensor of exactly the same shape, one number per weight.

True or false?

A gradient of −16 for a weight means the weight should be lowered.

False. A negative gradient means that raising the weight lowers the loss, so this weight should go up.

A weight tensor of shape 5 by 3 has a gradient tensor of shape 5 by 3.

True. There is one gradient per parameter, so the gradients have the same shape as the parameters.

Automatic differentiation: PyTorch records, then works backwards

Nudging every weight one at a time and recomputing the loss would work, but a model with a million weights would need a million extra passes for a single set of gradients. PyTorch does something much cheaper, called automatic differentiation (its engine is named torch.autograd).

You mark the tensors you want gradients for with requires_grad=True. From then on, every operation that uses them is recorded as it runs: PyTorch keeps a record of which operation produced which result from which inputs. For the one-weight model, the record is a short chain.

  • w 1.0, requires_grad
  • multiply by 2 prediction 2.0
  • subtract 6 difference −4.0
  • square loss 16.0
  • w to multiply by 2
  • multiply by 2 to subtract 6
  • subtract 6 to square

Each recorded operation knows how its output responds to a small nudge of its input. Calling backward() on the loss walks the record from the loss back to w and combines those responses by multiplying them. You can follow it with the same nudge arithmetic as before:

  • Nudging the difference (−4) up by 0.01 gives a loss of (−3.99)² = 15.9201, a change of about −8 per unit.
  • Subtracting 6 passes any change in the prediction straight on to the difference, so the loss also changes by −8 per unit of the prediction.
  • The prediction is w × 2, so it changes 2 per unit of w, and the loss changes by −8 × 2 = −16 per unit of w.

That is the same −16 the nudge table found, but obtained in one backward pass, and the same pass fills in the gradient of every marked tensor at once, however many there are. In code it takes a few lines, and it runs on an ordinary CPU:

Asking PyTorch for a gradient
import torch

w = torch.tensor(1.0, requires_grad=True)   # a weight PyTorch should track
print(w.grad)          # None: nothing computed yet

loss = (w * 2.0 - 6.0) ** 2
print(loss)            # tensor(16., grad_fn=<PowBackward0>)

loss.backward()        # work backwards from the loss
print(w.grad)          # tensor(-16.)
print(w)               # tensor(1., requires_grad=True): unchanged

A few details in that output are worth reading closely. The loss prints with grad_fn, the reference to the recorded operation that produced it, which is how you can tell a result is part of the record. The gradient lands in the .grad attribute of w, which is None until the first backward(). And w itself has not moved: backward() only computes gradients, it never changes a weight.

A few rules follow from how the record works:

  • Gradients exist only for floating-point (and complex) tensors, so weights are float tensors, never whole numbers.
  • Only the tensors you created and marked yourself get a .grad. They are the starting points of the record, which PyTorch calls leaf tensors. Intermediate results, such as the prediction, get none.
  • If you scale a weight after creating it, mark it only afterwards, with w.requires_grad_(). The trailing underscore means the change happens in place. This way the scaling is not part of the record, and w stays a starting point.
  • A record is used up by one backward() call. It is built again from scratch every time the loss is computed again.

True or false?

After loss.backward(), the weights have moved to a better value.

False. backward() only fills in .grad. The weights change only when your own code updates them.

PyTorch finds the gradients without nudging each weight and recomputing the loss.

True. It walks its record of operations backwards once from the loss, which gives every gradient in one pass.

Gradient descent: step against the gradient, then repeat

The gradient points the way the loss goes up. To make the loss go down, move each parameter a small step in the opposite direction: subtract its gradient, scaled down by a small number called the learning rate. This is gradient descent.

$$w_{\text{new}} = w - \text{learning rate} \times \text{gradient}$$

one step, for every parameter

Take the one-weight model with a learning rate of 0.1. At w = 1 the gradient is −16, so the step is −0.1 × −16 = +1.6, and w becomes 2.6. The loss drops from 16 to 0.64. Compute the loss again, find the new gradient (−3.2), take another step, and keep going: each step lands closer to w = 3, where the loss is lowest. Close to the bottom the gradient is small, so the steps become small on their own.

Three steps with a learning rate of 0.1

loss against w

  • loss

Written by hand in PyTorch, one step is: compute the loss, call backward(), then update the weight and clear its gradient. The last two lines sit inside torch.no_grad(); the two sections below explain why both are needed.

Gradient descent by hand
import torch

w = torch.tensor(1.0, requires_grad=True)
lr = 0.1   # learning rate

for step in range(3):
    loss = (w * 2.0 - 6.0) ** 2   # a new record every time
    loss.backward()               # fills w.grad
    with torch.no_grad():
        w -= lr * w.grad          # step against the gradient
        w.grad.zero_()            # clear it for the next step
    print(f"step {step}: loss {loss.item():.4f}, w now {w.item():.4f}")
What it prints (about these values)
step 0: loss 16.0000, w now 2.6000
step 1: loss 0.6400, w now 2.9200
step 2: loss 0.0256, w now 2.9840

loss.item() turns a one-number tensor into a plain Python number for printing. A real model follows exactly the same loop, only with many tensors of weights and a loss that has no simple formula: every parameter takes its own step against its own gradient, all in the same update, and the loss goes down from one step to the next as long as the steps are small enough.

The learning rate: how big each step is

The gradient gives the direction, and the learning rate decides how far to go. Running the same one-weight model from w = 1 with four different learning rates shows all the ways this can go.

Loss after each step, starting from w = 1
steprate 0.01rate 0.1rate 0.25rate 0.3
016161616
113.540.641631.36
211.460.02561661.47
39.700.001016120.47
48.210.0000416236.13
  • Too small (0.01): every step goes the right way, but the loss creeps down. Training would need many more steps to get anywhere.
  • Well chosen (0.1): the loss falls quickly and settles near its lowest point.
  • Too large (0.25): the first step jumps from w = 1 right over the lowest point to w = 5, where the loss is just as high, and the next step jumps back. The loss bounces and never improves.
  • Even larger (0.3): each jump overshoots further than the last, and the loss grows with every step.

The gradient only describes the loss right around the current weights. A small step stays where that description holds; a large one lands somewhere the gradient said nothing about. There is no single correct learning rate: a good value depends on the model and the data, and is usually found by trying a few values and watching the loss. If the loss jumps around or climbs, the rate is too high; if it falls very slowly, it can probably be raised.

True or false?

Doubling the learning rate always makes training reach a low loss faster.

False. Past a certain size the steps overshoot, and the loss bounces or grows instead of falling.

Near the lowest loss, steps get smaller even though the learning rate stays the same.

True. The step is the learning rate times the gradient, and the gradient shrinks towards 0 near the bottom.

Gradients add up until you clear them

A detail of backward() surprises almost everyone at first: it does not replace what is stored in .grad, it adds the new gradient to it. Compute the same loss twice and call backward() twice, and the stored gradient doubles.

backward() adds to the stored gradient
import torch

w = torch.tensor(1.0, requires_grad=True)

loss = (w * 2.0 - 6.0) ** 2
loss.backward()
print(w.grad)    # tensor(-16.)

loss = (w * 2.0 - 6.0) ** 2
loss.backward()
print(w.grad)    # tensor(-32.): added, not replaced

w.grad.zero_()
print(w.grad)    # tensor(0.)

Adding is deliberate: it lets several backward passes combine into one gradient before a single update, which some training methods rely on. In plain gradient descent, though, each step must use only the gradient of the current loss. If you never clear it, every step uses a running total of all the gradients so far. That total is mostly old gradients, so the step no longer matches where the weights are now: it can stay large near the lowest point, or keep pushing the old way past it.

So the stored gradients are cleared once per step. Two ways are standard: fill them with zeros with w.grad.zero_(), or set w.grad = None.

Where in the step you clear them matters. Right after the update, as in the loop above, is the safe place. Clearing at the top of each step also works, but not with zero_() on the very first step: before the first backward() the gradient is still None, and there is nothing to fill with zeros, so that call fails. What must never happen is clearing between backward() and the update, because that throws the gradient away before it is used.

True or false?

Calling loss.backward() twice without clearing gives the same gradient as calling it once.

False. Each call adds its gradient to what is stored, so two calls on the same loss leave twice the gradient.

Clearing the gradients right after each update is as correct as clearing them just before each backward() call.

True. Either way, each backward() starts from an empty gradient; only clearing between backward() and the update is wrong.

Switching off the recording for the update

The update w -= lr * w.grad is itself an operation on a tensor that requires gradients. With the recording on, PyTorch would treat it as part of the computation of the loss. It is not: it is the step that changes the model between two computations of the loss. PyTorch does not allow it. While recording is on, changing a marked leaf tensor in place stops with a RuntimeError, saying that a leaf that requires grad is being used in an in-place operation.

The way out is torch.no_grad(), a block written with with. Inside it nothing is recorded, and every result it computes has requires_grad=False, even when its inputs are marked.

The same computation with and without recording
import torch

w = torch.tensor(1.0, requires_grad=True)

y = w * 2.0
print(y.requires_grad)    # True: recorded

with torch.no_grad():
    y = w * 2.0
print(y.requires_grad)    # False: not recorded

Switching off the recording does not unmark the weight. After the with block, w still has requires_grad=True, so the next loss computed from it is recorded as usual and its backward() fills in a fresh gradient. Only the update and the clearing of the gradient run unrecorded, which is exactly what the loop needs. Any other computation that should not take part in gradients, such as measuring a model without training it, can run in the same kind of block.

True or false?

After an update inside torch.no_grad(), the weight no longer requires gradients.

False. Only the results computed inside the block are unmarked. The weight keeps requires_grad=True for the next step.

torch.no_grad() is needed for training, not only for making predictions.

True. Every hand-written update of the parameters runs inside it so that the update is not recorded.