Unit 2.7 · about 4 h
183 / 324Explicit training and evaluation loops with correct metrics
The loop is where grad state, eval state and metrics meet. A wrong reduction here fakes every comparison the rest of the stage makes.
- implement
- measure
You can now
- Write train and test loops with train and eval modes,
no_gradevaluation, zeroing, backward and step in the right order. - Aggregate loss and accuracy with stated reduction and sample weighting, and catch batch-mean versus sample-mean drift.
- Drive a loop to a stated gate (moons accuracy, workflow regression) and read its loss and accuracy printouts.
Covers
- Explicit train_one_epoch and evaluate loops
- Metric aggregation and reduction correctness
Study, in this order
2 steps
- Optimizing Model Parameters: `train_loop` and `test_loop`PyTorch - Learn the Basics
Hyperparameters (epochs, batch size, learning rate); Loss Function (
CrossEntropyLossover logits); Optimizer (zero_grad, backward, step); Full Implementation (train_loopwithmodel.train,test_loopwithmodel.evalandno_grad, accuracy accumulation) - HOML: mini-batch loops and metric aggregationHands-On Machine Learning with Scikit-Learn and PyTorch
Chapter 10, Implementing Mini-Batch Gradient Descent Using DataLoaders and Model Evaluation (printed pp. 335-339): the
train()andevaluate()functions, the batch-mean RMSE (0.5668) against the whole-set RMSE (0.6388), and the streaming TorchMetrics versionDepth · Footnote 10 calls the short last batch a negligible effect on a batch-mean MSE. Your reproduce measures that gap instead of assuming it.
Focus on
train_loopsetsmodel.train()andtest_loopsetsmodel.eval()withno_grad. The comments call both best practice even where the tiny net needs neither.- Zero before backward each iteration (or right after step, every iteration).
step()applies whatever sits in.grad, including stale values. - The tutorial
test_lossdivides by batch count, which weights batches equally. With an uneven tail batch that differs from the sample mean; correct over size is exact. CrossEntropyLosstakes raw logits and reduces by mean over the batch. Changing batch size changes the noise of that mean, not its expectation.
Reproduce closed-book
test_loop loss and your sample-weighted loss differ on an uneven tail batch.Traps
- Averaging per-batch losses with equal weights and calling it the epoch loss. Short tail batches then count as much as full ones.
- Evaluating without
model.eval().Dropoutkeeps dropping units, so evaluation becomes random, andBatchNormnormalizes with test-batch statistics while updating its running buffers on test data. - Logging
loss.item()but stepping on a different loss. The printed number and the backward graph must come from the same tensor.
Practice
Learn PyTorch 01: `SGD` training loop and test plots (tasks 1 to 4)
Exercises, tasks 1 to 4: straight-line dataset, L1Loss with SGD for 300 epochs testing every 20, test predictions with plots
Keep the loop explicit: no high-level trainer. Record the exact reduction of every logged number.
Learn PyTorch 02: moons classifier loop above 96 percent (tasks 1 to 4)
Exercises, tasks 1 to 4: make_moons split, nonlinear nn.Module, binary loss and optimizer, train and test loop past 96 percent accuracy with prints every 10 epochs
Stop at task 4 for this unit. Task 6 (pure-PyTorch tanh) belongs to the backward unit; tasks 5 to 7 are the stretch goals.
Self-test
-
Test set 10000, batch 64. The tutorial reports
test_loss /= num_batches. What does that number weight equally?Batches: 156 full plus one tail batch of 16. The tail batch counts as much as any full batch, so the figure is a batch mean, not the sample mean. -
Where must
zero_gradsit relative to backward and step, and what breaks if it is missing?Every iteration, before backward (or right after step). Without it,.gradaccumulates across batches andstep()applies stale plus fresh gradients together. -
test_loopwraps evaluation inno_gradbut the tutorial also setsmodel.eval(). What does each contribute?eval()switchesDropoutandBatchNormto evaluation behavior.no_grad()skips graph recording, saving memory and compute. -
Your evaluation loop uses
CrossEntropyLosswithreduction="mean"per batch. How do you report the exact per-sample mean loss over the test set?Accumulateloss.item()times the batch size (or usereduction="sum") and divide the total by the number of samples, not by the number of batches.
Completion criterion
Stop when
Both loops run from memory, every logged number states its reduction, and the moons run passes 96 percent with a sample-weighted loss you can defend.
Mark passed, then open 2.8 Only mark this when you can do it without notes.Leads to
- 2.8 Checkpoints, configuration and reproducibility Persist the loop state you can now run.
- 3.7 Objective checks, tiny-set overfit and shuffled-label controls Add overfit and shuffled-label controls to the loop.
Comes after
- 2.3 Modules, parameters, buffers and initializationTrain the module you can now inspect.
- 2.4 Backward, `zero_grad`, `gradcheck` and evaluation modesPut zeroing, backward and eval switching into a real loop.
- 2.6 Datasets, data loaders and samplersFeed the loop from a loader you trust.
- 3.8 Diagnosing failed runs: divergence, stale state, slices and seedsFix stale state with correct train and eval loops and metrics.
Resources for this unit
- PyTorch - Learn the Basics Complete Tensors, Datasets and DataLoaders, Transforms, Build Model, Autograd, Optimization, and Save and Load Model. Rebuild each essential example in a small src package instead of retaining a tutorial notebook.
- Hands-On Machine Learning with Scikit-Learn and PyTorch Read Chapter 10, Implementing Mini-Batch Gradient Descent Using DataLoaders and Model Evaluation, for the train and evaluate loops and how batch metrics must be aggregated.
Also in this section
- PyTorch - Autograd mechanics, serialization and reproducibility Read Autograd mechanics, Serialization semantics and Reproducibility. Test leaf behavior, saved tensors, grad modes, state dictionaries and the exact tolerance promised by one interrupted and resumed run.
- Learn PyTorch - selected framework exercises Complete exercise 00, tasks 1-5 in 01, tasks 1-7 in 02, tasks 5-13 in 03, tasks 1-3 in 05, and exercises 1-2 in 07. Recreate solutions independently and verify behavior against current official docs.
- Deep Learning with PyTorch, 2nd edition - framework foundations Read Sections 3.8-3.9 and 5.5 when tensor storage, strides or autograd need a second explanation, with the Chapter 3 and 5 companion notebooks for runnable cells. Inspect the Chapter 4 and 7 code only for a diagnosed data-representation or loading gap.
- NeetCode ML - PyTorch closing drills After the module gate, solve Pytorch Basics, Layer Normalization, Batch Normalization and RMS Normalization cold. Explain shapes, state and train-evaluation behavior aloud. These do not replace the package and resume test.
- PyTorch Automatic Mixed Precision recipe - Saving/Resuming Read the Saving/Resuming section: save
scaler.state_dict()with the model and optimizer state, at the start of an iteration or afterscaler.update(), and how to resume with or without AMP.