From eb16d34f152012f47fed3bef3b345b1ce64a8bcd Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 18 Nov 2026 04:17:17 -0800 Subject: [PATCH] matrix: the instructions gate judges the new runtime's own threads, a driver's left beside The burst rows' whole-process count swung by up to 25 million instructions per run between processes on NVIDIA, all of it in the driver's own "[vkrt] Analysis" thread, while rt's own threads held steady (48-50k instructions per command buffer on the 2080, 23k on the XTX). A gate on the whole count judged the driver. rt now registers the OS id of every thread it starts in Gauges::threads, at one place: the spawn helper device::start, which the reaper, block-maker, submit and completion threads and the cache store's removal thread all start through. A thread holds its slot until it ends. The list is bounded by construction (5 slots), nothing on a commit or submit path reads it, and Device::new's paths are untouched. devtools gains ThreadInstructions (per-thread user-space counters by OS id, a thread that already ended skipped) and this_thread. The harness reads the runtime's thread ids through Device::threads before a row's timed runs, counts them with its own thread, and records own_per_run and others_per_run beside per_run. Every counter read now sits outside the timed wall span. results.py, per the planner's ruling: EXACT, the new runtime's own count at most 1.03 times its stored count (instructions.tsv now holds own counts), ratcheting down; LENIENT, named on every row, the own count at most the old runtime's whole count, old's driver share not separable since the old runtime names no threads. A whole count with no own count fails the row. The base comparison skips the harness's counts: the gate judges them. Verified: scripts/matrix/test_results.py, 42 tests OK locally. Builds and the other suites run on the check job. --- .../metal2vulkan-devtools/src/instructions.rs | 135 +++++++++++++++++- .../metal2vulkan-harness/src/bin/harness.rs | 29 +++- crates/metal2vulkan-harness/src/lib.rs | 5 + crates/metal2vulkan-harness/src/old.rs | 5 + crates/metal2vulkan-harness/src/rt.rs | 7 + crates/metal2vulkan-harness/src/run.rs | 35 ++++- crates/metal2vulkan-rt/Cargo.toml | 6 +- crates/metal2vulkan-rt/README.md | 4 +- crates/metal2vulkan-rt/src/cache.rs | 22 +-- crates/metal2vulkan-rt/src/counters.rs | 67 ++++++++- crates/metal2vulkan-rt/src/device.rs | 35 +++-- crates/metal2vulkan-rt/src/tests/cache.rs | 41 +++--- crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/VALIDATION.md | 30 ++-- scripts/matrix/instructions.tsv | 9 +- scripts/matrix/results.py | 88 ++++++++---- scripts/matrix/test_results.py | 61 +++++--- 17 files changed, 451 insertions(+), 129 deletions(-) diff --git a/crates/metal2vulkan-devtools/src/instructions.rs b/crates/metal2vulkan-devtools/src/instructions.rs index f66719225..403132394 100644 --- a/crates/metal2vulkan-devtools/src/instructions.rs +++ b/crates/metal2vulkan-devtools/src/instructions.rs @@ -16,9 +16,11 @@ //! [`ProcessInstructions`] counts the whole process in user space: the thread that opens it and //! every thread started after, through one inherited counter per core type. That is what the //! harness records per timed run, so work a runtime moves onto its own threads still counts. +//! [`ThreadInstructions`] counts named threads alone, by their OS ids: the harness's own thread and +//! the threads a runtime says it started, apart from the threads a driver starts for itself. //! //! Only Linux offers the counters (read here on its little-endian targets): elsewhere -//! [`InstructionCounter::new`] and [`ProcessInstructions::new`] answer +//! [`InstructionCounter::new`], [`ProcessInstructions::new`] and [`ThreadInstructions::new`] answer //! [`io::ErrorKind::Unsupported`], and nothing records an `instructions` line there. use std::io; @@ -144,6 +146,80 @@ impl ProcessInstructions { } } +/// User-space instructions retired by the threads of this process whose OS ids were given to +/// [`ThreadInstructions::new`], each alone (not the threads it starts), summed over every core +/// type, since the open. +pub struct ThreadInstructions { + #[cfg(all(target_os = "linux", target_endian = "little"))] + events: Vec, + #[cfg(not(all(target_os = "linux", target_endian = "little")))] + never: std::convert::Infallible, +} + +impl ThreadInstructions { + /// Opens the counters on threads `ids` (Linux thread ids, as [`this_thread`] gives), counting + /// from now. A thread that already ended is skipped: it retires nothing more. An error is the + /// kernel's refusal, or [`io::ErrorKind::Unsupported`] off Linux. + pub fn new(ids: &[u64]) -> io::Result { + #[cfg(all(target_os = "linux", target_endian = "little"))] + { + let configs = linux::core_events()?; + let mut events = Vec::with_capacity(ids.len() * configs.len()); + for &id in ids { + let thread = libc::pid_t::try_from(id).map_err(|_| { + io::Error::new(io::ErrorKind::InvalidInput, format!("thread id {id}")) + })?; + for &config in &configs { + match linux::open_thread(thread, config) { + Ok(event) => events.push(event), + Err(error) if error.raw_os_error() == Some(libc::ESRCH) => break, + Err(error) => return Err(error), + } + } + } + Ok(Self { events }) + } + #[cfg(not(all(target_os = "linux", target_endian = "little")))] + { + let _ = ids; + Err(io::Error::new( + io::ErrorKind::Unsupported, + "user-space instruction counters are read through Linux's perf_event_open alone", + )) + } + } + + /// The user-space instructions the threads retired since the open. + pub fn read(&self) -> io::Result { + #[cfg(all(target_os = "linux", target_endian = "little"))] + { + let mut retired = 0; + for event in &self.events { + retired += linux::read(event)?; + } + Ok(retired) + } + #[cfg(not(all(target_os = "linux", target_endian = "little")))] + { + match self.never {} + } + } +} + +/// The calling thread's Linux thread id (`gettid`), which [`ThreadInstructions::new`] takes; `None` +/// off Linux. +pub fn this_thread() -> Option { + #[cfg(all(target_os = "linux", target_endian = "little"))] + { + // SAFETY: `gettid` takes no argument and cannot fail. + u64::try_from(unsafe { libc::syscall(libc::SYS_gettid) }).ok() + } + #[cfg(not(all(target_os = "linux", target_endian = "little")))] + { + None + } +} + #[cfg(all(target_os = "linux", target_endian = "little"))] mod linux { use std::fs::{self, File}; @@ -214,17 +290,28 @@ mod linux { open_with(config, INHERIT | EXCLUDE_KERNEL | EXCLUDE_HV) } + /// Thread `thread`'s own user-space instructions event of `config`, counting from now. + pub(super) fn open_thread(thread: libc::pid_t, config: u64) -> io::Result { + open_on(thread, config, EXCLUDE_KERNEL | EXCLUDE_HV) + } + /// The calling thread's user-space instructions event of `config` with the bit fields `flags`. fn open_with(config: u64, flags: u64) -> io::Result { + open_on(0, config, flags) + } + + /// Thread `thread`'s user-space instructions event of `config` (0: the calling thread) with the + /// bit fields `flags`. + fn open_on(thread: libc::pid_t, config: u64, flags: u64) -> io::Result { let mut attr = [0u8; ATTR_SIZE]; attr[ATTR_TYPE..ATTR_TYPE + 4].copy_from_slice(&TYPE_HARDWARE.to_ne_bytes()); attr[ATTR_SIZE_FIELD..ATTR_SIZE_FIELD + 4] .copy_from_slice(&(ATTR_SIZE as u32).to_ne_bytes()); attr[ATTR_CONFIG..ATTR_CONFIG + 8].copy_from_slice(&config.to_ne_bytes()); attr[ATTR_FLAGS..ATTR_FLAGS + 8].copy_from_slice(&flags.to_ne_bytes()); - let (thread, any_cpu, no_group): (libc::pid_t, libc::c_int, libc::c_int) = (0, -1, -1); + let (any_cpu, no_group): (libc::c_int, libc::c_int) = (-1, -1); // SAFETY: `attr` is a valid `perf_event_attr` of the size it states and outlives the - // call; pid 0 and cpu -1 name the calling thread on any CPU, with no group. + // call; `thread` names a thread (0 the calling one) and cpu -1 any CPU, with no group. let fd = unsafe { libc::syscall( libc::SYS_perf_event_open, @@ -263,7 +350,7 @@ mod linux { #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] mod tests { - use super::{InstructionCounter, ProcessInstructions}; + use super::{this_thread, InstructionCounter, ProcessInstructions, ThreadInstructions}; use std::path::Path; /// Iterations of the fixed loop on each CPU. @@ -382,6 +469,46 @@ mod tests { ); } + /// The thread counter counts the threads it was given and no other: a thread's fixed loop on + /// every CPU it may use is in the count of a counter opened on its id, the opening thread's own + /// loop is not. + #[test] + fn the_thread_counter_counts_the_threads_named_and_no_other() { + if !counters_offered() { + assert!( + ThreadInstructions::new(&[this_thread().expect("Linux")]).is_err(), + "the host offers no counters, yet a counter opened" + ); + return; + } + let cpus = allowed_cpus(); + let expected = 2 * ITERATIONS * cpus.len() as u64; + let worker_loops = ITERATIONS * cpus.len() as u64; + let (id_tx, id_rx) = std::sync::mpsc::channel(); + let (go_tx, go_rx) = std::sync::mpsc::channel::<()>(); + let worker = std::thread::spawn(move || { + id_tx.send(this_thread().expect("Linux")).expect("the id"); + go_rx.recv().expect("the go"); + for &cpu in &cpus { + pin(&[cpu]); + fixed_loop(ITERATIONS); + } + }); + let id = id_rx.recv().expect("the worker's id"); + let counter = ThreadInstructions::new(&[id]).expect("the host offers counters"); + let before = counter.read().expect("reading the counters"); + // The opening thread's own loop, as long as the worker's, which the counter is not on. + fixed_loop(worker_loops); + go_tx.send(()).expect("the go"); + worker.join().expect("the loop's thread"); + let counted = counter.read().expect("reading the counters") - before; + // The wait for the go, the pinning and the thread's end add their own instructions. + assert!( + (expected..expected + expected / 20).contains(&counted), + "{counted} user-space instructions counted for {expected}" + ); + } + /// The process counter counts a thread started after it opened: the fixed loop on every CPU /// that thread may use, on a thread of its own, is in the count once the thread ended. #[test] diff --git a/crates/metal2vulkan-harness/src/bin/harness.rs b/crates/metal2vulkan-harness/src/bin/harness.rs index 16d0b668a..14758bf10 100644 --- a/crates/metal2vulkan-harness/src/bin/harness.rs +++ b/crates/metal2vulkan-harness/src/bin/harness.rs @@ -644,12 +644,29 @@ fn print(runtime: &str, name: &str, report: &Report) { for (count, value) in &report.counts { println!("M2V-MATRIX metric harness-{runtime}/{name}/{count}_per_run {value}"); } - // The whole process's user-space instructions per timed run at the 50th percentile, where the - // kernel offered the counter; none for a row the device sizes, whose work follows the size. - let mut instructions = report.instructions.clone(); - instructions.sort_unstable(); - if let (Some(&p50), None) = (instructions.get(instructions.len() / 2), report.scaled_to) { - println!("M2V-MATRIX instructions harness-{runtime}/{name}/per_run {p50}"); + // User-space instructions per timed run at the 50th percentile, where the kernel offered the + // counter: the whole process's, the runtime's own threads' with the harness's where the + // runtime names its threads, and the rest, the threads a driver started for itself. None for a + // row the device sizes, whose work follows the size. + if report.scaled_to.is_none() { + let p50 = |mut values: Vec| { + values.sort_unstable(); + values.get(values.len() / 2).copied() + }; + if let Some(whole) = p50(report.instructions.clone()) { + println!("M2V-MATRIX instructions harness-{runtime}/{name}/per_run {whole}"); + } + if report.own_instructions.len() == report.instructions.len() { + let others = (report.instructions.iter().zip(&report.own_instructions)) + .map(|(whole, own)| whole.saturating_sub(*own)) + .collect(); + if let (Some(own), Some(others)) = (p50(report.own_instructions.clone()), p50(others)) { + println!("M2V-MATRIX instructions harness-{runtime}/{name}/own_per_run {own}"); + println!( + "M2V-MATRIX instructions harness-{runtime}/{name}/others_per_run {others}" + ); + } + } } } diff --git a/crates/metal2vulkan-harness/src/lib.rs b/crates/metal2vulkan-harness/src/lib.rs index d26667bb5..064bfa2b6 100644 --- a/crates/metal2vulkan-harness/src/lib.rs +++ b/crates/metal2vulkan-harness/src/lib.rs @@ -231,6 +231,11 @@ pub trait Device: Sized { /// they end with it. No Metal counterpart. fn gauges_after_drop(&self) -> Option; + /// The OS ids of the threads the runtime started for the device and runs now, by its own + /// account; empty where it gives none. The harness counts these and its own thread as the + /// runtime's work, apart from the threads a driver starts for itself. No Metal counterpart. + fn threads(&self) -> Vec; + /// How many `VkPipeline`s the runtime has created on the device so far, by its own count. No /// Metal counterpart. fn pipelines_created(&self) -> u64; diff --git a/crates/metal2vulkan-harness/src/old.rs b/crates/metal2vulkan-harness/src/old.rs index 729271ef6..8f92c16c5 100644 --- a/crates/metal2vulkan-harness/src/old.rs +++ b/crates/metal2vulkan-harness/src/old.rs @@ -58,6 +58,11 @@ impl crate::Device for runtime::Device { None } + /// None: the old runtime gives no account of its threads. + fn threads(&self) -> Vec { + Vec::new() + } + /// The `VkPipeline`s its pipeline states' variants made (`WorkCounts::variant_pipelines_made`): /// compute regions, replays and draws, those made at a state's creation among them. fn pipelines_created(&self) -> u64 { diff --git a/crates/metal2vulkan-harness/src/rt.rs b/crates/metal2vulkan-harness/src/rt.rs index 2b21a540e..42e37f2bf 100644 --- a/crates/metal2vulkan-harness/src/rt.rs +++ b/crates/metal2vulkan-harness/src/rt.rs @@ -401,6 +401,13 @@ impl crate::Device for Device { named(self.device.counters().gauges()) } + /// `Gauges::threads`: its reaper, block-maker, submit and completion threads, and its cache + /// directory's removal thread while one runs. + fn threads(&self) -> Vec { + let threads = self.device.counters().gauges().threads; + threads.into_iter().filter(|&id| id != 0).collect() + } + /// The same gauges through the device's counters, which stay readable once it is torn down. fn gauges_after_drop(&self) -> Option { let counters = self.device.counters(); diff --git a/crates/metal2vulkan-harness/src/run.rs b/crates/metal2vulkan-harness/src/run.rs index 5effd58b3..7823dd5aa 100644 --- a/crates/metal2vulkan-harness/src/run.rs +++ b/crates/metal2vulkan-harness/src/run.rs @@ -10,7 +10,7 @@ use crate::{ ComputeDevice, Device, Failed, Library, Refused, RenderCommandEncoder, Result, Storage, Texture, Waits, }; -use metal2vulkan_devtools::instructions::ProcessInstructions; +use metal2vulkan_devtools::instructions::{this_thread, ProcessInstructions, ThreadInstructions}; use std::collections::HashMap; use std::ops::Range; use std::path::PathBuf; @@ -187,10 +187,15 @@ 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 run's user-space instructions in the whole process over the same span, every thread - /// of the runtime and its driver included ([`count_instructions`]); empty where the kernel - /// refused the counter. + /// Each run's user-space instructions in the whole process from just before its command + /// buffer's creation through just after the wait, every thread of the runtime and its driver + /// included ([`count_instructions`]); empty where the kernel refused the counter. pub instructions: Vec, + /// Each run's user-space instructions over the same span on the harness's own thread and the + /// threads the runtime started ([`Device::threads`](crate::Device::threads)), the runtime's own + /// work; empty where the runtime names no thread or the kernel refused the counter. The rest + /// of [`instructions`](Self::instructions) is the threads a driver started for itself. + pub own_instructions: Vec, /// Each timed command buffer's time from just before its `commit` until its completed /// handler ran, in microseconds, by its place in its run: one list per place, the first /// committed first, each in the order the handlers ran. Empty unless the plan asks for it @@ -505,6 +510,18 @@ impl Harness { Ok((wait_run::(&before)?, encoded)) } + /// The counter of the runtime's own work: the harness's thread and the threads the runtime + /// started ([`Device::threads`](crate::Device::threads)); none where the runtime names no + /// thread or the kernel refuses the counter. + fn own_threads(&self) -> Option { + let runtime = self.device.threads(); + if runtime.is_empty() { + return None; + } + let ids: Vec = this_thread().into_iter().chain(runtime).collect(); + ThreadInstructions::new(&ids).ok() + } + /// Makes the library `source` names, where it is the render library or a metallib no plan /// named before. fn load(&mut self, source: &Source) -> Result<()> { @@ -1012,18 +1029,24 @@ impl Session for Harness { }; let completions = (plan.commit_to_complete).then(|| Arc::new(Completions::default())); let (submitted, infos) = (self.device.submissions(), self.device.submit_infos()); + let own = self.own_threads(); + let own_count = || own.as_ref().and_then(|own| own.read().ok()); for run in 1..=runs.timed { + // The counters are read outside the timed span, so their reads do not lengthen it. + let (retired, owned) = (instructions(), own_count()); let wall = Instant::now(); let cpu = clocks::process_cpu_nanos(); - let retired = instructions(); 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); } + report.wall_us.push(wall.elapsed().as_secs_f64() * 1e6); + if let (Some(before), Some(after)) = (owned, own_count()) { + report.own_instructions.push(after.saturating_sub(before)); + } if let (Some(before), Some(after)) = (retired, instructions()) { report.instructions.push(after.saturating_sub(before)); } - report.wall_us.push(wall.elapsed().as_secs_f64() * 1e6); report.encode_ns.push(encoded.as_nanos() as f64); report.gpu_us.push(gpu_us); if run == 100 || run == 200 { diff --git a/crates/metal2vulkan-rt/Cargo.toml b/crates/metal2vulkan-rt/Cargo.toml index 4657f9f04..e4ac49fb0 100644 --- a/crates/metal2vulkan-rt/Cargo.toml +++ b/crates/metal2vulkan-rt/Cargo.toml @@ -23,13 +23,13 @@ ash = { workspace = true, features = ["std", "loaded"] } # The translator: Metal AIR to SPIR-V, through its public API only. metal2vulkan = { version = "0.2.0", path = "../metal2vulkan", features = ["ash"] } -# The host clock of command buffer times on unix. +# The host clock of command buffer times, and the ids of the runtime's threads, on unix. [target.'cfg(unix)'.dependencies] libc.workspace = true -# The same on Windows: the performance counter. +# The same on Windows: the performance counter and `GetCurrentThreadId`. [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_System_Performance"] } +windows-sys = { workspace = true, features = ["Win32_System_Performance", "Win32_System_Threading"] } [dev-dependencies] # The tests' fixture assembler and fixture directories. Path-only, so publishing drops it. diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 223aa8edf..30438b082 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -45,7 +45,9 @@ time, so no driver free runs on the completion thread and a submission waits beh lowers the compute pipeline states' emulated-SIMD-group variants after their creation returned, and makes the device's pipeline cache when it starts and writes it to the cache directory once pipeline creation is quiet. While an old generation of the cache directory is removed, a thread of -the store's own does it, and ends with the removal; no teardown waits for it. +the store's own does it, and ends with the removal; no teardown waits for it. `Gauges::threads` +holds the OS id of each of these threads while it runs, so a tool can tell the runtime's own work +from the threads a driver starts for itself. A device is torn down when its last handle, and the last handle of every object made from it, is dropped; a committed command buffer and the blocks the consumer holds do not keep it alive. Teardown stops the submit thread, which submits what is ready and ends what it holds with diff --git a/crates/metal2vulkan-rt/src/cache.rs b/crates/metal2vulkan-rt/src/cache.rs index de5ebfda6..aea15516b 100644 --- a/crates/metal2vulkan-rt/src/cache.rs +++ b/crates/metal2vulkan-rt/src/cache.rs @@ -82,7 +82,6 @@ use std::io::{self, ErrorKind, Read, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering::Relaxed, Ordering::SeqCst}; use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError}; -use std::thread; use std::time::{Duration, SystemTime}; /// The cap of the lowerings in a cache directory where the consumer names none: half of it, what @@ -138,6 +137,8 @@ pub(crate) struct Store { /// Young's number as this store last read or wrote the state file, 0 before it has: what a /// lookup tries, without reading the file. It only grows. young: AtomicU64, + /// The device's counters, whose thread gauge holds the removal thread while it runs. + counters: Counters, /// The times the store listed the cache directory. #[cfg(test)] pub(crate) listings: AtomicUsize, @@ -149,7 +150,7 @@ pub(crate) struct Store { impl Store { /// The store in `root`, made where it is missing; it starts the removal of a generation a /// removal before left, and of an earlier version's pipeline data. - pub(crate) fn open(root: PathBuf, cap: u64) -> Arc { + pub(crate) fn open(root: PathBuf, cap: u64, counters: Counters) -> Arc { let _ = fs::create_dir_all(&root); let path = root.join(STATE); let opened = File::options() @@ -170,6 +171,7 @@ impl Store { writer: Mutex::new(()), removing: AtomicBool::new(false), young: AtomicU64::new(0), + counters, #[cfg(test)] listings: AtomicUsize::new(0), #[cfg(test)] @@ -270,7 +272,7 @@ impl Store { let start = std::time::Instant::now(); while self.removing.load(SeqCst) { assert!(start.elapsed().as_secs() < 60, "the removal ends"); - thread::sleep(std::time::Duration::from_millis(1)); + std::thread::sleep(std::time::Duration::from_millis(1)); } } @@ -415,9 +417,8 @@ impl Store { return; } let store = Arc::clone(self); - let started = thread::Builder::new() - .name("m2v-store-remove".to_string()) - .spawn(move || store.remove()); + let started = + crate::device::start("m2v-store-remove", &self.counters, move || store.remove()); if started.is_err() { self.removing.store(false, SeqCst); } @@ -829,10 +830,11 @@ unsafe fn data_size(device: &ash::Device, cache: vk::PipelineCache) -> u64 { } impl Caches { - /// A device's caches, in `dir` where there is one, the lowerings at most `cap` bytes. - pub(crate) fn new(dir: Option<&Path>, cap: u64) -> Caches { + /// A device's caches, in `dir` where there is one, the lowerings at most `cap` bytes; its + /// removal thread counts in `counters`' thread gauge. + pub(crate) fn new(dir: Option<&Path>, cap: u64, counters: &Counters) -> Caches { Caches { - store: dir.map(|dir| Store::open(dir.to_owned(), cap)), + store: dir.map(|dir| Store::open(dir.to_owned(), cap, counters.clone())), dir: dir.map(Path::to_owned), blob: OnceLock::new(), pipelines: Mutex::new(Pipelines { @@ -944,7 +946,7 @@ impl Caches { .writes_stalled .load(std::sync::atomic::Ordering::Acquire) { - thread::sleep(Duration::from_millis(1)); + std::thread::sleep(Duration::from_millis(1)); } if let Some(store) = &self.store { if store.put(file, bytes) { diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index 5cc4c2682..c6e32e2d6 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -4,6 +4,10 @@ use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; use std::sync::Arc; +/// The most threads a device runs at once: its reaper, block-maker, submit and completion +/// threads, and its cache directory's removal thread while one runs. +const THREADS: usize = 5; + /// A metric the runtime adds to. #[derive(Clone, Copy)] pub(crate) enum Metric { @@ -116,6 +120,8 @@ pub struct Counters { #[derive(Default)] struct Atomics { + /// [`Gauges::threads`]: each slot a running thread's id, 0 where none holds it. + threads: [AtomicU64; THREADS], submissions: AtomicU64, submit_infos: AtomicU64, passes: AtomicU64, @@ -439,10 +445,23 @@ impl Counters { } } + /// Holds a slot of [`Gauges::threads`] for the calling thread, a thread the runtime started, + /// until the guard drops as it ends. + pub(crate) fn thread_started(&self) -> ThreadSlot { + let id = os_thread_id(); + let slot = (self.atomics.threads.iter()) + .position(|slot| slot.compare_exchange(0, id, Relaxed, Relaxed).is_ok()); + ThreadSlot { + atomics: Arc::clone(&self.atomics), + slot, + } + } + /// No Metal counterpart: the live count of each kind of resource. pub fn gauges(&self) -> Gauges { let a = &self.atomics; Gauges { + threads: std::array::from_fn(|slot| a.threads[slot].load(Relaxed)), buffers: a.buffers.load(Relaxed), textures: a.textures.load(Relaxed), samplers: a.samplers.load(Relaxed), @@ -628,11 +647,57 @@ pub struct Metrics { pub capture_wait_nanos: u64, } +/// A thread's slot in [`Gauges::threads`], given back as it drops. +pub(crate) struct ThreadSlot { + atomics: Arc, + slot: Option, +} + +impl Drop for ThreadSlot { + fn drop(&mut self) { + if let Some(slot) = self.slot { + self.atomics.threads[slot].store(0, Relaxed); + } + } +} + +/// The calling thread's id as the OS numbers it: Linux's `gettid`, the Apple platforms' +/// `pthread_threadid_np`, Windows' `GetCurrentThreadId`; 0 on any other. +fn os_thread_id() -> u64 { + #[cfg(target_os = "linux")] + { + // SAFETY: `gettid` takes no argument and cannot fail. + unsafe { libc::syscall(libc::SYS_gettid) as u64 } + } + #[cfg(target_vendor = "apple")] + { + let mut id = 0; + // SAFETY: a null thread names the calling one, and `id` outlives the call. + unsafe { libc::pthread_threadid_np(0 as libc::pthread_t, &mut id) }; + id + } + #[cfg(windows)] + { + // SAFETY: it takes no argument and cannot fail. + u64::from(unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }) + } + #[cfg(not(any(target_os = "linux", target_vendor = "apple", windows)))] + { + 0 + } +} + /// No Metal counterpart: the live count of each kind of resource. Every one is zero once the -/// device is torn down. +/// device is torn down, [`threads`](Self::threads) once its cache directory's removal thread, +/// which no teardown waits for, has ended too. #[non_exhaustive] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Gauges { + /// The OS id of each thread the device runs (its reaper, block-maker, submit and completion + /// threads, and its cache directory's removal thread while one runs), in no order, 0 in a + /// slot no thread holds; all 0 on an OS whose thread ids the runtime does not read. The + /// harness tells the runtime's own threads from the driver's by them. + pub threads: [u64; THREADS], /// Buffers. pub buffers: u64, /// Textures: each one's image, its views and its memory, until the reaper frees them. diff --git a/crates/metal2vulkan-rt/src/device.rs b/crates/metal2vulkan-rt/src/device.rs index 781c5ad94..dfa721252 100644 --- a/crates/metal2vulkan-rt/src/device.rs +++ b/crates/metal2vulkan-rt/src/device.rs @@ -390,11 +390,12 @@ impl Device { answer(&mut properties.properties.limits); let max_allocations = properties.properties.limits.max_memory_allocation_count; let granularity = properties.properties.limits.buffer_image_granularity; + let counters = Counters::new(); let caches = Caches::new( options.pipeline_cache_dir.as_deref(), (options.pipeline_cache_cap).unwrap_or(cache::DEFAULT_CAP), + &counters, ); - let counters = Counters::new(); // SAFETY: the device was made from `raw` with `capabilities.features`, and the family is // its queues' family. let made = unsafe { objects(&device, &capabilities, &counters, max_allocations) }; @@ -709,19 +710,35 @@ impl Device { } } +/// Starts a thread of the runtime's named `name`, which runs `body` holding a slot of the +/// device's [`Gauges::threads`](crate::Gauges::threads) until it ends: every thread the runtime +/// starts starts here. +pub(crate) fn start( + name: &str, + counters: &Counters, + body: impl FnOnce() + Send + 'static, +) -> std::io::Result> { + let counters = counters.clone(); + thread::Builder::new() + .name(name.to_string()) + .spawn(move || { + let _slot = counters.thread_started(); + body(); + }) +} + /// Starts a runtime thread that serves `core` in `role`. fn spawn(name: &str, core: &Arc, role: Role, body: fn(Arc)) -> Result { let ended = Arc::new(Ended::default()); let ending = Ending(Arc::clone(&ended)); let core = Arc::clone(core); - let handle = thread::Builder::new() - .name(name.to_string()) - .spawn(move || { - let _ending = ending; - SERVES.set((Arc::as_ptr(&core) as usize, role)); - body(core); - }) - .map_err(Error::Thread)?; + let counters = core.counters.clone(); + let handle = start(name, &counters, move || { + let _ending = ending; + SERVES.set((Arc::as_ptr(&core) as usize, role)); + body(core); + }) + .map_err(Error::Thread)?; Ok(Runner { handle, ended, diff --git a/crates/metal2vulkan-rt/src/tests/cache.rs b/crates/metal2vulkan-rt/src/tests/cache.rs index fd0f62588..6a7785ad0 100644 --- a/crates/metal2vulkan-rt/src/tests/cache.rs +++ b/crates/metal2vulkan-rt/src/tests/cache.rs @@ -9,6 +9,7 @@ use crate::cache::{ blob_name, checksum, frame, prune_blobs, unframe, Pending, State, Store, BLOBS_KEPT, }; +use crate::counters::Counters; use std::fs; use std::io::ErrorKind; use std::path::{Path, PathBuf}; @@ -80,7 +81,7 @@ fn state(store: &Store) -> State { #[test] fn a_store_filled_past_its_cap_stays_within_it_and_moves_on() { let scratch = Scratch::new("store-cap"); - let store = Store::open(scratch.0.clone(), 1000); + let store = Store::open(scratch.0.clone(), 1000, Counters::new()); assert_eq!(state(&store), State { young: 1, bytes: 0 }); for n in 0..40 { assert!(store.put(&name(n), &[n as u8; 100]), "file {n} written"); @@ -124,7 +125,7 @@ fn a_store_filled_past_its_cap_stays_within_it_and_moves_on() { #[test] fn a_hit_in_old_moves_into_young_and_outlives_the_next_generation() { let scratch = Scratch::new("store-old"); - let store = Store::open(scratch.0.clone(), 1000); + let store = Store::open(scratch.0.clone(), 1000, Counters::new()); for n in 0..6 { assert!(store.put(&name(n), &[n as u8; 100])); } @@ -152,8 +153,8 @@ fn a_hit_in_old_moves_into_young_and_outlives_the_next_generation() { #[test] fn a_lookup_reads_no_state_and_sees_another_stores_move_at_its_next_write() { let scratch = Scratch::new("store-young"); - let first = Store::open(scratch.0.clone(), 1000); - let second = Store::open(scratch.0.clone(), 1000); + let first = Store::open(scratch.0.clone(), 1000, Counters::new()); + let second = Store::open(scratch.0.clone(), 1000, Counters::new()); assert!(first.put(&name(0), &[0; 100])); let reads = first.state_reads.load(Relaxed); for _ in 0..10 { @@ -189,7 +190,7 @@ fn a_lookup_reads_no_state_and_sees_another_stores_move_at_its_next_write() { #[test] fn a_reopened_store_reads_its_state_and_lists_no_directory() { let scratch = Scratch::new("store-reopen"); - let store = Store::open(scratch.0.clone(), 1000); + let store = Store::open(scratch.0.clone(), 1000, Counters::new()); assert_eq!( store.listings.load(Relaxed), 1, @@ -201,7 +202,7 @@ fn a_reopened_store_reads_its_state_and_lists_no_directory() { store.settle(); let before = state(&store); drop(store); - let reopened = Store::open(scratch.0.clone(), 1000); + let reopened = Store::open(scratch.0.clone(), 1000, Counters::new()); assert_eq!(state(&reopened), before); // Files 20 to 22 in young, file 15 in old. for n in [20, 21, 22, 15] { @@ -218,7 +219,7 @@ fn a_reopened_store_reads_its_state_and_lists_no_directory() { #[test] fn a_removal_cut_short_is_finished_by_the_next_open() { let scratch = Scratch::new("store-cut"); - let store = Store::open(scratch.0.clone(), 1000); + let store = Store::open(scratch.0.clone(), 1000, Counters::new()); for n in 0..16 { assert!(store.put(&name(n), &[n as u8; 100])); } @@ -232,7 +233,7 @@ fn a_removal_cut_short_is_finished_by_the_next_open() { fs::create_dir_all(path.parent().expect("a parent")).expect("the directory"); fs::write(&path, [0; 100]).expect("the file"); } - let reopened = Store::open(scratch.0.clone(), 1000); + let reopened = Store::open(scratch.0.clone(), 1000, Counters::new()); reopened.settle(); assert!(!reopened.generation(2).exists() && !reopened.generation(1).exists()); assert!(reopened.generation(3).exists() && reopened.generation(4).exists()); @@ -259,7 +260,7 @@ fn store_exit_child() { let Some(dir) = std::env::var_os(EXIT_DIR) else { return; }; - let store = Store::open(PathBuf::from(dir), EXIT_CAP); + let store = Store::open(PathBuf::from(dir), EXIT_CAP, Counters::new()); for n in 0..=2 * EXIT_FILES { assert!(store.put(&name(n), &[1; 10])); } @@ -290,7 +291,7 @@ fn a_process_that_exits_in_a_removal_leaves_it_to_the_next_open() { assert!(status.success(), "the child wrote every file"); let dead = scratch.0.join("g1"); assert!(dead.exists(), "the child exited before its removal ended"); - let reopened = Store::open(scratch.0.clone(), EXIT_CAP); + let reopened = Store::open(scratch.0.clone(), EXIT_CAP, Counters::new()); reopened.settle(); assert!(!dead.exists(), "the next open finished the removal"); assert_eq!( @@ -311,7 +312,7 @@ fn a_process_that_exits_in_a_removal_leaves_it_to_the_next_open() { #[test] fn a_torn_or_missing_state_is_rebuilt_from_the_generations() { let scratch = Scratch::new("store-state"); - let store = Store::open(scratch.0.clone(), 1000); + let store = Store::open(scratch.0.clone(), 1000, Counters::new()); for n in 0..13 { assert!(store.put(&name(n), &[n as u8; 100])); } @@ -320,7 +321,7 @@ fn a_torn_or_missing_state_is_rebuilt_from_the_generations() { drop(store); for torn in [&b"cut short"[..], &[7; 24][..], &[][..]] { fs::write(scratch.0.join("state"), torn).expect("the state torn"); - let reopened = Store::open(scratch.0.clone(), 1000); + let reopened = Store::open(scratch.0.clone(), 1000, Counters::new()); assert_eq!( reopened.listings.load(Relaxed), 1, @@ -337,7 +338,7 @@ fn a_torn_or_missing_state_is_rebuilt_from_the_generations() { assert_eq!(reopened.get(&name(12), whole), Some(vec![12; 100])); } fs::remove_file(scratch.0.join("state")).expect("the state removed"); - let reopened = Store::open(scratch.0.clone(), 1000); + let reopened = Store::open(scratch.0.clone(), 1000, Counters::new()); assert_eq!( state(&reopened), State { @@ -362,7 +363,7 @@ fn a_torn_or_missing_state_is_rebuilt_from_the_generations() { #[test] fn a_torn_file_is_a_miss_and_is_removed() { let scratch = Scratch::new("store-torn"); - let store = Store::open(scratch.0.clone(), 1000); + let store = Store::open(scratch.0.clone(), 1000, Counters::new()); let data: Vec = (0..=255).collect(); assert!(store.put(&name(1), &framed(&data))); let path = store.generation(1).join(name(1)); @@ -381,8 +382,8 @@ fn a_torn_file_is_a_miss_and_is_removed() { #[test] fn stores_on_one_directory_share_its_files_and_its_count() { let scratch = Scratch::new("store-share"); - let first = Store::open(scratch.0.clone(), 1000); - let second = Store::open(scratch.0.clone(), 1000); + let first = Store::open(scratch.0.clone(), 1000, Counters::new()); + let second = Store::open(scratch.0.clone(), 1000, Counters::new()); assert!(first.put(&name(1), b"compiled")); assert_eq!(second.get(&name(1), whole), Some(b"compiled".to_vec())); assert_eq!(state(&second).bytes, 8); @@ -534,7 +535,7 @@ fn the_write_queue_refuses_a_file_past_its_bound() { #[test] fn an_earlier_versions_pipeline_data_is_removed_at_open() { let scratch = Scratch::new("store-earlier"); - let store = Store::open(scratch.0.clone(), 1000); + let store = Store::open(scratch.0.clone(), 1000, Counters::new()); for n in 0..6 { assert!(store.put(&name(n), &[n as u8; 100])); } @@ -548,7 +549,7 @@ fn an_earlier_versions_pipeline_data_is_removed_at_open() { fs::create_dir_all(dir).expect("an earlier version's directory"); fs::write(dir.join(format!("{:064x}", 1)), [1; 50]).expect("its file"); } - let reopened = Store::open(scratch.0.clone(), 1000); + let reopened = Store::open(scratch.0.clone(), 1000, Counters::new()); reopened.settle(); for g in [1, 2] { let dir = scratch.0.join(format!("g{g}/pipelines")); @@ -605,7 +606,7 @@ fn store_stress_child() { let Some(dir) = std::env::var_os(STRESS_DIR) else { return; }; - let store = Store::open(PathBuf::from(dir), STRESS_CAP); + let store = Store::open(PathBuf::from(dir), STRESS_CAP, Counters::new()); assert_eq!(stress(&store, u64::from(std::process::id()), 4000), 0); store.settle(); } @@ -625,7 +626,7 @@ fn stores_in_threads_and_processes_racing_writes_moves_and_flips_corrupt_nothing }) .collect(); let stores: Vec> = (0..3) - .map(|_| Store::open(scratch.0.clone(), STRESS_CAP)) + .map(|_| Store::open(scratch.0.clone(), STRESS_CAP, Counters::new())) .collect(); std::thread::scope(|scope| { let workers: Vec<_> = (0..6) diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index e7bba95f2..a697215c8 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2308,6 +2308,7 @@ field metal2vulkan-rt::Gauges.stage_entries pub stage_entries: u64 field metal2vulkan-rt::Gauges.stage_entry_bytes pub stage_entry_bytes: u64 field metal2vulkan-rt::Gauges.staging_bytes pub staging_bytes: u64 field metal2vulkan-rt::Gauges.textures pub textures: u64 +field metal2vulkan-rt::Gauges.threads pub threads: [u64; THREADS] field metal2vulkan-rt::HeapRange.block pub block: BlockId field metal2vulkan-rt::HeapRange.len pub len: u64 field metal2vulkan-rt::HeapRange.offset pub offset: u64 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 554a6d785..807063b76 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -303,7 +303,7 @@ changes the harness sets the base for the next. | Kind | What it counts | Fails when | |---|---|---| | `metric` | A deterministic count per frame or per command buffer: submissions, passes, barriers, bytes copied, pipelines created | It is larger than the base's | -| `instructions` | User-space CPU instructions per draw or per dispatch, and per harness run (`harness-//per_run`: the whole process's, every runtime and driver thread counted, the p50 over the row's timed runs) | It is more than 1% over the base's (the old runtime's are parked) | +| `instructions` | User-space CPU instructions per draw or per dispatch, and per harness run, the p50 over the row's timed runs: the whole process's (`harness-//per_run`), and where the runtime names its threads, theirs with the harness's thread (`.../own_per_run`) and the rest, a driver's own threads (`.../others_per_run`) | It is more than 1% over the base's; the harness's counts are judged by the instructions gate instead | | `gauge` | Live objects of one resource kind, the key ending in the point it was read at: `@100` and `@200` (loop iterations), `@drop` (after the device dropped) | `@drop` is not 0, or `@200` differs from `@100`; for the memory pool's `blocks`, which frees allocations an earlier workload left idle once the most bytes in use over its window falls and the device is quiet for 20 ms, only `@200` over `@100` | | `time` | A duration in microseconds: what a program waits on in a harness workload's run, timed on the host: its last command buffer's commit-to-complete time where the workload times it (the others' lateness is a column of the harness's table and no record), else the host wall time a run adds (a run's GPU time is a record of its own, `harness-gpu-/`, parked here and judged by the harness budget) | Only as a cross-GPU outlier: its ratio to the base's is more than 1.25 times the median of that ratio over at least 3 GPUs | | `size` | The size a harness row whose size follows the device ran at (`long_4cb`) | The leg's two runtimes ran the row at different sizes: its times are then not compared (the harness budget) | @@ -350,15 +350,19 @@ a few percent where its host time spreads up to 1.3 (the XTX's `simd_reduce`: GP µs over 8 runs, host time 44.9-55.8 µs). The frame and burst rows (`WALL_ROWS` in `scripts/matrix/results.py`), whose GPU time spans the gaps between their command buffers and spreads as widely, stay on their times and floors, and where both runtimes counted them (Linux, -a node that grants the counter), each must also pass the instructions gate: its instructions per -timed run on the new runtime (the whole process's, `instructions harness-//per_run`) -at most the old runtime's, and at most 1.03 times its stored count -(`scripts/matrix/instructions.tsv`: one count per row where the legs agree within 3%, else one -per driver family). A stored count only ratchets down: a leg more than 1% under it is named, and -nothing raises it without a ruling; a row with none stored is named and gated against the old -runtime alone. The count repeats to well under 1% between runs where the time does not, so a -time that moves while its count holds names waits. Every row records its count; only these are -gated on it. A row whose GPU time varies on +a node that grants the counter), each must also pass the instructions gate, on the new runtime's +own instructions per timed run: those of the threads it started, which `Gauges::threads` names, +and of the harness's thread (`instructions harness-new//own_per_run`). A driver's own threads +are left out (`.../others_per_run`, shown beside): they swing by millions of instructions per run +between processes (NVIDIA's on `burst_160`, 0 to 25 million), where the runtime's own do not. +EXACT: the own count is at most 1.03 times its stored count (`scripts/matrix/instructions.tsv`: +one count per row where the legs agree within 3%, else one per driver family). A stored count +only ratchets down: a leg more than 1% under it is named, and nothing raises it without a ruling; +a row with none stored is named. LENIENT, named on every row: the own count is at most the old +runtime's whole count (`.../per_run`), the old runtime naming none of its threads, so its driver's +share cannot be taken out. A new runtime that records its whole count but not its own fails the +row. A time that moves while its count holds names waits. Every row records its counts; only +these are gated on them. A row whose GPU time varies on one card itself (`CARD_VARIANCE`: the XTX's `sampling` and `constant_managed`) is named on the leg's line as the card's variance and fails nothing. A row over it fails its leg unless a ruling, made after the work on that row, gave it a ceiling on that GPU (`HARNESS_CEILINGS` in `scripts/matrix/results.py`); a ceiling @@ -387,7 +391,7 @@ last GPU end, is recorded as `time harness-gpu-/` where the row ha judges a row on it as above, and shows it beside the times of a row it does not judge on it; it is parked for the `time` rule. `run` and `show` print, under each leg's line, every harness row's time and GPU time on both runtimes and the ratio of the times, and where the leg counted them, its instructions per -run and their ratio. +run (with the new runtime's own) and their ratios. The budget goes with the old runtime. The old runtime's translations do not move either. The golden hash table compiles through @@ -402,7 +406,9 @@ may open at `perf_event_paranoid` 2. On a hybrid x86 CPU it sums the event over unit, since the generic event counts on one of them only. `metal2vulkan_devtools::instructions::ProcessInstructions` measures the harness's: one counter per core type opened with `inherit` before the harness makes a device, so it counts every thread the -runtimes and their drivers start. Off Linux neither opens, so the Windows leg records no +runtimes and their drivers start. `metal2vulkan_devtools::instructions::ThreadInstructions` +measures the runtime's own: one counter per core type on each thread it names, opened by its OS +id before a row's timed runs. Off Linux none opens, so the Windows leg records no `instructions`; a node that refuses them records none either. The rules and the sizing of the matrix's jobs have their own tests, which need no cluster: diff --git a/scripts/matrix/instructions.tsv b/scripts/matrix/instructions.tsv index 705c1319a..ed4a8d51a 100644 --- a/scripts/matrix/instructions.tsv +++ b/scripts/matrix/instructions.tsv @@ -1,8 +1,9 @@ # The new runtime's user-space instructions per timed run that each frame and burst row -# (results.WALL_ROWS) is held to by the instructions gate (results.STORED_INSTRUCTIONS): the whole process's count, the p50 over a -# row's timed runs. One count per row in the `all` column where every leg's count lies within 3% +# (results.WALL_ROWS) is held to by the instructions gate (results.STORED_INSTRUCTIONS): its own +# threads' and the harness's thread's count (`own_per_run`, the threads a driver starts for itself +# left out), the p50 over a row's timed runs. One count per row in the `all` column where every leg's count lies within 3% # of the others', else one per driver family (a GPU leg id's vendor). A count only ratchets down: # a landing that lowers it by more than 1% stores the lower one, and nothing raises it without a -# ruling. A row with no count here is gated against the old runtime's count alone, and its line -# names it, until the counts of a matrix run are stored. +# ruling. A row with no count here is gated against the old runtime's whole count alone, and its +# line names it, until the counts of a matrix run are stored. row all diff --git a/scripts/matrix/results.py b/scripts/matrix/results.py index 5c62a06ab..6bf9d4fb2 100644 --- a/scripts/matrix/results.py +++ b/scripts/matrix/results.py @@ -253,7 +253,8 @@ def leg_problems(leg, records, base): problems.append(f"metric {key}: {was} -> {value}") for key, value in sorted(records["instructions"].items()): was = base["instructions"].get(key) - if was is not None and not key.startswith(PARKED_RECORDS) and value > was * (1 + INSTRUCTIONS_BAND): + if (was is not None and not key.startswith(PARKED_RECORDS + ("harness-",)) + and value > was * (1 + INSTRUCTIONS_BAND)): problems.append(f"instructions {key}: {was} -> {value} (+{(value / was - 1) * 100:.1f}%)") return problems @@ -350,14 +351,22 @@ def gpu_beside(times, runtime, row): #: The instructions gate of the frame and burst rows (WALL_ROWS), beside the judgement of their -#: time: on Linux, the whole process's user-space instructions per timed run (`instructions -#: harness-//per_run`, the p50 over its timed runs, every runtime and driver thread -#: counted). The new runtime's count is at most the old's, and at most HARNESS_BUDGET times its -#: stored count (STORED_INSTRUCTIONS), with no floor and no ceiling: the count repeats to well -#: under 1% (0.16 to 0.27% across processes on the 2080's node). A time that moves while the -#: count does not names waits. A leg that records no instructions (the kernel refused the -#: counter, or Windows) has no gate. Every row records its count; only these are gated on it. +#: time, on Linux's user-space instructions per timed run, each the p50 over the row's timed runs. +#: The harness records the whole process's (`instructions harness-//per_run`), and +#: where the runtime names the threads it started (the new runtime's `Gauges::threads`), the count +#: of those and the harness's own thread (`.../own_per_run`) and the rest, the threads a driver +#: started for itself (`.../others_per_run`). A driver's threads swing by millions of instructions +#: per run between processes (NVIDIA's on burst_160: 0 to 25 million), the runtime's own do not. +#: The gate is on the runtime's own: EXACT, the new runtime's own count at most HARNESS_BUDGET +#: times its stored count (STORED_INSTRUCTIONS), which ratchets down; and LENIENT, printed on +#: every row, the new runtime's own count at most the old's whole count, the old runtime naming +#: none of its threads, so its driver's share cannot be taken out. The base comparison of +#: leg_problems skips the harness's counts: this gate judges them. A leg that records no +#: instructions (the kernel refused the counter, or Windows) has no gate. Every row records its +#: counts; only these are gated on them. INSTRUCTIONS_PER_RUN = "/per_run" +#: The new runtime's own threads' count of a row, and the rest of the process's. +OWN_PER_RUN, OTHERS_PER_RUN = "/own_per_run", "/others_per_run" def read_counts(text): @@ -378,10 +387,11 @@ def read_counts(text): return counts -#: The new runtime's instructions per timed run that each WALL_ROWS row is held to -#: (`instructions.tsv`, beside this file): one count per row where the legs' counts lie within 3% -#: of each other, else one per driver family. A count only ratchets down: a landing that lowers a -#: row's count by more than 1% stores the lower one, and nothing raises it without a ruling. +#: The new runtime's own threads' instructions per timed run (OWN_PER_RUN) that each WALL_ROWS +#: row is held to (`instructions.tsv`, beside this file): one count per row where the legs' counts +#: lie within 3% of each other, else one per driver family. A count only ratchets down: a landing +#: that lowers a row's count by more than 1% stores the lower one, and nothing raises it without a +#: ruling. STORED_INSTRUCTIONS = read_counts((Path(__file__).resolve().parent / "instructions.tsv").read_text()) @@ -396,24 +406,33 @@ def stored_count(leg_id, row): def instruction_gate(leg_id, row, records): """ROW's instructions gate on LEG_ID from the leg's RECORDS: (problems, parked), both empty - where ROW is not a WALL_ROWS row or a runtime recorded no count. A count over the old - runtime's, or past HARNESS_BUDGET times the stored count, is a problem; one more than - INSTRUCTIONS_BAND under the stored count, or a row with none stored, is named.""" - counted = [records["instructions"].get(f"harness-{runtime}/{row}{INSTRUCTIONS_PER_RUN}") - for runtime in ("new", "old")] - if not row.startswith(WALL_ROWS) or not all(counted): + where ROW is not a WALL_ROWS row or a runtime recorded no whole count. EXACT: the new runtime's + own count past HARNESS_BUDGET times the stored count is a problem; one more than + INSTRUCTIONS_BAND under it, or a row with none stored, is named. LENIENT, named on every row: + the new runtime's own count over the old's whole count is a problem. A new runtime that + recorded its whole count but not its own is a problem: the gate could not run.""" + counted = records["instructions"] + new, old = (counted.get(f"harness-{runtime}/{row}{INSTRUCTIONS_PER_RUN}") for runtime in ("new", "old")) + if not row.startswith(WALL_ROWS) or not new or not old: return [], [] - (new, old), stored = counted, stored_count(leg_id, row) - line = (f"harness budget {row}: instructions new {new} per run over old {old} is {new / old:.3f}, " - + (f"stored {stored}" if stored else "none stored")) - if new > old: - return [f"{line}: new over old"], [] - if stored and new > HARNESS_BUDGET * stored: - return [f"{line}: past {HARNESS_BUDGET} times the stored count"], [] - if stored and new < (1 - INSTRUCTIONS_BAND) * stored: - return [], [f"{line}: more than {INSTRUCTIONS_BAND:.0%} under the stored count, which ratchets " - "down to it"] - return [], [] if stored else [line] + own, others = (counted.get(f"harness-new/{row}{part}") for part in (OWN_PER_RUN, OTHERS_PER_RUN)) + if own is None: + return [f"harness budget {row}: instructions new {new} per run, but no count of its own threads"], [] + problems, parked = [], [] + stored = stored_count(leg_id, row) + exact = f"harness budget {row}: EXACT instructions new own {own} per run, " + ( + f"stored {stored}, is {own / stored:.3f}" if stored else "none stored") + if stored and own > HARNESS_BUDGET * stored: + problems.append(f"{exact}: past {HARNESS_BUDGET} times the stored count") + elif stored and own < (1 - INSTRUCTIONS_BAND) * stored: + parked.append(f"{exact}: more than {INSTRUCTIONS_BAND:.0%} under the stored count, which ratchets " + "down to it") + elif not stored: + parked.append(exact) + lenient = (f"harness budget {row}: LENIENT instructions new own {own} per run over old whole {old} is " + f"{own / old:.3f}; new others {others}, old's driver threads not separable") + (problems if own > old else parked).append(lenient + (": new own over old whole" if own > old else "")) + return problems, parked #: The harness rows over HARNESS_BUDGET that a ruling gave a ceiling, per GPU leg, each a ratio of @@ -705,8 +724,9 @@ def harness_budget(leg_id, leg): def harness_rows(records): """Every harness row timed on either runtime in a leg's RECORDS, one line each: its time, its - GPU time (HARNESS_GPU) and, where recorded, its instructions per run, on the new runtime and on - the old, `-` where it has none, and new over old of the times and of the instructions.""" + GPU time (HARNESS_GPU) and, where recorded, its instructions per run (with its own threads' + where the runtime names them), on the new runtime and on the old, `-` where it has none, and + new over old of the times and of the instructions (and of new's own over old's whole).""" times, counted = records["time"], records["instructions"] rows = sorted({key.split("/", 1)[1] for key in times if key.startswith((HARNESS_NEW, HARNESS_OLD))}) lines = [] @@ -719,6 +739,9 @@ def harness_rows(records): instructions = counted.get(f"harness-{runtime}/{row}{INSTRUCTIONS_PER_RUN}") if instructions is not None: cell += f", {instructions} instructions" + own = counted.get(f"harness-{runtime}/{row}{OWN_PER_RUN}") + if own is not None: + cell += f" ({own} own)" cells.append(cell) new, old = times.get(HARNESS_NEW + row), times.get(HARNESS_OLD + row) ratio = f"{new / old:.3f}" if new is not None and old else "-" @@ -726,6 +749,9 @@ def harness_rows(records): new_i, old_i = (counted.get(f"harness-{runtime}/{row}{INSTRUCTIONS_PER_RUN}") for runtime in ("new", "old")) if new_i is not None and old_i: line += f", instructions {new_i / old_i:.3f}" + own = counted.get(f"harness-new/{row}{OWN_PER_RUN}") + if own is not None: + line += f", own over old {own / old_i:.3f}" lines.append(line) return lines diff --git a/scripts/matrix/test_results.py b/scripts/matrix/test_results.py index 8f885d590..ae3722e47 100644 --- a/scripts/matrix/test_results.py +++ b/scripts/matrix/test_results.py @@ -113,11 +113,13 @@ class RuleTests(unittest.TestCase): self.assertEqual(self.problems(recs(metric={"a/barriers": 5, "a/passes": 2}), base), ["metric a/barriers: 4 -> 5"]) - def test_the_old_runtime_s_instructions_are_not_compared_to_its_base(self): - base = recs(instructions={"harness-old/frame/per_run": 100000, "harness-new/frame/per_run": 50000}) - now = recs(instructions={"harness-old/frame/per_run": 105000, "harness-new/frame/per_run": 51000}) - self.assertEqual(self.problems(now, base), - ["instructions harness-new/frame/per_run: 50000 -> 51000 (+2.0%)"]) + def test_the_harness_s_instructions_are_not_compared_to_the_base(self): + # The instructions gate judges them (harness_budget); a driver's threads swing the whole count. + base = recs(instructions={"harness-old/frame/per_run": 100000, "harness-new/frame/per_run": 50000, + "harness-new/frame/own_per_run": 30000, "a/per_draw": 10000}) + now = recs(instructions={"harness-old/frame/per_run": 105000, "harness-new/frame/per_run": 71000, + "harness-new/frame/own_per_run": 31000, "a/per_draw": 10200}) + self.assertEqual(self.problems(now, base), ["instructions a/per_draw: 10000 -> 10200 (+2.0%)"]) def test_instructions_fail_past_one_percent(self): base = recs(instructions={"a/per_draw": 10000}) @@ -610,45 +612,60 @@ class HarnessBudgetTests(unittest.TestCase): "harness-new/create_64MiB/first_take": 50.0, "harness-old/create_64MiB/first_take": 40.0, "harness-old/sampling": 50.0, "harness-first/create_64MiB/first_take/2/new": 51.0, "loop/gpu": 1000.0} - counted = {"harness-new/frame/per_run": 61253, "harness-old/frame/per_run": 149185} + counted = {"harness-new/frame/per_run": 61253, "harness-old/frame/per_run": 149185, + "harness-new/frame/own_per_run": 40001, "harness-new/frame/others_per_run": 21252} self.assertEqual(results.harness_rows(recs(time=times, instructions=counted)), [ "create_64MiB/first_take new 50.0 us, GPU p50 - us | old 40.0 us, " "GPU p50 - us | 1.250", - "frame new 120.0 us, GPU p50 81.0 us, 61253 instructions | " - "old 100.0 us, GPU p50 80.2 us, 149185 instructions | 1.200, instructions 0.411", + "frame new 120.0 us, GPU p50 81.0 us, 61253 instructions " + "(40001 own) | old 100.0 us, GPU p50 80.2 us, 149185 instructions | 1.200, " + "instructions 0.411, own over old 0.268", "sampling new - us, GPU p50 - us | old 50.0 us, " "GPU p50 - us | -"]) def test_the_frame_and_burst_rows_keep_their_time_s_limit_and_pass_the_instructions_gate_too(self): times = {"harness-old/frame": 100.0, "harness-new/frame": 101.0, "harness-old/alu": 100.0, "harness-new/alu": 101.0} - counted = {"harness-new/frame/per_run": 61000, "harness-old/frame/per_run": 149000, + counted = {"harness-new/frame/per_run": 161000, "harness-old/frame/per_run": 149000, + "harness-new/frame/own_per_run": 61000, "harness-new/frame/others_per_run": 100000, "harness-new/alu/per_run": 9000, "harness-old/alu/per_run": 5000} def budget(leg_id, counts, these=times): return results.harness_budget(leg_id, leg_of(recs(time=these, instructions=counts))) - line = "harness budget frame: instructions new {} per run over old 149000 is {}, {}" + def lenient(own, ratio, others=100000, over=""): + return (f"harness budget frame: LENIENT instructions new own {own} per run over old whole 149000 is " + f"{ratio}; new others {others}, old's driver threads not separable{over}") + + exact = "harness budget frame: EXACT instructions new own {} per run, {}" with mock.patch.object(results, "HARNESS_CEILINGS", {}), \ mock.patch.object(results, "HARNESS_FLOORS", {}): # Both within the time's budget. alu, not a frame or burst row, has no gate, its count - # over old's though it is. + # over old's though it is. The whole count, a driver's threads in it, is over old's + # and judges nothing: the runtime's own count is the one gated. with mock.patch.object(results, "STORED_INSTRUCTIONS", {}): - self.assertEqual(budget("10de:1e87", counted), ([], [line.format(61000, "0.409", "none stored")])) + self.assertEqual(budget("10de:1e87", counted), ([], [ + exact.format(61000, "none stored"), lenient(61000, "0.409")])) stored = {"all": {"frame": 60000}} with mock.patch.object(results, "STORED_INSTRUCTIONS", stored): - # Within 1.03 times the stored count: nothing to say. - self.assertEqual(budget("10de:1e87", counted), ([], [])) - over = dict(counted, **{"harness-new/frame/per_run": 61900}) - self.assertEqual(budget("10de:1e87", over)[0], [ - line.format(61900, "0.415", "stored 60000") + ": past 1.03 times the stored count"]) - under = dict(counted, **{"harness-new/frame/per_run": 59000}) + # Within 1.03 times the stored count: only the lenient line. + self.assertEqual(budget("10de:1e87", counted), ([], [lenient(61000, "0.409")])) + over = dict(counted, **{"harness-new/frame/own_per_run": 61900}) + self.assertEqual(budget("10de:1e87", over), ([ + exact.format(61900, "stored 60000, is 1.032") + ": past 1.03 times the stored count"], + [lenient(61900, "0.415")])) + under = dict(counted, **{"harness-new/frame/own_per_run": 59000}) self.assertEqual(budget("10de:1e87", under), ([], [ - line.format(59000, "0.396", "stored 60000") + ": more than 1% under the stored count, " - "which ratchets down to it"])) - past_old = dict(counted, **{"harness-new/frame/per_run": 150000}) + exact.format(59000, "stored 60000, is 0.983") + ": more than 1% under the stored count, " + "which ratchets down to it", lenient(59000, "0.396")])) + past_old = dict(counted, **{"harness-new/frame/own_per_run": 150000}) self.assertEqual(budget("10de:1e87", past_old)[0], [ - line.format(150000, "1.007", "stored 60000") + ": new over old"]) + exact.format(150000, "stored 60000, is 2.500") + ": past 1.03 times the stored count", + lenient(150000, "1.007", over=": new own over old whole")]) + # A whole count with no count of the runtime's own threads: the gate could not run. + no_own = {key: value for key, value in counted.items() if "own" not in key and "others" not in key} + self.assertEqual(budget("10de:1e87", no_own)[0], [ + "harness budget frame: instructions new 161000 per run, but no count of its own threads"]) # A time past its limit still fails, its count within the gate though it is. slow = dict(times, **{"harness-new/frame": 120.0}) self.assertEqual(budget("10de:1e87", counted, slow)[0], [