From eb25ca898d20ee2cf76a2f826b510b2acff7b886 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 2 Nov 2026 20:35:46 -0800 Subject: [PATCH] The tracker orders each command by one use list, kept in the encoder's storage Each ordered command built its use list twice (EncoderUses::barrier, then record_reaching), each time through a fresh Vec and a fresh hash map, then a sort. The two lists differ only for untracked uses. - tracker.rs: EncoderUses::order compares and records a command in one call. The uses are merged in place (merge: a stable sort by key, then each key's equal ranges joined), into two lists the encoder keeps and clears per command; the second list (what the command is recorded with) is the compared one where every use is tracked, and made apart, in its own kept storage, only where one is not. - encoder.rs: track calls order. The same uses in the same order, so the same barriers: merging_in_place_keeps_each_key_and_range_once_in_order checks the merge against the map-based form it replaces over 2000 random commands. Check that fails without it: tests::tracker::an_encoder_orders_its_commands_in_storage_it_keeps (with a fresh Vec per command, the storage moves at the second command). Release, M3 Max, MoltenVK 1.4.2, host_ab, before and after interleaved three times (each a median of 3 rounds): | workload | before | after | |---|---:|---:| | many_blit_copy (ns) | 786-824 | 645-654 | | wide_blit_copy (ns) | 535-570 | 384-396 | | many_dispatch_resident (ns) | 3458-3595 | 3260-3414 | | wide_dispatch (ns) | 2398-2527 | 2148-2301 | | dispatch_resident_moving_256 (us/dispatch) | 1.78-2.39 | 1.65-1.69 | Allocations per call (percall, deterministic): dispatch 18.16 -> 14.16, copy_buffer_1k 6.07 -> 2.08, fill_buffer_256 8.06 -> 4.06, copy_buffer_to_texture 12.56 -> 8.63, fill_in_own_encoder 20.6 -> 17.6; calls many_blit_copy 14 -> 11, wide_blit_copy 6.5 -> 2.5. Verified: the runtime's tracker and host_aliases tests; the runtime GPU suite on MoltenVK 1504/1504. (cherry picked from commit a4f9f1c9a908c6289d4096cd37c32fa7a8866b94) (cherry picked from commit 55b4ba442f60e0a39630639ec383d760c8e2b945) (cherry picked from commit 4be1a7d13048620e22a628ec2dbb13e76660451b) (cherry picked from commit 56649bbf80d15bb6a0dbe0decfa898e5def0ce0f) --- crates/metal2vulkan-runtime/src/encoder.rs | 3 +- .../src/tests/host_aliases.rs | 3 +- .../metal2vulkan-runtime/src/tests/tracker.rs | 105 ++++++++++-- crates/metal2vulkan-runtime/src/tracker.rs | 152 +++++++++++------- 4 files changed, 188 insertions(+), 75 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 4c82d350b..2ef0f5f48 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -1121,8 +1121,7 @@ impl EncoderCore { // texture is no longer carried, whatever this encoder uses (`shadow::ShadowCarry`). self.shadows.wrote(tracked); self.open.command_buffer.note_dirty(tracked); - let barrier = self.uses.barrier(tracked, reach); - self.uses.record_reaching(stages, tracked, barrier, reach); + let barrier = self.uses.order(stages, tracked, reach); if barrier.is_some() { self.device().shared().counts.command_barrier(); } diff --git a/crates/metal2vulkan-runtime/src/tests/host_aliases.rs b/crates/metal2vulkan-runtime/src/tests/host_aliases.rs index fd28d6760..94b3b73e2 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_aliases.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_aliases.rs @@ -505,8 +505,7 @@ fn a_sample_through_a_second_key_waits_for_a_render_through_the_first() { let summary = |uses: &[Use]| { let mut encoder = EncoderUses::new(true); let uses = aliases.augment(uses).unwrap_or_else(|| uses.to_vec()); - let barrier = encoder.barrier(&uses, Reach::Unnamed); - encoder.record(vk::PipelineStageFlags2::NONE, &uses, barrier); + encoder.order(vk::PipelineStageFlags2::NONE, &uses, Reach::Unnamed); encoder.finish() }; let render = Use::writes( diff --git a/crates/metal2vulkan-runtime/src/tests/tracker.rs b/crates/metal2vulkan-runtime/src/tests/tracker.rs index 4bf64b37b..60c9a1656 100644 --- a/crates/metal2vulkan-runtime/src/tests/tracker.rs +++ b/crates/metal2vulkan-runtime/src/tests/tracker.rs @@ -3,8 +3,8 @@ //! `VkQueue`s, and the legacy masks. use crate::tracker::{ - ordered, Access, Barrier, EncoderUses, Footprint, GeometryWrites, IndirectReads, LegacyBarrier, - Point, Reach, Summary, Tracker, Use, UseRange, Wait, ENTRIES_PER_KEY, + merge, ordered, Access, Barrier, EncoderUses, Footprint, GeometryWrites, IndirectReads, + LegacyBarrier, Point, Reach, Summary, Tracker, Use, UseRange, Wait, ENTRIES_PER_KEY, }; use ash::vk; use std::ops::Range; @@ -60,8 +60,7 @@ fn barrier(src: Access, dst: Access) -> Option { fn encoder(commands: &[&[Use]]) -> Summary { let mut uses = EncoderUses::new(true); for command in commands { - let barrier = uses.barrier(command, Reach::Unnamed); - uses.record(vk::PipelineStageFlags2::NONE, command, barrier); + uses.order(vk::PipelineStageFlags2::NONE, command, Reach::Unnamed); } uses.finish() } @@ -717,9 +716,7 @@ fn untracked_memory_is_one_class_inside_an_encoder() { #[test] fn named_untracked_memory_orders_per_key_and_range_inside_an_encoder() { let named = |uses: &mut EncoderUses, command: &[Use]| { - let barrier = uses.barrier(command, Reach::Named); - uses.record_reaching(TRANSFER, command, barrier, Reach::Named); - barrier + uses.order(TRANSFER, command, Reach::Named) }; let write = |key, range| [Use::writes(key, false, bytes(range), copy_write())]; let read = |key, range| [Use::reads(key, false, bytes(range), copy_read())]; @@ -1006,8 +1003,7 @@ fn random_encoder(next: &mut impl FnMut(u64) -> u64) -> Summary { _ => reads(key, range, shader_read()), }; let command = [used]; - let barrier = uses.barrier(&command, Reach::Unnamed); - uses.record(vk::PipelineStageFlags2::NONE, &command, barrier); + uses.order(vk::PipelineStageFlags2::NONE, &command, Reach::Unnamed); } if next(4) == 0 { uses.wait_for_fence(100 + next(2), None); @@ -1407,8 +1403,7 @@ fn an_encoder_summary_stays_bounded() { let mut uses = EncoderUses::::new(true); for at in 0..1000u64 { let command = [reads(1, bytes(at * 4..at * 4 + 4), copy_read())]; - let barrier = uses.barrier(&command, Reach::Unnamed); - uses.record(TRANSFER, &command, barrier); + uses.order(TRANSFER, &command, Reach::Unnamed); } let summary = uses.finish(); assert!(summary.uses().len() <= ENTRIES_PER_KEY); @@ -1883,7 +1878,7 @@ fn a_resource_used_at_moving_ranges_allocates_its_list_once() { let mut uses = EncoderUses::new(false); for at in 0..3 * ENTRIES_PER_KEY as u64 { let used = [reads(1, bytes(256 * at..256 * at + 16), shader_read())]; - uses.record_reaching(COMPUTE, &used, None, Reach::Named); + uses.order(COMPUTE, &used, Reach::Named); if at > 0 { assert_eq!(uses.range_room(1), Some(ENTRIES_PER_KEY + 1), "range {at}"); } @@ -1924,3 +1919,89 @@ fn a_summary_lists_its_uses_by_resource_each_in_recorded_order() { .collect(); assert_eq!(got, expected); } + +/// An ordered encoder's commands write the uses it orders them by over the last command's storage +/// ([`EncoderUses::ordered_storage`]): commands of as many uses as the first make no list again, +/// and a command whose every use is tracked keeps the list it compared, making none apart; a +/// command with an untracked use makes the one it keeps once, and the commands like it after it +/// none. +#[test] +fn an_encoder_orders_its_commands_in_storage_it_keeps() { + let mut uses = EncoderUses::::new(true); + let tracked = [ + reads(1, bytes(0..64), copy_read()), + writes(2, bytes(0..64), copy_write()), + reads(1, bytes(0..64), shader_read()), + ]; + uses.order(TRANSFER, &tracked, Reach::Unnamed); + let first = uses.ordered_storage(); + assert_eq!(first[1].1, 0, "a list kept apart for tracked uses"); + for _ in 0..64 { + uses.order(TRANSFER, &tracked, Reach::Unnamed); + assert_eq!(uses.ordered_storage(), first); + } + let untracked = [ + reads(1, bytes(0..64), copy_read()), + Use::writes(3, false, bytes(0..64), copy_write()), + ]; + uses.order(TRANSFER, &untracked, Reach::Named); + let second = uses.ordered_storage(); + assert_eq!(second[0], first[0]); + assert!(second[1].1 > 0, "no list kept apart for an untracked use"); + for _ in 0..64 { + uses.order(TRANSFER, &untracked, Reach::Named); + uses.order(TRANSFER, &tracked, Reach::Unnamed); + assert_eq!(uses.ordered_storage(), second); + } +} + +/// The uses an encoder orders a command by are those a merge through a map of each key and range +/// makes, sorted by key ([`merge`]'s reference, the form it took before): for commands of random +/// uses of few keys and ranges, repeated and touching nothing among them, the same uses in the +/// same order, so the encoder's barriers are the same. +#[test] +fn merging_in_place_keeps_each_key_and_range_once_in_order() { + fn reference(uses: &[Use]) -> Vec> { + let mut merged: Vec> = Vec::new(); + let mut index = std::collections::HashMap::new(); + for used in uses.iter().filter(|used| !used.is_nothing()) { + match index.get(&(used.key, used.range.clone())) { + Some(&at) => { + let known: &mut Use = &mut merged[at]; + known.read = known.read.union(used.read); + known.write = known.write.union(used.write); + } + None => { + index.insert((used.key, used.range.clone()), merged.len()); + merged.push(used.clone()); + } + } + } + merged.sort_by_key(|used| used.key); + merged + } + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |n: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed % n + }; + for _ in 0..2000 { + let uses: Vec> = (0..next(12)) + .map(|_| { + let start = 16 * next(3); + let range = bytes(start..start + 16 * next(3)); + let access = + [copy_read(), copy_write(), shader_read(), Access::NONE][next(4) as usize]; + match next(2) { + 0 => reads(next(4), range, access), + _ => writes(next(4), range, access), + } + }) + .collect(); + let mut merged: Vec> = uses.iter().filter(|u| !u.is_nothing()).cloned().collect(); + merge(&mut merged); + assert_eq!(merged, reference(&uses), "{uses:?}"); + } +} diff --git a/crates/metal2vulkan-runtime/src/tracker.rs b/crates/metal2vulkan-runtime/src/tracker.rs index d19844221..d412f3ee8 100644 --- a/crates/metal2vulkan-runtime/src/tracker.rs +++ b/crates/metal2vulkan-runtime/src/tracker.rs @@ -7,7 +7,7 @@ //! encoder's dispatches run in encoded order: `MTLDispatchTypeSerial` "dispatches are executed //! in dispatched order", and a memory barrier on a serial encoder is "allowed, but ignored", so //! the order covers untracked resources too (Metal's headers; documented, not measured). Before -//! each command, [`EncoderUses::barrier`] compares its uses with the encoder's earlier commands: +//! each command, [`EncoderUses::order`] compares its uses with the encoder's earlier commands: //! tracked resources per resource and range. Untracked memory may alias across resources, so //! it orders by what a command's uses say of it ([`Reach`]). A command whose uses name every //! byte of untracked memory it touches (a blit's, a shadow's copy) orders per key and range @@ -312,7 +312,7 @@ impl Use { } /// Whether the use touches nothing: an empty range, or neither a read nor a write. - fn is_nothing(&self) -> bool { + pub(super) fn is_nothing(&self) -> bool { self.range.is_empty() || (self.read.is_empty() && self.write.is_empty()) } @@ -1041,27 +1041,32 @@ fn coalesce(entries: &mut Vec) { } } -/// The uses one per key and range, sorted by key, without the ones that touch nothing. -fn merged(uses: impl IntoIterator>) -> Vec> { - let mut merged: Vec> = Vec::new(); - let mut index: KeyMap<(S, UseRange), usize> = KeyMap::default(); - for used in uses { - if used.is_nothing() { - continue; +/// `uses` (none of which touches nothing) one per key and range, sorted by key, each key's ranges +/// in the order they first came, the reads and writes of a range's uses joined: in place, in their +/// own storage. +pub(super) fn merge(uses: &mut Vec>) { + // Stable: a key's uses keep their order. + uses.sort_by_key(|used| used.key); + // `uses[..kept]` are merged, `uses[group..kept]` those of the key at hand. + let mut kept = 0; + let mut group = 0; + for at in 0..uses.len() { + if group < kept && uses[group].key != uses[at].key { + group = kept; } - match index.get(&(used.key, used.range.clone())) { - Some(&at) => { - merged[at].read = merged[at].read.union(used.read); - merged[at].write = merged[at].write.union(used.write); + match (group..kept).find(|&k| uses[k].range == uses[at].range) { + Some(k) => { + let (read, write) = (uses[at].read, uses[at].write); + uses[k].read = uses[k].read.union(read); + uses[k].write = uses[k].write.union(write); } None => { - index.insert((used.key, used.range.clone()), merged.len()); - merged.push(used); + uses.swap(kept, at); + kept += 1; } } } - merged.sort_by_key(|used| used.key); - merged + uses.truncate(kept); } /// How far a command's uses say which untracked memory it touches, inside an encoder Metal orders @@ -1115,6 +1120,11 @@ pub(super) struct EncoderUses { held: Vec, /// A use of a held image but as a depth/stencil attachment was recorded after its hold. broke: bool, + /// The last command's uses as the encoder orders them ([`inside_uses`]): to compare with the + /// earlier commands', and as it keeps them where those differ (a command with an untracked + /// use). Each command's are written over the last one's storage. + compared: Vec>>, + kept: Vec>>, } /// A fence an encoder waits for or updates, and the stages of its draws the call names: a render @@ -1186,6 +1196,8 @@ impl EncoderUses { updates: Vec::new(), held: Vec::new(), broke: false, + compared: Vec::new(), + kept: Vec::new(), } } @@ -1196,19 +1208,41 @@ impl EncoderUses { /// The barrier a command with `uses`, which say what untracked memory it touches as `reach` /// does, needs after the encoder's earlier commands: none in an encoder whose commands are - /// not ordered. Nothing changes until [`EncoderUses::record`]. - pub(super) fn barrier(&self, uses: &[Use], reach: Reach) -> Option { + /// not ordered. Nothing the encoder orders by changes until [`EncoderUses::order`]. + pub(super) fn barrier(&mut self, uses: &[Use], reach: Reach) -> Option { if !self.ordered { return None; } + inside_uses(uses, reach, false, &mut self.compared); // One encoder runs on one queue: its commands need barriers, never waits. - depend( - &self.inside, - &inside_uses(uses, reach, false), - (Point::default(), 0), - ) - .barrier - .needed() + depend(&self.inside, &self.compared, (Point::default(), 0)) + .barrier + .needed() + } + + /// Order a command whose `uses` say what untracked memory it touches as `reach` does after the + /// encoder's earlier commands, and note it recorded, in `stages`, after the barrier it needs + /// ([`barrier`](Self::barrier)), which this answers. The command's uses as the encoder compares + /// them are those it keeps where every use is tracked ([`inside_uses`]), so they are made once. + pub(super) fn order( + &mut self, + stages: vk::PipelineStageFlags2, + uses: &[Use], + reach: Reach, + ) -> Option { + let barrier = self.barrier(uses, reach); + if self.ordered { + let kept = match uses.iter().all(|used| used.tracked) { + true => &self.compared, + false => { + inside_uses(uses, reach, true, &mut self.kept); + &self.kept + } + }; + admit(&mut self.inside, kept, barrier, &[], Point::default()); + } + self.note(stages, uses); + barrier } /// Note a recorded command that may touch untracked memory its uses do not name @@ -1219,18 +1253,16 @@ impl EncoderUses { uses: &[Use], barrier: Option, ) { - self.record_reaching(stages, uses, barrier, Reach::Unnamed); + if self.ordered { + inside_uses(uses, Reach::Unnamed, true, &mut self.kept); + admit(&mut self.inside, &self.kept, barrier, &[], Point::default()); + } + self.note(stages, uses); } - /// [`record`](Self::record) of a command whose `uses` say what untracked memory it touches - /// as `reach` does. - pub(super) fn record_reaching( - &mut self, - stages: vk::PipelineStageFlags2, - uses: &[Use], - barrier: Option, - reach: Reach, - ) { + /// Note a command the encoder orders recorded, in `stages`, with `uses`: its held images' + /// holds, its part's stages and tracked uses. + fn note(&mut self, stages: vk::PipelineStageFlags2, uses: &[Use]) { if !self.held.is_empty() { let held = &self.held; self.broke |= uses.iter().any(|used| { @@ -1242,16 +1274,6 @@ impl EncoderUses { part.stages |= uses.iter().fold(stages, |all, used| { all | used.read.stages | used.write.stages }); - if self.ordered { - admit( - &mut self.inside, - &inside_uses(uses, reach, true), - barrier, - &[], - Point::default(), - ); - } - let part = self.current(); // Room for a few resources at once, made at the part's first: grown from nothing, the map // would allocate again at its fourth and eighth. if part.tracked.capacity() == 0 { @@ -1700,18 +1722,20 @@ fn coalesce_uses(uses: &mut Vec>) { } } -/// The uses of a command of `reach` as the encoder orders them ([`Class`]): to compare with the -/// earlier commands' (`recorded` false), or as it keeps them (`recorded` true). A tracked use is -/// its key's. An untracked use of a [`Reach::Named`] command compares with its key's and with -/// the accesses of the commands that do not name theirs, and is kept as its key's and as an -/// access of all untracked memory; one of a [`Reach::Unnamed`] command compares with every -/// untracked access, and is kept as an access of all untracked memory, and of the commands that -/// do not name theirs. -fn inside_uses( +/// The uses of a command of `reach` as the encoder orders them ([`Class`]), written over `into`: +/// to compare with the earlier commands' (`recorded` false), or as it keeps them (`recorded` +/// true), one per class and range, sorted by class, without those that touch nothing ([`merge`]). +/// A tracked use is its key's, either way. An untracked use of a [`Reach::Named`] command compares +/// with its key's and with the accesses of the commands that do not name theirs, and is kept as +/// its key's and as an access of all untracked memory; one of a [`Reach::Unnamed`] command +/// compares with every untracked access, and is kept as an access of all untracked memory, and of +/// the commands that do not name theirs. +fn inside_uses( uses: &[Use], reach: Reach, recorded: bool, -) -> Vec>> { + into: &mut Vec>>, +) { let class = |used: &Use, key: Class, range: UseRange| Use { key, tracked: used.tracked, @@ -1719,7 +1743,8 @@ fn inside_uses( read: used.read, write: used.write, }; - merged(uses.iter().flat_map(|used| { + into.clear(); + for used in uses { let (first, second) = match (used.tracked, reach, recorded) { (true, _, _) => (Class::Key(used.key), None), (false, Reach::Named, false) => (Class::Key(used.key), Some(Class::Unnamed)), @@ -1731,11 +1756,13 @@ fn inside_uses( Class::Key(_) => used.range.clone(), Class::Untracked | Class::Unnamed => UseRange::UNTRACKED, }; - [Some(class(used, first, range))] + let classes = [Some(class(used, first, range))] .into_iter() .chain([second.map(|key| class(used, key, UseRange::UNTRACKED))]) - .flatten() - })) + .flatten(); + into.extend(classes.filter(|used| !used.is_nothing())); + } + merge(into); } /// What one ended encoder hands to its queue's tracker at commit. @@ -1858,6 +1885,13 @@ impl EncoderUses { let part = self.parts.iter().last()?; part.tracked.get(&key).map(|few| few.rest.capacity()) } + + /// Where the storage of the lists its last command was ordered by lies, and its room: the + /// list compared with the earlier commands', then the one kept apart ([`inside_uses`]). + #[cfg(test)] + pub(super) fn ordered_storage(&self) -> [(usize, usize); 2] { + [&self.compared, &self.kept].map(|list| (list.as_ptr().addr(), list.capacity())) + } } impl Summary {