The Computational Graph and grad_fn in PyTorch

JS
Jai Singh
24 Nov, 2026 4 min read 13 views

When you run operations on tensors that require gradients, PyTorch builds a directed graph behind the scenes. Each result remembers which operation created it, stored in its grad_fn attribute, and which inputs it came from. Calling backward() walks this graph from the output back to the inputs and applies the chain rule at every node. Understanding the graph explains most of autograd's rules and error messages.

Reading grad_fn

import torch

a = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(3.0, requires_grad=True)

c = a * b
d = c + a
e = d ** 2

print(c.grad_fn)    # <MulBackward0 object ...>
print(d.grad_fn)    # <AddBackward0 object ...>
print(e.grad_fn)    # <PowBackward0 object ...>
print(a.grad_fn)    # None  (a is a leaf)

Every tensor produced by a tracked operation has a grad_fn that names the backward function, such as MulBackward0. Tensors you create yourself have no grad_fn; they are called leaf tensors. Weights in a model are leaves, and so are input tensors, though inputs usually do not require gradients. After e.backward(), only the leaves with requires_grad=True receive a .grad value.

e.backward()
print(a.grad)   # de/da = 2*d*(b + 1) = 2*8*4 = 64
print(b.grad)   # de/db = 2*d*a = 2*8*2 = 32
print(a.is_leaf, c.is_leaf)   # True False

Here d = a*b + a = 8, so e = 64. The gradient with respect to a receives contributions from two paths: through the product and through the direct addition. Autograd sums them for you. Walking the graph by hand like this is a good way to check your understanding.

The graph is dynamic

PyTorch builds a new graph on every forward pass. That is why ordinary Python control flow works inside models. You can use an if statement that depends on a tensor value, or a loop with a different number of iterations each time, and autograd simply records whatever operations actually ran.

def f(x):
    if x.sum() > 0:
        return x * 2
    return x ** 2

x = torch.tensor([1.0, -3.0], requires_grad=True)
y = f(x)            # takes the x ** 2 branch because sum is -2
y.sum().backward()
print(x.grad)       # tensor([ 2., -6.])

Static-graph frameworks require special operators for conditionals. In PyTorch you just write Python, which makes recursive and variable-length models natural to express.

The graph is freed after backward

To save memory, PyTorch deletes the saved intermediate values once backward() has run. If you call backward() a second time on the same result, you get an error: "Trying to backward through the graph a second time". Normally this never happens, because every training step runs a new forward pass and builds a fresh graph. It appears when you reuse a tensor that was computed in an earlier step, for example a hidden state carried between iterations in a recurrent network.

w = torch.tensor(1.0, requires_grad=True)
loss = (w * 3) ** 2

loss.backward(retain_graph=True)   # keep the graph
loss.backward()                    # works, gradients accumulate
print(w.grad)                      # tensor(36.): 18 + 18

The retain_graph=True argument keeps the graph alive for another backward call. You rarely need it. If you are tempted to add it to silence an error in a training loop, first check whether you are accidentally carrying a tensor with history from one step to the next. The right fix is usually to detach() that tensor, which cuts it off from its past.

Inspecting the graph

You can walk the graph manually through grad_fn.next_functions, which lists the functions that feed into a node. This is useful for learning and for debugging unexpected gradient flow.

print(e.grad_fn.next_functions)
# ((<AddBackward0 ...>, 0), (None, 0))

Each entry pairs a previous function with the index of the output it consumed. A leaf shows up as an AccumulateGrad node, which is the object that writes into .grad. A None entry means that input does not require gradients, such as the constant 2 in d ** 2.

Why this matters in practice

  • Memory: the graph stores intermediate tensors, so activations from the forward pass stay alive until backward. This is the main reason training needs far more memory than inference.
  • Speed of inference: disabling tracking with torch.no_grad() stops the graph from being built, saving memory and time.
  • Silent breaks: operations that leave the graph, like converting to NumPy or using .item(), give results with no gradient history. If a loss has no grad_fn, backward() will fail.
  • Accumulating losses: storing total += loss keeps every step's graph alive. Use total += loss.item() when you only want the number for logging.

Checklist for graph problems

  1. If backward() says the tensor does not require grad, print loss.requires_grad and loss.grad_fn and trace back to find where the chain was broken.
  2. If memory grows every iteration, look for tensors with history being stored in a list or running total.
  3. If you see the "second time" error, detach carried-over state.
  4. If a weight has .grad equal to None, confirm that it is a leaf, requires grad, and was used in the forward pass for that loss.

The next post covers the tools for steering what autograd tracks: zero_grad, no_grad and detach.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.