Realm

Ml Vit

Runnable OA SDK tutorial.

Rust

Example

Tu_ml_vit.rs

1use oa::ml::{ItTraining, ItTrainingConfig, LossMetric, Module, ProgressBar, TrainingSummary};
2use oa::{Cli, LogMetrics};
3
4// Synthetic 3-class image task: horizontal bar, vertical bar, or diagonal
5// stripe on a 16x16 grayscale grid with light noise. Fixed geometry keeps
6// the contract free of padding; patches embed through a shared Linear.
7const IMAGE_SIDE: usize = 16;
8const PATCH_SIDE: usize = 4;
9const NUM_PATCHES: usize = (IMAGE_SIDE / PATCH_SIDE) * (IMAGE_SIDE / PATCH_SIDE); // 16
10const TOKENS: usize = NUM_PATCHES + 1; // 16 patches + 1 class token
11const NUM_CLASSES: usize = 3;
12const MODEL_WIDTH: usize = 32;
13const TRAINING_STEPS: usize = 200;
14const BATCH_SIZE: usize = 32;
15const EVAL_IMAGES: usize = 64;
16
17#[derive(Default)]
18struct VitConfig {
19 steps: u64,
20 batch: u64,
21 lr: f32,
22}
23
24struct ShapeRng(u64);
25
26impl ShapeRng {
27 fn new(seed: u64) -> Self {
28 Self(seed | 1)
29 }
30
31 fn next(&mut self) -> u64 {
32 self.0 = self
33 .0
34 .wrapping_mul(6364136223846793005)
35 .wrapping_add(1442695040888963407);
36 self.0 >> 11
37 }
38
39 fn unit(&mut self) -> f32 {
40 (self.next() % (1 << 24)) as f32 / ((1 << 24) as f32)
41 }
42
43 fn below(&mut self, bound: usize) -> usize {
44 (self.next() % bound as u64) as usize
45 }
46}
47
48// Emit `batch` images flattened as patch-major rows: batch * NUM_PATCHES
49// rows of PATCH_SIDE*PATCH_SIDE pixels, plus one class label each.
50fn next_batch(rng: &mut ShapeRng, batch: usize) -> (Vec<f32>, Vec<u32>) {
51 let mut patches = vec![0.0_f32; batch * NUM_PATCHES * PATCH_SIDE * PATCH_SIDE];
52 let mut labels = Vec::with_capacity(batch);
53 for image in 0..batch {
54 let class = rng.below(NUM_CLASSES) as u32;
55 labels.push(class);
56 let mut pixels = vec![0.0_f32; IMAGE_SIDE * IMAGE_SIDE];
57 for pixel in pixels.iter_mut() {
58 *pixel = 0.05 * rng.unit();
59 }
60 match class {
61 0 => {
62 let row = 2 + rng.below(IMAGE_SIDE - 4);
63 for column in 0..IMAGE_SIDE {
64 pixels[row * IMAGE_SIDE + column] = 0.85 + 0.1 * rng.unit();
65 }
66 }
67 1 => {
68 let column = 2 + rng.below(IMAGE_SIDE - 4);
69 for row in 0..IMAGE_SIDE {
70 pixels[row * IMAGE_SIDE + column] = 0.85 + 0.1 * rng.unit();
71 }
72 }
73 _ => {
74 let offset = 1 + rng.below(2);
75 for diagonal in 0..IMAGE_SIDE {
76 let column = diagonal + offset;
77 if column < IMAGE_SIDE {
78 pixels[diagonal * IMAGE_SIDE + column] = 0.85 + 0.1 * rng.unit();
79 }
80 }
81 }
82 }
83 let base = image * NUM_PATCHES * PATCH_SIDE * PATCH_SIDE;
84 for patch in 0..NUM_PATCHES {
85 let patch_row = (patch / (IMAGE_SIDE / PATCH_SIDE)) * PATCH_SIDE;
86 let patch_col = (patch % (IMAGE_SIDE / PATCH_SIDE)) * PATCH_SIDE;
87 for y in 0..PATCH_SIDE {
88 for x in 0..PATCH_SIDE {
89 patches[base + patch * PATCH_SIDE * PATCH_SIDE + y * PATCH_SIDE + x] =
90 pixels[(patch_row + y) * IMAGE_SIDE + patch_col + x];
91 }
92 }
93 }
94 }
95 (patches, labels)
96}
97
98struct Vit {
99 patch_projection: oa::ml::nn::Linear,
100 class_embedding: oa::ml::nn::Embedding,
101 position_embedding: oa::ml::nn::Embedding,
102 blocks: Vec<oa::ml::nn::TransformerBlock>,
103 final_norm: oa::ml::nn::LayerNorm,
104 head: oa::ml::nn::Linear,
105}
106
107impl Vit {
108 fn new(runtime: &oa::Runtime, seed: u64) -> oa::Result<Self> {
109 let patch_projection =
110 oa::ml::nn::Linear::new_with_seed_on(runtime, PATCH_SIDE * PATCH_SIDE, MODEL_WIDTH, seed)?;
111 let class_embedding =
112 oa::ml::nn::Embedding::new_with_seed_on(runtime, 1, MODEL_WIDTH, seed.wrapping_add(1))?;
113 let position_embedding =
114 oa::ml::nn::Embedding::new_with_seed_on(runtime, TOKENS, MODEL_WIDTH, seed.wrapping_add(2))?;
115 let mut blocks = Vec::new();
116 for layer in 0..2_usize {
117 let block = oa::ml::nn::TransformerBlock::new_with_seed_on(
118 runtime,
119 MODEL_WIDTH,
120 64,
121 TOKENS,
122 4,
123 1.0e-5,
124 seed.wrapping_add(3 + layer as u64),
125 )?;
126 block.set_attention_mode(oa::ml::nn::AttentionMode::Bidirectional);
127 blocks.push(block);
128 }
129 let final_norm = oa::ml::nn::LayerNorm::new_on(runtime, MODEL_WIDTH, 1.0e-5)?;
130 let head = oa::ml::nn::Linear::new_with_seed_on(
131 runtime,
132 MODEL_WIDTH,
133 NUM_CLASSES,
134 seed.wrapping_add(7),
135 )?;
136 Ok(Self {
137 patch_projection,
138 class_embedding,
139 position_embedding,
140 blocks,
141 final_norm,
142 head,
143 })
144 }
145
146 fn all_parameters(&self) -> oa::Result<Vec<oa::ml::Parameter>> {
147 let mut parameters = self.patch_projection.all_parameters()?;
148 parameters.extend(self.class_embedding.all_parameters()?);
149 parameters.extend(self.position_embedding.all_parameters()?);
150 for block in &self.blocks {
151 parameters.extend(block.all_parameters()?);
152 }
153 parameters.extend(self.final_norm.all_parameters()?);
154 parameters.extend(self.head.all_parameters()?);
155 Ok(parameters)
156 }
157
158 fn num_parameters(&self) -> oa::Result<usize> {
159 Ok(
160 self
161 .all_parameters()?
162 .iter()
163 .map(|parameter| parameter.data().shape().iter().product::<usize>())
164 .sum(),
165 )
166 }
167
168 // `patches` is [B*NUM_PATCHES, PATCH_SIDE*PATCH_SIDE]; logits are [B, C].
169 fn forward(&self, patches: &oa::Matrix, batch: usize) -> oa::Result<oa::Matrix> {
170 let cls_index = oa::Matrix::new_from_slice([1], &[0_u32])?;
171 let position_pattern = (0..batch)
172 .flat_map(|_| 0..TOKENS as u32)
173 .collect::<Vec<u32>>();
174 let position_indices = oa::Matrix::new_from_slice([batch * TOKENS], &position_pattern)?;
175 let patch_tokens = self.patch_projection.forward(patches)?;
176 let mut sequence_parts = Vec::with_capacity(batch * 2);
177 for item in 0..batch {
178 sequence_parts.push(self.class_embedding.forward(&cls_index)?);
179 sequence_parts.push(oa::matrix::slice(
180 &patch_tokens,
181 0,
182 (item * NUM_PATCHES) as i64,
183 ((item + 1) * NUM_PATCHES) as i64,
184 )?);
185 }
186 let sequence = oa::matrix::concat(&sequence_parts, 0)?;
187 let positions = self.position_embedding.forward(&position_indices)?;
188 let mut hidden = oa::matrix::add(&sequence, &positions)?;
189 for block in &self.blocks {
190 hidden = block.forward(&hidden)?;
191 }
192 let hidden = self.final_norm.forward(&hidden)?;
193 let mut class_rows = Vec::with_capacity(batch);
194 for item in 0..batch {
195 class_rows.push(oa::matrix::slice(
196 &hidden,
197 0,
198 (item * TOKENS) as i64,
199 (item * TOKENS + 1) as i64,
200 )?);
201 }
202 let class_tokens = oa::matrix::concat(&class_rows, 0)?;
203 self.head.forward(&class_tokens)
204 }
205}
206
207fn accuracy(logits: &oa::Matrix, labels: &[u32], batch: usize) -> oa::Result<f32> {
208 let values = logits.read_f32()?;
209 let correct = (0..batch)
210 .filter(|item| {
211 let row = &values[item * NUM_CLASSES..(item + 1) * NUM_CLASSES];
212 let prediction = row
213 .iter()
214 .enumerate()
215 .max_by(|left, right| left.1.total_cmp(right.1))
216 .map(|(index, _)| index as u32)
217 .expect("nonempty class logits");
218 prediction == labels[*item]
219 })
220 .count();
221 Ok(correct as f32 / batch as f32)
222}
223
224fn main() -> oa::Result<()> {
225 let mut cli = Cli::new("tu_ml_vit", "OA Tutorial — Vision Transformer");
226 cli.add_option(
227 "--steps",
228 |c: &mut VitConfig| &mut c.steps,
229 "training steps",
230 );
231 cli.add_option("--batch", |c: &mut VitConfig| &mut c.batch, "batch size");
232 cli.add_option("--lr", |c: &mut VitConfig| &mut c.lr, "learning rate");
233 if !cli.parse() {
234 return Ok(());
235 }
236 let steps = if cli.config().steps > 0 {
237 cli.config().steps as usize
238 } else {
239 TRAINING_STEPS
240 };
241 let batch = if cli.config().batch > 0 {
242 cli.config().batch as usize
243 } else {
244 BATCH_SIZE
245 };
246 let lr = if cli.config().lr > 0.0 {
247 cli.config().lr
248 } else {
249 0.005
250 };
251
252 let runtime = oa::Runtime::new()?;
253 oa::Runtime::set_default(runtime.clone());
254 let model = Vit::new(&runtime, 0x7B17)?;
255 let mut optimizer = oa::ml::AdamW::new(model.all_parameters()?, lr)?;
256 let mut rng = ShapeRng::new(0x5EED_7B17);
257
258 println!("\n╔══════════════════════════════════════════════════════════════════╗");
259 println!("║ OA Tutorial — Vision Transformer · patch + bidirectional (autograd)║");
260 println!("╚══════════════════════════════════════════════════════════════════╝\n");
261 println!("task: classify a 16x16 image as horizontal bar, vertical bar, or diagonal");
262 println!("model: patch Linear + class token + learned positions + 2 bidirectional blocks");
263 println!(
264 "params: {} Optimizer: AdamW(lr={lr})\n",
265 model.num_parameters()?
266 );
267 println!("training: {steps} steps · batch={batch} · tokens={TOKENS} · D={MODEL_WIDTH}");
268
269 let mut loss_metric = LossMetric::default();
270 let mut progress = ProgressBar::default();
271 let mut summary_callback = TrainingSummary::default();
272 let mut training = ItTraining::new(
273 &runtime,
274 &mut optimizer,
275 ItTrainingConfig {
276 total_steps: steps as u64,
277 batch_size: batch as u64,
278 sequence_length: (NUM_PATCHES * PATCH_SIDE * PATCH_SIDE) as u64,
279 sequence_unit: "pixel".into(),
280 timer_name: "vit_training_step".into(),
281 enable_gpu_timing: true,
282 ..ItTrainingConfig::default()
283 },
284 )?;
285 training.add_metric(&mut loss_metric);
286 training.add_callback(&mut progress);
287 training.add_callback(&mut summary_callback);
288
289 let mut metrics = LogMetrics::new();
290 let log_dir = oa::Path::var_rel("log/vision/vit");
291 if let Err(e) = metrics.open(&log_dir) {
292 eprintln!("[OA] metrics unavailable: {e}");
293 }
294
295 let mut initial_loss = 0.0_f32;
296 for _ in 0..steps {
297 assert!(training.step(
298 || {
299 let (patches, labels) = next_batch(&mut rng, batch);
300 Ok((
301 oa::Matrix::new_from_f32([batch * NUM_PATCHES, PATCH_SIDE * PATCH_SIDE], &patches)?,
302 oa::Matrix::new_from_slice([batch], &labels)?,
303 ))
304 },
305 |(patches, labels)| {
306 let tape = oa::ml::GradientTape::new();
307 let logits = model.forward(&patches, batch)?;
308 let loss = oa::ml::loss::cross_entropy(&logits, &labels)?;
309 tape.backward(&loss)?;
310 Ok(loss)
311 },
312 )?);
313 let snap = training.snapshot();
314 if snap.step_count() == 1 {
315 initial_loss = snap.last_loss().unwrap_or_default();
316 }
317 if let Some(loss) = snap.last_loss() {
318 metrics.log_scalar("loss", snap.step_count() as i64, loss as f64);
319 }
320 }
321 let program_diagnostics = training
322 .training_program()
323 .map(|program| program.diagnostics());
324 let training_result = training.finish()?;
325 let final_training_loss = training_result.last_loss().unwrap_or_default();
326
327 let (eval_patches, eval_labels) = next_batch(&mut rng, EVAL_IMAGES);
328 let patches = oa::Matrix::new_from_f32(
329 [EVAL_IMAGES * NUM_PATCHES, PATCH_SIDE * PATCH_SIDE],
330 &eval_patches,
331 )?;
332 let labels = oa::Matrix::new_from_slice([EVAL_IMAGES], &eval_labels)?;
333 let logits = model.forward(&patches, EVAL_IMAGES)?;
334 let evaluation_loss = oa::ml::loss::cross_entropy(&logits, &labels)?.read_f32()?[0];
335 let evaluation_accuracy = accuracy(&logits, &eval_labels, EVAL_IMAGES)?;
336
337 println!("\nEvaluation:");
338 println!(
339 " random-loss baseline ln({NUM_CLASSES}) = {:.4}",
340 (NUM_CLASSES as f64).ln()
341 );
342 println!(" loss: evaluation {evaluation_loss:.6} · last training {final_training_loss:.6}");
343 println!(" image accuracy: {:.1}%", evaluation_accuracy * 100.0);
344 println!(" steps: {steps} · batch: {batch} · lr: {lr}");
345
346 // Quantized-inference check: pack the trained patch projection to Q8 and
347 // compare its forward against the dense module on the same eval batch.
348 let quantized_projection = oa::ml::nn::QuantizedLinear::from_linear(
349 &model.patch_projection,
350 oa::ml::matrix::Quantization::Q8,
351 )?;
352 let dense_projection = model.patch_projection.forward(&patches)?.read_f32()?;
353 let packed_projection = quantized_projection.forward(&patches)?.read_f32()?;
354 let max_deviation = dense_projection
355 .iter()
356 .zip(&packed_projection)
357 .map(|(dense, packed)| (dense - packed).abs())
358 .fold(0.0_f32, f32::max);
359 println!(" quantized patch projection (Q8): max |Δ| {max_deviation:.6}");
360 assert!(
361 max_deviation <= 0.02,
362 "quantized projection deviates {max_deviation:.6} from the dense forward",
363 );
364 if let Some(diagnostics) = program_diagnostics {
365 println!(
366 " program: {} nodes · {} recording · {} cache hits · {} uploads",
367 diagnostics.node_count(),
368 diagnostics.command_recording_count(),
369 diagnostics.command_cache_hit_count(),
370 diagnostics.input_upload_count(),
371 );
372 }
373 if initial_loss > 0.0 {
374 println!(
375 " loss improvement: {:.2}x ({initial_loss:.4} → {final_training_loss:.4})",
376 initial_loss / final_training_loss.max(1.0e-9)
377 );
378 }
379
380 let loss_baseline = (NUM_CLASSES as f32).ln() * 0.3;
381 assert!(
382 evaluation_loss < loss_baseline && evaluation_accuracy >= 0.95,
383 "vit tutorial failed its convergence gate (loss {evaluation_loss:.6}, accuracy {:.3})",
384 evaluation_accuracy,
385 );
386 metrics.flush()?;
387 Ok(())
388}
389

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.