Micro autograd I: a scalar differentiation engine from scratch
Build a scalar autograd engine line by line in the style of micrograd, with a Value class that records the forward graph, topological backward propagation and gradient accumulation, then a small library of neurons, layers and MLPs to train a real classifier.
After this lesson you can
- Implement a Value class with operator overloading that builds the computational graph during the forward pass.
- Implement backward in topological order and explain why gradients accumulate with += and must be cleared between steps.
- Build Neuron, Layer and MLP abstractions with a parameters() method and train them with SGD.
- Verify the engine against finite differences and SymPy on random expressions.
- Measure the cost of the scalar approach and explain why it motivates tensor autograd.
Before you start
A sum with two paths
Write . If , the value is , but knowing it is not enough to train: we need to know how it changes when changes. The chain rule gives . The first term comes from the two uses of in the product and the second from the sum. An engine that replaces the gradient as each contribution arrives loses paths; a correct one accumulates them.
In the previous lesson you traversed a graph by hand. Now you will build a scalar autograd engine: every operation creates an object storing its value, parents and a local rule. The forward pass builds the graph; the backward pass traverses it in an order ensuring all contributions reach a node before propagating it. This is reverse-mode automatic differentiation, applied here to scalar numbers.
Try a*a+a with a=2 and follow the two product edges to the same node. The viewer uses its own restricted parser: it accepts the operations and functions listed there, and does not execute arbitrary Python code. The numbered boxes are in a topological order; this is not necessarily the only possible one.
The Value contract
A Value contains data, the scalar computed during forward; grad, the accumulated adjoint; _prev, the parents from which it was built; and _backward, a function that propagates the result’s adjoint to them. For a sum and a product,
The bar represents the derivative of the chosen output with respect to the node. The operation += is essential even when both parents are the same object. In the product a*a the two contributions are different uses of the same node and both must be added. The final value at a leaf depends on every path reaching it.
Order matters. In topological order each parent appears before the operation that uses it; reversing the order means all children consuming a node propagate before that node executes its own rule. The traversal below uses an explicit stack, so a long chain does not depend on Python’s recursion depth. Graph and stack memory still grow with the number of nodes.
To justify the recursion, call the operations that consume . If their adjoints are already known, the chain rule sums their paths:
The sum counts uses, not just distinct objects. The graph is acyclic because each new operation points to operands that already exist. Reverse order ensures all those are complete when visiting . Start with for the scalar output ; no full Jacobian is formed. For multiple outputs, you would need to specify which scalar combination or seed vector to differentiate.
The implementation below follows a deliberate convention: each backward() clears gradients of nodes with parents, initializes the output adjoint to one and accumulates at the leaves. This lets you sum gradients from several calls, but you must clear the parameters with zero_grad() before a new independent step. Constants are also graph leaves, although they are not returned as trainable parameters. If the output is a leaf, its own seed is accumulated.
Build the engine
The first cell is the complete engine. Its operations create a new node; reflected versions allow, for example, 2 * x. Subtraction and division are expressed using the primitives already defined. Each closure uses the forward value: do not modify data between forward and its backward pass. Parameter updates come after backward, and the next step builds a new graph.
In this design the parent tuple retains operands even if they are the same object, and seen only prevents repeated visits. The stack’s done marker distinguishes discovering a node from adding it to the order after its parents. Reversing that order gives correct propagation for branches and for multiple paths of different lengths. Objects are identified by identity: two leaves containing the same number are not therefore the same parameter.
import math
import numpy as np
class Value:
def __init__(self, data, children=(), op=''):
self.data = float(data)
self.grad = 0.0
self._prev = tuple(children)
self.op = op
self._backward = lambda: None
@staticmethod
def wrap(x):
return x if isinstance(x, Value) else Value(x)
def __add__(self, other):
other = Value.wrap(other)
out = Value(self.data + other.data, (self, other), '+')
def backward():
self.grad += out.grad
other.grad += out.grad
out._backward = backward
return out
__radd__ = __add__
def __mul__(self, other):
other = Value.wrap(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
__rmul__ = __mul__
def __neg__(self):
return self * -1
def __sub__(self, other):
return self + (-Value.wrap(other))
def __rsub__(self, other):
return Value.wrap(other) - self
def __truediv__(self, other):
return self * Value.wrap(other)**-1
def __rtruediv__(self, other):
return Value.wrap(other) / self
def __pow__(self, power):
if not isinstance(power, (int, float)):
raise TypeError('el exponente debe ser constante')
out = Value(self.data**power, (self,), f'**{power}')
def backward():
local = 0.0 if power == 0 else power*self.data**(power-1)
self.grad += local*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*t)*out.grad
out._backward = backward
return out
def relu(self):
out = Value(max(0., self.data), (self,), 'relu')
def backward():
self.grad += (self.data > 0)*out.grad
out._backward = backward
return out
def exp(self):
t = math.exp(self.data)
out = Value(t, (self,), 'exp')
def backward():
self.grad += t*out.grad
out._backward = backward
return out
def log(self):
if self.data <= 0:
raise ValueError('log requiere una entrada positiva')
out = Value(math.log(self.data), (self,), 'log')
def backward():
self.grad += out.grad/self.data
out._backward = backward
return out
def backward(self):
topo, seen = [], set()
stack = [(self, False)]
while stack:
node, done = stack.pop()
if done:
topo.append(node)
elif node not in seen:
seen.add(node)
stack.append((node, True))
stack.extend((parent, False)
for parent in reversed(node._prev))
for node in topo:
if node._prev:
node.grad = 0.0
self.grad += 1.0
for node in reversed(topo):
node._backward()
return len(topo)First check a shared graph and a deep chain. The output returns the number of nodes visited so you can inspect the cost. A second backward pass over the same graph adds another copy of the gradient at the leaf; clearing only the parameter restores the result of one pass.
a = Value(2)
q = a*a + a
print('valor, nodos', q.data, q.backward())
print('gradiente tras primera pasada', a.grad)
q.backward()
print('gradiente acumulado tras segunda pasada', a.grad)
a.grad = 0.0
q.backward()
print('tras limpiar la hoja', a.grad)
x = Value(1)
chain = x
for _ in range(1200):
chain = chain + 1
print('cadena: nodos, gradiente de entrada', chain.backward(), x.grad)Powers and logarithms follow the same pattern. If with constant real exponent and the real derivative exists, . If , with , . For tanh the previously computed value can be reused: . In exp the output is also the local derivative.
The engine does not store an immutable copy of all operands. The next experiment shows the risk: forward computed , but the product closure reads the altered value. The derivative at the original point is ; the result printed by backward after mutation does not correspond to that forward pass.
mutation_x = Value(3)
mutation_y = mutation_x * mutation_x
mutation_x.data = 10
mutation_y.backward()
print('valor del forward, gradiente después de mutar', mutation_y.data, mutation_x.grad)A production engine must retain what is needed and detect incompatible changes. For example, PyTorch stores tensors needed for backward and checks their version counters for detectable in-place modifications; this does not guarantee detection of mutations outside that mechanism. See Autograd mechanics, in-place correctness checks. Our engine lacks that protection: the safe rule here is to update only after propagation and build a new graph.
The size of _prev counts edges, not just distinct parents: a*a stores two references to a. The set seen prevents visiting the node twice during topological traversal; it does not remove the two contributions in _backward. Confusing these two things is a common source of errors.
A check that can fail
A gradient check compares the engine with two independent references. The central difference approximates the derivative with a small step, but combines truncation and rounding error. SymPy differentiates the expression symbolically; it does not replace testing the domains and branches of every operation either.
Here is evaluated at reproducible points. The graph is rebuilt for every evaluation and there is no ReLU at the check point. Compare absolute errors and change the seed or step; one case does not prove the entire engine correct.
import sympy as sp
sx, sy = sp.symbols('sx sy', real=True)
sym = sp.tanh(sx*sy) + sp.log(1+sx*sx) + sp.exp(sy/5)
symbolic = sp.lambdify((sx, sy), [sp.diff(sym, sx), sp.diff(sym, sy)], 'numpy')
def plain(x, y):
return np.tanh(x*y) + np.log1p(x*x) + np.exp(0.2*y)
def computed(x, y):
vx, vy = Value(x), Value(y)
out = (vx*vy).tanh() + (1+vx*vx).log() + (0.2*vy).exp()
out.backward()
return np.array([vx.grad, vy.grad])
rng = np.random.default_rng(12)
max_fd, max_symbolic = 0.0, 0.0
h = 1e-5
for x, y in rng.uniform(-1, 1, size=(8, 2)):
actual = computed(x, y)
finite = np.array([(plain(x+h, y)-plain(x-h, y))/(2*h),
(plain(x, y+h)-plain(x, y-h))/(2*h)])
expected = np.asarray(symbolic(x, y), dtype=float)
max_fd = max(max_fd, np.max(np.abs(actual-finite)))
max_symbolic = max(max_symbolic, np.max(np.abs(actual-expected)))
print('máximo error absoluto: diferencias finitas', max_fd)
print('máximo error absoluto: SymPy', max_symbolic)Besides formulas, test boundary conditions: sums and products with shared operands, zero powers where defined, positive inputs for logarithms, division and reflected operations. A central difference on a nondifferentiable function can produce a number that disagrees with the autograd convention without indicating a bug.
Changing input values does not change the preceding structure. The next battery also generates different structures: at each level it chooses a sum, product, power, tanh, exp or a logarithm whose argument is constructed positive. Each choice simultaneously creates the symbolic expression and the scalar graph; both derivatives are tested at a new point. Depth and input range remain small to avoid overflow and make the experiment reproducible.
def random_expression(depth, generator, vx, vy):
if depth == 0:
return (vx, sx) if generator.integers(2) == 0 else (vy, sy)
op = int(generator.integers(6))
left, ls = random_expression(depth-1, generator, vx, vy)
if op < 2:
right, rs = random_expression(depth-1, generator, vx, vy)
return (left+right, ls+rs) if op == 0 else (left*right, ls*rs)
if op == 2:
return left.tanh(), sp.tanh(ls)
if op == 3:
return left.exp(), sp.exp(ls)
if op == 4:
return (1+left*left).log(), sp.log(1+ls*ls)
return left**2, ls**2
generator = np.random.default_rng(44)
worst_sym, worst_fd = 0.0, 0.0
for _ in range(8):
px, py = generator.uniform(-0.5, 0.5, 2)
vx, vy = Value(px), Value(py)
scalar, expression = random_expression(3, generator, vx, vy)
scalar.backward()
grad = np.array([vx.grad, vy.grad])
exact = np.array([float(sp.diff(expression, v).subs({sx: px, sy: py}))
for v in (sx, sy)])
fn = sp.lambdify((sx, sy), expression, 'numpy')
finite = np.array([(fn(px+h, py)-fn(px-h, py))/(2*h),
(fn(px, py+h)-fn(px, py-h))/(2*h)])
worst_sym = max(worst_sym, np.max(np.abs(grad-exact)))
worst_fd = max(worst_fd, np.max(np.abs(grad-finite)))
print('ocho estructuras: errores máximos SymPy y diferencias finitas',
worst_sym, worst_fd)From scalar to network
The module parameter contract separates trainable objects from constants appearing when evaluating the network. A neuron stores its weights and bias; a layer gathers neurons and an MLP chains layers. parameters() returns trainable leaves and zero_grad() clears exactly those leaves. Inputs, intermediate results and constants are not included in SGD.
In this implementation each hidden neuron applies tanh and the output is linear: it returns a logit. The list sizes includes input and output. Parameters are initialized with a seeded NumPy generator; the example is not intended as a universal initialization recipe.
class Module:
def parameters(self):
return []
def zero_grad(self):
for p in self.parameters():
p.grad = 0.0
class Neuron(Module):
def __init__(self, nin, generator, nonlinear=True):
self.w = [Value(x) for x in generator.normal(0, 1/math.sqrt(nin), nin)]
self.b = Value(0)
self.nonlinear = nonlinear
def __call__(self, x):
if len(x) != len(self.w):
raise ValueError('la entrada debe coincidir con la anchura de la neurona')
result = self.b
for weight, value in zip(self.w, x):
result = result + weight*value
return result.tanh() if self.nonlinear else result
def parameters(self):
return self.w + [self.b]
class Layer(Module):
def __init__(self, nin, nout, generator, nonlinear=True):
self.neurons = [Neuron(nin, generator, nonlinear) for _ in range(nout)]
def __call__(self, x):
return [neuron(x) for neuron in self.neurons]
def parameters(self):
return [p for neuron in self.neurons for p in neuron.parameters()]
class MLP(Module):
def __init__(self, sizes, seed=3):
generator = np.random.default_rng(seed)
self.layers = [Layer(a, b, generator, i < len(sizes)-2)
for i, (a, b) in enumerate(zip(sizes[:-1], sizes[1:]))]
def __call__(self, x):
h = [Value.wrap(v) for v in x]
for layer in self.layers:
h = layer(h)
return h
def parameters(self):
return [p for layer in self.layers for p in layer.parameters()]
print('Las capas reciben exactamente la anchura indicada por su construcción.')The count depends on the particular implementation. Here every product and sum in the loop creates a node; every weight, bias and input is a leaf. An implementation that fuses operations or represents entire tensors builds a different graph, even if it computes the same function.
The interface saves the optimizer from needing to know the architecture: MLP.parameters() concatenates its layers’ parameters, and each layer concatenates those of its neurons. This also allows a neuron or layer to be tested separately. In this version the list contains references to the original objects, not copies of their numbers; updating a reference changes the parameter used by the next forward pass. The width check prevents zip from silently discarding components of an incorrectly sized input.
Train a real classifier
Generate two noisy moons, split training and test before optimizing, and convert labels to . The --- network emits a logit . For an example we use logistic loss and add only on the weights. The batch is averaged before adding regularization. The direct logistic term suffices for this run, but for extreme logits it should be replaced by a stable softplus implementation.
The interactive and lab share samples and the split, but are not the same run. The interactive uses a TypeScript implementation with hinge loss, initial width 8, uniform initialization with seed 31 and consecutive batches of eight; the lab below uses logistic loss, width 12 and random batches. Their curves and figures need not match. The interactive continuously displays test accuracy for exploration: if you change hyperparameters while looking at that number, you use it for selection and it ceases to be an independent test. To choose configurations, use validation and reserve another test set untouched until the end.
The following cells share browser state. Run setup and then the twelve blocks in order: each adds 50 steps until reaching 600. Do not run a block twice if you want to reproduce the experiment exactly. At each step a new graph is created, parameters are cleared, loss is propagated and only then are weights modified.
Regularization is not computed on the bias: it penalizes weight matrices and its gradient is added to the data gradient before the update. The batch generator selects only training indices and uses a different seed from the network and the split. The loss printed in each block belongs to the last batch, not the entire dataset, so it may fluctuate even when overall accuracy improves.
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
X_moons, labels_moons = make_moons(n_samples=100, noise=0.08, random_state=7)
train_idx, test_idx = train_test_split(
np.arange(len(labels_moons)), test_size=0.2,
stratify=labels_moons, random_state=42
)
y_moons = labels_moons*2 - 1
net = MLP([2, 12, 12, 1], seed=3)
batch_rng = np.random.default_rng(9)
weights = [w for layer in net.layers for neuron in layer.neurons for w in neuron.w]
steps_done = 0
print('entrenamiento, prueba, parámetros', len(train_idx), len(test_idx), len(net.parameters()))
def train_block(steps):
global steps_done
for _ in range(steps):
batch = batch_rng.choice(train_idx, 12, replace=False)
net.zero_grad()
losses = [(1 + (-float(y_moons[i])*net(X_moons[i])[0]).exp()).log()
for i in batch]
loss = sum(losses)/len(batch) + 0.0001*sum(w*w for w in weights)
nodes = loss.backward()
for p in net.parameters():
p.data -= 0.2*p.grad
steps_done += 1
print('pasos, pérdida del último lote, nodos del último grafo',
steps_done, round(loss.data, 5), nodes)train_block(50)train_block(50)train_block(50)train_block(50)train_block(50)train_block(50)train_block(50)train_block(50)train_block(50)train_block(50)train_block(50)train_block(50)Evaluate once on the held-out split. You have not used those labels to choose each update. Accuracy on 20 examples changes in increments of five percentage points and does not establish performance on other samples.
def accuracy(indices):
return np.mean([(net(X_moons[i])[0].data > 0) == bool(labels_moons[i])
for i in indices])
print('pasos, precisión entrenamiento, precisión prueba',
steps_done, accuracy(train_idx), accuracy(test_idx))The scalar graph helps understand and verify the rules, but creates objects and closures for every number and operation. The network and batch multiply that cost. A tensor library groups operations, reuses kernels and exploits vector hardware; comparing parameter counts alone is insufficient because many intermediate nodes are also constructed here.
The number of nodes is not the number of parameters: there are also inputs, constants, products, sums and activations for each batch example. Our traversal stores those nodes until backward finishes, along with the stack and closures. Both time and memory depend on the expression actually built. Browser measurements use Pyodide, NumPy without BLAS and one thread; they are observations in that shared environment, not a prediction for PyTorch or a GPU.
The micrograd engine presents the same idea of scalar values and accumulation. Our convention for clearing intermediates and the iterative stack should be read in this lesson’s code: they should not automatically be attributed to every version of other engines. The PyTorch autograd tutorial shows how the same principle appears with tensors.
To separate cost from correctness, compare the same batch, initial network and objective with a vectorized backward pass. The following comparison reconstructs matrices from scalar parameters and orders their gradients as parameters(). The NumPy version uses logaddexp for the loss and does not update weights. Compare the loss and all gradients before timing; a fast implementation with an incorrect gradient is not a valid reference.
compare_net = MLP([2, 12, 12, 1], seed=3)
compare_batch = np.random.default_rng(9).choice(train_idx, 12, replace=False)
xb = X_moons[compare_batch]
yb = y_moons[compare_batch]
reg = 0.0001
def scalar_pass():
compare_net.zero_grad()
scores = [compare_net(row)[0] for row in xb]
data_loss = sum((1 + (-float(y)*score).exp()).log()
for y, score in zip(yb, scores))/len(xb)
ws = [w for layer in compare_net.layers for neuron in layer.neurons
for w in neuron.w]
objective = data_loss + reg*sum(w*w for w in ws)
nodes = objective.backward()
return objective.data, np.array([p.grad for p in compare_net.parameters()]), nodes
def numpy_pass():
matrices = [np.array([[p.data for p in neuron.w]
for neuron in layer.neurons]).T
for layer in compare_net.layers]
biases = [np.array([neuron.b.data for neuron in layer.neurons])
for layer in compare_net.layers]
activations = [xb]
for i, (W, bias) in enumerate(zip(matrices, biases)):
z = activations[-1] @ W + bias
activations.append(np.tanh(z) if i < len(matrices)-1 else z)
margin = yb*activations[-1][:, 0]
objective = np.logaddexp(0, -margin).mean() + reg*sum(np.sum(W*W) for W in matrices)
delta = (-yb/(1+np.exp(margin))/len(xb))[:, None]
grads = [None]*len(matrices)
for i in range(len(matrices)-1, -1, -1):
dW = activations[i].T @ delta + 2*reg*matrices[i]
db = delta.sum(axis=0)
grads[i] = (dW, db)
if i > 0:
delta = (delta @ matrices[i].T)*(1-activations[i]**2)
ordered = []
for dW, db in grads:
for j in range(dW.shape[1]):
ordered.extend([*dW[:, j], db[j]])
return objective, np.array(ordered)
scalar_loss, scalar_grad, node_count = scalar_pass()
numpy_loss, numpy_grad = numpy_pass()
print('lote, parámetros, nodos', len(xb), len(scalar_grad), node_count)
print('pérdidas escalar y NumPy', scalar_loss, numpy_loss)
print('máxima diferencia absoluta entre gradientes', np.max(np.abs(scalar_grad-numpy_grad)))from time import perf_counter
for name, fn, repeat in [('escalar', scalar_pass, 4), ('NumPy', numpy_pass, 10)]:
start = perf_counter()
for _ in range(repeat):
fn()
print(name, 'segundos por pasada', (perf_counter()-start)/repeat)Both measurements include building their representation from parameters and compute a gradient, but use different numbers of repetitions. Repeat and observe the trend; do not interpret one number as a fixed time: the machine is shared, and the browser and data shape affect the result.
Exercises
def value_pow(x, p):
pass
def value_log(x):
passdef backward(root):
passdef scalar_cross_entropy(logits, target):
passA reverse engine stores the forward graph and local rules; it traverses nodes in reverse topological order and sums all contributions. zero_grad() separates independent optimization steps. Neurons, layers and the training loop do not need a new differentiation rule: they compose those primitives. The cost of many scalar objects explains why practical networks use tensor operations.