Autograd in PyTorch
In the NumPy autograd lesson you built a Tensor that records its parents and a _backward closure, sorts the graph and sweeps it in reverse. PyTorch's autograd is the same machine, written in C++ and extended with the controls a real training script needs: which tensors are tracked at all, which gradients are kept, how to cut a graph, how to switch recording off, how to get gradients of gradients, and how to plug in an operation of your own. This lesson goes through those controls one at a time and ends by running one graph through both engines to show that their gradients agree to six decimals.
All examples except the NumPy one are recorded: they ran on a CPU in the course's PyTorch image.
Leaves, non-leaves and the recorded graph
A tensor created by you with requires_grad=True is a leaf; model parameters are leaves. A tensor produced by an operation on tracked tensors is a non-leaf: it has a grad_fn, the backward node of the operation that made it, and that node points to the nodes of its inputs through next_functions. The chain ends at an AccumulateGrad node per leaf, which is where gradients are written into .grad.
By default backward() keeps gradients only for leaves: intermediate gradients are computed, passed on and thrown away, which saves memory. Call retain_grad() on a non-leaf to keep its gradient for inspection. Like the NumPy engine, PyTorch adds into .grad, so a second backward pass on a new graph doubles the gradient unless it is reset; and unlike the NumPy engine, it frees the graph's saved values after backward(), so a second backward through the same graph is an error (unless the first one passed retain_graph=True).
For a non-scalar output there is no single gradient, only the Jacobian . Reverse mode never builds ; it computes a vector-Jacobian product, and v.backward(gradient=u) supplies the vector:
loss.backward() on a scalar is the special case . Why reverse mode suits a scalar loss with millions of parameters is explained in forward and reverse mode.
import torch
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True) # leaves: created by you
w = torch.tensor(0.5, requires_grad=True)
y = w * x # non-leaf: the result of an op
y.retain_grad() # ask autograd to keep dz/dy
z = (y ** 2).sum()
print("is_leaf x", x.is_leaf, " w", w.is_leaf, " y", y.is_leaf, " z", z.is_leaf)
print("requires_grad y", y.requires_grad, " grad_fn z:", type(z.grad_fn).__name__)
node, chain = z.grad_fn, []
while node is not None: # walk the recorded graph backwards
chain.append(type(node).__name__)
node = node.next_functions[0][0] if node.next_functions else None
print("chain from z:", " -> ".join(chain))
z.backward()
print("dz/dx", x.grad.tolist(), " dz/dw", w.grad.item(), " dz/dy (retained)", y.grad.tolist())
z2 = ((w * x) ** 2).sum() # a new graph, same leaves
z2.backward()
print("after a second backward, x.grad accumulated:", x.grad.tolist())
x.grad = None; w.grad = None # what optimizer.zero_grad() does
try:
z2.backward() # the graph was freed after use
except RuntimeError as e:
print("backward twice on one graph -> RuntimeError:", str(e).split(".")[0])
v = x * 2 # a vector output
try:
v.backward()
except RuntimeError as e:
print("non-scalar backward -> RuntimeError:", e)
v.backward(gradient=torch.tensor([1.0, 0.1, 0.01])) # computes the vector-Jacobian product g^T J
print("x.grad with gradient=[1, 0.1, 0.01]:", [round(g, 4) for g in x.grad.tolist()])is_leaf x True w True y False z False
requires_grad y True grad_fn z: SumBackward0
chain from z: SumBackward0 -> PowBackward0 -> MulBackward0 -> AccumulateGrad
dz/dx [0.5, 1.0, 1.5] dz/dw 14.0 dz/dy (retained) [1.0, 2.0, 3.0]
after a second backward, x.grad accumulated: [1.0, 2.0, 3.0]
backward twice on one graph -> RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed)
non-scalar backward -> RuntimeError: grad can be implicitly created only for scalar outputs
x.grad with gradient=[1, 0.1, 0.01]: [2.0, 0.2, 0.02]
The printed facts, in order: and are leaves, and are not. The chain from z.grad_fn is SumBackward0 to PowBackward0 to MulBackward0 to an AccumulateGrad (following the first input each time; the multiplication's first input is w). For with , gives , , and the retained . A second, new graph adds the same amount again: x.grad becomes . Setting .grad = None is what optimizer.zero_grad() does by default. A second backward through the freed graph raises a RuntimeError, and so does backward() on a vector without gradient=. With and the result is .
Cutting and switching off the graph
Three tools stop recording, at three scopes:
| Tool | Scope | Result |
|---|---|---|
t.detach() |
one tensor | a tensor sharing the same memory, with no grad_fn and requires_grad=False |
with torch.no_grad(): |
a block | nothing inside is recorded; results have requires_grad=False |
with torch.inference_mode(): |
a block | like no_grad, plus no version counters: faster, but its results can never enter autograd later |
detach is the stop-gradient of the math: has the value of and derivative 0, so , not . It is used for targets computed from the model itself (target networks, teacher outputs) and for logging values without keeping the graph alive.
torch.autograd.grad(outputs, inputs) returns gradients instead of adding them to .grad. With create_graph=True the backward pass is itself recorded, so the returned gradient can be differentiated again: second derivatives, Hessian-vector products, and penalties on gradients such as the gradient penalty of WGAN-GP or input-gradient regularisation.
import torch
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = x * 3
d = y.detach() # same storage, cut from the graph
print("detach: requires_grad", d.requires_grad, " grad_fn", d.grad_fn, " shares memory", d.data_ptr() == y.data_ptr())
with torch.no_grad(): # nothing is recorded
p = x * 3
print("no_grad: requires_grad", p.requires_grad)
with torch.inference_mode(): # stricter and faster: no version counters
q = x * 3
print("inference_mode: requires_grad", q.requires_grad, " is_inference", q.is_inference())
try:
(q * x).sum().backward()
except RuntimeError as e:
print("inference tensor used in autograd -> RuntimeError")
# stop-gradient in a loss: only the first factor gets a gradient
x.grad = None
loss = (x * x.detach()).sum()
loss.backward()
print("grad of sum(x * x.detach()):", x.grad.tolist(), "(x, not 2x)")
# torch.autograd.grad returns gradients instead of filling .grad; create_graph=True makes them differentiable
t = torch.tensor(2.0, requires_grad=True)
f = t ** 3
(df,) = torch.autograd.grad(f, t, create_graph=True)
(d2f,) = torch.autograd.grad(df, t)
print("f = t^3 at t = 2: f' =", df.item(), " f'' =", d2f.item(), " t.grad still", t.grad)
# a gradient penalty uses the same trick: the norm of an input gradient, then backprop through it
w = torch.tensor([1.0, -2.0], requires_grad=True)
xin = torch.tensor([0.5, 1.5], requires_grad=True)
out = torch.tanh(w @ xin)
(g,) = torch.autograd.grad(out, xin, create_graph=True)
penalty = (g ** 2).sum()
penalty.backward()
print("input gradient", [round(v, 4) for v in g.tolist()], " d penalty / dw", [round(v, 4) for v in w.grad.tolist()])detach: requires_grad False grad_fn None shares memory True
no_grad: requires_grad False
inference_mode: requires_grad False is_inference True
inference tensor used in autograd -> RuntimeError
grad of sum(x * x.detach()): [1.0, 2.0, 3.0] (x, not 2x)
f = t^3 at t = 2: f' = 12.0 f'' = 12.0 t.grad still None
input gradient [0.0266, -0.0532] d penalty / dw [0.0084, 0.0181]
The detached tensor shares memory with y but has no history. Inside no_grad and inference_mode the result is untracked, and an inference tensor cannot be used in a graph later. The stop-gradient example gives , not . For at , the first call returns as a tensor that is still part of a graph, and the second differentiates it: . Neither call touched t.grad, which is still None. In the last lines the gradient of with respect to the input, , is itself a function of , and the penalty is backpropagated to , giving .
A custom operation and gradcheck
When an operation is missing, numerically delicate or needs a cheaper backward than autograd would derive, write a torch.autograd.Function with two static methods. forward(ctx, ...) computes the result and saves what the backward needs with ctx.save_for_backward; backward(ctx, grad_out) returns one gradient per input. This is exactly the contract of the layer-by-layer modules. torch.autograd.gradcheck then compares your backward with finite differences, which requires float64 inputs.
The example implements softplus, , whose derivative is , and a copy with a deliberate 10 % error in the backward:
import torch
from torch.autograd import gradcheck
class Softplus(torch.autograd.Function):
"""log(1 + e^x), written by hand: forward saves what backward needs."""
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return torch.logaddexp(x, torch.zeros_like(x)) # stable log(1 + e^x)
@staticmethod
def backward(ctx, grad_out):
(x,) = ctx.saved_tensors
return grad_out * torch.sigmoid(x) # d/dx log(1 + e^x) = sigmoid(x)
class BadSoftplus(Softplus):
@staticmethod
def backward(ctx, grad_out):
(x,) = ctx.saved_tensors
return grad_out * torch.sigmoid(x) * 0.9 # a deliberate 10 % error
torch.manual_seed(0)
x = torch.randn(6, dtype=torch.float64, requires_grad=True) # gradcheck needs float64
y = Softplus.apply(x)
print("matches F.softplus:", torch.allclose(y, torch.nn.functional.softplus(x)), " grad_fn:", type(y.grad_fn).__name__)
y.sum().backward()
print("grad equals sigmoid(x):", torch.allclose(x.grad, torch.sigmoid(x)))
print("gradcheck Softplus:", gradcheck(Softplus.apply, (x,), eps=1e-6, atol=1e-4))
print("gradcheck BadSoftplus:", gradcheck(BadSoftplus.apply, (x,), eps=1e-6, atol=1e-4, raise_exception=False))matches F.softplus: True grad_fn: SoftplusBackward
grad equals sigmoid(x): True
gradcheck Softplus: True
gradcheck BadSoftplus: False
The forward matches F.softplus, the result carries a SoftplusBackward node named after the class, and its gradient equals . gradcheck passes for the correct version and returns False for the wrong one (with raise_exception=False; by default it raises and prints the mismatching Jacobian). Run gradcheck on every custom Function before training with it; a wrong backward does not crash, it just trains badly.
The same graph in both engines
Finally the comparison with the NumPy engine. The graph is a small two-layer network with a tanh hidden layer, a cross-entropy loss and an L2 penalty on the first weight matrix,
with , a 3-5-3 network and all values drawn from the same NumPy generator. First the lesson-5 engine, with only the operations this graph uses; this one runs in the browser:
import numpy as np
def unbroadcast(g, shape):
while g.ndim > len(shape):
g = g.sum(axis=0)
for axis, size in enumerate(shape):
if size == 1 and g.shape[axis] != 1:
g = g.sum(axis=axis, keepdims=True)
return g
class Tensor: # the lesson-5 engine, the ops used here
def __init__(self, data, parents=()):
self.data = np.asarray(data, dtype=float)
self.grad = np.zeros_like(self.data)
self.parents = parents
self._backward = lambda: None
def _make(self, data, parents, backward):
out = Tensor(data, parents)
out._backward = lambda: backward(out.grad)
return out
def __add__(self, o):
def bw(g):
self.grad += unbroadcast(g, self.data.shape); o.grad += unbroadcast(g, o.data.shape)
return self._make(self.data + o.data, (self, o), bw)
def __mul__(self, o):
o = o if isinstance(o, Tensor) else Tensor(o)
def bw(g):
self.grad += unbroadcast(g * o.data, self.data.shape); o.grad += unbroadcast(g * self.data, o.data.shape)
return self._make(self.data * o.data, (self, o), bw)
def __matmul__(self, o):
def bw(g):
self.grad += g @ o.data.T; o.grad += self.data.T @ g
return self._make(self.data @ o.data, (self, o), bw)
def sum(self):
def bw(g):
self.grad += g * np.ones_like(self.data)
return self._make(self.data.sum(), (self,), bw)
def tanh(self):
t = np.tanh(self.data)
def bw(g):
self.grad += g * (1 - t ** 2)
return self._make(t, (self,), bw)
def cross_entropy(self, y):
Z = self.data - self.data.max(axis=1, keepdims=True)
P = np.exp(Z) / np.exp(Z).sum(axis=1, keepdims=True)
n = len(y)
def bw(g):
G = P.copy(); G[np.arange(n), y] -= 1
self.grad += g * G / n
return self._make(-np.log(P[np.arange(n), y]).mean(), (self,), bw)
def backward(self):
order, seen = [], set()
def visit(t):
if id(t) not in seen:
seen.add(id(t))
for p in t.parents:
visit(p)
order.append(t)
visit(self)
self.grad = np.ones_like(self.data)
for t in reversed(order):
t._backward()
rng = np.random.default_rng(0)
X = Tensor(rng.normal(size=(4, 3)))
W1 = Tensor(rng.normal(0, 0.5, (3, 5))); b1 = Tensor(rng.normal(0, 0.1, 5))
W2 = Tensor(rng.normal(0, 0.5, (5, 3))); b2 = Tensor(rng.normal(0, 0.1, 3))
y = np.array([0, 2, 1, 2])
loss = ((X @ W1 + b1).tanh() @ W2 + b2).cross_entropy(y) + (W1 * W1).sum() * 0.01
loss.backward()
print("loss ", round(float(loss.data), 6))
print("dL/dW1[0] ", np.round(W1.grad[0], 6).tolist())
print("dL/db1 ", np.round(b1.grad, 6).tolist())
print("dL/dW2[:,0]", np.round(W2.grad[:, 0], 6).tolist())
print("dL/db2 ", np.round(b2.grad, 6).tolist())
print("dL/dX[0] ", np.round(X.grad[0], 6).tolist())loss 1.499725
dL/dW1[0] [-0.030735, 0.09955, -0.456073, -0.10648, 0.334502]
dL/db1 [0.02892, -0.009024, 0.22331, 0.058876, -0.135142]
dL/dW2[:,0] [0.054177, -0.022644, -0.03704, 0.001915, 0.034714]
dL/db2 [0.074902, 0.100335, -0.175237]
dL/dX[0] [-0.011751, -0.025684, -0.038377]
And the same in PyTorch, every input a float64 leaf with requires_grad=True:
import numpy as np
import torch
import torch.nn.functional as F
rng = np.random.default_rng(0) # the same draws as the NumPy engine
t = lambda a: torch.tensor(a, requires_grad=True) # float64 leaves
X = t(rng.normal(size=(4, 3)))
W1 = t(rng.normal(0, 0.5, (3, 5))); b1 = t(rng.normal(0, 0.1, 5))
W2 = t(rng.normal(0, 0.5, (5, 3))); b2 = t(rng.normal(0, 0.1, 3))
y = torch.tensor([0, 2, 1, 2])
loss = F.cross_entropy(torch.tanh(X @ W1 + b1) @ W2 + b2, y) + (W1 * W1).sum() * 0.01
loss.backward()
r = lambda g: np.round(g.numpy(), 6).tolist()
print("loss ", round(loss.item(), 6))
print("dL/dW1[0] ", r(W1.grad[0]))
print("dL/db1 ", r(b1.grad))
print("dL/dW2[:,0]", r(W2.grad[:, 0]))
print("dL/db2 ", r(b2.grad))
print("dL/dX[0] ", r(X.grad[0]))loss 1.499725
dL/dW1[0] [-0.030735, 0.09955, -0.456073, -0.10648, 0.334502]
dL/db1 [0.02892, -0.009024, 0.22331, 0.058876, -0.135142]
dL/dW2[:,0] [0.054177, -0.022644, -0.03704, 0.001915, 0.034714]
dL/db2 [0.074902, 0.100335, -0.175237]
dL/dX[0] [-0.011751, -0.025684, -0.038377]
The two outputs are identical line for line: the loss 1.499725, the first row of starting , the bias gradients of the output layer, and even the input gradient of the first example, . The penalty's contribution arrives in through the mul and sum nodes in both engines, and PyTorch's fused F.cross_entropy has the same backward as the NumPy one. Here the PyTorch weights are plain leaves in NumPy layout, so no transposes are needed.
Pitfalls
- Reading
.gradof a non-leaf. It isNoneunless you calledretain_grad()beforebackward(), and PyTorch prints a warning when you access it. Useretain_grad()or a tensor hook for debugging. - Accumulating by accident. Every
backward()adds into.grad. Zero the gradients every step; accumulate on purpose only for gradient accumulation, and then divide the loss by the number of accumulated batches. - In-place changes to saved tensors.
x.relu_()orx += 1on a tensor that an earlier operation saved for its backward raises "one of the variables needed for gradient computation has been modified by an inplace operation". Use the out-of-place versions where it matters. - Turning a tensor into a Python number inside the graph.
.item(),.numpy()orfloat(t)leave autograd; anything computed from them is a constant. Keep the computation in tensor operations. - Using
inference_modetensors in training. Caching features computed underinference_modeand later feeding them into a model that is trained raises an error; compute them underno_grad(orclone()them) if they will meet autograd again.
Practice
a = torch.tensor(3.0, requires_grad=True),b = a * a,c = b + a,c.backward(). What isa.grad, and what isb.grad?
Answer
, so a.grad is tensor(7.). b is a non-leaf, so b.grad is None (with a warning) unless b.retain_grad() was called before backward(); then it is 1.
- Compute the Hessian-vector product of at for with
torch.autograd.grad, without building .
Answer
x = torch.tensor([1.0, 2.0], requires_grad=True)
(g,) = torch.autograd.grad((x ** 3).sum(), x, create_graph=True)
(hu,) = torch.autograd.grad(g, x, grad_outputs=torch.ones(2)), , so . The second call is a vector-Jacobian product of the gradient, which for a symmetric equals .
- Why must
gradcheckinputs be float64?
Answer
It compares analytic gradients with central differences with . In float32, with about 7 significant digits, the difference is mostly rounding noise, so even a correct backward fails the check.
- A target network in reinforcement learning computes
target = reward + gamma * q_target(next_state).max(1).values. Where doesdetach()(orno_grad) belong, and why?
Answer
On the target: compute it under torch.no_grad() or call .detach() on it. The loss should move the online network's prediction toward a fixed target; without the cut, gradients would also flow into the target computation and the regression target would chase the prediction.
Test yourself
Which tensors keep their .grad after loss.backward() by default?
- Every tensor in the graph
- Only leaves with
requires_grad=True - Only the loss
- Only tensors created under
no_grad
What does v.backward(gradient=u) compute for a vector output of ?
- The full Jacobian
- The vector-Jacobian product , added to
x.grad - The gradient of
- The Hessian of
What is the gradient of (x * x.detach()).sum() with respect to x?
2 * xx- Zero
x ** 2
What does create_graph=True in torch.autograd.grad make possible?
- Running backward on the GPU
- Differentiating the returned gradient again, for second derivatives or gradient penalties
- Keeping
.gradof non-leaves - Freeing memory faster
Why should every custom torch.autograd.Function be tested with gradcheck?
- PyTorch refuses to run it otherwise
- A wrong backward raises no error; it silently gives wrong gradients
- It makes the function faster
- It converts it to float64