Compare commits

..
Author SHA1 Message Date
Swastick Chowdhury 61aa904608 Merge b09d96fd62 into 0fdb995892 2026-11-25 00:00:39 +05:30
Swastickc b09d96fd62 bench: measure Metal startup in fresh processes and repeated runs (#178)
Add `xenora-bench startup`. It checks one manifest fixture against the
independent reference, then times it phase by phase in two regimes: a
series of fresh child processes that each create the Metal device and
queue, translate and run the fixture once, and one process that
repeats the run. Phases are launch to main, device and queue,
translation, library, pipeline, submission, GPU and readback, reported
as median, p90, p99 and maximum, with raw fresh samples in launch
order.

Every sample must produce the expected output. A wrong output, a
failed or hung child (killed after 60 s) or a damaged sample line
stops the run before any result is written. Children inherit the
environment so the recorded MTL_* validation state applies to both
regimes.

Document the method and one recorded release run on an Apple M4 in
docs/testing/benchmarks.md, and add a changelog entry. Measurement
only.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-24 23:59:59 +05:30
elforeign 0fdb995892 isa, decoder, shader, ref: VOP3A encodings of eleven VOP2 integer forms and the sixteen integer compares (#215) (#311)
* isa, decoder: VOP3 encodings of the eleven registry VOP2 integer forms (#215)

Eleven [[encoding_variant]] entries re-encode the VOP2 integer forms as
VOP3A (_e64) under operand rule vop3_vgpr2: two VGPR sources, no
modifiers, SRC2 the unused inline zero. Opcodes from the pinned XML,
checked against llvm-mc. Decoder known words and per-bit rejections.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* fixtures, decoder, shader: LLVM-assembled fixture and goldens for the eleven VOP3 VOP2 variants (#215)

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* ref, validation: independent guide-derived oracle for VOP3 integer VOP2 forms and Wave32 VOP3 compares (#215)

crates/ref and tests/validation/independent_ref.rs decode and run the eleven
VOP3A (_e64) integer VOP2 forms and the sixteen V_CMP_*_{I32,U32}_e64 compares
writing a 32-bit lane mask to one SGPR (s0-s105) or vcc_lo, derived from the
AMD RDNA 2 guide only. New suites vop3_integer.rs and vop3_compare.rs, with
ignored native Metal parts.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, decoder, shader: add VOP3A encodings for the sixteen integer compares (#215)

Sixteen gfx1030 Wave32 integer compares gain their VOP3A (_e64) encoding
as registry variants, with an explicit SGPR mask destination (guide 3.9,
13.3.3; pinned XML OPR_SREG), VCCZ branching through vcc_lo and
translation errors for reads of runtime-only SGPR results.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* fixtures, shader, validation: VOP3A compare fixture and native Metal runs (#215)

A fixture with all sixteen VOP3A integer compares (vcc_lo destination,
runtime s_cbranch_vccz) ties the new variants to fixture coverage, with
IR and MSL goldens. The VOP3 integer and compare Metal oracles now run in
the GPU gate: the translator they waited for is in this branch.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* changelog: VOP3A integer and compare encodings (#215)

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* shader, fixtures, docs: e64 compare names in the IR; status rows for the 27 VOP3A forms (#215)

The IR names a VOP3A compare by its _e64 mnemonic and prints its SGPR
destination; VOPC output is unchanged. The compare fixture now uses a
mid-range second source (so swapped unsigned opcodes change the golden)
and one plain SGPR destination. docs/status.toml and the rendered
instruction table list the 27 new forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* docs: use a recognized lowering phrase for the VOP3A integer rows (#215)

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: VOP3A variants exist only for the 32-bit VOPC compares (#215)

After main gained the 16-bit compares (#327), the dispatch test expected a
VOP3A encoding for every non-64-bit compare. Only the 32-bit ones have one.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 11:38:44 -06:00
5 changed files with 653 additions and 2 deletions

No files matched your search

+7
View File
@@ -17,6 +17,13 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Added
- Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated
submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline,
submission, GPU, readback), with median, p90, p99 and maximum. Every sample must produce the fixture's
expected output, or the run stops without writing results. `docs/testing/benchmarks.md` records one
release run on an Apple M4: a fresh process took about 43 ms (median), 36 ms of it creating the Metal
device and queue, while repeated runs in one process needed about 0.2 ms of host submission. Measurement
only; nothing was optimized.
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
+17 -2
View File
@@ -162,10 +162,21 @@ struct BatchResult {
pipelined: Stats,
}
mod startup;
mod startup_report;
fn main() -> Result<(), Box<dyn Error>> {
// Taken before anything else so a fresh startup child can report the time
// from its parent's spawn to `main`.
let entered = SystemTime::now();
let mut args = std::env::args().skip(1).peekable();
match args.peek().map(String::as_str) {
Some("startup") => return startup::run(args.skip(1)),
Some("startup-child") => return startup::child(entered, args.skip(1)),
_ => {}
}
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" => {
@@ -179,7 +190,11 @@ fn main() -> Result<(), Box<dyn Error>> {
.map_err(|_| "--reps must be a positive integer")?;
}
"--help" | "-h" => {
println!("usage: xenora-bench [--output DIR] [--reps N]");
println!(
"usage: xenora-bench [--output DIR] [--reps N]\n \
xenora-bench startup [--fixture NAME] [--words N] [--processes N] \
[--reps N] [--output DIR]"
);
return Ok(());
}
other => return Err(format!("unknown argument {other}").into()),
+405
View File
@@ -0,0 +1,405 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Metal startup distributions: fresh processes versus repeated submissions (#178).
//!
//! `xenora-bench startup` checks one manifest fixture against the independent
//! reference, then measures it two ways:
//!
//! - **Fresh process.** It launches its own executable `--processes` times. Each
//! child creates the Metal device and queue, translates the fixture, runs it
//! once with `run_words_profiled`, checks the output and prints one sample line.
//! - **Repeated.** In this process it creates one device, then translates and runs
//! the same fixture `--reps` times. The first run is reported on its own.
//!
//! Every sample must produce the expected words. One wrong output, failed child or
//! unparsable sample line stops the run before anything is written. The
//! numbers describe this host only; two distributions do not explain each other.
use std::error::Error;
use std::fs;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, ENTRY_POINT, compile};
use crate::startup_report::Report;
use crate::{Fixture, Metadata, expand, parse_manifest, percentile, slug};
const DEFAULT_PROCESSES: usize = 30;
const DEFAULT_REPS: usize = 100;
/// A fresh process that has not exited by then is killed and fails the run.
const CHILD_TIMEOUT: Duration = Duration::from_secs(60);
/// Phases of one run, in seconds. `spawn_to_main` exists only for fresh processes.
pub(crate) const PHASES: [&str; 8] = [
"spawn_to_main",
"device",
"translate",
"library",
"pipeline",
"submit",
"gpu",
"readback",
];
/// One run's phase timings, indexed like [`PHASES`].
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub(crate) struct Sample(pub(crate) [f64; PHASES.len()]);
impl Sample {
fn line(&self) -> String {
let fields: Vec<String> = PHASES
.iter()
.zip(self.0)
.map(|(name, value)| format!("{name}={value:e}"))
.collect();
format!("startup-sample {}", fields.join(" "))
}
/// Parses exactly the line [`Sample::line`] prints: every phase once, in order.
pub(crate) fn parse(line: &str) -> Result<Self, String> {
let rest = line
.strip_prefix("startup-sample ")
.ok_or("missing startup-sample prefix")?;
let fields: Vec<&str> = rest.split(' ').collect();
if fields.len() != PHASES.len() {
return Err(format!(
"expected {} fields, got {}",
PHASES.len(),
fields.len()
));
}
let mut sample = Self::default();
for (i, (field, name)) in fields.iter().zip(PHASES).enumerate() {
let value = field
.strip_prefix(name)
.and_then(|v| v.strip_prefix('='))
.ok_or_else(|| format!("field {i} is not {name}=<seconds>"))?;
let value: f64 = value.parse().map_err(|_| format!("bad {name} value"))?;
if !value.is_finite() || value < 0.0 {
return Err(format!("{name} must be finite and non-negative"));
}
sample.0[i] = value;
}
Ok(sample)
}
}
/// Median, tail and extremes of one phase.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Summary {
pub(crate) n: usize,
pub(crate) min: f64,
pub(crate) median: f64,
pub(crate) p90: f64,
pub(crate) p99: f64,
pub(crate) max: f64,
}
pub(crate) fn summarize(values: &[f64]) -> Option<Summary> {
if values.is_empty() {
return None;
}
let mut sorted = values.to_vec();
sorted.sort_by(f64::total_cmp);
Some(Summary {
n: sorted.len(),
min: sorted[0],
median: percentile(&sorted, 0.5),
p90: percentile(&sorted, 0.9),
p99: percentile(&sorted, 0.99),
max: sorted[sorted.len() - 1],
})
}
struct Options {
fixture: Option<String>,
words: Option<usize>,
processes: usize,
reps: usize,
output: PathBuf,
}
fn count(value: Option<String>, flag: &str) -> Result<usize, String> {
let n: usize = value
.ok_or_else(|| format!("{flag} needs a count"))?
.parse()
.map_err(|_| format!("{flag} must be a positive integer"))?;
if n == 0 {
return Err(format!("{flag} must be at least 1"));
}
Ok(n)
}
fn parse_options(mut args: impl Iterator<Item = String>) -> Result<Options, String> {
let mut options = Options {
fixture: None,
words: None,
processes: DEFAULT_PROCESSES,
reps: DEFAULT_REPS,
output: PathBuf::from("artifacts/startup"),
};
while let Some(arg) = args.next() {
match arg.as_str() {
"--fixture" => options.fixture = Some(args.next().ok_or("--fixture needs a name")?),
"--words" => options.words = Some(count(args.next(), "--words")?),
"--processes" => options.processes = count(args.next(), "--processes")?,
"--reps" => options.reps = count(args.next(), "--reps")?,
"--output" => {
options.output = PathBuf::from(args.next().ok_or("--output needs a path")?);
}
other => return Err(format!("unknown startup argument {other}")),
}
}
Ok(options)
}
/// The fixture to time and its word count, after the reference agrees with it.
fn select(options: &Options) -> Result<(Fixture, usize), Box<dyn Error>> {
let fixtures = parse_manifest(&fs::read_to_string("benchmarks/manifest.toml")?)?;
let fixture = match &options.fixture {
Some(name) => fixtures.into_iter().find(|f| &f.name == name),
None => fixtures.into_iter().next(),
}
.ok_or("fixture not found in benchmarks/manifest.toml")?;
let code = fs::read(&fixture.path)?;
let reference = xenora_ref::execute(&code, &fixture.input).map_err(|e| e.to_string())?;
if reference != fixture.expected {
return Err("reference disagrees with hand-derived expected values".into());
}
let words = options
.words
.unwrap_or_else(|| *fixture.sizes.first().unwrap_or(&fixture.input.len()));
Ok((fixture, words))
}
/// Translates and runs the fixture once on `metal`, checking the output.
fn run_once(
metal: &NativeCompute,
fixture: &Fixture,
words: usize,
sample: &mut Sample,
) -> Result<(), Box<dyn Error>> {
let input = expand(&fixture.input, words);
let expected = expand(&fixture.expected, words);
let start = Instant::now();
let code = fs::read(&fixture.path)?;
let compiled = compile(Architecture::Gfx1030, &code).map_err(|e| e.to_string())?;
sample.0[2] = start.elapsed().as_secs_f64();
let profile = metal
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
.map_err(|e| e.to_string())?;
if profile.output != expected {
return Err(format!("{} output disagrees with known answers", fixture.name).into());
}
sample.0[3] = profile.library_seconds;
sample.0[4] = profile.pipeline_seconds;
sample.0[5] = profile.host_seconds - profile.library_seconds - profile.pipeline_seconds;
sample.0[6] = profile.gpu_seconds;
sample.0[7] = profile.readback_seconds;
Ok(())
}
fn unix_nanos(time: SystemTime) -> u128 {
time.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos())
}
/// Entry point of one fresh child process, called first thing in `main`.
///
/// `entered` is the wall-clock time at `main`; the parent passes the wall-clock
/// time just before it spawned this process.
pub(crate) fn child(
entered: SystemTime,
mut args: impl Iterator<Item = String>,
) -> Result<(), Box<dyn Error>> {
let spawned: u128 = args.next().ok_or("missing spawn time")?.parse()?;
let options = parse_options(args)?;
let (fixture, words) = select(&options)?;
let mut sample = Sample::default();
sample.0[0] = unix_nanos(entered).saturating_sub(spawned) as f64 / 1e9;
let start = Instant::now();
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
sample.0[1] = start.elapsed().as_secs_f64();
run_once(&metal, &fixture, words, &mut sample)?;
println!("{}", sample.line());
Ok(())
}
fn forwarded(fixture: &Fixture, words: usize) -> Vec<String> {
vec![
"--fixture".into(),
fixture.name.clone(),
"--words".into(),
words.to_string(),
]
}
/// Runs one fresh child and returns its spawn-to-exit wall time and stdout.
///
/// The child inherits this process's environment on purpose, so its `MTL_*`
/// validation settings are the ones the run's metadata records.
fn spawn_child(
exe: &std::path::Path,
fixture: &Fixture,
words: usize,
) -> Result<(f64, String), Box<dyn Error>> {
let started = Instant::now();
let spawned = unix_nanos(SystemTime::now());
let mut child = Command::new(exe)
.arg("startup-child")
.arg(spawned.to_string())
.args(forwarded(fixture, words))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
// Drain both pipes while waiting, so a child that writes more than a pipe
// buffer (validation logs, for example) cannot block and look like a hang.
let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
std::thread::spawn(move || {
let mut text = String::new();
if let Some(mut pipe) = pipe {
let _ = pipe.read_to_string(&mut text);
}
text
})
};
let out = drain(child.stdout.take().map(|p| Box::new(p) as _));
let err = drain(child.stderr.take().map(|p| Box::new(p) as _));
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if started.elapsed() > CHILD_TIMEOUT {
child.kill()?;
child.wait()?;
return Err(format!("no exit within {} s", CHILD_TIMEOUT.as_secs()).into());
}
std::thread::sleep(Duration::from_millis(1));
};
let seconds = started.elapsed().as_secs_f64();
let stdout = out.join().map_err(|_| "stdout reader panicked")?;
let stderr = err.join().map_err(|_| "stderr reader panicked")?;
if !status.success() {
return Err(format!("{status}: {}", stderr.trim()).into());
}
Ok((seconds, stdout))
}
/// Runs both regimes and writes `startup.json` and `report.md`.
pub(crate) fn run(args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
let options = parse_options(args)?;
let (fixture, words) = select(&options)?;
let exe = std::env::current_exe()?;
let mut fresh = Vec::with_capacity(options.processes);
let mut wall = Vec::with_capacity(options.processes);
for i in 0..options.processes {
let (seconds, stdout) = spawn_child(&exe, &fixture, words)
.map_err(|e| format!("fresh process {i} failed: {e}"))?;
wall.push(seconds);
let line = stdout
.lines()
.find(|l| l.starts_with("startup-sample "))
.ok_or_else(|| format!("fresh process {i} printed no sample"))?;
fresh.push(Sample::parse(line).map_err(|e| format!("fresh process {i}: {e}"))?);
}
let mut first = Sample::default();
let start = Instant::now();
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
first.0[1] = start.elapsed().as_secs_f64();
run_once(&metal, &fixture, words, &mut first)?;
let mut repeated = Vec::with_capacity(options.reps);
for _ in 0..options.reps {
let mut sample = Sample::default();
run_once(&metal, &fixture, words, &mut sample)?;
repeated.push(sample);
}
let metadata = Metadata::collect(&metal.device_name(), options.reps);
let dir = options
.output
.join(slug(&metadata.device))
.join(&metadata.run_id);
fs::create_dir_all(&dir)?;
fs::write(dir.join("metadata.json"), metadata.to_json())?;
let report = Report {
fixture: &fixture.name,
words,
fresh: &fresh,
wall: &wall,
first: &first,
repeated: &repeated,
};
fs::write(dir.join("startup.json"), report.json())?;
let markdown = report.markdown(&metadata);
fs::write(dir.join("report.md"), &markdown)?;
println!("{markdown}");
println!("Startup results written to {}", dir.display());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sample_lines_round_trip() {
let sample = Sample([0.5, 1e-3, 2.5e-4, 0.0, 7.0, 1e-9, 3.25, 42.0]);
assert_eq!(Sample::parse(&sample.line()), Ok(sample));
}
#[test]
fn sample_lines_reject_damaged_input() {
let line = Sample([1.0; PHASES.len()]).line();
assert!(Sample::parse(&line.replacen("startup-sample", "sample", 1)).is_err());
assert!(Sample::parse(&line.replacen("device=", "devise=", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=-1e0", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=NaN", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=x", 1)).is_err());
assert!(Sample::parse(line.rsplit_once(' ').unwrap().0).is_err());
assert!(Sample::parse(&format!("{line} extra=1")).is_err());
// Phases out of order are refused even when every name is present.
let swapped = line
.replacen("device=", "TMP=", 1)
.replacen("translate=", "device=", 1)
.replacen("TMP=", "translate=", 1);
assert!(Sample::parse(&swapped).is_err());
}
#[test]
fn summary_uses_interpolated_percentiles() {
// 1..=100: position 0.9 * 99 = 89.1 lies between 90 and 91, and
// 0.99 * 99 = 98.01 between 99 and 100.
let values: Vec<f64> = (1..=100).rev().map(f64::from).collect();
let s = summarize(&values).unwrap();
assert_eq!((s.n, s.min, s.max), (100, 1.0, 100.0));
assert!((s.median - 50.5).abs() < 1e-9);
assert!((s.p90 - 90.1).abs() < 1e-9);
assert!((s.p99 - 99.01).abs() < 1e-9);
assert_eq!(summarize(&[]), None);
let one = summarize(&[3.0]).unwrap();
assert_eq!(
(one.median, one.p90, one.p99, one.max),
(3.0, 3.0, 3.0, 3.0)
);
}
#[test]
fn options_reject_bad_counts_and_flags() {
let parse = |args: &[&str]| parse_options(args.iter().map(|s| s.to_string()));
let defaults = parse(&[]).unwrap();
assert_eq!(
(defaults.processes, defaults.reps),
(DEFAULT_PROCESSES, DEFAULT_REPS)
);
let set = parse(&["--processes", "3", "--reps", "5", "--words", "64"]).unwrap();
assert_eq!((set.processes, set.reps, set.words), (3, 5, Some(64)));
assert!(parse(&["--processes", "0"]).is_err());
assert!(parse(&["--reps", "-1"]).is_err());
assert!(parse(&["--words"]).is_err());
assert!(parse(&["--fast"]).is_err());
}
}
+146
View File
@@ -0,0 +1,146 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! JSON and markdown output of `xenora-bench startup` (#178).
use std::fmt::Write as _;
use crate::startup::{PHASES, Sample, Summary, summarize};
use crate::{Metadata, json_str};
pub(crate) struct Report<'a> {
pub(crate) fixture: &'a str,
pub(crate) words: usize,
pub(crate) fresh: &'a [Sample],
pub(crate) wall: &'a [f64],
pub(crate) first: &'a Sample,
pub(crate) repeated: &'a [Sample],
}
fn column(samples: &[Sample], phase: usize) -> Vec<f64> {
samples.iter().map(|s| s.0[phase]).collect()
}
fn summary_json(summary: Option<Summary>) -> String {
summary.map_or_else(
|| "null".to_string(),
|s| {
format!(
"{{\"n\": {}, \"min\": {:e}, \"median\": {:e}, \"p90\": {:e}, \"p99\": {:e}, \"max\": {:e}}}",
s.n, s.min, s.median, s.p90, s.p99, s.max
)
},
)
}
impl Report<'_> {
pub(crate) fn json(&self) -> String {
let mut out = format!(
"{{\n \"fixture\": {},\n \"words\": {},\n \"process_wall\": {},\n",
json_str(self.fixture),
self.words,
summary_json(summarize(self.wall))
);
for (regime, samples) in [("fresh", self.fresh), ("repeated", self.repeated)] {
let _ = writeln!(out, " \"{regime}\": {{");
for (i, phase) in PHASES.iter().enumerate() {
let comma = if i + 1 < PHASES.len() { "," } else { "" };
let summary = if regime == "repeated" && i < 2 {
None
} else {
summarize(&column(samples, i))
};
let _ = writeln!(out, " \"{phase}\": {}{comma}", summary_json(summary));
}
out.push_str(" },\n");
}
let first: Vec<String> = PHASES
.iter()
.zip(self.first.0)
.skip(1)
.map(|(p, v)| format!("\"{p}\": {v:e}"))
.collect();
let _ = writeln!(out, " \"first_in_process\": {{{}}},", first.join(", "));
// Raw fresh-process samples in launch order, so a cold first process
// (for example an empty Metal shader cache) stays visible.
let rows: Vec<String> = self
.fresh
.iter()
.zip(self.wall)
.map(|(sample, wall)| {
let phases: Vec<String> = sample.0.iter().map(|v| format!("{v:e}")).collect();
format!("[{}, {wall:e}]", phases.join(", "))
})
.collect();
let _ = writeln!(
out,
" \"fresh_samples_columns\": [{}, \"process_wall\"],\n \"fresh_samples\": [\n {}\n ]\n}}",
PHASES
.iter()
.map(|p| json_str(p))
.collect::<Vec<_>>()
.join(", "),
rows.join(",\n ")
);
out
}
pub(crate) fn markdown(&self, metadata: &Metadata) -> String {
let ms = |v: f64| format!("{:.3}", v * 1e3);
let mut out = format!(
"# Metal startup: `{}`, {} words\n\nDevice {}, {} build, commit `{}`, API validation `{}`, shader validation `{}`, power `{}`, thermal `{}`.\n\nAll values in milliseconds. Fresh: {} processes. Repeated: {} runs after the first in one process. Every sample produced the expected output.\n\n| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
self.fixture,
self.words,
metadata.device,
metadata.profile,
metadata.commit,
metadata.api_validation,
metadata.shader_validation,
metadata.power,
metadata.thermal,
self.fresh.len(),
self.repeated.len(),
);
for (i, phase) in PHASES.iter().enumerate() {
let fresh = summarize(&column(self.fresh, i));
let repeated = (i >= 2)
.then(|| summarize(&column(self.repeated, i)))
.flatten();
let cells = |s: Option<Summary>| {
s.map_or_else(
|| "– | – | – | –".to_string(),
|s| {
format!(
"{} | {} | {} | {}",
ms(s.median),
ms(s.p90),
ms(s.p99),
ms(s.max)
)
},
)
};
let first = if i == 0 {
"–".to_string()
} else {
ms(self.first.0[i])
};
let _ = writeln!(
out,
"| `{phase}` | {} | {first} | {} |",
cells(fresh),
cells(repeated)
);
}
if let Some(s) = summarize(self.wall) {
let _ = writeln!(
out,
"| process wall (spawn to exit) | {} | {} | {} | {} | – | – | – | – | – |",
ms(s.median),
ms(s.p90),
ms(s.p99),
ms(s.max)
);
}
out
}
}
+78
View File
@@ -76,6 +76,84 @@ cargo build --release -p xenora-benchmarks
MTL_DEBUG_LAYER=0 MTL_SHADER_VALIDATION=0 ./target/release/xenora-bench --reps 7
```
## Startup distributions
`xenora-bench startup` measures what it costs to get one fixture result from
Metal, in two regimes:
- **Fresh process.** The harness launches its own executable `--processes`
times (default 30), one after another. Each child creates the Metal device and
queue, translates the fixture, runs it once and checks the output.
- **Repeated.** The harness process creates one device, runs the fixture once
(reported as *first in process*), then translates and runs it `--reps` more
times (default 100).
The fixture is the first one in `benchmarks/manifest.toml` unless `--fixture`
names another, at its smallest declared size unless `--words` sets one. The
independent reference must agree with the hand-derived expected values first,
and every sample in both regimes must produce the expected words. A wrong
output, a child that fails or does not exit within 60 seconds, or a damaged
sample line stops the run before anything is written.
| Phase | Source | Meaning |
| --- | --- | --- |
| `spawn_to_main` | wall clock, parent before spawn to child `main` | Process launch and Rust runtime start (fresh only) |
| `device` | host monotonic clock | `NativeCompute::new`: device and queue (fresh, and once in the repeated process) |
| `translate` | host monotonic clock | Read the fixture and run `xenora-shader::compile` |
| `library` | `RunProfile` | `newLibraryWithSource` |
| `pipeline` | `RunProfile` | Compute pipeline state creation |
| `submit` | `RunProfile` | `host` minus `library` and `pipeline`: buffers, encode, commit, wait |
| `gpu` | `GPUEndTime - GPUStartTime` | Command-buffer GPU execution |
| `readback` | `RunProfile` | Copy the output words back |
| process wall | host monotonic clock in the parent | Spawn to exit of one fresh child |
The report gives median, p90, p99 and maximum per phase. Percentiles
interpolate linearly, so with 30 processes p99 lies between the two largest
samples. `startup.json` also keeps every fresh sample in launch order.
Children inherit the parent's environment, so the `MTL_*` validation values in
`metadata.json` apply to both regimes. Results go to the ignored
`artifacts/startup/<hardware>/<run-id>/` unless `--output` says otherwise.
```sh
cargo build --release -p xenora-benchmarks
MTL_DEBUG_LAYER=0 MTL_SHADER_VALIDATION=0 ./target/release/xenora-bench startup
```
### Recorded run
Run `1795544761`, Apple M4, release build of `0fdb995` plus this harness, API
and shader validation off, AC power, no thermal warnings, started right after
the release build. Fixture `add`, 4 words, 30 fresh processes, 100 repeated
runs. All values in milliseconds.
| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `spawn_to_main` | 2.746 | 3.133 | 5.325 | 6.198 | – | – | – | – | – |
| `device` | 35.762 | 38.770 | 41.060 | 41.864 | 32.802 | – | – | – | – |
| `translate` | 0.061 | 0.071 | 0.084 | 0.089 | 0.067 | 0.016 | 0.023 | 0.041 | 0.043 |
| `library` | 0.402 | 0.434 | 18.595 | 25.976 | 0.399 | 0.006 | 0.010 | 0.018 | 0.019 |
| `pipeline` | 0.363 | 0.401 | 0.623 | 0.708 | 0.342 | 0.013 | 0.021 | 0.031 | 0.043 |
| `submit` | 1.665 | 1.894 | 1.951 | 1.953 | 1.647 | 0.214 | 0.384 | 0.440 | 3.941 |
| `gpu` | 0.007 | 0.008 | 0.010 | 0.011 | 0.008 | 0.007 | 0.008 | 0.061 | 1.742 |
| `readback` | 0.001 | 0.001 | 0.002 | 0.002 | 0.001 | < 0.001 | < 0.001 | < 0.001 | < 0.001 |
| process wall (spawn to exit) | 43.225 | 46.770 | 68.236 | 75.958 | – | – | – | – | – |
Observations, without causal claims:
- Device and queue creation is the largest fresh-process phase, about 36 ms of a
43 ms median process. Within one process it is paid once.
- The `library` tail came from the first child launched after the build
(25.976 ms; the other 29 were 0.36–0.45 ms). A second run immediately after,
`1795544763`, had a fresh `library` maximum of 0.446 ms, with `device` median
36.414 ms and process-wall median 44.111 ms. This fits an on-disk Metal
compilation cache, but the run does not show that.
- After the first run in a process, `library` and `pipeline` fall to about
0.01 ms and `submit` to about 0.2 ms. The `gpu` time for this 4-word kernel is
at timer scale in both regimes.
Two runs on one host do not describe other Apple GPU generations, sustained
load, other fixtures or larger word counts.
## Limitations
The corpus currently covers three synthetic gfx1030 compute fixtures under the