From df0e7ec05ea0edc7e0019fc02e7b8e962174a12c Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 15 Nov 2026 14:13:04 -0800 Subject: [PATCH] RUNTIME 2384: a fence update keeps its encoder group; the group orders after it by the narrowest barrier A guest compute benchmark's encoders each update one fence and wait for one (reims, 780M, c471372f87: fence updates = waits = encoders in every workload; 63 encoders a command buffer in one workload), and an encoder that updated a fence ended its fold group, so every encoder began its own VkCommandBuffer: 47.5 a submission, encoders_folded 54 of 117591. The driver's per-call work grows with every VkCommandBuffer, and on the Iris Xe a VkCommandBuffer boundary costs 18.25 us of GPU time against 0.64 us for the least barrier between dispatches (m3-max-33589). A fence update no longer ends its group. A later member's commands order after the update by a barrier recorded per command at the narrowest width that covers it: source, the updating encoders' writes in the stages the update covers (SHADER_STORAGE_WRITE in shader stages, TRANSFER_WRITE in transfer stages, attachment writes in a pass); destination, what the command can reach of memory no use names, in its own stages (SHADER_STORAGE_READ | SHADER_SAMPLED_READ | SHADER_STORAGE_WRITE, TRANSFER_READ | TRANSFER_WRITE), plus its untracked uses' own reads (indirect-argument or uniform reads only where an untracked use reads them); tracked resources keep the tracker's rule. Between two compute encoders that is the least barrier, SHADER_WRITE to SHADER_READ | SHADER_WRITE. The barrier precedes the member's commands whether or not it waits, since a wait anywhere in an encoder covers all its commands, which enter the shared VkCommandBuffer as they come; independent encoders that update fences no one in the group waits on so run one after another (accepted: the guest's encoders all wait). Across command buffers and queues nothing changes: Metal evaluates a fence at submission, a wait only orders after updates committed before it ("commit the command buffers with the producing passes before those with the consuming passes", MTLFence), a waiter on another VkQueue waits for the updater's batch end, and a group never crosses a batch, so no cycle can form. WorkCounts gains fold_fence_barriers and six folds_refused_* counts (the reason a join was refused: kind, tail, batch, state, parts, ends; one relaxed add on a refused join, nothing on a join). Tests that ended a group by a fence update now end it by a change of dispatch type or an event. Verified: PHOENIX (RADV 780M, release, interleaved, 600 command buffers of 24 encoders, m3-max-33626): fenced chain 47 -> 1 VkCommandBuffer a submission, mean call 56-79 -> 18-20 us, GPU start median 142-173 -> 101-105 us, GPU time median 146.7 -> 87.8 us (either wait order); independent fence-updating encoders 74.7 -> 88.0 us GPU (serialised, as accepted); unfenced control unchanged (49.2 us). fold_fence_barriers 13800 = 600 x 23; no folds_refused_* moved. Long-call bench, small listed: 539 -> 371 us mean call. Lane tip 8ae906a4fd: clippy plain, m2v_gpu, m2v_cpu_icd 0 (33633); lavapipe runtime suite 2829 passed at 143a0013f8 and tracker unit tests 85 (33621; 8ae906a4fd deletes only the dead Summary::has_updates); PHOENIX encoder_fold, render_fold, spares, fences 71 passed (33626). Iris before/after: m3-max-33627, pending. Public surface: WorkCounts (for the lanes) gains fold_fence_barriers and folds_refused_*, blessed in api_signatures.tsv; a struct literal of WorkCounts must name them, Default and readers are unaffected. --- .../src/command_buffer/fold.rs | 62 +++-- .../src/command_buffer/mod.rs | 7 + crates/metal2vulkan-runtime/src/encoder.rs | 39 ++- .../metal2vulkan-runtime/src/encoder_fold.rs | 226 ++++++++++++++- .../src/tests/encoder_fold.rs | 263 +++++++++++++++--- .../src/tests/fence_fold_bench.rs | 257 +++++++++++++++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/render_fold.rs | 22 +- .../metal2vulkan-runtime/src/tests/spares.rs | 36 ++- .../metal2vulkan-runtime/src/tests/tracker.rs | 44 +++ crates/metal2vulkan-runtime/src/tracker.rs | 13 +- .../metal2vulkan-runtime/src/work_counts.rs | 69 ++++- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 7 + docs/API.md | 10 +- 15 files changed, 947 insertions(+), 112 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/fence_fold_bench.rs diff --git a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs index 55e3f7881..49514cd3e 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs @@ -4,7 +4,7 @@ use super::{FailedEncoders, FailedSignals, Failure, State}; use crate::encoder::Overwrite; -use crate::encoder_fold::{Fold, FoldEnd, FoldOrder, Joining, Stashed}; +use crate::encoder_fold::{Fold, FoldEnd, FoldOrder, Joining, Refusal, Stashed}; use crate::replay::Replay; use crate::resource::ResourceKey; use crate::tracker::Summary; @@ -19,20 +19,38 @@ impl State { /// the tail, which the encoder records into, and, where it is the group's second encoder, the /// group's order built from its first part's summary (`Fold::order`). `None` where it joins /// none, the group left in place: the encoder's open closes it once it opened - /// ([`close_fold`](Self::close_fold)). On a device that splits at aliases + /// ([`close_fold`](Self::close_fold)). A refusal is counted by its reason ([`Refusal`]): the + /// group's, or, where the tail holds none, why the encoder before left none + /// ([`unfolded`](Self::unfolded)); the command buffer's first encoder is refused nothing. On + /// a device that splits at aliases /// (`alias_split.rs`), a render encoder whose pass records at its end joins as any encoder: /// the first command it records into the tail at its end, where its pass or a draw of it uses /// an image over bytes the group's earlier encoders wrote, goes in a new `VkCommandBuffer`. - pub(crate) fn join_fold(&mut self, joining: Joining, trail: bool) -> Option> { - let fold = self.fold.as_ref()?; - let joins = fold.admits(joining) - && self.tail == Some(fold.tail) - && self.batches.all().len() == fold.batches - && !self.batches.signals_pending() - && !self.predicated - && self.protection.options() == 0 - && !trail; - if !joins { + pub(crate) fn join_fold( + &mut self, + joining: Joining, + trail: bool, + counts: &Counters, + ) -> Option> { + let Some(fold) = self.fold.as_ref() else { + if let Some(why) = self.unfolded { + counts.fold_refused(why); + } + return None; + }; + let refused = if !fold.admits(joining) { + Some(Refusal::Kind) + } else if self.tail != Some(fold.tail) { + Some(Refusal::Tail) + } else if self.batches.all().len() != fold.batches || self.batches.signals_pending() { + Some(Refusal::Batch) + } else if self.predicated || self.protection.options() != 0 || trail { + Some(Refusal::State) + } else { + None + }; + if let Some(why) = refused { + counts.fold_refused(why); return None; } // Its second encoder orders after its first part, as that part's end left it. @@ -61,12 +79,20 @@ impl State { fold, in_tail, encoder, - plain, + ends, summary, log, } = end; - let may_lead = plain && !self.predicated && self.protection.options() == 0; - let leads = joining.filter(|_| may_lead); + // Why no group goes on past it, where none may. + self.unfolded = match (ends, joining) { + (Some(why), _) => Some(why), + (None, None) => Some(Refusal::State), + (None, Some(_)) if self.predicated || self.protection.options() != 0 => { + Some(Refusal::State) + } + (None, Some(_)) => None, + }; + let leads = joining.filter(|_| self.unfolded.is_none()); let mut log = log.map(|(log, executions)| Stashed { encoder, log, @@ -106,7 +132,11 @@ impl State { stashed, ))); } - _ => unkept.extend(log.map(|stashed| stashed.log)), + (Some(_), None) => { + self.unfolded = Some(Refusal::Tail); + unkept.extend(log.map(|stashed| stashed.log)); + } + (None, _) => unkept.extend(log.map(|stashed| stashed.log)), } unkept } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 7585e9145..12d241058 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -839,6 +839,10 @@ pub(super) struct State { /// the next such encoder may join, recording on into it (`encoder_fold.rs`); held by that /// encoder while it is open. pub(super) fold: Option>, + /// Why the tail holds no group the next encoder may join, where an encoder left none: the + /// reason its join is refused, counted as it opens (`State::join_fold`); `None` before the + /// first encoder, and while a group goes on. + pub(super) unfolded: Option, /// The first ended encoder a command-predication record left the work of out /// ([`leave_out_ended`](Self::leave_out_ended)): the commit splits a group it lies past the /// first of (`fold.rs`'s `split_failure`). @@ -1237,6 +1241,7 @@ impl State { recorded: Revised::new(Vec::new(), revision), tail: None, fold: None, + unfolded: None, held_logs: Vec::new(), stash_room: Some(Vec::new()), room: Room::default(), @@ -1380,6 +1385,7 @@ impl State { recorded: _, tail, fold, + unfolded, held_logs: _, stash_room: _, room: _, @@ -1507,6 +1513,7 @@ impl State { self.own_reached = own_reached; self.tail = tail; self.fold = fold; + self.unfolded = unfolded; self.parked_compute = parked_compute; self.left_out_from = left_out_from; self.split_units = split_units; diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 23d9f5bdf..4b45be25e 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -53,7 +53,7 @@ use super::compute::Parked; use super::copy_run::CopyRun; use super::deferred::{Deferred, StepInputs}; use super::degradation::NoticesFor; -use super::encoder_fold::{self, Fold, FoldEnd, Joining}; +use super::encoder_fold::{self, Fold, FoldEnd, Joining, Refusal}; use super::error::{ internal, invalid, vulkan, CommandBufferError, CopyQueueProblem, Error, VkResultCode, }; @@ -738,7 +738,14 @@ impl EncoderCore { return Err(invalid(call, problem)); } let shared = command_buffer.device().shared(); - let fold = joining.and_then(|joining| state.join_fold(joining, shared.encoder_trail)); + let fold = match joining { + Some(joining) => state.join_fold(joining, shared.encoder_trail, &shared.counts), + // It joins no group, nor leaves one for the next encoder. + None => { + state.unfolded = Some(Refusal::Kind); + None + } + }; let (raw, barriered) = match &fold { Some(fold) => { shared.counts.encoder_folded(); @@ -1442,10 +1449,14 @@ impl EncoderCore { let Some(fold) = self.fold.as_mut() else { return; }; + let fenced = fold.order.fenced_open(); let Some(barrier) = fold.order.everything() else { return; }; let shared = self.open.command_buffer.device().shared(); + if fenced { + shared.counts.fold_fence_barrier(); + } let reads = self.open.command_buffer.memory_reads(); // SAFETY: as in `barrier`. unsafe { barrier.record_reading(shared.vk(), raw, reads) }; @@ -1822,9 +1833,17 @@ impl EncoderCore { let barrier = encoder_fold::joined(barrier, self.owed.pay(uses)); // After the earlier encoders of the group it joined, as the tracker orders two encoders // of a batch (`encoder_fold.rs`). + // And after the writes its fence updates cover, to what the command may reach + // (`encoder_fold.rs`'s **Fences**). let barrier = match self.fold.as_mut() { Some(fold) => { + let fenced = fold.order.fence_barrier(stages, tracked); + if fenced.is_some() { + let shared = self.open.command_buffer.device().shared(); + shared.counts.fold_fence_barrier(); + } let joined = encoder_fold::joined(barrier, fold.order.barrier(tracked)); + let joined = encoder_fold::joined(joined, fenced); if let Some(joined) = joined { fold.order.ordered(joined); } @@ -3661,7 +3680,11 @@ impl EncoderCore { // begins or goes on in orders after (`encoder_fold.rs`); and whether that part leaves // nothing that needs a `VkCommandBuffer` of its own after it. let mut fold_summary = None; - let mut plain = joining.is_some() && count == 1 && left_out == 0 && !fails && !judged; + let mut ends = match (count, left_out > 0 || fails || judged) { + (1, false) => None, + (1, true) => Some(Refusal::Ends), + _ => Some(Refusal::Parts), + }; for (at, (raws, segments)) in parts.into_iter().enumerate() { let mut summary = summaries .next() @@ -3669,9 +3692,11 @@ impl EncoderCore { if at > 0 { state.host_step(); } - if plain { - plain = segments.is_empty() && !summary.has_updates(); - fold_summary = (plain && fold.is_some()).then(|| summary.clone()); + if joining.is_some() && ends.is_none() { + if !segments.is_empty() { + ends = Some(Refusal::Parts); + } + fold_summary = (ends.is_none() && fold.is_some()).then(|| summary.clone()); } // Its uses and fence waits join its group's first part's summary, whose // `VkCommandBuffer` its first commands went into; its own part keeps its fence @@ -3729,7 +3754,7 @@ impl EncoderCore { fold, in_tail, encoder, - plain, + ends, summary: fold_summary, log: held_log.map(|log| (log, executed)), }; diff --git a/crates/metal2vulkan-runtime/src/encoder_fold.rs b/crates/metal2vulkan-runtime/src/encoder_fold.rs index f465c1406..a50bbae41 100644 --- a/crates/metal2vulkan-runtime/src/encoder_fold.rs +++ b/crates/metal2vulkan-runtime/src/encoder_fold.rs @@ -15,7 +15,7 @@ //! - **Where.** A compute or blit encoder takes the tail where the encoder before it was a //! compute, blit or render encoder ([`Fold`], kept by the command buffer as that one ended, //! **Render encoders** below) whose recording is -//! one part, with no work left for later (no segment), no fence update and nothing that fails +//! one part, with no work left for later (no segment) and nothing that fails //! or faults its command buffer, nor work its batch's submission records after it or judges //! by its part (a write into an ASTC carrier, whose second twin's decode the submission records //! after the part; a texture it writes whole before any of its commands reads it, whose zeros @@ -23,9 +23,8 @@ //! semaphore wait or signal, host step or resource state encoder since: `Batches`), where the //! command buffer used no command predication, the encoder trail is off and its protection //! options are 0; a compute encoder only where the group's compute encoders are of its dispatch -//! type ([`Joining`]). So a group lies inside one batch, and a fence orders nothing inside it: -//! what a later encoder waits for is updated after the group's last. A blit encoder ends a unit -//! of command predication (`predication.rs`), so a group that holds one may hold compute +//! type ([`Joining`]). So a group lies inside one batch. A blit encoder and a fence update end +//! a unit of command predication (`predication.rs`), so a group that holds one may hold compute //! encoders of two units: a record that leaves its unit's work out (an unbalanced one) from an //! encoder past the group's first splits the group at the commit (**Failed**, below). Every //! compute and blit encoder logs its calls (`replay.rs`), and a render encoder takes a group @@ -52,7 +51,7 @@ //! its open, before any command of its own, as an encoder past the scheduler's planned //! barriers takes one from everything before at its open (`encoder.rs`). What its pass leaves //! for later (a draw or tile dispatch whose pipeline is being made, an execution of render -//! commands: `deferred.rs` segments), a fence update, or a write it judges by its part +//! commands: `deferred.rs` segments) or a write it judges by its part //! (`Overwrite`) ends the group after it, as for any encoder; a late resolve target //! (`render/late_resolve.rs`) is the pass's own, recorded at its end in its `VkCommandBuffer`. //! - **The barrier between them** is recorded as the encoder records, by the rule the tracker @@ -66,6 +65,39 @@ //! its commands) first records one barrier from every access of the group's earlier encoders to //! every later access ([`FoldOrder::everything`]). A memory barrier the program asks for //! touches no memory and records none of it: each command after it takes its own order. +//! - **Fences.** An encoder that updates a fence goes on in its group, and the next encoder may +//! join it. Metal orders a fence's wait after its last update committed or encoded before it +//! (the `MTLFence` page: "commit the command buffers with the producing passes before those +//! with the consuming passes", and in one command buffer "encode the producing passes before +//! the consuming passes"; across queues too: "Fences can synchronize passes you submit to +//! different queues"), and the tracker evaluates each wait at submission, after the fence's +//! last update in submission order (`tracker.rs`): a wait never refers to a later update, so no +//! two waits can wait for each other. A wait of another command buffer or queue orders after +//! the whole group, its `VkCommandBuffer` one in submission order and its batch's signal at its +//! end, as it ordered after the batch's end before; a group never crosses a batch. Inside the +//! group, every command of a later member orders after the writes the update covers +//! ([`FoldOrder::fence_barrier`]), whether or not its encoder waits for the fence: a wait +//! covers all of the encoder's commands, "a fence that the pass waits for before it runs any of +//! its commands" (`waitForFence:`), and the runtime waits for fences at an encoder's start, but +//! the call may come after some of its commands went into the group's `VkCommandBuffer`. The +//! barrier is the narrowest that covers a fence, joined to the command's own: from the +//! updating encoders' writes in the stages the update covers (storage writes in shader stages, +//! transfer writes in transfer stages, attachment writes in a pass's), to what the command may +//! reach of memory no use names in its own stages (storage and sampled reads and storage writes +//! in shader stages, transfer reads and writes in transfer stages) and to its untracked uses' +//! own reads and writes, so to an indirect argument or uniform read only where such a use reads +//! one (the tracked resources take the tracker's rule, above). One +//! recorded, a later command that reaches no more records none for it. It orders more than +//! Metal, which orders only an encoder that waits. A member's wait for a fence updated before +//! the group joins the group's first part's summary (**Its submission**, below), which the +//! tracker plans before the group. Counted: `WorkCounts::fold_fence_barriers`. +//! - **Refusals.** An encoder that asks for a group and joins none is counted as it opens by the +//! first reason that holds ([`Refusal`], `WorkCounts::folds_refused_kind` and kin): the +//! group's encoders are of another kind, its tail moved, a batch boundary came since, the +//! command buffer's state (command predication, protection options, the encoder trail), or, +//! where the tail holds no group, what the encoder before left (work for later or more than +//! one part, or something that ends a group). The command buffer's first encoder is refused +//! nothing. A refusal costs one counter's increment; a join, none. //! - **Image uses after buffer writes** (`alias_split.rs`). On a device whose driver's image uses //! miss a write through a buffer over their memory recorded before them in the same //! `VkCommandBuffer` (`DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer`), a command @@ -161,9 +193,16 @@ impl Prior { } /// The order of a group's next encoder's commands after the group's earlier encoders (the module -/// docs): what those did to the tracked resources, by resource and range. +/// docs): what those did to the tracked resources, by resource and range, and the writes of those +/// that updated a fence (**Fences** in the module docs). pub(crate) struct FoldOrder { priors: KeyMap>, + /// The writes the group's fence updates cover, in the stages the updating encoders' commands + /// ran in that each update covers: every later command of the group orders after them, to + /// what it may reach of memory no use names. Empty where no member updated a fence. + fenced: Access, + /// What the barriers since the last update made those writes visible to. + fenced_visible: Access, } impl FoldOrder { @@ -171,6 +210,8 @@ impl FoldOrder { pub(crate) fn none() -> FoldOrder { FoldOrder { priors: KeyMap::default(), + fenced: Access::NONE, + fenced_visible: Access::NONE, } } @@ -183,8 +224,14 @@ impl FoldOrder { /// Note the next encoder of the group ended, with `summary`: its uses come after everything /// before it in the group. A write of a range the earlier encoders used replaces what they did - /// there: a barrier ordered them before it as its commands recorded. + /// there: a barrier ordered them before it as its commands recorded. Its fence updates add the + /// writes of the stages they cover to the fenced writes, visible to nothing yet. pub(crate) fn join(&mut self, summary: &Summary) { + let updated = summary.update_stages(); + if !updated.is_empty() { + self.fenced = self.fenced.union(Access::new(updated, writes_in(updated))); + self.fenced_visible = Access::NONE; + } for used in summary.uses() { let priors = self.priors.entry(used.key).or_default(); if !used.write.is_empty() { @@ -271,10 +318,43 @@ impl FoldOrder { (!barrier.src.is_empty() && !barrier.dst.is_empty()).then_some(barrier) } + /// The barrier a command in `stages` with `uses` needs after the group's fenced writes: from + /// them to what the command may reach of memory no use names in its stages + /// ([`unnamed_access`]), and to each of its untracked uses' reads and writes (an indirect + /// argument or uniform read only where such a use reads one; a tracked resource is ordered by + /// [`barrier`](Self::barrier)), where the barriers since made them visible to none of it. + /// `None` where no member updated a fence, or they did. + pub(crate) fn fence_barrier( + &self, + stages: vk::PipelineStageFlags2, + uses: &[Use], + ) -> Option { + if self.fenced.is_empty() { + return None; + } + let untracked = uses.iter().filter(|used| !used.tracked); + let dst = untracked.fold(unnamed_access(stages), |dst, used| { + dst.union(used.read).union(used.write) + }); + (!dst.is_empty() && !self.fenced_visible.covers(dst)).then_some(Barrier { + src: self.fenced, + dst, + }) + } + + /// Whether fenced writes are left that a barrier from everything would order: what + /// [`everything`](Self::everything) records from besides the tracked resources' writes. + pub(crate) fn fenced_open(&self) -> bool { + !self.fenced.is_empty() && !self.fenced_visible.covers(Barrier::everything().dst) + } + /// Note `barrier` recorded: it made each earlier write its source covers visible to its /// destination, and ordered each earlier read its source stages hold before its destination /// stages (a global memory barrier orders every command before it in its source scope). pub(crate) fn ordered(&mut self, barrier: Barrier) { + if !self.fenced.is_empty() && barrier.src.covers(self.fenced) { + self.fenced_visible = self.fenced_visible.union(barrier.dst); + } for prior in self.priors.values_mut().flatten() { if barrier.src.covers(prior.write) { prior.visible = prior.visible.union(barrier.dst); @@ -285,12 +365,15 @@ impl FoldOrder { } } - /// The barrier from every access of the group's earlier encoders not yet ordered to every - /// later access: what a recording that bypasses the per-command order records first. `None` - /// where none is left to order. + /// The barrier from every access of the group's earlier encoders not yet ordered, and their + /// fenced writes, to every later access: what a recording that bypasses the per-command order + /// records first. `None` where none is left to order. pub(crate) fn everything(&self) -> Option { let all = vk::PipelineStageFlags2::ALL_COMMANDS; let mut src = Access::NONE; + if self.fenced_open() { + src = src.union(self.fenced); + } for prior in self.priors.values().flatten() { if !prior.write.is_empty() && !prior.visible.covers(Barrier::everything().dst) { src = src.union(prior.write); @@ -306,6 +389,93 @@ impl FoldOrder { } } +/// The stages of shaders: their storage and sampled accesses reach memory no use names (an +/// argument buffer's, a device address's). +const SHADER_STAGES: vk::PipelineStageFlags2 = vk::PipelineStageFlags2::from_raw( + vk::PipelineStageFlags2::VERTEX_SHADER.as_raw() + | vk::PipelineStageFlags2::TESSELLATION_CONTROL_SHADER.as_raw() + | vk::PipelineStageFlags2::TESSELLATION_EVALUATION_SHADER.as_raw() + | vk::PipelineStageFlags2::GEOMETRY_SHADER.as_raw() + | vk::PipelineStageFlags2::FRAGMENT_SHADER.as_raw() + | vk::PipelineStageFlags2::COMPUTE_SHADER.as_raw() + | vk::PipelineStageFlags2::TASK_SHADER_EXT.as_raw() + | vk::PipelineStageFlags2::MESH_SHADER_EXT.as_raw() + | vk::PipelineStageFlags2::PRE_RASTERIZATION_SHADERS.as_raw(), +); + +/// The stages of transfers. +const TRANSFER_STAGES: vk::PipelineStageFlags2 = vk::PipelineStageFlags2::from_raw( + vk::PipelineStageFlags2::ALL_TRANSFER.as_raw() + | vk::PipelineStageFlags2::COPY.as_raw() + | vk::PipelineStageFlags2::BLIT.as_raw() + | vk::PipelineStageFlags2::RESOLVE.as_raw() + | vk::PipelineStageFlags2::CLEAR.as_raw(), +); + +/// The stages of a pass's attachments. +const ATTACHMENT_STAGES: vk::PipelineStageFlags2 = vk::PipelineStageFlags2::from_raw( + vk::PipelineStageFlags2::COLOR_ATTACHMENT_OUTPUT.as_raw() + | vk::PipelineStageFlags2::EARLY_FRAGMENT_TESTS.as_raw() + | vk::PipelineStageFlags2::LATE_FRAGMENT_TESTS.as_raw(), +); + +/// The stages that name every command's. +const EVERY_STAGE: vk::PipelineStageFlags2 = vk::PipelineStageFlags2::from_raw( + vk::PipelineStageFlags2::ALL_COMMANDS.as_raw() | vk::PipelineStageFlags2::ALL_GRAPHICS.as_raw(), +); + +/// The write access types of commands in `stages`: storage writes in shader stages, transfer +/// writes in transfer stages, attachment writes in a pass's attachment stages, and every write +/// where `stages` names every command's. +fn writes_in(stages: vk::PipelineStageFlags2) -> vk::AccessFlags2 { + let mut access = vk::AccessFlags2::NONE; + if stages.intersects(EVERY_STAGE) { + access |= vk::AccessFlags2::MEMORY_WRITE; + } + if stages.intersects(SHADER_STAGES) { + access |= vk::AccessFlags2::SHADER_STORAGE_WRITE; + } + if stages.intersects(TRANSFER_STAGES) { + access |= vk::AccessFlags2::TRANSFER_WRITE; + } + if stages.intersects(ATTACHMENT_STAGES) { + access |= vk::AccessFlags2::COLOR_ATTACHMENT_WRITE + | vk::AccessFlags2::DEPTH_STENCIL_ATTACHMENT_WRITE; + } + access +} + +/// What a command in `stages` may reach of memory none of its uses names, which a fence orders +/// (**Fences** in the module docs): storage and sampled reads and storage writes in shader +/// stages, transfer reads and writes in transfer stages, attachment reads and writes in a pass's +/// attachment stages, and every access where `stages` names every command's. An indirect +/// argument, uniform, vertex or index read comes only from a use that names it. +fn unnamed_access(stages: vk::PipelineStageFlags2) -> Access { + let mut access = vk::AccessFlags2::NONE; + if stages.intersects(EVERY_STAGE) { + access |= vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE; + } + if stages.intersects(SHADER_STAGES) { + access |= vk::AccessFlags2::SHADER_STORAGE_READ + | vk::AccessFlags2::SHADER_SAMPLED_READ + | vk::AccessFlags2::SHADER_STORAGE_WRITE; + } + if stages.intersects(TRANSFER_STAGES) { + access |= vk::AccessFlags2::TRANSFER_READ | vk::AccessFlags2::TRANSFER_WRITE; + } + if stages.intersects(ATTACHMENT_STAGES) { + access |= vk::AccessFlags2::COLOR_ATTACHMENT_READ + | vk::AccessFlags2::COLOR_ATTACHMENT_WRITE + | vk::AccessFlags2::DEPTH_STENCIL_ATTACHMENT_READ + | vk::AccessFlags2::DEPTH_STENCIL_ATTACHMENT_WRITE; + } + let named = SHADER_STAGES | TRANSFER_STAGES | ATTACHMENT_STAGES | EVERY_STAGE; + match access.is_empty() { + true => Access::NONE, + false => Access::new(stages & named, access), + } +} + /// Merge a resource's priors into one per kind of range. fn coalesce(priors: &mut Vec) { let mut first = 0; @@ -368,6 +538,29 @@ impl Joining { } } +/// Why an encoder that asked for a group joined none (**Refusals** in the module docs): counted +/// as the encoder opens (`WorkCounts::folds_refused_kind` and kin). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Refusal { + /// The group's encoders are of another kind: a compute encoder of another dispatch type than + /// the group's compute encoders, or a render encoder that may not join. + Kind, + /// The group's tail is no longer the command buffer's last `VkCommandBuffer`. + Tail, + /// A batch boundary since the group's last encoder: an event's wait or signal, a host step, + /// a resource state encoder, or a signal pending. + Batch, + /// The command buffer used command predication, its protection options are not 0, or the + /// encoder trail is on. + State, + /// The encoder before left work for later (a segment) or went in more than one part. + Parts, + /// The encoder before fails or faults its command buffer, a command-predication record left + /// its work out, or its batch's submission records after it or judges by it (a write into an + /// ASTC carrier, an `Overwrite`). + Ends, +} + /// The group of encoders whose last ended one's `VkCommandBuffer` is its /// command buffer's tail and may take the next such encoder (the module docs): kept by the /// command buffer between encoders, held by the encoder that joined it while it is open. @@ -491,11 +684,14 @@ pub(crate) struct FoldEnd { pub(crate) in_tail: bool, /// Its place among its command buffer's ended encoders. pub(crate) encoder: usize, - /// Whether its one part leaves nothing that needs a `VkCommandBuffer` boundary after it: no - /// work for later, no fence update, nothing that fails or faults its command buffer, no write - /// into an ASTC carrier and no `Overwrite`. - pub(crate) plain: bool, - /// What that part used, where it is plain and joined a group, whose next encoders order + /// What its one part leaves that needs a `VkCommandBuffer` boundary after it, so no group + /// goes on past it: work for later or more than one part ([`Refusal::Parts`]), or something + /// that fails or faults its command buffer, work a command-predication record left out, a + /// write into an ASTC carrier or an `Overwrite` ([`Refusal::Ends`]); `None` where it leaves + /// nothing. + pub(crate) ends: Option, + /// What that part used, where it leaves nothing (`ends` is `None`) and joined a group, whose + /// next encoders order /// after it; `None` else (the first part of a group it begins holds its summary, which the /// group's second encoder orders after: `State::join_fold`). pub(crate) summary: Option>, diff --git a/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs b/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs index 9d65d97a6..d1e86bda9 100644 --- a/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs +++ b/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs @@ -1,8 +1,9 @@ //! Consecutive compute and blit encoders of one command buffer recorded into one //! `VkCommandBuffer` (`encoder_fold.rs`): which encoders join a group and what ends one, the //! barrier the tracker's rule records between two encoders of a group, a failure or work a -//! command-predication record leaves out that splits a group at the commit, and a rebind that -//! encodes a group again whole. +//! command-predication record leaves out that splits a group at the commit, a rebind that +//! encodes a group again whole, fences inside a group and across queues, and the refusals' +//! counts. //! //! [`dependent_encoders_of_a_group_read_what_the_encoders_before_them_wrote`] is the barrier's //! check: each small encoder reads the tail of the large write the encoder before it made, which @@ -21,8 +22,9 @@ use super::encoder_holds::words_of; use super::rebind_behind_a_wait::{Page, BYTES}; use crate::{ BlitOption, Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, CommitFailure, - ComputePipelineState, Device, EncoderKind, Error, EventRef, FailedEncoders, Origin, - ResourceOptions, Size, Submission, SubmissionCheck, Texture, TextureDescriptor, WorkCounts, + ComputePipelineState, Device, EncoderKind, Error, EventRef, FailedEncoders, Fence, + HazardTrackingMode, Origin, ResourceOptions, Size, Submission, SubmissionCheck, Texture, + TextureDescriptor, WorkCounts, }; use metal2vulkan::metal::{DispatchType, PixelFormat, TextureUsage}; use std::collections::BTreeSet; @@ -54,6 +56,15 @@ fn floats(device: &Device, words: u64, value: impl Fn(u64) -> f32) -> Buffer { .unwrap() } +/// An untracked `Shared` buffer of `words` floats, all 0: only a fence orders its commands +/// across encoders. +fn untracked(device: &Device, words: u64) -> Buffer { + let options = + ResourceOptions::shared().with_hazard_tracking_mode(HazardTrackingMode::Untracked); + let bytes = vec![0u8; (words * 4) as usize]; + device.new_buffer_with_bytes(&bytes, options).unwrap() +} + /// The floats of `buffer`, a host-visible buffer no command writes now. fn read(buffer: &Buffer) -> Vec { words_of(buffer).into_iter().map(f32::from_bits).collect() @@ -107,6 +118,32 @@ impl Kernel { encoder.end_encoding().unwrap(); } + /// [`dispatch`](Self::dispatch) of a serial encoder that first waits for `wait` and last + /// updates `update`, where given. + fn fenced( + &self, + command_buffer: &CommandBuffer, + (wait, update): (Option<&Fence>, Option<&Fence>), + (input, offset): (&Buffer, u64), + (output, words): (&Buffer, u64), + ) { + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + if let Some(fence) = wait { + encoder.wait_for_fence(fence).unwrap(); + } + encoder.set_compute_pipeline_state(&self.state).unwrap(); + encoder.set_buffer(Some(input), offset, 0).unwrap(); + encoder.set_buffer(Some(output), 0, 1).unwrap(); + encoder.set_buffer(Some(&self.scale), 0, 2).unwrap(); + encoder + .dispatch_threads(Size::new(words, 1, 1), Size::new(GROUP, 1, 1)) + .unwrap(); + if let Some(fence) = update { + encoder.update_fence(fence).unwrap(); + } + encoder.end_encoding().unwrap(); + } + /// A blit encoder of `command_buffer` that copies `words` floats of `source` from byte /// `offset` on into `destination`, ended. fn copy( @@ -151,6 +188,8 @@ struct Moved { begun: u64, /// `command_barriers`. barriers: u64, + /// `fold_fence_barriers`. + fence_barriers: u64, } impl Moved { @@ -159,6 +198,7 @@ impl Moved { folded: after.encoders_folded - before.encoders_folded, begun: after.command_buffers_begun_encoders - before.command_buffers_begun_encoders, barriers: after.command_barriers - before.command_barriers, + fence_barriers: after.fold_fence_barriers - before.fold_fence_barriers, } } } @@ -263,7 +303,8 @@ fn encoders_that_share_no_written_resource_record_no_barrier_between_them() { Moved { folded, begun: 1, - barriers: 0 + barriers: 0, + fence_barriers: 0, } ); for output in &outputs { @@ -297,17 +338,24 @@ fn a_change_of_dispatch_type_begins_a_group() { kernel.dispatch(&command_buffer, dispatch_type, (&input, 0), (output, SMALL)); } kernel.run(&command_buffer); - let moved = Moved::of(&before, &device.work_counts()); + let after = device.work_counts(); + let moved = Moved::of(&before, &after); assert_eq!((moved.folded, moved.begun), (2, 3), "{moved:?}"); + assert_eq!( + after.folds_refused_kind - before.folds_refused_kind, + 2, + "each change of dispatch type is a refusal of the group's kind" + ); for output in &outputs { assert_eq!(read(output), expected(SMALL, |i| 2 * i)); } } -/// An encoder that updates a fence ends its group, so a fence orders nothing inside one: the -/// encoder that waits for it begins a group of its own, which the encoder after it joins. +/// An encoder that updates a fence stays in its group: the encoder that waits for the fence joins +/// it after a barrier from everything before (`encoder_fold.rs`'s **Fences**), and the encoder +/// after that one joins it too, with no such barrier. Each reads what the one before wrote. #[test] -fn a_fence_update_ends_a_group() { +fn a_fence_update_stays_in_its_group() { let scratch = Scratch::new("fold-fence"); let kernel = Kernel::new(&scratch); let device = &kernel.device; @@ -323,26 +371,18 @@ fn a_fence_update_ends_a_group() { let before = device.work_counts(); let command_buffer = queue.command_buffer().unwrap(); - let mut encoder = command_buffer.compute_command_encoder().unwrap(); - encoder.set_compute_pipeline_state(&kernel.state).unwrap(); - encoder.set_buffer(Some(&input), 0, 0).unwrap(); - encoder.set_buffer(Some(&buffers[0]), 0, 1).unwrap(); - encoder.set_buffer(Some(&kernel.scale), 0, 2).unwrap(); - encoder - .dispatch_threads(Size::new(SMALL, 1, 1), Size::new(GROUP, 1, 1)) - .unwrap(); - encoder.update_fence(&fence).unwrap(); - encoder.end_encoding().unwrap(); - let mut encoder = command_buffer.compute_command_encoder().unwrap(); - encoder.wait_for_fence(&fence).unwrap(); - encoder.set_compute_pipeline_state(&kernel.state).unwrap(); - encoder.set_buffer(Some(&buffers[0]), 0, 0).unwrap(); - encoder.set_buffer(Some(&buffers[1]), 0, 1).unwrap(); - encoder.set_buffer(Some(&kernel.scale), 0, 2).unwrap(); - encoder - .dispatch_threads(Size::new(SMALL, 1, 1), Size::new(GROUP, 1, 1)) - .unwrap(); - encoder.end_encoding().unwrap(); + kernel.fenced( + &command_buffer, + (None, Some(&fence)), + (&input, 0), + (&buffers[0], SMALL), + ); + kernel.fenced( + &command_buffer, + (Some(&fence), None), + (&buffers[0], 0), + (&buffers[1], SMALL), + ); kernel.dispatch( &command_buffer, serial, @@ -351,16 +391,141 @@ fn a_fence_update_ends_a_group() { ); kernel.run(&command_buffer); let moved = Moved::of(&before, &device.work_counts()); - assert_eq!((moved.folded, moved.begun), (1, 2), "{moved:?}"); + assert_eq!( + (moved.folded, moved.begun, moved.fence_barriers), + (2, 1, 1), + "{moved:?}" + ); for (at, buffer) in buffers.iter().enumerate() { let times = at as u64 + 2; assert_eq!(read(buffer), expected(SMALL, |i| times * i), "buffer {at}"); } } -/// Three compute encoders and a blit encoder's fill of one group, the fill updating a fence, which -/// ends the group, and a compute encoder after it, committed as failed with `encoders`: which of -/// the five ran, read from what each wrote, and how many encoders the commit encoded again +/// A chain of `STEPS` large writes through untracked buffers, each encoder waiting for the fence +/// the one before updated and updating it, each followed by a small read of the tail of what it +/// wrote, also fenced: only the fence orders them. One group of `2 * STEPS` encoders in one +/// `VkCommandBuffer`, each after a barrier from everything before, and every word what the chain +/// computes. +#[test] +fn a_fenced_chain_over_untracked_buffers_records_into_one_command_buffer() { + let scratch = Scratch::new("fold-fenced-chain"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let tail = (LARGE - SMALL) * 4; + let large = [untracked(device, LARGE), untracked(device, LARGE)]; + let small: Vec = (0..STEPS).map(|_| untracked(device, SMALL)).collect(); + let fence = device.new_fence(); + let warm = [ + untracked(device, LARGE), + untracked(device, LARGE), + untracked(device, SMALL), + ]; + let serial = DispatchType::Serial; + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&warm[0], 0), (&warm[1], LARGE)); + kernel.dispatch(&command_buffer, serial, (&warm[1], tail), (&warm[2], SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + let fences = (Some(&fence), Some(&fence)); + for k in 0..STEPS as usize { + let (from, to) = (&large[k % 2], &large[(k + 1) % 2]); + kernel.fenced(&command_buffer, fences, (from, 0), (to, LARGE)); + kernel.fenced(&command_buffer, fences, (to, tail), (&small[k], SMALL)); + } + kernel.run(&command_buffer); + let moved = Moved::of(&before, &device.work_counts()); + // The words first: what a missing barrier changes. Step `k` writes `(k + 1) * i`. + let wrong: Vec<(u64, usize)> = (small.iter().enumerate()) + .map(|(k, small)| { + let k = k as u64; + let value = |j| (k + 1) * (LARGE - SMALL + j) + j; + let read = read(small); + let wanted = expected(SMALL, value); + (k, read.iter().zip(&wanted).filter(|(a, b)| a != b).count()) + }) + .filter(|&(_, wrong)| wrong > 0) + .collect(); + let last = &large[(STEPS % 2) as usize]; + let wrong_last = (read(last).iter().zip(expected(LARGE, |i| STEPS * i))) + .filter(|(a, b)| *a != b) + .count(); + println!( + "FOLD-FENCED-CHAIN {moved:?} small reads wrong (step, words) {wrong:?} last write's \ + words wrong {wrong_last}" + ); + assert_eq!( + (wrong, wrong_last), + (Vec::new(), 0), + "each encoder read what the one before wrote" + ); + let encoders = 2 * STEPS; + assert_eq!( + (moved.folded, moved.begun, moved.fence_barriers), + (encoders - 1, 1, encoders - 1), + "every encoder after the first joined the first's group after a barrier: {moved:?}" + ); +} + +/// A group of two encoders on one queue, the first writing an untracked buffer and updating a +/// fence, the second joining it; a command buffer of another queue committed after it waits for +/// the fence and reads what the first wrote: the wait orders after the whole group. +#[test] +fn a_fence_updated_inside_a_group_orders_another_queue_s_wait() { + let scratch = Scratch::new("fold-fence-queues"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let (writer, reader) = ( + device.new_command_queue().unwrap(), + device.new_command_queue().unwrap(), + ); + let tail = (LARGE - SMALL) * 4; + let input = floats(device, LARGE, |i| i as f32); + let written = untracked(device, LARGE); + let other = untracked(device, SMALL); + let read_back = untracked(device, SMALL); + let fence = device.new_fence(); + let warm = [untracked(device, LARGE), untracked(device, SMALL)]; + let serial = DispatchType::Serial; + let command_buffer = writer.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&warm[0], LARGE)); + kernel.dispatch(&command_buffer, serial, (&warm[0], tail), (&warm[1], SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let first = writer.command_buffer().unwrap(); + kernel.fenced(&first, (None, Some(&fence)), (&input, 0), (&written, LARGE)); + kernel.dispatch(&first, serial, (&input, 0), (&other, SMALL)); + let second = reader.command_buffer().unwrap(); + kernel.fenced( + &second, + (Some(&fence), None), + (&written, tail), + (&read_back, SMALL), + ); + first.commit().unwrap(); + kernel.run(&second); + first.wait_until_completed_for(WAIT).unwrap(); + let moved = Moved::of(&before, &device.work_counts()); + assert_eq!( + read(&read_back), + expected(SMALL, |j| 2 * (LARGE - SMALL + j) + j), + "the other queue's read after the wait read what the group's first encoder wrote" + ); + assert_eq!(read(&other), expected(SMALL, |i| 2 * i)); + assert_eq!( + (moved.folded, moved.begun, moved.fence_barriers), + (1, 2, 1), + "the writer's two encoders in one group, the reader's alone: {moved:?}" + ); +} + +/// Three serial compute encoders and a blit encoder's fill of one group, and a concurrent compute +/// encoder after it, which begins a group of its own, committed as failed with `encoders`: which +/// of the five ran, read from what each wrote, and how many encoders the commit encoded again /// (`WorkCounts::encoders_reencoded`). fn failed_with(encoders: FailedEncoders) -> ([bool; 5], u64) { let scratch = Scratch::new("fold-failed"); @@ -380,12 +545,16 @@ fn failed_with(encoders: FailedEncoders) -> ([bool; 5], u64) { for output in &outputs[..3] { kernel.dispatch(&command_buffer, serial, (&input, 0), (output, SMALL)); } - let fence = device.new_fence(); let mut blit = command_buffer.blit_command_encoder().unwrap(); blit.fill_buffer(&outputs[3], 0..SMALL * 4, FILL).unwrap(); - blit.update_fence(&fence).unwrap(); blit.end_encoding().unwrap(); - kernel.dispatch(&command_buffer, serial, (&input, 0), (&outputs[4], SMALL)); + let concurrent = DispatchType::Concurrent; + kernel.dispatch( + &command_buffer, + concurrent, + (&input, 0), + (&outputs[4], SMALL), + ); let moved = Moved::of(&before, &device.work_counts()); assert_eq!((moved.folded, moved.begun), (3, 2), "{moved:?}"); let failure = CommitFailure { @@ -518,7 +687,7 @@ fn a_first_failed_encoder_inside_a_group_runs_the_group_s_encoders_before_it() { assert_eq!(failed_with(from), ([true, false, false, false, false], 1)); } -/// A first failed encoder at a group's boundary (the encoder after a fence update) splits no +/// A first failed encoder at a group's boundary (an encoder of the other dispatch type) splits no /// group: the group before it runs as recorded. #[test] fn a_first_failed_encoder_at_a_group_s_boundary_fails_from_there() { @@ -825,8 +994,14 @@ fn an_event_signal_before_a_blit_encoder_begins_a_group() { kernel.copy(&command_buffer, (&outputs[0], 0), (&copied, SMALL)); kernel.dispatch(&command_buffer, serial, (&copied, 0), (&outputs[1], SMALL)); kernel.run(&command_buffer); - let moved = Moved::of(&before, &device.work_counts()); + let after = device.work_counts(); + let moved = Moved::of(&before, &after); assert_eq!((moved.folded, moved.begun), (1, 2), "{moved:?}"); + assert_eq!( + after.folds_refused_batch - before.folds_refused_batch, + 1, + "the signal is a batch boundary the blit encoder's join is refused at" + ); assert_eq!(read(&copied), expected(SMALL, |i| 2 * i)); assert_eq!(read(&outputs[1]), expected(SMALL, |i| 3 * i)); } @@ -1183,9 +1358,9 @@ fn work_left_out_past_a_group_s_first_encoder_splits_the_group() { ); } -/// A group of two compute encoders, the second writing a buffer over host pages and updating a -/// fence (which ends the group and its unit of command predication), then a compute encoder of -/// an If, so the command buffer used command predication: committed behind an event wait only +/// A group of two serial compute encoders, the second writing a buffer over host pages, then a +/// concurrent compute encoder (which begins a group and a unit of command predication of its own) +/// of an If, so the command buffer used command predication: committed behind an event wait only /// the host signals, the buffer rebound before the signal. The group's unit laid no step, so each /// of its encoders encodes again alone (`Predication::alone`): the rebind encodes both again, /// refusing none, and the command buffer writes the pages the buffer lies in. @@ -1222,7 +1397,6 @@ fn a_rebind_encodes_a_group_again_in_a_command_buffer_of_command_predication() { let word = device .new_buffer_with_bytes(&0u32.to_le_bytes(), ResourceOptions::shared()) .unwrap(); - let fence = device.new_fence(); let serial = DispatchType::Serial; let warm = floats(device, words, |_| 0.0); let command_buffer = queue.command_buffer().unwrap(); @@ -1245,9 +1419,10 @@ fn a_rebind_encodes_a_group_again_in_a_command_buffer_of_command_predication() { encoder .dispatch_threads(Size::new(words, 1, 1), Size::new(GROUP, 1, 1)) .unwrap(); - encoder.update_fence(&fence).unwrap(); encoder.end_encoding().unwrap(); - let mut encoder = command_buffer.compute_command_encoder().unwrap(); + let mut encoder = command_buffer + .compute_command_encoder_with_dispatch_type(DispatchType::Concurrent) + .unwrap(); // Comparison 0: `word == reference`, which holds. encoder.encode_start_if(Some(&word), 0, 0, 0).unwrap(); encoder.set_compute_pipeline_state(&kernel.state).unwrap(); diff --git a/crates/metal2vulkan-runtime/src/tests/fence_fold_bench.rs b/crates/metal2vulkan-runtime/src/tests/fence_fold_bench.rs new file mode 100644 index 000000000..782ef56fc --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/fence_fold_bench.rs @@ -0,0 +1,257 @@ +//! What a command buffer of fenced encoders costs: its encoders' opens and ends on the host, its +//! `vkQueueSubmit` call, the GPU's start after it, and its GPU time from its first command's start +//! to its last's end, by the shape of its encoders' fences (`encoder_fold.rs`'s **Fences**). The +//! shapes, each [`ENCODERS`] serial compute encoders of one dispatch over [`THREADS`] threads, a +//! command buffer at a time, waited for: +//! - **Independent, updating**: each writes a buffer of its own from one input and updates one +//! fence; none waits for it. Nothing orders them but what the runtime records. +//! - **Independent**: the same with no fence. +//! - **Chain, wait first**: each waits for the fence, then dispatches, reading what the one before +//! wrote through untracked buffers (only the fence orders them), then updates the fence. +//! - **Chain, wait after the dispatch**: the same with the wait after the dispatch, which still +//! covers it (`waitForFence:`, "a fence that the pass waits for before it runs any of its +//! commands"). +//! +//! Each shape runs [`COMMAND_BUFFERS`] command buffers a round, [`ROUNDS`] rounds, interleaved, on +//! a device that writes GPU timestamps. Printed (`FENCE-FOLD`), per shape: the +//! `VkCommandBuffer`s a submission and the encoders folded a command buffer, the mean host time +//! of an encoder's open (`compute_command_encoder`) and of its `end_encoding`, the mean call, and +//! the median and 90th percentile of the GPU's start after the call (`gpu_start_time` from +//! `kernel_end_time`) and of the GPU time (`gpu_end_time` from `gpu_start_time`); and the counts +//! named `folds_refused_*` and `fold_fence_barriers` that moved, read from the counts' `Debug` +//! form so that the bench builds where they do not exist. +//! +//! Ignored: run it in release under `--cfg m2v_gpu`, +//! `cargo test --release -p metal2vulkan-runtime --lib fence_fold_bench -- --ignored --nocapture`. + +use super::blit_holds::{plan_device, Scratch, WAIT}; +use crate::{ + Buffer, CommandBuffer, CommandQueue, ComputePipelineState, Device, Fence, HazardTrackingMode, + ResourceOptions, Size, WorkCounts, +}; +use std::collections::BTreeMap; +use std::time::Instant; + +/// The encoders of each command buffer. +const ENCODERS: usize = 24; +/// The threads of each dispatch, in threadgroups of [`GROUP`]. +const THREADS: u64 = 1 << 14; +const GROUP: u64 = 64; +/// The command buffers of each shape a round. +const COMMAND_BUFFERS: usize = 200; +/// The rounds. +const ROUNDS: usize = 3; + +/// A shape of a command buffer's encoders. +#[derive(Clone, Copy, PartialEq)] +enum Shape { + IndependentUpdating, + Independent, + WaitFirst, + WaitAfter, +} + +const SHAPES: [(Shape, &str); 4] = [ + (Shape::IndependentUpdating, "independent, updating"), + (Shape::Independent, "independent"), + (Shape::WaitFirst, "chain, wait first"), + (Shape::WaitAfter, "chain, wait after the dispatch"), +]; + +/// The kernel (`output[i] = input[i] * scale + i`) and what its shapes read and write. +struct Rig { + device: Device, + queue: CommandQueue, + state: ComputePipelineState, + scale: Buffer, + input: Buffer, + outputs: Vec, + chain: [Buffer; 2], + fence: Fence, +} + +/// The host time a command buffer's encoders' opens and ends took, in nanoseconds. +#[derive(Default)] +struct Host { + opens: u128, + ends: u128, +} + +impl Rig { + fn new(device: Device) -> Rig { + let floats = + |words: u64, options: ResourceOptions| device.new_buffer(words * 4, options).unwrap(); + let untracked = + ResourceOptions::private().with_hazard_tracking_mode(HazardTrackingMode::Untracked); + Rig { + state: super::dispatch_pending::state(&device), + scale: device + .new_buffer_with_bytes(&1f32.to_le_bytes(), ResourceOptions::shared()) + .unwrap(), + input: floats(THREADS, ResourceOptions::private()), + outputs: (0..ENCODERS) + .map(|_| floats(THREADS, ResourceOptions::private())) + .collect(), + chain: [floats(THREADS, untracked), floats(THREADS, untracked)], + fence: device.new_fence(), + queue: device.new_command_queue().unwrap(), + device, + } + } + + /// A command buffer of `shape`, committed, with the host time its encoders' opens and ends + /// took. + fn commit(&self, shape: Shape) -> (CommandBuffer, Host) { + let command_buffer = self.queue.command_buffer().unwrap(); + let mut host = Host::default(); + for k in 0..ENCODERS { + let opened = Instant::now(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + host.opens += opened.elapsed().as_nanos(); + if shape == Shape::WaitFirst { + encoder.wait_for_fence(&self.fence).unwrap(); + } + let (input, output) = match shape { + Shape::WaitFirst | Shape::WaitAfter => { + (&self.chain[k % 2], &self.chain[(k + 1) % 2]) + } + _ => (&self.input, &self.outputs[k]), + }; + encoder.set_compute_pipeline_state(&self.state).unwrap(); + encoder.set_buffer(Some(input), 0, 0).unwrap(); + encoder.set_buffer(Some(output), 0, 1).unwrap(); + encoder.set_buffer(Some(&self.scale), 0, 2).unwrap(); + encoder + .dispatch_threads(Size::new(THREADS, 1, 1), Size::new(GROUP, 1, 1)) + .unwrap(); + if shape == Shape::WaitAfter { + encoder.wait_for_fence(&self.fence).unwrap(); + } + if shape != Shape::Independent { + encoder.update_fence(&self.fence).unwrap(); + } + let ending = Instant::now(); + encoder.end_encoding().unwrap(); + host.ends += ending.elapsed().as_nanos(); + } + command_buffer.commit().unwrap(); + (command_buffer, host) + } +} + +/// The counts named `folds_refused_*` and `fold_fence_barriers` in `counts`' `Debug` form. +fn fold_counts(counts: &WorkCounts) -> BTreeMap { + let text = format!("{counts:?}"); + text.split([',', '{', '}']) + .filter_map(|field| { + let (name, value) = field.split_once(':')?; + let name = name.trim(); + if !(name.starts_with("folds_refused_") || name == "fold_fence_barriers") { + return None; + } + Some((name.to_owned(), value.trim().parse().ok()?)) + }) + .collect() +} + +/// What a shape's command buffers showed: the counts' change, the host times, and each one's GPU +/// start after its call and GPU time, in seconds. +#[derive(Default)] +struct Seen { + command_buffers: u64, + submissions: u64, + vk_command_buffers: u64, + folded: u64, + call_nanos: u64, + opens: u128, + ends: u128, + fold: BTreeMap, + starts: Vec, + gpu: Vec, +} + +impl Seen { + fn add( + &mut self, + (before, after): (&WorkCounts, &WorkCounts), + command_buffer: &CommandBuffer, + host: Host, + ) { + self.command_buffers += 1; + self.submissions += after.queue_submissions - before.queue_submissions; + self.vk_command_buffers += + after.command_buffers_submitted - before.command_buffers_submitted; + self.folded += after.encoders_folded - before.encoders_folded; + self.call_nanos += after.batch_submit_nanos - before.batch_submit_nanos; + self.opens += host.opens; + self.ends += host.ends; + let earlier = fold_counts(before); + for (name, value) in fold_counts(after) { + let moved = value - earlier.get(&name).copied().unwrap_or(0); + *self.fold.entry(name).or_default() += moved; + } + let (start, end) = ( + command_buffer.gpu_start_time().unwrap(), + command_buffer.gpu_end_time().unwrap(), + ); + self.starts.push(start - command_buffer.kernel_end_time()); + self.gpu.push(end - start); + } +} + +fn quantile(values: &[f64], q: f64) -> f64 { + let mut sorted = values.to_vec(); + sorted.sort_by(f64::total_cmp); + sorted[((sorted.len() as f64 * q) as usize).min(sorted.len() - 1)] * 1e6 +} + +#[test] +#[ignore = "a release benchmark: run with --ignored --nocapture"] +fn fence_fold_bench() { + let scratch = Scratch::new("fence-fold"); + let rig = Rig::new(plan_device(&scratch.0)); + println!("FENCE-FOLD on {}", rig.device.name()); + // Warm: the pipelines made, so no dispatch leaves work for later. + for (shape, _) in SHAPES { + rig.commit(shape).0.wait_until_completed_for(WAIT).unwrap(); + } + let mut seen: Vec = SHAPES.iter().map(|_| Seen::default()).collect(); + for _ in 0..ROUNDS { + for ((shape, _), seen) in SHAPES.iter().zip(&mut seen) { + for _ in 0..COMMAND_BUFFERS { + let before = rig.device.work_counts(); + let (command_buffer, host) = rig.commit(*shape); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let after = rig.device.work_counts(); + seen.add((&before, &after), &command_buffer, host); + } + } + } + for ((_, name), seen) in SHAPES.iter().zip(&seen) { + let submissions = seen.submissions.max(1); + let encoders = (seen.command_buffers * ENCODERS as u64) as f64; + let moved: Vec = (seen.fold.iter()) + .filter(|(_, value)| **value > 0) + .map(|(name, value)| format!("{name} {value}")) + .collect(); + println!( + "FENCE-FOLD {name}: {:.1} VkCommandBuffers a submission, {:.1} encoders folded a \ + command buffer; an encoder's open {:.2} us, its end {:.2} us; mean call {:.1} us; GPU \ + start after the call median {:.1} us, p90 {:.1} us; GPU time median {:.1} us, p90 \ + {:.1} us; moved: {}", + seen.vk_command_buffers as f64 / submissions as f64, + seen.folded as f64 / seen.command_buffers as f64, + seen.opens as f64 / encoders / 1e3, + seen.ends as f64 / encoders / 1e3, + seen.call_nanos as f64 / submissions as f64 / 1e3, + quantile(&seen.starts, 0.5), + quantile(&seen.starts, 0.9), + quantile(&seen.gpu, 0.5), + quantile(&seen.gpu, 0.9), + match moved.is_empty() { + true => "none".to_owned(), + false => moved.join(", "), + }, + ); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index f8ee6d63b..d5fae6da5 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -261,6 +261,8 @@ mod exported_semaphore; #[cfg(all(unix, any(m2v_gpu, m2v_cpu_icd)))] mod exported_textures; mod families; +#[cfg(m2v_gpu)] +mod fence_fold_bench; mod fences; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod fetch_composite; diff --git a/crates/metal2vulkan-runtime/src/tests/render_fold.rs b/crates/metal2vulkan-runtime/src/tests/render_fold.rs index 7480dc4c9..e592da03a 100644 --- a/crates/metal2vulkan-runtime/src/tests/render_fold.rs +++ b/crates/metal2vulkan-runtime/src/tests/render_fold.rs @@ -29,7 +29,7 @@ use crate::{ WorkCounts, }; use metal2vulkan::device::RenderLoweringPolicy; -use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureType, TextureUsage}; +use metal2vulkan::metal::{DispatchType, PixelFormat, PrimitiveType, TextureType, TextureUsage}; use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; use std::collections::BTreeSet; use std::num::NonZeroU64; @@ -170,7 +170,19 @@ impl Lane { /// A compute encoder that writes [`DRAWN`] for every vertex into `colors`, ended. fn dispatch(&self, command_buffer: &CommandBuffer, colors: &Buffer) { - let mut encoder = command_buffer.compute_command_encoder().unwrap(); + self.dispatch_of(command_buffer, DispatchType::Serial, colors); + } + + /// [`dispatch`](Self::dispatch) in an encoder of `dispatch_type`. + fn dispatch_of( + &self, + command_buffer: &CommandBuffer, + dispatch_type: DispatchType, + colors: &Buffer, + ) { + let mut encoder = command_buffer + .compute_command_encoder_with_dispatch_type(dispatch_type) + .unwrap(); encoder.set_compute_pipeline_state(&self.compute).unwrap(); encoder.set_buffer(Some(&self.from), 0, 0).unwrap(); encoder.set_buffer(Some(colors), 0, 1).unwrap(); @@ -683,7 +695,7 @@ fn a_late_resolve_records_in_its_group() { } /// A compute encoder, a render encoder, a compute encoder and a blit encoder's fill of one group, -/// the fill updating a fence, which ends the group, and a compute encoder after it, committed as +/// and a concurrent compute encoder after it, which begins a group of its own, committed as /// failed with `encoders`: which of the five ran (each compute encoder writes the colors of a /// buffer of its own, the render encoder draws over a target the copy after the commit reads), /// and how many encoders the commit encoded again (`WorkCounts::encoders_reencoded`). @@ -698,13 +710,11 @@ fn failed_with(encoders: FailedEncoders) -> ([bool; 5], u64) { lane.dispatch(&command_buffer, &outputs[0]); lane.draw(&command_buffer, &target, LoadAction::DontCare, &lane.colors); lane.dispatch(&command_buffer, &outputs[2]); - let fence = lane.device.new_fence(); let mut blit = command_buffer.blit_command_encoder().unwrap(); blit.fill_buffer(&outputs[3], 0..COLOR_WORDS * 4, 0x5a) .unwrap(); - blit.update_fence(&fence).unwrap(); blit.end_encoding().unwrap(); - lane.dispatch(&command_buffer, &outputs[4]); + lane.dispatch_of(&command_buffer, DispatchType::Concurrent, &outputs[4]); let moved = Moved::of(&before, &lane.device.work_counts()); assert_eq!((moved.folded, moved.begun), (3, 2), "{moved:?}"); let failure = CommitFailure { diff --git a/crates/metal2vulkan-runtime/src/tests/spares.rs b/crates/metal2vulkan-runtime/src/tests/spares.rs index ba633aa7f..9eb1884b1 100644 --- a/crates/metal2vulkan-runtime/src/tests/spares.rs +++ b/crates/metal2vulkan-runtime/src/tests/spares.rs @@ -732,10 +732,10 @@ mod device { use crate::tests::encoder_holds::library; use crate::tests::freed_memory::device; use crate::{ - Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, Fence, PipelineOptions, + Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, }; - use metal2vulkan::metal::PrimitiveType; + use metal2vulkan::metal::{DispatchType, PrimitiveType}; use metal2vulkan::pipeline::{RenderPipelineDescriptor, StageSource}; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -794,23 +794,31 @@ mod device { /// once it completed or failed. fn committed(queue: &CommandQueue, targets: &[&Buffer]) -> CommandBufferStatus { let command_buffer = queue.command_buffer().unwrap(); - let fence = queue.device().new_fence(); for (at, target) in targets.iter().enumerate() { - fill_apart(&command_buffer, target, at as u8, &fence); + fill_apart(&command_buffer, target, at); } command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); command_buffer.status() } - /// A blit encoder of `command_buffer` filling the first 256 bytes of `target` with `value` - /// that updates `fence`: an encoder that updates a fence ends the group of encoders it records - /// with (`encoder_fold.rs`), so each such encoder records into a `VkCommandBuffer` of its own, - /// which these tests count. - fn fill_apart(command_buffer: &CommandBuffer, target: &Buffer, value: u8, fence: &Fence) { + /// The `at`th fill of `command_buffer`: a compute encoder with no command, of the serial + /// dispatch type where `at` is even and of the concurrent one where it is odd, then a blit + /// encoder filling the first 256 bytes of `target` with `at`'s low byte. A compute encoder of + /// another dispatch type than its group's begins a group of encoders of its own + /// (`encoder_fold.rs`), which the blit encoder joins, so each fill records into a + /// `VkCommandBuffer` of its own, which these tests count. + fn fill_apart(command_buffer: &CommandBuffer, target: &Buffer, at: usize) { + let dispatch_type = match at % 2 { + 0 => DispatchType::Serial, + _ => DispatchType::Concurrent, + }; + let encoder = command_buffer + .compute_command_encoder_with_dispatch_type(dispatch_type) + .unwrap(); + encoder.end_encoding().unwrap(); let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.fill_buffer(target, 0..256, value).unwrap(); - blit.update_fence(fence).unwrap(); + blit.fill_buffer(target, 0..256, at as u8).unwrap(); blit.end_encoding().unwrap(); } @@ -978,9 +986,8 @@ mod device { let target = device.new_buffer(4096, ResourceOptions::private()).unwrap(); let encoded = |encoders: usize| { let command_buffer = queue.command_buffer().unwrap(); - let fence = device.new_fence(); for at in 0..encoders { - fill_apart(&command_buffer, &target, at as u8, &fence); + fill_apart(&command_buffer, &target, at); } command_buffer }; @@ -1070,9 +1077,8 @@ mod device { let command_buffers: Vec<_> = (0..APART) .map(|_| { let command_buffer = queue.command_buffer().unwrap(); - let fence = device.new_fence(); for at in 0..EACH { - fill_apart(&command_buffer, &target, at as u8, &fence); + fill_apart(&command_buffer, &target, at); } command_buffer }) diff --git a/crates/metal2vulkan-runtime/src/tests/tracker.rs b/crates/metal2vulkan-runtime/src/tests/tracker.rs index 7f15e4b48..bebc7be1d 100644 --- a/crates/metal2vulkan-runtime/src/tests/tracker.rs +++ b/crates/metal2vulkan-runtime/src/tests/tracker.rs @@ -1670,6 +1670,50 @@ fn a_folded_encoder_s_first_dispatch_takes_a_serial_encoder_s_barrier() { ); } +/// A group's encoder after one that wrote an untracked buffer and updated a fence +/// (`encoder_fold.rs`'s **Fences**): its first dispatch orders after the fenced writes by the +/// least barrier between dispatches; a later dispatch that reaches no more records none; one that +/// reads indirect arguments of an untracked buffer, a barrier widened to them alone; a tracked +/// uniform read, none, the tracked order covering it; and a group with no fence update, none. +#[test] +fn a_folded_encoder_after_a_fence_update_takes_the_least_barrier_widened_only_by_its_reads() { + let written = [Use::writes(5, false, bytes(0..64), shader_write())]; + let writer = |fence: Option| { + let mut first = EncoderUses::::new(true); + first.order(COMPUTE, &written, Reach::Unnamed); + if let Some(fence) = fence { + first.update_fence(fence, None); + } + FoldOrder::after(&first.finish()) + }; + let unfenced = writer(None); + let mut order = writer(Some(100)); + let dispatch = [Use::reads(5, false, bytes(0..64), shader_read())]; + assert_eq!(unfenced.fence_barrier(COMPUTE, &dispatch), None); + let fenced = order.fence_barrier(COMPUTE, &dispatch).unwrap(); + assert_eq!(fenced.legacy(), least_between_dispatches()); + order.ordered(fenced); + assert_eq!(order.fence_barrier(COMPUTE, &dispatch), None); + let uniform = Access::new(COMPUTE, vk::AccessFlags2::UNIFORM_READ); + assert_eq!( + order.fence_barrier(COMPUTE, &[Use::reads(7, true, bytes(0..16), uniform)]), + None + ); + let indirect = vk::PipelineStageFlags2::DRAW_INDIRECT; + let arguments = Access::new(indirect, vk::AccessFlags2::INDIRECT_COMMAND_READ); + let widened = order.fence_barrier( + COMPUTE | indirect, + &[Use::reads(6, false, bytes(0..16), arguments)], + ); + assert_eq!( + widened, + Some(Barrier { + src: fenced.src, + dst: fenced.dst.union(arguments) + }) + ); +} + #[test] fn a_memory_barrier_records_the_least_barrier_and_keeps_metal_s_promise() { assert_eq!( diff --git a/crates/metal2vulkan-runtime/src/tracker.rs b/crates/metal2vulkan-runtime/src/tracker.rs index c37b188d3..f7724acdf 100644 --- a/crates/metal2vulkan-runtime/src/tracker.rs +++ b/crates/metal2vulkan-runtime/src/tracker.rs @@ -2631,11 +2631,6 @@ impl Summary { Summary::of_fences(fences(&self.waits), fences(&self.updates)) } - /// Whether it updates a fence. - pub(super) fn has_updates(&self) -> bool { - !self.updates.is_empty() - } - /// Split it in two: its uses, stages and fence waits, and its fence updates alone, in its /// stages. A compute encoder recorded into the `VkCommandBuffer` of the encoders before it /// (`encoder_fold.rs`) joins the first to their first part's summary, where the work it @@ -2798,6 +2793,14 @@ impl Summary { &self.uses } + /// The stages its fence updates cover of those its commands ran in ([`FenceUse`]): none + /// where it updates no fence. + pub(super) fn update_stages(&self) -> vk::PipelineStageFlags2 { + (self.updates.iter()).fold(vk::PipelineStageFlags2::NONE, |all, used| { + all | used.covered(self.stages) + }) + } + /// Every stage the encoder's commands ran in. 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 6fe13115c..d1f8eea61 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -10,6 +10,7 @@ use super::churn_counts::{VkMaking, VkRelease}; use super::command_buffer::GroupEnd; use super::degradation::{Degradation, Told}; use super::device::lock; +use super::encoder_fold::Refusal; use super::heap_sets::Unkept; use super::memory::FreeCause; use super::recorder::CommandsRecorded; @@ -392,6 +393,13 @@ pub(crate) struct Counters { inline_passes_split: AtomicU64, encoders_barriered_at_open: AtomicU64, encoders_folded: AtomicU64, + folds_refused_kind: AtomicU64, + folds_refused_tail: AtomicU64, + folds_refused_batch: AtomicU64, + folds_refused_state: AtomicU64, + folds_refused_parts: AtomicU64, + folds_refused_ends: AtomicU64, + fold_fence_barriers: AtomicU64, parked_compute_taken: AtomicU64, record_lists_grown: AtomicU64, record_storage_kept: AtomicU64, @@ -3945,6 +3953,26 @@ impl Counters { self.encoders_folded.fetch_add(1, Ordering::Relaxed); } + /// A compute, blit or render encoder that asked for a group of encoders joined none, for + /// `why` (`encoder_fold.rs`'s **Refusals**). + pub(crate) fn fold_refused(&self, why: Refusal) { + let counter = match why { + Refusal::Kind => &self.folds_refused_kind, + Refusal::Tail => &self.folds_refused_tail, + Refusal::Batch => &self.folds_refused_batch, + Refusal::State => &self.folds_refused_state, + Refusal::Parts => &self.folds_refused_parts, + Refusal::Ends => &self.folds_refused_ends, + }; + counter.fetch_add(1, Ordering::Relaxed); + } + + /// A command of a group's encoder recorded a barrier after the writes a member's fence update + /// covers (`encoder_fold.rs`'s **Fences**). + pub(crate) fn fold_fence_barrier(&self) { + self.fold_fence_barriers.fetch_add(1, Ordering::Relaxed); + } + /// A compute encoder opened on the core's box and the bind state its command buffer's last /// compute encoder parked (`compute/live.rs`'s `Parked`). pub(crate) fn parked_compute_taken(&self) { @@ -7534,12 +7562,44 @@ pub struct WorkCounts { /// Compute, blit and render encoders that began no `VkCommandBuffer` of their own: each /// recorded into the one of the encoders before it in its command buffer, where nothing /// between them needs a boundary (the same batch, a compute encoder's dispatch type that of - /// the group's compute encoders, no work left for later, no fence update, nothing failing; a + /// the group's compute encoders, no work left for later, nothing failing; a /// render encoder's pass recorded at its end, with a log of its calls), after the barrier the /// tracker plans between two encoders of a batch, and its batch's submission submits no /// command buffer for it, of barriers or of its own. Of `encoder_command_buffers_begun`'s /// encoders, those it does not count. pub encoders_folded: u64, + /// Compute, blit and render encoders that asked for a group of encoders and joined none + /// because the group's encoders were of another kind: a compute encoder of another dispatch + /// type than the group's compute encoders, or a render encoder that may not join; and an + /// encoder after one that asks for no group. Each refusal is counted once, as the encoder + /// opens, by the first reason that holds, in the order of these counts; the command buffer's + /// first encoder is refused nothing (`encoder_fold.rs`'s **Refusals**). + pub folds_refused_kind: u64, + /// Of those refusals, where the group's shared `VkCommandBuffer` was no longer the command + /// buffer's last. + pub folds_refused_tail: u64, + /// Of those refusals, a batch boundary since the group's last encoder: an event's wait or + /// signal, a host step, a resource state encoder, or a signal pending. + pub folds_refused_batch: u64, + /// Of those refusals, where the command buffer used command predication, its protection + /// options were not 0, or the encoder trail was on. + pub folds_refused_state: u64, + /// Of those refusals, where the encoder before left work for later (a dispatch whose + /// pipelines were being made, an indirect command buffer's execution) or went in more than one + /// part (a host step inside it). + pub folds_refused_parts: u64, + /// Of those refusals, where the encoder before failed or faulted its command buffer, a + /// command-predication record left its work out, or its batch's submission records after it + /// or judges by it (a write into an ASTC carrier, a texture written whole before any of its + /// commands read it). + pub folds_refused_ends: u64, + /// Commands of encoders of a group after a member of it updated a fence whose barrier orders + /// them after the writes the update covers, whether or not their encoder waits for the fence + /// (a wait covers all of an encoder's commands, and may come after some of them went into the + /// group's `VkCommandBuffer`): from those writes to what the command may reach of memory no + /// use names in its stages and to its uses' accesses, once for each wider reach + /// (`encoder_fold.rs`'s **Fences**). + pub fold_fence_barriers: u64, /// Compute encoders that opened on the box of their core and the bind state (with what its /// last dispatch settled) the command buffer's last compute encoder left, rather than on the /// device's spares: each compute encoder's end parks them in its command buffer for the next, @@ -11973,6 +12033,13 @@ impl Device { inline_passes: counters.inline_passes.load(Ordering::Relaxed), encoders_barriered_at_open: counters.encoders_barriered_at_open.load(Ordering::Relaxed), encoders_folded: counters.encoders_folded.load(Ordering::Relaxed), + folds_refused_kind: counters.folds_refused_kind.load(Ordering::Relaxed), + folds_refused_tail: counters.folds_refused_tail.load(Ordering::Relaxed), + folds_refused_batch: counters.folds_refused_batch.load(Ordering::Relaxed), + folds_refused_state: counters.folds_refused_state.load(Ordering::Relaxed), + folds_refused_parts: counters.folds_refused_parts.load(Ordering::Relaxed), + folds_refused_ends: counters.folds_refused_ends.load(Ordering::Relaxed), + fold_fence_barriers: counters.fold_fence_barriers.load(Ordering::Relaxed), parked_compute_taken: counters.parked_compute_taken.load(Ordering::Relaxed), record_lists_grown: counters.record_lists_grown.load(Ordering::Relaxed), record_storage_kept: counters.record_storage_kept.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index c78544c78..4f57c65bc 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2383; +pub const RUNTIME_VERSION: u32 = 2384; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index ddb6082d4..6cb03a297 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3066,6 +3066,13 @@ field metal2vulkan-runtime::WorkCounts.first_work_order_waits pub first_work_ord field metal2vulkan-runtime::WorkCounts.first_work_waits pub first_work_waits: u64 field metal2vulkan-runtime::WorkCounts.first_work_waits_unused pub first_work_waits_unused: u64 field metal2vulkan-runtime::WorkCounts.flights_followed pub flights_followed: u64 +field metal2vulkan-runtime::WorkCounts.fold_fence_barriers pub fold_fence_barriers: u64 +field metal2vulkan-runtime::WorkCounts.folds_refused_batch pub folds_refused_batch: u64 +field metal2vulkan-runtime::WorkCounts.folds_refused_ends pub folds_refused_ends: u64 +field metal2vulkan-runtime::WorkCounts.folds_refused_kind pub folds_refused_kind: u64 +field metal2vulkan-runtime::WorkCounts.folds_refused_parts pub folds_refused_parts: u64 +field metal2vulkan-runtime::WorkCounts.folds_refused_state pub folds_refused_state: u64 +field metal2vulkan-runtime::WorkCounts.folds_refused_tail pub folds_refused_tail: u64 field metal2vulkan-runtime::WorkCounts.footprint_lock_waits pub footprint_lock_waits: u64 field metal2vulkan-runtime::WorkCounts.footprints_built pub footprints_built: u64 field metal2vulkan-runtime::WorkCounts.fragment_shader_libraries_made pub fragment_shader_libraries_made: u64 diff --git a/docs/API.md b/docs/API.md index 64da7c0a9..59cc70e60 100644 --- a/docs/API.md +++ b/docs/API.md @@ -5667,7 +5667,7 @@ each item named states the rule in full. laid a loop or left work out fails the whole group.** The runtime records a compute or blit encoder into the `VkCommandBuffer` of the compute, blit or render encoder before it where nothing needs a boundary between them: a compute encoder's dispatch type that of the group's - compute encoders, the same batch (no event wait or signal between them), no fence update or work + compute encoders, the same batch (no event wait or signal between them), no work left for later in the earlier one, nor a write into an ASTC texture or a write of a new texture whole before any read, no command predication yet, the encoder trail off (`DeviceOptions::encoder_trail`) and protection options 0 (`WorkCounts::encoders_folded` counts @@ -5681,7 +5681,13 @@ each item named states the rule in full. 3090), a command that uses an image over bytes written before it in its `VkCommandBuffer` goes on in a new one, a grouped encoder's in its own (`WorkCounts::command_buffers_split_at_aliases`); a grouped render encoder's pass goes on in a new one before it where the pass or one of its - draws uses such an image. A failure that + draws uses such an image. An encoder that updates a fence stays in its group: every command of + a later member orders after the writes the update covers, whether or not its encoder waits for + the fence, which orders more than Metal does, through the narrowest barrier that covers a + fence: from those writes' stages to the command's own stages' storage, sampled and transfer + accesses and its bound resources' accesses (`WorkCounts::fold_fence_barriers`); + `WorkCounts::folds_refused_kind` and its kin count the encoders that joined no group by reason. + A failure that fails some of such a group's encoders and not the others (a `FailedEncoders::From(n)` whose `n` lies inside it, a `FailedEncoders::Set` that names some of them, a fault or a recording failure at one)