Realm

Ml Resnet

Runnable OA SDK tutorial.

Rust

Example

Tu_ml_resnet.rs

1use oa::ml::{ItTraining, ItTrainingConfig, LossMetric, Module, ProgressBar, TrainingSummary};
2use oa::{Cli, LogMetrics};
3
4// Synthetic 3-class image task shared with tu_ml_vit: horizontal bar,
5// vertical bar, or diagonal stripe on a 16x16 grayscale grid with light
6// noise. The residual network keeps the full [B, C, H, W] contract.
7const IMAGE_SIDE: usize = 16;
8const CHANNELS: usize = 8;
9const NUM_CLASSES: usize = 3;
10const TRAINING_STEPS: usize = 200;
11const BATCH_SIZE: usize = 32;
12const EVAL_IMAGES: usize = 64;
13
14#[derive(Default)]
15struct ResNetConfig {
16 steps: u64,
17 batch: u64,
18 lr: f32,
19}
20
21struct ShapeRng(u64);
22
23impl ShapeRng {
24 fn new(seed: u64) -> Self {
25 Self(seed | 1)
26 }
27
28 fn next(&mut self) -> u64 {
29 self.0 = self
30 .0
31 .wrapping_mul(6364136223846793005)
32 .wrapping_add(1442695040888963407);
33 self.0 >> 11
34 }
35
36 fn unit(&mut self) -> f32 {
37 (self.next() % (1 << 24)) as f32 / ((1 << 24) as f32)
38 }
39
40 fn below(&mut self, bound: usize) -> usize {
41 (self.next() % bound as u64) as usize
42 }
43}
44
45fn next_batch(rng: &mut ShapeRng, batch: usize) -> (Vec<f32>, Vec<u32>) {
46 let mut images = vec![0.0_f32; batch * IMAGE_SIDE * IMAGE_SIDE];
47 let mut labels = Vec::with_capacity(batch);
48 for image in 0..batch {
49 let class = rng.below(NUM_CLASSES) as u32;
50 labels.push(class);
51 let base = image * IMAGE_SIDE * IMAGE_SIDE;
52 for pixel in 0..IMAGE_SIDE * IMAGE_SIDE {
53 images[base + pixel] = 0.05 * rng.unit();
54 }
55 match class {
56 0 => {
57 let row = 2 + rng.below(IMAGE_SIDE - 4);
58 for column in 0..IMAGE_SIDE {
59 images[base + row * IMAGE_SIDE + column] = 0.85 + 0.1 * rng.unit();
60 }
61 }
62 1 => {
63 let column = 2 + rng.below(IMAGE_SIDE - 4);
64 for row in 0..IMAGE_SIDE {
65 images[base + row * IMAGE_SIDE + column] = 0.85 + 0.1 * rng.unit();
66 }
67 }
68 _ => {
69 let offset = 1 + rng.below(2);
70 for diagonal in 0..IMAGE_SIDE {
71 let column = diagonal + offset;
72 if column < IMAGE_SIDE {
73 images[base + diagonal * IMAGE_SIDE + column] = 0.85 + 0.1 * rng.unit();
74 }
75 }
76 }
77 }
78 }
79 (images, labels)
80}
81
82// Standard residual stage: conv-bn-relu-conv-bn plus an identity skip,
83// then a final relu. Channel counts stay constant so no projection skip
84// is required.
85struct ResidualBlock {
86 conv_a: oa::ml::nn::Conv2d,
87 norm_a: oa::ml::nn::BatchNorm2d,
88 relu_a: oa::ml::nn::Relu,
89 conv_b: oa::ml::nn::Conv2d,
90 norm_b: oa::ml::nn::BatchNorm2d,
91 relu_out: oa::ml::nn::Relu,
92}
93
94impl ResidualBlock {
95 fn new(runtime: &oa::Runtime, seed: u64) -> oa::Result<Self> {
96 Ok(Self {
97 conv_a: oa::ml::nn::Conv2d::new_with_seed_on(runtime, CHANNELS, CHANNELS, 3, 1, 1, 1, seed)?,
98 norm_a: oa::ml::nn::BatchNorm2d::new_on(runtime, CHANNELS)?,
99 relu_a: oa::ml::nn::Relu::new(),
100 conv_b: oa::ml::nn::Conv2d::new_with_seed_on(
101 runtime,
102 CHANNELS,
103 CHANNELS,
104 3,
105 1,
106 1,
107 1,
108 seed.wrapping_add(1),
109 )?,
110 norm_b: oa::ml::nn::BatchNorm2d::new_on(runtime, CHANNELS)?,
111 relu_out: oa::ml::nn::Relu::new(),
112 })
113 }
114
115 fn forward(&self, input: &oa::Matrix) -> oa::Result<oa::Matrix> {
116 let hidden = self
117 .relu_a
118 .forward(&self.norm_a.forward(&self.conv_a.forward(input)?)?)?;
119 let hidden = self.norm_b.forward(&self.conv_b.forward(&hidden)?)?;
120 self.relu_out.forward(&oa::matrix::add(&hidden, input)?)
121 }
122
123 fn all_parameters(&self) -> oa::Result<Vec<oa::ml::Parameter>> {
124 let mut parameters = self.conv_a.all_parameters()?;
125 parameters.extend(self.norm_a.all_parameters()?);
126 parameters.extend(self.conv_b.all_parameters()?);
127 parameters.extend(self.norm_b.all_parameters()?);
128 Ok(parameters)
129 }
130}
131
132struct ResNet {
133 stem_conv: oa::ml::nn::Conv2d,
134 stem_norm: oa::ml::nn::BatchNorm2d,
135 stem_relu: oa::ml::nn::Relu,
136 blocks: Vec<ResidualBlock>,
137 pool: oa::ml::nn::AdaptiveAvgPool2d,
138 flatten: oa::ml::nn::Flatten,
139 head: oa::ml::nn::Linear,
140}
141
142impl ResNet {
143 fn new(runtime: &oa::Runtime, seed: u64) -> oa::Result<Self> {
144 let stem_conv = oa::ml::nn::Conv2d::new_with_seed_on(runtime, 1, CHANNELS, 3, 1, 1, 1, seed)?;
145 let stem_norm = oa::ml::nn::BatchNorm2d::new_on(runtime, CHANNELS)?;
146 let stem_relu = oa::ml::nn::Relu::new();
147 let mut blocks = Vec::new();
148 for layer in 0..2_usize {
149 blocks.push(ResidualBlock::new(
150 runtime,
151 seed.wrapping_add(3 + layer as u64 * 2),
152 )?);
153 }
154 let pool = oa::ml::nn::AdaptiveAvgPool2d::new(1)?;
155 let flatten = oa::ml::nn::Flatten::new(1, -1);
156 let head =
157 oa::ml::nn::Linear::new_with_seed_on(runtime, CHANNELS, NUM_CLASSES, seed.wrapping_add(9))?;
158 Ok(Self {
159 stem_conv,
160 stem_norm,
161 stem_relu,
162 blocks,
163 pool,
164 flatten,
165 head,
166 })
167 }
168
169 fn all_parameters(&self) -> oa::Result<Vec<oa::ml::Parameter>> {
170 let mut parameters = self.stem_conv.all_parameters()?;
171 parameters.extend(self.stem_norm.all_parameters()?);
172 for block in &self.blocks {
173 parameters.extend(block.all_parameters()?);
174 }
175 parameters.extend(self.head.all_parameters()?);
176 Ok(parameters)
177 }
178
179 fn num_parameters(&self) -> oa::Result<usize> {
180 Ok(
181 self
182 .all_parameters()?
183 .iter()
184 .map(|parameter| parameter.data().shape().iter().product::<usize>())
185 .sum(),
186 )
187 }
188
189 // `input` is NCHW [B, 1, IMAGE_SIDE, IMAGE_SIDE]; logits are [B, C].
190 fn forward(&self, input: &oa::Matrix) -> oa::Result<oa::Matrix> {
191 let mut hidden = self
192 .stem_relu
193 .forward(&self.stem_norm.forward(&self.stem_conv.forward(input)?)?)?;
194 for block in &self.blocks {
195 hidden = block.forward(&hidden)?;
196 }
197 let pooled = self.pool.forward(&hidden)?;
198 let features = self.flatten.forward(&pooled)?;
199 self.head.forward(&features)
200 }
201}
202
203fn accuracy(logits: &oa::Matrix, labels: &[u32], batch: usize) -> oa::Result<f32> {
204 let values = logits.read_f32()?;
205 let correct = (0..batch)
206 .filter(|item| {
207 let row = &values[item * NUM_CLASSES..(item + 1) * NUM_CLASSES];
208 let prediction = row
209 .iter()
210 .enumerate()
211 .max_by(|left, right| left.1.total_cmp(right.1))
212 .map(|(index, _)| index as u32)
213 .expect("nonempty class logits");
214 prediction == labels[*item]
215 })
216 .count();
217 Ok(correct as f32 / batch as f32)
218}
219
220fn main() -> oa::Result<()> {
221 let mut cli = Cli::new("tu_ml_resnet", "OA Tutorial — Residual ConvNet");
222 cli.add_option(
223 "--steps",
224 |c: &mut ResNetConfig| &mut c.steps,
225 "training steps",
226 );
227 cli.add_option("--batch", |c: &mut ResNetConfig| &mut c.batch, "batch size");
228 cli.add_option("--lr", |c: &mut ResNetConfig| &mut c.lr, "learning rate");
229 if !cli.parse() {
230 return Ok(());
231 }
232 let steps = if cli.config().steps > 0 {
233 cli.config().steps as usize
234 } else {
235 TRAINING_STEPS
236 };
237 let batch = if cli.config().batch > 0 {
238 cli.config().batch as usize
239 } else {
240 BATCH_SIZE
241 };
242 let lr = if cli.config().lr > 0.0 {
243 cli.config().lr
244 } else {
245 0.005
246 };
247
248 let runtime = oa::Runtime::new()?;
249 oa::Runtime::set_default(runtime.clone());
250 let model = ResNet::new(&runtime, 0x7E57)?;
251 let mut optimizer = oa::ml::AdamW::new(model.all_parameters()?, lr)?;
252 let mut rng = ShapeRng::new(0x5EED_7E57);
253
254 println!("\n╔══════════════════════════════════════════════════════════════════╗");
255 println!("║ OA Tutorial — Residual ConvNet · conv + BN + skip (autograd) ║");
256 println!("╚══════════════════════════════════════════════════════════════════╝\n");
257 println!("task: classify a 16x16 image as horizontal bar, vertical bar, or diagonal");
258 println!("model: conv stem + 2 residual blocks + global pool + linear head");
259 println!(
260 "params: {} Optimizer: AdamW(lr={lr})\n",
261 model.num_parameters()?
262 );
263 println!("training: {steps} steps · batch={batch} · input=[B,1,{IMAGE_SIDE},{IMAGE_SIDE}]");
264
265 let mut loss_metric = LossMetric::default();
266 let mut progress = ProgressBar::default();
267 let mut summary_callback = TrainingSummary::default();
268 let mut training = ItTraining::new(
269 &runtime,
270 &mut optimizer,
271 ItTrainingConfig {
272 total_steps: steps as u64,
273 batch_size: batch as u64,
274 sequence_length: (IMAGE_SIDE * IMAGE_SIDE) as u64,
275 sequence_unit: "pixel".into(),
276 timer_name: "resnet_training_step".into(),
277 enable_gpu_timing: true,
278 ..ItTrainingConfig::default()
279 },
280 )?;
281 training.add_metric(&mut loss_metric);
282 training.add_callback(&mut progress);
283 training.add_callback(&mut summary_callback);
284
285 let mut metrics = LogMetrics::new();
286 let log_dir = oa::Path::var_rel("log/vision/resnet");
287 if let Err(e) = metrics.open(&log_dir) {
288 eprintln!("[OA] metrics unavailable: {e}");
289 }
290
291 let mut initial_loss = 0.0_f32;
292 for _ in 0..steps {
293 assert!(training.step(
294 || {
295 let (images, labels) = next_batch(&mut rng, batch);
296 Ok((
297 oa::Matrix::new_from_f32([batch, 1, IMAGE_SIDE, IMAGE_SIDE], &images)?,
298 oa::Matrix::new_from_slice([batch], &labels)?,
299 ))
300 },
301 |(images, labels)| {
302 let tape = oa::ml::GradientTape::new();
303 let logits = model.forward(&images)?;
304 let loss = oa::ml::loss::cross_entropy(&logits, &labels)?;
305 tape.backward(&loss)?;
306 Ok(loss)
307 },
308 )?);
309 let snap = training.snapshot();
310 if snap.step_count() == 1 {
311 initial_loss = snap.last_loss().unwrap_or_default();
312 }
313 if let Some(loss) = snap.last_loss() {
314 metrics.log_scalar("loss", snap.step_count() as i64, loss as f64);
315 }
316 }
317 let program_diagnostics = training
318 .training_program()
319 .map(|program| program.diagnostics());
320 let training_result = training.finish()?;
321 let final_training_loss = training_result.last_loss().unwrap_or_default();
322
323 // Evaluation shares the training-mode batch-statistics BatchNorm path:
324 // running statistics freeze at program-record time under captured replay,
325 // so the honest eval metric normalizes over the 64-image eval batch.
326 let (eval_images, eval_labels) = next_batch(&mut rng, EVAL_IMAGES);
327 let images = oa::Matrix::new_from_f32([EVAL_IMAGES, 1, IMAGE_SIDE, IMAGE_SIDE], &eval_images)?;
328 let labels = oa::Matrix::new_from_slice([EVAL_IMAGES], &eval_labels)?;
329 let logits = model.forward(&images)?;
330 let evaluation_loss = oa::ml::loss::cross_entropy(&logits, &labels)?.read_f32()?[0];
331 let evaluation_accuracy = accuracy(&logits, &eval_labels, EVAL_IMAGES)?;
332
333 println!("\nEvaluation (batch-statistics BatchNorm):");
334 println!(
335 " random-loss baseline ln({NUM_CLASSES}) = {:.4}",
336 (NUM_CLASSES as f64).ln()
337 );
338 println!(" loss: evaluation {evaluation_loss:.6} · last training {final_training_loss:.6}");
339 println!(" image accuracy: {:.1}%", evaluation_accuracy * 100.0);
340 println!(" steps: {steps} · batch: {batch} · lr: {lr}");
341 if let Some(diagnostics) = program_diagnostics {
342 println!(
343 " program: {} nodes · {} recording · {} cache hits · {} uploads",
344 diagnostics.node_count(),
345 diagnostics.command_recording_count(),
346 diagnostics.command_cache_hit_count(),
347 diagnostics.input_upload_count(),
348 );
349 }
350 if initial_loss > 0.0 {
351 println!(
352 " loss improvement: {:.2}x ({initial_loss:.4} → {final_training_loss:.4})",
353 initial_loss / final_training_loss.max(1.0e-9)
354 );
355 }
356
357 let loss_baseline = (NUM_CLASSES as f32).ln() * 0.3;
358 assert!(
359 evaluation_loss < loss_baseline && evaluation_accuracy >= 0.95,
360 "resnet tutorial failed its convergence gate (loss {evaluation_loss:.6}, accuracy {:.3})",
361 evaluation_accuracy,
362 );
363 metrics.flush()?;
364 Ok(())
365}
366

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.