AI Systems First-Principles AI From Zero · Companion 02

Inside Automatic Differentiation: Building a Scalar Autograd Engine

Tracing computational graphs, topological sorting, and reverse-mode chain rule mechanics from scratch so backpropagation is never a black box.

Backpropagation is often presented as an esoteric neural-network trick. In reality, it is a clean graph algorithm executing the multivariable chain rule in reverse. Once you implement a scalar autograd engine in roughly fifty lines of Python, the mystery vanishes—and modern tensor libraries like PyTorch become transparent accelerators of the exact same protocol.

Why Reverse-Mode Differentiation Wins for Machine Learning

Suppose a function maps n learnable parameters to a single scalar loss L ∈ ℝ. Three classic ways exist to compute its derivatives:

Method Accuracy Cost for n Parameters → 1 Loss Core Limitation
Symbolic differentiation Exact algebraic form Exponential expression swell Produces unreadable, redundant formulas on deep loops
Finite differences Approximate (O(h) or O(h²)) n + 1 forward passes Prohibitive for millions of weights; floating-point cancellation
Forward-mode autodiff Exact (machine precision) n passes Ideal when outputs vastly outnumber inputs, not scalar loss
Reverse-mode autodiff Exact (machine precision) 1 forward + 1 backward pass Must store intermediate activations in memory during forward pass

Because neural network training almost always optimises a single scalar loss with respect to thousands or billions of weights, reverse-mode automatic differentiation delivers exact sensitivities at constant overhead relative to a forward pass.

Recording the Computational Graph

During the forward pass, each arithmetic operation does two things: it computes its numeric result and records its parent operands alongside a local _backward closure explaining how to push an incoming downstream gradient (self.grad) back to those parents.

class Scalar:
    def __init__(self, data: float, parents=()):
        self.data = float(data)
        self.grad = 0.0
        self._parents = set(parents)
        self._backward = lambda: None

    def __add__(self, other: "Scalar") -> "Scalar":
        out = Scalar(self.data + other.data, (self, other))
        def _backward():
            # Addition routes the downstream gradient unchanged to both branches
            self.grad += out.grad
            other.grad += out.grad
        out._backward = _backward
        return out

    def __mul__(self, other: "Scalar") -> "Scalar":
        out = Scalar(self.data * other.data, (self, other))
        def _backward():
            # Product rule: swap operand values and multiply by downstream gradient
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad
        out._backward = _backward
        return out

    def backward(self) -> None:
        topo, visited = [], set()
        def build_topo(node: "Scalar") -> None:
            if node not in visited:
                visited.add(node)
                for parent in node._parents:
                    build_topo(parent)
                topo.append(node)
        build_topo(self)

        self.grad = 1.0
        for node in reversed(topo):
            node._backward()

Two Subtle Invariants That Break Naive Implementations

First, inspect the += operator inside _backward. If the same variable x participates in multiple branches—such as y = x * x or a residual skip connection y = x + f(x)—the multivariable chain rule dictates that gradients sum across all outgoing paths. Writing self.grad = ... instead of self.grad += ... silently discards one branch and produces plausible-looking yet mathematically wrong training curves.

Second, inspect the topological sort (build_topo). A parent node must never execute its own _backward until every child depending on it has already finished contributing to parent.grad. Reversing a post-order depth-first traversal guarantees that dependency order across any directed acyclic graph.

Local Gradient Gates: Visualising Flow

Thinking of elementary operators as gradient routers makes debugging deep networks intuitive:

  • Addition (+) is a gradient distributor: it copies the incoming gradient identically to both inputs. This is precisely why residual connections (x + sublayer(x)) create an unobstructed gradient highway across dozens of Transformer blocks.
  • Multiplication (*) is a gradient swapper: each input receives the downstream gradient scaled by the other input’s forward value. Extreme activations on one branch therefore amplify gradients on the other.
  • ReLU (max(0, x)) is a binary valve: it passes gradients cleanly when x > 0 and zeroes them completely when x <= 0. If poor initialisation pushes a neuron permanently negative across the dataset, its gradient stays zero forever—a “dead ReLU”.
  • tanh and sigmoid compress extremes: near ±1 for tanh, the local derivative 1 − t² approaches zero, extinguishing upstream signal when pre-activations grow too large.

Verifying Gradients Numerically Before Trusting Training

Whenever you implement a custom activation, loss function, or fused kernel, verify your analytical backward pass against centred finite differences on random double-precision inputs:

def numerical_grad(fn, x: float, eps: float = 1e-6) -> float:
    return (fn(x + eps) - fn(x - eps)) / (2.0 * eps)

Compare param.grad against numerical_grad using relative error |g_a − g_n| / max(|g_a| + |g_n|, 1e-8). Values below 1e-7 confirm algebraic soundness; anything larger than 1e-4 almost always exposes a missing factor, flipped sign, or dropped accumulation path before you waste hours tuning hyperparameters on a broken engine.

Continue Reading