DL
intermediate
The PyTorch Training Loop
ML Engineer path · lesson 42 of 80Scikit-Learn hides training behind fit(). PyTorch makes you write the loop, and two of its lines exist purely to work around how autograd stores gradients. Forget one of them and the model quietly fails to train — no exception, no warning. Run both versions side by side.
Six lines, and what each one defends against
for epoch in range(n_epochs):
loss.backward() — Autograd in action: walk the graph backwards and compute the gradient of the loss with respect to every parameter. Crucially, this accumulates into each parameter's .grad rather than replacing it.
Gradients cleared each iteration, as they should be.
0.10
Loss at step 1
49.76
Loss at step 16
0.09
Converging
yes
The loss falls from 49.8 to 0.094 over sixteen steps. Every gradient is computed fresh, so each update is the step the optimiser actually intended.
Write the training loop
Sequence
Order the five lines inside a PyTorch batch loop.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
5 pieces left to place
Test your knowledge
20 questions
Question 1 of 20
Score: 0
What does calling backward() on a tensor do to the .grad attribute of every variable used to compute it?
Learn these first
Interview Questions
Meta
NVIDIA
OpenAI
Anthropic
Google
Amazon
Tesla
Microsoft
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required