no_grad, inference_mode & Grad Modes

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Autograd records every operation on a tensor that requires gradients so that backward() can replay it in reverse (see Autograd Fundamentals). Recording costs memory and time, and most code that is not training does not need it: validation, prediction, optimizer updates and weight initialization. PyTorch therefore offers a small family of switches, called grad modes, that turn recording off for a block of code or for part of a graph. This page explains each switch, what exactly it changes, how they differ in speed and in what you may do with the result, and the pitfalls that surprise people the first time.

Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31. The conceptual side of backpropagation is covered in Backpropagation & Automatic Differentiation.

The mechanisms at a glance

The official autograd note ("Locally disabling gradient computation") names three mechanisms: context managers that switch off recording for a whole block (no-grad mode and inference mode), the requires_grad flag that excludes individual subgraphs, and evaluation mode, which is not a gradient mechanism at all but is described next to them because it is so often confused with one.

Mechanism Scope Typical use

torch.no_grad()

A block, a function (as decorator) or a thread-local flag

Evaluation, optimizer steps, manual parameter updates, weight initialization

torch.enable_grad()

A block that re-enables recording inside a no_grad block

Computing a gradient inside otherwise gradient-free code

torch.set_grad_enabled(mode)

A block (context manager) or the rest of the thread (function call), with a Boolean argument

One code path that sometimes trains and sometimes evaluates

torch.inference_mode()

A block or a function; stronger and faster than no_grad

Pure inference where no result will ever take part in autograd

tensor.requires_grad_(False), module.requires_grad_(False)

Individual leaf tensors or all parameters of a module

Freezing layers in transfer learning

tensor.detach()

One tensor in the middle of a graph

Cutting the graph, logging values, targets and cached activations

module.eval()

Layers whose behaviour depends on training

Switching dropout off and batch normalization to running statistics

The three grad modes

The note defines three modes. In the default grad mode the requires_grad flag is honoured: an operation is recorded in the graph when at least one input requires gradients. In no-grad mode, operations are not recorded in the backward graph, even when their inputs have requires_grad=True; the outputs can nevertheless be used later in grad mode. Inference mode is the extreme version of no-grad: besides not recording, it also skips additional bookkeeping, so it can run faster, but "tensors created in inference mode will not be able to be used in computations to be recorded by autograd after exiting inference mode".

The documentation summarizes this in a table whose content is reproduced here in our own words:

Mode Excludes operations from the backward graph Skips extra autograd overhead Tensors usable in grad mode afterwards

default

No

No

Yes

no-grad

Yes

No

Yes

inference

Yes

Yes

No

torch.no_grad

torch.no_grad works as a context manager and as a decorator. Everything computed inside has requires_grad=False, even when it is computed from tensors that require gradients.

import torch

x = torch.ones(3, requires_grad=True)

with torch.no_grad():
    y = x * 2
print(y.requires_grad)           # False

z = x * 2
print(z.requires_grad)           # True


@torch.no_grad()
def predict(t):
    return t * 2


print(predict(x).requires_grad)  # False

Source: https://docs.pytorch.org/docs/stable/autograd.html (locally disabling gradient computation)

A very common use is updating parameters by hand. Autograd refuses an in-place modification of a leaf tensor that requires gradients, but inside no_grad the update is allowed and, importantly, is not recorded:

w = torch.randn(3, requires_grad=True)
loss = (w ** 2).sum()
loss.backward()

with torch.no_grad():
    w -= 0.1 * w.grad      # plain SGD step, not recorded in the graph
    w.grad.zero_()

Outside no_grad the same line w -= ... raises "a leaf Variable that requires grad is being used in an in-place operation". The built-in optimizers do this for you, and torch.nn.init functions use no-grad mode internally for the same reason (see nn.Module).

Inside a no-grad block, tensors that you create still start with requires_grad=False, but you can ask for gradients explicitly with requires_grad_(); they will take part in graphs built later, outside the block.

torch.enable_grad and torch.set_grad_enabled

torch.enable_grad() is the inverse of no_grad: it turns recording back on inside a no_grad or set_grad_enabled(False) block. It has no effect inside inference_mode, where recording cannot be re-enabled (the executed snippet showed requires_grad staying False for a tensor computed under enable_grad() inside inference_mode()).

torch.set_grad_enabled(mode) takes a Boolean and works both as a context manager and as a plain function. As a function it changes the flag for the rest of the current thread until you change it back, so prefer the context-manager form.

x = torch.ones(3, requires_grad=True)

with torch.no_grad():
    with torch.enable_grad():
        w = x * 3
    print(w.requires_grad)                  # True: recording re-enabled

is_train = False
with torch.set_grad_enabled(is_train):
    print((x * 2).requires_grad)            # False

torch.set_grad_enabled(False)               # function form: stays off
print(torch.is_grad_enabled())              # False
torch.set_grad_enabled(True)                # always restore it

Source: https://docs.pytorch.org/docs/stable/autograd.html (locally disabling gradient computation)

set_grad_enabled(is_train) is convenient for a single function that serves both training and validation, because the Boolean can be passed in. Two details are worth remembering:

  • The grad-mode flag is thread-local. A new thread starts with grad mode enabled, regardless of what the thread that created it was doing, so a worker thread started inside a no_grad block still records a graph unless it sets the mode itself. The snippet in the verification section below shows this.

  • Decorating a generator function with no_grad keeps the mode active while the generator runs (the executed snippet printed [False, False] for a decorated generator that reports torch.is_grad_enabled() at each yield).

torch.inference_mode

torch.inference_mode is the mode intended for production inference and for any evaluation code whose outputs will never be used for training. It is stricter than no_grad: view tracking and version-counter bookkeeping are disabled for the tensors created inside, which is where the speed advantage comes from. Like no_grad it works as a context manager and as a decorator, and it accepts a mode argument (inference_mode(False) turns it off, which is useful to keep the mode switchable by a flag).

import torch

x = torch.ones(3, requires_grad=True)

with torch.inference_mode():
    a = x * 2
    print(a.is_inference(), a.requires_grad, torch.is_inference_mode_enabled())
    # True False True

print(a.is_inference())    # True: still an inference tensor after the block

try:
    (a * x).sum().backward()
except RuntimeError as e:
    print("RuntimeError:", e)   # Inference tensors cannot be saved for backward ...

Tensors created inside the block are inference tensors. The restrictions that follow from that are the main pitfall of the mode:

  • An inference tensor cannot be saved for backward. Using one in an operation with a tensor that requires gradients, outside the block, raises RuntimeError: Inference tensors cannot be saved for backward.

  • An in-place update of an inference tensor outside inference mode is rejected: RuntimeError: Inplace update to inference tensor outside InferenceMode is not allowed.

  • Inside the block, ordinary (non-inference) tensors created before it can still be modified in place, and the result is not tracked.

  • The error messages suggest the escape hatch: .clone() an inference tensor outside the block to get a normal tensor that autograd can use. In the executed snippet, c.clone() outside the block returned a normal tensor.

  • torch.save of an inference tensor works (the snippet saved one successfully).

  • torch.inference_mode(False) nested inside an inference-mode block turns the mode off locally. torch.is_inference_mode_enabled() reports the current state and Tensor.is_inference() reports whether a given tensor is an inference tensor.

b = torch.ones(2, 2)
with torch.inference_mode():
    c = b * 2

try:
    c.add_(1)                       # in-place on an inference tensor, outside the block
except RuntimeError as e:
    print("RuntimeError:", e)

ok = c.clone()                      # a normal tensor
print(ok.is_inference())            # False

The autograd note’s advice for these errors is to fall back to no_grad: it is the safe default, and the extra speed of inference mode is worth chasing only for code that really is a closed inference path (a serving loop, an evaluation function, preprocessing). Compare with the training loop and evaluation, where the validation pass uses one of these modes.

requires_grad and freezing

The flag requires_grad marks which leaf tensors accumulate .grad. It defaults to False for ordinary tensors and to True for nn.Parameter. According to the note, the flag is meaningful only for leaf tensors: results of operations automatically get it when at least one input has it, and setting it directly on a non-leaf tensor is an error. During the forward pass an operation is recorded only if at least one input requires gradients; during the backward pass only leaf tensors with requires_grad=True accumulate gradients.

Freezing a part of a model for transfer learning (see Transfer Learning & Foundation Models and PyTorch transfer learning) uses the in-place method requires_grad_(False), available on tensors and on nn.Module:

import torch.nn as nn

model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2))
model[0].requires_grad_(False)                      # freeze the first layer

print([p.requires_grad for p in model[0].parameters()])   # [False, False]
print([p.requires_grad for p in model[2].parameters()])   # [True, True]

# Give the optimizer only the trainable parameters
trainable = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(trainable, lr=0.1)

Freezing a layer does not stop gradients from flowing through it to earlier layers that are trainable; it only prevents the layer’s own parameters from receiving gradients. It also does not change the layer’s behaviour in train() mode: a frozen BatchNorm layer still updates its running statistics unless you also call eval() on it.

detach

tensor.detach() returns a tensor that shares storage with the original but is cut off from the graph: requires_grad=False and no history. It is the right tool to log a loss value, to use a network output as a fixed target, or to carry a recurrent hidden state across truncated-backpropagation chunks without extending the graph (see RNN, LSTM & GRU).

p = x * 2
q = p.detach()
print(q.requires_grad)                  # False
print(q.data_ptr() == p.data_ptr())     # True: same memory

Because the memory is shared, modifying q in place also changes p, and autograd detects such modifications through the version counter and raises an error at backward() if p was needed. Use .detach().clone() when you need an independent copy, for example when storing values in a list during training: appending the loss tensor itself keeps the entire graph alive, whereas appending loss.item() or loss.detach() does not. The older attribute tensor.data also bypasses the graph but is discouraged because it hides in-place modifications from autograd.

eval mode is a different thing

model.eval() is equivalent to model.train(False). It flips the training attribute of every submodule and has no effect on gradient recording. Layers react to it individually: dropout is switched off, batch normalization uses its running statistics instead of the batch statistics and stops updating them, and so on. The official note therefore recommends calling model.train() before training and model.eval() for validation and testing, even if you are not sure the model has training-specific layers.

Evaluation therefore normally needs both switches, and they are independent:

model.eval()                       # layer behaviour
with torch.inference_mode():       # gradient recording and bookkeeping
    logits = model(batch)
model.train()                      # back to training behaviour

Forgetting eval() gives noisy, non-deterministic predictions and wrong batch-norm statistics; forgetting no_grad or inference_mode only costs memory and time. Calling eval() and checking d(t).requires_grad on a dropout layer, as done in the executed snippet, still prints True for an input that requires gradients: eval mode does not stop recording.

Choosing a mode

  • Training step: default mode, model.train().

  • Validation during training, where you may later want to reuse the tensors in a graph (for example gradient-penalty checks): torch.no_grad() and model.eval().

  • Serving, batch prediction, metric computation, data preprocessing: torch.inference_mode() and model.eval(), with .clone() on any result that must later re-enter autograd.

  • Optimizer updates, EMA/SWA updates and manual weight initialization: torch.no_grad().

  • Freezing parameters for the whole run: requires_grad_(False), plus passing only trainable parameters to the optimizer.

  • Computing gradients inside gradient-free code (for example a saliency map during evaluation): torch.enable_grad() inside the no_grad block, which does not work inside inference_mode.

Compile-time and export paths have their own rules: torch.compile guards on the grad mode and may recompile when it changes (see torch.compile), and exported programs capture a fixed behaviour (see torch.export).

Verifying the behaviour

The following script reproduces the thread claim above: it prints [True], because a new thread starts with grad mode enabled.

import threading
import torch

res = []


def worker():
    res.append(torch.is_grad_enabled())


with torch.no_grad():
    t = threading.Thread(target=worker)
    t.start()
    t.join()
print(res)                       # [True]

Source: https://docs.pytorch.org/docs/stable/autograd.html (locally disabling gradient computation)

Common pitfalls

  • Evaluating without no_grad or inference_mode quietly builds a graph for every batch and can exhaust GPU memory in a long validation loop.

  • Appending a tensor that requires gradients to a Python list (for example per-step losses) keeps its graph alive; append .item() or .detach().

  • Using an inference tensor in a training computation raises the "cannot be saved for backward" error; clone it first or use no_grad instead of inference mode for that code path.

  • Using set_grad_enabled(False) as a function and never restoring it disables gradients for the rest of the thread, a frequent cause of "element 0 of tensors does not require grad and does not have a grad_fn".

  • Assuming that eval() disables gradients, or that no_grad disables dropout: they are independent.

  • Relying on grad mode inside a new thread, process or DataLoader worker: the mode is not inherited.