What does model.eval() do in PyTorch?
par Équipe NextData
PyTorch tutorials call model.eval() before validation and model.train() before training. What does this change, and is it the same thing as torch.no_grad()?
Signaler
1 réponse
model.eval() switches the model to evaluation mode. It changes the behaviour of the layers that act differently in training and in inference:
- Dropout stops zeroing activations at random;
- Batch normalization uses its stored running statistics instead of the statistics of the current batch.
model.train() switches back. Layers without such a difference are unaffected.
It is not the same as torch.no_grad():
model.eval() |
torch.no_grad() |
|
|---|---|---|
| Changes layer behaviour | Yes | No |
| Stops gradient tracking | No | Yes |
| Benefit | Correct, deterministic predictions | No gradients are stored |
For validation and inference you normally want both:
model.eval()
with torch.no_grad():
for inputs, targets in validation_loader:
outputs = model(inputs)
...
model.train() # before resuming training
Common mistakes:
- Forgetting
model.eval(). Predictions vary from one call to the next and the validation score drops. Measured on a small network with batch normalization and dropout (PyTorch 2.14, average of 20 runs): accuracy was 0.911 withmodel.eval(), 0.870 without it when validating in batches of 32, and 0.713 in batches of 4. Two identical validation passes withouteval()differed by 0.006 on average. These figures depend on the model and the data. - Forgetting
model.train()afterwards. Dropout stays disabled for the rest of training, with no error message. - Assuming
eval()stops gradient tracking. It does not; that is the job oftorch.no_grad().
For the reviewer to check: recent PyTorch versions also provide torch.inference_mode(), a stricter alternative to torch.no_grad().
Réponse rédigée par l'équipe NextData et relue par un expert.
