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
  1. AI writes the tests, I write the code
  2. What stays the same
  3. Broadcasting: copy forward, sum backward
  4. Sum and mean: the mirror image
  5. Matmul
  6. Neuron and Layer become Linear
  7. The demo
  8. What bit me
  9. The name
  10. Where next

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:

  1. the Tensor container;
  2. the forward pass of the element-wise operations;
  3. backward();
  4. broadcasting;
  5. sum and mean;
  6. matrix multiplication;
  7. the nn module;
  8. 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 outij=xij+bj\text{out}_{ij} = x_{ij} + b_j, and each bjb_j is used in four outputs, one per row. If I nudge bjb_j a little, all four of them move, and the loss feels all four changes:

∂L∂bj=∑i∂L∂outij\frac{\partial L}{\partial b_j} = \sum_i \frac{\partial L}{\partial \text{out}_{ij}}

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 ε\varepsilon, all three outputs grow by ε\varepsilon, so the loss grows by (1+2+3) ε(1 + 2 + 3)\,\varepsilon. 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.

forward: copyb(3,)102030copies(4, 3)102030102030102030102030each b[j] is used 4 timesbackward: sumb.grad(3,)222630out.grad(4, 3)1234567891011122 + 5 + 8 + 11 = 26
Broadcasting in out = x + b, with x of shape (4, 3) and b of shape (3,). Forward, numpy stretches b into four copies, one for each row of x. Backward, the gradients of the four copies are summed into the b they came from. The wiring is the same, with the arrows reversed.

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:

  1. 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.
  2. 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 C=ABC = AB, with AA of shape (n,p)(n, p) and BB of shape (p,m)(p, m):

Cij=∑kAikBkjC_{ij} = \sum_k A_{ik} B_{kj}

Call G=∂L/∂CG = \partial L / \partial C the gradient that arrives at the output, which is out.grad in the code. The entry AikA_{ik} appears in CijC_{ij} for every jj, each time multiplied by BkjB_{kj}, and its gradient collects all these uses. The same goes for BkjB_{kj}, which appears in CijC_{ij} for every ii:

∂L∂Aik=∑jGijBkj=(GB⊤)ik∂L∂Bkj=∑iAikGij=(A⊤G)kj\frac{\partial L}{\partial A_{ik}} = \sum_j G_{ij} B_{kj} = (G B^\top)_{ik} \qquad \frac{\partial L}{\partial B_{kj}} = \sum_i A_{ik} G_{ij} = (A^\top G)_{kj}

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 AA must have the shape of AA, which is (n,p)(n, p). The ingredients are GG, of shape (n,m)(n, m), and BB, of shape (p,m)(p, m). When nn, pp and mm are all different, the only way to multiply the two into an (n,p)(n, p) matrix is GB⊤G B^\top. The same game gives A⊤GA^\top G for BB. Notice also that each matrix keeps its side: AA was on the left in ABAB, and A⊤A^\top is on the left in A⊤GA^\top G.

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:

microgradmyriograd
Forward passone example at a time, each coordinate wrapped in a Valueall 100 examples at once
Lossa list comprehension over the examplesone expression over the whole batch
Mini-batchesan optional batch_size, with random samplingremoved: the whole dataset is the batch
Decision boundarythe grid points go through the model one at a timethe 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.

The trained network on the two moons. Filled and hollow dots are the two classes of the 100 training points, and the shaded region is where the score of the network is positive. To draw it, the network was evaluated on a grid of about 120,000 points, in a single forward pass.

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 unbroadcast summed 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), the assert on 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 Python 0 is 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 is axis is not None.
  • A numpy integer is not a Python integer. 8 ** -1 is 0.125, but np.int64(8) ** -1 raises “Integers to negative integer powers are not allowed”. Division is self * other**-1, and my first mean computed its count with np.prod, which returns an np.int64. Now the divisor is wrapped in a Tensor first, and a Tensor always holds 64-bit floats.
  • A numpy array on the left. In y * scores, with y a numpy array and scores a Tensor, Python asks numpy first, and numpy does not step aside: it multiplies each element of y on 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 10410^4 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, log and tanh, which open the door to softmax and cross-entropy;
  • a batched @, for tensors with any number of dimensions;
  • an initialization scaled by 1/nin1/\sqrt{n_{in}};
  • 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

  1. Richard Feynman put it better. “What I cannot create, I do not understand” was written on his blackboard at the time of his death. ↩

  2. With numpy’s assert_allclose at atol=1e-10 (looser in one test), on top of its default relative tolerance of 10−710^{-7}, and with 64-bit floats on both sides. ↩

  3. 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)). ↩

  4. 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. ↩

  5. PyTorch has the same operation, under the name Tensor.sum_to_size. ↩

  6. The general, batched version needs swapaxes(-1, -2) instead of .T (which reverses all the axes), unbroadcast over the batch axes, and special cases for 1-D operands. ↩

  7. PyTorch’s nn.Linear stores the weight the other way round, as (nout, nin), and computes x @ W.T. It is the same math. It also draws the initial weights from a range scaled by 1/nin1/\sqrt{n_{in}}, which matters for wider and deeper networks. myriograd keeps micrograd’s uniform values between −1 and 1. ↩

  8. 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 10−410^{-4}, and 100 steps of gradient descent with a learning rate that goes from 1.0 down to about 0.1. ↩

  9. See Myria- on Wikipedia. ↩

← All writing