Skip to content
tmon.ch
Go back

tinycnn: A Convolutional Neural Network From Scratch in Rust

timondurot/tinycnn516 lines of Rust · 6 commits8 days of work, no README

tinycnn is a convolutional neural network I wrote by hand in Rust, in September 2022. That’s a few months before ChatGPT came out, so there was no AI to ask. Every line in it, I typed myself.

It’s from scratch, too. No PyTorch, no TensorFlow, no machine learning crate at all. It uses ndarray for the arrays, the mnist crate to read the data files and crossbeam for threads. Everything else, the layers, the backpropagation and the training loop, is mine.

Back then I watched the loss drop toward zero, saw that it was learning, and moved on to the next thing. I never wrote a README, and I never counted how many digits it actually gets right. So now, years later, I gave it to Opus 5.5 for one simple pass: build it, run it as it is, and find out how well it holds up. The code in the repo is exactly what I pushed in 2022. Nothing in it was changed for this post.

What it does

It learns to read handwritten digits. The dataset is MNIST: 70,000 tiny grayscale images, 28×28 pixels each, of digits people wrote by hand. It’s the “hello world” of image recognition.

You build a network by chaining layers. This is straight from main.rs, comment included:

//deeply intricate cnn mnist example

let mut my_mnist_network = TinyNetwork::new(vec![1, 28, 28])
                        .conv(2, 7).sigmoid()
                        .conv(4, 5).sigmoid()
                        .reshape(vec![4 * 18 * 18, 1])
                        .dense(100).sigmoid()
                        .dense(10).sigmoid();

“Deeply intricate.” Here’s what it actually is:

  1. 2 filters of 7×7. Each slides over the 28×28 image and produces a 22×22 map.
  2. 4 filters of 5×5. Each looks at both maps from step 1 and produces an 18×18 map.
  3. Flatten those 4 maps into one list of 1,296 numbers.
  4. 100 neurons, each connected to all 1,296.
  5. 10 outputs, one per digit. The highest one is the answer.

Six filters in total. It’s called tinycnn for a reason.

How a convolution works

A filter is a small grid of numbers. You slide it across the image, and at every position you multiply the filter with the pixels under it and add everything up. That gives one number per position, and together they form a new image: a map of where the filter “fires”. A filter with positive numbers on the left and negative ones on the right, for example, fires on vertical edges.

In a CNN nobody designs the filters. They start as random numbers, and training slowly turns them into whatever helps tell a 3 from an 8.

In tinycnn, the whole operation is four lines:

pub fn validcorrelate(image: ArrayView2<f32>, kernel: ArrayView2<f32>) -> Array2<f32> {
    Zip::from(image.windows(kernel.raw_dim())).map_collect(|window| {
        (&window * &kernel).sum()
    })
}

windows() hands out every filter-sized patch of the image, and each patch gets multiplied with the filter and summed.

The hard part is training. To learn, the network has to work out how much every single weight contributed to a wrong answer, and push it the other way. That’s backpropagation. For a convolution layer it turns out to be two more convolutions: one tells each filter how to change, the other passes the blame back to the layer before. tinycnn does both by hand:

//update kernels_deriv
subkernel_deriv.assign(&validcorrelate(image, o_deriv));
//update input_deriv
channel_deriv += &fullconvolve(o_deriv, subkernel);

Opus checked the math, and it’s right, including the part where the filter has to be flipped 180° for the second one.

Does it work?

It builds in 14 seconds. Before MNIST, main.rs runs a second example: a tiny network that learns XOR. XOR has no image to slide filters over, so this one has no convolutions at all, just two dense layers built with the same builder:

let mut my_xor_network = TinyNetwork::new(vec![2, 1])
                        .dense(3).sigmoid()
                        .dense(1).sigmoid();

That’s the point of it: tinycnn isn’t hard-wired to one CNN, and you can stack its layers into whatever network your data needs. The XOR network learns, too: its loss drops from 0.71 to 0.006.

Then it starts on MNIST, and the loss falls nicely for one full pass through the 60,000 training images. Then it crashes:

assertion failed: end <= axis_len

The training loop never stops, so it runs off the end of the data.

It also never tells you how many digits it actually gets right. It only prints the loss. Even the Rust compiler noticed:

warning: fields `validation` and `testing` are never read

So Opus wrote a one-off test, in a throwaway copy of the project. It trains my network with my training code and after each pass through the training data it counts how many of the held-out images the network gets right. The only differences are a loop that stops and the counting.

Passes through the dataValidation (9,000 images)Test (1,000 images)
192.2%92.2%
395.2%96.0%
596.4%97.0%
1097.3%97.5%
1597.7%97.7%

All 15 passes take under 5 minutes on a CPU.

For context, a single layer with no hidden neurons gets about 92% on MNIST. LeNet-5, the famous CNN from 1998, gets about 99%. tinycnn sits in between, with 6 filters, sigmoids everywhere and two training bugs. I’ll take it.

Draw a digit

This is the same network, running in your browser. Opus ported the forward pass to JavaScript line by line for this demo, and the weights come from a separate 15-pass training run of the original Rust code, which ended at 97.3% on the test images. Its outputs match the Rust version to six decimal places. Draw a digit, or load a real one from the MNIST test set.

It says?
Draw a digit on the left.
0
1
2
3
4
5
6
7
8
9
Input, 28×28
Layer 1: 2 filters, 7×7
Layer 2: 4 filters, 5×5
Everything after the input is what the 6 filters see. Brighter means a stronger response.

The bottom row shows what the 6 filters see. With only two filters, layer 1 mostly makes a blurred copy of the digit and an inverted one. Layer 2’s maps start to pick out particular strokes and directions.

It was only ever trained on MNIST, where every digit is drawn with a pen and neatly centered. Your drawing gets cropped, scaled and centered the same way before it goes in, but unusual handwriting can still throw it off. Also, the 10 bars don’t add up to 100%. Each output is its own independent sigmoid, so the network can be confident about two digits at once, or none.

The bad parts

It never checks its answers. The validation and test sets get loaded and are never used. The compiler warning above is the only thing in the whole project that knows they exist.

The training loop never ends. loop { ... cur += 20; } with nothing to stop it. After 60,000 images it asks for image 60,001 and crashes.

The first image counts twice. To add up the updates from a batch of 20 images, it starts with a copy of the first image’s update and then adds all 20, including the first one again. And it adds them up instead of averaging them, so the learning rate is secretly 20 times what settings.rs says.

The second conv layer has 200 weights and 1,296 biases. Normally each filter gets one bias. tinycnn gives every single output pixel its own.

Every weight starts between −1 and 1, no matter how many inputs its layer has. The first dense layer adds up 1,296 inputs per neuron, so the sums start out huge, and most of its sigmoids begin stuck near 0 or 1, where they barely learn. The usual fix is to shrink the starting range as the number of inputs grows.

unsafe impl Send for TinyNetwork {}. Rust refused to share the network between threads, so I told it to trust me. Writing Box<dyn Layer + Send + Sync> would have fixed it properly.

What I got right

Backpropagation through convolution layers, by hand, with the flipped filters and all, and it’s correct. That’s the part most people never write themselves. The layer builder reads like a real ML library. And a network with 6 filters, a couple of bugs and no idea how good it was turns out to read 97.7% of handwritten digits.


Share this post:

Previous Post
Rediscovering the Connect Four AI I wrote at 12
Next Post
PICKSMART / NEMR: turning a 2.9" Bluetooth price tag into a door sign