RUNTIME 2263: an execution's compute commands order by their records' barriers alone, in either kind of encoder

Metal's reference for MTLIndirectComputeCommand concurrentDispatchThreadgroups (and
concurrentDispatchThreads): "Compute commands encoded into an indirect command buffer don't
automatically serialize access to resources with other commands in the indirect command buffer.
Use barriers to serialize access to resources within a range of commands." and "If dispatchType
is serial, the compute command encoder adds a barrier before and after the range of commands. If
dispatchType is concurrent, then the compute command encoder does nothing". MSL 6.17.2: "In an
ICB, dispatches are always concurrent." The runtime ordered a serial encoder's execution as the
encoder's own dispatches: a barrier wherever their uses met (the host step and commit's
recording) or between every two commands (the GPU form).

Now a command runs after the earlier ones of its range only where its record sets a barrier, in
either kind of encoder; the segment's barriers from everything before and to everything after it
are the serial encoder's before and after the range (Execute loses `ordered`; ComputeKey loses
`ordered`, so a kept chunk runs in either kind of encoder; the GPU form puts a barrier between
two commands only where a route may set one in the records, CommandWrites::BARRIER; the
tracker's ordered_everything goes). docs/API.md's accepted difference quotes Metal's text. Not a
speed-for-accuracy choice (Metal's contract), so no FAST-PATHS row.

Also: kept_commands' compute tests note each command's own output window as an apart write
(the layer reported write-after-write between disjoint windows); trail_gpu_forms requires a GPU
form's scratch in device-local memory only without unified memory (a Private buffer lies in
system memory before the carve-out by design on the 780M), fixing the 780M lane failure.

From steelbrain/icbbarrier (b3f5e50f94, 7c5e5e60b2, fdfc1e412a; icbinherit). Verified on potluck
at fdfc1e412a: lavapipe 275/278 (28026; the 3 failures were lvpfails-owned and fixed by RUNTIME
2261 on development), clippy plain/m2v_gpu/m2v_cpu_icd and rustdoc 0 (28027), negative control
27962 (both new tests fail on the old runtime). XTX and 780M legs: not run (um790 down), owed at
the next pin's device legs.
This commit is contained in:
Anees Iqbal committed 2026-11-13 23:41:05 -08:00
1 parent 799e3dcd0a
commit 1f20452b37
12 files changed
+220 -110

No files matched your search

+4 -2
View File
@@ -1313,7 +1313,10 @@ impl ComputeCommandEncoder {
/// buffers as they are now where `icb` inherits them, and the resources the encoder made
/// resident so far, which its buffers' addresses resolve against: an address in none misses,
/// reading zero and dropping writes, and the execution report counts it. The encoder's commands
/// before run before them and its commands after run after them.
/// before run before them and its commands after run after them. Among themselves the commands
/// run in no order but where a command's record sets a barrier (`set_barrier`), which orders it
/// after every earlier command of the range, whatever the encoder's dispatch type: Metal's
/// serial encoder adds a barrier before and after the range alone.
///
/// Refused, changing nothing (`Invalid`): a buffer of another device, a range that ends
/// past its size (`IndirectCommandBufferProblem::Range`), and, for a range that is not
@@ -1544,7 +1547,6 @@ impl ComputeCommandEncoder {
range,
pipeline,
table,
ordered: self.dispatch_type == DispatchType::Serial,
gate,
preprocess_gate,
check: check.map(|(check, needs)| (Mutex::new(check), needs)),
+23 -27
View File
@@ -46,19 +46,18 @@
//! [`FREE_STATES_UNORDERED`] where no barrier goes between the commands
//! ([`DISPATCHES_PAST_ORDERED`] past [`FREE_STATES_ORDERED`] where one does): past those the
//! host step runs the execution, as it does it faster ([`dispatches_run`]).
//! - **Order.** In a serial encoder, a barrier between every two commands
//! (`Barrier::between_dispatches`): the commands run in Metal's order, one after another, which
//! orders them wherever their uses meet, as the records' uses are GPU data. In a concurrent
//! encoder, Metal orders a command only after a barrier its record sets: where no route that
//! wrote the buffer's records may set one (`IndirectCommandBuffer::command_writes`, no
//! `CommandWrites::BARRIER`), the indirect dispatches go with no barrier between them, and else
//! with one between every two. A route encoded after the commit can still run before the
//! execution only where the execution's batch waits for an event its command buffer signals, so
//! its batch is held until then ([`Rerecord`]): where the buffer's records may set a barrier by
//! the time the batch is submitted, the commands are recorded again then, with the barriers, from
//! what the commit found (no work on the GPU is waited for). The generated-commands path runs
//! the commands of a segment its records leave without a barrier together, as Metal's concurrent
//! commands may run.
//! - **Order.** Metal orders a command after the earlier ones of the range only where its record
//! sets a barrier, in either kind of encoder (`indirect_execute.rs`, **Order**; a serial
//! encoder adds a barrier before and after the range alone, which the segment's own are): where
//! no route that wrote the buffer's records may set one (`IndirectCommandBuffer::command_writes`,
//! no `CommandWrites::BARRIER`), the indirect dispatches go with no barrier between them, and
//! else with one between every two (`Barrier::between_dispatches`). A route encoded after the
//! commit can still run before the execution only where the execution's batch waits for an
//! event its command buffer signals, so its batch is held until then ([`Rerecord`]): where the
//! buffer's records may set a barrier by the time the batch is submitted, the commands are
//! recorded again then, with the barriers, from what the commit found (no work on the GPU is
//! waited for). The generated-commands path runs the commands of a segment its records leave
//! without a barrier together, as Metal's commands may run.
//! - **Command predication.** An execution inside a block runs its preprocess by
//! `vkCmdDispatchIndirect` from a gate the step before it writes (`predication.rs`,
//! `Execute::preprocess_gate`): one invocation per command where the counter is 0, else none.
@@ -139,8 +138,8 @@ const FLAT_THREADS: u32 = 64;
pub(super) const MAX_DISPATCHES: u64 = 1 << 15;
/// The variants (pipeline states the records may name) an execution the indirect dispatches run
/// may have, whatever its commands, where no barrier goes between them (a concurrent encoder's
/// whose records no route may set a barrier in, the module's order): with them every count of
/// may have, whatever its commands, where no barrier goes between them (an execution whose
/// records no route may set a barrier in, the module's order): with them every count of
/// commands ran faster on the GPU alone than in the host step. Each variant costs every command
/// one more indirect dispatch, which MoltenVK encodes as a Metal dispatch the GPU runs even at a
/// zero group count; past these, [`DISPATCHES_PAST_UNORDERED`] bounds those dispatches. Measured
@@ -160,8 +159,8 @@ pub(super) const FREE_STATES_UNORDERED: usize = 4;
/// host step.
pub(super) const DISPATCHES_PAST_UNORDERED: u64 = 256;
/// [`FREE_STATES_UNORDERED`] where a barrier goes between every two commands (a serial encoder's,
/// or a concurrent one's whose records may set one): MoltenVK ends its Metal compute encoder at
/// [`FREE_STATES_UNORDERED`] where a barrier goes between every two commands (where the buffer's
/// records may set one): MoltenVK ends its Metal compute encoder at
/// each barrier, which the host step's commands pay too, so a variant's dispatches weigh less
/// against it. Measured as [`FREE_STATES_UNORDERED`] was: at 256 commands 0.79x with one variant,
/// 0.90x with eight, 0.94x with twelve, 0.96x with fourteen and 1.06x with sixteen; at 64
@@ -225,8 +224,8 @@ struct Total {
}
/// An execution `commit` recorded on the GPU alone by indirect dispatches with no barrier
/// between its commands, in a concurrent encoder, as no route that wrote its buffer's records
/// could set a barrier (the module's order): what `commit` found, kept until the batch is submitted
/// between its commands, as no route that wrote its buffer's records could set a barrier (the
/// module's order): what `commit` found, kept until the batch is submitted
/// or the execution is recorded again with the barriers, where a route encoded since may set one.
pub(super) struct Rerecord {
icb: IndirectCommandBuffer,
@@ -280,9 +279,9 @@ pub(super) fn record(
}
let device = command_buffer.device();
let residency = command_buffer.residency()?.kernel();
// A serial encoder orders its commands wherever their uses meet; a concurrent one only after
// a barrier a record sets.
let ordered = execute.ordered || execute.icb.command_writes().may(CommandWrites::BARRIER);
// A command runs after the earlier ones only where its record sets a barrier, in either kind
// of encoder (**Order**).
let ordered = execute.icb.command_writes().may(CommandWrites::BARRIER);
let Some(total) = total(device, execute, &residency, ordered)? else {
return Ok(None);
};
@@ -666,7 +665,7 @@ fn record_total(
let uses = variant_uses(residency, prepared, inherited.then_some(&execute.table))?;
let preprocess_uses = [reads(storage, 0..storage.length())];
let mut core = EncoderCore::segment(command_buffer, execute.ordered)?;
let mut core = EncoderCore::segment(command_buffer, false)?;
let compute = vk::PipelineStageFlags2::COMPUTE_SHADER;
let group_count = pre.group_count;
core.command(compute, &preprocess_uses, |raw, command_buffer| {
@@ -700,11 +699,8 @@ fn record_total(
}
}
});
// The preprocess's writes before the commands' preprocessing, indirect and shader reads; in a
// serial encoder the commands need no barrier of the tracker's after the preprocess's read of
// the records, which a command's resident write of the buffer would otherwise ask.
// The preprocess's writes before the commands' preprocessing, indirect and shader reads.
core.barrier(Barrier::everything());
core.uses().ordered_everything();
let made = match form {
Form::Generated => {
let commands = device
@@ -83,9 +83,13 @@
//! recorded on the GPU alone (`gpu_execute.rs`), its check having nothing to see, whose check a
//! route encoded since gives something to see takes the host step before its batch is submitted
//! ([`Execute::outgrown`]).
//! - **Order.** Between commands, the segment orders as the encoder orders its dispatches (a
//! serial encoder's where their uses meet; a concurrent one's not at all), and a command with
//! its barrier set runs after every earlier command of the segment.
//! - **Order.** Between commands, the segment orders nothing but where a command's record sets
//! its barrier: that command runs after every earlier command of the segment. So it does in
//! either kind of encoder, as Metal's commands do (`MTLIndirectComputeCommand`'s
//! `concurrentDispatchThreadgroups`: they "don't automatically serialize access to resources
//! with other commands in the indirect command buffer", and a serial encoder "adds a barrier
//! before and after the range of commands"): the segment's barriers from everything before it
//! and to everything after it are that serial encoder's.
mod kept;
@@ -165,8 +169,6 @@ pub(super) struct Execute {
pub(super) pipeline: Option<ComputePipelineState>,
/// The encoder's bound buffers where the buffer inherits them; else empty.
pub(super) table: ArgumentTable,
/// Whether the encoder runs its dispatches in encoded order.
pub(super) ordered: bool,
/// The check of the block of command predication it was encoded in, if any
/// (`predication.rs`): a host step records it, and nothing where the counter skips.
pub(super) gate: Option<HostGate>,
@@ -405,7 +407,7 @@ impl Execute {
) -> Result<RecordedSegment, Error> {
// Its host step inside a block of command predication that skips runs nothing.
if states.is_some() && self.gate.as_ref().is_some_and(HostGate::skips) {
return EncoderCore::segment(command_buffer, self.ordered)?.end_segment();
return EncoderCore::segment(command_buffer, false)?.end_segment();
}
// Every encoder's resident resources, as the command buffer's are at the commit.
let residency = command_buffer.residency()?.kernel();
@@ -415,7 +417,8 @@ impl Execute {
return self.record_kept(command_buffer, &residency, keeping);
}
}
let mut core = EncoderCore::segment(command_buffer, self.ordered)?;
// Its commands run in no order among themselves, but for a record's barrier.
let mut core = EncoderCore::segment(command_buffer, false)?;
// The host step's commands take the large-buffer form, whose variants `settle` made.
let forms = match states {
Some(_) => BufferForms::Large,
@@ -11,10 +11,11 @@
//! (`kept_commands.rs`, **From the second execution**): a range's first execution records as
//! one that keeps nothing.
//! - **The key.** A chunk is recorded from its records and from the inputs [`ComputeKey`] holds:
//! the inherited pipeline state, whether the encoder runs its dispatches in encoded order, and
//! the resources made resident (`Residency::kept_key`, one list an execution, compared whole
//! once a list its kept chunks hold: `kept_commands::ResidentMet`). A kept chunk runs again only
//! under an equal key.
//! the inherited pipeline state and the resources made resident (`Residency::kept_key`, one
//! list an execution, compared whole once a list its kept chunks hold:
//! `kept_commands::ResidentMet`). A kept chunk runs again only under an equal key, in either
//! kind of encoder: its commands order by their records' barriers alone (`indirect_execute.rs`,
//! **Order**).
//! - **Each chunk** runs its kept recording again, or records apart into a primary of its own
//! (from a context of its own where an execution ran it before, no write reaching it since,
//! else from its command buffer's own, kept by none), as a segment of its own
@@ -48,7 +49,6 @@ use std::sync::Arc;
#[derive(Clone, PartialEq)]
pub(super) struct ComputeKey {
pipeline: Option<ComputePipelineState>,
ordered: bool,
resident: ResidentKey,
}
@@ -86,7 +86,6 @@ impl Execute {
let (kept, read_at) = self.icb.kept_chunks(range.clone())?;
let key = ComputeKey {
pipeline: self.pipeline.clone(),
ordered: self.ordered,
resident: ResidentKey::new(residency.kept_key(command_buffer.device())),
};
Some(Keeping { key, kept, read_at })
@@ -219,7 +218,7 @@ impl Execute {
.filter(|binding| binding.names_buffer())
.map(|binding| binding.address);
let resolved = kept_commands::resolutions(addresses, residency);
let mut core = EncoderCore::segment(command_buffer, self.ordered)?;
let mut core = EncoderCore::segment(command_buffer, false)?;
let mut misses = 0u32;
let forms = (residency, BufferForms::Bound);
self.dispatch(&mut core, commands.iter(), forms, &mut misses)?;
@@ -46,10 +46,11 @@
//! draw at its arguments). Its `vertex_id`, `instance_id` and `base_instance` are the command's
//! own, as Metal's, and so are the vertex and instance its attributes step by.
//! - **Scratch** (`bind::DrawReplayLayout`). A buffer of the runtime's own in `Private` memory
//! (`Device::scratch_buffer`), device-local, held until the command buffer completes: the GPU
//! alone reads and writes it, the merge passes' serial loops many times a command and every
//! draw its slot tables and arguments, where the upload arena on a discrete GPU is system
//! memory, read across the bus (`upload.rs`). The host writes its head alone
//! (`Device::scratch_buffer`), device-local without unified memory (with it, where the device
//! places `Private` memory: `memory.rs`'s `candidates`), held until the command buffer
//! completes: the GPU alone reads and writes it, the merge passes' serial loops many times a
//! command and every draw its slot tables and arguments, where the upload arena on a discrete
//! GPU is system memory, read across the bus (`upload.rs`). The host writes its head alone
//! (`DrawReplayLayout::uploaded`: the parameters, the resident root table and its set, their
//! extents, the encoder's buffers' root entries where they are inherited, and a merged
//! replay's header) into a region of the command
@@ -1,8 +1,8 @@
//! The encoder trail's GPU forms (`encoder_trail.rs`, **GPU forms**): an execution of render
//! commands the GPU wrote (a blit's copy of commands the CPU encoded) through a range read from a
//! buffer, which `commit` records in its merged GPU form (`render/executions/gpu.rs`), is named by
//! its shape, and its scratch, which lies in device-local memory
//! (`WorkCounts::gpu_form_device_local_bytes`), reads through the GPU's copy of it as the GPU
//! its shape, and its scratch, which lies where the device places `Private` memory (device-local
//! without unified memory: `WorkCounts::gpu_form_device_local_bytes`), reads through the GPU's copy of it as the GPU
//! left it once the command buffer completed: the range the GPU copied, the merged draw's
//! corners, the arguments of the commands inside the range and the most of them, and status
//! words of no fault; of draws of primitives, and of indexed draws over many blocks of the merge
@@ -146,9 +146,20 @@ fn executed_through_range(
if forms.is_empty() && counts.gpu_form_commands == 0 {
eprintln!("TRAIL-GPU-FORMS: the device records no execution in its GPU form");
} else {
// The scratch is `Private` memory, which lies where the device places it (`memory.rs`'s
// `candidates`): device-local without unified memory; with it, a type that is not
// device-local first where the device has one (a Radeon 780M's system memory beside its
// carve-out), which counts nothing.
let private = device.scratch_buffer(16).unwrap();
let device_local = private.own_pages_device_local() == Some(true);
assert!(
device_local || device.properties().has_unified_memory,
"a `Private` buffer outside device-local memory without unified memory"
);
assert_eq!(
local > 0,
"a GPU form's scratch outside device-local memory"
device_local,
"a GPU form's scratch lies where the device places `Private` memory"
);
}
forms
@@ -1554,13 +1554,6 @@ impl<K: Copy + Ord + Hash> EncoderUses<K> {
self.parts.push(Part::new());
}
/// Note a [`Barrier::everything`] recorded after the commands so far: every stage's every
/// access before it happens before every later command's, so a later command needs no barrier
/// after them. The part goes on: its summary keeps their uses.
pub(super) fn ordered_everything(&mut self) {
self.inside.clear();
}
/// The summary of the ended encoder, its parts joined (an encoder of one part: its part's).
pub(super) fn finish(self) -> Summary<K> {
self.finish_parts()
@@ -15,16 +15,21 @@
//! buffer writes before the execution; `sums` at a non-zero offset; `multiplier` bound at one
//! offset and moved by `setBufferOffset:` before the call; and `bias` inline bytes
//! (`setBytes:`).
//!
//! The host step runs an execution whose range a buffer holds, and orders its commands by their
//! records' barriers alone, in a serial encoder as in a concurrent one (the runtime's
//! `indirect_execute.rs`, **Order**): Metal's serial encoder adds a barrier before and after the
//! range of commands alone.
use super::degrade_notices::{counts, on_device_with};
use super::dispatch_executions::ran_flat;
use super::dispatch_executions::{barriers, own_barriers, ran_flat};
use super::indirect_host_steps::{complete, HOST_STEPS};
use super::render_executions::icb;
use super::render_inherited_buffers::reasons;
use super::{at_plan, buffer_with};
use crate::air_library::AirLibrary;
use crate::candidate::runtime_case::read_buffer;
use metal2vulkan::metal::{IndirectCommandType, ResourceUsage};
use metal2vulkan::metal::{DispatchType, IndirectCommandType, ResourceUsage};
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
use metal2vulkan_runtime::{
@@ -95,14 +100,31 @@ fn state(device: &Device, library: &Library, name: &str) -> ComputePipelineState
.unwrap()
}
/// How [`run`] executes the commands: in an encoder of `dispatch_type`, the range given in the
/// call, or, where `ranged`, read from a buffer (`execute_commands_in_buffer_indirect`), which the
/// host step runs.
#[derive(Clone, Copy, Debug)]
struct Encoding {
dispatch_type: DispatchType,
ranged: bool,
}
/// A serial encoder's execution of the range in the call.
const GIVEN: Encoding = Encoding {
dispatch_type: DispatchType::Serial,
ranged: false,
};
/// `writer` (`cid_encode`) writes [`COMMANDS`] commands into a buffer that inherits the encoder's
/// state and buffers, then an encoder executes them with `count` (`cid_count`) and its buffers:
/// what `sums` holds, the records the host read across the run, whether the command buffer ran a
/// flat variant (the GPU alone's execution record), and the host steps recorded.
/// state and buffers, then an encoder executes them as `encoding` says with `count` (`cid_count`)
/// and its buffers: what `sums` holds, the records the host read across the run, whether the
/// command buffer ran a flat variant (the GPU alone's execution record), the host steps recorded,
/// and the pipeline barriers recorded.
fn run(
device: &Device,
(writer, count): (&ComputePipelineState, &ComputePipelineState),
) -> (Vec<u32>, (u64, bool, u64)) {
encoding: Encoding,
) -> (Vec<u32>, (u64, bool, u64, u64)) {
let mut descriptor = IndirectCommandBufferDescriptor::new();
descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH;
descriptor.inherit_pipeline_state = true;
@@ -129,9 +151,12 @@ fn run(
let sums_bytes = 4 * (1 + MOST);
let sums = buffer_with(device, &at(SUMS_AT, &vec![0; sums_bytes as usize])).unwrap();
let multiplier = buffer_with(device, &at(MULTIPLIER_AT, &words([MULTIPLIER]))).unwrap();
// The execution range (location 0, length `COMMANDS`) a ranged execution reads.
let range = buffer_with(device, &words([0, COMMANDS as u32])).unwrap();
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let before = device.work_counts();
let barriers_before = barriers(device);
let mut blit = command_buffer.blit_command_encoder().unwrap();
let length = input.length() - INPUT_AT;
blit.copy_from_buffer_to_buffer(&staged, INPUT_AT, &input, INPUT_AT, length)
@@ -146,16 +171,20 @@ fn run(
let grid = Size::new(COMMANDS, 1, 1);
encoder.dispatch_threads(grid, grid).unwrap();
encoder.end_encoding().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
let mut encoder = command_buffer
.compute_command_encoder_with_dispatch_type(encoding.dispatch_type)
.unwrap();
encoder.set_compute_pipeline_state(count).unwrap();
encoder.set_buffer(Some(&input), INPUT_AT, 0).unwrap();
encoder.set_buffer(Some(&sums), SUMS_AT, 1).unwrap();
encoder.set_buffer(Some(&multiplier), 0, 2).unwrap();
encoder.set_buffer_offset(MULTIPLIER_AT, 2).unwrap();
encoder.set_bytes(&BIAS.to_le_bytes(), 3).unwrap();
encoder
.execute_commands_in_buffer(&icb, 0..COMMANDS)
.unwrap();
match encoding.ranged {
false => encoder.execute_commands_in_buffer(&icb, 0..COMMANDS),
true => encoder.execute_commands_in_buffer_indirect(&icb, &range, 0),
}
.unwrap();
encoder.end_encoding().unwrap();
complete(&command_buffer);
let after = device.work_counts();
@@ -163,6 +192,7 @@ fn run(
after.indirect_records_read - before.indirect_records_read,
ran_flat(&command_buffer),
after.host_steps_recorded - before.host_steps_recorded,
barriers(device) - barriers_before,
);
let bytes = read_buffer(&sums, SUMS_AT, sums_bytes).unwrap();
let words = bytes
@@ -195,8 +225,9 @@ fn inherited_buffers_dispatch_on_the_gpu_alone() {
&state(device, &library, "cid_encode"),
&state(device, &library, "cid_count"),
);
let (cold, (read, flat, _)) = run(device, states);
let (sums, counted) = run(device, states);
let (cold, (read, flat, _, _)) = run(device, states, GIVEN);
let (sums, (read_warm, flat_warm, steps, _)) = run(device, states, GIVEN);
let counted = (read_warm, flat_warm, steps);
let notices = messages.take_notices();
assert_eq!(
(read, flat),
@@ -217,3 +248,45 @@ fn inherited_buffers_dispatch_on_the_gpu_alone() {
});
}
}
/// The host step orders the commands by their records' barriers alone, in a serial encoder as in a
/// concurrent one (the module docs): an execution whose range a buffer holds, of commands that
/// each add to the inherited `sums` (their uses meet, as a serial encoder's own dispatches' would
/// need a barrier between every two), runs in the host step and computes what Metal computes in
/// both, and, once the states' pipelines and the queue's kept barriers are made (a first run of
/// each), records as many barriers in the serial encoder as in the concurrent one: none between
/// its commands, none of whose records sets one.
#[test]
fn a_host_step_orders_the_commands_by_their_barriers_alone() {
on_device_with(at_plan, |device, messages| {
let bitcode = llvm_assemble(&engine_dir().join("icb_inherited_dispatches.ll")).unwrap();
let library = device.new_library_with_air(&bitcode).unwrap();
let states = (
&state(device, &library, "cid_encode"),
&state(device, &library, "cid_count"),
);
let mut taken = Vec::new();
for dispatch_type in [DispatchType::Serial, DispatchType::Concurrent] {
let encoding = Encoding {
dispatch_type,
ranged: true,
};
let (cold, _) = run(device, states, encoding);
assert_eq!(cold, expected(), "{dispatch_type:?}: the first run");
let at = format!("{dispatch_type:?}");
taken.push(own_barriers(device, &at, || {
let (sums, (_, flat, steps, barriers)) = run(device, states, encoding);
assert_eq!(sums, expected(), "{at}");
assert_eq!((flat, steps), (false, 1), "{at}: in the host step");
barriers
}));
}
assert_eq!(
taken[0], taken[1],
"no barrier between the commands in the serial encoder, as in the concurrent one: \
{taken:?}"
);
let notices = counts(&messages.take_notices());
assert!(notices.contains_key(&HOST_STEPS[0]), "{notices:?}");
});
}
@@ -10,8 +10,9 @@
//!
//! - each command its own state, group count and buffers, a command never written and a reset
//! command nothing, in a serial and in a concurrent encoder, with commands times states indirect
//! dispatches and nothing announced; the serial encoder's with a barrier between every two
//! commands, the concurrent encoder's, whose records no route could set a barrier in, with none;
//! dispatches and nothing announced; with no barrier between the commands in either encoder, as
//! no route could set a barrier in the records (Metal's serial encoder adds a barrier before and
//! after the range alone);
//! - a concurrent encoder's execution whose buffer's records the CPU sets a barrier in after the
//! commit, before its batch is submitted (it waits for an event), recorded again with the
//! barriers, still on the GPU alone;
@@ -358,7 +359,7 @@ fn dispatches_indirect(device: &Device) -> u64 {
}
/// The pipeline barriers `device` replayed so far.
fn barriers(device: &Device) -> u64 {
pub(super) fn barriers(device: &Device) -> u64 {
device.work_counts().commands_recorded.cmd_pipeline_barrier
}
@@ -383,7 +384,7 @@ const WINDOW_RUNS: usize = 3;
/// uncounted runs before it did not, and record it to keep, its barriers counted with the
/// commands'. That run is not counted, and the window runs again, at most [`WINDOW_RUNS`] times:
/// a list recorded again at each of its uses fails every run.
fn own_barriers(device: &Device, at: &str, mut window: impl FnMut() -> u64) -> u64 {
pub(super) fn own_barriers(device: &Device, at: &str, mut window: impl FnMut() -> u64) -> u64 {
for _ in 0..WINDOW_RUNS {
let kept_before = kept_recorded(device);
let counted = window();
@@ -436,9 +437,10 @@ const STEPPED: [Degradation; 2] = [HOST_STEPS[0], Degradation::SplitDispatch];
/// Every command runs its own state, group count and buffers, and the unwritten and reset ones
/// nothing, in a serial and in a concurrent encoder: on the GPU alone, one indirect dispatch per
/// command and state, the execution record listing the flat variants, nothing announced. The
/// serial encoder's commands take a barrier between every two, the concurrent encoder's none: no
/// route set a barrier in the buffer's records. Both encoders run twice, and the second time is
/// command and state, the execution record listing the flat variants, nothing announced. Neither
/// encoder's commands take a barrier between them, as no route set a barrier in the buffer's
/// records: the serial encoder records as many barriers as the concurrent one, its barriers before
/// and after the range alone. Both encoders run twice, and the second time is
/// counted: the first records the queue's kept barrier command buffers ([`kept_recorded`]), and
/// the second counts a run that recorded none ([`own_barriers`]), so its barriers are the
/// commands' and their encoder's own.
@@ -485,9 +487,9 @@ fn each_command_runs_its_own_state_and_group_count() {
}
}
assert_eq!(
ordered[0] - ordered[1],
COMMANDS - 1,
"a barrier between every two commands in the serial encoder alone: {ordered:?}"
ordered[0], ordered[1],
"no barrier between the commands in the serial encoder, as in the concurrent one: \
{ordered:?}"
);
announced(device, messages, &[]);
});
@@ -564,7 +566,7 @@ fn a_copied_record_runs_its_released_state_s_program_on_the_gpu_alone() {
/// A concurrent encoder's execution recorded with no barrier between its commands is recorded
/// again with them where the CPU sets a barrier in one of the buffer's records after the commit,
/// before its batch is submitted (the batch waits for an event the CPU signals after the set): the
/// commands run on the GPU alone, with as many barriers as the serial encoder's, and write what
/// commands run on the GPU alone, with a barrier between every two, and write what
/// Metal computes. Without the set, none. A first execution without the set, not counted, records
/// the queue's kept barrier command buffers ([`kept_recorded`]); the counted ones count a run that
/// recorded none ([`own_barriers`]), so their barriers are the commands' and their encoder's own.
@@ -683,28 +685,34 @@ fn a_rebind_before_the_first_submission_reaches_the_execution_s_records_as_they_
/// so both bounds fall below the replay's 64 variants (`bind::MAX_REPLAY_VARIANTS`).
const BOUNDED: u64 = 2 * COMMANDS;
/// The most live states an execution of [`BOUNDED`] commands runs with on the GPU alone, as
/// The most live states an execution of [`BOUNDED`] commands runs with on the GPU alone, in an
/// encoder of its dispatch type, the CPU setting a barrier in a record or not, as
/// `runtime/gpu_execute.rs`'s `dispatches_run` bounds them: where its commands go with no barrier
/// between them (a concurrent encoder's, whose records no route could set a barrier in), four
/// free and 256 dispatches past them (`FREE_STATES_UNORDERED`, `DISPATCHES_PAST_UNORDERED`); where
/// they go with one (a serial encoder's), twelve and 512.
const MOST_STATES: [(DispatchType, u64); 2] = [
(DispatchType::Concurrent, 4 + 256 / BOUNDED),
(DispatchType::Serial, 12 + 512 / BOUNDED),
/// between them (whose records no route set a barrier in, in either encoder), four free and 256
/// dispatches past them (`FREE_STATES_UNORDERED`, `DISPATCHES_PAST_UNORDERED`); where they go with
/// one (a record's barrier set), twelve and 512.
const MOST_STATES: [(DispatchType, bool, u64); 3] = [
(DispatchType::Concurrent, false, 4 + 256 / BOUNDED),
(DispatchType::Serial, false, 4 + 256 / BOUNDED),
(DispatchType::Serial, true, 12 + 512 / BOUNDED),
];
/// An execution whose records may name as many live states as the GPU-alone path takes for its
/// commands in its encoder's order runs on the GPU alone, one indirect dispatch per command and
/// state, announcing nothing; with one more state alive, which no record names, the host step
/// runs it, faster, with no indirect dispatch, announced once. Both write what Metal computes, in
/// a concurrent and in a serial encoder.
/// a concurrent and in a serial encoder, and in a serial one with a record's barrier set.
#[test]
fn an_execution_of_more_states_than_the_gpu_path_takes_runs_in_the_host_step() {
for (dispatch_type, most) in MOST_STATES {
for (dispatch_type, barrier, most) in MOST_STATES {
on_device(|device, messages| {
let queue = device.new_command_queue().unwrap();
for states in [most, most + 1] {
let setup = Setup::sized(device, BOUNDED);
if barrier {
let command = setup.icb.indirect_compute_command_at(3).unwrap();
command.set_barrier().unwrap();
}
// Alive with `supportIndirectCommandBuffers` past the two the records name.
let unnamed = mark_states(device, states - setup.states.len() as u64);
let command_buffer = queue.command_buffer().unwrap();
@@ -719,7 +727,7 @@ fn an_execution_of_more_states_than_the_gpu_path_takes_runs_in_the_host_step() {
.unwrap();
encoder.end_encoding().unwrap();
complete(&command_buffer);
let at = format!("{dispatch_type:?} of {states} states");
let at = format!("{dispatch_type:?}, barrier {barrier}, of {states} states");
let mut want = expected(0..COMMANDS as usize);
want.resize(BOUNDED as usize * WINDOW, 0);
assert_eq!(setup.output(), want, "{at}");
@@ -22,12 +22,16 @@
//! handler, which hears of every command once.
//!
//! And so do compute commands: `icb_replay_template`, command `c` binding its own parameters and
//! output windows, so every command's dispatch writes words of its own.
//! output windows, so every command's dispatch writes words of its own. The commands run in no
//! order among themselves, as Metal's do (their records set no barrier), each binding the output
//! from its window on: the layer's write-after-write between two of them passes as apart writes
//! (`apart_writes.rs`), and nothing else.
use super::apart_writes::{layer_reported_nothing_but_apart_writes, NotedWrites};
use super::degrade_notices::on_device;
use super::indirect_host_steps::complete;
use super::render_executions::icb;
use super::{buffer_with, read_buffer};
use super::{buffer_with, read_buffer, Messages};
use crate::air_library::AirLibrary;
use metal2vulkan::metal::{IndirectCommandType, PixelFormat, PrimitiveType, RenderStages};
use metal2vulkan::metal::{ResourceUsage, TextureUsage};
@@ -468,18 +472,19 @@ fn a_checked_execution_keeps_where_its_check_sees_nothing() {
}
/// What the compute executions dispatch with: the commands' state, each command's parameters
/// (16 bytes apart: command `c`'s are `c + 1` and `1000 c`), their output, and a queue.
/// Command `c`'s four threads write `(c + 1)(t + 1) + 1000 c` to word `t` of its 16-byte window
/// of the output.
/// (16 bytes apart: command `c`'s are `c + 1` and `1000 c`), their output, a queue, and the
/// device's messages, which each run's claim reads. Command `c`'s four threads write
/// `(c + 1)(t + 1) + 1000 c` to word `t` of its 16-byte window of the output.
struct Dispatches {
state: ComputePipelineState,
params: Buffer,
out: Buffer,
queue: CommandQueue,
messages: Messages,
}
impl Dispatches {
fn new(device: &Device) -> Dispatches {
fn new(device: &Device, messages: &Messages) -> Dispatches {
let bitcode = llvm_assemble(&engine_dir().join("icb_replay_template.ll")).unwrap();
let library = device.new_library_with_air(&bitcode).unwrap();
let kernel = library
@@ -500,6 +505,7 @@ impl Dispatches {
params: buffer_with(device, &params).unwrap(),
out: buffer_with(device, &vec![0; 16 * N as usize]).unwrap(),
queue: device.new_command_queue().unwrap(),
messages: messages.clone(),
}
}
@@ -535,7 +541,8 @@ impl Dispatches {
}
/// In a command buffer of its own, committed and waited for: the output zeroed, then a
/// compute encoder that makes the buffers resident and executes `range` of `icb`.
/// compute encoder that makes the buffers resident and executes `range` of `icb`; then the
/// layer reported nothing but the commands' apart writes (the module docs).
fn run(&self, icb: &IndirectCommandBuffer, range: Range<u64>) {
self.run_with(icb, range, None, None);
}
@@ -549,6 +556,12 @@ impl Dispatches {
checked: Option<Checked<'_>>,
handler: Option<ExecutedCommandsHandler>,
) {
// Each command of the range writes its own window, at most.
let mut writes = NotedWrites::new(&self.messages);
for c in range.clone() {
writes.dispatched(&self.out, 16 * c..16 * c + 16);
}
let claim = format!("compute commands {range:?}");
let command_buffer = self.queue.command_buffer().unwrap();
if let Some(handler) = handler {
command_buffer
@@ -576,6 +589,7 @@ impl Dispatches {
.unwrap();
encoder.end_encoding().unwrap();
complete(&command_buffer);
layer_reported_nothing_but_apart_writes(&self.messages, &claim, &writes);
}
/// The output's words.
@@ -605,8 +619,8 @@ fn dispatched(ran: impl IntoIterator<Item = u64>, params: impl Fn(u64) -> u64) -
/// execution after; and after a blit's reset of commands, no kept recording runs.
#[test]
fn compute_commands_run_their_kept_recordings_until_written() {
on_device(|device, _| {
let work = Dispatches::new(device);
on_device(|device, messages| {
let work = Dispatches::new(device, messages);
let icb = work.icb(device);
let all = dispatched(0..N, |c| c);
let first = counted(device, || work.run(&icb, 0..N));
@@ -649,8 +663,8 @@ fn compute_commands_run_their_kept_recordings_until_written() {
/// recorded under once, whole, however many chunks hold it.
#[test]
fn a_compute_execution_compares_its_resident_resources_once() {
on_device(|device, _| {
let work = Dispatches::new(device);
on_device(|device, messages| {
let work = Dispatches::new(device, messages);
let icb = work.icb(device);
let run = || compared(device, || work.run(&icb, 0..N));
assert_eq!(run(), [0, 0], "the first execution keeps nothing");
@@ -666,8 +680,8 @@ fn a_compute_execution_compares_its_resident_resources_once() {
/// chunks from its second execution, as an unchecked one does.
#[test]
fn a_checked_compute_execution_keeps_where_its_check_sees_nothing() {
on_device(|device, _| {
let work = Dispatches::new(device);
on_device(|device, messages| {
let work = Dispatches::new(device, messages);
let icb = work.icb(device);
let all = dispatched(0..N, |c| c);
let calls = Arc::new(AtomicU64::new(0));
@@ -732,8 +746,8 @@ fn an_inline_execution_reads_its_records_a_chunk_at_a_time() {
/// hearing of every command once.
#[test]
fn an_inline_compute_execution_reads_its_records_a_chunk_at_a_time() {
on_device(|device, _| {
let work = Dispatches::new(device);
on_device(|device, messages| {
let work = Dispatches::new(device, messages);
let icb = work.icb(device);
let all = dispatched(0..N, |c| c);
let run = || runs_read(device, || work.run(&icb, 0..N));
+1 -1
View File
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 522;
/// 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 = 2262;
pub const RUNTIME_VERSION: u32 = 2263;
/// 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
+14 -4
View File
@@ -5129,10 +5129,20 @@ each item named states the rule in full.
(`CommandBuffer::add_executed_commands_handler`, no Metal counterpart): a handler is called each
time the runtime reads an execution's records, at `commit`, in a host step, or not at all for an
execution the GPU alone runs.
- **An execution the GPU alone runs orders its commands one after another in a serial encoder**,
where Metal orders them only where their uses meet: the uses are the records', which the GPU
writes. In a concurrent encoder its commands run together where no route that wrote the records
may set a barrier (`IndirectCommandBuffer::command_writes`), and one after another otherwise.
- **An execution's commands order by their records' barriers alone, in either kind of
encoder**, as Metal states for `MTLIndirectComputeCommand`'s `concurrentDispatchThreadgroups`:
"Compute commands encoded into an indirect command buffer don't automatically serialize access
to resources with other commands in the indirect command buffer. Use barriers to serialize
access to resources within a range of commands. See setBarrier()." and "When you execute the
commands in an indirect command buffer, the dispatchType property of the compute command encoder
determines whether the compute command encoder adds additional barriers. If dispatchType is
serial, the compute command encoder adds a barrier before and after the range of commands. If
dispatchType is concurrent, then the compute command encoder does nothing, and you are
responsible for synchronizing access to resources." The runtime runs a command after the earlier
ones of the range where its record sets a barrier, and adds a barrier before and after the range
in either kind of encoder. Where the GPU alone runs the execution and a route that wrote the
records may set a barrier (`IndirectCommandBuffer::command_writes`), every command runs after the
one before it.
- **Render commands the GPU may write run on the GPU alone** where the commit can tell from what
the records may hold (`IndirectCommandBuffer::command_writes`) that every command is a draw of one
primitive type under the encoder's pipeline state, which the buffer inherits, and whose vertex