RUNTIME 2475: Compute dispatches instantiate over the commands their bind state kept

What: BindingPlan::instantiate_dispatch_into writes a dispatch's commands over a kept
DispatchCommands, every field set as instantiate_dispatch sets it, the vectors keeping their
storage: each region's specialization (spec_key_into, region_specialization_into) and push
write's bytes, the argument table's bytes, the ranges, extents, holes and uses.
instantiate_dispatch is that method over no commands. The regions a dispatch plans take no list
of each axis's pieces (`Pieces`, numbers alone). In the runtime, compute::Instantiated keeps its
commands as storage when a value they may read moves, and a direct dispatch that instantiates
writes over them where nothing else holds them (the memo entry they were taken into is replaced
first: a dispatch that instantiates settled anew); builds with debug assertions instantiate
afresh and compare. WorkCounts::dispatches_instantiated_in_place counts them.

Why: a guest's compute encoders bind their buffers at moving offsets, one dispatch an encoder,
so their kept commands never serve again (reims's Iris walk: 96.6% of dispatches instantiated
anew). Profile (msi lavapipe, dispatch_chain --host 400 --only encoders --dispatches 5 --groups
64 --states 3 --binds tex-moved, calling thread): instantiate_dispatch 5.6% of its CPU, about
600 ns a dispatch, of it translator instantiate 3.4%, regions 1.6%, region_specialization 1.1%;
about fifteen allocations each instantiation. The commands read the buffer bindings that move,
so no memo of them is exact for this shape: the cut is the work of making them.

Verified: tests::bind::dispatch's
instantiating_over_kept_commands_gives_a_fresh_instantiation (more regions, fewer, none, another
state, the key's storage kept); compute_instantiated's
encoders_of_moving_offsets_instantiate_over_the_kept_commands (five encoders of one command
buffer: 5 instantiated, 4 in place, each writing at its own offset), on lavapipe.

Checks at the lane tip d52118ce95 (msi): clippy -D warnings --all-targets --all-features for metal2vulkan and the runtime, plain (m3-max-37686), m2v_cpu_icd (37688) and m2v_gpu (37689), all 0; rustdoc -D warnings 0 (37689); the translator bind::dispatch, plan::compute and graphics tests 42/42 (37686); the runtime compute, dispatch and encoder tests on lavapipe in a debug build, so every in-place instantiation was compared with a fresh one, 244/244 (37688). gem10 lavapipe m3-max-37685: dispatches_instantiated_in_place 0.80 a dispatch on the tex-moved row, every instantiation; that run's timing was unusable (rows the change does not touch moved more than the cut); one interleaved timing run follows.

With: dispatch_chain: an encoder's dispatch binds as its command buffer's dispatch index says (aac8651f23): at development the encoders shape never moved offsets or swapped textures.
This commit is contained in:
Anees Iqbal committed 2026-11-16 13:03:25 -08:00
1 parent ff32d9a89e
commit 8bcaf69f1d
11 files changed
+468 -163

No files matched your search

@@ -1447,7 +1447,7 @@ impl Ours<'_> {
if n > 0 && name == "barriers" {
encoder.memory_barrier_with_scope(BarrierScope::BUFFERS);
}
self.bind(&mut encoder, shape.binds, n as usize, &[])?;
self.bind(&mut encoder, shape.binds, dispatched as usize, &[])?;
shape.dispatch(&mut encoder, dispatched)?;
dispatched += 1;
}
@@ -1474,10 +1474,11 @@ impl Ours<'_> {
Ok((gpu * 1e6 / dispatches, wall * 1e6 / dispatches))
}
/// Bind what dispatch `n` of an encoder binds: the words, and `bump_wide`'s read-only
/// buffers (the next two of `churned`, the command buffer's buffers in its heap, where it has
/// any) or `bump_tex`'s textures the other way round from dispatch `n - 1`, with their word
/// of 1.
/// Bind what dispatch `n` of a command buffer binds, whatever encoder holds it: the words, and
/// `bump_wide`'s read-only buffers (the next two of `churned`, the command buffer's buffers in
/// its heap, where it has any) or `bump_tex`'s textures the other way round from dispatch
/// `n - 1`, with their word of 1, at the offsets `n` moves to: so the `encoders` shape's
/// dispatches, one an encoder, bind as the `serial` shape's do.
fn bind(
&self,
encoder: &mut ComputeCommandEncoder,
@@ -1593,7 +1594,7 @@ impl Ours<'_> {
let state = &self.states[dispatched as usize % self.states.len()];
encoder.set_compute_pipeline_state(state)?;
lap.lap(&mut at, Call::Pipeline);
self.bind(&mut encoder, shape.binds, n as usize, &churned)?;
self.bind(&mut encoder, shape.binds, dispatched as usize, &churned)?;
lap.lap(&mut at, Call::Bind);
shape.dispatch(&mut encoder, dispatched)?;
dispatched += 1;
+80 -22
View File
@@ -2625,48 +2625,86 @@ impl DispatchMemo {
/// does not read changed only in values its commands do not read: a program that binds two
/// textures of one shape in turn, an encoder for each dispatch, keeps them. Checked in builds
/// with debug assertions, where each dispatch that takes them instantiates again and compares.
/// - **Their storage, kept where the entry goes.** Commands no longer of the state stay as the
/// storage the next direct dispatch's instantiation writes over
/// (`BindingPlan::instantiate_dispatch_into`, `WorkCounts::dispatches_instantiated_in_place`)
/// where nothing else holds them (the memo's entry they were taken into goes before: a dispatch
/// that instantiates settled anew), so a program that binds a buffer at another offset at each
/// dispatch, an encoder for each, makes its commands' lists once. Exact: the method sets every
/// field as `instantiate_dispatch` does, which builds with debug assertions instantiate again
/// to compare.
#[derive(Default)]
pub(super) struct Instantiated(Option<KeptCommands>);
/// An [`Instantiated`]'s entry.
/// An [`Instantiated`]'s entry: its commands, and what they are of, where they still are.
struct KeptCommands {
/// `None` where a value they may read moved since: the commands are then storage alone.
of: Option<CommandsOf>,
commands: Arc<DispatchCommands>,
}
/// What a [`KeptCommands`]' commands are of.
struct CommandsOf {
planned: Weak<Planned>,
/// The dispatch they run: what it planned may be of another grid of its class
/// (`Planned::grids`).
dispatch: Dispatch,
/// The kinds of the state's values the commands may read.
reads: ValueKinds,
commands: Arc<DispatchCommands>,
}
impl CommandsOf {
fn new(planned: &Arc<Planned>, dispatch: Dispatch) -> CommandsOf {
CommandsOf {
planned: Arc::downgrade(planned),
dispatch,
reads: ValueKinds::dispatch_reads(&planned.plan),
}
}
}
impl Instantiated {
/// The commands kept, where they are of `planned` and `dispatch`.
fn of(&self, planned: &Arc<Planned>, dispatch: &Dispatch) -> Option<&Arc<DispatchCommands>> {
let kept = self.0.as_ref()?;
let of = std::ptr::eq(kept.planned.as_ptr(), Arc::as_ptr(planned));
(of && kept.dispatch == *dispatch).then_some(&kept.commands)
let of = kept.of.as_ref()?;
let same = std::ptr::eq(of.planned.as_ptr(), Arc::as_ptr(planned));
(same && of.dispatch == *dispatch).then_some(&kept.commands)
}
/// Keep `commands`, a direct dispatch's of `planned` and `dispatch`, in place of the entry.
fn keep(
/// The commands of a direct dispatch of `planned` and `dispatch`, kept in place of the
/// entry's: `over` writes them over the kept commands' storage where nothing else holds it
/// (with whether it did), else `fresh` makes them.
fn instantiate(
&mut self,
planned: &Arc<Planned>,
dispatch: Dispatch,
commands: Arc<DispatchCommands>,
) {
(planned, dispatch): (&Arc<Planned>, Dispatch),
fresh: impl FnOnce() -> Result<DispatchCommands, Error>,
over: impl FnOnce(&mut DispatchCommands) -> Result<(), Error>,
) -> Result<(Arc<DispatchCommands>, bool), Error> {
if let Some(kept) = &mut self.0 {
if let Some(commands) = Arc::get_mut(&mut kept.commands) {
// Of nothing while they are written, and after an error.
kept.of = None;
over(commands)?;
kept.of = Some(CommandsOf::new(planned, dispatch));
return Ok((Arc::clone(&kept.commands), true));
}
}
let commands = Arc::new(fresh()?);
self.0 = Some(KeptCommands {
planned: Arc::downgrade(planned),
dispatch,
reads: ValueKinds::dispatch_reads(&planned.plan),
commands,
of: Some(CommandsOf::new(planned, dispatch)),
commands: Arc::clone(&commands),
});
Ok((commands, false))
}
/// The state's values of the kinds `moved` names changed: the entry goes where its commands
/// may read one.
/// The state's values of the kinds `moved` names changed: the commands are of nothing where
/// they may read one, and are kept as storage alone.
fn moved(&mut self, moved: ValueKinds) {
if (self.0.as_ref()).is_some_and(|kept| kept.reads.meets(moved)) {
self.0 = None;
if let Some(kept) = &mut self.0 {
if (kept.of.as_ref()).is_some_and(|of| of.reads.meets(moved)) {
kept.of = None;
}
}
}
}
@@ -2876,14 +2914,34 @@ fn record(
Arc::clone(commands)
}
None => {
let commands = Arc::new(instantiate()?);
// A direct dispatch's are kept, over the storage of those kept before where
// nothing else holds it.
let commands = match (kept_commands, direct) {
(Some(memo), Some(_)) => {
let over = |commands: &mut DispatchCommands| {
(plan.instantiate_dispatch_into(state, &dispatch, commands))
.map_err(Error::Bind)?;
variant.keyed_regions(core.device(), commands);
debug_assert!(
instantiate().is_ok_and(|again| again == *commands),
"a dispatch's commands written over kept ones that are not \
those it instantiates"
);
Ok(())
};
let (commands, in_place) =
memo.instantiate((planned, dispatch), instantiate, over)?;
if in_place {
counts.dispatch_instantiated_in_place();
}
commands
}
_ => Arc::new(instantiate()?),
};
counts.dispatch_instantiated();
if from_aside {
counts.set_aside_commands_instantiated();
}
if let (Some(memo), Some(_)) = (kept_commands, direct) {
memo.keep(planned, dispatch, Arc::clone(&commands));
}
commands
}
};
@@ -8,15 +8,17 @@
//! each dispatch, as a guest compute benchmark's workloads bind them: the second dispatch on takes the
//! commands (`WorkCounts::dispatches_instantiated_as_before`), and each samples its own texture.
//! - **A buffer's binding**: the output bound at another offset instantiates again
//! (`dispatches_instantiated`) and writes there.
//! (`dispatches_instantiated`) and writes there; five encoders of one command buffer, each
//! binding it at the next offset, instantiate each dispatch but the first over the storage of
//! the commands the one before kept (`dispatches_instantiated_in_place`).
//! - **A field**: a buffer made resident (`use_resource`), which the state lists among its used
//! resources, instantiates again.
//! - **Texture bindings a plan reads**: texture buffers over one buffer at two offsets, read
//! through a texel-buffer view whose range the commands state, instantiate again at each change,
//! and each dispatch reads its own texels.
//!
//! Every dispatch is the only one of its compute encoder, in a command buffer of its own, waited
//! for before the next.
//! Every dispatch is the only one of its compute encoder, in a command buffer of its own (but the
//! five encoders'), waited for before the next.
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. The kernels are owned fixtures under
@@ -54,6 +56,15 @@ fn counts(device: &Device) -> [u64; 2] {
]
}
/// The dispatches whose commands were instantiated, and those instantiated over kept commands.
fn in_place(device: &Device) -> [u64; 2] {
let counts = device.work_counts();
[
counts.dispatches_instantiated,
counts.dispatches_instantiated_in_place,
]
}
/// A `Shared` buffer of `words`.
fn words(device: &Device, words: &[u32]) -> Buffer {
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
@@ -212,6 +223,44 @@ fn a_buffer_bound_at_another_offset_instantiates_again() {
}
}
/// Five encoders of one command buffer, each one dispatch binding the output at the next offset:
/// each instantiates, and each but the first over the commands the one before kept, which the
/// memo's entry of that dispatch no longer holds; each writes at its own offset.
#[test]
fn encoders_of_moving_offsets_instantiate_over_the_kept_commands() {
let scratch = Scratch::new("instantiated-in-place");
let device = device(&scratch.0);
let sampler = Sampler::new(&device);
let texture = texels(&device, [0.0, 1.0]);
let out = device.new_buffer(1280, ResourceOptions::shared()).unwrap();
let queue = device.new_command_queue().unwrap();
let before = in_place(&device);
let command_buffer = queue.command_buffer().unwrap();
let offsets = [0, 256, 512, 768, 1024];
for offset in offsets {
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(&sampler.state).unwrap();
encoder.set_texture(Some(&texture), 0).unwrap();
encoder
.set_sampler_state(Some(&sampler.nearest), 0)
.unwrap();
encoder.set_buffer(Some(&out), offset, 0).unwrap();
encoder.set_buffer(Some(&sampler.coords), 0, 1).unwrap();
let one = Size::new(1, 1, 1);
encoder.dispatch_threads(one, one).unwrap();
encoder.end_encoding().unwrap();
}
let after = in_place(&device);
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
let moved = [0, 1].map(|at| after[at] - before[at]);
assert_eq!(moved, [5, 4], "instantiated, of them over kept commands");
for offset in offsets {
assert_eq!(red(&out, offset), 1.0, "texel 1 at {offset}");
}
}
/// A buffer made resident, which the state lists among its used resources, instantiates again;
/// the same buffer made resident again keeps the commands.
#[test]
@@ -893,6 +893,7 @@ struct CommandCounters {
dispatches_settled_as_before: AtomicU64,
dispatches_settled_across_encoders: AtomicU64,
dispatches_instantiated: AtomicU64,
dispatches_instantiated_in_place: AtomicU64,
dispatches_instantiated_as_before: AtomicU64,
dispatches_from_set_aside: AtomicU64,
set_aside_commands_kept: AtomicU64,
@@ -2127,6 +2128,13 @@ impl Counting<'_> {
self.0.add(|counts| &counts.dispatches_instantiated, 1);
}
/// A compute encoder's dispatch whose commands `compute::record` instantiated over the
/// storage of those its kept bind state kept (`compute::Instantiated`).
pub(crate) fn dispatch_instantiated_in_place(&self) {
self.0
.add(|counts| &counts.dispatches_instantiated_in_place, 1);
}
/// A compute encoder's dispatch that took the commands its kept bind state kept of what it
/// planned (`compute::Instantiated`).
pub(crate) fn dispatch_instantiated_as_before(&self) {
@@ -9984,6 +9992,13 @@ pub struct WorkCounts {
/// execution, or of a host step. None for a compute encoder's dispatch counted in
/// `dispatches_settled_as_before` or `dispatches_instantiated_as_before`.
pub dispatches_instantiated: u64,
/// Of `dispatches_instantiated`, compute encoders' direct dispatches whose commands were
/// written over the storage of those their encoder's kept bind state kept
/// (`BindingPlan::instantiate_dispatch_into`, `compute::Instantiated`), which nothing else
/// held any more, rather than made anew: a dispatch of an encoder of its own that binds a
/// buffer at another offset than its pipeline state's last dispatch, for one. A function of
/// what the dispatches bind and of their order alone.
pub dispatches_instantiated_in_place: u64,
/// Compute encoders' dispatches that took the commands their encoder's kept bind state kept
/// rather than instantiating them (`compute::Instantiated`): those of the very variant, plan
/// and dispatch (`pipeline::Planned`) a direct dispatch of the encoder, or of an earlier
@@ -13088,6 +13103,9 @@ impl Device {
&counts.dispatches_settled_across_encoders
}),
dispatches_instantiated: commands(|counts| &counts.dispatches_instantiated),
dispatches_instantiated_in_place: commands(|counts| {
&counts.dispatches_instantiated_in_place
}),
dispatches_instantiated_as_before: commands(|counts| {
&counts.dispatches_instantiated_as_before
}),
+250 -128
View File
@@ -90,13 +90,14 @@
//! dispatch carries an [`IndirectClamp`] prepass and its region reads the clamp's scratch
//! ([`IndirectArgs::ClampScratch`]).
use crate::bind::graphics::zeroed;
use crate::bind::heap::HeapSource;
use crate::bind::indirect_clamp::IndirectClamp;
use crate::bind::instantiate::{
bind_buffers, put, slot_field, texel_ranges, BufferExtent, DescriptorBytes, DescriptorRange,
FieldBytes, IndirectRef, PushConstantWrite, PushHole, RootEntry, RootTable,
};
use crate::bind::plan::compute::{internal, not_implemented, spec_key};
use crate::bind::plan::compute::{internal, not_implemented, spec_key_into};
use crate::bind::plan::{
AccessClass, BindingPlan, ByteRange, ComputeTemplate, LocalRules, ResourceUse, UseTarget,
};
@@ -211,6 +212,23 @@ pub struct DispatchCommands {
pub uses: Vec<ResourceUse>,
}
impl DispatchCommands {
/// No dispatch's commands, which an instantiation writes over (`instantiate`).
fn none() -> DispatchCommands {
DispatchCommands {
regions: Vec::new(),
descriptor_bytes: Vec::new(),
descriptor_ranges: Vec::new(),
extents: Vec::new(),
push_holes: Vec::new(),
region_record: None,
root_table: None,
indirect_clamp: None,
uses: Vec::new(),
}
}
}
/// Where an indirect region reads its group counts.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -417,24 +435,61 @@ pub(crate) struct Region {
pub multi: bool,
}
/// One axis's pieces: `(base, count, local)`.
/// One piece of an axis: `(base, count, local)`.
type Piece = (u32, u32, u32);
/// `count` groups of `local` threads from group `base`, in chunks of at most `max`.
fn chunks(out: &mut Vec<Piece>, base: u32, count: u32, local: u32, max: u32) {
let max = max.max(1);
let mut done = 0;
while done < count {
let n = (count - done).min(max);
out.push((base + done, n, local));
done += n;
/// One axis's pieces: `count` groups of `local` threads from group `base`, in chunks of at most
/// `max`, then the edge piece where there is one. Held as these numbers alone, so a dispatch's
/// regions are planned with no list of each axis's pieces.
#[derive(Clone, Copy)]
struct Pieces {
base: u32,
count: u32,
local: u32,
max: u32,
edge: Option<Piece>,
}
impl Pieces {
/// `count` groups of `local` threads from group `base`, in chunks of at most `max`.
fn chunks(base: u32, count: u32, local: u32, max: u32) -> Pieces {
Pieces {
base,
count,
local,
max: max.max(1),
edge: None,
}
}
/// How many pieces the axis has.
fn len(&self) -> u64 {
u64::from(self.count.div_ceil(self.max)) + u64::from(self.edge.is_some())
}
/// The pieces in order: each chunk, then the edge.
fn iter(&self) -> impl Iterator<Item = Piece> {
let Pieces {
base,
count,
local,
max,
edge,
} = *self;
// Each chunk starts below `count`, so no start overflows.
(0..count.div_ceil(max))
.map(move |k| {
let done = k * max;
(base + done, (count - done).min(max), local)
})
.chain(edge)
}
}
/// The regions of a direct dispatch whose axes split into `pieces`; `MultiRegion` whenever there
/// is more than one region or `force_multi`.
fn product(pieces: [Vec<Piece>; 3], force_multi: bool) -> Result<Vec<Region>, BindError> {
let total: u64 = pieces.iter().map(|p| p.len() as u64).product();
fn product(pieces: [Pieces; 3], force_multi: bool) -> Result<Vec<Region>, BindError> {
let total: u64 = pieces.iter().map(Pieces::len).product();
if total > MAX_REGIONS {
let (i, _) = pieces
.iter()
@@ -449,9 +504,9 @@ fn product(pieces: [Vec<Piece>; 3], force_multi: bool) -> Result<Vec<Region>, Bi
}
let multi = force_multi || total > 1;
let mut out = Vec::with_capacity(total as usize);
for &(bx, cx, lx) in &pieces[0] {
for &(by, cy, ly) in &pieces[1] {
for &(bz, cz, lz) in &pieces[2] {
for (bx, cx, lx) in pieces[0].iter() {
for (by, cy, ly) in pieces[1].iter() {
for (bz, cz, lz) in pieces[2].iter() {
out.push(Region {
local: [lx, ly, lz],
groups: [cx, cy, cz],
@@ -646,11 +701,8 @@ pub(crate) fn regions(
if empty(groups) {
return Ok(planned(Vec::new(), grid, false));
}
let pieces = std::array::from_fn(|i| {
let mut p = Vec::new();
chunks(&mut p, 0, groups[i], l[i], rules.max_count[i]);
p
});
let pieces =
std::array::from_fn(|i| Pieces::chunks(0, groups[i], l[i], rules.max_count[i]));
// A partial-threadgroups variant's regions read their region, as its `Threads`
// regions do, so both run on its one `VkPipeline` of the dispatch's size.
let multi = tile_sized || ragged == Ragged::Partial;
@@ -675,15 +727,7 @@ pub(crate) fn regions(
return Ok(planned(Vec::new(), grid, false));
}
let pieces = std::array::from_fn(|i| {
let mut p = Vec::new();
chunks(
&mut p,
start[i],
end[i] - start[i],
l[i],
rules.max_count[i],
);
p
Pieces::chunks(start[i], end[i] - start[i], l[i], rules.max_count[i])
});
// Every region takes its first threadgroup from the push field.
Ok(planned(
@@ -734,16 +778,8 @@ pub(crate) fn regions(
// every thread is live, on the same `VkPipeline` of the dispatch's size.
let nonuniform = (0..3).any(|i| !threads[i].is_multiple_of(l[i]));
if ragged == Ragged::Partial {
let pieces: [Vec<Piece>; 3] = std::array::from_fn(|i| {
let mut p = Vec::new();
chunks(
&mut p,
0,
threads[i].div_ceil(l[i]),
l[i],
rules.max_count[i],
);
p
let pieces = std::array::from_fn(|i| {
Pieces::chunks(0, threads[i].div_ceil(l[i]), l[i], rules.max_count[i])
});
let fit = fit(rules, &[l])?;
let mut out = planned(
@@ -755,13 +791,12 @@ pub(crate) fn regions(
return Ok(out);
}
let mut edges = false;
let pieces: [Vec<Piece>; 3] = std::array::from_fn(|i| {
let pieces = std::array::from_fn(|i| {
let (full, rem) = (threads[i] / l[i], threads[i] % l[i]);
let mut p = Vec::new();
chunks(&mut p, 0, full, l[i], rules.max_count[i]);
let mut p = Pieces::chunks(0, full, l[i], rules.max_count[i]);
if rem > 0 {
edges = true;
p.push((full, 1, rem));
p.edge = Some((full, 1, rem));
}
p
});
@@ -839,6 +874,23 @@ impl BindingPlan {
state: &BindState,
dispatch: &Dispatch,
) -> Result<DispatchCommands, BindError> {
let mut commands = DispatchCommands::none();
self.instantiate_dispatch_into(state, dispatch, &mut commands)?;
Ok(commands)
}
/// [`instantiate_dispatch`](Self::instantiate_dispatch)'s commands, written over `commands`:
/// every field is set as `instantiate_dispatch` sets it, and the vectors (each region's
/// specialization and push write's bytes, and the argument table's, among them) keep the
/// storage the commands written there before left, so a consumer that keeps one
/// `DispatchCommands` from dispatch to dispatch allocates none of it again once it holds as
/// much. On an error `commands` holds no dispatch's commands.
pub fn instantiate_dispatch_into(
&self,
state: &BindState,
dispatch: &Dispatch,
commands: &mut DispatchCommands,
) -> Result<(), BindError> {
let t = self.compute_template("instantiate_dispatch")?;
let flat = self.variant.flat_grid;
let ragged = Ragged::of(&self.variant);
@@ -874,7 +926,7 @@ impl BindingPlan {
r.multi = true;
}
}
instantiate(t, planned, state, dispatch, records)
instantiate(t, planned, (state, dispatch), records, commands)
}
/// Whether [`instantiate_dispatch`](Self::instantiate_dispatch)'s commands may read a value the
@@ -952,7 +1004,15 @@ impl BindingPlan {
for r in &mut planned.regions {
r.multi = true;
}
instantiate(t, planned, state, &dispatch, Records::Replay)
let mut commands = DispatchCommands::none();
instantiate(
t,
planned,
(state, &dispatch),
Records::Replay,
&mut commands,
)?;
Ok(commands)
}
/// The variant of the pipeline a compute dispatch runs on: the plan's
@@ -1068,14 +1128,27 @@ fn region_specialization(
multi: bool,
reach: bool,
) -> SpecializationKey {
let mut key = SpecializationKey::new();
region_specialization_into(t, (local, multi, reach), &mut key);
key
}
/// [`region_specialization`]'s key of a region of `local` threads, `multi` and `reach`, written
/// over `key` in the storage its lists hold ([`spec_key_into`]).
fn region_specialization_into(
t: &ComputeTemplate,
(local, multi, reach): ([u32; 3], bool, bool),
key: &mut SpecializationKey,
) {
let n: u64 = local.iter().map(|&x| u64::from(x)).product();
spec_key(&t.spec, |k| match k {
let value = |k| match k {
SpecKey::LocalSize(a) => Some(u64::from(local[a as usize])),
SpecKey::FlatLocalSize => Some(n),
SpecKey::MultiRegion => Some(u64::from(multi)),
SpecKey::StageInReach => Some(u64::from(reach)),
other => t.fixed.iter().find(|(key, _)| *key == other).map(|f| f.1),
})
};
spec_key_into(&t.spec, value, key);
}
/// The stride the compute encoder binds kernel buffer `index` with in `state`
@@ -1221,13 +1294,27 @@ enum Records {
/// The commands of `dispatch` planned as `planned`, whose region records and group counts
/// `records` writes: for a device-replay variant (whose `dispatch` is the `ThreadgroupsIndirect` of
/// its threadgroup size) the region reads the replay's arguments and no root table is built.
/// Written over `out`: each of its fields set, its vectors cleared or their values overwritten in
/// place (each region's specialization and push write, the argument table's bytes), never
/// replaced. On an error `out` holds no dispatch's commands.
fn instantiate(
t: &ComputeTemplate,
planned: Planned,
state: &BindState,
dispatch: &Dispatch,
(state, dispatch): (&BindState, &Dispatch),
records: Records,
) -> Result<DispatchCommands, BindError> {
out: &mut DispatchCommands,
) -> Result<(), BindError> {
let DispatchCommands {
regions: regions_out,
descriptor_bytes,
descriptor_ranges,
extents,
push_holes,
region_record: region_record_out,
root_table: root_table_out,
indirect_clamp: indirect_clamp_out,
uses,
} = out;
let replay = records == Records::Replay;
// A kernel that reads the stage-in region needs the encoder's.
let region = match t.stage_in_region {
@@ -1239,18 +1326,76 @@ fn instantiate(
),
};
let (push_start, push_size) = t.push_range.unwrap_or((0, 0));
let mut push = vec![0u8; push_size as usize];
let mut table = vec![0u8; t.table.map_or(0, |(_, _, size)| size as usize)];
let compute = vk::ShaderStageFlags::COMPUTE;
// One region of the commands per planned region, each over the one a dispatch before left
// at its place where there is one.
let count = planned.regions.len();
regions_out.truncate(count);
while regions_out.len() < count {
regions_out.push(DispatchRegion {
specialization: SpecializationKey::new(),
group_count: [0; 3],
push_constants: Vec::new(),
indirect: None,
stage_flags: vk::PipelineShaderStageCreateFlags::empty(),
required_subgroup_size: None,
});
}
// Each region's one push write, where the plan pushes bytes.
for r in regions_out.iter_mut() {
let writes = &mut r.push_constants;
writes.truncate(usize::from(push_size > 0));
if push_size > 0 && writes.is_empty() {
writes.push(PushConstantWrite {
stages: compute,
offset: push_start,
bytes: Vec::new(),
});
}
for w in writes.iter_mut() {
w.stages = compute;
w.offset = push_start;
}
}
// The push bytes every region shares, written in the first region's write (a grid of no
// region pushes none, and writes them apart), and the argument table, in the first
// descriptor bytes.
let mut apart = Vec::new();
let push = match regions_out
.first_mut()
.and_then(|r| r.push_constants.first_mut())
{
Some(write) => zeroed(&mut write.bytes, push_size as usize),
None => zeroed(&mut apart, push_size as usize),
};
descriptor_bytes.truncate(usize::from(t.table.is_some()));
let mut no_table = Vec::new();
let table = match t.table {
Some((set, binding, size)) => {
if descriptor_bytes.is_empty() {
descriptor_bytes.push(DescriptorBytes {
set,
binding,
bytes: Vec::new(),
});
}
let written = &mut descriptor_bytes[0];
written.set = set;
written.binding = binding;
zeroed(&mut written.bytes, size as usize)
}
None => &mut no_table,
};
// Buffer slots: descriptor ranges and residuals, root entries, extents; texel buffers.
let (mut descriptor_ranges, mut extents) = (Vec::new(), Vec::new());
let bound = bind_buffers(&t.buffers, state, &mut descriptor_ranges, &mut extents)?;
descriptor_ranges.clear();
extents.clear();
let bound = bind_buffers(&t.buffers, state, descriptor_ranges, extents)?;
descriptor_ranges.extend(texel_ranges(&t.resources, state)?);
// The root table: the Psb entries and the resident set.
let mut push_holes = Vec::new();
let root_table = match t.root_first {
push_holes.clear();
*root_table_out = match t.root_first {
// A replay variant's root table is its command's slot table.
Some(_) if replay => None,
Some(first) => {
@@ -1307,13 +1452,23 @@ fn instantiate(
field => slot_field(field, &bound.residuals, &t.resources, state)
.ok_or_else(|| internal(format!("a compute push field {field:?}")))?,
};
put(&mut push, push_start, &mut table, f.loc, &bytes)?;
put(push, push_start, table, f.loc, &bytes)?;
}
let region_field = t
.fields
.iter()
.find(|f| f.field == PushField::DispatchRegion)
.map(|f| f.loc);
// Every later region's push bytes start as the first's.
if let Some((first, rest)) = regions_out.split_first_mut() {
if let Some(shared) = first.push_constants.first() {
for r in rest {
for w in &mut r.push_constants {
w.bytes.clone_from(&shared.bytes);
}
}
}
}
// Regions.
let Planned {
@@ -1324,19 +1479,21 @@ fn instantiate(
..
} = planned;
let reach = stage_in_reach(t, region, grid, state);
let mut regions = Vec::with_capacity(planned.len());
for r in planned {
let mut bytes = push.clone();
for (r, out) in planned.into_iter().zip(regions_out.iter_mut()) {
if let Some(loc) = region_field {
let b = match nonuniform {
true => nonuniform_region_bytes(r.base, grid, nominal),
false => region_bytes(r.base, grid, nominal),
}
.ok_or_else(|| internal("an unpackable nominal threadgroup size"))?;
put(&mut bytes, push_start, &mut [], loc, &b)?;
let bytes = match out.push_constants.first_mut() {
Some(write) => &mut write.bytes[..],
None => &mut [],
};
put(bytes, push_start, &mut [], loc, &b)?;
}
let specialization = region_specialization(t, r.local, r.multi, reach);
let indirect = match *dispatch {
region_specialization_into(t, (r.local, r.multi, reach), &mut out.specialization);
out.indirect = match *dispatch {
Dispatch::ThreadgroupsIndirect { .. } if replay => Some(IndirectArgs::Replay),
Dispatch::ThreadgroupsIndirect { indirect, .. } => {
Some(if records == Records::Binder && needs_clamp(&t.local) {
@@ -1347,26 +1504,13 @@ fn instantiate(
}
_ => None,
};
regions.push(DispatchRegion {
specialization,
group_count: r.groups,
push_constants: if push_size == 0 {
Vec::new()
} else {
vec![PushConstantWrite {
stages: compute,
offset: push_start,
bytes,
}]
},
indirect,
stage_flags: region_flags(&t.local, r.local),
required_subgroup_size: t.local.required_subgroup_size,
});
out.group_count = r.groups;
out.stage_flags = region_flags(&t.local, r.local);
out.required_subgroup_size = t.local.required_subgroup_size;
}
// A preprocess checks its group counts against the limit.
let indirect_clamp = match *dispatch {
*indirect_clamp_out = match *dispatch {
Dispatch::ThreadgroupsIndirect { indirect, .. }
if records == Records::Binder && needs_clamp(&t.local) =>
{
@@ -1385,7 +1529,7 @@ fn instantiate(
// A direct dispatch on a flat variant reads its region from the record the consumer writes
// (base 0, the dispatch's threadgroup size, and the grid in threads), since the flat lowering
// reads the record by address wherever its group counts come from.
let region_record = match (records, *dispatch) {
*region_record_out = match (records, *dispatch) {
(Records::Flat, Dispatch::ThreadgroupsIndirect { .. }) | (Records::Binder, _) => None,
(Records::Flat, _) => Some(
region_bytes([0; 3], grid, nominal)
@@ -1393,54 +1537,32 @@ fn instantiate(
),
(Records::Replay, _) => None,
};
let mut descriptor_bytes = match t.table {
Some((set, binding, _)) => vec![DescriptorBytes {
set,
binding,
bytes: table,
}],
None => Vec::new(),
};
descriptor_bytes.extend(crate::bind::heap::table_bytes(&t.resources, state)?);
let uses = match *dispatch {
Dispatch::ThreadgroupsIndirect { .. } => {
let (class, stages) = if indirect_clamp.is_some() {
(
AccessClass::Storage,
vk::PipelineStageFlags2::COMPUTE_SHADER,
)
} else {
(
AccessClass::Indirect,
vk::PipelineStageFlags2::DRAW_INDIRECT,
)
};
vec![ResourceUse {
resource: UseTarget::Indirect,
access: AccessSet::READ,
class,
stages,
range: Some(ByteRange {
offset: 0,
len: u64::from(IndirectClamp::SCRATCH_BYTES),
}),
}]
}
Dispatch::Threadgroups { .. }
| Dispatch::Threads { .. }
| Dispatch::ThreadgroupRange { .. } => Vec::new(),
};
Ok(DispatchCommands {
regions,
descriptor_bytes,
descriptor_ranges,
extents,
push_holes,
region_record,
root_table,
indirect_clamp,
uses,
})
uses.clear();
if let Dispatch::ThreadgroupsIndirect { .. } = *dispatch {
let (class, stages) = if indirect_clamp_out.is_some() {
(
AccessClass::Storage,
vk::PipelineStageFlags2::COMPUTE_SHADER,
)
} else {
(
AccessClass::Indirect,
vk::PipelineStageFlags2::DRAW_INDIRECT,
)
};
uses.push(ResourceUse {
resource: UseTarget::Indirect,
access: AccessSet::READ,
class,
stages,
range: Some(ByteRange {
offset: 0,
len: u64::from(IndirectClamp::SCRATCH_BYTES),
}),
});
}
Ok(())
}
/// Whether an indirect dispatch needs the clamp prepass: some axis of the device's group-count
@@ -268,6 +268,46 @@ fn dispatch_threads_edges_become_multi_region_dispatches() {
.is_empty());
}
/// `instantiate_dispatch_into` over commands a dispatch before left, of more regions, fewer, none,
/// another state: each time the commands a fresh `instantiate_dispatch` gives, in the storage
/// kept (a region's specialization written over a key of as many constants allocates nothing).
#[test]
fn instantiating_over_kept_commands_gives_a_fresh_instantiation() {
let plan = compute_plan(&template(), VariantKey::new());
let threads = |threads| Dispatch::Threads {
threads,
threads_per_group: [16, 2, 1],
};
let split = Dispatch::Threadgroups {
groups: [70000, 1, 2],
threads_per_group: [1, 1, 1],
};
let dispatches = [
(threads([40, 3, 1]), 0),
(threads([64, 4, 1]), 64),
(split, 0),
(threads([0, 4, 1]), 64),
(threads([40, 3, 1]), 128),
(threads([64, 4, 1]), 128),
];
let mut kept = plan
.instantiate_dispatch(&state(0), &threads([64, 4, 1]))
.expect("first");
for (at, (d, offset)) in dispatches.into_iter().enumerate() {
let s = state(offset);
let data = kept.regions.first().map(|r| r.specialization.data.as_ptr());
plan.instantiate_dispatch_into(&s, &d, &mut kept)
.expect("into");
let fresh = plan.instantiate_dispatch(&s, &d).expect("fresh");
assert_eq!(kept, fresh, "dispatch {at}");
// The first region's key, kept, is written in the storage it held.
let first = kept.regions.first().map(|r| r.specialization.data.as_ptr());
if let (Some(was), Some(now)) = (data, first) {
assert_eq!(was, now, "dispatch {at}: the key's storage");
}
}
}
#[test]
fn group_counts_above_the_limit_are_split_with_their_base() {
let t = template();
+1 -1
View File
@@ -5446,7 +5446,7 @@ fn reused<T>(list: &mut Vec<T>, at: usize, made: impl FnOnce() -> T) -> &mut T {
}
/// `bytes`, made `len` zero bytes in the storage it holds.
fn zeroed(bytes: &mut Vec<u8>, len: usize) -> &mut Vec<u8> {
pub(crate) fn zeroed(bytes: &mut Vec<u8>, len: usize) -> &mut Vec<u8> {
bytes.clear();
bytes.resize(len, 0);
bytes
+13 -1
View File
@@ -357,6 +357,19 @@ pub(crate) fn spec_key(
value: impl Fn(SpecKey) -> Option<u64>,
) -> SpecializationKey {
let mut key = SpecializationKey::new();
spec_key_into(layout, value, &mut key);
key
}
/// [`spec_key`]'s key, written over `key` in the storage its two lists hold: a key written over
/// one of as many constants allocates nothing.
pub(crate) fn spec_key_into(
layout: &[SpecConstant],
value: impl Fn(SpecKey) -> Option<u64>,
key: &mut SpecializationKey,
) {
key.entries.clear();
key.data.clear();
for (at, c) in layout.iter().enumerate() {
let Some(v) = value(c.key) else { continue };
// Room for the rest of the layout at once, rather than growing a push at a time: a
@@ -376,7 +389,6 @@ pub(crate) fn spec_key(
key.data
.extend_from_slice(&v.to_le_bytes()[..size as usize]);
}
key
}
fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<BindingPlan, BindError> {
+1 -1
View File
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 524;
/// 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 = 2474;
pub const RUNTIME_VERSION: u32 = 2475;
/// 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
@@ -2940,6 +2940,7 @@ field metal2vulkan-runtime::WorkCounts.dispatch_uses_tracked pub dispatch_uses_t
field metal2vulkan-runtime::WorkCounts.dispatches_from_set_aside pub dispatches_from_set_aside: u64
field metal2vulkan-runtime::WorkCounts.dispatches_instantiated pub dispatches_instantiated: u64
field metal2vulkan-runtime::WorkCounts.dispatches_instantiated_as_before pub dispatches_instantiated_as_before: u64
field metal2vulkan-runtime::WorkCounts.dispatches_instantiated_in_place pub dispatches_instantiated_in_place: u64
field metal2vulkan-runtime::WorkCounts.dispatches_planned_across_grids pub dispatches_planned_across_grids: u64
field metal2vulkan-runtime::WorkCounts.dispatches_planned_as_before pub dispatches_planned_as_before: u64
field metal2vulkan-runtime::WorkCounts.dispatches_pushing_set_zero pub dispatches_pushing_set_zero: u64
@@ -9536,6 +9537,7 @@ method metal2vulkan::bind::BindingPlan::heap_elements pub fn heap_elements(&self
method metal2vulkan::bind::BindingPlan::heap_slots pub fn heap_slots(&self) -> impl Iterator<Item = SlotRef> + '_
method metal2vulkan::bind::BindingPlan::heap_tables_into pub fn heap_tables_into(&self, state: &BindState, tables: &mut Vec<crate::bind::instantiate::DescriptorBytes>) -> Result<(), BindError>
method metal2vulkan::bind::BindingPlan::instantiate_dispatch pub fn instantiate_dispatch(&self, state: &BindState, dispatch: &Dispatch) -> Result<DispatchCommands, BindError>
method metal2vulkan::bind::BindingPlan::instantiate_dispatch_into pub fn instantiate_dispatch_into(&self, state: &BindState, dispatch: &Dispatch, commands: &mut DispatchCommands) -> Result<(), BindError>
method metal2vulkan::bind::BindingPlan::instantiate_draw pub fn instantiate_draw(&self, state: &BindState, draw: &DrawCall) -> Result<DrawCommands, BindError>
method metal2vulkan::bind::BindingPlan::instantiate_draw_apart_into pub fn instantiate_draw_apart_into(&self, state: &BindState, draw: &DrawCall, commands: &mut DrawCommands) -> Result<(), BindError>
method metal2vulkan::bind::BindingPlan::instantiate_draw_into pub fn instantiate_draw_into(&self, state: &BindState, draw: &DrawCall, commands: &mut DrawCommands) -> Result<(), BindError>
Can't render this file because it is too large.
+4 -1
View File
@@ -1692,7 +1692,10 @@ reads the buffer's bytes inside the range.
`instantiate_draw_into` writes the same commands over a `DrawCommands` you keep, in the storage
its vectors already hold: keep one from draw to draw (`DrawCommands::default()` to start) and the
draws allocate none of it again once it holds as much.
draws allocate none of it again once it holds as much. `instantiate_dispatch_into` does the same
for a compute dispatch over a `DispatchCommands` you keep (one `instantiate_dispatch` made, to
start): each region's specialization and push bytes, and the argument table's, are written in the
storage the commands before held.
`dispatch_reads` says which slot classes' bound values, past their shape, a compute plan's
`instantiate_dispatch` may read: buffer slots always; texture slots only where the plan binds a