30 Mins

2. Autograd & Backpropagation

Understanding Computational Graphs

PyTorch uses a Dynamic Computational Graph (DCG) approach. When you perform operations on tensors with requires_grad=True, PyTorch tracks these operations in a directed acyclic graph (DAG). Nodes represent tensors, and edges represent functions applied to those tensors.

The DCG is built on the fly as you execute your code. This is significantly different from static graphs used in earlier frameworks, allowing for greater flexibility when handling conditional statements or dynamic input sizes during runtime.

Operator Note: The grad_fn attribute points to the function that created the tensor, allowing for backpropagation through the chain rule.
Python 3
import torch
x = torch.tensor(2.0, requires_grad=True)
y = x**2 + 3 * x
# The graph is implicitly built during the definition of y
print(f"Tensor: {y}")
print(f"Gradient function: {y.grad_fn}")

The Mechanism of .backward()

Once you have a scalar output (like a loss value), you call .backward() to trigger the chain rule propagation. This function computes the derivative of the scalar output with respect to all leaf variables that contributed to its creation.

Crucially, gradients are accumulated into the .grad attribute of the leaf tensors rather than being overwritten. This design choice is intentional, as it allows for gradient accumulation techniques in batch training scenarios where you might compute gradients over multiple forward passes before performing an optimization step.

Operator Note: Always call zero_() on your optimizer or parameters after each optimization step to prevent gradient accumulation artifacts from previous iterations.
Python 3
w = torch.tensor([1.0, 2.0], requires_grad=True)
z = torch.sum(w**3)
z.backward()
# Gradients are now stored in w.grad
print(f"Gradients: {w.grad}")
# Manually clearing gradients for next iteration
w.grad.zero_()

Leaf vs Non-Leaf Variables

Leaf tensors are tensors that are created by the user, such as model weights or input data. They represent the source nodes in the computational graph. Non-leaf tensors are the result of operations performed on these leaves.

Only leaf variables with requires_grad=True will have their gradients populated in their .grad attribute. Intermediate tensors are generally discarded after the backward pass to save memory, unless specifically requested via retain_grad().

Operator Note: If you receive a warning about gradients not being computed for a specific tensor, check if it is a leaf node or if it was modified in-place before the backward pass.
Python 3
a = torch.tensor(1.0, requires_grad=True)
b = a * 2 # b is a non-leaf tensor
c = b ** 2
c.backward()
print(f"Is a a leaf: {a.is_leaf}")
print(f"Is b a leaf: {b.is_leaf}")
print(f"Gradient of a: {a.grad}")

Inference and Efficiency

During inference, tracking gradients is a computational waste. PyTorch provides the torch.no_grad() context manager to disable gradient calculation, which significantly reduces memory consumption and speeds up evaluation.

Additionally, the .detach() method is used to remove a tensor from the computational graph, effectively treating it as a constant without any history of how it was derived. This is standard practice in GANs or reinforcement learning when you want to update one model while keeping the other frozen.

Operator Note: Always wrap validation loops in torch.no_grad() to ensure your evaluation phase is memory-efficient and doesn't interfere with your training graph.
Python 3
x = torch.tensor(1.0, requires_grad=True)
with torch.no_grad():
    y = x * 2
# y will have requires_grad=False and no grad_fn
print(f"y requires_grad: {y.requires_grad}")
# Detach example
z = x.detach()
print(f"z requires_grad: {z.requires_grad}")

Knowledge Check

Ready to test your understanding of 2. Autograd & Backpropagation?

Back