The annotated PyTorch training loop
TL;DR Highlight
Misplacing lines in a PyTorch training loop silently breaks training without raising any error
Who Should Read
A developer writing their own PyTorch training loop who can't figure out why loss won't converge or memory keeps growing
Core Mechanics
- Failures are silent
- Misplaced lines can make training fail to converge, give wrong results, or use too much memory.
- Most of these raise no exception, so they are hard to spot.
- Put zero_grad before backward
- Placing it after backward makes gradients from multiple batches accumulate.
- The update then uses their sum instead of the current batch alone.
- Placement of clip_grad_norm_ matters
- Called before backward, grad is empty and the call does nothing.
- Called after optimiser.step(), it clips gradients already applied and has no effect.
- Don't forget model.train() after validation
- Without it, Dropout stays off and BatchNorm uses frozen statistics.
- No error is raised.
- Use torch.no_grad() in validation
- Without it, an autograd graph builds on every validation batch until OOM.
- With it, memory drops roughly by half versus a training-mode forward pass.
- Move the model to device before building the optimiser
- Combining a dtype conversion like .half().to(device) allocates new Parameter objects.
- An optimiser built earlier updates the discarded originals.
- Call scheduler.step() once per epoch
- Inside the batch loop, LR decays len(loader) times per epoch.
Community Reactions
- Opinion that PyTorch already hides complexity well
- The commenter says you can build a GPT model with readable code.
- They argue many breaking points are natural because deep learning isn't trivial.
- Interest in the host site
- One commenter asked whether anyone had used the site before.
- Mobile rendering bug report
- A commenter said the site's foundations course page doesn't render correctly on mobile.
How to Apply
- Audit your loop's line order today
- Open your existing loop and confirm the order zero_grad, forward, loss, backward, clip, step.
- Check that scheduler.step() sits outside the batch loop.
- Add eval, no_grad and train restore to validation
- Use model.eval() and with torch.no_grad() right before validation.
- Make sure model.train() runs at the start of the next epoch.
- Use gradient accumulation when GPU memory is short
- Divide the loss by ACCUM_STEPS and only call backward each batch.
- Run clip, step and zero_grad every ACCUM_STEPS batches.
- Add set_seed when you need reproducibility
- Seed torch, cuda, numpy and random before building the model and loader.
- If num_workers is above 0, also pass a generator and worker_init_fn.
Try It
# Paste into Claude or ChatGPT (the article's checklist turned into a prompt)
Review the PyTorch training loop below. Check each item one by one, and for any problem give the line number and corrected code.
1. Is optimiser.zero_grad() before loss.backward()
2. Is clip_grad_norm_ after backward and before optimiser.step()
3. Is scheduler.step() outside the batch loop (once per epoch)
4. Does it return to model.train() after validation
5. Does validation use torch.no_grad()
6. Do model.to(device) and dtype conversions come before building the optimiser
7. Does logging use loss.item() instead of loss
{{training loop code}}Terminology
Related Papers
Quadrillion-parameter transformers and how to train them
On fixed data, much bigger models with scaled weight decay and ensembling keep loss falling as compute grows.
Astra can read and write weights to improve Qwen
An LLM edited Qwen3.5-0.8B's weights directly, lifting MATH-500 from 7.9% to 48.1%.
Show HN: Qwen3-4B with the AI writing tics trained out
Distilling Qwen3-4B with LoRA cut its AI-writing slop score from 121 to 12.5 per 1000 words
Dust: Pretraining Transformers Without Backpropagation
Adding per-token noise to activations lets transformers pretrain without backpropagation, rivaling backprop.
Show HN: TurboGPT: train 22KiB transformer in 13s
A CUDA C++ project trains a tiny byte-level GPT in under a minute.
I had Gemini train its own replacement for $9
Fine-tuning GLiNER on $9 of Gemini labels reached 0.83 F1 locally.
Learning to solve hard problems in RL for LLMs by never giving up
Cutting compute on easy problems and retrying hard ones in RL raised accuracy on the hardest problems
Training a 3.8B LLM to 0.384 CORE for $998
A 3.8B LLM trained on 8 B200s in 43 hours for $998 scored 0.384 on CORE.