Controlling Gradients: zero_grad, no_grad and detach
Three tools control gradients in PyTorch. zero_grad() clears old gradients so they do not pile up between steps. torch.no_grad() turns off graph building for a block of code. detach() returns a tensor that shares data but is cut off from the graph. Getting these right avoids silent training bugs and saves a lot of memory.
Gradients accumulate
By design, backward() adds to the existing .grad instead of replacing it. This is useful for gradient accumulation across several mini-batches, but in a normal training loop it is a bug if you forget to reset.
import torch
w = torch.tensor(1.0, requires_grad=True)
for i in range(3):
loss = (w * 2) ** 2 # derivative is 8*w = 8
loss.backward()
print(i, w.grad)
# 0 tensor(8.)
# 1 tensor(16.)
# 2 tensor(24.)
The true gradient is 8 each time, but the stored value grows because nothing cleared it. In a real loop the optimiser would then take steps in the wrong direction and training would behave strangely, often with a loss that stops improving or explodes.
Clearing gradients
With an optimiser you call optimizer.zero_grad() at the start of each step, or right after optimizer.step(). For a single tensor use w.grad.zero_().
w = torch.nn.Parameter(torch.tensor(1.0))
opt = torch.optim.SGD([w], lr=0.1)
for i in range(3):
opt.zero_grad() # clear before computing new gradients
loss = (w * 2) ** 2
loss.backward()
opt.step()
print(i, w.grad.item(), w.item())
Recent PyTorch versions set gradients to None by default when you call zero_grad() (the set_to_none=True behaviour), which is slightly faster and saves memory. If your own code reads p.grad directly after clearing, remember that it may be None rather than a tensor of zeros.
torch.no_grad(): inference and updates
Inside a with torch.no_grad(): block, operations do not record a graph, so results have requires_grad=False. Use it whenever you do not need gradients: evaluation, prediction, and manual weight updates.
model = torch.nn.Linear(4, 1)
x = torch.rand(2, 4)
out = model(x)
print(out.requires_grad) # True
with torch.no_grad():
out = model(x)
print(out.requires_grad) # False
This saves memory because intermediate activations are not kept for a backward pass, and it makes the code run faster. You can also use it as a decorator: @torch.no_grad() above a function such as evaluate. There is a related context manager, torch.inference_mode(), which is slightly stricter and faster, and is a good choice for pure inference code. Tensors created in inference mode cannot later be used in autograd, so use no_grad if you might need them for training.
detach(): cut a tensor from the graph
x = torch.tensor([1.0, 2.0], requires_grad=True)
y = x * 3
z = y.detach() # same values, no history
print(z.requires_grad) # False
# A detached tensor shares memory with the original
z[0] = 100.0
print(y) # tensor([100., 6.], grad_fn=<MulBackward0>)
Use detach() when you want a value as a constant: for logging, converting to NumPy, using a target network's output in reinforcement learning, or passing a hidden state to the next batch in a recurrent network without back-propagating through earlier batches. Because the detached tensor shares storage, changing it changes the original. Call .detach().clone() for an independent copy.
Turning tracking on and off for parameters
To freeze part of a model, such as the pretrained layers in transfer learning, set requires_grad_(False) on its parameters.
model = torch.nn.Sequential(
torch.nn.Linear(10, 5),
torch.nn.ReLU(),
torch.nn.Linear(5, 1),
)
for p in model[0].parameters():
p.requires_grad_(False) # freeze the first layer
trainable = [n for n, p in model.named_parameters() if p.requires_grad]
print(trainable) # ['2.weight', '2.bias']
Frozen parameters get no gradient and are skipped by optimisers that you build from only the trainable ones. This both saves compute and keeps those weights unchanged.
Common mistakes
- Forgetting
zero_grad(): loss behaves oddly because gradients from previous steps are mixed in. - Calling
zero_grad()betweenbackward()andstep(): this wipes the gradients before they are used, so no learning happens. - Evaluating without
no_grad: memory grows and evaluation is slower than necessary. - Storing losses with history: use
loss.item()orloss.detach()when logging. - Detaching too early: if a tensor in the middle of your model is detached, layers before it receive no gradient and silently stop training.
A correct step order is always: clear gradients, forward pass, loss, backward(), step(). Next you will use everything from this section to fit a line without any nn helpers.
Comments
No comments yet. Have a question or a tip? Be the first to share it.