Recognize speech commands in Rust
Train and inspect a Speech Commands classifier with OA and OADS.
Start the walkthrough · Jump to complete source
Train a CNN to recognize eight spoken commands. This walkthrough follows the TensorFlow simple audio tutorial using OA for signal processing and training and OADS for the complete 8,000-clip mini Speech Commands pack used in that tutorial.
Run in Rust
Run from the OASDK root.
cargo run --release --example tu_ml_audio_commands -- --epochs 10
The default schedule uses up to ten epochs and 64 clips per batch.
Set OA_DATA_DIR to share the OADS cache. Use --preview-only for waveform
and spectrogram inspection or --steps 32 --batch 8 for a short replay check.
Select a specific Vulkan device with --device INDEX.
1. Load and inspect the audio
OADS verifies and loads every recording in the mini pack. It scales PCM to
[-1, 1] and pads each mono 16 kHz clip to 16,000 samples. Each command has
1,000 examples. The class IDs are down, go, left, no, right,
stop, up, and yes.
1let data = MiniSpeechCommands::load_on(&runtime, &MiniSpeechCommandsConfig::default())?;2println!("{:?} {:?}", data.samples().shape(), data.labels().shape());3
The input and label shapes are [8000, 1, 16000] and [8000]. Both
programs use OA's seed-42 shuffle to reserve 6,400 clips for training, 800
for validation, and 800 for the final test. This gives matching Rust and
Python splits with the same proportions as the reference. The TensorFlow
loader uses its own file order and shuffle.
2. Convert waveforms to spectrograms
A short-time Fourier transform measures how a clip's frequency content
changes over time. Apply a periodic Hann window to 255 samples, advance by
128 samples and use a 256-point FFT. OA returns the magnitudes of 129
nonnegative-frequency bins in 124 frames. Add a channel axis so the CNN
receives [batch, 1, 124, 129] in OA's channel-first layout.
1let magnitude = audio.stft(StftConfig {2 fft_size: 256, hop_size: 128, win_size: 255, center: false,3 ..Default::default()4})?;5let features = magnitude.reshape([batch, 1, 124, 129])?;6
The frequency plots use log magnitude to make quiet components easier to spot. The CNN receives linear magnitudes.
3. Build the classifier
Fit a scalar mean and standard deviation on the training spectrograms. Bilinearly resize each spectrogram to 32×32, then apply the fitted statistics to training, validation, test and inference inputs. The tutorial caches the resized features before training, so replay reuses the prepared batch shape.
| Layer | Output per clip |
|---|---|
| Bilinear resize and normalization | 1 × 32 × 32 |
| 3×3 convolution, ReLU | 32 × 30 × 30 |
| 3×3 convolution, ReLU | 64 × 28 × 28 |
| 2×2 max pooling and Dropout(0.25) | 64 × 14 × 14 |
| Flatten and dense ReLU | 128 |
| Dropout(0.5) and dense | 8 logits |
The model has 1,625,608 trainable values. The output logits go into sparse
cross-entropy. AdamW uses zero weight decay and the reference Adam settings
with a learning rate of 0.001 and epsilon of 1e-7.
4. Train with compiled replay
ItTraining owns the optimizer updates, loss metric, progress bar, and
summary. The prepare callback uploads fresh data and integer labels. The
record callback builds the forward and backward pass. OA warms up eagerly,
captures a fixed-shape update, and replays the compiled step with new data.
The programs verify cached replay, a zero fallback count, and agreement
between completed steps and optimizer updates.
1|(input, target)| {2 let tape = GradientTape::new();3 let logits = model.forward(&input)?;4 let loss = ml::loss::cross_entropy(&logits, &target)?;5 tape.backward(&loss)?;6 Ok(loss)7}8
After each epoch, switch dropout off and evaluate the validation split. Return to training mode for the next epoch. Stop after two consecutive epochs without a lower validation loss, as in the reference.
The figures below come from the Rust run on Mesa llvmpipe. It completed 1,000 updates across 10 epochs with 64 clips per batch. Validation and test each used all 800 clips in their respective splits.
1Split: 6400 train · 800 validation · 800 test23epoch 1/104 100/100 |██████████| 640.66s · 6406.56 ms/step · 10 sample/s · 10 clip/s · loss: 1.48965 100/100 — 640.7s 6407 ms/step · accuracy: 0.3695 · loss: 1.7173 · val_accuracy: 0.5687 · val_loss: 1.322267epoch 2/108 100/100 |██████████| 631.58s · 6315.83 ms/step · 10 sample/s · 10 clip/s · loss: 0.90259 100/100 — 631.6s 6316 ms/step · accuracy: 0.5794 · loss: 1.1938 · val_accuracy: 0.6937 · val_loss: 0.91091011epoch 3/1012 100/100 |██████████| 647.30s · 6473.04 ms/step · 10 sample/s · 10 clip/s · loss: 0.747213 100/100 — 647.3s 6473 ms/step · accuracy: 0.6656 · loss: 0.9184 · val_accuracy: 0.7550 · val_loss: 0.75561415epoch 4/1016 100/100 |██████████| 666.33s · 6663.31 ms/step · 10 sample/s · 10 clip/s · loss: 0.724017 100/100 — 666.3s 6663 ms/step · accuracy: 0.7222 · loss: 0.7634 · val_accuracy: 0.7887 · val_loss: 0.68211819epoch 5/1020 100/100 |██████████| 650.52s · 6505.17 ms/step · 10 sample/s · 10 clip/s · loss: 0.749921 100/100 — 650.5s 6505 ms/step · accuracy: 0.7631 · loss: 0.6610 · val_accuracy: 0.7875 · val_loss: 0.61872223epoch 6/1024 100/100 |██████████| 668.60s · 6686.01 ms/step · 10 sample/s · 10 clip/s · loss: 0.643325 100/100 — 668.6s 6686 ms/step · accuracy: 0.7834 · loss: 0.5844 · val_accuracy: 0.8263 · val_loss: 0.55752627epoch 7/1028 100/100 |██████████| 772.45s · 7724.53 ms/step · 8 sample/s · 8 clip/s · loss: 0.435129 100/100 — 772.5s 7725 ms/step · accuracy: 0.8205 · loss: 0.5022 · val_accuracy: 0.8325 · val_loss: 0.52833031epoch 8/1032 100/100 |██████████| 624.43s · 6244.27 ms/step · 10 sample/s · 10 clip/s · loss: 0.458633 100/100 — 624.4s 6244 ms/step · accuracy: 0.8341 · loss: 0.4664 · val_accuracy: 0.8462 · val_loss: 0.49243435epoch 9/1036 100/100 |██████████| 625.37s · 6253.73 ms/step · 10 sample/s · 10 clip/s · loss: 0.462737 100/100 — 625.4s 6254 ms/step · accuracy: 0.8466 · loss: 0.4179 · val_accuracy: 0.8387 · val_loss: 0.48373839epoch 10/1040 100/100 |██████████| 626.66s · 6266.61 ms/step · 10 sample/s · 10 clip/s · loss: 0.264541 100/100 — 626.7s 6267 ms/step · accuracy: 0.8633 · loss: 0.3874 · val_accuracy: 0.8438 · val_loss: 0.47444243Summary:44 loss: initial 2.169622 · final 0.264475 · mean 0.76119645 Wall: 6727.78 ms/step · 10 sample/s · 10 clip/s46 GPU (commands_training_step): mean 6552.149 ms/step · p50 6301.367 · p95 7600.801 · min 5730.167 · max 22208.496 · 10 sample/s · 10 clip/s · wall-GPU gap 3%47 run: 6727.78s · 1000 steps · batch 644849Compiled step: 33 nodes · 999 cache hits50Test accuracy: 83.50% · test loss: 0.52028951WAV prediction: no (74.30%)52
TensorFlow reports 82.33% test accuracy and 0.513843 test loss for its published run. It uses a different split, so compare these numbers as separate experiments. TensorFlow test results
5. Evaluate on the test split
After training, compute sample-weighted loss and accuracy over the 800 held-out
clips. The confusion matrix counts true labels down the rows and predictions
across the columns. Its diagonal sum must match OA's device-side count of
correct predictions. A uniform eight-way guess has a cross-entropy of
ln(8) ≈ 2.0794.
6. Predict the command in a WAV file
The example writes a held-out no clip to sample.wav and decodes it
through the inference path. Pass --wav PATH to use a different recording.
OA decodes to mono, resamples to 16 kHz when needed, and pads or trims to one
second. Apply the same STFT, resize, and standardization, then use softmax
on the eight logits.
7. Save and reload inference
The run writes commands.oam and preprocessing.json to
var/tutorials/audio_commands/rust/ by default. It reloads the model,
optimizer, and normalization statistics and verifies that the same waveform
gives identical scores. Run the saved classifier on a WAV file without
loading the dataset or training again.
cargo run --release --example tu_ml_audio_commands -- --load var/tutorials/audio_commands/rust --wav path/to/clip.wav
To regenerate the figures from the Rust run, use the shared plot script
with an environment containing oapython.
python src/py/tutorials/ml/tu_ml_audio_commands/plots.py \var/tutorials/audio_commands/rust src/rs/tutorials/ml/tu_ml_audio_commands/asset
Attribution
The walkthrough adapts the experiment from Google's Simple audio recognition tutorial. Google distributes the tutorial prose under CC BY 4.0 and its code samples under Apache 2.0. The OA examples and plots were generated independently. Google's mini Speech Commands recordings are distributed under CC BY 4.0. See the dataset paper for collection details.
Example
1//! Train and inspect the TensorFlow mini Speech Commands workload with OA.23use std::{4 path::{Path, PathBuf},5 rc::Rc,6};78use anyhow::{Context, Result, ensure};9use oa::{10 Audio, AudioChannelLayout, Image, Matrix, Runtime,11 audio::{ResampleConfig, StftConfig},12 image::{ImageFormat, ImageLayout, InterpolationMode},13 ml::{14 self, AdamW, GradientTape, ItTraining, ItTrainingConfig, LossMetric, Module, ProgressBar,15 TrainingSummary, nn,16 },17};18use oads::{MiniSpeechCommands, MiniSpeechCommandsConfig};19use serde_json::json;2021const COMMANDS: [&str; 8] = ["down", "go", "left", "no", "right", "stop", "up", "yes"];22const SAMPLES: usize = 16_000;23const FRAMES: usize = 124;24const BINS: usize = 129;25const SIDE: usize = 32;26const SEED: u64 = 42;27const CHUNK: usize = 64;2829fn arg(flag: &str) -> Option<String> {30 std::env::args().skip_while(|value| value != flag).nth(1)31}3233fn shuffled(count: usize, seed: u64) -> Result<Vec<usize>> {34 let mut order = (0..count as i64).collect::<Vec<_>>();35 oa::data::shuffle(&mut order, seed)?;36 Ok(order.into_iter().map(|index| index as usize).collect())37}3839fn waveforms(dataset: &MiniSpeechCommands, rows: &[usize]) -> Result<Vec<f32>> {40 let indices = rows.iter().map(|&index| index as u32).collect::<Vec<_>>();41 let indices = Matrix::new_from_slice([indices.len()], &indices)?;42 Ok(43 dataset44 .samples()45 .reshape([8000, SAMPLES])?46 .gather(&indices)?47 .read_f32()?,48 )49}5051fn spectrogram(rows: &[f32], runtime: &Runtime) -> Result<Matrix> {52 let batch = rows.len() / SAMPLES;53 let audio = Audio::new_from_planar_f32(54 runtime,55 rows,56 batch,57 SAMPLES as u32,58 AudioChannelLayout::Unknown,59 )?;60 let magnitude = audio.stft(StftConfig {61 fft_size: 256,62 hop_size: 128,63 win_size: 255,64 center: false,65 ..Default::default()66 })?;67 ensure!(68 magnitude.shape() == [batch, FRAMES, BINS],69 "unexpected STFT geometry"70 );71 Ok(magnitude.reshape([batch, 1, FRAMES, BINS])?)72}7374fn resize(magnitude: Matrix) -> Result<Matrix> {75 let image = Image::new(magnitude, ImageLayout::Nchw, ImageFormat::Gray)?;76 Ok(77 image78 .resize(SIDE as u32, SIDE as u32, InterpolationMode::Bilinear)?79 .into_matrix(),80 )81}8283fn extract(84 dataset: &MiniSpeechCommands,85 indices: &[usize],86 runtime: &Runtime,87 fit: bool,88) -> Result<(Vec<f32>, f32, f32)> {89 let mut features = Vec::with_capacity(indices.len() * SIDE * SIDE);90 let (mut sum, mut squared) = (0.0, 0.0);91 for rows in indices.chunks(CHUNK) {92 let magnitude = spectrogram(&waveforms(dataset, rows)?, runtime)?;93 if fit {94 for value in magnitude.read_f32()? {95 let value = f64::from(value);96 sum += value;97 squared += value * value;98 }99 }100 features.extend(resize(magnitude)?.read_f32()?);101 }102 let count = (indices.len() * FRAMES * BINS) as f64;103 let mean = sum / count;104 let inv_std = (squared / count - mean * mean)105 .max(0.0)106 .sqrt()107 .max(1e-7)108 .recip();109 Ok((features, mean as f32, inv_std as f32))110}111112fn classifier(runtime: &Runtime) -> Result<nn::Sequential> {113 let mut model = nn::Sequential::new();114 model.add_named(115 "conv1",116 Rc::new(nn::Conv2d::new_with_seed_on(117 runtime, 1, 32, 3, 1, 0, 1, SEED,118 )?),119 )?;120 model.add_named("relu1", Rc::new(nn::Relu::new()))?;121 model.add_named(122 "conv2",123 Rc::new(nn::Conv2d::new_with_seed_on(124 runtime,125 32,126 64,127 3,128 1,129 0,130 1,131 SEED + 1,132 )?),133 )?;134 model.add_named("relu2", Rc::new(nn::Relu::new()))?;135 model.add_named("pool", Rc::new(nn::MaxPool2d::new(2)?))?;136 model.add_named(137 "drop1",138 Rc::new(nn::Dropout::new_with_seed(0.25, SEED + 4)?),139 )?;140 model.add_named("flatten", Rc::new(nn::Flatten::new(1, -1)))?;141 model.add_named(142 "dense1",143 Rc::new(nn::Linear::new_with_seed_on(144 runtime,145 64 * 14 * 14,146 128,147 SEED + 2,148 )?),149 )?;150 model.add_named("relu3", Rc::new(nn::Relu::new()))?;151 model.add_named("drop2", Rc::new(nn::Dropout::new_with_seed(0.5, SEED + 5)?))?;152 model.add_named(153 "dense2",154 Rc::new(nn::Linear::new_with_seed_on(155 runtime,156 128,157 COMMANDS.len(),158 SEED + 3,159 )?),160 )?;161 Ok(model)162}163164fn argmax(scores: &[f32]) -> usize {165 scores166 .iter()167 .enumerate()168 .rev()169 .max_by(|a, b| a.1.total_cmp(b.1))170 .expect("nonempty scores")171 .0172}173174type Confusion = [[u32; COMMANDS.len()]; COMMANDS.len()];175176fn evaluate(177 model: &impl Module,178 features: &[f32],179 labels: &[u32],180 batch: usize,181 confusion: bool,182) -> Result<(f64, f64, Confusion)> {183 let mut correct = 0_u64;184 let mut loss_sum = 0.0;185 let mut table = [[0; COMMANDS.len()]; COMMANDS.len()];186 for (block, targets) in labels.chunks(batch).enumerate() {187 let begin = block * batch * SIDE * SIDE;188 let end = begin + targets.len() * SIDE * SIDE;189 let input = Matrix::new_from_slice([targets.len(), 1, SIDE, SIDE], &features[begin..end])?;190 let target = Matrix::new_from_slice([targets.len()], targets)?;191 let logits = model.forward(&input)?;192 correct += u64::from(logits.categorical_accuracy_count(&target)?.read::<u32>()?[0]);193 loss_sum +=194 f64::from(ml::loss::cross_entropy(&logits, &target)?.read_f32()?[0]) * targets.len() as f64;195 if confusion {196 let scores = logits.read_f32()?;197 let (rows, remainder) = scores.as_chunks::<{ COMMANDS.len() }>();198 ensure!(199 rows.len() == targets.len() && remainder.is_empty(),200 "invalid logits shape"201 );202 for (&label, row) in targets.iter().zip(rows) {203 table[label as usize][argmax(row)] += 1;204 }205 }206 }207 if confusion {208 ensure!(209 (0..COMMANDS.len())210 .map(|i| u64::from(table[i][i]))211 .sum::<u64>()212 == correct,213 "confusion matrix disagrees with OA accuracy"214 );215 }216 Ok((217 correct as f64 / labels.len() as f64,218 loss_sum / labels.len() as f64,219 table,220 ))221}222223fn predict(224 model: &impl Module,225 waveform: &[f32],226 runtime: &Runtime,227 mean: f32,228 inv_std: f32,229) -> Result<Vec<f32>> {230 let mut features = resize(spectrogram(waveform, runtime)?)?.read_f32()?;231 oasdk::ml::audio::standardize(&mut features, mean, inv_std);232 let input = Matrix::new_from_slice([1, 1, SIDE, SIDE], &features)?;233 Ok(model.forward(&input)?.softmax(-1)?.read_f32()?)234}235236fn read_waveform(path: &Path) -> Result<Vec<f32>> {237 let mut mono = oa::audio::decode_file(path)?.to_mono()?;238 if mono.sample_rate() != SAMPLES as u32 {239 mono = mono.resample(ResampleConfig {240 out_rate: SAMPLES as u32,241 ..Default::default()242 })?;243 }244 let mut waveform = mono.as_matrix().read_f32()?;245 waveform.resize(SAMPLES, 0.0);246 Ok(waveform)247}248249fn new_optimizer(model: &impl Module) -> Result<AdamW> {250 Ok(AdamW::new_with_hyperparameters(251 model.all_parameters()?,252 0.001,253 0.9,254 0.999,255 1e-7,256 0.0,257 )?)258}259260fn load_classifier(261 directory: &Path,262 runtime: &Runtime,263) -> Result<(nn::Sequential, AdamW, [f32; 2])> {264 let model = classifier(runtime)?;265 model.eval();266 let mut optimizer = new_optimizer(&model)?;267 ml::load_checkpoint(directory.join("commands.oam"), &model, &mut optimizer)?;268 let stats: serde_json::Value =269 serde_json::from_slice(&std::fs::read(directory.join("preprocessing.json"))?)?;270 let mean = stats["mean"].as_f64().context("missing mean")? as f32;271 let inv_std = stats["inv_std"]272 .as_f64()273 .context("missing inverse standard deviation")? as f32;274 Ok((model, optimizer, [mean, inv_std]))275}276277fn report_prediction(scores: &[f32]) {278 let choice = argmax(scores);279 println!(280 "WAV prediction: {} ({:.2}%)",281 COMMANDS[choice],282 100.0 * scores[choice]283 );284}285286fn main() -> Result<()> {287 let epochs = arg("--epochs").map_or(Ok(10), |value| value.parse::<usize>())?;288 let batch = arg("--batch").map_or(Ok(64), |value| value.parse::<usize>())?;289 let step_limit = arg("--steps")290 .map(|value| value.parse::<usize>())291 .transpose()?;292 ensure!(293 epochs >= 1 && (1..=128).contains(&batch) && step_limit.is_none_or(|steps| steps >= 3),294 "require epochs >= 1, batch in 1..128, and at least three replay smoke steps"295 );296 let mut builder = Runtime::builder();297 if let Some(index) = arg("--device") {298 builder = builder.devices(oa::DeviceSelection::Index(index.parse()?));299 }300 let runtime = builder.build()?;301 Runtime::set_default(runtime.clone());302 let wav = arg("--wav").map(PathBuf::from);303 if let Some(directory) = arg("--load") {304 let path = wav.as_deref().context("--load requires --wav")?;305 let (model, _, [mean, inv_std]) = load_classifier(Path::new(&directory), &runtime)?;306 let scores = predict(&model, &read_waveform(path)?, &runtime, mean, inv_std)?;307 report_prediction(&scores);308 return Ok(());309 }310 let output = arg("--output").map_or_else(311 || PathBuf::from("var/tutorials/audio_commands/rust"),312 PathBuf::from,313 );314 std::fs::create_dir_all(&output)?;315 let dataset = MiniSpeechCommands::load_on(&runtime, &MiniSpeechCommandsConfig::default())?;316 ensure!(317 dataset.samples().shape() == [8000, 1, SAMPLES],318 "unexpected OADS pack dimensions"319 );320 let labels = dataset321 .labels()322 .read_f32()?323 .into_iter()324 .map(|value| value as u32)325 .collect::<Vec<_>>();326 ensure!(327 (0..COMMANDS.len() as u32)328 .all(|label| labels.iter().filter(|&&value| value == label).count() == 1000),329 "unexpected command distribution in the OADS pack"330 );331 let order = shuffled(8000, SEED)?;332 let (train_idx, held_out) = order.split_at(6400);333 let (val_idx, test_idx) = held_out.split_at(800);334 println!("Split: 6400 train · 800 validation · 800 test");335 let clips = waveforms(&dataset, &train_idx[..9])?;336 let preview = json!({337 "commands": COMMANDS, "labels": train_idx[..9].iter().map(|&i| labels[i]).collect::<Vec<_>>(),338 "spectrograms": spectrogram(&clips, &runtime)?.read_f32()?, "waveforms": clips,339 });340 std::fs::write(output.join("preview.json"), serde_json::to_vec(&preview)?)?;341 if std::env::args().any(|value| value == "--preview-only") {342 return Ok(());343 }344 let (mut train_features_host, mean, inv_std) = extract(&dataset, train_idx, &runtime, true)?;345 let (mut val_features, _, _) = extract(&dataset, val_idx, &runtime, false)?;346 let (mut test_features, _, _) = extract(&dataset, test_idx, &runtime, false)?;347 for split in [348 &mut train_features_host,349 &mut val_features,350 &mut test_features,351 ] {352 oasdk::ml::audio::standardize(split, mean, inv_std);353 }354 let labels_for = |indices: &[usize]| {355 indices356 .iter()357 .map(|&index| labels[index])358 .collect::<Vec<_>>()359 };360 let (train_labels_host, val_labels, test_labels) = (361 labels_for(train_idx),362 labels_for(val_idx),363 labels_for(test_idx),364 );365 let no_index = test_idx366 .iter()367 .copied()368 .find(|&index| COMMANDS[labels[index] as usize] == "no")369 .context("missing test clip for no")?;370 let waveform = waveforms(&dataset, &[no_index])?;371 drop(dataset);372 let source_label = wav.is_none().then_some("no");373 let path = match wav {374 Some(path) => path,375 None => {376 let path = output.join("sample.wav");377 let clip = Audio::new_from_planar_f32(378 &runtime,379 &waveform,380 1,381 SAMPLES as u32,382 AudioChannelLayout::Mono,383 )?;384 oa::audio::save_wav_f32(&path, &clip)?;385 path386 }387 };388 let waveform = read_waveform(&path)?;389 let model = classifier(&runtime)?;390 ensure!(391 model.num_parameters()? == 1_625_608,392 "unexpected CNN parameter count"393 );394 model.train(true);395 runtime.checkpoint()?.wait()?;396 let mut optimizer = new_optimizer(&model)?;397 let windows = train_idx.len() / batch;398 let steps = step_limit.unwrap_or(epochs * windows);399 let clip_feature_len = SIDE * SIDE;400 let mut loss_metric = LossMetric::default();401 let mut progress = ProgressBar::default();402 let mut summary_callback = TrainingSummary::default();403 let mut training = ItTraining::new(404 &runtime,405 &mut optimizer,406 ItTrainingConfig {407 total_steps: steps as u64,408 steps_per_epoch: windows as u64,409 batch_size: batch as u64,410 source_unit: "clip".into(),411 timer_name: "commands_training_step".into(),412 enable_gpu_timing: true,413 ..ItTrainingConfig::default()414 },415 )?;416 training.add_metric(&mut loss_metric);417 training.add_callback(&mut progress);418 training.add_callback(&mut summary_callback);419420 let mut history = Vec::new();421 let mut best_loss = f64::INFINITY;422 let mut stale_epochs = 0;423 let mut order = Vec::new();424 // The per-step accuracy count is recorded as an extra program output and425 // read back after each step — the same readback the loss metric uses.426 let step_correct = std::cell::RefCell::new(Option::<oa::Matrix>::None);427 let mut epoch_correct = 0_u64;428 let mut epoch_clips = 0_u64;429 for step in 0..steps {430 training.record_source_units(batch as u64);431 if step % windows == 0 {432 order = shuffled(train_idx.len(), SEED + (step / windows) as u64)?;433 }434 assert!(training.step(435 || {436 let begin = (step % windows) * batch;437 let rows = &order[begin..begin + batch];438 let mut values = Vec::with_capacity(batch * clip_feature_len);439 let mut labels = Vec::with_capacity(batch);440 for &row in rows {441 values.extend_from_slice(442 &train_features_host[row * clip_feature_len..(row + 1) * clip_feature_len],443 );444 labels.push(train_labels_host[row]);445 }446 let input = Matrix::new_from_slice([batch, 1, SIDE, SIDE], &values)?;447 let target = Matrix::new_from_slice([batch], &labels)?;448 Ok((input, target))449 },450 |(input, target)| {451 let tape = GradientTape::new();452 let logits = model.forward(&input)?;453 let loss = oa::ml::loss::cross_entropy(&logits, &target)?;454 tape.backward(&loss)?;455 *step_correct.borrow_mut() =456 Some(oa::matrix::categorical_accuracy_count(&logits, &target)?);457 Ok(loss)458 },459 )?);460 if let Some(count) = &*step_correct.borrow() {461 epoch_correct += count.read::<u32>()?[0] as u64;462 }463 epoch_clips += batch as u64;464 let snapshot = training.snapshot();465 if snapshot.is_epoch_boundary() {466 model.eval();467 let (val_accuracy, val_loss, _) = evaluate(&model, &val_features, &val_labels, batch, false)?;468 model.train(true);469 let seconds = snapshot.epoch_elapsed().as_secs_f64();470 println!(471 " {}/{} — {seconds:.1}s {:.0} ms/step · accuracy: {:.4} · loss: {:.4} · val_accuracy: {val_accuracy:.4} · val_loss: {val_loss:.4}",472 snapshot.step_in_epoch(),473 snapshot.steps_in_epoch(),474 seconds * 1e3 / snapshot.steps_in_epoch().max(1) as f64,475 epoch_correct as f64 / epoch_clips.max(1) as f64,476 snapshot.epoch_mean_loss(),477 );478 history.push(json!({479 "loss": snapshot.epoch_mean_loss(), "accuracy": epoch_correct as f64 / epoch_clips as f64,480 "val_loss": val_loss, "val_accuracy": val_accuracy,481 }));482 if val_loss < best_loss {483 best_loss = val_loss;484 stale_epochs = 0;485 } else {486 stale_epochs += 1;487 if stale_epochs >= 2 {488 println!("Early stopping after two epochs without validation loss improvement");489 break;490 }491 }492 epoch_correct = 0;493 epoch_clips = 0;494 }495 }496 let diagnostics = training497 .training_program()498 .map(|program| program.diagnostics());499 let fallbacks = training.program_capture_fallback_count();500 let result = training.finish()?;501 let diagnostics = diagnostics.context("training capture did not produce a compiled step")?;502 ensure!(503 diagnostics.command_cache_hit_count() > 0 && fallbacks == 0,504 "expected cached training replay, observed {fallbacks} fallbacks"505 );506 ensure!(507 u64::from(optimizer.step_count()) == result.step_count(),508 "optimizer update count mismatch"509 );510 println!(511 "Compiled step: {} nodes · {} cache hits",512 diagnostics.node_count(),513 diagnostics.command_cache_hit_count()514 );515 model.eval();516 let (accuracy, loss, confusion) = evaluate(&model, &test_features, &test_labels, batch, true)?;517 let scores = predict(&model, &waveform, &runtime, mean, inv_std)?;518 ensure!(519 (scores.iter().sum::<f32>() - 1.0).abs() < 2e-5,520 "invalid softmax"521 );522 println!(523 "Test accuracy: {:.2}% · test loss: {loss:.6}",524 accuracy * 100.0525 );526 report_prediction(&scores);527528 let checkpoint = output.join("commands.oam");529 ml::save_checkpoint(&checkpoint, &model, &optimizer)?;530 let stats = output.join("preprocessing.json");531 std::fs::write(532 &stats,533 serde_json::to_vec(&json!({"mean": mean, "inv_std": inv_std}))?,534 )?;535 let (reloaded, reloaded_optimizer, [saved_mean, saved_inv_std]) =536 load_classifier(&output, &runtime)?;537 ensure!(538 predict(&reloaded, &waveform, &runtime, saved_mean, saved_inv_std)? == scores,539 "reload changed inference"540 );541 ensure!(542 reloaded_optimizer.step_count() == optimizer.step_count(),543 "reload changed optimizer step count"544 );545 let results = json!({546 "history": history, "test_accuracy": accuracy, "test_loss": loss, "confusion": confusion,547 "scores": scores, "waveform": waveform, "source_label": source_label,548 "steps": result.step_count(), "cache_hits": diagnostics.command_cache_hit_count(),549 });550 std::fs::write(output.join("results.json"), serde_json::to_vec(&results)?)?;551 Ok(())552}553
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.