diff --git a/crates/metal2vulkan-runtime/src/pipeline/kept.rs b/crates/metal2vulkan-runtime/src/pipeline/kept.rs index 54b31baff..780e723ef 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/kept.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/kept.rs @@ -50,6 +50,7 @@ use super::graphics::GraphicsKey; use super::objects::{SamplerSet, StageObject}; +use super::region_ledger::{Listed, Unlisted}; use super::shared_layouts::SharedLayout; use super::RegionKey; use crate::device::DeviceShared; @@ -233,7 +234,7 @@ impl Entry { fn destroy(&self, shared: &DeviceShared) { for pipeline in &self.pipelines { if let Place::Region(key) = &pipeline.place { - shared.region_ledger.forget(self.instance, key); + shared.region_ledger.forget_destroyed(self.instance, key); } pipeline.destroy(shared); } @@ -244,13 +245,42 @@ impl Entry { fn prune(&mut self, shared: &DeviceShared) { let instance = self.instance; self.pipelines.retain(|pipeline| match &pipeline.place { - Place::Region(key) if !shared.region_ledger.lists(instance, key) => { + Place::Region(key) if !listed(shared, instance, key) => { pipeline.destroy(shared); false } _ => true, }); } + + /// Destroy its region pipeline at `key`, if it keeps one. + fn prune_key(&mut self, shared: &DeviceShared, key: &RegionKey) { + let at = (self.pipelines.iter()) + .position(|pipeline| matches!(&pipeline.place, Place::Region(at) if at == key)); + if let Some(at) = at { + self.pipelines.remove(at).destroy(shared); + } + } +} + +/// Whether the device's ledger lists `instance`'s `key`, for a prune of the kept variants. +fn listed(shared: &DeviceShared, instance: Instance, key: &RegionKey) -> bool { + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + PRUNE_LOOKS.with(|looks| looks.set(looks.get() + 1)); + shared.region_ledger.lists(instance, key) +} + +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +thread_local! { + /// The keys this thread's prunes of the kept variants asked the device's ledger of, in the + /// device tests that read it (`tests::region_widths`). + static PRUNE_LOOKS: Cell = const { Cell::new(0) }; +} + +/// How many keys this thread's prunes of the kept variants asked the device's ledger of so far. +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +pub(crate) fn prune_looks() -> u64 { + PRUNE_LOOKS.with(Cell::get) } /// A release from any thread, queued until a variant is made ([`Kept::take`]). @@ -325,6 +355,17 @@ impl Entries { entries.back_mut() } + /// Destroy the kept region pipeline of `listed`, a key that left the device's ledger, where + /// the ledger lists it no longer. + fn prune(&mut self, shared: &DeviceShared, (instance, key): Listed) { + if listed(shared, instance, &key) { + return; + } + if let Some(entry) = self.0.iter_mut().find(|e| e.instance == instance) { + entry.prune_key(shared, &key); + } + } + /// Apply `arrival`, a release by its last holder: an instance's objects, or one of its /// `VkPipeline`s. fn apply(&mut self, shared: &DeviceShared, arrival: Arrival) { @@ -374,10 +415,20 @@ impl Kept { for arrival in self.arrived.drain(..) { self.entries.apply(shared, arrival); } - // The region pipelines the ledger let go past its bound since the last settle. - if let Some(times) = shared.region_ledger.prune_due() { - for entry in &mut self.entries.0 { - entry.prune(shared); + // The region pipelines the ledger let go past its bound since the last settle: those of + // the keys it names, each looked up once (`region_ledger.rs`). + if let Some((times, unlisted)) = shared.region_ledger.take_unlisted() { + match unlisted { + Unlisted::Keys(keys) => { + for listed in keys { + self.entries.prune(shared, listed); + } + } + Unlisted::Every => { + for entry in &mut self.entries.0 { + entry.prune(shared); + } + } } shared.region_ledger.pruned_at(times); } diff --git a/crates/metal2vulkan-runtime/src/pipeline/region_ledger.rs b/crates/metal2vulkan-runtime/src/pipeline/region_ledger.rs index a42d1bbd1..3860daeb7 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/region_ledger.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/region_ledger.rs @@ -19,6 +19,12 @@ //! theirs is (`Kept::settle`): they keep only the region pipelines the ledger lists. Either way //! the `VkPipeline` is destroyed once its last holder lets go of it: a command in flight, or an //! encoder's memo of what a dispatch planned. +//! - **Named, not searched.** The ledger names each key that leaves its list, past its bound or +//! forgotten by its memo ([`Unlisted`]), and the kept variants' settle looks at those keys +//! alone, not at every region pipeline they keep: a full ledger lets a key go at each key made, +//! and the settle after each must cost the keys it let go. Past as many named keys as the bound +//! (a run of host steps' makings, which settle nothing), it names none and the settle looks at +//! every kept region pipeline once. //! - **One copy each.** A region pipeline a variant's own bound or the ledger lets go is destroyed //! at its last release, never kept ([`RawPipeline::doom`]): a kept instance holds only what its //! variant's memo held when it was released, each listed once. @@ -45,7 +51,15 @@ use std::sync::{Arc, Mutex}; pub(crate) const DEVICE_REGION_PIPELINES: usize = 2 * super::REGION_PIPELINES; /// A listed region pipeline: its variant's instance and its key. -type Listed = (Instance, RegionKey); +pub(super) type Listed = (Instance, RegionKey); + +/// The keys that left the ledger's list since the kept variants last settled (the module docs). +pub(super) enum Unlisted { + /// These, each named as it left; a key listed again since among them. + Keys(Vec), + /// More than the ledger's bound: every kept region pipeline is to be looked at. + Every, +} /// The device's ledger (the module docs). pub(crate) struct RegionLedger { @@ -67,6 +81,23 @@ struct Ledger { bound: usize, /// Keys past the bound whose memos may still hold them made. past: Vec<(Listed, WeakMaking)>, + /// The keys that left the list since the kept variants last settled ([`Unlisted`]), `None` + /// past the bound's count of them. + unlisted: Option>, +} + +impl Ledger { + /// `listed` left the list: named for the kept variants' next settle, until more than the + /// bound's count of keys left since the last. + fn unlist(&mut self, listed: &Listed) { + let bound = self.bound; + if let Some(keys) = &mut self.unlisted { + match keys.len() < bound { + true => keys.push(listed.clone()), + false => self.unlisted = None, + } + } + } } impl RegionLedger { @@ -77,6 +108,7 @@ impl RegionLedger { listed: Lru::counted(usize::MAX), bound, past: Vec::new(), + unlisted: Some(Vec::new()), }), due: AtomicBool::new(false), times: AtomicU64::new(0), @@ -95,6 +127,7 @@ impl RegionLedger { let Some(oldest) = state.listed.pop_oldest() else { break; }; + state.unlist(&oldest.0); state.past.push(oldest); gone += 1; } @@ -110,15 +143,25 @@ impl RegionLedger { lock(&self.state).listed.get(listed); } - /// `instance`'s `key`, no longer kept: whether it was listed. + /// `instance`'s `key`, no longer kept by its memo: whether it was listed. Named for the kept + /// variants' next settle, which destroys a kept pipeline of it ([`Unlisted`]). pub(super) fn forget(&self, instance: Instance, key: &RegionKey) -> bool { let listed = (instance, key.clone()); let mut state = lock(&self.state); let was = state.listed.peek(&listed).is_some(); state.listed.remove(&listed); + if was { + state.unlist(&listed); + } was } + /// `instance`'s `key`, its kept pipeline destroyed with its kept instance: no longer listed, + /// and named for no settle. + pub(super) fn forget_destroyed(&self, instance: Instance, key: &RegionKey) { + lock(&self.state).listed.remove(&(instance, key.clone())); + } + /// Whether `instance`'s `key` is listed: what a kept instance may keep. pub(super) fn lists(&self, instance: Instance, key: &RegionKey) -> bool { (lock(&self.state).listed) @@ -126,11 +169,28 @@ impl RegionLedger { .is_some() } - /// How many times keys went past the bound so far, where that is more than when the kept - /// variants last destroyed what it no longer lists ([`pruned_at`](Self::pruned_at)). - pub(super) fn prune_due(&self) -> Option { + /// Whether keys went past the bound since the kept variants last destroyed what it no longer + /// lists ([`pruned_at`](Self::pruned_at)). + pub(super) fn prune_due(&self) -> bool { + self.times.load(Ordering::Acquire) != self.pruned.load(Ordering::Acquire) + } + + /// Where keys went past the bound since the kept variants last destroyed what it no longer + /// lists: how many times they went so far, and the keys that left the list since the kept + /// variants last settled ([`Unlisted`]), taken; else `None`, the keys kept for the next. + pub(super) fn take_unlisted(&self) -> Option<(u64, Unlisted)> { + let mut state = lock(&self.state); + // Read under the lock `kept` counts under, so the keys taken are those up to `times`. let times = self.times.load(Ordering::Acquire); - (times != self.pruned.load(Ordering::Acquire)).then_some(times) + if times == self.pruned.load(Ordering::Acquire) { + return None; + } + let unlisted = match &mut state.unlisted { + Some(keys) => Unlisted::Keys(std::mem::take(keys)), + None => Unlisted::Every, + }; + state.unlisted.get_or_insert_with(Vec::new); + Some((times, unlisted)) } /// The kept variants destroyed what it no longer listed when keys had gone past the bound @@ -181,7 +241,7 @@ impl RegionLedger { /// kept variants'. pub(super) fn let_go(shared: &DeviceShared) { shared.region_ledger.let_go_past(); - if shared.region_ledger.prune_due().is_some() { + if shared.region_ledger.prune_due() { lock(&shared.kept).settle_let_go(shared); } } diff --git a/crates/metal2vulkan-runtime/src/tests/region_widths.rs b/crates/metal2vulkan-runtime/src/tests/region_widths.rs index 261901428..58486aa43 100644 --- a/crates/metal2vulkan-runtime/src/tests/region_widths.rs +++ b/crates/metal2vulkan-runtime/src/tests/region_widths.rs @@ -17,6 +17,11 @@ //! bound across every variant's region pipelines (`pipeline/region_ledger.rs`), a released //! variant's kept instance included. //! +//! [`a_full_ledger_s_settle_looks_at_the_keys_it_let_go_alone`]: what the kept variants' settle +//! after each key a full ledger lets go looks at. Printed (`KEPT-PRUNE`): the keys its settles +//! asked the ledger of, and the dispatch call's host time, the median and the least, in a release +//! build the A/B of the settle's cost. +//! //! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. The module is LLVM text written here //! (`llvm-as`). @@ -26,10 +31,11 @@ use super::opencl_mode::{words, words_buffer}; use super::spares_bench::process_memory; use super::uniform_bind_offsets::idle; use crate::device::lock; +use crate::pipeline::kept::prune_looks; use crate::{CommandBufferStatus, ComputePipelineState, Device, PipelineOptions, Size}; use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; use std::ops::RangeInclusive; -use std::time::Instant; +use std::time::{Duration, Instant}; /// The widest threadgroup the stream asks for. const WIDEST: u32 = 64; @@ -91,9 +97,16 @@ fn run(device: &Device, state: &ComputePipelineState, n: u32) { } /// Dispatch `n` threads in threadgroups of `width`, wait, and check what Metal writes: `gid % -/// width + plus` at each of the grid's words, and nothing past them. -fn dispatch(device: &Device, state: &ComputePipelineState, (n, width): (u32, u32), plus: u32) { - let out = words_buffer(device, &[UNWRITTEN; GRIDS as usize]); +/// width + plus` at each of the grid's words, and nothing past them (at least [`GRIDS`] words). +/// The dispatch call's host time. +fn dispatch( + device: &Device, + state: &ComputePipelineState, + (n, width): (u32, u32), + plus: u32, +) -> Duration { + let length = GRIDS.max(n); + let out = words_buffer(device, &vec![UNWRITTEN; length as usize]); let queue = device.new_command_queue().unwrap(); let command_buffer = queue.command_buffer().unwrap(); let mut encoder = command_buffer.compute_command_encoder().unwrap(); @@ -101,19 +114,22 @@ fn dispatch(device: &Device, state: &ComputePipelineState, (n, width): (u32, u32 encoder.set_buffer(Some(&out), 0, 0).unwrap(); let threads = Size::new(u64::from(n), 1, 1); let group = Size::new(u64::from(width), 1, 1); + let called = Instant::now(); encoder.dispatch_threads(threads, group).unwrap(); + let call = called.elapsed(); encoder.end_encoding().unwrap(); command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); let written = words(&out); - let want: Vec = (0..GRIDS) + let want: Vec = (0..length) .map(|gid| match gid < n { true => gid % width + plus, false => UNWRITTEN, }) .collect(); assert_eq!(written, want, "{n} threads in threadgroups of {width}"); + call } /// Two passes of the stream: the first makes each region key once, the second none. @@ -242,3 +258,69 @@ fn two_kernels_past_the_device_bound_make_a_key_again_only_once_it_is_let_go() { ); assert_eq!(shared.region_ledger.listed(), BOUND); } + +/// The region pipelines of the released kernel in the settle test, as many as a variant keeps +/// (`pipeline/mod.rs`, `REGION_PIPELINES`), and the device's bound there. +const KEPT_KEYS: u32 = 256; + +/// The keys of the other kernel in the settle test, each letting one of the kept ones go. +const LET_GO: u32 = 64; + +/// A kernel's [`KEPT_KEYS`] region pipelines (widths 1 to 256, one key each) kept for its released +/// state under a device bound of as many, then another kernel's [`LET_GO`] keys, each letting the +/// least recently used kept one go: the settle at each of those dispatches asks the ledger of the +/// key it let go alone, not of every region pipeline the kept instance holds (which would be +/// 14,368 looks), and destroys that one. +#[test] +fn a_full_ledger_s_settle_looks_at_the_keys_it_let_go_alone() { + let scratch = Scratch::new("region-prune"); + let device = device(&scratch.0); + let shared = device.shared(); + shared.region_ledger.bound_at(KEPT_KEYS as usize); + let first = state(&device, KERNEL); + for n in 1..=KEPT_KEYS { + dispatch(&device, &first, (n, n), 0); + } + assert_eq!(shared.region_ledger.listed(), KEPT_KEYS as usize); + drop(first); + idle(&device); + let kept = (1, KEPT_KEYS as usize); + let until = Instant::now() + WAIT; + while lock(&shared.kept).held() != kept { + assert!( + Instant::now() < until, + "the kept variants hold {:?} after {WAIT:?}", + lock(&shared.kept).held() + ); + std::thread::sleep(Duration::from_millis(1)); + } + let second = state(&device, &KERNEL.replace(STORE, STORE_PLUS_ONE)); + let evicted = device.work_counts().region_pipelines_evicted; + let looks = prune_looks(); + let mut calls: Vec = (1..=LET_GO) + .map(|n| dispatch(&device, &second, (n, n), 1)) + .collect(); + let looked = prune_looks() - looks; + calls.sort(); + println!( + "KEPT-PRUNE {}: {KEPT_KEYS} kept region pipelines, {LET_GO} let go: the settles looked \ + at {looked} keys; dispatch call median {:?}, least {:?}", + device.name(), + calls[calls.len() / 2], + calls[0] + ); + assert_eq!( + device.work_counts().region_pipelines_evicted - evicted, + u64::from(LET_GO), + "the keys the ledger let go" + ); + assert_eq!( + lock(&shared.kept).held(), + (1, (KEPT_KEYS - LET_GO) as usize), + "the kept instance after the ledger let {LET_GO} of its region pipelines go" + ); + assert!( + looked <= u64::from(LET_GO), + "the settles looked at {looked} keys for the {LET_GO} the ledger let go" + ); +}