← Back to Blog

Backpropagation and Automatic Differentiation

Introduction

Training a neural network means adjusting its parameters to reduce a loss, and that requires the derivative of the loss with respect to every parameter. A modern network can have millions or billions of them. Backpropagation computes all of those derivatives at about the cost of a small, constant number of forward passes.

By the end of this article you should be able to trace backpropagation by hand on a small graph, explain why deep learning uses reverse mode rather than forward mode, and read a small automatic differentiation engine, which is included below and has been executed.

The Chain Rule on a Graph

Any computation can be written as a graph of simple operations, each with a known local derivative. If a loss L depends on a through an intermediate value p, the chain rule says:

dL/da = dL/dp × dp/da

Backpropagation is the chain rule applied in an efficient order. A forward pass computes and stores each intermediate value. A backward pass starts from the loss, whose derivative with respect to itself is 1, and walks the graph in reverse. Each node multiplies its accumulated derivative by the local derivative of each input and passes the result back. If a value is used in more than one place, its contributions are added.

A Worked Example

Take one neuron with a sigmoid output and binary cross-entropy loss, for one example with x = 2 and label y = 1, starting from w = 0.5 and b = −0.5.

Forward stepValueLocal derivativeBackward value
a = w·x + b0.5000da/dw = x = 2, da/db = 1dL/dw = −0.7551, dL/db = −0.3775
p = σ(a)0.6225dp/da = p(1 − p) = 0.2350dL/da = −0.3775
L = −ln(p)0.4741dL/dp = −1/p = −1.6065dL/dp = −1.6065

Read the last column from the bottom up: −1.6065 × 0.2350 = −0.3775, then −0.3775 × 2 = −0.7551. Both gradients are negative, so increasing w or b reduces the loss, as expected for a positive example with p below 1.

Each number is computed in your browser by the same steps as the table, with y = 1. Push w·x + b far below zero and notice the size of the gradients: with this loss they approach −x and −1, so the model still gets a strong correction when it is badly wrong. Push it far above zero and they approach zero, because the prediction is already correct.

A Small Autodiff Engine

Automatic differentiation is not symbolic differentiation, which manipulates formulas, and it is not numerical differentiation, which uses finite differences. It records operations on actual values and applies exact local derivatives. This engine implements reverse mode for the example above:

import math

class Value:
    """A number that records how it was computed."""

    def __init__(self, data, parents=(), local_grads=()):
        self.data = data
        self.grad = 0.0
        self.parents = parents          # inputs to the operation
        self.local_grads = local_grads  # d(self)/d(parent), one per parent

    def __add__(self, other):
        return Value(self.data + other.data, (self, other), (1.0, 1.0))

    def __mul__(self, other):
        return Value(self.data * other.data, (self, other), (other.data, self.data))

    def sigmoid(self):
        p = 1.0 / (1.0 + math.exp(-self.data))
        return Value(p, (self,), (p * (1.0 - p),))

    def neg_log(self):
        return Value(-math.log(self.data), (self,), (-1.0 / self.data,))

    def backward(self):
        # Visit each node after every node that depends on it.
        order, seen = [], set()

        def visit(node):
            if node not in seen:
                seen.add(node)
                for parent in node.parents:
                    visit(parent)
                order.append(node)

        visit(self)
        self.grad = 1.0
        for node in reversed(order):
            for parent, local in zip(node.parents, node.local_grads):
                parent.grad += node.grad * local  # the chain rule


w, b, x = Value(0.5), Value(-0.5), Value(2.0)
loss = (w * x + b).sigmoid().neg_log()   # label y = 1
loss.backward()
print(f"loss = {loss.data:.4f}, dL/dw = {w.grad:.4f}, dL/db = {b.grad:.4f}")

Running it prints loss = 0.4741, dL/dw = -0.7551, dL/db = -0.3775, which matches the table. The same calculation in PyTorch looks like this:

import torch

w = torch.tensor(0.5, requires_grad=True)
b = torch.tensor(-0.5, requires_grad=True)
x, y = torch.tensor(2.0), torch.tensor(1.0)

loss = torch.nn.functional.binary_cross_entropy(torch.sigmoid(w * x + b), y)
loss.backward()
print(w.grad, b.grad)

PyTorch builds the graph as operations run, and backward() fills in each leaf's .grad. Gradients accumulate across calls, which is why training loops zero them at each step.

Why Reverse Mode?

Forward mode pushes derivatives from inputs to outputs. One pass gives the derivative of every output with respect to one input. Reverse mode gives the derivative of one output with respect to every input.

Forward modeReverse mode
Passes needed for the full gradientOne per inputOne per output
Best whenFew inputs, many outputsMany inputs, few outputs
MemoryLow: no stored graphMust retain intermediates for the backward pass

A training loss is a single scalar that depends on many parameters, which is the ideal case for reverse mode. Its cost is memory: intermediate values must be kept until the backward pass. Gradient checkpointing reduces this by recomputing some values instead of storing them.

Where Things Go Wrong

Vanishing and exploding gradients. Backpropagation multiplies many local derivatives. If they tend to be small, early layers receive tiny gradients; if they tend to be large, updates can blow up. This is the context for the activation functions article, and for careful initialization, normalization, and residual connections.

Non-differentiable points. ReLU has no derivative at exactly zero. Frameworks use a subgradient, usually 0, there, and this rarely matters in practice.

Blocked gradients. Operations such as argmax have zero gradient almost everywhere, and detaching a tensor deliberately cuts the graph. Either can silently stop part of a model from learning.

A useful check. When writing a custom gradient, compare it with a central finite difference, (f(w + ε) − f(w − ε)) / 2ε. For the example above, this gives about −0.7551 for w.

Key idea: backpropagation computes gradients. It does not choose how to use them. Deciding how to step is the job of an optimizer, covered in Optimization Techniques.

References