diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a0bad7..d84912a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,13 @@ remains unsupported. - Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status. ### 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 an opt-in, budgeted staged upload for RGBA8 textures (#144). `MetalRgba8Texture::upload_staged` fills a Private-storage texture through one reused Shared staging buffer that never exceeds a `StagingBudget`. It copies whole-row bands with a blit encoder and reuses the buffer only after the previous command buffer has diff --git a/benchmarks/src/main.rs b/benchmarks/src/main.rs index 490ae6d..d443dc9 100644 --- a/benchmarks/src/main.rs +++ b/benchmarks/src/main.rs @@ -162,10 +162,21 @@ struct BatchResult { pipelined: Stats, } +mod startup; +mod startup_report; + fn main() -> Result<(), Box> { + // 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> { .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()), diff --git a/benchmarks/src/startup.rs b/benchmarks/src/startup.rs new file mode 100644 index 0000000..a19169d --- /dev/null +++ b/benchmarks/src/startup.rs @@ -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 = 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 { + 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}="))?; + 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 { + 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, + words: Option, + processes: usize, + reps: usize, + output: PathBuf, +} + +fn count(value: Option, flag: &str) -> Result { + 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) -> Result { + 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> { + 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> { + 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, +) -> Result<(), Box> { + 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 { + 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> { + 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>| { + 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) -> Result<(), Box> { + 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 = (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()); + } +} diff --git a/benchmarks/src/startup_report.rs b/benchmarks/src/startup_report.rs new file mode 100644 index 0000000..995ef95 --- /dev/null +++ b/benchmarks/src/startup_report.rs @@ -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 { + samples.iter().map(|s| s.0[phase]).collect() +} + +fn summary_json(summary: Option) -> 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 = 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 = self + .fresh + .iter() + .zip(self.wall) + .map(|(sample, wall)| { + let phases: Vec = 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::>() + .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| { + 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 + } +} diff --git a/docs/testing/benchmarks.md b/docs/testing/benchmarks.md index bb2c50e..4aeb4b3 100644 --- a/docs/testing/benchmarks.md +++ b/docs/testing/benchmarks.md @@ -76,6 +76,88 @@ 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///` 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 + +This is the imported contributor's record for the named source revision. +The integration review does not reproduce or independently accept the full +measurement protocol below. + +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