From 26d00a396ccdd0c066766a7ed0a1b9eb0b1efb9a Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 7 Nov 2026 23:32:00 -0800 Subject: [PATCH] Weigh a reader of its pass's color by what it covered in its last measured pass The area rule weighs a reader through no scissor at the share least favourable to each form, since a draw's recording cannot know what it covers. A 1280x720 or 1080p reader covering the whole target therefore took the snapshot, 1.97-2.34x the split's GPU time on the Radeon 780M, while the consumer's readers over 3% of a 3662x2039 target need the snapshot (Iris 12.8 -> 1.7 ms a frame). Both shapes weigh the same at recording, so no static rule serves both. Now, on a device with occlusionQueryPrecise that resets queries on the host, each reader the rule would weigh records its drawing commands inside a precise occlusion query of its pass's own pool (render/coverage.rs). As the command buffer completes, the count is kept on the reader's first color's texture, keyed by the pipeline state and the reader's place among that state's readers of the texture in the pass. Later passes weigh that reader at its count: the snapshot where SNAPSHOT_PIXEL_COST per covered pixel per color costs no more than the split's copy. A device without precise queries or host reset, a reader inside an app's visibility query (already refused the snapshot), a pending pipeline's draw and a replay record no query and keep the area rule. Instances recorded inline after a split keep the query's begin and end with their draws. Both forms are exact; a stale count costs the form it chose until a pass after the change completes. Counted: WorkCounts::coverage_queries and reading_draws_by_coverage. The crossover lane runs each cell once untimed so its timed frame is weighed by the learned count. Tests: tests::learned_coverage (forms and bytes across a sparse -> whole -> sparse change; an app's Counting visibility query keeps its count with a reader inside), coverage unit tests. (cherry picked from commit 1108cd1bdebfb15f9da91b39ed80d91d8624bc28) --- .../examples/host_ab/runtime.rs | 2 + .../src/pipeline/render.rs | 6 + crates/metal2vulkan-runtime/src/render.rs | 57 +++ .../src/render/coverage.rs | 299 ++++++++++++++++ .../src/render/inline_splits.rs | 21 ++ .../src/render/snapshot.rs | 93 ++++- .../src/tests/learned_coverage.rs | 330 ++++++++++++++++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + crates/metal2vulkan-runtime/src/texture.rs | 31 ++ .../metal2vulkan-runtime/src/work_counts.rs | 26 ++ .../src/runtime_lane/attachment_read_costs.rs | 8 +- crates/metal2vulkan/tests/api_signatures.tsv | 2 + docs/API.md | 2 +- 13 files changed, 866 insertions(+), 13 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/render/coverage.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/learned_coverage.rs diff --git a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs index 23ae22903..b556b72ce 100644 --- a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs +++ b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs @@ -2053,6 +2053,8 @@ impl Gpu for Runtime { ("attachment_read_clears", c.attachment_read_clears), ("reading_draws_snapshotted", c.reading_draws_snapshotted), ("snapshot_inline_splits", c.snapshot_inline_splits), + ("reading_draws_by_coverage", c.reading_draws_by_coverage), + ("coverage_queries", c.coverage_queries), ("reading_draws_pinned", c.reading_draws_pinned), ("stand_ins_after_pins", c.stand_ins_after_pins), ("feedback_loop_alias_images", c.feedback_loop_alias_images), diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index 5ef16082e..e98b9f407 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -2258,6 +2258,12 @@ impl GraphicsState { Arc::ptr_eq(&self.0, &other.0) } + /// The state's address, while the program holds it: what a reader of its draws is known by + /// across passes (`render/coverage.rs`). + pub(crate) fn address(&self) -> usize { + Arc::as_ptr(&self.0).addr() + } + /// Another reference to the state, which a command buffer holds it by /// (`EncoderCore::retain_shared`). pub(crate) fn held(&self) -> Arc { diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 640a10e21..461325ef2 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -398,6 +398,7 @@ mod arguments; mod bound; mod call_checks; mod color_groups; +pub(crate) mod coverage; mod deferral; mod draw_again; mod draw_room; @@ -1465,6 +1466,9 @@ pub(crate) struct RenderLowering { /// (`set_object_threadgroup_memory_length`), which its mesh draws bind. object_threadgroup_lengths: BTreeMap, visibility: Visibility, + /// The pass's readers of its own colors the area rule weighed, and those it measures + /// (`render/coverage.rs`). + readers: coverage::Readers, /// The tile stage's table, which tile dispatches bind (`tile_dispatch.rs`). tile: ArgumentTable, /// The pass's tile dispatches, each recorded after the instance before it. @@ -2177,6 +2181,7 @@ impl RenderLowering { scissors: ScissorRects::metal_default(area), render_target_array_length, visibility: Visibility::new(layout.visibility.clone()), + readers: coverage::Readers::default(), layout: Versioned::new(layout), passes: vec![(shape, compatible)], pipeline: None, @@ -4232,6 +4237,7 @@ impl RenderLowering { mut layout, passes, mut visibility, + readers, dispatches, scratch: tile_scratch, shadow, @@ -4271,6 +4277,11 @@ impl RenderLowering { // The bind state its last draw left, which the device's next render encoder starts from // (`live_bind.rs`): no draw holds it once the encoder ends. core.device().shared().live_binds.give(live); + // The pass's measured readers, whose counts their textures take as the command buffer + // completes (`render/coverage.rs`): held with its pool until then. + if let Some(readback) = readers.readback() { + core.retain(readback); + } // The pass's instances in order: the earlier ones (a pass split), then the current one. let mut instances = earlier; instances.push(current); @@ -8033,6 +8044,13 @@ impl RenderLowering { // through a snapshot where it can (`render/snapshot.rs`): asked of the plan, kept where // the plan reads so, else `None` and the split. let mut snapshot = self.snapshot_wanted(&pipeline, &reformats); + // Weighed by what it covered when a pass last measured it, else by the area rule, and + // measured where the device measures readers: its drawing commands record inside the + // query (`render/coverage.rs`). + let mut covered_query = None; + if let Some(wanted) = snapshot.take() { + (snapshot, covered_query) = self.snapshot_by_area(&pipeline, wanted)?; + } // Its runtime samplers' address modes as the textures they sample map them: what it // settles under, and binds with. let sampler_maps = self.sampler_maps(&pipeline, &pass_start)?; @@ -10372,7 +10390,34 @@ impl RenderLowering { None => (&pushes[a][..], vk_draws), } }; + // A measured reader's drawing commands record inside its query, into its instance or + // kept with its draws where the instance is kept (`render/inline_splits.rs`); not + // those of a pipeline still being made, which a later step records, nor a replay's + // (`render/coverage.rs`). A query never recorded reads as never run. + let covered_query = + covered_query.filter(|_| made_now.is_some() && self.replayed.is_none()); for &phase in phases { + let counted = covered_query.filter(|_| phase != Some(snapshot::Phase::Snapshot)); + if let Some((pool, query)) = counted { + match &mut self.current.kept { + Some(kept) => kept.begin_query(pool, query), + // SAFETY: the instance's command buffer (or the pass's, inline) is + // recording inside its pass, which has one sample and one layer (the + // area rule's checks); the query is the pass's own, reset on the host and + // begun nowhere else; no other occlusion query is active (no visibility + // query is, the checks); the pool is held until the command buffer + // completes. + None => unsafe { + device.shared().vk().cmd_begin_query( + self.current.draws, + pool, + query, + vk::QueryControlFlags::PRECISE, + ) + }, + } + device.shared().counts.coverage_query(); + } let mut first = true; // Amplification by amplification, each through its recordings' regions: Metal // renders every primitive of one before the next's, and a pixel's regions are one. @@ -10467,6 +10512,18 @@ impl RenderLowering { } } } + if let Some((pool, query)) = counted { + match &mut self.current.kept { + Some(kept) => kept.end_query(pool, query), + // SAFETY: the query this phase began, in the same subpass. + None => unsafe { + device + .shared() + .vk() + .cmd_end_query(self.current.draws, pool, query) + }, + } + } } draw_alone = states_recorded.draw_alone(); states_recorded.count(self.core.counts()); diff --git a/crates/metal2vulkan-runtime/src/render/coverage.rs b/crates/metal2vulkan-runtime/src/render/coverage.rs new file mode 100644 index 000000000..8e434f5a2 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/render/coverage.rs @@ -0,0 +1,299 @@ +//! What a reader of its own pass's color covered, learned from a pass that ran: the area rule +//! (`render/snapshot.rs`) weighs the snapshot at the share of the draw's scissors least favourable +//! to it, as a draw's recording cannot know what it covers; once a pass showed what a reader +//! covered, its later passes weigh the snapshot at that. +//! +//! - **Why.** A reader through no scissor of a large target weighs the same at recording whether +//! it covers 3% of the target (the consumer's readers, `runtime_lane::attachment_read_costs:: +//! self_reads`) or all of it (`snapshot_area_costs`' whole-target rows): the rule takes the +//! snapshot for both, which costs the second about twice the split on the Radeon 780M. +//! - **Measured.** Each reader the rule weighs (a draw that could read through snapshots, of a +//! private color, every check before the rule passed: `RenderLowering::snapshot_wanted`) records +//! its drawing commands inside a precise occlusion query of its pass's own pool (Vulkan's +//! `VK_QUERY_CONTROL_PRECISE_BIT`: "the query result will be the number of samples that passed"), +//! whichever form it took: its snapshot draws' fragments are its drawing draws' (the snapshot +//! module's docs), and the pass has one sample (the rule's checks). As the command buffer +//! completes, each query's count is kept on the reader's first color's texture (the one a view +//! was made from), by the reader's identity: its pipeline state and its place among that +//! state's readers of the texture in its pass ([`ReaderKey`]). A texture keeps [`LEARNED`] at +//! most, the oldest going first, and each later pass's count replaces its reader's. +//! - **Weighed.** A reader whose identity has a count takes the snapshot where the snapshot draw's +//! `SNAPSHOT_PIXEL_COST` (`render/snapshot.rs`) at each pixel it covered, for each color, costs no +//! more than the split's copy ([`snapshot_covers`]), the two forms' fixed costs (about a mebibyte +//! of the copy each, measured) left out on both sides; a reader with none is weighed by the +//! area rule. Counted: `WorkCounts::reading_draws_by_coverage`, and the queries recorded, +//! `WorkCounts::coverage_queries`. +//! - **What a stale count costs.** A reader that covers another share than its count holds takes +//! the form the count chose until a pass after the change completes: one pass where each waits +//! for the one before, more where passes are committed ahead of the GPU. Both forms are exact: +//! the count picks between them only. +//! - **Not measured** where the device lacks `occlusionQueryPrecise` (an imprecise query states +//! only zero or not, which is no coverage) or does not reset queries on the host (an adopted +//! device, `gpu_time.rs`): its readers are weighed by the area rule alone. Nor while a +//! visibility query of the program's is active, which the rule's checks already refuse the +//! snapshot for (one occlusion query is active at a time); nor a reader whose pipeline was still +//! being made (a later step records its draw) or that a replay records, nor past [`MEASURED`] +//! readers of a pass. An instance recorded inline after a split keeps the query's begin and end +//! with its draws (`render/inline_splits.rs`), recorded once with them. A query whose commands +//! never ran (an instance a reroute replaced, `render/reroute.rs`) reads as unavailable and +//! teaches nothing. A draw that is no such reader records nothing and makes no pool. +//! - **A driver that counts per color** (`RuntimeDriverDefect::OcclusionCountPerColorOutput`, +//! ANV): its count is the pixels times the colors the fragment function writes, which weighs +//! the snapshot higher, toward the split the area rule would have weighed too. + +use crate::device::Device; +use crate::error::{vulkan, Error}; +use crate::exit_guard::{self, Call}; +use crate::texture::Texture; +use ash::vk; +use metal2vulkan::device::VkFeature; +use std::collections::VecDeque; + +/// The readers one pass measures, at most: its pool's queries. +const MEASURED: u32 = 64; + +/// The readers' counts a texture keeps, at most. +pub(crate) const LEARNED: usize = 32; + +/// A reader's identity across its passes: its pipeline state's (by address, while the program +/// holds it) and its place among that state's readers of the texture in its pass, from 0. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ReaderKey { + state: usize, + ordinal: u32, +} + +/// The counts a texture learned of its readers (`Texture::learned_coverage`), the latest of +/// each, [`LEARNED`] at most. +#[derive(Debug, Default)] +pub(crate) struct Learned(VecDeque<(ReaderKey, u64)>); + +impl Learned { + /// The pixels `key` covered in the latest pass that counted them. + pub(crate) fn get(&self, key: ReaderKey) -> Option { + self.0 + .iter() + .find(|(k, _)| *k == key) + .map(|&(_, covered)| covered) + } + + /// `key` covered `covered` pixels in a pass that completed: its count from now on, the + /// oldest count going where the texture keeps [`LEARNED`]. + pub(crate) fn learn(&mut self, key: ReaderKey, covered: u64) { + match self.0.iter_mut().find(|(k, _)| *k == key) { + Some(entry) => entry.1 = covered, + None => { + if self.0.len() == LEARNED { + self.0.pop_front(); + } + self.0.push_back((key, covered)); + } + } + } +} + +/// Whether a reader that covered `covered` pixels over all the colors it reads through +/// snapshots takes the snapshot: its snapshot draw at `SNAPSHOT_PIXEL_COST` (`render/snapshot.rs`) +/// bytes of the split's copy for each costs no more than the split's copy of `copied` bytes. +pub(crate) fn snapshot_covers(covered: u64, copied: u64) -> bool { + u128::from(covered) * u128::from(super::snapshot::SNAPSHOT_PIXEL_COST) <= u128::from(copied) +} + +/// A reader one pass measures: its query, its first color's texture and its identity. +struct Measured { + query: u32, + texture: Texture, + key: ReaderKey, +} + +/// One pass's readers: each one's place among its state's readers of its texture, and, where +/// the device measures them, the pool its first measured reader made and the readers measured. +#[derive(Default)] +pub(super) struct Readers { + ordinals: Vec<((usize, usize), u32)>, + /// The device measures readers: `None` until the pass's first reader asks. + measures: Option, + pool: Option, + used: u32, + measured: Vec, +} + +impl Readers { + /// The identity of the draw of the state at `state` reading `texture` (the one a view was + /// made from) as the next of that state's readers of it in the pass. + pub(super) fn next_key(&mut self, state: usize, texture: &Texture) -> ReaderKey { + let pair = (state, texture.root_address()); + let ordinal = match self.ordinals.iter_mut().find(|(p, _)| *p == pair) { + Some((_, next)) => { + *next += 1; + *next - 1 + } + None => { + self.ordinals.push((pair, 1)); + 0 + } + }; + ReaderKey { state, ordinal } + } + + /// Measure the reader `key` of `texture` where `device` measures readers and the pass has a + /// query left: the query its drawing commands record inside, from the pass's pool, made and + /// reset on the host at its first. `None` where it is not measured. + pub(super) fn measure( + &mut self, + device: &Device, + texture: &Texture, + key: ReaderKey, + ) -> Result, Error> { + let measures = *self.measures.get_or_insert_with(|| { + let shared = device.shared(); + shared.timing.resets_on_host() + && device + .properties() + .description + .has(VkFeature::OcclusionQueryPrecise) + }); + if !measures || self.used == MEASURED { + return Ok(None); + } + let pool = match &self.pool { + Some(pool) => pool.raw, + None => self.pool.insert(Pool::new(device)?).raw, + }; + let query = self.used; + self.used += 1; + self.measured.push(Measured { + query, + texture: texture.clone(), + key, + }); + Ok(Some((pool, query))) + } + + /// What the pass's command buffer holds until it completes, to read its readers' counts + /// then: `None` where the pass measured none. + pub(super) fn readback(self) -> Option { + let pool = self.pool?; + Some(Readback { + pool, + measured: self.measured, + }) + } +} + +/// A pass's occlusion query pool, released as it drops. +struct Pool { + device: Device, + raw: vk::QueryPool, +} + +impl Pool { + /// A pool of [`MEASURED`] occlusion queries, reset on the host, on a device that resets + /// queries there (`gpu_time.rs`). + fn new(device: &Device) -> Result { + let info = vk::QueryPoolCreateInfo::default() + .query_type(vk::QueryType::OCCLUSION) + .query_count(MEASURED); + let raw = device.shared().vk(); + // SAFETY: the device is live and `info` valid. + let pool = unsafe { raw.create_query_pool(&info, None) }.map_err(vulkan)?; + exit_guard::called(Call::CreateQueryPool); + // SAFETY: the device enables `hostQueryReset` (`Readers::measure`), and no command uses + // the new pool. + unsafe { raw.reset_query_pool(pool, 0, MEASURED) }; + exit_guard::called(Call::ResetQueryPool); + Ok(Pool { + device: device.clone(), + raw: pool, + }) + } +} + +impl Drop for Pool { + fn drop(&mut self) { + // Once the process is exiting, the pool is left to its end (`exit_guard`). + let Some(_busy) = exit_guard::enter() else { + return; + }; + // SAFETY: no pending command uses the pool: its pass's command buffer held it until it + // completed, or never recorded it. + unsafe { crate::release::object(self.device.shared().vk(), self.raw) }; + } +} + +/// A pass's measured readers, held by its command buffer until it completes ([`Readers::readback`]): +/// as it drops, each query that ran gives its reader's count to its texture. +pub(super) struct Readback { + pool: Pool, + measured: Vec, +} + +impl Drop for Readback { + fn drop(&mut self) { + if self.measured.is_empty() { + return; + } + let Some(_busy) = exit_guard::enter() else { + return; + }; + let mut results = vec![[0u64; 2]; MEASURED as usize]; + // SAFETY: the pool's queries, each recorded by the pass whose command buffer completed or + // never ran: 64-bit values, each with its availability, so one that never ran reads as + // unavailable ("If VK_QUERY_RESULT_WAIT_BIT and VK_QUERY_RESULT_PARTIAL_BIT are both not + // set then no result values are written to pData for queries that are in the unavailable + // state ... However, availability state is still written"). + let read = unsafe { + self.pool.device.shared().vk().get_query_pool_results( + self.pool.raw, + 0, + &mut results, + vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WITH_AVAILABILITY, + ) + }; + exit_guard::called(Call::GetQueryPoolResults); + if !matches!(read, Ok(()) | Err(vk::Result::NOT_READY)) { + return; + } + for measured in &self.measured { + let [covered, available] = results[measured.query as usize]; + if available != 0 { + measured.texture.learn_coverage(measured.key, covered); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn key(ordinal: u32) -> ReaderKey { + ReaderKey { state: 7, ordinal } + } + + #[test] + fn a_later_count_replaces_its_readers_and_the_oldest_goes_first() { + let mut learned = Learned::default(); + learned.learn(key(0), 10); + learned.learn(key(0), 20); + assert_eq!(learned.get(key(0)), Some(20)); + for ordinal in 1..LEARNED as u32 { + learned.learn(key(ordinal), 1); + } + assert_eq!(learned.get(key(0)), Some(20)); + learned.learn(key(LEARNED as u32), 1); + assert_eq!(learned.get(key(0)), None, "the oldest count went"); + assert_eq!(learned.get(key(1)), Some(1)); + } + + #[test] + fn a_reader_takes_the_snapshot_where_what_it_covered_costs_no_more_than_the_copy() { + let cost = super::super::snapshot::SNAPSHOT_PIXEL_COST; + assert!(snapshot_covers(100, 100 * cost)); + assert!(!snapshot_covers(101, 100 * cost)); + // The consumer's reader of 600x400 over 3662x2039 `BGRA8Unorm`: the snapshot. + assert!(snapshot_covers(600 * 400, 3662 * 2039 * 4)); + // One covering the whole target: the split. + assert!(!snapshot_covers(3662 * 2039, 3662 * 2039 * 4)); + } +} diff --git a/crates/metal2vulkan-runtime/src/render/inline_splits.rs b/crates/metal2vulkan-runtime/src/render/inline_splits.rs index d77ee999e..d2355bf2f 100644 --- a/crates/metal2vulkan-runtime/src/render/inline_splits.rs +++ b/crates/metal2vulkan-runtime/src/render/inline_splits.rs @@ -170,6 +170,10 @@ enum KeptCommand { /// A barrier before a draw whose fragment shader touches what a draw before it wrote before /// its fragments, of the view mask (`render_target::after_geometry_writes`). GeometryBarrier(u32, LegacyBarrier), + /// The begin of the precise occlusion query a reader's drawing commands record inside, and + /// its end, of the pool and query (`render/coverage.rs`). + BeginQuery(vk::QueryPool, u32), + EndQuery(vk::QueryPool, u32), } impl Kept { @@ -214,6 +218,19 @@ impl Kept { .commands .push(KeptCommand::GeometryBarrier(view_mask, barrier)); } + + /// Keep the begin of a reader's coverage query, before its drawing commands + /// (`render/coverage.rs`). + pub(super) fn begin_query(&mut self, pool: vk::QueryPool, query: u32) { + self.room + .commands + .push(KeptCommand::BeginQuery(pool, query)); + } + + /// Keep the end of a reader's coverage query, after its drawing commands. + pub(super) fn end_query(&mut self, pool: vk::QueryPool, query: u32) { + self.room.commands.push(KeptCommand::EndQuery(pool, query)); + } } /// A render pass and framebuffer inline instances after a split begin in: a render pass of @@ -627,6 +644,10 @@ fn record_kept( KeptCommand::GeometryBarrier(view_mask, barrier) => { render_target::after_geometry_writes(raw, held, *view_mask, *barrier) } + KeptCommand::BeginQuery(pool, query) => { + raw.cmd_begin_query(held, *pool, *query, vk::QueryControlFlags::PRECISE) + } + KeptCommand::EndQuery(pool, query) => raw.cmd_end_query(held, *pool, *query), } } } diff --git a/crates/metal2vulkan-runtime/src/render/snapshot.rs b/crates/metal2vulkan-runtime/src/render/snapshot.rs index 135dfd6fc..e3376736f 100644 --- a/crates/metal2vulkan-runtime/src/render/snapshot.rs +++ b/crates/metal2vulkan-runtime/src/render/snapshot.rs @@ -118,6 +118,14 @@ //! withholds `fragmentShaderPixelInterlock`) a reader over 1.5% of the target took 0.09 to 0.43 //! times the split's GPU time, and one over the whole target 1.03 to 1.20 times on the Iris Xe, //! 1.95 to 2.30 times on the Radeon 780M and 1.30 to 2.10 times on the RX 7900 XTX. +//! - **Learned coverage.** On a device that measures readers (`occlusionQueryPrecise`, queries +//! reset on the host), each reader the area rule would weigh records its drawing commands inside +//! a precise occlusion query, and once a pass completed, that reader's later passes are weighed +//! at the pixels it covered then instead (`render/coverage.rs`): the snapshot where its draw at +//! [`SNAPSHOT_PIXEL_COST`] for each of those pixels, for each color, costs no more than the +//! split's copy. A reader covering the whole target takes the split from its second pass on, one +//! covering 3% of it keeps the snapshot. Both forms give Metal's results; a reader whose +//! coverage changes takes the form its old count chose until a pass after the change completes. //! - **Pins.** A fetch of a color in the pixel interlock reads and writes its image as a storage //! image, so a later fetch of a color whose image lacks `STORAGE` renders it through a stand-in //! (`attachment_stand_in.rs`), which the pass's end puts in place for the whole pass, copied in @@ -188,7 +196,7 @@ pub(super) fn form(plan: &BindingPlan, slot: u32) -> Option { /// color's codes, 4 bytes a pixel, costs about what one of the fetched lanes' bits, 16, does. /// Measured at about 14 on the Iris Xe and 20 on the Radeon 780M /// (`runtime_lane::attachment_read_costs::snapshot_area_costs`). -const SNAPSHOT_PIXEL_COST: u64 = 20; +pub(super) const SNAPSHOT_PIXEL_COST: u64 = 20; /// What either form costs a draw whatever it covers, in bytes of the split's copy (the module /// docs' area rule): the snapshot's two barriers and its second draw, or the split's end of one @@ -320,8 +328,9 @@ pub(super) fn phase_hole(holes: &[PushHole]) -> Option<(vk::ShaderStageFlags, u3 impl RenderLowering { /// What a draw of `pipeline` (its state's base) through `reformats` asks to read through - /// snapshots, where it can ask (the module docs' checks that come before the plan); `None` - /// where it reads no attachment so or takes the split. + /// snapshots, where it can ask (the module docs' checks that come before the area rule and + /// the plan, [`snapshot_by_area`](Self::snapshot_by_area) weighing it next); `None` where it + /// reads no attachment so or a check takes the split. pub(super) fn snapshot_wanted( &self, pipeline: &DrawingState, @@ -413,14 +422,62 @@ impl RenderLowering { if shared { return self.snapshot_fallback("the draw reads two attachments of one image"); } - if !self.snapshot_cheaper(pipeline, &colors) { - return self.snapshot_fallback( - "area: the snapshot draw over the draw's scissors costs more than the split's copy", - ); - } Some(wanted) } + /// Whether the draw of `pipeline` that asks to read the pass's colors through snapshots as + /// `wanted` ([`snapshot_wanted`](Self::snapshot_wanted)) takes them: where it costs no more + /// than the split ([`snapshot_cheaper`](Self::snapshot_cheaper)), weighed at what the reader + /// covered in the latest pass that measured it, where one did, else by the area rule; and, + /// where the device measures readers, the query of the pass's its drawing commands record + /// inside, whose count its texture keeps as the pass completes (`render/coverage.rs`). `None` + /// where it takes the split. + pub(super) fn snapshot_by_area( + &mut self, + pipeline: &DrawingState, + wanted: Wanted, + ) -> Result<(Option, Option<(vk::QueryPool, u32)>), crate::Error> { + let colors: Vec = (0..self.layout.colors.len()) + .filter(|&i| wanted.feedback.has(i)) + .collect(); + let first = colors + .first() + .and_then(|&index| self.layout.colors.get(index)?.as_ref()) + .map(|color| color.target.texture.clone()); + // A reader over a buffer's bytes takes the snapshot at any area: nothing to learn. + let reader = match first { + Some(texture) if !self.over_bytes(&colors) => { + Some((self.readers.next_key(pipeline.address(), &texture), texture)) + } + _ => None, + }; + let learned = reader + .as_ref() + .and_then(|(key, texture)| texture.learned_coverage(*key)); + if learned.is_some() { + self.core + .device() + .shared() + .counts + .reading_draw_by_coverage(); + } + let within = self.snapshot_cheaper(pipeline, &colors, learned); + let query = match reader { + Some((key, texture)) => self.readers.measure(self.core.device(), &texture, key)?, + None => None, + }; + let wanted = match (within, learned) { + (true, _) => Some(wanted), + (false, Some(_)) => self.snapshot_fallback( + "coverage: the snapshot draw over the pixels the reader covered when last measured costs more than the split's copy", + ), + (false, None) => self.snapshot_fallback( + "area: the snapshot draw over the draw's scissors costs more than the split's copy", + ), + }; + Ok((wanted, query)) + } + /// Whether the draw of `pipeline` reads the pass's color `index`, whose own image a later /// fetch would not keep (`keeps_own_attachment`), through a snapshot of that image all the /// same, pinning it (the module docs): where nothing the pass's end decides from the whole @@ -461,12 +518,26 @@ impl RenderLowering { /// Whether a draw of `pipeline` that reads the pass's `colors` through snapshots costs no /// more than the split would: at any area over a buffer's bytes - /// ([`over_bytes`](Self::over_bytes)), else by the area rule ([`snapshot_within`]) over + /// ([`over_bytes`](Self::over_bytes)); else, where the reader covered `learned` pixels in the + /// latest pass that measured it, by what the snapshot draw costs over them + /// (`coverage::snapshot_covers`); else by the area rule ([`snapshot_within`]) over /// [`snapshot_weights`](Self::snapshot_weights); counted by its size where /// `METAL2VULKAN_LOG_PIPELINES` is set (`reader_sizes.rs`). - fn snapshot_cheaper(&self, pipeline: &DrawingState, colors: &[usize]) -> bool { + fn snapshot_cheaper( + &self, + pipeline: &DrawingState, + colors: &[usize], + learned: Option, + ) -> bool { let (covered, pixels, bytes, copied) = self.snapshot_weights(pipeline, colors); - let within = self.over_bytes(colors) || snapshot_within(covered, copied); + let within = self.over_bytes(colors) + || match learned { + Some(drawn) => super::coverage::snapshot_covers( + drawn.saturating_mul(colors.len() as u64), + copied, + ), + None => snapshot_within(covered, copied), + }; if crate::pipeline::creation_log_enabled() { let device = self.core.device(); let line = crate::device::lock(&device.shared().reader_sizes) diff --git a/crates/metal2vulkan-runtime/src/tests/learned_coverage.rs b/crates/metal2vulkan-runtime/src/tests/learned_coverage.rs new file mode 100644 index 000000000..87dd6e528 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/learned_coverage.rs @@ -0,0 +1,330 @@ +//! A reader of its pass's private color through no scissor, weighed by what it covered in the +//! pass before (`render/coverage.rs`), on a device that takes the snapshot path +//! (`render/snapshot.rs`) and measures readers (`occlusionQueryPrecise`, queries reset on the +//! host). Each pass, a command buffer of its own over a [`SIDE`]-square `BGRA8Unorm` target, fills +//! a rectangle with a red of its own, then after a barrier draws the rectangle with `tob_read`, +//! each fragment writing the texel it read: the pass's red at every pixel of the rectangle, as +//! Metal orders the barrier, whichever form the reader took. The rectangle is [`SPARSE`] for two +//! passes, the whole target for three, then [`SPARSE`] for two more. +//! +//! - The first pass has no count: the area rule takes the snapshot through the whole target's +//! scissor. Each later pass takes the form the pass before's count chose: the snapshot over +//! [`SPARSE`]'s pixels, the split over the whole target's. So the first pass after each change +//! takes the form the count before it chose, one pass, and the next the new count's. +//! - A device without the snapshot path splits every reader and records no query; one that takes +//! it but measures nothing weighs every reader by the area rule: the snapshot. +//! +//! An app's visibility query around a reader (`Counting`) keeps its count, the fill's samples and +//! the reader's: the reader takes the split, as the snapshot path refuses it while a visibility +//! query is active, and records no query of its own. +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are `tob_rect`, +//! `tob_solid` and `tob_read` of the owned fixture `validation/fixtures/public/engine/tob_renders.ll` +//! (`llvm-as`). + +use super::blit_holds::{device, Scratch, WAIT}; +use super::encoder_holds::{bytes_of, library}; +use crate::framebuffer_fetch::through_storage; +use crate::{ + BlitOption, CommandQueue, CpuCacheMode, Device, HazardTrackingMode, LoadAction, Origin, + PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, StorageMode, + StoreAction, Texture, TextureDescriptor, VisibilityResultMode, WorkCounts, +}; +use metal2vulkan::device::VkFeature; +use metal2vulkan::metal::{BarrierScope, PixelFormat, PrimitiveType, RenderStages, TextureUsage}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; +use std::time::{Duration, Instant}; + +/// The target's side, in pixels: through the whole target's scissor, a reader of a 4-byte color +/// with no count takes the snapshot by the area rule. +const SIDE: u64 = 1024; + +/// The target's format. +const FORMAT: PixelFormat = PixelFormat::BGRA8Unorm; + +/// The sparse reader's rectangle, `[x0, y0, x1, y1]`: 4096 pixels, whose snapshot draw costs +/// less than the split's copy of the target. +const SPARSE: [u64; 4] = [100, 200, 164, 264]; + +/// The whole target. +const WHOLE: [u64; 4] = [0, 0, SIDE, SIDE]; + +/// The red the first pass clears the target to. +const CLEARED: u8 = 20; + +/// The red pass `pass` fills its rectangle with. +fn red_of(pass: usize) -> u8 { + 40 + 25 * pass as u8 +} + +/// The state of `tob_rect` and `tob_renders.ll`'s `fragment`, into a color of [`FORMAT`]. +fn state(device: &Device, fragment: &str) -> RenderPipelineState { + let function = |name: &str| { + let function = library(device, "engine/tob_renders.ll") + .new_function_with_name(name) + .unwrap(); + StageSource::Function(function.function_descriptor()) + }; + let mut descriptor = RenderPipelineDescriptor::new(function("tob_rect")); + descriptor.fragment = Some(function(fragment)); + descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(FORMAT)); + device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() +} + +/// A private [`FORMAT`] render target that shaders read, its hazards tracked where `tracked`. +fn target(device: &Device, tracked: bool) -> Texture { + let mut d = TextureDescriptor::texture_2d(FORMAT, SIDE, SIDE, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = match tracked { + true => ResourceOptions::private(), + false => ResourceOptions::new( + StorageMode::Private, + CpuCacheMode::DefaultCache, + HazardTrackingMode::Untracked, + ), + }; + device.new_texture(&d).unwrap() +} + +/// The corners, in normalized device coordinates, of the target's pixels `[x0, x1) x [y0, y1)`. +fn corners([x0, y0, x1, y1]: [u64; 4]) -> Vec { + let x = |p: u64| p as f32 / SIDE as f32 * 2.0 - 1.0; + let y = |p: u64| 1.0 - p as f32 / SIDE as f32 * 2.0; + bytes_of(&[x(x0), y(y1), x(x1), y(y0)], f32::to_le_bytes) +} + +/// Pass `pass` over `target`, a command buffer of its own, committed and completed: a fill of +/// `rect` with the pass's red, a barrier, and the reader over `rect` through the whole target's +/// scissor, all inside a `Counting` visibility query at offset 0 of `visibility` where given. +/// The target's red at each pixel after it. +fn pass_over( + queue: &CommandQueue, + target: &Texture, + (fill, read): (&RenderPipelineState, &RenderPipelineState), + (pass, rect): (usize, [u64; 4]), + visibility: Option<&crate::Buffer>, +) -> Vec { + let device = queue.device(); + let row = SIDE * 4; + let back = device + .new_buffer(SIDE * row, ResourceOptions::shared()) + .unwrap(); + let mut descriptor = RenderPassDescriptor::new(); + let color = &mut descriptor.color_attachments[0]; + color.texture = Some(target.clone()); + color.load_action = match pass { + 0 => LoadAction::Clear, + _ => LoadAction::Load, + }; + color.clear_color = crate::ClearColor::new(f64::from(CLEARED) / 255.0, 0.0, 0.0, 1.0); + color.store_action = StoreAction::Store; + descriptor.visibility_result_buffer = visibility.cloned(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&descriptor).unwrap(); + if visibility.is_some() { + (encoder.set_visibility_result_mode(VisibilityResultMode::Counting, 0)).unwrap(); + } + encoder.set_render_pipeline_state(fill).unwrap(); + encoder.set_vertex_bytes(&corners(rect), 0).unwrap(); + let red = f32::from(red_of(pass)) / 255.0; + let rgba = bytes_of(&[red, 0.0, 0.0, 1.0], f32::to_le_bytes); + encoder.set_fragment_bytes(&rgba, 0).unwrap(); + (encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap(); + let fragment = RenderStages::FRAGMENT; + encoder.memory_barrier_with_scope(BarrierScope::RENDER_TARGETS, fragment, fragment); + encoder.set_render_pipeline_state(read).unwrap(); + encoder.set_fragment_texture(Some(target), 0).unwrap(); + (encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap(); + encoder.end_encoding().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + (blit.copy_from_texture_to_buffer( + target, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(SIDE, SIDE, 1), + &back, + 0, + row, + SIDE * row, + BlitOption::None, + )) + .unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + let texels = super::merge_scratch::read(&back, SIDE * row); + // `BGRA8Unorm`'s red is its third byte. + texels.chunks(4).map(|texel| texel[2]).collect() +} + +/// Wait until the device's pipeline pool makes nothing. +fn settled(device: &Device) { + let until = Instant::now() + WAIT; + while device.work_counts().pipeline_pool_busy != 0 { + assert!(Instant::now() < until, "the pipeline pool still busy"); + std::thread::sleep(Duration::from_millis(1)); + } +} + +/// The device's answers: whether it takes the snapshot path for a private target's reader +/// (`render/snapshot.rs`: the snapshot draws' features, and a fetch in the pixel interlock), and +/// whether it measures readers (`render/coverage.rs`: `occlusionQueryPrecise`, and queries reset +/// on the host). +fn answers(device: &Device) -> (bool, bool) { + let profile = device.compile_device().profile(); + let snapshots = device.shared().color_write_masks.is_some() && through_storage(profile); + let precise = device + .properties() + .description + .has(VkFeature::OcclusionQueryPrecise); + let host_reset = device.shared().timing.resets_on_host(); + eprintln!( + "LEARNED-COVERAGE {}: snapshots {snapshots}, occlusionQueryPrecise {precise}, host \ + reset {host_reset}", + device.name() + ); + (snapshots, snapshots && precise && host_reset) +} + +/// What a pass moved of the counts between `before` and `after`: its splits, readers through +/// snapshots, coverage queries, and readers weighed by a count. +fn moved(before: &WorkCounts, after: &WorkCounts) -> [u64; 4] { + [ + after.attachment_read_splits - before.attachment_read_splits, + after.reading_draws_snapshotted - before.reading_draws_snapshotted, + after.coverage_queries - before.coverage_queries, + after.reading_draws_by_coverage - before.reading_draws_by_coverage, + ] +} + +/// The device made, its states and its pipelines made by two passes over an untracked target. +fn prepared(cache: &Scratch) -> (Device, CommandQueue, [RenderPipelineState; 2]) { + let device = device(&cache.0); + let queue = device.new_command_queue().unwrap(); + let states = [state(&device, "tob_solid"), state(&device, "tob_read")]; + let warm = target(&device, false); + for pass in 0..2 { + pass_over( + &queue, + &warm, + (&states[0], &states[1]), + (pass, SPARSE), + None, + ); + } + settled(&device); + (device, queue, states) +} + +#[test] +fn a_readers_form_follows_what_it_covered_in_the_pass_before() { + let cache = Scratch::new("learned-coverage"); + let (device, queue, [fill, read]) = prepared(&cache); + let (snapshots, measures) = answers(&device); + let target = target(&device, true); + let rects = [SPARSE, SPARSE, WHOLE, WHOLE, WHOLE, SPARSE, SPARSE]; + let mut want_reds = vec![CLEARED; (SIDE * SIDE) as usize]; + let mut learned: Option<[u64; 4]> = None; + for (pass, &rect) in rects.iter().enumerate() { + let before = device.work_counts(); + let reds = pass_over(&queue, &target, (&fill, &read), (pass, rect), None); + let moved = moved(&before, &device.work_counts()); + eprintln!( + "LEARNED-COVERAGE pass {pass} over {rect:?}: (splits, snapshotted, queries, by \ + coverage) {moved:?}" + ); + let [x0, y0, x1, y1] = rect; + for y in y0..y1 { + for x in x0..x1 { + want_reds[(y * SIDE + x) as usize] = red_of(pass); + } + } + // Both forms read what the fill wrote: Metal's answer, byte for byte. + if let Some(i) = (0..reds.len()).find(|&i| reds[i] != want_reds[i]) { + let (x, y) = (i as u64 % SIDE, i as u64 / SIDE); + panic!( + "pass {pass}: pixel ({x}, {y}) holds red {}, not {}", + reds[i], want_reds[i] + ); + } + // The pass before's count chooses, the whole target's the split; with none, the area + // rule the snapshot. + let split = measures && learned == Some(WHOLE); + let want = match (snapshots, measures) { + (false, _) => [1, 0, 0, 0], + (true, false) => [0, 1, 0, 0], + (true, true) => [ + u64::from(split), + u64::from(!split), + 1, + u64::from(learned.is_some()), + ], + }; + assert_eq!( + moved, + want, + "pass {pass} over {rect:?} on {}: splits, snapshotted, queries, by coverage", + device.name() + ); + learned = Some(rect); + } +} + +#[test] +fn an_apps_visibility_query_keeps_its_count_with_a_reader_inside_it() { + let cache = Scratch::new("learned-coverage-visibility"); + let (device, queue, [fill, read]) = prepared(&cache); + let (snapshots, measures) = answers(&device); + let precise = device + .properties() + .description + .has(VkFeature::OcclusionQueryPrecise); + if !precise { + eprintln!( + "LEARNED-COVERAGE {}: no counting visibility without occlusionQueryPrecise", + device.name() + ); + return; + } + let target = target(&device, true); + let results = device.new_buffer(8, ResourceOptions::shared()).unwrap(); + let [x0, y0, x1, y1] = SPARSE; + let pixels = (x1 - x0) * (y1 - y0); + // Without the app's query, the reader records one of its own where the device measures. + let before = device.work_counts(); + pass_over(&queue, &target, (&fill, &read), (0, SPARSE), None); + let alone = moved(&before, &device.work_counts()); + assert_eq!(alone[2], u64::from(measures), "{alone:?}: queries alone"); + // Inside the app's query: the split, no query of its own, and the app's count is the fill's + // samples and the reader's. + let before = device.work_counts(); + let reds = pass_over(&queue, &target, (&fill, &read), (1, SPARSE), Some(&results)); + let inside = moved(&before, &device.work_counts()); + eprintln!( + "LEARNED-COVERAGE {} inside a visibility query: (splits, snapshotted, queries, by \ + coverage) {inside:?}", + device.name() + ); + assert_eq!( + reds[(y0 * SIDE + x0) as usize], + red_of(1), + "the reader read the fill" + ); + assert_eq!(inside[2], 0, "{inside:?}: no query inside the app's"); + assert_eq!( + inside[..2], + [1, 0], + "{inside:?}: the split (snapshots {snapshots})" + ); + let count = u64::from_le_bytes(super::merge_scratch::read(&results, 8).try_into().unwrap()); + assert_eq!( + count, + 2 * pixels, + "the app's count: the fill's samples and the reader's" + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 837f92cd0..ff18b144a 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -241,6 +241,8 @@ mod kept_heap_uses; mod kept_images; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod layer_claim; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod learned_coverage; mod left; mod linear_alignment; mod linear_attachment; diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 14f7152f2..85ce5d1ec 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -430,6 +430,10 @@ pub(super) struct TextureShared { /// texture's texels into before it reads them (`texture/attached_reads.rs`), one a form, each /// made at the first such draw: on the texture a view was made from, never a view's own. snapshot: Mutex>, + /// What the draws that read it where their pass renders it covered, by reader, as passes + /// that measured them completed (`render/coverage.rs`): on the texture a view was made from, + /// never a view's own. + coverage: Mutex, /// A memoryless texture's backings, one per queue and subresource, made at the first pass /// that needs one and kept with the texture (`attachment_stand_in::kept_backing`). kept_backings: Mutex>, @@ -4327,6 +4331,32 @@ pub(super) enum IdUse { } impl Texture { + /// The texture a view was made from, through every view between; else this one. + fn root(&self) -> &Texture { + let mut owner = self; + while let Some(parent) = &owner.0.parent { + owner = parent; + } + owner + } + + /// The identity a reader of the texture is known by across passes (`render/coverage.rs`): + /// the address of the texture a view was made from, while it lives. + pub(crate) fn root_address(&self) -> usize { + Arc::as_ptr(&self.root().0).addr() + } + + /// The pixels the reader `key` of the texture covered in the latest pass that measured it + /// (`render/coverage.rs`). + pub(crate) fn learned_coverage(&self, key: crate::render::coverage::ReaderKey) -> Option { + crate::device::lock(&self.root().0.coverage).get(key) + } + + /// The reader `key` of the texture covered `covered` pixels in a pass that completed. + pub(crate) fn learn_coverage(&self, key: crate::render::coverage::ReaderKey, covered: u64) { + crate::device::lock(&self.root().0.coverage).learn(key, covered); + } + /// A new texture object of `device` over `storage`, presenting `record`, a view of `parent` /// if any, with its resource ID as `id_use` says. A program's texture takes its ID's slot, /// and the device's texture table and heap sets hold it there (`heap_sets::place`). @@ -4381,6 +4411,7 @@ impl Texture { usage_shadow: OnceLock::new(), usage_shadow_making: Mutex::new(()), snapshot: Mutex::new(Vec::new()), + coverage: Mutex::default(), kept_backings: Mutex::new(Vec::new()), render_shadow: Mutex::new(None), heap, diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 5d6774a6e..225047778 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -474,6 +474,8 @@ pub(crate) struct Counters { attachment_read_clears: AtomicU64, reading_draws_snapshotted: AtomicU64, snapshot_inline_splits: AtomicU64, + reading_draws_by_coverage: AtomicU64, + coverage_queries: AtomicU64, reading_draws_pinned: AtomicU64, stand_ins_after_pins: AtomicU64, feedback_loop_alias_images: AtomicU64, @@ -3457,6 +3459,19 @@ impl Counters { self.snapshot_inline_splits.fetch_add(1, Ordering::Relaxed); } + /// A reader of its pass's color was weighed by what it covered when a pass last measured it + /// (`render/coverage.rs`). + pub(crate) fn reading_draw_by_coverage(&self) { + self.reading_draws_by_coverage + .fetch_add(1, Ordering::Relaxed); + } + + /// A reader of its pass's color recorded its drawing commands inside an occlusion query + /// that measures what it covers (`render/coverage.rs`). + pub(crate) fn coverage_query(&self) { + self.coverage_queries.fetch_add(1, Ordering::Relaxed); + } + /// A draw read through a snapshot a color whose image a later fetch would render through a /// stand-in, its instance pinned to the color's own image (`render/snapshot.rs`). pub(crate) fn reading_draw_pinned(&self) { @@ -6600,6 +6615,15 @@ pub struct WorkCounts { /// was recorded inline, its render pass instance begun without the feedback loop layout the /// snapshot needs (`render/snapshot.rs`, `render/inline_first.rs`). pub snapshot_inline_splits: u64, + /// Draws that read a color of their render pass after a memory barrier, which the area rule + /// weighs between the snapshot and the split, weighed by the pixels they covered in the + /// latest pass that measured them rather than by their scissors (`render/coverage.rs`): + /// among `reading_draws_snapshotted` or `attachment_read_splits`, as they took. + pub reading_draws_by_coverage: u64, + /// Occlusion queries such draws recorded their drawing commands inside, whose counts their + /// textures keep as the command buffers complete (`render/coverage.rs`): one a draw, on a + /// device with `occlusionQueryPrecise` that resets queries on the host. + pub coverage_queries: u64, /// Of `reading_draws_snapshotted`, the draws that read a color whose image lacks the /// `STORAGE` a later framebuffer fetch of it in the interlock would need, so that a fetch would /// render it through a stand-in for the whole pass: each pins its instance, and those before @@ -7521,6 +7545,8 @@ impl Device { attachment_read_clears: counters.attachment_read_clears.load(Ordering::Relaxed), reading_draws_snapshotted: counters.reading_draws_snapshotted.load(Ordering::Relaxed), snapshot_inline_splits: counters.snapshot_inline_splits.load(Ordering::Relaxed), + reading_draws_by_coverage: counters.reading_draws_by_coverage.load(Ordering::Relaxed), + coverage_queries: counters.coverage_queries.load(Ordering::Relaxed), reading_draws_pinned: counters.reading_draws_pinned.load(Ordering::Relaxed), stand_ins_after_pins: counters.stand_ins_after_pins.load(Ordering::Relaxed), feedback_loop_alias_images: counters.feedback_loop_alias_images.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/attachment_read_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/attachment_read_costs.rs index 8df77d066..1d217f337 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/attachment_read_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/attachment_read_costs.rs @@ -29,7 +29,9 @@ //! and a reader (`tob_read`) through the scissor whose rectangle, at the same corner, covers a //! share of it. The cells cross the scissor's sides ([`SCISSORS`]), the share the reader covers //! ([`COVERAGES`]) and the fill: the whole scissor, or at most [`GUEST_FILL`]. The cells run in -//! turn, round after round, so the GPU's clock weighs on each alike; printed per cell +//! turn, round after round, so the GPU's clock weighs on each alike, each cell's timed frame after +//! an untimed one of its own, so its readers are weighed by what they covered there where the +//! device learns it (`render/coverage.rs`), not by what the cell before covered; printed per cell //! (`SNAPSHOT-CROSSOVER`): the median GPU time per pass, the readers the device snapshotted and //! split, the texels copied in per pass, and the clock (`gt_cur_freq_mhz`) at the first and last //! round. @@ -480,6 +482,10 @@ fn snapshot_crossover() { for round in 0..ROUNDS { for (index, cell) in cells.iter().enumerate() { let target = if cell.host { &host } else { &private }; + // An untimed frame of the cell first, so its readers are weighed by what a pass of + // the cell covered, where the device learns it (`render/coverage.rs`), not by the + // cell before's. + cross_frame(&queue, target, &fill, &read, cell); clocks.entry(index).or_default().push(clock()); let before = device.work_counts(); let gpu = cross_frame(&queue, target, &fill, &read, cell); diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 217b24aaa..c8d6dc8cc 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2618,6 +2618,7 @@ field metal2vulkan-runtime::WorkCounts.copied_rebind_pages_moved pub copied_rebi field metal2vulkan-runtime::WorkCounts.copied_unwritable_pages pub copied_unwritable_pages: u64 field metal2vulkan-runtime::WorkCounts.copy_regions_split pub copy_regions_split: u64 field metal2vulkan-runtime::WorkCounts.copy_sites pub copy_sites: [CopySite; 32] +field metal2vulkan-runtime::WorkCounts.coverage_queries pub coverage_queries: u64 field metal2vulkan-runtime::WorkCounts.cpu_block_decodes pub cpu_block_decodes: u64 field metal2vulkan-runtime::WorkCounts.creation_dispatch_pipelines_drawn pub creation_dispatch_pipelines_drawn: u64 field metal2vulkan-runtime::WorkCounts.creation_dispatch_pipelines_made pub creation_dispatch_pipelines_made: u64 @@ -2938,6 +2939,7 @@ field metal2vulkan-runtime::WorkCounts.queue_switch_checks_recalled pub queue_sw field metal2vulkan-runtime::WorkCounts.queue_switch_checks_run pub queue_switch_checks_run: u64 field metal2vulkan-runtime::WorkCounts.queues_gone_long pub queues_gone_long: u64 field metal2vulkan-runtime::WorkCounts.queues_sharing_a_vk_queue pub queues_sharing_a_vk_queue: u64 +field metal2vulkan-runtime::WorkCounts.reading_draws_by_coverage pub reading_draws_by_coverage: u64 field metal2vulkan-runtime::WorkCounts.reading_draws_pinned pub reading_draws_pinned: u64 field metal2vulkan-runtime::WorkCounts.reading_draws_snapshotted pub reading_draws_snapshotted: u64 field metal2vulkan-runtime::WorkCounts.reencodes_refused pub reencodes_refused: u64 diff --git a/docs/API.md b/docs/API.md index 3f689faf2..6842eed83 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1537,7 +1537,7 @@ driver cache record or not, or another caller's) and the link; and, once per rea that reads its own pass's color attachment after a barrier took the split rather than a snapshot (id name `metal2vulkan-snapshot-fallback`, `Info` severity; `WorkCounts::reading_draws_snapshotted` counts those that took a snapshot), and now and then a count of the draws the snapshot's area rule -weighed, by their scissors' share of the target, texel bytes and side of the rule (id name +weighed, by their scissors' share of the target, texel bytes and the form each took (id name `metal2vulkan-snapshot-readers`, `Info` severity). With `METAL2VULKAN_LOG_MEMORY` set, a device logs one line per `VkDeviceMemory` it allocates, imports or frees (id name `metal2vulkan-memory`, `Info` severity): what it holds (a block of buffers or images, a host-memory import with its host