TExcelTAD
Home › Calculus Essentials › Mini Project: A Tiny Autodiff Engine

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 θ←θ−η ∂L/∂θ\theta \leftarrow \theta - \eta\,\partial L/\partial\theta
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 (∂ output/∂ this value\partial\,\text{output}/\partial\,\text{this value}, 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.

python · try it yourself
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: f=a2b+c⋅af = a^2 b + c \cdot a, so ∂f/∂a=2ab+c=−12+10=−2\partial f/\partial a = 2ab + c = -12 + 10 = -2, ∂f/∂b=a2=4\partial f/\partial b = a^2 = 4 and ∂f/∂c=a=2\partial f/\partial c = a = 2. The value a is used twice (in a⋅ba \cdot b and in e⋅ae \cdot a); its two contributions, −6 (through a⋅ba \cdot b) and 4 (through e⋅ae \cdot a), add up, which is why every back uses +=.

Step 2: The full engine

Now add the remaining pieces:

  • __pow__ (with a plain-number exponent), tanh and exp, each with its local derivative: nxn−1n x^{n-1}, 1−tanh⁡21 - \tanh^2, exe^x.
  • Subtraction, negation and division expressed through the operations we have (a−b=a+(−1)⋅ba - b = a + (-1) \cdot b, a/b=a⋅b−1a / b = a \cdot b^{-1}), so they get gradients for free; __radd__/__rmul__ let us write 2 * x or x + 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 calls back in reverse order.

Then test the engine the way frameworks are tested: compare every gradient with a central finite difference.

python · try it yourself
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 tanh⁡(w1x1+⋯+wnxn+b)\tanh(w_1 x_1 + \cdots + w_n x_n + b), 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 [−1,1][-1, 1], so every run is identical.

python · try it yourself
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 [−1,1]2[-1, 1]^2, labelled +1 if 2x1−x2>0.32x_1 - x_2 > 0.3 and −1 otherwise. A single neuron draws a straight boundary, so it can learn this rule. Each epoch:

  1. compute the mean squared error L=1n∑(y^i−yi)2L = \frac{1}{n} \sum (\hat{y}_i - y_i)^2 over all points (one big graph),
  2. reset every parameter's grad to 0 (gradients accumulate with +=, so stale ones would leak in),
  3. L.backward(),
  4. step each parameter: p←p−η ∂L/∂pp \leftarrow p - \eta\,\partial L/\partial p.
python · try it yourself
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 (2.18,−0.96)(2.18, -0.96) point almost exactly along (2,−1)(2, -1), the direction of the true rule. The bias is negative as the rule's threshold requires, but smaller than 0.3⋅scale0.3 \cdot \text{scale}: 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 (1,1)(1, 1) and (−1,−1)(-1, -1) are labelled −1, the points (1,−1)(1, -1) and (−1,1)(-1, 1) are labelled +1, and no straight line separates them. A hidden layer of 4 tanh neurons bends the boundary.

python · try it yourself
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 ±1\pm 1. 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 x>0x > 0 else 0) and log, then train with a cross-entropy loss.
  • Add momentum: keep a velocity per parameter, v←0.9v−η⋅gradv \leftarrow 0.9v - \eta \cdot \text{grad}, p←p+vp \leftarrow p + v. 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?

  1. To save memory
  2. Because back uses +=, so gradients from the previous epoch would be added to the new ones
  3. Because tanh needs it
  4. It is not necessary

In Step 1, why is ∂f/∂a\partial f/\partial a the sum of two contributions?

  1. Because aa is used in two places in the expression
  2. Because aa is negative
  3. Because of floating-point rounding
  4. Because ff is linear

Why can't a single neuron learn XOR?

  1. Its learning rate is too low
  2. tanh is not differentiable
  3. Its decision boundary is a straight line, and XOR's classes are not linearly separable
  4. XOR has too many points