◆ AI All-in-One

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
↗ Plan a path here

Read first

BackpropagationPython for AI

This leads to

—
The full path from zero — 17 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Supervised Learning
  13. Linear Regression
  14. The Perceptron
  15. Logistic Regression
  16. Neural Networks
  17. Backpropagation
  18. 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.

a = 2 grad −24 b = −3 grad 16 c = 10 grad 8 × e = −6 grad 8 + d = 4 grad 8 x² L = 16 grad 1 × local: ∂e/∂a = b, ∂e/∂b = a local: 1 and 1 (passes through) local: 2d = 8 forward: compute values backward: grad × local L = (a·b + c)²
Fig. 1 The computation graph for L = (a·b + c)², with a = 2, b = −3, c = 10. The forward pass (top numbers) computes values left to right. The backward pass (bottom numbers, red) starts with a gradient of 1 at L and multiplies by each operation's local derivative on the way back.

How it works

A worked example by hand

Take three inputs, a=2a = 2, b=−3b = -3 and c=10c = 10, and compute

d=a⋅b+c=4,L=d2=16d = a \cdot b + c = 4, \qquad L = d^2 = 16

Now go backwards. We want ∂L∂a\frac{\partial L}{\partial a}, ∂L∂b\frac{\partial L}{\partial b} and ∂L∂c\frac{\partial L}{\partial c}: how much LL changes when each input is nudged.

  1. Start at the end: ∂L∂L=1\frac{\partial L}{\partial L} = 1.
  2. L=d2L = d^2, whose local derivative is 2d=82d = 8. So ∂L∂d=8×1=8\frac{\partial L}{\partial d} = 8 \times 1 = 8.
  3. d=e+cd = e + c, where e=a⋅b=−6e = a \cdot b = -6. Addition passes the gradient through unchanged: ∂L∂c=8\frac{\partial L}{\partial c} = 8 and ∂L∂e=8\frac{\partial L}{\partial e} = 8.
  4. e=a⋅be = a \cdot b. The local derivative with respect to aa is bb, and with respect to bb is aa. So ∂L∂a=b×8=−24\frac{\partial L}{\partial a} = b \times 8 = -24 and ∂L∂b=a×8=16\frac{\partial L}{\partial b} = a \times 8 = 16.

Check one by nudging: increase aa from 2 to 2.001. Then d=2.001×(−3)+10=3.997d = 2.001 \times (-3) + 10 = 3.997 and L=15.976L = 15.976, a drop of about 0.024, which is −24×0.001-24 \times 0.001. 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.

  1. Gradients accumulate with +=. If a value is used twice, as in a * a or 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 with optimizer.zero_grad() in PyTorch.
  2. 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 tanh⁡(xw+b)\tanh(x w + b) with x=0.5x = 0.5, w=−1.5w = -1.5, b=2b = 2 gives gradients −0.4206-0.4206, 0.14020.1402 and 0.28040.2804 for xx, ww and bb 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: tanh⁡(w⋅x+b)\tanh(\mathbf{w} \cdot \mathbf{x} + b). 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.

1. Forward pass preds = [model(x) for x in xs] 2. Loss loss = Σ (pred − y)² 3. Zero gradients p.grad = 0 for every parameter 4. Backward pass loss.backward() 5. Update p.data −= η · p.grad repeat until the loss is low
Fig. 2 The training loop that every neural network uses, here with our engine. Each step runs the network forward, measures the loss, clears old gradients, backpropagates new ones and nudges every parameter downhill. PyTorch's loop has exactly the same five parts.

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 [1,−1,−1,1][1, -1, -1, 1]. 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.0 makes 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.grad instead 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 _backward in the wrong order. Without the topological sort, a node may pass on its gradient before receiving all of it.
  • Mutating data inside the graph. Changing p.data is 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 hh (say 10−610^{-6}), recompute the output, and compare (f(x+h)−f(x))/h(f(x+h) - f(x))/h with your gradient. Libraries such as PyTorch provide torch.autograd.gradcheck for exactly this. A gradient bug rarely crashes. It makes training quietly worse.

Where it leads

  • PyTorch is this engine scaled up: values become tensors, _backward closures become optimised kernels, and MLP becomes nn.Module.
  • Add more operations to your engine: relu, exp and log. With exp and log you 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

  1. Add a relu method to Value (output max(0, x), local derivative 1 if x > 0 else 0) and use it instead of tanh in the hidden layers. Does training still work?
  2. Remove the gradient-zeroing loop and run training again. What happens to the loss?
  3. Add exp to Value and check your gradient with finite differences on Value(1.5).exp().

Hint for 3: the derivative of exe^x is exe^x, so in _backward use out.data. The finite-difference estimate is (math.exp(1.5 + 1e-6) - math.exp(1.5)) / 1e-6, about 4.4817.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. With a = 2, b = −3, c = 10, d = a·b + c and L = d², what is ∂L/∂a?

  2. In the Value class, why does _backward use self.grad += ... instead of self.grad = ...?

  3. Why does backward() sort the graph into topological order before calling each _backward?

  4. You delete the line that resets p.grad = 0.0 before each loss.backward(). What happens to training?

  5. What lets you write a * b + c on Value objects and have your own code record the operations?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Tool

micrograd

Andrej Karpathy · Intermediate · Free

A tiny autograd engine in about 100 lines. Reading it is the best way to demystify backprop.

Video

Neural Networks: Zero to Hero

Andrej Karpathy · Intermediate · Free

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.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/programming/autograd-from-scratch.md