TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › A Small Autograd Engine for Arrays

A Small Autograd Engine for Arrays

The layer API of the previous lesson still asks you to write a backward for every module. A new idea, say multiplying two branches or adding a penalty on the weights, means a new module and a new hand-derived gradient. Automatic differentiation removes that last bit of manual work: you write only the forward computation with ordinary-looking operations, and every operation records itself in a graph together with its local derivative. One call to backward() then walks the graph from the loss back to the inputs.

The Mathematics track builds this idea for single numbers in a tiny autodiff engine, and forward and reverse mode explains why deep learning uses reverse mode. This lesson builds the version that matters for neural networks: a Tensor class that wraps a whole NumPy array, so one node is a matrix product or a ReLU over a batch rather than one multiplication. Two new problems appear at array level: gradients of matrix products, and broadcasting.

How reverse mode works on a graph

Every Tensor holds its value data, a gradient grad of the same shape (initially zeros), the tensors it was computed from (parents), and a closure _backward that knows the local rule of the operation that created it. For c=a⊙bc = a \odot b the closure adds cˉ⊙b\bar c \odot b to a.grad and cˉ⊙a\bar c \odot a to b.grad, where cˉ=∂L/∂c\bar c = \partial L / \partial c is the gradient already accumulated in c.grad.

L X matmul add relu matmul add cross_entropy W1 b1 W2 b2 backward: visit the nodes in reverse topological order, each _backward adds into its parents' .grad forward: every op creates a Tensor that remembers its parents

backward() on the loss does three things:

  1. Topological sort. A depth-first search from the loss lists every node after all of its parents.
  2. Seed. It sets ∂L/∂L=1\partial L / \partial L = 1.
  3. Sweep. It calls _backward on the nodes in reverse order. When a node's turn comes, every node that used it has already pushed its contribution into its grad, so the gradient is complete before it is passed on.

The closures add (+=) into the parents' gradients rather than assigning. That is the multivariate chain rule: if a tensor feeds several operations, its gradient is the sum over all paths,

∂L∂x=∑k∂L∂yk∂yk∂x\frac{\partial L}{\partial x} = \sum_{k} \frac{\partial L}{\partial y_k} \frac{\partial y_k}{\partial x}

where yky_k are the tensors computed directly from xx.

Broadcasting needs an un-broadcast

When a bias b∈Rhb \in \mathbb{R}^{h} is added to a batch Z∈Rn×hZ \in \mathbb{R}^{n \times h}, NumPy silently copies bb into every row. The forward pass used bb nn times, so by the sum rule above its gradient is the sum of the upstream gradient over the copied axis:

Y=Z+1b⊤⇒∂L∂b=∑i=1nYˉi,:Y = Z + \mathbf{1} b^\top \quad \Rightarrow \quad \frac{\partial L}{\partial b} = \sum_{i=1}^{n} \bar Y_{i,:}

In general, unbroadcast(g, shape) sums the gradient over every axis that broadcasting added in front and over every axis where the original had size 1, so the result has the original shape. Every binary operation runs its parents' gradients through it. For the other operations the local rules are the usual ones: for C=ABC = AB, Aˉ=CˉB⊤\bar A = \bar C B^\top and Bˉ=A⊤Cˉ\bar B = A^\top \bar C (as for Linear); for s=∑xs = \sum x, every entry gets sˉ\bar s; and for an elementwise ff, xˉ=yˉ⊙f′(x)\bar x = \bar y \odot f'(x). The rules for arrays are covered more fully in einsum and broadcasting.

A minimal engine: add, mul, sum

The whole mechanism fits in a few dozen lines. Two tests: a tensor used twice, f=∑(x⊙x+x)f = \sum (x \odot x + x) with ∂f/∂x=2x+1\partial f / \partial x = 2x + 1, and a bias broadcast over a batch:

python · try it yourself
import numpy as np

def unbroadcast(g, shape):
    """Sum g over the axes that broadcasting added or stretched, so it has `shape` again."""
    while g.ndim > len(shape):
        g = g.sum(axis=0)
    for axis, size in enumerate(shape):
        if size == 1 and g.shape[axis] != 1:
            g = g.sum(axis=axis, keepdims=True)
    return g

class Tensor:
    def __init__(self, data, parents=()):
        self.data = np.asarray(data, dtype=float)
        self.grad = np.zeros_like(self.data)
        self.parents = parents
        self._backward = lambda: None           # set by the op that created this tensor

    def __add__(self, other):
        out = Tensor(self.data + other.data, (self, other))
        def _backward():
            self.grad += unbroadcast(out.grad, self.data.shape)
            other.grad += unbroadcast(out.grad, other.data.shape)
        out._backward = _backward
        return out

    def __mul__(self, other):
        out = Tensor(self.data * other.data, (self, other))
        def _backward():
            self.grad += unbroadcast(out.grad * other.data, self.data.shape)
            other.grad += unbroadcast(out.grad * self.data, other.data.shape)
        out._backward = _backward
        return out

    def sum(self):
        out = Tensor(self.data.sum(), (self,))
        def _backward():
            self.grad += out.grad * np.ones_like(self.data)
        out._backward = _backward
        return out

    def backward(self):
        order, seen = [], set()
        def visit(t):                           # depth-first: parents before children
            if id(t) not in seen:
                seen.add(id(t))
                for p in t.parents:
                    visit(p)
                order.append(t)
        visit(self)
        self.grad = np.ones_like(self.data)     # dL/dL = 1
        for t in reversed(order):               # children before parents
            t._backward()
        return order

# a tensor used twice: f = sum(x * x + x), df/dx = 2x + 1
x = Tensor([1.0, 2.0, 3.0])
f = (x * x + x).sum()
order = f.backward()
print("f =", float(f.data), " grad x =", x.grad.tolist(), " nodes in topological order:", len(order))

# broadcasting: a bias of shape (3,) added to a batch of shape (2, 3)
X = Tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = Tensor([0.1, 0.2, 0.3])
w = Tensor([[1.0, 0.0, -1.0], [2.0, 1.0, 0.0]])
L = ((X + b) * w).sum()
L.backward()
print("grad b =", b.grad.tolist(), "(column sums of w)  grad X =", X.grad.tolist())
f = 20.0  grad x = [3.0, 5.0, 7.0]  nodes in topological order: 4
grad b = [3.0, 1.0, -1.0] (column sums of w)  grad X = [[1.0, 0.0, -1.0], [2.0, 1.0, 0.0]]

For x=(1,2,3)x = (1, 2, 3) the gradient is (3,5,7)=2x+1(3, 5, 7) = 2x + 1. The 2x2x comes from xx appearing on both sides of the product: __mul__ adds cˉ⊙x\bar c \odot x to x.grad twice, once as self and once as other, and the += keeps both. Replace every += in the engine by = and the result is (1,2,3)(1, 2, 3): each assignment overwrites the contributions that arrived before it, silently. The graph has 4 nodes: xx, the product, the sum x⊙x+xx \odot x + x and the final sum.

For the broadcast bias, b.grad is (3,1,−1)(3, 1, -1), the column sums of ww: each entry of bb was used in both rows. X.grad equals ww, as it should for ∑(X+b)⊙w\sum (X + b) \odot w.

The full engine

Now the operations an MLP needs: +, *, - and negation with broadcasting, @ for 2-D matrices, sum and mean with an optional axis, relu, tanh, exp, log, and a fused, numerically stable cross_entropy(y) that takes logits and integer labels (its backward is the (P−Y)/n(P - Y)/n of output layers and losses). Every operation is checked against central differences, then a whole 3-5-3 MLP loss is checked, and the fused cross-entropy is compared with the same loss built from the primitives exp, sum, log and mean:

python · try it yourself
import numpy as np

def unbroadcast(g, shape):
    while g.ndim > len(shape):
        g = g.sum(axis=0)
    for axis, size in enumerate(shape):
        if size == 1 and g.shape[axis] != 1:
            g = g.sum(axis=axis, keepdims=True)
    return g

def as_tensor(x):
    return x if isinstance(x, Tensor) else Tensor(x)

class Tensor:
    def __init__(self, data, parents=(), op=""):
        self.data = np.asarray(data, dtype=float)
        self.grad = np.zeros_like(self.data)
        self.parents, self.op = parents, op
        self._backward = lambda: None

    shape = property(lambda self: self.data.shape)
    def __repr__(self):
        return f"Tensor(shape={self.shape}, op='{self.op}')"

    def __add__(self, other):
        other = as_tensor(other)
        out = Tensor(self.data + other.data, (self, other), "add")
        def _backward():
            self.grad += unbroadcast(out.grad, self.shape)
            other.grad += unbroadcast(out.grad, other.shape)
        out._backward = _backward
        return out

    def __mul__(self, other):
        other = as_tensor(other)
        out = Tensor(self.data * other.data, (self, other), "mul")
        def _backward():
            self.grad += unbroadcast(out.grad * other.data, self.shape)
            other.grad += unbroadcast(out.grad * self.data, other.shape)
        out._backward = _backward
        return out

    __radd__, __rmul__ = __add__, __mul__
    def __neg__(self): return self * -1.0
    def __sub__(self, other): return self + (-as_tensor(other))

    def __matmul__(self, other):                       # 2-D @ 2-D
        out = Tensor(self.data @ other.data, (self, other), "matmul")
        def _backward():
            self.grad += out.grad @ other.data.T
            other.grad += self.data.T @ out.grad
        out._backward = _backward
        return out

    def sum(self, axis=None, keepdims=False):
        out = Tensor(self.data.sum(axis=axis, keepdims=keepdims), (self,), "sum")
        def _backward():
            g = out.grad if keepdims or axis is None else np.expand_dims(out.grad, axis)
            self.grad += np.broadcast_to(g, self.shape)
        out._backward = _backward
        return out

    def mean(self, axis=None, keepdims=False):
        n = self.data.size if axis is None else self.shape[axis]
        return self.sum(axis, keepdims) * (1.0 / n)

    def _unary(self, value, local_grad, op):           # elementwise f with f'(x) given
        out = Tensor(value, (self,), op)
        def _backward():
            self.grad += out.grad * local_grad()
        out._backward = _backward
        return out

    def relu(self): return self._unary(np.maximum(self.data, 0), lambda: (self.data > 0) * 1.0, "relu")
    def tanh(self):
        t = np.tanh(self.data)
        return self._unary(t, lambda: 1 - t ** 2, "tanh")
    def exp(self):
        e = np.exp(self.data)
        return self._unary(e, lambda: e, "exp")
    def log(self): return self._unary(np.log(self.data), lambda: 1 / self.data, "log")

    def cross_entropy(self, y):                         # fused, stable: logits (n, C), y (n,) ints
        Z = self.data - self.data.max(axis=1, keepdims=True)
        P = np.exp(Z) / np.exp(Z).sum(axis=1, keepdims=True)
        n = len(y)
        out = Tensor(-np.log(P[np.arange(n), y]).mean(), (self,), "cross_entropy")
        def _backward():
            G = P.copy(); G[np.arange(n), y] -= 1
            self.grad += out.grad * G / n
        out._backward = _backward
        return out

    def backward(self):
        order, seen = [], set()
        def visit(t):
            if id(t) not in seen:
                seen.add(id(t))
                for p in t.parents:
                    visit(p)
                order.append(t)
        visit(self)
        self.grad = np.ones_like(self.data)             # leaves accumulate, as in PyTorch
        for t in reversed(order):
            t._backward()
        return order

def numeric_grad(f, t, h=1e-6):                         # central differences, one entry at a time
    g = np.zeros_like(t.data)
    for idx in np.ndindex(t.shape):
        old = t.data[idx]
        t.data[idx] = old + h; up = f().data
        t.data[idx] = old - h; down = f().data
        t.data[idx] = old
        g[idx] = (up - down) / (2 * h)
    return g

def zero(*ts):
    for t in ts:
        t.grad = np.zeros_like(t.data)

def check(name, f, *inputs):
    zero(*inputs)
    f().backward()
    worst = max(np.abs(t.grad - numeric_grad(f, t)).max() / max(np.abs(t.grad).max(), 1e-8) for t in inputs)
    print(f"{name:34s} relative error < 1e-6: {bool(worst < 1e-6)}")

rng = np.random.default_rng(0)
A = Tensor(rng.normal(size=(4, 3))); B = Tensor(rng.normal(size=(3, 2)))
c = Tensor(rng.normal(size=(3,))); P = Tensor(rng.uniform(0.5, 2.0, size=(4, 3)))
check("add with broadcast (4,3)+(3,)", lambda: ((A + c) * A).sum(), A, c)
check("mul, sub, neg", lambda: (A * P - A * A).sum(), A, P)
check("matmul", lambda: ((A @ B) * (A @ B)).sum(), A, B)
check("sum(axis=0), mean(axis=1)", lambda: (A.sum(axis=0) * c).sum() + (A.mean(axis=1) * A.mean(axis=1)).sum(), A, c)
check("relu, tanh", lambda: (A.relu() * A.tanh()).sum(), A)
check("exp, log", lambda: (A.exp() + P.log() * A).mean(), A, P)

y = np.array([0, 2, 1, 2])
W1 = Tensor(rng.normal(0, 0.5, (3, 5))); b1 = Tensor(np.zeros(5))
W2 = Tensor(rng.normal(0, 0.5, (5, 3))); b2 = Tensor(np.zeros(3))
mlp = lambda: ((A @ W1 + b1).relu() @ W2 + b2).cross_entropy(y)
check("MLP with fused cross_entropy", mlp, W1, b1, W2, b2, A)

# the same loss from primitives: -mean(sum(onehot * log_softmax))
def ce_from_primitives():
    Z = (A @ W1 + b1).relu() @ W2 + b2
    log_p = Z - Z.exp().sum(axis=1, keepdims=True).log()
    return -(log_p * np.eye(3)[y]).sum(axis=1).mean()
zero(W1); loss = mlp(); order = loss.backward(); g_fused = W1.grad.copy()
zero(W1); loss2 = ce_from_primitives(); order2 = loss2.backward()
print("fused loss", round(float(loss.data), 6), " primitive loss", round(float(loss2.data), 6),
      " same grad W1:", bool(np.allclose(g_fused, W1.grad)))
print("fused graph:", len(order), "nodes:", [t.op or "leaf" for t in order])
print("primitive graph:", len(order2), "nodes")
add with broadcast (4,3)+(3,)      relative error < 1e-6: True
mul, sub, neg                      relative error < 1e-6: True
matmul                             relative error < 1e-6: True
sum(axis=0), mean(axis=1)          relative error < 1e-6: True
relu, tanh                         relative error < 1e-6: True
exp, log                           relative error < 1e-6: True
MLP with fused cross_entropy       relative error < 1e-6: True
fused loss 1.026527  primitive loss 1.026527  same grad W1: True
fused graph: 11 nodes: ['leaf', 'leaf', 'matmul', 'leaf', 'add', 'relu', 'leaf', 'matmul', 'leaf', 'add', 'cross_entropy']
primitive graph: 24 nodes

All seven checks pass with a relative error below 10−610^{-6}, including the broadcast add of a (3,)(3,) vector to a (4,3)(4, 3) matrix and the reductions along an axis. The fused and the primitive cross-entropy give the same loss, 1.026527, and the same gradient for W1W_1. The difference is the graph: the fused version has 11 nodes, listed in topological order (leaves first, cross_entropy last, exactly the order of the figure), while the primitive one has 24. A fused operation is faster, uses less memory for cached values and is more stable, because it subtracts the maximum before exponentiating. Note that ce_from_primitives skips that subtraction and only works here because the logits are small. That is why frameworks provide cross_entropy and log_softmax as single operations.

Like PyTorch, this engine accumulates into the leaves: calling backward on a second loss adds to the gradients of the first. That is why the checks set the gradients to zero before each pass, and why the training loop in the next lesson needs zero_grad().

What the engine leaves out

PyTorch's autograd is this design with industrial details added. It frees the graph after backward() (a second call raises an error unless you ask to keep it), stores which inputs each operation actually needs instead of capturing everything in closures, tracks requires_grad so that no graph is built for data or under no_grad, detects in-place changes to cached tensors with version counters, and runs the backward operations in C++ on any device. Autograd in PyTorch runs the same graph in both engines and compares the numbers.

Pitfalls

  • Assigning instead of accumulating. self.grad = ... in a closure is correct only as long as a tensor is used once. The first time a weight is shared or a tensor is reused, gradients go missing without any error.
  • Not un-broadcasting. Without unbroadcast, b.grad += out.grad tries to add an (n, h) array to an (h,) one and raises an error; if the shapes happen to broadcast (for example a (1, h) parameter), it silently computes the wrong values.
  • Calling backward() twice on the same graph. In this engine, intermediate gradients from the first pass are still there and are added again, so the leaves get more than twice the right value. Build a new graph (run the forward pass again) for every step.
  • Deep recursion in the topological sort. The recursive visit is fine for an MLP; a graph with thousands of sequential nodes (a long RNN unrolled step by step) exceeds Python's recursion limit. Real engines use an explicit stack.
  • Checking gradients at kinks. ReLU's derivative jumps at 0, so a central difference whose two points straddle a zero input disagrees with the analytic value. Random float64 inputs rarely hit it; a hand-made input with exact zeros will.

Practice

  1. Add a __pow__(self, k) method for a constant exponent kk.
Answer
python
def __pow__(self, k):
    out = Tensor(self.data ** k, (self,), "pow")
    def _backward():
        self.grad += out.grad * k * self.data ** (k - 1)
    out._backward = _backward
    return out
  1. What does unbroadcast return for a gradient of shape (8, 4, 5) and a parameter of shape (4, 1)?
Answer

First it sums over the leading axis that broadcasting added, giving (4, 5); then over axis 1, where the parameter has size 1, with keepdims=True, giving (4, 1). Each parameter entry collects the gradient of the 8⋅5=408 \cdot 5 = 40 positions it was copied to.

  1. The engine keeps no list of the tensors it created; it only has parent pointers. Why is a depth-first search from the loss the right way to find the nodes and their order?
Answer

Starting from the loss, the search reaches exactly the tensors the loss depends on (a tensor computed but never used in the loss is skipped), and appending a node only after all of its parents gives an order in which every node comes after its inputs. Reversed, every node comes after all of its consumers, so its gradient is complete when its _backward runs. An engine that records a global "tape" of operations could instead replay the tape backwards; PyTorch counts, for each node, how many consumers have still to deliver their gradient.

  1. Why can the fused cross_entropy backward ignore out.grad being anything other than 1 in a normal training step, and why does the code still multiply by it?
Answer

When the cross-entropy is the loss itself, out.grad is the seed 1. But the loss may be scaled or combined, for example ce * 0.5 + penalty, and then out.grad is 0.5. Multiplying keeps the rule correct wherever the operation sits in the graph.

Test yourself

Why do the _backward closures use += on their parents' gradients?

  1. For numerical stability
  2. A tensor used in several operations gets the sum of the gradients along all paths
  3. To save memory
  4. Because NumPy arrays are immutable

A bias of shape (h,) was broadcast-added to a batch of shape (n, h). What is its gradient?

  1. The upstream gradient, shape (n, h)
  2. The upstream gradient summed over the batch axis, shape (h,)
  3. The upstream gradient averaged over the batch axis
  4. Zero, since a bias is constant

In what order does backward() call the _backward closures?

  1. In the order the tensors were created
  2. In reverse topological order, starting from the loss
  3. In random order, since addition commutes
  4. Leaves first

For C=ABC = AB with upstream gradient Cˉ\bar C, what is Aˉ\bar A?

  1. A⊤CˉA^\top \bar C
  2. CˉB⊤\bar C B^\top
  3. BCˉB \bar C
  4. Cˉ⊤B\bar C^\top B