Autograd From Scratch

October 10, 2026 (2w ago)

Stack: Python, pytest, mypy, ruff, black, GitHub Actions, semantic-release · Repo: Axeloooo/autograd-from-scratch

Problem

This project builds backpropagation in plain Python from one idea: a scalar Value node that records the operation that produced it and a closure that pushes gradients back to its inputs. A small Neuron / Layer / MLP library sits on top and trains on tiny datasets.

The runtime has no dependencies (dependencies = []), and engine, network and graph export total about 260 lines.

Architecture diagram

  nn.py:   Neuron --> Layer --> MLP
                                 |
                  forward pass builds the graph
                                 v
  +----------------------------------------------------+
  | engine.py   Value                                  |
  |   data, grad, label, _prev, _op, _backward         |
  |   add / mul / pow / exp / log / tanh / relu        |
  |   each op = new Value + closure doing  grad += ... |
  +----------------------------------------------------+
        |                                  |
        | backward(): iterative            | trace() / to_dot()
        | topological sort, then           | graph.py
        | reversed _backward calls         v
        v                            Graphviz DOT text
  MLP.parameters()  (.grad filled in)
        |
        v
  p.data -= lr * p.grad      <- update loop lives in the README and tests

Value stores its data, gradient, child nodes, the operation and a backward closure. backward() sorts the graph topologically, seeds the root gradient with 1.0 and runs the closures in reverse. graph.py walks the same graph to emit DOT text. The training loop is deliberately not library code.

Key decisions

Challenges

Results

Links