Write a PyTorch Training Loop from Scratch
Machine LearningModel answerLast updated
Implement a complete per-batch training loop in PyTorch, covering device placement, gradient management, and per-epoch loss tracking.
Write a PyTorch Training Loop from Scratch
You have the following ingredients already prepared for you:
model— atorch.nn.Modulerepresenting your neural networktrain_loader— aDataLoaderthat yields(inputs, targets)tuplesoptimizer— a PyTorch optimizer (e.g. Adam, SGD)loss_fn— a callable loss function (e.g.nn.CrossEntropyLoss())device— a string ortorch.deviceindicating where computation should run ("cpu"or"cuda")num_epochs— how many full passes over the dataset to perform
Implement the function below:
def train(
model, train_loader, optimizer, loss_fn, device, num_epochs, verbose=True
) -> list[float]:
...
Your implementation must:
- Move the model to
devicebefore training begins. - Set the model to training mode at the start of each epoch.
- For every batch, execute the following steps in the correct order:
- Move inputs and targets to
device - Clear accumulated gradients
- Run the forward pass
- Compute the loss
- Run backpropagation
- Update model parameters
- Move inputs and targets to
- Return a list of average per-sample training losses, one per epoch. Use size-weighted averaging so partial final batches are handled correctly.
- Avoid retaining the computation graph across batches.
When verbose=True, print the epoch number and average loss after each epoch.
What to address in your answer:
- The exact order of operations inside the batch loop, and why each step must come where it does
- Common bugs that arise from getting this order wrong
- How to compute a correct epoch-level average loss
- Memory and performance considerations
- Edge cases worth handling
Hints
Hint 1
PyTorch accumulates gradients by default — they don't reset between backward calls unless you explicitly clear them. Where you place that reset relative to the other steps matters more than it seems.
Hint 2
Use loss.item() to extract the scalar loss value for bookkeeping. Accumulating the tensor itself keeps the entire computation graph alive for every batch, which leaks memory fast on GPU.
Hint 3
The last batch from a DataLoader is often smaller than the rest. If your loss function uses reduction='mean', averaging those per-batch means directly gives a slightly wrong epoch average — weight each batch by its actual batch size instead.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Key idea
Every PyTorch training loop is built around one fixed per-batch sequence. Get the order right, understand why it's right, and handle the edge cases cleanly. That's the whole problem.
The correct order of operations
Within each batch, the steps must follow this sequence:
- Move data to the device
- Zero gradients —
optimizer.zero_grad(set_to_none=True) - Forward pass —
outputs = model(inputs) - Compute loss —
loss = loss_fn(outputs, targets) - Backward pass —
loss.backward() - Update parameters —
optimizer.step()
Why this order is non-negotiable:
-
Zero gradients before backward. PyTorch accumulates gradients into
param.gradon everybackward()call rather than overwriting them. This design choice enables gradient accumulation across micro-batches, but it means if you skipzero_grad(), each update uses the sum of all previous batches' gradients. Training either diverges or behaves unpredictably. The one place you must never putzero_grad()is betweenbackward()andstep()— that erases the gradients you just computed before the optimizer can use them. -
Forward before loss. The forward pass constructs the autograd computation graph. The loss is a scalar node at the top of that graph. Reversing this makes no sense structurally.
-
loss.backward()beforeoptimizer.step(). Backward traverses the graph and populatesparam.grad. The optimizer reads those values to compute parameter updates. Callingstep()beforebackward()applies stale or zero gradients. -
model.train()at the start of each epoch. Layers like Dropout and BatchNorm behave differently during training versus inference. Ifmodel.eval()was called somewhere earlier in your code, skippingmodel.train()silently changes how those layers behave without any error. -
model.to(device)once, before the loop. This moves parameters in place. The optimizer's references to those parameters remain valid. One nuance: if the optimizer already has accumulated state (e.g. Adam's first and second moment estimates from a checkpoint), that state must also live on the correct device.
Computing per-epoch loss correctly
Most loss functions default to reduction="mean", meaning they return the average loss over the batch. The last batch is often smaller than the rest. If you naively average those per-batch means, the final partial batch gets the same weight as a full batch, which slightly skews the reported number.
The correct approach is size-weighted averaging:
running_loss += loss.item() * batch_size
num_samples += batch_size
# ...
epoch_loss = running_loss / num_samples
Using loss.item() (not loss) is important here. Accumulating the tensor keeps a reference to every batch's computation graph and leaks GPU memory. .item() extracts a plain Python float and releases the graph.
Complete solution
import math
from typing import List
import torch
from torch import nn
from torch.utils.data import DataLoader
def train(
model: nn.Module,
train_loader: DataLoader,
optimizer: torch.optim.Optimizer,
loss_fn: nn.Module,
device: torch.device | str,
num_epochs: int,
verbose: bool = True,
) -> List[float]:
"""Train model in place; return size-weighted average loss per epoch."""
device = torch.device(device)
model.to(device)
history: List[float] = []
for epoch in range(num_epochs):
model.train() # re-enable dropout / batchnorm training behavior
running_loss = 0.0
num_samples = 0
for inputs, targets in train_loader:
# 1. Move batch to the model's device
inputs = inputs.to(device, non_blocking=True)
targets = targets.to(device, non_blocking=True)
# 2. Clear accumulated gradients
optimizer.zero_grad(set_to_none=True)
# 3. Forward pass — builds the autograd graph
outputs = model(inputs)
# 4. Compute scalar loss
loss = loss_fn(outputs, targets)
# 5. Backward pass — fills param.grad for each parameter
loss.backward()
# 6. Update parameters using param.grad values
optimizer.step()
# Bookkeeping — .item() releases the graph reference
batch_size = inputs.size(0)
running_loss += loss.item() * batch_size
num_samples += batch_size
epoch_loss = running_loss / num_samples if num_samples > 0 else math.nan
history.append(epoch_loss)
if verbose:
print(f"Epoch {epoch + 1}/{num_epochs} loss: {epoch_loss:.4f}")
return history
Complexity
- Time: O(E × N × C), where E is epochs, N is training samples, and C is the cost of one forward+backward pass per sample. The loop itself adds O(1) overhead per batch.
- Space: O(P + B × A), where P covers parameters, gradients, and optimizer state (Adam stores two extra momentum tensors per parameter, so roughly 4× parameter memory), and B × A is activation memory for one batch. Because
backward()frees the graph and we storeloss.item(), only one batch's graph lives in memory at a time.
Edge cases and common mistakes
num_epochs = 0: the loop body never runs; return an empty list.- Empty DataLoader:
num_samplesstays zero, so guard against division by zero and returnnanor skip reporting. - Forgetting to move targets to the device. Moving only inputs is a very common mistake and produces a device-mismatch error on GPU. Both tensors must move.
- Gradient clipping. If you need it (e.g. for RNNs), insert
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)betweenbackward()andstep(), never before or after. - Non-finite loss. A NaN or inf loss silently corrupts all parameters. Production loops often check
torch.isfinite(loss)and break early. set_to_none=Truevs zeroing. The default in recent PyTorch isset_to_none=True. It sets gradients toNoneinstead of filling with zeros, saving a memset and allowing the optimizer to skip parameters that received no gradient this step.non_blocking=Trueon.to(device). When the DataLoader usespin_memory=True, this flag lets the host-to-device copy overlap with GPU compute on the previous batch, improving throughput at no correctness cost.