Artificial IntelligencePyTorch from scratch
1. Autograd and gradients
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:
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.
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)))\):
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:
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:
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.
.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.
| 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:
A training step consists of four operations:
- Forward: compute the predictions and the loss.
- Backward: call
loss.backward()to fill in.gradon every leaf tensor. - Parameter update: adjust the weights with gradient descent inside a
no_grad()block. - Zeroing the gradients: clear
.gradbefore 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():
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:
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}\):
PyTorch provides both through torch.autograd.functional:
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
NaNlosses.
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:
In PyTorch it is a single call, placed between .backward() and the optimiser 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 withctx.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.
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-exptricks). - 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:
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:
@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:
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
| Output | |
|---|---|
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).
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
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
Exercise 4¶
Simulate a training step:
- Define the weights as
w=0.5,b=0.0andlr=0.1. Do they require gradients by default? - Define
x = torch.linspace(0,1, 20)and computey_true = 3*x +2andy_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
tryblock, computew -= lr * w.grad. What error do you get? This explains the difference between the two graphs. - Compute
w.data -= lr*w.gradand 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 whentorch.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.
| Output | |
|---|---|
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.
| Output | |
|---|---|
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.
| Output | |
|---|---|
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:
autograddoesn'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,
autogradwill 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()
| Output | |
|---|---|
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
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
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.
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
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
| 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

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:
PyTorch computes the global gradient norm over all the parameters:
If \(\|g\| > \text{max\_norm}\), it rescales all the gradients proportionally so that the norm is exactly max_norm:
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
| Output | |
|---|---|
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.
*