Optimizer and train eval modes
Quick answer
Training alternates prediction, loss, gradient computation and parameter updates. Evaluation uses frozen parameters, appropriate module mode and no unnecessary gradient recording. Saving a checkpoint is a separate artifact-management task. Static examples tested locally with PyTorch 2.10.0+cpu; ByteMind execution is unverified.
One SGD update
import torchw=torch.nn.Parameter(torch.tensor(2.))opt=torch.optim.SGD([w],lr=0.25)opt.zero_grad(set_to_none=True)loss=(w-0)**2loss.backward()opt.step()print(w.item())Expected output: 1.0. The gradient is four and the step subtracts one.
How it works
For each training batch: model.train(), optimizer.zero_grad(set_to_none=True), forward, scalar loss, loss.backward(), optimizer.step(). Usually call train once per epoch. For evaluation call model.eval() and use no_grad or inference_mode. Dropout is random in training and identity in evaluation; batch normalization uses running statistics in evaluation when configured to track them. Neither eval nor no_grad alone provides both controls. Sum per-sample losses and divide by sample count, particularly for short final batches. For binary classification BCEWithLogitsLoss expects raw logits and float targets of matching shape. For inference save a locally generated state_dict, record trusted provenance and checksum, reconstruct the architecture, and load with explicit weights_only=True and map_location="cpu". Restricted loading is not proof of safety; never load untrusted checkpoints, and do not allowlist unknown objects. Full resumption also needs optimizer, RNG and scheduler state where applicable. CPU seeds, thread count and deterministic algorithms reduce variability but cannot guarantee cross-version or cross-device bitwise identity.
Evaluation mode and gradient mode
import torchfrom torch import nnm=nn.Dropout(p=0.5)x=torch.ones(4,requires_grad=True)m.eval()y=m(x)*2with torch.no_grad(): z=m(x)*2print(y.tolist(),y.requires_grad,z.requires_grad,m.training)Expected output: [2.0, 2.0, 2.0, 2.0] True False False. Dropout is inactive in eval, while no_grad separately suppresses graph recording.
Common mistakes
Forget zero_grad and gradients accumulate across batches. Applying sigmoid before BCEWithLogitsLoss changes the objective. Do not perform optimizer updates on evaluation data. Avoid saving arbitrary executable model objects or treating a checksum from an untrusted source as authentication.
Practice and next steps
Run the milestone, compare finite differences with autograd, inspect the held-out evaluation and verify that predictions survive the trusted weights-only round trip. Next: TensorFlow and Keras engineering.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Optimizer and train eval modes — knowledge check
Apply optimizer and train eval modes to small examples and debugging scenarios.
Which operation clears old gradients?
Which loss accepts raw binary logits?
Which combination is appropriate for ordinary inference?
What should be loaded for a trusted inference checkpoint?
Why record seeds and versions?