Run PyTorch inference with the correct model and gradient modes
Reliable inference needs two independent decisions. Put the model into evaluation mode so layers behave appropriately, and disable gradient recording when predictions will not participate in training. Calling only one of these can leave unnecessary autograd work or training-specific layer behavior active.
Understand the two controls
model.eval() changes the module's training flag recursively. Dropout stops randomly dropping activations. Batch normalization normally uses its learned running statistics rather than updating them from the current batch. An ordinary linear layer has no special evaluation behavior. Custom modules can inspect the flag and implement their own distinction.
Autograd evaluation-mode explanation
.
torch.inference_mode() controls autograd bookkeeping for operations in its context. It does not call eval() for you. It is suitable when you want final predictions that will not later enter a gradient-recorded calculation. torch.no_grad() is less restrictive and is often convenient when creating tensors that will subsequently be used in training.
Inference-mode reference
.
Run an observable example
Use Python 3.14 and PyTorch 2.15. A CPU installation is enough. Save the example as inference.py and run it with Python.
import torch
from torch import nn
model = nn.Sequential(nn.Linear(2, 2), nn.Dropout(p=0.5))
with torch.no_grad():
model[0].weight.copy_(torch.eye(2))
model[0].bias.zero_()
x = torch.tensor([[2.0, 4.0]])
model.eval()
# Evaluation mode alone still records a gradient graph.
ordinary = model(x)
assert ordinary.requires_grad
with torch.inference_mode():
prediction = model(x)
assert not prediction.requires_grad
assert not model.training
assert not model[1].training
assert torch.equal(prediction, x)
print(prediction.tolist())
The output is [[2.0, 4.0]]. The linear layer was initialized as the identity, and dropout is inactive in evaluation mode. The first assertion demonstrates why calling eval() alone does not disable gradients. The second forward pass produces the same values without a gradient graph.
During training, dropout applies its probability rule and rescales retained activations. Do not write a test that assumes two random outputs must differ. They can coincide by chance. Test the documented evaluation behavior instead, as this example does. Dropout reference .
Return to training after validation
A conventional training loop can switch modes around validation. Restore the previous flag even when validation raises an exception.
was_training = model.training
try:
model.eval()
with torch.no_grad():
validation_prediction = model(x)
finally:
model.train(was_training)
This pattern assumes the model normally uses one training mode for its whole module tree. If you intentionally keep selected submodules in evaluation mode, preserve and restore those choices separately. A recursive train(True) would otherwise undo them.
Avoid misleading diagnoses
Evaluation mode does not load a checkpoint, freeze parameters, choose a device or guarantee deterministic kernels. Verify the trained weights, preprocessing and input device separately when predictions look wrong. Gradient disabling also does not clear gradients already stored on parameters from an earlier backward pass.
Batch normalization has an additional configuration boundary. With track_running_stats=False, it uses batch statistics in both training and evaluation modes. Small inference batches can therefore behave differently from a model using saved running statistics. Check the actual module configuration rather than assuming that every batch-normalization layer has the default behavior.
BatchNorm1d reference
.
The example and restoration path were checked on CPU with PyTorch 2.15. Their purpose is to verify mode semantics. They do not measure accelerator performance or prediction quality.
Question provenance
This article addresses What does model.eval() do in pytorch? , asked by Gulzar on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored. No answer text or code is reproduced.
Author: Herman Schoenfeld