Training Loops in PyTorch
Part of the Machine Learning Roadmap
In short
Keras hides the training loop behind fit(). PyTorch makes you write it. That feels like extra work for about a day, and then it becomes your superpower: you can see, debug and change every step of training.
A PyTorch training loop repeats the same steps for each batch: forward pass, compute loss, zero the gradients, backward pass and optimizer step, with a separate validation loop using torch.no_grad(). Writing it yourself makes every model you train later easy to debug.

Think of it like this
The roti routine
Making rotis is the same five moves on repeat: roll the dough (forward pass), check if it's round (loss), wipe the board clean (zero gradients), notice where it went lopsided (backward pass), adjust your hands (optimizer step). Then the next roti. Every so often you just taste one without changing anything: that's the validation loop.
Watch it happen
One training step on one batch
1/6The DataLoader hands over 64 shuffled examples and labels, moved to the GPU if there is one.
The big ideas
What you need to know
Five lines, every batch
Forward, loss, zero_grad, backward, step. The order of zero_grad and backward matters.
train() and eval() modes
model.train() turns dropout and batch norm training behaviour on. model.eval() turns it off for validation.
torch.no_grad() for validation
Skip building the gradient graph when you're only measuring. It saves memory and time.
Same device for everything
Model and batches must both be on the CPU or both on the GPU. Use a device variable and .to(device).
See it in code
Walk through the code
1import torch2import torch.nn as nn3from torch.utils.data import DataLoader, TensorDataset4 5device = "cuda" if torch.cuda.is_available() else "cpu"6X, y = torch.randn(5000, 20), torch.randint(0, 2, (5000,))7train_dl = DataLoader(TensorDataset(X[:4000], y[:4000]), batch_size=64, shuffle=True)8val_dl = DataLoader(TensorDataset(X[4000:], y[4000:]), batch_size=256)9 10model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Dropout(0.2), nn.Linear(64, 2)).to(device)11loss_fn = nn.CrossEntropyLoss()12optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)13 14for epoch in range(10):15 model.train()16 for xb, yb in train_dl:17 xb, yb = xb.to(device), yb.to(device)18 logits = model(xb)19 loss = loss_fn(logits, yb)20 optimizer.zero_grad()21 loss.backward()22 optimizer.step()23 24 model.eval()25 correct, val_loss = 0, 0.026 with torch.no_grad():27 for xb, yb in val_dl:28 xb, yb = xb.to(device), yb.to(device)29 logits = model(xb)30 val_loss += loss_fn(logits, yb).item() * len(yb)31 correct += (logits.argmax(dim=1) == yb).sum().item()32 print(epoch, round(val_loss / 1000, 4), correct / 1000)1/6Pick a device, make data, and wrap it in DataLoaders. Only the training loader shuffles.
A complete train and validation loop. Swap in your own dataset and model and the skeleton stays the same.
Save yourself the pain
Common mistakes
Oops
Forgetting optimizer.zero_grad().
Do this instead
Gradients pile up across batches and training goes haywire. Zero them every step, before backward().
Oops
Applying softmax before nn.CrossEntropyLoss.
Do this instead
CrossEntropyLoss applies log-softmax itself. Pass raw logits, or the loss is wrong and training slows.
Oops
Validating without model.eval().
Do this instead
Dropout stays active and your validation scores become noisy and too pessimistic. Switch modes every epoch.
Your mission
Train on Fashion-MNIST
Quick check
What is the correct order inside a PyTorch training step?
Go deeper
- 1Write a full training and validation loop with a Dataset and DataLoader.
- 2Log training and validation loss per epoch and save the best model's state_dict.
- 3Overfit a tiny batch on purpose to check the loop can learn at all.
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.