torch.inference_mode vs torch.no_grad in PyTorch
Codemia Knowledge Hub ·
torch.no_grad() and torch.inference_mode() both disable gradient computation, but they are not interchangeable. inference_mode is stricter and faster, meant for pure inference paths whose outputs never need gradients. no_grad is more permissive: it stops gradient tracking but leaves tensors as normal tensors, so it suits mixed workflows like validation inside a training script.
What torch.no_grad() does
torch.no_grad() stops PyTorch from building the autograd graph for operations inside the context. That saves memory (no gradient tensors stored) and time (no graph construction).
Tensors produced inside no_grad are regular tensors. You can mutate them and use them in later autograd operations outside the block. Only gradient recording is removed.
It also works as a decorator:
What torch.inference_mode() does
torch.inference_mode() also disables autograd, but it creates inference tensors with extra restrictions: they cannot be used in autograd computations later and cannot be mutated in certain ways. In exchange, PyTorch skips internal bookkeeping that no_grad still performs.
Using an inference tensor in a gradient-tracked operation outside the block raises an error:
Side-by-side comparison
| Feature | torch.no_grad() | torch.inference_mode() |
| Disables gradient tracking | Yes | Yes |
| Saves memory | Yes | Yes, more aggressively |
| Tensors usable in autograd later | Yes | No (raises error) |
| Skips version counting | No | Yes |
| Skips view tracking | No | Yes |
| Performance benefit | Good | Better |
| Available since | PyTorch 0.4 | PyTorch 1.9 |
| Safe for mixed workflows | Yes | No |
| Recommended for production inference | Works but not optimal | Yes |
Where the speedup comes from
inference_mode removes two kinds of bookkeeping:
- Version counting: PyTorch keeps a version counter on every tensor to detect in-place modifications that could invalidate the autograd graph.
- View tracking: when you create a view (for example
tensor.view(...)ortensor[0]), PyTorch normally records its relationship to the base tensor for autograd correctness.
The savings add up in models with many operations, especially transformers with heavy view and reshape usage. To measure it on your own setup:
The exact speedup depends on model and hardware. For small models it is negligible; for large models with complex tensor operations, inference_mode can be measurably faster.
When to use each
Use torch.inference_mode() for
- serving predictions in a production API
- evaluating on a test dataset with no training interaction
- deploying a model whose outputs never need gradients
- benchmarking inference throughput
If your inference path is genuinely read-only, using no_grad out of habit leaves performance on the table.
Use torch.no_grad() for
- validation loops inside a training script where tensors might interact with training logic
- computing loss for logging during training, where loss tensors may feed metrics that touch autograd
- debugging model outputs and inspecting intermediate tensors
- older codebases written before
inference_modeexisted - GAN training loops where generator outputs feed back into discriminator gradients
Code that works under no_grad may fail under inference_mode: if any tensor from inside the block touches a gradient-tracked computation, you get a RuntimeError. Nesting the two is not neutral: tensors created anywhere inside an inference_mode block are inference tensors (is_inference() returns True), even when that block sits inside no_grad, so they carry the same restrictions.
Neither replaces model.eval()
This is the most common source of bugs. The context managers control autograd; model.eval() controls module behavior.
| Concern | Controlled by |
| Gradient computation | torch.no_grad() / torch.inference_mode() |
| Dropout behavior | model.eval() / model.train() |
| BatchNorm statistics | model.eval() / model.train() |
Without model.eval(), dropout still randomly zeroes activations and BatchNorm uses batch statistics instead of running statistics, so results are wrong and non-deterministic. Correct inference combines both:
After validation, call model.train() again before the next training iteration, or the model trains with dropout and batch norm in eval mode.
Decorator form
Both work as decorators, which is equivalent to wrapping the whole function body in the context manager:
Related reading
- PyTorch using LR-Scheduler with param groups of different LR's
- PyTorch What's the difference between state_dict and parameters?
- Quantize a Keras neural network model
- Question about Backpropagation Algorithm with Artificial Neural Networks -- Order of updating
- pytorch torchvision.datasets.ImageFolder FileNotFoundError Found no valid file for the classes .ipynb_checkpoints
- Pytorch ValueError optimizer got an empty parameter list
- Q-learning vs dynamic programming
- Q-learning vs temporal-difference vs model-based reinforcement learning
System design interview problems on this topic
- Design an LLM Inference Service: solution and walkthrough
- Design a GPU Cluster Scheduler for ML Training: solution and walkthrough
- Design ChatGPT: solution and walkthrough
- Design an E-commerce Recommendation System: solution and walkthrough

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.