From 8b15f6574b91d80b0f0787bce69dad18cac45c30 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 17 Nov 2026 13:52:20 -0800 Subject: [PATCH] harness: frame_5cb, a frame of five command buffers, with each command buffer's commit-to-complete time The recordings of a game commit a median of five command buffers a frame, against the one of a desktop session's frame that the frame row has. frame_5cb is that frame in compute alone: five command buffers of frame's shape (four lcg_step dispatches each, bindings set per dispatch, the increment from a Managed buffer), committed back to back and waited for once, 20 dispatches a run. Of the two rows, this one decides how many batches a runtime may keep in flight: with five commits and two in flight, three join a later batch. Beside the run's GPU span and its submissions, the row prints each command buffer's commit-to-complete time, at the 50th and 99th percentiles of the timed runs' command buffers: a plan that asks for it (Plan::commit_to_complete, frame_5cb alone) gives each command buffer of its timed runs a completed handler (addCompletedHandler:, the harness's CommandBuffer trait's new add_completed_handler) that reads the time from just before its commit until the handler runs. The warm-up, the first run and the counted run take no handler, and the other rows' command buffers take none, so their measurement is as before. After the timed runs the harness waits up to ten seconds for every handler to have run (a handler may run after the wait for its command buffer returns) and fails the row otherwise. The table gains two columns, c2c_us_p50 and c2c_us_p99, "-" for rows without the handlers. The device test of every authored workload checks that a run reports one commit-to-complete time per command buffer where the plan asks for them, and none elsewhere; a unit test checks that frame_5cb is frame's command buffer five times over. --- crates/metal2vulkan-harness/src/authored.rs | 29 ++++++- .../metal2vulkan-harness/src/bin/harness.rs | 10 ++- .../metal2vulkan-harness/src/description.rs | 1 + crates/metal2vulkan-harness/src/lib.rs | 11 ++- crates/metal2vulkan-harness/src/old.rs | 7 ++ crates/metal2vulkan-harness/src/plan.rs | 11 +++ crates/metal2vulkan-harness/src/rt.rs | 4 + crates/metal2vulkan-harness/src/run.rs | 77 +++++++++++++++++-- crates/metal2vulkan-harness/src/tests.rs | 10 +++ crates/metal2vulkan-harness/tests/authored.rs | 13 +++- 10 files changed, 158 insertions(+), 15 deletions(-) diff --git a/crates/metal2vulkan-harness/src/authored.rs b/crates/metal2vulkan-harness/src/authored.rs index 2b02edc76..138697a19 100644 --- a/crates/metal2vulkan-harness/src/authored.rs +++ b/crates/metal2vulkan-harness/src/authored.rs @@ -19,7 +19,7 @@ pub struct Workload { } /// The authored workloads. -pub const WORKLOADS: [Workload; 17] = [ +pub const WORKLOADS: [Workload; 18] = [ Workload { name: "bandwidth", plan: bandwidth, @@ -48,6 +48,10 @@ pub const WORKLOADS: [Workload; 17] = [ name: "frame", plan: frame, }, + Workload { + name: "frame_5cb", + plan: frame_5cb, + }, Workload { name: "burst_160", plan: burst_160, @@ -154,6 +158,7 @@ fn bandwidth() -> Plan { outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, } } @@ -195,6 +200,7 @@ fn alu() -> Plan { outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, } } @@ -230,6 +236,7 @@ fn threadgroup_scan() -> Plan { outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, } } @@ -285,6 +292,7 @@ fn simd_reduce() -> Plan { outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, } } @@ -341,6 +349,7 @@ fn image_filter() -> Plan { outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, } } @@ -386,6 +395,7 @@ fn dispatch_chain() -> Plan { outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, } } @@ -425,6 +435,17 @@ fn frame() -> Plan { lcg_frame("frame", 1, 4, None, Storage::Managed) } +/// A game's median frame, in the shape its recordings commit (a median of five command buffers a +/// frame), in compute alone: a run is five command buffers of four `lcg_step` dispatches each, +/// `frame`'s command buffer five times over ([`lcg_frame`]), committed back to back and waited +/// for once. Each command buffer's commit-to-complete time is timed (`Plan::commit_to_complete`). +fn frame_5cb() -> Plan { + Plan { + commit_to_complete: true, + ..lcg_frame("frame_5cb", 5, 4, None, Storage::Managed) + } +} + /// A burst of small command buffers: a run is 160 command buffers of two `lcg_step` dispatches /// each ([`lcg_frame`]). fn burst_160() -> Plan { @@ -501,6 +522,7 @@ fn lcg_frame( outputs: Vec::new(), per_command_buffer: Some(per), per_encoder, + commit_to_complete: false, } } @@ -543,6 +565,7 @@ fn wide_bindings() -> Plan { outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, } } @@ -581,6 +604,7 @@ fn waves() -> Plan { outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, } } @@ -624,6 +648,7 @@ fn narrow_ints() -> Plan { outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, } } @@ -679,6 +704,7 @@ fn zero_products() -> Plan { outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, } } @@ -769,6 +795,7 @@ fn sampling_plan( outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, } } diff --git a/crates/metal2vulkan-harness/src/bin/harness.rs b/crates/metal2vulkan-harness/src/bin/harness.rs index 1f1080f8c..d771d67d5 100644 --- a/crates/metal2vulkan-harness/src/bin/harness.rs +++ b/crates/metal2vulkan-harness/src/bin/harness.rs @@ -168,7 +168,7 @@ fn run_all(args: &Args) -> Result { ); if !workloads.is_empty() { println!( - "{:<17} {:<8} {:>10} {:>11} {:>11} {:>11} {:>11} {:>11} {:>18} {:>15} {:>11} gauges @100 -> @200", + "{:<17} {:<8} {:>10} {:>11} {:>11} {:>11} {:>11} {:>11} {:>18} {:>15} {:>11} {:>11} {:>11} gauges @100 -> @200", "workload", "runtime", "dispatches", @@ -180,6 +180,8 @@ fn run_all(args: &Args) -> Result { "encode_ns/dispatch", "cpu_ns/dispatch", "submits/run", + "c2c_us_p50", + "c2c_us_p99", ); } let set = if args.description.is_some() { @@ -337,13 +339,15 @@ fn print_create(runtime: &str, create: &Create, report: &CreateReport) { /// `report`'s row, and its matrix lines. fn print(runtime: &str, name: &str, report: &Report) { let gpu = |p| percentile(&report.gpu_us, p).map_or("-".to_owned(), |us| format!("{us:.1}")); + let commit = + |p| percentile(&report.commit_us, p).map_or("-".to_owned(), |us| format!("{us:.1}")); let per_dispatch = |values: &[f64]| { percentile(values, 50).map_or("-".to_owned(), |ns| { format!("{:.0}", ns / report.dispatches as f64) }) }; println!( - "{name:<17} {runtime:<8} {:>10} {:>11} {:>11} {:>11} {:>11} {:>11} {:>18} {:>15} {:>11} {}", + "{name:<17} {runtime:<8} {:>10} {:>11} {:>11} {:>11} {:>11} {:>11} {:>18} {:>15} {:>11} {:>11} {:>11} {}", report.dispatches, warmup(&report.warmup), gpu(10), @@ -353,6 +357,8 @@ fn print(runtime: &str, name: &str, report: &Report) { per_dispatch(&report.encode_ns), per_dispatch(&report.cpu_ns), report.submissions, + commit(50), + commit(99), gauges(&report.gauges), ); matrix(runtime, name, &report.gpu_us, &report.gauges); diff --git a/crates/metal2vulkan-harness/src/description.rs b/crates/metal2vulkan-harness/src/description.rs index fc2aea3c1..02321ced8 100644 --- a/crates/metal2vulkan-harness/src/description.rs +++ b/crates/metal2vulkan-harness/src/description.rs @@ -93,6 +93,7 @@ impl Described { outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, }; let mut lines = self.lines.iter().map(|(number, words)| { let words: Vec<&str> = words.iter().map(String::as_str).collect(); diff --git a/crates/metal2vulkan-harness/src/lib.rs b/crates/metal2vulkan-harness/src/lib.rs index 4c3c0f0bd..77f583545 100644 --- a/crates/metal2vulkan-harness/src/lib.rs +++ b/crates/metal2vulkan-harness/src/lib.rs @@ -11,7 +11,8 @@ //! A workload is a [`plan::Plan`]: its buffers and their starting contents, the dispatches of one //! run and how many go in each command buffer, the contents its buffers must hold after the first //! run, and the buffers runtimes compare. Most workloads put a run in one command buffer; `frame` -//! is shaped like a window server's frame, 160 command buffers of two small dispatches each. +//! and `frame_5cb` are frames of one and of five command buffers of four small dispatches each, +//! and the `burst_` workloads bursts of 160 and 2,000. //! A [`run::Session`] makes its objects, checks the first run, then times the rest. The authored //! workloads ([`authored`]) are MSL kernels committed as public fixtures //! (`crates/metal2vulkan-validation/fixtures/public/harness/workloads.metal`, compiled by @@ -43,7 +44,10 @@ //! 90th percentiles of the timed runs, the encoding thread's wall time per dispatch from the //! command buffer's creation through `commit`'s return, and the process's CPU time per dispatch //! from there to the return of the wait for the run before (unix only), each the median of the -//! timed runs; and the runtime's gauges after the 100th and 200th timed runs. Per creation +//! timed runs; where the workload asks for it ([`plan::Plan::commit_to_complete`]), the time of +//! each timed command buffer from just before its `commit` until its completed handler ran, at +//! the 50th and 99th percentiles of all of them; and the runtime's gauges after the 100th and +//! 200th timed runs. Per creation //! workload and runtime it prints the warm-up, the wall time of `newBufferWithLength:options:` at //! the same percentiles, and the gauges. Beside each row it prints lines for the matrix's runner //! (docs/VALIDATION.md, "The matrix"): @@ -267,6 +271,9 @@ pub trait CommandBuffer { /// `GPUEndTime`, in seconds. fn gpu_end_time(&self) -> Result; + + /// `addCompletedHandler:`, with a handler that reads nothing of the command buffer. + fn add_completed_handler(&self, handler: Box) -> Result<()>; } /// `MTLComputeCommandEncoder`. diff --git a/crates/metal2vulkan-harness/src/old.rs b/crates/metal2vulkan-harness/src/old.rs index dfd1a9814..1b3710f6b 100644 --- a/crates/metal2vulkan-harness/src/old.rs +++ b/crates/metal2vulkan-harness/src/old.rs @@ -187,6 +187,13 @@ impl crate::CommandBuffer for runtime::CommandBuffer { fn gpu_end_time(&self) -> Result { Ok(runtime::CommandBuffer::gpu_end_time(self)?) } + + fn add_completed_handler(&self, handler: Box) -> Result<()> { + Ok(runtime::CommandBuffer::add_completed_handler( + self, + Box::new(move |_| handler()), + )?) + } } impl crate::ComputeCommandEncoder for runtime::ComputeCommandEncoder { diff --git a/crates/metal2vulkan-harness/src/plan.rs b/crates/metal2vulkan-harness/src/plan.rs index b7bd3a4bd..68e46d907 100644 --- a/crates/metal2vulkan-harness/src/plan.rs +++ b/crates/metal2vulkan-harness/src/plan.rs @@ -30,6 +30,12 @@ pub struct Plan { /// order; `None`: one encoder holds the command buffer's. A binding stays set for the /// dispatches after it in its encoder, not in the next. pub per_encoder: Option, + /// Whether each command buffer of its timed runs takes a completed handler + /// (`addCompletedHandler:`) that times it from just before its `commit` until the handler + /// runs: its commit-to-complete time ([`Report::commit_us`]). The others take no handler. + /// + /// [`Report::commit_us`]: crate::run::Report::commit_us + pub commit_to_complete: bool, /// What the first run must leave in its buffers: a CPU reference. pub expect: Vec, /// What the first run must leave in its textures: a CPU reference. @@ -309,6 +315,11 @@ impl Values { } impl Plan { + /// The command buffers of one run. + pub fn command_buffers(&self) -> usize { + (self.per_command_buffer).map_or(1, |per| self.dispatches.len().div_ceil(per)) + } + /// `Ok` where every index it names exists and every length is whole and agrees. pub fn validate(&self) -> Result<()> { let name = &self.name; diff --git a/crates/metal2vulkan-harness/src/rt.rs b/crates/metal2vulkan-harness/src/rt.rs index ea342243a..41634abf0 100644 --- a/crates/metal2vulkan-harness/src/rt.rs +++ b/crates/metal2vulkan-harness/src/rt.rs @@ -394,6 +394,10 @@ impl crate::CommandBuffer for rt::CommandBuffer { fn gpu_end_time(&self) -> Result { Ok(rt::CommandBuffer::gpu_end_time(self) as f64 / 1e9) } + + fn add_completed_handler(&self, handler: Box) -> Result<()> { + rt::CommandBuffer::add_completed_handler(self, move |_| handler()).map_err(error) + } } impl crate::ComputeCommandEncoder for rt::ComputeCommandEncoder { diff --git a/crates/metal2vulkan-harness/src/run.rs b/crates/metal2vulkan-harness/src/run.rs index 12e48bd55..22265c365 100644 --- a/crates/metal2vulkan-harness/src/run.rs +++ b/crates/metal2vulkan-harness/src/run.rs @@ -8,6 +8,7 @@ use crate::{ use std::collections::HashMap; use std::ops::Range; use std::path::PathBuf; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::time::{Duration, Instant}; /// The kernel of the authored library that moves bytes for the harness, 16 a thread. @@ -134,6 +135,10 @@ pub struct Report { /// Each run's process CPU time from before its command buffer's creation through the return /// of the wait for the run before it, in nanoseconds; empty where the host has no such clock. pub cpu_ns: Vec, + /// Each timed command buffer's time from just before its `commit` until its completed + /// handler ran, in microseconds, in the order the handlers ran; empty unless the plan asks + /// for it ([`Plan::commit_to_complete`]). + pub commit_us: Vec, /// The device's gauges after the 100th and the 200th timed run, where there were that many, /// read once the work committed by then completed: what the runs left behind. pub gauges: Vec<(u32, Vec<(&'static str, u64)>)>, @@ -143,6 +148,42 @@ pub struct Report { pub warmup: Warmup, } +/// The commit-to-complete times that the completed handlers of a plan's timed command buffers +/// report ([`Plan::commit_to_complete`]). +#[derive(Default)] +struct Completions { + /// The times reported, in microseconds, in the order the handlers ran. + times: Mutex>, + /// Signalled at each report. + reported: Condvar, +} + +/// How long [`Completions::wait`] waits for the handlers of command buffers already complete. +const HANDLERS_RUN: Duration = Duration::from_secs(10); + +impl Completions { + /// Reports one command buffer's commit-to-complete time. + fn ran(&self, time: Duration) { + let mut times = self.times.lock().unwrap_or_else(PoisonError::into_inner); + times.push(time.as_secs_f64() * 1e6); + self.reported.notify_all(); + } + + /// The times of the first `count` handlers to run, once they have: a completed handler may + /// run after the wait for its command buffer returns. An error where fewer have run within + /// [`HANDLERS_RUN`]. + fn wait(&self, count: usize) -> Result> { + let times = self.times.lock().unwrap_or_else(PoisonError::into_inner); + let (times, _) = (self.reported) + .wait_timeout_while(times, HANDLERS_RUN, |times| times.len() < count) + .unwrap_or_else(PoisonError::into_inner); + if times.len() < count { + return Err(format!("{} of {count} completed handlers ran", times.len()).into()); + } + Ok(times[..count].to_vec()) + } +} + /// `Ok` where `other`'s outputs of `plan` match `reference`'s, each by its comparison. pub fn compare_outputs(plan: &Plan, reference: &Report, other: &Report) -> Result<()> { let pairs = reference.outputs.iter().zip(&other.outputs); @@ -266,14 +307,17 @@ impl Harness { /// Commits a run of `plan`, then waits for `in_flight`, the run before it, which the new one /// replaces: that run's GPU time in microseconds, and the new run's encoding time, from its /// first command buffer's creation through its last `commit`'s return. + /// Where `completions` is given, each command buffer of the new run reports its + /// commit-to-complete time there. fn next( &self, plan: &Plan, made: &Made, in_flight: &mut Vec, + completions: Option<&Arc>, ) -> Result<(f64, Duration)> { let started = Instant::now(); - let run = self.commit_run(plan, made)?; + let run = self.commit_run(plan, made, completions)?; let encoded = started.elapsed(); let before = std::mem::replace(in_flight, run); Ok((wait_run::(&before)?, encoded)) @@ -350,11 +394,23 @@ impl Harness { } /// A run of `plan`, committed: its command buffers in order, `per_command_buffer` - /// dispatches each (or all in one), with no wait between. - fn commit_run(&self, plan: &Plan, made: &Made) -> Result> { + /// dispatches each (or all in one), with no wait between. Where `completions` is given, each + /// takes a completed handler that reports its commit-to-complete time there. + fn commit_run( + &self, + plan: &Plan, + made: &Made, + completions: Option<&Arc>, + ) -> Result> { parts(0..plan.dispatches.len(), plan.per_command_buffer) .map(|range| { let command_buffer = self.encode(plan, made, range)?; + if let Some(completions) = completions { + let (completions, committed) = (Arc::clone(completions), Instant::now()); + command_buffer.add_completed_handler(Box::new(move || { + completions.ran(committed.elapsed()); + }))?; + } command_buffer.commit()?; Ok(command_buffer) }) @@ -559,7 +615,7 @@ impl Session for Harness { } self.fill(&plan.buffers, &made.buffers)?; self.fill_textures(&plan.textures, &made.textures)?; - wait_run::(&self.commit_run(plan, &made)?)?; + wait_run::(&self.commit_run(plan, &made, None)?)?; for expect in &plan.expect { let storage = plan.buffers[expect.buffer].storage; let bytes = self.read( @@ -585,17 +641,18 @@ impl Session for Harness { // The runs after the first keep two command buffers in flight: each is committed while // the GPU runs the one before it, so the GPU does not idle between runs and its clock // holds, as it does under a program that keeps it busy. - let mut in_flight = self.commit_run(plan, &made)?; - let warmup = warm_up(runs, || Ok(self.next(plan, &made, &mut in_flight)?.0))?; + let mut in_flight = self.commit_run(plan, &made, None)?; + let warmup = warm_up(runs, || Ok(self.next(plan, &made, &mut in_flight, None)?.0))?; let mut report = Report { dispatches: plan.dispatches.len(), outputs, warmup, ..Report::default() }; + let completions = (plan.commit_to_complete).then(|| Arc::new(Completions::default())); for run in 1..=runs.timed { let cpu = clocks::process_cpu_nanos(); - let (gpu_us, encoded) = self.next(plan, &made, &mut in_flight)?; + let (gpu_us, encoded) = self.next(plan, &made, &mut in_flight, completions.as_ref())?; if let (Some(before), Some(after)) = (cpu, clocks::process_cpu_nanos()) { report.cpu_ns.push(after.saturating_sub(before) as f64); } @@ -609,8 +666,12 @@ impl Session for Harness { } } wait_run::(&in_flight)?; + if let Some(completions) = completions { + let count = runs.timed as usize * plan.command_buffers(); + report.commit_us = completions.wait(count)?; + } let (before, submissions) = (self.device.counts(), self.device.submissions()); - wait_run::(&self.commit_run(plan, &made)?)?; + wait_run::(&self.commit_run(plan, &made, None)?)?; report.counts = (before.into_iter().zip(self.device.counts())) .map(|((count, before), (_, after))| (count, after - before)) .collect(); diff --git a/crates/metal2vulkan-harness/src/tests.rs b/crates/metal2vulkan-harness/src/tests.rs index 6e65fdac1..39b6366f9 100644 --- a/crates/metal2vulkan-harness/src/tests.rs +++ b/crates/metal2vulkan-harness/src/tests.rs @@ -109,6 +109,7 @@ fn one_buffer_plan(length: u64, contents: Option>, bound: usize) -> Plan outputs: Vec::new(), per_command_buffer: None, per_encoder: None, + commit_to_complete: false, } } @@ -186,6 +187,15 @@ fn a_plan_with_a_part_tile_texture_a_missing_texture_or_too_many_texels_is_refus /// A run's dispatches cut into command buffers, and a command buffer's into encoders: whole parts /// in order, the last one shorter. +#[test] +fn the_five_buffer_frame_is_the_frame_five_times_over_with_its_handlers() { + let plan = |name| (WORKLOADS.iter().find(|w| w.name == name).unwrap().plan)(); + let (frame, five) = (plan("frame"), plan("frame_5cb")); + assert_eq!((frame.command_buffers(), five.command_buffers()), (1, 5)); + assert_eq!(five.dispatches.len(), 5 * frame.dispatches.len()); + assert!(five.commit_to_complete && !frame.commit_to_complete); +} + #[test] fn parts_cut_a_range_in_order_the_last_one_shorter() { let cut = diff --git a/crates/metal2vulkan-harness/tests/authored.rs b/crates/metal2vulkan-harness/tests/authored.rs index 53b4cd472..9033254b0 100644 --- a/crates/metal2vulkan-harness/tests/authored.rs +++ b/crates/metal2vulkan-harness/tests/authored.rs @@ -16,8 +16,17 @@ fn every_workload(session: &mut dyn Session) { }; for workload in authored::WORKLOADS { let name = workload.name; - match session.run(&(workload.plan)(), runs) { - Ok(report) => assert_eq!(report.gpu_us.len(), 1, "{name}"), + let plan = (workload.plan)(); + match session.run(&plan, runs) { + Ok(report) => { + assert_eq!(report.gpu_us.len(), 1, "{name}"); + let handlers = if plan.commit_to_complete { + plan.command_buffers() + } else { + 0 + }; + assert_eq!(report.commit_us.len(), handlers, "{name}"); + } Err(why) => match why.downcast::() { Ok(refused) => println!("{name}: REFUSED: {refused}"), Err(why) => panic!("{name}: {why}"),