diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 0dd9cf411..55ab459ac 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -1830,6 +1830,12 @@ made, with no lock, and never rewritten for layouts. backlog, and a backlog whose last piece just completed passes no queue idle longer. A queue's backlog waits for as long as other queues that commit only when idle keep the device's room taken: Metal promises no order between queues, and the runtime keeps no aging rule for it. + Where one queue keeps 20 ms command buffers in flight, each signalling a waiter committed to + another queue, that waiter takes a place in the room, so the long queue's next starts one + completion round trip after the one before it ends: its GPU idle before each grew to about + 0.45 ms on the RX 7900 XTX (job m3-max-68440) and the Iris Xe (job m3-max-68441) and 0.6 ms on + an RTX 3090 (job m3-max-68465), its GPU time a command buffer by 1.0%, 1.4% and 2.5% (by 0.3%, + 0.9% and 1.1% where the other queue's command buffers wait for nothing). Without room, the ones committed meanwhile are held in one group of at most sixteen, each scheduled as it joins; one the group does not take is held too, not yet in a group, scheduled as it would be in one (its waits met, in its queue's order, @@ -1863,8 +1869,13 @@ made, with no lock, and never rewritten for layouts. dispatches of a kernel with no measured rate yet, which share a piece of their own, and any other, and where a compute or blit encoder opens after a full piece, never before or inside a render pass (`Metrics::cuts`). A dispatch's expected run is its kernel's rate, the GPU run of - one threadgroup as the pieces that ran the kernel measured with their own timestamps, times its - threadgroups; an indirect dispatch, whose threadgroups only the GPU reads, counts as one. So a + one threadgroup as the pieces that ran the kernel measured it, times its threadgroups; an + indirect dispatch, whose threadgroups only the GPU reads, counts as one. A command buffer of + one segment (not cut, and not split at an event) is one piece, timed by its own two timestamps, + which hold no other submission's run, and writes no other; the first piece of several runs from + the command buffer's start to a timestamp at the piece's end; each other piece, and a first + whose dispatches follow a blit or render encoder's commands, is timed by two timestamps of its + own. So a command buffer of another queue committed while one runs goes between two of its pieces (`Metrics::pieces_passed`), unless it holds a buffer or texture the cut one holds (by the ids the hazards track them by, a heap's resources by the heap's), waits on a fence the cut one diff --git a/crates/metal2vulkan-runtime/src/command.rs b/crates/metal2vulkan-runtime/src/command.rs index 6aa9d50d4..16bc0760c 100644 --- a/crates/metal2vulkan-runtime/src/command.rs +++ b/crates/metal2vulkan-runtime/src/command.rs @@ -365,8 +365,10 @@ pub(crate) struct Segment { pub(crate) managed_reached: Vec>, /// Its dispatches, which bound it as a piece (`crate::piece`). pub(crate) work: Work, - /// Its own pair of timestamp queries, from its first dispatch to its end, whose span feeds - /// its kernels' rates; None where it dispatches nothing or found no pair. + /// Its own pair of timestamp queries, whose span feeds its kernels' rates: from its first + /// dispatch to its end; of the first segment, taken only as it splits, its end alone, its run + /// starting at the command buffer's own start. None where it dispatches nothing or found no + /// pair, and for the only segment, which the command buffer's own pair spans (`retire`). pub(crate) stamps: Option, /// A submission carried it, so its pair was written. pub(crate) sent: bool, @@ -1082,6 +1084,20 @@ impl Building { /// Starts a new segment after the last one. fn split(&mut self) -> Result<(), Error> { + // The first segment's run starts at the command buffer's own start, where no other + // encoder's commands lead its dispatches: its pair, taken as it ends, gives the end, its + // first query written only so the pair reads whole. + let first = self.gpu.segments.len() == 1; + let last = self.last(); + let timed = last.stamps.is_some() || last.work.is_empty() || last.work.led(); + if let (true, false, Some(command)) = (first, timed, last.command) { + let core = self.device.core(); + let pair = core.stamps.take(&core.device, &core.counters); + if let Some(pair) = pair { + times::write_start(&core.device, command, pair.pool, pair.first); + } + self.last().stamps = pair; + } self.close(&[], None)?; self.gpu.segments.push(Segment::default()); Ok(()) @@ -1132,9 +1148,12 @@ impl Building { } /// Writes the start of the current segment's own pair into `command`, its command buffer, - /// before its first dispatch, where the device gives a pair. + /// before its first dispatch, where the device gives a pair: not in the command buffer's + /// first segment where no other encoder's commands lead it, whose run starts at the command + /// buffer's own start ([`split`](Self::split)). pub(crate) fn stamp_piece(&mut self, command: vk::CommandBuffer) { - if self.last().stamps.is_some() { + let last = self.gpu.segments.len() - 1; + if (last == 0 && !self.last().work.led()) || self.last().stamps.is_some() { return; } let core = self.device.core(); @@ -1742,22 +1761,35 @@ pub(crate) fn retire( ) { let Completion { gpu_times, + ticks, round, spans, } = completion; // Where its retirement begins, the step before its handlers (`Round::steps`): one clock read. let retiring = times::host_time(); - // Each piece's own run, by its own pair, sets its kernels' rates (`crate::piece`), and its - // pair goes back, reset where a submission wrote it. + // Each piece's own run sets its kernels' rates (`crate::piece`): the first segment's from the + // command buffer's own start, unless another encoder's commands lead its dispatches, to its + // own pair's end or, the only one, the command buffer's own end; each other by its own pair. + // Each pair goes back, reset where a submission wrote it. let mut pieces = 0; - for segment in &gpu.segments { + if let ([segment], Some((start, end)), None) = (&gpu.segments[..], ticks, error) { + if segment.stamps.is_none() && !segment.work.led() { + segment.work.ran(core.ticks.span(start, end)); + } + } + for (index, segment) in gpu.segments.iter().enumerate() { let Some(pair) = segment.stamps else { continue; }; if let (true, None) = (segment.sent, error) { // SAFETY: the pair's pool is the device's, and only this retirement resets its two // queries, after this read. - if let Some((start, end)) = unsafe { pair.times(&core.device, &core.counters) } { + let read = unsafe { pair.times(&core.device, &core.counters) }; + let start = |own| match index == 0 && !segment.work.led() { + true => ticks.map(|(start, _)| start), + false => Some(own), + }; + if let Some((start, end)) = read.and_then(|(own, end)| Some((start(own)?, end))) { let run = core.ticks.span(start, end); segment.work.ran(run); pieces += run; diff --git a/crates/metal2vulkan-runtime/src/complete.rs b/crates/metal2vulkan-runtime/src/complete.rs index 53b064737..961500d95 100644 --- a/crates/metal2vulkan-runtime/src/complete.rs +++ b/crates/metal2vulkan-runtime/src/complete.rs @@ -539,9 +539,11 @@ impl Round { } /// What the completion thread knows of a command buffer's completion as it retires it: its GPU -/// times where they were read, its round, and the GPU spans retired before it. +/// times where they were read, placed on the host clock and as the GPU wrote them, its round, +/// and the GPU spans retired before it. pub(crate) struct Completion<'a> { pub(crate) gpu_times: Option<(u64, u64)>, + pub(crate) ticks: Option<(u64, u64)>, pub(crate) round: &'a Round, pub(crate) spans: &'a Spans, } @@ -756,6 +758,7 @@ pub(crate) fn run(core: Arc) { .map(|(stamps, calibration)| calibration.place(&core.ticks, stamps, seen)); let completion = Completion { gpu_times: times, + ticks: stamps, round: &round, spans: &spans, }; diff --git a/crates/metal2vulkan-runtime/src/piece.rs b/crates/metal2vulkan-runtime/src/piece.rs index 57cc5a2f1..d1b02ea08 100644 --- a/crates/metal2vulkan-runtime/src/piece.rs +++ b/crates/metal2vulkan-runtime/src/piece.rs @@ -4,8 +4,11 @@ //! while one runs waits for that piece rather than for the whole command buffer //! (`crate::submit`). A dispatch's expected run is its kernel's rate, the run of one of its //! threadgroups, times its threadgroups. Each rate comes from the runs of the pieces that ran the -//! kernel, each piece timed by its own pair of timestamps, so the work of another queue's command -//! buffer that went between two pieces is in no rate. The rate is scheduling data, as a queue's +//! kernel: a command buffer of one piece timed by its own two timestamps, which nothing of another +//! submission passes inside; the first piece of several from the command buffer's start to a +//! timestamp at the piece's end; each later piece by a pair of its own. So the work of another +//! queue's command buffer that went between two pieces is in no rate, and a command buffer that +//! is not cut writes no timestamp past its own two. The rate is scheduling data, as a queue's //! expected run is (`QueueInner::expected_run`): it bounds where a piece ends, and never chooses //! between two forms of the work. @@ -64,6 +67,9 @@ pub(crate) struct Work { /// which counts as one, a dispatch of a kernel of unknown rate beside others, or commands of /// a blit or render encoder after its first dispatch. blind: bool, + /// Commands of a blit or render encoder come before its first dispatch, so a span from the + /// command buffer's start would hold them: its own pair starts at its first dispatch. + led: bool, } impl Work { @@ -116,9 +122,15 @@ impl Work { } } - /// Commands of another encoder follow its dispatches in the piece. + /// Commands of another encoder go in the piece: after its dispatches, or ahead of them. pub(crate) fn blind(&mut self) { self.blind |= !self.is_empty(); + self.led |= self.is_empty(); + } + + /// Whether commands of another encoder came before its first dispatch. + pub(crate) fn led(&self) -> bool { + self.led } /// The piece ran `nanos` on the GPU: a kernel alone in it takes its rate from that run, and diff --git a/crates/metal2vulkan-runtime/src/tests/pieces.rs b/crates/metal2vulkan-runtime/src/tests/pieces.rs index 62735ef9e..0d1512315 100644 --- a/crates/metal2vulkan-runtime/src/tests/pieces.rs +++ b/crates/metal2vulkan-runtime/src/tests/pieces.rs @@ -9,8 +9,9 @@ //! next waits for every piece, a cut command buffer is scheduled at its first piece and kept by an //! abandon, and an idle queue's commit waits for no more than the two pieces on the device //! behind five queues' backlogs. Without the gate: the cuts counted, a kernel of unknown rate in -//! a piece of its own whose run sets its rate, a dispatch past the bound uncut, and a blit encoder -//! after a full piece cut. +//! a piece of its own whose run sets its rate, a dispatch past the bound uncut, a blit encoder +//! after a full piece cut, and a command buffer of one piece, committed behind another queue's +//! long one, taking a rate that holds none of the long one's run. #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { @@ -18,6 +19,7 @@ mod on_device { each_device, fill, finished, shared_event, within, word, Arena, Busy, BODY_RUN, }; use crate::tests::compute::on_device::{add, step}; + use crate::tests::gpu_span::on_device::{dispatches_for, long, words, WORDS}; use crate::{ Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, ComputeCommandEncoder, ComputePipelineState, Device, DispatchType, @@ -473,4 +475,82 @@ mod on_device { assert_eq!(word(&filled), 7, "{name}"); }); } + + /// A command buffer of one piece takes no pair of timestamps past its own, and its kernel's + /// rate from its own two, which hold no other submission's run: one dispatch of `add` + /// committed to a queue right behind another queue's command buffer of about 20 ms of + /// dispatches, uncut (its kernel's rate the test's own), takes a rate under twice the rate it + /// takes alone. The ratio is printed. A start written before the long one ends would put its + /// tail in the rate. + #[test] + fn every_device_rates_a_one_piece_command_buffer_without_the_run_ahead_of_it() { + each_device("pieces_rate_behind", |name, _, device| { + let (long_state, add) = (step(&device), add(&device)); + let words = words(&device); + let mut arena = Arena::new(&device); + let slots = [arena.buffer(), arena.buffer(), arena.buffer()]; + let (first, second) = (queue(&device), queue(&device)); + let count = dispatches_for(name, &first, &long_state, &words, 20_000_000); + // One dispatch of `add` on the second queue, its rate unknown, so its run sets it. + let one = || { + add.inner.compiled.rate.set_for_test(u64::MAX); + let command_buffer = second.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.compute_command_encoder(DispatchType::Serial)) + .expect("an encoder"); + encoder.set_compute_pipeline_state(&add).expect("a state"); + for (index, buffer) in (0..).zip(&slots) { + encoder + .set_buffer(Some(buffer), 0, index) + .expect("a buffer"); + } + (encoder.dispatch_threadgroups([1, 1, 1], [64, 1, 1])).expect("a dispatch"); + encoder.end_encoding(); + command_buffer + }; + let rate = || (add.inner.compiled.rate.expected(1000)).expect("a rate"); + // The first meets every first use; the second is the rate alone. + for _ in 0..2 { + let alone = one(); + alone.commit().expect("a commit"); + completed(name, &alone); + } + let alone = rate(); + // Recorded, it holds its own pair of timestamps alone (`Building::stamp_piece`). + let stamps = &device.core().stamps; + let out = stamps.out_for_test(); + let recorded = one(); + assert_eq!( + stamps.out_for_test() - out, + 1, + "{name}: the pairs a command buffer of one piece takes" + ); + recorded.commit().expect("a commit"); + completed(name, &recorded); + long_state.inner.compiled.rate.set_for_test(1); + let ahead = long(&first, &long_state, &words, count, WORDS); + let behind = one(); + ahead.commit().expect("a commit"); + behind.commit().expect("a commit"); + assert_ne!( + ahead.status(), + CommandBufferStatus::Completed, + "{name}: the long command buffer still runs as the short one is committed" + ); + completed(name, &ahead); + completed(name, &behind); + let run = (ahead.gpu_end_time()).saturating_sub(ahead.gpu_start_time()); + let behind_rate = rate(); + let ratio = behind_rate as f64 / alone.max(1) as f64; + println!( + "pieces_rate_behind: {name}: alone {alone} ps a threadgroup, behind a {} us \ + command buffer {behind_rate} ps: ratio {ratio:.2}", + run / 1000 + ); + assert!( + behind_rate < alone.saturating_mul(2), + "{name}: the rate behind the long command buffer, {behind_rate} ps, against \ + {alone} ps alone" + ); + }); + } } diff --git a/crates/metal2vulkan-runtime/src/times.rs b/crates/metal2vulkan-runtime/src/times.rs index 2d703c9cd..437b6a2b3 100644 --- a/crates/metal2vulkan-runtime/src/times.rs +++ b/crates/metal2vulkan-runtime/src/times.rs @@ -379,6 +379,14 @@ impl StampPools { Some(Pair { pool, first: 0 }) } + /// For the device tests: the pairs taken and not given back. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn out_for_test(&self) -> usize { + let state = lock(&self.state); + let made = state.pools.len().saturating_sub(1) * (POOL_QUERIES / 2) as usize; + made + state.next as usize - state.free.len() + } + /// Gives back `pair`, both its queries reset. pub(crate) fn give_back(&self, pair: Pair) { lock(&self.state).free.push(pair);