diff --git a/crates/metal2vulkan-runtime/examples/dispatch_chain.rs b/crates/metal2vulkan-runtime/examples/dispatch_chain.rs index cc6948bca..335417549 100644 --- a/crates/metal2vulkan-runtime/examples/dispatch_chain.rs +++ b/crates/metal2vulkan-runtime/examples/dispatch_chain.rs @@ -15,6 +15,13 @@ //! //! - **`encoders`**: `N` compute encoders of one dispatch each, as a program that opens an encoder //! for each dispatch records them; +//! - **`blits`**: `encoders` with a blit encoder after each compute encoder, which copies the +//! words into a `Private` buffer of their length, as an image workload copies between its +//! dispatches: `2N` encoders, each copy reading what the dispatch before it wrote and each +//! dispatch writing what the copy before it read. The copy's buffer is checked as the words are; +//! - **`copies`**: `N` blit encoders of that copy alone, no dispatch: what a program of blit +//! encoders alone costs (each line's "dispatch" is a copy). The copies' buffer must hold the +//! words' zeros; //! - **`serial`**: one serial compute encoder of the `N` dispatches; //! - **`concurrent`**: one concurrent encoder of them, with no memory barrier: nothing orders the //! dispatches, so this is the kernels' own time with no barrier between them (their words race, @@ -92,7 +99,8 @@ //! ``` //! //! `make` is `command_buffer`, `open` the encoders' opening, `pipeline` and `bind` the state's -//! calls, `end` `end_encoding`; `encode` is their sum and `commit` the `commit_and_submit` call; +//! calls, `end` `end_encoding` (with `blits`, a dispatch's blit encoder's opening, copy and end +//! count in its `open`, `dispatch` and `end`; with `copies`, each blit encoder's alone); `encode` is their sum and `commit` the `commit_and_submit` call; //! `thread_cpu` the calling thread's CPU time over both (`CLOCK_THREAD_CPUTIME_ID`), and //! `least_encode_commit` the least run's. `HOST-COMMIT` splits the commit call by the device's //! commit phases (`WorkCounts::commit_lowering_nanos` and kin). `HOST-THREADS` is each group of the @@ -125,9 +133,9 @@ use ash::vk; use metal2vulkan::bind::SamplerDescriptor; use metal2vulkan::metal::{BarrierScope, DispatchType, PixelFormat, TextureUsage}; use metal2vulkan_runtime::{ - Buffer, CommandBufferStatus, CommandQueue, ComputeCommandEncoder, ComputePipelineState, Device, - DeviceOptions, Heap, HeapDescriptor, HeapType, HostMemory, PipelineOptions, ResourceOptions, - SamplerState, Size, Texture, TextureDescriptor, WorkCounts, + Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, ComputeCommandEncoder, + ComputePipelineState, Device, DeviceOptions, Heap, HeapDescriptor, HeapType, HostMemory, + PipelineOptions, ResourceOptions, SamplerState, Size, Texture, TextureDescriptor, WorkCounts, }; use std::collections::BTreeMap; use std::io::Write; @@ -755,6 +763,8 @@ struct Ours<'a> { textures: [Texture; 2], sampler: SamplerState, readback: Buffer, + /// What the `blits` shape's copies write. + copies: Buffer, /// The heap each command buffer of the host's time makes its buffers in (`--heap-churn`). churn: Option, } @@ -768,10 +778,14 @@ impl Ours<'_> { let groups = Size::new(u64::from(shape.groups), 1, 1); let threads = Size::new(u64::from(shape.threads), 1, 1); let encoders = match name { - "encoders" => shape.dispatches, + "encoders" | "blits" | "copies" => shape.dispatches, _ => 1, }; for _ in 0..encoders { + if name == "copies" { + self.copy(&command_buffer)?; + continue; + } let mut encoder = match name { "concurrent" | "barriers" => command_buffer .compute_command_encoder_with_dispatch_type(DispatchType::Concurrent)?, @@ -786,6 +800,9 @@ impl Ours<'_> { encoder.dispatch_threadgroups(groups, threads)?; } encoder.end_encoding()?; + if name == "blits" { + self.copy(&command_buffer)?; + } } std::thread::sleep(shape.idle); command_buffer.commit()?; @@ -850,7 +867,7 @@ impl Ours<'_> { let groups = Size::new(u64::from(shape.groups), 1, 1); let threads = Size::new(u64::from(shape.threads), 1, 1); let encoders = match name { - "encoders" => shape.dispatches, + "encoders" | "blits" | "copies" => shape.dispatches, _ => 1, }; let mut lap = Lap::default(); @@ -862,6 +879,10 @@ impl Ours<'_> { let churned = self.churned(shape)?; lap.lap(&mut at, Call::Place); for _ in 0..encoders { + if name == "copies" { + self.copy_lapped(&command_buffer, &mut lap, &mut at)?; + continue; + } let mut encoder = match name { "concurrent" | "barriers" => command_buffer .compute_command_encoder_with_dispatch_type(DispatchType::Concurrent)?, @@ -881,6 +902,9 @@ impl Ours<'_> { } encoder.end_encoding()?; lap.lap(&mut at, Call::End); + if name == "blits" { + self.copy_lapped(&command_buffer, &mut lap, &mut at)?; + } } command_buffer.commit_and_submit()?; lap.lap(&mut at, Call::Commit); @@ -1003,6 +1027,31 @@ impl Ours<'_> { Ok(()) } + /// A blit encoder of `command_buffer` that copies the words into `copies`, ended (`blits`). + fn copy(&self, command_buffer: &CommandBuffer) -> Result<()> { + let mut blit = command_buffer.blit_command_encoder()?; + blit.copy_from_buffer_to_buffer(&self.words, 0, &self.copies, 0, self.words.length())?; + blit.end_encoding()?; + Ok(()) + } + + /// [`copy`](Self::copy), its opening, copy and end timed as an encoder's opening, dispatch + /// and end. + fn copy_lapped( + &self, + command_buffer: &CommandBuffer, + lap: &mut Lap, + at: &mut Instant, + ) -> Result<()> { + let mut blit = command_buffer.blit_command_encoder()?; + lap.lap(at, Call::Open); + blit.copy_from_buffer_to_buffer(&self.words, 0, &self.copies, 0, self.words.length())?; + lap.lap(at, Call::Dispatch); + blit.end_encoding()?; + lap.lap(at, Call::End); + Ok(()) + } + fn fill(&self, value: u8) -> Result<()> { let queue = self.device.new_command_queue()?; let command_buffer = queue.command_buffer()?; @@ -1019,12 +1068,25 @@ impl Ours<'_> { Ok(()) } - /// Copy the words back and check each is `want`. + /// Copy the words back and check each is `want`; with `blits`, the last copy's too; with + /// `copies`, which dispatches nothing, the copies' alone, the words' zeros. fn check(&self, want: u32, name: &str) -> Result<()> { + match name { + "copies" => self.check_words(&self.copies, 0, name), + "blits" => { + self.check_words(&self.words, want, name)?; + self.check_words(&self.copies, want, "blits' copies") + } + _ => self.check_words(&self.words, want, name), + } + } + + /// Copy `words` back and check each is `want`. + fn check_words(&self, words: &Buffer, want: u32, name: &str) -> Result<()> { let queue = self.device.new_command_queue()?; let command_buffer = queue.command_buffer()?; let mut blit = command_buffer.blit_command_encoder()?; - blit.copy_from_buffer_to_buffer(&self.words, 0, &self.readback, 0, self.words.length())?; + blit.copy_from_buffer_to_buffer(words, 0, &self.readback, 0, words.length())?; blit.end_encoding()?; command_buffer.commit()?; command_buffer @@ -1587,9 +1649,17 @@ fn main() -> Result<()> { textures: [texture()?, texture()?], sampler: device.new_sampler_state(&SamplerDescriptor::new())?, readback: device.new_buffer(bytes, ResourceOptions::shared())?, + copies: device.new_buffer(bytes, ResourceOptions::private())?, churn, }; - for shape_name in ["encoders", "serial", "concurrent", "barriers"] { + for shape_name in [ + "encoders", + "blits", + "copies", + "serial", + "concurrent", + "barriers", + ] { match (shape.runs(shape_name), shape.host) { (false, _) => {} (true, Some(command_buffers)) => { diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index aa47b4492..3c5723234 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -28,6 +28,7 @@ use super::buffer::Buffer; use super::command_buffer::CommandBuffer; use super::degradation::Degradation; use super::encoder::{EncoderCore, Replayed}; +use super::encoder_fold::Joining; use super::error::{invalid, Error, Problem}; use super::fresh_unwritten::FreshRead; use super::managed_copy::{AtCompletion, CopyBack, Staging, SyncTarget}; @@ -166,8 +167,9 @@ pub struct BlitCommandEncoder { /// The copies of the heap shadows among the textures the encoder's blits named /// ([`BlitCommandEncoder::see`]), each once. shadows: Vec>, - /// Its calls so far, where the device had a buffer over host pages as it opened - /// (`replay.rs`): `None` where it logs nothing, or no longer. + /// Its calls so far (`replay.rs`), which encode it again at a rebind of a buffer over host + /// pages it named, or at a commit whose failure fails some of its group's encoders and not it + /// (`encoder_fold.rs`): `None` where it logs nothing (encoding again). log: Option>, /// The protection options it was made under where they end Metal's process at its first /// command (`command_buffer/protection.rs`): each command is refused. @@ -188,18 +190,21 @@ impl CommandBuffer { /// after one was abandoned, and after commit. pub fn blit_command_encoder(&self) -> Result { let _for = self.notices_for(); + // It joins the group of compute and blit encoders before it, recording into their + // `VkCommandBuffer`, where it may (`encoder_fold.rs`); and it logs its calls + // (`replay.rs`), which encode it again at a rebind of a buffer over host pages it named, + // or at a commit whose failure fails some of its group's encoders and not it. let core = EncoderCore::open( self, "blit_command_encoder", EncoderKind::Blit, - (true, None), + (true, Some(Joining::Blit)), )?; Ok(BlitCommandEncoder { core, pattern: None, shadows: Vec::new(), - log: (self.device().shared().rebinds.any()) - .then(|| self.device().shared().scheduler.spare_logs().blit()), + log: Some(self.device().shared().scheduler.spare_logs().blit()), aborts: self.protected_blit(), fill_tiles: FillTiles::default(), }) diff --git a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs index 5a349b384..b596d98c4 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs @@ -1,23 +1,25 @@ -//! A command buffer's groups of compute encoders recorded into one `VkCommandBuffer` -//! (`encoder_fold.rs`): the group its tail holds, which compute encoder joins it, its logs, and -//! the failures that split a group. +//! A command buffer's groups of compute and blit encoders recorded into one `VkCommandBuffer` +//! (`encoder_fold.rs`): the group its tail holds, which encoder joins it, its logs, and the +//! failures and left out work that split a group. -use super::{FailedEncoders, Failure, State}; -use crate::encoder_fold::{Fold, FoldEnd, FoldOrder, Joining, Stashed}; +use super::{FailedEncoders, FailedSignals, Failure, State}; +use crate::encoder::Overwrite; +use crate::encoder_fold::{Fold, FoldEnd, Joining, Stashed}; use crate::replay::Replay; use crate::resource::ResourceKey; use crate::tracker::Summary; +use crate::used_resources::EncoderKind; use crate::work_counts::Counters; use std::collections::BTreeSet; impl State { - /// The group the compute encoder opening now joins, asking `joining`, where its command - /// buffer's tail holds one it may join (`encoder_fold.rs`'s **Where**): taken, with the tail, - /// which the encoder records into. `None` where it joins none, the group left in place: the - /// encoder's open closes it once it opened ([`close_fold`](Self::close_fold)). + /// The group the compute or blit encoder opening now joins, asking `joining`, where its + /// command buffer's tail holds one it may join (`encoder_fold.rs`'s **Where**): taken, with + /// the tail, which the encoder records into. `None` where it joins none, the group left in + /// place: the encoder's open closes it once it opened ([`close_fold`](Self::close_fold)). pub(crate) fn join_fold(&mut self, joining: Joining, trail: bool) -> Option> { let fold = self.fold.as_ref()?; - let joins = fold.joining == joining + let joins = fold.admits(joining) && self.tail == Some(fold.tail) && self.batches.all().len() == fold.batches && !self.batches.signals_pending() @@ -31,7 +33,7 @@ impl State { self.fold.take() } - /// A compute encoder ended (`end`), its last `VkCommandBuffer` the tail: it goes on in the + /// A compute or blit encoder ended (`end`), its last `VkCommandBuffer` the tail: it goes on in the /// group it joined where the tail is still that group's and it leaves nothing that needs a /// boundary, else the group closes and it begins one of its own where it may lead one (its /// one part leaves nothing that needs a boundary, the command buffer used no command @@ -58,8 +60,8 @@ impl State { fold.members.end = encoder + 1; fold.stashed.extend(log.take()); let goes_on = self.tail == Some(fold.tail); - if let (Some((_, summary)), true) = (&leads, goes_on) { - fold.order.join(summary); + if let (Some((joining, summary)), true) = (&leads, goes_on) { + fold.went_on(*joining, summary); fold.batches = self.batches.all().len(); self.fold = Some(fold); return unkept; @@ -69,27 +71,34 @@ impl State { } match (leads, self.tail) { (Some((joining, summary)), Some(tail)) => { - self.fold = Some(Box::new(Fold { + let (leader, batches) = (self.recorded.len() - 1, self.batches.all().len()); + let stashed = log.into_iter().collect(); + self.fold = Some(Box::new(Fold::begun( tail, - leader: self.recorded.len() - 1, - members: encoder..encoder + 1, - batches: self.batches.all().len(), - joining, - order: FoldOrder::after(&summary), - stashed: log.into_iter().collect(), - })); + (leader, encoder), + (batches, joining), + (&summary, stashed), + ))); } _ => unkept.extend(log.map(|stashed| stashed.log)), } unkept } - /// Join `worked`, the uses and fence waits of a compute encoder whose commands went into the + /// Join `worked`, the uses and fence waits of an encoder whose commands went into the /// `VkCommandBuffer` of the group it joined, to the summary of that group's first part, - /// `leader`, which the batch's submission plans the group's barrier and waits by. - pub(crate) fn join_leader(&mut self, leader: usize, worked: Summary) { + /// `leader`, which the batch's submission plans the group's barrier and waits by; and + /// `overwrites`, its whole writes that stand as that part's would (`Fold::overwrites_join`), + /// to that part's, which the submission judges them by. + pub(crate) fn join_leader( + &mut self, + leader: usize, + worked: Summary, + overwrites: Vec, + ) { if let Some(part) = self.recorded.get_mut(leader) { part.summary.join(worked); + part.overwrites.extend(overwrites); } } @@ -135,42 +144,48 @@ impl State { unkept } - /// At the commit, `failure` as the groups of compute encoders recorded into one - /// `VkCommandBuffer` take it (`encoder_fold.rs`'s **Failed**): a group it fails in part is + /// At the commit, `failure` and the work a command-predication record left out + /// (`State::left_out_from`) as the groups of encoders recorded into one `VkCommandBuffer` + /// take them (`encoder_fold.rs`'s **Failed**): a group they fail or leave out in part is /// split, each encoder of it that runs to be encoded again from its log, kept now, into /// `VkCommandBuffer`s of its own before the first submission (`reencode.rs`), and the group's - /// shared one never submitted; where one of them cannot be encoded again (its unit of command - /// predication laid a loop or left work out, `Predication::alone`), the failure fails that - /// whole group instead. With - /// `failure`, the encoders that run of each group split, the units to encode again. The logs - /// held for the commit that no split takes stay held, for the command buffer's release to - /// give back to the device's spares ([`unsplit_logs`](Self::unsplit_logs)). + /// shared one never submitted; where one of them cannot be encoded again + /// ([`encodes_again_apart`](Self::encodes_again_apart), or its log is gone), the failure fails + /// that whole group instead (a failure that fails those encoders alone, with no error, where + /// the commit has none). With the failure, the encoders that run of each group split, the + /// units to encode again. The logs held for the commit that no split takes stay held, for the + /// command buffer's release to give back to the device's spares + /// ([`unsplit_logs`](Self::unsplit_logs)). pub(super) fn split_failure( &mut self, failure: Option, ) -> (Option, Vec>) { let mut units = Vec::new(); - let Some(mut failure) = failure else { - return (None, units); - }; + let left_out = self.left_out_from; + if failure.is_none() && left_out.is_none() { + return (failure, units); + } let groups: BTreeSet<(usize, usize)> = (self.ended.iter()) .filter_map(|record| record.group.as_ref()) .map(|group| (group.start, group.end)) .collect(); let mut whole = BTreeSet::new(); for (start, end) in groups { - let fails = |encoder: &usize| failure.encoders.fails(*encoder); - let running: Vec = (start..end).filter(|encoder| !fails(encoder)).collect(); + let runs = |encoder: &usize| { + Failure::runs(failure.as_ref(), *encoder) + && left_out.is_none_or(|first| *encoder < first) + }; + let running: Vec = (start..end).filter(runs).collect(); if running.is_empty() || running.len() == end - start { continue; } let logged = running.iter().all(|&encoder| { - (!self.predicated || self.predication.alone(encoder)) + self.encodes_again_apart(encoder) && (self.ended[encoder].replay.is_some() || self.held_logs.iter().any(|held| held.encoder == encoder)) }); if !logged { - whole.extend(start..end); + whole.extend(running); continue; } for &encoder in &running { @@ -195,12 +210,34 @@ impl State { } units.push(running); } - if !whole.is_empty() { - failure.encoders = failure.encoders.with(&whole, self.ended.len()); + if whole.is_empty() { + return (failure, units); } + let ended = self.ended.len(); + let failure = match failure { + Some(mut failure) => { + failure.encoders = failure.encoders.with(&whole, ended); + failure + } + None => Failure { + encoders: FailedEncoders::Set(whole), + signals: FailedSignals::Every, + error: None, + }, + }; (Some(failure), units) } + /// Whether ended encoder `encoder`, of a group recorded into one `VkCommandBuffer`, encodes + /// again apart as the command buffer's command predication holds it: every one where it used + /// none; a compute encoder whose unit nothing reached into or out of (`Predication::alone`); + /// a blit encoder, which belongs to no unit (`predication.rs`). + pub(super) fn encodes_again_apart(&self, encoder: usize) -> bool { + !self.predicated + || (self.ended.get(encoder)).is_some_and(|record| record.kind != EncoderKind::Compute) + || self.predication.alone(encoder) + } + /// The logs held for the commit that no split took (`split_failure`): for the command /// buffer's release to give back to the device's spares without this lock, on its queue's /// handler thread, as it gives back the logs its encoders kept (`replay.rs`). diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index a23d0976b..10fe086c8 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -826,10 +826,14 @@ pub(super) struct State { /// into it as the batch ends ([`CommandBufferShared::close_tail`]), or it ends as it is where /// a later encoder joins its batch. pub(super) tail: Option, - /// The group of compute encoders whose last one's `VkCommandBuffer` is `tail`, which the next - /// compute encoder may join, recording on into it (`encoder_fold.rs`); held by that encoder - /// while it is open. + /// The group of compute and blit encoders whose last one's `VkCommandBuffer` is `tail`, which + /// 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>, + /// 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`). + pub(super) left_out_from: Option, /// The logs of the closed groups' encoders kept for nothing else, held for the commit, whose /// failure may split a group (`fold.rs`'s `split_failure`), and given back to the device's /// spares in the release. @@ -2135,8 +2139,11 @@ impl State { /// A command-predication record dropped what the ended encoders from `first` on recorded, /// its unit's earlier encoders (`predication.rs`): each of their parts runs nothing, as a - /// failed encoder's ([`fail_part`](Self::fail_part)). + /// failed encoder's ([`fail_part`](Self::fail_part)). A group of encoders recorded into one + /// `VkCommandBuffer` whose first lies before `first` holds their commands in that one, which + /// its first part runs: the commit splits it (`fold.rs`'s `split_failure`). pub(super) fn leave_out_ended(&mut self, first: usize) { + self.left_out_from = Some(self.left_out_from.map_or(first, |from| from.min(first))); let State { recorded, retained, @@ -2545,6 +2552,7 @@ impl CommandBuffer { tail: None, fold: None, held_logs: Vec::new(), + left_out_from: None, split_units: Vec::new(), folds: Vec::new(), prefix: None, @@ -3983,9 +3991,9 @@ impl CommandBuffer { true => Some(Failure::revoked()), false => failure, }; - // A group of compute encoders in one `VkCommandBuffer` the failure fails in part is - // split: its encoders that run are encoded again apart before the first submission - // (`encoder_fold.rs`'s **Failed**). + // A group of encoders in one `VkCommandBuffer` the failure fails, or a + // command-predication record left out, in part is split: its encoders that run are + // encoded again apart before the first submission (`encoder_fold.rs`'s **Failed**). let (failure, split) = state.split_failure(failure); // The encoders that run: all but those `failure` fails. let runs = |encoder: usize| Failure::runs(failure.as_ref(), encoder); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 5d1080940..8da7d906f 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -58,12 +58,13 @@ //! and it keeps the run's scratch after its own merge where a later pass went on over it, a //! linear attachment's run's box copied in again first (`State::replaying_keeps`, recorded by //! `EncoderCore::finish_replay`). Its run's other passes are not encoded again. -//! - **Groups whole.** The compute encoders of a group recorded into one `VkCommandBuffer` -//! (`encoder_fold.rs`) are encoded again together: a rebind that moves one encodes each again, -//! into `VkCommandBuffer`s of its own, and puts them in their places together, or puts none -//! where one of them kept no log, is refused or does not fit its place. +//! - **Groups whole.** The compute and blit encoders of a group recorded into one +//! `VkCommandBuffer` (`encoder_fold.rs`) are encoded again together: a rebind that moves one +//! encodes each again, into `VkCommandBuffer`s of its own, and puts them in their places +//! together, or puts none where one of them kept no log, is refused or does not fit its place. //! - **Split at the commit.** A commit whose failure fails some of a group's encoders and not the -//! others (`encoder_fold.rs`'s **Failed**) marks the command buffer as a rebind does, and its +//! others, or after a command-predication record left out the work of some of them +//! (`encoder_fold.rs`'s **Failed**), marks the command buffer as a rebind does, and its //! own call encodes the group's encoders that run again, each into `VkCommandBuffer`s of its //! own, before the scheduler sees its batches; where one cannot be encoded again or does not //! fit its place, those encoders run nothing after all (`State::fail_unsplit`), as the whole @@ -182,8 +183,8 @@ impl CommandBufferShared { let handle = CommandBuffer(Arc::clone(self)); // The encoders encoded again, whose segments the encoding again recorded. let mut spliced = Vec::new(); - // Each unit's encoders are encoded again before any takes its place: a group of compute - // encoders recorded into one `VkCommandBuffer` takes its places whole or not at all + // Each unit's encoders are encoded again before any takes its place: a group of encoders + // recorded into one `VkCommandBuffer` takes its places whole or not at all // (`encoder_fold.rs`). for (split, unit) in units { let members: Vec = unit.iter().map(|(at, _)| *at).collect(); @@ -453,9 +454,9 @@ impl CommandBufferShared { /// work than its encoding again's. const UNFIT: &str = "its place holds other parts or work than its encoding again's"; -/// Why an encoder of a group of compute encoders recorded into one `VkCommandBuffer` keeps its -/// first recording where the group cannot be encoded again whole (`encoder_fold.rs`). -const TOGETHER: &str = "it records into one VkCommandBuffer with compute encoders around it, \ +/// Why an encoder of a group of compute and blit encoders recorded into one `VkCommandBuffer` +/// keeps its first recording where the group cannot be encoded again whole (`encoder_fold.rs`). +const TOGETHER: &str = "it records into one VkCommandBuffer with encoders around it, \ which are not all encoded again"; /// An ended encoder encoded again, for its place ([`State::splice_replay`]). @@ -492,11 +493,12 @@ impl State { } /// The units the rebind's turn encodes again of `moved`, the ended encoders it moved, with - /// their logs, in order: each encoder alone, but an encoder of a group of compute encoders - /// recorded into one `VkCommandBuffer` with every encoder of its group (`encoder_fold.rs`), - /// whose shared recording none may leave alone. A group one of whose encoders kept no log, or - /// of a command buffer that used command predication, is encoded again by none: its moved - /// encoders keep their first recording, the refusal noted and counted. + /// their logs, in order: each encoder alone, but an encoder of a group of compute and blit + /// encoders recorded into one `VkCommandBuffer` with every encoder of its group + /// (`encoder_fold.rs`), whose shared recording none may leave alone. A group one of whose + /// encoders kept no log, or cannot be encoded again apart in its command buffer's command + /// predication (`State::encodes_again_apart`), is encoded again by none: its moved encoders + /// keep their first recording, the refusal noted and counted. pub(super) fn encoded_together( &mut self, moved: Vec<(usize, Arc)>, @@ -519,7 +521,8 @@ impl State { Some((member, Arc::clone(log))) }) .collect(); - match logs.filter(|_| !self.predicated) { + let apart = (group.clone()).all(|member| self.encodes_again_apart(member)); + match logs.filter(|_| apart) { Some(unit) => units.push(unit), None => { for record in &mut self.ended[group] { diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index be8599b6f..9cfa198ea 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -275,11 +275,11 @@ impl CommandBuffer { let _for = self.notices_for(); // Metal's process ends here under some protection options (`command_buffer/protection.rs`). self.refuse_protected_encoder(call)?; - // It joins the group of compute encoders before it, recording into their + // It joins the group of compute and blit encoders before it, recording into their // `VkCommandBuffer`, where it may (`encoder_fold.rs`); and it logs its calls (`replay.rs`), // which encode it again at a rebind of a buffer over host pages it named, or at a commit // whose failure fails some of its group's encoders and not it. - let joining = Joining { dispatch_type }; + let joining = Joining::Compute(dispatch_type); let serial = dispatch_type == DispatchType::Serial; let opened = EncoderCore::open(self, call, EncoderKind::Compute, (serial, Some(joining)))?; let mut core = opened.boxed(); diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index fa641f3cd..dcdabf00b 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -3,9 +3,9 @@ //! //! - **Recording.** `open` allocates a primary `VkCommandBuffer` from the command buffer's pool //! and begins it; `end` ends it and appends it to the command buffer's recordings, which -//! `commit` submits in that order. A compute encoder records on instead in the one of the -//! compute encoders before it where nothing between them needs a boundary, a barrier from their -//! commands before each of its own that needs one (`encoder_fold.rs`). +//! `commit` submits in that order. A compute or blit encoder records on instead in the one of +//! the compute and blit encoders before it where nothing between them needs a boundary, a +//! barrier from their commands before each of its own that needs one (`encoder_fold.rs`). //! - **Segments**. An indirect command buffer's commands may change until the command buffer is //! committed, so an encoder that executes them [`defer`](EncoderCore::defer)s them: it ends its //! `VkCommandBuffer` there and goes on in a new one, and the segment's own is recorded later @@ -411,7 +411,7 @@ pub(super) struct EncoderCore { /// command buffer. Not `recorded`: a pass may hold it, and what records before that pass /// goes in another before it, which leads the encoder's then. barriered: Option, - /// What a compute encoder asked, as it opened, of the group of compute encoders its command + /// What a compute or blit encoder asked, as it opened, of the group of encoders its command /// buffer's tail held (`encoder_fold.rs`); `None` for any other encoder. joining: Option, /// The group it joined, recording on into its tail, which its group's first part holds @@ -669,8 +669,8 @@ impl EncoderCore { } /// Open an encoder on `command_buffer` for Metal's `call`, `ordered` when Metal runs its - /// commands in encoded order (a blit or serial compute encoder); a compute encoder asks - /// `joining` of the group of compute encoders the command buffer's tail holds, which it joins + /// commands in encoded order (a blit or serial compute encoder); a compute or blit encoder + /// asks `joining` of the group of encoders the command buffer's tail holds, which it joins /// where it may, recording on into the tail (`encoder_fold.rs`). Refused when the command /// buffer is committed, has an open encoder, or has an abandoned one. pub(super) fn open( @@ -726,7 +726,7 @@ impl EncoderCore { // the group it joined), under the state lock, and only this encoder records it now; the // device made by the runtime enables `hostQueryReset` (`gpu_time.rs`). let times = unsafe { shared.timing.encoders().open(shared.vk(), raw) }; - // A group of compute encoders it did not join takes no encoder from here. + // A group of compute and blit encoders it did not join takes no encoder from here. let unkept = state.close_fold(&shared.counts); state.encoder_open = true; // Made under the protection options set now (`command_buffer/protection.rs`). @@ -1143,7 +1143,7 @@ impl EncoderCore { } /// Record a barrier of the runtime's own between the commands it records, recorded as a - /// command that bypasses the order of the group of compute encoders the encoder joined + /// command that bypasses the order of the group of encoders the encoder joined /// ([`recording`](Self::recording)). pub(super) fn barrier(&mut self, barrier: Barrier) { let Some(raw) = self.recording() else { @@ -1327,7 +1327,8 @@ impl EncoderCore { /// ([`gather`](Self::gather)). `None` where none can be made, which abandons the command /// buffer (as a failure to end one does, [`defer`](Self::defer)). /// - /// In an encoder that joined a group of compute encoders (`encoder_fold.rs`), whose commands + /// In an encoder that joined a group of compute and blit encoders (`encoder_fold.rs`), whose + /// commands /// record here without the order each command takes after the group's earlier encoders /// ([`track`](Self::track)), a barrier from everything of theirs not yet ordered to /// everything after goes first. @@ -1338,7 +1339,7 @@ impl EncoderCore { } /// [`recording`](Self::recording) for a command [`track`](Self::track) ordered after the - /// group of compute encoders the encoder joined. + /// group of encoders the encoder joined. fn recording_ordered(&mut self) -> Option { let raw = self.raw_recording()?; self.record_gathers(raw); @@ -3189,8 +3190,8 @@ impl EncoderCore { } Some(_) => None, }; - // A log not kept goes back to the device's spares (`replay.rs`); a compute encoder's - // waits for its end, which keeps it where the encoder is in a group of compute encoders + // A log not kept goes back to the device's spares (`replay.rs`); a compute or blit + // encoder's waits for its end, which keeps it where the encoder is in a group of encoders // that may be encoded again (`encoder_fold.rs`). let mut held_log = None; let replay = replay.and_then(|log| { @@ -3302,7 +3303,8 @@ impl EncoderCore { let command_buffer_id = open.command_buffer.object_id().get(); let trail = trail.map(|notes| notes.described(kind, command_buffer_id, encoder)); state.encoder_holds(encoder, uses.held().to_vec()); - // Whether it may begin or go on in a group of compute encoders (`encoder_fold.rs`). + // Whether it may begin or go on in a group of compute and blit encoders + // (`encoder_fold.rs`). let fails = fails_command_buffer.is_some() || faults.is_some(); match fails_command_buffer { Some(CommandBufferError::GpuHang) => { @@ -3359,15 +3361,18 @@ impl EncoderCore { let parts = into_parts(ended, segments, base); // The writes into ASTC carriers go with the last part (a blit encoder's only one). let count = parts.len(); + // What its batch's submission records after its part or judges by it: a group it begins + // or goes on in takes no encoder after it (`encoder_fold.rs`). + let judged = !twin_writes.is_empty() || !overwrites.is_empty(); let mut twin_writes = Some(twin_writes); // Its whole writes go with its first part, which records its pass's clears before its // draws; none where a command-predication record left parts out before it. let mut overwrites = (left_out == 0).then_some(overwrites); - // What a compute encoder of one part used, which the next encoder of a group of compute - // encoders it 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. + // What a compute or blit encoder of one part used, which the next encoder of a group it + // 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; + let mut plain = joining.is_some() && count == 1 && left_out == 0 && !fails && !judged; for (at, (raws, segments)) in parts.into_iter().enumerate() { let mut summary = summaries .next() @@ -3382,11 +3387,22 @@ impl EncoderCore { // 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 // updates, and, where it went on in `VkCommandBuffer`s of its own, all of them. + // Its whole writes, where all its commands went there and they stand as that part's + // would, go with it (`Fold::overwrites_join`). if let (0, true, Some(fold)) = (at, shared_first, &fold) { let own = !raws.is_empty() || !segments.is_empty(); let full = own.then(|| summary.clone()); let (worked, updated) = summary.split_updates(); - state.join_leader(fold.leader, worked); + let whole = match (own, overwrites.as_mut()) { + (false, Some(writes)) => { + let (joins, stays) = + (writes.drain(..)).partition(|write| fold.overwrites_join(write.key)); + *writes = stays; + joins + } + _ => Vec::new(), + }; + state.join_leader(fold.leader, worked, whole); summary = full.unwrap_or(updated); } let twin_writes = match at + 1 == count { @@ -3415,8 +3431,8 @@ impl EncoderCore { ); } state.tail = Some(raw); - // It begins a group of compute encoders, goes on in the one it joined, or closes it - // (`encoder_fold.rs`). + // It begins a group of compute and blit encoders, goes on in the one it joined, or closes + // it (`encoder_fold.rs`). if joining.is_some() { let shared = open.command_buffer.device().shared(); let end = FoldEnd { diff --git a/crates/metal2vulkan-runtime/src/encoder_fold.rs b/crates/metal2vulkan-runtime/src/encoder_fold.rs index dfc4bcfc4..2262a9c74 100644 --- a/crates/metal2vulkan-runtime/src/encoder_fold.rs +++ b/crates/metal2vulkan-runtime/src/encoder_fold.rs @@ -1,24 +1,33 @@ -//! Consecutive compute encoders of one command buffer recorded into one `VkCommandBuffer`. +//! Consecutive compute and blit encoders of one command buffer recorded into one +//! `VkCommandBuffer`. //! //! Every encoder records into a primary `VkCommandBuffer` of its own (`encoder.rs`), and each //! batch's submission puts the barrier the tracker plans before each encoder in a command buffer //! of barriers of its own (`command_buffer/submit.rs`, `command_buffer/kept_barriers.rs`): a //! command buffer of `N` one-dispatch compute encoders went to the queue as `2N - 1` command //! buffers. Each boundary between command buffers costs GPU time beyond a barrier inside one -//! (`examples/dispatch_chain.rs`). A compute encoder that opens where the encoder before it +//! (`examples/dispatch_chain.rs`), and each `vkBeginCommandBuffer` host time (ANV clears its +//! command buffer state there). A compute or blit encoder that opens where the encoder before it //! leaves nothing that needs a boundary records on in that encoder's `VkCommandBuffer`, the //! command buffer's tail, and its batch's submission submits no command buffer for it. //! -//! - **Where.** A compute encoder takes the tail where the encoder before it was a compute -//! encoder of the same dispatch type ([`Fold`], kept by the command buffer as that one ended) -//! whose recording is one part, with no work left for later (no segment), no fence update and -//! nothing that fails or faults its command buffer, in the same batch (no event or 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. So a group lies inside one batch and one unit of command predication (`predication.rs`), -//! and a fence orders nothing inside it: what a later encoder waits for is updated after the -//! group's last. Every compute encoder logs its calls (`replay.rs`), so each of a group's -//! encoders can be encoded again apart. Counted: `WorkCounts::encoders_folded`. +//! - **Where.** A compute or blit encoder takes the tail where the encoder before it was a compute +//! or blit encoder ([`Fold`], kept by the command buffer as that one ended) whose recording is +//! one part, with no work left for later (no segment), no fence update 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 +//! the submission leaves out by what its part read: `Overwrite`), in the same batch (no event or +//! 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 +//! 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`), so each of a group's encoders can be +//! encoded again apart. Counted: `WorkCounts::encoders_folded`. //! - **The barrier between them** is recorded as the encoder records, by the rule the tracker //! applies between two encoders of one batch: from each earlier write of a tracked resource's //! overlapping range to a later read or write, its accesses made visible, and from each earlier @@ -43,14 +52,17 @@ //! again is not encoded again, and its moved members are refused. //! - **Failed.** A failure of the command buffer that fails some of a group's encoders and not //! the others (`CommandBuffer::commit_failed`'s first failed encoder or set inside a group, a -//! recording failure or a fault at a folded encoder) splits the group at the commit -//! (`State::split_failure`): the encoders that run are encoded again from their logs, each into -//! `VkCommandBuffer`s of its own, before the first submission, the shared one never submitted, -//! and the failed ones run nothing: exactly the encoders the failure names run nothing, as on -//! Metal. Where the encoders that run cannot all be encoded again (their unit of command -//! predication laid a loop or left work out, so a command of theirs encoded again would run -//! outside its block: `Predication::alone`; or a call answers otherwise when encoded again), -//! the failure fails the whole group (docs/API.md, "A command buffer committed as failed"). +//! recording failure or a fault at a folded encoder), and a command-predication record that +//! leaves out the work of its unit's encoders from one past a group's first +//! (`State::leave_out_ended`), splits the group at the commit (`State::split_failure`): the +//! encoders that run are encoded again from their logs, each into `VkCommandBuffer`s of its +//! own, before the first submission, the shared one never submitted, and the failed or left out +//! ones run nothing: exactly the encoders the failure names, or the record leaves out, run +//! nothing, as on Metal. Where the encoders that run cannot all be encoded again (a compute +//! encoder whose unit of command predication laid a loop or left work out, so a command of its +//! encoded again would run outside its block: `Predication::alone`; a blit encoder belongs to no +//! unit; or a call answers otherwise when encoded again), the failure fails the whole group +//! (docs/API.md, "A command buffer committed as failed"). //! - **Logs.** A group's members' logs are held from the group's close for the commit, which //! keeps them for every member where one member keeps its own for a rebind, and keeps those of //! a group its failure splits; the rest stay held until the command buffer's release, which @@ -146,6 +158,11 @@ impl FoldOrder { } } + /// Whether the group's earlier encoders used the resource of `key`. + fn names(&self, key: K) -> bool { + self.priors.contains_key(&key) + } + /// The barrier a command with `uses` needs after the group's earlier encoders: from a write /// of an overlapping range of a tracked resource not yet visible to the command's read or /// write of it, and from a read of one not yet ordered before its write, as the tracker @@ -262,16 +279,30 @@ pub(crate) struct Stashed { pub(crate) executions: Range, } -/// What a compute encoder asks of the group its command buffer's tail may hold, as it opens: its -/// dispatch type. +/// What an encoder asks of the group its command buffer's tail may hold, as it opens: a compute +/// encoder joins one whose compute encoders are of its dispatch type (or that holds none), as a +/// unit of command predication holds compute encoders of one dispatch type (`predication.rs`); a +/// blit encoder joins any. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Joining { - pub(crate) dispatch_type: DispatchType, +pub(crate) enum Joining { + Compute(DispatchType), + Blit, } -/// The group of compute encoders whose last ended one's `VkCommandBuffer` is its command buffer's -/// tail and may take the next compute encoder (the module docs): kept by the command buffer -/// between encoders, held by the encoder that joined it while it is open. +impl Joining { + /// The dispatch type of the compute encoders of a group it joins: its own, a compute + /// encoder's; `group`'s, a blit encoder's. + fn dispatch_type(self, group: Option) -> Option { + match self { + Joining::Compute(dispatch_type) => Some(dispatch_type), + Joining::Blit => group, + } + } +} + +/// The group of compute and blit 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. pub(crate) struct Fold { /// The tail: the group's shared `VkCommandBuffer`, the last of its first part's. pub(crate) tail: vk::CommandBuffer, @@ -283,15 +314,67 @@ pub(crate) struct Fold { /// How many batches the command buffer had as the group's last encoder ended: a later /// encoder joins it only in that batch. pub(crate) batches: usize, - /// What its encoders asked as they opened: one dispatch type. - pub(crate) joining: Joining, + /// The dispatch type of its compute encoders; `None` while it holds blit encoders alone. + pub(crate) dispatch_type: Option, + /// Whether every encoder it holds is a blit encoder: a later one's write of a texture whole + /// joins its first part's (`Fold::overwrites_join`). + pub(crate) blits_alone: bool, /// What its encoders did, which the next one's commands order after. pub(crate) order: FoldOrder, /// Its members' logs not kept by themselves. pub(crate) stashed: Vec, } -/// A compute encoder's end as the group of compute encoders it begins or goes on in takes it +impl Fold { + /// Whether an encoder that asks `joining` may join it, by what it holds. + pub(crate) fn admits(&self, joining: Joining) -> bool { + match joining { + Joining::Compute(dispatch_type) => self + .dispatch_type + .is_none_or(|group| group == dispatch_type), + Joining::Blit => true, + } + } + + /// The group `joining`'s encoder begins, its first part `leader`, its first `VkCommandBuffer` + /// the tail. + pub(crate) fn begun( + tail: vk::CommandBuffer, + (leader, encoder): (usize, usize), + (batches, joining): (usize, Joining), + (summary, stashed): (&Summary, Vec), + ) -> Fold { + Fold { + tail, + leader, + members: encoder..encoder + 1, + batches, + dispatch_type: joining.dispatch_type(None), + blits_alone: joining == Joining::Blit, + order: FoldOrder::after(summary), + stashed, + } + } + + /// `joining`'s encoder, which ended with `summary`, goes on in the group. + pub(crate) fn went_on(&mut self, joining: Joining, summary: &Summary) { + self.dispatch_type = joining.dispatch_type(self.dispatch_type); + self.blits_alone &= joining == Joining::Blit; + self.order.join(summary); + } + + /// Whether a folded encoder's write of the image of `key` whole, before any of its commands + /// reads it (`Overwrite`), stands as the write of the group's first part would: every + /// earlier encoder of the group is a blit encoder (any other's commands may reach a texture + /// unnamed) and none named the image. Its first part's then holds it, which the batch's + /// submission judges as it judged the encoder's own part before any encoder was folded + /// (`submit.rs`'s `first_overwrites`). + pub(crate) fn overwrites_join(&self, key: ResourceKey) -> bool { + self.blits_alone && !self.order.names(key) + } +} + +/// A compute or blit encoder's end as the group it begins or goes on in takes it /// (`State::fold_ended`). pub(crate) struct FoldEnd { /// What it asked as it opened; `None` where no group may take it (the encoder trail is on). @@ -302,7 +385,8 @@ pub(crate) struct FoldEnd { pub(crate) encoder: usize, /// What its one part used, where that 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. `None` where it is not so. + /// command buffer, no write into an ASTC carrier and no `Overwrite`. `None` where it is not + /// so. pub(crate) summary: Option>, /// Its log, which it did not keep, with its executions' place. pub(crate) log: Option<(Replay, Range)>, diff --git a/crates/metal2vulkan-runtime/src/replay.rs b/crates/metal2vulkan-runtime/src/replay.rs index 5fa6adcd9..71c2285bd 100644 --- a/crates/metal2vulkan-runtime/src/replay.rs +++ b/crates/metal2vulkan-runtime/src/replay.rs @@ -15,11 +15,12 @@ //! ([`CallLog::refuse`]: the encoder's `logged`, a render encoder's call made at once): encoded //! again, it is refused again and the calls after it run, as they ran after its refusal. A call //! that answers otherwise than at its first encoding leaves the encoder as it was encoded first -//! ([`Replay::run`] fails, and the encoder is not encoded again). A blit or render encoder's -//! log starts at its open where the device has a buffer over host pages (`Rebinds::any`), else -//! it logs nothing; a compute encoder always logs, as a commit whose failure splits the group of -//! compute encoders it recorded with encodes it again (`encoder_fold.rs`). It costs one push per call; a slice of buffers, offsets, textures or bytes goes -//! into one of the log's arenas, so the common calls allocate nothing of their own. +//! ([`Replay::run`] fails, and the encoder is not encoded again). A render encoder's log +//! starts at its open where the device has a buffer over host pages (`Rebinds::any`), else it +//! logs nothing; a compute or blit encoder always logs, as a commit whose failure splits the +//! group of encoders it recorded with encodes it again (`encoder_fold.rs`). It costs one push +//! per call; a slice of buffers, offsets, textures or bytes goes into one of the log's arenas, +//! so the common calls allocate nothing of their own. //! - **What is kept.** The command buffer keeps an ended encoder's log only where a command of //! it named a buffer over host pages and the encoder can be encoded again: it left no segment //! for later (an indirect stage-in region) but an indirect command buffer's execution, which @@ -47,7 +48,7 @@ //! 27.0.1, probe `dealloc-probe`). And no other thread may hold such a handle past the //! completion: a no-copy buffer's deallocator would run where it went, on the scheduler's thread //! for one, whose own hold of the command buffer keeps the deallocator's wait for it from -//! returning (`scheduler::Spent`). A log let go of in the release (a group of compute +//! returning (`scheduler::Spent`). A log let go of in the release (a group of compute and blit //! encoders' held for the commit among them, `encoder_fold.rs`), or at its encoder's end where //! it is not kept, is cleared (its calls and handles go then) and its room kept for the //! device's next encoders ([`SpareLogs`]), so the encoding thread's logs reuse their memory diff --git a/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs b/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs index ee7ac9daf..14d513a1c 100644 --- a/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs +++ b/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs @@ -1,11 +1,14 @@ -//! Consecutive compute 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 that splits a group at the commit, and -//! a rebind that encodes a group again whole. +//! 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. //! //! [`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 -//! a GPU that overlaps two dispatches with no barrier between them may read before it is written. +//! a GPU that overlaps two dispatches with no barrier between them may read before it is written; +//! [`compute_and_blit_encoders_of_a_chain_record_into_one_command_buffer`] the same through a +//! blit encoder's copy between them. //! //! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. The kernel is `scale_and_offset` of the @@ -17,11 +20,11 @@ use super::dispatch_pending::state; use super::encoder_holds::words_of; use super::rebind_behind_a_wait::{Page, BYTES}; use crate::{ - Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, CommitFailure, - ComputePipelineState, Device, Error, EventRef, FailedEncoders, ResourceOptions, Size, - WorkCounts, + BlitOption, Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, CommitFailure, + ComputePipelineState, Device, Error, EventRef, FailedEncoders, Origin, ResourceOptions, Size, + Texture, TextureDescriptor, WorkCounts, }; -use metal2vulkan::metal::DispatchType; +use metal2vulkan::metal::{DispatchType, PixelFormat, TextureUsage}; use std::collections::BTreeSet; /// The words of a large write: threadgroups enough that a GPU runs them in many waves. @@ -101,6 +104,28 @@ impl Kernel { 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( + &self, + command_buffer: &CommandBuffer, + (source, offset): (&Buffer, u64), + (destination, words): (&Buffer, u64), + ) { + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_buffer(source, offset, destination, 0, words * 4) + .unwrap(); + blit.end_encoding().unwrap(); + } + + /// A blit encoder of `command_buffer` that fills `buffer`'s first `words` floats' bytes with + /// [`FILL`], ended. + fn fill(&self, command_buffer: &CommandBuffer, buffer: &Buffer, words: u64) { + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(buffer, 0..words * 4, FILL).unwrap(); + blit.end_encoding().unwrap(); + } + /// Commit `command_buffer` and wait for it: it completes with no error. fn run(&self, command_buffer: &CommandBuffer) { command_buffer.commit().unwrap(); @@ -330,9 +355,10 @@ fn a_fence_update_ends_a_group() { } } -/// Three encoders of one group, a blit encoder's fill, 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 (`WorkCounts::encoders_reencoded`). +/// 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 +/// (`WorkCounts::encoders_reencoded`). fn failed_with(encoders: FailedEncoders) -> ([bool; 5], u64) { let scratch = Scratch::new("fold-failed"); let kernel = Kernel::new(&scratch); @@ -351,12 +377,14 @@ 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 moved = Moved::of(&before, &device.work_counts()); - assert_eq!((moved.folded, moved.begun), (2, 3), "{moved:?}"); + assert_eq!((moved.folded, moved.begun), (3, 2), "{moved:?}"); let failure = CommitFailure { code: 2, encoders, @@ -387,11 +415,28 @@ fn failed_with(encoders: FailedEncoders) -> ([bool; 5], u64) { } /// A failed set that names one encoder of a group fails that encoder alone, as on Metal: the -/// group's other two are encoded again apart at the commit, and the encoders after it run. +/// group's other three, the blit encoder among them, are encoded again apart at the commit, and +/// the encoder after it runs. #[test] fn a_failed_encoder_inside_a_group_fails_alone() { let set = FailedEncoders::Set(BTreeSet::from([1])); - assert_eq!(failed_with(set), ([true, false, true, true, true], 2)); + assert_eq!(failed_with(set), ([true, false, true, true, true], 3)); +} + +/// A failed set that names a group's blit encoder fails it alone: the group's compute encoders are +/// encoded again apart at the commit. +#[test] +fn a_failed_blit_encoder_inside_a_group_fails_alone() { + let set = FailedEncoders::Set(BTreeSet::from([3])); + assert_eq!(failed_with(set), ([true, true, true, false, true], 3)); +} + +/// A first failed encoder at a group's blit encoder fails from there on: the group's compute +/// encoders before it are encoded again apart at the commit, and run. +#[test] +fn a_first_failed_blit_encoder_inside_a_group_runs_the_encoders_before_it() { + let from = FailedEncoders::From(3); + assert_eq!(failed_with(from), ([true, true, true, false, false], 3)); } /// A first failed encoder inside a group fails from there on, as on Metal: the group's first @@ -402,12 +447,12 @@ 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 (an encoder that is not a compute encoder) splits -/// no group: the group before it runs as recorded. +/// A first failed encoder at a group's boundary (the encoder after a fence update) splits no +/// group: the group before it runs as recorded. #[test] fn a_first_failed_encoder_at_a_group_s_boundary_fails_from_there() { - let from = FailedEncoders::From(3); - assert_eq!(failed_with(from), ([true, true, true, false, false], 0)); + let from = FailedEncoders::From(4); + assert_eq!(failed_with(from), ([true, true, true, true, false], 0)); } /// The shape of a consumer's protection probe: a compute encoder, then a second one, folded into @@ -602,3 +647,584 @@ fn a_rebind_encodes_every_encoder_of_a_group_again() { .collect(); assert_eq!(written, expected(words, |i| 3 * i)); } + +/// A chain of `STEPS` large writes, each from the buffer the one before wrote into the other, +/// each followed by a blit encoder's copy of the tail of what it wrote and a small read of that +/// copy, each one encoder: one group of `3 * STEPS` compute and blit encoders in one +/// `VkCommandBuffer`, each copy after a barrier from the large write before it and each small read +/// after one from the copy, and every word what the chain computes. +#[test] +fn compute_and_blit_encoders_of_a_chain_record_into_one_command_buffer() { + let scratch = Scratch::new("fold-blit-chain"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let tail = (LARGE - SMALL) * 4; + let large = [ + floats(device, LARGE, |_| 0.0), + floats(device, LARGE, |_| 0.0), + ]; + let copies: Vec = (0..STEPS).map(|_| floats(device, SMALL, |_| 0.0)).collect(); + let small: Vec = (0..STEPS).map(|_| floats(device, SMALL, |_| 0.0)).collect(); + // Warm, over buffers of its own, as the compute chain warms. + let warm = [ + floats(device, LARGE, |_| 0.0), + floats(device, LARGE, |_| 0.0), + floats(device, SMALL, |_| 0.0), + ]; + let command_buffer = queue.command_buffer().unwrap(); + let serial = DispatchType::Serial; + 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(); + for k in 0..STEPS as usize { + let (from, to) = (&large[k % 2], &large[(k + 1) % 2]); + kernel.dispatch(&command_buffer, serial, (from, 0), (to, LARGE)); + kernel.copy(&command_buffer, (to, tail), (&copies[k], SMALL)); + kernel.dispatch(&command_buffer, serial, (&copies[k], 0), (&small[k], SMALL)); + } + kernel.run(&command_buffer); + let after = device.work_counts(); + let moved = Moved::of(&before, &after); + let submitted = after.command_buffers_submitted - before.command_buffers_submitted; + // Copy `k` holds the tail of write `k`, `(k + 1) * i`; read `k` adds `j` to word `j` of it. + let wrong = |buffers: &[Buffer], plus: u64| -> Vec<(u64, usize)> { + (buffers.iter().enumerate()) + .map(|(k, buffer)| { + let k = k as u64; + let wanted = expected(SMALL, |j| (k + 1) * (LARGE - SMALL + j) + plus * j); + let read = read(buffer); + (k, read.iter().zip(&wanted).filter(|(a, b)| a != b).count()) + }) + .filter(|&(_, wrong)| wrong > 0) + .collect() + }; + let (wrong_copies, wrong_reads) = (wrong(&copies, 0), wrong(&small, 1)); + println!( + "FOLD-BLIT-CHAIN {moved:?} submitted {submitted} copies wrong (write, words) \ + {wrong_copies:?} reads wrong {wrong_reads:?}" + ); + assert_eq!( + (wrong_copies, wrong_reads), + (Vec::new(), Vec::new()), + "each copy read what the write before it wrote, each read what the copy before it wrote" + ); + let encoders = 3 * STEPS; + assert_eq!( + (moved.folded, moved.begun), + (encoders - 1, 1), + "every encoder after the first joined the first's group: {moved:?}" + ); + assert!( + moved.barriers >= 2 * STEPS, + "each copy waits for the write before it, each read for the copy: {moved:?}" + ); +} + +/// An event signal between a compute encoder and a blit encoder ends the batch, and so the +/// group: the blit encoder begins a group of its own, which the compute encoder after it joins. +#[test] +fn an_event_signal_before_a_blit_encoder_begins_a_group() { + let scratch = Scratch::new("fold-blit-event"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let input = floats(device, SMALL, |i| i as f32); + let outputs = [ + floats(device, SMALL, |_| 0.0), + floats(device, SMALL, |_| 0.0), + ]; + let copied = floats(device, SMALL, |_| 0.0); + let event = device.new_shared_event().unwrap(); + let serial = DispatchType::Serial; + let warm = floats(device, SMALL, |_| 0.0); + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&warm, SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&outputs[0], SMALL)); + command_buffer + .encode_signal_event(EventRef::Shared(&event), 1) + .unwrap(); + 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()); + assert_eq!((moved.folded, moved.begun), (1, 2), "{moved:?}"); + assert_eq!(read(&copied), expected(SMALL, |i| 2 * i)); + assert_eq!(read(&outputs[1]), expected(SMALL, |i| 3 * i)); +} + +/// A group's compute encoders are of one dispatch type, a blit encoder between them or not: a +/// concurrent encoder after a serial encoder and a blit encoder begins a group of its own, which +/// the blit encoder after it joins. +#[test] +fn a_change_of_dispatch_type_across_a_blit_encoder_begins_a_group() { + let scratch = Scratch::new("fold-blit-types"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let input = floats(device, SMALL, |i| i as f32); + let outputs = [ + floats(device, SMALL, |_| 0.0), + floats(device, SMALL, |_| 0.0), + ]; + let copies = [ + floats(device, SMALL, |_| 0.0), + floats(device, SMALL, |_| 0.0), + ]; + let (serial, concurrent) = (DispatchType::Serial, DispatchType::Concurrent); + let warm = floats(device, SMALL, |_| 0.0); + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&warm, SMALL)); + kernel.dispatch(&command_buffer, concurrent, (&input, 0), (&warm, SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + for (dispatch_type, (output, copy)) in [serial, concurrent] + .into_iter() + .zip(outputs.iter().zip(&copies)) + { + kernel.dispatch(&command_buffer, dispatch_type, (&input, 0), (output, SMALL)); + kernel.copy(&command_buffer, (output, 0), (copy, SMALL)); + } + kernel.run(&command_buffer); + let moved = Moved::of(&before, &device.work_counts()); + assert_eq!((moved.folded, moved.begun), (2, 2), "{moved:?}"); + for copy in &copies { + assert_eq!(read(copy), expected(SMALL, |i| 2 * i)); + } +} + +/// No encoder joins a group once its command buffer used command predication: a blit encoder +/// after a compute encoder's If begins a `VkCommandBuffer` of its own, and so does the compute +/// encoder after it. +#[test] +fn no_blit_encoder_joins_a_group_after_command_predication() { + let scratch = Scratch::new("fold-blit-predicated"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let input = floats(device, SMALL, |i| i as f32); + let outputs = [ + floats(device, SMALL, |_| 0.0), + floats(device, SMALL, |_| 0.0), + ]; + let copied = floats(device, SMALL, |_| 0.0); + let word = device + .new_buffer_with_bytes(&0u32.to_le_bytes(), ResourceOptions::shared()) + .unwrap(); + let serial = DispatchType::Serial; + let warm = floats(device, SMALL, |_| 0.0); + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&warm, SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().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(); + encoder.set_buffer(Some(&input), 0, 0).unwrap(); + encoder.set_buffer(Some(&outputs[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(); + assert!(encoder.encode_end_if().unwrap(), "the If ends"); + encoder.end_encoding().unwrap(); + 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()); + assert_eq!((moved.folded, moved.begun), (0, 3), "{moved:?}"); + assert_eq!(read(&copied), expected(SMALL, |i| 2 * i)); + assert_eq!(read(&outputs[1]), expected(SMALL, |i| 3 * i)); +} + +/// A new `Private` texture of `SIDE`² `RGBA8Unorm` texels, shader-read. +fn new_texture(device: &Device) -> Texture { + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::private(); + device.new_texture(&descriptor).unwrap() +} + +/// The side of [`new_texture`]'s textures. +const SIDE: u64 = 16; + +/// A blit encoder of `command_buffer` copying `source`, `SIDE`² texels of 4 bytes, into the whole +/// of `texture`, ended. +fn copy_whole(command_buffer: &CommandBuffer, source: &Buffer, texture: &Texture) { + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_texture( + source, + 0, + SIDE * 4, + SIDE * SIDE * 4, + Size::new(SIDE, SIDE, 1), + texture, + 0, + 0, + Origin::new(0, 0, 0), + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); +} + +/// The bytes of `texture`, `SIDE`² texels of 4 bytes, copied out. +fn texels(device: &Device, texture: &Texture) -> Vec { + let length = SIDE * SIDE * 4; + let out = device + .new_buffer(length, ResourceOptions::shared()) + .unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(SIDE, SIDE, 1), + &out, + 0, + SIDE * 4, + length, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + // SAFETY: the shared buffer's bytes, which no command uses now. + unsafe { std::slice::from_raw_parts(out.contents().unwrap().as_ptr(), length as usize) } + .to_vec() +} + +/// A blit encoder that writes a new `Private` texture whole before any of its commands reads it +/// (`Overwrite`, on a device that zero-fills new `Private` textures) ends its group: the compute +/// encoder after it begins a `VkCommandBuffer` of its own. Where every encoder of the group +/// before it is a blit encoder that named nothing of the texture, its write still leaves the +/// texture's zeros out (`WorkCounts::private_textures_overwritten_unfilled`), as it did in a +/// `VkCommandBuffer` of its own; after a compute encoder, whose commands may reach a texture +/// unnamed, it keeps them, as it did. +#[test] +fn a_blit_encoder_that_writes_a_new_texture_whole_ends_its_group() { + let scratch = Scratch::new("fold-blit-overwrite"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let zero_fills = !device.properties().lossless_compression; + let input = floats(device, SMALL, |i| i as f32); + let output = floats(device, SMALL, |_| 0.0); + let filled = floats(device, SMALL, |_| 0.0); + let bytes: Vec = (0..SIDE * SIDE * 4).map(|i| (i * 37 + 11) as u8).collect(); + let source = device + .new_buffer_with_bytes(&bytes, ResourceOptions::shared()) + .unwrap(); + let serial = DispatchType::Serial; + let warm = floats(device, SMALL, |_| 0.0); + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&warm, SMALL)); + kernel.run(&command_buffer); + let overwritten = |counts: &WorkCounts| counts.private_textures_overwritten_unfilled; + + // A fill, the copy into the whole texture, and a dispatch. + let texture = new_texture(device); + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + kernel.fill(&command_buffer, &filled, SMALL); + copy_whole(&command_buffer, &source, &texture); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&output, SMALL)); + kernel.run(&command_buffer); + let after = device.work_counts(); + let moved = Moved::of(&before, &after); + let left_out = overwritten(&after) - overwritten(&before); + println!("FOLD-BLIT-OVERWRITE zero fills {zero_fills}: {moved:?} zeros left out {left_out}"); + let counted = u64::from(zero_fills); + assert_eq!( + (moved.folded, moved.begun, left_out), + (2 - counted, 1 + counted, counted), + "the copy joined the fill's group, and ended it where it wrote the texture whole" + ); + assert_eq!(texels(device, &texture), bytes, "the copy"); + assert_eq!(read(&output), expected(SMALL, |i| 2 * i)); + + // A dispatch, then the copy into the whole texture: it keeps the zeros. + let texture = new_texture(device); + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&output, SMALL)); + copy_whole(&command_buffer, &source, &texture); + kernel.run(&command_buffer); + let after = device.work_counts(); + let moved = Moved::of(&before, &after); + assert_eq!( + ( + moved.folded, + moved.begun, + overwritten(&after) - overwritten(&before) + ), + (1, 1, 0), + "the copy joined the dispatch's group and took the zeros" + ); + assert_eq!( + texels(device, &texture), + bytes, + "the copy after the dispatch" + ); +} + +/// A blit encoder that writes an ASTC texture's carrier, whose second twin's decode its batch's +/// submission records after its part (`texture/decoded_twin.rs`), ends its group: the compute +/// encoder after it begins a `VkCommandBuffer` of its own. +#[test] +fn a_blit_encoder_that_writes_an_astc_carrier_ends_its_group() { + let scratch = Scratch::new("fold-blit-carrier"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let input = floats(device, SMALL, |i| i as f32); + let output = floats(device, SMALL, |_| 0.0); + let filled = floats(device, SMALL, |_| 0.0); + // Eight `ASTC_4x2` texels square, two 16-byte blocks a row of blocks, written in its top + // half (a part of it, so no `Overwrite`). + let side = 8; + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::ASTC4x2LDR, side, side, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::private(); + let carried = device.new_texture(&descriptor).unwrap(); + let blocks = device + .new_buffer_with_bytes(&[0x5a; 64], ResourceOptions::shared()) + .unwrap(); + let serial = DispatchType::Serial; + let warm = floats(device, SMALL, |_| 0.0); + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&warm, SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + kernel.fill(&command_buffer, &filled, SMALL); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_texture( + &blocks, + 0, + 32, + 64, + Size::new(side, side / 2, 1), + &carried, + 0, + 0, + Origin::new(0, 0, 0), + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&output, SMALL)); + kernel.run(&command_buffer); + let after = device.work_counts(); + let moved = Moved::of(&before, &after); + let checked = after.second_twin_checks - before.second_twin_checks; + println!("FOLD-BLIT-CARRIER {moved:?} carrier writes checked {checked}"); + assert_eq!(checked, 1, "the copy wrote the carrier"); + assert_eq!( + (moved.folded, moved.begun), + (1, 2), + "the copy joined the fill's group and ended it" + ); + assert_eq!(read(&output), expected(SMALL, |i| 2 * i)); +} + +/// A group of a compute encoder, a blit encoder and a compute encoder that begins the next unit +/// of command predication (`predication.rs`: a blit encoder ends a unit), whose unbalanced End +/// leaves its unit's work out: the dispatch it leaves out lies in the group's `VkCommandBuffer`, +/// so the commit splits the group, encoding the first two encoders again apart, and the left out +/// dispatch runs nothing, as on Metal; the first two run. +#[test] +fn work_left_out_past_a_group_s_first_encoder_splits_the_group() { + let scratch = Scratch::new("fold-blit-left-out"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let input = floats(device, SMALL, |i| i as f32); + let outputs = [ + floats(device, SMALL, |_| 0.0), + floats(device, SMALL, |_| 0.0), + ]; + let copied = floats(device, SMALL, |_| 0.0); + let serial = DispatchType::Serial; + let warm = floats(device, SMALL, |_| 0.0); + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&warm, SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&outputs[0], SMALL)); + kernel.copy(&command_buffer, (&outputs[0], 0), (&copied, SMALL)); + 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(&outputs[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(); + // No block is open: an unbalanced End, which answers NO and leaves the unit's work out. + assert!(!encoder.encode_end_if().unwrap(), "the End is unbalanced"); + encoder.end_encoding().unwrap(); + let folded = device.work_counts().encoders_folded - before.encoders_folded; + assert_eq!( + folded, 2, + "the blit and the second compute encoder joined the first's group" + ); + kernel.run(&command_buffer); + let after = device.work_counts(); + let reencoded = after.encoders_reencoded - before.encoders_reencoded; + let left_out_ran = words_of(&outputs[1]).iter().any(|&word| word != 0); + println!( + "FOLD-BLIT-LEFT-OUT encoded again {reencoded}, the left out dispatch ran {left_out_ran}" + ); + assert!(!left_out_ran, "the left out dispatch ran nothing"); + assert_eq!( + read(&outputs[0]), + expected(SMALL, |i| 2 * i), + "the first encoder ran" + ); + assert_eq!( + read(&copied), + expected(SMALL, |i| 2 * i), + "the blit encoder ran" + ); + assert_eq!( + reencoded, 2, + "the first two encoders were encoded again apart" + ); +} + +/// 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 +/// 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. +#[test] +fn a_rebind_encodes_a_group_again_in_a_command_buffer_of_command_predication() { + // Declared before the device, so dropped after it. + let pages = [Page::new(), Page::new()]; + let scratch = Scratch::new("fold-rebind-predicated"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let words = (BYTES / 4) as u64; + let input = floats(device, words, |i| i as f32); + let middle = floats(device, words, |_| 0.0); + let other = floats(device, words, |_| 0.0); + // SAFETY: each page outlives every buffer over it (dropped after the device), and only the + // buffer's commands use it while it lives. + let made = unsafe { + device.new_buffer_with_bytes_no_copy( + pages[0].memory(), + BYTES as u64, + ResourceOptions::shared(), + None, + ) + }; + let output = match made { + Ok(buffer) => buffer, + Err(Error::Unsupported(gap)) => { + eprintln!("FOLD-REBIND-PREDICATED: the device imports no host memory: {gap:?}"); + return; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + }; + 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(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&middle, words)); + kernel.dispatch(&command_buffer, serial, (&middle, 0), (&warm, words)); + kernel.run(&command_buffer); + + let gate = device.new_shared_event().unwrap(); + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + command_buffer + .encode_wait_for_event(EventRef::Shared(&gate), 1) + .unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&middle, words)); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&kernel.state).unwrap(); + encoder.set_buffer(Some(&middle), 0, 0).unwrap(); + encoder.set_buffer(Some(&output), 0, 1).unwrap(); + encoder.set_buffer(Some(&kernel.scale), 0, 2).unwrap(); + 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(); + // Comparison 0: `word == reference`, which holds. + encoder.encode_start_if(Some(&word), 0, 0, 0).unwrap(); + encoder.set_compute_pipeline_state(&kernel.state).unwrap(); + encoder.set_buffer(Some(&input), 0, 0).unwrap(); + encoder.set_buffer(Some(&other), 0, 1).unwrap(); + encoder.set_buffer(Some(&kernel.scale), 0, 2).unwrap(); + encoder + .dispatch_threads(Size::new(words, 1, 1), Size::new(GROUP, 1, 1)) + .unwrap(); + assert!(encoder.encode_end_if().unwrap(), "the If ends"); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + assert_eq!(output.detach_backing(), Ok(true)); + // SAFETY: as above. + unsafe { output.rebind_bytes_no_copy(pages[1].memory(), None, None) }.unwrap(); + // Read before the signal: the rebind encodes again in its own call. + let after = device.work_counts(); + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!( + command_buffer.status(), + CommandBufferStatus::Completed, + "{:?}", + command_buffer.error() + ); + assert_eq!(after.encoders_folded - before.encoders_folded, 1); + assert_eq!( + ( + after.encoders_reencoded - before.encoders_reencoded, + after.reencodes_refused - before.reencodes_refused + ), + (2, 0), + "the rebind encoded both encoders of the group again" + ); + assert!( + !pages[0].written(), + "the group wrote the pages the buffer left" + ); + let written: Vec = pages[1] + .words() + .iter() + .copied() + .map(f32::from_bits) + .collect(); + assert_eq!(written, expected(words, |i| 3 * i)); + assert_eq!( + read(&other), + expected(words, |i| 2 * i), + "the If's dispatch ran" + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/spares.rs b/crates/metal2vulkan-runtime/src/tests/spares.rs index 38b9cd0c5..e143f657c 100644 --- a/crates/metal2vulkan-runtime/src/tests/spares.rs +++ b/crates/metal2vulkan-runtime/src/tests/spares.rs @@ -697,8 +697,8 @@ mod device { use crate::tests::encoder_holds::library; use crate::tests::freed_memory::device; use crate::{ - Buffer, CommandBufferStatus, CommandQueue, Device, PipelineOptions, RenderPassDescriptor, - RenderPipelineState, ResourceOptions, + Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, Fence, PipelineOptions, + RenderPassDescriptor, RenderPipelineState, ResourceOptions, }; use ash::vk; use metal2vulkan::metal::PrimitiveType; @@ -760,16 +760,26 @@ 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() { - let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.fill_buffer(target, 0..256, at as u8).unwrap(); - blit.end_encoding().unwrap(); + fill_apart(&command_buffer, target, at as u8, &fence); } 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) { + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(target, 0..256, value).unwrap(); + blit.update_fence(fence).unwrap(); + blit.end_encoding().unwrap(); + } + /// The device's free thread held at each free until this drops, a failing case's unwinding /// too, so that the device's teardown, which waits for the frees, never waits for a hold left /// behind. @@ -934,10 +944,9 @@ 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 { - let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.fill_buffer(&target, 0..256, at as u8).unwrap(); - blit.end_encoding().unwrap(); + fill_apart(&command_buffer, &target, at as u8, &fence); } command_buffer }; @@ -1029,10 +1038,9 @@ 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 { - let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.fill_buffer(&target, 0..256, at as u8).unwrap(); - blit.end_encoding().unwrap(); + fill_apart(&command_buffer, &target, at as u8, &fence); } command_buffer }) diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 49b3a354e..c6e273b55 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -3668,8 +3668,8 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } - /// A compute encoder joined the group of compute encoders before it, recording into their - /// `VkCommandBuffer` (`encoder_fold.rs`). + /// A compute or blit encoder joined the group of compute and blit encoders before it, + /// recording into their `VkCommandBuffer` (`encoder_fold.rs`). pub(crate) fn encoder_folded(&self) { self.encoders_folded.fetch_add(1, Ordering::Relaxed); } @@ -7066,12 +7066,13 @@ pub struct WorkCounts { /// their barriers. Such a barrier orders every command of the encoder after every command /// before it, where Metal orders only those whose resources meet. pub encoders_barriered_at_open: u64, - /// Compute encoders that began no `VkCommandBuffer` of their own: each recorded into the one - /// of the compute encoders before it in its command buffer, where nothing between them needs a - /// boundary (the same batch and dispatch type, no work left for later, no fence update, - /// nothing failing), 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. + /// Compute and blit encoders that began no `VkCommandBuffer` of their own: each recorded into + /// the one of the compute and blit 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), + /// 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, /// Of `command_buffers_begun`, the device's own submissions' and staging submissions'. pub command_buffers_begun_internal: u64, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 09bd5888a..dc1966e3f 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 = 522; /// 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 = 2292; +pub const RUNTIME_VERSION: u32 = 2293; /// 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/docs/API.md b/docs/API.md index 842c79945..515569fb2 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2097,7 +2097,7 @@ program called, its total and share, and its time per encoder at the median and logs one line per command buffer whose GPU time is `N` ms or more, 1024 at most: each encoder's place, kind, states, dispatches and draws, offset from the command buffer's GPU start and time. An encoder whose recording ran nothing reads no time and counts as not timed: one encoded again (a -rebind, a failure that splits a group of compute encoders), one left out by command predication or +rebind, a failure that splits a group of compute and blit encoders), one left out by command predication or failed, and one that ended inside a predicated loop. An encoder whose parts went in submissions apart, with a host step between them, counts the time between them. It does nothing on a device whose queue family writes no timestamps, one the runtime adopted (it resets query pools on the @@ -5417,21 +5417,24 @@ each item named states the rule in full. **A command buffer committed as failed** (`CommandBuffer::commit_failed`) -- **A failure inside a group of compute encoders whose unit of command predication laid a loop - or left work out fails the whole group.** The runtime records a compute encoder into the - `VkCommandBuffer` of the compute encoder before it where nothing needs a boundary between them: - the same dispatch type, the same batch (no event wait or signal between them), no fence update - or work left for later in the earlier one, no command predication yet, the encoder trail off - (`DeviceOptions::encoder_trail`) and protection options 0 (`WorkCounts::encoders_folded` counts - each). 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) splits it at the commit: the encoders that run are - recorded again from their logs, each into `VkCommandBuffer`s of its own, so exactly the - encoders the failure names run nothing, as on Metal. Where the group lies in a unit of command - predication that a later encoder of the command buffer made lay a loop - (`ComputeCommandEncoder::encode_start_while`, `encode_start_do_while`) or leave work out (an - unbalanced record), its encoders cannot be recorded again outside their blocks, and such a - failure fails the whole group instead, where Metal runs the group's encoders before `n` and +- **A failure inside a group of compute and blit encoders whose unit of command predication 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 or blit 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 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 each). 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) + splits it at the commit: the encoders that run are recorded again from their logs, each into + `VkCommandBuffer`s of its own, so exactly the encoders the failure names run nothing, as on + Metal; so does an unbalanced record that leaves out the work of its unit's encoders from one past + the group's first (a blit encoder ends a unit of command predication). Where a running compute + encoder of the group lies in a unit of command predication that a later encoder of the command + buffer made lay a loop (`ComputeCommandEncoder::encode_start_while`, `encode_start_do_while`) or + leave work out (an unbalanced record), it cannot be recorded again outside its blocks, and such + a failure fails the whole group instead, where Metal runs the group's encoders before `n` and those the set leaves out. So does a group one of whose calls answers otherwise when recorded again. diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 87591f359..09bda1678 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -1196,16 +1196,18 @@ driver's. Each is open work. compute encoder its unit of command predication reaches past, which is one whose unit laid a step before it opened or one of its own that the unit's later encoders read, and one whose unit laid a loop or left work out; work on the GPU alone) fail `EncodedUseRebound` (announced). -- **A failure inside a group of compute encoders recorded together, whose unit of command - predication laid a loop or left work out, fails the whole group** (`encoder_fold.rs`, +- **A failure inside a group of compute and blit encoders recorded together, whose unit of + command predication laid a loop or left work out, fails the whole group** (`encoder_fold.rs`, `command_buffer/fold.rs`'s `State::split_failure`). A `CommandBuffer::commit_failed` whose `FailedEncoders::From(n)` lies inside such a group, or whose `FailedEncoders::Set` names some of its encoders, splits the group at the commit and records its running encoders again from their - logs. Where a later compute encoder of the group's unit of predication (the run of compute + logs; so does an unbalanced record whose unit's work, left out, begins past the group's first + encoder (a blit encoder ends a unit, so a group may hold two units' compute encoders). Where a + later compute encoder of a running compute encoder's unit of predication (the run of compute encoders of one dispatch type it lies in, `predication.rs`) called `encode_start_while` or - `encode_start_do_while`, or left a record unbalanced, the group's encoders cannot be recorded - again outside the unit's blocks, so the group runs nothing, where Metal runs its encoders the - failure does not name. + `encode_start_do_while`, or left a record unbalanced, that encoder cannot be recorded again + outside the unit's blocks, so the group runs nothing, where Metal runs its encoders the failure + does not name. A blit encoder belongs to no unit and is always recorded again. - **A copied rebind under a texture in place, where the device's check did not pass fresh pages and its own linear image lies at another pitch, is refused** (`NotImplemented(RebindTextures)`). A rebind whose pages the gate refuses, or whose bytes moved in their page, copies them, and the @@ -2312,8 +2314,8 @@ compares with Metal's. `DontCare`, a multisampled, layered or resolved pass, and the other kinds `WorkCounts::passes_not_inline_*` count). A batch begins one more before each of the first 2,048 encoders of its command buffer that needs a barrier, and none past them (`encoder.rs`, - `WorkCounts::encoders_barriered_at_open`); a compute encoder recorded into the - `VkCommandBuffer` of the compute encoders before it takes none (`encoder_fold.rs`, + `WorkCounts::encoders_barriered_at_open`); a compute or blit encoder recorded into the + `VkCommandBuffer` of the compute and blit encoders before it takes none (`encoder_fold.rs`, `WorkCounts::encoders_folded`). On ms01's Iris Xe one command buffer of 10,000 render passes, each a draw beside a cleared depth target, runs in 12,049 command buffers (`tests::many_passes`); one of such passes recorded inline encoded 16,173 and refused to open