From 7b1725eb3424ff0dd4dd4aa89fd879d95ca5fd7b Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 14 Nov 2026 21:39:26 -0800 Subject: [PATCH] RUNTIME 2336: Lay no more of a predicated loop's copies than keep its waiting host steps within 16 On RADV, runtime_lane::predication::every_dispatch_form_runs_in_each_pass_past_the_copies ran 40-77 s alone and passed its 60 s wait for one command buffer under the suite. The cost is the runtime's, not the test's breadth: each piece of work a host step records after the GPU's work before it (an indirect dispatch of a kernel that observes its partition, an indirect command buffer's execution inside a block) is its own batch, a round trip to the host (submit, wait for the GPU, record, submit) in every run of a loop's laying, whether its copy's pass runs or skips. A loop was laid down as 64 copies (16 inside another), bounded only by its commands (LAID_BUDGET), so the test's inner DoWhile of 20 + 1 passes inside a DoWhile of two laid 1024 copies of its body: measured on lavapipe at the base (msi job m3-max-31287, a timing probe), its command buffer's first run recorded 4097 host steps and made 8195 submissions (6145 and 12291 on the device without device addresses, whose step form records six such pieces a pass), where its 21 passes ran 84 (126); the DoWhile of 100 passes 257 (385). That command buffer was 94% of the test's 21,772 submissions, and each costs a GPU round trip, a few milliseconds on RADV. copies_of now bounds a loop's copies by a second budget too: the work apart whose host step waits for the GPU (Deferred::gpu_written) that its copies lay down, at most WAITED_BUDGET (16), counted as LAID_BUDGET counts commands, from the first copy's, inner loops' copies included (Predication::waited, Looping::waited_at). A loop of no such work keeps its 64 or 16 copies. A loop that ends before its copies pays at most 16 round trips for the copies it skips, and one that runs past them one more round trip, its check, per 16. The run-again path, unchanged, takes any count of copies down to one. Tests: every_dispatch_form_runs_in_each_pass and the failing test assert each loop's first run records at most 16 host steps and the check (257 and 4097 at the base: the negative control); the 100 passes no longer run again exactly once. docs/API.md and docs/RUNTIME-PORTING.md name the new bound. With abd0662e9f: the budget trades nothing for accuracy, so it has no FAST-PATHS row. --- .../metal2vulkan-runtime/src/predication.rs | 44 +++++++++++++++---- .../src/runtime_lane/predication.rs | 35 ++++++++++----- crates/metal2vulkan/src/cache/mod.rs | 2 +- docs/API.md | 8 ++-- docs/RUNTIME-PORTING.md | 2 +- 5 files changed, 65 insertions(+), 26 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/predication.rs b/crates/metal2vulkan-runtime/src/predication.rs index 991906c16..73cb757ae 100644 --- a/crates/metal2vulkan-runtime/src/predication.rs +++ b/crates/metal2vulkan-runtime/src/predication.rs @@ -108,10 +108,13 @@ //! with the encoder's state it ran with, `Captures`, carried from an encoder to the next of its //! unit, the boundary a barrier and the ended encoder's residency); at the End the encoder //! encodes the further copies ([`copies_of`]): 64 in all, or 16 inside another loop, but no more -//! than keep the steps and gated dispatches the loop lays down within [`LAID_BUDGET`] (counting -//! the first copy's, inner loops' copies included), and at least one, so neither a long body -//! nor nesting multiplies a loop's commands past what a driver takes in one command buffer; -//! each behind a copy start step and closed by a copy end step, and then a step past them. The +//! than keep the steps and gated dispatches the loop lays down within [`LAID_BUDGET`] and its +//! work apart whose host step waits for the GPU within [`WAITED_BUDGET`] (each counting the +//! first copy's, inner loops' copies included), and at least one: so neither a long body nor +//! nesting multiplies a loop's commands past what a driver takes in one command buffer, nor the +//! round trips to the host its runs pay for copies whose passes skip (each such work apart is +//! one in every run of the laying, its pass run or skipped); each behind a copy start step and +//! closed by a copy end step, and then a step past them. The //! copies share a flag the first failing test sets, after which every copy skips; the first //! copy's start takes the flag as clear (`PredicationOp::WhileFirst`, `PredicationOp::DoFirst`). //! A step past the copies halts the unit where the loop would run another: it sets the unit's @@ -189,6 +192,10 @@ pub(super) struct Predication { /// The steps and gated dispatches recorded so far: what a loop's copies lay down is counted /// from it ([`copies_of`]). laid: u64, + /// The work apart left inside a loop's laying so far whose host step waits for the GPU + /// (`Deferred::gpu_written`): what a loop's copies lay down of it is counted from it + /// ([`copies_of`]). + waited: u64, /// An unbalanced record just dropped what its unit's encoders recorded before it, from the /// encoder at this place among the command buffer's ended encoders on, which the open encoder /// leaves out of the command buffer's work ([`take_left_out`](Self::take_left_out)). @@ -242,16 +249,29 @@ const NESTED_COPIES: u64 = 16; /// copies of the outer three (some 400,000 commands in one command buffer). const LAID_BUDGET: u64 = 16_384; +/// The work apart whose host step waits for the GPU's work before it (`Deferred::gpu_written`: an +/// indirect dispatch or an indirect command buffer's execution a host step records, among others) +/// a loop's copies lay down, at most, where the first copy alone does not pass it: each is a round +/// trip to the host in every run of the laying, through the scheduler's gate in its first run and +/// the check's thread in each run again, whether its copy's pass runs or skips. A loop running past +/// its copies then pays one more round trip, its check, per this many; one ending before them pays +/// this many at most for the copies it skips. A cost cut alone: every pass runs as Metal's does +/// whatever the copies, and no answer changes, so it trades nothing for accuracy and has no row in +/// `docs/FAST-PATHS.md`. +const WAITED_BUDGET: u64 = 16; + /// The copies laid down in all of a loop with `depth` loops open around it whose first copy laid -/// down `first` steps and gated dispatches: [`FIRST_COPIES`] or [`NESTED_COPIES`], but no more than -/// keep them within [`LAID_BUDGET`], and at least one. -fn copies_of(depth: usize, first: u64) -> u64 { +/// down `first` steps and gated dispatches and `waited` pieces of work apart whose host step waits +/// for the GPU: [`FIRST_COPIES`] or [`NESTED_COPIES`], but no more than keep them within +/// [`LAID_BUDGET`] and [`WAITED_BUDGET`], and at least one. +fn copies_of(depth: usize, (first, waited): (u64, u64)) -> u64 { let most = if depth == 0 { FIRST_COPIES } else { NESTED_COPIES }; - (LAID_BUDGET / first.max(1)).clamp(1, most) + let by_waits = WAITED_BUDGET.checked_div(waited).unwrap_or(most); + (LAID_BUDGET / first.max(1)).min(by_waits).clamp(1, most) } /// A record's condition: the `u32` Metal reads, compared so with `reference`: at `place`, its @@ -511,6 +531,9 @@ pub(super) struct Looping { id: u32, /// The command buffer's steps and gated dispatches laid down before it ([`Predication::laid`]). laid_at: u64, + /// The work apart whose host step waits for the GPU laid down before it + /// ([`Predication::waited`]). + waited_at: u64, } /// An End of a loop: Metal's answer, the step to record, if any, whether it closed the loop @@ -1063,6 +1086,7 @@ impl Predication { if let Some(laying) = &mut self.laying { let before = laying.pieces.len().saturating_sub(1); laying.pieces.insert(before, Piece::Apart(work.clone())); + self.waited += u64::from(work.gpu_written()); } } @@ -1113,6 +1137,7 @@ impl Predication { flag: uploads.upload(device, &[], 16)?, id: self.loops, laid_at: self.laid, + waited_at: self.waited, }; let record = self.copy_step(uploads, device, &looping, true)?; self.open(&record, Kind::Loop(looping), dead)?; @@ -1841,7 +1866,8 @@ impl ComputeCommandEncoder { ) -> Result<(), Error> { let copies = self.predication(|predication, _, _| { let first = predication.laid - looping.laid_at; - Ok(copies_of(predication.loops_open(), first)) + let waited = predication.waited - looping.waited_at; + Ok(copies_of(predication.loops_open(), (first, waited))) })?; // The commands of the unit's earlier encoders replay here with what those made resident. for (_, event) in body { diff --git a/crates/metal2vulkan-validation/src/runtime_lane/predication.rs b/crates/metal2vulkan-validation/src/runtime_lane/predication.rs index fa214f661..64beee950 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/predication.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/predication.rs @@ -1594,12 +1594,17 @@ fn loop_streams_run_as_metal_ran() { /// Every dispatch form inside a loop runs in each pass: the forms of /// [`every_dispatch_form_runs_as_its_block_says`] in a DoWhile of three passes mark three times -/// each. +/// each. Each piece of work a host step records after the GPU's work before it (the forms' four, +/// six in the bound step form) is a round trip to the host whether its copy's pass runs or skips, +/// so the loop's copies hold 16 of them at most, not 64 copies' (256 or 384): the command buffer's +/// host steps are those and the loop's check. #[test] fn every_dispatch_form_runs_in_each_pass() { on_device(|device| { let marks = Marks::new(device); let forms = Forms::new(device, &marks); + let steps = || device.work_counts().host_steps_recorded; + let before = steps(); let queue = device.new_command_queue().unwrap(); let command_buffer = queue.command_buffer().unwrap(); let mut encoder = command_buffer.compute_command_encoder().unwrap(); @@ -1618,25 +1623,31 @@ fn every_dispatch_form_runs_in_each_pass() { counts[tag as usize] = 3; } assert_eq!(marks.counts(), counts); + let stepped = steps() - before; + assert!(stepped <= 16 + 1, "the loop's {stepped} host steps"); }); } /// Every dispatch form inside a loop that runs past its copies runs in each pass: the forms of /// [`every_dispatch_form_runs_as_its_block_says`], whose indirect dispatches of `prd_mark_group` /// and whose executions host steps record apart from the loop's command buffers, in a DoWhile of -/// 100 passes (64 copies, run again once), and in a DoWhile of 20 passes, then one more, inside a -/// DoWhile of two (16 copies of the inner loop). Each run again records the work apart again where -/// it lies, as its first run did. +/// 100 passes, and in a DoWhile of 20 passes, then one more, inside a DoWhile of two. Each run +/// again records the work apart again where it lies, as its first run did. Each of those host +/// steps is a round trip to the host in every run, whether its copy's pass runs or skips, so the +/// copies laid hold 16 of them at most, not those of 64 copies, or of 64 of 16 (4096 host steps, +/// 6144 in the bound step form, for the 84 or 126 that 21 passes run): the first run's host steps +/// are those and the loop's check. #[test] fn every_dispatch_form_runs_in_each_pass_past_the_copies() { on_device(|device| { let queue = device.new_command_queue().unwrap(); let base = Forms::command_tag(2) - 6; let again = || device.work_counts().predicated_loop_runs_again; + let steps = || device.work_counts().host_steps_recorded; // One DoWhile of 100 passes. let marks = Marks::new(device); let forms = Forms::new(device, &marks); - let before = again(); + let (before, stepped) = (again(), steps()); let command_buffer = queue.command_buffer().unwrap(); let mut encoder = command_buffer.compute_command_encoder().unwrap(); forms.resident(&mut encoder, &marks); @@ -1653,15 +1664,13 @@ fn every_dispatch_form_runs_in_each_pass_past_the_copies() { counts[tag as usize] = 100; } assert_eq!(marks.counts(), counts); - assert_eq!( - again() - before, - 1, - "the 100 passes ran again past 64 copies" - ); + assert!(again() > before, "the 100 passes ran past their copies"); + let stepped = steps() - stepped; + assert!(stepped <= 16 + 1, "the first run's {stepped} host steps"); // An inner DoWhile of 20 passes, then of one, in a DoWhile of two. let marks = Marks::new(device); let forms = Forms::new(device, &marks); - let before = again(); + let (before, stepped) = (again(), steps()); let command_buffer = queue.command_buffer().unwrap(); let mut encoder = command_buffer.compute_command_encoder().unwrap(); forms.resident(&mut encoder, &marks); @@ -1683,7 +1692,9 @@ fn every_dispatch_form_runs_in_each_pass_past_the_copies() { counts[tag as usize] = 21; } assert_eq!(marks.counts(), counts); - assert!(again() > before, "the inner loop ran past its 16 copies"); + assert!(again() > before, "the inner loop ran past its copies"); + let stepped = steps() - stepped; + assert!(stepped <= 16 + 1, "the first run's {stepped} host steps"); }); } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index aa7e80db4..4239ec117 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 = 2335; +pub const RUNTIME_VERSION: u32 = 2336; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/docs/API.md b/docs/API.md index d5bb4814e..9985b2c2f 100644 --- a/docs/API.md +++ b/docs/API.md @@ -5389,9 +5389,11 @@ each item named states the rule in full. its live blocks left open where a unit ends failing the command buffer as Metal's GPU recovery does (`PredicationOpenAtUnitEnd`). Loops nest to any depth and run as many passes as Metal's. A loop is laid down as 64 copies (16 inside another loop, fewer where they would lay down more - than 16384 steps and gated dispatches, and at least one); where it runs past them, a check - submits its copies again, from where it stopped, until it ends, each time a round trip to the - host, holding the batches after it on its queue (and those on other queues that use what the + than 16384 steps and gated dispatches, or more than 16 pieces of work a host step records after + the GPU's work before it, an indirect dispatch's or an execution's, each a round trip to the + host in every run whether its pass runs or not, and at least one); where it runs past them, a + check submits its copies again, from where it stopped, until it ends, each time a round trip to + the host, holding the batches after it on its queue (and those on other queues that use what the loop uses), and nothing encoded before the loop runs again. A loop without bound runs on, as Metal's does, after the program let go of its queue and device too, until the process ends or the device is lost. A loop running again stops, as Metal's does, at the GPU's recovery from a diff --git a/docs/RUNTIME-PORTING.md b/docs/RUNTIME-PORTING.md index 06c782f32..e2416417d 100644 --- a/docs/RUNTIME-PORTING.md +++ b/docs/RUNTIME-PORTING.md @@ -163,7 +163,7 @@ narrow refusal that the call's rustdoc describes. | `DispatchThreadgroupsIndirect` | `dispatchThreadgroupsWithIndirectBuffer:indirectBufferOffset:…` | `ComputeCommandEncoder::dispatch_threadgroups_indirect` | | `DispatchThreads` | `dispatchThreads:threadsPerThreadgroup:` | `ComputeCommandEncoder::dispatch_threads` | | `DispatchThreadsIndirect` | `dispatchThreadsWithIndirectBuffer:indirectBufferOffset:` (SPI) | `ComputeCommandEncoder::dispatch_threads_indirect` (a host step reads the arguments) | -| `EncodeStartDoWhile` | `encodeStartDoWhile` (SPI) | `ComputeCommandEncoder::encode_start_do_while`, as Metal runs it, its body in its unit's later encoders included, nested to any depth, laid down as 64 copies of the loop's commands (16 inside another loop, fewer past 16384 steps and gated dispatches, at least one), submitted again from where the loop stopped until it ends; a loop without bound runs until the process ends, as Metal's does | +| `EncodeStartDoWhile` | `encodeStartDoWhile` (SPI) | `ComputeCommandEncoder::encode_start_do_while`, as Metal runs it, its body in its unit's later encoders included, nested to any depth, laid down as 64 copies of the loop's commands (16 inside another loop, fewer past 16384 steps and gated dispatches or 16 pieces of work a host step records after the GPU's work before it, at least one), submitted again from where the loop stopped until it ends; a loop without bound runs until the process ends, as Metal's does | | `EncodeStartElse` | `encodeStartElse` (SPI) | `ComputeCommandEncoder::encode_start_else`, as Metal runs it; with no block open an unbalanced record, dropping its range of the unit's work as Metal's does, the unit's dispatches before its first record included | | `EncodeStartIf` | `encodeStartIf:offset:comparison:referenceValue:` (SPI) | `ComputeCommandEncoder::encode_start_if`, as Metal runs it, on a counter the runtime's step kernel moves; a live block open where its unit ends fails the command buffer where its commands skip there, as Metal's GPU recovery does (`PredicationOpenAtUnitEnd`); a word past its buffer reads as Metal reads it (the heap's bytes, or zero; zero announced where Metal reads unrelated memory) *(partial)* | | `EncodeStartWhile` | `encodeStartWhile:offset:comparison:referenceValue:` (SPI) | `ComputeCommandEncoder::encode_start_while`, as Metal runs it, laid down as `encode_start_do_while`'s loops are; its word read as `encode_start_if` reads it *(partial)* |