Blog · Deep learning

PyTorch model.eval() vs torch.no_grad(): what each does and why you need both

model.eval() switches dropout and batch norm to inference behavior; torch.no_grad() stops gradient tracking. Use both to validate, with checked code.

model.eval() changes how layers such as dropout and batch normalization behave. torch.no_grad() stops PyTorch from recording operations for gradients. The two are independent, so for validation and inference you normally use both. model.eval() alone still builds the autograd graph and spends memory on it; torch.no_grad() alone leaves dropout switched on and lets batch normalization keep updating its running statistics.

Mixing them up makes validation noisy, wastes memory or quietly changes the model during evaluation. Below, a short validation function uses both correctly, and two small experiments show what each switch does on its own. The examples run on a CPU with PyTorch and download nothing.

model.eval() vs torch.no_grad() at a glance

Question model.train() model.eval() torch.no_grad() torch.inference_mode()
What it controls The module's mode flag The module's mode flag Gradient recording Gradient recording, with less bookkeeping
Dropout Randomly zeroes values Passes values through unchanged Unchanged: follows the module's mode Unchanged: follows the module's mode
Batch normalization Uses batch statistics, updates running ones Uses stored running statistics Unchanged: follows the module's mode Unchanged: follows the module's mode
Builds the graph for backward() Yes Yes No No, and its tensors cannot be used in autograd later
Typical use Training steps With no_grad for validation and inference With eval() for validation and inference Pure inference, such as serving predictions

Validate a model the right way

This function switches to evaluation mode, turns off gradient recording, and puts the model back in whatever mode the caller had. The model contains both batch normalization and dropout, so it shows the difference:

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(4, 8), nn.BatchNorm1d(8), nn.ReLU(), nn.Dropout(0.5), nn.Linear(8, 1))
data = TensorDataset(torch.randn(64, 4), torch.randn(64, 1))
loader = DataLoader(data, batch_size=16)
loss_fn = nn.MSELoss()


def evaluate(model, loader, loss_fn):
    was_training = model.training
    model.eval()  # dropout off, batch norm uses its stored statistics
    total, count = 0.0, 0
    with torch.no_grad():  # no graph: less memory, faster
        for inputs, targets in loader:
            total += loss_fn(model(inputs), targets).item() * len(targets)
            count += len(targets)
    model.train(was_training)  # restore the caller's mode
    return total / count


bn = model[1]
before = bn.running_mean.clone()
first, second = evaluate(model, loader, loss_fn), evaluate(model, loader, loss_fn)
print("same loss on repeat:", first == second)
print("batch-norm statistics unchanged:", torch.equal(before, bn.running_mean))
print("back in training mode:", model.training)

# The common mistake: no_grad without eval()
with torch.no_grad():
    a, b = model(data.tensors[0]), model(data.tensors[0])
print("no_grad alone, same output twice:", torch.equal(a, b))
print("no_grad alone, statistics unchanged:", torch.equal(before, bn.running_mean))

Checked output:

same loss on repeat: True
batch-norm statistics unchanged: True
back in training mode: True
no_grad alone, same output twice: False
no_grad alone, statistics unchanged: False

With both switches, two validation passes give the same loss and leave the model untouched. With no_grad alone, dropout makes two passes over the same data disagree, and batch normalization has absorbed the validation batch into its running statistics, even though no gradient was ever computed.

Restoring the previous mode, rather than always calling model.train() on the way out, keeps the helper safe when the caller was already evaluating. Models that deliberately mix modes in their submodules need a more careful restoration policy.

The two switches are independent

This experiment applies each switch alone to a dropout layer and a tensor of sixteen ones:

import torch
from torch import nn

torch.manual_seed(7)
x = torch.ones(16, requires_grad=True)
dropout = nn.Dropout(p=0.5)

dropout.train()
with torch.no_grad():
    masked = dropout(x)
print("training still masks without gradients:", bool((masked == 0).any()))
print("training result records gradients:", masked.requires_grad)

dropout.eval()
evaluated = dropout(x * 2)
assert torch.equal(evaluated, torch.full_like(x, 2))
print("eval records gradients:", evaluated.requires_grad)
evaluated.sum().backward()
assert torch.equal(x.grad, torch.full_like(x, 2))

with torch.inference_mode():
    prediction = dropout(x * 2)
print("inference result records gradients:", prediction.requires_grad)
assert torch.equal(prediction, evaluated.detach())

Checked output:

training still masks without gradients: True
training result records gradients: False
eval records gradients: True
inference result records gradients: False

In training mode, dropout still masks values inside no_grad. In evaluation mode, dropout passes values through, yet the result still records gradients and backward() works. The seed makes the mask reproducible here; the script checks behavior rather than a particular random mask.

What model.eval() changes

Calling .eval() is the same as .train(False), and it sets the flag on every child module. Dropout and batch normalization read that flag, and custom modules can too. Many layers, including a plain linear layer, compute exactly the same thing in either mode.

Batch normalization adds state. With its usual settings, training mode normalises each batch with that batch's statistics and updates running averages, while evaluation mode uses the stored averages. Validation in training mode therefore changes the model, even inside no_grad. The PyTorch Module reference documents the mode switch, and the BatchNorm1d reference the running statistics.

The same detail matters when you freeze a pretrained model: requires_grad = False does not stop batch normalization from updating, as the transfer learning vs fine-tuning guide shows.

What torch.no_grad() and inference_mode change

Gradient recording keeps the intermediate values that backpropagation needs. Turning it off saves memory and time when you only want predictions. It does not change any module's mode flag.

torch.inference_mode() skips more bookkeeping than no_grad, but tensors created inside it cannot be used in autograd later. Trying it raises RuntimeError: Inference tensors cannot be saved for backward. Use it for a pure prediction path, and no_grad when results might feed later gradient computation. The autograd notes compare the modes.

Evaluation with gradients can be intentional. Input-gradient analysis, such as a saliency map, needs derivatives while keeping evaluation behavior, so it uses model.eval() without no_grad.

Common mistakes and their symptoms

Symptom Likely cause Fix
Validation scores change between runs on the same data Dropout still active: model.eval() was not called Call model.eval() before validating
Validation runs out of memory or is slow Gradients are being recorded Wrap validation in torch.no_grad()
Training gets worse after each validation pass Batch-norm statistics updated by validation batches Validate in evaluation mode
The model stops improving after the first validation Training continued in evaluation mode Call model.train() at the start of each training phase
Inference tensors cannot be saved for backward A tensor from inference_mode was used in autograd Use no_grad there, or clone the tensor first

No mode switch fixes leakage from preprocessing fitted on all the data, repeated groups across splits or features from the future. Those belong to the experiment design, covered in cross-validation for groups and time.

Common questions

Does model.eval() turn off gradients?

No. It only changes layer behavior. Outputs still record gradients unless you also use torch.no_grad() or torch.inference_mode().

Do I need model.eval() if I already use torch.no_grad()?

Yes, whenever the model has dropout, batch normalization or any custom layer that reads the training flag. Otherwise predictions stay random and batch-norm statistics keep changing.

Should I use torch.inference_mode() or torch.no_grad()?

Use inference_mode for code that only makes predictions, such as a serving endpoint. Use no_grad when the results might later be used in a computation that needs gradients.

Do I need to call model.train() after evaluation?

Yes, before the next training step, or dropout and batch normalization stay in evaluation behavior. A helper that restores the previous mode, like evaluate above, does this for you.

Does model.eval() matter for a model without dropout or batch norm?

Its outputs will be the same in both modes. Calling it is still a good habit, because layers added later, or inside a pretrained model, may depend on it.

Keep learning

Follow a full training step in a neural network forward and backward pass, and check tensor sizes with the convolution output shape walkthrough. The upcoming Deep Learning course outline shows where PyTorch, regularisation and normalization fit.

Code checked with PyTorch 2.15 on 29 October 2026.

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.