From 565fbd9153eae8485a12a66b2ef464868c7b04cc Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 3 Nov 2026 04:24:39 -0800 Subject: [PATCH] Run unchanged indirect commands from kept recordings, chunk by chunk An execution of an indirect command buffer read, decoded and recorded every command again at every commit, so an unchanged execution of 16384 draws cost about 44 ms of commit on the M3 Max and 64 ms on the RTX 5080 laptop, where Metal's costs 2 ms. A profile of the render case put a third of it in the records' decode and moves and the rest in recording the draws. Now an execution of commands the CPU encoded records them in chunks of 256 (kept_commands.rs). A render chunk records into a secondary of its own, begun for simultaneous use against the instance's compatible pass, through an encoder over a core of its own whose effects the pass's core takes (EncoderCore::capture, absorb); a compute chunk records as a segment of its own, behind a barrier from everything before. Each chunk takes its command pool, descriptor arena and uploads from a context of its own, lent to the command buffer while it records and held by every command buffer that runs it. A chunk whose recording is plain (every draw passes draw_again's keep test but for being replayed, no step outside its command buffer, nothing its command buffer alone holds, no released state) is kept on the buffer with what it was recorded from: the encoder's inputs (RenderKey, ComputeKey: the inherited state, the pass's compatible pass, shape, extent and sample positions, the encoder's state and scissors, the resident resources), each address its commands named and what it resolved to, and the no-copy moves. A later execution of the chunk under equal inputs, every address resolving as before, nothing detached and every held object alive, runs the kept command buffer and notes its uses, keys, holds and executions again (EncoderCore::run_kept), reading no record. Every CPU write of a command forgets its chunk under the lock the write takes; the buffer's first GPU write forgets them all; a recording from records written meanwhile is not kept. A chunk that is not plain records the rest of the range as before and is noted, so later executions of it record as before until a write reaches it. The buffer's per-command state moves to a map, so a buffer of commands never encoded holds nothing for them. WorkCounts::indirect_chunks_kept and indirect_commands_kept count the kept path. docs/FAST-PATHS.md's known gaps list the executions that still record every command at every commit. Verified on the M3 Max (MoltenVK 1.4.2), --cfg m2v_gpu, under the validation layer: runtime_lane::kept_commands, 5 tests: unchanged render commands run 3 kept chunks of 600 commands reading no record, into another target and twice in one pass; a command written again or reset records its chunk alone; a blit's reset runs no kept chunk and its commands draw nothing; another residency or range records again; compute commands the same, with a command written again and a blit reset. 446 of 448 tests of the 33 lanes that execute indirect commands pass; the two others (extended_range_blends half outputs, padded_loads loading pass) are among the MoltenVK reds the parent already has. clippy -D warnings, plain and --cfg m2v_gpu, for the runtime and validation crates; the runtime's kept_commands unit test; the translator's fast_paths, api_signatures and api_surface tests. Needs a RUNTIME_VERSION bump and a runtime-sources pin. (cherry picked from commit 21b9438ec5b8cbf7a1e79c5dfbf84cdad7b43d91) (cherry picked from commit 922caf3199378b029bafc201429f80b0d43bb048) --- .../src/argument_table.rs | 10 + .../src/command_buffer/mod.rs | 61 +++ crates/metal2vulkan-runtime/src/encoder.rs | 266 +++++++++- .../src/executed_commands.rs | 6 + .../src/indirect_command_buffer.rs | 184 ++++--- .../src/indirect_execute.rs | 49 +- .../src/indirect_execute/kept.rs | 197 +++++++ .../metal2vulkan-runtime/src/kept_commands.rs | 363 +++++++++++++ crates/metal2vulkan-runtime/src/lib.rs | 1 + crates/metal2vulkan-runtime/src/rebind.rs | 10 + crates/metal2vulkan-runtime/src/render.rs | 35 +- .../src/render/executions.rs | 72 ++- .../src/render/executions/kept.rs | 480 ++++++++++++++++++ crates/metal2vulkan-runtime/src/residency.rs | 13 + crates/metal2vulkan-runtime/src/retained.rs | 24 + crates/metal2vulkan-runtime/src/tracker.rs | 16 +- .../metal2vulkan-runtime/src/work_counts.rs | 18 + .../src/runtime_lane.rs | 4 + .../src/runtime_lane/execution_costs.rs | 324 ++++++++++++ .../src/runtime_lane/kept_commands.rs | 452 +++++++++++++++++ crates/metal2vulkan/tests/api_signatures.tsv | 2 + docs/FAST-PATHS.md | 13 + 22 files changed, 2497 insertions(+), 103 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/indirect_execute/kept.rs create mode 100644 crates/metal2vulkan-runtime/src/kept_commands.rs create mode 100644 crates/metal2vulkan-runtime/src/render/executions/kept.rs create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/execution_costs.rs create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/kept_commands.rs diff --git a/crates/metal2vulkan-runtime/src/argument_table.rs b/crates/metal2vulkan-runtime/src/argument_table.rs index 2aa865af1..dd637aba2 100644 --- a/crates/metal2vulkan-runtime/src/argument_table.rs +++ b/crates/metal2vulkan-runtime/src/argument_table.rs @@ -843,6 +843,16 @@ impl ArgumentTable { Ok(()) } + /// Whether it binds nothing: no buffer, function table, null table, texture, sampler or bytes. + pub(super) fn binds_nothing(&self) -> bool { + self.buffers.is_empty() + && self.function_tables.is_empty() + && self.null_tables.is_empty() + && self.textures.is_empty() + && self.samplers.is_empty() + && self.bytes.is_empty() + } + /// Whether a texture slot of `stage` that `interface`'s function statically uses holds a /// memoryless texture, a texture buffer's too. Plain Metal fails the command buffer of a /// command that runs such a function (`CommandBufferError::InvalidResource`), whether or not diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 9bfa05023..bd357e124 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -85,6 +85,7 @@ use super::gpu_pools::{IndexPool, PoolKind, PoolLease}; use super::gpu_time::{self, KernelTimes, Life, Placement, Stamped, Times}; use super::heap::Heap; use super::heap_sets::HeapUse; +use super::kept_commands::KeptContext; use super::live_buffers::LiveTable; use super::pipeline::budget::Urgency; use super::pipeline::kept::StepNumbers; @@ -552,6 +553,16 @@ pub(super) struct State { /// apart (`rerun.rs`): every `VkCommandBuffer` the command buffer hands out meanwhile comes /// from it, and goes back to it for the next run again. rerun_pool: Option>>, + /// The context of a chunk of an indirect command buffer's commands the commit records to keep + /// (`kept_commands.rs`), while it does: every `VkCommandBuffer` the command buffer hands out + /// meanwhile comes from its pool, begun for simultaneous use where it is a render pass's + /// secondary or a segment's primary, and every set and upload from its arenas; and how many + /// its pool had handed out when it was lent. + kept: Option<(Arc, usize)>, + /// How many times a command reached what the command buffer alone holds for its commands: its + /// execution status words, index pool and mesh records pool. A recording that reached them is + /// not kept (`kept_commands.rs`). + own_reached: u64, /// The ended encoders' recordings, in encoding order. recorded: Vec, /// The last ended encoder's last `VkCommandBuffer`, still recording: its batch's end goes @@ -1774,6 +1785,12 @@ impl State { } } + /// Whether a chunk's context is lent (`CommandBuffer::lend_kept`): the command buffers it + /// hands out are begun for simultaneous use. + pub(super) fn keeping(&self) -> bool { + self.kept.is_some() + } + /// The device address of the command buffer's execution status words, uploaded (all zero, /// `ExecutionStatus::initial`) when a command first reaches them; `None` on a device without /// device addresses. @@ -1790,6 +1807,7 @@ impl State { /// The command buffer's execution status words, uploaded (all zero, `ExecutionStatus::initial`) /// when a command first reaches them. pub(super) fn status_words(&mut self, device: &Device) -> Result { + self.own_reached += 1; if let Some(words) = &self.status_words { return Ok(words.clone()); } @@ -1809,6 +1827,7 @@ impl State { /// `CommandQueue::id`), leased from the device (`gpu_pools.rs`): the block's `VkBuffer` and /// bytes, the header's included. pub(super) fn index_pool(&mut self, device: &Device, queue: u64) -> Result { + self.own_reached += 1; if let Some((counter, block)) = &self.index_pool { return Ok(IndexPool::of(counter, block)); } @@ -1831,6 +1850,7 @@ impl State { device: &Device, queue: u64, ) -> Result<(vk::Buffer, u64), Error> { + self.own_reached += 1; if let Some(pool) = &self.mesh_pool { return Ok((pool.raw(), pool.bytes())); } @@ -1896,6 +1916,8 @@ impl CommandBuffer { committing: false, pool: None, rerun_pool: None, + kept: None, + own_reached: 0, recorded: Vec::new(), tail: None, folds: Vec::new(), @@ -2190,6 +2212,42 @@ impl CommandBuffer { Ok(residency.with_live(live)) } + /// The queue family of its queue's `VkQueue`. + pub(super) fn queue_family(&self) -> u32 { + let shared = self.0.device.shared(); + shared.queue_family_of(self.0.queue.vk_queue()) + } + + /// Lend `context` to the command buffer while the commit records a chunk to keep + /// (`State::kept`), its arenas taking every set and upload meanwhile; `None`: take back the + /// one lent, each `VkCommandBuffer` it handed out meanwhile ended there and counted as ended + /// among the command buffer's own (`CommandBufferShared::end_raw`), which no longer counts it. + pub(super) fn lend_kept(&self, context: Option<&Arc>) { + let mut state = self.state(); + state + .uploads + .lend(context.map(|context| Arc::clone(&context.uploads))); + state + .descriptors + .lend(context.map(|context| Arc::clone(&context.descriptors))); + let lent = match context { + Some(context) => state + .kept + .replace((Arc::clone(context), context.handed_out())), + None => state.kept.take(), + }; + if let (None, Some((context, handed))) = (context, lent) { + let ended = context.handed_out().saturating_sub(handed) as u64; + self.0.raws_ended.fetch_sub(ended, Ordering::Relaxed); + } + } + + /// How many times a command reached what the command buffer alone holds for its commands + /// (`State::own_reached`). + pub(super) fn own_reached(&self) -> u64 { + self.state().own_reached + } + /// An encoder's primary command buffer, from this command buffer's pool, made on first use: /// the encoder records into it at each call, on the program's thread. The caller holds /// `state` (the pool is externally synchronized). @@ -4116,6 +4174,9 @@ impl CommandBufferShared { state: &mut State, level: vk::CommandBufferLevel, ) -> Result { + if let Some((context, _)) = &state.kept { + return context.hand_out(level).map(|(raw, _)| raw); + } if let Some(pool) = &state.rerun_pool { return hand_out(&self.device, &mut lock(pool), level); } diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 2f2805ada..b7940a00a 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -43,6 +43,7 @@ use super::index_rewrite::{ self, CommandedList, GatherHeld, GatherRequest, GatherRuns, GatheredList, IndirectGatherRequest, RewriteRunRequest, }; +use super::kept_commands::KeptEffects; use super::noted_apart::{NotedApart, NotedInto}; use super::pending_dispatch::PendingDispatch; use super::pipeline::VariantObjects; @@ -240,6 +241,20 @@ pub(super) struct RecordedSegment { pub(super) faults: ReplayFaults, } +impl RecordedSegment { + /// `other`, recorded after it, joined into it: one segment of both. + pub(super) fn join(&mut self, other: RecordedSegment) { + self.raws.extend(other.raws); + self.summary.join(other.summary); + self.retained.join(other.retained); + self.executions.extend(other.executions); + self.keys.extend(other.keys); + self.taken.join(other.taken); + self.resident_misses = self.resident_misses.wrapping_add(other.resident_misses); + self.faults = ReplayFaults(self.faults.0 | other.faults.0); + } +} + /// The state every open encoder carries. pub(super) struct EncoderCore { open: OpenGuard, @@ -533,13 +548,17 @@ impl EncoderCore { /// A core of `command_buffer` over a new `VkCommandBuffer` of its pool, begun, that abandons /// nothing when dropped. fn segment_raw(command_buffer: &CommandBuffer, ordered: bool) -> Result { - let raw = { + let (raw, keeping) = { let mut state = command_buffer.state(); - command_buffer.allocate_raw(&mut state)? + (command_buffer.allocate_raw(&mut state)?, state.keeping()) }; let device = command_buffer.device().shared().vk(); - let begin = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); + // A chunk kept for later command buffers (`kept_commands.rs`) may run in several at once. + let submits = match keeping { + true => vk::CommandBufferUsageFlags::SIMULTANEOUS_USE, + false => vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT, + }; + let begin = vk::CommandBufferBeginInfo::default().flags(submits); // SAFETY: the command buffer was just allocated from the pool, and only this core // records it. unsafe { device.begin_command_buffer(raw, &begin) }.map_err(vulkan)?; @@ -548,7 +567,22 @@ impl EncoderCore { .shared() .counts .encoder_command_buffer_begun(Begun::Segment); - Ok(EncoderCore { + Ok(EncoderCore::over(command_buffer, raw, ordered)) + } + + /// A core that records apart for a segment of `command_buffer`, unordered (`kept_commands.rs`): + /// a render execution's chunk, its draws into a secondary of their own, which notes, holds and + /// counts apart from the segment's core until that core takes what it did + /// ([`absorb`](Self::absorb)). It has no `VkCommandBuffer` until a command records outside the + /// draws' secondaries; dropped, it abandons nothing. + pub(super) fn capture(command_buffer: &CommandBuffer) -> EncoderCore { + EncoderCore::over(command_buffer, vk::CommandBuffer::null(), false) + } + + /// A core of `command_buffer` over `raw`, begun, or none (null), recording nothing yet, that + /// abandons nothing when dropped. + fn over(command_buffer: &CommandBuffer, raw: vk::CommandBuffer, ordered: bool) -> EncoderCore { + EncoderCore { open: OpenGuard { command_buffer: command_buffer.clone(), ended: true, @@ -583,7 +617,7 @@ impl EncoderCore { replaying: crate::replay::is_replaying(), last_set_zero: LastSetZero::default(), _not_sync: PhantomData, - }) + } } /// The device. @@ -2468,6 +2502,226 @@ impl EncoderCore { faults: ReplayFaults::default(), }) } + + /// End a core of [`capture`](Self::capture): the gather runs left open recorded, and what it + /// recorded outside the draws' secondaries, if anything, ended. Refused (internal) where it + /// deferred work, held a render pass or used a shadowed texture, which no execution's chunk + /// does. + pub(super) fn finish_capture(mut self) -> Result { + if !self.segments.is_empty() || self.pass.is_some() || self.used_shadows() { + return Err(internal( + "a recording apart that deferred work, held a pass or used a shadowed texture", + )); + } + self.flush_gathers(); + if self.raw != vk::CommandBuffer::null() { + // SAFETY: as in `barrier`. + unsafe { self.open.command_buffer.end_raw(self.raw) }.map_err(vulkan)?; + self.ended.push(self.raw); + } + let EncoderCore { + ended, + uses, + retained, + executions, + keys, + taken, + holds, + heaps, + kept_leases, + attachment_shadows, + first_copies, + twin_writes, + fails_command_buffer, + faults, + resident_unheld, + .. + } = self; + Ok(Captured { + raws: ended, + summary: uses.finish(), + retained, + executions, + keys, + taken, + holds, + heaps, + kept_leases, + attachment_shadows, + first_copies, + twin_writes, + fails_command_buffer, + faults, + resident_unheld, + }) + } + + /// Take what a core of [`capture`](Self::capture) did, as if this core had done it (an + /// unordered one: a render pass's segment's): its uses noted, its holds, executions, keys, + /// pages and heaps; and what it recorded outside its draws' secondaries placed after what + /// this core recorded so far, between barriers from everything before and to everything + /// after, this core going on in a new command buffer. Refused where the current one does not + /// end or the new one cannot be begun. + pub(super) fn absorb(&mut self, captured: Captured) -> Result<(), Error> { + let Captured { + raws, + summary, + retained, + executions, + keys, + taken, + holds, + heaps, + kept_leases, + attachment_shadows, + first_copies, + twin_writes, + fails_command_buffer, + faults, + resident_unheld, + } = captured; + if !raws.is_empty() { + self.flush_gathers(); + self.barrier(Barrier::everything()); + if self.raw != vk::CommandBuffer::null() { + // SAFETY: as in `barrier`. + unsafe { self.open.command_buffer.end_raw(self.raw) }.map_err(vulkan)?; + self.ended.push(self.raw); + } + self.ended.extend(raws); + self.raw = self.continuation()?.0; + self.recorded = true; + self.barrier(Barrier::everything()); + } + self.uses.record(summary.stages(), summary.uses(), None); + self.retained.join(retained); + self.executions.extend(executions); + self.keys.extend(keys); + self.taken.join(taken); + self.holds.join(holds); + for heap in heaps { + if !self.heaps.contains(&heap) { + self.heaps.push(heap); + } + } + self.kept_leases.extend(kept_leases); + self.attachment_shadows.extend(attachment_shadows); + self.first_copies.extend(first_copies); + self.twin_writes.extend(twin_writes); + if self.fails_command_buffer.is_none() { + self.fails_command_buffer = fails_command_buffer; + } + if self.faults.is_none() { + self.faults = faults; + } + self.resident_unheld.extend(resident_unheld); + Ok(()) + } + + /// Do what a kept chunk's recording did (`kept_commands.rs`), which this core's command + /// buffer runs again: note its uses, those of keys it did not name as reached through the + /// resident set alone (`note_reaching`, which holds the pages of buffers over host pages and + /// names the rest, as its commands did); keep its keys; hold `held`, what it held, upgraded; + /// and add its execution records where the device keeps them. An unordered core's alone. + pub(super) fn run_kept( + &mut self, + effects: &KeptEffects, + held: Vec>, + ) -> Result<(), Error> { + let summary = &effects.summary; + let resident: BTreeSet = summary + .keys() + .filter(|key| !effects.named.contains(key)) + .collect(); + self.note_reaching(summary.stages(), (summary.uses(), &resident), None)?; + self.touch_keys(effects.keys.iter().copied()); + for object in held { + self.retain_shared(object); + } + if self.records_executions() { + self.executions.extend(effects.executions.iter().cloned()); + } + Ok(()) + } +} + +/// What a core of [`EncoderCore::capture`] did, its recording ended +/// ([`finish_capture`](EncoderCore::finish_capture)): what its segment's core takes +/// ([`absorb`](EncoderCore::absorb)), and, of a plain one, what a kept recording does again +/// (`kept_commands.rs`). +pub(super) struct Captured { + /// What it recorded outside the draws' secondaries, ended, in order. + raws: Vec, + pub(super) summary: Summary, + pub(super) retained: Retained, + pub(super) executions: Vec, + pub(super) keys: BTreeSet, + pub(super) taken: Taken, + holds: Holds, + heaps: Vec, + kept_leases: Vec, + attachment_shadows: Vec, + first_copies: Vec<(ResourceKey, u64)>, + twin_writes: Vec, + fails_command_buffer: Option, + faults: Option, + resident_unheld: Vec, +} + +impl Captured { + /// Whether it only noted uses, kept keys, held shared objects, recorded executions and took + /// pages of buffers over host pages, which a command buffer that runs its recording again + /// does again as it notes the uses ([`EncoderCore::run_kept`]): nothing recorded outside the + /// draws' secondaries, no heap reached, no shadowed texture's work, no failure or fault, no + /// detached buffer named and no rasterization-rate map taken. + pub(super) fn plain(&self) -> bool { + self.raws.is_empty() + && self.heaps.is_empty() + && self.kept_leases.is_empty() + && self.attachment_shadows.is_empty() + && self.first_copies.is_empty() + && self.twin_writes.is_empty() + && self.fails_command_buffer.is_none() + && self.faults.is_none() + && self.resident_unheld.is_empty() + && !self.taken.dead() + && self.taken.rate_map_id().is_none() + } + + /// A segment of what it recorded, then `raws` (a kept chunk's: `indirect_execute/kept.rs`), + /// with what it noted, held, executed, kept and took. Refused (internal) where it did more + /// than a compute chunk's kept recording does again ([`EncoderCore::run_kept`]): it reached + /// a heap, a shadowed texture's work or a rate map, or failed. + pub(super) fn into_segment( + self, + raws: Vec, + ) -> Result { + let more = !self.heaps.is_empty() + || !self.kept_leases.is_empty() + || !self.attachment_shadows.is_empty() + || !self.first_copies.is_empty() + || !self.twin_writes.is_empty() + || self.fails_command_buffer.is_some() + || self.faults.is_some() + || self.taken.rate_map_id().is_some(); + if more { + return Err(internal( + "a kept chunk's run that did more than its recording", + )); + } + let mut recorded = self.raws; + recorded.extend(raws); + Ok(RecordedSegment { + raws: recorded, + summary: self.summary, + retained: self.retained, + executions: self.executions, + keys: self.keys, + taken: self.taken, + resident_misses: 0, + faults: ReplayFaults::default(), + }) + } } /// A run of shadowed textures' copies in an encoder whose commands Metal leaves unordered diff --git a/crates/metal2vulkan-runtime/src/executed_commands.rs b/crates/metal2vulkan-runtime/src/executed_commands.rs index 04fca314d..4afee9568 100644 --- a/crates/metal2vulkan-runtime/src/executed_commands.rs +++ b/crates/metal2vulkan-runtime/src/executed_commands.rs @@ -102,6 +102,12 @@ impl CommandBuffer { /// Hand the handlers the facts `facts` gathers of an execution of `buffer` read at `read`, /// under `residency`, the command buffer's, where it has handlers; with no lock held. + /// Whether the command buffer has an executed-commands handler, which an execution reports + /// the commands it ran to ([`report_executed`](Self::report_executed)). + pub(crate) fn reports_executed(&self) -> bool { + !self.state().executed_handlers.is_empty() + } + pub(crate) fn report_executed( &self, buffer: &IndirectCommandBuffer, diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs index 45e121fcf..d7431e731 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs @@ -71,6 +71,7 @@ use super::device::lock; use super::error::{internal, invalid, Error, MemoryKind, Problem, RuntimeGap}; use super::families::GpuFamily; use super::indirect_execute::Unforeseen; +use super::kept_commands::{self, KeptChunk, KeptChunks}; use super::memory::MemoryClass; use super::pipeline::{ ComputePipelineState, ComputeProgram, RenderPipelineState, RenderProgram, RenderStateKind, @@ -625,7 +626,7 @@ impl Device { inheritance, size, options, - pipelines: Mutex::new(vec![None; size as usize]), + pipelines: Mutex::default(), gpu_written: AtomicBool::new(false), unforeseen: Mutex::new(Vec::new()), cpu_writes: AtomicU64::new(0), @@ -658,6 +659,39 @@ enum CommandState { Render(WeakRenderPipelineState, RenderProgram, IdStamp, Named), } +/// What the CPU left beside a buffer's records: the pipeline state it set on each command it +/// set one on (`CommandState`), by index, none for the rest, so a buffer of commands never +/// encoded holds nothing for them; and the kept recordings of its chunks (`kept_commands.rs`), +/// which each write of a command forgets. +#[derive(Default)] +struct Commands { + states: BTreeMap, + kept: KeptChunks, +} + +impl Commands { + /// The state the CPU set on command `index`. + fn state(&self, index: u32) -> Option { + self.states.get(&index).cloned() + } + + /// The states the CPU set on commands `range`, in order. + fn states_in(&self, range: Range) -> Vec { + self.states + .range(range) + .map(|(_, set)| set.clone()) + .collect() + } + + /// Set `set` as the state the CPU set on command `index` (none: none). + fn set(&mut self, index: u32, set: Option) { + match set { + Some(set) => self.states.insert(index, set), + None => self.states.remove(&index), + }; + } +} + /// The ID a state had when the CPU set it on a command, and the serial of its hold of the ID, /// which tells whether the state was the ID's last holder (`ResourceIds::released_pipeline`); /// and its `uniqueIdentifier`, which Metal's getter answers after the state's release. @@ -815,6 +849,13 @@ enum Unmatched { #[derive(Debug, Default)] pub(super) struct Released(Vec<(u32, u64, Unmatched)>); +impl Released { + /// Whether no command runs otherwise than Metal's may. + pub(super) fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + /// The bytes of the records of `size` commands, header included. fn storage_length(size: u32) -> u64 { COMMAND_BUFFER_HEADER_BYTES as u64 + u64::from(size) * COMMAND_BYTES as u64 @@ -979,9 +1020,9 @@ struct IcbShared { size: u32, /// The options asked for, the hazard tracking mode resolved. options: ResourceOptions, - /// The pipeline state the CPU set on each command (`CommandState`). Held while the CPU - /// writes a record, so writes are one at a time. - pipelines: Mutex>>, + /// The pipeline state the CPU set on each command, and the kept recordings of its chunks + /// ([`Commands`]). Held while the CPU writes a record, so writes are one at a time. + pipelines: Mutex, /// An encoder made the buffer resident for writing: the GPU may write its records from then /// on (`written_by_gpu`). Set, and read where it decides, under `unforeseen`'s lock. gpu_written: AtomicBool, @@ -1450,8 +1491,14 @@ impl IndirectCommandBuffer { Ok(read(&view)) } - /// Write `record` as command `index` (below the size). The caller holds `pipelines`. - fn write(&self, index: u32, record: &CommandRecord) -> Result<(), Error> { + /// Write `record` as command `index` (below the size), under `commands`, the caller's hold + /// of `pipelines`. + fn write( + &self, + commands: &mut Commands, + index: u32, + record: &CommandRecord, + ) -> Result<(), Error> { let mut bytes = [0; COMMAND_BYTES]; record .encode_into(&mut bytes) @@ -1464,14 +1511,16 @@ impl IndirectCommandBuffer { COMMAND_BYTES, ); } - self.wrote(); + self.wrote(commands, index..index + 1); Ok(()) } - /// Count a write of the CPU's ([`cpu_writes`](Self::cpu_writes)), made. The caller holds - /// `pipelines`. - fn wrote(&self) { + /// Count a write of the CPU's of commands `range` ([`cpu_writes`](Self::cpu_writes)), made, + /// and forget the kept recordings of the chunks they lie in (`kept_commands.rs`), under + /// `commands`, the caller's hold of `pipelines`. + fn wrote(&self, commands: &mut Commands, range: Range) { self.0.cpu_writes.fetch_add(1, Ordering::Release); + commands.kept.wrote(range); } /// The CPU's writes of the records, and of the slots past them, so far: setters, resets and @@ -1486,12 +1535,12 @@ impl IndirectCommandBuffer { /// Reset commands `range` (inside the size). fn reset_commands(&self, range: Range) -> Result<(), Error> { - let mut pipelines = lock(&self.0.pipelines); + let mut commands = lock(&self.0.pipelines); for index in range.clone() { - self.write(index, &CommandRecord::default())?; - pipelines[index as usize] = None; + self.write(&mut commands, index, &CommandRecord::default())?; + commands.set(index, None); } - self.clear_overflow(range) + self.clear_overflow(&mut commands, range) } /// `range` as commands, refused unless it starts below the size and ends at or before it, as @@ -1677,7 +1726,7 @@ impl IndirectCommandBuffer { /// setter writes its field, the rest of the record as the GPU and the CPU left it /// (`CommandRecord::write_field`); then what the record holds joins what its records may. fn edit(&self, index: u32, field: RecordField, set: Option) -> Result<(), Error> { - let mut pipelines = lock(&self.0.pipelines); + let mut commands = lock(&self.0.pipelines); let mut bytes = self.record_now(index)?; let written = CommandRecord::write_field(&mut bytes, field).map_err(|error| match error { @@ -1696,12 +1745,11 @@ impl IndirectCommandBuffer { written.len(), ); } - self.wrote(); - let pipeline = &mut pipelines[index as usize]; + self.wrote(&mut commands, index..index + 1); if let Some(set) = set { - *pipeline = Some(set); + commands.set(index, Some(set)); } - let named = pipeline.as_ref().map(CommandState::named); + let named = commands.states.get(&index).map(CommandState::named); let writes = RecordView::new(&bytes).map_err(|_| undecodable())?.writes(); self.0.written.add_record(writes, named); Ok(()) @@ -1715,11 +1763,13 @@ impl IndirectCommandBuffer { index: u32, reset: impl FnOnce(&mut CommandRecord, &mut Option), ) -> Result<(), Error> { - let mut pipelines = lock(&self.0.pipelines); + let mut commands = lock(&self.0.pipelines); let mut record = self.record(index)?; - reset(&mut record, &mut pipelines[index as usize]); - self.write(index, &record)?; - self.clear_overflow(index..index + 1) + let mut set = commands.states.remove(&index); + reset(&mut record, &mut set); + commands.set(index, set); + self.write(&mut commands, index, &record)?; + self.clear_overflow(&mut commands, index..index + 1) } /// Set `set`'s buffer on command `index`, for `call`, at the buffer's address plus the offset's @@ -1775,8 +1825,8 @@ impl IndirectCommandBuffer { // Past the slots the record holds no function binds a buffer (Metal's argument tables // hold 31): plain Metal keeps it for its private getters, and so does the overflow. if slot >= RECORD_BUFFERS { - let _writing = lock(&self.0.pipelines); - return self.write_overflow(index, stage, slot, Some(binding)); + let mut commands = lock(&self.0.pipelines); + return self.write_overflow(&mut commands, index, stage, slot, Some(binding)); } let field = RecordField::Buffer { stage, @@ -1867,9 +1917,11 @@ impl IndirectCommandBuffer { } /// Write `binding` (none: unset) at `slot` of `stage` of command `index`, past the record's - /// slots and below the descriptor's count. The caller holds `pipelines`. + /// slots and below the descriptor's count, under `commands`, the caller's hold of + /// `pipelines`. fn write_overflow( &self, + commands: &mut Commands, index: u32, stage: BufferStage, slot: u32, @@ -1891,7 +1943,7 @@ impl IndirectCommandBuffer { bytes[..8].copy_from_slice(&address.to_le_bytes()); bytes[8..].copy_from_slice(&stride.to_le_bytes()); self.write_overflow_at(at, &bytes)?; - self.wrote(); + self.wrote(commands, index..index + 1); Ok(()) } @@ -1974,8 +2026,9 @@ impl IndirectCommandBuffer { } /// Clear the slots past the record's of commands `range`, as a CPU reset does: all but - /// their dispatch words ([`Overflow::cpu_reset_bytes`]). The caller holds `pipelines`. - fn clear_overflow(&self, range: Range) -> Result<(), Error> { + /// their dispatch words ([`Overflow::cpu_reset_bytes`]), under `commands`, the caller's hold + /// of `pipelines`. + fn clear_overflow(&self, commands: &mut Commands, range: Range) -> Result<(), Error> { let Some(overflow) = self.0.overflow.as_ref() else { return Ok(()); }; @@ -1983,7 +2036,7 @@ impl IndirectCommandBuffer { .storage .contents() .ok_or_else(|| internal("an indirect command buffer's overflow is not mapped"))?; - for index in range { + for index in range.clone() { let bytes = overflow.cpu_reset_bytes(index); // SAFETY: as `write_overflow`'s; `bytes` lies inside the overflow. unsafe { @@ -1994,7 +2047,7 @@ impl IndirectCommandBuffer { ); } } - self.wrote(); + self.wrote(commands, range); Ok(()) } @@ -2142,9 +2195,9 @@ impl IndirectCommandBuffer { return; } let sets: Vec> = { - let pipelines = lock(&self.0.pipelines); + let commands = lock(&self.0.pipelines); held.iter() - .map(|&(index, _)| pipelines.get(index as usize).cloned().flatten()) + .map(|&(index, _)| commands.state(index)) .collect() }; let read = held @@ -2215,14 +2268,14 @@ impl IndirectCommandBuffer { &self, index: u32, ) -> Result<(Option, Option, Option), Error> { - let pipelines = lock(&self.0.pipelines); + let commands = lock(&self.0.pipelines); let (reported, runs) = self.read_record(index, |view| { ( view.pipeline(), view.pipeline().or(view.retained_pipeline()), ) })?; - Ok((reported, runs, pipelines[index as usize].clone())) + Ok((reported, runs, commands.state(index))) } /// What [`commands`](Self::commands) reads of compute command `index`'s pipeline state @@ -2374,6 +2427,35 @@ impl IndirectCommandBuffer { Ok(range.start as u32..range.end as u32) } + /// The kept recordings of the chunks of commands `range` (inside the size), in order, `None` + /// for a chunk none is kept of (`kept_commands.rs`); whether an execution last recorded one of + /// them otherwise than plainly; and the CPU's writes so far ([`cpu_writes`](Self::cpu_writes)), + /// read under the same lock. + pub(super) fn kept_chunks( + &self, + range: Range, + ) -> (Vec>>, bool, u64) { + let commands = lock(&self.0.pipelines); + let kept = kept_commands::chunks(range.clone()) + .map(|(chunk, _)| commands.kept.get(chunk)) + .collect(); + (kept, commands.kept.stepped_in(range), self.cpu_writes()) + } + + /// Keep `kept`, the recording of chunk `chunk` from its records as the CPU's writes `read_at` + /// left them, or (`None`) note that it was not plain: only where no write came since and the + /// GPU may not write the records. + pub(super) fn keep_chunk(&self, chunk: u32, kept: Option>, read_at: u64) { + let mut commands = lock(&self.0.pipelines); + if self.cpu_writes() != read_at || self.gpu_written() { + return; + } + match kept { + Some(kept) => commands.kept.keep(chunk, kept), + None => commands.kept.stepped(chunk), + } + } + /// The records' buffer: what an encoder makes resident for the buffer, and where a function's /// command encoders write (`gpu_resource_id`). pub(super) fn storage(&self) -> &Buffer { @@ -2402,6 +2484,9 @@ impl IndirectCommandBuffer { if pending.is_empty() { watched.clear(); self.0.gpu_written.store(true, Ordering::Release); + drop(watched); + // No execution reads the CPU's records at commit from now on. + lock(&self.0.pipelines).kept.clear(); return; } pending @@ -2434,12 +2519,7 @@ impl IndirectCommandBuffer { /// them as Metal's copied records do (`released_programs.rs`). pub(super) fn keep_copied(&self, source: &IndirectCommandBuffer, range: Range) { let mut copied = lock(&source.0.kept).clone(); - let sets: Vec = { - let pipelines = lock(&source.0.pipelines); - range - .filter_map(|index| pipelines.get(index as usize).cloned().flatten()) - .collect() - }; + let sets: Vec = { lock(&source.0.pipelines).states_in(range) }; // Upgraded with no lock of either buffer held: a state dropped here releases its ID. for (stamp, program) in sets.iter().filter_map(CommandState::kept) { copied.keep(stamp.id, stamp.serial, program); @@ -2544,12 +2624,7 @@ impl IndirectCommandBuffer { if kept.is_empty() { return Some(states); } - let sets: Vec = { - let pipelines = lock(&self.0.pipelines); - range - .filter_map(|index| pipelines.get(index as usize).cloned().flatten()) - .collect() - }; + let sets: Vec = { lock(&self.0.pipelines).states_in(range) }; // Upgraded with no lock of the buffer held: a state dropped here releases its ID. let set_live = sets .iter() @@ -2831,9 +2906,9 @@ impl IndirectCommandBuffer { .shared() .counts .indirect_records_read(range.len() as u64); - let pipelines = lock(&self.0.pipelines); + let commands = lock(&self.0.pipelines); range - .map(|index| Ok((self.record(index)?, pipelines[index as usize].clone()))) + .map(|index| Ok((self.record(index)?, commands.state(index)))) .collect() } @@ -2916,12 +2991,7 @@ impl IndirectCommandBuffer { /// (`name_state`), which an execution the GPU alone runs, by the states alive at its commit /// (`gpu_execute.rs`), does not hold. pub(super) fn sets_a_released_state(&self, range: Range) -> bool { - let sets: Vec = { - let pipelines = lock(&self.0.pipelines); - range - .filter_map(|index| pipelines.get(index as usize).cloned().flatten()) - .collect() - }; + let sets: Vec = { lock(&self.0.pipelines).states_in(range) }; // Upgraded with no lock of the buffer held: a state dropped here releases its ID. sets.iter().any(CommandState::released) } @@ -2935,10 +3005,10 @@ impl IndirectCommandBuffer { of: &Of, ) -> (Vec>, Released) { let sets: Vec> = { - let pipelines = lock(&self.0.pipelines); + let commands = lock(&self.0.pipelines); (start..) .take(records.len()) - .map(|index| pipelines.get(index as usize).cloned().flatten()) + .map(|index| commands.state(index)) .collect() }; let mut unmatched = Vec::new(); diff --git a/crates/metal2vulkan-runtime/src/indirect_execute.rs b/crates/metal2vulkan-runtime/src/indirect_execute.rs index 51ebc3476..620fc4173 100644 --- a/crates/metal2vulkan-runtime/src/indirect_execute.rs +++ b/crates/metal2vulkan-runtime/src/indirect_execute.rs @@ -81,6 +81,8 @@ //! serial encoder's where their uses meet; a concurrent one's not at all), and a command with //! its barrier set runs after every earlier command of the segment. +mod kept; + use super::argument_table::ArgumentTable; use super::buffer::Buffer; use super::command_buffer::CommandBuffer; @@ -321,20 +323,25 @@ impl Execute { command_buffer: &CommandBuffer, states: Option<&[ComputePipelineState]>, ) -> Result { - let mut core = EncoderCore::segment(command_buffer, self.ordered)?; // Its host step inside a block of command predication that skips runs nothing. if states.is_some() && self.gate.as_ref().is_some_and(HostGate::skips) { - return core.end_segment(); + return EncoderCore::segment(command_buffer, self.ordered)?.end_segment(); } - let max_length = max_length(&core); + // Every encoder's resident resources, as the command buffer's are at the commit. + let residency = command_buffer.residency()?.kernel(); + // Commands the CPU encoded, which their chunks' kept recordings may run (`kept.rs`). + if states.is_none() { + if let Some(keeping) = self.keeping(command_buffer, &residency) { + return self.record_kept(command_buffer, &residency, keeping); + } + } + let mut core = EncoderCore::segment(command_buffer, self.ordered)?; // The host step's commands take the large-buffer form, whose variants `settle` made. let forms = match states { Some(_) => BufferForms::Large, None => BufferForms::Bound, }; let (commands, faults) = self.commands(states)?; - // Every encoder's resident resources, as the command buffer's are at the commit. - let residency = command_buffer.residency()?.kernel(); // What the commands run, for the command buffer's handlers (`executed_commands.rs`). let read = match states { Some(_) => RecordsRead::HostStep, @@ -357,15 +364,34 @@ impl Execute { (commands, false) }); let mut misses = 0u32; + let commands = commands.iter().flatten(); + self.dispatch(&mut core, commands, (&residency, forms), &mut misses)?; + let mut segment = core.end_segment()?; + segment.resident_misses = misses; + segment.faults = faults; + Ok(segment) + } + + /// Record `commands`' dispatches through `core`, resolving against `residency`, the command + /// buffer's, their variants in `forms` ([`record`](Self::record)'s), each resident-set miss + /// counted in `misses`. A command's barrier orders it after the commands before it here. + fn dispatch<'a>( + &self, + core: &mut EncoderCore, + commands: impl IntoIterator, + (residency, forms): (&Residency, BufferForms), + misses: &mut u32, + ) -> Result<(), Error> { + let max_length = max_length(core); let mut ran = false; - for (record, own) in commands.iter().flatten() { + for (record, own) in commands { let Some((pipeline, dispatch)) = self.runnable(record, own.as_ref()) else { continue; }; if record.barrier && ran { core.barrier(Barrier::between_dispatches()); } - let bindings = self.bindings(record, max_length, &residency, &mut misses); + let bindings = self.bindings(record, max_length, residency, misses); // A stride past 32 bits that a stage-in layout of `MTLBufferLayoutStrideDynamic` // reads: Metal's answer is not measured, and the fetch's `u32` displacement cannot // place it. @@ -389,14 +415,11 @@ impl Execute { ) { return Err(refusal); } - let tables = bindings.tables(self, pipeline, record, &residency, forms)?; - record_dispatch(&mut core, &tables, CALL, dispatch)?; + let tables = bindings.tables(self, pipeline, record, residency, forms)?; + record_dispatch(core, &tables, CALL, dispatch)?; ran = true; } - let mut segment = core.end_segment()?; - segment.resident_misses = misses; - segment.faults = faults; - Ok(segment) + Ok(()) } /// Settle, on the thread that commits or flags the buffer, what the host step needs to diff --git a/crates/metal2vulkan-runtime/src/indirect_execute/kept.rs b/crates/metal2vulkan-runtime/src/indirect_execute/kept.rs new file mode 100644 index 000000000..966f24664 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/indirect_execute/kept.rs @@ -0,0 +1,197 @@ +//! An execution of compute commands the CPU encoded, recorded chunk by chunk so a later one runs +//! the chunks no write reached again (`kept_commands.rs`). +//! +//! - **Which executions.** One `commit` records from the CPU's records (not the host step), of a +//! range in the call, outside a block of command predication, with no check of the caller's, +//! no inherited table that binds anything, in a command buffer with no executed-commands handler +//! that is not encoded again after its commit; and no chunk of its range last recorded +//! otherwise than plainly. +//! - **The key.** A chunk is recorded from its records and from the inputs [`ComputeKey`] holds: +//! the inherited pipeline state, whether the encoder runs its dispatches in encoded order, and +//! the resources made resident (`Residency::kept_key`). A kept chunk runs again only under an +//! equal key. +//! - **Each chunk** runs its kept recording again, or records apart into a primary of its own, +//! as a segment of its own (`EncoderCore::segment`): after a barrier from everything before, +//! and with one to everything after, so it orders against nothing else of the execution's, as a +//! command's barrier at its start would. Its recording is plain where it noted no shadowed +//! texture's work, named no detached buffer, named no released state, recorded into one command +//! buffer, held only shared objects, and reached nothing its command buffer alone holds +//! (`CommandBuffer::own_reached`); a plain chunk is kept, any other noted, so later executions +//! of it record as before until a write reaches it. The execution's segment is its chunks', in +//! order. + +use super::{Execute, ExecutionRange}; +use crate::command_buffer::CommandBuffer; +use crate::encoder::{EncoderCore, RecordedSegment}; +use crate::error::Error; +use crate::indirect_command_buffer::Reader; +use crate::kept_commands::{self, KeptChunk, KeptContext, KeptEffects}; +use crate::pipeline::{BufferForms, ComputePipelineState}; +use crate::residency::Residency; +use crate::resource::ResourceKey; +use metal2vulkan::bind::indirect_commands::BufferStage; +use metal2vulkan::bind::{ReplayFaults, UsedResource}; +use std::ops::Range; +use std::sync::atomic::Ordering; +use std::sync::Arc; + +/// What a chunk of an execution's dispatches is recorded from beside its records (the module +/// docs). +#[derive(Clone, PartialEq)] +pub(super) struct ComputeKey { + pipeline: Option, + ordered: bool, + resident: (Vec, Vec), +} + +/// An execution that keeps its commands (the module docs): its key, its range's kept chunks in +/// order, and the CPU's writes of the buffer as they were looked up. +pub(super) struct Keeping { + key: ComputeKey, + kept: Vec>>, + read_at: u64, +} + +impl Execute { + /// Whether the execution keeps its commands (the module docs), recorded by `command_buffer` + /// against `residency`: its key and its chunks. + pub(super) fn keeping( + &self, + command_buffer: &CommandBuffer, + residency: &Residency, + ) -> Option { + let ExecutionRange::Fixed(range) = &self.range else { + return None; + }; + let inherited = self.icb.descriptor().inherit_buffers; + let keeps = !range.is_empty() + && !self.icb.gpu_written() + && self.check.is_none() + && self.gate.is_none() + && self.preprocess_gate.is_none() + && (!inherited || self.table.binds_nothing()) + && !crate::replay::is_replaying() + && !command_buffer.reports_executed(); + if !keeps { + return None; + } + let (kept, stepped, read_at) = self.icb.kept_chunks(range.clone()); + if stepped { + return None; + } + let key = ComputeKey { + pipeline: self.pipeline.clone(), + ordered: self.ordered, + resident: residency.kept_key(), + }; + Some(Keeping { key, kept, read_at }) + } + + /// Record the commands chunk by chunk into a segment of `command_buffer` (the module docs), + /// resolving against `residency`, the command buffer's: `record`'s, where the execution keeps + /// its commands (`keeping`). + pub(super) fn record_kept( + &self, + command_buffer: &CommandBuffer, + residency: &Residency, + keeping: Keeping, + ) -> Result { + let (range, faults) = self.range()?; + let Keeping { key, kept, read_at } = keeping; + // Counted before the records are read: a write meanwhile records it again. + self.read_at.store(read_at, Ordering::Release); + let counts = &command_buffer.device().shared().counts; + let mut parts = Vec::new(); + for ((chunk, covered), kept) in kept_commands::chunks(range).zip(kept) { + let again = kept.and_then(|kept| { + let held = kept.runs_again(command_buffer, (&key, &covered), residency)?; + Some((kept, held)) + }); + if let Some((kept, held)) = again { + let mut core = EncoderCore::capture(command_buffer); + core.run_kept(&kept.effects, held)?; + let raw = kept.raw; + let misses = kept.misses; + core.retain_shared(kept); + let mut part = core.finish_capture()?.into_segment(vec![raw])?; + part.resident_misses = misses; + counts.indirect_chunk_kept(u64::from(covered.end - covered.start)); + parts.push(part); + continue; + } + let context = KeptContext::new(command_buffer)?; + let reached = command_buffer.own_reached(); + command_buffer.lend_kept(Some(&context)); + let apart = self.record_apart(command_buffer, residency, covered.clone()); + command_buffer.lend_kept(None); + let (mut part, resolved, (moved, plain)) = apart?; + let held = part.retained.all_shared(); + let keeps = plain && command_buffer.own_reached() == reached && part.raws.len() == 1; + match (keeps, held) { + (true, Some(held)) => { + let effects = KeptEffects::new( + part.summary.clone(), + (part.keys.clone(), part.taken.named().clone()), + &held, + part.executions.clone(), + ); + let kept = KeptChunk::new( + (Arc::clone(&context), part.raws[0]), + covered, + Box::new(key.clone()), + (resolved, moved), + effects, + (part.resident_misses, ReplayFaults::default()), + ); + self.icb.keep_chunk(chunk, Some(Arc::new(kept)), read_at); + } + (true, None) | (false, _) => self.icb.keep_chunk(chunk, None, read_at), + } + part.retained.shared(context); + parts.push(part); + } + let mut parts = parts.into_iter(); + let mut segment = parts.next().unwrap_or_else(EncoderCore::unrecorded_segment); + for part in parts { + segment.join(part); + } + segment.faults = ReplayFaults(segment.faults.0 | faults.0); + Ok(segment) + } + + /// Record commands `covered` apart (the module docs) into a segment of `command_buffer`, + /// resolving against `residency`: the segment, the addresses they named and what they + /// resolved to, the no-copy buffers' moves before it read its records, and whether it is + /// plain but for what its command buffer alone holds. + fn record_apart( + &self, + command_buffer: &CommandBuffer, + residency: &Residency, + covered: Range, + ) -> Result<(RecordedSegment, Vec, (u64, bool)), Error> { + let moved = crate::buffer::host_cells_moved(); + let (commands, released) = self.icb.records(covered, Reader::Commit)?; + self.icb.degrade_released(&released); + let descriptor = *self.icb.descriptor(); + let addresses = commands + .iter() + .filter(|_| !descriptor.inherit_buffers) + .flat_map(|(record, _)| { + let bindings = record.bindings.buffers(BufferStage::Kernel); + let count = descriptor.max_kernel_buffer_bind_count; + (0..count).zip(bindings).filter_map(|(_, binding)| *binding) + }) + .filter(|binding| binding.names_buffer()) + .map(|binding| binding.address); + let resolved = kept_commands::resolutions(addresses, residency); + let mut core = EncoderCore::segment(command_buffer, self.ordered)?; + let mut misses = 0u32; + let forms = (residency, BufferForms::Bound); + self.dispatch(&mut core, commands.iter(), forms, &mut misses)?; + let shadows = core.used_shadows(); + let mut segment = core.end_segment()?; + segment.resident_misses = misses; + let plain = !shadows && !segment.taken.dead() && released.is_empty(); + Ok((segment, resolved, (moved, plain))) + } +} diff --git a/crates/metal2vulkan-runtime/src/kept_commands.rs b/crates/metal2vulkan-runtime/src/kept_commands.rs new file mode 100644 index 000000000..7b0ce83e4 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/kept_commands.rs @@ -0,0 +1,363 @@ +//! Recordings of an indirect command buffer's commands, kept from one execution to the next: +//! a command buffer that executes commands no write reached since an earlier one recorded them, +//! under the same inputs, runs that recording again and records nothing of them. +//! +//! - **By chunk.** The buffer's commands fall into chunks of [`CHUNK`], aligned on their indices. +//! An execution that may keep its commands (each encoder's rules: `render/executions.rs`, +//! `indirect_execute.rs`) records each chunk its range covers apart, a render chunk into a +//! secondary command buffer of the execution's render pass instance, a compute chunk into a +//! primary of its segment, from a pool, descriptor arena and upload arena of the chunk's own +//! ([`KeptContext`]), lent to the command buffer while it records the chunk and held by every +//! command buffer that runs the recording until it completes. A chunk whose recording is plain +//! (each encoder's rules: nothing of it records outside its command buffer, and nothing of it +//! reaches what the command buffer alone holds) is kept ([`KeptChunk`]): its command buffer, +//! begun for simultaneous use, the uses its commands noted, the keys they named, weak holds on +//! what they held, their execution records, and what it was recorded from (the encoder's +//! inputs, each address its commands named and what it resolved to, the no-copy buffers' +//! moves). +//! - **Run again.** A later execution of the chunk's commands under equal inputs, where every +//! address resolves as it did, nothing moved, nothing it named is detached and everything it +//! held lives, runs the kept command buffer: its command buffer notes the uses again, keeps the +//! keys, holds what the recording held and the chunk, and adds the execution records, as the +//! recording's own did, and counts it (`WorkCounts::indirect_chunks_kept`, +//! `indirect_commands_kept`). Its records are not read. +//! - **Forgotten** at the CPU's every write of one of the chunk's commands (a setter, a reset, a +//! slot past the record's), under the lock the write takes; for good at the buffer's first +//! GPU write (`IndirectCommandBuffer::written_by_gpu`), after which no execution reads the +//! CPU's records at commit; and where its inputs differ, its next recording replacing it. A +//! recording made from records the CPU wrote while it recorded them is not kept. What a +//! command buffer recorded from a kept chunk stays its own: a write after its commit has its +//! host step record the execution again from the records as they stand then, as before. + +use crate::command_buffer::{command_pool, hand_out, CommandBuffer}; +use crate::descriptor_arena::DescriptorArena; +use crate::device::{lock, Device}; +use crate::error::Error; +use crate::execution::Execution; +use crate::residency::Residency; +use crate::resource::ResourceKey; +use crate::spares::CommandPool; +use crate::tracker::Summary; +use crate::upload::Uploads; +use ash::vk; +use metal2vulkan::bind::ReplayFaults; +use std::any::Any; +use std::collections::{BTreeMap, BTreeSet}; +use std::ops::Range; +use std::sync::{Arc, Mutex, Weak}; + +/// The commands of a chunk: a render chunk's draws record into one secondary command buffer, a +/// compute chunk's dispatches into one primary. +pub(super) const CHUNK: u32 = 256; + +/// The chunks `range` falls into, in order: each chunk's index and the commands of `range` it +/// covers. +pub(super) fn chunks(range: Range) -> impl Iterator)> { + let mut start = range.start; + std::iter::from_fn(move || { + if start >= range.end { + return None; + } + let chunk = start / CHUNK; + let next = (u64::from(chunk) + 1) * u64::from(CHUNK); + let end = u32::try_from(next).map_or(range.end, |next| next.min(range.end)); + let covered = start..end; + start = end; + Some((chunk, covered)) + }) +} + +/// The chunks of `range`, as [`chunks`] gives them: their indices. +fn chunks_of(range: Range) -> Range { + match range.is_empty() { + true => 0..0, + false => range.start / CHUNK..(range.end - 1) / CHUNK + 1, + } +} + +/// What a chunk's recording takes its command buffers, sets and uploads from (the module docs): +/// lent to the command buffer that records the chunk while it does (`State::kept`), held by each +/// command buffer that runs what it recorded until it completes, and handed back to the device's +/// spares as the last hold goes. +pub(super) struct KeptContext { + device: Device, + /// Its queue family: its command buffers run on that family's queues alone. + pub(super) family: u32, + pool: Mutex>, + pub(super) uploads: Arc>, + pub(super) descriptors: Arc>, +} + +impl KeptContext { + /// A context for a recording of `command_buffer`'s, of its queue's family: a spare command + /// pool of the device's, or a new one. + pub(super) fn new(command_buffer: &CommandBuffer) -> Result, Error> { + let device = command_buffer.device(); + let family = command_buffer.queue_family(); + let pool = command_pool(device, family)?; + Ok(Arc::new(KeptContext { + device: device.clone(), + family, + pool: Mutex::new(Some(pool)), + uploads: Arc::new(Mutex::new(Uploads::new())), + descriptors: Arc::new(Mutex::new(DescriptorArena::default())), + })) + } + + /// A `VkCommandBuffer` of `level` from its pool (`command_buffer::hand_out`), and how many it + /// handed out so far, this one included. + pub(super) fn hand_out( + &self, + level: vk::CommandBufferLevel, + ) -> Result<(vk::CommandBuffer, usize), Error> { + let mut pool = lock(&self.pool); + let pool = pool + .as_mut() + .ok_or_else(|| crate::error::internal("a kept recording's pool given back"))?; + let raw = hand_out(&self.device, pool, level)?; + Ok((raw, pool.handed_out())) + } + + /// How many command buffers its pool handed out. + pub(super) fn handed_out(&self) -> usize { + lock(&self.pool).as_ref().map_or(0, CommandPool::handed_out) + } +} + +/// No command buffer holds it, so nothing of it is pending: its pool goes to the device's spares, +/// to be reset as it is taken again, and its descriptor pools too. +impl Drop for KeptContext { + fn drop(&mut self) { + let pool = lock(&self.pool).take(); + if let Some(pool) = pool { + let shared = self.device.shared(); + shared.spares.give_command_pool(shared, pool, false); + } + lock(&self.descriptors).give_back(); + } +} + +/// What a kept chunk's recording did to its encoder, which a command buffer that runs it again +/// does to its own (the module docs). +pub(super) struct KeptEffects { + /// The uses its commands noted, joined, in every stage they ran in. + pub(super) summary: Summary, + /// The keys its commands named and bound. + pub(super) keys: BTreeSet, + /// The keys its commands named for themselves, beside those they reached through the + /// resident set alone (`Taken`). + pub(super) named: BTreeSet, + /// What it held until its command buffer completed: weakly, so a kept chunk holds nothing a + /// program let go of. + held: Vec>, + /// Its execution records, where the device keeps them. + pub(super) executions: Vec, +} + +impl KeptEffects { + /// The effects of a recording that noted `summary`, kept `keys`, named `named`, held `held` + /// and recorded `executions`. + pub(super) fn new( + summary: Summary, + (keys, named): (BTreeSet, BTreeSet), + held: &[Arc], + executions: Vec, + ) -> KeptEffects { + KeptEffects { + summary, + keys, + named, + held: held.iter().map(Arc::downgrade).collect(), + executions, + } + } + + /// What it held, each upgraded; `None` where one went. + fn held(&self) -> Option>> { + self.held.iter().map(Weak::upgrade).collect() + } +} + +/// An address a kept chunk's commands named and the buffer it resolved to then (`None`: none). +pub(super) type Resolution = (u64, Option); + +/// `addresses`, a chunk's commands' (in any order, any repeated), each resolved against +/// `residency` as [`KeptChunk::runs_again`] resolves them again: one address of each buffer an +/// address lies inside of, where the buffer is no heap's (no other buffer holds its addresses, so +/// every address inside it resolves to it while that one does), and every other address, once. +pub(super) fn resolutions( + addresses: impl IntoIterator, + residency: &Residency, +) -> Vec { + let mut buffers = BTreeMap::new(); + let mut others = BTreeMap::new(); + for address in addresses { + if others.contains_key(&address) { + continue; + } + let resolved = residency.resolve(address); + match &resolved { + Some((buffer, offset)) if buffer.heap().is_none() && *offset < buffer.length() => { + buffers.entry(buffer.identity().key).or_insert(address); + } + Some(_) | None => { + let key = resolved.map(|(buffer, _)| buffer.identity().key); + others.insert(address, key); + } + } + } + let buffers = buffers + .into_iter() + .map(|(key, address)| (address, Some(key))); + buffers.chain(others).collect() +} + +/// A chunk's kept recording (the module docs). +pub(super) struct KeptChunk { + context: Arc, + /// Its command buffer, ended: a render chunk's secondary, a compute chunk's primary. + pub(super) raw: vk::CommandBuffer, + /// The buffer's commands it records. + pub(super) covered: Range, + /// The inputs its encoder recorded it from, which a later execution's must equal (each + /// encoder's own). + key: Box, + /// Each address its commands named, once, and what it resolved to. + resolved: Vec, + /// The no-copy buffers' moves when it was recorded (`buffer::host_cells_moved`). + moved: u64, + pub(super) effects: KeptEffects, + /// The resident-set misses and faults its recording found. + pub(super) misses: u32, + pub(super) faults: ReplayFaults, +} + +impl KeptChunk { + /// The kept recording `raw`, of `context`, of commands `covered`, under `key`, its addresses + /// `resolved` so, recorded while the no-copy buffers had moved `moved` times. + pub(super) fn new( + (context, raw): (Arc, vk::CommandBuffer), + covered: Range, + key: Box, + (resolved, moved): (Vec, u64), + effects: KeptEffects, + (misses, faults): (u32, ReplayFaults), + ) -> KeptChunk { + KeptChunk { + context, + raw, + covered, + key, + resolved, + moved, + effects, + misses, + faults, + } + } + + /// What a command buffer of `command_buffer`'s queue family that runs it again under `key`, + /// resolving against `residency`, holds of it: what its recording held, upgraded; `None` + /// where it may not run again (the module docs). + pub(super) fn runs_again( + &self, + command_buffer: &CommandBuffer, + (key, covered): (&K, &Range), + residency: &Residency, + ) -> Option>> { + let same = self.covered == *covered + && self.context.family == command_buffer.queue_family() + && self.key.downcast_ref::() == Some(key) + && self.moved == crate::buffer::host_cells_moved(); + if !same { + return None; + } + let resolves = self.resolved.iter().all(|&(address, key)| { + residency.resolve(address).map(|(b, _)| b.identity().key) == key + }); + if !resolves { + return None; + } + let rebinds = &command_buffer.device().shared().rebinds; + if rebinds.any_detached(self.effects.keys.iter().copied()) { + return None; + } + self.effects.held() + } +} + +/// The kept chunks of a buffer's commands, and those whose last recording was not plain, by +/// chunk: held under the lock every CPU write of the buffer's records takes +/// (`IndirectCommandBuffer::kept`). +#[derive(Default)] +pub(super) struct KeptChunks { + kept: BTreeMap>, + /// The chunks an execution last recorded otherwise than plainly: an execution of them records + /// as one, until a write reaches one. + stepped: BTreeSet, +} + +impl KeptChunks { + /// The CPU wrote commands `range`: forget the chunks they lie in. + pub(super) fn wrote(&mut self, range: Range) { + if self.kept.is_empty() && self.stepped.is_empty() { + return; + } + let chunks = chunks_of(range); + self.kept.retain(|chunk, _| !chunks.contains(chunk)); + self.stepped.retain(|chunk| !chunks.contains(chunk)); + } + + /// The GPU may write the records from now on: forget every chunk. + pub(super) fn clear(&mut self) { + self.kept.clear(); + self.stepped.clear(); + } + + /// The kept chunk `chunk`, if any. + pub(super) fn get(&self, chunk: u32) -> Option> { + self.kept.get(&chunk).cloned() + } + + /// Whether an execution last recorded a chunk of `range` otherwise than plainly. + pub(super) fn stepped_in(&self, range: Range) -> bool { + let chunks = chunks_of(range); + self.stepped.range(chunks).next().is_some() + } + + /// Keep `kept`, chunk `chunk`'s recording. + pub(super) fn keep(&mut self, chunk: u32, kept: Arc) { + self.stepped.remove(&chunk); + self.kept.insert(chunk, kept); + } + + /// Note that chunk `chunk`'s recording was not plain. + pub(super) fn stepped(&mut self, chunk: u32) { + self.kept.remove(&chunk); + self.stepped.insert(chunk); + } +} + +#[cfg(test)] +mod tests { + use super::{chunks, chunks_of, CHUNK}; + + #[test] + fn chunks_cover_a_range_in_aligned_pieces() { + let pieces: Vec<_> = chunks(10..CHUNK * 2 + 5).collect(); + assert_eq!( + pieces, + [ + (0, 10..CHUNK), + (1, CHUNK..CHUNK * 2), + (2, CHUNK * 2..CHUNK * 2 + 5) + ] + ); + assert_eq!(chunks(5..5).count(), 0); + let last: Vec<_> = chunks(u32::MAX - 3..u32::MAX).collect(); + assert_eq!(last, [((u32::MAX - 3) / CHUNK, u32::MAX - 3..u32::MAX)]); + assert_eq!(chunks_of(10..CHUNK * 2 + 5), 0..3); + assert_eq!(chunks_of(CHUNK..CHUNK * 2), 1..2); + assert_eq!(chunks_of(7..7), 0..0); + } +} diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index a82f06e26..7f3df6f0d 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -136,6 +136,7 @@ mod indirect_dispatch; mod indirect_execute; mod interop; mod kept_bytes; +mod kept_commands; mod key_hash; mod library; mod linear_attachment; diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index 0dbaa7768..6c16a3185 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -726,6 +726,11 @@ impl Holds { self.keys.is_empty() } + /// Take `other`'s holds, which it then lets go of nothing of. + pub(super) fn join(&mut self, mut other: Holds) { + self.keys.append(&mut other.keys); + } + /// What a command an encoder encodes again took of `key` ([`Rebinds::pin`]), held by /// nothing here. pub(super) fn pin(&self, key: ResourceKey) -> Option { @@ -821,6 +826,11 @@ impl Taken { self.named.insert(key); } + /// The keys a command named. + pub(super) fn named(&self) -> &BTreeSet { + &self.named + } + /// Whether a command named a buffer over host pages ([`named_pins`](Self::named_pins) holds /// one). pub(super) fn names_a_pin(&self) -> bool { diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 37ac66a8c..e420acab3 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -1479,6 +1479,13 @@ pub(crate) struct RenderLowering { /// The encoder records an execution's commands (`render/executions.rs`): a draw that needs /// another instance than the execution's is refused. replaying: bool, + /// Every draw it replayed so far was plain: one a direct draw of the encoder's would keep for + /// drawing again (`render/draw_again.rs`) but for its being replayed, which no notice the + /// device announces at every occurrence met (`kept_commands.rs`). A chunk of an execution's + /// commands whose draws were all plain is kept. + replay_plain: bool, + /// The draw being drawn reached that keep's test and passed it ([`replay_plain`]). + plain_drawn: bool, /// The place among the command buffer's ended encoders of the encoder whose execution it /// replays (`RenderExecution`), which names a draw of the commands it drops /// (`CommandBuffer::drop_late_draw`); `None` where it replays none. @@ -2059,6 +2066,8 @@ impl RenderLowering { draw_calls: 0, tile_dispatch_calls: 0, replaying: false, + replay_plain: false, + plain_drawn: false, executing_encoder: None, rerouting: false, forms: BufferForms::Bound, @@ -2112,11 +2121,13 @@ impl CommandBuffer { let inheritance = vk::CommandBufferInheritanceInfo::default() .render_pass(compatible.raw) .subpass(0); + // A chunk kept for later command buffers (`kept_commands.rs`) may run in several at once. + let submits = match state.keeping() { + true => vk::CommandBufferUsageFlags::SIMULTANEOUS_USE, + false => vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT, + }; let begin = vk::CommandBufferBeginInfo::default() - .flags( - vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT - | vk::CommandBufferUsageFlags::RENDER_PASS_CONTINUE, - ) + .flags(submits | vk::CommandBufferUsageFlags::RENDER_PASS_CONTINUE) .inheritance_info(&inheritance); // SAFETY: the command buffer was just allocated from the pool, under the state lock; // the compatible pass lives as long as the encoder, and its command buffer after. @@ -7195,7 +7206,9 @@ impl RenderLowering { color_groups::Turn::Later(false) => return Err(color_groups::gap()), color_groups::Turn::Later(true) if self.group_skips() => self.group_skipped(), _ => { + self.plain_drawn = false; let drawn = self.draw_resident(call, assembly, draw, buffers, empty); + self.replay_plain &= self.plain_drawn; self.group_outcome(turn, drawn.is_ok()); if drawn.is_err() { self.forget_again(); @@ -7259,6 +7272,8 @@ impl RenderLowering { } } } + // A replayed draw that met a notice announced at every occurrence must meet it again. + self.replay_plain &= !watch.met(); self.kept_again(&watch, (reads, !empty && rasterizes, depth_writes), checked); Ok(()) } @@ -9777,11 +9792,10 @@ impl RenderLowering { let extended = |c: &render_pass::ColorTarget| { ExtendedRange::of(c.target.texture.pixel_format()).is_some() }; - let keeps = stepless + let plain = stepless && !barriered && !empty && !culled - && !self.replaying && !self.rerouting && self.replayed.is_none() && self.grouped.is_none() @@ -9833,9 +9847,12 @@ impl RenderLowering { && live.state.extended_shadows.is_empty() && !plan.variant.extended_range.values().any(planes) && !(self.layout.colors.iter().flatten()).any(extended) - && !plan.descriptors.iter().any(ycbcr) - // Its uses noted as the next draw would find them noted (`noted_apart.rs`). - && self.core.noted_now(&live.noted); + && !plan.descriptors.iter().any(ycbcr); + // A replayed draw plain so would be kept but for its being replayed: a chunk of its + // execution's commands whose draws all are is kept (`kept_commands.rs`). + self.plain_drawn = plain; + // Its uses noted as the next draw would find them noted (`noted_apart.rs`). + let keeps = plain && !self.replaying && self.core.noted_now(&live.noted); if keeps { let execution = records.then(|| draw_again::KeptExecution { pipeline: ExecutedPipeline::Render(Arc::clone(variant.shared_pipeline())), diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index 71e891ed9..04859cd32 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -348,6 +348,7 @@ use std::time::Instant; mod ahead; mod cause; mod gpu; +mod kept; /// The call an execution's refusals name. const CALL: &str = "execute_commands_in_buffer"; @@ -1362,11 +1363,12 @@ pub(super) struct PassStorage { pub(super) shadow: Option, } -/// One run of an execution's commands: the secondary command buffer its draws recorded into, -/// and the shape and views of the render pass instance it runs in where a command's draw needed -/// another than its instance's (attachments it fetches as storage images, views of its own). +/// One run of an execution's commands: the secondary command buffers its draws recorded into, in +/// order (one, but for the chunks of a kept execution's: `kept.rs`), and the shape and views of +/// the render pass instance it runs in where a command's draw needed another than its instance's +/// (attachments it fetches as storage images, views of its own). struct Run { - draws: vk::CommandBuffer, + draws: Vec, other: Option<(PassShape, ViewSetup)>, /// Its draws test and write the stencil in the shader: the shadow is filled before it and /// copied back after it, as around an encoder's instance of such draws. @@ -2010,6 +2012,19 @@ impl RenderExecution { self.record_gpu(core, (command_buffer, residency), form, (storage, rendered))?; return self.finish(encoder, found, rendered, &device); } + // Commands the CPU encoded, which their chunks' kept recordings may run (`kept.rs`). + if !step { + if let Some(keeping) = self.keeping(command_buffer, residency, rendered) { + let rendering = (storage, rendered); + return self.record_kept( + core, + (command_buffer, residency), + keeping, + found, + rendering, + ); + } + } let (commands, faults) = self.commands(&device, step)?; found.faults = ReplayFaults(found.faults.0 | faults.0); // What the commands run, for the command buffer's handlers (`executed_commands.rs`). @@ -2063,8 +2078,27 @@ impl RenderExecution { (storage, layout, residency), forms, ); + self.replay( + &mut encoder, + commands.into_iter().flatten(), + residency, + found, + )?; + self.finish(encoder, found, rendered, &device) + } + + /// Replay `commands` through `encoder` (`record`'s), resolving against `residency`, the + /// command buffer's, what their draws found noted into `found`. A mesh or patch draw is no + /// plain draw (`RenderLowering::replay_plain`). + fn replay( + &self, + encoder: &mut RenderLowering, + commands: impl IntoIterator, + residency: &Residency, + found: &mut Found, + ) -> Result<(), Error> { let inherited = self.icb.descriptor().inherit_buffers; - for (record, own) in commands.into_iter().flatten() { + for (record, own) in commands { // A command's barrier: its draw records into the execution's next run, which its // pass runs in a render pass instance of its own after a barrier from everything // before, so it sees the earlier draws' writes as plain Metal's does; but where the @@ -2168,7 +2202,10 @@ impl RenderExecution { Draw::Indexed(draw, (buffer, offset)) => { encoder.draw_indexed(CALL, draw, &buffer, offset)?; } - Draw::Mesh(grid, object, mesh) => encoder.draw_mesh(CALL, grid, object, mesh)?, + Draw::Mesh(grid, object, mesh) => { + encoder.replay_plain = false; + encoder.draw_mesh(CALL, grid, object, mesh)? + } Draw::Patches { mut draw, patch_indices, @@ -2176,6 +2213,7 @@ impl RenderExecution { factors, scale: _, } => { + encoder.replay_plain = false; // Metal draws a command's patches with its pipeline's control points, whatever // the record holds (measured). draw.control_points = control_points.unwrap_or(draw.control_points); @@ -2201,7 +2239,7 @@ impl RenderExecution { } } } - self.finish(encoder, found, rendered, &device) + Ok(()) } /// The recording `encoder` made of the commands, its runs ended (`record`'s): what its draws @@ -2281,7 +2319,7 @@ impl RenderExecution { }) .collect::, Error>>()?; runs.push(Run { - draws: run.draws, + draws: vec![run.draws], other, shadow: run.shadow, steps, @@ -2289,9 +2327,9 @@ impl RenderExecution { before: run.before, }); } - for run in &runs { + for raw in runs.iter().flat_map(|run| &run.draws) { // SAFETY: only this recording records the secondary command buffers. - unsafe { core.command_buffer().end_raw(run.draws) }.map_err(vulkan)?; + unsafe { core.command_buffer().end_raw(*raw) }.map_err(vulkan)?; } Ok(Recorded { core, @@ -2405,6 +2443,8 @@ impl RenderExecution { draw_calls: 0, tile_dispatch_calls: 0, replaying: true, + replay_plain: true, + plain_drawn: false, executing_encoder: Some(self.encoder), rerouting: false, forms, @@ -3149,14 +3189,14 @@ impl DeferredPass { let mut runs: Vec<(Option<&Run>, Vec)> = vec![(None, Vec::new())]; for piece in &instance.pieces { let (first, later) = match *piece { - Piece::Draws(draws) => (draws, &[][..]), + Piece::Draws(draws) => (vec![draws], &[][..]), // A draw's own secondary, recorded once its pipeline is made. Piece::Pending(index) => { let draw = self .pending .get(index) .ok_or_else(|| internal("a pending draw the pass does not hold"))?; - (draw.record(command_buffer)?, &[][..]) + (vec![draw.record(command_buffer)?], &[][..]) } Piece::Execution(index) => match recorded[index].split_first() { // An execution's first run shares its instance's render pass instance @@ -3164,15 +3204,15 @@ impl DeferredPass { Some((first, _)) if !first.before.is_empty() => { return Err(internal("an execution's first run with steps before it")) } - Some((first, later)) => (first.draws, later), + Some((first, later)) => (first.draws.clone(), later), None => return Err(internal("an execution of no runs")), }, }; match runs.last_mut() { - Some((last, run)) if last.is_none_or(Run::takes_more) => run.push(first), - _ => runs.push((None, vec![first])), + Some((last, run)) if last.is_none_or(Run::takes_more) => run.extend(first), + _ => runs.push((None, first)), } - runs.extend(later.iter().map(|run| (Some(run), vec![run.draws]))); + runs.extend(later.iter().map(|run| (Some(run), run.draws.clone()))); } let count = runs.len(); let run_passes = instance diff --git a/crates/metal2vulkan-runtime/src/render/executions/kept.rs b/crates/metal2vulkan-runtime/src/render/executions/kept.rs new file mode 100644 index 000000000..2698b2680 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/render/executions/kept.rs @@ -0,0 +1,480 @@ +//! An execution of render commands the CPU encoded, recorded chunk by chunk so a later one runs +//! the chunks no write reached again (`kept_commands.rs`). +//! +//! - **Which executions.** One `commit` records from the CPU's records (no host step, no GPU +//! form), of a range in the call, with no check of the caller's, no visibility result counted, +//! no shadowed texture, no tile threadgroup memory argument set or reached, no rasterization +//! rate map, no memoryless attachment or stand-in, no record barrier the buffer may hold, no +//! write before the fragments and no indirect read of the encoder's draws before the call, no +//! fragment write of the pass noted before it, no inherited table that binds anything, in a +//! command buffer with no executed-commands handler that is not encoded again after its commit; +//! and no chunk of its range last recorded otherwise than plainly. +//! - **The key.** A chunk is recorded from its records and from the inputs [`RenderKey`] holds: +//! the inherited pipeline state, the instance's compatible pass and shape, the pass's extent, +//! layers, samples and sample positions, the attachments that are among the resources made +//! resident, the encoder's state, scissor rectangles, render target array length and +//! amplification at the call, whether the pass holds tile imageblock data, and the resources +//! made resident (`Residency::kept_key`). A kept chunk runs again only under an equal key. +//! - **Each chunk** runs its kept recording again, or records apart: its draws into a secondary of +//! its own, begun against the instance's compatible pass, through an encoder of the call's +//! state over a core of its own (`EncoderCore::capture`), which the pass's core then takes +//! (`EncoderCore::absorb`). Its draws are plain where each one is (`RenderLowering::replay_plain`) +//! and they left the pass's storage and layout as they found them in one run: such a chunk's +//! secondary joins the others in the execution's first run, and is kept where its recording +//! did nothing a later command buffer cannot do again (`Captured::plain`) and reached nothing +//! its command buffer alone holds (`CommandBuffer::own_reached`). Plain draws write no memory, +//! so no draw of a later chunk depends on them but through the attachments, which the chunks' +//! order in their subpass keeps. +//! - **A chunk that is not plain** is no more apart: its encoder records the rest of the range +//! too, as the execution's would, its runs after the plain chunks' (its first sharing their +//! run, as an execution's first run shares its instance with the encoder's draws before the +//! call, which its encoder's state takes for granted), and the chunk is noted, so later +//! executions of it record as before until a write reaches it. + +use super::{ + Asked, Command, Draw, ExecutionRange, Found, PassStorage, PointIndices, Recorded, + RenderExecution, Rendered, Run, Visibility, +}; +use crate::amplification::Amplification; +use crate::command_buffer::CommandBuffer; +use crate::encoder::EncoderCore; +use crate::error::{internal, vulkan, Error}; +use crate::indirect_command_buffer::Reader; +use crate::kept_commands::{self, KeptChunk, KeptContext, KeptEffects, Resolution}; +use crate::pipeline::{BufferForms, RenderPipelineState}; +use crate::render::{memoryless, RenderLowering}; +use crate::render_pass::PassLayout; +use crate::render_state::{EncoderState, ScissorRects}; +use crate::render_target::{PassShape, RenderPassObject}; +use crate::residency::Residency; +use crate::resource::ResourceKey; +use crate::sample_positions::Sixteenths; +use metal2vulkan::bind::indirect_commands::{BufferStage, CommandRecord}; +use metal2vulkan::bind::{ReplayFaults, UsedResource}; +use std::collections::BTreeSet; +use std::ops::Range; +use std::sync::atomic::Ordering; +use std::sync::Arc; + +/// What a chunk of an execution's draws is recorded from beside its records (the module docs). +#[derive(Clone)] +pub(super) struct RenderKey { + pipeline: Option, + /// Held, so no other pass takes its `VkRenderPass`'s handle while the key lives: a key of the + /// same handle names the same pass, which the device keeps for the shape (each encoder holds + /// a pass object of its own over it). + compatible: Arc, + shape: PassShape, + extent: [u32; 2], + layers: u32, + samples: u32, + sample_positions: Vec, + attached: Vec, + state: EncoderState, + scissors: ScissorRects, + render_target_array_length: u32, + amplification: Amplification, + tile_imageblock: bool, + resident: (Vec, Vec), +} + +impl PartialEq for RenderKey { + fn eq(&self, other: &RenderKey) -> bool { + self.pipeline == other.pipeline + && self.compatible.raw == other.compatible.raw + && self.shape == other.shape + && self.extent == other.extent + && self.layers == other.layers + && self.samples == other.samples + && self.sample_positions == other.sample_positions + && self.attached == other.attached + && self.state.same_values(&other.state) + && self.scissors == other.scissors + && self.render_target_array_length == other.render_target_array_length + && self.amplification == other.amplification + && self.tile_imageblock == other.tile_imageblock + && self.resident == other.resident + } +} + +/// An execution that keeps its commands (the module docs): its key, its range's kept chunks in +/// order, and the CPU's writes of the buffer as they were looked up. +pub(super) struct Keeping { + key: RenderKey, + kept: Vec>>, + read_at: u64, +} + +/// A chunk recorded apart: its encoder after its commands, the addresses they named and what +/// they resolved to, the no-copy buffers' moves before it read its records, and whether a command +/// of it named a released state. +struct Apart { + encoder: RenderLowering, + resolved: Vec, + moved: u64, + released: bool, +} + +impl RenderExecution { + /// Whether the execution keeps its commands (the module docs), recorded by `command_buffer` + /// against `residency` in a pass `rendered` lays out: its key and its chunks. + pub(super) fn keeping( + &self, + command_buffer: &CommandBuffer, + residency: &Residency, + rendered: &Rendered, + ) -> Option { + let snapshot = &self.snapshot; + let layout = &snapshot.layout; + let ExecutionRange::Fixed(range) = &self.range else { + return None; + }; + let inherited = self.icb.descriptor().inherit_buffers; + let tables = [ + &snapshot.vertex, + &snapshot.fragment, + &snapshot.object, + &snapshot.mesh, + ]; + let binds_nothing = tables.iter().all(|table| table.binds_nothing()); + let colors = layout.colors.iter().flatten(); + let plain_colors = colors + .clone() + .all(|color| color.stand_in.is_none() && color.planes.is_none()); + let memoryless_target = colors.clone().any(|color| memoryless(&color.target)) + || (layout.depth_stencil.as_ref()) + .is_some_and(|ds| ds.stand_in.is_some() || memoryless(&ds.target)); + let keeps = !range.is_empty() + && !self.icb.gpu_written() + && self.check.is_none() + && self.lent.is_none() + && layout.visibility.is_none() + && self.shadows.is_empty() + && !self.icb.may_hold_barriers() + && !snapshot.tile_memory.set() + && !snapshot.tile_memory_reached + && snapshot.rate_map.is_none() + && snapshot.geometry_writes.is_empty() + && snapshot.indirect_reads.is_empty() + && !snapshot.pass_start.fragment_wrote() + && (!inherited || binds_nothing) + && rendered.backed.is_empty() + && plain_colors + && !memoryless_target + && !crate::replay::is_replaying() + && !command_buffer.reports_executed(); + if !keeps { + return None; + } + let (kept, stepped, read_at) = self.icb.kept_chunks(range.clone()); + if stepped { + return None; + } + let resident = residency.kept_key(); + // An attachment is among them as a texture made resident, or in a heap or over a buffer + // made resident. + let keys: BTreeSet = resident.1.iter().copied().collect(); + let attached = colors + .map(|color| &color.target.texture) + .chain(layout.depth_stencil.as_ref().map(|ds| &ds.target.texture)) + .filter(|texture| { + keys.contains(&texture.use_key()) + || texture.bytes_key().is_some_and(|key| keys.contains(&key)) + }) + .map(|texture| texture.use_key()) + .collect(); + let key = RenderKey { + pipeline: self.pipeline.clone(), + compatible: Arc::clone(&snapshot.compatible), + shape: snapshot.shape.clone(), + extent: layout.extent, + layers: layout.layers, + samples: layout.samples, + sample_positions: layout.sample_positions.clone(), + attached, + state: snapshot.state.clone(), + scissors: snapshot.scissors.clone(), + render_target_array_length: snapshot.render_target_array_length, + amplification: snapshot.amplification.clone(), + tile_imageblock: snapshot.tile_imageblock, + resident, + }; + Some(Keeping { key, kept, read_at }) + } + + /// Record the commands chunk by chunk through `core`, the pass's (the module docs), into + /// secondaries begun against the execution's instance, over the pass's `storage`, in a pass + /// `rendered` lays out, with `residency`, `command_buffer`'s: `record`'s, where the execution + /// keeps its commands (`keeping`). + pub(super) fn record_kept( + &self, + mut core: EncoderCore, + (command_buffer, residency): (&CommandBuffer, &Residency), + keeping: Keeping, + found: &mut Found, + (storage, rendered): (PassStorage, &mut Rendered), + ) -> Result { + let device = command_buffer.device().clone(); + let (range, faults) = self.range.commands(self.icb.size())?; + found.faults = ReplayFaults(found.faults.0 | faults.0); + let Keeping { key, kept, read_at } = keeping; + // Counted before the records are read: a write meanwhile records it again. + self.read_at.store(read_at, Ordering::Release); + let layout = rendered.backing(&self.snapshot.layout)?; + let mut draws = Vec::new(); + let mut rest = None; + for ((chunk, covered), kept) in kept_commands::chunks(range.clone()).zip(kept) { + let again = kept.and_then(|kept| { + let held = kept.runs_again(command_buffer, (&key, &covered), residency)?; + Some((kept, held)) + }); + if let Some((kept, held)) = again { + core.run_kept(&kept.effects, held)?; + found.misses = found.misses.wrapping_add(kept.misses); + found.faults = ReplayFaults(found.faults.0 | kept.faults.0); + draws.push(kept.raw); + device + .shared() + .counts + .indirect_chunk_kept(u64::from(covered.end - covered.start)); + core.retain_shared(kept); + continue; + } + let context = KeptContext::new(command_buffer)?; + core.retain_shared(Arc::clone(&context) as _); + let reached = command_buffer.own_reached(); + command_buffer.lend_kept(Some(&context)); + let mut chunk_found = Found::default(); + let apart = self.record_apart( + (command_buffer, residency), + covered.clone(), + (&storage, &layout), + &mut chunk_found, + ); + command_buffer.lend_kept(None); + let Apart { + encoder, + resolved, + moved, + released, + } = apart?; + let plain = encoder.replay_plain + && encoder.earlier.is_empty() + && same_storage(&storage, &encoder) + && same_layout(&layout, &encoder.layout); + if !plain { + self.icb.keep_chunk(chunk, None, read_at); + rest = Some((encoder, covered.end, chunk_found)); + break; + } + let raw = encoder.current.draws; + let capture = self.end_apart(encoder, &device)?; + let captured = capture.finish_capture()?; + let held = captured.retained.all_shared(); + let keeps = captured.plain() && !released && command_buffer.own_reached() == reached; + if let (true, Some(held)) = (keeps, held) { + let effects = KeptEffects::new( + captured.summary.clone(), + (captured.keys.clone(), captured.taken.named().clone()), + &held, + captured.executions.clone(), + ); + let kept = KeptChunk::new( + (context, raw), + covered, + Box::new(key.clone()), + (resolved, moved), + effects, + (chunk_found.misses, chunk_found.faults), + ); + self.icb.keep_chunk(chunk, Some(Arc::new(kept)), read_at); + } + core.absorb(captured)?; + found.misses = found.misses.wrapping_add(chunk_found.misses); + found.faults = ReplayFaults(found.faults.0 | chunk_found.faults.0); + draws.push(raw); + } + let Some((mut encoder, from, chunk_found)) = rest else { + let run = Run { + draws, + other: None, + shadow: false, + steps: None, + framed: Vec::new(), + before: Vec::new(), + }; + return Ok(Recorded { + core, + runs: vec![run], + storage, + layout, + }); + }; + // The rest of the range, from the chunk that is not plain on, through its encoder, as the + // execution's own records them. + found.misses = found.misses.wrapping_add(chunk_found.misses); + found.faults = ReplayFaults(found.faults.0 | chunk_found.faults.0); + if from < range.end { + let (commands, released) = self.icb.render_records(from..range.end, Reader::Commit)?; + self.icb.degrade_released(&released); + self.replay(&mut encoder, commands, residency, found)?; + } + let tail = self.finish(encoder, found, rendered, &device)?; + let Recorded { + core: capture, + mut runs, + storage, + layout, + } = tail; + core.absorb(capture.finish_capture()?)?; + let first = runs + .first_mut() + .ok_or_else(|| internal("an execution's rest of no runs"))?; + draws.append(&mut first.draws); + first.draws = draws; + Ok(Recorded { + core, + runs, + storage, + layout, + }) + } + + /// Record commands `covered` apart (the module docs): through an encoder of the call's state + /// over a core of its own into a secondary of its own, begun against the instance's + /// compatible pass, over the pass's `storage`, in `layout`, the call's; what their draws found + /// noted into `found`. + fn record_apart( + &self, + (command_buffer, residency): (&CommandBuffer, &Residency), + covered: Range, + (storage, layout): (&PassStorage, &PassLayout), + found: &mut Found, + ) -> Result { + let snapshot = &self.snapshot; + let moved = crate::buffer::host_cells_moved(); + let (commands, released) = self.icb.render_records(covered, Reader::Commit)?; + self.icb.degrade_released(&released); + let resolved = self.resolutions(&commands, residency); + let draws = command_buffer.begin_draws(&snapshot.compatible)?; + let raw = command_buffer.device().shared().vk(); + let visibility = Visibility::borrowing(None, None, raw, draws); + let mut encoder = self.replay_encoder( + EncoderCore::capture(command_buffer), + (draws, visibility), + (storage.clone(), layout.clone(), residency), + BufferForms::Bound, + ); + self.replay(&mut encoder, commands, residency, found)?; + Ok(Apart { + encoder, + resolved, + moved, + released: !released.is_empty(), + }) + } + + /// End a plain chunk's encoder: its secondary ended. Its core back. + fn end_apart( + &self, + encoder: RenderLowering, + device: &crate::Device, + ) -> Result { + let raw = device.shared().vk(); + let RenderLowering { + core, + current, + mut visibility, + .. + } = encoder; + visibility.end(raw, current.draws); + visibility.close_spares(raw, current.draws); + // SAFETY: only this recording records the secondary command buffer. + unsafe { core.command_buffer().end_raw(current.draws) }.map_err(vulkan)?; + Ok(core) + } + + /// The addresses `commands` name (their buffers', where the buffer does not inherit them, + /// and their draws'), resolved against `residency` (`kept_commands::resolutions`). + fn resolutions(&self, commands: &[Command], residency: &Residency) -> Vec { + let descriptor = self.icb.descriptor(); + let stages = [ + (BufferStage::Vertex, descriptor.max_vertex_buffer_bind_count), + ( + BufferStage::Fragment, + descriptor.max_fragment_buffer_bind_count, + ), + (BufferStage::Object, descriptor.max_object_buffer_bind_count), + (BufferStage::Mesh, descriptor.max_mesh_buffer_bind_count), + ]; + let addresses = commands.iter().flat_map(|(record, _)| { + let bound = stages + .iter() + .filter(|_| !descriptor.inherit_buffers) + .flat_map(|&(stage, count)| { + let bindings = record.bindings.buffers(stage); + (0..count).zip(bindings).filter_map(|(_, binding)| *binding) + }) + .filter(|binding| binding.names_buffer()) + .map(|binding| binding.address); + bound + .chain(addresses(record, &self.icb)) + .collect::>() + }); + kept_commands::resolutions(addresses, residency) + } +} + +/// The addresses a command's draw names: its index buffer's, and a patch draw's buffers'. +fn addresses( + record: &CommandRecord, + icb: &crate::indirect_command_buffer::IndirectCommandBuffer, +) -> Vec { + let Asked::Draw(draw) = Asked::of(&record.action, icb) else { + return Vec::new(); + }; + match draw { + Draw::Primitives(..) | Draw::Mesh(..) => Vec::new(), + Draw::Indexed(_, address) => vec![address], + Draw::Patches { + patch_indices, + control_point_indices, + factors, + .. + } => { + let points = match control_point_indices { + PointIndices::Buffer(address) => Some(address), + PointIndices::Own | PointIndices::Zero => None, + }; + patch_indices + .into_iter() + .chain(points) + .chain([factors.buffer]) + .collect() + } + } +} + +/// Whether a chunk's `encoder` left the pass's storage as `storage` held it: it made none. (No +/// draw of an execution that keeps its commands reaches the tile threadgroup memory.) +fn same_storage(storage: &PassStorage, encoder: &RenderLowering) -> bool { + storage.imageblock.is_some() == encoder.imageblock.is_some() + && storage.shadow.is_some() == encoder.shadow.is_some() +} + +/// Whether a chunk's draws left the pass's layout as `before` held it: no stand-in or sample +/// planes made. +fn same_layout(before: &PassLayout, after: &PassLayout) -> bool { + let colors = |layout: &PassLayout| { + (layout.colors.iter()) + .map(|color| { + color + .as_ref() + .map(|c| (c.stand_in.is_some(), c.planes.is_some())) + }) + .collect::>() + }; + let depth = + |layout: &PassLayout| (layout.depth_stencil.as_ref()).map(|ds| ds.stand_in.is_some()); + colors(before) == colors(after) && depth(before) == depth(after) +} diff --git a/crates/metal2vulkan-runtime/src/residency.rs b/crates/metal2vulkan-runtime/src/residency.rs index 664260815..93e30e289 100644 --- a/crates/metal2vulkan-runtime/src/residency.rs +++ b/crates/metal2vulkan-runtime/src/residency.rs @@ -489,6 +489,19 @@ impl Residency { used } + /// What a kept recording of commands that resolved and bound against it was recorded from + /// (`kept_commands.rs`): its resources as the bind state states them, and each one's key, + /// in order. + pub(super) fn kept_key(&self) -> (Vec, Vec) { + let keys = self.used.iter().map(|(used, ..)| match used { + Used::Buffer(buffer) => buffer.identity().key, + Used::Heap { bytes, .. } => bytes.identity().key, + Used::Texture(texture) => texture.use_key(), + Used::IndirectCommandBuffer(icb) => icb.storage().identity().key, + }); + (self.used_resources(), keys.collect()) + } + /// The resource of `token`. pub(super) fn get(&self, token: u32) -> Option<&Used> { self.used.get(token as usize).map(|(used, ..)| used) diff --git a/crates/metal2vulkan-runtime/src/retained.rs b/crates/metal2vulkan-runtime/src/retained.rs index f50f0ed7f..42ffae0af 100644 --- a/crates/metal2vulkan-runtime/src/retained.rs +++ b/crates/metal2vulkan-runtime/src/retained.rs @@ -106,6 +106,30 @@ impl Retained { self.holds().push(Held::Shared(object)); } + /// Hold what `other` holds too, after its own, in its order. + pub(super) fn join(&mut self, other: Retained) { + let Some(mut holds) = other.holds else { + return; + }; + self.holds().append(&mut holds.0); + } + + /// Another reference to each object it holds, in order, where every hold is of a shared + /// object (`kept_commands.rs`); `None` where one is boxed. + pub(super) fn all_shared(&self) -> Option>> { + let Some(holds) = &self.holds else { + return Some(Vec::new()); + }; + holds + .0 + .iter() + .map(|held| match held { + Held::Shared(object) => Some(Arc::clone(object)), + Held::Boxed(_) => None, + }) + .collect() + } + /// The holds' storage, made at the first. fn holds(&mut self) -> &mut Vec { let holds = self diff --git a/crates/metal2vulkan-runtime/src/tracker.rs b/crates/metal2vulkan-runtime/src/tracker.rs index 78d005cc6..dd450b9c4 100644 --- a/crates/metal2vulkan-runtime/src/tracker.rs +++ b/crates/metal2vulkan-runtime/src/tracker.rs @@ -1567,6 +1567,10 @@ impl KeptUses { } } + fn is_empty(&self) -> bool { + self.uses.is_empty() + } + fn push(&mut self, used: Use) { if used.range.is_empty() { return; @@ -1604,6 +1608,11 @@ impl IndirectReads { } } + /// Whether it holds no read. + pub(super) fn is_empty(&self) -> bool { + self.reads.is_empty() + } + /// Add the indirect argument reads of a draw with `uses`. pub(super) fn add(&mut self, uses: &[Use]) { for used in uses.iter().filter(|used| { @@ -1659,6 +1668,11 @@ impl GeometryWrites { } } + /// Whether it holds no write. + pub(super) fn is_empty(&self) -> bool { + self.writes.is_empty() + } + /// Add the writes before its fragments of a draw with `uses`: a use that writes in one of /// those stages and in the fragment stage too is taken as written before the fragments, which /// claims more and stays exact. @@ -1914,13 +1928,11 @@ impl EncoderUses { impl Summary { /// The tracked uses. - #[cfg(test)] pub(super) fn uses(&self) -> &[Use] { &self.uses } /// Every stage the encoder's commands ran in. - #[cfg(test)] pub(super) fn stages(&self) -> vk::PipelineStageFlags2 { self.stages } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 1de337695..d12b73877 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -146,6 +146,8 @@ pub(crate) struct Counters { visibility_queries_begun: AtomicU64, indirect_draws_recorded: AtomicU64, indirect_records_read: AtomicU64, + indirect_chunks_kept: AtomicU64, + indirect_commands_kept: AtomicU64, gpu_form_commands: AtomicU64, merged_draw_commands: AtomicU64, gpu_pool_blocks_made: AtomicU64, @@ -1127,6 +1129,14 @@ impl Counters { .fetch_add(count, Ordering::Relaxed); } + /// An execution ran a chunk of `commands` of an indirect command buffer's from its kept + /// recording (`kept_commands.rs`), reading none of their records. + pub(crate) fn indirect_chunk_kept(&self, commands: u64) { + self.indirect_chunks_kept.fetch_add(1, Ordering::Relaxed); + self.indirect_commands_kept + .fetch_add(commands, Ordering::Relaxed); + } + /// `count` commands of an execution of render commands were recorded in its GPU form /// (`render/executions/gpu.rs`): the device reads their records. pub(crate) fn gpu_form_commands(&self, count: u64) { @@ -3738,6 +3748,12 @@ pub struct WorkCounts { /// `IndirectCommandCheck`) or `IndirectCommandBuffer::commands` reads it; a setter's own /// read of the command it changes is not counted. pub indirect_records_read: u64, + /// Chunks of indirect command buffers' commands an execution ran from the recording an + /// earlier one kept, one each time (`kept_commands.rs`): their command buffer runs that + /// recording again, and their records are not read. + pub indirect_chunks_kept: u64, + /// The commands of those chunks, one a command each time. + pub indirect_commands_kept: u64, /// Commands of executions of render commands recorded in their GPU form, one a command each /// time (`render/executions/gpu.rs`): the device read their records, the host none. pub gpu_form_commands: u64, @@ -5661,6 +5677,8 @@ impl Device { visibility_queries_begun: counters.visibility_queries_begun.load(Ordering::Relaxed), indirect_draws_recorded: counters.indirect_draws_recorded.load(Ordering::Relaxed), indirect_records_read: counters.indirect_records_read.load(Ordering::Relaxed), + indirect_chunks_kept: counters.indirect_chunks_kept.load(Ordering::Relaxed), + indirect_commands_kept: counters.indirect_commands_kept.load(Ordering::Relaxed), gpu_form_commands: counters.gpu_form_commands.load(Ordering::Relaxed), merged_draw_commands: counters.merged_draw_commands.load(Ordering::Relaxed), gpu_pool_blocks_made: counters.gpu_pool_blocks_made.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 91ee8e0c6..dd399812c 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -404,6 +404,8 @@ mod event_round_trips; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod events; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod execution_costs; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod executions; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod exits; @@ -553,6 +555,8 @@ mod kept_apart; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod kept_buffer_bytes; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod kept_commands; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod kept_images; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod kept_resolves; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/execution_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/execution_costs.rs new file mode 100644 index 000000000..046ad9acb --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/execution_costs.rs @@ -0,0 +1,324 @@ +//! What executing an indirect command buffer the CPU encoded costs on the device the cfg selects, +//! without the validation layer: report only, in release builds, to weigh the runtime's +//! execution path before and after a change to it. +//! +//! The workload is the consumer's (macOS guests over the runtime): a buffer of `n` commands, each +//! a render pipeline state set and a draw of one triangle (`rt6_resolve_half`, `rt6_resolve_white` +//! into a 64x64 `BGRA8Unorm` target), or a compute pipeline state set, two kernel buffers (the +//! second at a 16-byte window of its own, so no two commands write the same bytes), a threadgroup +//! length and a dispatch of one threadgroup of 4 threads (`icb_replay_template`), encoded once +//! and then executed whole, each execution in a command buffer of its own, committed and waited +//! for: +//! +//! - **`unchanged`**: no command written since the last execution; +//! - **`one re-encoded`**: command 0 encoded again before the execution, as it was; +//! - **`all re-encoded`**: every command encoded again, as it was. +//! +//! Each case runs [`WARM`] untimed executions first, then [`TIMED`], and is printed as an +//! `EXECUTE-COST` line: the median and the range of the encoder's time (its creation through +//! `end_encoding`), of `commit` and of the time from `commit` until `wait_until_completed` +//! returned, and of the wall time over all three, per execution; and the device's counters over +//! the timed executions: the records read and decoded (`WorkCounts::indirect_records_read`), and +//! the chunks of commands run from a kept recording and the commands those held +//! (`WorkCounts::indirect_chunks_kept`, `indirect_commands_kept`). +//! +//! Ignored by default: a measurement, not a check. Run it by name with `--run-ignored all`, in a +//! build with `--cfg m2v_system_alloc`, whose lib test binary keeps the system allocator as a +//! consumer's process does. + +use super::draw_costs::percentiles; +use super::{buffer_with, validated_device_with, Messages, ScratchCache, WAIT}; +use crate::air_library::AirLibrary; +use crate::gpu::TEST_DEVICE; +use metal2vulkan::metal::{ + IndirectCommandType, PixelFormat, PrimitiveType, ResourceUsage, TextureUsage, +}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, +}; +use metal2vulkan_devtools::{engine_dir, llvm_assemble}; +use metal2vulkan_runtime::{ + Buffer, CommandBufferStatus, CommandQueue, ComputePipelineState, Device, IndirectCommandBuffer, + IndirectCommandBufferDescriptor, LoadAction, PipelineOptions, RenderPassDescriptor, + RenderPipelineState, ResourceOptions, ResourceRef, Size, StoreAction, Texture, + TextureDescriptor, WorkCounts, +}; +use std::time::{Duration, Instant}; + +/// The untimed and the timed executions of each case. +const WARM: usize = 2; +const TIMED: usize = 5; +/// The command counts measured. +const COUNTS: [u64; 2] = [1024, 16384]; +/// The target's side. +const TARGET_SIDE: u64 = 64; + +/// What is written before an execution (the module docs). +#[derive(Clone, Copy, Debug)] +enum Case { + Unchanged, + OneReencoded, + AllReencoded, +} + +impl Case { + fn name(self) -> &'static str { + match self { + Case::Unchanged => "unchanged", + Case::OneReencoded => "one re-encoded", + Case::AllReencoded => "all re-encoded", + } + } +} + +/// The commands' kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Render, + Compute, +} + +/// One execution's times. +struct Times { + encoded: Duration, + commit: Duration, + wait: Duration, +} + +/// The device, its queue and the states the commands set. +struct Workload { + device: Device, + queue: CommandQueue, + render: RenderPipelineState, + compute: ComputePipelineState, + target: Texture, + params: Buffer, + out: Buffer, +} + +impl Workload { + fn new(device: Device) -> Workload { + let library = |ll: &str| { + device + .new_library_with_air(&llvm_assemble(&engine_dir().join(ll)).unwrap()) + .unwrap() + }; + let resolves = library("rt6_resolves.ll"); + let function = |name| { + StageSource::Function( + resolves + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + }; + let mut render = RenderPipelineDescriptor::new(function("rt6_resolve_half")); + render.fragment = Some(function("rt6_resolve_white")); + render.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::BGRA8Unorm)); + render.support_indirect_command_buffers = true; + let render = device + .new_render_pipeline_state(&render, &PipelineOptions::default()) + .unwrap(); + let kernel = library("icb_replay_template.ll") + .new_function_with_name("icb_replay_template") + .unwrap(); + let mut compute = + ComputePipelineDescriptor::new(StageSource::Function(kernel.function_descriptor())); + compute.support_indirect_command_buffers = true; + let compute = device + .new_compute_pipeline_state(&compute, &PipelineOptions::default()) + .unwrap(); + let mut target = + TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, TARGET_SIDE, TARGET_SIDE, false); + target.usage = TextureUsage::RENDER_TARGET; + target.resource_options = ResourceOptions::private(); + let params = [3u32, 7].map(u32::to_le_bytes).concat(); + Workload { + queue: device.new_command_queue().unwrap(), + target: device.new_texture(&target).unwrap(), + params: buffer_with(&device, ¶ms).unwrap(), + out: buffer_with(&device, &vec![0; 16 * COUNTS[1] as usize]).unwrap(), + render, + compute, + device, + } + } + + /// A buffer of `n` commands of `kind`. + fn icb(&self, kind: Kind, n: u64) -> IndirectCommandBuffer { + let mut descriptor = IndirectCommandBufferDescriptor::new(); + match kind { + Kind::Render => descriptor.command_types = IndirectCommandType::DRAW, + Kind::Compute => { + descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH; + descriptor.max_kernel_buffer_bind_count = 2; + descriptor.max_kernel_threadgroup_memory_bind_count = 1; + } + } + self.device + .new_indirect_command_buffer(&descriptor, n, ResourceOptions::shared()) + .unwrap() + } + + /// Encode command `index` of `icb`, of `kind`. + fn encode(&self, icb: &IndirectCommandBuffer, kind: Kind, index: u64) { + match kind { + Kind::Render => { + let command = icb.indirect_render_command_at(index).unwrap(); + command.set_render_pipeline_state(&self.render).unwrap(); + command + .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); + } + Kind::Compute => { + let command = icb.indirect_compute_command_at(index).unwrap(); + command.set_compute_pipeline_state(&self.compute).unwrap(); + command.set_kernel_buffer(Some(&self.params), 0, 0).unwrap(); + command + .set_kernel_buffer(Some(&self.out), 16 * index, 1) + .unwrap(); + command.set_threadgroup_memory_length(16, 0).unwrap(); + command + .concurrent_dispatch_threadgroups(Size::new(1, 1, 1), Size::new(4, 1, 1)) + .unwrap(); + } + } + } + + /// Execute every command of `icb`, of `kind`, in a command buffer of its own, committed and + /// waited for. + fn execute(&self, icb: &IndirectCommandBuffer, kind: Kind) -> Times { + let start = Instant::now(); + let command_buffer = self.queue.command_buffer().unwrap(); + match kind { + Kind::Render => { + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(self.target.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder + .execute_commands_in_buffer(icb, 0..icb.size()) + .unwrap(); + encoder.end_encoding().unwrap(); + } + Kind::Compute => { + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + let used = [ + ResourceRef::Buffer(&self.params), + ResourceRef::Buffer(&self.out), + ]; + encoder + .use_resources(&used, ResourceUsage::READ.union(ResourceUsage::WRITE)) + .unwrap(); + encoder + .execute_commands_in_buffer(icb, 0..icb.size()) + .unwrap(); + encoder.end_encoding().unwrap(); + } + } + let encoded = start.elapsed(); + let committed = Instant::now(); + command_buffer.commit().unwrap(); + let commit = committed.elapsed(); + let waited = Instant::now(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let wait = waited.elapsed(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + Times { + encoded, + commit, + wait, + } + } +} + +/// `values` in milliseconds as "median (low to high)". +fn spread(values: Vec) -> String { + let low = values.iter().copied().fold(f64::INFINITY, f64::min); + let high = values.iter().copied().fold(0.0, f64::max); + let [_, median, _] = percentiles(values); + format!("{median:.2} ({low:.2} to {high:.2})") +} + +/// The execution path's costs, printed (the module docs), for `kinds`. +fn measure(kinds: &[Kind]) { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| { + options.layers.clear(); + // A consumer's device keeps no execution record. + options.record_executions = false; + }) + .unwrap(); + let name = device.name().to_owned(); + let work = Workload::new(device); + eprintln!( + "EXECUTE-COST {name}: {WARM} untimed and {TIMED} timed executions a case, each in a \ + command buffer of its own" + ); + for &kind in kinds { + for n in COUNTS { + let icb = work.icb(kind, n); + for index in 0..n { + work.encode(&icb, kind, index); + } + for case in [Case::Unchanged, Case::OneReencoded, Case::AllReencoded] { + let run = || { + match case { + Case::Unchanged => {} + Case::OneReencoded => work.encode(&icb, kind, 0), + Case::AllReencoded => { + for index in 0..n { + work.encode(&icb, kind, index); + } + } + } + work.execute(&icb, kind) + }; + for _ in 0..WARM { + run(); + } + let before = work.device.work_counts(); + let times: Vec = (0..TIMED).map(|_| run()).collect(); + let after = work.device.work_counts(); + let delta = |f: fn(&WorkCounts) -> u64| f(&after) - f(&before); + let ms = |f: fn(&Times) -> Duration| { + spread(times.iter().map(|t| f(t).as_secs_f64() * 1e3).collect()) + }; + eprintln!( + "EXECUTE-COST {name}: {kind:?} n={n} {}: wall {} ms; encode {} ms, commit {} \ + ms, commit to completion {} ms; over {TIMED}: {} records read, {} \ + chunks kept holding {} commands", + case.name(), + ms(|t| t.encoded + t.commit + t.wait), + ms(|t| t.encoded), + ms(|t| t.commit), + ms(|t| t.wait), + delta(|c| c.indirect_records_read), + delta(|c| c.indirect_chunks_kept), + delta(|c| c.indirect_commands_kept), + ); + } + } + } +} + +#[test] +#[ignore = "a measurement, not a check: run by name with --run-ignored all"] +fn execution_costs() { + measure(&[Kind::Render, Kind::Compute]); +} + +#[test] +#[ignore = "a measurement, not a check: run by name with --run-ignored all"] +fn execution_costs_render() { + measure(&[Kind::Render]); +} + +#[test] +#[ignore = "a measurement, not a check: run by name with --run-ignored all"] +fn execution_costs_compute() { + measure(&[Kind::Compute]); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/kept_commands.rs b/crates/metal2vulkan-validation/src/runtime_lane/kept_commands.rs new file mode 100644 index 000000000..565981938 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/kept_commands.rs @@ -0,0 +1,452 @@ +//! Executions of commands the CPU encoded that run their chunks' kept recordings again (the +//! runtime's `kept_commands.rs`, `render/executions/kept.rs`), on the device the cfg selects, +//! under the validation layer. `icb_merged_draws`' vertex function places vertex `vid` at +//! `xy[vid]`, one pixel, and carries its command's mark (vertex buffer 0) and `vid` flat into a +//! `RGBA32Uint` target. Command `c` draws vertex `c`, its mark `100 + c`, at pixel `c` of the +//! target, so every command's draw is a pixel of its own. They draw as Metal's draws of the +//! commands do, and: +//! +//! - an execution of commands no write reached since an earlier one recorded them runs that +//! recording again, chunk by chunk, reading no record: in another command buffer, into another +//! target, and twice in one pass; +//! - a command encoded again or reset records its chunk again, and only it; +//! - a write of the GPU's (a blit's reset) runs no kept recording; +//! - another set of resident resources, or another range, records its chunks again. +//! +//! And so do compute commands: `icb_replay_template`, command `c` binding its own parameters and +//! output windows, so every command's dispatch writes words of its own. + +use super::degrade_notices::on_device; +use super::indirect_host_steps::complete; +use super::render_executions::icb; +use super::{buffer_with, read_buffer}; +use crate::air_library::AirLibrary; +use metal2vulkan::metal::{IndirectCommandType, PixelFormat, PrimitiveType, RenderStages}; +use metal2vulkan::metal::{ResourceUsage, TextureUsage}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, +}; +use metal2vulkan_devtools::{engine_dir, llvm_assemble}; +use metal2vulkan_runtime::{ + Buffer, ClearColor, CommandQueue, ComputePipelineState, Device, IndirectCommandBuffer, + IndirectCommandBufferDescriptor, LoadAction, PipelineOptions, Region, RenderPassDescriptor, + RenderPipelineState, ResourceOptions, ResourceRef, Size, StoreAction, Texture, + TextureDescriptor, +}; +use std::ops::Range; + +/// The target's width and height. +const W: u64 = 64; +const H: u64 = 48; +/// The commands: three chunks of the runtime's 256, the last a part. +const N: u64 = 600; + +/// What the executions draw with: the commands' state, their buffers, the target and a queue. +struct Scene { + state: RenderPipelineState, + marks: Buffer, + frame: Buffer, + xy: Buffer, + queue: CommandQueue, +} + +impl Scene { + fn new(device: &Device) -> Scene { + let bitcode = llvm_assemble(&engine_dir().join("icb_merged_draws.ll")).unwrap(); + let library = device.new_library_with_air(&bitcode).unwrap(); + let function = |name: &str| { + StageSource::Function( + library + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + }; + let mut descriptor = RenderPipelineDescriptor::new(function("icb_merged_vertex")); + descriptor.fragment = Some(function("icb_merged_fragment")); + descriptor.color_attachments[0] = + Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Uint)); + descriptor.support_indirect_command_buffers = true; + let state = device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap(); + let words = |values: Vec| -> Vec { + values.into_iter().flat_map(u32::to_le_bytes).collect() + }; + let floats = |values: Vec| -> Vec { + values.into_iter().flat_map(f32::to_le_bytes).collect() + }; + let pixels = (0..W * H).flat_map(|p| [(p % W) as f32 + 0.5, (p / W) as f32 + 0.5]); + Scene { + state, + marks: buffer_with(device, &words((0..W * H).map(|c| 100 + c as u32).collect())) + .unwrap(), + frame: buffer_with(device, &floats(vec![W as f32, H as f32, 0.0, 0.0])).unwrap(), + xy: buffer_with(device, &floats(pixels.collect())).unwrap(), + queue: device.new_command_queue().unwrap(), + } + } + + /// A buffer of [`N`] commands that inherit the encoder's state, each written + /// ([`write`](Self::write)). + fn icb(&self, device: &Device) -> IndirectCommandBuffer { + let mut descriptor = IndirectCommandBufferDescriptor::new(); + descriptor.command_types = IndirectCommandType::DRAW; + descriptor.inherit_pipeline_state = true; + descriptor.max_vertex_buffer_bind_count = 3; + descriptor.max_fragment_buffer_bind_count = 0; + let icb = icb(device, &descriptor, N); + for c in 0..N { + self.write(&icb, c, c); + } + icb + } + + /// Write command `c` of `icb`: its mark, the frame and the pixels as vertex buffers 0 to 2, + /// and a draw of vertex `vertex` alone. + fn write(&self, icb: &IndirectCommandBuffer, c: u64, vertex: u64) { + let command = icb.indirect_render_command_at(c).unwrap(); + command + .set_vertex_buffer(Some(&self.marks), 4 * c, 0) + .unwrap(); + command.set_vertex_buffer(Some(&self.frame), 0, 1).unwrap(); + command.set_vertex_buffer(Some(&self.xy), 0, 2).unwrap(); + command + .draw_primitives(PrimitiveType::Point, vertex, 1, 1, 0) + .unwrap(); + } + + /// A target: `RGBA32Uint`, `W` by `H`, `Shared`, a render target. + fn target(device: &Device) -> Texture { + let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA32Uint, W, H, false); + target.usage = TextureUsage::RENDER_TARGET; + target.resource_options = ResourceOptions::shared(); + device.new_texture(&target).unwrap() + } + + /// In a command buffer of its own, committed and waited for: a pass over `target`, cleared, + /// that makes the commands' buffers and `extra` resident and executes `range` of `icb` + /// `times` times. + fn run( + &self, + target: &Texture, + icb: &IndirectCommandBuffer, + (range, times): (Range, usize), + extra: Option<&Buffer>, + ) { + let command_buffer = self.queue.command_buffer().unwrap(); + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(target.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&self.state).unwrap(); + for buffer in [&self.marks, &self.frame, &self.xy] + .into_iter() + .chain(extra) + { + encoder + .use_resource( + buffer.as_resource(), + ResourceUsage::READ, + RenderStages::VERTEX, + ) + .unwrap(); + } + for _ in 0..times { + encoder + .execute_commands_in_buffer(icb, range.clone()) + .unwrap(); + } + encoder.end_encoding().unwrap(); + complete(&command_buffer); + } +} + +/// `target`'s pixels' marks and vertices, pixel by pixel. +fn pixels(target: &Texture) -> Vec<[u32; 2]> { + let mut bytes = vec![0u8; (16 * W * H) as usize]; + target + .get_bytes(&mut bytes, 16 * W, 0, Region::new_2d(0, 0, W, H), 0, 0) + .unwrap(); + let word = |p: &[u8; 16], i: usize| u32::from_le_bytes(p[4 * i..4 * i + 4].try_into().unwrap()); + let pixels = bytes.as_chunks::<16>().0.iter(); + pixels.map(|p| [word(p, 0), word(p, 1)]).collect() +} + +/// What Metal's draws of commands `drawn` leave: command `c`'s mark at the pixel of the vertex +/// it draws, `vertex(c)`. +fn drawn(drawn: impl IntoIterator, vertex: impl Fn(u64) -> u64) -> Vec<[u32; 2]> { + let mut out = vec![[0; 2]; (W * H) as usize]; + for c in drawn { + let v = vertex(c); + out[v as usize] = [100 + c as u32, v as u32]; + } + out +} + +/// Across `run`: the records the host read, the chunks run from kept recordings and the commands +/// those held. +fn counted(device: &Device, run: impl FnOnce()) -> [u64; 3] { + let before = device.work_counts(); + run(); + let after = device.work_counts(); + [ + after.indirect_records_read - before.indirect_records_read, + after.indirect_chunks_kept - before.indirect_chunks_kept, + after.indirect_commands_kept - before.indirect_commands_kept, + ] +} + +/// An execution of commands no write reached since one recorded them runs that recording again, +/// reading no record: in another command buffer, into another target, and twice in one pass. +#[test] +fn unchanged_commands_run_their_kept_recordings() { + on_device(|device, _| { + let scene = Scene::new(device); + let icb = scene.icb(device); + let (a, b) = (Scene::target(device), Scene::target(device)); + let all = drawn(0..N, |c| c); + let first = counted(device, || scene.run(&a, &icb, (0..N, 1), None)); + assert_eq!(first, [N, 0, 0], "the first execution reads every record"); + assert_eq!(pixels(&a), all); + let again = counted(device, || scene.run(&a, &icb, (0..N, 1), None)); + assert_eq!(again, [0, 3, N], "three chunks kept"); + assert_eq!(pixels(&a), all); + let other = counted(device, || scene.run(&b, &icb, (0..N, 1), None)); + assert_eq!(other, [0, 3, N], "kept into another target"); + assert_eq!(pixels(&b), all); + let twice = counted(device, || scene.run(&a, &icb, (0..N, 2), None)); + assert_eq!(twice, [0, 6, 2 * N], "kept twice in one pass"); + assert_eq!(pixels(&a), all); + }); +} + +/// A command encoded again, or reset, records its chunk again, and only it; the next execution +/// runs every chunk's kept recording again. +#[test] +fn a_command_written_again_records_its_chunk_alone() { + on_device(|device, _| { + let scene = Scene::new(device); + let icb = scene.icb(device); + let target = Scene::target(device); + scene.run(&target, &icb, (0..N, 1), None); + // Command 300 draws vertex 1000 now; command 520 is reset, and draws nothing. + scene.write(&icb, 300, 1000); + icb.reset_with_range(520..521).unwrap(); + let vertex = |c| if c == 300 { 1000 } else { c }; + let expected = drawn((0..N).filter(|&c| c != 520), vertex); + let written = counted(device, || scene.run(&target, &icb, (0..N, 1), None)); + assert_eq!( + written, + [256 + (N - 512), 1, 256], + "chunks 1 and 2 recorded again" + ); + assert_eq!(pixels(&target), expected); + let again = counted(device, || scene.run(&target, &icb, (0..N, 1), None)); + assert_eq!(again, [0, 3, N]); + assert_eq!(pixels(&target), expected); + }); +} + +/// A write of the GPU's into the buffer (a blit's reset of commands of every chunk) runs no kept +/// recording: the reset commands draw nothing. +#[test] +fn a_gpu_write_runs_no_kept_recording() { + on_device(|device, _| { + let scene = Scene::new(device); + let icb = scene.icb(device); + let target = Scene::target(device); + scene.run(&target, &icb, (0..N, 1), None); + scene.run(&target, &icb, (0..N, 1), None); + let command_buffer = scene.queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.reset_commands_in_buffer(&icb, 200..550).unwrap(); + blit.end_encoding().unwrap(); + complete(&command_buffer); + let [_, chunks, _] = counted(device, || scene.run(&target, &icb, (0..N, 1), None)); + assert_eq!(chunks, 0, "no chunk kept after the GPU's write"); + let expected = drawn((0..200).chain(550..N), |c| c); + assert_eq!(pixels(&target), expected); + }); +} + +/// Another set of resident resources records the chunks again, and so does another range; each +/// runs its own recording again after. +#[test] +fn another_residency_or_range_records_its_chunks_again() { + on_device(|device, _| { + let scene = Scene::new(device); + let icb = scene.icb(device); + let target = Scene::target(device); + let extra = buffer_with(device, &[0; 16]).unwrap(); + let all = drawn(0..N, |c| c); + scene.run(&target, &icb, (0..N, 1), None); + let resident = counted(device, || scene.run(&target, &icb, (0..N, 1), Some(&extra))); + assert_eq!(resident, [N, 0, 0], "another residency records again"); + assert_eq!(pixels(&target), all); + let again = counted(device, || scene.run(&target, &icb, (0..N, 1), Some(&extra))); + assert_eq!(again, [0, 3, N]); + assert_eq!(pixels(&target), all); + // Commands 100..400: chunk 0 from 100, and chunk 1 to 400, both recorded again. + let part = counted(device, || { + scene.run(&target, &icb, (100..400, 1), Some(&extra)) + }); + assert_eq!(part, [300, 0, 0], "another range records again"); + assert_eq!(pixels(&target), drawn(100..400, |c| c)); + let part = counted(device, || { + scene.run(&target, &icb, (100..400, 1), Some(&extra)) + }); + assert_eq!(part, [0, 2, 300]); + assert_eq!(pixels(&target), drawn(100..400, |c| c)); + // The whole range again: chunk 2 kept from the first executions. + let whole = counted(device, || scene.run(&target, &icb, (0..N, 1), Some(&extra))); + assert_eq!(whole, [512, 1, N - 512]); + assert_eq!(pixels(&target), all); + }); +} + +/// What the compute executions dispatch with: the commands' state, each command's parameters +/// (16 bytes apart: command `c`'s are `c + 1` and `1000 c`), their output, and a queue. +/// Command `c`'s four threads write `(c + 1)(t + 1) + 1000 c` to word `t` of its 16-byte window +/// of the output. +struct Dispatches { + state: ComputePipelineState, + params: Buffer, + out: Buffer, + queue: CommandQueue, +} + +impl Dispatches { + fn new(device: &Device) -> Dispatches { + let bitcode = llvm_assemble(&engine_dir().join("icb_replay_template.ll")).unwrap(); + let library = device.new_library_with_air(&bitcode).unwrap(); + let kernel = library + .new_function_with_name("icb_replay_template") + .unwrap(); + let mut descriptor = + ComputePipelineDescriptor::new(StageSource::Function(kernel.function_descriptor())); + descriptor.support_indirect_command_buffers = true; + let state = device + .new_compute_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap(); + let params: Vec = (0..N as u32) + .flat_map(|c| [c + 1, 1000 * c, 0, 0]) + .flat_map(u32::to_le_bytes) + .collect(); + Dispatches { + state, + params: buffer_with(device, ¶ms).unwrap(), + out: buffer_with(device, &vec![0; 16 * N as usize]).unwrap(), + queue: device.new_command_queue().unwrap(), + } + } + + /// A buffer of [`N`] concurrent dispatch commands, each written + /// ([`write`](Self::write)). + fn icb(&self, device: &Device) -> IndirectCommandBuffer { + let mut descriptor = IndirectCommandBufferDescriptor::new(); + descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH; + descriptor.max_kernel_buffer_bind_count = 2; + descriptor.max_kernel_threadgroup_memory_bind_count = 1; + let icb = icb(device, &descriptor, N); + for c in 0..N { + self.write(&icb, c, c); + } + icb + } + + /// Write command `c` of `icb`: the state, command `params`'s parameters and command `c`'s + /// output window, and one threadgroup of four threads. + fn write(&self, icb: &IndirectCommandBuffer, c: u64, params: u64) { + let command = icb.indirect_compute_command_at(c).unwrap(); + command.set_compute_pipeline_state(&self.state).unwrap(); + command + .set_kernel_buffer(Some(&self.params), 16 * params, 0) + .unwrap(); + command + .set_kernel_buffer(Some(&self.out), 16 * c, 1) + .unwrap(); + command.set_threadgroup_memory_length(16, 0).unwrap(); + command + .concurrent_dispatch_threadgroups(Size::new(1, 1, 1), Size::new(4, 1, 1)) + .unwrap(); + } + + /// In a command buffer of its own, committed and waited for: the output zeroed, then a + /// compute encoder that makes the buffers resident and executes `range` of `icb`. + fn run(&self, icb: &IndirectCommandBuffer, range: Range) { + let command_buffer = self.queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(&self.out, 0..16 * N, 0).unwrap(); + blit.end_encoding().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + let used = [ + ResourceRef::Buffer(&self.params), + ResourceRef::Buffer(&self.out), + ]; + encoder + .use_resources(&used, ResourceUsage::READ.union(ResourceUsage::WRITE)) + .unwrap(); + encoder.execute_commands_in_buffer(icb, range).unwrap(); + encoder.end_encoding().unwrap(); + complete(&command_buffer); + } + + /// The output's words. + fn out(&self) -> Vec { + let bytes = read_buffer(&self.out, 0, 16 * N).unwrap(); + let words = bytes.as_chunks::<4>().0.iter(); + words.map(|word| u32::from_le_bytes(*word)).collect() + } +} + +/// What Metal's dispatches of commands `ran` leave in the output: command `c`'s parameters +/// `params(c)`'s words in its window. +fn dispatched(ran: impl IntoIterator, params: impl Fn(u64) -> u64) -> Vec { + let mut out = vec![0; 4 * N as usize]; + for c in ran { + let p = params(c) as u32; + for t in 0..4u32 { + out[(4 * c) as usize + t as usize] = (p + 1) * (t + 1) + 1000 * p; + } + } + out +} + +/// Compute commands no write reached since an execution recorded them run that recording again, +/// reading no record; a command encoded again records its chunk again, and only it; and after a +/// blit's reset of commands, no kept recording runs. +#[test] +fn compute_commands_run_their_kept_recordings_until_written() { + on_device(|device, _| { + let work = Dispatches::new(device); + let icb = work.icb(device); + let all = dispatched(0..N, |c| c); + let first = counted(device, || work.run(&icb, 0..N)); + assert_eq!(first, [N, 0, 0], "the first execution reads every record"); + assert_eq!(work.out(), all); + let again = counted(device, || work.run(&icb, 0..N)); + assert_eq!(again, [0, 3, N], "three chunks kept"); + assert_eq!(work.out(), all); + // Command 300 takes command 7's parameters now. + work.write(&icb, 300, 7); + let params = |c| if c == 300 { 7 } else { c }; + let written = counted(device, || work.run(&icb, 0..N)); + assert_eq!(written, [256, 2, N - 256], "chunk 1 recorded again"); + assert_eq!(work.out(), dispatched(0..N, params)); + let again = counted(device, || work.run(&icb, 0..N)); + assert_eq!(again, [0, 3, N]); + assert_eq!(work.out(), dispatched(0..N, params)); + let command_buffer = work.queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.reset_commands_in_buffer(&icb, 200..550).unwrap(); + blit.end_encoding().unwrap(); + complete(&command_buffer); + let [_, chunks, _] = counted(device, || work.run(&icb, 0..N)); + assert_eq!(chunks, 0, "no chunk kept after the GPU's write"); + assert_eq!(work.out(), dispatched((0..200).chain(550..N), params)); + }); +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 8ff8ba13d..b83715a89 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2741,6 +2741,8 @@ field metal2vulkan-runtime::WorkCounts.in_place_checks_passed pub in_place_check field metal2vulkan-runtime::WorkCounts.in_place_checks_recalled pub in_place_checks_recalled: u64 field metal2vulkan-runtime::WorkCounts.in_place_checks_run pub in_place_checks_run: u64 field metal2vulkan-runtime::WorkCounts.in_place_checks_unchecked pub in_place_checks_unchecked: u64 +field metal2vulkan-runtime::WorkCounts.indirect_chunks_kept pub indirect_chunks_kept: u64 +field metal2vulkan-runtime::WorkCounts.indirect_commands_kept pub indirect_commands_kept: u64 field metal2vulkan-runtime::WorkCounts.indirect_draws_recorded pub indirect_draws_recorded: u64 field metal2vulkan-runtime::WorkCounts.indirect_records_read pub indirect_records_read: u64 field metal2vulkan-runtime::WorkCounts.inline_memoryless_write_splits pub inline_memoryless_write_splits: u64 diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 68830fd18..2bd8c3bad 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -964,3 +964,16 @@ else. around it in about 1.1e9 checks), while a loading and storing pass rewrites the whole 32x32 tile it draws in (`shadow.rs`, **Stored attachments**). A blit's partial writes keep the kernel's rule. Not announced. +- **An execution of indirect commands costs a decode and a recording per command at every commit + where it runs no kept recording** (`kept_commands.rs`). An execution of commands the CPU encoded + runs each 256-command chunk that no write reached since an earlier execution recorded it, under + the same inputs, from that recording, reading no record (`WorkCounts::indirect_chunks_kept`, + `indirect_commands_kept`). Every other execution reads and records each of its commands at each + commit: one of a buffer the GPU may write (from its first `use_resource` for writing or blit + into it on), a host step, a range read from a buffer, one with a check, a visibility result, + tile threadgroup memory, a rasterization-rate map, a memoryless attachment, a shadowed texture, + or an inherited table that binds anything, one in a command buffer with an executed-commands + handler, a compute one inside command predication, and one of a range holding a chunk whose last + recording was not plain (a mesh or patch draw, a draw that splits its instance or needs work + around it, one that meets a notice its device announces at each occurrence), until a write + reaches that chunk. Not announced.