From f40cc8595bf058018b47e60690d44a302b72bebc Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 14 Nov 2026 17:40:26 -0800 Subject: [PATCH] RUNTIME 2325: A rate-mapped pass's host step decodes GPU-written records on the GPU (its GPU route) A render pass over a rasterization-rate map that executes an indirect command buffer the GPU may write goes to the host step. There the host read every record, decoded it and drew each command through the probe and the fan-out routes. On the consumer's RTX 3090 that step took 44.7 ms of a 65.8 ms frame, reading 781 records a frame. The only rule its executions broke was the rate map's. At a host step that fans the pass's triangles out, an execution whose records the GPU may write, and which takes its merged GPU form once the rate map's rule is passed over (the cause.rs decision), now takes its GPU route (render/executions/gpu_route.rs): - The step records the form's prework: the head, the preprocess and the two merge passes. It copies each command's first corner and the merged draw's two VkDrawIndirectCommands to the host, submits that with a fence and waits, as it does for its probe. - The host reads those words and no record. Each command that draws becomes one direct draw of its corners in the state's merged variant, with the merged header pushed (RenderLowering::merged_header). - The probe and the routes take those draws as they take commands the host read: probed, then fanned out, boxed, in parts or region by region. A long corner draw is cut into piece-sized ranges, as an indexed command is. - The host reads the records as before where the total reaches MERGED_CHUNK corners, where the prefix does not rise to the total, or where the prework did not complete. RenderExecution::record_gpu's prework moves into RenderExecution::prework, which both paths share. The replay loop takes a GPU route's corners beside the records the host read (Replayed, StepCommand). The new counters are WorkCounts::rate_map_gpu_routes and rate_map_gpu_route_wait_nanos. Tests: - New, tests::rate_mapped_gpu_route. Eight commands of a buffer that inherits the encoder's pipeline state: grids, one in two instances, one without indices, and the large, medium and wide triangles the probe flags. Each command is nearer than the one before, under LessEqual depth and half-alpha blending. It asserts no record read, one route, one probe and three flagged draws, and that the colour and Depth32Float bytes equal the encoder's own draws. - Changed, tests::host_step_rules. Its empty command, through the route, counts as nothing_to_probe. Also in this landing (the lane's later commits): - d2728b735e: the step's commands are one vector of reads or of corners (no per-command enum of 3.3 KB); clippy. - 51afad9359: HostReplayedIndirectCommands' cost names the GPU route's second round trip (the notice's text changes). RUNTIME 2325: an unchanged artifact's rate-mapped host step now decodes GPU-written records on the GPU, and the notice's text changes. Negative controls (m3-max-30703): the plan.rs lifts reverted fail a_merged_draw_s_variant_fans_out (NotImplemented(RasterizationRateMap)); the route turned off fails rate_mapped_gpu_route's counts ([8, 0, 1, 3] against [0, 1, 1, 3]). --- .../metal2vulkan-runtime/src/degradation.rs | 7 +- .../src/rate_mapped_pass.rs | 4 +- crates/metal2vulkan-runtime/src/render.rs | 9 +- .../src/render/executions.rs | 291 ++++++++--- .../src/render/executions/gpu.rs | 225 ++++++--- .../src/render/executions/gpu_route.rs | 242 ++++++++++ .../src/render/fan_out.rs | 14 +- .../src/tests/host_step_rules.rs | 14 +- crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/rate_mapped_gpu_route.rs | 451 ++++++++++++++++++ .../metal2vulkan-runtime/src/work_counts.rs | 35 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 2 + docs/API.md | 6 +- 14 files changed, 1155 insertions(+), 149 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/render/executions/gpu_route.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/rate_mapped_gpu_route.rs diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index acb7a1625..39ba9662d 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -728,7 +728,12 @@ degradations! { resource the execution may reach (one made resident, the records), and the first \ command of a threadgroup size or threadgroup lengths its pipeline state has not \ dispatched makes that VkPipeline then, as does a render command's draw of a state \ - the CPU set on none of the commands. The commands run in the large-buffer form \ + the CPU set on none of the commands. In a rate-mapped pass whose host step fans \ + its triangles out, a render execution kept from the GPU alone by the rate map alone \ + has its records decoded on the GPU at the step, which reads back each command's \ + corners and none of its records, and its commands run in their merged variant \ + (WorkCounts::rate_map_gpu_routes): a second round trip, for the decode, comes \ + before the probe's. Other commands run in the large-buffer form \ (their range-limited buffer slots at device addresses, with in-shader bounds \ checks), whose variants the commit compiles for every pipeline state a record may \ name (for a render execution, every state the CPU set on its commands; or, for an \ diff --git a/crates/metal2vulkan-runtime/src/rate_mapped_pass.rs b/crates/metal2vulkan-runtime/src/rate_mapped_pass.rs index eb9e25a60..fed041990 100644 --- a/crates/metal2vulkan-runtime/src/rate_mapped_pass.rs +++ b/crates/metal2vulkan-runtime/src/rate_mapped_pass.rs @@ -176,7 +176,9 @@ //! several would put an instance's later primitives before the next instance's earlier ones), //! whose pipeline reads no `[[primitive_id]]` (each range counts its primitives from 0) and //! writes no memory. Each range's vertices, instance and base vertex are the draw's -//! (`WorkCounts::rate_map_index_ranges`). Any other draw rides whole in the piece it begins in, +//! (`WorkCounts::rate_map_index_ranges`). A GPU route's draw of a command's corners +//! (`render/executions/gpu_route.rs`), such a list in one instance whatever its command's +//! instances, is cut so too, as ranges of its corners. Any other draw rides whole in the piece it begins in, //! however much work it holds: a strip, an instanced draw, a draw without indices, a mesh or //! patch draw, one of such a pipeline; and the encoder's own draws are not cut at all //! (`docs/FAST-PATHS.md`, known gaps). So a piece of draws cut so holds less than twice diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 30802547b..4e71ba474 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -1786,6 +1786,10 @@ pub(crate) struct RenderLowering { /// Where it records an execution's GPU form, the replay's draws, which its draw records in /// place of its own (`render/executions/gpu.rs`). replayed: Option, + /// Where it records an execution's GPU route at a host step, the device address of its + /// merged replay's header, which each draw's `PushHole::MergedDrawAddress` takes: its draws + /// are direct draws of the commands' corners (`render/executions/gpu_route.rs`). + merged_header: Option, /// Where the encoder records an execution's commands, the tracked uses of the pass's draws /// before the execution, in the stages a draw runs in inside its pass (`PASS_DRAW_STAGES`): /// which an emulated mesh command's dispatches, recorded before the pass, must not touch but @@ -2580,6 +2584,7 @@ impl RenderLowering { rerouting: false, forms: BufferForms::Bound, replayed: None, + merged_header: None, drawn_before: Vec::new(), run_barrier: false, piece_split: false, @@ -9811,7 +9816,8 @@ impl RenderLowering { .ok_or_else(|| internal("a heap's draw without its argument samplers"))?; tables = tables.with_heap(states, heap); } - if let Some(header) = self.replayed.as_ref().and_then(|r| r.merged_header()) { + let replayed = self.replayed.as_ref().and_then(|r| r.merged_header()); + if let Some(header) = replayed.or(self.merged_header) { tables = tables.with_merged_header(header); } // A list in the private list form is read at its address, which the device gives the @@ -11738,6 +11744,7 @@ impl RenderLowering { && !culled && !self.rerouting && self.replayed.is_none() + && self.merged_header.is_none() && self.grouped.is_none() && self.rate_map.is_none() && matches!(draw_pipeline, DrawPipeline::Made(_)) diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index 2b89d36dd..872af1be7 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -28,7 +28,10 @@ //! execution of the pass runs on the GPU alone (`executions/gpu.rs`, which states which do and //! when the decision is taken again), and otherwise the scheduler's host step records it once //! the work before it completed, which the device announces once -//! (`Degradation::HostReplayedIndirectCommands`). The step draws in the large-buffer form, whose +//! (`Degradation::HostReplayedIndirectCommands`). At a host step that fans a rate-mapped pass's +//! triangles out, an execution kept from the GPU alone by the rate map alone has its records +//! decoded on the GPU there, and the host reads its commands' corners and none of its records +//! (`executions/gpu_route.rs`). The step draws in the large-buffer form, whose //! variant no command's buffer lengths change (`BufferForms::Large`), and the commit settles what //! it will draw (the step compiled each draw's variant and `VkPipeline` as it met them, after the //! commit returned): for each state the records name as the CPU wrote them (the inherited one, @@ -363,6 +366,7 @@ use std::time::Instant; mod ahead; mod cause; mod gpu; +mod gpu_route; mod kept; use kept::Keeps; @@ -1046,6 +1050,54 @@ struct Snapshot { /// A command to run: its record, and the render pipeline state it names (`None`: none). pub(super) type Command = (CommandRecord, Option); +/// The commands of an execution a host step's probe and routes record (`render/fan_out.rs`): +/// those the host read, `None` where a record runs nothing for a fault; or those of its GPU route +/// that draw, each its corners in its merged draw, and the type they draw +/// (`executions/gpu_route.rs`). +pub(super) enum StepDraws { + Read(Vec>), + Corners(Vec>, PrimitiveType), +} + +impl StepDraws { + /// The commands. + pub(super) fn len(&self) -> usize { + match self { + StepDraws::Read(commands) => commands.len(), + StepDraws::Corners(corners, _) => corners.len(), + } + } + + /// Of the commands `range`, those that run, as the replay loop records them. + fn replayed(&self, range: Range) -> Vec> { + match self { + StepDraws::Read(commands) => (commands[range].iter().flatten()) + .map(Replayed::Record) + .collect(), + StepDraws::Corners(corners, primitive_type) => (corners[range].iter()) + .map(|corners| { + let count = corners.end - corners.start; + Replayed::Corners(corners.start, count, *primitive_type) + }) + .collect(), + } + } +} + +/// A command the replay loop records ([`RenderExecution::replay`]): a record and the state it +/// names, or a GPU route's command, its first corner, its corners and the type they draw. +#[derive(Clone, Copy)] +pub(super) enum Replayed<'c> { + Record(&'c Command), + Corners(u32, u32, PrimitiveType), +} + +impl<'c> From<&'c Command> for Replayed<'c> { + fn from(command: &'c Command) -> Replayed<'c> { + Replayed::Record(command) + } +} + /// An execution's probe at a host step that fans the pass's triangles out, of all its parts /// ([`DeferredPass::probe_parts`]): the index of each command's draw among the probe's draws, by /// its place among the commands that run, where it was probed; `None` where its commands are drawn @@ -1068,9 +1120,20 @@ type SubmittedPart = ( ); /// The host step's commands of an execution, read once for its probe and its recording -/// ([`RenderExecution::step_commands`]): the commands, `None` where a record runs nothing for a -/// fault, the command they start at, and the faults the range and the records hold. -type StepCommands = (Vec>, u32, ReplayFaults); +/// ([`RenderExecution::step_commands`]), or its GPU route's (`executions/gpu_route.rs`): the +/// commands, `None` where a record runs nothing for a fault, the command they start at, the +/// faults the range and the records hold, and a GPU route's merged header's device address. +type StepCommands = (StepDraws, u32, ReplayFaults, Option); + +/// The buffer forms of a host step's draws of an execution's commands: the large-buffer form, +/// whose variants `commit` settled (`RenderExecution::settle`); the merged one for its GPU +/// route's, whose merged replay's header lies at `header` (`executions/gpu_route.rs`). +fn step_forms(header: Option) -> BufferForms { + match header { + Some(_) => BufferForms::Merged, + None => BufferForms::Large, + } +} /// What [`RenderExecution::probe`] recorded of a part of an execution's commands. struct ProbedPart { @@ -1195,6 +1258,24 @@ fn index_ranges_of(pipeline: &RenderPipelineState, draw: &IndexedDraw) -> Option list_vertices(pipeline, draw.primitive_type, draw.instance_count) } +/// The vertices of each primitive of `call` of `pipeline` as `assembly`, a GPU route's draw of a +/// command's corners (`executions/gpu_route.rs`), where they may be drawn as consecutive ranges as +/// a command's indices are ([`list_vertices`]'s): its corners are its command's whole primitives, +/// each instance's in turn, in one instance of the draw. +fn corner_ranges_of( + pipeline: &RenderPipelineState, + assembly: Assembly, + call: &DrawCall, +) -> Option { + match (assembly, call) { + (Assembly::Primitives(primitive_type), DrawCall::Primitives { instance_count, .. }) => { + let primitive_type = DrawPrimitiveType::Public(primitive_type); + list_vertices(pipeline, primitive_type, *instance_count) + } + _ => None, + } +} + /// The triangles of `draw` of `pipeline`, and whether its parts begin at even ones, where a draw /// the probe flagged is drawn in parts (`render/fan_out.rs`, **Parts**): a list of triangles whose /// vertices or indices may be drawn as consecutive ranges ([`list_vertices`]), its parts of a @@ -2459,41 +2540,41 @@ impl RenderExecution { /// step, each seen by the check before any is recorded: the commands, `None` where a record /// runs nothing for a fault, the command they start at, and the faults the range and the /// records hold. - fn step_commands( - &self, - device: &Device, - ) -> Result<(Vec>, u32, ReplayFaults), Error> { + fn step_commands(&self, device: &Device) -> Result { let (range, faults) = self.range.commands(self.icb.size()); let check = self.check.as_ref().filter(|_| self.check_sees_now()); let start = range.start; let (commands, written) = self.written_commands(device, range, check)?; - Ok((commands, start, ReplayFaults(faults.0 | written.0))) + let commands = StepDraws::Read(commands); + Ok((commands, start, ReplayFaults(faults.0 | written.0), None)) } /// Record the probe of `commands`, a part of the host step's - /// ([`step_commands`](Self::step_commands)), through an encoder of `core` into a secondary - /// begun against the execution's instance, over the pass's `storage`, with `residency`, the - /// command buffer's, its draws taking indices of `flags` from `from` (`render/fan_out.rs`): - /// the core back, and what it recorded ([`ProbedPart`]): where its commands recorded in more - /// than one run, or not in the instance's shape, every command of the execution is drawn - /// region by region. + /// ([`step_commands`](Self::step_commands)), or of its GPU route's, whose merged replay's + /// header lies at `header` (`executions/gpu_route.rs`), through an encoder of `core` into a + /// secondary begun against the execution's instance, over the pass's `storage`, with + /// `residency`, the command buffer's, its draws taking indices of `flags` from `from` + /// (`render/fan_out.rs`): the core back, and what it recorded ([`ProbedPart`]): where its + /// commands recorded in more than one run, or not in the instance's shape, every command of + /// the execution is drawn region by region. fn probe( &self, core: EncoderCore, (command_buffer, residency): (&CommandBuffer, &Residency), - commands: &[Option], + (commands, header): (&[Replayed<'_>], Option), (flags, from, storage): (vk::DescriptorBufferInfo, u32, PassStorage), ) -> Result<(EncoderCore, ProbedPart), Error> { let snapshot = &self.snapshot; let layout = snapshot.layout.clone(); - let large = BufferForms::Large; let lent = (command_buffer, None); - let mut encoder = self.begin_replay(core, lent, (storage, layout, residency), large)?; + let forms = step_forms(header); + let mut encoder = self.begin_replay(core, lent, (storage, layout, residency), forms)?; + encoder.merged_header = header; encoder.fan_run = Some(FanOutRun::Probe(Probe::new(flags, from))); let mut found = Found::default(); let mut live = LiveBind::default(); let replaying = (&mut encoder, &mut live); - self.replay(replaying, commands.iter().flatten(), residency, &mut found)?; + self.replay(replaying, commands.iter().copied(), residency, &mut found)?; let raw = command_buffer.device().shared().vk(); encoder.visibility.end(raw, encoder.current.draws); encoder.visibility.close_spares(raw, encoder.current.draws); @@ -2540,9 +2621,9 @@ impl RenderExecution { } /// [`record`](Self::record) at a host step that fans the pass's triangles out, of the commands - /// `routes` holds, read once for the probe and for this recording (`render/fan_out.rs`): each - /// command's draw the probe probed and flagged none of the triangles of, fanned out, and the - /// others region by region, in order. + /// `routes` holds, read once for the probe and for this recording, or its GPU route's + /// (`render/fan_out.rs`, `executions/gpu_route.rs`): each command's draw the probe probed and + /// flagged none of the triangles of, fanned out, and the others region by region, in order. fn record_routes( &self, core: EncoderCore, @@ -2553,18 +2634,32 @@ impl RenderExecution { ) -> Result { let device = command_buffer.device().clone(); found.faults = ReplayFaults(found.faults.0 | routes.faults.0); - if command_buffer.reports_executed() { - let executed = routes.commands.iter().map(Option::as_ref); - let read = (RecordsRead::HostStep, residency); - self.report(command_buffer, read, routes.start, executed); + match (routes.header, &self.pipeline) { + // The GPU reads the records: the handlers learn the state their commands run, as of + // the GPU form's (`gpu.rs`). + (Some(_), Some(pipeline)) => { + command_buffer.report_executed(&self.icb, RecordsRead::Gpu, residency, || { + (Vec::new(), pipeline.can_encode_indirect_commands()) + }) + } + (Some(_), None) => return Err(internal("a GPU route without its pipeline state")), + (None, _) if command_buffer.reports_executed() => { + if let StepDraws::Read(commands) = &routes.commands { + let executed = commands.iter().map(Option::as_ref); + let read = (RecordsRead::HostStep, residency); + self.report(command_buffer, read, routes.start, executed); + } + } + (None, _) => {} } let layout = rendered.backing(&self.snapshot.layout)?; let lent = (command_buffer, self.lent.clone()); - let large = BufferForms::Large; - let mut encoder = self.begin_replay(core, lent, (storage, layout, residency), large)?; + let forms = step_forms(routes.header); + let mut encoder = self.begin_replay(core, lent, (storage, layout, residency), forms)?; + encoder.merged_header = routes.header; encoder.fan_run = Some(FanOutRun::Route(Arc::clone(&routes))); let mut live = LiveBind::default(); - let commands = routes.commands.iter().flatten(); + let commands = routes.commands.replayed(0..routes.commands.len()); self.replay((&mut encoder, &mut live), commands, residency, found)?; self.finish(encoder, found, rendered, &device) } @@ -2600,11 +2695,13 @@ impl RenderExecution { /// Replay `commands` through `encoder` (`record`'s), resolving against `residency`, the /// command buffer's, what their draws found noted into `found`. A mesh or patch draw is no - /// plain draw (`RenderLowering::replay_plain`). - fn replay<'c>( + /// plain draw (`RenderLowering::replay_plain`). A GPU route's command draws its corners + /// directly, with the encoder's tables at the call as the GPU form's draw has them + /// (`executions/gpu_route.rs`). + fn replay<'c, C: Into>>( &self, (encoder, live): (&mut RenderLowering, &mut LiveBind), - commands: impl IntoIterator, + commands: impl IntoIterator, residency: &Residency, found: &mut Found, ) -> Result<(), Error> { @@ -2629,7 +2726,12 @@ impl RenderExecution { // state noted once (`encoder_trail.rs`, **Host steps**). let mut trail = (encoder.core.device().shared().encoder_trail) .then(|| (crate::encoder_trail::Notes::default(), None)); - for (place, (record, own)) in commands.into_iter().enumerate() { + for (place, command) in commands.into_iter().enumerate() { + let command: Replayed<'c> = command.into(); + let (record, own) = match command { + Replayed::Record((record, own)) => (Some(record), own.as_ref()), + Replayed::Corners(..) => (None, None), + }; if let (Some((notes, last)), Some(own)) = (&mut trail, own) { if *last != Some(own) { notes.render(own); @@ -2645,7 +2747,8 @@ impl RenderExecution { // those the commit made ahead or the recording makes (`record_forms`), for a barrier // the CPU set later. A barrier neither may have set is a record the runtime does not // write, a fault, as before. - if record.barrier { + let barrier = record.is_some_and(|record| record.barrier); + if barrier { if !self.icb.may_hold_barriers() { found.faults = ReplayFaults(found.faults.0 | ReplayFaults::RECORD.0); continue; @@ -2660,12 +2763,24 @@ impl RenderExecution { } } } - encoder.command_barrier = record.barrier; + encoder.command_barrier = barrier; // What the command's draw records where the host step fans the pass's triangles out. encoder.fan_out = encoder.fan_run.as_ref().and_then(|run| run.begin(place)); encoder.fanned = (false, false); encoder.boxed = false; - let asked = Asked::of(&record.action, &self.icb); + let asked = match (command, record) { + (Replayed::Corners(first, count, primitive_type), _) => { + let draw = DrawCall::Primitives { + vertex_start: first, + vertex_count: count, + instance_count: 1, + base_instance: 0, + }; + Asked::Draw(Draw::Primitives(Assembly::Primitives(primitive_type), draw)) + } + (_, Some(record)) => Asked::of(&record.action, &self.icb), + (_, None) => continue, + }; let draw = match asked { Asked::Draw(draw) => draw, Asked::Nothing => continue, @@ -2674,7 +2789,7 @@ impl RenderExecution { continue; } }; - let Some(pipeline) = self.pipeline.as_ref().or(own.as_ref()).cloned() else { + let Some(pipeline) = self.pipeline.as_ref().or(own).cloned() else { continue; }; let draw = match draw.resolve(residency, pipeline_point_index_size(&pipeline)) { @@ -2689,7 +2804,14 @@ impl RenderExecution { } }; if let (Some((notes, _)), false) = (&mut trail, probing) { - if let Some((indexed, primitive, count, instances)) = trail_draw(&record.action) { + let drew = match (command, record) { + (Replayed::Corners(_, count, primitive_type), _) => { + Some((false, primitive_type.as_raw(), count, 1)) + } + (_, Some(record)) => trail_draw(&record.action), + (_, None) => None, + }; + if let Some((indexed, primitive, count, instances)) = drew { notes.drew(indexed, primitive, count, instances); } } @@ -2715,13 +2837,16 @@ impl RenderExecution { (encoder.shape_inputs()).check_pipeline(CALL, &pipeline, &encoder.layout)?; // A mesh draw's object function takes the command's threadgroup memory lengths, 0 // where it set none, never the encoder's (the M3 Max); a patch draw's take none. - encoder.object_threadgroup_lengths = match &draw { - Draw::Mesh(..) => object_threadgroup_lengths(record), - Draw::Primitives(..) | Draw::Indexed(..) | Draw::Patches { .. } => BTreeMap::new(), + encoder.object_threadgroup_lengths = match (&draw, record) { + (Draw::Mesh(..), Some(record)) => object_threadgroup_lengths(record), + (Draw::Mesh(..), None) + | (Draw::Primitives(..) | Draw::Indexed(..) | Draw::Patches { .. }, _) => { + BTreeMap::new() + } }; let control_points = pipeline_control_points(&pipeline); encoder.pipeline = Some(pipeline); - if !inherited { + if let (false, Some(record)) = (inherited, record) { let descriptor = self.icb.descriptor(); let misses = &mut found.misses; let mut table = @@ -2808,13 +2933,62 @@ impl RenderExecution { }) .collect(), }; - for (at, (fan_out, draw, triangles, bounds)) in draws.into_iter().enumerate() { + for (at, (fan_out, mut draw, triangles, bounds)) in + draws.into_iter().enumerate() + { if at > 0 { regions = note(found.piece_after(encoder)); found.piece_before(encoder); } encoder.fan_out = fan_out; encoder.run_bounds = bounds; + // A GPU route's command's corners, a list of one instance, drawn as + // consecutive ranges where they would hold more than a piece's work, as a + // command's indices are (below); a fanned-out draw, and a probe, whole. + let corners = matches!(command, Replayed::Corners(..)); + let cut = corners + && encoder.rate_map.is_some() + && !probing + && encoder.fan_out.is_none(); + let per_primitive = cut + .then(|| corner_ranges_of(encoder.pipeline.as_ref()?, assembly, &draw)) + .flatten(); + if let Some(per_primitive) = per_primitive { + let mut ranges = 0u64; + while let DrawCall::Primitives { + vertex_start, + vertex_count, + instance_count, + base_instance, + } = draw + { + let most = rate_mapped_pass::index_range(regions, per_primitive); + if vertex_count <= most { + break; + } + let range = DrawCall::Primitives { + vertex_start, + vertex_count: most, + instance_count, + base_instance, + }; + let none = DrawBuffers::default(); + encoder.draw(live, CALL, assembly, range, none, false)?; + regions = note(found.piece_after(encoder)); + found.piece_before(encoder); + draw = DrawCall::Primitives { + vertex_start: vertex_start + most, + vertex_count: vertex_count - most, + instance_count, + base_instance, + }; + ranges += 1; + } + if ranges > 0 { + let counts = &encoder.core.device().shared().counts; + counts.rate_map_index_ranges(ranges); + } + } encoder.draw(live, CALL, assembly, draw, DrawBuffers::default(), false)?; encoder.run_bounds = None; drawn.push((triangles, encoder.fanned.0, encoder.boxed)); @@ -3186,6 +3360,7 @@ impl RenderExecution { rerouting: false, forms, replayed: None, + merged_header: None, drawn_before: snapshot.drawn.clone(), run_barrier: false, piece_split: false, @@ -4468,12 +4643,16 @@ impl DeferredPass { } } } + // Each execution over the map: its GPU route's commands, where it takes one, which ran + // before the probe (`executions/gpu_route.rs`); else its commands read once. + let (gpu_routes, prework) = self.gpu_routes(command_buffer, residency)?; let mut reads = Vec::with_capacity(self.executions.len()); - for execution in &self.executions { + for (execution, gpu_route) in self.executions.iter().zip(gpu_routes) { let fans = execution.snapshot.rate_map.is_some() && execution.shadows.is_empty(); - reads.push(match fans { - true => Some(execution.step_commands(device)?), - false => None, + reads.push(match (fans, gpu_route) { + (true, Some(gpu_route)) => Some(gpu_route.step_commands()), + (true, None) => Some(execution.step_commands(device)?), + (false, _) => None, }); } // `PROBE_DRAW_WORDS` words a probed draw, at most one a command. @@ -4483,7 +4662,8 @@ impl DeferredPass { let draw_words = u64::from(PROBE_DRAW_WORDS); let mut probes: Vec = Vec::with_capacity(reads.len()); let mut found_draws: Arc<[Probed]> = Arc::from([]); - let mut probed = None; + // The GPU routes' recording, which ran: what it used and took, held with the pass's. + let mut probed = prework; if commands > 0 { let len = 4 * draw_words * commands as u64; let flags = command_buffer.state().uploads.upload(device, &[], len)?; @@ -4538,7 +4718,7 @@ impl DeferredPass { unprobed(Unprobed::ProbingNone); } // The parts' recordings, which ran: what they used and took, held with the pass's. - probed = parts.recorded.into_iter().reduce(|mut joined, part| { + probed = (probed.into_iter().chain(parts.recorded)).reduce(|mut joined, part| { joined.join(part); joined }); @@ -4547,12 +4727,13 @@ impl DeferredPass { } let routes = (reads.into_iter().enumerate()) .map(|(at, read)| { - let (commands, start, faults) = read?; + let (commands, start, faults, header) = read?; let slots = probes.get(at).cloned().flatten().unwrap_or_default(); Some(Arc::new(FanOutRoutes { commands, start, faults, + header, slots, probed: Arc::clone(&found_draws), })) @@ -4582,7 +4763,7 @@ impl DeferredPass { let mut draws: Vec<(usize, vk::CommandBuffer)> = Vec::new(); let mut held = 0; for ((execution, read), home) in self.executions.iter().zip(reads).zip(homes) { - let (Some((commands, ..)), Some(home)) = (read, home) else { + let (Some((commands, _, _, header)), Some(home)) = (read, home) else { probes.push(None); continue; }; @@ -4592,10 +4773,10 @@ impl DeferredPass { let mut at = 0; while at < commands.len() { let take = (part - held).min(commands.len() - at); - let these = &commands[at..at + take]; + let these = commands.replayed(at..at + take); let probing = (flags, next, self.storage.clone()); - let (back, probed) = - execution.probe(core, (command_buffer, residency), these, probing)?; + let at_step = (command_buffer, residency); + let (back, probed) = execution.probe(core, at_step, (&these, *header), probing)?; core = back; if probed.apart { apart = true; @@ -4605,7 +4786,7 @@ impl DeferredPass { // Each command's draw by its place among the execution's commands that run. slots.resize(placed, None); slots.extend(probed.slots); - placed += these.iter().flatten().count(); + placed += these.len(); draws.extend(probed.draws.map(|draws| (*home, draws))); at += take; held += take; diff --git a/crates/metal2vulkan-runtime/src/render/executions/gpu.rs b/crates/metal2vulkan-runtime/src/render/executions/gpu.rs index 0f4c41e96..6c315a03d 100644 --- a/crates/metal2vulkan-runtime/src/render/executions/gpu.rs +++ b/crates/metal2vulkan-runtime/src/render/executions/gpu.rs @@ -115,8 +115,13 @@ //! submitted signal reaches it. A CPU write after that races the GPU, as on Metal. //! - **Faults.** A record the host's decode refuses draws nothing, and the execution report //! states why (`bind::ReplayFaults`), as the host step's; the others draw. +//! - **At a host step of a rate-mapped pass** that fans its triangles out, an execution that takes +//! this form, merged, but for the pass's rate map has its records decoded on the GPU all the +//! same: the step runs the preprocess and the merge passes, reads back each command's corners, +//! and draws them (`gpu_route.rs`). use std::ops::Range; +use std::sync::Arc; use super::super::bound::{Bound, Recorded}; use super::super::line_width::LineRoute; @@ -136,6 +141,7 @@ use crate::executed_commands::RecordsRead; use crate::indirect_command_buffer::IndirectCommandBuffer; use crate::indirect_execute::{ExecutionRange, RANGE_BYTES}; use crate::live_bind::LiveBind; +use crate::live_buffers::LiveTable; use crate::owned_kernel::OwnedModule; use crate::pipeline::{BufferForms, GraphicsState, RenderStateKind, Settled}; use crate::residency::Residency; @@ -167,6 +173,43 @@ pub(super) struct GpuForm { /// buffers as they lay then, which the command buffer's first submission points at the set as /// it lies then. pre: DrawReplayPreprocess, + /// The live buffers' table its resident set holds the ranges of: a host step's GPU route holds + /// it until the command buffer completes (`gpu_route.rs`), as a first submission holds the + /// one it points the set at. + live: Arc, +} + +impl GpuForm { + /// Whether its commands merge into one draw (the module docs, **Merged**). + pub(super) fn merged(&self) -> bool { + self.pre.layout.merged.is_some() + } + + /// Where its scratch's sections lie. + pub(super) fn layout(&self) -> &DrawReplayLayout { + &self.pre.layout + } + + /// The primitive type every command that draws draws. + pub(super) fn primitive_type(&self) -> PrimitiveType { + self.primitive_type + } + + /// The live buffers' table its resident set holds the ranges of. + pub(super) fn live(&self) -> &Arc { + &self.live + } +} + +/// What an execution's GPU form records before its draws ([`RenderExecution::prework`]): its +/// scratch, the bytes from the scratch's start to the replay's layout (its root table at a +/// multiple of an entry), the layout's device address, and the head's upload, which the command +/// buffer's first submission points at the resident set where `commit` recorded it. +pub(super) struct Prework { + pub(super) scratch: Buffer, + pub(super) lead: u64, + pub(super) address: u64, + head: Upload, } /// The slot table one push hole of a replayed draw names: the vertex function's or the fragment @@ -525,6 +568,7 @@ impl RenderExecution { decided, primitive_type, pre, + live, }) } @@ -587,11 +631,10 @@ impl RenderExecution { /// Record the execution's GPU form `form` (the module docs) through `core`, a segment of /// `command_buffer` with `residency` (the command buffer's), at `commit` or by its host step - /// (`step`): the preprocess and the barrier after it, then the commands' draws into a - /// secondary begun against the execution's instance, over the pass's `storage`, in the call's - /// layout as `rendered` backs it. The encoder trail notes the form and its scratch - /// (`encoder_trail.rs`, **GPU forms**). Returns the encoder that drew them, its runs to end - /// ([`finish`](Self::finish)). + /// (`step`): the preprocess and the barrier after it ([`prework`](Self::prework)), then the + /// commands' draws into a secondary begun against the execution's instance, over the pass's + /// `storage`, in the call's layout as `rendered` backs it. Returns the encoder that drew them, + /// its runs to end ([`finish`](Self::finish)). pub(super) fn record_gpu( &self, mut core: EncoderCore, @@ -608,6 +651,96 @@ impl RenderExecution { (Vec::new(), pipeline.can_encode_indirect_commands()) }); let pre = &form.pre; + let Prework { + scratch, + lead, + address, + head, + } = self.prework(&mut core, command_buffer, (form, step))?; + // Its resident set as the live buffers and what its encoders made resident lie now: the + // command buffer's first submission points its table at the set as it lies then, in the + // head the copy carries in as it runs. + command_buffer.state().replay_table(ReplayTable { + upload: head, + at: pre.layout.resident_offset, + address: address + pre.layout.resident_offset, + }); + let draws = command_buffer.begin_draws(&snapshot.compatible)?; + let raw = device.shared().vk(); + let visibility = + Visibility::borrowing(snapshot.layout.visibility.clone(), None, raw, draws); + let layout = rendered.backing(&snapshot.layout)?; + let (forms, first_at) = match pre.layout.merged { + Some(merged) => (BufferForms::Merged, merged.draw_offset(0)), + None => (BufferForms::Replay, pre.layout.argument_offset(0, 0)), + }; + let mut encoder = self.replay_encoder( + core, + (draws, visibility), + (storage, layout, residency.clone()), + forms, + ); + // The first draw reads its arguments where the preprocess (or the last merge pass) + // wrote them. + let first = DrawSource::new( + &scratch, + lead + first_at, + DRAW_ARGUMENT_BYTES, + 4, + false, + false, + )?; + let draw = DrawCall::Indirect { + indirect: IndirectRef::new(0, first.at), + indexed: None, + }; + let (buffer, offset) = scratch.at(lead); + encoder.replayed = Some(ReplayedDraws { + address, + buffer, + offset, + layout: pre.layout, + }); + (encoder.shape_inputs()).check_pipeline(CALL, pipeline, &encoder.layout)?; + encoder.pipeline = Some(pipeline.clone()); + let buffers = DrawBuffers { + indirect: Some(first), + ..DrawBuffers::default() + }; + let assembly = Assembly::Primitives(form.primitive_type); + // Its draw starts from an empty bind state, as an encoder's first draw may. + encoder.draw( + &mut LiveBind::default(), + CALL, + assembly, + draw, + buffers, + false, + )?; + encoder.replayed = None; + let counts = &device.shared().counts; + counts.gpu_form_commands(u64::from(pre.layout.commands)); + if pre.layout.merged.is_some() { + counts.merged_draw_commands(u64::from(pre.layout.commands)); + } + Ok(encoder) + } + + /// Record into `core`, a segment of `command_buffer`, what the execution's GPU form `form` + /// runs before its draws (the module docs, **What runs** and **Scratch**), at `commit` or by + /// its host step (`step`): the head's upload carried into a scratch of its own, a range read + /// from a buffer copied into its parameters, the preprocess, and a merged replay's two passes, + /// each after a barrier from everything before and with one after. The encoder trail notes + /// the form and its scratch (`encoder_trail.rs`, **GPU forms**). Returns where the scratch + /// lies ([`Prework`]), which `core` holds. + pub(super) fn prework( + &self, + core: &mut EncoderCore, + command_buffer: &CommandBuffer, + (form, step): (&GpuForm, bool), + ) -> Result { + let device = command_buffer.device().clone(); + let pre = &form.pre; let kernel = device.owned_kernel(OwnedModule::DrawReplayPreprocess)?; let no_address = || internal("a draw replay on a device without device addresses"); let records = self.icb.storage(); @@ -681,10 +814,10 @@ impl RenderExecution { // bytes into the parameters. Both for the preprocess. let (chunk, at) = head.buffer(); let into = (&scratch, lead); - copy_bytes(&mut core, (chunk, at), into, pre.layout.uploaded); + copy_bytes(core, (chunk, at), into, pre.layout.uploaded); if let ExecutionRange::Indirect { buffer, offset } = &self.range { let into = (&scratch, lead + pre.layout.range_offset()); - copy_bytes(&mut core, (buffer, *offset), into, RANGE_BYTES); + copy_bytes(core, (buffer, *offset), into, RANGE_BYTES); } // The preprocess reads the records and writes the scratch past its head. let compute = vk::PipelineStageFlags2::COMPUTE_SHADER; @@ -762,75 +895,14 @@ impl RenderExecution { } } if let Some(mirror) = &mirror { - copy_sections(&mut core, (&scratch, lead), mirror, §ions); + copy_sections(core, (&scratch, lead), mirror, §ions); } - // Its resident set as the live buffers and what its encoders made resident lie now: the - // command buffer's first submission points its table at the set as it lies then, in the - // head the copy carries in as it runs. - command_buffer.state().replay_table(ReplayTable { - upload: head, - at: pre.layout.resident_offset, - address: address + pre.layout.resident_offset, - }); - let draws = command_buffer.begin_draws(&snapshot.compatible)?; - let raw = device.shared().vk(); - let visibility = - Visibility::borrowing(snapshot.layout.visibility.clone(), None, raw, draws); - let layout = rendered.backing(&snapshot.layout)?; - let (forms, first_at) = match pre.layout.merged { - Some(merged) => (BufferForms::Merged, merged.draw_offset(0)), - None => (BufferForms::Replay, pre.layout.argument_offset(0, 0)), - }; - let mut encoder = self.replay_encoder( - core, - (draws, visibility), - (storage, layout, residency.clone()), - forms, - ); - // The first draw reads its arguments where the preprocess (or the last merge pass) - // wrote them. - let first = DrawSource::new( - &scratch, - lead + first_at, - DRAW_ARGUMENT_BYTES, - 4, - false, - false, - )?; - let draw = DrawCall::Indirect { - indirect: IndirectRef::new(0, first.at), - indexed: None, - }; - let (buffer, offset) = scratch.at(lead); - encoder.replayed = Some(ReplayedDraws { + Ok(Prework { + scratch, + lead, address, - buffer, - offset, - layout: pre.layout, - }); - (encoder.shape_inputs()).check_pipeline(CALL, pipeline, &encoder.layout)?; - encoder.pipeline = Some(pipeline.clone()); - let buffers = DrawBuffers { - indirect: Some(first), - ..DrawBuffers::default() - }; - let assembly = Assembly::Primitives(form.primitive_type); - // Its draw starts from an empty bind state, as an encoder's first draw may. - encoder.draw( - &mut LiveBind::default(), - CALL, - assembly, - draw, - buffers, - false, - )?; - encoder.replayed = None; - let counts = &device.shared().counts; - counts.gpu_form_commands(u64::from(pre.layout.commands)); - if pre.layout.merged.is_some() { - counts.merged_draw_commands(u64::from(pre.layout.commands)); - } - Ok(encoder) + head, + }) } } @@ -970,8 +1042,9 @@ fn scratch_head( Ok(bytes) } -/// The rule of a pass over a rasterization-rate map, which the GPU form does not draw. -const RATE_MAP: &str = "the pass has a rasterization rate map"; +/// The rule of a pass over a rasterization-rate map, which the GPU form does not draw; a host +/// step's GPU route passes over it (`gpu_route.rs`). +pub(super) const RATE_MAP: &str = "the pass has a rasterization rate map"; impl RenderLowering { /// The buffer slots the vertex and fragment functions of a command's draw of `state` as diff --git a/crates/metal2vulkan-runtime/src/render/executions/gpu_route.rs b/crates/metal2vulkan-runtime/src/render/executions/gpu_route.rs new file mode 100644 index 000000000..4dde30263 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/render/executions/gpu_route.rs @@ -0,0 +1,242 @@ +//! The GPU route of a host step that fans a rate-mapped pass's triangles out (`render/fan_out.rs`): +//! an execution whose records the GPU may write, and which takes its merged GPU form but for the +//! pass's rasterization-rate map (`gpu.rs`; the decision passes over that one rule, `cause.rs`), +//! has its records decoded on the GPU. The host never reads them. +//! +//! - **What runs first.** The step records the form's prework for each such execution of the pass +//! (`RenderExecution::prework`: the head carried into a scratch of its own, the preprocess, and +//! the two merge passes). Then a copy of each one's prefix (each command's first corner in the +//! merged draw, a `u64`) and of its merged draw's two `VkDrawIndirectCommand`s into the command +//! buffer's upload arena, behind a barrier to the host. The step submits that with a fence and +//! waits for it, as for its probe (`DeferredPass::submit_probe`). The host reads those words +//! alone, no record (`WorkCounts::indirect_records_read`). +//! - **Its commands' draws.** Each command that draws is one direct draw of its corners in the +//! state's merged variant (`BufferForms::Merged`), with the merged replay's header pushed +//! (`PushHole::MergedDrawAddress`): corners `[first, next)`, the prefix's, the last command's +//! next the total. Its vertex function finds the command, its vertex and its instance as the +//! merged draw's does (`bind::replay`'s merged docs): its `VertexIndex` is the corner, as in a +//! merged draw's first draw's first instance (a total below `MERGED_CHUNK`). The probe and the +//! routes take those draws as they take the draws of the commands the host read +//! (`render/fan_out.rs`): probed, then fanned out, boxed, in parts or region by region. Vulkan +//! rasterizes one draw's primitives in instance order, then in order within an instance +//! ("Primitive Order"), and the draws in order, so a pixel takes the commands' fragments in the +//! commands' order and each command's in its own, as the merged draw's. +//! - **Where the host reads the records instead**, as without the route: a total of +//! `MERGED_CHUNK` corners or more, a prefix that does not rise to the total, and a step whose +//! prework did not complete. +//! - **What the pass holds.** The scratch, the head and the live buffers' table its resident set's +//! ranges lie in, until the command buffer completes. The prework's resident set is the command +//! buffer's as the step resolves it (`residency.rs`), as the host's read resolves the records' +//! addresses, so no first submission points it again (`command_buffer/first_submission.rs`). +//! - Counted: `WorkCounts::rate_map_gpu_routes` and `rate_map_gpu_route_wait_nanos`. + +use std::ops::Range; +use std::sync::Arc; +use std::time::Instant; + +use super::cause::Passed; +use super::gpu::{GpuForm, Prework, RATE_MAP}; +use super::{DeferredPass, HostStepCause, StepCommands, StepDraws}; +use crate::blit::{reads, writes}; +use crate::command_buffer::CommandBuffer; +use crate::encoder::{EncoderCore, RecordedSegment}; +use crate::error::{internal, Error}; +use crate::residency::Residency; +use crate::tracker::Barrier; +use crate::upload::Upload; +use ash::vk; +use metal2vulkan::bind::{ReplayFaults, DRAW_ARGUMENT_BYTES}; +use metal2vulkan::metal::PrimitiveType; + +/// An execution's GPU route at its host step, its prework run (the module docs): the merged +/// replay's header's device address, the type its commands draw, and each command that draws, its +/// corners in the merged draw, in order. +pub(super) struct GpuRoute { + header: u64, + primitive_type: PrimitiveType, + corners: Vec>, +} + +impl GpuRoute { + /// Its commands as a host step's probe and routes take them: each that draws, its corners; + /// from no command the host read, with no fault the host found, and its header. + pub(super) fn step_commands(self) -> StepCommands { + let commands = StepDraws::Corners(self.corners, self.primitive_type); + (commands, 0, ReplayFaults::default(), Some(self.header)) + } +} + +/// An execution's prework as the step recorded it: its form, where its scratch lies, and the upload +/// its words for the host are copied into. +type Recorded = (GpuForm, Prework, Upload); + +impl DeferredPass { + /// The GPU routes of the pass's executions at its host step, by index (the module docs): + /// `None` for an execution that takes none, whose records the step reads; and the recording + /// of their prework, which ran, for the pass's segment to join. Nothing where none takes one. + pub(super) fn gpu_routes( + &self, + command_buffer: &CommandBuffer, + residency: &Residency, + ) -> Result<(Vec>, Option), Error> { + let none = || -> Vec> { self.executions.iter().map(|_| None).collect() }; + // The decision again, passing over the rate map's rule alone; merged forms alone. + let mut passed = Passed::default(); + passed.pass(&HostStepCause::Rule(RATE_MAP)); + let mut core = EncoderCore::segment(command_buffer, false)?; + let mut forms = Vec::with_capacity(self.executions.len()); + for execution in &self.executions { + let takes = execution.snapshot.rate_map.is_some() + && execution.shadows.is_empty() + && execution.icb.gpu_written(); + if !takes { + forms.push(None); + continue; + } + let storage = self.storage.clone(); + let (back, form) = execution.gpu_form(core, (storage, residency), &passed); + core = back; + forms.push(form.ok().filter(GpuForm::merged)); + } + if forms.iter().all(Option::is_none) { + return Ok((none(), None)); + } + let mut recorded: Vec> = Vec::with_capacity(forms.len()); + for (execution, form) in self.executions.iter().zip(forms) { + let Some(form) = form else { + recorded.push(None); + continue; + }; + let prework = execution.prework(&mut core, command_buffer, (&form, true))?; + let words = read_back(&mut core, command_buffer, &form, &prework)?; + core.retain(Arc::clone(form.live())); + recorded.push(Some((form, prework, words))); + } + core.barrier(Barrier::to_host()); + let mut segment = core.end_segment()?; + let what = "a rate-mapped pass's GPU route"; + // SAFETY: the segment's command buffers, of the command buffer's pool, ended and recorded + // for this submission alone; what they use the segment holds, which the pass's joins, and + // the host waits for the submission before the step ends. + let fenced = unsafe { command_buffer.submit_fenced(&segment.raws, what) }?; + segment.raws.clear(); + segment.piece_ends.clear(); + segment.executions.clear(); + let started = Instant::now(); + let completed = match &fenced { + Some(fenced) => command_buffer.wait_fenced(std::slice::from_ref(fenced), what)?, + None => false, + }; + let counts = &command_buffer.device().shared().counts; + counts.rate_map_gpu_route_waited(started.elapsed()); + if !completed { + return Ok((none(), Some(segment))); + } + let routes: Vec> = (recorded.into_iter()) + .map(|recorded| { + let (form, prework, words) = recorded?; + route(&form, &prework, &words) + }) + .collect(); + counts.rate_map_gpu_routes(routes.iter().flatten().count() as u64); + Ok((routes, Some(segment))) + } +} + +/// Record into `core`, a segment of `command_buffer`, a copy of `form`'s prefix and its merged +/// draw's two `VkDrawIndirectCommand`s from `prework`'s scratch into an upload of the command +/// buffer's arena, after the barrier that follows the last merge pass: the upload, the prefix +/// first. +fn read_back( + core: &mut EncoderCore, + command_buffer: &CommandBuffer, + form: &GpuForm, + prework: &Prework, +) -> Result { + let layout = form.layout(); + let merged = (layout.merged).ok_or_else(|| internal("a GPU route that does not merge"))?; + let prefix = 8 * u64::from(layout.commands); + let draws = 2 * DRAW_ARGUMENT_BYTES; + let device = command_buffer.device(); + let words = (command_buffer.state().uploads).upload(device, &[], prefix + draws)?; + let (scratch, lead) = (&prework.scratch, prework.lead); + let (chunk, at) = words.buffer(); + let (from, src) = scratch.at(lead); + let (to, dst) = chunk.at(at); + let regions = [ + vk::BufferCopy { + src_offset: src + merged.prefix_offset, + dst_offset: dst, + size: prefix, + }, + vk::BufferCopy { + src_offset: src + merged.draws_offset, + dst_offset: dst + prefix, + size: draws, + }, + ]; + let uses = [ + reads( + scratch, + lead + merged.prefix_offset..lead + merged.prefix_offset + prefix, + ), + reads( + scratch, + lead + merged.draws_offset..lead + merged.draws_offset + draws, + ), + writes(chunk, at..at + prefix + draws), + ]; + core.command( + vk::PipelineStageFlags2::TRANSFER, + &uses, + |raw, command_buffer| { + // SAFETY: the segment's command buffer is recording outside a render pass; the + // scratch lives until it completes (the segment holds it) and so does the upload (the + // arena); both regions lie in both: the prefix and the draws in the scratch's layout, + // and the upload holds them both. + unsafe { raw.cmd_copy_buffer(command_buffer, from, to, ®ions) }; + }, + ); + Ok(words) +} + +/// The route of `form`'s commands from the words its prework wrote into `words` +/// ([`read_back`]): `None` where the host reads the records instead (the module docs). +fn route(form: &GpuForm, prework: &Prework, words: &Upload) -> Option { + let layout = form.layout(); + let merged = layout.merged?; + let commands = usize::try_from(layout.commands).ok()?; + let len = 8 * commands + 2 * DRAW_ARGUMENT_BYTES as usize; + let mut bytes = vec![0u8; len]; + // SAFETY: the submission that wrote the words completed, its writes made visible to the host + // by its last barrier; the bytes are writable and apart from the upload. + unsafe { words.copy_out(0, bytes.as_mut_ptr(), len as u64) }; + let (prefix, draws) = bytes.split_at(8 * commands); + let word = + |at: usize| u32::from_le_bytes([draws[at], draws[at + 1], draws[at + 2], draws[at + 3]]); + // `VkDrawIndirectCommand`: `vertexCount`, `instanceCount`, `firstVertex`, `firstInstance`. + // The first draw's whole chunks, and the second's vertices. + let (chunks, rest) = (word(4), word(16)); + if chunks > 0 { + return None; + } + let total = u64::from(rest); + let firsts: Vec = (prefix.as_chunks::<8>().0.iter()) + .map(|first| u64::from_le_bytes(*first)) + .collect(); + let mut corners = Vec::new(); + for (at, &first) in firsts.iter().enumerate() { + let next = firsts.get(at + 1).copied().unwrap_or(total); + if first > next || next > total { + return None; + } + if next > first { + corners.push(u32::try_from(first).ok()?..u32::try_from(next).ok()?); + } + } + Some(GpuRoute { + header: prework.address + merged.header_offset, + primitive_type: form.primitive_type(), + corners, + }) +} diff --git a/crates/metal2vulkan-runtime/src/render/fan_out.rs b/crates/metal2vulkan-runtime/src/render/fan_out.rs index a562188cf..6271a1092 100644 --- a/crates/metal2vulkan-runtime/src/render/fan_out.rs +++ b/crates/metal2vulkan-runtime/src/render/fan_out.rs @@ -56,7 +56,7 @@ //! rasterizer the same position for a vertex in a region, so a draw that tests `Equal` the depth //! another stored meets it whichever route each took. -use super::executions::Command; +use super::executions::StepDraws; use crate::binding::PushWrite; use crate::error::{internal, Error}; use crate::rate_mapped_pass::RUN_GAP; @@ -518,14 +518,16 @@ impl FanOutRun { } /// The routes of an execution's commands at its host step (the module docs): the commands as the -/// step read them, once, for the probe and the routes alike, from command `start`; the faults the -/// read found; the index of each command's draw among the probe's, by its place among the -/// commands that run, where it was probed; and what the probe found of each draw it probed, by -/// its index. +/// step read them, once, for the probe and the routes alike, from command `start`, or its GPU +/// route's (`render/executions/gpu_route.rs`); the faults the read found; a GPU route's merged +/// replay's header's device address; the index of each command's draw among the probe's, by its +/// place among the commands that run, where it was probed; and what the probe found of each draw +/// it probed, by its index. pub(super) struct FanOutRoutes { - pub(super) commands: Vec>, + pub(super) commands: StepDraws, pub(super) start: u32, pub(super) faults: ReplayFaults, + pub(super) header: Option, pub(super) slots: Vec>, pub(super) probed: Arc<[Probed]>, } diff --git a/crates/metal2vulkan-runtime/src/tests/host_step_rules.rs b/crates/metal2vulkan-runtime/src/tests/host_step_rules.rs index f417d67e5..2ce5b274b 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_step_rules.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_step_rules.rs @@ -9,7 +9,8 @@ //! command, inheriting the encoder's pipeline state, is executed in a rate-mapped pass: alone, its //! notice names the rate map and nothing past it, the rest of the GPU form's rules kept; with a //! visibility result mode set, its notice names that rule first and the rate map past it. An -//! execution of the empty command alone probes no draw, counted so. +//! execution of the empty command alone probes no draw, counted so: read and probing none, or, +//! through its GPU route, with no command to probe. //! //! A device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind //! of device the cfg selects. The functions are `tob_triangle` and `tob_solid` of the owned @@ -221,11 +222,14 @@ fn a_host_step_notice_names_every_rule_its_pass_breaks() { assert_eq!(probe_counts(&before, &after), one, "the triangle alone"); let (before, after) = workload.frame(0..1, true); assert_eq!(probe_counts(&before, &after), one, "counting visibility"); - // The empty command alone: read, and no draw probed; or unfanned. + // The empty command alone: read, and no draw probed; through its GPU route, where it takes + // one (`render/executions/gpu_route.rs`), no command that draws; or unfanned. let (before, after) = workload.frame(1..2, false); - let nothing = match fans { - true => [0, 0, 0, 1], - false => [0, 1, 0, 0], + let routed = after.rate_map_gpu_routes - before.rate_map_gpu_routes; + let nothing = match (fans, routed) { + (true, 0) => [0, 0, 0, 1], + (true, _) => [0, 0, 1, 0], + (false, _) => [0, 1, 0, 0], }; assert_eq!(probe_counts(&before, &after), nothing, "the empty command"); diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 1c8790d33..41f0284b3 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -591,6 +591,8 @@ mod rate_mapped_depth_equal; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rate_mapped_fan_out; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod rate_mapped_gpu_route; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rate_mapped_pieces; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rate_mapped_region_boxes; diff --git a/crates/metal2vulkan-runtime/src/tests/rate_mapped_gpu_route.rs b/crates/metal2vulkan-runtime/src/tests/rate_mapped_gpu_route.rs new file mode 100644 index 000000000..7a598db26 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/rate_mapped_gpu_route.rs @@ -0,0 +1,451 @@ +//! A rate-mapped pass's executed commands at a host step, through the execution's GPU route +//! (`render/executions/gpu_route.rs`): the records the GPU may write, of a buffer that inherits +//! the encoder's pipeline state, are decoded on the GPU, and the host reads none of them +//! (`WorkCounts::indirect_records_read`), only each command's corners, which it probes and routes +//! as it routes the commands it reads (`render/fan_out.rs`). Every command but three draws a grid +//! of small triangles twice, one of them in two instances; one draws a triangle over the whole +//! target, another a triangle over four tiles a side, and two the grid with two of its triangles +//! far apart, one with indices and one without, so the probe flags three. Each command's positions +//! lie nearer than the one's before it, so each passes the `LessEqual` depth test over the earlier +//! ones and blends its colour at half alpha over them. The target's colour and depth bytes are +//! those of the same commands drawn on the encoder in the same pass: a command or a triangle lost, +//! drawn twice or out of order, a copy drawn into another region, or a vertex placed otherwise, +//! changes them. +//! +//! A device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind +//! of device the cfg selects. The functions are `cfb_depth_vertex` of the owned fixture +//! `validation/fixtures/public/engine/cfb_sample_depth.ll`, which draws each vertex where its +//! buffer holds it, and `tob_solid` of `engine/tob_renders.ll` (`llvm-as`). + +use super::blit_holds::{Scratch, WAIT}; +use super::encoder_holds::library; +use super::rate_mapped_fan_out::{device_under, differing}; +use crate::write_routes::GpuWriter; +use crate::{ + BlitOption, Buffer, ClearColor, CommandBufferStatus, CommandQueue, DepthStencilState, Device, + IndirectCommandBuffer, IndirectCommandBufferDescriptor, Library, LoadAction, Origin, + PipelineOptions, RasterizationRateMap, RenderPassDescriptor, RenderPipelineState, + ResourceOptions, Size, StoreAction, TextureDescriptor, WorkCounts, +}; +use metal2vulkan::bind::{RateMapDescriptor, RateMapLayerDescriptor}; +use metal2vulkan::device::{RateMapRegionPolicy, VkFeature}; +use metal2vulkan::metal::state::DepthStencilDescriptor; +use metal2vulkan::metal::{ + BlendFactor, CompareFunction, IndexType, IndirectCommandType, PixelFormat, PrimitiveType, + TextureUsage, +}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; + +/// The grid's quads on a side, the commands, the one without indices, the one in two instances, +/// the large and the medium triangles', and the grid with wide triangles', the triangles they +/// replace, in blocks far apart. +const GRID: u32 = 16; +const COMMANDS: u32 = 8; +const FLAT: u32 = 0; +const TWICE: u32 = 2; +const LARGE: u32 = 3; +const MEDIUM: u32 = 5; +const MIXED: u32 = 7; +const WIDE_AT: u32 = 300; +const WIDE_FAR: u32 = 900; +/// A grid command's indices: the grid's triangles, twice. +const INDICES: u32 = 2 * GRID * GRID * 6; +/// The map's screen side, and its quality samples on both axes. +const SCREEN: u32 = 512; +const QUALITY: [f32; 5] = [0.3, 0.6, 1.0, 0.6, 0.3]; + +/// The device, its queue, and what the frames draw with: each shape's positions, a copy for each +/// command one after another, each copy nearer than the one before it. +struct Workload { + device: Device, + queue: CommandQueue, + pipeline: RenderPipelineState, + depth: DepthStencilState, + grid: Buffer, + grid_indices: Buffer, + mixed_indices: Buffer, + mixed_vertices: Buffer, + large: Buffer, + large_indices: Buffer, + medium_indices: Buffer, + colors: Buffer, + icb: IndirectCommandBuffer, + map: RasterizationRateMap, + /// The bytes of one command's copy of the grid's, the wide grid's and the triangles' + /// positions. + copies: [u64; 3], +} + +/// What a command draws: its positions and the offset of its copy of them, its indices (`None`: +/// none, its vertices in order), their count, and its instances. +type Drawn<'a> = (&'a Buffer, u64, Option<&'a Buffer>, u32, u32); + +impl Workload { + fn new(device: Device) -> Workload { + let (vertex, solid) = ( + library(&device, "engine/cfb_sample_depth.ll"), + library(&device, "engine/tob_renders.ll"), + ); + let function = |library: &Library, name| { + StageSource::Function( + library + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + }; + let mut descriptor = RenderPipelineDescriptor::new(function(&vertex, "cfb_depth_vertex")); + descriptor.fragment = Some(function(&solid, "tob_solid")); + let mut color = ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm); + color.blending_enabled = true; + color.source_rgb_blend_factor = BlendFactor::SourceAlpha; + color.source_alpha_blend_factor = BlendFactor::SourceAlpha; + color.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha; + color.destination_alpha_blend_factor = BlendFactor::OneMinusSourceAlpha; + descriptor.color_attachments[0] = Some(color); + descriptor.depth_format = Some(PixelFormat::Depth32Float); + descriptor.support_indirect_command_buffers = true; + let pipeline = device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap(); + let mut depth = DepthStencilDescriptor::default(); + depth.depth_compare_function = CompareFunction::LessEqual; + depth.depth_write_enabled = true; + let depth = device.new_depth_stencil_state(&depth).unwrap(); + // Each of `corners` at the depth of command `k`'s copy: nearer for each later command, + // and sloped along `x`, so the depth varies over each triangle. + let copies = |corners: &[[f32; 2]]| -> Vec { + (0..COMMANDS) + .flat_map(|k| { + corners + .iter() + .flat_map(move |&[x, y]| [x, y, 0.5 + 0.1 * x - 0.04 * k as f32, 1.0]) + }) + .flat_map(f32::to_le_bytes) + .collect() + }; + // The grid's corners over the target, and its triangles twice. + let at = |i: u32| i as f32 * 2.0 / GRID as f32 - 1.0; + let grid: Vec<[f32; 2]> = (0..=GRID) + .flat_map(|y| (0..=GRID).map(move |x| [at(x), at(y)])) + .collect(); + let corner = |x: u32, y: u32| y * (GRID + 1) + x; + let triangles: Vec = (0..GRID * GRID) + .flat_map(|quad| { + let (x, y) = (quad % GRID, quad / GRID); + let [a, b, c, d] = [ + corner(x, y), + corner(x + 1, y), + corner(x, y + 1), + corner(x + 1, y + 1), + ]; + [a, b, c, b, d, c] + }) + .collect(); + let twice = [&triangles[..], &triangles[..]].concat(); + let index_bytes = + |indices: &[u32]| -> Vec { indices.iter().flat_map(|i| i.to_le_bytes()).collect() }; + // The grid with triangle `WIDE_AT` over the target's lower left half, and `WIDE_FAR` over + // its upper right half. + let mut mixed = twice.clone(); + let wide = 3 * WIDE_AT as usize; + mixed[wide..wide + 3].copy_from_slice(&[corner(0, 0), corner(GRID, 0), corner(0, GRID)]); + let far = 3 * WIDE_FAR as usize; + mixed[far..far + 3].copy_from_slice(&[ + corner(GRID, GRID), + corner(0, GRID), + corner(GRID, 0), + ]); + let mixed_vertices: Vec<[f32; 2]> = (mixed.iter()) + .map(|&i| [at(i % (GRID + 1)), at(i / (GRID + 1))]) + .collect(); + // One triangle over the whole target, and one from the centre of a tile of the map + // (32 screen pixels) to the centre of the fourth after it, on each axis. + let large = [ + [-1.0f32, -1.0], + [3.0, -1.0], + [-1.0, 3.0], + [-0.4375, -0.4375], + [-0.0625, -0.4375], + [-0.4375, -0.0625], + ]; + // Each command's colour at half alpha, 256 bytes apart. + let colors: Vec = (0..COMMANDS) + .flat_map(|k| { + let k = k as f32; + let mut slot = [k / 8.0, 1.0 - k / 8.0, 0.25 + k / 16.0, 0.5] + .map(f32::to_le_bytes) + .concat(); + slot.resize(256, 0); + slot + }) + .collect(); + let buffer = |bytes: &[u8]| { + (device.new_buffer_with_bytes(bytes, ResourceOptions::shared())).unwrap() + }; + let per_copy = |corners: usize| 16 * corners as u64; + let mut icb = IndirectCommandBufferDescriptor::new(); + icb.command_types = IndirectCommandType::DRAW | IndirectCommandType::DRAW_INDEXED; + icb.inherit_pipeline_state = true; + icb.inherit_buffers = false; + icb.max_vertex_buffer_bind_count = 1; + icb.max_fragment_buffer_bind_count = 1; + let icb = device + .new_indirect_command_buffer(&icb, u64::from(COMMANDS), ResourceOptions::shared()) + .unwrap(); + let mut map = RateMapDescriptor::new([SCREEN, SCREEN]); + map.layers = vec![RateMapLayerDescriptor::new( + QUALITY.to_vec(), + QUALITY.to_vec(), + )]; + let map = device.new_rasterization_rate_map(&map).unwrap(); + let workload = Workload { + queue: device.new_command_queue().unwrap(), + pipeline, + depth, + grid: buffer(&copies(&grid)), + grid_indices: buffer(&index_bytes(&twice)), + mixed_indices: buffer(&index_bytes(&mixed)), + mixed_vertices: buffer(&copies(&mixed_vertices)), + large: buffer(&copies(&large)), + large_indices: buffer(&index_bytes(&[0, 1, 2])), + medium_indices: buffer(&index_bytes(&[3, 4, 5])), + colors: buffer(&colors), + icb, + map, + device, + copies: [ + per_copy(grid.len()), + per_copy(mixed_vertices.len()), + per_copy(large.len()), + ], + }; + for k in 0..COMMANDS { + let command = workload + .icb + .indirect_render_command_at(u64::from(k)) + .unwrap(); + let (positions, offset, indices, count, instances) = workload.drawn(k); + command + .set_vertex_buffer(Some(positions), offset, 0) + .unwrap(); + command + .set_fragment_buffer(Some(&workload.colors), u64::from(k) * 256, 0) + .unwrap(); + let (count, instances) = (u64::from(count), u64::from(instances)); + match indices { + Some(indices) => command.draw_indexed_primitives( + PrimitiveType::Triangle, + count, + IndexType::UInt32, + indices, + 0, + instances, + 0, + 0, + ), + None => command.draw_primitives(PrimitiveType::Triangle, 0, count, instances, 0), + } + .unwrap(); + } + // The GPU may write the records: the host step records the pass. + workload.icb.written_by_gpu(GpuWriter::Reset); + drop(workload.icb.gpu_write()); + workload + } + + /// What command `k` draws. + fn drawn(&self, k: u32) -> Drawn<'_> { + let copy = |bytes: u64| u64::from(k) * bytes; + let [grid, mixed, large] = self.copies; + match k { + FLAT => (&self.mixed_vertices, copy(mixed), None, INDICES, 1), + LARGE => (&self.large, copy(large), Some(&self.large_indices), 3, 1), + MEDIUM => (&self.large, copy(large), Some(&self.medium_indices), 3, 1), + MIXED => ( + &self.grid, + copy(grid), + Some(&self.mixed_indices), + INDICES, + 1, + ), + TWICE => (&self.grid, copy(grid), Some(&self.grid_indices), INDICES, 2), + _ => (&self.grid, copy(grid), Some(&self.grid_indices), INDICES, 1), + } + } + + /// One frame into a colour target of the map's physical size cleared to opaque black and a + /// depth target cleared to 1: the commands executed from the indirect command buffer where + /// `executed`, else drawn on the encoder. The colour's bytes, the depth's, and the device's + /// counts over the frame. + fn frame(&self, executed: bool) -> (Vec, Vec, WorkCounts, WorkCounts) { + let size = self.map.physical_size_for_layer(0); + let (width, height) = (size.width, size.height); + let texture = |format| { + let mut d = TextureDescriptor::texture_2d(format, width, height, false); + d.usage = TextureUsage::RENDER_TARGET; + d.resource_options = ResourceOptions::private(); + self.device.new_texture(&d).unwrap() + }; + let (target, depth) = ( + texture(PixelFormat::RGBA8Unorm), + texture(PixelFormat::Depth32Float), + ); + let bytes = width * height * 4; + let back = || (self.device.new_buffer(bytes, ResourceOptions::shared())).unwrap(); + let (color_back, depth_back) = (back(), back()); + let before = self.device.work_counts(); + let command_buffer = self.queue.command_buffer().unwrap(); + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(target.clone()); + color.load_action = LoadAction::Clear; + color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 1.0); + color.store_action = StoreAction::Store; + pass.depth_attachment.texture = Some(depth.clone()); + pass.depth_attachment.load_action = LoadAction::Clear; + pass.depth_attachment.clear_depth = 1.0; + pass.depth_attachment.store_action = StoreAction::Store; + pass.rasterization_rate_map = Some(self.map.clone()); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&self.pipeline).unwrap(); + encoder.set_depth_stencil_state(&self.depth).unwrap(); + match executed { + true => encoder + .execute_commands_in_buffer(&self.icb, 0..u64::from(COMMANDS)) + .unwrap(), + false => { + for k in 0..COMMANDS { + let (positions, offset, indices, count, instances) = self.drawn(k); + encoder + .set_vertex_buffer(Some(positions), offset, 0) + .unwrap(); + encoder + .set_fragment_buffer(Some(&self.colors), u64::from(k) * 256, 0) + .unwrap(); + match indices { + Some(indices) => encoder.draw_indexed_primitives( + PrimitiveType::Triangle, + count, + IndexType::UInt32, + indices, + 0, + instances, + 0, + 0, + ), + None => { + encoder.draw_primitives(PrimitiveType::Triangle, 0, count, instances, 0) + } + } + .unwrap(); + } + } + } + encoder.end_encoding().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + for (texture, back) in [(&target, &color_back), (&depth, &depth_back)] { + blit.copy_from_texture_to_buffer( + texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(width, height, 1), + back, + 0, + width * 4, + bytes, + BlitOption::None, + ) + .unwrap(); + } + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + drop(command_buffer); + let after = self.device.work_counts(); + let read = |back: &Buffer| { + let at = back.contents().unwrap().as_ptr(); + // SAFETY: the read-back buffer's bytes, which no command writes now. + unsafe { std::slice::from_raw_parts(at, bytes as usize) }.to_vec() + }; + (read(&color_back), read(&depth_back), before, after) + } +} + +/// Whether `device` enables the features the fan-out and its probe take. +fn fans_out(device: &Device) -> bool { + let features = &device.compile_device().profile().enabled().features; + [ + VkFeature::GeometryShader, + VkFeature::ShaderClipDistance, + VkFeature::VertexPipelineStoresAndAtomics, + ] + .iter() + .all(|feature| features.contains(feature)) +} + +/// The records read, the GPU routes, the probes and the draws they flagged between two counts. +fn route_counts(before: &WorkCounts, after: &WorkCounts) -> [u64; 4] { + [ + after.indirect_records_read - before.indirect_records_read, + after.rate_map_gpu_routes - before.rate_map_gpu_routes, + after.rate_map_probes - before.rate_map_probes, + after.rate_map_flagged_draws - before.rate_map_flagged_draws, + ] +} + +/// On a device that fans out, the host step records the execution through its GPU route: it +/// reads no record, probes the commands' corners once and flags the three draws that touch more +/// regions than the fan-out's copies. Elsewhere it reads the records. Either way the colour and the +/// depth are the encoder's draws', bit for bit. +#[test] +fn a_gpu_route_draws_the_encoder_s_pixels_and_depth_reading_no_record() { + let scratch = Scratch::new("rate-mapped-gpu-route"); + let workload = Workload::new(device_under(&scratch.0, RateMapRegionPolicy::FanOut)); + let (drawn, drawn_depth, before, after) = workload.frame(false); + assert_eq!( + route_counts(&before, &after)[1..], + [0; 3], + "the encoder's draws" + ); + let (executed, executed_depth, before, after) = workload.frame(true); + let counts = route_counts(&before, &after); + let wait = after.rate_map_gpu_route_wait_nanos - before.rate_map_gpu_route_wait_nanos; + let fanned = after.rate_map_fanned_draws - before.rate_map_fanned_draws; + let parted = after.rate_map_parted_draws - before.rate_map_parted_draws; + let copies = after.rate_map_region_copy_draws - before.rate_map_region_copy_draws; + let boxed = after.rate_map_boxed_draws - before.rate_map_boxed_draws; + eprintln!( + "RATE-MAP-GPU-ROUTE records read, routes, probes, flagged {counts:?}; waited {wait} ns; \ + {fanned} fanned, {parted} in parts, {copies} through the region-copy variant, {boxed} \ + boxed" + ); + match fans_out(&workload.device) { + true => { + assert_eq!( + counts, + [0, 1, 1, 3], + "records read, routes, probes, flagged" + ); + assert!(wait > 0, "the host's wait for the route's prework"); + } + false => assert_eq!(counts[1..], [0; 3], "routes, probes, flagged"), + } + // Every pixel took the commands' blends: none is the clear's black. + assert!( + drawn.chunks(4).all(|texel| texel[..3] != [0, 0, 0]), + "a pixel the commands did not draw" + ); + let (differ, first) = differing(&drawn, &executed); + assert_eq!( + differ, 0, + "colour texels the execution draws otherwise, the first {first:?}" + ); + let (differ, first) = differing(&drawn_depth, &executed_depth); + assert_eq!( + differ, 0, + "depth texels the execution draws otherwise, the first {first:?}" + ); +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 10c22f7ea..35e98892d 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -255,6 +255,8 @@ pub(crate) struct Counters { rate_map_steps_unfanned: AtomicU64, rate_map_steps_nothing_to_probe: AtomicU64, rate_map_steps_probing_none: AtomicU64, + rate_map_gpu_routes: AtomicU64, + rate_map_gpu_route_wait_nanos: AtomicU64, rate_map_flagged_draws: AtomicU64, rate_map_flagged_triangles: AtomicU64, rate_map_fanned_draws: AtomicU64, @@ -3391,6 +3393,18 @@ impl Counters { counter.fetch_add(1, Ordering::Relaxed); } + /// A host step recorded `routes` executions of a rate-mapped pass in their GPU route + /// (`render/executions/gpu_route.rs`). + pub(crate) fn rate_map_gpu_routes(&self, routes: u64) { + (self.rate_map_gpu_routes).fetch_add(routes, Ordering::Relaxed); + } + + /// A host step waited `took` for its GPU routes' prework (`render/executions/gpu_route.rs`). + pub(crate) fn rate_map_gpu_route_waited(&self, took: std::time::Duration) { + let nanos = u64::try_from(took.as_nanos()).unwrap_or(u64::MAX); + (self.rate_map_gpu_route_wait_nanos).fetch_add(nanos, Ordering::Relaxed); + } + /// A draw the probe flagged was drawn in parts (`render/fan_out.rs`, **Parts**), of which /// `by_regions` triangles region by region, in `runs` parts. pub(crate) fn rate_map_drawn_in_parts(&self, by_regions: u64, runs: u64) { @@ -8071,7 +8085,8 @@ pub struct WorkCounts { /// **Pieces**). pub rate_map_pieces: u64, /// Ranges past the first that executed commands' draws in rate-mapped passes were drawn as, - /// each a range of the draw's indices drawn as a draw of its own, so a piece may begin between + /// each a range of the draw's indices (or of a GPU route's command's corners, + /// `render/executions/gpu_route.rs`) drawn as a draw of its own, so a piece may begin between /// them: a draw that alone would hold more than a piece's work (`rate_mapped_pass.rs`, /// **Pieces**). pub rate_map_index_ranges: u64, @@ -8112,7 +8127,8 @@ pub struct WorkCounts { /// shadowed texture the pass uses. Their commands are drawn region by region. pub rate_map_steps_unfanned: u64, /// Such passes a host step fanned out that read no command to probe: each execution over the - /// map of an empty range, or over a shadowed texture. + /// map of an empty range, over a shadowed texture, or recorded in its GPU route with no + /// command that draws ([`rate_map_gpu_routes`](Self::rate_map_gpu_routes)). pub rate_map_steps_nothing_to_probe: u64, /// Such passes a host step fanned out that read commands to probe and probed no draw: none of /// them drew (empty or reset commands, or records that run nothing for a fault), each @@ -8120,6 +8136,18 @@ pub struct WorkCounts { /// the probe failed. With [`rate_map_probes`](Self::rate_map_probes) and these two, every /// rate-mapped pass a host step recorded is counted once. pub rate_map_steps_probing_none: u64, + /// Executions of such passes a host step recorded in their GPU route + /// (`render/executions/gpu_route.rs`): an execution whose records the GPU may write, and + /// which takes its merged GPU form but for the pass's rate map, has its records decoded on + /// the GPU and its commands' corners read back, so the host reads none of its records + /// ([`indirect_records_read`](Self::indirect_records_read)). Its commands are probed and + /// routed as the records the host reads are. + pub rate_map_gpu_routes: u64, + /// The host's wait for those routes' prework (the preprocess and the merge passes), in + /// nanoseconds on the host's clock, from its submission until the host saw it complete, one + /// submission a host step for all of the pass's routes. Part of + /// [`host_step_nanos`](Self::host_step_nanos). + pub rate_map_gpu_route_wait_nanos: u64, /// The draws they probed that they flagged: a triangle crosses `w = 0` or touches more /// regions than the fan-out's copies. Each is drawn in parts /// ([`rate_map_parted_draws`](Self::rate_map_parted_draws)), or region by region whole where @@ -11732,6 +11760,9 @@ impl Device { .load(Ordering::Relaxed), rate_map_steps_probing_none: (counters.rate_map_steps_probing_none) .load(Ordering::Relaxed), + rate_map_gpu_routes: counters.rate_map_gpu_routes.load(Ordering::Relaxed), + rate_map_gpu_route_wait_nanos: (counters.rate_map_gpu_route_wait_nanos) + .load(Ordering::Relaxed), rate_map_flagged_draws: counters.rate_map_flagged_draws.load(Ordering::Relaxed), rate_map_flagged_triangles: (counters.rate_map_flagged_triangles) .load(Ordering::Relaxed), diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 566bdad38..f28252579 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 = 2324; +pub const RUNTIME_VERSION: u32 = 2325; /// 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 a27389b5d..9e3859ccb 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3386,6 +3386,8 @@ field metal2vulkan-runtime::WorkCounts.rate_map_fanned_vertices_boxed_256 pub ra field metal2vulkan-runtime::WorkCounts.rate_map_fanned_vertices_boxed_64 pub rate_map_fanned_vertices_boxed_64: u64 field metal2vulkan-runtime::WorkCounts.rate_map_flagged_draws pub rate_map_flagged_draws: u64 field metal2vulkan-runtime::WorkCounts.rate_map_flagged_triangles pub rate_map_flagged_triangles: u64 +field metal2vulkan-runtime::WorkCounts.rate_map_gpu_route_wait_nanos pub rate_map_gpu_route_wait_nanos: u64 +field metal2vulkan-runtime::WorkCounts.rate_map_gpu_routes pub rate_map_gpu_routes: u64 field metal2vulkan-runtime::WorkCounts.rate_map_index_ranges pub rate_map_index_ranges: u64 field metal2vulkan-runtime::WorkCounts.rate_map_own_copy_vertex_regions pub rate_map_own_copy_vertex_regions: u64 field metal2vulkan-runtime::WorkCounts.rate_map_parted_draws pub rate_map_parted_draws: u64 diff --git a/docs/API.md b/docs/API.md index 1d88d6921..ff0398b6b 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2710,7 +2710,11 @@ bound. later one that shares a resource the execution may reach (one made resident, the records), and the first command of a threadgroup size or threadgroup lengths its pipeline state has not dispatched makes that VkPipeline then, as does a render command's draw of a state the CPU set on none of the - commands. The commands run in the large-buffer form (their range-limited buffer slots at device + commands. In a rate-mapped pass whose host step fans its triangles out, a render execution kept + from the GPU alone by the rate map alone has its records decoded on the GPU at the step, which + reads back each command's corners and none of its records, and its commands run in their merged + variant (`WorkCounts::rate_map_gpu_routes`): a second round trip, for the decode, comes before + the probe's. Other commands run in the large-buffer form (their range-limited buffer slots at device addresses, with in-shader bounds checks), whose variants the commit compiles for every pipeline state a record may name (for a render execution, every state the CPU set on its commands; or, for an execution committed before a route that may write the records met the buffer, the call