From 8562b28fe4cd5c25e018dc1ad41e443fd80d2358 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 16 Nov 2026 04:32:27 -0800 Subject: [PATCH] RUNTIME 2446: Shadows: a split merge on the host copies no piece; its kernel skips their columns A merge on the host past shadow_merge::HOST_WHOLE_BYTES split: its host step stored the pieces of each row in lines beside the texels, and its kernel the rest. To keep the kernel off those lines, the GPU copied the pieces' kept bytes into an arena region and their changed bytes over them in the kept part: two vkCmdCopyBuffer calls of one region per piece. On the Iris Xe (ANV) that work cost about 7 to 9 us a region, growing with the rows, not the bytes: about 0.6 ms for 34 rows (m3-max-35898) and about 15 ms for 1024 (m3-max-36118: a BGRA8 1023x1024 render target over host pages drew in 17.57 ms a command buffer as a shadow against 1.26 ms in place, its host step 0.28 ms of it). Now the kernel takes a column window (bind::ShadowMergeModule: two more push words, PUSH_BYTES 24; shape_within, shape the whole row): a word outside the columns is neither read nor written in either store form, and counts as unchanged in its block. A split merge pushes the words between each row's pieces where every row's pieces lie at the same places in it (shadow_merge::columns: whole words, the same head and tail each row; rows whose pitch is no multiple of the line differ, and those merges go on the host whole). It records the changed copy and its dispatches alone, with no save, no mask, two fewer barriers and no arena region; the host step reads each piece's kept and changed bytes in the scratch's two parts, which nothing writes after the changed copy. Removed: HostMerge::saved, ShadowMerge::saves, ShadowCopy::merge_saves, the merge's region in EncoderCore::merge_on_host, MergeDrain::_region, and the split's copy uses of the kept part. The bound stays 1 MiB; its doc comment states the measured costs. Linear merges push the whole row. Tests: - bind::shadow_merge's a_region_merged_within_columns_leaves_the_words_outside_them: 70 rows of 6 words, columns 1 to 4, every word changed; words outside the columns keep the current buffer's, in both store forms, and a window of every column equals shape. - shadow_runs' merges_on_the_host_go_whole_up_to_the_bound_and_split_past_it also asserts shadow_merge_words_examined: every word of the whole merge's rows; for the split, the words between each row's pieces alone (height * (row bytes - line) / 4). - shadow_write_lines' cost test gains a 4K shape: 3839 RGBA16Float texels a row, 2160 rows 30720 bytes apart. The merge module is under no golden table (golden_hashes covers the fixtures' translations). api_signatures: PUSH_BYTES, shape, and the new shape_within. Degradation kinds added: none. Landing note: msi m3-max-36189 at 4b09425f2d (same tree): clippy metal2vulkan + runtime, all targets and features, CLIPPY=0. The API tables, the module tests, rustdoc, clippy m2v_gpu / m2v_cpu_icd, the lavapipe control (development's whole-row kernel fails the split test's words-examined count) and the touched suites, PHOENIX and the Iris re-time follow on development. --- crates/metal2vulkan-runtime/src/encoder.rs | 50 +--- .../metal2vulkan-runtime/src/linear_merge.rs | 2 +- crates/metal2vulkan-runtime/src/shadow.rs | 39 +-- .../metal2vulkan-runtime/src/shadow_merge.rs | 246 ++++++++---------- .../metal2vulkan-runtime/src/shadow_splice.rs | 49 ++-- .../src/tests/shadow_runs.rs | 21 +- .../src/tests/shadow_write_lines.rs | 13 +- crates/metal2vulkan/src/bind/shadow_merge.rs | 116 +++++++-- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 5 +- docs/API.md | 3 +- docs/FAST-PATHS.md | 11 +- 12 files changed, 295 insertions(+), 262 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index fc59da731..ea20bc553 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -2988,8 +2988,8 @@ impl EncoderCore { spliced.extend(self.splice(&mut run, copy, plan)); continue; } - if let Some(saves) = splices.then(|| copy.merge_saves()).flatten() { - spliced.extend(self.merge_on_host(&mut run, copy, saves)); + if splices && copy.merges_on_host_now() { + spliced.extend(self.merge_on_host(&mut run, copy)); continue; } // A shadow takes the view a dispatch reads on a device that dispatches alone. @@ -3151,52 +3151,24 @@ impl EncoderCore { Some((HostWrite::Splice(splice.drain), written)) } - /// Record `copy`, a merge on the host whose host step reads `saves` bytes of a region of the - /// command buffer's arena (`shadow_splice.rs`, **Merges**; none where it merges every byte), in - /// `run`, as [`shadow_command`](Self::shadow_command) records any shadowed texture's copy: the - /// copy of the texels the commands left into its scratch's changed part, and, where its kernel - /// merges the rest, the copies of the host step's pieces and its dispatches. The CPU's part, - /// and the merge's write of its truth's bytes, where it recorded. Where the region cannot be - /// had, the command buffer fails, as a recording that fails does. + /// Record `copy`, a merge on the host (`shadow_splice.rs`, **Merges**), in `run`, as + /// [`shadow_command`](Self::shadow_command) records any shadowed texture's copy: the copy of + /// the texels the commands left into its scratch's changed part, and, where its kernel merges + /// all but the host step's pieces, its dispatches. The CPU's part, and the merge's write of its + /// truth's bytes, where it recorded. fn merge_on_host( &mut self, run: &mut ShadowRun, copy: &ShadowCopy, - saves: u64, ) -> Option<(HostWrite, Use)> { - let device = self.device().clone(); - let region = match saves { - 0 => None, - saves => { - let line = device.shared().in_place.line(); - let mut state = self.open.command_buffer.state(); - Some(shadow_splice::region( - &mut state.uploads, - &device, - saves, - line, - )) - } - }; - let region = match region.transpose() { - Ok(region) => region, - Err(error) => { - self.fail_command_buffer(recording_error(&device, error)); - return None; - } - }; - let saved = region - .as_ref() - .map(|region| (region.raw(), region.offset())); - let drain = copy.merge_drain(region)?; + let drain = copy.merge_drain()?; let uses = copy.uses(); let recorded = std::cell::Cell::new(false); let record = |device: &Vk, raw: vk::CommandBuffer| { // SAFETY: the encoder's command buffer is recording outside a render pass; its - // commands retain the shadowed texture (its image), the merge (its scratch) and its - // arena (the region) until it completes, and every image rests in the `GENERAL` - // layout. - unsafe { copy.record_on_host(device, raw, saved) }; + // commands retain the shadowed texture (its image) and the merge (its scratch) until + // it completes, and every image rests in the `GENERAL` layout. + unsafe { copy.record_on_host(device, raw) }; recorded.set(true); }; self.shadow_command(run, (copy.stages(), &uses, true), record); diff --git a/crates/metal2vulkan-runtime/src/linear_merge.rs b/crates/metal2vulkan-runtime/src/linear_merge.rs index e1d179c18..47f97cea1 100644 --- a/crates/metal2vulkan-runtime/src/linear_merge.rs +++ b/crates/metal2vulkan-runtime/src/linear_merge.rs @@ -84,7 +84,7 @@ pub(super) const MERGE_STAGES: vk::PipelineStageFlags2 = vk::PipelineStageFlags2 /// One dispatch of the merge: its workgroups and push bytes. struct Dispatch { groups: u32, - shape: [u8; 16], + shape: [u8; 24], } /// The merge of one linear attachment's pass (the module docs). diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs index f15aeea12..264feb937 100644 --- a/crates/metal2vulkan-runtime/src/shadow.rs +++ b/crates/metal2vulkan-runtime/src/shadow.rs @@ -290,7 +290,6 @@ use super::texture::heap_two_planes::{HeapPlaneCopies, TwoPlaneHeapLayout}; use super::texture::surface_pairs::PairsConversion; use super::texture::Texture; use super::tracker::{Access, Barrier, Use, UseRange}; -use super::upload::Upload; use super::values::StorageMode; use super::view_plan::{reinterpretation_refused, ViewRecord}; use super::ycbcr::{YCbCrConversion, YCbCrWriteBack}; @@ -2194,49 +2193,39 @@ impl ShadowCopy { } } - /// Where this copy is a merge on the host (`ShadowMerge::saves`, `shadow_splice.rs`) over its - /// truth's pages as they lie now, the bytes of the arena's region its host step reads the - /// pieces' kept bytes from (0 where it merges every byte). `None` for any other copy, and a - /// buffer whose pages went. - pub(super) fn merge_saves(&self) -> Option { + /// Whether this copy is a merge on the host (`ShadowMerge::on_host`, `shadow_splice.rs`) over + /// its truth's pages as they lie now: not for any other copy, nor a buffer whose pages went. + pub(super) fn merges_on_host_now(&self) -> bool { let Step::Merge(merge) = &self.step else { - return None; + return false; }; - let saves = merge.saves()?; - self.copies.pages_base().map(|_| saves) + merge.on_host() && self.copies.pages_base().is_some() } - /// This merge's CPU part, where it merges on the host ([`merge_saves`](Self::merge_saves)): - /// over its truth's pages as they lie now, the pieces' kept bytes in `region` where its kernel - /// merges the rest. `None` for any other copy, a buffer whose pages went, and a merge whose - /// kernel merges the rest given no region. - pub(super) fn merge_drain(&self, region: Option) -> Option { + /// This merge's CPU part, where it merges on the host + /// ([`merges_on_host_now`](Self::merges_on_host_now)): over its truth's pages as they lie now. + /// `None` for any other copy, and a buffer whose pages went. + pub(super) fn merge_drain(&self) -> Option { let Step::Merge(merge) = &self.step else { return None; }; let (buffer, _) = self.copies.host_truth()?; let (_, base) = host_base(&buffer)?; - merge.drain(base, region) + merge.drain(base) } /// Record the GPU's part of this merge on the host ([`merge_drain`](Self::merge_drain)): the /// copy of the texels the commands left into its changed part, and, where its kernel merges - /// all but its host step's pieces, `saved` their region's `VkBuffer` and offset, the copies of - /// their bytes and its dispatches (`ShadowMerge::record_on_host`). + /// all but its host step's pieces, its dispatches (`ShadowMerge::record_on_host`). /// /// # Safety /// - /// As [`record`](Self::record); the region lives until the command buffer completes. - pub(super) unsafe fn record_on_host( - &self, - device: &Vk, - command_buffer: vk::CommandBuffer, - saved: Option<(vk::Buffer, u64)>, - ) { + /// As [`record`](Self::record). + pub(super) unsafe fn record_on_host(&self, device: &Vk, command_buffer: vk::CommandBuffer) { if let Step::Merge(merge) = &self.step { let moves = self.moves.as_deref(); // SAFETY: the caller's contract, which the merge's record takes. - unsafe { merge.record_on_host(device, command_buffer, (&self.copies, moves), saved) }; + unsafe { merge.record_on_host(device, command_buffer, (&self.copies, moves)) }; } } diff --git a/crates/metal2vulkan-runtime/src/shadow_merge.rs b/crates/metal2vulkan-runtime/src/shadow_merge.rs index 09ecc53cc..aed956cf9 100644 --- a/crates/metal2vulkan-runtime/src/shadow_merge.rs +++ b/crates/metal2vulkan-runtime/src/shadow_merge.rs @@ -127,11 +127,14 @@ //! into its two parts in a `Shared` scratch (its pool's `ScratchKind::ShadowHost`, its shadow's //! spares that the CPU maps). Where the encoder's own copies record it, a host step after them //! compares and stores every byte of its rows where they hold at most [`HOST_WHOLE_BYTES`] (or -//! it is not cut); past them its kernel merges the rows' bytes in the other lines, storing -//! changed words alone (`ShadowMergeStores::Words`), and the host step the rest -//! ([`ShadowMerge::record_on_host`], [`ShadowMerge::drain`], -//! `WorkCounts::shadow_merges_on_host`). Its kernel's sets are made as for any merge in place, -//! for the places that record it whole (between a pass's instances). +//! it is not cut, or its rows' pieces in those lines lie at different places in them); past +//! them its kernel merges each row's words between its pieces, the columns its shape pushes +//! (`bind::ShadowMergeModule::shape_within`), storing changed words alone +//! (`ShadowMergeStores::Words`), and the host step the pieces, read in the parts, no copy of +//! them made ([`ShadowMerge::record_on_host`], [`ShadowMerge::drain`], +//! `WorkCounts::shadow_merges_on_host`; the words outside the columns count in no +//! `WorkCounts::shadow_merge_words_examined`). Its kernel's sets are made as for any merge in +//! place, for the places that record it whole (between a pass's instances). //! - **The kernel** (`bind::shadow_merge_module`, one per device and form, `owned_kernel.rs`): four //! 4-byte words an invocation, each a workgroup's invocations apart from the next, so one //! store's words are consecutive across the invocations that run together (its module docs, @@ -170,7 +173,6 @@ use super::shadow_splice::{self, MergeDrain, Rows}; use super::texture::heap_tiled::SampleMoves; use super::texture::kept_image::{KeptImage, KeptImages, KeptLease, TakenImage}; use super::tracker::{Access, Barrier, ImagePlace, Use, UseRange}; -use super::upload::Upload; use super::values::{CpuCacheMode, HazardTrackingMode, ResourceOptions, StorageMode}; use super::Device; use crate::device::functions::Vk; @@ -189,14 +191,16 @@ const GROUP_BYTES: u64 = 4 * (ShadowMergeModule::WORDS * ShadowMergeModule::LOCA const PART_ALIGNMENT: u64 = 256; /// The most bytes the cut rows of a merge on the host hold for its host step to merge them all -/// (`shadow_splice.rs`, **Merges**); past them it splits, its kernel merging all but the pieces -/// beside the texels. Below the bound the whole merge costs the host less than the split's own -/// GPU work costs the command buffer. Measured on the Iris Xe of RPL-P under ANV: that work (two -/// buffer copies of the pieces, three barriers and the kernel's dispatch) took about 0.6 ms a -/// command buffer for a 34x34 `RGBA16Float` target, and the host step's loop about 0.30 ns a byte -/// (4.97 ms for a 1920x1080 one's 16.6 MB, half its texels changed), so the split pays from about -/// 2 MB; the bound is half that. The whole merge also keeps a CPU write to a texel the commands -/// left in a line whose other bytes they changed, which the kernel's store may put back. +/// (`shadow_splice.rs`, **Merges**); past them it splits, its kernel merging each row's words +/// between its pieces ([`columns`]) and its host step the pieces. Measured on the Iris Xe of +/// RPL-P under ANV: the host step's loop takes about 0.3 ns a byte from heap memory (4.4 ms for a +/// 1920x1080 `RGBA16Float` texture's 16.6 MB, half its texels changed) and about 0.9 ns a byte +/// merging into pointer-imported host pages (954 us for 256 rows of 4,092 bytes). The split's GPU +/// part is its kernel's dispatch, with no copy of the pieces: a copy of one region per row costs +/// that device about 7 to 9 us a region (two a row took about 0.6 ms for 34 rows and 15 ms for +/// 1,024), so the kernel leaves each row's piece columns alone instead. The whole merge also +/// keeps a CPU write to a texel the commands left in a line whose other bytes they changed, which +/// the kernel's store may put back. const HOST_WHOLE_BYTES: u64 = 1 << 20; /// The most scratch buffers a shadow keeps for its next merges ([`ScratchSpares`]): one a frame's @@ -422,12 +426,29 @@ pub(super) struct ShadowMerge { /// pushed where the device pushes (`OwnedBinds`). binds: OwnedBinds, /// Each window's workgroups (along x and y) and push bytes. - dispatches: Vec<([u32; 2], [u8; 16])>, + dispatches: Vec<([u32; 2], Push)>, /// Where it merges on the host (`shadow_splice.rs`, **Merges**), what the host step reads and /// writes; `None` where its kernel merges. host: Option, } +/// The push bytes of one of a merge's dispatches: its kernel's shape. +enum Push { + /// `bind::ShadowMergeModule`'s, for a merge that reads the parts. + Parts([u8; 24]), + /// `bind::ShadowMergeImageModule`'s, for one that fetches the texels from the shadow. + Fetched([u8; 16]), +} + +impl Push { + fn bytes(&self) -> &[u8] { + match self { + Push::Parts(bytes) => bytes, + Push::Fetched(bytes) => bytes, + } + } +} + /// What a merge on the host compares and stores: the host addresses of its kept and changed /// parts, of a `Shared` scratch, and each piece: where it lies in the buffer's `VkBuffer`, its byte /// of each part, and its bytes. @@ -438,10 +459,10 @@ struct HostMerge { /// rows in lines beside its texels (`shadow_splice::beside_texels`), its kernel merging the /// rest. pieces: Vec<(u64, u64, u64)>, - /// Where its kernel merges the rest, the bytes the pieces' kept bytes take, back to back, in - /// the region of the arena the GPU copies them into before it - /// ([`ShadowMerge::record_on_host`]); `None` where the host step merges every byte. - saved: Option, + /// Its kernel merges the rest of its rows, the words between each row's pieces ([`columns`]), + /// after the copy of the texels the commands left; else the host step merges every byte, and + /// nothing is dispatched. + kernel: bool, } impl ShadowMerge { @@ -514,7 +535,8 @@ impl ShadowMerge { // Cut to its texels' rows, one with no piece of them in a line that also holds bytes // beside the texels goes by its kernel alone, as anywhere; one whose rows hold at most // `HOST_WHOLE_BYTES` goes on the host whole, as does one not cut; past them its host step - // takes those pieces (`pieces`), and its kernel the rest. + // takes those pieces (`pieces`), and its kernel the words between them, where every row's + // lie at the same columns (`columns`), else the host step merges every byte. let on_host = in_place && copies.merges_on_host(device); let cut = in_place.then(|| cut_of(copies, area)).flatten(); let pieces = (on_host) @@ -525,6 +547,10 @@ impl ShadowMerge { (cut.as_ref()) .is_some_and(|(_, geometry)| geometry.rows * geometry.row_bytes > HOST_WHOLE_BYTES) }); + let columns = (pieces.as_ref()) + .zip(cut.as_ref()) + .and_then(|(pieces, (_, geometry))| columns(pieces, geometry)); + let pieces = pieces.filter(|_| columns.is_some()); let limits = &device.properties().description.limits; let range = u64::from(limits.max_storage_buffer_range); let [groups, groups_y] = @@ -549,6 +575,7 @@ impl ShadowMerge { // merge goes there. let host = host || (on_host && cut.is_none()); let pieces = pieces.filter(|_| host && cut.is_some()); + let columns = columns.filter(|_| pieces.is_some()); let part = match &cut { Some((_, geometry, ..)) => geometry.rows * geometry.row_bytes, None => rounded, @@ -699,11 +726,10 @@ impl ShadowMerge { Some([held.first(), held.get(1)].map(|b| b.and_then(|b| mapped(b, 0)))) } }; - // What the host step merges: the pieces of a cut's rows beside its texels, their kept bytes - // copied back to back into a region (`saved` of them), else each row the merge reaches, - // the cut rectangle's, row after row in the parts, or every byte of the texture's, laid - // out as in the buffer. - let saved = (pieces.as_ref()).map(|pieces| pieces.iter().map(|&(.., bytes)| bytes).sum()); + // What the host step merges: the pieces of a cut's rows beside its texels, else each row + // the merge reaches, the cut rectangle's, row after row in the parts, or every byte of the + // texture's, laid out as in the buffer. + let kernel = pieces.is_some(); let pieces = match (pieces, &cut) { (Some(pieces), _) => pieces, (None, Some((_, geometry, ..))) => (0..geometry.rows) @@ -719,7 +745,7 @@ impl ShadowMerge { kept, changed, pieces, - saved, + kernel, }), Some(_) => { return Err(internal( @@ -840,15 +866,19 @@ impl ShadowMerge { let changed_window = (changed.raw, changed.at + start * row_bytes, size); sets.push(set(vec![kept_window(kept), changed_window, current_window])); let total = count * words; - let shape = ShadowMergeModule::shape( + // Each row's words between its pieces, which the host step takes, where + // it takes them; else every word. + let merged = columns.clone().unwrap_or(0..words); + let shape = ShadowMergeModule::shape_within( u32_of(words)?, u32_of(total)?, row_words, first_word, + u32_of(merged.start)?..u32_of(merged.end)?, ); let groups = ShadowMergeModule::groups(u32_of(total)?); - dispatches.push(([groups, 1], shape)); - examined += total; + dispatches.push(([groups, 1], Push::Parts(shape))); + examined += count * (merged.end - merged.start); } (None, kept_in) => { // The kept texels: the kept part's rows, or the kept image's, fetched at @@ -863,7 +893,7 @@ impl ShadowMerge { let read = (fetched.map(|(_, read)| read)) .ok_or_else(|| internal("a fetching merge without its read"))?; let groups = ShadowMergeImageModule::groups(read, [width, u32_of(count)?]); - dispatches.push((groups, shape)); + dispatches.push((groups, Push::Fetched(shape))); examined += u64::from(width) * u64::from(read.words()) * count; } } @@ -910,7 +940,7 @@ impl ShadowMerge { ])); // The window's words, one row of them. let shape = ShadowMergeModule::shape(words, words, 0, first_word); - dispatches.push(([ShadowMergeModule::groups(words), 1], shape)); + dispatches.push(([ShadowMergeModule::groups(words), 1], Push::Parts(shape))); examined += u64::from(words); start += size; } @@ -920,7 +950,7 @@ impl ShadowMerge { // that stores the tiles of its area, cut to the texels' rows (the module docs); but where // the host step stores the pieces beside the texels, whose lines a block's store holding // one would write back from the GPU. - let split = (host.as_ref()).is_some_and(|host| host.saved.is_some()); + let split = (host.as_ref()).is_some_and(|host| host.kernel); let stores = match blocks && !two_ways && cut.is_some() && !split { true => ShadowMergeStores::Blocks, false => ShadowMergeStores::Words, @@ -1117,114 +1147,53 @@ impl ShadowMerge { self.texels } - /// Where it merges on the host (`shadow_splice.rs`, **Merges**), the bytes of the arena's - /// region its host step reads the pieces' kept bytes from: 0 where the host step merges every - /// byte; `None` where it merges by its kernel. - pub(super) fn saves(&self) -> Option { - (self.host.as_ref()).map(|host| host.saved.unwrap_or(0)) + /// Whether it merges on the host (`shadow_splice.rs`, **Merges**). + pub(super) fn on_host(&self) -> bool { + self.host.is_some() } /// The CPU's part of this merge on the host, into the truth's pages, whose `VkBuffer`'s byte - /// `v` lies at the host address `v + base`: each piece the host step compares and stores - /// (each row the merge reaches, the cut rectangle's, row after row in the parts, else every - /// byte of the texture's, laid out as in the buffer; or, where its kernel merges the rest, the - /// pieces beside its texels, whose kept bytes the GPU copies into `region`, - /// [`record_on_host`](Self::record_on_host)). `None` where it merges by its kernel, or where - /// its kernel merges the rest and `region` is none or unmapped. - pub(super) fn drain(self: &Arc, base: u64, region: Option) -> Option { + /// `v` lies at the host address `v + base`: each piece the host step compares and stores, from + /// its kept and changed parts (each row the merge reaches, the cut rectangle's, row after row + /// in the parts, else every byte of the texture's, laid out as in the buffer; or, where its + /// kernel merges the rest, the pieces beside its texels). `None` where it merges by its kernel. + pub(super) fn drain(self: &Arc, base: u64) -> Option { let host = self.host.as_ref()?; - let kept = match (host.saved, ®ion) { - (None, _) => host.kept, - (Some(_), Some(region)) => { - let (chunk, at) = region.buffer(); - chunk.mapped_contents()?.as_ptr().addr() as u64 + at - } - (Some(_), None) => return None, - }; - let mut into = 0; let pieces = (host.pieces.iter()) - .map(|&(at, part, bytes)| { - let kept = match host.saved { - Some(_) => { - into += bytes; - into - bytes - } - None => part, - }; - (at.wrapping_add(base), kept, part, bytes) - }) + .map(|&(at, part, bytes)| (at.wrapping_add(base), part, bytes)) .collect(); Some(MergeDrain { _merge: Arc::clone(self), - _region: region, - kept, + kept: host.kept, changed: host.changed, pieces, }) } /// Record the GPU's part of a merge on the host (`shadow_splice.rs`, **Merges**): the copy of - /// the texels the commands left into the changed part; and, where its kernel merges all but - /// the pieces its host step takes, `saved` the arena's region the host step reads their kept - /// bytes from ([`saves`](Self::saves) of them, its `VkBuffer` and offset), the copy of those - /// kept bytes there, then, after a barrier, of their changed bytes over them in the kept part, - /// so that its dispatches, after another, find them unchanged and store none of them, and a - /// barrier to everything after. The host step reads the parts and the region once its batch - /// completed, which ends with the barrier to the host. + /// the texels the commands left into the changed part; and, where its kernel merges the words + /// between each row's pieces, after a barrier, its dispatches, which leave the pieces' words + /// to the host step ([`columns`]), and a barrier to everything after. The host step reads the + /// parts once its batch completed, which ends with the barrier to the host. /// /// # Safety /// - /// As `record_merge`; the region lives until the command buffer completes (its arena's). + /// As `record_merge`. pub(super) unsafe fn record_on_host( &self, device: &Vk, command_buffer: vk::CommandBuffer, (copies, moves): (&ShadowCopies, Option<&SampleMoves>), - saved: Option<(vk::Buffer, u64)>, ) { // SAFETY: the caller's contract. unsafe { self.record_changed(device, command_buffer, (copies, moves)) }; - let ( - Some(HostMerge { - pieces, - saved: Some(_), - .. - }), - Some((region, at)), - KeptIn::Part(kept), - Changed::Copied { part: changed, .. }, - ) = (&self.host, saved, self.kept_in, &self.changed) - else { - return; - }; - let mut into = at; - let saves: Vec = (pieces.iter()) - .map(|&(_, part, size)| { - into += size; - vk::BufferCopy { - src_offset: kept.at + part, - dst_offset: into - size, - size, - } - }) - .collect(); - let masks: Vec = (pieces.iter()) - .map(|&(_, part, size)| vk::BufferCopy { - src_offset: changed.at + part, - dst_offset: kept.at + part, - size, - }) - .collect(); - // SAFETY: the caller's contract; the pieces lie in the parts' rows, and back to back in - // the region, which holds `saves` bytes; the copies over the kept part read the changed - // part's bytes, apart from them. - unsafe { - device.cmd_copy_buffer(command_buffer, kept.raw, region, &saves); - Barrier::everything().record(device, command_buffer); - device.cmd_copy_buffer(command_buffer, changed.raw, kept.raw, &masks); - Barrier::everything().record(device, command_buffer); - self.record_dispatches(device, command_buffer); - Barrier::everything().record(device, command_buffer); + if (self.host.as_ref()).is_some_and(|host| host.kernel) { + // SAFETY: the caller's contract; the dispatches read the parts the copy wrote. + unsafe { + Barrier::everything().record(device, command_buffer); + self.record_dispatches(device, command_buffer); + Barrier::everything().record(device, command_buffer); + } } } @@ -1372,26 +1341,14 @@ impl ShadowMerge { Changed::Copied { ref dispatch, .. } => dispatch.is_some(), Changed::Fetched => true, }; - // A merge whose host step takes the pieces beside the texels also copies their kept bytes - // out of the kept part and their changed bytes over them (`record_on_host`). - let kept = match (self.kept_in, self.saves()) { - (KeptIn::Part(_), Some(saves)) if saves > 0 => Use { - key, - tracked, - range, - read: Access::new( - vk::PipelineStageFlags2::COPY | vk::PipelineStageFlags2::COMPUTE_SHADER, - vk::AccessFlags2::TRANSFER_READ | vk::AccessFlags2::SHADER_STORAGE_READ, - ), - write: transfer(vk::AccessFlags2::TRANSFER_WRITE), - }, - (KeptIn::Part(_), _) => Use::reads( + let kept = match self.kept_in { + KeptIn::Part(_) => Use::reads( key, tracked, range, storage(vk::AccessFlags2::SHADER_STORAGE_READ), ), - (KeptIn::Image { .. }, _) => Use::reads( + KeptIn::Image { .. } => Use::reads( key, tracked, range, @@ -1523,7 +1480,7 @@ impl ShadowMerge { self.kernel.layout, vk::ShaderStageFlags::COMPUTE, 0, - shape, + shape.bytes(), ); device.cmd_dispatch(command_buffer, groups[0], groups[1], 1); } @@ -1684,6 +1641,33 @@ fn beside( Some(shadow_splice::beside_texels(texture, cut, base, line)) } +/// The words of each row of `geometry` the kernel of a merge on the host merges, its host step +/// taking `pieces` (each one's place in the `VkBuffer`, its byte of each part and its bytes, +/// [`beside`]): those after the row's piece at its start and before its piece at its end, where +/// every row has the same pieces at the same places in it, each of whole words; `None` where they +/// differ (rows whose pitch is no multiple of the device's line start at different places in +/// theirs), which the host step then merges whole. The kernel so stores into no line the host +/// step stores into, and no copy of the pieces is made: the host step reads their bytes in the +/// kept and changed parts, which nothing writes after the changed copy. +fn columns(pieces: &[(u64, u64, u64)], geometry: &Geometry) -> Option> { + let row = geometry.row_bytes; + // Each row's piece at its start and at its end, their bytes. + let mut ends = vec![(0, 0); usize::try_from(geometry.rows).ok()?]; + for &(_, part, bytes) in pieces { + let (r, at) = (usize::try_from(part / row).ok()?, part % row); + let end = ends.get_mut(r)?; + match (at, at + bytes == row) { + (0, _) => end.0 = bytes, + (_, true) => end.1 = bytes, + (_, false) => return None, + } + } + let (head, tail) = *ends.first()?; + let same = ends.iter().all(|&end| end == (head, tail)); + let words = head.is_multiple_of(4) && tail.is_multiple_of(4) && head + tail <= row; + (same && words).then(|| head / 4..(row - tail) / 4) +} + /// Whether `bind::shadow_merge_image_module` takes the rectangle of `cut`: its first texel's /// coordinates and its last row's below 65536 (the shape's origin), and its row's workgroups /// within `groups` (`maxComputeWorkGroupCount[0]`); its rows go in bands of at most diff --git a/crates/metal2vulkan-runtime/src/shadow_splice.rs b/crates/metal2vulkan-runtime/src/shadow_splice.rs index 2fc771d07..780ff5f94 100644 --- a/crates/metal2vulkan-runtime/src/shadow_splice.rs +++ b/crates/metal2vulkan-runtime/src/shadow_splice.rs @@ -42,14 +42,16 @@ //! the commands left go into a `Shared` scratch, as two parts; the host step merges each row's //! bytes in the lines that also hold bytes of no row of the texture's (those between its rows, //! before its first and past its last, the bytes the probe above measured Metal keeping), and its -//! kernel the rest, whose lines hold its texels alone. Before the kernel the GPU copies those -//! pieces' kept bytes into a region of the command buffer's arena, then their changed bytes over -//! them in the kept part, so the kernel finds them unchanged and stores none of them; the host step -//! compares the region's bytes with the changed part's and stores those that differ -//! ([`store_differing`]). A merge none of whose rows' lines holds a byte beside its texels goes by -//! its kernel alone, as anywhere; one whose cut rows hold at most `shadow_merge::HOST_WHOLE_BYTES` -//! (1 MiB), where the whole merge costs the host less than the split's GPU work, and one not cut to -//! its texels' rows (`shadow_merge.rs`, **Cut**), go on the host whole: the host step compares and +//! kernel the rest, whose lines hold its texels alone. Each row's pieces lying at the same places +//! in it, the kernel merges only the words between them (its shape's columns, +//! `bind::ShadowMergeModule::shape_within`), so it stores into none of their lines; the host step +//! compares their kept part's bytes with the changed part's and stores those that differ +//! ([`store_differing`]); nothing copies the pieces (a copy of one small region a row cost the +//! Iris Xe about 7 to 9 us a region). A merge none of whose rows' lines holds a byte beside its +//! texels goes by its kernel alone, as anywhere; one whose cut rows hold at most +//! `shadow_merge::HOST_WHOLE_BYTES` (1 MiB), one whose rows' pieces lie at different places in +//! them (rows whose pitch is no multiple of a line), and one not cut to its texels' rows +//! (`shadow_merge.rs`, **Cut**), go on the host whole: the host step compares and //! stores every byte of the rows (`WorkCounts::shadow_merges_on_host`, //! `shadow_merge_bytes_on_host`; each host step counted in `shadow_host_steps`). Where the kernel //! stores, a CPU write to a texel the commands left, in a line whose other bytes they changed, @@ -556,22 +558,17 @@ pub(super) struct SpliceDrain { } /// The CPU's part of a shadow's merge on the host (`shadow_merge.rs`, **On the host**): the -/// texels the commands left, in the merge's scratch, and those kept before them, there or in the -/// region the GPU copied them into, compared piece by piece, and each byte that differs stored -/// into the truth's pages. It holds nothing of the program's, as a [`SpliceDrain`]. +/// texels the commands left and those kept before them, in the merge's scratch, compared piece by +/// piece, and each byte that differs stored into the truth's pages. It holds nothing of the +/// program's, as a [`SpliceDrain`]. pub(super) struct MergeDrain { /// The merge, which holds its scratch. pub(super) _merge: Arc, - /// The region of the command buffer's arena the GPU copied the pieces' kept bytes into, where - /// the merge's kernel merges the rest (the module docs' **Merges**): held until the step. - pub(super) _region: Option, - /// The host addresses of the kept bytes' first (the kept part's, or the region's) and the - /// changed part's. + /// The host addresses of the kept part's first byte and the changed part's. pub(super) kept: u64, pub(super) changed: u64, - /// Each piece's host address in the pages, its byte of the kept bytes and of the changed part, - /// and its bytes. - pub(super) pieces: Vec<(u64, u64, u64, u64)>, + /// Each piece's host address in the pages, its byte of each part, and its bytes. + pub(super) pieces: Vec<(u64, u64, u64)>, } impl MergeDrain { @@ -580,18 +577,14 @@ impl MergeDrain { /// The bytes compared. fn run(&self) -> u64 { let mut compared = 0; - for &(host, kept, changed, length) in &self.pieces { + for &(host, at, length) in &self.pieces { // SAFETY: both hold `length` bytes from there (the merge's scratch, a `Shared` buffer - // the merge holds, and the arena's region, mapped while they live), which the GPU's - // copies wrote before the batches this step follows completed, and which no command - // writes any more. + // the merge holds, mapped while it lives), which the GPU's copies wrote before the + // batches this step follows completed, and which no command writes any more. let (kept, changed) = unsafe { ( - std::slice::from_raw_parts((self.kept + kept) as *const u8, length as usize), - std::slice::from_raw_parts( - (self.changed + changed) as *const u8, - length as usize, - ), + std::slice::from_raw_parts((self.kept + at) as *const u8, length as usize), + std::slice::from_raw_parts((self.changed + at) as *const u8, length as usize), ) }; // SAFETY: the piece's host bytes lie in the truth's pages, which stay mapped until the diff --git a/crates/metal2vulkan-runtime/src/tests/shadow_runs.rs b/crates/metal2vulkan-runtime/src/tests/shadow_runs.rs index 4d67be348..a9f10757b 100644 --- a/crates/metal2vulkan-runtime/src/tests/shadow_runs.rs +++ b/crates/metal2vulkan-runtime/src/tests/shadow_runs.rs @@ -818,7 +818,9 @@ const INTO_PAGE: usize = 16; /// from [`INTO_PAGE`] bytes into one, so every row's first and last lines hold bytes beside its /// texels, a pass over a 512x512 texture (1 MiB of rows) compares every byte of its rows on the /// host, and one over a 512x513 texture each row's bytes in its first and last lines alone, its -/// kernel merging the rest; each takes one host step. +/// kernel examining only the words between them, which every row holds at the same columns (the +/// merge's shape's, `bind::ShadowMergeModule::shape_within`), so no copy of those lines is made; +/// each takes one host step. #[test] fn merges_on_the_host_go_whole_up_to_the_bound_and_split_past_it() { let host = Host::into_page(ROW * H, INTO_PAGE); @@ -855,20 +857,23 @@ fn merges_on_the_host_go_whole_up_to_the_bound_and_split_past_it() { delta(|c| c.shadow_merges_on_host), delta(|c| c.shadow_merge_bytes_on_host), delta(|c| c.shadow_host_steps), + delta(|c| c.shadow_merge_words_examined), ); - // Whole: every byte of the rows. Split: each row's first line's bytes and its last's, a - // line's in all (its start and end as far into their lines, its pitch whole lines). - let (form, compared) = match rows <= 1 << 20 { - true => ("whole", rows), - false => ("split", height * line), + // Whole: every byte of the rows on the host (its kernel planned over every word, and not + // dispatched). Split: each row's first line's bytes and its last's, a line's in all (its + // start and end as far into their lines, its pitch whole lines), and the kernel the words + // between them. + let (form, compared, examined) = match rows <= 1 << 20 { + true => ("whole", rows, rows / 4), + false => ("split", height * line, height * (width * TEXEL - line) / 4), }; println!( "SHADOW-RUNS bound: {width}x{height}, {rows} bytes of rows: merges on the host, bytes \ - compared, host steps {counted:?}" + compared, host steps, words the kernel examines {counted:?}" ); assert_eq!( counted, - (1, compared, 1), + (1, compared, 1, examined), "a {width}x{height} texture's merge on the host goes {form}" ); } diff --git a/crates/metal2vulkan-runtime/src/tests/shadow_write_lines.rs b/crates/metal2vulkan-runtime/src/tests/shadow_write_lines.rs index 2c94ca37b..95b054096 100644 --- a/crates/metal2vulkan-runtime/src/tests/shadow_write_lines.rs +++ b/crates/metal2vulkan-runtime/src/tests/shadow_write_lines.rs @@ -84,6 +84,10 @@ const CHECK_WAIT: Duration = Duration::from_secs(120); const SHORT_WIDTH: u64 = 1023; const PAGE_ROW: u64 = 4096; const SHORT_HEIGHTS: [u64; 2] = [256, 1024]; +/// The cost test's 4K shape: 3839 `RGBA16Float` texels a row, 2160 rows, 30720 bytes apart (a 3840 +/// wide target's pitch), so each row ends 8 bytes inside a line; 66 MB of rows, inside the 64 MiB +/// a udmabuf takes by default. +const LARGE: (u64, u64, u64) = (3839, 2160, 30720); /// The device made without `VK_EXT_external_memory_host`, so that a no-copy buffer is imported as /// dma-bufs of its pages, every texture over host pages a shadow. @@ -527,9 +531,12 @@ fn a_copy_back_splices_by_the_device_s_check() { drop(ram); } -/// The cost of a write back, spliced and merged on the host or not: for the guest's shape and a +/// The cost of a write back, spliced and merged on the host or not: for the guest's shape, a /// 1920x1080 `RGBA16Float` IOSurface plane (rows 15360 bytes apart, each on a line, so its copy -/// back splices nothing, and its merge goes by its kernel alone), a pass that clears and stores it +/// back splices nothing, and its merge goes by its kernel alone), and a 4K one whose rows end a +/// texel short of their pitch ([`LARGE`]: each row's last line holds bytes beside its texels, and +/// its rows hold far more than `shadow_merge::HOST_WHOLE_BYTES`, so its merge on the host splits, +/// its kernel merging all but those lines), a pass that clears and stores it /// (a copy back) and one that loads it, draws over its right half and stores it (a keep and a /// merge), each [`COST_ROUNDS`] command buffers committed and waited for under each verdict, the /// verdicts unanswered (spliced, on the host) and passed (as before) alternating round by round @@ -551,7 +558,7 @@ fn costs_of_a_write_back_spliced_or_not() { let queue = device.new_command_queue().unwrap(); let state = drawing(&device, PixelFormat::RGBA16Float); let checks = &device.shared().in_place; - for (width, height, row) in [(WIDTH, HEIGHT, ROW), (1920, 1080, 15360)] { + for (width, height, row) in [(WIDTH, HEIGHT, ROW), (1920, 1080, 15360), LARGE] { let length = row * height; let file = (length as usize).next_multiple_of(host_page()); let ram = Ram::new(file, 0, file); diff --git a/crates/metal2vulkan/src/bind/shadow_merge.rs b/crates/metal2vulkan/src/bind/shadow_merge.rs index 4cbdd6040..685229e4b 100644 --- a/crates/metal2vulkan/src/bind/shadow_merge.rs +++ b/crates/metal2vulkan/src/bind/shadow_merge.rs @@ -32,14 +32,21 @@ //! //! The shape's words, in order: `width`, the words of one row of the region (at least 1); //! `count`, the region's words (`width` times its rows); `row_words`, the current buffer's rows -//! apart in words; and `first_word`, the word of the region's first in the current binding. -//! Invocation `l` of workgroup `g` takes the words `i = 4Ng + Nk + l` for `k` from 0 to 3 -//! ([`ShadowMergeModule::WORDS`], `N` [`ShadowMergeModule::LOCAL_SIZE`]), one after the other; a -//! word `i` below `count` takes word `i` of the kept and changed buffers and, +//! apart in words; `first_word`, the word of the region's first in the current binding; and +//! `columns_start` and `columns_end`, the words of each row the dispatch merges, `i % width` from +//! the first to before the second ([`ShadowMergeModule::shape_within`]; every word of the row for +//! [`ShadowMergeModule::shape`]). Invocation `l` of workgroup `g` takes the words +//! `i = 4Ng + Nk + l` for `k` from 0 to 3 ([`ShadowMergeModule::WORDS`], `N` +//! [`ShadowMergeModule::LOCAL_SIZE`]), one after the other; a word `i` below `count` whose +//! column `i % width` lies in the columns takes word `i` of the kept and changed buffers and, //! where they differ, word `first_word + (i / width) · row_words + i % width` of the current //! buffer: each of its bytes where the changed word's differs from the kept one's becomes the //! changed word's, and the others keep the current word's. Where the kept and changed words are -//! equal it reads and writes nothing of the current buffer; a word past `count` does nothing. +//! equal it reads and writes nothing of the current buffer; a word past `count`, or outside the +//! columns, does nothing: it is not read in the kept and changed buffers either, and counts as +//! unchanged in its block under whole-block stores. A consumer whose rows' first or last words +//! lie in memory another writer's stores must not share (a device that writes back the lines of +//! memory its stores end in whole) leaves those columns out and merges them itself. //! A dispatch takes [`ShadowMergeModule::groups`] workgroups. Contiguous bytes are one row: //! `width` and `count` the words, `row_words` any, `first_word` 0. A consumer whose bytes //! exceed `maxStorageBufferRange` or `maxComputeWorkGroupCount[0]` workgroups binds them in @@ -83,6 +90,7 @@ //! `SHADER_STORAGE_WRITE` in `COMPUTE_SHADER` before the dispatch; its writes → //! `TRANSFER_READ` before the current buffer is copied back, or the bytes' next use. +use std::ops::Range; use std::sync::Arc; use crate::budget::{Budget, Meter}; @@ -122,8 +130,9 @@ impl ShadowMergeModule { pub const LOCAL_SIZE: u32 = 64; /// The words one invocation merges, one after the other. pub const WORDS: u32 = 4; - /// Bytes of the `COMPUTE` push-constant range at offset 0: the region's shape. - pub const PUSH_BYTES: u32 = 16; + /// Bytes of the `COMPUTE` push-constant range at offset 0: the region's shape and its + /// columns. + pub const PUSH_BYTES: u32 = 24; /// Bytes of one block under whole-block stores ([`ShadowMergeStores::Blocks`]): the /// `LOCAL_SIZE` consecutive words a workgroup takes in one step (the module docs). pub const BLOCK_BYTES: u32 = 4 * Self::LOCAL_SIZE; @@ -134,10 +143,30 @@ impl ShadowMergeModule { } /// The push bytes of a region of `count` words, `width` a row (at least 1), its rows - /// `row_words` apart in the current buffer from its word `first_word` (the module docs). - pub fn shape(width: u32, count: u32, row_words: u32, first_word: u32) -> [u8; 16] { - let words = [width, count, row_words, first_word]; - let mut bytes = [0; 16]; + /// `row_words` apart in the current buffer from its word `first_word`, every word of each row + /// merged (the module docs). + pub fn shape(width: u32, count: u32, row_words: u32, first_word: u32) -> [u8; 24] { + Self::shape_within(width, count, row_words, first_word, 0..width) + } + + /// As [`shape`](Self::shape), merging of each row only the words whose column (`i % width`) + /// lies in `columns`: the others are neither read nor written, as the words past the region. + pub fn shape_within( + width: u32, + count: u32, + row_words: u32, + first_word: u32, + columns: Range, + ) -> [u8; 24] { + let words = [ + width, + count, + row_words, + first_word, + columns.start, + columns.end, + ]; + let mut bytes = [0; 24]; for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) { chunk.copy_from_slice(&word.to_le_bytes()); } @@ -193,8 +222,8 @@ const SHAPE: PushField = PushField::DispatchRegion; /// The merge module as a typed module, before serialization: the module /// [`shadow_merge_module`] serializes, which the CPU interpreter runs. Its bindings are the -/// symbols `KEPT`, `CHANGED` and `CURRENT`, and its push field the shape, a `uvec4` (the module -/// docs). +/// symbols `KEPT`, `CHANGED` and `CURRENT`, and its push field the shape, a `uvec4`, then its +/// columns, a `uvec2` (the module docs). fn typed_module(blocks: bool) -> BResult { let mut b = ModuleBuilder::new(); let u32_ = b.ty(Type::Int { @@ -202,8 +231,10 @@ fn typed_module(blocks: bool) -> BResult { signed: false, })?; let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; + let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 })?; let uvec4 = b.ty(Type::Vector { elem: u32_, len: 4 })?; let m_shape = b.push_member(SHAPE, uvec4, 0)?; + let m_columns = b.push_member(SHAPE, uvec2, 16)?; let push = b.push_global()?; let kept = words_buffer(&mut b, KEPT, u32_)?; let changed = words_buffer(&mut b, CHANGED, u32_)?; @@ -234,6 +265,20 @@ fn typed_module(blocks: bool) -> BResult { let count = f.composite_extract(shape, &[1])?; let row_words = f.composite_extract(shape, &[2])?; let first_word = f.composite_extract(shape, &[3])?; + let member = u32_value(&mut f, m_columns.index)?; + let columns = f.access_chain(push, &[member])?; + let columns = f.load(columns, MemAccess::default())?; + let columns_start = f.composite_extract(columns, &[0])?; + let columns_end = f.composite_extract(columns, &[1])?; + // Whether word `i` is one the dispatch merges: below `count`, its column in the columns. + let merges = move |f: &mut FunctionBuilder<'_>, i: Value| -> BResult { + let inside = f.binary(BinOp::ULessThan, i, count)?; + let x = f.binary(BinOp::UMod, i, width)?; + let after = f.binary(BinOp::UGreaterThanEqual, x, columns_start)?; + let before = f.binary(BinOp::ULessThan, x, columns_end)?; + let column = f.binary(BinOp::LogicalAnd, after, before)?; + f.binary(BinOp::LogicalAnd, inside, column) + }; // The workgroup's first word, plus the invocation's place in it: its words lie `LOCAL_SIZE` // apart from there, so each of the four stores below falls on consecutive words across // consecutive invocations (the module docs). @@ -256,8 +301,9 @@ fn typed_module(blocks: bool) -> BResult { f.binary(BinOp::IAdd, base, step)? } }; - let inside = f.binary(BinOp::ULessThan, i, count)?; - // A word past the region reads the region's first, and counts as unchanged. + let inside = merges(&mut f, i)?; + // A word past the region or outside its columns reads the region's first, and counts + // as unchanged. let read = f.select(inside, i, zero)?; let p = f.access_chain(kept, &[zero, read])?; let before = f.load(p, MemAccess::default())?; @@ -293,7 +339,7 @@ fn typed_module(blocks: bool) -> BResult { f.binary(BinOp::IAdd, base, step)? } }; - let inside = f.binary(BinOp::ULessThan, i, count)?; + let inside = merges(&mut f, i)?; let merge: ArmFn<'_, ()> = Box::new(move |f, _| { let p = f.access_chain(kept, &[zero, i])?; let before = f.load(p, MemAccess::default())?; @@ -533,7 +579,7 @@ mod tests { kept: &[u8], changed: &[u8], current: &[u8], - shape: &[u8; 16], + shape: &[u8; 24], groups: u32, ) -> Vec { let mut out = Vec::new(); @@ -554,7 +600,7 @@ mod tests { kept: &[u8], changed: &[u8], current: &[u8], - shape: &[u8; 16], + shape: &[u8; 24], groups: u32, blocks: bool, ) -> (Vec, Vec) { @@ -644,6 +690,40 @@ mod tests { assert_eq!(merged_in(&kept, &changed, ¤t, &shape, 1), want); } + /// A region of rows merged within columns: each row's words outside them keep the current + /// buffer's, though the command changed them (the words a consumer merges itself, those in + /// lines of memory beside the rows), and inside them the merge is the rule's; in both forms of + /// the stores, whose blocks here cross the columns' edges. + #[test] + fn a_region_merged_within_columns_leaves_the_words_outside_them() { + // 70 rows of 6 words, rows 9 apart from word 1, columns 1 to 4: two workgroups' blocks, + // each crossing rows and the columns' edges. + let (width, rows, row_words, first_word) = (6u32, 70u32, 9u32, 1u32); + let count = width * rows; + let kept = vec![0u8; 4 * count as usize]; + // Every byte of every word changed. + let changed = vec![0x5au8; 4 * count as usize]; + let last = first_word + (rows - 1) * row_words + width; + let current: Vec = (0..4 * last).map(|at| (at % 251) as u8 ^ 0xc3).collect(); + let mut want = current.clone(); + for i in 0..count { + if (1..4).contains(&(i % width)) { + let word = first_word + (i / width) * row_words + i % width; + want[(4 * word) as usize..][..4].copy_from_slice(&[0x5a; 4]); + } + } + let shape = ShadowMergeModule::shape_within(width, count, row_words, first_word, 1..4); + let groups = ShadowMergeModule::groups(count); + assert_eq!(groups, 2, "two workgroups"); + assert_eq!(merged_in(&kept, &changed, ¤t, &shape, groups), want); + // Every column is the region whole, as `shape` gives it. + let whole = ShadowMergeModule::shape_within(width, count, row_words, first_word, 0..width); + assert_eq!( + whole, + ShadowMergeModule::shape(width, count, row_words, first_word) + ); + } + /// The merge's rule word by word, over a region whose words are not a multiple of the /// `WORDS * LOCAL_SIZE` a workgroup takes (so the last workgroup's invocations run past /// them, each word of the tail guarded on its own) and over a mix of words the command left diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 2cf35a695..97407989f 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2445; +pub const RUNTIME_VERSION: u32 = 2446; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index d46bfdf21..30b582bde 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -857,7 +857,7 @@ assoc-const-value metal2vulkan::bind::ShadowMergeModule::CHANGED_BINDING 1 assoc-const-value metal2vulkan::bind::ShadowMergeModule::CURRENT_BINDING 2 assoc-const-value metal2vulkan::bind::ShadowMergeModule::KEPT_BINDING 0 assoc-const-value metal2vulkan::bind::ShadowMergeModule::LOCAL_SIZE 64 -assoc-const-value metal2vulkan::bind::ShadowMergeModule::PUSH_BYTES 16 +assoc-const-value metal2vulkan::bind::ShadowMergeModule::PUSH_BYTES 24 assoc-const-value metal2vulkan::bind::ShadowMergeModule::SET 0 assoc-const-value metal2vulkan::bind::ShadowMergeModule::WORDS 4 assoc-const-value metal2vulkan::bind::ShadowMergeRead::ALL [ShadowMergeRead::Words(ShadowTexelView::R32Uint), ShadowMergeRead::Words(ShadowTexelView::R8G8B8A8Uint), ShadowMergeRead::Words(ShadowTexelView::R32G32Uint), ShadowMergeRead::Words(ShadowTexelView::R32G32B32A32Uint), ShadowMergeRead::Words(ShadowTexelView::R8Uint), ShadowMergeRead::Words(ShadowTexelView::R16Uint), ShadowMergeRead::B8G8R8A8Unorm, ShadowMergeRead::R8G8B8A8Unorm] @@ -9819,7 +9819,8 @@ method metal2vulkan::bind::ShadowCopyInModule::shape pub fn shape([x0, y0]: [u32 method metal2vulkan::bind::ShadowMergeImageModule::groups pub fn groups(read: ShadowMergeRead, [width, height]: [u32; 2]) -> [u32; 2] method metal2vulkan::bind::ShadowMergeImageModule::shape pub fn shape([x0, y0]: [u32; 2], width: u32, row_words: u32, first_word: u32) -> [u8; 16] method metal2vulkan::bind::ShadowMergeModule::groups pub fn groups(count: u32) -> u32 -method metal2vulkan::bind::ShadowMergeModule::shape pub fn shape(width: u32, count: u32, row_words: u32, first_word: u32) -> [u8; 16] +method metal2vulkan::bind::ShadowMergeModule::shape pub fn shape(width: u32, count: u32, row_words: u32, first_word: u32) -> [u8; 24] +method metal2vulkan::bind::ShadowMergeModule::shape_within pub fn shape_within(width: u32, count: u32, row_words: u32, first_word: u32, columns: Range) -> [u8; 24] method metal2vulkan::bind::ShadowMergeRead::words pub fn words(self) -> u32 method metal2vulkan::bind::ShadowTexelView::words pub fn words(self) -> u32 method metal2vulkan::bind::SlotRebinds::slots pub fn slots(&self) -> &[SlotRef] diff --git a/docs/API.md b/docs/API.md index 0e740c80a..39c096443 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2511,7 +2511,8 @@ bound. stores each byte that differs of each row's bytes in the lines that also hold bytes beside them (`WorkCounts::shadow_merges_on_host`, `shadow_merge_bytes_on_host`, `shadow_host_steps`; a merge none of whose rows' lines holds such a byte goes by its kernel alone, and one whose rows - hold at most 1 MiB goes on the host whole; docs/FAST-PATHS.md, **Known gaps**, the Iris Xe's + hold at most 1 MiB, or whose rows' pieces in those lines lie at different places in them, goes + on the host whole; docs/FAST-PATHS.md, **Known gaps**, the Iris Xe's line write-back, which may still put back a CPU write to a texel the commands left in a line whose other bytes they changed, where the kernel stores). Where the device is measured to run it faster so (`DriverFact::ShadowCopyBackDispatchFaster`), a copy back of a one-slice texture of 4-, diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index df077ceee..f47773ea0 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -928,11 +928,12 @@ driver's. Each is open work. the rows and around them (`WorkCounts::shadow_merges_on_host`, `shadow_merge_bytes_on_host`, `shadow_merge_host_nanos`; each host step in `shadow_host_steps`). A merge none of whose rows' lines holds such a byte goes by its kernel alone, as on any device; one whose cut rows hold at - most 1 MiB (`shadow_merge::HOST_WHOLE_BYTES`, where the whole merge costs the host less than the - split's GPU work: on the Iris about 0.6 ms a command buffer for that work against about 0.30 ns a - byte for the host step's loop), and one not cut to its texels' rows (`shadow_merge.rs`, - **Cut**), go on the host whole. Such a texture opens no run of passes (`pass_runs.rs`). Metal's - contract for those bytes is measured: + most 1 MiB (`shadow_merge::HOST_WHOLE_BYTES`), one whose rows' pieces in those lines lie at + different places in them (rows whose pitch is no multiple of a line), and one not cut to its + texels' rows (`shadow_merge.rs`, **Cut**), go on the host whole; past the bound the kernel + merges each row's words between its pieces (the columns its shape pushes) and the host step the + pieces, read in the scratch, which no copy moves. Such a texture opens no run + of passes (`pass_runs.rs`). Metal's contract for those bytes is measured: `crates/metal2vulkan-conformance/probes/row_padding_writes.m` found an M3 Max, a Radeon Pro 5300M and an Intel UHD 630 keeping every CPU write to the bytes between and around a texture's rows under clears, stores and draws, and over IOSurfaces under kernels. No probe measured a CPU