MNIST from scratch

August 10, 2026

Introduction

This project has been a personal effort of mine to fully understand the basics of deep learning. I did the project entirely without AI, as its objective was my own understanding, not the result itself. I used AI to proofread this post, to make its figures and the interactive demo, and to write the PyTorch implementation I used for comparison.

The project had three parts:

  1. Build a tensor data structure, also known as an n-dimensional array. Implement the generic product using Einstein notation, like einsum in NumPy or PyTorch.
  2. Build automatic differentiation on top of these tensors.
  3. Use these two components to train a tiny MNIST classifier.

Try the model: draw a digit

Prediction

—

Tensors and einsum notation

A tensor is a fancy name for an array with any number of dimensions. So a scalar number is just a tensor with 0 dimensions, a vector is a tensor with 1 dimension, and a matrix is a tensor with 2 dimensions. We can imagine “cubes” as tensors with 3 dimensions (stacks of matrices), and so on for any number of dimensions.

Multiplying two tensors can be done in many different ways. The generic product using Einstein notation is called einsum. Here’s what one such multiplication looks like. For a 3-dimensional tensor $A$ and a 4-dimensional tensor $B$, we have

$$ \bigl[A_{ijk},\,B_{lmik}\bigr]_{km} = \sum_{ijl}A_{ijk}B_{lmik}. $$

In this notation, the subscript outside the brackets lists the indices we keep, in order. Here we keep $k$ and $m$, so the output is a 2-dimensional tensor. We just sum over all indices that do not appear in the output. Furthermore, if an index appears in both inputs, we are implicitly requiring that the two inputs have the same size along the corresponding dimensions.

This is a super general way to define multiplication. For instance, the classical matrix-vector product is just $\bigl[A_{ij},\,x_{j}\bigr]_{i}$ and the matrix-matrix product is $\bigl[A_{ij},\,B_{jk}\bigr]_{ik}$. The dot product is $\bigl[x_{i},\,y_{i}\bigr]$ and the outer product is $\bigl[x_{i},\,y_{j}\bigr]_{ij}$.

Automatic differentiation

This is the core algorithm in deep learning. The idea is that if I design my model $M$ as a differentiable function of the inputs $x$ and some parameters $\theta$, and use a differentiable loss, then

$$ \text{Loss}(M(x, \theta), y) $$

is also differentiable. Thus I can compute the gradient of the loss with respect to the parameters of $M$. Then I update the parameters using that gradient:

$$ \theta \leftarrow \theta - \eta \nabla_\theta \text{Loss}(M(x, \theta), y). $$

Automatic differentiation computes such gradients efficiently. The way it works here is that it keeps track of intermediate values during the computation of $M(x, \theta)$. And it keeps track of partial derivatives of each intermediate value with respect to its inputs. Then, when the loss is computed, the algorithm travels back through the graph and uses the chain rule to compute the gradient of the loss with respect to each intermediate value.

MNIST classifier

Finally, I used all of this to build a handwritten digit classifier using the famous MNIST dataset. The model I trained is very simple:

$$ \begin{aligned} H_{bh} &= \operatorname{ReLU}\!\left(\bigl[X_{bp},\,(W_1)_{ph}\bigr]_{bh}\right),\\ M(X)_{bd} &= \bigl[H_{bh},\,(W_2)_{hd}\bigr]_{bd}. \end{aligned} $$

Each row $b$ of $X$ is a flattened image. The first weight matrix maps its 784 pixels ($p$) to 256 hidden units ($h$), and the second maps those to 10 digit scores ($d$).

For training, I summed the losses for 16 samples and then took a gradient step. You can see the training plot and try the model yourself in the interactive UI.

Plots of MNIST training loss and success rate over the course of training
Training loss and success rate for the from-scratch MNIST implementation.

The complete implementation is available on GitHub.

Comparison with PyTorch and AI

For the sake of humiliation, I asked GPT-6-sol to implement the same thing from scratch using PyTorch. It took no more than a few minutes to write, and training ran about 10,000 times faster. A single epoch took 2.93 seconds instead of 8 hours and 40 minutes. The gap is not surprising. PyTorch is a thin Python layer over heavily optimized C/C++ (and, on a GPU, CUDA) kernels, so the actual number crunching never runs in the Python interpreter. My implementation is written entirely in Python and it was never optimized for performance.

The most surprising thing, maybe, is how much fun I had along the way. This crazy feeling of understanding each and every line of code and being in the flow for many hours straight. I hope that coding will become like horse riding. Useless, but people who really like it still do it.