Record, combine, and multiply matrices in Rust
Current source-owned tutorial. API availability differs by language.
The Rust program validates matrix multiplication against an independent CPU reference and reports exploratory eager timings. The Python tab demonstrates the current Core basics API; it is not a paired timing run.
Start the walkthrough · Jump to complete source
The first OA compute tutorial: obtain the default Runtime, record domain
operations with no submit or wait ceremony, compose matrix expressions in
every supported spelling, verify tiled F32 matmul against an independent
CPU reference, and measure eager and compiled replay performance. 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_core_basics
The default run covers recording, syntax, correctness, and both performance
sections. Use --correctness-only for the oracle sweep alone,
--benchmark-only for timing, or --case NAME --warmup N --samples N to
focus on one geometry.
1. Record on the default runtime
Runtime::current() returns this thread's default runtime, lazily
initializing the Vulkan instance, logical device, allocator, and queues on
first use. matrix::ones, matrix::full, and matrix::add record into its
private eager session and return Matrix values immediately as semantic
handles. checkpoint submits all pending eager work without blocking the
host, and read_f32 is the explicit device to host boundary.
1let runtime = Runtime::current()?;2let a = matrix::ones([64, 128])?;3let b = matrix::full([64, 128], 2.0_f32)?;4let output = matrix::add(&a, &b)?;5runtime.checkpoint()?.wait()?;6let values = output.read_f32()?;7
11. Default runtime and eager recording2 add(ones, full(2))[0] = 3.0 · checkpoint flushed, 8192 elements3
2. Basic syntax
matrix::matmul computes the transposed product C = A @ Bᵀ, that is
[M, K] × [N, K] into [M, N]. Elementwise spelling is deliberately
separate from the matmul contract: the operator, method, associated call,
and module function forms share one kernel body and agree on the result.
1let one = matrix::ones([2, 3])?;2let two = matrix::full([2, 3], 2.0)?;3let product = matrix::matmul(&one, &two)?;4let values = product.read_f32()?;5
1[2,3] × [2,3]ᵀ -> [2, 2]: [6.0, 6.0, 6.0, 6.0]2operator / method / associated / module calls agree3
3. Correctness against a CPU reference
Eight geometries cover square, tall, wide, irregular, GEMV, and MNIST shaped problems. Deterministic inputs feed both an independent scalar CPU triple loop and the device path; the normalized error must stay within FP32 tolerance.
1tiny-square [ 8, 8, 8] norm_err=7.26e-8 ok2square [ 128, 128, 128] norm_err=8.33e-8 ok3tall-skinny [ 512, 64, 128] norm_err=8.33e-8 ok4short-wide [ 64, 512, 128] norm_err=8.33e-8 ok5irregular [ 100, 130, 77] norm_err=1.37e-7 ok6gemv-decode [ 1, 256, 256] norm_err=8.33e-8 ok7mnist-hidden [ 64, 128, 784] norm_err=5.44e-8 ok8mnist-logits [ 64, 10, 128] norm_err=8.33e-8 ok9All correctness checks passed.10
4. Eager submit and readback timing
The eager boundary measures a matmul call through synchronized full output
readback, including the device to host copy. A constant input oracle checks
every timed geometry before warmup so NaNs or a wrong kernel cannot hide
behind timing alone.
5. Compiled replay timing
Runtime::capture records the matmul once into an execution plan.
submit_timed replays it and reports the device timestamp, with no readback
in the measured region. The same oracle verifies the captured output before
timing starts.
1let (plan, output) = runtime.capture(|| matrix::matmul(&left, &right))?;2runtime.submit(&plan)?.wait()?;3let duration = runtime.submit_timed(&plan)?.device_duration()?;4
1square-1024 [ 1024, 1024, 1024] p50= 3.464 ms p95= 11.229 ms 620.00 GFLOP/s2BENCH name=square-1024 m=1024 n=1024 k=1024 boundary=replay_submit_timed p50_ms=3.463698 p95_ms=11.228802 gflops=619.9973693
Replay timing reflects the kernel alone. These are exploratory numbers from one process on one device, not release benchmark evidence.
The Python tutorial runs the same record, expression, and matmul sequence
with the oa.matrix module API.
Source
Rust example · Full Python walkthrough
Example
1use std::{env, hint::black_box, time::Instant};23use anyhow::{Context, bail, ensure};4use oa::{Matrix, Runtime, matrix};56const CORRECTNESS_CASES: &[ShapeCase] = &[7 ShapeCase::new("tiny-square", 8, 8, 8),8 ShapeCase::new("square", 128, 128, 128),9 ShapeCase::new("tall-skinny", 512, 64, 128),10 ShapeCase::new("short-wide", 64, 512, 128),11 ShapeCase::new("irregular", 100, 130, 77),12 ShapeCase::new("gemv-decode", 1, 256, 256),13 ShapeCase::new("mnist-hidden", 64, 128, 784),14 ShapeCase::new("mnist-logits", 64, 10, 128),15];1617const PERFORMANCE_CASES: &[ShapeCase] = &[18 ShapeCase::new("square-512", 512, 512, 512),19 ShapeCase::new("square-1024", 1024, 1024, 1024),20 ShapeCase::new("square-2048", 2048, 2048, 2048),21 ShapeCase::new("tall-skinny", 4096, 128, 1024),22 ShapeCase::new("short-wide", 128, 4096, 1024),23 ShapeCase::new("gemv-decode", 1, 4096, 4096),24];2526#[derive(Clone, Copy)]27struct ShapeCase {28 name: &'static str,29 m: usize,30 n: usize,31 k: usize,32}3334impl ShapeCase {35 const fn new(name: &'static str, m: usize, n: usize, k: usize) -> Self {36 Self { name, m, n, k }37 }38}3940struct Options {41 correctness: bool,42 benchmark: bool,43 warmup: usize,44 samples: usize,45 case: Option<String>,46}4748struct PerfResult {49 p50_ms: f64,50 p95_ms: f64,51 gflops: f64,52}5354fn main() -> anyhow::Result<()> {55 let options = parse_options()?;5657 println!("OA Rust Core Basics");58 println!("contract: FP32 [M,K] × [N,K] -> [M,N]");59 demo_runtime_recording()?;60 demo_basic_syntax()?;6162 if options.correctness {63 run_correctness_suite()?;64 }65 if options.benchmark {66 run_performance_suite(&options)?;67 }68 Ok(())69}7071fn parse_options() -> anyhow::Result<Options> {72 let mut options = Options {73 correctness: true,74 benchmark: true,75 warmup: 5,76 samples: 20,77 case: None,78 };79 let mut arguments = env::args().skip(1);80 while let Some(argument) = arguments.next() {81 match argument.as_str() {82 "--correctness-only" => options.benchmark = false,83 "--benchmark-only" => options.correctness = false,84 "--warmup" => options.warmup = parse_count("--warmup", arguments.next())?,85 "--samples" => options.samples = parse_count("--samples", arguments.next())?,86 "--case" => {87 options.case = Some(88 arguments89 .next()90 .context("--case requires a performance-case name")?,91 );92 }93 "--help" | "-h" => {94 println!(95 "usage: tu_core_basics [--correctness-only|--benchmark-only] \96 [--case NAME] [--warmup N] [--samples N]"97 );98 std::process::exit(0);99 }100 _ => bail!("unknown argument: {argument}"),101 }102 }103 ensure!(options.samples > 0, "--samples must be greater than zero");104 Ok(options)105}106107fn parse_count(flag: &str, value: Option<String>) -> anyhow::Result<usize> {108 value109 .with_context(|| format!("{flag} requires a non-negative integer"))?110 .parse()111 .with_context(|| format!("{flag} requires a non-negative integer"))112}113114fn demo_runtime_recording() -> anyhow::Result<()> {115 println!("\n1. Default runtime and eager recording");116 let runtime = Runtime::current()?;117 let a = matrix::ones([64, 128])?;118 let b = matrix::full([64, 128], 2.0_f32)?;119 let output = matrix::add(&a, &b)?;120121 // `checkpoint` submits all pending eager work without blocking the host.122 // Optional: `read_f32` below flushes and waits on its own.123 runtime.checkpoint()?.wait()?;124125 let values = output.read_f32()?;126 let first = values.first().copied().unwrap_or(f32::NAN);127 ensure!(128 (first - 3.0_f32).abs() <= 1e-5 && output.shape() == [64, 128] && values.len() == 64 * 128,129 "unexpected recorded add result"130 );131 println!(132 " add(ones, full(2))[0] = {first:.1} · checkpoint flushed, {} elements",133 values.len()134 );135 Ok(())136}137138fn demo_basic_syntax() -> anyhow::Result<()> {139 println!("\n2. Basic syntax");140 let one = matrix::ones([2, 3])?;141 let two = matrix::full([2, 3], 2.0)?;142 let product = matrix::matmul(&one, &two)?;143 let values = product.read_f32()?;144 ensure!(product.shape() == [2, 2], "unexpected output shape");145 ensure!(146 values == [6.0; 4],147 "unexpected introductory result: {values:?}"148 );149 println!(" [2,3] × [2,3]ᵀ -> {:?}: {values:?}", product.shape());150151 // Operators, methods, associated calls and module functions share one body.152 // Elementwise multiplication is distinct from A @ B-transpose above.153 for elementwise in [154 (&one * &two)?,155 one.mul(&two)?,156 Matrix::mul(&one, &two)?,157 matrix::mul(&one, &two)?,158 ] {159 ensure!(160 elementwise.read_f32()? == [2.0; 6],161 "elementwise API mismatch"162 );163 }164 let added = (&one + &two)?;165 ensure!(added.read_f32()? == [3.0; 6], "addition operator mismatch");166 println!(" operator / method / associated / module calls agree");167 Ok(())168}169170fn run_correctness_suite() -> anyhow::Result<()> {171 println!("\n3. Correctness vs independent CPU reference");172 for (index, &case) in CORRECTNESS_CASES.iter().enumerate() {173 let left_values = values(case.m * case.k, index * 2 + 3);174 let right_values = values(case.n * case.k, index * 2 + 11);175 let expected = cpu_matmul_nt(&left_values, &right_values, case.m, case.n, case.k);176 let left = Matrix::new_from_f32([case.m, case.k], &left_values)?;177 let right = Matrix::new_from_f32([case.n, case.k], &right_values)?;178 let output = matrix::matmul(&left, &right)?;179 let actual = output.read_f32()?;180 let error = normalized_error(&actual, &expected)?;181 ensure!(error <= 1.0e-4, "{} exceeded the FP32 tolerance", case.name);182 println!(183 " {:<16} [{:5},{:5},{:5}] norm_err={error:.2e} ok",184 case.name, case.m, case.n, case.k185 );186 }187 println!(" All correctness checks passed.");188 Ok(())189}190191fn run_performance_suite(options: &Options) -> anyhow::Result<()> {192 println!("\n4. Exploratory eager end-to-end performance");193 println!(" boundary: matmul call through synchronized full output readback");194 println!(195 " warmup={} samples={} (one process; not release benchmark evidence)",196 options.warmup, options.samples197 );198199 let mut matched = options.case.is_none();200 for &case in PERFORMANCE_CASES {201 if !selected(options, case) {202 continue;203 }204 matched = true;205 let result = bench_one(case, options.warmup, options.samples)?;206 print_result(case, &result, "eager_submit_readback");207 }208 ensure!(matched, "unknown performance case: {:?}", options.case);209210 println!("\n5. Compiled replay performance");211 println!(" boundary: captured matmul plan, device-timestamped replay (no readback)");212 println!(213 " warmup={} samples={} (one process; same kernel, replay boundary)",214 options.warmup, options.samples215 );216217 let runtime = Runtime::new()?;218 Runtime::set_default(runtime.clone());219 for &case in PERFORMANCE_CASES {220 if !selected(options, case) {221 continue;222 }223 let result = bench_one_replay(&runtime, case, options.warmup, options.samples)?;224 print_result(case, &result, "replay_submit_timed");225 }226 Ok(())227}228229fn selected(options: &Options, case: ShapeCase) -> bool {230 options.case.as_deref().is_none_or(|name| name == case.name)231}232233fn print_result(case: ShapeCase, result: &PerfResult, boundary: &str) {234 println!(235 " {:<16} [{:5},{:5},{:5}] p50={:9.3} ms p95={:9.3} ms {:9.2} GFLOP/s",236 case.name, case.m, case.n, case.k, result.p50_ms, result.p95_ms, result.gflops237 );238 println!(239 "BENCH name={} m={} n={} k={} boundary={} p50_ms={:.6} p95_ms={:.6} gflops={:.6}",240 case.name, case.m, case.n, case.k, boundary, result.p50_ms, result.p95_ms, result.gflops241 );242}243244fn bench_one(case: ShapeCase, warmup: usize, sample_count: usize) -> anyhow::Result<PerfResult> {245 let left = matrix::full([case.m, case.k], 0.25)?;246 let right = matrix::full([case.n, case.k], 0.5)?;247 // Constant-input oracle checks every timed geometry before warmup.248 // A positive norm or maximum-error reduction alone must not hide NaNs.249 let expected = case.k as f32 * 0.125;250 let actual = matrix::matmul(&left, &right)?.read_f32()?;251 ensure!(252 actual.len() == case.m * case.n253 && actual254 .iter()255 .all(|&value| value.is_finite()256 && (value - expected).abs() <= expected.abs().max(1.0) * 1.0e-5),257 "{} independent constant-input oracle failed",258 case.name259 );260 println!(261 "ORACLE name={} correctness=pass elements={} expected={expected}",262 case.name,263 actual.len()264 );265 for _ in 0..warmup {266 let output = matrix::matmul(&left, &right)?;267 black_box(output.read_f32()?);268 }269270 let mut samples = Vec::with_capacity(sample_count);271 for _ in 0..sample_count {272 let start = Instant::now();273 let output = matrix::matmul(&left, &right)?;274 black_box(output.read_f32()?);275 samples.push(start.elapsed().as_secs_f64() * 1_000.0);276 }277 samples.sort_by(f64::total_cmp);278 let p50_ms = percentile(&samples, 0.50);279 let p95_ms = percentile(&samples, 0.95);280 let gflop = 2.0 * case.m as f64 * case.n as f64 * case.k as f64 / 1.0e9;281 Ok(PerfResult {282 p50_ms,283 p95_ms,284 gflops: gflop / (p50_ms / 1_000.0),285 })286}287288fn bench_one_replay(289 runtime: &Runtime,290 case: ShapeCase,291 warmup: usize,292 sample_count: usize,293) -> anyhow::Result<PerfResult> {294 let left = matrix::full([case.m, case.k], 0.25)?;295 let right = matrix::full([case.n, case.k], 0.5)?;296 let (plan, output) = runtime297 .capture(|| matrix::matmul(&left, &right))298 .context("capture matmul execution plan")?;299 runtime.submit(&plan)?.wait()?;300 let expected = case.k as f32 * 0.125;301 let actual = output.read_f32()?;302 ensure!(303 actual.len() == case.m * case.n304 && actual305 .iter()306 .all(|&value| value.is_finite()307 && (value - expected).abs() <= expected.abs().max(1.0) * 1.0e-5),308 "{} replay constant-input oracle failed",309 case.name310 );311 for _ in 0..warmup {312 runtime.submit(&plan)?.wait()?;313 }314315 let mut samples = Vec::with_capacity(sample_count);316 for _ in 0..sample_count {317 let duration = runtime.submit_timed(&plan)?.device_duration()?;318 samples.push(duration.as_secs_f64() * 1_000.0);319 }320 samples.sort_by(f64::total_cmp);321 let p50_ms = percentile(&samples, 0.50);322 let p95_ms = percentile(&samples, 0.95);323 let gflop = 2.0 * case.m as f64 * case.n as f64 * case.k as f64 / 1.0e9;324 Ok(PerfResult {325 p50_ms,326 p95_ms,327 gflops: gflop / (p50_ms / 1_000.0),328 })329}330331fn percentile(samples: &[f64], percentile: f64) -> f64 {332 let index = ((percentile * samples.len() as f64).ceil() as usize)333 .saturating_sub(1)334 .min(samples.len() - 1);335 samples[index]336}337338fn values(length: usize, salt: usize) -> Vec<f32> {339 (0..length)340 .map(|index| (((index * 17 + salt) % 29) as f32 - 14.0) / 7.0)341 .collect()342}343344fn cpu_matmul_nt(left: &[f32], right: &[f32], m: usize, n: usize, k: usize) -> Vec<f32> {345 let mut output = vec![0.0; m * n];346 for row in 0..m {347 for column in 0..n {348 for inner in 0..k {349 output[row * n + column] += left[row * k + inner] * right[column * k + inner];350 }351 }352 }353 output354}355356fn normalized_error(actual: &[f32], expected: &[f32]) -> anyhow::Result<f64> {357 ensure!(358 actual.len() == expected.len(),359 "output length differs from CPU oracle"360 );361 let mut max_error = 0.0_f64;362 let mut max_reference = 1.0e-6_f64;363 for (&actual, &expected) in actual.iter().zip(expected) {364 max_error = max_error.max((f64::from(actual) - f64::from(expected)).abs());365 max_reference = max_reference.max(f64::from(expected).abs());366 }367 Ok(max_error / max_reference)368}369
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.