PyTorch
torch.no_grad
torch.inference_mode
deep learning optimization
machine learning efficiency

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).

python
1import torch
2
3model = MyModel()
4model.eval()
5
6x = torch.randn(1, 3, 224, 224)
7
8with torch.no_grad():
9    output = model(x)
10    # output.requires_grad is False
11    # No computation graph built
12    # But output tensors behave like normal tensors

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:

python
@torch.no_grad()
def predict(model, x):
    return model(x)

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.

python
1import torch
2
3model = MyModel()
4model.eval()
5
6x = torch.randn(1, 3, 224, 224)
7
8with torch.inference_mode():
9    output = model(x)
10    # output is an "inference tensor"
11    # Cannot be used in autograd outside this block
12    # PyTorch skips version counting and view tracking

Using an inference tensor in a gradient-tracked operation outside the block raises an error:

python
1with torch.inference_mode():
2    y = model(x)
3
4# This will raise an error:
5z = y * torch.tensor([1.0], requires_grad=True)
6# RuntimeError: Inference tensors cannot be saved for backward. ...

Side-by-side comparison

Featuretorch.no_grad()torch.inference_mode()
Disables gradient trackingYesYes
Saves memoryYesYes, more aggressively
Tensors usable in autograd laterYesNo (raises error)
Skips version countingNoYes
Skips view trackingNoYes
Performance benefitGoodBetter
Available sincePyTorch 0.4PyTorch 1.9
Safe for mixed workflowsYesNo
Recommended for production inferenceWorks but not optimalYes

Where the speedup comes from

inference_mode removes two kinds of bookkeeping:

  1. Version counting: PyTorch keeps a version counter on every tensor to detect in-place modifications that could invalidate the autograd graph.
  2. View tracking: when you create a view (for example tensor.view(...) or tensor[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:

python
1import torch
2import time
3
4model = torch.nn.Linear(1000, 1000).cuda()
5x = torch.randn(64, 1000).cuda()
6
7# Benchmark no_grad
8torch.cuda.synchronize()
9start = time.perf_counter()
10for _ in range(10000):
11    with torch.no_grad():
12        _ = model(x)
13torch.cuda.synchronize()
14no_grad_time = time.perf_counter() - start
15
16# Benchmark inference_mode
17torch.cuda.synchronize()
18start = time.perf_counter()
19for _ in range(10000):
20    with torch.inference_mode():
21        _ = model(x)
22torch.cuda.synchronize()
23inference_time = time.perf_counter() - start
24
25print(f"no_grad: {no_grad_time:.3f}s")
26print(f"inference_mode: {inference_time:.3f}s")

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
python
1@torch.inference_mode()
2def serve_prediction(model, input_tensor):
3    model.eval()
4    return model(input_tensor)

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_mode existed
  • GAN training loops where generator outputs feed back into discriminator gradients
python
1# Validation loop inside training
2model.eval()
3val_loss = 0.0
4
5with torch.no_grad():
6    for batch in val_loader:
7        output = model(batch)
8        loss = criterion(output, batch.target)
9        val_loss += loss.item()
10
11model.train()

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.

ConcernControlled by
Gradient computationtorch.no_grad() / torch.inference_mode()
Dropout behaviormodel.eval() / model.train()
BatchNorm statisticsmodel.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:

python
1model.eval()  # Switch modules to eval behavior
2
3with torch.inference_mode():  # Disable autograd
4    output = model(input_tensor)

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:

python
1@torch.inference_mode()
2def predict(model, x):
3    model.eval()
4    return model(x)
5
6@torch.no_grad()
7def compute_metrics(model, data):
8    model.eval()
9    outputs = model(data)
10    return calculate_metrics(outputs)

Course
Intermediate
27 lessons
15 hours
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 course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design