Foundations to Frontier
Tests
E. Deep Learning › E0 Core Concepts (concept pages)

Building an Autograd Engine from Scratch

An autograd engine computes gradients automatically. Every operation on its tensors records its inputs and a small backward function; calling backward on the loss walks this recorded graph in reverse topological order, and each node adds its contribution to its inputs' gradients. A scalar engine (one node per number) is simple and shows the idea, but practical engines work on whole arrays, so one node covers a matrix product over the whole batch, and they must undo broadcasting by summing gradients over expanded axes. This page builds a tensor autograd engine with addition, multiplication, matrix products, activations and a fused cross-entropy, explains gradient accumulation, broadcasting and topological ordering, and compares scalar and tensor engines. In the exercises you implement the engine, verify it against finite differences and train a network with it, then measure how graph size scales for scalar versus tensor engines.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A calculator that remembers

Imagine a calculator that writes down every step it performs. When you ask how the final answer depends on each input, it reads its notes backwards and works out each step’s contribution. An autograd engine is that calculator for arrays: it records operations as you compute, then replays them in reverse to produce gradients.

A tensor autograd graph: one node per array operation
X · 32×2grad ?W1 · 2×16grad ?X @ W1 · 32×16grad ?b1 · 16grad ?+ b1 · 32×16grad ?tanh · 32×16grad ?W2 · 16×2grad ?@ W2 · 32×2grad ?b2 · 2grad ?+ b2 · 32×2grad ?loss · scalargrad ?
tensor graph: 11 nodes, whatever the sizes · scalar graph for the same computation: roughly 5,586 nodes
Blue boxes are leaves (data and parameters). Backward runs in reverse topological order, and every gradient has exactly the shape of its value. The biases were broadcast over the batch in the forward pass, so their gradients are summed over the batch on the way back. A scalar engine would create a node for every single multiplication, so its graph grows with batch × width, while the tensor engine keeps 11 nodes and lets fast matrix code do the work inside each one.
Why engineers care

PyTorch, JAX and TensorFlow are autograd engines. Building a small one removes the magic: you learn why gradients accumulate, why shapes must match, what “detach” and “no_grad” do, and how memory is spent. All of this matters when writing custom layers or debugging training of perception and control networks.

📝 Quick check (Level 0)
0/3 answered
  1. 1. An autograd engine records…
  2. 2. Gradients are computed by…
  3. 3. PyTorch's loss.backward() is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The pieces by hand

Each node stores:

  • its value;
  • a gradient buffer (initially zero);
  • its parents;
  • a backward function that adds its local contribution to its parents’ gradients.

Local rules (G is the upstream gradient ∂L/∂out):

  • add: both inputs receive G;
  • multiply, elementwise: x receives G·y and y receives G·x;
  • matmul: C = AB gives A the gradient G Bᵀ and B the gradient Aᵀ G. For c = a·b with a = (1, 2) and b = (3, 4)ᵀ, ∂c/∂a = (3, 4) and ∂c/∂b = (1, 2)ᵀ;
  • tanh: the input receives G ⊙ (1 − t²), using the stored output t;
  • sum: every input entry receives G.

Accumulate, don’t overwrite. A value used several times receives the sum of all its uses’ gradients. For y = x² + 3x at x = 2, the three uses of x give 2 + 2 + 3 = 7, which is dy/dx.

Broadcasting. Adding a bias of shape (H) to a batch of shape (B, H) copies it B times. Its gradient must therefore be summed over the batch axis to recover shape (H). With an all-ones upstream gradient of shape (3, 4), a bias of shape (4) gets (3, 3, 3, 3).

Backward pass. Topologically sort the graph from the loss, set ∂L/∂L = 1, and call each node’s backward function in reverse order.

📝 Quick check (Level 1)
0/3 answered
  1. 1. For C = AB, ∂L/∂A is…
  2. 2. A bias broadcast over a batch of 8 receives…
  3. 3. Why accumulate gradients with +=?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.

Building it

The engine is a Tensor class that wraps a numpy array. Each operation (__add__, __mul__, __matmul__, relu, tanh, sum, cross_entropy) returns a new Tensor that knows its parents and its backward closure. backward() sorts the graph by depth-first search and runs the closures in reverse.

Fused cross-entropy. Computing softmax, then log, then indexing as separate nodes works but is numerically fragile. A single node that computes the log-sum-exp stably and whose backward is (P − Y)/B is both faster and safer. Frameworks do the same.

Exercise 1.

  • The engine’s gradients for ((a + b).relu() @ c × 2).sum(), with b broadcast over rows, matched finite differences to 2.0 × 10⁻¹⁰, and b’s gradient had b’s shape (4).
  • Training a 2 → 16 → 2 tanh network on 200 moon points cut the loss from 0.551 to 0.027 in 1000 steps, reaching training accuracy 0.995.
x = torch.randn(32, 2, requires_grad=False)
W = torch.randn(2, 16, requires_grad=True)
loss = torch.tanh(x @ W).sum()
loss.backward(); print(W.grad.shape)          # torch.Size([2, 16])
with torch.no_grad(): W -= 0.1 * W.grad; W.grad.zero_()
🐍 Exercise 1: a tensor autograd engine
Implement a Tensor class with add, mul (with broadcasting), matmul, relu, tanh, sum and fused cross-entropy, a reverse-topological backward pass, check it with finite differences and train a small network on two moons.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Why fuse softmax and cross-entropy into one node?
  2. 2. Before each training step you must…
  3. 3. The backward order is…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory and design choices

Correctness. Reverse-mode AD computes exact derivatives (up to rounding) of the program as written. For a scalar output its cost is a small constant times the forward cost (Griewank and Walther, 2008).

Memory. Each node must keep the values its backward function needs: inputs for products, outputs for tanh and sigmoid. This is the activation memory of training.

  • torch.no_grad() turns recording off.
  • .detach() cuts a value out of the graph.
  • Checkpointing frees intermediate values and recomputes them.

Define-by-run versus define-then-run. PyTorch builds the graph afresh as the code executes, so Python control flow just works. TensorFlow 1 and JAX’s jit trace a graph first and then optimise and compile it. JAX also composes grad with vmap and jit as function transformations.

Higher-order gradients. If backward functions are themselves written with differentiable operations, the engine can differentiate its own gradients (create_graph=True). Hessian-vector products then cost about two backward passes.

Pitfalls.

  • In-place updates of values needed later corrupt gradients. PyTorch tracks versions to detect this.
  • Non-differentiable points (ReLU at 0) use a conventional subgradient.
  • Integer operations carry no gradient.

Interview questions.

  • Why do frameworks accumulate into .grad instead of overwriting it? To support values used several times, and gradient accumulation across micro-batches. Users must zero the buffers each step.
  • Why are tensor engines so much faster than scalar ones? Each node runs one optimised array kernel. Graph bookkeeping is per operation, not per number (exercise 2).
📝 Quick check (Level 3)
0/3 answered
  1. 1. torch.no_grad() is used to…
  2. 2. JAX's jit is an example of…
  3. 3. In-place modification of a value needed in backward…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

Scalar versus tensor engines

History.

  • R. Wengert (1964) described forward-mode automatic differentiation.
  • S. Linnainmaa (1970) and B. Speelpenning (1980) described reverse mode.
  • Theano (2010), Autograd (Maclaurin, Duvenaud and Adams, 2015), PyTorch (Paszke et al., 2017, 2019) and JAX (2018) brought tensor autograd to machine learning.
  • A. Karpathy’s micrograd (2020) popularised the 100-line scalar engine.

Exercise 2. The same 2-layer tanh network with cross-entropy loss is built in both engines. Both give the same gradients, with a maximum difference of about 10⁻¹⁷.

batch hidden tensor-graph nodes scalar-graph nodes ratio scalar time / tensor time
8 4 11 457 42 7×
8 16 11 1 573 143 23×
32 16 11 6 037 549 113×
32 64 11 23 173 2 107 265×
  • The tensor graph has 11 nodes whatever the sizes. Each matrix product or activation over the whole batch is one node.
  • The scalar graph grew with batch × width, to over 23 000 Python objects for a tiny network. Its run time grew with it, while the tensor engine’s per-node work went to fast array code.
  • The time ratio depends on the machine and changes from run to run, and in the browser it is different again, but the trend is the same.
  • Gradients agreed to machine precision, so the speed-up costs nothing in correctness. This is why real engines operate on tensors and push the arithmetic into optimised kernels.
🐍 Exercise 2 (research): scalar versus tensor autograd
Implement a scalar (micrograd-style) engine with add, mul, tanh, exp and log, build the same network and loss in both engines, and compare graph sizes, gradients and run times.

Autograd in AI, robotics and aerospace

  • Differentiable programming: trajectory optimisation, system identification and learned simulators differentiate through physics code with autograd.
  • Custom operations: adding a new sensor model or loss as an autograd function with a hand-written backward (C3-2).
  • Deployment: inference engines strip the autograd machinery entirely, removing its memory and bookkeeping costs.

References

  1. A. Griewank, A. Walther (2008). Evaluating Derivatives, 2nd ed. SIAM.
  2. A. G. Baydin, B. A. Pearlmutter, A. A. Radul, J. M. Siskind (2018). “Automatic differentiation in machine learning: a survey.” JMLR 18.
  3. A. Paszke et al. (2019). “PyTorch: an imperative style, high-performance deep learning library.” Advances in NeurIPS 32.
  4. D. Maclaurin, D. Duvenaud, R. P. Adams (2015). “Autograd: effortless gradients in numpy.” ICML AutoML Workshop.