Keep each batch's footprint for the scheduler's order, built once from what it is built from

The scheduler's order across queues compares a held batch with each later queue's head by
their footprints (scheduler/order.rs), and its memo lasts one pass: every pass, one at each
commit and completion on any queue, built the held batch's footprint again, copying and sorting
every use of its summaries under its command buffer's lock. On the replayed-frames page at 5000
resident pairs on the M3 (macOS sample, 4 s), that was 193 of the scheduler thread's 571 busy
samples, and the host step's draws, which take the same lock, waited 137 samples for it.

CommandBufferShared::footprint now keeps each batch's footprint (State::footprints) with what it
was built from (FootprintSources), and a later ask takes the kept one while that holds:

- The recordings' revision. State::recorded is a Parts, whose every mutable access moves the
  revision (DerefMut), so no change to an encoder's summary, a segment's recording or its bound
  (a host step's recording, a rebind's encoding again, a submission's scrubs and joins) leaves a
  kept footprint standing.
- The batch's encoders (its range among the recordings).
- Which summary each segment takes (Taken: a loop's laying, its recording, or the bound commit
  gave its host step): what may change while the recordings stand, as a route met since makes
  the GPU write what a segment's work reads or outgrows what commit recorded for good, or a
  recording falls due again.

A footprint a segment's known uses join (Segment::known_summary, made from the device's aliases
as they stand) is built at each ask, as before. A kept footprint is built from uses copied out
under the lock (Footprint::gathered) and sorted without it (Footprint::sorted), and is kept only
where the revision did not move meanwhile. WorkCounts::footprints_built counts the builds; the
scheduler shares the footprint (Arc).

Lane: replayed_frames::a_batch_s_footprint_is_built_once_however_many_passes_look holds the page's
frame for its host step while a bystander commits on another queue until the frame completes, and
asserts at most one build a bystander command buffer and two for each of the frame's batches.

Verified: nothing yet; the M3 jobs (clippy, the lanes, the negative control, the page's sample
before and after) follow.

(cherry picked from commit d862eadd34ac9f218de5c1a0952c2d22a1e5b0b8)
This commit is contained in:
Anees Iqbal committed 2026-11-05 02:08:24 -08:00
1 parent 347b9870c4
commit 90edf6fd2f
6 files changed
+240 -36

No files matched your search

@@ -530,6 +530,63 @@ impl FailedEncoders {
}
}
/// A command buffer's ended encoders' recordings, in encoding order, and a revision that every
/// mutable access to them moves: a batch's footprint built from them is kept while the revision
/// holds ([`CommandBufferShared::footprint`]), as nothing can change them but through such an
/// access.
#[derive(Default)]
struct Parts {
parts: Vec<Recorded>,
revision: u64,
}
impl std::ops::Deref for Parts {
type Target = Vec<Recorded>;
fn deref(&self) -> &Vec<Recorded> {
&self.parts
}
}
impl std::ops::DerefMut for Parts {
fn deref_mut(&mut self) -> &mut Vec<Recorded> {
self.revision += 1;
&mut self.parts
}
}
/// A batch's footprint as [`CommandBufferShared::footprint`] built it, with what it was built
/// from.
struct BuiltFootprint {
from: FootprintSources,
footprint: Arc<Footprint<ResourceKey>>,
}
/// What a batch's footprint is built from: the recordings' revision ([`Parts`]), the batch's
/// encoders among them, and the summary each of its segments takes, in order. Two equal ones
/// build equal footprints: every summary taken lies in the recordings, which nothing changes
/// without moving the revision, and which one a segment takes is what may change while they
/// stand (a route met since makes the GPU write what its work reads, or outgrows what `commit`
/// recorded for good; a host step records it; a recording is due again).
#[derive(PartialEq)]
struct FootprintSources {
revision: u64,
range: Range<usize>,
taken: Vec<Taken>,
}
/// The summary a segment's share of its batch's footprint takes
/// ([`CommandBufferShared::footprint`]).
#[derive(Clone, Copy, PartialEq)]
enum Taken {
/// A loop's check: what its laying's parts use.
Laying,
/// Its recording's.
Recording,
/// What `commit` bounded its host step's recording by.
Bound,
}
/// A command buffer's mutable state.
pub(super) struct State {
status: CommandBufferStatus,
@@ -580,7 +637,10 @@ pub(super) struct State {
/// not kept (`kept_commands.rs`).
own_reached: u64,
/// The ended encoders' recordings, in encoding order.
recorded: Vec<Recorded>,
recorded: Parts,
/// Each batch's footprint as the scheduler last had it built, by batch
/// ([`CommandBufferShared::footprint`]).
footprints: Vec<Option<BuiltFootprint>>,
/// The last ended encoder's last `VkCommandBuffer`, still recording: its batch's end goes
/// into it as the batch ends ([`CommandBufferShared::close_tail`]), or it ends as it is where
/// a later encoder joins its batch.
@@ -1971,7 +2031,8 @@ impl CommandBuffer {
rerun_pool: None,
kept: None,
own_reached: 0,
recorded: Vec::new(),
recorded: Parts::default(),
footprints: Vec::new(),
tail: None,
folds: Vec::new(),
prefix: None,
@@ -3990,41 +4051,85 @@ impl CommandBufferShared {
/// `None` while some of it is not known: such a segment `commit` could not bound, one its
/// submission records (a scrub), or a resource state encoder's update, whose uses its
/// submission adds. A loop's check adds what its laying's parts use, which it may run again.
pub(crate) fn footprint(&self, index: usize) -> Option<Footprint<ResourceKey>> {
let state = lock(&self.state);
let range = state.batch_range(index);
let recorded = &state.recorded[range.clone()];
let mut summaries = Vec::new();
let mut known = Vec::new();
for (at, encoder) in recorded.iter().enumerate() {
if !encoder.sparse.is_empty() {
return None;
}
summaries.push(&encoder.summary);
for segment in &encoder.segments {
// A loop's check may run its laying again: what the laying's parts use (`rerun.rs`).
if let Deferred::Loop(check) = &segment.work {
let laying = state.recorded.get(check.from()..range.start + at);
summaries.extend(laying.into_iter().flatten().map(|part| &part.summary));
continue;
///
/// Built where a pass first asks, and kept (`State::footprints`): a later ask takes the kept
/// one while what it was built from holds ([`FootprintSources`]), so the scheduler's passes,
/// one at each commit and completion on every queue, build each batch's once, not once a
/// pass (`WorkCounts::footprints_built`). Its uses are copied out under the command buffer's
/// lock and sorted without it, which a host step's draws take. A footprint a segment's
/// known uses join is built at each ask, as those are made from the device's aliases as
/// they stand (`DeferredPass::known_summary`).
pub(crate) fn footprint(&self, index: usize) -> Option<Arc<Footprint<ResourceKey>>> {
let counts = &self.device.shared().counts;
let (from, gathered) = {
let state = lock(&self.state);
let range = state.batch_range(index);
let recorded = &state.recorded[range.clone()];
let mut summaries = Vec::new();
let mut known = Vec::new();
let mut taken = Vec::new();
for (at, encoder) in recorded.iter().enumerate() {
if !encoder.sparse.is_empty() {
return None;
}
match &segment.recorded {
// One recorded again on the GPU alone uses what its recording does; one a
// route outgrew, what its host step finds.
Some(recording)
if !segment.needs_step()
|| (segment.rerecords() && !segment.work.outgrown()) =>
{
summaries.push(&recording.summary)
summaries.push(&encoder.summary);
for segment in &encoder.segments {
// A loop's check may run its laying again: what the laying's parts use
// (`rerun.rs`).
if let Deferred::Loop(check) = &segment.work {
let laying = state.recorded.get(check.from()..range.start + at);
summaries.extend(laying.into_iter().flatten().map(|part| &part.summary));
taken.push(Taken::Laying);
continue;
}
match &segment.recorded {
// One recorded again on the GPU alone uses what its recording does; one a
// route outgrew, what its host step finds.
Some(recording)
if !segment.needs_step()
|| (segment.rerecords() && !segment.work.outgrown()) =>
{
summaries.push(&recording.summary);
taken.push(Taken::Recording);
}
// One its host step records for what the GPU may write: what `commit`
// bounded its recording's uses by, where it could (`Segment::bound`).
_ if segment.steps_after_the_gpu() => {
summaries.push(segment.bound.as_ref()?);
taken.push(Taken::Bound);
}
_ => known.push(segment.known_summary(&self.device)?),
}
// One its host step records for what the GPU may write: what `commit` bounded
// its recording's uses by, where it could (`Segment::bound`).
_ if segment.steps_after_the_gpu() => summaries.push(segment.bound.as_ref()?),
_ => known.push(segment.known_summary(&self.device)?),
}
}
if !known.is_empty() {
counts.footprint_built();
let all = summaries.into_iter().chain(&known);
return Some(Arc::new(Footprint::of(all)));
}
let from = FootprintSources {
revision: state.recorded.revision,
range,
taken,
};
let kept = state.footprints.get(index).and_then(Option::as_ref);
if let Some(kept) = kept.filter(|kept| kept.from == from) {
return Some(Arc::clone(&kept.footprint));
}
(from, Footprint::gathered(summaries))
};
let footprint = Arc::new(gathered.sorted());
counts.footprint_built();
let mut state = lock(&self.state);
// Kept where nothing it was built from changed meanwhile.
if state.recorded.revision == from.revision {
if state.footprints.len() <= index {
state.footprints.resize_with(index + 1, || None);
}
let footprint = Arc::clone(&footprint);
state.footprints[index] = Some(BuiltFootprint { from, footprint });
}
Some(Footprint::of(summaries.into_iter().chain(&known)))
Some(footprint)
}
/// The host step of batch `index` (`deferred.rs`): on the steps' thread (`scheduler/steps.rs`),
@@ -2325,7 +2325,7 @@ fn gate_heads(state: &mut State, behind: &[u64], left: &mut Left<Work>, awaits:
fn is_behind(
order: &Order<Held>,
binary: &BinarySignals<vk::Semaphore>,
memo: &mut Behind<Option<Footprint<ResourceKey>>>,
memo: &mut Behind<Option<Arc<Footprint<ResourceKey>>>>,
sequence: u64,
) -> bool {
order.is_behind(
@@ -2334,8 +2334,9 @@ fn is_behind(
(
&mut |held: &Held| binary.ready(&held.binary_needs) && events_reachable(held),
&mut |held: &Held| held.buffer.footprint(held.index),
&|earlier: &Option<Footprint<ResourceKey>>, later: &Option<Footprint<ResourceKey>>| {
tracker::ordered(earlier.as_ref(), later.as_ref())
&|earlier: &Option<Arc<Footprint<ResourceKey>>>,
later: &Option<Arc<Footprint<ResourceKey>>>| {
tracker::ordered(earlier.as_deref(), later.as_deref())
},
),
)
+16 -1
View File
@@ -1955,6 +1955,16 @@ pub(super) struct Footprint<K> {
impl<K: Copy + Ord> Footprint<K> {
/// The footprint of a batch whose work these summaries hold.
pub(super) fn of<'a>(summaries: impl IntoIterator<Item = &'a Summary<K>>) -> Footprint<K>
where
K: 'a,
{
Footprint::gathered(summaries).sorted()
}
/// What these summaries' footprint holds, copied out of them, its uses not sorted yet
/// ([`sorted`](Self::sorted)): a caller that must not hold the summaries' lock while it
/// sorts gathers under it and sorts after.
pub(super) fn gathered<'a>(summaries: impl IntoIterator<Item = &'a Summary<K>>) -> Footprint<K>
where
K: 'a,
{
@@ -1972,10 +1982,15 @@ impl<K: Copy + Ord> Footprint<K> {
.updates
.extend(summary.updates.iter().map(|used| used.fence));
}
footprint.uses.sort_by_key(|used| used.key);
footprint
}
/// The footprint [`gathered`](Self::gathered) made, its uses sorted by resource.
pub(super) fn sorted(mut self) -> Footprint<K> {
self.uses.sort_by_key(|used| used.key);
self
}
/// Whether a tracked use of the batch names a resource `named` answers for.
pub(super) fn names_any(&self, mut named: impl FnMut(&K) -> bool) -> bool {
self.uses.iter().any(|used| named(&used.key))
@@ -208,6 +208,7 @@ pub(crate) struct Counters {
scheduler_passes_at_commit: AtomicU64,
batches_submitted_at_commit: AtomicU64,
batches_checked_at_commit: AtomicU64,
footprints_built: AtomicU64,
command_buffer_wakes: AtomicU64,
command_buffer_wakes_spared: AtomicU64,
event_wakes: AtomicU64,
@@ -1557,6 +1558,12 @@ impl Counters {
(self.batches_submitted_by_waiters).fetch_add(batches as u64, Ordering::Relaxed);
}
/// A batch's footprint for the scheduler's order across queues was built: none was kept, or
/// what it is built from changed since (`CommandBufferShared::footprint`).
pub(crate) fn footprint_built(&self) {
self.footprints_built.fetch_add(1, Ordering::Relaxed);
}
/// A thread that committed with `CommandBuffer::commit_and_submit` made a pass of its own
/// over the scheduler's order and submitted `batches` batches itself, the submission checks
/// of `checked` of them run by it first (`Scheduler::submit_at_commit`).
@@ -4413,6 +4420,13 @@ pub struct WorkCounts {
/// device or by the host. A head whose checks wait for a GPU signal to land, or whose checks
/// the scheduler's thread took first, is left to that thread, uncounted here.
pub batches_checked_at_commit: u64,
/// Footprints of batches the scheduler built to order them across queues
/// (`scheduler/order.rs`), one each time: each batch's is built where a pass first compares
/// it with another queue's and kept, and built again only where what it is built from
/// changed since (its command buffer's recordings, or the summary one of its segments takes,
/// as a host step records the segment), or a segment of it takes uses its work knows, which
/// are built at each look (`CommandBufferShared::footprint`).
pub footprints_built: u64,
/// Passes the scheduler's thread made over its order (`scheduler/mod.rs`): one takes in what
/// was committed and submits what is ready; one more follows a submission check or a host
/// step the thread ran without its lock, a waker's nudge during a pass, and a pass that
@@ -6264,6 +6278,7 @@ impl Device {
.batches_submitted_by_waiters
.load(Ordering::Relaxed),
scheduler_passes_at_commit: counters.scheduler_passes_at_commit.load(Ordering::Relaxed),
footprints_built: counters.footprints_built.load(Ordering::Relaxed),
batches_submitted_at_commit: counters
.batches_submitted_at_commit
.load(Ordering::Relaxed),
@@ -501,6 +501,73 @@ fn replayed_frames() {
}
}
/// The encoders of a page's frame ([`Page::frame_with`]): the encoding pass, the executing
/// pass and the blit that copies out its pixels.
const FRAME_ENCODERS: u64 = 3;
/// While the page's frame is held for its host step (`WorkCounts::heads_held_for_host_steps`), a
/// bystander on another queue commits a command buffer at a time, again as each completes, until
/// the frame completes: each commit and completion makes a pass of the scheduler's, which compares
/// the bystander's head with the held frame by their footprints (`scheduler/order.rs`). Each
/// batch's footprint is built once, however many passes look at it, and again only where what it
/// is built from changed, as where the frame's host step records its batch
/// (`WorkCounts::footprints_built`): at most one a bystander's command buffer and two for each of
/// the frame's batches, which its [`FRAME_ENCODERS`] bound; a footprint built at each look builds
/// one a pass. The validation layer stays silent.
#[test]
fn a_batch_s_footprint_is_built_once_however_many_passes_look() {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
{
let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap();
let name = device.name().to_owned();
let page = Page::new(&device, CHECKED_DRAWS);
let (page_queue, other) = (
device.new_command_queue().unwrap(),
device.new_command_queue().unwrap(),
);
let own = device.new_buffer(256, ResourceOptions::shared()).unwrap();
// A first frame makes the pipelines the next one records with.
let first = page.frame(&page_queue);
first.wait_until_completed_for(WAIT).unwrap();
let done = AtomicBool::new(false);
let before = device.work_counts();
let stood = thread::scope(|scope| {
let stood = scope.spawn(|| {
commit_until(&other, &done, |command_buffer| {
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.fill_buffer(&own, 0..256, 7).unwrap();
blit.end_encoding().unwrap();
})
});
let frame = page.frame(&page_queue);
frame.wait_until_completed_for(WAIT).unwrap();
assert_eq!(frame.status(), CommandBufferStatus::Completed);
done.store(true, Ordering::Release);
stood.join().unwrap()
});
let after = device.work_counts();
let held = after.heads_held_for_host_steps - before.heads_held_for_host_steps;
let built = after.footprints_built - before.footprints_built;
let passes = after.scheduler_passes - before.scheduler_passes;
let committed = stood.count as u64;
eprintln!(
"FOOTPRINTS {name}: {built} built in {passes} passes, the frame held {held} times, \
{committed} bystander command buffers"
);
assert!(
held > 0,
"on {name}: the frame was not held for its host step"
);
assert!(
built <= committed + 2 * FRAME_ENCODERS,
"on {name}: {built} footprints built for {committed} bystander command buffers and \
the frame, in {passes} passes"
);
}
layer_reported_nothing_at_all(&messages);
}
/// What another queue's command buffer encodes in a case of
/// [`a_replayed_execution_holds_only_what_shares_its_resources`].
type Encode<'a> = dyn Fn(&CommandBuffer) + 'a;
@@ -2646,6 +2646,7 @@ field metal2vulkan-runtime::WorkCounts.finales_folded pub finales_folded: u64
field metal2vulkan-runtime::WorkCounts.first_work_order_wait_nanos pub first_work_order_wait_nanos: u64
field metal2vulkan-runtime::WorkCounts.first_work_order_waits pub first_work_order_waits: u64
field metal2vulkan-runtime::WorkCounts.flights_followed pub flights_followed: u64
field metal2vulkan-runtime::WorkCounts.footprints_built pub footprints_built: u64
field metal2vulkan-runtime::WorkCounts.fragment_shader_libraries_made pub fragment_shader_libraries_made: u64
field metal2vulkan-runtime::WorkCounts.free_thread_queue_full pub free_thread_queue_full: u64
field metal2vulkan-runtime::WorkCounts.freed_memory_parked pub freed_memory_parked: u64
Can't render this file because it is too large.