Level 3 In-Depth AI · Programming and Tools
Build an Autograd Engine from Scratch
Write a tiny automatic-differentiation engine in about 70 lines of plain Python, a Value class that records every operation and backpropagates gradients through them, then use it to build and train a small neural network. The best way to make backpropagation concrete.
- Level
- ●●●●● Intermediate
- Reading
- 12 min
- To learn it well
- 1 hour to read, an evening to build
- Builds on
- 17 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 17 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Backpropagation
- Build an Autograd Engine from Scratch
Read them roughly in this order. See it on the concept map →
Why it matters
Every modern deep-learning library, including PyTorch, JAX and TensorFlow, has at its heart an autograd engine (short for automatic gradient). You write the forward calculation of your model in ordinary code. The library records what you did and, when you call .backward(), computes the gradient of the loss with respect to every parameter. That gradient is what Gradient Descent needs to improve the model. Without autograd, you would have to derive and code the derivatives of every model by hand, and a The Transformer has billions of parameters.
The Backpropagation chapter explains the mathematics: the The Chain Rule applied backwards through a graph of operations. This chapter turns that into working code. You will build a small engine, about 70 lines of plain Python with no libraries, closely modelled on Andrej Karpathy's teaching library micrograd. Then you will build a neural network on top of it and train it. After this, loss.backward() in PyTorch will never feel like magic again, because you will have written it yourself.
The intuition
Imagine every number in your calculation carries a little notebook. When two numbers are combined, say multiplied, the result writes in its notebook: "I was made by multiplying these two, and here is how to share blame between them."
After the calculation finishes, you have a final number, the loss. You ask: how much did each input contribute to it? Starting from the loss, you walk backwards through the notebooks. Each result passes blame back to the numbers that made it, using a simple local rule for its own operation. For addition, both inputs get the full blame. For multiplication, each input's blame is scaled by the other input's value. When you reach the start, every input holds its gradient.
The web of "who made whom" is the computation graph. The local rule for each operation is its local derivative. Walking backwards and multiplying local derivatives along the way is the chain rule. That is all backpropagation is.
How it works
A worked example by hand
Take three inputs, , and , and compute
Now go backwards. We want , and : how much changes when each input is nudged.
- Start at the end: .
- , whose local derivative is . So .
- , where . Addition passes the gradient through unchanged: and .
- . The local derivative with respect to is , and with respect to is . So and .
Check one by nudging: increase from 2 to 2.001. Then and , a drop of about 0.024, which is . The gradient is right.
The Value class
The engine is one class, Value, which wraps a single number. Each Value stores:
data, the number itself;grad, the gradient of the final output with respect to this value, starting at 0;_prev, the values it was computed from (its children in the graph);_backward, a small function that knows how to pass this value's gradient to its children.
The trick that makes it feel natural is operator overloading: defining the special methods __add__, __mul__ and so on, so that a * b + c on Value objects calls our code, which computes the result and records how it was made. Each operation creates a new Value and attaches a _backward closure that applies that operation's local derivative.
Two details matter.
- Gradients accumulate with
+=. If a value is used twice, as ina * aor a weight shared across examples, gradient flows back to it along both paths and the contributions must be added, not overwritten. This is also why you must reset gradients to zero before every training step, exactly as withoptimizer.zero_grad()in PyTorch. - Order matters. A node may only pass its gradient back after it has received all of its own gradient. So
backward()first sorts the graph into topological order, a list in which every node comes after all the nodes it depends on, and then visits that list in reverse.
Here is the complete engine. Save it as engine.py.
import math
class Value:
"""A number that remembers how it was made, so it can backpropagate."""
def __init__(self, data, _children=(), _op=""):
self.data = data
self.grad = 0.0 # dL/d(this value), filled in by backward()
self._backward = lambda: None # how to pass gradient to the children
self._prev = set(_children)
self._op = _op
def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other), "+")
def _backward():
self.grad += out.grad # d(a+b)/da = 1
other.grad += out.grad # d(a+b)/db = 1
out._backward = _backward
return out
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other), "*")
def _backward():
self.grad += other.data * out.grad # d(a*b)/da = b
other.grad += self.data * out.grad # d(a*b)/db = a
out._backward = _backward
return out
def __pow__(self, k): # k is a plain number
out = Value(self.data ** k, (self,), f"**{k}")
def _backward():
self.grad += k * self.data ** (k - 1) * out.grad
out._backward = _backward
return out
def tanh(self):
t = math.tanh(self.data)
out = Value(t, (self,), "tanh")
def _backward():
self.grad += (1 - t ** 2) * out.grad # d tanh(x)/dx = 1 - tanh²
out._backward = _backward
return out
def backward(self):
# Order the graph so each node comes after everything it depends on.
order, seen = [], set()
def build(v):
if v not in seen:
seen.add(v)
for child in v._prev:
build(child)
order.append(v)
build(self)
self.grad = 1.0 # dL/dL = 1
for v in reversed(order): # walk backwards: output to inputs
v._backward()
# Conveniences so that -a, a - b, 2 * a and a / b all work.
def __neg__(self): return self * -1
def __sub__(self, other): return self + (-other)
def __radd__(self, other): return self + other
def __rmul__(self, other): return self * other
def __truediv__(self, other): return self * other ** -1
def __repr__(self): return f"Value(data={self.data:.4f}, grad={self.grad:.4f})"
The __r...__ methods handle expressions such as 2 * a, where the plain number comes first. Subtraction and division are built from the operations we already have, so they get correct gradients for free.
Run the worked example to check the engine against the hand calculation:
from engine import Value
a, b, c = Value(2.0), Value(-3.0), Value(10.0)
d = a * b + c
L = d ** 2
L.backward()
print(a, b, c, d, sep="\n")
# Value(data=2.0000, grad=-24.0000)
# Value(data=-3.0000, grad=16.0000)
# Value(data=10.0000, grad=8.0000)
# Value(data=4.0000, grad=8.0000)
Exactly the numbers we derived by hand. As a second check, a single neuron with , , gives gradients , and for , and in our engine, and PyTorch's torch.tanh with requires_grad=True reports the same values to every printed digit.
From numbers to a neural network
A neuron computes a weighted sum of its inputs plus a bias, then applies an activation function: . With Value objects, that is one line. A layer is a list of neurons that all see the same inputs. A multilayer perceptron (MLP) is a list of layers, each feeding the next. Every weight and bias is a Value, so after a forward pass the whole network, the loss and all the arithmetic between them form one big computation graph, and a single loss.backward() fills in the gradient of every parameter.
Key idea Autograd is just bookkeeping. Every operation records its inputs and its local derivative.
backward()visits the operations in reverse order, multiplying and adding up gradients as it goes. That is the chain rule, applied automatically.
In code
Here is a complete neural network built on engine.py, trained on four tiny examples to output +1 or −1. It has 41 parameters in total: three inputs, two hidden layers of four neurons, and one output neuron. Save it next to engine.py and run it, or paste both files into a single notebook cell and drop the import line.
import random
from engine import Value
class Neuron:
def __init__(self, n_inputs):
self.w = [Value(random.uniform(-1, 1)) for _ in range(n_inputs)]
self.b = Value(0.0)
def __call__(self, x):
act = sum((wi * xi for wi, xi in zip(self.w, x)), self.b) # w·x + b
return act.tanh()
def parameters(self):
return self.w + [self.b]
class Layer:
def __init__(self, n_inputs, n_outputs):
self.neurons = [Neuron(n_inputs) for _ in range(n_outputs)]
def __call__(self, x):
out = [n(x) for n in self.neurons]
return out[0] if len(out) == 1 else out
def parameters(self):
return [p for n in self.neurons for p in n.parameters()]
class MLP:
def __init__(self, n_inputs, layer_sizes):
sizes = [n_inputs] + layer_sizes
self.layers = [Layer(sizes[i], sizes[i + 1]) for i in range(len(layer_sizes))]
def __call__(self, x):
for layer in self.layers:
x = layer(x)
return x
def parameters(self):
return [p for layer in self.layers for p in layer.parameters()]
random.seed(1)
xs = [[2.0, 3.0, -1.0], [3.0, -1.0, 0.5], [0.5, 1.0, 1.0], [1.0, 1.0, -1.0]]
ys = [1.0, -1.0, -1.0, 1.0] # the target for each example
model = MLP(3, [4, 4, 1]) # 3 inputs, two hidden layers of 4, 1 output
print("parameters:", len(model.parameters()))
for step in range(51):
preds = [model(x) for x in xs] # forward pass
loss = sum((p - y) ** 2 for p, y in zip(preds, ys)) # squared error
for p in model.parameters():
p.grad = 0.0 # zero the gradients
loss.backward() # backward pass
for p in model.parameters():
p.data -= 0.05 * p.grad # gradient descent step
if step % 10 == 0:
print(f"step {step:2d} loss {loss.data:.4f}")
print([round(model(x).data, 3) for x in xs])
# parameters: 41
# step 0 loss 4.5167
# step 10 loss 0.1225
# step 20 loss 0.0470
# step 30 loss 0.0280
# step 40 loss 0.0196
# step 50 loss 0.0150
# [0.949, -0.928, -0.943, 0.94]
The loss falls from 4.5 to 0.015 in 50 steps, and the outputs approach the targets . Notice how the classes mirror PyTorch: Neuron, Layer and MLP each have a __call__ (PyTorch calls it forward) and a parameters() method, which is exactly what nn.Module provides. The loop's five lines, forward, loss, zero gradients, backward and update, are the same five lines in PyTorch, only with optimizer.zero_grad() and optimizer.step().
Common pitfalls
- Forgetting to zero gradients. Because gradients accumulate, skipping
p.grad = 0.0makes each step use the sum of all previous gradients, so the steps keep growing. Removing that line from the script above makes the loss jump from 4.5 to 8.0 by step 10, swing wildly, and then get stuck at 4.0, with one of the four examples permanently wrong. - Overwriting instead of accumulating. Writing
self.grad = out.gradinstead of+=gives wrong gradients whenever a value is used more than once, which in a neural network is almost always. The bug is silent: training just works worse. - Calling
_backwardin the wrong order. Without the topological sort, a node may pass on its gradient before receiving all of it. - Mutating
datainside the graph. Changingp.datais fine between steps. Changing values during the forward pass breaks the recorded local derivatives. - Expecting speed. Every single multiplication is a Python object. This engine is thousands of times slower than PyTorch, which works on whole Tensors and Shapes at once in compiled code on GPUs. The ideas are identical. The engineering is not.
Watch out Always test a hand-written gradient. The standard check is finite differences: nudge an input by a tiny amount (say ), recompute the output, and compare with your gradient. Libraries such as PyTorch provide
torch.autograd.gradcheckfor exactly this. A gradient bug rarely crashes. It makes training quietly worse.
Where it leads
- PyTorch is this engine scaled up: values become tensors,
_backwardclosures become optimised kernels, andMLPbecomesnn.Module. - Add more operations to your engine:
relu,expandlog. Withexpandlogyou can implement cross-entropy and train a classifier. Each new operation needs only its forward value and its local derivative. - Backpropagation explains why reverse mode is efficient: one backward pass gives the gradients of a single loss with respect to all parameters, at about the cost of one or two forward passes.
- Build a GPT from Scratch uses PyTorch's autograd, which you now understand, to train a small GPT.
A bit of history
Automatic differentiation is older than deep learning. Its forward mode was described by Robert Wengert in 1964, and Seppo Linnainmaa described reverse-mode differentiation, the kind used here, in his 1970 master's thesis. Rumelhart, Hinton and Williams made it famous for neural networks in 1986 under the name backpropagation. Early deep-learning libraries such as Theano (2007) built a graph first and then ran it. Chainer (2015) and then PyTorch (2016) popularised the "define-by-run" style used in this chapter, where the graph is recorded as ordinary code runs, which makes debugging with normal Python tools possible. Andrej Karpathy released micrograd in 2020 as a teaching tool, and his video building it step by step has become one of the most popular introductions to how neural networks really learn.
Try it
- Add a
relumethod toValue(outputmax(0, x), local derivative 1 ifx > 0else 0) and use it instead oftanhin the hidden layers. Does training still work?- Remove the gradient-zeroing loop and run training again. What happens to the loss?
- Add
exptoValueand check your gradient with finite differences onValue(1.5).exp().Hint for 3: the derivative of is , so in
_backwarduseout.data. The finite-difference estimate is(math.exp(1.5 + 1e-6) - math.exp(1.5)) / 1e-6, about 4.4817.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
The spelled-out intro to neural networks and backpropagation: building micrograd
A patient 2.5-hour live-coding session that builds micrograd from nothing and trains a small network with it. The ideal companion to this chapter.
micrograd
A tiny autograd engine in about 100 lines. Reading it is the best way to demystify backprop.
Neural Networks: Zero to Hero
A video series that builds backprop, language models and finally GPT from an empty file. Many people consider it the best way to really understand LLMs.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Automatic Differentiation with torch.autograd
The official tutorial on how PyTorch records computation graphs and computes gradients with backward().
Learning representations by back-propagating errors
The paper that popularised backpropagation for training multi-layer networks.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/programming/autograd-from-scratch.md