TExcelTAD

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.

tensors (top) and the grad_fn nodes autograd records (bottom) w (leaf) x (leaf) y = w * x z = sum(y**2) non-leaf, retain_grad() AccumulateGrad (w, x) MulBackward0 PowBackward0 SumBackward0 z.grad_fn backward runs right to left; AccumulateGrad writes w.grad and x.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 v=f(x)∈Rmv = f(x) \in \mathbb{R}^m there is no single gradient, only the Jacobian J=∂v/∂xJ = \partial v / \partial x. Reverse mode never builds JJ; it computes a vector-Jacobian product, and v.backward(gradient=u) supplies the vector:

x.grad+=u⊤J=∑i=1mui∂vi∂xx.\text{grad} \mathrel{+}= u^\top J = \sum_{i=1}^{m} u_i \frac{\partial v_i}{\partial x}

loss.backward() on a scalar is the special case u=1u = 1. Why reverse mode suits a scalar loss with millions of parameters is explained in forward and reverse mode.

python · try it yourself
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: xx and ww are leaves, yy and zz 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 z=∑(wxi)2z = \sum (w x_i)^2 with w=0.5w = 0.5, ∂z/∂xi=2w2xi\partial z / \partial x_i = 2 w^2 x_i gives (0.5,1.0,1.5)(0.5, 1.0, 1.5), ∂z/∂w=2w∑xi2=14\partial z / \partial w = 2 w \sum x_i^2 = 14, and the retained ∂z/∂y=2y=(1,2,3)\partial z / \partial y = 2y = (1, 2, 3). A second, new graph adds the same amount again: x.grad becomes (1,2,3)(1, 2, 3). 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 u=(1,0.1,0.01)u = (1, 0.1, 0.01) and J=2IJ = 2I the result is (2,0.2,0.02)(2, 0.2, 0.02).

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: sg⁡(x)\operatorname{sg}(x) has the value of xx and derivative 0, so ddx(x⋅sg⁡(x))=sg⁡(x)=x\frac{d}{dx}\left(x \cdot \operatorname{sg}(x)\right) = \operatorname{sg}(x) = x, not 2x2x. 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.

python · try it yourself
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 (1,2,3)=x(1, 2, 3) = x, not 2x2x. For f(t)=t3f(t) = t^3 at t=2t = 2, the first call returns f′(2)=3⋅4=12f'(2) = 3 \cdot 4 = 12 as a tensor that is still part of a graph, and the second differentiates it: f′′(2)=6⋅2=12f''(2) = 6 \cdot 2 = 12. Neither call touched t.grad, which is still None. In the last lines the gradient of tanh⁡(w⊤x)\tanh(w^\top x) with respect to the input, (0.0266,−0.0532)(0.0266, -0.0532), is itself a function of ww, and the penalty ∥∇x∥2\lVert \nabla_x \rVert^2 is backpropagated to ww, giving (0.0084,0.0181)(0.0084, 0.0181).

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, log⁡(1+ex)\log(1 + e^x), whose derivative is σ(x)\sigma(x), and a copy with a deliberate 10 % error in the backward:

python · try it yourself
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 σ(x)\sigma(x). 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,

L=CE⁡(tanh⁡(XW1+b1)W2+b2, y)+0.01∑j,k(W1)jk2L = \operatorname{CE}\left(\tanh(X W_1 + b_1) W_2 + b_2,\ y\right) + 0.01 \sum_{j,k} (W_1)_{jk}^2

with X∈R4×3X \in \mathbb{R}^{4 \times 3}, 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:

python · try it yourself
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:

python · try it yourself
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 ∂L/∂W1\partial L / \partial W_1 starting −0.030735,0.09955,−0.456073-0.030735, 0.09955, -0.456073, the bias gradients (0.074902,0.100335,−0.175237)(0.074902, 0.100335, -0.175237) of the output layer, and even the input gradient ∂L/∂X\partial L / \partial X of the first example, (−0.011751,−0.025684,−0.038377)(-0.011751, -0.025684, -0.038377). The penalty's contribution 0.02 W10.02\,W_1 arrives in ∂L/∂W1\partial L / \partial W_1 through the mul and sum nodes in both engines, and PyTorch's fused F.cross_entropy has the same (P−Y)/n(P - Y)/n backward as the NumPy one. Here the PyTorch weights are plain leaves in NumPy layout, so no transposes are needed.

Pitfalls

  • Reading .grad of a non-leaf. It is None unless you called retain_grad() before backward(), and PyTorch prints a warning when you access it. Use retain_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_() or x += 1 on 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() or float(t) leave autograd; anything computed from them is a constant. Keep the computation in tensor operations.
  • Using inference_mode tensors in training. Caching features computed under inference_mode and later feeding them into a model that is trained raises an error; compute them under no_grad (or clone() them) if they will meet autograd again.

Practice

  1. a = torch.tensor(3.0, requires_grad=True), b = a * a, c = b + a, c.backward(). What is a.grad, and what is b.grad?
Answer

∂c/∂a=2a+1=7\partial c / \partial a = 2a + 1 = 7, 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.

  1. Compute the Hessian-vector product HuH u of f(x)=∑ixi3f(x) = \sum_i x_i^3 at x=(1,2)x = (1, 2) for u=(1,1)u = (1, 1) with torch.autograd.grad, without building HH.
Answer
python
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))

g=3x2g = 3x^2, H=diag⁡(6x)H = \operatorname{diag}(6x), so Hu=(6,12)Hu = (6, 12). The second call is a vector-Jacobian product of the gradient, which for a symmetric HH equals HuHu.

  1. Why must gradcheck inputs be float64?
Answer

It compares analytic gradients with central differences (f(x+ε)−f(x−ε))/2ε(f(x + \varepsilon) - f(x - \varepsilon)) / 2\varepsilon with ε=10−6\varepsilon = 10^{-6}. In float32, with about 7 significant digits, the difference f(x+ε)−f(x−ε)f(x + \varepsilon) - f(x - \varepsilon) is mostly rounding noise, so even a correct backward fails the check.

  1. A target network in reinforcement learning computes target = reward + gamma * q_target(next_state).max(1).values. Where does detach() (or no_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?

  1. Every tensor in the graph
  2. Only leaves with requires_grad=True
  3. Only the loss
  4. Only tensors created under no_grad

What does v.backward(gradient=u) compute for a vector output vv of xx?

  1. The full Jacobian ∂v/∂x\partial v / \partial x
  2. The vector-Jacobian product u⊤Ju^\top J, added to x.grad
  3. The gradient of ∥v∥\lVert v \rVert
  4. The Hessian of vv

What is the gradient of (x * x.detach()).sum() with respect to x?

  1. 2 * x
  2. x
  3. Zero
  4. x ** 2

What does create_graph=True in torch.autograd.grad make possible?

  1. Running backward on the GPU
  2. Differentiating the returned gradient again, for second derivatives or gradient penalties
  3. Keeping .grad of non-leaves
  4. Freeing memory faster

Why should every custom torch.autograd.Function be tested with gradcheck?

  1. PyTorch refuses to run it otherwise
  2. A wrong backward raises no error; it silently gives wrong gradients
  3. It makes the function faster
  4. It converts it to float64