From eaa4a4b89170f7ccc377c791ce91c0691a5fd22b Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 26 Oct 2026 10:06:03 +0200 Subject: [PATCH] Count the driver's pipeline makings and the shader cache's directory in time The steps this packet landed as, in order: - Re-pin the runtime sources at the landing tip Content: the tree of `development` at cc1852dadd, unchanged. --- .../src/device/compiles.rs | 182 ++++++++++++++- crates/metal2vulkan-runtime/src/device/mod.rs | 7 + .../src/shader_cache/mod.rs | 88 +++++-- .../src/shader_cache/store.rs | 145 +++++++++--- .../src/tests/creation_split.rs | 216 ++++++++++++++++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 3 + .../src/tests/shader_cache_time.rs | 191 ++++++++++++++++ .../metal2vulkan-runtime/src/work_counts.rs | 79 +++++++ .../runtime-sources.sha256 | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 12 + 10 files changed, 868 insertions(+), 57 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/creation_split.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/shader_cache_time.rs diff --git a/crates/metal2vulkan-runtime/src/device/compiles.rs b/crates/metal2vulkan-runtime/src/device/compiles.rs index cdebcddae..85514a24b 100644 --- a/crates/metal2vulkan-runtime/src/device/compiles.rs +++ b/crates/metal2vulkan-runtime/src/device/compiles.rs @@ -37,6 +37,13 @@ //! (`std::thread::scope`). Each device counts the calls in progress here, and in builds with //! debug assertions the runtime's last hold of the device ([`unregister`], in the teardown just //! before `vkDestroyDevice`) checks that none is. +//! - **The time in the driver is counted.** Each call's nanoseconds inside the driver's entry +//! point are added to its device's record, graphics and compute apart ([`driver_nanos`], +//! `WorkCounts::render_pipeline_create_nanos` and `compute_pipeline_create_nanos`). The clock is +//! read on whichever thread makes the call, just before and just after the driver's one call, so +//! a call relayed to a thread of the runtime's is counted there and none is dropped; the relay's +//! own thread start and join, which the asking thread pays, lie outside the window and are the +//! runtime's. //! - Elsewhere than macOS there is no class: every call is made on the asking thread. //! //! The device's creation (`create.rs`) runs `vkCreateDevice` through [`at_user_initiated`] too, @@ -48,11 +55,11 @@ use crate::{DebugMessage, MessageSink}; use ash::vk; use std::cell::RefCell; use std::ffi::{c_void, CStr}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, PoisonError, RwLock}; /// A device whose pipeline makings come here: its driver's entry points, the runtime's holds of -/// it, and its calls in progress. +/// it, its calls in progress, and the time they spent in the driver. struct Driver { device: vk::Device, /// The runtime's devices over it: adopting one `VkDevice` twice holds it twice. @@ -60,6 +67,17 @@ struct Driver { graphics: vk::PFN_vkCreateGraphicsPipelines, compute: vk::PFN_vkCreateComputePipelines, in_progress: Arc, + nanos: Arc, +} + +/// The time a routed device's pipeline makings spent inside its driver's entry points, by call +/// ([`driver_nanos`], `WorkCounts::render_pipeline_create_nanos` and +/// `compute_pipeline_create_nanos`). One record per `VkDevice`, so a `VkDevice` the runtime holds +/// twice counts each making in both its devices' figures. +#[derive(Default)] +struct Nanos { + graphics: AtomicU64, + compute: AtomicU64, } /// Every device routed here and not yet let go ([`route`], [`unregister`]). @@ -95,6 +113,7 @@ pub(super) unsafe fn route(device: ash::Device) -> ash::Device { graphics: functions.create_graphics_pipelines, compute: functions.create_compute_pipelines, in_progress: Arc::default(), + nanos: Arc::default(), }), } } @@ -142,17 +161,31 @@ pub(super) fn unregister(device: vk::Device) { } } +/// Nanoseconds `device`'s pipeline makings spent inside its driver's entry points so far, graphics +/// then compute; zeroes for a device not routed (`WorkCounts::render_pipeline_create_nanos`). +pub(super) fn driver_nanos(device: vk::Device) -> (u64, u64) { + let drivers = DRIVERS.read().unwrap_or_else(PoisonError::into_inner); + match drivers.iter().find(|driver| driver.device == device) { + Some(driver) => ( + driver.nanos.graphics.load(Ordering::Relaxed), + driver.nanos.compute.load(Ordering::Relaxed), + ), + None => (0, 0), + } +} + /// One call in progress on a routed device, counted until it returns. struct InProgress(Arc); impl InProgress { - /// `device`'s driver entry points, with this call counted in progress; none for a device - /// not routed. + /// `device`'s driver entry points and its record of their time, with this call counted in + /// progress; none for a device not routed. fn of( device: vk::Device, ) -> Option<( vk::PFN_vkCreateGraphicsPipelines, vk::PFN_vkCreateComputePipelines, + Arc, InProgress, )> { let drivers = DRIVERS.read().unwrap_or_else(PoisonError::into_inner); @@ -161,11 +194,24 @@ impl InProgress { Some(( driver.graphics, driver.compute, + Arc::clone(&driver.nanos), InProgress(Arc::clone(&driver.in_progress)), )) } } +/// `call`, the driver's one pipeline-making call, with the nanoseconds it took added to `counter`: +/// the clock is read on whichever thread makes the call, just before and just after it, so the +/// whole of the driver's work is in the window and nothing else of the runtime's is. The pair +/// costs 27 ns on an M3 Max, against a driver's hundred microseconds and more. +fn counting(counter: &AtomicU64, call: impl FnOnce() -> R) -> R { + let entered = crate::gpu_time::host_nanos(); + let made = call(); + let taken = crate::gpu_time::host_nanos().saturating_sub(entered); + counter.fetch_add(taken, Ordering::Relaxed); + made +} + impl Drop for InProgress { fn drop(&mut self) { self.0.fetch_sub(1, Ordering::SeqCst); @@ -292,7 +338,7 @@ unsafe extern "system" fn create_graphics_pipelines( p_allocator: *const vk::AllocationCallbacks<'_>, p_pipelines: *mut vk::Pipeline, ) -> vk::Result { - let Some((driver, _, _in_progress)) = InProgress::of(device) else { + let Some((driver, _, nanos, _in_progress)) = InProgress::of(device) else { return vk::Result::ERROR_UNKNOWN; }; let asked = Sent::new(( @@ -305,7 +351,9 @@ unsafe extern "system" fn create_graphics_pipelines( at_user_initiated(move || { let (cache, count, infos, allocator, pipelines) = asked.into_inner(); // SAFETY: the caller's arguments, alive and untouched while it waits for this call. - let made = unsafe { driver(device, cache, count, infos, allocator, pipelines) }; + let made = counting(&nanos.graphics, || unsafe { + driver(device, cache, count, infos, allocator, pipelines) + }); exit_guard::called(Call::CreateGraphicsPipelines); made }) @@ -320,7 +368,7 @@ unsafe extern "system" fn create_compute_pipelines( p_allocator: *const vk::AllocationCallbacks<'_>, p_pipelines: *mut vk::Pipeline, ) -> vk::Result { - let Some((_, driver, _in_progress)) = InProgress::of(device) else { + let Some((_, driver, nanos, _in_progress)) = InProgress::of(device) else { return vk::Result::ERROR_UNKNOWN; }; let asked = Sent::new(( @@ -333,7 +381,9 @@ unsafe extern "system" fn create_compute_pipelines( at_user_initiated(move || { let (cache, count, infos, allocator, pipelines) = asked.into_inner(); // SAFETY: the caller's arguments, alive and untouched while it waits for this call. - let made = unsafe { driver(device, cache, count, infos, allocator, pipelines) }; + let made = counting(&nanos.compute, || unsafe { + driver(device, cache, count, infos, allocator, pipelines) + }); exit_guard::called(Call::CreateComputePipelines); made }) @@ -434,6 +484,122 @@ mod tests { .expect("the warning of a dynamic restart") } + /// How long a slow driver's pipeline making spends in the driver, in nanoseconds: a sleep, so + /// the call takes at least this however loaded the host is. + const SPENT: u64 = 2_000_000; + + /// The makings of each kind [`a_making_s_time_in_the_driver_is_counted_by_the_call_it_made`] + /// asks for. + const MAKINGS: u64 = 3; + + /// Spend [`SPENT`] nanoseconds, as a driver's compile does. + fn spend() { + std::thread::sleep(std::time::Duration::from_nanos(SPENT)); + } + + /// A driver's `vkCreateGraphicsPipelines` that spends [`SPENT`] nanoseconds and makes nothing. + unsafe extern "system" fn slow_graphics( + _: vk::Device, + _: vk::PipelineCache, + _: u32, + _: *const vk::GraphicsPipelineCreateInfo<'_>, + _: *const vk::AllocationCallbacks<'_>, + _: *mut vk::Pipeline, + ) -> vk::Result { + spend(); + vk::Result::SUCCESS + } + + /// A driver's `vkCreateComputePipelines` that spends [`SPENT`] nanoseconds and makes nothing. + unsafe extern "system" fn slow_compute( + _: vk::Device, + _: vk::PipelineCache, + _: u32, + _: *const vk::ComputePipelineCreateInfo<'_>, + _: *const vk::AllocationCallbacks<'_>, + _: *mut vk::Pipeline, + ) -> vk::Result { + spend(); + vk::Result::SUCCESS + } + + /// A device of handle `handle` whose driver has both slow makings, routed. + fn routed_slow(handle: u64) -> ash::Device { + let graphics: vk::PFN_vkCreateGraphicsPipelines = slow_graphics; + let compute: vk::PFN_vkCreateComputePipelines = slow_compute; + // SAFETY: a table of the two slow makings and ash's stubs; no other entry point is called. + let driver = unsafe { + ash::Device::load_with( + |name| { + if name == c"vkCreateGraphicsPipelines" { + graphics as *const c_void + } else if name == c"vkCreateComputePipelines" { + compute as *const c_void + } else { + std::ptr::null() + } + }, + vk::Device::from_raw(handle), + ) + }; + // SAFETY: its functions are the driver's. + unsafe { route(driver) } + } + + /// The time a pipeline making spends inside the driver is counted on whichever thread makes + /// the call, and by the call it made: makings of one kind leave the other kind's figure + /// untouched, so a render-heavy run and a dispatch-heavy one are told apart. Each making here + /// sleeps [`SPENT`] nanoseconds in the driver, so the floor holds however loaded the host is; + /// a door that timed nothing would read zero for both. + #[test] + fn a_making_s_time_in_the_driver_is_counted_by_the_call_it_made() { + let device = routed_slow(0x6d32_7600_0010); + let handle = device.handle(); + assert_eq!( + super::driver_nanos(handle), + (0, 0), + "a device just routed has made nothing" + ); + let graphics_info = vk::GraphicsPipelineCreateInfo::default(); + for _ in 0..MAKINGS { + // SAFETY: the routed device's making is the slow driver's, which reads no argument. + let _ = unsafe { + device.create_graphics_pipelines(vk::PipelineCache::null(), &[graphics_info], None) + }; + } + let (graphics, compute) = super::driver_nanos(handle); + assert!( + graphics >= MAKINGS * SPENT, + "{MAKINGS} graphics makings of {SPENT} ns each read {graphics} ns" + ); + assert_eq!( + compute, 0, + "a graphics making is not counted as a compute one" + ); + let compute_info = vk::ComputePipelineCreateInfo::default(); + for _ in 0..MAKINGS { + // SAFETY: as above. + let _ = unsafe { + device.create_compute_pipelines(vk::PipelineCache::null(), &[compute_info], None) + }; + } + let (graphics_after, compute_after) = super::driver_nanos(handle); + assert!( + compute_after >= MAKINGS * SPENT, + "{MAKINGS} compute makings of {SPENT} ns each read {compute_after} ns" + ); + assert_eq!( + graphics_after, graphics, + "a compute making is not counted as a graphics one" + ); + unregister(handle); + assert_eq!( + super::driver_nanos(handle), + (0, 0), + "the record went with the device's last hold" + ); + } + /// A device of handle `handle` whose driver has only `driver` ([`told`] or [`reports`]), /// routed. fn routed(handle: u64, driver: vk::PFN_vkCreateGraphicsPipelines) -> ash::Device { diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index d670bea70..c939d8b6f 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -540,6 +540,13 @@ impl DeviceShared { self.functions.get() } + /// Nanoseconds the device's pipeline makings spent inside its driver, graphics then compute + /// (`compiles.rs`, `WorkCounts::render_pipeline_create_nanos` and + /// `compute_pipeline_create_nanos`). + pub(super) fn pipeline_create_nanos(&self) -> (u64, u64) { + compiles::driver_nanos(self.vk().handle()) + } + /// How much GPU work of the program's own the device has been given /// ([`gpu_work`](Self::gpu_work) field): the count a texture's host shadow is read against /// (`texture/host_shadow.rs`). diff --git a/crates/metal2vulkan-runtime/src/shader_cache/mod.rs b/crates/metal2vulkan-runtime/src/shader_cache/mod.rs index af7d08f60..fe3cbb99c 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/mod.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/mod.rs @@ -70,7 +70,7 @@ use sha2::{Digest, Sha256}; use std::path::{Path, PathBuf}; use std::sync::atomic::Ordering; use std::sync::Arc; -use store::{count, entry_name, Directory, Lookup, Store}; +use store::{count, entry_name, Directory, Looked, Lookup, Store}; use worker::{Asked, Worker}; /// The default cap of a cache directory, in bytes: 25 GiB. @@ -152,6 +152,19 @@ pub(crate) fn found_in_cache( Some(whole.flags.contains(hit) || every_stage) } +/// What a device's shader cache directory cost it ([`ShaderCache::directory_time`]), which +/// `WorkCounts` reports and [`ShaderCacheStatistics`] does not. Not part of the API. +pub(super) struct DirectoryTime { + /// `WorkCounts::shader_cache_read_nanos`. + pub(super) read_nanos: u64, + /// `WorkCounts::shader_cache_write_nanos`. + pub(super) write_nanos: u64, + /// `WorkCounts::shader_cache_off_thread_nanos`. + pub(super) off_thread_nanos: u64, + /// `WorkCounts::shader_cache_writes_on_thread`. + pub(super) writes_on_thread: u64, +} + /// A device's shader cache counts since it was made ([`Device::shader_cache_statistics`]). No /// Metal counterpart. #[non_exhaustive] @@ -161,6 +174,28 @@ pub struct ShaderCacheStatistics { pub hits: u64, /// Artifact lookups that found nothing usable, for any reason; each was compiled. pub misses: u64, + /// Of [`hits`](Self::hits), those of a translated function: a creation asks for one per stage + /// it compiles. The three kinds are counted apart because only the kind says which artifact a + /// lookup decoded, and they differ in size and in how often a creation stores one -- a + /// creation that makes one answered lookup and one unanswered one cannot be read off the + /// whole counts. + pub function_hits: u64, + /// Of [`misses`](Self::misses), those of a translated function: each one a function + /// translated. + pub function_misses: u64, + /// Of [`hits`](Self::hits), those of a compiled compute pipeline: a compute or tile state's + /// whole artifact, which such a creation stores on every miss + /// (`pipeline/sources.rs`'s `kernel`). + pub compute_pipeline_hits: u64, + /// Of [`misses`](Self::misses), those of a compiled compute pipeline. + pub compute_pipeline_misses: u64, + /// Of [`hits`](Self::hits), those of a compiled render pipeline: a render state's whole + /// artifact, which such a creation stores only where linking a variant again would translate + /// (`pipeline/sources.rs`'s `linked_render`), so a warm render creation decodes none of + /// these. + pub render_pipeline_hits: u64, + /// Of [`misses`](Self::misses), those of a compiled render pipeline. + pub render_pipeline_misses: u64, /// Entries found under the right name whose contents failed the checks, each removed. pub rejected: u64, /// Entries that could not be read. @@ -467,7 +502,7 @@ impl ShaderCache { compile: &metal2vulkan::device::Device, key: &FunctionCompileKey, ) -> Option<(CompiledFunction, u64)> { - self.load(EntryKind::Function, key.digest(), compile, |bytes| { + self.load(Looked::Function, key.digest(), compile, |bytes| { CompiledFunction::from_bytes_for_key(bytes, key, compile) }) } @@ -475,8 +510,9 @@ impl ShaderCache { /// Whether the directory holds the function of `key` for `compile`'s profile: its file is in /// place, or its write is queued for the cache thread (`worker.rs`), whose rename has not /// happened yet. A question about the directory, so it reads no contents, decodes nothing and - /// counts in no statistic: a hit here is not a lookup answered, and a miss is not a - /// translation. + /// counts in no hit or miss: a hit here is not a lookup answered, and a miss is not a + /// translation. Its one `stat` is counted in the directory's read time + /// (`WorkCounts::shader_cache_read_nanos`). pub(super) fn holds_function( &self, compile: &metal2vulkan::device::Device, @@ -512,7 +548,7 @@ impl ShaderCache { compile: &metal2vulkan::device::Device, key: &PipelineKey, ) -> Option<(ComputePipeline, u64)> { - self.load(EntryKind::ComputePipeline, key.digest(), compile, |bytes| { + self.load(Looked::ComputePipeline, key.digest(), compile, |bytes| { ComputePipeline::from_bytes_for_key(bytes, key, compile) }) } @@ -538,7 +574,7 @@ impl ShaderCache { compile: &metal2vulkan::device::Device, key: &PipelineKey, ) -> Option<(RenderPipeline, u64)> { - self.load(EntryKind::RenderPipeline, key.digest(), compile, |bytes| { + self.load(Looked::RenderPipeline, key.digest(), compile, |bytes| { RenderPipeline::from_bytes_for_key(bytes, key, compile) }) } @@ -557,11 +593,12 @@ impl ShaderCache { ) } - /// The entry of `kind` under `key` for `compile`'s profile, as `decode` accepts it, and its - /// length. A miss when absent, unreadable, or refused (then removed). + /// The entry of `looked`'s kind under `key` for `compile`'s profile, as `decode` accepts it, + /// and its length. A miss when absent, unreadable, or refused (then removed). Counted in the + /// whole hit and miss counts and in `looked`'s own. fn load( &self, - kind: EntryKind, + looked: Looked, key: &Hash256, compile: &metal2vulkan::device::Device, decode: impl FnOnce(&[u8]) -> Result, @@ -569,7 +606,7 @@ impl ShaderCache { let counters = &self.store.counters; let name = entry_name( self.store.directory().build(), - kind, + looked.kind(), key, &compile.profile_fingerprint(), ); @@ -579,11 +616,12 @@ impl ShaderCache { Lookup::Hit(found) => Some(found), Lookup::Absent | Lookup::Unreadable | Lookup::Rejected => None, }; - count(if found.is_some() { - &counters.hits - } else { - &counters.misses - }); + let (whole, by) = match found.is_some() { + true => (&counters.hits, &counters.hits_by), + false => (&counters.misses, &counters.misses_by), + }; + count(whole); + count(&by[looked as usize]); found } @@ -614,6 +652,20 @@ impl ShaderCache { length } + /// What the directory cost this device: its time, the asking threads' apart from the cache + /// thread's, and the entries an asking thread wrote itself + /// (`WorkCounts::shader_cache_read_nanos` and its fellows). + pub(super) fn directory_time(&self) -> DirectoryTime { + let counters = &self.store.counters; + let read = |counter: &std::sync::atomic::AtomicU64| counter.load(Ordering::Relaxed); + DirectoryTime { + read_nanos: read(&counters.read_nanos), + write_nanos: read(&counters.write_nanos), + off_thread_nanos: read(&counters.off_thread_nanos), + writes_on_thread: read(&counters.writes_on_thread), + } + } + /// The counts so far. fn statistics(&self) -> ShaderCacheStatistics { let counters = &self.store.counters; @@ -621,6 +673,12 @@ impl ShaderCache { ShaderCacheStatistics { hits: read(&counters.hits), misses: read(&counters.misses), + function_hits: read(&counters.hits_by[Looked::Function as usize]), + function_misses: read(&counters.misses_by[Looked::Function as usize]), + compute_pipeline_hits: read(&counters.hits_by[Looked::ComputePipeline as usize]), + compute_pipeline_misses: read(&counters.misses_by[Looked::ComputePipeline as usize]), + render_pipeline_hits: read(&counters.hits_by[Looked::RenderPipeline as usize]), + render_pipeline_misses: read(&counters.misses_by[Looked::RenderPipeline as usize]), rejected: read(&counters.rejected), read_failures: read(&counters.read_failures), writes: read(&counters.writes), diff --git a/crates/metal2vulkan-runtime/src/shader_cache/store.rs b/crates/metal2vulkan-runtime/src/shader_cache/store.rs index cb9ddbb42..9bf0d9a94 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/store.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/store.rs @@ -21,6 +21,12 @@ //! bounded, an entry queued is visible to this device's lookups at once, and what is queued when //! the device goes is written before its drop returns (`worker.rs` states the bound and what //! happens at it). A store with no cache thread (the tests') writes on the calling thread. +//! - **The directory's time is counted**, in three figures the asking thread's are apart from the +//! cache thread's: the reads ([`Counters::read_nanos`]), the writes a thread that asked made +//! itself ([`Counters::write_nanos`]), and everything the device's cache thread did here +//! ([`Counters::off_thread_nanos`]). Each is read from the host's clock around the directory's +//! calls alone, so a lookup the write queue answered, and the encode and decode of an entry's +//! bytes, are in none of them (`WorkCounts::shader_cache_read_nanos`). //! - Every scan that finds the directory past its cap removes the least recently used entries, //! by their access time, which a hit refreshes, down to [`LOW_WATER`] of the cap. At device //! creation the scan also removes other builds' directories that nothing used for @@ -193,6 +199,10 @@ enum Found { pub(crate) struct Counters { pub(crate) hits: AtomicU64, pub(crate) misses: AtomicU64, + /// Of `hits`, by the kind of artifact looked up, in [`Looked`]'s order. + pub(crate) hits_by: [AtomicU64; Looked::COUNT], + /// Of `misses`, likewise. + pub(crate) misses_by: [AtomicU64; Looked::COUNT], pub(crate) rejected: AtomicU64, pub(crate) read_failures: AtomicU64, pub(crate) writes: AtomicU64, @@ -217,6 +227,50 @@ pub(crate) struct Counters { /// /// [`ShaderCacheStatistics`]: super::ShaderCacheStatistics pub(crate) driver_caches_shared: AtomicU64, + /// Nanoseconds the directory's reads took on the threads that asked for an artifact: the + /// questions about an entry ([`Store::holds`]), the reads of one ([`Store::load`], + /// [`Store::load_content`]), the refresh of a hit's access time, and the removal of an entry + /// a decoder refused or that is longer than the directory takes. Not in + /// [`ShaderCacheStatistics`]; `WorkCounts::shader_cache_read_nanos` reports it. + /// + /// [`ShaderCacheStatistics`]: super::ShaderCacheStatistics + pub(crate) read_nanos: AtomicU64, + /// Nanoseconds the directory's writes took on the threads that asked for an artifact: the + /// `mkdir`, the temporary file, its write and flush and the `rename` of each entry a thread + /// wrote itself because the queue was at a bound or the store has no cache thread + /// (`writes_on_thread`). Reported as `WorkCounts::shader_cache_write_nanos`. + pub(crate) write_nanos: AtomicU64, + /// Nanoseconds the device's cache thread spent in the directory: the writes it took from the + /// queue (`writes_queued`), and the scans and removals that bound the directory. None of it + /// is on a creation's path. Reported as `WorkCounts::shader_cache_off_thread_nanos`. + pub(crate) off_thread_nanos: AtomicU64, +} + +/// The kinds of artifact a lookup asks the directory for, which [`Counters::hits_by`] and +/// [`Counters::misses_by`] count apart: one entry kind each, and the three a pipeline state's +/// creation looks up. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Looked { + /// A translated function ([`EntryKind::Function`]). + Function = 0, + /// A compiled compute pipeline ([`EntryKind::ComputePipeline`]). + ComputePipeline = 1, + /// A compiled render pipeline ([`EntryKind::RenderPipeline`]). + RenderPipeline = 2, +} + +impl Looked { + /// How many there are. + pub(crate) const COUNT: usize = 3; + + /// The kind of entry it is looked up as. + pub(crate) fn kind(self) -> EntryKind { + match self { + Looked::Function => EntryKind::Function, + Looked::ComputePipeline => EntryKind::ComputePipeline, + Looked::RenderPipeline => EntryKind::RenderPipeline, + } + } } impl Counters { @@ -229,6 +283,17 @@ impl Counters { } } +/// Run `f`, the directory's calls and nothing else, with the nanoseconds they took on this thread +/// added to `counter` ([`Counters::read_nanos`] and its two fellows). Two clock reads, 27 ns +/// together on an M3 Max, against the microseconds of the filesystem call they bracket. +fn timed(counter: &AtomicU64, f: impl FnOnce() -> R) -> R { + let entered = crate::gpu_time::host_nanos(); + let done = f(); + let taken = crate::gpu_time::host_nanos().saturating_sub(entered); + counter.fetch_add(taken, Ordering::Relaxed); + done +} + /// Add one to `counter`. pub(super) fn count(counter: &AtomicU64) { counter.fetch_add(1, Ordering::Relaxed); @@ -354,14 +419,16 @@ impl Store { /// Whether the entry named `name` is there to be read: its file is in place and of a length /// this directory takes, or its write is queued for the cache thread, whose rename has not - /// happened yet. Reads no contents and counts nothing -- it is a question about the - /// directory, not a lookup of an entry. + /// happened yet. Reads no contents and counts in no hit or miss -- it is a question about the + /// directory, not a lookup of an entry -- but its `stat` is in [`Counters::read_nanos`]. pub(crate) fn holds(&self, name: &str) -> bool { let path = self.directory.entry_path(name); if self.asked.as_ref().is_some_and(|asked| asked.holds(&path)) { return true; } - fs::metadata(&path).is_ok_and(|metadata| metadata.len() <= self.entry_limit()) + timed(&self.counters.read_nanos, || { + fs::metadata(&path).is_ok_and(|metadata| metadata.len() <= self.entry_limit()) + }) } /// The entry named `name`, as `decode` accepts it. A hit refreshes the entry's access @@ -431,7 +498,7 @@ impl Store { /// a hit from the queue (no file) is counted as one the directory had not written yet. fn accepted(&self, file: Option<&fs::File>) { match file { - Some(file) => touch(file), + Some(file) => timed(&self.counters.read_nanos, || touch(file)), None => count(&self.counters.queued_hits), } } @@ -442,13 +509,14 @@ impl Store { if let Some(asked) = &self.asked { asked.discard(path); } - remove(path); + timed(&self.counters.read_nanos, || remove(path)); count(&self.counters.rejected); } /// Write `bytes` as the record named `name` in the content directory, as /// [`Store::write_soon`] writes an entry: on the cache thread, counted in no statistic but - /// the bytes the directory holds. + /// the bytes the directory holds and, where this thread writes it itself, the time + /// ([`Counters::write_nanos`]). pub(crate) fn write_record_soon(&self, name: &str, bytes: Vec) -> io::Result { self.write_soon_at(self.directory.record_path(name), name, bytes) } @@ -460,28 +528,30 @@ impl Store { if let Some(bytes) = self.asked.as_ref().and_then(|asked| asked.pending(path)) { return Found::Queued(bytes); } - let file = match fs::File::open(path) { - Ok(file) => file, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Found::Absent, - Err(_) => return Found::Failed, - }; - let Ok(length) = file.metadata().map(|metadata| metadata.len()) else { - return Found::Failed; - }; - let limit = self.entry_limit(); - if length > limit { - remove(path); - return Found::Absent; - } - let mut bytes = Vec::with_capacity(usize::try_from(length).unwrap_or(0)); - match (&file).take(limit + 1).read_to_end(&mut bytes) { - Ok(_) if bytes.len() as u64 <= limit => Found::Bytes(bytes, file), - Ok(_) => { + timed(&self.counters.read_nanos, || { + let file = match fs::File::open(path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Found::Absent, + Err(_) => return Found::Failed, + }; + let Ok(length) = file.metadata().map(|metadata| metadata.len()) else { + return Found::Failed; + }; + let limit = self.entry_limit(); + if length > limit { remove(path); - Found::Absent + return Found::Absent; } - Err(_) => Found::Failed, - } + let mut bytes = Vec::with_capacity(usize::try_from(length).unwrap_or(0)); + match (&file).take(limit + 1).read_to_end(&mut bytes) { + Ok(_) if bytes.len() as u64 <= limit => Found::Bytes(bytes, file), + Ok(_) => { + remove(path); + Found::Absent + } + Err(_) => Found::Failed, + } + }) } /// Give `bytes` to the cache thread to write as the entry named `name` (`worker.rs`): the @@ -499,7 +569,9 @@ impl Store { let takeable = length <= QUEUED_BYTES && length <= self.entry_limit(); let Some(asked) = self.asked.as_ref().filter(|_| takeable) else { count(&self.counters.writes_on_thread); - return self.write_at(&path, name, &bytes); + return timed(&self.counters.write_nanos, || { + self.write_at(&path, name, &bytes) + }); }; match asked.queue(Queued::new(path, bytes)) { None => { @@ -508,19 +580,25 @@ impl Store { } Some(write) => { count(&self.counters.writes_on_thread); - self.write_at(&write.path, name, &write.bytes) + timed(&self.counters.write_nanos, || { + self.write_at(&write.path, name, &write.bytes) + }) } } } /// Write the entry at `path` that the cache thread took, counting a failure as the calling - /// thread's would be counted (`ShaderCacheStatistics::write_failures`). + /// thread's would be counted (`ShaderCacheStatistics::write_failures`) and its time as the + /// cache thread's ([`Counters::off_thread_nanos`]). pub(crate) fn write_queued(&self, path: &Path, bytes: &[u8]) { let name = path .file_name() .and_then(|name| name.to_str()) .unwrap_or("entry"); - if self.write_at(path, name, bytes).is_err() { + let written = timed(&self.counters.off_thread_nanos, || { + self.write_at(path, name, bytes) + }); + if written.is_err() { self.write_failed(); } } @@ -565,15 +643,16 @@ impl Store { /// The scan at device creation: remove other builds' directories nothing used for /// [`UNUSED_BUILD`] and stale temporary files, count what remains, and remove the least - /// recently used entries if that is past the cap. Stops early when `stop` is set. + /// recently used entries if that is past the cap. Stops early when `stop` is set. The cache + /// thread's time ([`Counters::off_thread_nanos`]). pub(crate) fn sweep(&self, stop: &AtomicBool) { - self.scan(stop, true); + timed(&self.counters.off_thread_nanos, || self.scan(stop, true)); } /// Bring the directory under its cap: count every build's entries again and remove the /// least recently used past it. Stops early when `stop` is set. pub(crate) fn evict(&self, stop: &AtomicBool) { - self.scan(stop, false); + timed(&self.counters.off_thread_nanos, || self.scan(stop, false)); } /// [`Store::sweep`] (with `unused_builds`) or [`Store::evict`]. diff --git a/crates/metal2vulkan-runtime/src/tests/creation_split.rs b/crates/metal2vulkan-runtime/src/tests/creation_split.rs new file mode 100644 index 000000000..11c9d98c5 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/creation_split.rs @@ -0,0 +1,216 @@ +//! Which part of a pipeline state's creation is the driver's and which is ours +//! (`WorkCounts::render_pipeline_create_nanos`, `compute_pipeline_create_nanos`, +//! `shader_cache_read_nanos`, and `ShaderCacheStatistics`' hits and misses by kind). +//! +//! # Why these are read out here +//! +//! A probe outside the runtime times a creation whole, so it cannot tell the driver's compile from +//! the runtime's own work, and nothing in a `WorkCounts` said how long the driver was in +//! `vkCreateGraphicsPipelines` or how long the shader cache's directory was under a creation. This +//! test is the proof that the figures reach a `WorkCounts` through the device's real door +//! (`device/compiles.rs`) and are attributed to the right field. It asserts no magnitude: what +//! they are on a given device is the device's business. That the two driver calls are counted +//! apart is held host-independently against a fake driver in +//! `device::compiles::tests::a_making_s_time_in_the_driver_is_counted_by_the_call_it_made`. +//! +//! # The attribution it holds +//! +//! - **A creation that makes no `VkPipeline` adds no driver time.** A compute state's creation +//! makes its region's pipeline at the dispatch, not at the creation, so on a device that +//! predicts no region the sweep here makes none -- and both driver figures must stand still +//! while the directory's reads move. The two figures are asserted to move *exactly* where a +//! `VkPipeline` was made, so the leg holds on a device that does predict one as well. +//! - **A render creation's time is the graphics call's.** It moves the render figure and leaves +//! the compute figure where it was. +//! - **Every creation asks the directory**, so the reads move in both legs. A creation of this +//! shape hands every entry to the cache thread, so it writes none itself and the two figures of +//! its own writes stay at zero together. +//! - **The hits and misses by kind add up to the whole hits and misses**, and a cold compute sweep +//! misses a compute pipeline's entry while missing no render pipeline's. Without the split, a +//! creation's one answered lookup and one unanswered one could not be told apart by kind. +//! +//! A device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). The kernel +//! and the function pair are the owned fixtures +//! `validation/fixtures/public/engine/kernel_stage_in.ll` and `ubo_bind_offsets.ll` (`llvm-as`). + +use super::blit_holds::{device, Scratch}; +use super::descriptor_key_once::descriptor; +use crate::{Device, PipelineOptions, ShaderCacheStatistics}; +use metal2vulkan::metal::{AttributeFormat, StepFunction}; +use metal2vulkan::pipeline::{ + ComputePipelineDescriptor, StageInputAttributeDescriptor, StageInputDescriptor, + StageInputLayoutDescriptor, StageSource, +}; +use std::path::Path; + +/// The compute states the sweep makes. +const SWEEP: u32 = 4; + +/// The attributes the fixture's kernel declares and reads. +const READ: [(u32, AttributeFormat, u32); 5] = [ + (0, AttributeFormat::Float4, 0), + (1, AttributeFormat::UInt4, 16), + (2, AttributeFormat::Int, 32), + (3, AttributeFormat::Half2, 36), + (4, AttributeFormat::Int4, 48), +]; + +/// A compute state of the fixture's `[[stage_in]]` kernel, its layout's stride `step` bytes wider +/// than the last, so every row of the sweep is its own descriptor and its own pipeline. +fn compute(device: &Device, library: &crate::Library, step: u32) { + let function = library + .new_function_with_name("stage_in_fetch_wide") + .unwrap(); + let mut made = + ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())); + let mut stage_input = StageInputDescriptor::new(); + for (index, format, offset) in READ { + stage_input + .attributes + .insert(index, StageInputAttributeDescriptor::new(format, offset, 0)); + } + let mut layout = StageInputLayoutDescriptor::new(Some(64 + step)); + layout.step_function = StepFunction::ThreadPositionInGridX; + stage_input.layouts.insert(0, layout); + made.stage_input = Some(stage_input); + device + .new_compute_pipeline_state(&made, &PipelineOptions::default()) + .unwrap(); +} + +/// The hits and misses by kind add up to the whole counts. +fn adds_up(made: &ShaderCacheStatistics) { + assert_eq!( + made.function_hits + made.compute_pipeline_hits + made.render_pipeline_hits, + made.hits, + "the hits by kind are every hit: {made:?}" + ); + assert_eq!( + made.function_misses + made.compute_pipeline_misses + made.render_pipeline_misses, + made.misses, + "the misses by kind are every miss: {made:?}" + ); +} + +/// The time the driver spends making a state's pipelines reaches the state's device's +/// `WorkCounts`, by the call it made, and the shader cache directory's reads reach it beside them. +#[test] +fn a_creation_s_driver_time_and_directory_reads_reach_the_work_counts() { + let scratch = Scratch::new("creation-split"); + let device = device(&scratch.0); + let ll = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/fixtures/public/engine/kernel_stage_in.ll"); + let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap(); + let library = device.new_library_with_compile_library( + metal2vulkan::library::Library::from_air(&bitcode).unwrap(), + ); + let before = device.work_counts(); + for row in 0..SWEEP { + compute(&device, &library, 16 * (row + 1)); + } + let swept = device.work_counts(); + // A compute state's creation makes its region's pipeline at the dispatch unless the device + // predicts one, so the driver figures move exactly where a `VkPipeline` was made. + let made_a_pipeline = swept.variant_pipelines_made > before.variant_pipelines_made + || swept.creation_pipelines_made > before.creation_pipelines_made; + assert_eq!( + swept.compute_pipeline_create_nanos > before.compute_pipeline_create_nanos, + made_a_pipeline, + "the compute figure moves exactly where the sweep made a `VkPipeline`: {} to {} ns, \ + {} to {} variants and {} to {} at creation", + before.compute_pipeline_create_nanos, + swept.compute_pipeline_create_nanos, + before.variant_pipelines_made, + swept.variant_pipelines_made, + before.creation_pipelines_made, + swept.creation_pipelines_made + ); + assert_eq!( + swept.render_pipeline_create_nanos, before.render_pipeline_create_nanos, + "a compute sweep makes no graphics pipeline, so the graphics figure stands still" + ); + assert!( + swept.shader_cache_read_nanos > before.shader_cache_read_nanos, + "a compute sweep asked the directory nothing: {} to {} ns", + before.shader_cache_read_nanos, + swept.shader_cache_read_nanos + ); + let cold = device.shader_cache_statistics(); + adds_up(&cold); + assert!( + cold.function_misses > 0, + "a cold compute sweep must translate its kernel: {cold:?}" + ); + assert_eq!( + (cold.render_pipeline_hits, cold.render_pipeline_misses), + (0, 0), + "a compute sweep looks up no render pipeline: {cold:?}" + ); + assert!( + cold.compute_pipeline_misses > 0, + "a cold compute sweep must miss its own pipelines' entries: {cold:?}" + ); + // A render state of the other fixture: now the graphics call is made, and it is the graphics + // figure that moves. + let render = descriptor(&device); + let state = device + .new_render_pipeline_state(&render, &PipelineOptions::default()) + .unwrap(); + let after = device.work_counts(); + assert!( + after.variant_pipelines_made > swept.variant_pipelines_made + || after.creation_pipelines_made > swept.creation_pipelines_made, + "the render creation must make a `VkPipeline` at all: {after:?}" + ); + assert!( + after.render_pipeline_create_nanos > swept.render_pipeline_create_nanos, + "a render creation's `vkCreateGraphicsPipelines` read no time: {} to {} ns", + swept.render_pipeline_create_nanos, + after.render_pipeline_create_nanos + ); + assert_eq!( + after.compute_pipeline_create_nanos, swept.compute_pipeline_create_nanos, + "a render creation makes no compute pipeline, so the compute figure stands still" + ); + assert!( + after.shader_cache_read_nanos > swept.shader_cache_read_nanos, + "a render creation asked the directory nothing" + ); + assert_eq!( + ( + after.shader_cache_write_nanos > 0, + after.shader_cache_writes_on_thread > 0 + ), + (false, false), + "no creation of this shape writes its own cache entry: the queue takes them all \ + (`tests::shader_cache_off_thread`), and {} ns of writes with {} such writes would \ + disagree", + after.shader_cache_write_nanos, + after.shader_cache_writes_on_thread + ); + let warm = device.shader_cache_statistics(); + adds_up(&warm); + assert!( + warm.function_misses > cold.function_misses, + "the render creation must translate its pair: {warm:?}" + ); + println!( + "creation split: {SWEEP} compute states and one render state; driver {} us graphics and \ + {} us compute; directory {} us read, {} us written by a creating thread ({} entries), \ + {} us on the cache thread; by kind, functions {}/{} hit/missed, compute pipelines {}/{}, \ + render pipelines {}/{}", + after.render_pipeline_create_nanos / 1_000, + after.compute_pipeline_create_nanos / 1_000, + after.shader_cache_read_nanos / 1_000, + after.shader_cache_write_nanos / 1_000, + after.shader_cache_writes_on_thread, + after.shader_cache_off_thread_nanos / 1_000, + warm.function_hits, + warm.function_misses, + warm.compute_pipeline_hits, + warm.compute_pipeline_misses, + warm.render_pipeline_hits, + warm.render_pipeline_misses, + ); + drop(state); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 9e466a998..33a3cb3f0 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -50,6 +50,8 @@ mod cpu_copy_layouts; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod creation_prediction_kinds; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod creation_split; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod deferred_calls; mod degradation; mod degradation_catalogue; @@ -238,6 +240,7 @@ mod shader_cache; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod shader_cache_off_thread; mod shader_cache_queue; +mod shader_cache_time; mod shadow; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod shadow_carried_read; diff --git a/crates/metal2vulkan-runtime/src/tests/shader_cache_time.rs b/crates/metal2vulkan-runtime/src/tests/shader_cache_time.rs new file mode 100644 index 000000000..c134fa01b --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/shader_cache_time.rs @@ -0,0 +1,191 @@ +//! What the shader cache's directory costs in time, and which thread pays it +//! (`WorkCounts::shader_cache_read_nanos`, `shader_cache_write_nanos`, +//! `shader_cache_off_thread_nanos`). +//! +//! # Why the three are apart +//! +//! A pipeline state's creation reaches the directory on its own thread, and the device's cache +//! thread reaches it beside the creation. A single figure over both could not say whether a +//! creation that took 300 microseconds waited for the directory or merely ran next to a thread +//! that did, which is the whole question a consumer asks of these counters. So the reads and the +//! writes a thread that asked made itself are counted apart from everything the cache thread did. +//! +//! # What is in each window +//! +//! The directory's calls alone: the window opens just before the filesystem call and closes just +//! after it, so a lookup the write queue answered, which reads no file, and the encode and decode +//! of an entry's bytes are in none of the three. Each test here holds that by moving one window +//! and asserting the others stand still, so a window drawn around the wrong work fails rather +//! than passing with a larger number. +//! +//! The entries are the driver's pipeline cache frames, as `tests::shader_cache`'s are, and each +//! test owns an empty directory it removes. + +use super::shader_cache::{store, store_with_queue, Scratch, BUILD}; +use crate::shader_cache::store::{entry_name, Lookup, Store}; +use crate::shader_cache::worker::{drain, Asked, QUEUED_WRITES}; +use crate::shader_cache::EntryKind; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +const NO_PROFILE: [u8; 32] = [0; 32]; + +/// How many lookups or writes each leg makes: enough that a window that times the calls reads +/// well past the clock's own resolution, few enough that none of this is a benchmark. +const ROUND: u32 = 32; + +/// The entry name of the made-up key `n`. +fn name(n: u32) -> String { + entry_name(&BUILD, EntryKind::PipelineData, &[n as u8; 32], &NO_PROFILE) +} + +/// The three figures: the reads, the writes a thread that asked made itself, and the cache +/// thread's. +fn nanos(store: &Store) -> (u64, u64, u64) { + let read = |counter: &std::sync::atomic::AtomicU64| counter.load(Ordering::Relaxed); + ( + read(&store.counters.read_nanos), + read(&store.counters.write_nanos), + read(&store.counters.off_thread_nanos), + ) +} + +/// Look the entry named `name` up, taking whatever bytes are there. +fn look(store: &Store, name: &str) -> Lookup> { + store.load(name, |read: &[u8]| Ok::, ()>(read.to_vec())) +} + +/// A lookup that reaches the directory is counted in the reads and in nothing else, whether it +/// finds the entry or not; a write the asking thread makes itself is counted in the writes and in +/// nothing else. The cache thread's figure stays zero throughout: this store has no cache thread, +/// so every call here is the asking thread's. +#[test] +fn a_lookup_is_read_time_and_a_creation_s_own_write_is_write_time() { + let scratch = Scratch::new(); + let store = store(scratch.path(), BUILD, 1 << 30); + assert_eq!(nanos(&store), (0, 0, 0), "a store that has done nothing"); + // Absent entries: the `open` of each is a read and nothing else. + for n in 0..ROUND { + assert_eq!(look(&store, &name(n)), Lookup::Absent); + } + let (absent, written, thread) = nanos(&store); + assert!(absent > 0, "{ROUND} lookups of absent entries read 0 ns"); + assert_eq!( + (written, thread), + (0, 0), + "a lookup is not a write and not the cache thread's" + ); + // Writes on this thread: the store has no cache thread, so each is this thread's four calls. + for n in 0..ROUND { + store.write_soon(&name(n), vec![n as u8; 256]).unwrap(); + } + let (after_writes, written, thread) = nanos(&store); + assert!(written > 0, "{ROUND} writes on this thread took 0 ns"); + assert_eq!( + (after_writes, thread), + (absent, 0), + "a write is not a read and not the cache thread's" + ); + assert_eq!( + store.counters.writes_on_thread.load(Ordering::Relaxed), + u64::from(ROUND), + "every write was this thread's" + ); + // Hits: the `open`, the `read` and the access-time refresh of each are reads. + for n in 0..ROUND { + assert!(matches!(look(&store, &name(n)), Lookup::Hit(_))); + } + let (hits, write_after, thread) = nanos(&store); + assert!(hits > after_writes, "{ROUND} hits read no time"); + assert_eq!( + (write_after, thread), + (written, 0), + "a hit is not a write and not the cache thread's" + ); + // A question about an entry is a `stat`, counted in the reads like any other. + for n in 0..ROUND { + assert!(store.holds(&name(n))); + } + assert!( + nanos(&store).0 > hits, + "{ROUND} questions about entries read no time" + ); +} + +/// A write the device's cache thread took is the cache thread's time, and a write the asking +/// thread made because the queue was at its count bound is the asking thread's: the counter that +/// partitions creations by which one wrote (`writes_on_thread`) and the two time figures agree. +/// A lookup the queue answered reads no directory at all. +#[test] +fn a_queued_write_is_the_cache_thread_s_time_and_a_bounded_one_the_asker_s() { + let scratch = Scratch::new(); + let asked = Arc::new(Asked::new()); + let store = store_with_queue(scratch.path(), BUILD, 1 << 30, Arc::clone(&asked)); + // Filling the queue to its count bound: each of these is queued and written by nobody yet. + for n in 0..QUEUED_WRITES as u32 { + store.write_soon(&name(n), vec![n as u8; 256]).unwrap(); + } + assert_eq!( + nanos(&store), + (0, 0, 0), + "a queued write touches the directory on no thread" + ); + assert_eq!(store.counters.writes_on_thread.load(Ordering::Relaxed), 0); + // A lookup the queue answers reads no file. + assert!(matches!(look(&store, &name(0)), Lookup::Hit(_))); + assert_eq!(store.counters.queued_hits.load(Ordering::Relaxed), 1); + assert_eq!( + nanos(&store), + (0, 0, 0), + "a lookup the queue answered reads no directory" + ); + // One more: the queue is at its bound, so this creation writes its own entry, and pays for it. + let over = name(QUEUED_WRITES as u32); + store.write_soon(&over, vec![9; 256]).unwrap(); + let (read, written, thread) = nanos(&store); + assert_eq!( + store.counters.writes_on_thread.load(Ordering::Relaxed), + 1, + "the creation past the bound wrote its own entry" + ); + assert!(written > 0, "the creation's own write took 0 ns"); + assert_eq!( + (read, thread), + (0, 0), + "the creation's own write is neither a read nor the cache thread's" + ); + // The drain is the cache thread's work: it writes every queued entry on its own time. + drain(&asked, &store); + let (read_after, write_after, thread) = nanos(&store); + assert!(thread > 0, "the drain of the queue took 0 ns"); + assert_eq!( + (read_after, write_after), + (read, written), + "the cache thread's writes are neither reads nor the asking threads' writes" + ); + assert_eq!( + store.counters.writes_queued.load(Ordering::Relaxed), + QUEUED_WRITES as u64 + ); +} + +/// The scan that bounds the directory is the cache thread's time, never a creation's: it runs at +/// device creation and at every eviction, on the thread, and reads the whole directory. +#[test] +fn the_scan_that_bounds_the_directory_is_the_cache_thread_s_time() { + let scratch = Scratch::new(); + let store = store(scratch.path(), BUILD, 1 << 30); + for n in 0..ROUND { + store.write_soon(&name(n), vec![n as u8; 256]).unwrap(); + } + let (read, written, thread) = nanos(&store); + assert_eq!(thread, 0, "nothing has scanned yet"); + store.sweep(&AtomicBool::new(false)); + let (read_after, write_after, thread) = nanos(&store); + assert!(thread > 0, "the sweep of the directory took 0 ns"); + assert_eq!( + (read_after, write_after), + (read, written), + "the scan is neither a lookup's read nor an asking thread's write" + ); +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 3d1f921ff..5ed3fce1b 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -2868,6 +2868,74 @@ pub struct WorkCounts { /// `VkPipeline`s pipeline states' variants made (compute regions and their emulated mesh /// stages, indirect-bindable replays, and draws): none for one a released variant kept. pub variant_pipelines_made: u64, + /// Nanoseconds the runtime's `vkCreateGraphicsPipelines` calls spent inside the driver, from + /// the entry to its return (`device/compiles.rs`, the one door every graphics pipeline the + /// runtime makes on the device goes through): a state's variants and its creation's predicted + /// key (`pipeline/graphics.rs`), the device's own blit, resolve, copy and interleave + /// pipelines, and priming's. A call that makes several pipelines counts once, as the one call + /// it is. + /// + /// The clock is read on whichever thread makes the call, so none is dropped and none counted + /// twice: a program's thread; one of the pipeline pool's, which runs a creation's first piece + /// on the calling thread and the rest on its own (`pipeline/pool.rs`); or, where the asking + /// thread is below the user-initiated class on macOS, a thread of the runtime's that makes the + /// call while the asking thread waits (`device/compiles.rs`). Outside the window, and so the + /// runtime's rather than the driver's: the start and join of that thread, the building of the + /// create infos, and the `VkShaderModule`s, which are a Vulkan call of their own before this + /// one and are shared between creations (`shader_modules_made`, `shader_modules_shared`) -- + /// on MoltenVK 1.4.2 one module is 100-190 us and is not made per creation. + /// + /// A render state's creation that makes no `VkPipeline` adds nothing here, a tile state's + /// among them (its creation makes none at all). A `VkDevice` the runtime adopted twice counts + /// each making in both its devices' figures. + pub render_pipeline_create_nanos: u64, + /// Nanoseconds the runtime's `vkCreateComputePipelines` calls spent inside the driver, read + /// exactly as [`render_pipeline_create_nanos`](Self::render_pipeline_create_nanos) is and over + /// the same one door: a compute state's variants and regions, a tile dispatch's, the device's + /// own blit, fill, mipmap and copy kernels, and priming's. The two are apart because a + /// dispatch-heavy run and a draw-heavy run ask the driver for different work, and one figure + /// over both cannot say which. + pub compute_pipeline_create_nanos: u64, + /// Nanoseconds the shader cache's directory reads took on the threads that asked for an + /// artifact (`shader_cache/store.rs`): the `stat` of each question about an entry + /// (`holds_function`, which a render creation's linking asks once per stage), and the `open`, + /// `stat` and `read` of each entry read -- a translated function, a compiled compute or render + /// pipeline, a render descriptor's linked-use answers, its reflection, its variant record, and + /// a making's driver pipeline data -- with the refresh of a hit's access time and the removal + /// of an entry a decoder refused. + /// + /// The directory's calls alone are in the window. A lookup the device's memo answered never + /// reaches the directory; one the write queue answered reads no file + /// (`ShaderCacheStatistics::queued_hits`); and the encode and decode of an entry's bytes lie + /// outside it, which matters because the kinds differ -- a compute or tile state stores its + /// artifact on every miss and a later process decodes it, where a render state stores one only + /// when linking a variant again would translate, so a warm render creation decodes none + /// (`pipeline/sources.rs`). `ShaderCacheStatistics`' per-kind hits and misses say which kind a + /// run's lookups walked. These reads are always on a thread that asked -- a program's or one + /// of the pipeline pool's -- never the cache thread's. + pub shader_cache_read_nanos: u64, + /// Nanoseconds the shader cache's directory writes took on the threads that asked for an + /// artifact: the `mkdir`, the temporary file, its write and flush, and the `rename` over the + /// entry -- four journalled filesystem calls -- of each entry such a thread wrote itself, + /// which is each entry counted in + /// [`shader_cache_writes_on_thread`](Self::shader_cache_writes_on_thread). A creation whose + /// entry the device's cache thread took adds nothing here. + pub shader_cache_write_nanos: u64, + /// Nanoseconds the device's cache thread spent in the directory (`shader_cache/worker.rs`): + /// the writes it took from the queue, and the scan at device creation and the removals that + /// keep the directory under its cap. None of this is on a creation's path -- it is here so the + /// directory's whole cost is attributable and no part of it is dropped -- and it is host CPU + /// that runs beside the program's threads. + pub shader_cache_off_thread_nanos: u64, + /// Entries a thread that asked for an artifact wrote itself rather than hand to the device's + /// cache thread, because the queue was at one of its bounds or the entry is larger than the + /// whole bound: the same count as `ShaderCacheStatistics::writes_on_thread`, here because a + /// cost record carries `WorkCounts` and not that type. It partitions creations by a mechanism + /// rather than by their cost: on an M3 Max a creation on a fresh key that writes its own entry + /// costs about 180 us more than one the cache thread took (a median 223.9 us against 42.6 us), + /// so this is the largest mechanism left in a creation that reaches 200 us, and the time it + /// took is [`shader_cache_write_nanos`](Self::shader_cache_write_nanos). + pub shader_cache_writes_on_thread: u64, /// Of those, the makings that waited for a twin's making in the air, of the same functions /// and specialization, to land before their own (`pipeline/flight.rs`). pub flights_followed: u64, @@ -4441,6 +4509,11 @@ impl Device { // (`render/deferral.rs`). self.shared().deferred.lower_all(); let counters = &self.shared().counts; + // The driver's time in its pipeline makings (`device/compiles.rs`, by `VkDevice`), and + // what the shader cache's directory cost (`shader_cache/store.rs`): neither is in + // `Counters`. + let (render_create_nanos, compute_create_nanos) = self.shared().pipeline_create_nanos(); + let directory = self.shared().shader_cache.directory_time(); let churn = counters.churn.snapshot(); let group_end = |end: GroupEnd| counters.group_ends[end as usize].load(Ordering::Relaxed); let first_work_order = self.shared().textures.first_moves.submissions_waited(); @@ -4543,6 +4616,12 @@ impl Device { pipeline_layouts_made: counters.pipeline_layouts_made.load(Ordering::Relaxed), pipeline_layouts_shared: counters.pipeline_layouts_shared.load(Ordering::Relaxed), variant_pipelines_made: counters.variant_pipelines_made.load(Ordering::Relaxed), + render_pipeline_create_nanos: render_create_nanos, + compute_pipeline_create_nanos: compute_create_nanos, + shader_cache_read_nanos: directory.read_nanos, + shader_cache_write_nanos: directory.write_nanos, + shader_cache_off_thread_nanos: directory.off_thread_nanos, + shader_cache_writes_on_thread: directory.writes_on_thread, flights_followed: counters.flights_followed.load(Ordering::Relaxed), predicated_loop_runs_again: counters.predicated_loop_runs_again.load(Ordering::Relaxed), variants_taken_back: counters.variants_taken_back.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index d7525865d..b34347258 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -b5e0d8741a35ff411d4c5597448ab63a4dcd54a9ce55785eb792fc5fc60e1d0f +910c256f8c1505a85e6e48c3707b45b299ffda568ac542a2c41bd1423e749332 diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index d1a185e83..1ccc86c1b 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2381,6 +2381,8 @@ field metal2vulkan-runtime::ShaderCacheError.path pub path: Option field metal2vulkan-runtime::ShaderCacheOptions.capacity pub capacity: u64 field metal2vulkan-runtime::ShaderCacheOptions.directory pub directory: Option field metal2vulkan-runtime::ShaderCacheOptions.memory_capacity pub memory_capacity: u64 +field metal2vulkan-runtime::ShaderCacheStatistics.compute_pipeline_hits pub compute_pipeline_hits: u64 +field metal2vulkan-runtime::ShaderCacheStatistics.compute_pipeline_misses pub compute_pipeline_misses: u64 field metal2vulkan-runtime::ShaderCacheStatistics.driver_data_found pub driver_data_found: u64 field metal2vulkan-runtime::ShaderCacheStatistics.driver_data_mismatched pub driver_data_mismatched: u64 field metal2vulkan-runtime::ShaderCacheStatistics.driver_data_truncated pub driver_data_truncated: u64 @@ -2390,11 +2392,15 @@ field metal2vulkan-runtime::ShaderCacheStatistics.driver_pipeline_hits pub drive field metal2vulkan-runtime::ShaderCacheStatistics.driver_pipeline_misses pub driver_pipeline_misses: u64 field metal2vulkan-runtime::ShaderCacheStatistics.driver_saves pub driver_saves: u64 field metal2vulkan-runtime::ShaderCacheStatistics.evictions pub evictions: u64 +field metal2vulkan-runtime::ShaderCacheStatistics.function_hits pub function_hits: u64 +field metal2vulkan-runtime::ShaderCacheStatistics.function_misses pub function_misses: u64 field metal2vulkan-runtime::ShaderCacheStatistics.hits pub hits: u64 field metal2vulkan-runtime::ShaderCacheStatistics.misses pub misses: u64 field metal2vulkan-runtime::ShaderCacheStatistics.queued_hits pub queued_hits: u64 field metal2vulkan-runtime::ShaderCacheStatistics.read_failures pub read_failures: u64 field metal2vulkan-runtime::ShaderCacheStatistics.rejected pub rejected: u64 +field metal2vulkan-runtime::ShaderCacheStatistics.render_pipeline_hits pub render_pipeline_hits: u64 +field metal2vulkan-runtime::ShaderCacheStatistics.render_pipeline_misses pub render_pipeline_misses: u64 field metal2vulkan-runtime::ShaderCacheStatistics.write_failures pub write_failures: u64 field metal2vulkan-runtime::ShaderCacheStatistics.writes pub writes: u64 field metal2vulkan-runtime::ShaderCacheStatistics.writes_on_thread pub writes_on_thread: u64 @@ -2554,6 +2560,7 @@ field metal2vulkan-runtime::WorkCounts.completion_arms pub completion_arms: u64 field metal2vulkan-runtime::WorkCounts.completion_arms_after_a_wake pub completion_arms_after_a_wake: u64 field metal2vulkan-runtime::WorkCounts.completion_reads_ran_ahead pub completion_reads_ran_ahead: u64 field metal2vulkan-runtime::WorkCounts.compressed_rows_rewritten pub compressed_rows_rewritten: u64 +field metal2vulkan-runtime::WorkCounts.compute_pipeline_create_nanos pub compute_pipeline_create_nanos: u64 field metal2vulkan-runtime::WorkCounts.copy_regions_split pub copy_regions_split: u64 field metal2vulkan-runtime::WorkCounts.copy_sites pub copy_sites: [CopySite; 32] field metal2vulkan-runtime::WorkCounts.cpu_block_decodes pub cpu_block_decodes: u64 @@ -2771,6 +2778,7 @@ field metal2vulkan-runtime::WorkCounts.render_passes_begun_inline_splits pub ren field metal2vulkan-runtime::WorkCounts.render_passes_begun_instances pub render_passes_begun_instances: u64 field metal2vulkan-runtime::WorkCounts.render_passes_begun_resolves pub render_passes_begun_resolves: u64 field metal2vulkan-runtime::WorkCounts.render_passes_made pub render_passes_made: u64 +field metal2vulkan-runtime::WorkCounts.render_pipeline_create_nanos pub render_pipeline_create_nanos: u64 field metal2vulkan-runtime::WorkCounts.replay_log_bytes pub replay_log_bytes: u64 field metal2vulkan-runtime::WorkCounts.replay_logs_kept pub replay_logs_kept: u64 field metal2vulkan-runtime::WorkCounts.replay_tables_pointed pub replay_tables_pointed: u64 @@ -2804,6 +2812,10 @@ field metal2vulkan-runtime::WorkCounts.set_zero_sets_reused pub set_zero_sets_re field metal2vulkan-runtime::WorkCounts.set_zero_writes_if_shapes_shared pub set_zero_writes_if_shapes_shared: u64 field metal2vulkan-runtime::WorkCounts.set_zero_writes_on_equal_shape_switches pub set_zero_writes_on_equal_shape_switches: u64 field metal2vulkan-runtime::WorkCounts.set_zero_writes_pushed pub set_zero_writes_pushed: u64 +field metal2vulkan-runtime::WorkCounts.shader_cache_off_thread_nanos pub shader_cache_off_thread_nanos: u64 +field metal2vulkan-runtime::WorkCounts.shader_cache_read_nanos pub shader_cache_read_nanos: u64 +field metal2vulkan-runtime::WorkCounts.shader_cache_write_nanos pub shader_cache_write_nanos: u64 +field metal2vulkan-runtime::WorkCounts.shader_cache_writes_on_thread pub shader_cache_writes_on_thread: u64 field metal2vulkan-runtime::WorkCounts.shader_modules_made pub shader_modules_made: u64 field metal2vulkan-runtime::WorkCounts.shader_modules_shared pub shader_modules_shared: u64 field metal2vulkan-runtime::WorkCounts.shadow_attachment_clears pub shadow_attachment_clears: u64