7 routes42 sections324 units

Unit 2.7 · about 4 h

183 / 324

Explicit 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_grad evaluation, 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

  1. Optimizing Model Parameters: `train_loop` and `test_loop`
    PyTorch - Learn the Basics

    Hyperparameters (epochs, batch size, learning rate); Loss Function (CrossEntropyLoss over logits); Optimizer (zero_grad, backward, step); Full Implementation (train_loop with model.train, test_loop with model.eval and no_grad, accuracy accumulation)

  2. HOML: mini-batch loops and metric aggregation
    Hands-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() and evaluate() functions, the batch-mean RMSE (0.5668) against the whole-set RMSE (0.6388), and the streaming TorchMetrics version

    Depth · 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_loop sets model.train() and test_loop sets model.eval() with no_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_loss divides by batch count, which weights batches equally. With an uneven tail batch that differs from the sample mean; correct over size is exact.
  • CrossEntropyLoss takes raw logits and reduces by mean over the batch. Changing batch size changes the noise of that mean, not its expectation.

Reproduce closed-book

From memory, write train and test loops with sample-weighted loss and accuracy, train the Learn PyTorch 01 workflow model, and reach its task gates. Then show the tutorial 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(). Dropout keeps dropping units, so evaluation becomes random, and BatchNorm normalizes 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

  1. Test set 10000, batch 64. The tutorial reports test_loss /= num_batches. What does that number weight equally?

  2. Where must zero_grad sit relative to backward and step, and what breaks if it is missing?

  3. test_loop wraps evaluation in no_grad but the tutorial also sets model.eval(). What does each contribute?

  4. Your evaluation loop uses CrossEntropyLoss with reduction="mean" per batch. How do you report the exact per-sample mean loss over the test set?

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

Comes after

Resources for this unit

  • PyTorch - Learn the Basics
    PyTorchprimarycourse
    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
    Aurelien Geron (O'Reilly, 2025)supporttheory
    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
    PyTorchrequiredreference
    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
    Daniel Bourkerequiredpractice
    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
    Howard Huang, Luca Antiga, Eli Stevens and Thomas Viehmann (Manning)supportimplementation
    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
    NeetCodeoptionalpractice
    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
    PyTorchreferencereference
    Read the Saving/Resuming section: save scaler.state_dict() with the model and optimizer state, at the start of an iteration or after scaler.update(), and how to resume with or without AMP.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels