mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 03:39:52 +00:00
feat: add correctness-gated benchmark harness and a second interpreter
Add a manifest-driven benchmark binary that verifies each fixture against the independent reference and the GPU before timing it, reports per-stage CPU and GPU durations with medians and quartiles, and writes metadata, raw JSON and a markdown report. Extend the Metal backend with a profiled execution path that reads command-buffer GPU start and end times. Add a structurally independent second interpreter for the demo subset in the semantic-review suite. It imports neither the decoder, ISA nor reference and re-derives the encodings from the RDNA 2 field layout. A differential test compares both interpreters across all three fixtures on boundary-dense and pseudorandom inputs. Signed-off-by: Ranveer Soni <git@ranveersoni.me>
This commit is contained in:
15 files changed
+1378
-4
No files matched your search
@@ -52,6 +52,8 @@ Read docs/interfaces.md and docs/progress.md before implementation.
|
||||
- Run native GPU correctness: `scripts/test-gpu.sh`
|
||||
- Run the three RDNA-to-Metal fixtures: `scripts/demo.sh`
|
||||
- Run independent CPU validation: `cargo test --locked -p xenora-semantic-review`
|
||||
- Run the correctness-gated benchmark suite: `scripts/benchmark.sh` (idle machine, release, validation off)
|
||||
- Run source mutation on decoder/shader/ref: `scripts/mutation.sh` (R2 owns triage)
|
||||
- Check claims and dependency direction: `scripts/audit/claims.sh` and `scripts/audit/dependencies.sh`
|
||||
- Fuzz one CPU-only parser at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference>` (600 seconds by default).
|
||||
|
||||
|
||||
Generated
+31
@@ -8,6 +8,16 @@ version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "dispatch2"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.5"
|
||||
@@ -17,6 +27,17 @@ dependencies = [
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-foundation"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"dispatch2",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-encode"
|
||||
version = "4.1.0"
|
||||
@@ -41,6 +62,7 @@ checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"objc2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
@@ -53,6 +75,15 @@ dependencies = [
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-benchmarks"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-decoder"
|
||||
version = "0.1.0"
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
[workspace]
|
||||
members = ["crates/*", "tests/validation"]
|
||||
members = ["crates/*", "tests/validation", "benchmarks"]
|
||||
resolver = "3"
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "xenora-benchmarks"
|
||||
description = "Correctness-gated native Metal benchmark harness for the Phase 01 corpus"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "xenora-bench"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
xenora-shader = { path = "../crates/shader" }
|
||||
xenora-ref = { path = "../crates/ref" }
|
||||
xenora-metal = { path = "../crates/metal" }
|
||||
@@ -0,0 +1,33 @@
|
||||
# Benchmark corpus for the Phase 01 correctness-gated harness.
|
||||
#
|
||||
# Supported subset: `[[fixture]]` tables with string and integer-array values.
|
||||
# A shader is timed only after it passes correctness in the same run. `sizes`
|
||||
# are word counts for the one-invocation-per-word synthetic ABI.
|
||||
# See docs/testing/benchmarks.md for the protocol and metadata fields.
|
||||
|
||||
[[fixture]]
|
||||
name = "add"
|
||||
stage = "compute"
|
||||
source = "translated-rdna"
|
||||
path = "fixtures/rdna2/add.bin"
|
||||
input = [0, 1, 4294967295, 3989547400]
|
||||
expected = [305419896, 305419897, 305419895, 0]
|
||||
sizes = [4, 64, 256, 1024, 4096]
|
||||
|
||||
[[fixture]]
|
||||
name = "bitwise-branch"
|
||||
stage = "compute"
|
||||
source = "translated-rdna"
|
||||
path = "fixtures/rdna2/bitwise-branch.bin"
|
||||
input = [0, 1, 4294967295, 3989547400]
|
||||
expected = [305419896, 305419897, 315315847, 318723824]
|
||||
sizes = [4, 64, 256, 1024, 4096]
|
||||
|
||||
[[fixture]]
|
||||
name = "float-exact"
|
||||
stage = "compute"
|
||||
source = "translated-rdna"
|
||||
path = "fixtures/rdna2/float-exact.bin"
|
||||
input = [0, 1, 4294967295, 3989547400]
|
||||
expected = [1091305472, 1091305472, 1092616192, 1092616192]
|
||||
sizes = [4, 64, 256, 1024, 4096]
|
||||
@@ -0,0 +1,688 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Correctness-gated benchmark harness for the Phase 01 corpus.
|
||||
//!
|
||||
//! Reads `benchmarks/manifest.toml`, verifies every fixture against the
|
||||
//! independent reference and the native GPU before timing it, then writes
|
||||
//! metadata, raw JSON and a generated markdown report. A fixture that fails
|
||||
//! correctness is excluded and listed as such; it is never timed.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt::Write as _;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, ENTRY_POINT, compile};
|
||||
|
||||
const WARMUP_REPS: usize = 2;
|
||||
const DEFAULT_REPS: usize = 7;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Fixture {
|
||||
name: String,
|
||||
stage: String,
|
||||
source: String,
|
||||
path: String,
|
||||
input: Vec<u32>,
|
||||
expected: Vec<u32>,
|
||||
sizes: Vec<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct Stats {
|
||||
median: f64,
|
||||
min: f64,
|
||||
max: f64,
|
||||
q1: f64,
|
||||
q3: f64,
|
||||
reps: usize,
|
||||
}
|
||||
|
||||
impl Stats {
|
||||
fn from_samples(mut samples: Vec<f64>) -> Self {
|
||||
if samples.is_empty() {
|
||||
return Self::default();
|
||||
}
|
||||
samples.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let n = samples.len();
|
||||
let median = percentile(&samples, 0.5);
|
||||
Self {
|
||||
median,
|
||||
min: samples[0],
|
||||
max: samples[n - 1],
|
||||
q1: percentile(&samples, 0.25),
|
||||
q3: percentile(&samples, 0.75),
|
||||
reps: n,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn percentile(sorted: &[f64], fraction: f64) -> f64 {
|
||||
if sorted.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let position = fraction * (sorted.len() - 1) as f64;
|
||||
let lower = position.floor() as usize;
|
||||
let upper = position.ceil() as usize;
|
||||
if lower == upper {
|
||||
sorted[lower]
|
||||
} else {
|
||||
let weight = position - lower as f64;
|
||||
sorted[lower] * (1.0 - weight) + sorted[upper] * weight
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct SizeResult {
|
||||
words: usize,
|
||||
compile: Stats,
|
||||
library: Stats,
|
||||
pipeline: Stats,
|
||||
gpu: Stats,
|
||||
host: Stats,
|
||||
/// Fraction of samples whose GPU timestamp delta was zero.
|
||||
gpu_zero_fraction: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct FixtureResult {
|
||||
name: String,
|
||||
stage: String,
|
||||
source: String,
|
||||
status: String,
|
||||
reason: String,
|
||||
sizes: Vec<SizeResult>,
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut output = PathBuf::from("benchmarks/results");
|
||||
let mut reps = DEFAULT_REPS;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--output" => {
|
||||
output = PathBuf::from(args.next().ok_or("--output needs a path")?);
|
||||
}
|
||||
"--reps" => {
|
||||
reps = args
|
||||
.next()
|
||||
.ok_or("--reps needs a count")?
|
||||
.parse()
|
||||
.map_err(|_| "--reps must be a positive integer")?;
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!("usage: xenora-bench [--output DIR] [--reps N]");
|
||||
return Ok(());
|
||||
}
|
||||
other => return Err(format!("unknown argument {other}").into()),
|
||||
}
|
||||
}
|
||||
if reps == 0 {
|
||||
return Err("--reps must be at least 1".into());
|
||||
}
|
||||
|
||||
let manifest_text = fs::read_to_string("benchmarks/manifest.toml")?;
|
||||
let fixtures = parse_manifest(&manifest_text)?;
|
||||
if fixtures.is_empty() {
|
||||
return Err("manifest lists no fixtures".into());
|
||||
}
|
||||
|
||||
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
|
||||
let device = metal.device_name();
|
||||
let metadata = Metadata::collect(&device, reps);
|
||||
|
||||
let mut results = Vec::with_capacity(fixtures.len());
|
||||
for fixture in &fixtures {
|
||||
results.push(run_fixture(&metal, fixture, reps));
|
||||
}
|
||||
|
||||
let run_id = metadata.run_id.clone();
|
||||
let hardware_dir = slug(&device);
|
||||
let run_dir = output.join(&hardware_dir).join(&run_id);
|
||||
fs::create_dir_all(&run_dir)?;
|
||||
|
||||
fs::write(run_dir.join("metadata.json"), metadata.to_json())?;
|
||||
fs::write(run_dir.join("results.json"), results_json(&results))?;
|
||||
fs::write(
|
||||
run_dir.join("report.md"),
|
||||
report_markdown(&metadata, &results),
|
||||
)?;
|
||||
|
||||
println!("Benchmark results written to {}", run_dir.display());
|
||||
for result in &results {
|
||||
println!(
|
||||
" {:<16} {:<10} {}",
|
||||
result.name,
|
||||
result.status,
|
||||
if result.reason.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("({})", result.reason)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let excluded = results.iter().filter(|r| r.status != "benchmarked").count();
|
||||
if excluded > 0 {
|
||||
return Err(format!("{excluded} fixture(s) excluded from timing").into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> FixtureResult {
|
||||
let mut result = FixtureResult {
|
||||
name: fixture.name.clone(),
|
||||
stage: fixture.stage.clone(),
|
||||
source: fixture.source.clone(),
|
||||
status: "not-implemented".to_string(),
|
||||
reason: String::new(),
|
||||
sizes: Vec::new(),
|
||||
};
|
||||
|
||||
let code = match fs::read(&fixture.path) {
|
||||
Ok(code) => code,
|
||||
Err(error) => {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = format!("cannot read {}: {error}", fixture.path);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
let compiled = match compile(Architecture::Gfx1030, &code) {
|
||||
Ok(compiled) => compiled,
|
||||
Err(error) => {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = format!("compile failed: {error}");
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
// Independent reference on the declared base input.
|
||||
let reference = match xenora_ref::execute(&code, &fixture.input) {
|
||||
Ok(reference) => reference,
|
||||
Err(error) => {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = format!("reference execution failed: {error}");
|
||||
return result;
|
||||
}
|
||||
};
|
||||
if reference != fixture.expected {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = "reference disagrees with hand-derived expected values".to_string();
|
||||
return result;
|
||||
}
|
||||
|
||||
// Native correctness at the smallest declared size before any timing.
|
||||
let base_words = *fixture.sizes.first().unwrap_or(&fixture.input.len());
|
||||
let base_input = expand(&fixture.input, base_words);
|
||||
let base_expected = expand(&fixture.expected, base_words);
|
||||
match metal.run_words(&compiled.msl, ENTRY_POINT, &base_input) {
|
||||
Ok(actual) if actual == base_expected => {}
|
||||
Ok(_) => {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = "GPU output disagrees with known answers".to_string();
|
||||
return result;
|
||||
}
|
||||
Err(error) => {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = format!("GPU execution failed: {error}");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
for &words in &fixture.sizes {
|
||||
let input = expand(&fixture.input, words);
|
||||
let expected = expand(&fixture.expected, words);
|
||||
let mut compile_samples = Vec::with_capacity(reps);
|
||||
let mut library_samples = Vec::with_capacity(reps);
|
||||
let mut pipeline_samples = Vec::with_capacity(reps);
|
||||
let mut gpu_samples = Vec::with_capacity(reps);
|
||||
let mut host_samples = Vec::with_capacity(reps);
|
||||
let mut gpu_zero = 0usize;
|
||||
|
||||
let mut mismatch = None;
|
||||
for rep in 0..(WARMUP_REPS + reps) {
|
||||
let compile_start = std::time::Instant::now();
|
||||
let recompiled = match compile(Architecture::Gfx1030, &code) {
|
||||
Ok(compiled) => compiled,
|
||||
Err(error) => {
|
||||
mismatch = Some(format!("compile failed at {words} words: {error}"));
|
||||
break;
|
||||
}
|
||||
};
|
||||
let compile_seconds = compile_start.elapsed().as_secs_f64();
|
||||
|
||||
let profile = match metal.run_words_profiled(&recompiled.msl, ENTRY_POINT, &input) {
|
||||
Ok(profile) => profile,
|
||||
Err(error) => {
|
||||
mismatch = Some(format!("GPU run failed at {words} words: {error}"));
|
||||
break;
|
||||
}
|
||||
};
|
||||
if profile.output != expected {
|
||||
mismatch = Some(format!("GPU mismatch at {words} words"));
|
||||
break;
|
||||
}
|
||||
if rep < WARMUP_REPS {
|
||||
continue;
|
||||
}
|
||||
compile_samples.push(compile_seconds);
|
||||
library_samples.push(profile.library_seconds);
|
||||
pipeline_samples.push(profile.pipeline_seconds);
|
||||
gpu_samples.push(profile.gpu_seconds);
|
||||
host_samples.push(profile.host_seconds);
|
||||
if profile.gpu_seconds <= 0.0 {
|
||||
gpu_zero += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(reason) = mismatch {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = reason;
|
||||
return result;
|
||||
}
|
||||
|
||||
let measured = gpu_samples.len();
|
||||
result.sizes.push(SizeResult {
|
||||
words,
|
||||
compile: Stats::from_samples(compile_samples),
|
||||
library: Stats::from_samples(library_samples),
|
||||
pipeline: Stats::from_samples(pipeline_samples),
|
||||
gpu: Stats::from_samples(gpu_samples),
|
||||
host: Stats::from_samples(host_samples),
|
||||
gpu_zero_fraction: if measured == 0 {
|
||||
0.0
|
||||
} else {
|
||||
gpu_zero as f64 / measured as f64
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
result.status = "benchmarked".to_string();
|
||||
result
|
||||
}
|
||||
|
||||
fn expand(base: &[u32], words: usize) -> Vec<u32> {
|
||||
(0..words).map(|i| base[i % base.len()]).collect()
|
||||
}
|
||||
|
||||
// --- Manifest parsing (documented subset: [[fixture]] tables, string and int arrays) ---
|
||||
|
||||
fn parse_manifest(text: &str) -> Result<Vec<Fixture>, String> {
|
||||
let mut fixtures = Vec::new();
|
||||
let mut current: Option<Fixture> = None;
|
||||
for (line_no, raw) in text.lines().enumerate() {
|
||||
let line = raw.split('#').next().unwrap_or("").trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if line == "[[fixture]]" {
|
||||
if let Some(fixture) = current.take() {
|
||||
fixtures.push(finish(fixture, line_no)?);
|
||||
}
|
||||
current = Some(Fixture {
|
||||
name: String::new(),
|
||||
stage: String::new(),
|
||||
source: String::new(),
|
||||
path: String::new(),
|
||||
input: Vec::new(),
|
||||
expected: Vec::new(),
|
||||
sizes: Vec::new(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let Some(fixture) = current.as_mut() else {
|
||||
return Err(format!(
|
||||
"line {}: key outside a [[fixture]] table",
|
||||
line_no + 1
|
||||
));
|
||||
};
|
||||
let (key, value) = line
|
||||
.split_once('=')
|
||||
.ok_or_else(|| format!("line {}: expected key = value", line_no + 1))?;
|
||||
let key = key.trim();
|
||||
let value = value.trim();
|
||||
match key {
|
||||
"name" => fixture.name = parse_string(value)?,
|
||||
"stage" => fixture.stage = parse_string(value)?,
|
||||
"source" => fixture.source = parse_string(value)?,
|
||||
"path" => fixture.path = parse_string(value)?,
|
||||
"input" => fixture.input = parse_int_array(value)?,
|
||||
"expected" => fixture.expected = parse_int_array(value)?,
|
||||
"sizes" => {
|
||||
fixture.sizes = parse_int_array(value)?
|
||||
.into_iter()
|
||||
.map(|n| n as usize)
|
||||
.collect();
|
||||
}
|
||||
other => return Err(format!("line {}: unknown key {other}", line_no + 1)),
|
||||
}
|
||||
}
|
||||
if let Some(fixture) = current.take() {
|
||||
fixtures.push(finish(fixture, 0)?);
|
||||
}
|
||||
Ok(fixtures)
|
||||
}
|
||||
|
||||
fn finish(fixture: Fixture, line_no: usize) -> Result<Fixture, String> {
|
||||
let context = if fixture.name.is_empty() {
|
||||
format!("fixture ending near line {line_no}")
|
||||
} else {
|
||||
format!("fixture {}", fixture.name)
|
||||
};
|
||||
if fixture.name.is_empty()
|
||||
|| fixture.stage.is_empty()
|
||||
|| fixture.source.is_empty()
|
||||
|| fixture.path.is_empty()
|
||||
{
|
||||
return Err(format!("{context}: missing required string field"));
|
||||
}
|
||||
if fixture.input.is_empty() || fixture.expected.len() != fixture.input.len() {
|
||||
return Err(format!(
|
||||
"{context}: input and expected must be equal-length"
|
||||
));
|
||||
}
|
||||
if fixture.sizes.is_empty() || fixture.sizes.contains(&0) {
|
||||
return Err(format!(
|
||||
"{context}: sizes must be a nonempty list of positive integers"
|
||||
));
|
||||
}
|
||||
Ok(fixture)
|
||||
}
|
||||
|
||||
fn parse_string(value: &str) -> Result<String, String> {
|
||||
let trimmed = value.trim();
|
||||
let inner = trimmed
|
||||
.strip_prefix('"')
|
||||
.and_then(|v| v.strip_suffix('"'))
|
||||
.ok_or_else(|| format!("expected a quoted string, got {trimmed}"))?;
|
||||
Ok(inner.to_string())
|
||||
}
|
||||
|
||||
fn parse_int_array(value: &str) -> Result<Vec<u32>, String> {
|
||||
let trimmed = value.trim();
|
||||
let inner = trimmed
|
||||
.strip_prefix('[')
|
||||
.and_then(|v| v.strip_suffix(']'))
|
||||
.ok_or_else(|| format!("expected an integer array, got {trimmed}"))?;
|
||||
if inner.trim().is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
inner
|
||||
.split(',')
|
||||
.map(|item| {
|
||||
item.trim()
|
||||
.parse::<u32>()
|
||||
.map_err(|_| format!("invalid integer {}", item.trim()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// --- Metadata and output ---
|
||||
|
||||
struct Metadata {
|
||||
run_id: String,
|
||||
timestamp: String,
|
||||
device: String,
|
||||
host_arch: String,
|
||||
os_version: String,
|
||||
os_build: String,
|
||||
rustc: String,
|
||||
xcode: String,
|
||||
commit: String,
|
||||
profile: String,
|
||||
api_validation: String,
|
||||
shader_validation: String,
|
||||
reps: usize,
|
||||
warmup: usize,
|
||||
}
|
||||
|
||||
impl Metadata {
|
||||
fn collect(device: &str, reps: usize) -> Self {
|
||||
let seconds = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
Self {
|
||||
run_id: format!("run-{seconds}"),
|
||||
timestamp: format!("unix:{seconds}"),
|
||||
device: device.to_string(),
|
||||
host_arch: std::env::consts::ARCH.to_string(),
|
||||
os_version: command_line("sw_vers", &["-productVersion"]),
|
||||
os_build: command_line("sw_vers", &["-buildVersion"]),
|
||||
rustc: command_line("rustc", &["-vV"])
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap_or("unknown")
|
||||
.to_string(),
|
||||
xcode: command_line("xcodebuild", &["-version"])
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap_or("unknown")
|
||||
.to_string(),
|
||||
commit: command_line("git", &["rev-parse", "HEAD"]),
|
||||
profile: if cfg!(debug_assertions) {
|
||||
"debug"
|
||||
} else {
|
||||
"release"
|
||||
}
|
||||
.to_string(),
|
||||
api_validation: env_or("MTL_DEBUG_LAYER"),
|
||||
shader_validation: env_or("MTL_SHADER_VALIDATION"),
|
||||
reps,
|
||||
warmup: WARMUP_REPS,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> String {
|
||||
format!(
|
||||
"{{\n \"run_id\": {},\n \"timestamp\": {},\n \"device\": {},\n \"host_arch\": {},\n \"os_version\": {},\n \"os_build\": {},\n \"rustc\": {},\n \"xcode\": {},\n \"commit\": {},\n \"profile\": {},\n \"api_validation\": {},\n \"shader_validation\": {},\n \"reps\": {},\n \"warmup\": {}\n}}\n",
|
||||
json_str(&self.run_id),
|
||||
json_str(&self.timestamp),
|
||||
json_str(&self.device),
|
||||
json_str(&self.host_arch),
|
||||
json_str(&self.os_version),
|
||||
json_str(&self.os_build),
|
||||
json_str(&self.rustc),
|
||||
json_str(&self.xcode),
|
||||
json_str(&self.commit),
|
||||
json_str(&self.profile),
|
||||
json_str(&self.api_validation),
|
||||
json_str(&self.shader_validation),
|
||||
self.reps,
|
||||
self.warmup
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn command_line(program: &str, args: &[&str]) -> String {
|
||||
match Command::new(program).args(args).output() {
|
||||
Ok(output) if output.status.success() => {
|
||||
String::from_utf8_lossy(&output.stdout).trim().to_string()
|
||||
}
|
||||
_ => "unavailable".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn env_or(key: &str) -> String {
|
||||
std::env::var(key).unwrap_or_else(|_| "unset".to_string())
|
||||
}
|
||||
|
||||
fn slug(device: &str) -> String {
|
||||
device
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
c.to_ascii_lowercase()
|
||||
} else {
|
||||
'-'
|
||||
}
|
||||
})
|
||||
.collect::<String>()
|
||||
.trim_matches('-')
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn json_str(value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len() + 2);
|
||||
out.push('"');
|
||||
for c in value.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => {
|
||||
let _ = write!(out, "\\u{:04x}", c as u32);
|
||||
}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
fn stats_json(stats: &Stats) -> String {
|
||||
format!(
|
||||
"{{ \"median\": {:.9e}, \"min\": {:.9e}, \"max\": {:.9e}, \"q1\": {:.9e}, \"q3\": {:.9e}, \"reps\": {} }}",
|
||||
stats.median, stats.min, stats.max, stats.q1, stats.q3, stats.reps
|
||||
)
|
||||
}
|
||||
|
||||
fn results_json(results: &[FixtureResult]) -> String {
|
||||
let mut out = String::from("{\n \"fixtures\": [\n");
|
||||
for (index, result) in results.iter().enumerate() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {{\n \"name\": {},\n \"stage\": {},\n \"source\": {},\n \"status\": {},\n \"reason\": {},\n \"sizes\": [",
|
||||
json_str(&result.name),
|
||||
json_str(&result.stage),
|
||||
json_str(&result.source),
|
||||
json_str(&result.status),
|
||||
json_str(&result.reason)
|
||||
);
|
||||
for (size_index, size) in result.sizes.iter().enumerate() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"gpu_zero_fraction\": {:.4} }}{}",
|
||||
size.words,
|
||||
stats_json(&size.compile),
|
||||
stats_json(&size.library),
|
||||
stats_json(&size.pipeline),
|
||||
stats_json(&size.gpu),
|
||||
stats_json(&size.host),
|
||||
size.gpu_zero_fraction,
|
||||
if size_index + 1 == result.sizes.len() {
|
||||
""
|
||||
} else {
|
||||
","
|
||||
}
|
||||
);
|
||||
}
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" ]\n }}{}",
|
||||
if index + 1 == results.len() { "" } else { "," }
|
||||
);
|
||||
}
|
||||
out.push_str(" ]\n}\n");
|
||||
out
|
||||
}
|
||||
|
||||
fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String {
|
||||
let mut out = String::new();
|
||||
let _ = writeln!(out, "# Xenora benchmark report");
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. \
|
||||
Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol."
|
||||
);
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "## Environment");
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "| Field | Value |");
|
||||
let _ = writeln!(out, "| --- | --- |");
|
||||
for (key, value) in [
|
||||
("Device", metadata.device.as_str()),
|
||||
("Host arch", metadata.host_arch.as_str()),
|
||||
("macOS", metadata.os_version.as_str()),
|
||||
("Build", metadata.os_build.as_str()),
|
||||
("Rust", metadata.rustc.as_str()),
|
||||
("Xcode", metadata.xcode.as_str()),
|
||||
("Commit", metadata.commit.as_str()),
|
||||
("Profile", metadata.profile.as_str()),
|
||||
("API validation", metadata.api_validation.as_str()),
|
||||
("Shader validation", metadata.shader_validation.as_str()),
|
||||
] {
|
||||
let _ = writeln!(out, "| {key} | {} |", value.replace('|', "\\|"));
|
||||
}
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| Repetitions | {} measured, {} warm-up |",
|
||||
metadata.reps, metadata.warmup
|
||||
);
|
||||
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "## Coverage");
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "| Fixture | Stage | Source | Status |");
|
||||
let _ = writeln!(out, "| --- | --- | --- | --- |");
|
||||
for result in results {
|
||||
let status = if result.reason.is_empty() {
|
||||
result.status.clone()
|
||||
} else {
|
||||
format!("{} ({})", result.status, result.reason)
|
||||
};
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {} | {} | {} |",
|
||||
result.name,
|
||||
result.stage,
|
||||
result.source,
|
||||
status.replace('|', "\\|")
|
||||
);
|
||||
}
|
||||
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "## Timings");
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Durations in microseconds. `compile` is the Rust decode/IR/MSL pipeline, \
|
||||
`library` and `pipeline` are Metal compilation stages, `gpu` is the command-buffer \
|
||||
GPU time, and `host` is the wall time of one dispatch. Values are medians with \
|
||||
interquartile range; minimum and maximum are in `results.json`."
|
||||
);
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| Fixture | Words | compile | library | pipeline | gpu | host | IQR(gpu) | zero-gpu |"
|
||||
);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |"
|
||||
);
|
||||
for result in results.iter().filter(|r| r.status == "benchmarked") {
|
||||
for size in &result.sizes {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.0}% |",
|
||||
result.name,
|
||||
size.words,
|
||||
size.compile.median * 1e6,
|
||||
size.library.median * 1e6,
|
||||
size.pipeline.median * 1e6,
|
||||
size.gpu.median * 1e6,
|
||||
size.host.median * 1e6,
|
||||
(size.gpu.q3 - size.gpu.q1) * 1e6,
|
||||
size.gpu_zero_fraction * 100.0
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -40,4 +40,5 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
|
||||
"MTLPipeline",
|
||||
"MTLResource",
|
||||
"MTLTypes",
|
||||
"objc2-core-foundation",
|
||||
] }
|
||||
@@ -2,6 +2,7 @@ use std::ffi::c_void;
|
||||
use std::fmt;
|
||||
use std::mem::size_of_val;
|
||||
use std::ptr::{NonNull, copy_nonoverlapping};
|
||||
use std::time::Instant;
|
||||
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
|
||||
@@ -43,6 +44,20 @@ impl fmt::Display for MetalError {
|
||||
|
||||
impl std::error::Error for MetalError {}
|
||||
|
||||
/// One compiled-and-dispatched kernel with its measured stage timings.
|
||||
///
|
||||
/// Durations come from monotonic host clocks for the compiler stages and from
|
||||
/// the command buffer's GPU start and end timestamps for `gpu_seconds`. They
|
||||
/// measure a single submission and are not a benchmark distribution.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunProfile {
|
||||
pub library_seconds: f64,
|
||||
pub pipeline_seconds: f64,
|
||||
pub gpu_seconds: f64,
|
||||
pub host_seconds: f64,
|
||||
pub output: Vec<u32>,
|
||||
}
|
||||
|
||||
/// A native Metal device and its command queue for the Phase 01 fixture ABI.
|
||||
pub struct NativeCompute {
|
||||
device: Retained<ProtocolObject<dyn MTLDevice>>,
|
||||
@@ -96,6 +111,24 @@ impl NativeCompute {
|
||||
entry: &str,
|
||||
input: &[u32],
|
||||
) -> Result<Vec<u32>, MetalError> {
|
||||
self.run_words_profiled(source, entry, input)
|
||||
.map(|profile| profile.output)
|
||||
}
|
||||
|
||||
/// Run trusted MSL and report the measured compilation and execution stages.
|
||||
///
|
||||
/// Applies the same bounds and completion checks as [`Self::run_words`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for out-of-policy input sizes, compilation, resource setup,
|
||||
/// dispatch or completion failure.
|
||||
pub fn run_words_profiled(
|
||||
&self,
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: &[u32],
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
|
||||
return Err(MetalError::new(
|
||||
"dispatch bounds",
|
||||
@@ -112,7 +145,8 @@ impl NativeCompute {
|
||||
autoreleasepool(|_| self.run(source, entry, input))
|
||||
}
|
||||
|
||||
fn run(&self, source: &str, entry: &str, input: &[u32]) -> Result<Vec<u32>, MetalError> {
|
||||
fn run(&self, source: &str, entry: &str, input: &[u32]) -> Result<RunProfile, MetalError> {
|
||||
let host_start = Instant::now();
|
||||
let options = MTLCompileOptions::new();
|
||||
if !options.respondsToSelector(sel!(setMathMode:))
|
||||
|| !options.respondsToSelector(sel!(setMathFloatingPointFunctions:))
|
||||
@@ -124,6 +158,7 @@ impl NativeCompute {
|
||||
}
|
||||
options.setMathMode(MTLMathMode::Safe);
|
||||
options.setMathFloatingPointFunctions(MTLMathFloatingPointFunctions::Precise);
|
||||
let library_start = Instant::now();
|
||||
let library = self
|
||||
.device
|
||||
.newLibraryWithSource_options_error(&NSString::from_str(source), Some(&options))
|
||||
@@ -133,11 +168,13 @@ impl NativeCompute {
|
||||
error.localizedDescription().to_string(),
|
||||
)
|
||||
})?;
|
||||
let library_seconds = library_start.elapsed().as_secs_f64();
|
||||
let function = library
|
||||
.newFunctionWithName(&NSString::from_str(entry))
|
||||
.ok_or_else(|| {
|
||||
MetalError::new("newFunctionWithName", format!("missing entry {entry}"))
|
||||
})?;
|
||||
let pipeline_start = Instant::now();
|
||||
let pipeline = self
|
||||
.device
|
||||
.newComputePipelineStateWithFunction_error(&function)
|
||||
@@ -147,6 +184,7 @@ impl NativeCompute {
|
||||
error.localizedDescription().to_string(),
|
||||
)
|
||||
})?;
|
||||
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
|
||||
verify_shader_validation(&pipeline)?;
|
||||
|
||||
let width = MAX_THREADS_PER_GROUP
|
||||
@@ -197,6 +235,8 @@ impl NativeCompute {
|
||||
);
|
||||
return Err(MetalError::new("waitUntilCompleted", error));
|
||||
}
|
||||
let gpu_seconds = command.GPUEndTime() - command.GPUStartTime();
|
||||
let host_seconds = host_start.elapsed().as_secs_f64();
|
||||
// SAFETY: Metal copied the initialized words into distinct shared storage.
|
||||
// The GPU finished before the CPU touches that storage. Both ranges are
|
||||
// valid for byte_len bytes and don't overlap. A byte copy requires no
|
||||
@@ -208,7 +248,13 @@ impl NativeCompute {
|
||||
byte_len,
|
||||
);
|
||||
}
|
||||
Ok(words)
|
||||
Ok(RunProfile {
|
||||
library_seconds,
|
||||
pipeline_seconds,
|
||||
gpu_seconds,
|
||||
host_seconds,
|
||||
output: words,
|
||||
})
|
||||
}
|
||||
|
||||
fn new_buffer(
|
||||
|
||||
@@ -7,4 +7,4 @@ compile_error!("Xenora's Metal backend requires ARM64 macOS");
|
||||
mod compute;
|
||||
|
||||
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
|
||||
pub use compute::{MetalError, NativeCompute};
|
||||
pub use compute::{MetalError, NativeCompute, RunProfile};
|
||||
@@ -17,3 +17,8 @@
|
||||
The encoding and instruction semantics are based on AMD's RDNA 2 ISA reference guide 70648, dated 30 November 2020, sections “Instruction Encoding” and “Microcode Formats.” Evidence is class C for applicability to Xbox hardware. The exact gfx1030 encodings, including VGPR 255 and VOP3 source-field crossings, were checked with LLVM 23.1.6 `llvm-mc` (class E). The project uses the document as a specification reference and distributes no specification text or LLVM code. [AMD RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf)
|
||||
|
||||
Run `cargo test -p xenora-ref` for fixture results, both conditional paths, invalid targets, the exact FP32 domain, truncation, wait enforcement and register-index boundaries. This author-run suite is development evidence. Independent validation and three-way decode agreement are separately tracked release gates.
|
||||
|
||||
## Second independent interpreter (semantic review)
|
||||
|
||||
`tests/validation/independent_ref.rs` is a second interpreter for the same subset, written for the semantic-review suite. It imports neither `xenora-decoder`, `xenora-isa` nor `xenora-ref`; it re-decodes the RDNA 2 encoding fields and executes a program-counter machine. The review test `second_interpreter_agrees_with_reference_on_boundary_and_random_inputs` compares the two interpreters on all three demo fixtures over boundary-dense and pseudorandom inputs (about 3,268 inputs per fixture, including the 2^32 addition wrap, the FP32 selection bit and signed/unsigned extremes). Agreement here is spec-derived evidence (class B/C), not Xbox hardware observation. This is R2-owned validation and is distinct from the production reference.
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# Benchmark protocol
|
||||
|
||||
The benchmark harness measures every shader in the correctness corpus that passes
|
||||
its correctness test in the same run. It never reports a number for a shader that
|
||||
failed or was skipped.
|
||||
|
||||
## Corpus
|
||||
|
||||
`benchmarks/manifest.toml` lists each fixture with its stage, source, binary path,
|
||||
declared input and hand-derived expected output, and the word counts to time. The
|
||||
manifest uses a documented subset of TOML (`[[fixture]]` tables with string and
|
||||
integer-array values) parsed by the harness, so no external TOML dependency is
|
||||
pulled into the workspace.
|
||||
|
||||
A fixture is added to the corpus by adding a table. If it passes correctness it is
|
||||
benchmarked automatically; there is no separate opt-in list.
|
||||
|
||||
## Correctness gate
|
||||
|
||||
Before any timing, the harness requires all of the following for each fixture:
|
||||
|
||||
1. The Rust pipeline (`xenora-shader::compile`) accepts the binary.
|
||||
2. The independent reference interpreter agrees with the hand-derived `expected`
|
||||
values on the declared input.
|
||||
3. The native GPU produces the expected output for the smallest declared size.
|
||||
|
||||
If any step fails the fixture is marked `excluded` with a reason, listed in the
|
||||
coverage table, and not timed. A nonempty exclusion set makes the harness exit
|
||||
nonzero.
|
||||
|
||||
## What is measured
|
||||
|
||||
Per fixture and per word count, over `--reps` measured repetitions after two
|
||||
warm-up repetitions:
|
||||
|
||||
| Field | Source | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `compile` | host monotonic clock | Rust decode, lift, verify and MSL generation |
|
||||
| `library` | host monotonic clock | `newLibraryWithSource` Metal compilation |
|
||||
| `pipeline` | host monotonic clock | compute pipeline state creation |
|
||||
| `gpu` | `GPUEndTime - GPUStartTime` | command-buffer GPU execution time |
|
||||
| `host` | host monotonic clock | wall time of one compile-and-dispatch call |
|
||||
|
||||
`gpu_zero_fraction` records the share of samples whose GPU timestamp delta was
|
||||
zero, which happens for very short kernels. A high value means the GPU timing is
|
||||
at timer resolution and should not be read as a precise duration.
|
||||
|
||||
Statistics reported are median, minimum, maximum and the first and third quartiles.
|
||||
The report never uses best-of.
|
||||
|
||||
## Protocol
|
||||
|
||||
- Release builds only for published numbers; the metadata records the profile.
|
||||
- The machine must be otherwise idle, on AC power, with the thermal state noted.
|
||||
- Validation is off for timing runs. The metadata records the `MTL_DEBUG_LAYER`
|
||||
and `MTL_SHADER_VALIDATION` values in effect so a validated run is never confused
|
||||
with a timing run.
|
||||
- The fanless M5 MacBook Air throttles under sustained load; a single run does not
|
||||
characterize sustained performance.
|
||||
- No comparison to Xbox hardware, other emulators or other platforms is made.
|
||||
|
||||
## Output
|
||||
|
||||
`benchmarks/results/<hardware>/<run-id>/` contains `metadata.json`, `results.json`
|
||||
and `report.md`. Only small text reports are committed. Raw logs stay under the
|
||||
ignored `artifacts/` directory.
|
||||
|
||||
## Reproduction
|
||||
|
||||
```sh
|
||||
cargo build --release -p xenora-benchmarks
|
||||
MTL_DEBUG_LAYER=0 MTL_SHADER_VALIDATION=0 ./target/release/xenora-bench --reps 7
|
||||
```
|
||||
|
||||
## Limitations
|
||||
|
||||
The corpus currently covers three synthetic gfx1030 compute fixtures under the
|
||||
[synthetic memory ABI](../adr/0003-demo-memory-model.md). It does not measure
|
||||
graphics stages, guest containers, Wave64 or divergence. Translation-versus-native
|
||||
baseline ratios are not reported because no hand-written native MSL baseline exists
|
||||
yet for these fixtures.
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# Timing runs must be on an idle machine with validation off.
|
||||
export MTL_DEBUG_LAYER=${MTL_DEBUG_LAYER:-0}
|
||||
export MTL_SHADER_VALIDATION=${MTL_SHADER_VALIDATION:-0}
|
||||
export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4}
|
||||
|
||||
cargo build --locked --release -p xenora-benchmarks
|
||||
exec ./target/release/xenora-bench "$@"
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# Source mutation campaign for the critical Phase 01 modules.
|
||||
# R2 owns execution and survivor triage; this script only reproduces the run.
|
||||
# Tests run for the mutated package only (cargo-mutants default), so this stays
|
||||
# CPU-only and never dispatches GPU work.
|
||||
out=${1:-artifacts/mutation/campaign-$(date +%Y%m%d-%H%M%S)}
|
||||
mkdir -p "$out"
|
||||
export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-2}
|
||||
|
||||
cargo mutants --workspace \
|
||||
--file 'crates/decoder/src/**' \
|
||||
--file 'crates/shader/src/**' \
|
||||
--file 'crates/ref/src/**' \
|
||||
--jobs 2 \
|
||||
--timeout 60 \
|
||||
--output "$out"
|
||||
@@ -0,0 +1,385 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! A second, structurally independent interpreter for the demo instruction
|
||||
//! subset, used only by the semantic-review tests.
|
||||
//!
|
||||
//! This module deliberately imports neither `xenora-decoder`, `xenora-isa` nor
|
||||
//! `xenora-ref`. It re-decodes the gfx1030 encodings from the AMD RDNA 2 ISA
|
||||
//! field layout and executes them with an explicit program-counter machine, so
|
||||
//! a defect in the production decoder or reference cannot cancel out here.
|
||||
//!
|
||||
//! Scope matches the three demo fixtures: scalar move/compare/branch, VOP1
|
||||
//! move, VOP2 bitwise and float, VOP3 add-no-carry, MUBUF load/store and the
|
||||
//! two waits plus `s_endpgm`. Anything else is a controlled error.
|
||||
|
||||
const MAX_CODE_BYTES: usize = 1024;
|
||||
const MAX_INPUT_WORDS: usize = 4096;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Src {
|
||||
Reg(u8),
|
||||
Imm(u32),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Insn {
|
||||
SMov(u8, Src),
|
||||
SCmpEq(Src, Src),
|
||||
BranchScc0(usize),
|
||||
Branch(usize),
|
||||
VMov(u8, Src),
|
||||
VAddNc(u8, u8, u8),
|
||||
VAnd(u8, u8, u8),
|
||||
VXor(u8, u8, u8),
|
||||
VAddF(u8, u8, u8),
|
||||
VMulF(u8, u8, u8),
|
||||
Load { data: u8, index: u8, resource: u8 },
|
||||
Store { data: u8, index: u8, resource: u8 },
|
||||
WaitRead,
|
||||
WaitWrite,
|
||||
End,
|
||||
}
|
||||
|
||||
/// Execute the synthetic fixture ABI and return one output word per input word.
|
||||
pub fn execute(code: &[u8], input: &[u32]) -> Result<Vec<u32>, String> {
|
||||
if input.is_empty() || input.len() > MAX_INPUT_WORDS {
|
||||
return Err("input word count outside limits".to_string());
|
||||
}
|
||||
if code.len() > MAX_CODE_BYTES {
|
||||
return Err("code exceeds limit".to_string());
|
||||
}
|
||||
let program = decode(code)?;
|
||||
input.iter().map(|&word| run_lane(&program, word)).collect()
|
||||
}
|
||||
|
||||
fn run_lane(program: &[(usize, Insn)], lane_input: u32) -> Result<u32, String> {
|
||||
let mut vgpr = [None::<u32>; 256];
|
||||
let mut sgpr = [None::<u32>; 106];
|
||||
let mut scc: Option<bool> = None;
|
||||
let mut pending_read: Option<u8> = None;
|
||||
let mut pending_write: Option<u32> = None;
|
||||
let mut written: Option<u32> = None;
|
||||
let mut pc = 0usize;
|
||||
|
||||
while pc < program.len() {
|
||||
let (offset, insn) = program[pc];
|
||||
let read_v = |reg: u8| -> Result<u32, String> {
|
||||
if reg == 0 {
|
||||
return Err(format!("{offset:#x}: v0 is the resource index"));
|
||||
}
|
||||
if pending_read == Some(reg) {
|
||||
return Err(format!("{offset:#x}: read before load wait"));
|
||||
}
|
||||
vgpr[reg as usize].ok_or_else(|| format!("{offset:#x}: uninitialized v{reg}"))
|
||||
};
|
||||
let read_s = |src: Src| -> Result<u32, String> {
|
||||
match src {
|
||||
Src::Imm(value) => Ok(value),
|
||||
Src::Reg(reg) => {
|
||||
sgpr[reg as usize].ok_or_else(|| format!("{offset:#x}: uninitialized s{reg}"))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
match insn {
|
||||
Insn::Load {
|
||||
data,
|
||||
index,
|
||||
resource,
|
||||
} => {
|
||||
if index != 0 || resource != 0 {
|
||||
return Err(format!("{offset:#x}: load outside synthetic ABI"));
|
||||
}
|
||||
if data == 0 || pending_read.is_some() {
|
||||
return Err(format!("{offset:#x}: invalid or overlapping load"));
|
||||
}
|
||||
pending_read = Some(data);
|
||||
}
|
||||
Insn::Store {
|
||||
data,
|
||||
index,
|
||||
resource,
|
||||
} => {
|
||||
if index != 0 || resource != 4 {
|
||||
return Err(format!("{offset:#x}: store outside synthetic ABI"));
|
||||
}
|
||||
let value = read_v(data)?;
|
||||
if pending_write.is_some() || written.is_some() {
|
||||
return Err(format!("{offset:#x}: multiple output writes"));
|
||||
}
|
||||
pending_write = Some(value);
|
||||
}
|
||||
Insn::WaitRead => {
|
||||
if let Some(dst) = pending_read.take() {
|
||||
vgpr[dst as usize] = Some(lane_input);
|
||||
}
|
||||
}
|
||||
Insn::WaitWrite => {
|
||||
if let Some(value) = pending_write.take() {
|
||||
written = Some(value);
|
||||
}
|
||||
}
|
||||
Insn::VMov(dst, src) => {
|
||||
let value = match src {
|
||||
Src::Imm(value) => value,
|
||||
Src::Reg(reg) => read_v(reg)?,
|
||||
};
|
||||
if dst == 0 {
|
||||
return Err(format!("{offset:#x}: move writes v0"));
|
||||
}
|
||||
vgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::VAddNc(dst, a, b) => {
|
||||
let value = read_v(a)?.wrapping_add(read_v(b)?);
|
||||
vgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::VAnd(dst, a, b) => {
|
||||
let value = read_v(a)? & read_v(b)?;
|
||||
vgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::VXor(dst, a, b) => {
|
||||
let value = read_v(a)? ^ read_v(b)?;
|
||||
vgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::VAddF(dst, a, b) => {
|
||||
let value = exact_float(true, read_v(a)?, read_v(b)?, offset)?;
|
||||
vgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::VMulF(dst, a, b) => {
|
||||
let value = exact_float(false, read_v(a)?, read_v(b)?, offset)?;
|
||||
vgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::SMov(dst, src) => {
|
||||
if dst < 8 {
|
||||
return Err(format!("{offset:#x}: write to a resource SGPR"));
|
||||
}
|
||||
sgpr[dst as usize] = Some(read_s(src)?);
|
||||
}
|
||||
Insn::SCmpEq(a, b) => {
|
||||
scc = Some(read_s(a)? == read_s(b)?);
|
||||
}
|
||||
Insn::BranchScc0(target) => {
|
||||
let condition = scc.ok_or_else(|| format!("{offset:#x}: uninitialized SCC"))?;
|
||||
if !condition {
|
||||
pc = index_of(program, target, offset)?;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
Insn::Branch(target) => {
|
||||
pc = index_of(program, target, offset)?;
|
||||
continue;
|
||||
}
|
||||
Insn::End => {
|
||||
if pending_read.is_some() || pending_write.is_some() {
|
||||
return Err(format!("{offset:#x}: outstanding transfer at end"));
|
||||
}
|
||||
if pc + 1 != program.len() {
|
||||
return Err(format!("{offset:#x}: code after s_endpgm"));
|
||||
}
|
||||
return written.ok_or_else(|| format!("{offset:#x}: missing output store"));
|
||||
}
|
||||
}
|
||||
pc += 1;
|
||||
}
|
||||
Err("stream ended without s_endpgm".to_string())
|
||||
}
|
||||
|
||||
fn index_of(program: &[(usize, Insn)], target: usize, offset: usize) -> Result<usize, String> {
|
||||
program
|
||||
.iter()
|
||||
.position(|(at, _)| *at == target)
|
||||
.ok_or_else(|| format!("{offset:#x}: branch target {target:#x} is not a boundary"))
|
||||
}
|
||||
|
||||
fn exact_float(add: bool, a_bits: u32, b_bits: u32, offset: usize) -> Result<u32, String> {
|
||||
let (a, b) = (f32::from_bits(a_bits), f32::from_bits(b_bits));
|
||||
if !a.is_normal() || !b.is_normal() || a.is_sign_negative() || b.is_sign_negative() {
|
||||
return Err(format!("{offset:#x}: float outside positive normal domain"));
|
||||
}
|
||||
let (a, b) = (f64::from(a), f64::from(b));
|
||||
let exact = if add { a + b } else { a * b };
|
||||
let result = exact as f32;
|
||||
if !result.is_normal() || f64::from(result) != exact {
|
||||
return Err(format!("{offset:#x}: float result not exact binary32"));
|
||||
}
|
||||
Ok(result.to_bits())
|
||||
}
|
||||
|
||||
fn decode(code: &[u8]) -> Result<Vec<(usize, Insn)>, String> {
|
||||
let mut program = Vec::new();
|
||||
let mut offset = 0;
|
||||
while offset < code.len() {
|
||||
let (insn, len) = decode_one(code, offset)?;
|
||||
program.push((offset, insn));
|
||||
offset += len;
|
||||
}
|
||||
for &(at, insn) in &program {
|
||||
if let Insn::Branch(target) | Insn::BranchScc0(target) = insn
|
||||
&& !program.iter().any(|(boundary, _)| *boundary == target)
|
||||
{
|
||||
return Err(format!(
|
||||
"{at:#x}: branch target {target:#x} is not a boundary"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(program)
|
||||
}
|
||||
|
||||
fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
let first = word(code, offset)?;
|
||||
let fail = |detail: &str| format!("{offset:#x}: {detail}");
|
||||
|
||||
// Opcode masks and values are the AMD RDNA 2 ISA encoding fields.
|
||||
if first & 0xfffc_0000 == 0xe030_0000 {
|
||||
let second = word(code, offset + 4)?;
|
||||
let (data, index, resource) = mubuf(second).ok_or_else(|| fail("bad MUBUF load form"))?;
|
||||
return Ok((
|
||||
Insn::Load {
|
||||
data,
|
||||
index,
|
||||
resource,
|
||||
},
|
||||
8,
|
||||
));
|
||||
}
|
||||
if first & 0xfffc_0000 == 0xe070_0000 {
|
||||
let second = word(code, offset + 4)?;
|
||||
let (data, index, resource) = mubuf(second).ok_or_else(|| fail("bad MUBUF store form"))?;
|
||||
return Ok((
|
||||
Insn::Store {
|
||||
data,
|
||||
index,
|
||||
resource,
|
||||
},
|
||||
8,
|
||||
));
|
||||
}
|
||||
if first & 0xfe01_fe00 == 0x7e00_0200 {
|
||||
let dst = (first >> 17) as u8;
|
||||
let selector = first & 0x1ff;
|
||||
let (src, len) = if selector == 255 {
|
||||
(Src::Imm(word(code, offset + 4)?), 8)
|
||||
} else {
|
||||
(
|
||||
vector_source(selector).ok_or_else(|| fail("bad VOP1 source"))?,
|
||||
4,
|
||||
)
|
||||
};
|
||||
return Ok((Insn::VMov(dst, src), len));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xd525_0000 {
|
||||
let second = word(code, offset + 4)?;
|
||||
let src0 = second & 0x1ff;
|
||||
let src1 = (second >> 9) & 0x1ff;
|
||||
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
|
||||
return Err(fail("bad VOP3 add form"));
|
||||
}
|
||||
return Ok((Insn::VAddNc(first as u8, src0 as u8, src1 as u8), 8));
|
||||
}
|
||||
if first & 0xff80_ff00 == 0xbe80_0300 {
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
let (src, len) = scalar_source(code, offset, first as u8)?;
|
||||
return Ok((Insn::SMov(dst, src), len));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xbf06_0000 {
|
||||
let a = first as u8;
|
||||
let b = (first >> 8) as u8;
|
||||
if a == 255 && b == 255 {
|
||||
return Err(fail("two scalar literals"));
|
||||
}
|
||||
let (sa, la) = scalar_source(code, offset, a)?;
|
||||
let (sb, lb) = scalar_source(code, offset, b)?;
|
||||
return Ok((Insn::SCmpEq(sa, sb), la.max(lb)));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xbf82_0000 {
|
||||
return Ok((Insn::Branch(branch_target(first, offset)?), 4));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xbf84_0000 {
|
||||
return Ok((Insn::BranchScc0(branch_target(first, offset)?), 4));
|
||||
}
|
||||
for (mask, value, kind) in [
|
||||
(0xfe00_0000, 0x3600_0000u32, 0u8),
|
||||
(0xfe00_0000, 0x3a00_0000, 1),
|
||||
(0xfe00_0000, 0x0600_0000, 2),
|
||||
(0xfe00_0000, 0x1000_0000, 3),
|
||||
] {
|
||||
if first & mask == value {
|
||||
if first & 0x100 == 0 {
|
||||
return Err(fail("VOP2 source modifier"));
|
||||
}
|
||||
let dst = (first >> 17) as u8;
|
||||
let a = first as u8;
|
||||
let b = (first >> 9) as u8;
|
||||
let insn = match kind {
|
||||
0 => Insn::VAnd(dst, a, b),
|
||||
1 => Insn::VXor(dst, a, b),
|
||||
2 => Insn::VAddF(dst, a, b),
|
||||
_ => Insn::VMulF(dst, a, b),
|
||||
};
|
||||
return Ok((insn, 4));
|
||||
}
|
||||
}
|
||||
if first & 0xffff_0000 == 0xbf8c_0000 {
|
||||
if first != 0xbf8c_3f70 {
|
||||
return Err(fail("waitcnt not vmcnt(0)"));
|
||||
}
|
||||
return Ok((Insn::WaitRead, 4));
|
||||
}
|
||||
if first & 0xff80_0000 == 0xbb80_0000 {
|
||||
if first != 0xbbfd_0000 {
|
||||
return Err(fail("waitcnt_vscnt not null,0"));
|
||||
}
|
||||
return Ok((Insn::WaitWrite, 4));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xbf81_0000 {
|
||||
if first != 0xbf81_0000 {
|
||||
return Err(fail("endpgm immediate"));
|
||||
}
|
||||
return Ok((Insn::End, 4));
|
||||
}
|
||||
Err(fail("unsupported opcode"))
|
||||
}
|
||||
|
||||
fn mubuf(second: u32) -> Option<(u8, u8, u8)> {
|
||||
if second & 0xffe0_0000 != 0x8000_0000 {
|
||||
return None;
|
||||
}
|
||||
let index = second as u8;
|
||||
let data = (second >> 8) as u8;
|
||||
let resource = ((second >> 16) & 0x1f) as u8 * 4;
|
||||
(resource <= 102).then_some((data, index, resource))
|
||||
}
|
||||
|
||||
fn vector_source(selector: u32) -> Option<Src> {
|
||||
match selector {
|
||||
128..=192 => Some(Src::Imm(selector - 128)),
|
||||
193..=208 => Some(Src::Imm(192u32.wrapping_sub(selector))),
|
||||
242 => Some(Src::Imm(0x3f80_0000)),
|
||||
256..=511 => Some(Src::Reg(selector as u8)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn scalar_source(code: &[u8], offset: usize, selector: u8) -> Result<(Src, usize), String> {
|
||||
match selector {
|
||||
0..=105 => Ok((Src::Reg(selector), 4)),
|
||||
128..=192 => Ok((Src::Imm(u32::from(selector - 128)), 4)),
|
||||
193..=208 => Ok((Src::Imm(192u32.wrapping_sub(u32::from(selector))), 4)),
|
||||
255 => Ok((Src::Imm(word(code, offset + 4)?), 8)),
|
||||
_ => Err(format!("{offset:#x}: bad scalar source")),
|
||||
}
|
||||
}
|
||||
|
||||
fn branch_target(first: u32, offset: usize) -> Result<usize, String> {
|
||||
let displacement = first as u16 as i16;
|
||||
let words =
|
||||
usize::try_from(displacement).map_err(|_| format!("{offset:#x}: backward branch"))?;
|
||||
Ok(offset + 4 + words * 4)
|
||||
}
|
||||
|
||||
fn word(code: &[u8], offset: usize) -> Result<u32, String> {
|
||||
let bytes = code
|
||||
.get(offset..offset + 4)
|
||||
.ok_or_else(|| format!("{offset:#x}: truncated instruction"))?;
|
||||
Ok(u32::from_le_bytes(bytes.try_into().unwrap()))
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
#[cfg(test)]
|
||||
mod independent_ref;
|
||||
|
||||
#[cfg(test)]
|
||||
mod review {
|
||||
use xenora_shader::{Architecture, compile};
|
||||
@@ -122,4 +125,52 @@ mod review {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_interpreter_agrees_with_reference_on_boundary_and_random_inputs() {
|
||||
use super::independent_ref;
|
||||
let fixtures: [(&[u8], &str); 3] = [
|
||||
(include_bytes!("../../fixtures/rdna2/add.bin"), "add"),
|
||||
(
|
||||
include_bytes!("../../fixtures/rdna2/bitwise-branch.bin"),
|
||||
"bitwise-branch",
|
||||
),
|
||||
(
|
||||
include_bytes!("../../fixtures/rdna2/float-exact.bin"),
|
||||
"float-exact",
|
||||
),
|
||||
];
|
||||
let mut inputs: Vec<u32> = vec![
|
||||
0,
|
||||
1,
|
||||
u32::MAX,
|
||||
0x8000_0000,
|
||||
0x7fff_ffff,
|
||||
0xedcb_a988,
|
||||
0x0040_0000,
|
||||
0x0040_0001,
|
||||
0x007f_ffff,
|
||||
0x0080_0000,
|
||||
0x00ff_00ff,
|
||||
0xff00_ff00,
|
||||
];
|
||||
for base in [
|
||||
0xedcb_a988u32.wrapping_sub(64),
|
||||
0x0040_0000u32.wrapping_sub(64),
|
||||
] {
|
||||
inputs.extend((0..128).map(|i| base.wrapping_add(i)));
|
||||
}
|
||||
let mut seed = 0x9e37_79b9u32;
|
||||
inputs.extend((0..3000).map(|_| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
seed
|
||||
}));
|
||||
for (code, name) in fixtures {
|
||||
let expected = xenora_ref::execute(code, &inputs).unwrap();
|
||||
let actual = independent_ref::execute(code, &inputs).unwrap();
|
||||
assert_eq!(actual, expected, "fixture {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user