Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 2: Programming Toolkit

The PyTorch training loop

P2.745 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Every neural network in this course, from a small classifier to a large language model, is trained by the same short loop. Once you can read and write it, a training script stops being magic: each line has one job, and each bug has a known cause.

  • Building a convolutional network that classifies images in PyTorch uses exactly this loop, with a bigger model in the middle. (P5.7: Build a CNN)
  • Optimizers such as Adam change only the line that creates the optimizer, so the loop you learn here stays the same when you change the optimizer. (P4.13: Optimizers)
  • The training recipe and debugging lesson starts from this loop: overfit one batch, read the train and validation loss curves, and check each line. (P4.22: The training recipe and debugging)
  • Training a large model on many GPUs wraps this same loop in code that splits each batch across devices. (P10.B6: Distributed training, coming soon)

Before this: PyTorch tensors and autograd, Stochastic and mini-batch gradient descent, Computational graphs and automatic differentiation

After this lesson you can

  • Write the training loop from memory, with the five steps in the right order, and say what goes wrong if you reorder them
  • Build a model with nn.Module or nn.Sequential, and say what parameters() returns and what the forward method is for
  • Feed a model with Dataset, TensorDataset and DataLoader, and count the batches in an epoch
  • Add a validation pass with model.eval() and torch.no_grad(), and log the loss correctly
  • Move a model and its batches to a GPU, and recognise the common bugs on sight

In P0.2 you ran a loop by hand: predict, measure the loss, nudge the numbers, repeat. A neural network with a billion parameters is trained by the same loop. Nothing in it changes except the size of the model and the amount of data. PyTorch gives you ready-made pieces for each part, and your job is to connect them in the right order. This lesson shows the pieces and the order.

PyTorch does not run in your browser, so the code here runs in a notebook. Every output shown below was produced by running that notebook on a CPU (PyTorch 2.9.1, scikit-learn 1.8.0). Open it in Colab (source on GitHub). It needs no GPU and no downloads, and runs in a few seconds. Tensors, requires_grad and .backward() are taught in P2.6; here we use them without re-teaching them.

The loop from P0.2, in PyTorch

Here is the P0.2 loop with the same three points (1,2)(1,2), (2,3)(2,3), (3,7)(3,7), the same start w=1w=1, b=0b=0, the same learning rate 0.050.05 and the same 200 updates. The model y^=wx+b\hat{y}=wx+b is nn.Linear(1, 1).

import torch
import torch.nn as nn

x = torch.tensor([[1.0], [2.0], [3.0]])    # shape (3, 1): 3 examples, 1 feature
y = torch.tensor([[2.0], [3.0], [7.0]])

model = nn.Linear(1, 1)
with torch.no_grad():                      # set the starting guess by hand
    model.weight.fill_(1.0)
    model.bias.fill_(0.0)

loss_fn = nn.MSELoss()                     # mean of (prediction - target)^2
optimizer = torch.optim.SGD(model.parameters(), lr=0.05)

for step in range(201):
    pred = model(x)                        # 1. forward
    loss = loss_fn(pred, y)                # 2. loss
    if step in (0, 1, 2, 5, 10, 50, 200):
        print(f"step {step:3d}  w={model.weight.item():.3f}  b={model.bias.item():.3f}  loss={loss.item():.3f}")
    if step == 200:
        break
    optimizer.zero_grad()                  # 3. clear old gradients
    loss.backward()                        # 4. new gradients
    optimizer.step()                       # 5. update

with torch.no_grad():
    print("prediction for x = 2.5:", round(model(torch.tensor([[2.5]])).item(), 2))
step   0  w=1.000  b=0.000  loss=6.000
step   1  w=1.500  b=0.200  loss=1.807
step   2  w=1.727  b=0.280  loss=0.970
step   5  w=1.909  b=0.302  loss=0.747
step  10  w=1.958  b=0.232  loss=0.718
step  50  w=2.166  b=-0.240  loss=0.583
step 200  w=2.446  b=-0.876  loss=0.502
prediction for x = 2.5: 5.24

These are the numbers of P0.2: the loss 6.0006.000, then w=1.5w=1.5, b=0.2b=0.2 after the first update, then losses 1.8071.807 and 0.9700.970, and a prediction of 5.245.24 at x=2.5x=2.5 after 200 updates (the exact best line gives 5.255.25). The NumPy loop computed the slopes with a formula you wrote. In PyTorch, loss.backward() finds them for you (P1.C10, P2.6), and optimizer.step() does the “move against the slope” line. The rest of this lesson is about those five lines, and about everything around them that a real model needs: a model that is more than one line, data that comes in batches, a check on held-out data, and a GPU.

The loop as a picture

Epoch loop one epoch = one full pass over the training data

Batch loop one optimizer step per batch, until the loader runs out

Next batch: back to step 3.

Evaluation once per epoch, on validation data, with no learning

Next epoch: back to step 1.

for epoch in range(num_epochs):    model.train()    for xb, yb in train_loader:        pred = model(xb)        loss = loss_fn(pred, yb)        optimizer.zero_grad()        loss.backward()        optimizer.step()    model.eval()    with torch.no_grad():        for xv, yv in val_loader:            val = loss_fn(model(xv), yv)

Step 1 of 11: Start an epoch loop

for epoch in range(num_epochs):

An epoch is one full pass over the training data. Training runs for a number of epochs that you choose.

The training loop as nested frames, next to the same loop as code. Pick any step, or use Previous and Next, to highlight its line of code and read what it does. Blue marks forward values, orange marks gradients, green marks the update; each step also carries a text label, so colour is not the only signal. The batch loop is the part you will write most often: five lines, once per batch. The full loop below also adds up the validation loss weighted by batch size.

Read the diagram from the top. An epoch is one full pass over the training data. Inside an epoch, the batch loop takes one small group of examples at a time and does the five-line step on it. After the last batch, the evaluation frame measures the model on held-out validation data, without changing it. Then the next epoch starts. The sections below take the pieces in the order you build them: the model, the loss, the optimizer, the order of the five lines, the data, and then evaluation.

Intuition

Think of a student practising with a coach. The model is the student. For each batch of practice questions the student answers (forward), the coach marks the answers (loss), the coach writes down what was wrong and why (backward: the gradients), and the student changes how they think (step). Between questions the coach rubs out the old notes (zero_grad), or the notes from different batches would pile up on one page. At the end of each week there is a test (evaluation), where the student is not allowed to learn from the answers.

Where the picture breaks: a real “student” is only a long list of numbers, and the coach’s notes are just one more list of numbers, the gradient, with one entry per parameter.

Math

For a batch B\mathcal{B} of BB examples, the loss is the average of the per-example losses, LB(θ)=1B∑i∈BL(fθ(xi),yi)\mathcal{L}_{\mathcal{B}}(\boldsymbol{\theta}) = \frac{1}{B}\sum_{i\in\mathcal{B}} L(f_{\boldsymbol{\theta}}(\mathbf{x}_i), y_i). The five lines compute this loss, its gradient, and one update with learning rate η\eta:

θ←θ−η ∇θLB(θ).\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta\,\nabla_{\boldsymbol{\theta}}\mathcal{L}_{\mathcal{B}}(\boldsymbol{\theta}).

This is mini-batch gradient descent (P1.F4). With one batch that holds the whole dataset it is plain gradient descent (P1.F3), which is what the P0.2 loop above does with B=3B=3. backward() computes ∇θLB\nabla_{\boldsymbol{\theta}}\mathcal{L}_{\mathcal{B}} and adds it into each parameter’s .grad; this is why zero_grad is needed.

Code

for xb, yb in train_loader:        # one batch
    pred = model(xb)               # forward
    loss = loss_fn(pred, yb)       # loss
    optimizer.zero_grad()          # clear old gradients
    loss.backward()                # new gradients into .grad
    optimizer.step()               # update the parameters

These five lines are the same for a line fit and for a large network. Only the model, the loss function and the data change.

The model: nn.Module

A model in PyTorch is an nn.Module. You write a class with two methods. In __init__ you create the layers and assign them to self, and in forward you say how an input flows through them. Assigning a layer to self registers it, which is how PyTorch later finds its parameters.

class Net(nn.Module):
    def __init__(self, d_in, d_hidden, n_classes):
        super().__init__()                          # always first
        self.hidden = nn.Linear(d_in, d_hidden)     # layers assigned to self are registered
        self.act = nn.ReLU()
        self.out = nn.Linear(d_hidden, n_classes)

    def forward(self, x):
        return self.out(self.act(self.hidden(x)))

net = Net(2, 16, 2)
print(net)
for name, p in net.named_parameters():
    print(f"{name:14s} {tuple(p.shape)}")
print("number of parameters:", sum(p.numel() for p in net.parameters()))

# The same network written with nn.Sequential
seq = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 2))
print("Sequential parameters:", sum(p.numel() for p in seq.parameters()))
Net(
  (hidden): Linear(in_features=2, out_features=16, bias=True)
  (act): ReLU()
  (out): Linear(in_features=16, out_features=2, bias=True)
)
hidden.weight  (16, 2)
hidden.bias    (16,)
out.weight     (2, 16)
out.bias       (2,)
number of parameters: 82
Sequential parameters: 82

The parts, one by one.

  • nn.Linear(d_in, d_out) computes Wx+b\mathbf{W}\mathbf{x}+\mathbf{b} for each example (P4.1, P4.5). PyTorch stores a batch as rows, so in code it is x @ W.T + b. Its weight has shape (d_out, d_in). Here the two layers have 4848 and 3434 parameters, 8282 in all.
  • forward describes the computation for a batch. The input has a leading batch dimension: x has shape (B, 2), and the output has shape (B, 2).
  • Call the model, do not call forward. Write model(x). The call runs forward and also does bookkeeping that PyTorch relies on (hooks, for example). Calling model.forward(x) directly skips it.
  • model.parameters() gives every parameter tensor of every registered layer, and named_parameters() gives them with names. The optimizer will update exactly these. Each parameter has requires_grad=True already (P2.6).
  • nn.Sequential is a shortcut when the layers just run one after another. Use a class when the data flow is more than a straight line.

There is one trap. Only modules assigned to self are registered. A plain Python list of layers is not:

class Broken(nn.Module):
    def __init__(self):
        super().__init__()
        self.layers = [nn.Linear(2, 16), nn.Linear(16, 2)]   # plain list

class Fixed(nn.Module):
    def __init__(self):
        super().__init__()
        self.layers = nn.ModuleList([nn.Linear(2, 16), nn.Linear(16, 2)])

print("plain list :", sum(p.numel() for p in Broken().parameters()), "parameters")
print("ModuleList :", sum(p.numel() for p in Fixed().parameters()), "parameters")
plain list : 0 parameters
ModuleList : 82 parameters

With the plain list the optimizer would be given no parameters, and nothing would learn. Use nn.ModuleList (or nn.Sequential) for a collection of layers.

The loss function

A loss function takes the predictions and the targets and returns one number, the average loss over the batch (P4.6).

  • nn.MSELoss() is the mean squared error, for predicting numbers (regression). Call it as loss_fn(pred, target). The two must have the same shape. If pred has shape (3, 1) and target has shape (3,), PyTorch warns and broadcasts them into a 3×33\times3 grid of differences. For the P0.2 data that turns the correct loss 6.06.0 into 9.3339.333, and the model trains toward the wrong thing.
  • nn.CrossEntropyLoss() is for classification (P1.E3). It takes raw scores, called logits, of shape (B, C). The targets are usually class indices of type torch.long (64-bit integers), shape (B,); float class probabilities of shape (B, C) are also accepted. It applies log-softmax itself (P1.G2), so you must not put a softmax at the end of your model.
logits = torch.tensor([[2.0, 0.5, -1.0], [0.1, 0.2, 3.0]])     # 2 examples, 3 classes
good = torch.tensor([0, 2])                                     # class indices, int64
print("class indices :", nn.CrossEntropyLoss()(logits, good).item())
print("same as hand  :", torch.nn.functional.nll_loss(logits.log_softmax(dim=1), good).item())
try:
    nn.CrossEntropyLoss()(logits, torch.tensor([0.0, 2.0]))     # float class numbers
except RuntimeError as e:
    print("RuntimeError:", str(e))
class indices : 0.17545640468597412
same as hand  : 0.17545640468597412
RuntimeError: expected scalar type Long but found Float

(CrossEntropyLoss also accepts float targets of shape (B, C), which it reads as class probabilities. A float vector of class numbers is not that, so it raises the error above.)

The optimizer

An optimizer holds references to the parameters and knows how to change them using their gradients. You give it the parameters and the learning rate η\eta:

optimizer = torch.optim.SGD(model.parameters(), lr=0.05)

torch.optim.SGD with its default settings does exactly θ←θ−η g\boldsymbol{\theta}\leftarrow\boldsymbol{\theta}-\eta\,\mathbf{g} (P1.F3, P1.F4). Add momentum=0.9 for the momentum variant (P1.F5). Other optimizers have the same interface: torch.optim.Adam(model.parameters(), lr=1e-3) is a one-line swap, and why Adam is often easier to get working (though not better everywhere) is in P4.13. Learning-rate schedules that change η\eta during training are in P4.14.

An optimizer does two things, through two methods:

  • optimizer.zero_grad() clears the .grad of every parameter it holds. (By default it sets them to None, which is the same as zero for the next backward pass and saves a little memory.)
  • optimizer.step() reads each parameter’s .grad and updates the parameter. It does not compute gradients; loss.backward() does.

The five lines, and why their order matters

For each batch:

  1. Forward: pred = model(xb). Compute the predictions. PyTorch records the operations (P1.C10).
  2. Loss: loss = loss_fn(pred, yb). One number for the batch.
  3. optimizer.zero_grad(): clear the gradients left by the previous batch.
  4. loss.backward(): compute the gradient of the loss with respect to every parameter, and add it into .grad.
  5. optimizer.step(): use .grad to update the parameters.

The order has two rules. backward must come after the loss (it needs the recorded graph), and step must come after backward (it needs the gradients). The third line, zero_grad, must run before backward, and after the previous step. Put it first in the batch (as above), or last, after step; both work. Put it between backward and step and you erase the gradient just before it is used. Here is what happens (for plain SGD) to the P0.2 start w=1w=1, b=0b=0 after one batch with η=0.05\eta=0.05:

OrderResult after one batchWhy
zero_grad, backward, stepw=1.5w=1.5, b=0.2b=0.2the correct update from P0.2
backward, zero_grad, stepw=1.0w=1.0, b=0.0b=0.0the gradient is erased, so nothing changes

Gradients add up

The reason zero_grad exists is the rule from P1.C10: a backward pass adds to .grad. Calling backward three times without clearing, on the data above where the true gradient for ww is −10-10, gives:

lin = nn.Linear(1, 1)
with torch.no_grad():
    lin.weight.fill_(1.0); lin.bias.fill_(0.0)
xs, ys = torch.tensor([[1.0], [2.0], [3.0]]), torch.tensor([[2.0], [3.0], [7.0]])
for k in range(3):
    nn.MSELoss()(lin(xs), ys).backward()            # no zero_grad in between
    print(f"after backward #{k + 1}: weight.grad = {lin.weight.grad.item():.3f}")
lin.zero_grad()
nn.MSELoss()(lin(xs), ys).backward()
print("after zero_grad then one backward:", round(lin.weight.grad.item(), 3))
after backward #1: weight.grad = -10.000
after backward #2: weight.grad = -20.000
after backward #3: weight.grad = -30.000
after zero_grad then one backward: -10.0

If you forget zero_grad, each step uses the sum of all earlier gradients: a gradient that is wrong and keeps growing. The loss may fall for a while and then misbehave, which makes this bug hard to spot. (Adding gradients on purpose is a trick called gradient accumulation, which lets you simulate a larger batch than fits in memory; P4.15.)

The data: Dataset, TensorDataset, DataLoader

The loop above uses three points at once. Real data has too many examples to use all of them in each step, so we take batches (P1.F4). PyTorch separates two jobs: a Dataset knows how to give you example number ii, and a DataLoader turns a dataset into a stream of batches.

Dataset

A map-style Dataset is any class with a __getitem__ method, which returns example ii, and a __len__ method, which returns how many examples there are. It is the same idea as the hand-written class with __len__ and __getitem__ in P2.1. __getitem__ is the required part. __len__ is not enforced when you create the dataset, but DataLoader needs it to shuffle and to count batches, so write it.

For the next examples we need data, and we make it in code: 600 points in two interleaved half-moons from scikit-learn, with a label 0 or 1 for each. We keep 400 for training and 200 for validation. (The notebook shows this code; here we focus on what comes out.)

from torch.utils.data import Dataset, TensorDataset, DataLoader

class PointsDataset(Dataset):                   # a hand-written map-style Dataset
    def __init__(self, X, y):
        self.X, self.y = X, y
    def __len__(self):                          # how many examples
        return len(self.X)
    def __getitem__(self, i):                   # example number i
        return self.X[i], self.y[i]

ds = PointsDataset(X_train, y_train)
print("len:", len(ds))
print("ds[0]:", ds[0])

ds2 = TensorDataset(X_train, y_train)           # the ready-made version of the same thing
print("TensorDataset gives the same pair:", torch.equal(ds2[0][0], ds[0][0]) and torch.equal(ds2[0][1], ds[0][1]))
len: 400
ds[0]: (tensor([-0.6340,  0.6449]), tensor(0))
TensorDataset gives the same pair: True

Here X_train has shape (400, 2) and type float32, and y_train has shape (400,) and type int64 (the class indices that CrossEntropyLoss wants). TensorDataset(X, y) is the ready-made version for data that is already in tensors: example ii is (X[i], y[i]). Write your own Dataset when an example must be built on demand, for instance by reading an image file or tokenizing a text. The loader below calls __getitem__ once per example in a batch.

DataLoader

loader = DataLoader(ds2, batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(1))
print("batches per epoch:", len(loader))
for epoch in range(2):
    sizes = [xb.shape[0] for xb, yb in loader]
    print("epoch", epoch, "batch sizes:", sizes)

xb, yb = next(iter(loader))
print("one batch:", xb.shape, xb.dtype, yb.shape, yb.dtype)

loader_drop = DataLoader(ds2, batch_size=64, shuffle=True, drop_last=True)
print("with drop_last=True:", len(loader_drop), "batches of 64")
batches per epoch: 7
epoch 0 batch sizes: [64, 64, 64, 64, 64, 64, 16]
epoch 1 batch sizes: [64, 64, 64, 64, 64, 64, 16]
one batch: torch.Size([64, 2]) torch.float32 torch.Size([64]) torch.int64
with drop_last=True: 6 batches of 64

What the arguments do:

  • batch_size: how many examples per batch. The loader stacks the examples into one tensor with a new leading batch dimension: (64, 2) and (64,).
  • shuffle=True: a new random order every epoch. Use it for training, so each epoch sees the examples in a new order, and the model cannot pick up a pattern from the order the data happens to be stored in (for example, all of one class first). For validation, shuffling does no harm, but it is not needed: the average over the validation set is the same in any order.
  • drop_last: 400 examples do not divide by 64, so the last batch has only 400−6⋅64=16400-6\cdot64=16. With drop_last=True that small batch is thrown away (each epoch drops a different 16 when shuffling). The default keeps it.
  • num_workers: the default 00 loads data in the main process. A larger number starts that many helper processes that prepare batches in parallel. It helps when each example is slow to load, such as decoding an image, and it is pointless for small tensors held in memory. (On Windows and macOS, worker processes start by re-importing your script, so put the training code under if __name__ == "__main__":, or each worker would run it again.)
  • generator: the random-number generator used for shuffling. Giving it a seeded torch.Generator makes the order of batches repeatable (P1.G3). Here is that, with two different epochs:
def first_labels(seed):
    dl = DataLoader(ds2, batch_size=8, shuffle=True, generator=torch.Generator().manual_seed(seed))
    return [next(iter(dl))[1].tolist() for _ in range(2)]     # first batch of two different epochs

print("seed 5, epochs 1 and 2:", first_labels(5))
print("seed 5 again          :", first_labels(5))
seed 5, epochs 1 and 2: [[0, 0, 0, 1, 0, 0, 1, 0], [0, 1, 0, 1, 0, 0, 0, 1]]
seed 5 again          : [[0, 0, 0, 1, 0, 0, 1, 0], [0, 1, 0, 1, 0, 0, 0, 1]]

The two epochs differ from each other (a new shuffle each epoch), and a second run with the same seed repeats both exactly. The same seed repeats a run only with the same library version and hardware (P1.G3).

Epochs and iterations

An iteration (or step) is one pass through the five lines, on one batch. An epoch is one full pass over the training data. With NN examples and batch size BB, one epoch has ⌈N/B⌉\lceil N/B\rceil iterations (⌊N/B⌋\lfloor N/B\rfloor with drop_last=True). With our 400 training examples, batch size 6464 gives 77 iterations per epoch, and the batch size 3232 used in the full loop below gives 1313 (12 full batches and one of 16), so 30 epochs make 390 optimizer steps. The P1.F4 lesson explains how batch size changes the noise of each step.

Validation: model.eval() and torch.no_grad()

Training loss tells you how well the model fits the data it learns from. What you care about is data it has not seen (P0.2, P3.A4), so after each epoch we measure the loss on validation examples that were never used for a step. Two switches matter for this pass.

  • model.train() and model.eval() set the model to training or evaluation mode. Some layers behave differently in the two. Dropout (P4.17) randomly zeroes values during training and does nothing in evaluation. Batch normalization (P4.19) uses the statistics of the current batch during training and stored averages in evaluation. A model made only of Linear and ReLU layers is unaffected, but get into the habit anyway: forgetting it is a classic bug. A new model starts in training mode, so call model.train() again at the top of each epoch after an evaluation.
  • torch.no_grad() is a context manager that stops PyTorch recording operations. Validation never calls backward, so the record would only waste memory and time.

These are independent. eval() changes how layers compute; no_grad() changes whether PyTorch keeps a graph. You normally use both for validation.

The complete loop

Here is the whole thing: a small network on the half-moons data with a train and validation pass per epoch. The batch loop is the one you already know; around it, a .to(device) for each batch (next section), a running loss, and the evaluation.

torch.manual_seed(0)
model = Net(2, 16, 2).to(device)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)

train_loader = DataLoader(TensorDataset(X_train, y_train), batch_size=32, shuffle=True,
                          generator=torch.Generator().manual_seed(0))
val_loader = DataLoader(TensorDataset(X_val, y_val), batch_size=200)   # no shuffling needed

for epoch in range(1, 31):
    model.train()                                   # training mode
    train_loss = 0.0
    for xb, yb in train_loader:
        xb, yb = xb.to(device), yb.to(device)       # move the batch to the model's device
        logits = model(xb)                          # forward
        loss = loss_fn(logits, yb)                  # loss on this batch
        optimizer.zero_grad()                       # clear old gradients
        loss.backward()                             # backward
        optimizer.step()                            # update
        train_loss += loss.item() * xb.shape[0]     # .item(): a plain number, no graph kept
    train_loss /= len(train_loader.dataset)

    model.eval()                                    # evaluation mode
    val_loss, correct = 0.0, 0
    with torch.no_grad():                           # no graph needed for validation
        for xb, yb in val_loader:
            xb, yb = xb.to(device), yb.to(device)
            logits = model(xb)
            val_loss += loss_fn(logits, yb).item() * xb.shape[0]
            correct += (logits.argmax(dim=1) == yb).sum().item()
    val_loss /= len(val_loader.dataset)

    if epoch in (1, 2, 3, 5, 10, 20, 30):
        print(f"epoch {epoch:2d}  train loss {train_loss:.3f}  val loss {val_loss:.3f}  val accuracy {correct / len(val_loader.dataset):.3f}")
epoch  1  train loss 0.584  val loss 0.391  val accuracy 0.850
epoch  2  train loss 0.299  val loss 0.300  val accuracy 0.870
epoch  3  train loss 0.258  val loss 0.337  val accuracy 0.860
epoch  5  train loss 0.294  val loss 0.283  val accuracy 0.875
epoch 10  train loss 0.136  val loss 0.211  val accuracy 0.900
epoch 20  train loss 0.077  val loss 0.143  val accuracy 0.945
epoch 30  train loss 0.071  val loss 0.129  val accuracy 0.960

Both losses fall. Note that the train loss is the average while the model was changing during the epoch, so it is not exactly the loss of the model at the end of the epoch. The validation loss is measured on a fixed model. Exact values can change a little across PyTorch versions and hardware, even with the seeds.

How to log the loss correctly:

  • Use loss.item(), a plain Python number, not the loss tensor. A tensor that remembers its graph (total = total + loss) keeps every batch’s graph alive in memory.

  • Weight by batch size. The loss of each batch is already an average over that batch, and the last batch can be smaller. Multiply each batch loss by its size, add, and divide by the total number of examples, as the code does. The last batch is also smaller than the others when NN is not a multiple of BB, which matters for layers that use batch statistics; that is one reason people use drop_last=True. If six batches of 6464 have loss 0.50.5 and one batch of 1616 has loss 1.01.0, the right average is

    6⋅64⋅0.5+16⋅1.0400=0.52,\frac{6\cdot64\cdot0.5+16\cdot1.0}{400}=0.52,

    while the plain mean of the seven batch losses is 0.5710.571.

  • Training and validation losses together are the main diagnostic (P4.22). If the training loss keeps falling and the validation loss turns upward, the model is starting to memorize (overfitting, P3.A3).

Devices: CPU and GPU

Tensors live on a device: "cpu" or "cuda" (an NVIDIA GPU). A GPU does large tensor operations much faster (P2.6). The model and its inputs must be on the same device. The standard pattern is:

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)                    # parameters move (do this before creating the optimizer)
# in the loop:
xb, yb = xb.to(device), yb.to(device)       # every batch moves
  • For a Module, .to(device) moves the parameters in place, so you can write model.to(device). For a tensor it returns a new tensor, so you must assign it: xb = xb.to(device).
  • Move the model before you build the optimizer. It is the safe habit: the PyTorch documentation asks for it for .cuda(), and in other cases (for example when parameters get replaced) an optimizer built earlier would hold the old tensors. (For a Module, .to(device) converts the parameters in place, so an earlier optimizer usually still works, but do not rely on it.)
  • If you forget to move the batch, PyTorch raises an error such as RuntimeError: Expected all tensors to be on the same device, but got mat1 is on cpu, different from other tensors on cuda:0. The wording varies with the operation. The fix is to move the tensors. In Colab, choose Runtime, Change runtime type and pick a GPU; every notebook cell here works on the CPU too.
  • Moving data from the CPU to a GPU takes time. Move once per batch, not once per number, and do not call .item() or .cpu() on every step unless you need the value.

Save and load

Go deeper Saving and loading a model: state_dict

A model’s learned numbers are in its state_dict(), a dictionary from parameter names to tensors. Save that, not the whole model object, because the object depends on the exact code that defined the class. To load, build the same architecture first and then load the numbers into it:

import io
buffer = io.BytesIO()                                  # in memory; use a file name like "model.pt" to save to disk
torch.save(model.state_dict(), buffer)
print("saved", len(buffer.getvalue()), "bytes;", "keys:", list(model.state_dict().keys()))

buffer.seek(0)
restored = Net(2, 16, 2)                               # build the same architecture first
restored.load_state_dict(torch.load(buffer, map_location="cpu"))
restored.eval(); model.eval()
same = torch.equal(restored(X_val[:5]), model.to("cpu")(X_val[:5]))
print("restored model gives the same outputs:", same)
saved 2653 bytes; keys: ['hidden.weight', 'hidden.bias', 'out.weight', 'out.bias']
restored model gives the same outputs: True

map_location="cpu" loads the tensors onto the CPU even if they were saved from a GPU. Only load files you trust: loading goes through Python’s pickle, which can run code. PyTorch 2.6 and later (including 2.9, used here) load with weights_only=True by default, which restricts what a file may contain, but the safe habit stays: do not load model files from sources you do not trust. To resume training and not just predict, also save optimizer.state_dict() (momentum and similar numbers live there) and the epoch number.

Common bugs

Every one of these is a mistake people make once. Each is easy to recognise when you know the symptom.

  • Forgetting zero_grad(). Symptom: Gradients grow every step; training is erratic or diverges. Fix: Call it once per batch, before backward().
  • zero_grad() between backward() and step(). Symptom: The loss never changes (the update is zero). Fix: Move it before backward() or after step().
  • loss.backward() twice on the same loss. Symptom: RuntimeError: Trying to backward through the graph a second time. Fix: One backward per forward.
  • softmax before CrossEntropyLoss. Symptom: Trains, but badly and slowly; the loss cannot go to 00. Fix: Pass raw logits.
  • Class numbers stored as floats instead of integers. Symptom: RuntimeError: expected scalar type Long but found Float. Fix: y.long(), shape (B,).
  • Forgetting model.eval() for validation. Symptom: Metrics change from run to run, or are worse than they should be. Fix: model.eval() before, model.train() after.
  • Adding up loss tensors. Symptom: Memory grows every step. Fix: loss.item().
  • Model and batch on different devices. Symptom: RuntimeError: Expected all tensors to be on the same device. Fix: .to(device) for the model and each batch.
  • Layers in a plain Python list. Symptom: parameters() is empty; nothing learns. Fix: nn.ModuleList or nn.Sequential.
  • Wrong shapes for MSELoss. Symptom: A warning about target size, and a wrong loss value. Fix: Make pred and target the same shape.

The notebook runs several of these on purpose. Two numbers, so you can recognise them:

  • Softmax before CrossEntropyLoss. For logits (4,0,0)(4,0,0) and target class 0 the right loss is 0.0360.036, but with a softmax applied first it is 0.5740.574. The loss applies softmax a second time to numbers that are already probabilities. For 3 classes it can then never fall below ln⁡e+2e=0.551\ln\frac{e+2}{e}=0.551, even for a perfect prediction.
  • Forgetting eval(). A model with Dropout(0.5) in training mode gives 0.580.58 and then 1.8151.815 for the same input twice. In evaluation mode it gives 0.4360.436 both times.
Go deeper What this lesson leaves out

A real training script adds a few more pieces. Weight initialization (how the parameters start, P4.12), learning-rate schedules (P4.14), regularization such as dropout and weight decay (P4.17) and gradient clipping (P4.16) all plug into the loop above without changing its shape. Mixed precision and multi-GPU training (P10.B5, P10.B6) wrap the same five lines. And a well-organised project adds early stopping and checkpoints on top. The skeleton you learned here stays the same.

Try it

Open the Colab notebook and run it top to bottom. Then try these changes, one at a time:

  • Delete the optimizer.zero_grad() line in the P0.2 loop and watch the loss.
  • Swap torch.optim.SGD for torch.optim.Adam (with lr=0.01 and no momentum) in the half-moons loop and compare the losses after 5 epochs.
  • Set shuffle=False for the training loader and see what changes.
  • Add nn.Dropout(0.5) after the hidden layer of Net, then remove the model.eval() line and compare the validation accuracy.

Quiz

Check your understanding

  1. Which order of the five lines in the batch loop is correct?

  2. What should the last layer of a classifier return when it is trained with nn.CrossEntropyLoss?

  3. At w=1w=1, b=0b=0 on the P0.2 data, the gradient of the loss with respect to ww is −10-10. You call loss.backward() three times in a row with no zero_grad in between. What is w.grad at the end?

  4. A dataset has 1000 examples and the DataLoader uses batch_size=32 with drop_last=False. How many optimizer steps happen in one epoch?

  5. Why does a validation loop use torch.no_grad()?

  6. The validation accuracy of a model with a Dropout layer changes every time you evaluate the same weights on the same data. Which is the most likely cause?

Exercises

  1. A dataset has N=1000N=1000 examples, the batch size is 3232, and you train for 10 epochs. How many optimizer steps are there with drop_last=False, and with drop_last=True?
    Show answerWith drop_last=False there are ⌈1000/32⌉=32\lceil1000/32\rceil=32 batches per epoch (31 of 32 and one of 8), so 320320 steps. With drop_last=True there are 3131 batches per epoch, so 310310 steps, and 8 examples are skipped each epoch (a different 8 each time when shuffling).
  2. A parameter is w=2w=2 with gradient 33. Plain SGD with η=0.1\eta=0.1 takes one step. What is ww after the step? If you had forgotten zero_grad() and the same gradient was computed twice, what would ww be?
    Show answerw=2−0.1⋅3=1.7w=2-0.1\cdot3=1.7. With the forgotten clear, .grad holds 3+3=63+3=6, so w=2−0.1⋅6=1.4w=2-0.1\cdot6=1.4.
  3. Is this loop correct? loss = loss_fn(model(xb), yb); loss.backward(); optimizer.step(); optimizer.zero_grad().
    Show answerYes, it works. zero_grad only has to run after the previous step and before the next backward, and here it runs at the end of each batch. (The first batch starts with empty gradients, so nothing is lost.) The loop breaks only if zero_grad sits between backward and step.
  4. A classifier has 3 classes and 5 examples. What shape and type must the targets have for nn.CrossEntropyLoss, and what shape do the logits have?
    Show answerLogits: shape (5, 3), floats. Targets, if you give class indices: shape (5,) with integers in {0,1,2}\{0,1,2\}, type torch.long. (Float class probabilities of shape (5, 3) are also accepted.)
  5. Six batches of 6464 have average loss 0.50.5 and a seventh batch of 1616 has loss 1.01.0. What is the average loss over all 400400 examples, and what do you get if you just average the seven batch losses?
    Show answerThe weighted average is 6⋅64⋅0.5+16⋅1.0400=208400=0.52\frac{6\cdot64\cdot0.5+16\cdot1.0}{400}=\frac{208}{400}=0.52. The plain mean of the seven numbers is 6⋅0.5+1.07=0.571\frac{6\cdot0.5+1.0}{7}=0.571, which gives the small batch too much weight.
  6. How many parameters does nn.Sequential(nn.Linear(10, 5), nn.ReLU(), nn.Linear(5, 1)) have, and how many tensors does parameters() return?
    Show answerThe first layer has 10⋅5+5=5510\cdot5+5=55, the second has 5⋅1+1=65\cdot1+1=6, so 6161 numbers. ReLU has no parameters. parameters() returns 4 tensors (two weights and two biases).
  7. Why can a model that is correct and trained well still give strange validation numbers if you forget model.eval(), and which layers would you have to have in the model for it to matter?
    Show answerIn training mode, dropout still zeroes random values and batch normalization uses the statistics of the current batch, so outputs differ from evaluation behaviour and can change from call to call. A model with only Linear and ReLU layers is not affected, which is why this bug can hide for a long time.
  8. Code: in the P0.2 loop, move optimizer.zero_grad() to sit between loss.backward() and optimizer.step(). What do the printed weights do, and why?
    Show answerThey stay at w=1w=1 and b=0b=0 for all 200 steps, and the loss stays at 6.0006.000: the gradients are erased before the step, so every update is zero.

Key takeaways

  • One training step has five lines: forward (pred = model(xb)), loss (loss = loss_fn(pred, yb)), optimizer.zero_grad(), loss.backward(), optimizer.step(). Run it once per batch, and repeat the whole pass over the data for several epochs.
  • backward() adds to each parameter's .grad, it does not replace it. So gradients must be cleared (zero_grad) before each backward. step() then reads .grad and updates the parameters; it does not compute gradients.
  • An nn.Module registers its layers in __init__ (assigned to self) and describes the computation in forward. Call model(x), not model.forward(x). model.parameters() lists everything the optimizer will update. Layers hidden in a plain Python list are not registered.
  • A map-style Dataset needs __getitem__ (and __len__ for shuffling and counting). TensorDataset wraps tensors. DataLoader cuts a dataset into batches: shuffle=True for training, not needed for validation; the last batch is smaller unless drop_last=True.
  • model.train() and model.eval() switch layers such as dropout and batch normalization between training and evaluation behaviour. torch.no_grad() stops PyTorch recording the graph. Validation uses both, and never calls backward or step.
  • nn.CrossEntropyLoss takes raw scores (logits) and, usually, class indices as Long tensors. Do not apply softmax first. Log loss.item(), not the loss tensor, and weight each batch by its size when averaging.
  • The model and each batch must be on the same device. Move the model with model.to(device) before building the optimizer, and move every batch inside the loop. Save and load parameters with state_dict().
Found a mistake? Tell us