Skip to content

CNN Image Classifier

Full source in examples/cnn.rs. Run it with cargo run --release --example cnn.

What This Shows

  • Building 2D convolutional models with Conv2d (NHWC layout)
  • Using global average pooling via mean_axes(&[1, 2])
  • Training with nn::cross_entropy, value_and_grad, and AdamW

Model Definition

The classifier distinguishes synthetic horizontal vs. vertical bar images with two strided convolutions followed by a linear head.

#[module]
struct TinyCnn {
    c1: Conv2d,
    c2: Conv2d,
    head: Linear,
}

impl TinyCnn {
    fn new(classes: usize) -> Self {
        Self {
            c1: Conv2d::new(1, 8, 3).stride(2),
            c2: Conv2d::new(8, 16, 3).stride(2),
            head: Linear::new(16, classes),
        }
    }

    fn forward(&self, x: &Tensor) -> Tensor {
        let h = self.c1.forward(x).relu();
        let h = self.c2.forward(&h).relu();
        self.head.forward(&h.mean_axes(&[1, 2]))
    }

    fn loss(&self, x: &Tensor, targets: &Tensor) -> Tensor {
        nn::cross_entropy(&self.forward(x), targets)
    }
}

Compiled Training Step

A single jit-compiled AdamW step reduces cross-entropy loss from 0.696 to 0.000 within 40 iterations.

let train_step = jit(move |(mut m, mut o): (TinyCnn, AdamW<TinyCnn>)| {
    let (loss, grads) = value_and_grad(|p| p.loss(&images, &labels), &m);
    o.step(&mut m, &grads);
    (m, o, loss)
});