From 2f9a3a3782dd7cd46567db495d5695d669a382c8 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 3 Nov 2026 02:20:48 -0800 Subject: [PATCH] A command buffer joins its ended encoders' resources where its work reads them, not as each ends MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each compute or render encoder's end joined everything it made resident into its command buffer's residency (Residency::join_encoder: a clone and a hash insert per resource), and each later encoder's open walked every texture of that union for the shadowed ones. Most command buffers' work never reads the union: only the commit's and host steps' recordings against every encoder's resources (CommandBuffer::residency), the resident set of a GPU-alone recording, a texture made in a heap since, and an encoder encoded again do. - command_buffer/mod.rs: an encoder's end joins its heaps at once (join_encoder_heaps) and leaves its resources in its record; State::joined_residency joins the records not joined yet, in the order they ended, at the first read (CommandBuffer::residency, make_resident, fresh_ranges, a splice of an encoder encoded again, before the textures its heaps made since). The union holds what the eager join made, in the same token order: State::sync_heaps joins the records first where a heap made textures, as each encoder's join came before them. The commit's sync of its heaps and an encoder's open (State::inherited) read no resource list unless one did. - residency.rs: each residency lists its shadowed textures' tokens (shadowed), found where an open first asks for them (find_shadowed) and each texture looked at once, so making a texture resident reads nothing of it, and an open starts with the shadowed textures of the joined union and of the records not joined yet, in the order they were made resident, with the joined usage and stages, at the cost of their count. The join's resource and heap halves and sync_heaps's finding and joining halves are split out. - WorkCounts::resident_resources_joined counts the joins (api_signatures.tsv blessed: one field). The records hold what their encoders made resident until the command buffer completes, as before, and the union goes with them, so nothing lives longer or shorter. The same resources, usages, stages, tokens, shadows and heaps at every read. Release numbers, M3 Max (host_ab --only encode, runtime side, median of 3 rounds, µs; before is this landing without this commit, after with it, two or three interleaved runs each): before (3 runs) after (3 runs) resident_0 end_call 14.1 11.6 14.9 11.3 14.4 15.1 resident_256 end_call 34.7 25.6 37.3 11.1 13.3 15.4 resident_4096 end_call 230.3 152.3 244.3 11.4 14.1 15.5 resident_moving_4096 end_call 170.5 154.3 248.6 10.7 11.8 15.2 resident_textures_256 end_call 41.5 29.5 43.1 11.2 13.0 15.3 resident_textures_4096 end_call 287.8 193.5 294.6 11.5 12.9 15.8 resident_4096 use_call 346.1 379.3 335.1 326.1 297.3 342.0 resident_textures_256 use_call 38.0 37.0 36.9 35.1 35.1 37.2 resident_textures_4096 use_call 450.3 481.0 430.3 409.5 419.6 438.3 resident_4096 encode/dispatch 1.73 1.32 1.62 1.74 1.65 1.65 resident_textures_4096 encode 2.20 1.78 1.93 1.93 1.99 1.97 static encode/dispatch 1.75 1.74 1.61 1.62 1.64 1.60 The end call no longer grows with what the encoder made resident, and the useResources call does not take the cost instead. A first form of this change looked for a texture's shadow as it was made resident; that put about 80 µs into resident_textures_4096's use_call (260 to 317 against 188 to 200 before, four interleaved runs each), which is why the shadowed textures are found where an open first asks for them. Percall's counts are the same with and without this commit; the calls workload's end_compute allocates 5 a call where it allocated 8.5. Checks that fail without it, in tests/joined_residency.rs: - ended_encoders_join_their_command_buffer_s_residency_where_it_is_read: with the second encoder's open joining the records (the eager join's timing), its first assert fails (16 joined where 0). - shadowed_textures_made_resident_reach_the_next_encoders_in_order: with find_shadowed looking at none, its first assert fails (no shadowed texture inherited). Verified: the runtime GPU suite on the M3 (1527 passed, 3 skipped); cargo clippy -p metal2vulkan -p metal2vulkan-runtime --all-targets --all-features -D warnings, with and without --cfg m2v_gpu; scripts/api-signatures/signatures.py --check. (cherry picked from commit 18553c295c98dabe4c74fc226be6b45955c0c13a) (cherry picked from commit ae56cfdfdd2e4cb1e9b189c7ce303d680fbc2b7f) --- .../examples/host_ab/runtime.rs | 1 + .../src/command_buffer/first_submission.rs | 12 +- .../src/command_buffer/mod.rs | 86 +++++++++-- .../src/command_buffer/reencode.rs | 5 + crates/metal2vulkan-runtime/src/residency.rs | 105 ++++++++++--- .../src/tests/joined_residency.rs | 140 ++++++++++++++++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../metal2vulkan-runtime/src/work_counts.rs | 16 ++ crates/metal2vulkan/tests/api_signatures.tsv | 1 + 9 files changed, 329 insertions(+), 39 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/joined_residency.rs diff --git a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs index 8e730b132..30e9d42d1 100644 --- a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs +++ b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs @@ -1740,6 +1740,7 @@ impl Gpu for Runtime { c.dispatch_used_resources_listed, ), ("resident_textures_looked_at", c.resident_textures_looked_at), + ("resident_resources_joined", c.resident_resources_joined), ("heap_tables_worked_out", c.heap_tables_worked_out), ("argument_samplers_taken", c.argument_samplers_taken), ("bind_views_worked_out", c.bind_views_worked_out), diff --git a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs index 320c37598..0cfda9504 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs @@ -72,7 +72,6 @@ use super::{write_fields, CommandBufferShared, Resident, State}; use crate::error::{internal, CommandBufferError, Error}; use crate::live_buffers::LiveTable; use crate::rebind::{SubmittedHolds, Submitting}; -use crate::residency::Residency; use crate::upload::Upload; use crate::used_resources::UsedResources; use crate::values::CommandBufferStatus; @@ -228,7 +227,7 @@ impl State { }) if table.generation() != now => {} _ => return Ok(()), } - let fresh = self.fresh_ranges(); + let fresh = self.fresh_ranges(device); self.remake_resident(device, &fresh) } @@ -242,7 +241,7 @@ impl State { fn point_replay_tables(&mut self, device: &Device, moved: bool) -> Result<(), Error> { let live = device.shared().live_buffers.table(device)?; if moved { - let ranges = live.ranges().chain(self.fresh_ranges()); + let ranges = live.ranges().chain(self.fresh_ranges(device)); let (bytes, count) = ResidentSet::replay_bytes(ranges); let len = bytes.len() as u64; let upload = @@ -265,10 +264,9 @@ impl State { } /// The ranges of what its encoders made resident, as it lies now. - fn fresh_ranges(&self) -> Vec { - self.residency - .as_ref() - .map(Residency::resident_ranges) + fn fresh_ranges(&mut self, device: &Device) -> Vec { + (self.joined_residency(&device.shared().counts)) + .map(|residency| residency.resident_ranges()) .unwrap_or_default() } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 7a8c540c3..92994a61a 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -108,6 +108,7 @@ use super::unique_identifier::ScheduledWork; use super::upload::{Upload, Uploads}; use super::used_resources::{names_any, EncoderKind, EncoderRecord, Reached, ReadRecord}; use super::values::CommandBufferStatus; +use super::work_counts::Counters; use super::{Buffer, CommandQueue, Device}; use crate::release; use ash::vk; @@ -703,8 +704,12 @@ pub(super) struct State { pub(super) holds: Vec, /// What its ended encoders made resident, every encoder's joined (`residency.rs`): the /// residency the work its commit and host steps record resolves and binds against. Released - /// with what it retained, as it completes. + /// with what it retained, as it completes. Its heaps are joined as each encoder ends, and the + /// resources of the encoders from `joined` on where its work first reads it + /// ([`joined_residency`](Self::joined_residency)). residency: Option, + /// The ended encoders whose resources `residency` holds joined: those before this place. + joined: usize, /// Its ended encoders, in the order they ended, each with what its commands use /// (`used_resources.rs`): the keys its commands' uses and bindings named, its placed /// segments' among them, and what it made resident. Their uses are let go as it completes. @@ -816,8 +821,10 @@ impl State { /// An encoder of `kind` ended, its commands' uses and bindings having named `keys`, having /// made `residency` resident (a compute or render encoder's): it joins the ended encoders, /// with the event waits and signals encoded before it, and what it made resident joins the - /// command buffer's residency (`Residency::join_encoder`). Its place among the ended - /// encoders, which each of its recordings' parts carries. + /// command buffer's residency (`Residency::join_encoder`): its heaps now, its resources where + /// the command buffer's work first reads that residency + /// ([`joined_residency`](Self::joined_residency)). Its place among the ended encoders, which + /// each of its recordings' parts carries. pub(super) fn encoder_ended( &mut self, kind: EncoderKind, @@ -828,7 +835,7 @@ impl State { if let Some(ended) = &residency { self.residency .get_or_insert_with(Residency::default) - .join_encoder(ended, kind == EncoderKind::Compute); + .join_encoder_heaps(ended, kind == EncoderKind::Compute); } let (event_waits_before, event_signals_before) = self.batches.events(); self.ended.push(EncoderRecord { @@ -1003,6 +1010,60 @@ impl State { } } + /// Its residency, with the resources of its ended encoders not joined into it yet joined, in + /// the order they ended, each counted (`WorkCounts::resident_resources_joined`): what its + /// work reads. Joined at the first read after they ended, it holds what it would hold had + /// each joined as it ended, in the same order: the textures made in its heaps since join + /// after them ([`sync_heaps`](Self::sync_heaps)), and an encoder encoded again joins first + /// (`reencode.rs`). + pub(super) fn joined_residency(&mut self, counts: &Counters) -> Option<&mut Residency> { + let residency = self.residency.as_mut()?; + for record in &self.ended[self.joined..] { + if let Some(ended) = &record.residency { + let compute = record.kind == EncoderKind::Compute; + let joined = residency.join_encoder_resources(ended, compute); + if joined > 0 { + counts.resident_resources_joined(joined as u64); + } + } + } + self.joined = self.ended.len(); + Some(residency) + } + + /// Make resident the textures made in its heaps since (`Residency::sync_heaps`): its ended + /// encoders' resources joined first where it finds any + /// ([`joined_residency`](Self::joined_residency)), so they lie where they would have. + fn sync_heaps(&mut self, counts: &Counters) { + let Some(residency) = &mut self.residency else { + return; + }; + let made = residency.heap_textures(); + if made.is_empty() { + return; + } + if let Some(residency) = self.joined_residency(counts) { + drop(residency.join_heap_textures(made)); + } + } + + /// What its next compute or render (`render`) encoder starts with (`Residency::shadows`): + /// the shadowed textures its ended encoders made resident, those its residency joined and + /// those it has yet to, in the order they were made resident. + fn inherited(&mut self, render: bool) -> Residency { + let Some(residency) = &mut self.residency else { + return Residency::default(); + }; + let mut shadows = residency.shadows(render); + for record in &mut self.ended[self.joined..] { + if let Some(ended) = &mut record.residency { + let compute = record.kind == EncoderKind::Compute; + ended.shadows_onto(&mut shadows, render, compute); + } + } + shadows + } + /// Let go of what its ended encoders' commands use, as it completes: their keys, and what /// they made resident, for the caller to release without this lock. fn let_go_of_uses(&mut self) -> Vec { @@ -1087,7 +1148,7 @@ impl State { let live = device.shared().live_buffers.table(device)?; let set = live.set(); let mut beyond: Vec = self.root_ranges.iter().copied().collect(); - if let Some(residency) = &self.residency { + if let Some(residency) = self.joined_residency(&device.shared().counts) { beyond.extend(residency.resident_ranges()); } beyond.retain(|range| !set.holds(range)); @@ -1873,6 +1934,7 @@ impl CommandBuffer { used_heaps: Vec::new(), holds: Vec::new(), residency: None, + joined: 0, ended: Vec::new(), root_tables: Vec::new(), root_ranges: HashSet::new(), @@ -2097,17 +2159,15 @@ impl CommandBuffer { /// the heaps they used made since included. pub(super) fn inherited_residency(&self, render: bool) -> Residency { let mut state = self.state(); - let Some(residency) = &mut state.residency else { - return Residency::default(); - }; - residency.sync_heaps(); - residency.shadows(render) + state.sync_heaps(&self.0.device.shared().counts); + state.inherited(render) } /// What its ended encoders made resident, every encoder's joined (`residency.rs`): what the /// work its commit and host steps record resolves and binds against. pub(super) fn residency(&self) -> Result { - let residency = self.state().residency.clone().unwrap_or_default(); + let counts = &self.0.device.shared().counts; + let residency = (self.state().joined_residency(counts).cloned()).unwrap_or_default(); // With the device's live buffers, which an address in no resource made resident // resolves against (`live_buffers.rs`): a host step's, the command buffer holds until it // completes. @@ -2814,9 +2874,7 @@ impl CommandBuffer { state.committing = true; // Its heaps reach every texture they hold now, for the work recorded below and by its // host steps. - if let Some(residency) = &mut state.residency { - residency.sync_heaps(); - } + state.sync_heaps(&self.0.device.shared().counts); let (segments, places): (Vec<(Deferred, bool)>, Vec) = state .recorded .iter() diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index d5b36ba9f..c79ce0592 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -175,6 +175,11 @@ impl CommandBufferShared { // What a refused splice held goes after the lock. let spliced_now = { let mut state = lock(&self.state); + // Its residency joins what the first encoding made resident before the encoding + // again takes that one's place (`State::joined_residency`). + if residency.is_some() { + state.joined_residency(counts); + } let spliced = state.splice_replay(at, replayed, residency); if let (Ok(()), Some(predication)) = (&spliced, predication) { state.predication.take_checks(predication); diff --git a/crates/metal2vulkan-runtime/src/residency.rs b/crates/metal2vulkan-runtime/src/residency.rs index 5980054ad..664260815 100644 --- a/crates/metal2vulkan-runtime/src/residency.rs +++ b/crates/metal2vulkan-runtime/src/residency.rs @@ -37,9 +37,13 @@ //! - **The command buffer's** (the coordinator's ruling of 2026-10-07). Metal's residency belongs //! to the command buffer: on an M3 Max, an indirect command buffer's compute command executed by //! one compute encoder wrote a buffer that only a later encoder's `useResource:` named, and one a -//! later blit filled. So each encoder, as it ends, joins what it made resident into its command -//! buffer's residency ([`Residency::join_encoder`]), and the commit makes resident the textures -//! made since in the heaps it holds (`sync_heaps`). The work recorded at the commit or by a host +//! later blit filled. So what each encoder made resident joins its command buffer's residency +//! ([`Residency::join_encoder`]): its heaps as it ends, and its resources where the command +//! buffer's own work first reads that residency after it ended (`State::joined_residency` in +//! `command_buffer/mod.rs`), each ended encoder's in the order they ended, so the residency +//! holds what it would had each joined as it ended, in the same order, and a command buffer whose +//! work never reads it joins none (`WorkCounts::resident_resources_joined`). The commit makes +//! resident the textures made since in the heaps it holds (`sync_heaps`). The work recorded at the commit or by a host //! step (an indirect command buffer's executions, compute and render, and an indirect dispatch //! the host reads) resolves and binds against that residency, every encoder's, made resident //! before the call or after it. A compute encoder's resources reach every render stage there, as @@ -125,6 +129,14 @@ pub(super) struct Residency { /// The tokens of the textures among `used`: a command's look at the textures made resident /// costs their count, not every resource's. textures: Vec, + /// The tokens of the shadowed textures (`shadow.rs`) among the first `textures_looked_at` of + /// `textures`, in the order they were made resident: what a command buffer's next encoder + /// starts with ([`shadows`](Self::shadows)) costs their count. Found where that is first + /// asked ([`find_shadowed`](Self::find_shadowed)), so making a texture resident reads + /// nothing of it, and each texture is looked at once. + shadowed: Vec, + /// How many of `textures` [`find_shadowed`](Self::find_shadowed) has looked at. + textures_looked_at: usize, /// The heaps the encoder used, each with the render stages it used it in and the number of /// the first of its textures not made resident yet (`Heap::textures_from`). heaps: Vec, @@ -278,6 +290,14 @@ impl Residency { /// resident resources. Those it first uses here (held as [`use_resource`](Self::use_resource) /// holds what it makes resident). A heap that made no texture since costs one lock. pub(super) fn sync_heaps(&mut self) -> Vec { + let made = self.heap_textures(); + self.join_heap_textures(made) + } + + /// The textures made in the heaps it used since it last looked, each with the render stages + /// it used its heap in: what [`sync_heaps`](Self::sync_heaps) makes resident. A heap that + /// made no texture since costs one lock. + pub(super) fn heap_textures(&mut self) -> Vec<(Texture, RenderStages)> { let mut made = Vec::new(); for used in &mut self.heaps { if used.heap.textures_made() == used.next { @@ -289,6 +309,12 @@ impl Residency { // The number it looks from on: what a later look reads. self.generation = next_generation(); } + made + } + + /// Make resident for reading `made`, the textures [`heap_textures`](Self::heap_textures) + /// found: those it first uses here. + pub(super) fn join_heap_textures(&mut self, made: Vec<(Texture, RenderStages)>) -> Vec { made.into_iter() .filter_map(|(texture, stages)| { self.join(Used::Texture(texture), ResourceUsage::READ, stages) @@ -302,15 +328,25 @@ impl Residency { /// none; a heap keeps the least number of a texture not made resident yet, so the commit's /// [`sync_heaps`](Self::sync_heaps) makes resident every texture made in it since. pub(super) fn join_encoder(&mut self, ended: &Residency, compute: bool) { - let reach = |stages: RenderStages| match compute { - true => every_render_stage(), - false => stages, - }; + self.join_encoder_resources(ended, compute); + self.join_encoder_heaps(ended, compute); + } + + /// The resources of [`join_encoder`](Self::join_encoder): each with its usage, in the render + /// stages it named, or every render stage for a compute encoder's. How many `ended` holds. + pub(super) fn join_encoder_resources(&mut self, ended: &Residency, compute: bool) -> usize { for (used, usage, stages) in &ended.used { - self.join(used.clone(), *usage, reach(*stages)); + self.join(used.clone(), *usage, reached(*stages, compute)); } + ended.used.len() + } + + /// The heaps of [`join_encoder`](Self::join_encoder): each in the render stages it named, or + /// every render stage for a compute encoder's, keeping the least number of a texture not made + /// resident yet. + pub(super) fn join_encoder_heaps(&mut self, ended: &Residency, compute: bool) { for heap in &ended.heaps { - let stages = reach(heap.stages); + let stages = reached(heap.stages, compute); match self.heap_use(&heap.heap) { Some(had) => { had.stages = had.stages.union(stages); @@ -395,7 +431,7 @@ impl Residency { return None; } let token = u32::try_from(self.used.len()).expect("fewer than 2^32 resources resident"); - match used { + match &used { Used::IndirectCommandBuffer(_) => self.indirect.push(token), Used::Texture(_) => self.textures.push(token), Used::Buffer(_) | Used::Heap { .. } => {} @@ -526,19 +562,43 @@ impl Residency { /// command buffer's residency (the module docs): the shadowed textures (`shadow.rs`) its /// ended encoders made resident, each with its usage and, for a render encoder, its render /// stages (a compute encoder names none). - pub(super) fn shadows(&self, render: bool) -> Residency { + pub(super) fn shadows(&mut self, render: bool) -> Residency { let mut shadows = Residency::default(); - // Its textures alone, in the order they were made resident. - let shadowed = - (self.resident_textures()).filter(|(texture, ..)| texture.shadow().is_some()); - for (texture, usage, stages) in shadowed { + self.shadows_onto(&mut shadows, render, false); + shadows + } + + /// Look for the shadowed textures (`shadowed`) among those made resident since it last + /// looked, in the order they were made resident. + fn find_shadowed(&mut self) { + for &token in &self.textures[self.textures_looked_at..] { + if let Some((Used::Texture(texture), ..)) = self.used.get(token as usize) { + if texture.shadow().is_some() { + self.shadowed.push(token); + } + } + } + self.textures_looked_at = self.textures.len(); + } + + /// Join onto `shadows`, what a command buffer's next compute or render (`render`) encoder + /// starts with ([`shadows`](Self::shadows)), the shadowed textures this residency holds, in the + /// order they were made resident: this an ended encoder's not joined into its command + /// buffer's yet, a compute encoder's (`compute`) reaching every render stage, as it would + /// there. + pub(super) fn shadows_onto(&mut self, shadows: &mut Residency, render: bool, compute: bool) { + self.find_shadowed(); + for &token in &self.shadowed { + let Some((Used::Texture(texture), usage, stages)) = self.used.get(token as usize) + else { + continue; + }; let stages = match render { - true => stages, + true => reached(*stages, compute), false => RenderStages::empty(), }; - shadows.join(Used::Texture(texture.clone()), usage, stages); + shadows.join(Used::Texture(texture.clone()), *usage, stages); } - shadows } /// The textures made resident, each with its usage and render stages. @@ -590,6 +650,15 @@ impl Residency { } // Two are equal where they are one resource: a heap by the heap alone. +/// The render stages a resource made resident in `stages` reaches in its command buffer's +/// residency: every one for a compute encoder's (`compute`), which names none. +fn reached(stages: RenderStages, compute: bool) -> RenderStages { + match compute { + true => every_render_stage(), + false => stages, + } +} + impl PartialEq for Used { fn eq(&self, other: &Used) -> bool { match (self, other) { diff --git a/crates/metal2vulkan-runtime/src/tests/joined_residency.rs b/crates/metal2vulkan-runtime/src/tests/joined_residency.rs new file mode 100644 index 000000000..19c9c1978 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/joined_residency.rs @@ -0,0 +1,140 @@ +//! A command buffer's residency joins the resources its ended encoders made resident where its +//! own work reads it (`command_buffer::State::joined_residency`), never as an encoder ends: the +//! encoders opened after, their shadowed textures inherited (none here), join none, a read joins +//! each ended encoder's resources once, in the order they ended, and a read after joins none +//! more (`WorkCounts::resident_resources_joined`). The shadowed textures (`shadow.rs`) an ended +//! encoder made resident reach the encoders opened after, whether its resources are joined yet or +//! not, each once and in the order they were made resident; making a texture resident reads +//! nothing of it, the open that first asks looks at each once (`Residency::find_shadowed`). +//! +//! 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. + +use crate::{ + Buffer, CommandBufferStatus, Device, DeviceKind, DeviceOptions, ResourceOptions, Texture, + TextureDescriptor, +}; +use metal2vulkan::metal::{PixelFormat, ResourceUsage, TextureUsage}; + +/// The device the cfg selects: a CPU device under `m2v_cpu_icd`, else a GPU. +fn device() -> Device { + let options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + ..DeviceOptions::default() + }; + Device::system_default_with(&options).unwrap() +} + +/// Two compute encoders make 16 buffers resident each, 8 of them the same: ending them and +/// opening the second joins nothing; the command buffer's residency, read, joins all 32 and holds +/// the 24 buffers once each, the first encoder's first; read again, it joins none. +#[test] +fn ended_encoders_join_their_command_buffer_s_residency_where_it_is_read() { + let device = device(); + let queue = device.new_command_queue().unwrap(); + let buffers: Vec = (0..24) + .map(|_| device.new_buffer(256, ResourceOptions::default()).unwrap()) + .collect(); + let joined = || device.work_counts().resident_resources_joined; + let before = joined(); + let command_buffer = queue.command_buffer().unwrap(); + for some in [&buffers[..16], &buffers[8..]] { + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + let resources: Vec<_> = some.iter().map(|buffer| buffer.as_resource()).collect(); + encoder + .use_resources(&resources, ResourceUsage::READ) + .unwrap(); + encoder.end_encoding().unwrap(); + } + assert_eq!(joined() - before, 0, "an encoder's end or open joined"); + let residency = command_buffer.residency().unwrap(); + assert_eq!(joined() - before, 32); + let held: Vec<&Buffer> = (residency.resources()) + .filter_map(|used| match used { + crate::residency::Used::Buffer(buffer) => Some(buffer), + _ => None, + }) + .collect(); + assert!( + held.iter().copied().eq(buffers.iter()), + "each buffer once, in the order made resident" + ); + drop(command_buffer.residency().unwrap()); + assert_eq!(joined() - before, 32, "a second read joined again"); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed().unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); +} + +/// A texture over a `Shared` buffer's bytes in rows of 352 bytes, not a multiple of 256, so a +/// shadow wherever the device lays no image's rows so (`shadow_carried_read.rs`): its own buffer, +/// held with it. +fn shadowed(device: &Device) -> (Buffer, Texture) { + let buffer = device + .new_buffer(352 * 5, ResourceOptions::shared()) + .unwrap(); + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 68, 5, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&descriptor, 0, 352).unwrap(); + assert!(texture.shadow().is_some(), "the device took no shadow"); + (buffer, texture) +} + +/// Three compute encoders of one command buffer: the first makes a plain texture and a shadowed +/// one resident, the second another shadowed one and the first again, and the third, after a read +/// joined the first two into the command buffer's residency, the plain one. Each next encoder +/// starts with the shadowed textures alone, the first's first, whether the encoders before are +/// joined or not. +#[test] +fn shadowed_textures_made_resident_reach_the_next_encoders_in_order() { + let device = device(); + let queue = device.new_command_queue().unwrap(); + let ((_first_bytes, first), (_second_bytes, second)) = (shadowed(&device), shadowed(&device)); + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 4, 4, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::private(); + let plain = device.new_texture(&descriptor).unwrap(); + assert!(plain.shadow().is_none()); + let command_buffer = queue.command_buffer().unwrap(); + let inherited = || { + let residency = command_buffer.inherited_residency(false); + residency.textures().cloned().collect::>() + }; + let resident = |textures: &[&Texture]| { + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + let resources: Vec<_> = textures + .iter() + .map(|texture| texture.as_resource()) + .collect(); + encoder + .use_resources(&resources, ResourceUsage::READ) + .unwrap(); + encoder.end_encoding().unwrap(); + }; + resident(&[&plain, &first]); + assert_eq!(inherited(), [first.clone()], "after the first encoder"); + resident(&[&second, &first]); + assert_eq!( + inherited(), + [first.clone(), second.clone()], + "after the second encoder, neither joined" + ); + drop(command_buffer.residency().unwrap()); + resident(&[&plain]); + assert_eq!( + inherited(), + [first.clone(), second.clone()], + "after the third encoder, the first two joined" + ); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed().unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 442595ca8..65338f29e 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -168,6 +168,8 @@ mod inline_continues; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod inline_splits; mod interop; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod joined_residency; mod keeper; mod kept_barriers; #[cfg(any(m2v_gpu, m2v_cpu_icd))] diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index a56d2d58a..5629f0ebd 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -245,6 +245,7 @@ pub(crate) struct Counters { dispatch_shapes_found: AtomicU64, dispatch_used_resources_listed: AtomicU64, resident_textures_looked_at: AtomicU64, + resident_resources_joined: AtomicU64, heap_tables_worked_out: AtomicU64, argument_samplers_taken: AtomicU64, bind_views_worked_out: AtomicU64, @@ -1752,6 +1753,13 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } + /// `count` resources an ended encoder made resident were joined into its command buffer's + /// residency (`command_buffer::State::joined_residency`). + pub(crate) fn resident_resources_joined(&self, count: u64) { + self.resident_resources_joined + .fetch_add(count, Ordering::Relaxed); + } + /// A command's pipeline layout was read for the device's texture and sampler tables it binds /// (`heap_sets::HeapTables`, `texture_table`, `sampler_table`). pub(crate) fn heap_tables_worked_out(&self) { @@ -4334,6 +4342,13 @@ pub struct WorkCounts { /// texture handles after each change of what it made resident. None for a dispatch after which /// neither changed, however many textures it made resident. pub resident_textures_looked_at: u64, + /// Resources an ended compute or render encoder made resident, joined into its command + /// buffer's residency: at the first read of that residency after the encoder ended (the work + /// its commit or a host step records against every encoder's resources, its resident set, a + /// texture made in a heap it used since, an encoder encoded again), each of the encoder's + /// resources once. None for a command buffer whose work never reads it, however many + /// resources its encoders made resident. + pub resident_resources_joined: u64, /// Reads of a pipeline layout for the device's texture and sampler tables its commands bind /// (`heap_sets.rs`): one per variant for compute dispatches, at its first (`HeapTables`); one /// per table looked for at each draw and tile dispatch (`heap_sets::texture_table`, @@ -5749,6 +5764,7 @@ impl Device { .load(Ordering::Relaxed), resident_textures_looked_at: (counters.resident_textures_looked_at) .load(Ordering::Relaxed), + resident_resources_joined: (counters.resident_resources_joined).load(Ordering::Relaxed), heap_tables_worked_out: counters.heap_tables_worked_out.load(Ordering::Relaxed), argument_samplers_taken: counters.argument_samplers_taken.load(Ordering::Relaxed), bind_views_worked_out: counters.bind_views_worked_out.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 2d28a80b0..64018db9e 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2840,6 +2840,7 @@ field metal2vulkan-runtime::WorkCounts.replay_logs_kept pub replay_logs_kept: u6 field metal2vulkan-runtime::WorkCounts.replay_tables_pointed pub replay_tables_pointed: u64 field metal2vulkan-runtime::WorkCounts.requirement_images_made pub requirement_images_made: u64 field metal2vulkan-runtime::WorkCounts.requirement_limits_asked pub requirement_limits_asked: u64 +field metal2vulkan-runtime::WorkCounts.resident_resources_joined pub resident_resources_joined: u64 field metal2vulkan-runtime::WorkCounts.resident_textures_looked_at pub resident_textures_looked_at: u64 field metal2vulkan-runtime::WorkCounts.residual_form_draws pub residual_form_draws: u64 field metal2vulkan-runtime::WorkCounts.residual_form_makings pub residual_form_makings: u64