Skip to content
mentoor

Topic 4 of 5 · 5 min read

Writing a PyTorch training loop

Goal: Write a training loop with a validation pass and checkpointing and find the missing step in a broken one.

A training loop repeats five steps per batch (forward, loss, zero, backward, step), then checks a validation set without learning, and saves a checkpoint when validation improves.

Check yourself · 1 of 3

Which order is correct inside one training step?

Choose one answer

Why it matters

PyTorch gives you no fit(). The loop is yours, so a missing line fails silently. An assistant can write a loop that runs for hours and trains nothing because one step is gone. If you know the order, you can spot the gap in seconds.

How to do it

  1. Per batch, in this order. Move data to the device, run the model, compute the loss, call optimizer.zero_grad(), call loss.backward(), call optimizer.step().
  2. Set the mode. model.train() at the start of each epoch's training phase.
  3. Validate without learning. model.eval() and with torch.no_grad(): then average the loss or accuracy over the whole validation loader. No backward, no step.
  4. Save a checkpoint when it improves. torch.save(model.state_dict(), "best.pt") when validation loss is the lowest so far. Save the optimizer state too if you want to resume.
  5. Log one line per epoch with train loss, validation loss and the epoch number. A loop you cannot read in the log is a loop you cannot debug.

Before and after

# Weak: validation that trains and never ends up saved
for epoch in range(10):
    for x, y in val_loader:
        loss = loss_fn(model(x), y)
        loss.backward()
        optimizer.step()

This "validates" with gradient steps on the validation set, so the metric is meaningless, and nothing is saved.

best = float("inf")
for epoch in range(10):
    model.train()
    for x, y in train_loader:
        x, y = x.to(device), y.to(device)
        optimizer.zero_grad()
        loss = loss_fn(model(x), y)
        loss.backward()
        optimizer.step()
    model.eval()
    total = 0.0
    with torch.no_grad():
        for x, y in val_loader:
            x, y = x.to(device), y.to(device)
            total += loss_fn(model(x), y).item() * len(x)
    val = total / len(val_loader.dataset)
    if val < best:
        best = val
        torch.save(model.state_dict(), "best.pt")
    print(f"epoch {epoch} val_loss {val:.4f}")

What goes wrong

  • Missing zero_grad or step. The loss stays flat or explodes.
  • Training on validation data. Validation loss looks excellent, test results do not.
  • Using .item() for the running total in the graph, versus keeping the tensor, which stores history and leaks memory. Take .item() for logging.
  • Saving only the last epoch, which may be overfit, instead of the best.

Examples

Spotting the missing step

for x, y in train_loader:
    loss = loss_fn(model(x), y)
    loss.backward()
    optimizer.step()

There is no optimizer.zero_grad(). The loop runs, but each step uses the sum of all earlier gradients. The log shows a loss that falls briefly, then swings or rises.

Resuming from a checkpoint

torch.save({"model": model.state_dict(), "opt": optimizer.state_dict(), "epoch": epoch}, "ckpt.pt")
ckpt = torch.load("ckpt.pt")
model.load_state_dict(ckpt["model"])

Saving the optimizer state as well keeps momentum and Adam statistics, so a resumed run continues the same curve.

Key points

  • Each training batch runs forward, loss, zero_grad, backward and step, and dropping any one of them breaks learning silently.
  • Validation uses model.eval() and torch.no_grad(), with no backward pass and no optimizer step.
  • Average validation loss over the whole dataset, weighting by batch size when the last batch is smaller.
  • Save state_dict when validation improves, not just after the final epoch.
  • Log train and validation loss per epoch so a bad run is visible early.

Common mistakes

  • Leaving out zero_grad() or optimizer.step() and not noticing because the code still runs.
  • Running a gradient step during validation.
  • Saving the model object with pickle instead of its state_dict, which breaks when the class code changes.
  • Judging a run by training loss alone, which keeps falling even when the model overfits.

Check yourself · 2 of 3

During validation, which calls should be absent from the loop?

Choose one answer

Check yourself · 3 of 3

When should you save the best checkpoint?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic