Deep learning and neural networksLoading progress…

The training loop

Translate an inspected NumPy model into tensors, modules, automatic differentiation and a clear training loop.

The five lines every training loop contains

Inside the loop over batches, a PyTorch training step is the same five lines in the same order. Each one maps to something from the earlier chapters.

Line 1 of 5
▶ optimizer.zero_grad()
  pred = model(xb)
  loss = loss_fn(pred, yb)
  loss.backward()
  optimizer.step()

Clear the gradient left from the previous batch.

w.grad = None
One iteration on a one-weight model. Step through the lines and watch w and its gradient change.
for xb, yb in loader:
    optimizer.zero_grad()          # 1. clear old gradients
    pred = model(xb)               # 2. forward
    loss = loss_fn(pred, yb)       # 3. loss
    loss.backward()                # 4. gradients
    optimizer.step()               # 5. update the weights

Two switches that are easy to confuse

model.train() and model.eval() change how certain layers behave (dropout is active only in train mode, batch norm uses batch or running statistics). torch.no_grad() stops gradient recording. They are separate settings: for validation you normally want both.

Predict first. Does model.eval() alone disable autograd?

Chapter context

PyTorch provides tensor operations and differentiation infrastructure. The framework removes bookkeeping, but it does not remove the need to understand dimensions, parameter ownership, device placement and evaluation behavior.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

For a batch X of shape (B,d), a dense output with h features has shape (B,h). torch.nn.Linear stores weight with shape (h,d) and computes X times weight-transpose plus bias. Parameter count is d*h+h. PyTorch execution belongs in a linked notebook or supported runtime; the chapter does not assume browser PyTorch.

Worked example

A batch has shape (2,4). A Linear(4,3) layer stores a (3,4) weight and a length-three bias. Its output is (2,3). The parameter count is 4×3+3=15. This differs from the batch's element count: model parameters are shared across both examples.

Reference code

The following example uses the Python standard library and does not call a remote service.

batch, inputs, outputs = 2,4,3
weight_shape = (outputs,inputs)
output_shape = (batch,outputs)
assert weight_shape == (3,4)
assert output_shape == (2,3)
assert inputs*outputs+outputs == 15

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

eval mode and no_grad are independent. Model parameters do not multiply with batch size. A tensor detached for logging must not replace the tensor used to compute the training loss.