Skip to content

Artificial IntelligencePyTorch from scratch

1. Autograd and gradients

Guide · Pytorch, Autograd, Backpropagation · updated on 24/11/2026

Author: Ángel Fernández Caravaca
Date: March 13, 2026

Why gradients matter in deep learning?

Training a neural network is, at heart, an optimisation problem. Given a model with trainable parameters θ and a loss function L(θ) that measures the prediction error, the goal is to find the parameter values that minimise L. The standard algorithm for this is gradient descent:

\[\theta \leftarrow \theta - \eta \cdot \nabla_\theta L\]

where η is the learning rate and ∇θL is the gradient of the loss with respect to each parameter. Computing these gradients by hand in deep architectures, with many layers, is intractable: that is exactly the problem torch.autograd solves automatically.


The computational graph

Every time PyTorch runs an operation involving at least one tensor with requires_grad=True, it silently records that operation as a node in a directed acyclic graph (DAG) called the computational graph.

  • Leaf nodes are the tensors created by the user (inputs, weights, biases).
  • Interior nodes represent the intermediate results of operations (sums, products, activations).
  • Edges encode the functional dependency between tensors.

Each interior node stores a grad_fn: a reference to the backward function (that is, the local differentiation rule) of the operation that created it. This graph is the data structure that makes automatic differentiation possible.

1
2
3
x ──┐
    ├──[mul]── z ──[add]── y     ← the forward pass builds the graph
w ──┘

Since PyTorch uses a dynamic graph (Define-by-Run), the structure is rebuilt from scratch on every forward pass. This means control flow (if, for, while) can change the graph's topology between iterations, which makes it suitable for architectures with a variable structure.


Backpropagation and the chain rule

Backpropagation is an efficient algorithm for computing all the partial derivatives of a scalar loss with respect to all the parameters at once, in a single backward pass through the computational graph.

It is a direct application of the calculus chain rule. For a composite function \(L = f(g(h(x)))\):

\[\frac{dL}{dx} = \frac{dL}{df} \cdot \frac{df}{dg} \cdot \frac{dg}{dh} \cdot \frac{dh}{dx}\]

Backpropagation walks the graph from the output (the loss) to the leaf tensors, multiplying the local Jacobians at each step. This backward pass is triggered by calling .backward() on a scalar tensor.

After calling .backward(), every leaf tensor with requires_grad=True accumulates its gradient in the .grad attribute:

y.backward()   # triggers the backward pass through the graph
x.grad         # ∂y/∂x, already computed

Gradient accumulation and zero_grad()

A key, and often surprising, behaviour of PyTorch's autograd engine is that gradients accumulate (are summed) in .grad across several calls to .backward() instead of being overwritten.

This is intentional: some training schemes (e.g. gradient accumulation over micro-batches or the temporal unrolling of RNNs) need gradients to be summed. In a standard training loop, however, it means that if they are not zeroed before each update, they are silently corrupted.

The fix is to call .zero_() on the gradient tensor (or, if you use an optimiser, optimizer.zero_grad()) at the start of each iteration:

# Wrong: gradients grow without limit step after step
for _ in range(steps):
    loss.backward()
    w -= lr * w.grad

# Right
for _ in range(steps):
    loss.backward()
    w -= lr * w.grad
    w.grad.zero_()

Controlling gradient tracking

Not every computation in a training pipeline needs to record gradients. Inference, evaluation and manual weight updates should run outside the autograd engine so as not to waste memory and computation unnecessarily.

PyTorch offers two complementary mechanisms:

torch.no_grad()

A context manager that globally disables gradient tracking for all operations inside the block. No grad_fn is attached to the output tensors and no graph is built. It is the standard way to evaluate a model and to update parameters by hand.

1
2
3
with torch.no_grad():
    prediction = model(x)        # no graph is built
    w -= lr * w.grad             # safe in-place update

.detach()

Returns a new tensor that shares the same data as the original but is detached from the computational graph: it has no grad_fn and doesn't propagate gradients. Unlike no_grad(), it acts on a single tensor rather than on a block of code.

loss_value = loss.detach()    # extract a scalar to log it without breaking the graph
Mechanism Scope Creates a new tensor? Use
torch.no_grad() Block No Inference, manual updates
.detach() Tensor Yes (shared data) Logging, cutting the gradient flow

Manual gradient descent

Before introducing nn.Module and optimisers, it is instructive to implement the full training loop by hand. Given a simple linear model y_hat = w * x + b and the mean squared error (MSE) loss:

\[L = \frac{1}{N}\sum_{i=1}^{N}(\hat{y}_i - y_i)^2\]

A training step consists of four operations:

  1. Forward: compute the predictions and the loss.
  2. Backward: call loss.backward() to fill in .grad on every leaf tensor.
  3. Parameter update: adjust the weights with gradient descent inside a no_grad() block.
  4. Zeroing the gradients: clear .grad before the next iteration.

This manual loop is the conceptual basis that PyTorch's optimisers (SGD, Adam, etc.) abstract away, but understanding it is essential for diagnosing failing training runs.


Higher-order derivatives

By default, the computational graph is freed after calling .backward(). To compute higher-order gradients (that is, derivatives of derivatives), the graph of the backward pass itself must be kept, which is achieved by passing create_graph=True to torch.autograd.grad():

dy_dx = torch.autograd.grad(y, x, create_graph=True)[0]
d2y_dx2 = torch.autograd.grad(dy_dx, x)[0]

Higher-order gradients show up in several advanced machine learning scenarios:

  • Meta-learning (e.g. MAML): the outer loop optimises through the inner loop's gradient update, which requires gradients of gradients.
  • Physics-informed neural networks (PINNs): the loss includes residuals of differential equations, which require second or higher-order derivatives of the network's output with respect to its inputs.
  • Penalty regularisation: methods such as the gradient penalty in Wasserstein GANs penalise the norm of the discriminator's gradient.

Jacobians and Hessians

For vector-valued functions, the generalisation of the derivative is the Jacobian matrix. Given \(f: \mathbb{R}^n \rightarrow \mathbb{R}^m\), the Jacobian \(J \in \mathbb{R}^{m \times n}\) is defined as:

\[J_{ij} = \frac{\partial f_i}{\partial x_j}\]

For scalar functions of a vector input, the Jacobian reduces to a gradient vector. When the function maps vectors to vectors, the full matrix is needed.

The Hessian \(H \in \mathbb{R}^{n \times n}\) is the matrix of second-order partial derivatives of a scalar function \(g: \mathbb{R}^n \rightarrow \mathbb{R}\):

\[H_{ij} = \frac{\partial^2 g}{\partial x_i \, \partial x_j}\]

PyTorch provides both through torch.autograd.functional:

J = torch.autograd.functional.jacobian(f, x)
H = torch.autograd.functional.hessian(g, x)

The Hessian is particularly relevant in second-order optimisation methods (Newton's method, L-BFGS) and in analysing the curvature of the loss landscape.


Gradient pathologies: explosion and clipping

In deep networks trained with gradient descent, two related instabilities can appear during backpropagation:

  • Vanishing gradients: gradients become exponentially small as they propagate backwards through many layers, so the first layers learn very slowly or not at all. It is especially common with sigmoid/tanh activations and in deep recurrent networks.
  • Exploding gradients: gradients become exponentially large and cause weight updates so large that they destabilise training, often with NaN losses.

Gradient clipping is the standard mitigation for explosion. It rescales the gradient vector so that its norm doesn't exceed max_norm before the update step:

\[\text{if } \|\mathbf{g}\| > \text{max\_norm}, \quad \mathbf{g} \leftarrow \mathbf{g} \cdot \frac{\text{max\_norm}}{\|\mathbf{g}\|}\]

In PyTorch it is a single call, placed between .backward() and the optimiser step:

1
2
3
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()

Monitoring the gradient norm per epoch is a standard diagnostic tool for detecting training instabilities.


Custom autograd functions

PyTorch's autograd engine can be extended with your own differentiable operations by subclassing torch.autograd.Function and implementing two static methods:

  • forward(ctx, *inputs): runs the operation and, optionally, saves the tensors the backward pass will need with ctx.save_for_backward().
  • backward(ctx, grad_output): receives the gradient coming from above and returns the local gradients with respect to each input, applying the chain rule.
class MySqrt(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x):
        result = x.sqrt()
        ctx.save_for_backward(result)
        return result

    @staticmethod
    def backward(ctx, grad_output):
        (result,) = ctx.saved_tensors
        return grad_output / (2 * result)

This mechanism is necessary when:

  • The operation can't be expressed with PyTorch's existing primitives (e.g. a custom CUDA kernel).
  • The analytical backward is more numerically stable than the one autograd would derive automatically (e.g. log-sum-exp tricks).
  • Performance demands a fused, hand-written backward implementation.

Checking correctness: gradcheck

torch.autograd.gradcheck() checks that a custom backward implementation matches the numerical Jacobian computed by finite differences:

\[\frac{\partial f}{\partial x_i} \approx \frac{f(x + \epsilon \mathbf{e}_i) - f(x - \epsilon \mathbf{e}_i)}{2\epsilon}\]

It is the standard tool for validating any custom autograd.Function before using it in production code.

Python decorators

A decorator is a function that wraps another one to modify or extend its behaviour. The @decorator syntax is nothing more than a function that modifies another function; it is what is usually called "syntactic sugar". For example:

1
2
3
4
5
6
@staticmethod
def forward(ctx, x): ...

# Is exactly the same as:
def forward(ctx, x): ...
forward = staticmethod(forward)

@staticmethod tells Python that a method needs neither the instance (self) nor the class (cls): it is a normal function that lives inside a class for organisational purposes. It can be called directly from the class without creating an object:

MyClass.my_method(x)  # No instance needed

In PyTorch's torch.autograd.Function, @staticmethod is mandatory: PyTorch calls forward and backward directly from the class and uses ctx as the communication object between the two methods, in the role self would normally play.

  • Important decorators worth knowing
Decorator Explanation Use cases
@staticmethod Defines a method that receives neither self nor cls. It is just a function inside a class's namespace. Helper functions logically related to a class but that don't need its state. Mandatory in torch.autograd.Function.
@classmethod Receives cls (the class itself) instead of self. Alternative constructors, factory methods, access to class attributes.
@property Turns a method into a read-only attribute. Avoids calling it with (). Computed attributes, controlled access to internal state.
@property.setter Defines what happens when a value is assigned to a @property. Validating input before storing a value.
@abstractmethod Forces subclasses to implement the method. Must be used with ABC. Defining interfaces and base classes.
@dataclass Automatically generates __init__, __repr__, __eq__ and more from the class's attributes. Clean data containers without boilerplate.
@functools.wraps Used when writing your own decorators to preserve the original function's metadata. Building your own decorators correctly.
@functools.lru_cache Caches a function's results so that repeated calls with the same arguments are instant. Expensive or recursive functions (e.g. Fibonacci).
@torch.no_grad Disables gradient computation inside the block. Inference loops and model evaluation in PyTorch.
---

Exercises

Use the official documentation while solving the exercises.

Exercise 1

Define x = tensor(2.0, requires_grad=True) and compute \(y = 3x^2 + 2x - 1\). Backpropagate and check by hand that \(\frac{dy}{dx} = 6x + 2\) evaluated at \(x=2\) gives \(14\).

Show solution
import torch

# Point at which we will evaluate the derivative:
x = torch.tensor(2.0, requires_grad=True)
print(f'Leaf node variable: x = {x.item()}')

# Function to differentiate:
y = 3*x**2 + 2*x - 1
print(f'Function to be differenciated: y(x) = 3*x**2 + 2*x - 1')
print(f'Result of forward propagation: y({x.item()}) = {y}')

# Walk the computational graph:
y.backward()

# Get the derivative:
derivative = x.grad
print(f"Derivative y'(x={x.item()}) = {derivative}")
Output
1
2
3
4
Leaf node variable: x = 2.0
Function to be differenciated: y(x) = 3*x**2 + 2*x - 1
Result of forward propagation: y(2.0) = 15.0
Derivative y'(x=2.0) = 14.0

Comment: unlike symbolic differentiation (e.g. SymPy), PyTorch doesn't return an analytical expression for the derivative. Instead, y = 3*x**2 + 2*x - 1 is evaluated to a concrete number (y=15.0) while, at the same time, a computational graph is built that encodes the functional relationship between y and x.

When .backward() is called, PyTorch walks this graph in reverse, applies the exact local differentiation rules at each node and accumulates the result directly in x: dy/dx evaluated at x=2 = 14.

  • Intuitive idea: PyTorch has the differentiation rules you learnt at school (power rule, product rule, chain rule, etc.) "programmed in" for every primitive operation it supports.

  • What it really does:

Look inside the autograd engine with torchviz. Run pip install torchviz and the following cell. Change the expression for \(y\) and analyse how PyTorch dynamically modifies the graph's nodes and edges in response to your mathematical changes. (graphviz is required).

1
2
3
4
5
6
7
from torchviz import make_dot
from IPython.display import display

x = torch.tensor(2.0, requires_grad=True)
y = x**2 + x + torch.log(x)

display(make_dot(y, params={"x": x, "y": y}))

Output of cell 5

Exercise 2

Given a vector x = [1.0, 2.0, 3.0] with requires_grad=True, compute \(L = \sum x^2\) and get the gradient. What value do you expect for each element?

Show solution
# Create the tensor:
x = torch.tensor([1, 2, 3], dtype=torch.float32, requires_grad=True)
print(f'x = {x}')

# Compute L = sum(x²)
L = torch.sum(torch.pow(x,2))
print(f'L = {L.item()}')

# Walk the computational graph:
L.backward()

# Get the derivative:
derivative = x.grad
print(f'dL/dx = {derivative}')
Output
1
2
3
x = tensor([1., 2., 3.], requires_grad=True)
L = 14.0
dL/dx = tensor([2., 4., 6.])

Exercise 3

Create x = tensor(1.0, requires_grad=True) and backpropagate twice in a loop over a simple function (e.g. x**2) without calling zero_grad(). Observe the problem. Fix it with x.grad.zero_() and explain why PyTorch accumulates gradients by default. (You are not computing the second derivative!)

Show solution
# Create the tensor:
x = torch.tensor(1.0, requires_grad=True)

# Compute the same derivative twice without zero_grad()
print('--- Without zero_grad() ---')
for i in range(2):
    y = x ** 2
    y.backward()
    print(f"{i+1}º grad: {x.grad}") # Should return 1º grad: 2.0; 2º grad: 2.0, but...
x.grad.zero_()

print("--- With zero_grad() ---")
for i in range(2):

    y = x ** 2
    y.backward()
    print(f"{i+1}º  grad: {x.grad}")
    x.grad.zero_()
Output
1
2
3
4
5
6
--- Without zero_grad() ---
1º grad: 2.0
2º grad: 4.0
--- With zero_grad() ---
1º  grad: 2.0
2º  grad: 2.0

Exercise 4

Simulate a training step:

  • Define the weights as w=0.5, b=0.0 and lr=0.1. Do they require gradients by default?
  • Define x = torch.linspace(0,1, 20) and compute y_true = 3*x +2 and y_pred = w*x + b. What values do you expect w and b to take after the update?
  • Compute the MSE loss and show the computational graph.
  • Backpropagate and update the weights by hand with the following approaches, in order:
  • Compute w = w - lr * w.grad. Show the computational graph. How does it differ from the previous one?
  • Inside a try block, compute w -= lr * w.grad. What error do you get? This explains the difference between the two graphs.
  • Compute w.data -= lr*w.grad and show the computational graph. What has changed by accessing .data?
  • Finally, update the weights inside a torch.no_grad() block and show the graph. Notice how the graph goes back to its original clean state.
  • Use .detach() to extract a tensor's value without its computation history. Add a comment explaining when you would use .detach() and when torch.no_grad().
Show solution

Explanation:

.detach() vs torch.no_grad():

  • .detach() acts on a single, already existing tensor: it returns a view of that tensor without gradient history. The rest of the graph is left intact. Typical cases are logging values, computing metrics or converting to NumPy: any situation in which you need to extract a value without dragging its computation history along.

  • torch.no_grad() is a context manager that stops autograd from recording any new operation performed inside it. Nothing is extracted from an existing graph: no graph is built in the first place. It is the standard approach for inference loops and parameter updates.

In short: use .detach() when you want to pull a tensor out of an existing graph; use torch.no_grad() when you want a whole block of operations to be invisible to autograd from the start.

# Define the weights --> They are trainable parameters, so they require gradients:
w = torch.tensor(0.5, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
lr = 0.01 # This one doesn't require gradients.
# Set up a problem:
x = torch.linspace(0,1, 20)
y_true = 3*x + 2
y_pred = w*x + b # They should converge to w = 3 and b = 2

# Loss + visualisation
loss = ((y_pred - y_true)**2).mean()
display(make_dot(loss, {'w':w, 'b':b, 'loss':loss}))

Output of cell 11

# Backpropagation with w = w - lr*w.grad

# Show w and b before updating:
print('--- Before uptdate ---')
loss_value = loss.detach()
w_value = w.detach()
b_value = b.detach()
print(f'Loss = {loss_value:.4f}')
print(f'w = {w_value}')
print(f'b = {b_value}')

loss.backward()
w = w - lr*w.grad
b = b - lr*b.grad
print('--- After the Update ---')
print(f'New w = {w.item()}')
print(f'New b = {b.item()}')

# Visualisation:
display(make_dot(loss, {'w':w, 'b':b, 'loss':loss}))
Output
1
2
3
4
5
6
7
--- Before uptdate ---
Loss = 11.1382
w = 0.5
b = 0.0
--- After the Update ---
New w = 0.5371052622795105
New b = 0.0650000050663948

Output of cell 12

Here we have lost the leaf nodes w and b. This is because the update step (w = w - lr*w.grad) creates new tensors that are the result of an operation, so they are no longer leaf nodes. The variables w and b now point to those new tensors, which are not part of the original computational graph of loss.

# Define the weights --> They are trainable parameters, so they require gradients:
w = torch.tensor(0.5, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
lr = 0.01 # This one doesn't require gradients.
# Set up a problem:
x = torch.linspace(0,1, 20)
y_true = 3*x + 2
y_pred = w*x + b # They should converge to w = 3 and b = 2

# Loss + visualisation
loss = ((y_pred - y_true)**2).mean()
loss.backward()
# Try the update:
try:
    w -= lr*w.grad
    b -= lr*b.grad
except RuntimeError as e:
    print(f'RuntimeError: {e}')
Output
RuntimeError: a leaf Variable that requires grad is being used in an in-place operation.

As mentioned above, w -=lr*w.grad creates new tensors, so they are no longer leaf nodes. Unlike the previous cell, here an explicit error is raised.

# Backpropagation with w.data:

# Define the weights --> They are trainable parameters, so they require gradients:
w = torch.tensor(0.5, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
lr = 0.01 # This one doesn't require gradients.

# Set up a problem:
x = torch.linspace(0,1, 20)
y_true = 3*x + 2
y_pred = w*x + b # They should converge to w = 3 and b = 2

# Loss + visualisation
loss = ((y_pred - y_true)**2).mean()

loss.backward()

# Update:
print('--- Before uptdate ---')
loss_value = loss.detach()
w_value = w.detach()
b_value = b.detach()
print(f'Loss = {loss_value:.4f}')
print(f'w = {w_value}')
print(f'b = {b_value}')

w.data -= lr*w.grad
b.data -= lr*b.grad

print('--- After the Update ---')
w_value = w.detach()
b_value = b.detach()
print(f'New w = {w_value:.4f}')
print(f'New b = {b_value:.4f}')

display(make_dot(loss, {'w':w, 'b':b, 'loss':loss}))
Output
1
2
3
4
5
6
7
--- Before uptdate ---
Loss = 11.1382
w = 0.5
b = 0.0
--- After the Update ---
New w = 0.5371
New b = 0.0650

Output of cell 16

Although modifying tensor.data may look like a quick way to update the weights without recording the operation in the computational graph, it is an outdated and very dangerous practice in production.

The reason is that using .data completely bypasses autograd's version tracking and safety checks. Specifically:

  • Memory corruption: by running w.data -= ..., you rewrite the underlying memory without telling the framework.
  • Loss of graph integrity: autograd doesn't find out that the tensor's value has changed (without .data, on the other hand, it does detect it).
  • Silent poisoning: if that modified tensor is used in later forward passes or gradient computations, autograd will use a stale state. The result is mathematically incorrect gradients. The code won't crash: it will simply fail to converge or learn incorrect patterns without warning.

The standard good practice: torch.no_grad()

# Backpropagation with w.data:

# Define the weights --> They are trainable parameters, so they require gradients:
w = torch.tensor(0.5, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
lr = 0.01 # This one doesn't require gradients.

# Set up a problem:
x = torch.linspace(0,1, 20)
y_true = 3*x + 2
y_pred = w*x + b # They should converge to w = 3 and b = 2

# Loss + visualisation
loss = ((y_pred - y_true)**2).mean()
loss.backward()

# Update:
print('--- Before uptdate ---')
loss_value = loss.detach()
w_value = w.detach()
b_value = b.detach()
print(f'Loss = {loss_value:.4f}')
print(f'w = {w_value}')
print(f'b = {b_value}')

with torch.no_grad():
    w -= lr*w.grad
    b -= lr*b.grad

print('--- After the Update ---')
print(f'New w = {w.item()}')
print(f'New b = {b.item()}')

display(make_dot(loss, {'w':w, 'b':b, 'loss':loss}))
Output
1
2
3
4
5
6
7
--- Before uptdate ---
Loss = 11.1382
w = 0.5
b = 0.0
--- After the Update ---
New w = 0.5371052622795105
New b = 0.0650000050663948

Output of cell 18

Exercise 5

Without using nn.Module, define w and b as 0-dimensional tensors with requires_grad=True. Generate a dataset of 100 samples with \(x \sim \text{Uniform}(0,1)\) and synthetic labels \(y = 2x + 1 + \varepsilon\), where \(\varepsilon \sim \mathcal{N}(0, 0.1^2)\). Train for 100 epochs with MSE loss and a learning rate lr = 0.1. After each backward pass, update the parameters by hand inside a torch.no_grad() block and zero the gradients manually. Show the loss every 10 epochs and check that w converges to \(\sim 2\) and b to \(\sim 1\).

Show solution
torch.manual_seed(42)
# Define w and b:
w = torch.tensor(0.5, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)

learning_rate = 0.1

# Synthetic data:
x = torch.rand(100)
epsilon = torch.randn(100) * 0.1
y_true = 2*x + 1 + epsilon

# Training:
epochs = 100
for i in range(epochs):
    y_pred = w*x + b
    loss = ((y_pred - y_true)**2).mean()

    if (i % 10 == 0) or (i == epochs - 1):
        print(f'--- Epoch {i} ---')
        loss_value = loss.detach()
        w_value = w.detach()
        b_value = b.detach()

        print(f'Loss: {loss_value:.4f}')
        print(f'W = {w_value:.4f}')
        print(f'b = {b_value:.4f}')

    loss.backward()
    with torch.no_grad():
        w -= learning_rate * w.grad
        b -= learning_rate * b.grad
        w.grad.zero_()
        b.grad.zero_()
Output
--- Epoch 0 ---
Loss: 3.3317
W = 0.5000
b = 0.0000
--- Epoch 10 ---
Loss: 0.0461
W = 1.3195
b = 1.2801
--- Epoch 20 ---
Loss: 0.0302
W = 1.4320
b = 1.3068
--- Epoch 30 ---
Loss: 0.0246
W = 1.4993
b = 1.2741
--- Epoch 40 ---
Loss: 0.0204
W = 1.5566
b = 1.2426
--- Epoch 50 ---
Loss: 0.0171
W = 1.6067
b = 1.2150
--- Epoch 60 ---
Loss: 0.0147
W = 1.6504
b = 1.1908
--- Epoch 70 ---
Loss: 0.0128
W = 1.6886
b = 1.1697
--- Epoch 80 ---
Loss: 0.0113
W = 1.7220
b = 1.1512
--- Epoch 90 ---
Loss: 0.0102
W = 1.7512
b = 1.1351
--- Epoch 99 ---
Loss: 0.0094
W = 1.7743
b = 1.1223

Exercise 6

Define x = torch.tensor(1.0, requires_grad=True) and compute \(y = \log(\sigma(x^2))\), where \(\sigma\) is the sigmoid function. Backpropagate and show x.grad. Then apply the chain rule by hand to obtain \(\frac{dy}{dx}\) and evaluate it at \(x = 1.0\). Check that both values match with torch.isclose().

Show solution
# Chain rule with torch:
x = torch.tensor(1.0, requires_grad=True)
y = torch.log(torch.sigmoid(x**2))

y.backward()
print(f'Derivative with x.grad = {x.grad:.4f}')

# Chain rule by hand:
diff = 2*x/(torch.exp(x**2) +1)
print(f'Manual differentiation: {diff:.4f}')

# Do they match?
print(f'Do they match?\n{torch.isclose(x.grad, diff).item()}')
Output
1
2
3
4
Derivative with x.grad = 0.5379
Manual differentiation: 0.5379
Do they match?
True

Exercise 7

Compute the second derivative of \(y = x^4 - 3x^2\) at \(x = 2.0\) using torch.autograd.grad() with create_graph=True. Verify the result analytically. When would higher-order gradients be useful in machine learning?

Show solution

Some examples where defining our own derivatives can be useful are:

  • Second-order optimisation: Hessian matrices for curvature (e.g. Newton's method).
  • Meta-learning (MAML): backpropagating through the inner loop's gradient steps.
  • Regularisation: penalising gradient norms (e.g. WGAN-GP).
  • PINNs: loss functions that incorporate partial differential equations.
  • Hyperparameter tuning: differentiating the validation loss with respect to the hyperparameters.
  • Uncertainty estimation: inverse Hessian for Laplace approximations.
x = torch.tensor(2.0, requires_grad=True)
y = torch.pow(x, 4) - 3*torch.pow(x, 2)

# First derivative:
dy_dx = torch.autograd.grad(y,x, create_graph=True)
print(f'1º derivative (autograd): {dy_dx[0]:.4f}')
print(f'1º derivative (analytically): {(4*x**3 - 6*x):.4f}')

# Second derivative:
dy2_dx2 = torch.autograd.grad(dy_dx[0], x, create_graph=True)
print(f'2º derivative (autograd): {dy2_dx2[0]:.4f}')
print(f'2º derivative (analytically): {(12*x**2 - 6):.4f}')
Output
1
2
3
4
1º derivative (autograd): 20.0000
1º derivative (analytically): 20.0000
2º derivative (autograd): 42.0000
2º derivative (analytically): 42.0000

Exercise 8

Given an input vector \(x = [1.0, 2.0, 3.0]\) and the function \(f(x) = [x_1^2, x_1 x_2, x_3^3]\), compute the full Jacobian matrix with torch.autograd.functional.jacobian(). Then compute the Hessian of \(g(x) = x_1^2 + 2x_2^2 + x_3^2\). Hint: define f(x) and g(x) as lambda functions.

Show solution
1
2
3
4
5
6
7
8
x = torch.tensor([1,2,3], dtype=torch.float32, requires_grad=True)
f = lambda x: torch.stack([x[0]**2, x[0]*x[1], x[2]**3])
g = lambda x: x[0]**2 + 2*x[1]**2 + x[2]**2

jacob = torch.autograd.functional.jacobian(f, x)
hess = torch.autograd.functional.hessian(g,x)
print(jacob)
print(hess)
Output
1
2
3
4
5
6
tensor([[ 2.,  0.,  0.],
        [ 2.,  1.,  0.],
        [ 0.,  0., 27.]])
tensor([[2., 0., 0.],
        [0., 4., 0.],
        [0., 0., 2.]])

Exercise 9

Train a small fully connected network with 3 nn.Linear layers and nn.ReLU activations on synthetic regression data (200 samples, 10 input features, 1 output). Use SGD with a deliberately high learning rate (lr = 10.0) and train for 80 epochs.

First, train without gradient clipping and observe how the gradient norm and the loss behave. Then repeat the experiment three times applying torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm) after loss.backward() and before optimizer.step(), with max_norm ∈ {10.0, 1.0, 0.1}.

In each run, record per epoch the global gradient norm returned by clip_grad_norm_() (which reflects the norm before clipping) and the MSE loss. Finally, draw two side-by-side subplots: - Left: MSE loss per epoch for the 4 configurations. - Right: gradient norm per epoch (log scale) for the 4 configurations.

Compare the training stability across configurations and explain the trade-off between a very small max_norm (slow learning) and no clipping at all (divergence).

  • Hint:
    • Architecture: 10 → Linear(10,64) → ReLU() → Linear(64,64) → ReLU() → Linear (64,1)
    • Loss: nn.MSELoss
    • Optimiser: torch.optim.SGD
Show solution
import pandas as pd

# Data:
torch.manual_seed(42)
X = torch.randn(200, 10)
y = torch.randn(200, 1)

df_X = pd.DataFrame(X.numpy(), columns=[f"x{i+1}" for i in range(10)])
df_y = pd.DataFrame(y.numpy(), columns=["y"])
dataframe = pd.concat([df_X, df_y], axis=1)

dataframe
x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 y
0 1.926915 1.487284 0.900717 -2.105521 0.678418 -1.234545 -0.043067 -1.604667 -0.752135 1.648723 -0.992757
1 -0.392479 -1.403607 -0.727881 -0.559430 -0.768839 0.762445 1.642317 -0.159597 -0.497398 0.439589 -0.255756
2 -0.758131 1.078318 0.800801 1.680621 1.279124 1.296423 0.610466 1.334738 -0.231624 0.041759 -0.958570
3 -0.251575 0.859859 -1.384674 -0.871236 -0.223366 1.717361 0.318880 -0.424519 0.305721 -0.774593 -0.570275
4 -1.557572 0.995636 -0.879786 -0.601142 -1.274151 2.122785 -1.234653 -0.487914 -0.913823 -0.658137 0.192817
... ... ... ... ... ... ... ... ... ... ... ...
195 1.443667 0.196146 -0.833257 -0.952684 -0.363669 -1.247925 -0.092614 0.653364 0.163699 1.345614 -0.667007
196 -0.369537 -0.471416 0.477922 0.850947 0.368844 1.062230 1.763923 -0.048380 0.912708 -1.390617 0.287722
197 -0.709612 0.930798 -0.424322 -0.482174 0.477377 -0.178998 0.493735 0.561208 -1.798656 -0.607846 -0.854220
198 -0.587634 -0.345177 -0.728777 -1.495753 0.735095 -0.269319 0.450859 0.040917 -0.069333 0.258576 0.750013
199 0.477546 -1.488918 -1.293003 0.879566 0.073064 0.996736 1.023791 -1.213252 0.974454 0.453227 -2.154439

200 rows × 11 columns

import torch.nn as nn
torch.manual_seed(42)
# Loss, epochs and learning rate:
loss_fn = nn.MSELoss()
epochs = 80
lr = 10

# Configurations:
configs = {"No clipping": None,
           "max_norm = 10": 10,
           "max_norm = 1.0": 1.0,
           "max_norm = 0.1": 0.1}

# Train each configuration:
results = {}
for key, max_norm in configs.items():
    # Create the model for the configuration:
    model = nn.Sequential(nn.Linear(10, 64), nn.ReLU(),
                       nn.Linear(64,64), nn.ReLU(),
                       nn.Linear(64,1))

    # Optimiser:
    optimizer = torch.optim.SGD(model.parameters(), lr=lr)

    # Lists to store the data:
    losses, grad_norms = [], []
    print(f'Starting training with {key}')
    for epoch in range(epochs):

        optimizer.zero_grad()
        loss = loss_fn(model(X), y)
        loss.backward()

        if max_norm is not None:
            total_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=max_norm).item()
        else:
            total_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=float('inf')).item()

        optimizer.step()

        losses.append(loss.item())
        grad_norms.append(total_norm)
        if epoch % 10 == 0 or epoch == epochs - 1 :
            print(f'Epoch {epoch} ----->  Loss: {loss.item():.4f}   ;   Grad_Norm: {total_norm}')
    results[key] = {'loss':losses,'grad_norm':grad_norms}
Output
Starting training with No clipping
Epoch 0 ----->  Loss: 0.9953   ;   Grad_Norm: 0.858018159866333
Epoch 10 ----->  Loss: nan   ;   Grad_Norm: nan
Epoch 20 ----->  Loss: nan   ;   Grad_Norm: nan
Epoch 30 ----->  Loss: nan   ;   Grad_Norm: nan
Epoch 40 ----->  Loss: nan   ;   Grad_Norm: nan
Epoch 50 ----->  Loss: nan   ;   Grad_Norm: nan
Epoch 60 ----->  Loss: nan   ;   Grad_Norm: nan
Epoch 70 ----->  Loss: nan   ;   Grad_Norm: nan
Epoch 79 ----->  Loss: nan   ;   Grad_Norm: nan
Starting training with max_norm = 10
Epoch 0 ----->  Loss: 0.9639   ;   Grad_Norm: 0.8588319420814514
Epoch 10 ----->  Loss: 4473683.0000   ;   Grad_Norm: 2109432.5
Epoch 20 ----->  Loss: 7758.7305   ;   Grad_Norm: 176.15699768066406
Epoch 30 ----->  Loss: 7758.7212   ;   Grad_Norm: 176.15687561035156
Epoch 40 ----->  Loss: 7758.7212   ;   Grad_Norm: 176.15687561035156
Epoch 50 ----->  Loss: 7758.7212   ;   Grad_Norm: 176.15687561035156
Epoch 60 ----->  Loss: 7758.7212   ;   Grad_Norm: 176.15687561035156
Epoch 70 ----->  Loss: 7758.7212   ;   Grad_Norm: 176.15687561035156
Epoch 79 ----->  Loss: 143.0325   ;   Grad_Norm: 23.84311294555664
Starting training with max_norm = 1.0
Epoch 0 ----->  Loss: 0.9187   ;   Grad_Norm: 0.23576533794403076
Epoch 10 ----->  Loss: 66.4816   ;   Grad_Norm: 16.1954345703125
Epoch 20 ----->  Loss: 66.4814   ;   Grad_Norm: 16.195384979248047
Epoch 30 ----->  Loss: 66.4814   ;   Grad_Norm: 16.19536781311035
Epoch 40 ----->  Loss: 66.4813   ;   Grad_Norm: 16.195358276367188
Epoch 50 ----->  Loss: 66.4812   ;   Grad_Norm: 16.195348739624023
Epoch 60 ----->  Loss: 66.4810   ;   Grad_Norm: 16.195329666137695
Epoch 70 ----->  Loss: 66.4809   ;   Grad_Norm: 16.1953125
Epoch 79 ----->  Loss: 4.5279   ;   Grad_Norm: 3.8047077655792236
Starting training with max_norm = 0.1
Epoch 0 ----->  Loss: 0.9061   ;   Grad_Norm: 0.18277660012245178
Epoch 10 ----->  Loss: 1.2903   ;   Grad_Norm: 1.5171394348144531
Epoch 20 ----->  Loss: 1.1552   ;   Grad_Norm: 1.3623524904251099
Epoch 30 ----->  Loss: 1.0212   ;   Grad_Norm: 1.4269465208053589
Epoch 40 ----->  Loss: 0.9418   ;   Grad_Norm: 1.402063012123108
Epoch 50 ----->  Loss: 0.8406   ;   Grad_Norm: 1.419020414352417
Epoch 60 ----->  Loss: 0.8271   ;   Grad_Norm: 1.5968881845474243
Epoch 70 ----->  Loss: 0.7105   ;   Grad_Norm: 1.5595043897628784
Epoch 79 ----->  Loss: 0.6362   ;   Grad_Norm: 1.504143476486206
import matplotlib.pyplot as plt
epoch_range = range(len(results["No clipping"]["loss"]))

colors = {"No clipping":   "red",
          "max_norm = 10":  "orange",
          "max_norm = 1.0": "blue",
          "max_norm = 0.1": "green"}

fig = plt.figure(figsize=(18, 9))
fig.suptitle(f"Gradient Clipping — LR={lr}", fontsize=14, fontweight="bold")

for i, (label, data) in enumerate(results.items()):
    ax = fig.add_subplot(2, 4, i + 1)
    ax.plot(epoch_range, data["loss"], color=colors[label])
    ax.set_title(label)
    ax.set_xlabel("Epoch")
    ax.set_ylabel("Loss")
    ax.grid(alpha=0.3)


ax_grad = fig.add_subplot(2, 1, 2)
for label, data in results.items():
    ax_grad.plot(epoch_range, data["grad_norm"], label=label, color=colors[label])
ax_grad.set_title("Gradient norm per epoch")
ax_grad.set_xlabel("Epoch")
ax_grad.set_ylabel("‖grad‖")
ax_grad.set_yscale("log")
ax_grad.legend()
ax_grad.grid(alpha=0.3)

plt.tight_layout()
plt.show()

Output of cell 30

How to read the plots?

No clipping (red): the loss explodes to ~\(10^{24}\) and the run dies around epoch 3: the network ends up completely broken. The gradient norm reaches ~\(10^4\) almost instantly.

max_norm = 10 (orange): still unstable. The loss shoots up to ~\(10^9\) in the first epochs and then drops almost to zero, but the gradient norm stays chaotic and large (~10²). The network "survives" by luck, not because it learns.

max_norm = 1.0 (blue): the loss oscillates violently between 0 and 80 over the 80 epochs: the gradient norm is capped at ~1, but lr=10 is still too aggressive. It never converges.

max_norm = 0.1 (green): the only configuration that actually learns. The loss falls from ~2.5 with a downward trend, with some oscillation. The gradient norm stays bounded near 1.

What is gradient clipping?

During backpropagation, gradients can grow exponentially through deep networks, especially with high learning rates or long sequences. When you call:

torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)

PyTorch computes the global gradient norm over all the parameters:

\[\|g\| = \sqrt{\sum_{p} \|g_p\|^2}\]

If \(\|g\| > \text{max\_norm}\), it rescales all the gradients proportionally so that the norm is exactly max_norm:

\[g \leftarrow g \cdot \frac{\text{max\_norm}}{\|g\|}\]

The direction of the gradient is preserved; only its magnitude is reduced.

Why does it matter?

Without clipping, a single bad update can push the weights to extreme values, which makes every subsequent gradient even larger: a feedback loop called exploding gradients. Clipping acts as a safety valve: it lets the network take large steps when the gradients are small, but prevents catastrophic updates when they shoot up. It is especially critical in:

  • RNNs and LSTMs (long sequences amplify gradients over time)
  • Schedules with high learning rates
  • The start of training, when the weights are randomly initialised and unstable

The trade-off the plot shows: a max_norm that is too large doesn't help (orange, blue) and one that is too small slows learning down but at least keeps it stable (green). In practice, you would also lower the learning rate along with clipping.

Exercise 10

Implement your own SoftPlus activation function \(f(x) = \log(1 + e^x)\) by subclassing torch.autograd.Function with your own forward() and backward() methods. Verify that the gradient is mathematically correct by checking it with torch.autograd.gradcheck().

Show solution
# 1. Custom SoftPlus through torch.autograd.Function
class SoftPlusFunction(torch.autograd.Function):

    @staticmethod
    def forward(ctx, x):
        # f(x) = log(1 + e^x)
        ctx.save_for_backward(x)
        return torch.log(1 + torch.exp(x))

    @staticmethod
    def backward(ctx, grad_output):
        # f'(x) = e^x / (1 + e^x) = sigmoid(x)
        x, = ctx.saved_tensors
        grad_input = torch.sigmoid(x)
        return grad_output * grad_input   # chain rule


# Wrapper as an nn.Module (optional, but handy)
class SoftPlus(nn.Module):
    def forward(self, x):
        return SoftPlusFunction.apply(x)


# Manual check
x = torch.tensor([-2.0, -1.0, 0.0, 1.0, 2.0], requires_grad=True)

custom_out  = SoftPlusFunction.apply(x)
pytorch_out = torch.nn.functional.softplus(x)

print("Custom  :", custom_out.detach())
print("PyTorch :", pytorch_out.detach())
print("Match   :", torch.allclose(custom_out, pytorch_out))

# Gradient check  --> gradcheck requires float64 and small tensors
x_check = torch.randn(5, dtype=torch.float64, requires_grad=True)

passed = torch.autograd.gradcheck(
    SoftPlusFunction.apply,
    x_check,
    eps=1e-6,    # numerical perturbation for the finite differences
    atol=1e-4,   # absolute tolerance
    rtol=1e-3    # relative tolerance
)

print(f"\nGradcheck passed: {passed}")
Output
1
2
3
4
5
Custom  : tensor([0.1269, 0.3133, 0.6931, 1.3133, 2.1269])
PyTorch : tensor([0.1269, 0.3133, 0.6931, 1.3133, 2.1269])
Match   : True

Gradcheck passed: True

Summary

torch.autograd is the mathematical engine that makes end-to-end differentiable programming possible in PyTorch. The topics in this entry (from the mechanics of the computational graph and backpropagation, through gradient accumulation, tracking control and higher-order derivatives, to custom operations) make up the complete conceptual toolkit needed to understand, debug and extend any gradient-based training procedure. *

See also