Realm

Fit a linear regression model in Rust

Current source-owned tutorial. API availability differs by language.

Rust · Python

Start the walkthrough · Jump to complete source

The smallest complete OA training loop: five scalar samples, one Linear layer, AdamW, and the ItTraining step lifecycle that captures the recorded step once and replays it for the rest of the schedule. This walkthrough follows the same experiment as the C++ tuMnistClassifierAg tutorial. The output below is from the Rust run with OA 0.18.0 on Intel Iris Xe with Mesa 26.3.1.

Run in Rust

From the OASDK root, with oa-dev as a sibling checkout:

cargo run --release --example tu_ml_basics

1. Create the training pair

The model learns the line y = 2x − 1 from five samples. Runtime::current() returns this thread's lazily initialized default runtime, and constructors that omit an explicit runtime upload on it.

1let runtime = Runtime::current()?;
2let x = Matrix::new_from_slice([SAMPLES, 1], &[-2.0, -1.0, 0.0, 1.0, 2.0])?;
3let target = Matrix::new_from_slice([SAMPLES, 1], &[-3.0, -1.0, 1.0, 3.0, 5.0])?;
4

2. Build the model and measure the initial loss

Linear::new_with_seed initializes weight and bias with a seeded Glorot uniform draw and a zero bias, giving two trainable parameters. AdamW receives weight decay 0.0 so the update matches plain Adam. An eager forward pass and mse give the loss before training.

1let model = Linear::new_with_seed(1, 1, 0)?;
2let mut optimizer = AdamW::new_with_hyperparameters(
3 model.all_parameters()?, 0.05, 0.9, 0.999, 1e-7, 0.0,
4)?;
5let initial_loss = f64::from(metric::scalar_loss(&loss::mse(&model.forward(&x)?, &target)?)?);
6

3. Drive the schedule through ItTraining

ItTraining::new borrows the default runtime and requires an AdamW optimizer: whole program capture is implemented for AdamW. The iterator owns step counting, epoch accounting, callback dispatch, and the capture and replay lifecycle. ProgressBar renders the progress bar for each epoch and TrainingSummary prints the final totals.

1let mut progress = ProgressBar::default();
2let mut summary = TrainingSummary::default();
3let mut training = ItTraining::new(
4 &runtime,
5 &mut optimizer,
6 ItTrainingConfig {
7 total_steps: STEPS,
8 steps_per_epoch: STEPS_PER_EPOCH,
9 batch_size: SAMPLES as u64,
10 ..ItTrainingConfig::default()
11 },
12)?;
13training.add_callback(&mut progress);
14training.add_callback(&mut summary);
15

4. Record one step, replay seventy nine

Each step uploads the batch's row indices through prepare, then record gathers the batch, runs forward, mse, and backward under a GradientTape and returns the loss. The first step runs eagerly; the second is captured into a compiled command that replays for every subsequent step. snapshot() reports the mean loss for the completed epoch.

1let admitted = training.step(
2 || Matrix::new_from_slice([SAMPLES], &rows),
3 |indices| {
4 let batch = x.gather(&indices)?;
5 let targets = target.gather(&indices)?;
6 let tape = GradientTape::new();
7 let prediction = model.forward(&batch)?;
8 let loss = loss::mse(&prediction, &targets)?;
9 tape.backward(&loss)?;
10 Ok(loss)
11 },
12)?;
13
1epoch 1/5
2 16/16 |██████████| 0.01s · 0.65 ms/step · 7.73K sample/s · loss: 0.0867
3 epoch 1: mean loss 0.74184
4
5…
6
7epoch 5/5
8 16/16 |██████████| 0.01s · 0.32 ms/step · 15.47K sample/s · loss: 0.0000
9 epoch 5: mean loss 0.00077
10

5. Check the replay and the fit

finish completes the lifecycle and returns the step totals; the diagnostics confirm the recorded step was compiled once and replayed 79 times without a capture fallback. The final assertions require the loss below 1% of its initial value and every prediction within 0.1 of the target.

1Summary:
2 loss: initial 1.903632 · final 0.000050 · mean 0.160425
3 Wall: 0.56 ms/step · 8.88K sample/s
4 run: 0.05s · 80 steps · batch 5
5Compiled step: 10 nodes · 79 cache hits
6loss: 1.903632 -> 0.000018
7[-3.0058205, -1.0049047, 0.9960111, 2.9969268, 4.997843]
8

The Python program runs the identical schedule and prints the same loss trajectory. Seeded initialization and the donor update kernels match across languages.

Source

Rust example · Full Python walkthrough

Example

1//! Fit a one-layer regression model with OA autograd and the ItTraining iterator.
2
3use anyhow::{Context, Result, ensure};
4use oa::ml::nn::Linear;
5use oa::ml::{
6 AdamW, GradientTape, ItTraining, ItTrainingConfig, Module, ProgressBar, TrainingSummary, loss,
7 metric,
8};
9use oa::{Matrix, Runtime};
10
11const SAMPLES: usize = 5;
12const EPOCHS: u64 = 5;
13const STEPS_PER_EPOCH: u64 = 16;
14const STEPS: u64 = EPOCHS * STEPS_PER_EPOCH;
15
16fn main() -> Result<()> {
17 let runtime = Runtime::current()?;
18 let x = Matrix::new_from_slice([SAMPLES, 1], &[-2.0, -1.0, 0.0, 1.0, 2.0])?;
19 let target = Matrix::new_from_slice([SAMPLES, 1], &[-3.0, -1.0, 1.0, 3.0, 5.0])?;
20
21 let model = Linear::new_with_seed(1, 1, 0)?;
22 let parameters = model.all_parameters()?;
23 ensure!(
24 parameters.len() == 2,
25 "expected one weight and one bias parameter"
26 );
27 let mut optimizer = AdamW::new_with_hyperparameters(parameters, 0.05, 0.9, 0.999, 1e-7, 0.0)?;
28
29 let initial_loss = f64::from(metric::scalar_loss(&loss::mse(
30 &model.forward(&x)?,
31 &target,
32 )?)?);
33
34 let mut progress = ProgressBar::default();
35 let mut summary = TrainingSummary::default();
36 let mut training = ItTraining::new(
37 &runtime,
38 &mut optimizer,
39 ItTrainingConfig {
40 total_steps: STEPS,
41 steps_per_epoch: STEPS_PER_EPOCH,
42 batch_size: SAMPLES as u64,
43 ..ItTrainingConfig::default()
44 },
45 )?;
46 training.add_callback(&mut progress);
47 training.add_callback(&mut summary);
48
49 let rows = (0..SAMPLES as u32).collect::<Vec<_>>();
50 for epoch in 1..=EPOCHS {
51 for _ in 0..STEPS_PER_EPOCH {
52 let admitted = training.step(
53 || Matrix::new_from_slice([SAMPLES], &rows),
54 |indices| {
55 let batch = x.gather(&indices)?;
56 let targets = target.gather(&indices)?;
57 let tape = GradientTape::new();
58 let prediction = model.forward(&batch)?;
59 let loss = loss::mse(&prediction, &targets)?;
60 tape.backward(&loss)?;
61 Ok(loss)
62 },
63 )?;
64 ensure!(admitted, "training stopped before the schedule finished");
65 }
66 println!(
67 " epoch {epoch}: mean loss {:.5}",
68 training.snapshot().epoch_mean_loss()
69 );
70 }
71
72 let diagnostics = training
73 .training_program()
74 .map(|program| program.diagnostics());
75 let fallbacks = training.program_capture_fallback_count();
76 let result = training.finish()?;
77 let diagnostics = diagnostics.context("training capture did not produce a compiled step")?;
78 ensure!(
79 diagnostics.command_cache_hit_count() > 0 && fallbacks == 0,
80 "expected cached training replay, observed {fallbacks} capture fallbacks"
81 );
82 ensure!(
83 result.step_count() == STEPS && u64::from(optimizer.step_count()) == STEPS,
84 "AdamW update count disagrees with the training schedule"
85 );
86 println!(
87 "Compiled step: {} nodes · {} cache hits",
88 diagnostics.node_count(),
89 diagnostics.command_cache_hit_count()
90 );
91
92 let final_loss = f64::from(metric::scalar_loss(&loss::mse(
93 &model.forward(&x)?,
94 &target,
95 )?)?);
96 let values = model.forward(&x)?.read_f32()?;
97
98 ensure!(
99 final_loss < initial_loss * 0.01,
100 "training loss did not fall"
101 );
102 let expected = [-3.0_f32, -1.0, 1.0, 3.0, 5.0];
103 ensure!(
104 values
105 .iter()
106 .zip(expected)
107 .all(|(&a, b)| (a - b).abs() < 0.1),
108 "predictions did not converge to the target line"
109 );
110
111 println!("loss: {initial_loss:.6} -> {final_loss:.6}");
112 println!("{values:?}");
113 Ok(())
114}
115

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.