Mini Project: A Tiny Autodiff Engine
In this project you will build a reverse-mode automatic differentiation engine from scratch in plain Python, about 70 lines, and then use it to train a single neuron and a tiny two-layer neural network. Nothing is imported except math and random. It pulls together the chain rule, partial derivatives, backpropagation, automatic differentiation and gradient descent.
What we are building: a Value class that wraps a number, remembers which operation produced it, and can push gradients backwards through everything that was computed from it. On top of it: Neuron, Layer and MLP classes, and a training loop whose printed loss falls epoch by epoch.
| Step | New concepts |
|---|---|
| 1. A value that remembers | graph nodes, local derivatives for + and *, manual backward pass |
| 2. The full engine | more operations, grad += for reused values, topological order, gradient check |
| 3. Neurons and layers | weights as Values, tanh activation, parameter lists |
| 4. Train one neuron | mean squared error, zeroing gradients, the update |
| 5. Train a two-layer net on XOR | why a hidden layer is needed, the loss falling |
Note: Every step is a complete program, so each block repeats the classes from the previous step. The engine is written for clarity, not speed: one Python object per number. Real frameworks apply the same idea to whole arrays at once.
Step 1: A value that remembers
A Value holds data, a grad (, filled in later) and its parents. Each operation creates a new Value and attaches a small back function that knows the local derivative: for out = a + b both inputs get out.grad; for out = a * b, a gets b·out.grad and b gets a·out.grad. For now we call the back functions by hand, in reverse order.
class Value:
def __init__(self, data, parents=()):
self.data, self.grad, self.parents = data, 0.0, parents
self.back = lambda: None
def __add__(self, other):
out = Value(self.data + other.data, (self, other))
def back():
self.grad += out.grad
other.grad += out.grad
out.back = back
return out
def __mul__(self, other):
out = Value(self.data * other.data, (self, other))
def back():
self.grad += other.data * out.grad
other.grad += self.data * out.grad
out.back = back
return out
a, b, c = Value(2.0), Value(-3.0), Value(10.0)
d = a * b # -6
e = d + c # 4
f = e * a # 8 f = (a·b + c)·a
f.grad = 1.0
for node in [f, e, d]: # reverse order of creation
node.back()
print(f"f = {f.data}")
print(f"df/da = {a.grad} df/db = {b.grad} df/dc = {c.grad}")f = 8.0
df/da = -2.0 df/db = 4.0 df/dc = 2.0
Check by hand: , so , and . The value a is used twice (in and in ); its two contributions, −6 (through ) and 4 (through ), add up, which is why every back uses +=.
Step 2: The full engine
Now add the remaining pieces:
__pow__(with a plain-number exponent),tanhandexp, each with its local derivative: , , .- Subtraction, negation and division expressed through the operations we have (, ), so they get gradients for free;
__radd__/__rmul__let us write2 * xorx + 1. backward(), which finds a topological order of the graph (every node after all of its inputs) with an iterative depth-first search, sets the output's grad to 1 and callsbackin reverse order.
Then test the engine the way frameworks are tested: compare every gradient with a central finite difference.
import math
class Value:
def __init__(self, data, parents=()):
self.data, self.grad, self.parents = float(data), 0.0, parents
self.back = lambda: None
def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other))
def back():
self.grad += out.grad
other.grad += out.grad
out.back = back
return out
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other))
def back():
self.grad += other.data * out.grad
other.grad += self.data * out.grad
out.back = back
return out
def __pow__(self, n): # n is a plain number
out = Value(self.data ** n, (self,))
def back():
self.grad += n * self.data ** (n - 1) * out.grad
out.back = back
return out
def tanh(self):
t = math.tanh(self.data)
out = Value(t, (self,))
def back():
self.grad += (1 - t * t) * out.grad
out.back = back
return out
def exp(self):
e = math.exp(self.data)
out = Value(e, (self,))
def back():
self.grad += e * out.grad
out.back = back
return out
__radd__ = __add__
__rmul__ = __mul__
def __neg__(self): return self * -1
def __sub__(self, other): return self + (-other)
def __rsub__(self, other): return other + (-self)
def __truediv__(self, other):
return self * (other ** -1 if isinstance(other, Value) else 1 / other)
def __rtruediv__(self, other): return other * self ** -1
def backward(self):
order, seen, stack = [], set(), [(self, False)]
while stack: # iterative depth-first search
v, done = stack.pop()
if done:
order.append(v)
elif v not in seen:
seen.add(v)
stack.append((v, True))
stack.extend((p, False) for p in v.parents if p not in seen)
self.grad = 1.0
for v in reversed(order):
v.back()
def f(a, b, c):
return (a * b + c).tanh() * a ** 2 + (b / c).exp() - 3 * a
a, b, c = Value(0.6), Value(-1.2), Value(0.8)
out = f(a, b, c)
out.backward()
print(f"f = {out.data:.6f}")
h = 1e-6
point = [0.6, -1.2, 0.8]
for i, (name, v) in enumerate(zip("abc", (a, b, c))):
up, down = point.copy(), point.copy()
up[i] += h; down[i] -= h
num = (f(*map(Value, up)).data - f(*map(Value, down)).data) / (2 * h)
print(f"df/d{name}: engine {v.grad: .6f} numeric {num: .6f}")f = -1.548131
df/da: engine -3.333451 numeric -3.333451
df/db: engine 0.493536 numeric 0.493536
df/dc: engine 0.776075 numeric 0.776075
All three gradients agree. If they did not, the fault would be in one of the back functions, and testing each operation alone would find it.
Step 3: Neurons and layers
A neuron computes , with its weights and bias stored as Values so gradients can reach them. A layer is a list of neurons that all see the same inputs, and an MLP (multi-layer perceptron) chains layers. Weights start as seeded random numbers in , so every run is identical.
import math
import random
class Value:
def __init__(self, data, parents=()):
self.data, self.grad, self.parents = float(data), 0.0, parents
self.back = lambda: None
def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other))
def back():
self.grad += out.grad
other.grad += out.grad
out.back = back
return out
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other))
def back():
self.grad += other.data * out.grad
other.grad += self.data * out.grad
out.back = back
return out
def __pow__(self, n): # n is a plain number
out = Value(self.data ** n, (self,))
def back():
self.grad += n * self.data ** (n - 1) * out.grad
out.back = back
return out
def tanh(self):
t = math.tanh(self.data)
out = Value(t, (self,))
def back():
self.grad += (1 - t * t) * out.grad
out.back = back
return out
def exp(self):
e = math.exp(self.data)
out = Value(e, (self,))
def back():
self.grad += e * out.grad
out.back = back
return out
__radd__ = __add__
__rmul__ = __mul__
def __neg__(self): return self * -1
def __sub__(self, other): return self + (-other)
def __rsub__(self, other): return other + (-self)
def __truediv__(self, other):
return self * (other ** -1 if isinstance(other, Value) else 1 / other)
def __rtruediv__(self, other): return other * self ** -1
def backward(self):
order, seen, stack = [], set(), [(self, False)]
while stack: # iterative depth-first search
v, done = stack.pop()
if done:
order.append(v)
elif v not in seen:
seen.add(v)
stack.append((v, True))
stack.extend((p, False) for p in v.parents if p not in seen)
self.grad = 1.0
for v in reversed(order):
v.back()
class Neuron:
def __init__(self, n_in, rng, act=True):
self.w = [Value(rng.uniform(-1, 1)) for _ in range(n_in)]
self.b = Value(0.0)
self.act = act
def __call__(self, x):
z = sum((wi * xi for wi, xi in zip(self.w, x)), self.b)
return z.tanh() if self.act else z
def parameters(self):
return self.w + [self.b]
class Layer:
def __init__(self, n_in, n_out, rng):
self.neurons = [Neuron(n_in, rng) for _ in range(n_out)]
def __call__(self, x):
return [n(x) for n in self.neurons]
def parameters(self):
return [p for n in self.neurons for p in n.parameters()]
class MLP:
def __init__(self, sizes, rng):
self.layers = [Layer(a, b, rng) for a, b in zip(sizes, sizes[1:])]
def __call__(self, x):
for layer in self.layers:
x = layer(x)
return x[0] if len(x) == 1 else x
def parameters(self):
return [p for layer in self.layers for p in layer.parameters()]
rng = random.Random(1)
neuron = Neuron(2, rng)
net = MLP([2, 4, 1], rng)
print("neuron parameters:", len(neuron.parameters()))
print("MLP 2-4-1 parameters:", len(net.parameters()), "(4·(2+1) + 1·(4+1))")
y = net([0.5, -1.0])
print(f"net([0.5, -1.0]) = {y.data:.6f}")
y.backward()
print("first three gradients:", [round(p.grad, 6) for p in net.parameters()[:3]])neuron parameters: 3
MLP 2-4-1 parameters: 17 (4·(2+1) + 1·(4+1))
net([0.5, -1.0]) = -0.277084
first three gradients: [0.18408, -0.36816, 0.36816]
One backward() call filled in the gradient of the output with respect to all 17 parameters.
Step 4: Train one neuron
A small seeded dataset: 16 points in the square , labelled +1 if and −1 otherwise. A single neuron draws a straight boundary, so it can learn this rule. Each epoch:
- compute the mean squared error over all points (one big graph),
- reset every parameter's grad to 0 (gradients accumulate with
+=, so stale ones would leak in), L.backward(),- step each parameter: .
import math
import random
class Value:
def __init__(self, data, parents=()):
self.data, self.grad, self.parents = float(data), 0.0, parents
self.back = lambda: None
def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other))
def back():
self.grad += out.grad
other.grad += out.grad
out.back = back
return out
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other))
def back():
self.grad += other.data * out.grad
other.grad += self.data * out.grad
out.back = back
return out
def __pow__(self, n): # n is a plain number
out = Value(self.data ** n, (self,))
def back():
self.grad += n * self.data ** (n - 1) * out.grad
out.back = back
return out
def tanh(self):
t = math.tanh(self.data)
out = Value(t, (self,))
def back():
self.grad += (1 - t * t) * out.grad
out.back = back
return out
def exp(self):
e = math.exp(self.data)
out = Value(e, (self,))
def back():
self.grad += e * out.grad
out.back = back
return out
__radd__ = __add__
__rmul__ = __mul__
def __neg__(self): return self * -1
def __sub__(self, other): return self + (-other)
def __rsub__(self, other): return other + (-self)
def __truediv__(self, other):
return self * (other ** -1 if isinstance(other, Value) else 1 / other)
def __rtruediv__(self, other): return other * self ** -1
def backward(self):
order, seen, stack = [], set(), [(self, False)]
while stack: # iterative depth-first search
v, done = stack.pop()
if done:
order.append(v)
elif v not in seen:
seen.add(v)
stack.append((v, True))
stack.extend((p, False) for p in v.parents if p not in seen)
self.grad = 1.0
for v in reversed(order):
v.back()
class Neuron:
def __init__(self, n_in, rng, act=True):
self.w = [Value(rng.uniform(-1, 1)) for _ in range(n_in)]
self.b = Value(0.0)
self.act = act
def __call__(self, x):
z = sum((wi * xi for wi, xi in zip(self.w, x)), self.b)
return z.tanh() if self.act else z
def parameters(self):
return self.w + [self.b]
class Layer:
def __init__(self, n_in, n_out, rng):
self.neurons = [Neuron(n_in, rng) for _ in range(n_out)]
def __call__(self, x):
return [n(x) for n in self.neurons]
def parameters(self):
return [p for n in self.neurons for p in n.parameters()]
class MLP:
def __init__(self, sizes, rng):
self.layers = [Layer(a, b, rng) for a, b in zip(sizes, sizes[1:])]
def __call__(self, x):
for layer in self.layers:
x = layer(x)
return x[0] if len(x) == 1 else x
def parameters(self):
return [p for layer in self.layers for p in layer.parameters()]
rng = random.Random(7)
X = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(16)]
Y = [1.0 if 2 * x1 - x2 > 0.3 else -1.0 for x1, x2 in X]
neuron = Neuron(2, rng)
lr = 0.2
for epoch in range(1, 61):
loss = sum(((neuron(x) - y) ** 2 for x, y in zip(X, Y)), Value(0.0)) / len(X)
for p in neuron.parameters():
p.grad = 0.0
loss.backward()
for p in neuron.parameters():
p.data -= lr * p.grad
if epoch == 1 or epoch % 10 == 0:
print(f"epoch {epoch:2d}: loss {loss.data:.4f}")
correct = sum((neuron(x).data > 0) == (y > 0) for x, y in zip(X, Y))
w1, w2, b = (p.data for p in neuron.parameters())
print(f"accuracy {correct}/{len(X)} w = ({w1:.3f}, {w2:.3f}) b = {b:.3f}")epoch 1: loss 0.9054
epoch 10: loss 0.3143
epoch 20: loss 0.2244
epoch 30: loss 0.1869
epoch 40: loss 0.1647
epoch 50: loss 0.1493
epoch 60: loss 0.1377
accuracy 16/16 w = (2.184, -0.963) b = -0.141
The loss falls steadily and every point ends up on the right side. The learned weights point almost exactly along , the direction of the true rule. The bias is negative as the rule's threshold requires, but smaller than : with only 16 points, any boundary in the gap between the two classes classifies them all correctly, so the data pins the direction more tightly than the offset.
Step 5: Train a two-layer net on XOR
XOR is the classic problem one neuron cannot solve: the points and are labelled −1, the points and are labelled +1, and no straight line separates them. A hidden layer of 4 tanh neurons bends the boundary.
import math
import random
class Value:
def __init__(self, data, parents=()):
self.data, self.grad, self.parents = float(data), 0.0, parents
self.back = lambda: None
def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other))
def back():
self.grad += out.grad
other.grad += out.grad
out.back = back
return out
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other))
def back():
self.grad += other.data * out.grad
other.grad += self.data * out.grad
out.back = back
return out
def __pow__(self, n): # n is a plain number
out = Value(self.data ** n, (self,))
def back():
self.grad += n * self.data ** (n - 1) * out.grad
out.back = back
return out
def tanh(self):
t = math.tanh(self.data)
out = Value(t, (self,))
def back():
self.grad += (1 - t * t) * out.grad
out.back = back
return out
def exp(self):
e = math.exp(self.data)
out = Value(e, (self,))
def back():
self.grad += e * out.grad
out.back = back
return out
__radd__ = __add__
__rmul__ = __mul__
def __neg__(self): return self * -1
def __sub__(self, other): return self + (-other)
def __rsub__(self, other): return other + (-self)
def __truediv__(self, other):
return self * (other ** -1 if isinstance(other, Value) else 1 / other)
def __rtruediv__(self, other): return other * self ** -1
def backward(self):
order, seen, stack = [], set(), [(self, False)]
while stack: # iterative depth-first search
v, done = stack.pop()
if done:
order.append(v)
elif v not in seen:
seen.add(v)
stack.append((v, True))
stack.extend((p, False) for p in v.parents if p not in seen)
self.grad = 1.0
for v in reversed(order):
v.back()
class Neuron:
def __init__(self, n_in, rng, act=True):
self.w = [Value(rng.uniform(-1, 1)) for _ in range(n_in)]
self.b = Value(0.0)
self.act = act
def __call__(self, x):
z = sum((wi * xi for wi, xi in zip(self.w, x)), self.b)
return z.tanh() if self.act else z
def parameters(self):
return self.w + [self.b]
class Layer:
def __init__(self, n_in, n_out, rng):
self.neurons = [Neuron(n_in, rng) for _ in range(n_out)]
def __call__(self, x):
return [n(x) for n in self.neurons]
def parameters(self):
return [p for n in self.neurons for p in n.parameters()]
class MLP:
def __init__(self, sizes, rng):
self.layers = [Layer(a, b, rng) for a, b in zip(sizes, sizes[1:])]
def __call__(self, x):
for layer in self.layers:
x = layer(x)
return x[0] if len(x) == 1 else x
def parameters(self):
return [p for layer in self.layers for p in layer.parameters()]
rng = random.Random(1)
net = MLP([2, 4, 1], rng)
X = [(1, 1), (-1, -1), (1, -1), (-1, 1)]
Y = [-1.0, -1.0, 1.0, 1.0]
lr = 0.2
for epoch in range(1, 101):
loss = sum(((net(x) - y) ** 2 for x, y in zip(X, Y)), Value(0.0)) / len(X)
for p in net.parameters():
p.grad = 0.0
loss.backward()
for p in net.parameters():
p.data -= lr * p.grad
if epoch == 1 or epoch % 20 == 0:
print(f"epoch {epoch:3d}: loss {loss.data:.5f}")
for x, y in zip(X, Y):
print(f"{x} -> {net(x).data: .3f} (target {y:+.0f})")epoch 1: loss 1.01952
epoch 20: loss 0.13344
epoch 40: loss 0.04578
epoch 60: loss 0.02555
epoch 80: loss 0.01724
epoch 100: loss 0.01283
(1, 1) -> -0.901 (target -1)
(-1, -1) -> -0.895 (target -1)
(1, -1) -> 0.878 (target +1)
(-1, 1) -> 0.877 (target +1)
The loss falls from about 1 to near 0.01, and all four predictions have the right sign and are close to . You have trained a neural network with an engine you wrote yourself: the same loop, scaled up to tensors and billions of parameters, trains every modern model (neural networks, how LLMs are trained).
Tip: Try
random.Random(3)in Step 5: training starts on a plateau where the loss barely moves for 60 epochs before it drops. Plateaus and the sensitivity to initialisation are real problems in deep learning, and the reason for careful weight initialisation and optimisers like Adam.
Ideas to extend it
- Add
relu(local derivative 1 if else 0) andlog, then train with a cross-entropy loss. - Add momentum: keep a velocity per parameter, , . Compare how fast the XOR loss falls.
- Use mini-batches: each step uses a random subset of the data (stochastic gradient descent).
- Count graph nodes per epoch and see why frameworks work on arrays instead of single numbers.
Test yourself
Why must each parameter's grad be reset to 0 before every backward pass?
- To save memory
- Because
backuses+=, so gradients from the previous epoch would be added to the new ones - Because tanh needs it
- It is not necessary
In Step 1, why is the sum of two contributions?
- Because is used in two places in the expression
- Because is negative
- Because of floating-point rounding
- Because is linear
Why can't a single neuron learn XOR?
- Its learning rate is too low
- tanh is not differentiable
- Its decision boundary is a straight line, and XOR's classes are not linearly separable
- XOR has too many points