Train a classifier and render a prediction grid in Rust
Current source-owned tutorial. API availability differs by language.
Start the walkthrough · Jump to complete source
Train a small MLP on Fashion-MNIST, run inference on 25 test images, and render the results as a 5×5 oa::plot::Figure grid. Green titles mark correct predictions, red titles mark misses with the actual class shown as a caption.
Run
cargo run -p sdk --release --example tu_image_grid_classify -- <data_dir> --save grid.png --steps 300
<data_dir> must contain the four Fashion-MNIST IDX files (train-images-idx3-ubyte, train-labels-idx1-ubyte, t10k-images-idx3-ubyte, t10k-labels-idx1-ubyte), defaulting to ./data/fashionMnist. --save writes the grid headlessly; without it the program opens an oa::Viewer window. --steps sets the training step count (default 2000).
Expected output:
Loaded 60000 train / 10000 test images
epoch 1/1
300/300 |██████████| 0.57s · 1.91 ms/step · 33.43K sample/s · loss: 0.3941
Summary:
loss: initial 2.332655 · final 0.394115 · mean 0.642502
Wall: 1.91 ms/step · 33.42K sample/s
run: 0.57s · 300 steps · batch 64
Training done.
Prediction grid: 21 / 25 correct on the first 25 test images
Saved: grid.png
1. Load the IDX dataset
load_mnist_idx reads the IDX containers directly: it validates the magic headers (0x0803 images, 0x0801 labels), checks the 28×28 geometry, and keeps the raw u8 buffers. Raw pixel bytes are needed twice, once normalized to f32 for training and once verbatim for the tile textures.
2. A two-layer MLP as a Module
MnistClassifier composes 784 → Relu(128) → 10 and registers its Linear layers in a ModuleRegistry so all_parameters can enumerate the weights for the optimizer.
1impl Module for MnistClassifier {2 fn forward(&self, input: &Matrix) -> oa::Result<Matrix> {3 let h = self.fc1.forward(input)?;4 let h = self.relu.forward(&h)?;5 self.fc2.forward(&h)6 }78 fn registry(&self) -> &ModuleRegistry {9 &self.registry10 }11}12
3. ItTraining drives the loop
Training is AdamW at lr 0.001 through ItTraining with the usual observers: LossMetric, ProgressBar, TrainingSummary. The data closure slices 64-image windows out of the training set and uploads them as Matrix batches; the step closure runs the forward pass under a GradientTape and backpropagates the cross-entropy loss.
1let mut optimizer = oa::ml::AdamW::new(params, 0.001)?;2let mut training = ItTraining::new(runtime, &mut optimizer, ItTrainingConfig {3 total_steps: train_steps,4 steps_per_epoch,5 batch_size: BATCH as u64,6 timer_name: "image_grid_classify_step".into(),7 ..ItTrainingConfig::default()8})?;9training.add_metric(&mut loss_metric);10training.add_callback(&mut progress);11training.add_callback(&mut summary);12
4. Inference produces tiles, not numbers
The first 25 test images go through model.forward, oa::matrix::softmax, and a host readback. Each argmax result pairs with an RGBA8 texture built from the raw grayscale bytes:
1let probs = oa::matrix::softmax(&logits, -1)?;2let host_probs = probs.read_f32()?;3// per image: argmax over the class row4let tile = oa::render::texture_from_rgba8(&rgba, 28, 28)?;5
5. imshow plus colored titles fill the grid
populate_figure assigns one Axes cell per image. ax.imshow draws the texture; title_color carries the predicted class in green or red, and misses add the actual class as a muted caption_color.
1ax.imshow(cell.tile.clone());2if cell.correct {3 ax.title_color(CLASSES[cell.predicted], color_success());4} else {5 ax.title_color(CLASSES[cell.predicted], color_error());6 ax.caption_color(CLASSES[cell.actual], color_muted());7}8ax.grid(false);9ax.legend(false);10
6. Two sinks, one figure
--save mode runs everything on Runtime::current() and calls fig.save_to(path). Interactive mode wraps the same pipeline in ImageGridClassifySource, a ViewerLiveSource whose open trains and fills the figure and whose render draws fig.render_frame each frame, driven by oa::Viewer on a presentation runtime built from the SDL window's required extensions.
What you built
End-to-end GPU pipeline: raw IDX bytes to trained MLP to a composited prediction grid, with the same figure renderable headlessly or in a live window. The full source is sdk/rs/tutorials/plot/tu_image_grid_classify/tu_image_grid_classify.rs. The same ItTraining workflow on a smaller model is on the MNIST tutorial page.
Example
Tu_image_grid_classify.rs
1// OA Tutorial: Image-grid Classification (Fashion-MNIST 5×5 grid)2//3// level-1 API: oa::ml::Module + oa::plot::Figure / Axes (imshow / title / caption)4//5// Parallel to the TF Keras classification tutorial, same 5×5 prediction grid,6// OA Rust syntax, GPU all the way through the compositor.7//8// Same renderer body, two sinks:9// tu_image_grid_classify → show (interactive window)10// tu_image_grid_classify --save grid.png → save_to (batch headless)11//12// usage:13// tu_image_grid_classify [data_dir] [--save path.png] [--steps N]14//15// Default data dir: ./data/fashionMnist16//17// Donor reference: tuImageGridClassify.cpp1819use std::path::{Path, PathBuf};20use std::rc::Rc;2122use oa::ml::{23 GradientTape, ItTraining, ItTrainingConfig, LossMetric, Module, ModuleRegistry, ProgressBar,24 TrainingSummary,25};26use oa::plot::{Axes, Figure, FigureConfig};27use oa::ui::Ui;28use oa::{Color, Matrix, Runtime, Texture, ViewerLiveCapabilities, ViewerLiveSource};2930// ── Fashion-MNIST class names ─────────────────────────────────────────────────3132const CLASSES: [&str; 10] = [33 "T-shirt", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Boot",34];35const NUM_CLASSES: usize = 10;3637// ── Title colors (donor: kSuccess / kError / kMuted) ─────────────────────────3839fn color_success() -> Color {40 Color::new(0.188, 0.820, 0.345, 1.0) // #30d15841}42fn color_error() -> Color {43 Color::new(1.000, 0.271, 0.227, 1.0) // #ff453a44}45fn color_muted() -> Color {46 Color::new(0.565, 0.565, 0.565, 1.0) // #90909047}4849// ── Fashion-MNIST IDX file loader ─────────────────────────────────────────────5051/// Raw decoded IDX dataset.52struct MnistData {53 /// Raw U8 pixel bytes, `count × 784`.54 images: Vec<u8>,55 /// Raw U8 label bytes, `count × 1`.56 labels: Vec<u8>,57 count: usize,58}5960fn read_be32(bytes: &[u8], offset: &mut usize) -> Option<u32> {61 if bytes.len().checked_sub(*offset)? < 4 {62 return None;63 }64 let b = &bytes[*offset..*offset + 4];65 *offset += 4;66 Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))67}6869fn load_mnist_idx(dir: &Path, img_file: &str, lbl_file: &str) -> Option<MnistData> {70 let img_bytes = std::fs::read(dir.join(img_file)).ok()?;71 let lbl_bytes = std::fs::read(dir.join(lbl_file)).ok()?;7273 let mut io = 0usize;74 let mut lo = 0usize;7576 let img_magic = read_be32(&img_bytes, &mut io)?;77 if img_magic != 0x0000_0803 {78 return None;79 }80 let n = read_be32(&img_bytes, &mut io)? as usize;81 let rows = read_be32(&img_bytes, &mut io)? as usize;82 let cols = read_be32(&img_bytes, &mut io)? as usize;83 if rows != 28 || cols != 28 {84 return None;85 }8687 let lbl_magic = read_be32(&lbl_bytes, &mut lo)?;88 if lbl_magic != 0x0000_0801 {89 return None;90 }91 let lbl_n = read_be32(&lbl_bytes, &mut lo)? as usize;92 if lbl_n != n {93 return None;94 }9596 let img_expected = n * 784;97 if io + img_expected != img_bytes.len() || lo + n != lbl_bytes.len() {98 return None;99 }100101 Some(MnistData {102 images: img_bytes[io..].to_vec(),103 labels: lbl_bytes[lo..].to_vec(),104 count: n,105 })106}107108// ── MLP classifier: 784 → ReLU(128) → 10 ────────────────────────────────────109110/// Two-layer MLP. Donor: `MnistClassifier` in tuImageGridClassify.cpp.111struct MnistClassifier {112 fc1: Rc<oa::ml::nn::Linear>,113 fc2: Rc<oa::ml::nn::Linear>,114 relu: oa::ml::nn::Relu,115 registry: ModuleRegistry,116}117118impl MnistClassifier {119 fn new() -> oa::Result<Self> {120 let fc1 = Rc::new(oa::ml::nn::Linear::new_with_seed(784, 128, 1)?);121 let fc2 = Rc::new(oa::ml::nn::Linear::new_with_seed(128, NUM_CLASSES, 2)?);122 let relu = oa::ml::nn::Relu::new();123 let mut registry = ModuleRegistry::new();124 registry.register_module("fc1", fc1.clone() as Rc<dyn Module>)?;125 registry.register_module("fc2", fc2.clone() as Rc<dyn Module>)?;126 Ok(Self {127 fc1,128 fc2,129 relu,130 registry,131 })132 }133}134135impl Module for MnistClassifier {136 fn forward(&self, input: &Matrix) -> oa::Result<Matrix> {137 let h = self.fc1.forward(input)?;138 let h = self.relu.forward(&h)?;139 self.fc2.forward(&h)140 }141142 fn registry(&self) -> &ModuleRegistry {143 &self.registry144 }145}146147// ── Grid cell: one tile + prediction info ────────────────────────────────────148149struct GridCell {150 /// 28×28 RGBA8 texture.151 tile: Texture,152 actual: usize,153 predicted: usize,154 correct: bool,155}156157// ── Training + inference pipeline ────────────────────────────────────────────158159const GRID_ROWS: usize = 5;160const GRID_COLS: usize = 5;161const GRID_N: usize = GRID_ROWS * GRID_COLS; // 25162163/// Train an MLP on Fashion-MNIST, then infer on the first 25 test images.164fn train_and_predict_grid(165 runtime: &Runtime,166 data_dir: &Path,167 train_steps: u64,168) -> anyhow::Result<Vec<GridCell>> {169 Runtime::set_default(runtime.clone());170 // Load raw test data (pixel bytes needed for textures).171 let test_raw = load_mnist_idx(data_dir, "t10k-images-idx3-ubyte", "t10k-labels-idx1-ubyte")172 .ok_or_else(|| {173 anyhow::anyhow!(174 "Fashion-MNIST test set not found at {}: \175 download from https://github.com/zalandoresearch/fashion-mnist",176 data_dir.display()177 )178 })?;179180 // Load training data.181 let train_raw = load_mnist_idx(182 data_dir,183 "train-images-idx3-ubyte",184 "train-labels-idx1-ubyte",185 )186 .ok_or_else(|| {187 anyhow::anyhow!(188 "Fashion-MNIST training set not found at {}",189 data_dir.display()190 )191 })?;192193 println!(194 "Loaded {} train / {} test images",195 train_raw.count, test_raw.count196 );197198 // Build model + optimizer.199 let model = MnistClassifier::new()?;200 let params = model.all_parameters()?;201 let mut optimizer = oa::ml::AdamW::new(params, 0.001)?;202203 const BATCH: usize = 64;204 let steps_per_epoch = (train_raw.count / BATCH) as u64;205206 let mut loss_metric = LossMetric::default();207 let mut progress = ProgressBar::default();208 let mut summary = TrainingSummary::default();209 let mut training = ItTraining::new(210 runtime,211 &mut optimizer,212 ItTrainingConfig {213 total_steps: train_steps,214 steps_per_epoch,215 batch_size: BATCH as u64,216 timer_name: "image_grid_classify_step".into(),217 ..ItTrainingConfig::default()218 },219 )?;220 training.add_metric(&mut loss_metric);221 training.add_callback(&mut progress);222 training.add_callback(&mut summary);223224 // Advance through the training set sequentially (deterministic, no shuffle).225 let n_train = train_raw.count;226 let mut step_offset = 0usize;227228 while training.step(229 || {230 let start = (step_offset * BATCH) % n_train.saturating_sub(1).max(BATCH);231 step_offset = step_offset.wrapping_add(1);232233 let mut x_f32 = vec![0.0f32; BATCH * 784];234 let mut y_u32 = vec![0u32; BATCH];235 for bi in 0..BATCH {236 let si = (start + bi).min(n_train - 1);237 let src = &train_raw.images[si * 784..(si + 1) * 784];238 for (j, &pixel) in src.iter().enumerate() {239 x_f32[bi * 784 + j] = pixel as f32 / 255.0;240 }241 y_u32[bi] = train_raw.labels[si] as u32;242 }243 let x = Matrix::new_from_slice([BATCH, 784], &x_f32)?;244 let y = Matrix::new_from_slice([BATCH], &y_u32)?;245 Ok((x, y))246 },247 |(x, y)| {248 let tape = GradientTape::new();249 let logits = model.forward(&x)?;250 let loss = oa::ml::loss::cross_entropy(&logits, &y)?;251 tape.backward(&loss)?;252 Ok(loss)253 },254 )? {}255256 training.finish()?;257 println!("Training done.");258259 // ── Inference on the first GRID_N test images ─────────────────────────260261 let mut x_f32 = vec![0.0f32; GRID_N * 784];262 for (i, pixel) in test_raw.images[..GRID_N * 784].iter().enumerate() {263 x_f32[i] = *pixel as f32 / 255.0;264 }265 let x_test = Matrix::new_from_slice([GRID_N, 784], &x_f32)?;266 let logits = model.forward(&x_test)?;267 let probs = oa::matrix::softmax(&logits, -1)?;268 let host_probs = probs.read_f32()?;269270 // Build grid cells.271 let mut cells = Vec::with_capacity(GRID_N);272 for i in 0..GRID_N {273 // Argmax for predicted class.274 let row = &host_probs[i * NUM_CLASSES..(i + 1) * NUM_CLASSES];275 let predicted = row276 .iter()277 .enumerate()278 .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))279 .map(|(idx, _)| idx)280 .unwrap_or(0);281 let actual = test_raw.labels[i] as usize;282283 // Build an RGBA8 grayscale texture from raw pixel bytes.284 let src = &test_raw.images[i * 784..(i + 1) * 784];285 let mut rgba = vec![0u8; 28 * 28 * 4];286 for (p, &g) in src.iter().enumerate() {287 rgba[p * 4] = g;288 rgba[p * 4 + 1] = g;289 rgba[p * 4 + 2] = g;290 rgba[p * 4 + 3] = 255;291 }292 let tile = oa::render::texture_from_rgba8(&rgba, 28, 28)?;293294 cells.push(GridCell {295 tile,296 actual,297 predicted,298 correct: predicted == actual,299 });300 }301302 let correct_count = cells.iter().filter(|c| c.correct).count();303 println!(304 "Prediction grid: {} / {} correct on the first {} test images",305 correct_count, GRID_N, GRID_N306 );307308 Ok(cells)309}310311// ── Figure population ─────────────────────────────────────────────────────────312313fn populate_figure(fig: &mut Figure, cells: &[GridCell]) {314 for (i, cell) in cells.iter().enumerate().take(GRID_N) {315 let row = (i / GRID_COLS) as i32;316 let col = (i % GRID_COLS) as i32;317 let ax: &mut Axes = fig.ax(row, col);318 ax.imshow(cell.tile.clone());319 if cell.correct {320 ax.title_color(CLASSES[cell.predicted], color_success());321 } else {322 ax.title_color(CLASSES[cell.predicted], color_error());323 ax.caption_color(CLASSES[cell.actual], color_muted());324 }325 // No grid lines or legend for image cells.326 ax.grid(false);327 ax.legend(false);328 }329}330331// ── ViewerLiveSource: drives the figure from inside a Viewer lifecycle ────────332333/// Donor: `ImageGridClassifySource` in tuImageGridClassify.cpp.334pub struct ImageGridClassifySource {335 data_dir: PathBuf,336 train_steps: u64,337 fig: Figure,338 cells: Vec<GridCell>,339}340341impl ImageGridClassifySource {342 pub fn new(data_dir: PathBuf, train_steps: u64) -> Self {343 let fig = Figure::new(FigureConfig {344 rows: GRID_ROWS as i32,345 cols: GRID_COLS as i32,346 width: 800,347 height: 800,348 h_spacing: 8,349 v_spacing: 8,350 padding: 8,351 ..Default::default()352 });353 Self {354 data_dir,355 train_steps,356 fig,357 cells: Vec::new(),358 }359 }360}361362impl ViewerLiveSource for ImageGridClassifySource {363 fn capabilities(&self) -> ViewerLiveCapabilities {364 ViewerLiveCapabilities::default()365 }366367 fn open(&mut self, runtime: &Runtime) -> oa::Result<()> {368 self.cells = train_and_predict_grid(runtime, &self.data_dir, self.train_steps)369 .map_err(|e| oa::Error::callback(e.to_string()))?;370 populate_figure(&mut self.fig, &self.cells);371 Ok(())372 }373374 fn update(&mut self, _delta_ms: f32) -> oa::Result<()> {375 Ok(())376 }377378 fn render(&mut self, ui: &mut Ui<'_>, width: u32, height: u32) -> oa::Result<()> {379 self.fig.render_frame(width, height, ui)380 }381382 fn close(&mut self) -> oa::Result<()> {383 self.cells.clear();384 Ok(())385 }386}387388// ── CLI + main ────────────────────────────────────────────────────────────────389390fn usage(program: &str) {391 eprintln!(392 "usage: {program} [data_dir] [--save path.png] [--steps N]\n\393 \n\394 data_dir path to the Fashion-MNIST IDX files (default: ./data/fashionMnist)\n\395 --save write the 5×5 grid as a PNG instead of opening a window\n\396 --steps number of training steps (default: 2000)"397 );398}399400fn main() -> anyhow::Result<()> {401 let mut data_dir = PathBuf::from("data/fashionMnist");402 let mut save_path: Option<String> = None;403 let mut train_steps: u64 = 2000;404 let mut positional_done = false;405406 let args: Vec<String> = std::env::args().collect();407 let mut i = 1;408 while i < args.len() {409 match args[i].as_str() {410 "--save" if i + 1 < args.len() => {411 i += 1;412 save_path = Some(args[i].clone());413 }414 "--steps" if i + 1 < args.len() => {415 i += 1;416 train_steps = args[i].parse().unwrap_or(2000);417 }418 "--help" => {419 usage(&args[0]);420 return Ok(());421 }422 other if !positional_done && !other.starts_with('-') => {423 data_dir = PathBuf::from(other);424 positional_done = true;425 }426 other => {427 eprintln!("unknown argument: {other}");428 usage(&args[0]);429 std::process::exit(1);430 }431 }432 i += 1;433 }434435 println!();436 println!("╔══════════════════════════════════════════════════════════════════╗");437 println!("║ OA Tutorial · Fashion-MNIST Prediction grid (oa::plot) ║");438 println!("║ Train → Predict → display (5×5 grid, 25 test images) ║");439 println!("║ Green title = correct · Red title = wrong ║");440 println!(441 "║ Mode: {:<58}║",442 if save_path.is_some() {443 "save_to (headless PNG output)"444 } else {445 "show (interactive window)"446 }447 );448 println!("╚══════════════════════════════════════════════════════════════════╝");449 println!();450451 // ── save mode: compute-only runtime, no swapchain ─────────────────────────452 if let Some(ref path) = save_path {453 let runtime = Runtime::current()?;454 Runtime::set_default(runtime.clone());455 let cells = train_and_predict_grid(&runtime, &data_dir, train_steps)?;456 let mut fig = Figure::new(FigureConfig {457 rows: GRID_ROWS as i32,458 cols: GRID_COLS as i32,459 width: 800,460 height: 800,461 h_spacing: 8,462 v_spacing: 8,463 padding: 4,464 ..Default::default()465 });466 populate_figure(&mut fig, &cells);467 fig.save_to(path)?;468 println!("Saved: {path}");469 return Ok(());470 }471472 // ── show mode: Viewer lifecycle with a live figure source ─────────────────473 let mut source = ImageGridClassifySource::new(data_dir, train_steps);474 let config = oa::ViewerConfig {475 mode: oa::ViewerMode::Live,476 width: 800,477 height: 800,478 show_help: false,479 show_stats: false,480 show_timeline: false,481 ..Default::default()482 };483 let mut viewer = oa::Viewer::new(config);484 viewer.set_live_source(&mut source);485486 let window = oa::SdlWindow::new("OA · Fashion-MNIST grid", 800, 800)487 .map_err(|e| anyhow::anyhow!("SDL window: {e}"))?;488 let extensions = window489 .required_instance_extensions()490 .map_err(|e| anyhow::anyhow!("SDL extensions: {e}"))?;491 let runtime = Runtime::builder().instance_extensions(extensions).build()?;492 Runtime::set_default(runtime.clone());493 viewer.run(&runtime)?;494 Ok(())495}496
Run Rust tutorials from the OA SDK checkout with cargo run --release --example <name>. Run Python with the environment containing the OA native extension. Consult each program's arguments and capability checks before running it.