From 45d18535d309b1924377ade2ff3cbbece02ba5e2 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 17 Nov 2026 20:33:22 -0800 Subject: [PATCH] rt: a group's command buffers share one submit info where no event wait or signal separates them, and a group holds sixteen The planner's ruled form. A submission's segments go in as few VkSubmitInfo2s as its event waits and signals allow: a segment that waits on nothing joins the info before it where that one signals nothing (submit::infos), the upload with the first. Each command buffer keeps its own timestamps and its commands, barriers and completion are unchanged: only the info boundaries move. The UHD 630's driver paid about 160 us for each info (probe 06860a3848, job m3-max-43935: burst_160 at a group of eight 1.9-2.9 ms merged against 28-30 ms in separate infos and 11.6-25.8 ms on the old runtime); the 2080, RX 550 and 3090 ran merged within 1% of separate. A group holds sixteen command buffers, by the ruled rule (no bound if the UHD without one is within 3% of its best arm, else sixteen): on the UHD, merged burst_160 ran 1.85 ms at sixteen and 3.6-4.1 ms unbounded (job m3-max-44105). Metrics::submit_infos counts the infos passed, so the merged path shows it ran. Tests: tests::submit_infos (the merge rule: shared until an event wait or signal, a signal-only info, one segment, none); every_device_shares_submit_infos_within_a_group_and_records_what_it_ records_alone (a group mixing a Private fill, a Shared fill whose end barrier reaches the host, an empty command buffer, an event signal and its wait: barriers, passes, bytes copied and the words equal to the same command buffers committed one at a time; fewer infos than command buffers in groups, one each alone). --- crates/metal2vulkan-rt/README.md | 11 +- crates/metal2vulkan-rt/src/counters.rs | 10 ++ crates/metal2vulkan-rt/src/submit.rs | 59 +++++++-- crates/metal2vulkan-rt/src/tests/command.rs | 125 ++++++++++++++++++ crates/metal2vulkan-rt/src/tests/mod.rs | 1 + .../metal2vulkan-rt/src/tests/submit_infos.rs | 80 +++++++++++ crates/metal2vulkan/tests/api_signatures.tsv | 1 + 7 files changed, 271 insertions(+), 16 deletions(-) create mode 100644 crates/metal2vulkan-rt/src/tests/submit_infos.rs diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 3975f1fef..cd2bac7c9 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -455,15 +455,18 @@ made, with no lock, and never rewritten for layouts. `enqueue` takes the command buffer's place in its queue; `commit` hands it to the submit thread and returns. A committed command buffer holds no device handle. - The submit thread passes what is ready to `vkQueueSubmit2` in the device's commit order, each - queue's command buffers in groups: a submission holds at most four command buffers of one + queue's command buffers in groups: a submission holds at most sixteen command buffers of one queue, ahead of them the upload (zero fills, texture copies and new textures' moves to their - home layouts), and only its last submit info signals the progress semaphore. The upload records + home layouts), and only its last submit info signals the progress semaphore. Consecutive + command buffers that no event wait or signal separates share one submit info, the upload with + the first: the GPU runs them in order either way, and a driver may pay for each info (the UHD + 630's paid about 160 us apiece). `Metrics::submit_infos` counts them. The upload records at most 4,096 calls and keeps at most 64 MiB on its own account: the staging buffers of copies larger than the staging region, and the textures and blocks released while it held them. A call that finds it past either submits it and waits for it to complete before recording, so nothing grows without a commit. While fewer than two of a queue's submissions are not yet seen complete, each of its command buffers goes at once, alone. While two are, the ones committed meanwhile - are held in one group, each scheduled as it joins, and the group goes when it holds four, when + are held in one group, each scheduled as it joins, and the group goes when it holds sixteen, when a completion leaves fewer than two in flight (the completion thread wakes the submit thread as it retires; no commit or wait is needed), when the host is to wait for one of them (`wait_until_completed`, or `CommandQueue::send_now`, the hint for a wait the runtime does not @@ -480,7 +483,7 @@ made, with no lock, and never rewritten for layouts. submission's in commit order: the status, the blocks they kept, their recorders and their place in the queue, then the handlers. Scheduled and completed handlers run on it, every device's in turn, so no handler waits for a command buffer. A command buffer of a group is seen complete - with the group's last: up to the GPU time of the three after it late. Only a queue already two + with the group's last: up to the GPU time of the fifteen after it late. Only a queue already two submissions behind holds a group; one whose submissions have completed sends its next command buffer alone. Without a wait or a hint, the lateness is bounded only while two submissions are in flight, and the completion that leaves fewer sends the group. The worst case measured: four diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index b130bafb6..9b2127a7a 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -89,6 +89,7 @@ pub struct Counters { #[derive(Default)] struct Atomics { submissions: AtomicU64, + submit_infos: AtomicU64, passes: AtomicU64, barriers: AtomicU64, bytes_copied: AtomicU64, @@ -183,6 +184,11 @@ impl Counters { a.commit_lock_wait_max_nanos.fetch_max(nanos, Relaxed); } + /// A submission of `infos` submit infos ([`Metrics::submit_infos`]). + pub(crate) fn submitted_infos(&self, infos: u64) { + self.atomics.submit_infos.fetch_add(infos, Relaxed); + } + /// `bytes` more copied for a call ([`Metrics::bytes_copied`]). pub(crate) fn copied(&self, bytes: u64) { self.atomics.bytes_copied.fetch_add(bytes, Relaxed); @@ -271,6 +277,7 @@ impl Counters { let a = &self.atomics; Metrics { submissions: a.submissions.load(Relaxed), + submit_infos: a.submit_infos.load(Relaxed), passes: a.passes.load(Relaxed), barriers: a.barriers.load(Relaxed), bytes_copied: a.bytes_copied.load(Relaxed), @@ -326,6 +333,9 @@ impl Counters { pub struct Metrics { /// `vkQueueSubmit2` calls. pub submissions: u64, + /// The `VkSubmitInfo2`s those calls passed: the command buffers of a submission that no event + /// wait or signal separates share one, and the upload shares the first. + pub submit_infos: u64, /// Encoders recorded: compute and blit, and later render. pub passes: u64, /// Pipeline-barrier commands recorded into command buffers' work: one at the end of each diff --git a/crates/metal2vulkan-rt/src/submit.rs b/crates/metal2vulkan-rt/src/submit.rs index b2d02b356..cf67db1bb 100644 --- a/crates/metal2vulkan-rt/src/submit.rs +++ b/crates/metal2vulkan-rt/src/submit.rs @@ -38,8 +38,10 @@ use std::collections::{HashMap, VecDeque}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak}; -/// The command buffers one submission ends at most. -const GROUP: usize = 4; +/// The command buffers one submission ends at most. A larger group is fewer submissions, until +/// the group grows past what a completion can release: on the UHD 630, sixteen ran a burst of 160 +/// command buffers in half the time no bound did (probe 06860a3848, job m3-max-44105). +const GROUP: usize = 16; /// The submissions of a queue not yet seen complete at which its command buffers are held in a /// group. @@ -264,12 +266,43 @@ struct Batch { wrote: Vec, } -/// One segment's submit info. +/// One segment's part of a submit info: its event waits, its commands and its signals. #[derive(Default)] -struct Staged { - waits: Vec>, - command: Option>, - signals: Vec>, +pub(crate) struct Staged { + pub(crate) waits: Vec>, + pub(crate) command: Option>, + pub(crate) signals: Vec>, +} + +/// One `VkSubmitInfo2` of a submission: the waits of its first segment, the commands of each of +/// its segments, and the signals of its last. +pub(crate) struct Info<'a> { + pub(crate) waits: &'a [vk::SemaphoreSubmitInfo<'static>], + pub(crate) commands: Vec>, + pub(crate) signals: &'a [vk::SemaphoreSubmitInfo<'static>], +} + +/// The submit infos of a submission's segments, in order: a segment that waits on nothing joins +/// the info before it where that one signals nothing, so only an event wait or signal starts a new +/// one. The GPU runs the command buffers of one info in order, as it runs those of consecutive +/// infos, and a driver may pay for each info: the UHD 630's paid about 160 us apiece (probe +/// 06860a3848, job m3-max-43935). +pub(crate) fn infos(segments: &[Staged]) -> Vec> { + let mut infos: Vec> = Vec::with_capacity(1); + for staged in segments { + match infos.last_mut() { + Some(last) if staged.waits.is_empty() && last.signals.is_empty() => { + last.commands.extend(staged.command); + last.signals = &staged.signals; + } + _ => infos.push(Info { + waits: &staged.waits, + commands: staged.command.into_iter().collect(), + signals: &staged.signals, + }), + } + } + infos } /// A command buffer of a submission: with an error where it ended before it was submitted. @@ -1433,13 +1466,14 @@ fn submit(core: &Core, value: u64, upload: Option, batch: Batch) { ..Staged::default() }), } - let infos: Vec> = segments + let merged = infos(&segments); + let infos: Vec> = merged .iter() - .map(|staged| { + .map(|info| { vk::SubmitInfo2::default() - .wait_semaphore_infos(&staged.waits) - .command_buffer_infos(staged.command.as_slice()) - .signal_semaphore_infos(&staged.signals) + .wait_semaphore_infos(info.waits) + .command_buffer_infos(&info.commands) + .signal_semaphore_infos(info.signals) }) .collect(); if ok { @@ -1450,6 +1484,7 @@ fn submit(core: &Core, value: u64, upload: Option, batch: Batch) { ok = unsafe { device.queue_submit2(*queue, &infos, vk::Fence::null()) }.is_ok(); drop(queue); core.counters.count(Metric::Submissions); + core.counters.submitted_infos(infos.len() as u64); } if !ok { complete::lose(core); diff --git a/crates/metal2vulkan-rt/src/tests/command.rs b/crates/metal2vulkan-rt/src/tests/command.rs index c35bf2b42..2c5089f38 100644 --- a/crates/metal2vulkan-rt/src/tests/command.rs +++ b/crates/metal2vulkan-rt/src/tests/command.rs @@ -1706,4 +1706,129 @@ pub(crate) mod on_device { drop((queue, device)); }); } + + /// The command buffers of a group share submit infos where no event wait or signal separates + /// them, and record what they record alone. A mix of a fill whose segment's end barrier + /// reaches commands, a Shared fill whose end barrier reaches the host, a command buffer with + /// nothing for the GPU (no timestamps, no info), and an event's signal and wait (which end and + /// lead infos) records the same barriers, passes and bytes copied and leaves the same words + /// committed behind two busy submissions, held in groups, as committed one at a time; the + /// groups pass fewer submit infos than the mix has command buffers with commands, and one at a + /// time passes one each. + #[test] + fn every_device_shares_submit_infos_within_a_group_and_records_what_it_records_alone() { + each_device("command_infos", |name, _, device| { + let busy = private(&device); + let queue = queue(&device); + let mut arena = Arena::new(&device); + let (a, b) = (arena.buffer(), arena.buffer()); + let event = shared_event(&device); + let counters = device.counters(); + // The mix, each command buffer handed to `commit` as it is made: the fills write + // `base + 1..=3` into `a` and `value` into every byte of `b`. + let mix = |base: u32, value: u8, signal: u64, commit: &dyn Fn(&CommandBuffer)| { + let first = queue.command_buffer().expect("a command buffer"); + fill(&first, &a, base + 1); + commit(&first); + let shared = queue.command_buffer().expect("a command buffer"); + let mut encoder = shared.blit_command_encoder().expect("an encoder"); + encoder.fill_buffer(&b, 0..256, value).expect("a fill"); + encoder.end_encoding(); + commit(&shared); + let empty = queue.command_buffer().expect("a command buffer"); + commit(&empty); + let signals = queue.command_buffer().expect("a command buffer"); + fill(&signals, &a, base + 2); + signals + .encode_signal_event(event.as_event(), signal) + .expect("a signal"); + commit(&signals); + let waits = queue.command_buffer().expect("a command buffer"); + waits + .encode_wait_for_event(event.as_event(), signal) + .expect("a wait"); + fill(&waits, &a, base + 3); + commit(&waits); + vec![first, shared, empty, signals, waits] + }; + let deterministic = || { + let m = counters.metrics(); + (m.barriers, m.passes, m.bytes_copied) + }; + let infos = || counters.metrics().submit_infos; + let bytes = |buffer: &Buffer| { + let contents = buffer.contents().expect("a Shared buffer"); + // SAFETY: the buffer is alive and 256 bytes long, and no command writes it now. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), 256) }.to_vec() + }; + + // Behind two busy submissions: the mix is held in groups. + let busy_work = || { + let command_buffer = queue.command_buffer().expect("a command buffer"); + let (target, offset) = busy.device_range(); + command_buffer + .record_for_test(&[&busy], |device, command| { + for word in 0..16 { + // SAFETY: the command buffer is recording; the range is the + // buffer's, in whole words. + unsafe { + device.cmd_fill_buffer(command, target, offset, BLOCK_LEN, word) + }; + } + }) + .expect("fills"); + command_buffer.commit().expect("a commit"); + command_buffer + }; + let held = [busy_work(), busy_work()]; + let (before, infos_before) = (deterministic(), infos()); + let grouped = mix(10, 0x5a, 1, &|command_buffer| { + command_buffer.commit().expect("a commit") + }); + for command_buffer in held.iter().chain(&grouped) { + finished(name, command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + } + let in_groups = (deterministic(), infos() - infos_before); + let grouped_words = (word(&a), bytes(&b)); + + // One at a time, each complete before the next is made. + let (before_alone, infos_alone) = (deterministic(), infos()); + let alone = mix(10, 0x5a, 2, &|command_buffer| { + command_buffer.commit().expect("a commit"); + finished(name, command_buffer); + }); + let one_at_a_time = (deterministic(), infos() - infos_alone); + let delta = |(after, _): ((u64, u64, u64), u64), (b, p, c): (u64, u64, u64)| { + (after.0 - b, after.1 - p, after.2 - c) + }; + assert_eq!( + delta(in_groups, before), + delta(one_at_a_time, before_alone), + "{name}: barriers, passes and bytes copied, in groups and one at a time" + ); + assert_eq!( + grouped_words, + (word(&a), bytes(&b)), + "{name}: the words, in groups and one at a time" + ); + assert_eq!((word(&a), bytes(&b)), (13, vec![0x5a; 256]), "{name}"); + assert!( + in_groups.1 < 4, + "{name}: {} submit infos for four command buffers with commands, in groups", + in_groups.1 + ); + assert_eq!( + one_at_a_time.1, 4, + "{name}: one submit info each, one at a time" + ); + println!( + "{name}: the mix passed {} submit infos in groups", + in_groups.1 + ); + drop(( + grouped, alone, held, a, b, arena, event, busy, queue, device, + )); + }); + } } diff --git a/crates/metal2vulkan-rt/src/tests/mod.rs b/crates/metal2vulkan-rt/src/tests/mod.rs index bfbbd8f31..01659a989 100644 --- a/crates/metal2vulkan-rt/src/tests/mod.rs +++ b/crates/metal2vulkan-rt/src/tests/mod.rs @@ -26,6 +26,7 @@ mod sampler; mod sampling; mod spill; mod staging; +mod submit_infos; mod texture; mod translate; mod upload; diff --git a/crates/metal2vulkan-rt/src/tests/submit_infos.rs b/crates/metal2vulkan-rt/src/tests/submit_infos.rs new file mode 100644 index 000000000..1d2326789 --- /dev/null +++ b/crates/metal2vulkan-rt/src/tests/submit_infos.rs @@ -0,0 +1,80 @@ +//! A submission's segments in submit infos: consecutive segments share one where no event wait +//! or signal separates them. + +use crate::submit::{infos, Staged}; +use ash::vk::{self, Handle}; + +fn command(raw: u64) -> Option> { + Some(vk::CommandBufferSubmitInfo::default().command_buffer(vk::CommandBuffer::from_raw(raw))) +} + +fn semaphore(raw: u64, value: u64) -> vk::SemaphoreSubmitInfo<'static> { + vk::SemaphoreSubmitInfo::default() + .semaphore(vk::Semaphore::from_raw(raw)) + .value(value) +} + +/// Each info as (the raw semaphores it waits on, its command buffers, the semaphores it signals). +fn shape(segments: &[Staged]) -> Vec<(Vec, Vec, Vec)> { + let raw = |infos: &[vk::SemaphoreSubmitInfo<'static>]| -> Vec { + infos.iter().map(|info| info.semaphore.as_raw()).collect() + }; + (infos(segments).iter()) + .map(|info| { + ( + raw(info.waits), + (info.commands.iter()) + .map(|c| c.command_buffer.as_raw()) + .collect(), + raw(info.signals), + ) + }) + .collect() +} + +#[test] +fn segments_share_a_submit_info_until_an_event_wait_or_signal() { + let staged = |waits: &[u64], raw: Option, signals: &[u64]| Staged { + waits: waits.iter().map(|&w| semaphore(w, 1)).collect(), + command: raw.and_then(command), + signals: signals.iter().map(|&s| semaphore(s, 1)).collect(), + }; + // The upload, three command buffers, the third signalling event 7; then one waiting on event + // 8, one more, and the last with the progress semaphore (9). + let segments = [ + staged(&[], Some(1), &[]), + staged(&[], Some(2), &[]), + staged(&[], Some(3), &[]), + staged(&[], Some(4), &[7]), + staged(&[8], Some(5), &[]), + staged(&[], Some(6), &[]), + staged(&[], Some(10), &[9]), + ]; + assert_eq!( + shape(&segments), + [ + (vec![], vec![1, 2, 3, 4], vec![7]), + (vec![8], vec![5, 6, 10], vec![9]), + ] + ); + // A signal alone (no commands) after a signal starts its own info; a wait right after a + // signal does too; one segment is one info. + let segments = [ + staged(&[], Some(1), &[7]), + staged(&[], None, &[9]), + staged(&[8], Some(2), &[]), + ]; + assert_eq!( + shape(&segments), + [ + (vec![], vec![1], vec![7]), + (vec![], vec![], vec![9]), + (vec![8], vec![2], vec![]), + ] + ); + assert_eq!( + shape(&[staged(&[], Some(1), &[9])]), + [(vec![], vec![1], vec![9])] + ); + assert!(shape(&[]).is_empty()); +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 33922d490..ba4734a60 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2310,6 +2310,7 @@ field metal2vulkan-rt::Metrics.passes pub passes: u64 field metal2vulkan-rt::Metrics.pipelines_created pub pipelines_created: u64 field metal2vulkan-rt::Metrics.ring_writes pub ring_writes: u64 field metal2vulkan-rt::Metrics.submissions pub submissions: u64 +field metal2vulkan-rt::Metrics.submit_infos pub submit_infos: u64 field metal2vulkan-rt::Metrics.synchronizations pub synchronizations: u64 field metal2vulkan-rt::Metrics.translations pub translations: u64 field metal2vulkan-rt::Metrics.translations_loaded pub translations_loaded: u64