From 7089c6ddb83dbd8840dddea63badb67c14d7a22a Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 5 Nov 2026 05:35:55 -0800 Subject: [PATCH] Find a token-ordered state's heap members searching forward from the last one's entries A heap part worked out (KeptHeap::bring_in, twice a frame on the replayed textured page: one a render encoder, over its 5002 textures) looks up each heap member's entries among the state's used resources twice, for the handle tables and for the heap elements. A state listed in token order was searched by two binary searches over the whole list a member, about 20 000 entries: member_id was 52 of the steps thread's 2146 samples in a 6 s window on the M3 at c83f120a2b. A plan's members that name used resources ascend by token (heap::members walks the shape's map), so UsedByToken::Listed now keeps where the last lookup's entries ended and searches forward from there, doubling a bound and searching under it (forward), where the token lies past it; else from the list's start, as before. Same entries, at about the distance between members. Verified (M3, potluck): the new test bind::heap::tests::a_state_in_token_order_finds_its_members_searching_forward passes: 4096 texture members each beside a buffer compare at most 8 entries a member for the tables and for the elements, each answering as the state in no order does, and members in reverse order are found alike. Negative control: the search from the list's start at every lookup fails it (the tables' bound). The translator's heap and bind-shape tests 20/20. Timing, the replayed textured page, against c83f120a2b, interleaved, two rounds of 3 frames: warm host_step_ms 28.1-31.2 -> 27.0-29.7, encoding to completion 60.7-68.5 -> 59.9-62.8 ms, pixels e3306dc52a1c9e86 at every frame of both. Sampled (6 s, steps thread): member_id 52 -> 7 samples, bring_in 70 -> 28, heap_elements 26 -> 2 (2146 and 2069 samples). The runtime's suite 1656/1656 and the residency and draw lanes 248/248 with --cfg m2v_gpu; the frame-cost lane passes (19.38 allocations a draw, bound 20). clippy -D warnings with --cfg m2v_gpu over the translator, the runtime and validation. (cherry picked from commit 55d9e418c2f38125a3958add7a6a7495213f4480) --- crates/metal2vulkan/src/bind/heap.rs | 52 +++++++++++++++--- crates/metal2vulkan/src/bind/heap/tests.rs | 61 +++++++++++++++++++++- 2 files changed, 104 insertions(+), 9 deletions(-) diff --git a/crates/metal2vulkan/src/bind/heap.rs b/crates/metal2vulkan/src/bind/heap.rs index ecb0647b6..7f746ceac 100644 --- a/crates/metal2vulkan/src/bind/heap.rs +++ b/crates/metal2vulkan/src/bind/heap.rs @@ -115,6 +115,7 @@ //! directory's entry holds the table's address in its element and flags words, and a listed table //! without one cannot be represented. +use std::cell::Cell; use std::collections::{BTreeMap, BTreeSet}; use crate::bind::neutral::image_classes; @@ -1492,13 +1493,40 @@ pub(crate) fn planner<'p, 'a>( /// The used resources of a bind state by token, in the state's order: a list the consumer gives /// in token order (`BindState::used_in_token_order`), whose entries of a token a heap member finds -/// by search, at the logarithm of their count; else gathered by token once per instantiation, so -/// each heap member finds its entries without rescanning the state. +/// by search forward from where the last member's ended (a plan's members ascend by token, +/// [`members`]), so a plan's members together cost about the list's length; else gathered by +/// token once per instantiation, so each heap member finds its entries without rescanning the +/// state. enum UsedByToken<'s> { - Listed(&'s [UsedResource]), + /// The list, and where the last lookup's entries ended in it. + Listed(&'s [UsedResource], Cell), Gathered(BTreeMap>), } +#[cfg(test)] +thread_local! { + /// The entries of a listed state that lookups of its used resources compared + /// ([`forward`]), on this thread. + static LISTED_LOOKED_AT: Cell = const { Cell::new(0) }; +} + +/// The partition point of `items` under `below`, which holds of a prefix of them: found by +/// doubling a bound from their start, then searching under it, at the logarithm of the point +/// rather than of their count. +fn forward(items: &[T], below: impl Fn(&T) -> bool) -> usize { + let below = |item: &T| { + #[cfg(test)] + LISTED_LOOKED_AT.with(|looked| looked.set(looked.get() + 1)); + below(item) + }; + let mut end = 1; + while end <= items.len() && below(&items[end - 1]) { + end *= 2; + } + let start = end / 2; + start + items[start..end.min(items.len())].partition_point(below) +} + impl<'s> UsedByToken<'s> { /// `state`'s used resources by token. fn of(state: &'s BindState) -> UsedByToken<'s> { @@ -1508,7 +1536,7 @@ impl<'s> UsedByToken<'s> { used.windows(2).all(|w| w[0].token <= w[1].token), "used resources listed in token order are not" ); - return UsedByToken::Listed(used); + return UsedByToken::Listed(used, Cell::new(0)); } let mut gathered: BTreeMap> = BTreeMap::new(); for u in used { @@ -1517,12 +1545,20 @@ impl<'s> UsedByToken<'s> { UsedByToken::Gathered(gathered) } - /// The entries of `token`, in the state's order; `None` where it lists none. + /// The entries of `token`, in the state's order; `None` where it lists none. A listed + /// state's are searched forward from where the last lookup's ended, where they lie past it, + /// else from the list's start. fn get(&self, token: u32) -> Option + '_> { let (listed, gathered): (&'s [UsedResource], &[&'s UsedResource]) = match self { - UsedByToken::Listed(used) => { - let start = used.partition_point(|u| u.token < token); - let end = start + used[start..].partition_point(|u| u.token == token); + UsedByToken::Listed(used, from) => { + let before = from.get().checked_sub(1).and_then(|at| used.get(at)); + let base = match before { + Some(before) if before.token < token => from.get(), + Some(_) | None => 0, + }; + let start = base + forward(&used[base..], |u| u.token < token); + let end = start + forward(&used[start..], |u| u.token == token); + from.set(end); (&used[start..end], &[]) } UsedByToken::Gathered(gathered) => (&[], gathered.get(&token)?), diff --git a/crates/metal2vulkan/src/bind/heap/tests.rs b/crates/metal2vulkan/src/bind/heap/tests.rs index c0835b2b7..fb3627387 100644 --- a/crates/metal2vulkan/src/bind/heap/tests.rs +++ b/crates/metal2vulkan/src/bind/heap/tests.rs @@ -1472,7 +1472,7 @@ fn a_state_in_token_order_finds_its_members_by_search() { }; let mut ordered = state.clone(); ordered.used_in_token_order = true; - assert!(matches!(UsedByToken::of(&ordered), UsedByToken::Listed(_))); + assert!(matches!(UsedByToken::of(&ordered), UsedByToken::Listed(..))); assert!(matches!(UsedByToken::of(&state), UsedByToken::Gathered(_))); let tables = |state: &BindState| handle_table_bytes(&template.heap_members, &[planned], state); let elements = |state: &BindState| heap_elements(&template, state, 1024); @@ -1503,3 +1503,62 @@ fn a_state_in_token_order_finds_its_members_by_search() { assert!(matches!(elements(&missing), Err(BindError::Internal(_)))); } } + +/// A state listed in token order finds its heap members' entries searching forward from where +/// the last member's ended, the plan's members ascending by token (`members`): 4096 textures, +/// each beside a buffer, compare a few entries a member (an upper bound of 8), not the logarithm +/// of the 8192 listed twice over, for the tables and for the elements; each answering as the same +/// state in no order does. A member past an out-of-order lookup is searched from the list's start +/// and found alike. +#[test] +fn a_state_in_token_order_finds_its_members_searching_forward() { + const MEMBERS: u32 = 4096; + let t2d = shape(TextureType::Type2D, PixelFormat::RGBA8Unorm, 1, READ); + let mut state = BindState::default(); + let mut template = ResourceTemplate::default(); + for member in 0..MEMBERS { + let token = 2 * member + 1; + state + .used_resources + .push(UsedResource::new(ResourceClass::Buffer, token - 1)); + let class = ResourceClass::Texture(TextureFacts::new( + TextureType::Type2D, + PixelFormat::RGBA8Unorm, + )); + let mut texture = UsedResource::new(class, token); + texture.resource_id = Some(u64::from(token) + 1); + state.used_resources.push(texture); + template.heap_members.push(HeapMember { + source: HeapSource::Used(token), + shape: t2d, + stages: vec![Stage::Kernel], + }); + } + state.heap_placement = HeapPlacement::ResourceId; + let planned = PlannedHandleTable { + set: 0, + binding: 4, + stage: Stage::Kernel, + entries: 2 * MEMBERS + 8, + }; + let mut ordered = state.clone(); + ordered.used_in_token_order = true; + let looked_at = |work: &dyn Fn()| { + LISTED_LOOKED_AT.with(|looked| looked.set(0)); + work(); + LISTED_LOOKED_AT.with(Cell::get) + }; + let tables = |state: &BindState| handle_table_bytes(&template.heap_members, &[planned], state); + let elements = |state: &BindState| heap_elements(&template, state, 4 * MEMBERS); + let bound = 8 * u64::from(MEMBERS); + let looked = looked_at(&|| assert_eq!(tables(&ordered).unwrap(), tables(&state).unwrap())); + assert!(looked <= bound, "the tables' lookups compared {looked}"); + let looked = looked_at(&|| assert_eq!(elements(&ordered).unwrap(), elements(&state).unwrap())); + assert!(looked <= bound, "the elements' lookups compared {looked}"); + // The members in another order: each found from the list's start where it lies before the + // last, as the same state in no order finds it. + let mut shuffled = template.clone(); + shuffled.heap_members.reverse(); + let elements = |state: &BindState| heap_elements(&shuffled, state, 4 * MEMBERS); + assert_eq!(elements(&ordered).unwrap(), elements(&state).unwrap()); +}