From 017ff31e2fd0bb09fd22ccd02c5a89fd10499c9a Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 17 Nov 2026 05:10:48 -0800 Subject: [PATCH] wip harness crate --- .github/workflows/ci.yml | 7 +- AGENTS.md | 5 +- CONTRIBUTING.md | 5 +- Cargo.toml | 1 + crates/metal2vulkan-harness/Cargo.toml | 39 +++ crates/metal2vulkan-harness/src/authored.rs | 304 ++++++++++++++++++ .../metal2vulkan-harness/src/bin/harness.rs | 149 +++++++++ crates/metal2vulkan-harness/src/clocks.rs | 26 ++ crates/metal2vulkan-harness/src/lib.rs | 164 ++++++++++ crates/metal2vulkan-harness/src/old.rs | 161 ++++++++++ crates/metal2vulkan-harness/src/plan.rs | 222 +++++++++++++ crates/metal2vulkan-harness/src/run.rs | 275 ++++++++++++++++ crates/metal2vulkan-harness/src/tests.rs | 85 +++++ crates/metal2vulkan-harness/tests/authored.rs | 23 ++ docs/VALIDATION.md | 2 +- 15 files changed, 1460 insertions(+), 8 deletions(-) create mode 100644 crates/metal2vulkan-harness/Cargo.toml create mode 100644 crates/metal2vulkan-harness/src/authored.rs create mode 100644 crates/metal2vulkan-harness/src/bin/harness.rs create mode 100644 crates/metal2vulkan-harness/src/clocks.rs create mode 100644 crates/metal2vulkan-harness/src/lib.rs create mode 100644 crates/metal2vulkan-harness/src/old.rs create mode 100644 crates/metal2vulkan-harness/src/plan.rs create mode 100644 crates/metal2vulkan-harness/src/run.rs create mode 100644 crates/metal2vulkan-harness/src/tests.rs create mode 100644 crates/metal2vulkan-harness/tests/authored.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4a1341ca1..e20091c35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -168,7 +168,8 @@ jobs: metal2vulkan-runtime=0 \ metal2vulkan-validation=0 \ metal2vulkan-conformance=0 \ - metal2vulkan-devtools=0 + metal2vulkan-devtools=0 \ + metal2vulkan-harness=0 do crate=${row%=*} ceiling=${row#*=} @@ -195,12 +196,12 @@ jobs: # builds alone against the others' packages, so none reads a file outside its own directory. # Validation and the dev-tools crate are not published. - name: Package the published crates - run: cargo package --workspace --exclude metal2vulkan-validation --exclude metal2vulkan-conformance --exclude metal2vulkan-devtools --exclude metal2vulkan-rt + run: cargo package --workspace --exclude metal2vulkan-validation --exclude metal2vulkan-conformance --exclude metal2vulkan-devtools --exclude metal2vulkan-rt --exclude metal2vulkan-harness # With the AIR front end's crate's own tests, and the dev-tools crate's: # its tool runner and L3 checks. - name: Test metal2vulkan - run: cargo nextest run -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-rt -p metal2vulkan-runtime -p metal2vulkan-devtools --all-features + run: cargo nextest run -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-rt -p metal2vulkan-runtime -p metal2vulkan-devtools -p metal2vulkan-harness --all-features # GPU-free on every host: tests that open a device compile only under `--cfg m2v_gpu` or # `--cfg m2v_cpu_icd`, and no device-opening code runs without one of them. diff --git a/AGENTS.md b/AGENTS.md index 3a9735f7e..73c69b65e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ the current task. ## The project metal2vulkan runs Metal shaders and Metal programs on Vulkan. It is a Cargo workspace (a virtual -manifest at the root) of seven crates under `crates/`: +manifest at the root) of eight crates under `crates/`: | Crate | Published | What it is | |---|---|---| @@ -17,6 +17,7 @@ manifest at the root) of seven crates under `crates/`: | `crates/metal2vulkan-validation` | no | Authored semantic cases, Metal and Vulkan execution, harvest, the corpus index and audits | | `crates/metal2vulkan-conformance` | no | The Metal conformance suite: one case run on Metal and on the runtime, recorded and compared field by field. Independent of the harvested corpus | | `crates/metal2vulkan-devtools` | no | The external-tool runner, fixture assemblers and fixture paths the tests share | +| `crates/metal2vulkan-harness` | no | The runtimes' compute harness: one set of compute workloads through each runtime's Metal-shaped API on one GPU, checked against CPU references, then timed. The regression gate between the old runtime and the new | The three published crates share one version; `metal2vulkan` pins `metal2vulkan-air` exactly (`=0.x.y`). License: dual, `GPL-2.0-or-later OR LGPL-3.0-or-later`, at the recipient's choice. The @@ -258,7 +259,7 @@ doctests, so they have their own line. The gate: cargo fmt --all cargo clippy --workspace --all-targets --all-features -- -D warnings RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps -cargo nextest run -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-rt -p metal2vulkan-runtime -p metal2vulkan-devtools --all-features +cargo nextest run -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-rt -p metal2vulkan-runtime -p metal2vulkan-devtools -p metal2vulkan-harness --all-features cargo nextest run -p metal2vulkan-validation --all-features cargo nextest run -p metal2vulkan-conformance --all-features cargo test --workspace --all-features --doc diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7abf9ac01..ec3a1ee55 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -37,7 +37,8 @@ they bind people too. │ │ ├── fixtures/public/ # our own synthetic fixtures (.ll, .air.ll, .metal, .spvasm) │ │ ├── profiles/ # committed Khronos device profiles │ │ └── corpus/ # authored cases and observations (local/ is private, ignored) -│ └── metal2vulkan-devtools/ # unpublished: tool runner, fixture assemblers +│ ├── metal2vulkan-devtools/ # unpublished: tool runner, fixture assemblers +│ └── metal2vulkan-harness/ # unpublished: the runtimes' compute harness (crate docs) ├── docs/ # guides and generated references ├── scripts/ # developer utilities and generators ├── Cargo.toml # the virtual workspace @@ -52,7 +53,7 @@ cargo fmt --all cargo clippy --workspace --all-targets --all-features -- -D warnings RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps scripts/api-docs # the translator's API reference; fails on a link to a hidden item -cargo nextest run -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-rt -p metal2vulkan-runtime -p metal2vulkan-devtools --all-features +cargo nextest run -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-rt -p metal2vulkan-runtime -p metal2vulkan-devtools -p metal2vulkan-harness --all-features cargo nextest run -p metal2vulkan-validation --all-features cargo test --workspace --all-features --doc ``` diff --git a/Cargo.toml b/Cargo.toml index 4fd85f8c8..8c4435057 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ members = [ "crates/metal2vulkan-air", "crates/metal2vulkan-conformance", "crates/metal2vulkan-devtools", + "crates/metal2vulkan-harness", "crates/metal2vulkan-rt", "crates/metal2vulkan-runtime", "crates/metal2vulkan-validation", diff --git a/crates/metal2vulkan-harness/Cargo.toml b/crates/metal2vulkan-harness/Cargo.toml new file mode 100644 index 000000000..949877cb2 --- /dev/null +++ b/crates/metal2vulkan-harness/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "metal2vulkan-harness" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +description = "The runtimes' compute harness: one set of Metal compute workloads through each runtime's Metal-shaped API, checked and timed" +# Dev-only: never published. +publish = false +autobins = false + +[lib] +name = "metal2vulkan_harness" +path = "src/lib.rs" + +# The harness's command (src/bin/harness.rs). It has no unit tests, so `test = false` keeps +# `cargo test`, nextest and `clippy --all-targets` from building a test harness of it. +[[bin]] +name = "harness" +path = "src/bin/harness.rs" +test = false + +[dependencies] +# The translator, for the library of AIR bitcode the old runtime takes (`old.rs`). +metal2vulkan = { path = "../metal2vulkan" } +# The old runtime, behind the harness's traits in `old.rs` alone. +metal2vulkan-runtime = { path = "../metal2vulkan-runtime" } +# The fixture directory and `llvm-as` of the authored workloads' library. +metal2vulkan-devtools = { path = "../metal2vulkan-devtools" } + +# The process's CPU clock (`clocks.rs`). +[target.'cfg(unix)'.dependencies] +libc.workspace = true + +# The device test compiles only under the validation crate's GPU safety cfgs +# (docs/VALIDATION.md): `--cfg m2v_gpu` (a real GPU) or `--cfg m2v_cpu_icd` (a CPU ICD). +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(m2v_gpu)", "cfg(m2v_cpu_icd)"] } diff --git a/crates/metal2vulkan-harness/src/authored.rs b/crates/metal2vulkan-harness/src/authored.rs new file mode 100644 index 000000000..c0cabedc6 --- /dev/null +++ b/crates/metal2vulkan-harness/src/authored.rs @@ -0,0 +1,304 @@ +//! The authored workloads: the kernels of the public fixture `harness/workloads.metal`, their +//! inputs made here from a fixed seed, and the CPU reference of their results. Every result is +//! exact on any device but the ALU workload's, whose `float` chains are held to a tolerance. + +use crate::plan::{Binding, BufferPlan, Dispatch, Expect, Grid, Plan, Values}; +use crate::{Result, Storage}; + +/// The authored workloads by name, each with the builder of its plan. A plan holds its inputs and +/// expected results (up to 128 MiB), so each is built when it runs. +pub const WORKLOADS: [(&str, fn() -> Plan); 6] = [ + ("bandwidth", bandwidth), + ("alu", alu), + ("threadgroup_scan", threadgroup_scan), + ("simd_reduce", simd_reduce), + ("image_filter", image_filter), + ("dispatch_chain", dispatch_chain), +]; + +/// The authored library's AIR bitcode: the fixture's LLVM text, assembled by `llvm-as`. +pub fn library_air() -> Result> { + let ll = metal2vulkan_devtools::fixtures_dir().join("harness/workloads.ll"); + metal2vulkan_devtools::llvm_assemble(&ll) + .map_err(|why| format!("llvm-as {}: {why:?}", ll.display()).into()) +} + +/// Bandwidth-bound: 64 MiB of `float4`s read and 64 MiB written, `x * 2 + 1` each +/// (`scale_offset`), in `Private` storage. Every input is a whole number below 256. +fn bandwidth() -> Plan { + const VECTORS: u64 = 4 << 20; + let input: Vec = (words(1, 4 * VECTORS as usize).into_iter()) + .map(|word| (word & 255) as f32) + .collect(); + let output = input.iter().map(|x| (x * 2.0 + 1.0).to_bits()).collect(); + Plan { + name: "bandwidth".to_owned(), + buffers: vec![private(float_bytes(&input)), unset(16 * VECTORS)], + dispatches: vec![Dispatch { + function: "scale_offset".to_owned(), + bindings: vec![ + buffer(0, 0), + buffer(1, 1), + bytes(2, float_bytes(&[2.0, 1.0])), + ], + grid: Grid::groups_of_256(VECTORS / 256), + }], + expect: vec![Expect { + buffer: 1, + values: Values::Words(output), + }], + } +} + +/// ALU-bound: 2^19 threads, each two dependent FMA chains of 1024 rounds (`fma_chains`). A +/// thread starts from its index's low ten bits, so the reference runs the 1024 starts. +fn alu() -> Plan { + const THREADS: usize = 1 << 19; + const ROUNDS: u32 = 1024; + let ends: Vec = (0..1024u32) + .map(|start| { + let mut a = (start & 31) as f32 / 32.0; + let mut b = ((start >> 5) & 31) as f32 / 32.0; + for _ in 0..ROUNDS { + a = a.mul_add(0.9375, b * 0.0625); + b = b.mul_add(0.875, a * 0.125); + } + a + b + }) + .collect(); + Plan { + name: "alu".to_owned(), + buffers: vec![unset(4 * THREADS as u64)], + dispatches: vec![Dispatch { + function: "fma_chains".to_owned(), + bindings: vec![buffer(0, 0), bytes(1, ROUNDS.to_le_bytes().to_vec())], + grid: Grid::groups_of_256(THREADS as u64 / 256), + }], + expect: vec![Expect { + buffer: 0, + values: Values::Floats { + values: (0..THREADS).map(|thread| ends[thread % 1024]).collect(), + tolerance: 1e-4, + }, + }], + } +} + +/// Threadgroup memory with barriers: the inclusive prefix sums of each 256 of 8 Mi words +/// (`block_scan`, 16 barriers a threadgroup). +fn threadgroup_scan() -> Plan { + const WORDS: usize = 8 << 20; + let input = words(2, WORDS); + let mut output = Vec::with_capacity(WORDS); + for block in input.chunks(256) { + let mut sum = 0u32; + for &word in block { + sum = sum.wrapping_add(word); + output.push(sum); + } + } + Plan { + name: "threadgroup_scan".to_owned(), + buffers: vec![private(word_bytes(&input)), unset(4 * WORDS as u64)], + dispatches: vec![Dispatch { + function: "block_scan".to_owned(), + bindings: vec![buffer(0, 0), buffer(1, 1)], + grid: Grid::groups_of_256(WORDS as u64 / 256), + }], + expect: vec![Expect { + buffer: 1, + values: Values::Words(output), + }], + } +} + +/// SIMD reductions: the wrapping sum of 16 Mi words in two dispatches of `reduce_sum`, the first +/// a sum per 4096 words, the second the sum of those into a `Shared` buffer. +fn simd_reduce() -> Plan { + const WORDS: u32 = 16 << 20; + const CHUNK: u32 = 4096; + const GROUPS: u32 = WORDS / CHUNK; + let input = words(3, WORDS as usize); + let sum = |words: &[u32]| words.iter().fold(0u32, |sum, &word| sum.wrapping_add(word)); + let partials: Vec = input.chunks(CHUNK as usize).map(sum).collect(); + let total = sum(&partials); + let shape = |count: u32, chunk: u32| word_bytes(&[count, chunk]); + Plan { + name: "simd_reduce".to_owned(), + buffers: vec![ + private(word_bytes(&input)), + unset(4 * GROUPS as u64), + BufferPlan { + length: 16, + storage: Storage::Shared, + contents: Some(vec![0; 16]), + }, + ], + dispatches: vec![ + Dispatch { + function: "reduce_sum".to_owned(), + bindings: vec![buffer(0, 0), buffer(1, 1), bytes(2, shape(WORDS, CHUNK))], + grid: Grid::groups_of_256(GROUPS as u64), + }, + Dispatch { + function: "reduce_sum".to_owned(), + bindings: vec![buffer(0, 1), buffer(1, 2), bytes(2, shape(GROUPS, GROUPS))], + grid: Grid::groups_of_256(1), + }, + ], + expect: vec![ + Expect { + buffer: 1, + values: Values::Words(partials), + }, + Expect { + buffer: 2, + values: Values::Words(vec![total, 0, 0, 0]), + }, + ], + } +} + +/// 2D image-like indexing: a 3x3 binomial filter over a 1920x1080 image of `float4` texels +/// (`binomial3x3`), on a grid of one thread a texel in threadgroups of 16x16, the bottom row's +/// partial. Every input channel is a whole number below 256. +fn image_filter() -> Plan { + const WIDTH: usize = 1920; + const HEIGHT: usize = 1080; + let input: Vec = (words(4, 4 * WIDTH * HEIGHT).into_iter()) + .map(|word| (word & 255) as f32) + .collect(); + let at = |x: usize, y: usize, dx: isize, dy: isize| { + let x = x.saturating_add_signed(dx).min(WIDTH - 1); + let y = y.saturating_add_signed(dy).min(HEIGHT - 1); + 4 * (y * WIDTH + x) + }; + let mut output = Vec::with_capacity(input.len()); + for y in 0..HEIGHT { + for x in 0..WIDTH { + let mut sum = [0.0f32; 4]; + for dy in -1..=1isize { + for dx in -1..=1isize { + let weight = (2 - dx.abs()) as f32 * (2 - dy.abs()) as f32; + let texel = at(x, y, dx, dy); + for (channel, sum) in sum.iter_mut().enumerate() { + *sum += input[texel + channel] * weight; + } + } + } + output.extend(sum.map(|sum| (sum * 0.0625).to_bits())); + } + } + let size = word_bytes(&[WIDTH as u32, HEIGHT as u32]); + Plan { + name: "image_filter".to_owned(), + buffers: vec![private(float_bytes(&input)), unset(4 * input.len() as u64)], + dispatches: vec![Dispatch { + function: "binomial3x3".to_owned(), + bindings: vec![buffer(0, 0), buffer(1, 1), bytes(2, size)], + grid: Grid::Threads { + threads: [WIDTH as u64, HEIGHT as u64, 1], + per_group: [16, 16, 1], + }, + }], + expect: vec![Expect { + buffer: 1, + values: Values::Words(output), + }], + } +} + +/// Many tiny dispatches in a chain: 512 dispatches of one threadgroup of `lcg_step` over the +/// same 256 words, each its own increment by `setBytes`, each reading what the one before wrote. +fn dispatch_chain() -> Plan { + const WORDS: usize = 256; + const STEPS: u32 = 512; + let increment = |step: u32| 1_013_904_223u32.wrapping_add(step); + let input = words(5, WORDS); + let output = (input.iter()) + .map(|&word| { + (0..STEPS).fold(word, |word, step| { + word.wrapping_mul(1_664_525).wrapping_add(increment(step)) + }) + }) + .collect(); + let dispatches = (0..STEPS) + .map(|step| { + let set_bytes = bytes(1, increment(step).to_le_bytes().to_vec()); + Dispatch { + function: "lcg_step".to_owned(), + bindings: match step { + 0 => vec![buffer(0, 0), set_bytes], + _ => vec![set_bytes], + }, + grid: Grid::groups_of_256(1), + } + }) + .collect(); + Plan { + name: "dispatch_chain".to_owned(), + buffers: vec![private(word_bytes(&input))], + dispatches, + expect: vec![Expect { + buffer: 0, + values: Values::Words(output), + }], + } +} + +/// `count` words of SplitMix64 from `seed`, the low half of each output. +fn words(seed: u64, count: usize) -> Vec { + let mut state = seed; + (0..count) + .map(|_| { + state = state.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = state; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + (z ^ (z >> 31)) as u32 + }) + .collect() +} + +fn word_bytes(words: &[u32]) -> Vec { + words.iter().flat_map(|word| word.to_le_bytes()).collect() +} + +fn float_bytes(values: &[f32]) -> Vec { + values + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect() +} + +/// A `Private` buffer starting with `contents`. +fn private(contents: Vec) -> BufferPlan { + BufferPlan { + length: contents.len() as u64, + storage: Storage::Private, + contents: Some(contents), + } +} + +/// A `Private` buffer of `length` bytes whose first run writes before it reads. +fn unset(length: u64) -> BufferPlan { + BufferPlan { + length, + storage: Storage::Private, + contents: None, + } +} + +/// `setBuffer:offset:atIndex:` of the plan's buffer `buffer` at its start. +fn buffer(index: u32, buffer: usize) -> Binding { + Binding::Buffer { + index, + buffer, + offset: 0, + } +} + +/// `setBytes:length:atIndex:`. +fn bytes(index: u32, bytes: Vec) -> Binding { + Binding::Bytes { index, bytes } +} diff --git a/crates/metal2vulkan-harness/src/bin/harness.rs b/crates/metal2vulkan-harness/src/bin/harness.rs new file mode 100644 index 000000000..1487dd79a --- /dev/null +++ b/crates/metal2vulkan-harness/src/bin/harness.rs @@ -0,0 +1,149 @@ +//! The harness's command: the authored workloads on one runtime, checked, then timed (the crate's +//! docs). +//! +//! ```text +//! harness --runtime old [--runs N] [--warmup N] [--only NAME,NAME...] +//! ``` +//! +//! It exits 0 when every workload it ran matched its reference, 1 when one did not or failed, +//! and 2 when it could not start. + +use metal2vulkan_harness::run::{percentile, Harness, Report, Runs}; +use metal2vulkan_harness::{authored, old, Code, Device, Result}; +use std::process::ExitCode; + +/// The command's arguments. +struct Args { + runtime: String, + runs: Runs, + only: Option>, +} + +const USAGE: &str = "usage: harness --runtime old [--runs N] [--warmup N] [--only NAME,NAME...]"; + +fn main() -> ExitCode { + let ran = parse(std::env::args().skip(1)).and_then(|args| match args.runtime.as_str() { + "old" => run_all(&old::system_default()?, &args), + other => Err(format!("no runtime {other}; the runtimes are: old").into()), + }); + match ran { + Ok(true) => ExitCode::SUCCESS, + Ok(false) => ExitCode::FAILURE, + Err(why) => { + eprintln!("harness: {why}"); + ExitCode::from(2) + } + } +} + +fn parse(mut args: impl Iterator) -> Result { + let mut parsed = Args { + runtime: String::new(), + runs: Runs { + warmup: 5, + timed: 200, + }, + only: None, + }; + while let Some(flag) = args.next() { + let mut value = || { + args.next() + .ok_or_else(|| format!("{flag} needs a value; {USAGE}")) + }; + match flag.as_str() { + "--runtime" => parsed.runtime = value()?, + "--runs" => parsed.runs.timed = value()?.parse()?, + "--warmup" => parsed.runs.warmup = value()?.parse()?, + "--only" => { + let names: Vec = value()?.split(',').map(str::to_owned).collect(); + for name in &names { + if !authored::WORKLOADS.iter().any(|(known, _)| known == name) { + let known = authored::WORKLOADS.map(|(known, _)| known).join(", "); + return Err( + format!("no workload {name}; the workloads are: {known}").into() + ); + } + } + parsed.only = Some(names); + } + _ => return Err(format!("unknown argument {flag}; {USAGE}").into()), + } + } + if parsed.runtime.is_empty() { + return Err(USAGE.into()); + } + Ok(parsed) +} + +/// Every selected workload on `device`; whether each matched its reference. +fn run_all(device: &D, args: &Args) -> Result { + let runtime = &args.runtime; + println!("device: {}", device.name()); + println!( + "runtime: {runtime}; warmup runs {}, timed runs {}", + args.runs.warmup, args.runs.timed + ); + let air = authored::library_air()?; + let library = device.new_library(Code::Air(&air))?; + let harness = Harness::new(device, &library)?; + println!( + "{:<17} {:>10} {:>11} {:>11} {:>11} {:>18} {:>15} gauges @100 -> @200", + "workload", + "dispatches", + "gpu_us_p10", + "gpu_us_p50", + "gpu_us_p90", + "encode_ns/dispatch", + "cpu_ns/dispatch", + ); + let mut matched = true; + for (name, build) in authored::WORKLOADS { + if (args.only.as_ref()).is_some_and(|only| !only.iter().any(|selected| selected == name)) { + continue; + } + match harness.run(&library, &build(), args.runs) { + Ok(report) => print(runtime, name, &report), + Err(why) => { + println!("{name}: FAILED: {why}"); + matched = false; + } + } + } + Ok(matched) +} + +/// `report`'s row, and its matrix line where it timed a run. +fn print(runtime: &str, name: &str, report: &Report) { + let gpu = |p| percentile(&report.gpu_us, p).map_or("-".to_owned(), |us| format!("{us:.1}")); + let per_dispatch = |values: &[f64]| { + percentile(values, 50).map_or("-".to_owned(), |ns| { + format!("{:.0}", ns / report.dispatches as f64) + }) + }; + let gauges = match report.gauges.as_slice() { + [] => "-".to_owned(), + [(_, only)] => (only.iter()) + .map(|(gauge, value)| format!("{gauge} {value}")) + .collect::>() + .join(", "), + [(_, first), (_, last), ..] => (first.iter().zip(last)) + .map(|((gauge, first), (_, last))| { + let grew = if last > first { " GREW" } else { "" }; + format!("{gauge} {first} -> {last}{grew}") + }) + .collect::>() + .join(", "), + }; + println!( + "{name:<17} {:>10} {:>11} {:>11} {:>11} {:>18} {:>15} {gauges}", + report.dispatches, + gpu(10), + gpu(50), + gpu(90), + per_dispatch(&report.encode_ns), + per_dispatch(&report.cpu_ns), + ); + if let Some(median) = percentile(&report.gpu_us, 50) { + println!("M2V-MATRIX time harness-{runtime}/{name} {median:.3}"); + } +} diff --git a/crates/metal2vulkan-harness/src/clocks.rs b/crates/metal2vulkan-harness/src/clocks.rs new file mode 100644 index 000000000..dfb07ce02 --- /dev/null +++ b/crates/metal2vulkan-harness/src/clocks.rs @@ -0,0 +1,26 @@ +//! The process's CPU clock. + +/// The whole process's CPU time, every thread of it, user and system, in nanoseconds; `None` +/// where the host does not answer it (and on hosts other than unix, whose process times count in +/// scheduler ticks, too coarse for one command buffer). +#[cfg(unix)] +pub fn process_cpu_nanos() -> Option { + let mut when = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: `clock_gettime` writes the one `timespec` it is given and reads nothing else. + let answered = unsafe { libc::clock_gettime(libc::CLOCK_PROCESS_CPUTIME_ID, &mut when) }; + if answered != 0 { + return None; + } + let seconds = u64::try_from(when.tv_sec).ok()?; + let nanos = u64::try_from(when.tv_nsec).ok()?; + seconds.checked_mul(1_000_000_000)?.checked_add(nanos) +} + +/// See the unix form: no host clock fine enough here. +#[cfg(not(unix))] +pub fn process_cpu_nanos() -> Option { + None +} diff --git a/crates/metal2vulkan-harness/src/lib.rs b/crates/metal2vulkan-harness/src/lib.rs new file mode 100644 index 000000000..e9627c697 --- /dev/null +++ b/crates/metal2vulkan-harness/src/lib.rs @@ -0,0 +1,164 @@ +//! The runtimes' compute harness: one set of Metal compute workloads run through a runtime's +//! Metal-shaped API on one GPU, with no guest. Each workload's result is checked against a CPU +//! reference before any time is reported. It is a regression gate between the runtimes, not a +//! measure against native Metal. +//! +//! The traits below are the Metal compute subset the workloads call, one method per Metal call. +//! A runtime implements them once: the old runtime in [`old`], which the cutover deletes with its +//! file. +//! +//! A workload is a [`plan::Plan`]: its buffers and their starting contents, the dispatches of one +//! run, and the contents its buffers must hold after the first run. [`run::run`] makes its +//! objects, checks the first run, then times the rest. The authored workloads ([`authored`]) are +//! MSL kernels committed as public fixtures (`crates/metal2vulkan-validation/fixtures/public/ +//! harness/workloads.metal`, compiled by `scripts/regen-air-fixtures --dir harness`); their +//! library is the fixture's LLVM text, assembled by `llvm-as` from `PATH`. +//! +//! ```sh +//! cargo run --release -p metal2vulkan-harness -- --runtime old [--runs 200] [--warmup 5] \ +//! [--only bandwidth,alu] +//! ``` +//! +//! The command prints, per workload: the GPU time of a run (`GPUEndTime - GPUStartTime`) at the +//! 10th, 50th and 90th percentiles, the encoding thread's wall time per dispatch from the command +//! buffer's creation through `commit`'s return, and the process's CPU time per dispatch from +//! there to the wait's return (unix only), each the median of the timed runs; and the runtime's +//! gauges after the 100th and 200th timed runs. For each workload it also prints a line +//! `M2V-MATRIX time harness-/ ` for the matrix's runner. + +use std::ptr::NonNull; + +pub mod authored; +mod clocks; +pub mod old; +pub mod plan; +pub mod run; + +#[cfg(test)] +mod tests; + +/// A harness error: a runtime's own, boxed, or the harness's words. +pub type Error = Box; + +/// A harness result. +pub type Result = std::result::Result; + +/// An `MTLSize`: width, height and depth. +pub type Size = [u64; 3]; + +/// The storage mode of a buffer the workloads make (`MTLStorageMode`); the CPU cache mode and +/// hazard tracking are Metal's defaults. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Storage { + /// `MTLStorageModeShared`: the CPU reads and writes it through `contents`. + Shared, + /// `MTLStorageModePrivate`: the GPU's alone. + Private, +} + +/// A library's code. +#[derive(Clone, Copy, Debug)] +pub enum Code<'a> { + /// A metallib, as `newLibraryWithData:error:` takes it. + Metallib(&'a [u8]), + /// AIR bitcode, which Metal takes in no call: the translator's library of it. + Air(&'a [u8]), +} + +/// `MTLDevice`: the device a runtime opened, and the types of the objects it makes. +pub trait Device: Sized { + /// `MTLBuffer`. + type Buffer: Buffer; + /// `MTLLibrary`. + type Library: Library; + /// `MTLFunction`. + type Function; + /// `MTLComputePipelineState`. + type ComputePipelineState; + /// `MTLCommandQueue`. + type CommandQueue: CommandQueue; + /// `MTLCommandBuffer`. + type CommandBuffer: CommandBuffer; + /// `MTLComputeCommandEncoder`. + type ComputeCommandEncoder: ComputeCommandEncoder; + + /// `name`. + fn name(&self) -> String; + + /// `newBufferWithLength:options:` of `storage`. + fn new_buffer(&self, length: u64, storage: Storage) -> Result; + + /// `newLibraryWithData:error:` of a metallib; of AIR bitcode, the translator's library. + fn new_library(&self, code: Code<'_>) -> Result; + + /// `newComputePipelineStateWithFunction:error:`. + fn new_compute_pipeline_state( + &self, + function: &Self::Function, + ) -> Result; + + /// `newCommandQueue`. + fn new_command_queue(&self) -> Result; + + /// The runtime's live gauges by name: how many of each thing it holds now. No Metal + /// counterpart. + fn gauges(&self) -> Vec<(&'static str, u64)>; +} + +/// `MTLBuffer`. +pub trait Buffer { + /// `contents`: the CPU address of the buffer's bytes; `None` for `Private` storage. + fn contents(&self) -> Option>; +} + +/// `MTLLibrary`. +pub trait Library { + /// `newFunctionWithName:`. + fn new_function(&self, name: &str) -> Result; +} + +/// `MTLCommandQueue`. +pub trait CommandQueue { + /// `commandBuffer`. + fn command_buffer(&self) -> Result; +} + +/// `MTLCommandBuffer`. +pub trait CommandBuffer { + /// `computeCommandEncoder`: a serial compute encoder. + fn compute_command_encoder(&self) -> Result; + + /// `commit`. + fn commit(&self) -> Result<()>; + + /// `waitUntilCompleted`; an error unless the command buffer's `status` is then + /// `MTLCommandBufferStatusCompleted`. + fn wait_until_completed(&self) -> Result<()>; + + /// `GPUStartTime`, in seconds. + fn gpu_start_time(&self) -> Result; + + /// `GPUEndTime`, in seconds. + fn gpu_end_time(&self) -> Result; +} + +/// `MTLComputeCommandEncoder`. +pub trait ComputeCommandEncoder { + /// `setComputePipelineState:`. + fn set_compute_pipeline_state(&mut self, state: &D::ComputePipelineState) -> Result<()>; + + /// `setBuffer:offset:atIndex:`. + fn set_buffer(&mut self, buffer: &D::Buffer, offset: u64, index: u32) -> Result<()>; + + /// `setBytes:length:atIndex:`. + fn set_bytes(&mut self, bytes: &[u8], index: u32) -> Result<()>; + + /// `dispatchThreadgroups:threadsPerThreadgroup:`. + fn dispatch_threadgroups(&mut self, groups: Size, threads: Size) -> Result<()>; + + /// `dispatchThreads:threadsPerThreadgroup:`. + fn dispatch_threads(&mut self, threads: Size, per_group: Size) -> Result<()>; + + /// `endEncoding`. + fn end_encoding(self) -> Result<()>; +} diff --git a/crates/metal2vulkan-harness/src/old.rs b/crates/metal2vulkan-harness/src/old.rs new file mode 100644 index 000000000..1e98134e4 --- /dev/null +++ b/crates/metal2vulkan-harness/src/old.rs @@ -0,0 +1,161 @@ +//! The old runtime (`metal2vulkan-runtime`) behind the harness's traits, each method its call of +//! the same name. The cutover deletes this file, its `mod` line, the `--runtime old` arm of the +//! command and the crate's dependency on the old runtime. + +use crate::{Code, Result, Size, Storage}; +use metal2vulkan_runtime as runtime; +use runtime::{CommandBufferStatus, PipelineOptions, ResourceOptions}; +use std::ptr::NonNull; + +/// The old runtime's `MTLCreateSystemDefaultDevice`: the preferred Vulkan physical device +/// (discrete, then integrated, virtual, CPU) it can open, with its default options. +pub fn system_default() -> Result { + Ok(runtime::Device::system_default()?) +} + +fn size(size: Size) -> runtime::Size { + runtime::Size::new(size[0], size[1], size[2]) +} + +impl crate::Device for runtime::Device { + type Buffer = runtime::Buffer; + type Library = runtime::Library; + type Function = runtime::Function; + type ComputePipelineState = runtime::ComputePipelineState; + type CommandQueue = runtime::CommandQueue; + type CommandBuffer = runtime::CommandBuffer; + type ComputeCommandEncoder = runtime::ComputeCommandEncoder; + + fn name(&self) -> String { + runtime::Device::name(self).to_owned() + } + + fn new_buffer(&self, length: u64, storage: Storage) -> Result { + let options = match storage { + Storage::Shared => ResourceOptions::shared(), + Storage::Private => ResourceOptions::private(), + }; + Ok(runtime::Device::new_buffer(self, length, options)?) + } + + fn new_library(&self, code: Code<'_>) -> Result { + match code { + Code::Metallib(bytes) => Ok(self.new_library_with_data(bytes)?), + Code::Air(bytes) => { + let library = metal2vulkan::library::Library::from_air(bytes)?; + Ok(self.new_library_with_compile_library(library)) + } + } + } + + fn new_compute_pipeline_state( + &self, + function: &runtime::Function, + ) -> Result { + Ok(self.new_compute_pipeline_state_with_function(function, &PipelineOptions::default())?) + } + + fn new_command_queue(&self) -> Result { + Ok(runtime::Device::new_command_queue(self)?) + } + + /// Its pooled and dedicated `VkDeviceMemory` blocks with a placement in them, and its empty + /// kept ones (`WorkCounts`). + fn gauges(&self) -> Vec<(&'static str, u64)> { + let counts = self.work_counts(); + vec![ + ("memory_blocks", counts.memory_blocks_live), + ("dedicated_blocks", counts.dedicated_memory_blocks_live), + ("empty_blocks", counts.empty_memory_blocks_live), + ] + } +} + +impl crate::Buffer for runtime::Buffer { + fn contents(&self) -> Option> { + runtime::Buffer::contents(self) + } +} + +impl crate::Library for runtime::Library { + fn new_function(&self, name: &str) -> Result { + Ok(self.new_function_with_name(name)?) + } +} + +impl crate::CommandQueue for runtime::CommandQueue { + fn command_buffer(&self) -> Result { + Ok(runtime::CommandQueue::command_buffer(self)?) + } +} + +impl crate::CommandBuffer for runtime::CommandBuffer { + fn compute_command_encoder(&self) -> Result { + Ok(runtime::CommandBuffer::compute_command_encoder(self)?) + } + + fn commit(&self) -> Result<()> { + Ok(runtime::CommandBuffer::commit(self)?) + } + + fn wait_until_completed(&self) -> Result<()> { + runtime::CommandBuffer::wait_until_completed(self)?; + match self.status() { + CommandBufferStatus::Completed => Ok(()), + status => { + Err(format!("the command buffer ended {status:?}: {:?}", self.error()).into()) + } + } + } + + fn gpu_start_time(&self) -> Result { + Ok(runtime::CommandBuffer::gpu_start_time(self)?) + } + + fn gpu_end_time(&self) -> Result { + Ok(runtime::CommandBuffer::gpu_end_time(self)?) + } +} + +impl crate::ComputeCommandEncoder for runtime::ComputeCommandEncoder { + fn set_compute_pipeline_state(&mut self, state: &runtime::ComputePipelineState) -> Result<()> { + Ok(runtime::ComputeCommandEncoder::set_compute_pipeline_state( + self, state, + )?) + } + + fn set_buffer(&mut self, buffer: &runtime::Buffer, offset: u64, index: u32) -> Result<()> { + Ok(runtime::ComputeCommandEncoder::set_buffer( + self, + Some(buffer), + offset, + index, + )?) + } + + fn set_bytes(&mut self, bytes: &[u8], index: u32) -> Result<()> { + Ok(runtime::ComputeCommandEncoder::set_bytes( + self, bytes, index, + )?) + } + + fn dispatch_threadgroups(&mut self, groups: Size, threads: Size) -> Result<()> { + Ok(runtime::ComputeCommandEncoder::dispatch_threadgroups( + self, + size(groups), + size(threads), + )?) + } + + fn dispatch_threads(&mut self, threads: Size, per_group: Size) -> Result<()> { + Ok(runtime::ComputeCommandEncoder::dispatch_threads( + self, + size(threads), + size(per_group), + )?) + } + + fn end_encoding(self) -> Result<()> { + Ok(runtime::ComputeCommandEncoder::end_encoding(self)?) + } +} diff --git a/crates/metal2vulkan-harness/src/plan.rs b/crates/metal2vulkan-harness/src/plan.rs new file mode 100644 index 000000000..b813a70b8 --- /dev/null +++ b/crates/metal2vulkan-harness/src/plan.rs @@ -0,0 +1,222 @@ +//! A workload as data: what [`run::run`](crate::run::run) makes, the calls of one run, and what +//! the first run must leave in the buffers. + +use crate::{Result, Size, Storage}; + +/// One workload. +#[derive(Clone, Debug)] +pub struct Plan { + /// Its name in reports. + pub name: String, + /// The buffers it makes, in order; dispatches and expectations name them by index. + pub buffers: Vec, + /// The dispatches of one run, in order, all in one compute encoder of one command buffer. + pub dispatches: Vec, + /// What the first run must leave in its buffers. + pub expect: Vec, +} + +/// One buffer of a plan. +#[derive(Clone, Debug)] +pub struct BufferPlan { + /// Its length in bytes: a multiple of 16, the harness's transfer unit. + pub length: u64, + /// Its storage mode. + pub storage: Storage, + /// The bytes it starts with, `length` of them: for `Shared` storage written through + /// `contents`, for `Private` copied in from a `Shared` buffer by the harness's own kernel. + /// `None`: as `newBufferWithLength:` made it. + pub contents: Option>, +} + +/// One dispatch: the calls an encoder makes for it. The pipeline state is set where it differs +/// from the dispatch before's; bindings stay set for the dispatches after, as Metal's do. +#[derive(Clone, Debug)] +pub struct Dispatch { + /// The kernel's name in the plan's library. + pub function: String, + /// The binding calls before the dispatch, in order. + pub bindings: Vec, + /// The dispatch call. + pub grid: Grid, +} + +/// A binding call. +#[derive(Clone, Debug)] +pub enum Binding { + /// `setBuffer:offset:atIndex:` of the plan's buffer `buffer`. + Buffer { + /// The argument table index. + index: u32, + /// The plan's buffer. + buffer: usize, + /// The offset in it. + offset: u64, + }, + /// `setBytes:length:atIndex:`. + Bytes { + /// The argument table index. + index: u32, + /// The bytes. + bytes: Vec, + }, +} + +/// A dispatch call. +#[derive(Clone, Copy, Debug)] +pub enum Grid { + /// `dispatchThreadgroups:threadsPerThreadgroup:`. + Threadgroups { + /// Threadgroups per grid. + groups: Size, + /// Threads per threadgroup. + threads: Size, + }, + /// `dispatchThreads:threadsPerThreadgroup:`. + Threads { + /// Threads per grid. + threads: Size, + /// Threads per threadgroup. + per_group: Size, + }, +} + +impl Grid { + /// Threadgroups of 256 threads in one dimension. + pub fn groups_of_256(groups: u64) -> Grid { + Grid::Threadgroups { + groups: [groups, 1, 1], + threads: [256, 1, 1], + } + } +} + +/// What a buffer must hold after the first run. +#[derive(Clone, Debug)] +pub struct Expect { + /// The plan's buffer. + pub buffer: usize, + /// Its contents from its start. + pub values: Values, +} + +/// Expected contents. +#[derive(Clone, Debug)] +pub enum Values { + /// 32-bit words, each exactly. + Words(Vec), + /// `float`s, each within `tolerance` of its value: the device's own arithmetic may differ + /// from the CPU's in its last bits. + Floats { + /// The values. + values: Vec, + /// The largest difference allowed. + tolerance: f32, + }, +} + +impl Values { + /// The bytes the values cover. + pub fn length(&self) -> u64 { + let count = match self { + Values::Words(words) => words.len(), + Values::Floats { values, .. } => values.len(), + }; + 4 * count as u64 + } + + /// `Ok` where `bytes` (little-endian) holds the values; else how many differ and the first. + pub fn compare(&self, bytes: &[u8]) -> Result<()> { + let words = bytes + .as_chunks::<4>() + .0 + .iter() + .map(|w| u32::from_le_bytes(*w)); + let (mut differ, mut first) = (0usize, None); + let mut note = |index: usize, got: String, want: String| { + differ += 1; + first.get_or_insert((index, got, want)); + }; + match self { + Values::Words(want) => { + for (index, (got, &want)) in words.zip(want).enumerate() { + if got != want { + note(index, format!("{got:#x}"), format!("{want:#x}")); + } + } + } + Values::Floats { values, tolerance } => { + for (index, (got, &want)) in words.map(f32::from_bits).zip(values).enumerate() { + // False for a NaN on either side, which then differs. + let within = (got - want).abs() <= *tolerance; + if !within { + note(index, format!("{got}"), format!("{want} +- {tolerance}")); + } + } + } + } + match first { + None => Ok(()), + Some((index, got, want)) => Err(format!( + "{differ} values differ; the first, [{index}], is {got}, not {want}" + ) + .into()), + } + } +} + +impl Plan { + /// `Ok` where every index it names exists and every length is whole and agrees. + pub fn validate(&self) -> Result<()> { + let name = &self.name; + for (i, buffer) in self.buffers.iter().enumerate() { + if buffer.length == 0 || buffer.length % 16 != 0 { + return Err(format!( + "{name}: buffer {i}'s length {} is not a positive multiple of 16", + buffer.length + ) + .into()); + } + if let Some(contents) = &buffer.contents { + if contents.len() as u64 != buffer.length { + return Err(format!( + "{name}: buffer {i} has {} bytes of contents for {}", + contents.len(), + buffer.length + ) + .into()); + } + } + } + let known = |buffer: usize| buffer < self.buffers.len(); + for (i, dispatch) in self.dispatches.iter().enumerate() { + for binding in &dispatch.bindings { + if let Binding::Buffer { buffer, .. } = binding { + if !known(*buffer) { + return Err(format!( + "{name}: dispatch {i} binds buffer {buffer}, which the plan lacks" + ) + .into()); + } + } + } + } + for expect in &self.expect { + if !known(expect.buffer) { + return Err(format!( + "{name}: an expectation names buffer {}, which the plan lacks", + expect.buffer + ) + .into()); + } + if expect.values.length() > self.buffers[expect.buffer].length { + return Err(format!( + "{name}: buffer {} is shorter than its expected values", + expect.buffer + ) + .into()); + } + } + Ok(()) + } +} diff --git a/crates/metal2vulkan-harness/src/run.rs b/crates/metal2vulkan-harness/src/run.rs new file mode 100644 index 000000000..2e65ed9ae --- /dev/null +++ b/crates/metal2vulkan-harness/src/run.rs @@ -0,0 +1,275 @@ +//! A plan on a device: its objects made, its first run checked, the runs after it timed. + +use crate::plan::{Binding, BufferPlan, Grid, Plan}; +use crate::{ + clocks, Buffer, CommandBuffer, CommandQueue, ComputeCommandEncoder, Device, Library, Result, + Storage, +}; +use std::time::Instant; + +/// The kernel of the authored library that moves bytes for the harness, 16 a thread. +const COPY_FUNCTION: &str = "copy_words"; + +/// The most threadgroups a dispatch of the copy kernel takes in x: the least +/// `maxComputeWorkGroupCount[0]` Vulkan allows. +const COPY_GROUPS: u64 = 65535; + +/// How many runs follow the checked first one: `warmup` untimed, then `timed`. +#[derive(Clone, Copy, Debug)] +pub struct Runs { + /// Untimed runs. + pub warmup: u32, + /// Timed runs. + pub timed: u32, +} + +/// What the timed runs of a plan measured. +#[derive(Clone, Debug, Default)] +pub struct Report { + /// The dispatches of a run. + pub dispatches: usize, + /// Each run's GPU time, `GPUEndTime - GPUStartTime`, in microseconds. + pub gpu_us: Vec, + /// Each run's encoding thread's wall time from the command buffer's creation through + /// `commit`'s return, in nanoseconds. + pub encode_ns: Vec, + /// Each run's process CPU time from before the command buffer's creation through the wait's + /// return, in nanoseconds; empty where the host has no such clock. + pub cpu_ns: Vec, + /// The device's gauges after the 100th and the 200th timed run, where there were that many. + pub gauges: Vec<(u32, Vec<(&'static str, u64)>)>, +} + +/// The `p`th percentile of `values` by nearest rank; `None` for no values. +pub fn percentile(values: &[f64], p: u32) -> Option { + let mut sorted = values.to_vec(); + sorted.sort_by(f64::total_cmp); + let rank = (p as usize * sorted.len()).div_ceil(100).max(1); + sorted.get(rank - 1).copied() +} + +/// The harness on a device: its own queue and copy kernel. +pub struct Harness<'d, D: Device> { + device: &'d D, + queue: D::CommandQueue, + copy: D::ComputePipelineState, +} + +/// A plan's objects on the device. +struct Made { + buffers: Vec, + states: Vec, + /// The index in `states` of each dispatch's. + state_of: Vec, +} + +impl<'d, D: Device> Harness<'d, D> { + /// The harness on `device`, its copy kernel from `library`, the authored workloads'. + pub fn new(device: &'d D, library: &D::Library) -> Result { + let copy = device.new_compute_pipeline_state(&library.new_function(COPY_FUNCTION)?)?; + Ok(Harness { + device, + queue: device.new_command_queue()?, + copy, + }) + } + + /// `plan`'s kernels from `library`: its first run, checked against its expectations, then + /// `runs`. + pub fn run(&self, library: &D::Library, plan: &Plan, runs: Runs) -> Result { + plan.validate()?; + let made = self.make(library, plan)?; + self.fill(&plan.buffers, &made.buffers)?; + let first = self.encode(plan, &made)?; + first.commit()?; + first.wait_until_completed()?; + for expect in &plan.expect { + let storage = plan.buffers[expect.buffer].storage; + let bytes = self.read( + &made.buffers[expect.buffer], + storage, + expect.values.length(), + )?; + let buffer = expect.buffer; + (expect.values.compare(&bytes)) + .map_err(|why| format!("{}: buffer {buffer}: {why}", plan.name))?; + } + for _ in 0..runs.warmup { + let command_buffer = self.encode(plan, &made)?; + command_buffer.commit()?; + command_buffer.wait_until_completed()?; + } + let mut report = Report { + dispatches: plan.dispatches.len(), + ..Report::default() + }; + for run in 1..=runs.timed { + let cpu = clocks::process_cpu_nanos(); + let started = Instant::now(); + let command_buffer = self.encode(plan, &made)?; + command_buffer.commit()?; + let encoded = started.elapsed(); + command_buffer.wait_until_completed()?; + if let (Some(before), Some(after)) = (cpu, clocks::process_cpu_nanos()) { + report.cpu_ns.push(after.saturating_sub(before) as f64); + } + report.encode_ns.push(encoded.as_nanos() as f64); + let gpu = command_buffer.gpu_end_time()? - command_buffer.gpu_start_time()?; + report.gpu_us.push(gpu * 1e6); + if run == 100 || run == 200 { + report.gauges.push((run, self.device.gauges())); + } + } + Ok(report) + } + + /// `plan`'s pipeline states, one per kernel, and its buffers. + fn make(&self, library: &D::Library, plan: &Plan) -> Result> { + let mut functions: Vec<&str> = Vec::new(); + let mut states = Vec::new(); + let mut state_of = Vec::with_capacity(plan.dispatches.len()); + for dispatch in &plan.dispatches { + let name = dispatch.function.as_str(); + let at = match functions.iter().position(|&known| known == name) { + Some(at) => at, + None => { + let function = library.new_function(name)?; + states.push(self.device.new_compute_pipeline_state(&function)?); + functions.push(name); + functions.len() - 1 + } + }; + state_of.push(at); + } + let buffers = (plan.buffers.iter()) + .map(|buffer| self.device.new_buffer(buffer.length, buffer.storage)) + .collect::>>()?; + Ok(Made { + buffers, + states, + state_of, + }) + } + + /// One run of `plan`: a command buffer of one compute encoder, ended, not committed. + fn encode(&self, plan: &Plan, made: &Made) -> Result { + let command_buffer = self.queue.command_buffer()?; + let mut encoder = command_buffer.compute_command_encoder()?; + let mut current = None; + for (dispatch, &state) in plan.dispatches.iter().zip(&made.state_of) { + if current != Some(state) { + encoder.set_compute_pipeline_state(&made.states[state])?; + current = Some(state); + } + for binding in &dispatch.bindings { + match binding { + Binding::Buffer { + index, + buffer, + offset, + } => encoder.set_buffer(&made.buffers[*buffer], *offset, *index)?, + Binding::Bytes { index, bytes } => encoder.set_bytes(bytes, *index)?, + } + } + match dispatch.grid { + Grid::Threadgroups { groups, threads } => { + encoder.dispatch_threadgroups(groups, threads)? + } + Grid::Threads { threads, per_group } => { + encoder.dispatch_threads(threads, per_group)? + } + } + } + encoder.end_encoding()?; + Ok(command_buffer) + } + + /// Every buffer's starting contents: a `Shared` one's written through `contents`, a + /// `Private` one's copied in from a `Shared` buffer, all in one command buffer, waited for. + fn fill(&self, plans: &[BufferPlan], buffers: &[D::Buffer]) -> Result<()> { + let mut staged = Vec::new(); + for (plan, buffer) in plans.iter().zip(buffers) { + let Some(contents) = &plan.contents else { + continue; + }; + match plan.storage { + Storage::Shared => write(buffer, contents)?, + Storage::Private => { + let stage = self.device.new_buffer(plan.length, Storage::Shared)?; + write(&stage, contents)?; + staged.push((stage, buffer, plan.length)); + } + } + } + if staged.is_empty() { + return Ok(()); + } + let command_buffer = self.queue.command_buffer()?; + let mut encoder = command_buffer.compute_command_encoder()?; + encoder.set_compute_pipeline_state(&self.copy)?; + for (stage, buffer, length) in &staged { + copy::(&mut encoder, stage, buffer, *length)?; + } + encoder.end_encoding()?; + command_buffer.commit()?; + command_buffer.wait_until_completed() + } + + /// The first `length` bytes of `buffer`: a `Shared` one's through `contents`, a `Private` + /// one's copied out to a `Shared` buffer first. + fn read(&self, buffer: &D::Buffer, storage: Storage, length: u64) -> Result> { + if storage == Storage::Shared { + return bytes(buffer, length); + } + // Buffer lengths are whole multiples of 16 (`Plan::validate`), so this is within it. + let whole = length.next_multiple_of(16); + let stage = self.device.new_buffer(whole, Storage::Shared)?; + let command_buffer = self.queue.command_buffer()?; + let mut encoder = command_buffer.compute_command_encoder()?; + encoder.set_compute_pipeline_state(&self.copy)?; + copy::(&mut encoder, buffer, &stage, whole)?; + encoder.end_encoding()?; + command_buffer.commit()?; + command_buffer.wait_until_completed()?; + bytes(&stage, length) + } +} + +/// Dispatches of the copy kernel, already set on `encoder`, moving the first `length` bytes (a +/// multiple of 16) of `from` to `to`, in as many dispatches as the threadgroup count limit needs. +fn copy( + encoder: &mut D::ComputeCommandEncoder, + from: &D::Buffer, + to: &D::Buffer, + length: u64, +) -> Result<()> { + let most = COPY_GROUPS * 256 * 16; + let mut offset = 0; + while offset < length { + let bytes = (length - offset).min(most); + encoder.set_buffer(from, offset, 0)?; + encoder.set_buffer(to, offset, 1)?; + encoder.dispatch_threads([bytes / 16, 1, 1], [256, 1, 1])?; + offset += bytes; + } + Ok(()) +} + +/// `bytes` written at the start of the `Shared` buffer `buffer`, which no GPU work uses now. +fn write(buffer: &impl Buffer, bytes: &[u8]) -> Result<()> { + let contents = buffer.contents().ok_or("a Shared buffer has no contents")?; + // SAFETY: `contents` holds the buffer's bytes, at least `bytes.len()` of them (the plan's + // length, `Plan::validate`), and no command buffer uses them now. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) }; + Ok(()) +} + +/// A copy of the first `length` bytes of the `Shared` buffer `buffer`, which no GPU work writes +/// now. +fn bytes(buffer: &impl Buffer, length: u64) -> Result> { + let contents = buffer.contents().ok_or("a Shared buffer has no contents")?; + // SAFETY: `contents` holds the buffer's bytes, at least `length` of them (the caller's + // length), and no command buffer writes them now. + let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), length as usize) }; + Ok(bytes.to_vec()) +} diff --git a/crates/metal2vulkan-harness/src/tests.rs b/crates/metal2vulkan-harness/src/tests.rs new file mode 100644 index 000000000..640653e8f --- /dev/null +++ b/crates/metal2vulkan-harness/src/tests.rs @@ -0,0 +1,85 @@ +//! The harness's CPU-side parts: its statistics, its comparisons and its plans. + +use crate::authored::WORKLOADS; +use crate::plan::{Binding, BufferPlan, Dispatch, Expect, Grid, Plan, Values}; +use crate::run::percentile; +use crate::Storage; + +#[test] +fn percentiles_take_the_nearest_rank() { + let values: Vec = (1..=10).rev().map(f64::from).collect(); + assert_eq!(percentile(&values, 10), Some(1.0)); + assert_eq!(percentile(&values, 50), Some(5.0)); + assert_eq!(percentile(&values, 90), Some(9.0)); + assert_eq!(percentile(&[7.0], 10), Some(7.0)); + assert_eq!(percentile(&[], 50), None); +} + +fn le(words: &[u32]) -> Vec { + words.iter().flat_map(|word| word.to_le_bytes()).collect() +} + +#[test] +fn a_comparison_names_how_many_values_differ_and_the_first() { + let want = Values::Words(vec![1, 2, 3, 4]); + assert!(want.compare(&le(&[1, 2, 3, 4])).is_ok()); + let why = want.compare(&le(&[1, 9, 3, 8])).unwrap_err().to_string(); + assert_eq!(why, "2 values differ; the first, [1], is 0x9, not 0x2"); +} + +#[test] +fn floats_differ_past_their_tolerance_and_at_a_nan() { + let want = Values::Floats { + values: vec![1.0, 2.0], + tolerance: 0.25, + }; + let floats = |values: [f32; 2]| le(&values.map(f32::to_bits)); + assert!(want.compare(&floats([1.2, 1.8])).is_ok()); + assert!(want.compare(&floats([1.3, 2.0])).is_err()); + assert!(want.compare(&floats([f32::NAN, 2.0])).is_err()); +} + +fn one_buffer_plan(length: u64, contents: Option>, bound: usize) -> Plan { + Plan { + name: "probe".to_owned(), + buffers: vec![BufferPlan { + length, + storage: Storage::Private, + contents, + }], + dispatches: vec![Dispatch { + function: "copy_words".to_owned(), + bindings: vec![Binding::Buffer { + index: 0, + buffer: bound, + offset: 0, + }], + grid: Grid::groups_of_256(1), + }], + expect: vec![Expect { + buffer: 0, + values: Values::Words(vec![0; 4]), + }], + } +} + +#[test] +fn a_plan_with_a_part_length_or_a_missing_buffer_is_refused() { + assert!(one_buffer_plan(16, None, 0).validate().is_ok()); + assert!(one_buffer_plan(12, None, 0).validate().is_err()); + assert!(one_buffer_plan(16, Some(vec![0; 8]), 0).validate().is_err()); + assert!(one_buffer_plan(16, None, 1).validate().is_err()); + let mut short = one_buffer_plan(16, None, 0); + short.expect[0].values = Values::Words(vec![0; 5]); + assert!(short.validate().is_err()); +} + +/// Each authored plan is whole: its builder's inputs, kernels and references agree in shape. +#[test] +fn every_authored_plan_validates() { + for (name, build) in WORKLOADS { + let plan = build(); + assert_eq!(plan.name, name); + plan.validate().unwrap(); + } +} diff --git a/crates/metal2vulkan-harness/tests/authored.rs b/crates/metal2vulkan-harness/tests/authored.rs new file mode 100644 index 000000000..5ea7c3a93 --- /dev/null +++ b/crates/metal2vulkan-harness/tests/authored.rs @@ -0,0 +1,23 @@ +//! Every authored workload's first run matches its CPU reference on the old runtime, on the +//! device the cfg names (docs/VALIDATION.md). +#![cfg(any(m2v_gpu, m2v_cpu_icd))] + +use metal2vulkan_harness::run::{Harness, Runs}; +use metal2vulkan_harness::{authored, old, Code, Device}; + +#[test] +fn every_authored_workload_matches_its_reference_on_the_old_runtime() { + let device = old::system_default().unwrap(); + let air = authored::library_air().unwrap(); + let library = device.new_library(Code::Air(&air)).unwrap(); + let harness = Harness::new(&device, &library).unwrap(); + let runs = Runs { + warmup: 0, + timed: 1, + }; + for (name, build) in authored::WORKLOADS { + let report = + (harness.run(&library, &build(), runs)).unwrap_or_else(|why| panic!("{name}: {why}")); + assert_eq!(report.gpu_us.len(), 1, "{name}"); + } +} diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 8091cd0b4..7cf407df9 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -25,7 +25,7 @@ every option. ```sh cargo fmt --all cargo clippy --workspace --all-targets --all-features -- -D warnings -cargo nextest run -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-rt -p metal2vulkan-runtime -p metal2vulkan-devtools --all-features +cargo nextest run -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-rt -p metal2vulkan-runtime -p metal2vulkan-devtools -p metal2vulkan-harness --all-features cargo nextest run -p metal2vulkan-validation --all-features cargo test --workspace --all-features --doc ```