autograd engine

Reverse-mode automatic differentiation from first principles, extended from micrograd into something you can train with.

Read the code on GitHub →
Year
2025
Status
Public on GitHub
Built with
Python, graphviz
engine.py, two methods of Value
    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
            other.grad += self.data * out.grad
        out._backward = _backward
        return out

    def backward(self):
        topo = []
        visited = set()
        def build_topo(v):
            if v not in visited:
                visited.add(v)
                for child in v._prev:
                    build_topo(child)
                topo.append(v)
        build_topo(self)
        self.grad = 1
        for v in reversed(topo):
            v._backward()

Every Value remembers the values it came from and how to pass a gradient back to them. backward sorts the graph topologically and runs those closures in reverse, and that's all backpropagation is.

On top of micrograd it adds sigmoid and tanh, type hints, mini-batches through the MLP, a training loop, L1 and L2 regularisation, dropout, and a draw_dot that labels the whole computation graph.