PREP WITH PROOF
Menu
CERTIFICATION STUDY GUIDES / PRACTICAL GUIDE

PyTorch inference_mode vs no_grad: Train a Frozen Encoder’s Head

Use torch.no_grad() when frozen features feed a trainable head. A worked PTCA example shows why inference_mode can fail and how to check the weight gradient.

THE QUICK ANSWER

Use torch.no_grad() around a frozen encoder when its output feeds a trainable head. The encoder forward stays out of the gradient graph, and the head can still save those features to compute its weight gradients. Use torch.inference_mode() for a forward pass whose outputs stay outside gradient-tracked computation, such as a stand-alone validation pass. Call model.eval() separately when you need evaluation behavior from layers such as Dropout.

Find the first operation that still needs gradients

You inherited a PyTorch training loop that replaces the classifier on top of a frozen encoder. The code wraps the encoder forward in inference_mode(). It fails when the new linear head consumes the features, even though those features have requires_grad=False. The head’s weight gradient still depends on the values of its input, so the linear operation tries to save that input for backward. PyTorch disallows saving an inference tensor for backward. The exception can therefore appear during the head’s forward pass.

Choose the context based on where the features go. If the head is being fitted, export ordinary tensors from the encoder with no_grad() and run the head and loss in normal grad mode. If a complete forward pass only produces held-out predictions and metrics, inference_mode() can cover that pass.

Source: PyTorch reference for inference_mode ↗

Work out the weight gradient before you run the code

Take one feature row [1, 2, 3], one head with weights [1, 0, 0], and a target of 0. The prediction is 1. With a squared error of (prediction − target)², the head’s weight gradient is 2 × (1 − 0) × [1, 2, 3] = [2, 4, 6]. Even a frozen encoder supplies the numbers used in this calculation.

This CPU example uses an identity weight matrix for the encoder so the features are easy to check. It records the head and loss after no_grad() has ended. The two assertions verify exactly which parameters get gradients.

import torch
from torch import nn

encoder = nn.Linear(3, 3, bias=False).eval()
encoder.requires_grad_(False)
head = nn.Linear(3, 1, bias=False).train()
x = torch.tensor([[1.0, 2.0, 3.0]])

with torch.no_grad():
    encoder.weight.copy_(torch.eye(3))
    head.weight.copy_(torch.tensor([[1.0, 0.0, 0.0]]))
    features = encoder(x)

prediction = head(features)
loss = (prediction - 0.0).square().mean()
loss.backward()

assert encoder.weight.grad is None
torch.testing.assert_close(
    head.weight.grad, torch.tensor([[2.0, 4.0, 6.0]])
)

PTCA practice question: Which scope should change?

The encoder must stay frozen in evaluation mode. The classifier must learn from the encoder’s output. Which change preserves both requirements?

A. Keep the encoder in eval(), run its forward pass under no_grad(), then compute the head and loss outside the context. This is the correct choice. The head can save ordinary feature tensors while the encoder stays frozen.

B. Put both forwards and the loss under no_grad(), then call backward() outside the context. The head’s operations ran with gradient recording disabled. Leaving the context later cannot recover the graph.

C. Keep inference_mode() on the encoder and call head.train() before consuming its features. train() selects a module’s training behavior. The features are still inference tensors, so a trainable linear head can still hit the save-for-backward error.

Source: PyTorch autograd mechanics and grad modes ↗

Check the tensor, the graph and the module mode

Inspect features.is_inference() when you suspect an inference tensor crossed into a training step. Then check loss.requires_grad before calling backward() and head.weight.grad afterwards. If validation still produces inconsistent results on identical inputs, inspect module.training separately. Gradient mode controls recording, while eval() controls the behavior of modules that implement an evaluation mode.

If you later fine-tune the encoder, re-enable gradients on the intended parameters, include them in the optimizer and remove the no_grad() boundary around the trainable forward. Select train() or eval() for the affected modules based on the behavior you want during fine-tuning.

Source: PyTorch autograd mechanics and grad modes ↗

KEEP THESE THREE THINGS

Your next steps

  1. Use no_grad() for frozen features that feed a trainable operation.
  2. Place a validation-only forward in inference_mode() when its outputs stay outside gradient-tracked computation.
  3. Check the head gradient and the encoder’s module mode independently.

Sources & official resources

Linked resources checked on 2026-12-01. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →