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 , , , the same start , , the same learning rate and the same 200 updates. The model 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 , then , after the first update, then losses and , and a prediction of at after 200 updates (the exact best line gives ). 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.
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 of examples, the loss is the average of the per-example losses, . The five lines compute this loss, its gradient, and one update with learning rate :
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 . backward() computes 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 parametersThese 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 for each example (P4.1, P4.5). PyTorch stores a batch as rows, so in code it isx @ W.T + b. Its weight has shape(d_out, d_in). Here the two layers have and parameters, in all.forwarddescribes the computation for a batch. The input has a leading batch dimension:xhas shape(B, 2), and the output has shape(B, 2).- Call the model, do not call
forward. Writemodel(x). The call runsforwardand also does bookkeeping that PyTorch relies on (hooks, for example). Callingmodel.forward(x)directly skips it. model.parameters()gives every parameter tensor of every registered layer, andnamed_parameters()gives them with names. The optimizer will update exactly these. Each parameter hasrequires_grad=Truealready (P2.6).nn.Sequentialis 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 asloss_fn(pred, target). The two must have the same shape. Ifpredhas shape(3, 1)andtargethas shape(3,), PyTorch warns and broadcasts them into a grid of differences. For the P0.2 data that turns the correct loss into , 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 typetorch.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 :
optimizer = torch.optim.SGD(model.parameters(), lr=0.05)
torch.optim.SGD with its default settings does exactly (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 during training are in P4.14.
An optimizer does two things, through two methods:
optimizer.zero_grad()clears the.gradof every parameter it holds. (By default it sets them toNone, which is the same as zero for the next backward pass and saves a little memory.)optimizer.step()reads each parameter’s.gradand updates the parameter. It does not compute gradients;loss.backward()does.
The five lines, and why their order matters
For each batch:
- Forward:
pred = model(xb). Compute the predictions. PyTorch records the operations (P1.C10). - Loss:
loss = loss_fn(pred, yb). One number for the batch. optimizer.zero_grad(): clear the gradients left by the previous batch.loss.backward(): compute the gradient of the loss with respect to every parameter, and add it into.grad.optimizer.step(): use.gradto 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 , after one batch with :
| Order | Result after one batch | Why |
|---|---|---|
| zero_grad, backward, step | , | the correct update from P0.2 |
| backward, zero_grad, step | , | the 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 is , 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 , 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 , 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 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 . Withdrop_last=Truethat small batch is thrown away (each epoch drops a different 16 when shuffling). The default keeps it.num_workers: the default 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 underif __name__ == "__main__":, or each worker would run it again.)generator: the random-number generator used for shuffling. Giving it a seededtorch.Generatormakes 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 examples and batch size , one epoch has iterations ( with drop_last=True). With our 400 training examples, batch size gives iterations per epoch, and the batch size used in the full loop below gives (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()andmodel.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 ofLinearandReLUlayers is unaffected, but get into the habit anyway: forgetting it is a classic bug. A new model starts in training mode, so callmodel.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 callsbackward, 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 is not a multiple of , which matters for layers that use batch statistics; that is one reason people use
drop_last=True. If six batches of have loss and one batch of has loss , the right average iswhile the plain mean of the seven batch losses is .
-
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 writemodel.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 aModule,.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: Truemap_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, beforebackward(). zero_grad()betweenbackward()andstep(). Symptom: The loss never changes (the update is zero). Fix: Move it beforebackward()or afterstep().loss.backward()twice on the same loss. Symptom:RuntimeError: Trying to backward through the graph a second time. Fix: One backward per forward.softmaxbeforeCrossEntropyLoss. Symptom: Trains, but badly and slowly; the loss cannot go to . 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
losstensors. 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.ModuleListornn.Sequential. - Wrong shapes for
MSELoss. Symptom: A warning about target size, and a wrong loss value. Fix: Makepredandtargetthe same shape.
The notebook runs several of these on purpose. Two numbers, so you can recognise them:
- Softmax before
CrossEntropyLoss. For logits and target class 0 the right loss is , but with a softmax applied first it is . The loss applies softmax a second time to numbers that are already probabilities. For 3 classes it can then never fall below , even for a perfect prediction. - Forgetting
eval(). A model withDropout(0.5)in training mode gives and then for the same input twice. In evaluation mode it gives 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.SGDfortorch.optim.Adam(withlr=0.01and no momentum) in the half-moons loop and compare the losses after 5 epochs. - Set
shuffle=Falsefor the training loader and see what changes. - Add
nn.Dropout(0.5)after the hidden layer ofNet, then remove themodel.eval()line and compare the validation accuracy.
Quiz
Check your understanding
Which order of the five lines in the batch loop is correct?
Gradients are cleared before the backward pass, which fills them, and the step reads them afterwards. Clearing them between the backward pass and the step erases the gradients just before they are used, so the parameters would not change. A step before the backward pass would use stale gradients, and a backward pass needs the loss to exist first.
What should the last layer of a classifier return when it is trained with nn.CrossEntropyLoss?
CrossEntropyLoss applies log-softmax internally, so raw logits are what it expects. A softmax before it is applied twice, which flattens the loss and stops it reaching 0. The model should output scores, not one-hot vectors, and the loss does not need bounded inputs.
At , on the P0.2 data, the gradient of the loss with respect to is . You call loss.backward() three times in a row with no zero_grad in between. What is w.grad at the end?
Each backward pass adds its gradient to .grad, so the values after the three calls are -10, -20 and -30. If .grad were replaced each time it would stay at -10, which is not what happens. The value is not 0, and nothing is averaged.
A dataset has 1000 examples and the DataLoader uses batch_size=32 with drop_last=False. How many optimizer steps happen in one epoch?
1000 divided by 32 is 31 full batches plus a last batch of 8 examples (31 times 32 is 992), so there are 32 batches, and one optimizer step per batch. With drop_last=True the small batch is dropped and there would be 31. One step per example, 1000, would be batch size 1.
Why does a validation loop use torch.no_grad()?
Validation never calls backward, so the record of operations would be wasted. Switching dropout and batch normalization is the job of model.eval(). The weights only change when step() is called, which validation never does. Without no_grad the code still runs; it just uses more memory.
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?
In training mode dropout zeroes a random set of values on every forward pass, so the same input gives different outputs. zero_grad has no effect on a forward pass, the learning rate has no effect when the weights are not being updated, and the order of validation examples does not change the average.
Exercises
- A dataset has examples, the batch size is , and you train for 10 epochs. How many optimizer steps are there with
drop_last=False, and withdrop_last=True?Show answer
Withdrop_last=Falsethere are batches per epoch (31 of 32 and one of 8), so steps. Withdrop_last=Truethere are batches per epoch, so steps, and 8 examples are skipped each epoch (a different 8 each time when shuffling). - A parameter is with gradient . Plain SGD with takes one step. What is after the step? If you had forgotten
zero_grad()and the same gradient was computed twice, what would be?Show answer
. With the forgotten clear,.gradholds , so . - Is this loop correct?
loss = loss_fn(model(xb), yb); loss.backward(); optimizer.step(); optimizer.zero_grad().Show answer
Yes, it works.zero_gradonly has to run after the previousstepand before the nextbackward, 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 ifzero_gradsits betweenbackwardandstep. - 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 answer
Logits: shape(5, 3), floats. Targets, if you give class indices: shape(5,)with integers in , typetorch.long. (Float class probabilities of shape(5, 3)are also accepted.) - Six batches of have average loss and a seventh batch of has loss . What is the average loss over all examples, and what do you get if you just average the seven batch losses?
Show answer
The weighted average is . The plain mean of the seven numbers is , which gives the small batch too much weight. - How many parameters does
nn.Sequential(nn.Linear(10, 5), nn.ReLU(), nn.Linear(5, 1))have, and how many tensors doesparameters()return?Show answer
The first layer has , the second has , so numbers.ReLUhas no parameters.parameters()returns 4 tensors (two weights and two biases). - 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 answer
In 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 onlyLinearandReLUlayers is not affected, which is why this bug can hide for a long time. - Code: in the P0.2 loop, move
optimizer.zero_grad()to sit betweenloss.backward()andoptimizer.step(). What do the printed weights do, and why?Show answer
They stay at and for all 200 steps, and the loss stays at : the gradients are erased before the step, so every update is zero.