Every PyTorch training step is the same five lines
Memorize this rhythm. You'll write it ten thousand times across your career, and it never changes:
optimizer.zero_grad()— clear accumulated gradients from the previous step.output = model(batch)— forward pass. Builds the autograd graph.loss = criterion(output, target)— compute the scalar loss.loss.backward()— backward pass. Populates.gradon every leaf.optimizer.step()— apply the update rule using the gradients.
The order is non-negotiable. Forward must happen before loss; loss before backward; backward before step; step after gradients exist; zero_grad before any of it (or at the very end of the previous iteration). Mixing them produces silent bugs.
What wraps the five steps
- An outer loop over epochs (one full pass through the dataset).
- An inner loop over batches from a DataLoader.
model.train()at the top of each epoch (or once before the loop, since training is the default mode).- A periodic evaluation pass (use
model.eval()+torch.inference_mode()).
That's the whole skeleton. Everything else — schedulers, gradient clipping, mixed precision, logging, checkpointing — is a layer on top of these five steps.