machine learning13 min readAI-assisted
myriograd: From Scalars to Tensors
Karpathy's micrograd, rebuilt on tensors by hand with AI as a teacher. What changes in backpropagation when numbers get a shape?
Contents
Andrej Karpathy’s micrograd is a wonderful educational resource. In about 100 lines of Python it implements backpropagation, the algorithm that trains neural networks, and in the video that comes with it Karpathy builds it from scratch, one step at a time. After watching it, calling loss.backward() in PyTorch stops being magic.
Well, almost. micrograd makes one big simplification, and its README says so openly: “The DAG only operates over scalar values”. Every number in the network is its own little Python object. PyTorch works with tensors instead: whole arrays travel through the graph, they are broadcast against each other, summed and matrix-multiplied, and somehow every gradient comes back with the right shape. That “somehow” was the part I did not really understand.
I only understand something if I build it1. So I built myriograd: micrograd, with every scalar Value replaced by a Tensor backed by a numpy array. This post goes through what had to change. It turned out to be surprisingly little, and the little that changes is the interesting part.
I assume you know micrograd, or have watched the video, and that you are comfortable with numpy and a bit of calculus.
AI writes the tests, I write the code
An AI agent could have written the whole project in a couple of minutes, and I would have learned nothing. So I used AI in a different role: as a teacher.
The AI wrote a test file for each step of the implementation, and I implemented the steps one at a time, until the tests passed:
- the
Tensorcontainer; - the forward pass of the element-wise operations;
backward();- broadcasting;
sumandmean;- matrix multiplication;
- the
nnmodule; - training a small network end to end.
For each step I worked out the derivatives by hand before turning them into code. Along the way the AI explained the concepts I was missing and reviewed what I wrote, but the implementation and the algebra are mine.
The tests have one property that I really like: every gradient is checked against PyTorch. A small helper takes a function such as lambda a, b: a @ b, runs it on myriograd tensors and on PyTorch tensors holding the same numbers, calls backward() on both, and compares the outputs and the gradients of every input2. Most of the 111 tests are comparisons of this kind, and two of them are micrograd’s own tests, ported to tensors. So when the tests pass, myriograd computes the same gradients as PyTorch on everything they cover.
The result is small: engine.py is 150 lines (micrograd’s is 94) and nn.py is 53 (micrograd’s is 60).
What stays the same
If you know micrograd, you already know most of myriograd. Every operation creates a new node, which remembers its inputs and a small _backward function that passes the gradient of the output on to the inputs. backward() sorts the graph topologically and calls those functions in reverse order. Gradients are accumulated with +=, because a value that is used twice receives a gradient from each use. Negation, subtraction and division are still built from +, * and **. All of this carries over almost line by line.
The first difference is that gradients have shapes. x.grad holds the derivative of the loss with respect to every element of x, so it is an array with the shape of x.data. For element-wise operations there is not much more to say. In c = a * b, with a and b of the same shape, c[i] depends only on a[i] and b[i], so micrograd’s scalar rule holds position by position. Take ReLU:
def relu(self):
out_data = np.maximum(self.data, 0)
out = Tensor(out_data, (self,), "ReLU")
def _backward():
self.grad += out.grad * (out.data > 0)
out._backward = _backward
return out
micrograd’s line is self.grad += (out.data > 0) * out.grad. It is the same rule, except that there out.data > 0 is a single boolean, and here it is a whole array of them: a mask.
The start of the backward pass changes just as little: micrograd sets the gradient of the final node to 1, and myriograd sets it to an array of ones, np.ones_like(self.data)3.
If it all ended here, this would be a very short post.
Broadcasting: copy forward, sum backward
The element-wise picture breaks on something as innocent as a * 2.
Like micrograd, myriograd wraps the plain number 2 into a node of its own, here a Tensor of shape (). In the forward pass, numpy happily multiplies a (4, 3) array by it. In the backward pass, micrograd’s rule tries to add a (4, 3) gradient into a gradient of shape (), and numpy refuses:
ValueError: non-broadcastable output operand with shape () doesn't match the broadcast shape (4,3)
The forward pass did something that the backward pass has to undo: it took one number and quietly used it in 12 places. This is broadcasting, and tensor code is full of it. The bias that is added to every example of a batch is the classic case.
So what is the right gradient? Take x of shape (4, 3) and b of shape (3,). Then , and each is used in four outputs, one per row. If I nudge a little, all four of them move, and the loss feels all four changes:
A tiny example with numbers: x = [4, 5, 6], b = [10], and a gradient of [1, 2, 3] arriving at the output. If b grows by , all three outputs grow by , so the loss grows by . Therefore b.grad = [6].
The rule is: a copy in the forward pass is a sum in the backward pass. And it is not even a new rule! It is the reason why micrograd uses +=: in a + a the value a is used twice, and its gradient is the sum of the two contributions. Broadcasting is the same reuse, only implicit: numpy makes the copies, so nobody writes them down4.
numpy aligns shapes from the right, and it can stretch a shape in exactly two ways. The function that undoes them, unbroadcast5, therefore has two parts:
- New axes in front, as in
(3,)→(4, 3). To undo it, sum over the first axis until the number of axes is right again. - Axes of size 1 that were stretched, as in
(4, 1)→(4, 3). To undo it, sum over that axis but keep it, with size 1.
def unbroadcast(grad, shape):
"""Sum grad down to shape, undoing numpy broadcasting."""
while grad.ndim > len(shape):
# Removing left-most dimensions.
grad = grad.sum(axis=0, keepdims=False)
for index, value in enumerate(shape):
if value == 1:
grad = grad.sum(axis=index, keepdims=True)
assert grad.shape == shape, f"grad shape {grad.shape} != {shape}"
return grad
With it, the backward functions of + and * are micrograd’s, wrapped in unbroadcast:
# inside __add__
def _backward():
# dC/dA = dC/dB = 1
self.grad += unbroadcast(out.grad, self.shape)
other.grad += unbroadcast(out.grad, other.shape)
# inside __mul__
def _backward():
self.grad += unbroadcast(out.grad * other.data, self.shape)
other.grad += unbroadcast(out.grad * self.data, other.shape)
In __mul__ the order matters: unbroadcast comes last. Each copy of a broadcast value was multiplied by a different number, so each product has to be computed first, and only then can the copies be added up. Summing first would lose track of which copy met which number.
When neither operand was stretched, unbroadcast changes nothing, and we are back to the element-wise case.
Sum and mean: the mirror image
A reduction does the opposite of broadcasting. sum takes many numbers and adds them into one, or into a few when an axis is given. Each input enters its output with weight 1, so in the backward pass each input simply receives the gradient of the output it went into. The gradient is copied back, and copying is exactly what broadcasting does:
def sum(self, axis=None, keepdims=False):
out_data = self.data.sum(axis=axis, keepdims=keepdims)
out = Tensor(out_data, (self,), f"sum(axis={axis}, keepdims={keepdims})")
def _backward():
out_grad = out.grad
if not keepdims and axis is not None:
out_grad = np.expand_dims(out.grad, axis)
self.grad += np.broadcast_to(out_grad, self.shape)
out._backward = _backward
return out
The symmetry is complete: broadcasting copies forward and sums backward, while sum sums forward and copies backward.
The expand_dims line is there because of a trap. With keepdims=False the summed axis disappears from the output, and it has to be put back, with size 1 and in the right position, before the gradient is broadcast. Otherwise numpy aligns from the right, and the gradient may land in the wrong place. Take x.sum(axis=1). If x has shape (2, 3), the gradient has shape (2,) and does not broadcast to (2, 3): an error, which is the good case. If x has shape (3, 3), it broadcasts without complaining, and the gradient of each row ends up along a column. No error, only wrong numbers.
mean needs no backward function of its own, because it is a sum divided by a count:
def mean(self, axis=None, keepdims=False):
total = self.sum(axis, keepdims)
count = self.data.size / total.data.size
return total / count
The count is the number of inputs that went into each output, which is the size of the input divided by the size of the output. That one line covers every choice of axis, and the gradient comes for free, because division is built from * and ** as in micrograd.
Matmul
Matrix multiplication is the only operation that needs a real derivation. Take , with of shape and of shape :
Call the gradient that arrives at the output, which is out.grad in the code. The entry appears in for every , each time multiplied by , and its gradient collects all these uses. The same goes for , which appears in for every :
In code, that is two lines:
def __matmul__(self, other):
assert self.data.ndim == 2 and other.data.ndim == 2, "Only 2D matmul supported"
out = Tensor(self.data @ other.data, (self, other), "@")
def _backward():
self.grad += out.grad @ other.data.T
other.grad += self.data.T @ out.grad
out._backward = _backward
return out
There is a nice way to rebuild these formulas without any index, from the shapes alone. The gradient of must have the shape of , which is . The ingredients are , of shape , and , of shape . When , and are all different, the only way to multiply the two into an matrix is . The same game gives for . Notice also that each matrix keeps its side: was on the left in , and is on the left in .
There is no unbroadcast here, because a 2-D matmul never broadcasts. I limited @ to two dimensions on purpose: a layer of an MLP needs nothing more than (batch, nin) @ (nin, nout)6.
Neuron and Layer become Linear
This is where tensors pay off. In micrograd a layer is a list of neurons, and each neuron is a list of scalar weights that are multiplied by the inputs one by one:
# micrograd
class Neuron(Module):
def __init__(self, nin, nonlin=True):
self.w = [Value(random.uniform(-1,1)) for _ in range(nin)]
self.b = Value(0)
self.nonlin = nonlin
def __call__(self, x):
act = sum((wi*xi for wi,xi in zip(self.w, x)), self.b)
return act.relu() if self.nonlin else act
In myriograd the weights of a whole layer are one matrix W, of shape (nin, nout), and the biases are one vector b, of shape (nout,). Neuron and Layer collapse into a single class:
# myriograd
class Linear(Module):
def __init__(self, nin, nout, nonlin=True):
self.W = Tensor(np.random.uniform(-1, 1, size=(nin, nout)))
self.b = Tensor(np.zeros(nout))
self.nonlin = nonlin
def __call__(self, x):
lin = x @ self.W + self.b
return lin.relu() if self.nonlin else lin
(Both excerpts leave out parameters() and __repr__.)
The line x @ self.W + self.b brings matmul and broadcasting together. x is a whole batch of examples, of shape (batch, nin), and the matmul turns it into (batch, nout). Adding b broadcasts it across the batch, so in the backward pass unbroadcast sums the gradient of b over all the examples. That is exactly the gradient we want, and nobody had to write it7.
MLP is micrograd’s, with Layer replaced by Linear.
The demo
micrograd ends with a demo, in which a small network learns to separate two interleaving half-moons of points. I reproduced it with the same setup: the two-moons data, the same network of 337 parameters, the same loss and the same learning-rate schedule8. What changes is how the data goes through the network:
| micrograd | myriograd | |
|---|---|---|
| Forward pass | one example at a time, each coordinate wrapped in a Value | all 100 examples at once |
| Loss | a list comprehension over the examples | one expression over the whole batch |
| Mini-batches | an optional batch_size, with random sampling | removed: the whole dataset is the batch |
| Decision boundary | the grid points go through the model one at a time | the whole grid in one more forward pass |
The whole loss function is:
def loss():
scores = model(Tensor(X)) # (100, 1)
data_loss = (1 - scores * y).relu().mean()
reg_loss = 1e-4 * sum((p * p).sum() for p in model.parameters())
accuracy = np.mean((scores.data > 0) == (y > 0))
return data_loss + reg_loss, accuracy
Training starts from a loss of 1.58 and an accuracy of 48%. After 10 steps the accuracy is 91%. At step 40 it is 100%, where it stays until the end, with a final loss of about 0.012.
micrograd’s notebook draws its version of this picture on a grid with a step of 0.25, one point at a time. Here the grid is just one more batch, model(Tensor(grid)), so the figure above could afford a step of 0.01. I did not benchmark anything, though: the point of the exercise was never speed.
What bit me
Some of the bugs I hit along the way are worth telling, because each one comes with a small lesson.
- Counting axes while removing them. My first
unbroadcastsummed axis 0, then axis 1, then axis 2. But once axis 0 is summed away, the others shift to the left, and the next axis to remove is axis 0 again. When a(2, 3, 4, 5)gradient was summed down to(4, 5), theasserton the shape caught it. From(2, 2, 2, 2)down to(2, 2), all the shapes were right and the numbers were wrong, silently. Matching shapes prove little, especially when all the sizes are equal. =instead of+=. While rewriting__mul__for broadcasting, I lost the accumulation. The new tests failed in cryptic ways, but an old one named the problem:test_reuse_mul_accumulates. Run the whole test suite after every change, not only the tests of the current step.if axis:when the axis is 0. In Python0is falsy, so my check skipped the first axis. It did no harm, but only by coincidence: for axis 0, numpy’s right-alignment happens to put the gradient in the right place anyway. The correct check isaxis is not None.- A numpy integer is not a Python integer.
8 ** -1is0.125, butnp.int64(8) ** -1raises “Integers to negative integer powers are not allowed”. Division isself * other**-1, and my firstmeancomputed its count withnp.prod, which returns annp.int64. Now the divisor is wrapped in aTensorfirst, and aTensoralways holds 64-bit floats. - A numpy array on the left. In
y * scores, withya numpy array andscoresaTensor, Python asks numpy first, and numpy does not step aside: it multiplies each element ofyon its own, and returns an array of Python objects. The fix is a single class attribute,__array_ufunc__ = None, which tells numpy to step aside. This one was a suggestion of the AI, and a neat one.
The name
micro- means tiny. myrio- is a rarer spelling of myria-, from the Greek mýrioi, “ten thousand”, as in myriad. It was the prefix for in the original French metric system of 1795, and it was not kept when the SI prefixes were adopted in 19609. From one scalar at a time to myriads of numbers at once.
Where next
myriograd is a toy, like the project it comes from. A few natural next steps, each one a good exercise:
exp,logandtanh, which open the door to softmax and cross-entropy;- a batched
@, for tensors with any number of dimensions; - an initialization scaled by ;
- an optimizer class.
What stays with me is how little had to change. micrograd’s design survives untouched: the graph, the closures, the topological sort, the +=. What tensors add fits in two sentences. When the forward pass copies, the backward pass sums, and when the forward pass sums, the backward pass copies. And when the forward pass multiplies by a matrix, the backward pass multiplies by its transpose.
As for the method, I can only recommend it. A teacher who writes the exercises, checks every answer against PyTorch and is always available turned a vague “I should understand autodiff better” into eight small problems that I could actually solve. The understanding, though, came from solving them myself.
The code is on GitHub: uv run pytest checks the gradients against PyTorch, and demo.ipynb trains the network above.
Footnotes
-
Richard Feynman put it better. “What I cannot create, I do not understand” was written on his blackboard at the time of his death. ↩
-
With numpy’s
assert_allcloseatatol=1e-10(looser in one test), on top of its default relative tolerance of , and with 64-bit floats on both sides. ↩ -
For an output that is not a scalar, this is the same as backpropagating from the sum of its elements. In PyTorch it would be
out.backward(torch.ones_like(out)). ↩ -
A more formal way to say it: broadcasting is a linear map, the backward pass of a linear map is its transpose, and the transpose of “copy” is “sum”. Note that it is always the gradient that gets summed, never the data. ↩
-
PyTorch has the same operation, under the name
Tensor.sum_to_size. ↩ -
The general, batched version needs
swapaxes(-1, -2)instead of.T(which reverses all the axes),unbroadcastover the batch axes, and special cases for 1-D operands. ↩ -
PyTorch’s
nn.Linearstores the weight the other way round, as(nout, nin), and computesx @ W.T. It is the same math. It also draws the initial weights from a range scaled by , which matters for wider and deeper networks. myriograd keeps micrograd’s uniform values between −1 and 1. ↩ -
make_moons(n_samples=100, noise=0.1)with labels −1 and +1,MLP(2, [16, 16, 1]), the SVM max-margin loss plus L2 regularization with a coefficient of , and 100 steps of gradient descent with a learning rate that goes from 1.0 down to about 0.1. ↩