RUNTIME 2228 / ARTIFACT_FORMAT 518: a dispatch of an inert kernel records no Vulkan dispatch

The translator records, from the final SPIR-V (ModuleStats::inert, spirv/verify/effects.rs),
whether a kernel can affect anything outside its invocation: inert means no loop, and no store,
atomic or image write to any storage class but Function, Private or Workgroup, in the entry or
anything it calls. Anything not classified counts as writing. A module with a loop is never
inert, since a kernel that never terminates is the one case where skipping would change the
outcome. The runtime's compute record path (compute::record, shared by direct, threads, indirect
and the host-encoded ICB path) records no vkCmdDispatch for an inert pipeline and counts it in
WorkCounts::dispatches_skipped_inert. The encoder's fences, events, barriers and the command
buffer's completion are unchanged, and a skipped dispatch's reads take no hazard tracking. Metal's
answer is the same: nothing an inert kernel does is observable, and counter sampling is a
RuntimeGap. GPU-encoded ICBs don't go through record and still dispatch. API.md documents it.

Why: on the RTX 2080 (gbt-2080, m3-max-25739, pin 69) the guest's upload_uchar_buffer kernel is
empty (`ret void`, its one buffer argument unused) and is dispatched as 1-thread threadgroups:
3,661 command buffers of it alone, 6,853 dispatches, 11.7 s of GPU time over the walk (p50
0.11 ms, p90 1.0 ms, max 111 ms a dispatch).

Verified (ftconv, at 80a7769421 on 80ff4aafa7, step codes read inside the jobs):
- 25890 engine_inert (4 profiles x 7 kernels incl. the codec round trip): NEXTEST=0, 1/1.
- 25912 lavapipe --cfg m2v_cpu_icd runtime inert_dispatch: NEXTEST=0, 3/3. Counter: empty
  direct/threads/indirect +3, workgroup-store-only +1, loop and device-store +0 (fills write
  1..=N); a fence and an event around a skipped dispatch still order a later read of an earlier
  write.
- 25913 clippy --workspace --all-targets --all-features -D warnings (plain): CLIPPY=0.
Not yet run at landing: clippy under m2v_gpu and m2v_cpu_icd, rustdoc -D warnings (dispatched by
ftconv), the 2080 before/after run and a walk with the counter.

ARTIFACT_FORMAT_VERSION 517 -> 518 (the artifact codec carries inert); RUNTIME_VERSION
2227 -> 2228.
This commit is contained in:
Anees Iqbal committed 2026-11-13 09:58:44 -08:00
1 parent b36335e5ba
commit 3969e96010
14 files changed
+668 -6

No files matched your search

+20 -3
View File
@@ -44,6 +44,14 @@
//! there on its folded variant of the call's threadgroup size, behind the same preprocess; any
//! other dispatch's arguments are copied there, and a host step records it as the direct dispatch
//! they state once the work before it completed (`indirect_dispatch`).
//!
//! A dispatch of an inert kernel (`ComputePipelineState::inert`: its module holds no loop and
//! writes nothing but its invocations' own and its threadgroups' memory) records no Vulkan
//! dispatch, direct, indirect or an indirect command buffer's alike (`record`), after Metal's
//! checks of step 1: nothing it does outlasts it, so nothing later reads it, and the runtime
//! samples no counter that would count its threads (`RuntimeGap::CounterSampleBuffers`). Its
//! reads take no hazard tracking. The encoder's barriers, fences and the command buffer's events
//! and completion stay as they are (`WorkCounts::dispatches_skipped_inert`).
use super::address_map::{self, SamplerMaps};
use super::argument_table::{check_index, ArgumentTable, Stamp};
@@ -920,8 +928,12 @@ impl ComputeCommandEncoder {
/// `dispatchThreadgroups:threadsPerThreadgroup:`. A threadgroup Metal runs nothing for (its
/// size 0 or above the state's maximum, the module docs) records nothing; a count axis past
/// 32 bits is taken modulo `2^32`, and one that is 0 runs nothing. Refused: no pipeline state
/// set (plain Metal faults).
/// 32 bits is taken modulo `2^32`, and one that is 0 runs nothing. A dispatch of an inert
/// kernel (no loop, and no write but to its threads' own and its threadgroups' memory) records
/// no Vulkan dispatch: what it computes ends with it, and Metal's counter sampling, which
/// could count its threads, is the runtime's gap (`RuntimeGap::CounterSampleBuffers`); the
/// encoder's barriers and fences stay as they are. Refused: no pipeline state set (plain
/// Metal faults).
pub fn dispatch_threadgroups(&mut self, groups: Size, threads: Size) -> Result<(), Error> {
self.logged(
|_| ComputeCall::Threadgroups(groups, threads),
@@ -2328,7 +2340,8 @@ impl DispatchMemo {
/// direct one takes what its last dispatch settled where it has the same inputs
/// ([`DispatchMemo`]). And one whose `VkPipeline`s are not made yet hands their making to the
/// device's pool and records later (`pending_dispatch.rs`): an execution's or a host step's
/// dispatch waits for them.
/// dispatch waits for them. A dispatch of an inert kernel records nothing and answers `Ok(true)`,
/// taken (the module docs).
fn record(
core: &mut EncoderCore,
tables: &DispatchTables<'_>,
@@ -2337,6 +2350,10 @@ fn record(
own: Option<(usize, &mut LiveDispatch)>,
) -> Result<bool, Error> {
let pipeline = tables.pipeline;
if pipeline.inert() {
core.counts().dispatch_skipped_inert();
return Ok(true);
}
let (direct, gpu) = match counts {
Counts::Direct(dispatch) => (Some(dispatch), None),
Counts::Flat(gpu) => (None, Some(gpu)),
@@ -1371,6 +1371,17 @@ impl ComputePipelineState {
})
}
/// Whether the state is a kernel's whose module is inert
/// ([`ModuleStats::inert`](metal2vulkan::pipeline::ModuleStats::inert)): it holds no loop and
/// writes nothing but its invocations' own and its threadgroups' memory, so a dispatch of it
/// ends and leaves nothing a later command or the program can read. A compute encoder records
/// no Vulkan dispatch of it (`compute::record`). The base variant answers for every variant:
/// they bind and partition the kernel otherwise, and store what it stores. A tile function's
/// state is never inert: its threadgroup memory is the render pass's imageblock.
pub(super) fn inert(&self) -> bool {
!self.is_tile() && self.0.base.pipeline.stage.stats.inert
}
/// Whether the kernel reads texture handles from memory (its layout has a handle table): only
/// then does a dispatch reach a resident heap's textures.
pub(super) fn reads_texture_handles(&self) -> bool {
@@ -0,0 +1,296 @@
//! A dispatch of an inert kernel (`ComputePipelineState::inert`: its module holds no loop and
//! writes nothing but its threads' own and its threadgroups' memory) records no Vulkan dispatch
//! (`compute::record`, `WorkCounts::dispatches_skipped_inert`), and what orders around it still
//! orders:
//!
//! - **Skipped.** A kernel that does nothing, dispatched in threadgroups of one thread, as threads
//! and indirectly, and a kernel that writes only threadgroup memory: each dispatch is counted.
//! - **Recorded.** A kernel that stores to a device buffer writes its words, and one that loops
//! though it writes only threadgroup memory runs: neither is counted.
//! - **Fences.** An encoder whose only dispatch is skipped waits for one fence and updates another,
//! and a later encoder that waits for the second reads what an earlier one wrote, over buffers
//! whose hazards the runtime does not track.
//! - **Events.** A command buffer whose only dispatch is skipped waits for a shared event's value
//! and signals the next, on a queue of its own, and a third command buffer that waits for that
//! value reads what the first wrote; the three are committed in reverse order.
//!
//! 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 module is LLVM text written here
//! (`llvm-as`).
use super::blit_holds::{device, Scratch, WAIT};
use super::opencl_mode::{words, words_buffer};
use crate::{
Buffer, CommandBufferStatus, ComputePipelineState, Device, EventRef, HazardTrackingMode,
PipelineOptions, ResourceOptions, Size,
};
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
/// Five kernels of buffers `a` (index 0) and `b` (index 1) and the thread's grid position:
/// `empty` does nothing; `tg_only` stores to threadgroup memory; `loop_tg` stores `a[0]` times to
/// threadgroup memory; `fill` stores `gid + 1` at `b[gid]`; `twice` stores `2 * a[gid]` at
/// `b[gid]`.
const KERNELS: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\
target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\
@tg = internal addrspace(3) global [64 x i32] undef, align 4\n\n\
define void @empty(ptr addrspace(1) noundef %a, ptr addrspace(1) noundef %b, i32 noundef %gid) {\n\
entry:\n\
ret void\n\
}\n\n\
define void @tg_only(ptr addrspace(1) noundef %a, ptr addrspace(1) noundef %b, i32 noundef %gid) {\n\
entry:\n\
%i = and i32 %gid, 63\n\
%iw = zext i32 %i to i64\n\
%p = getelementptr inbounds [64 x i32], ptr addrspace(3) @tg, i64 0, i64 %iw\n\
store i32 %gid, ptr addrspace(3) %p, align 4\n\
ret void\n\
}\n\n\
define void @loop_tg(ptr addrspace(1) noundef %a, ptr addrspace(1) noundef %b, i32 noundef %gid) {\n\
entry:\n\
%n = load i32, ptr addrspace(1) %a, align 4\n\
%none = icmp eq i32 %n, 0\n\
br i1 %none, label %done, label %body\n\
body:\n\
%i = phi i32 [ 0, %entry ], [ %i.next, %body ]\n\
%k = and i32 %i, 63\n\
%kw = zext i32 %k to i64\n\
%p = getelementptr inbounds [64 x i32], ptr addrspace(3) @tg, i64 0, i64 %kw\n\
store i32 %i, ptr addrspace(3) %p, align 4\n\
%i.next = add nuw i32 %i, 1\n\
%more = icmp ult i32 %i.next, %n\n\
br i1 %more, label %body, label %done\n\
done:\n\
ret void\n\
}\n\n\
define void @fill(ptr addrspace(1) noundef %a, ptr addrspace(1) noundef %b, i32 noundef %gid) {\n\
entry:\n\
%v = add i32 %gid, 1\n\
%gw = zext i32 %gid to i64\n\
%p = getelementptr inbounds i32, ptr addrspace(1) %b, i64 %gw\n\
store i32 %v, ptr addrspace(1) %p, align 4\n\
ret void\n\
}\n\n\
define void @twice(ptr addrspace(1) noundef %a, ptr addrspace(1) noundef %b, i32 noundef %gid) {\n\
entry:\n\
%gw = zext i32 %gid to i64\n\
%q = getelementptr inbounds i32, ptr addrspace(1) %a, i64 %gw\n\
%x = load i32, ptr addrspace(1) %q, align 4\n\
%v = shl i32 %x, 1\n\
%p = getelementptr inbounds i32, ptr addrspace(1) %b, i64 %gw\n\
store i32 %v, ptr addrspace(1) %p, align 4\n\
ret void\n\
}\n\n\
!llvm.module.flags = !{!0, !1}\n!air.kernel = !{!20, !21, !22, !23, !24}\n!air.version = !{!8}\n!air.language_version = !{!9}\n\
!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\
!1 = !{i32 7, !\"air.max_threadgroup_buffers\", i32 31}\n\
!3 = !{}\n!4 = !{!5, !6, !7}\n\
!5 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"a\"}\n\
!6 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 1, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"b\"}\n\
!7 = !{i32 2, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"gid\"}\n\
!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\
!20 = !{ptr @empty, !3, !4}\n!21 = !{ptr @tg_only, !3, !4}\n!22 = !{ptr @loop_tg, !3, !4}\n\
!23 = !{ptr @fill, !3, !4}\n!24 = !{ptr @twice, !3, !4}\n";
/// The words the tests write and read.
const N: u32 = 1024;
/// The state of kernel `name` of [`KERNELS`].
fn state(device: &Device, name: &str) -> ComputePipelineState {
let air = metal2vulkan_devtools::llvm_assemble_text(KERNELS).unwrap();
let library = metal2vulkan::library::Library::from_air(&air).unwrap();
let function = device
.new_library_with_compile_library(library)
.new_function_with_name(name)
.unwrap();
let descriptor =
ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor()));
device
.new_compute_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap()
}
/// A shared buffer of `N` zero words whose hazards the runtime does not track.
fn untracked(device: &Device) -> Buffer {
let options =
ResourceOptions::shared().with_hazard_tracking_mode(HazardTrackingMode::Untracked);
device
.new_buffer_with_bytes(&vec![0; 4 * N as usize], options)
.unwrap()
}
/// `2 * (i + 1)` for every `i < N`: what `twice` stores from what `fill` stored.
fn doubled_fill() -> Vec<u32> {
(0..N).map(|i| 2 * (i + 1)).collect()
}
/// The device's count of skipped dispatches.
fn skipped(device: &Device) -> u64 {
device.work_counts().dispatches_skipped_inert
}
/// The inert kernels' dispatches, direct in threadgroups of one thread, as threads and indirect,
/// are counted skipped; the device store's and the loop's are not, and the store writes its words.
#[test]
fn an_inert_kernel_records_no_dispatch_and_a_writing_or_looping_one_does() {
let scratch = Scratch::new("inert-dispatch");
let device = device(&scratch.0);
let (empty, tg_only, loop_tg, fill) = (
state(&device, "empty"),
state(&device, "tg_only"),
state(&device, "loop_tg"),
state(&device, "fill"),
);
let count = words_buffer(&device, &[5]);
let out = words_buffer(&device, &[0; N as usize]);
let arguments = words_buffer(&device, &[4, 1, 1]);
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_buffer(Some(&count), 0, 0).unwrap();
encoder.set_buffer(Some(&out), 0, 1).unwrap();
let one = Size::new(1, 1, 1);
let before = skipped(&device);
encoder.set_compute_pipeline_state(&empty).unwrap();
encoder
.dispatch_threadgroups(Size::new(4096, 1, 1), one)
.unwrap();
encoder
.dispatch_threads(Size::new(1000, 1, 1), Size::new(64, 1, 1))
.unwrap();
encoder
.dispatch_threadgroups_indirect(&arguments, 0, one)
.unwrap();
assert_eq!(
skipped(&device) - before,
3,
"the empty kernel's dispatches"
);
encoder.set_compute_pipeline_state(&tg_only).unwrap();
encoder
.dispatch_threadgroups(Size::new(4, 1, 1), Size::new(64, 1, 1))
.unwrap();
assert_eq!(skipped(&device) - before, 4, "the threadgroup store's");
encoder.set_compute_pipeline_state(&loop_tg).unwrap();
encoder
.dispatch_threadgroups(one, Size::new(64, 1, 1))
.unwrap();
encoder.set_compute_pipeline_state(&fill).unwrap();
encoder
.dispatch_threads(Size::new(u64::from(N), 1, 1), Size::new(64, 1, 1))
.unwrap();
assert_eq!(skipped(&device) - before, 4, "the loop's and the store's");
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
assert_eq!(words(&out), (1..=N).collect::<Vec<_>>());
}
/// An encoder whose only dispatch is skipped waits for the first encoder's fence and updates its
/// own, which the third waits for: the third reads what the first wrote, over untracked buffers.
#[test]
fn fences_around_a_skipped_dispatch_order_a_later_read_of_an_earlier_write() {
let scratch = Scratch::new("inert-fences");
let device = device(&scratch.0);
let (empty, fill, twice) = (
state(&device, "empty"),
state(&device, "fill"),
state(&device, "twice"),
);
let (x, y) = (untracked(&device), untracked(&device));
let (written, passed) = (device.new_fence(), device.new_fence());
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let grid = Size::new(u64::from(N), 1, 1);
let group = Size::new(64, 1, 1);
let before = skipped(&device);
let mut first = command_buffer.compute_command_encoder().unwrap();
first.set_compute_pipeline_state(&fill).unwrap();
first.set_buffer(Some(&x), 0, 1).unwrap();
first.dispatch_threads(grid, group).unwrap();
first.update_fence(&written).unwrap();
first.end_encoding().unwrap();
let mut skipping = command_buffer.compute_command_encoder().unwrap();
skipping.wait_for_fence(&written).unwrap();
skipping.set_compute_pipeline_state(&empty).unwrap();
skipping
.dispatch_threadgroups(Size::new(u64::from(N), 1, 1), Size::new(1, 1, 1))
.unwrap();
skipping.update_fence(&passed).unwrap();
skipping.end_encoding().unwrap();
let mut last = command_buffer.compute_command_encoder().unwrap();
last.wait_for_fence(&passed).unwrap();
last.set_compute_pipeline_state(&twice).unwrap();
last.set_buffer(Some(&x), 0, 0).unwrap();
last.set_buffer(Some(&y), 0, 1).unwrap();
last.dispatch_threads(grid, group).unwrap();
last.end_encoding().unwrap();
assert_eq!(skipped(&device) - before, 1);
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
assert_eq!(words(&y), doubled_fill());
}
/// A command buffer whose only dispatch is skipped waits for a shared event's 1 and signals 2, on a
/// queue of its own; a third, waiting for 2, reads what the first wrote before it signalled 1.
/// Committed last first, so only the event orders them.
#[test]
fn events_around_a_skipped_dispatch_order_a_later_read_of_an_earlier_write() {
let scratch = Scratch::new("inert-events");
let device = device(&scratch.0);
let (empty, fill, twice) = (
state(&device, "empty"),
state(&device, "fill"),
state(&device, "twice"),
);
let (x, y) = (untracked(&device), untracked(&device));
let event = device.new_shared_event().unwrap();
let queues: Vec<_> = (0..3)
.map(|_| device.new_command_queue().unwrap())
.collect();
let grid = Size::new(u64::from(N), 1, 1);
let group = Size::new(64, 1, 1);
let before = skipped(&device);
let writer = queues[0].command_buffer().unwrap();
let mut encoder = writer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(&fill).unwrap();
encoder.set_buffer(Some(&x), 0, 1).unwrap();
encoder.dispatch_threads(grid, group).unwrap();
encoder.end_encoding().unwrap();
writer
.encode_signal_event(EventRef::Shared(&event), 1)
.unwrap();
let skipping = queues[1].command_buffer().unwrap();
skipping
.encode_wait_for_event(EventRef::Shared(&event), 1)
.unwrap();
let mut encoder = skipping.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(&empty).unwrap();
encoder
.dispatch_threadgroups(Size::new(u64::from(N), 1, 1), Size::new(1, 1, 1))
.unwrap();
encoder.end_encoding().unwrap();
skipping
.encode_signal_event(EventRef::Shared(&event), 2)
.unwrap();
let reader = queues[2].command_buffer().unwrap();
reader
.encode_wait_for_event(EventRef::Shared(&event), 2)
.unwrap();
let mut encoder = reader.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(&twice).unwrap();
encoder.set_buffer(Some(&x), 0, 0).unwrap();
encoder.set_buffer(Some(&y), 0, 1).unwrap();
encoder.dispatch_threads(grid, group).unwrap();
encoder.end_encoding().unwrap();
assert_eq!(skipped(&device) - before, 1);
for command_buffer in [&reader, &skipping, &writer] {
command_buffer.commit().unwrap();
}
for command_buffer in [&writer, &skipping, &reader] {
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
}
assert_eq!(words(&y), doubled_fill());
}
@@ -364,6 +364,8 @@ mod indirect_command_buffer;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod indirect_command_buffer_device;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod inert_dispatch;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod inline_continues;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod inline_splits;
@@ -757,6 +757,7 @@ struct CommandCounters {
dispatch_shapes_found: AtomicU64,
dispatch_used_resources_listed: AtomicU64,
dispatches_settled_as_before: AtomicU64,
dispatches_skipped_inert: AtomicU64,
dispatches_planned_as_before: AtomicU64,
whole_dispatches_on_partial_variants: AtomicU64,
dispatches_pushing_set_zero: AtomicU64,
@@ -1683,6 +1684,11 @@ impl Counting<'_> {
self.0.add(|counts| &counts.dispatches_settled_as_before, 1);
}
/// A dispatch of an inert kernel that recorded no Vulkan dispatch (`compute::record`).
pub(crate) fn dispatch_skipped_inert(&self) {
self.0.add(|counts| &counts.dispatches_skipped_inert, 1);
}
/// A direct dispatch that settled a bind state of the shape its state's last direct dispatch
/// planned and took what that one planned (`pipeline::Planned`).
pub(crate) fn dispatch_planned_as_before(&self) {
@@ -8096,6 +8102,12 @@ pub struct WorkCounts {
/// visible-function table, while no no-copy buffer moved, no sampler state was made or went
/// and no buffer took a resident indirect command buffer's ID (`compute::DispatchMemo`).
pub dispatches_settled_as_before: u64,
/// Dispatches of an inert kernel (`ModuleStats::inert`: no loop, and no write but to its
/// invocations' own and its threadgroups' memory) that recorded no Vulkan dispatch, direct,
/// indirect and an indirect command buffer's alike (`compute::record`): nothing such a
/// dispatch does outlasts it, and the runtime samples no counter that would count its
/// threads. Not counted in `dispatches_settled_as_before`.
pub dispatches_skipped_inert: u64,
/// Direct dispatches that settled their bind state again (another table, another residency,
/// another encoder) into one of the shape their pipeline state's last direct dispatch that
/// planned planned, of the same dispatch and buffer forms, and took that one's variant and
@@ -10666,6 +10678,7 @@ impl Device {
}),
host_holds_looked_up: commands(|counts| &counts.host_holds_looked_up),
dispatches_settled_as_before: commands(|counts| &counts.dispatches_settled_as_before),
dispatches_skipped_inert: commands(|counts| &counts.dispatches_skipped_inert),
dispatches_planned_as_before: commands(|counts| &counts.dispatches_planned_as_before),
whole_dispatches_on_partial_variants: commands(|counts| {
&counts.whole_dispatches_on_partial_variants
+4
View File
@@ -774,6 +774,7 @@ impl Codec for ModuleStats {
instructions: _,
constructs: _,
loops: _,
inert: _,
} = self;
Node::ZERO
}
@@ -785,6 +786,7 @@ impl Codec for ModuleStats {
instructions,
constructs,
loops,
inert,
} = self;
functions.put(w);
blocks.put(w);
@@ -792,6 +794,7 @@ impl Codec for ModuleStats {
instructions.put(w);
constructs.put(w);
loops.put(w);
inert.put(w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
Ok(ModuleStats {
@@ -801,6 +804,7 @@ impl Codec for ModuleStats {
instructions: Codec::get(r)?,
constructs: Codec::get(r)?,
loops: Codec::get(r)?,
inert: Codec::get(r)?,
})
}
}
+2 -2
View File
@@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2093;
/// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag
/// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that
/// bumps it says what changed; this comment keeps no history.
pub const ARTIFACT_FORMAT_VERSION: u32 = 517;
pub const ARTIFACT_FORMAT_VERSION: u32 = 518;
/// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding
/// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 517;
/// 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 = 2227;
pub const RUNTIME_VERSION: u32 = 2228;
/// 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
@@ -419,6 +419,14 @@ pub struct ModuleStats {
pub constructs: u32,
/// Loops. The structurizer makes none of its own, so this is the input's own loop count.
pub loops: u32,
/// Whether the module is inert: it holds no loop, and no instruction of any of its functions
/// writes memory other than an invocation's own and its workgroup's (`Function`, `Private`
/// and `Workgroup` storage), writes an image, or emits or drops an output of its stage. So
/// every invocation ends, and a dispatch of a kernel of it leaves nothing behind but the time
/// it took: `metal2vulkan-runtime` records none. An instruction the classification does not
/// name as reading or computing alone (an interlock, a ray query) makes it not inert.
#[cfg_attr(feature = "serde", serde(default))]
pub inert: bool,
}
/// A precision note a stage records only where a specialized module runs an arm that keeps its
@@ -0,0 +1,133 @@
//! Whether a finished module is inert
//! ([`ModuleStats::inert`](crate::pipeline::artifact::ModuleStats::inert)):
//! every invocation of it ends, and none leaves anything behind its workgroup.
//!
//! An invocation ends where the module holds no loop: SPIR-V has no recursion (the verifier's
//! call-graph rule) and no backward edge but a loop's, so every path through every function is
//! finite. It leaves nothing behind where no instruction or terminator of the module, in any of its
//! functions, can:
//!
//! - store, write atomically or exchange through a pointer to memory other than `Function`,
//! `Private` or `Workgroup` storage (an invocation's own and its workgroup's, which end with the
//! workgroup), or through a pointer whose type is not one of those;
//! - write an image;
//! - emit an output of its stage, or change which of its outputs land: a mesh function's
//! outputs, a geometry function's vertices and primitives, a task function's launch, a
//! fragment's demotion, kill or termination;
//! - do anything the classification below does not name as reading or computing alone: an
//! interlock and a ray query count as effects, so a module holding one is never inert.
//!
//! Every instruction and terminator form is named in an exhaustive `match`, so a form added to the
//! IR does not compile until it is classified here.
use crate::budget::Meter;
use crate::spirv::ids::Value;
use crate::spirv::ir::{Inst, Merge, StorageClass, Terminator, Type, TypedModule};
use super::VerifyError;
/// Whether `m` is inert (the module docs), metered one step a block and one an instruction.
pub(super) fn inert(m: &TypedModule, meter: &mut Meter) -> Result<bool, VerifyError> {
if !m.loops.is_empty() {
return Ok(false);
}
for block in &m.blocks {
meter.tick(
u32::try_from(block.insts.len())
.unwrap_or(u32::MAX)
.saturating_add(1),
)?;
if matches!(block.merge, Some(Merge::Loop { .. })) || !ends_inert(&block.term) {
return Ok(false);
}
if !block.insts.iter().all(|node| leaves_nothing(m, &node.inst)) {
return Ok(false);
}
}
Ok(true)
}
/// Whether the terminator leaves the invocation's outputs and memory as they are.
fn ends_inert(term: &Terminator) -> bool {
match term {
Terminator::Branch(_)
| Terminator::CondBranch { .. }
| Terminator::Switch { .. }
| Terminator::Return
| Terminator::ReturnValue(_)
| Terminator::Unreachable => true,
Terminator::Kill | Terminator::TerminateInvocation | Terminator::EmitMeshTasks { .. } => {
false
}
}
}
/// Whether the instruction writes nothing past the invocation's own and its workgroup's memory and
/// emits nothing.
fn leaves_nothing(m: &TypedModule, inst: &Inst) -> bool {
match inst {
Inst::Store { ptr, .. }
| Inst::AtomicStore { ptr, .. }
| Inst::Atomic { ptr, .. }
| Inst::AtomicCompareExchange { ptr, .. } => local(m, *ptr),
Inst::ImageWrite { .. }
| Inst::BeginInterlock
| Inst::EndInterlock
| Inst::DemoteToHelperInvocation
| Inst::SetMeshOutputs { .. }
| Inst::EmitVertex
| Inst::EndPrimitive
| Inst::RayQuery(_) => false,
Inst::Load { .. }
| Inst::Unary { .. }
| Inst::Binary { .. }
| Inst::Select { .. }
| Inst::BitFieldInsert { .. }
| Inst::Fma { .. }
| Inst::BitFieldExtract { .. }
| Inst::Convert { .. }
| Inst::CompositeConstruct { .. }
| Inst::CompositeExtract { .. }
| Inst::CompositeInsert { .. }
| Inst::VectorExtractDynamic { .. }
| Inst::VectorInsertDynamic { .. }
| Inst::VectorShuffle { .. }
| Inst::Undef
| Inst::AccessChain { .. }
| Inst::ArrayLength { .. }
| Inst::Call { .. }
| Inst::AtomicLoad { .. }
| Inst::ImageTexelPointer { .. }
| Inst::ControlBarrier { .. }
| Inst::MemoryBarrier { .. }
| Inst::SampledImage { .. }
| Inst::Image(_)
| Inst::ImageSample { .. }
| Inst::ImageFetch { .. }
| Inst::ImageGather { .. }
| Inst::ImageDrefGather { .. }
| Inst::ImageRead { .. }
| Inst::ImageSparseTexelsResident(_)
| Inst::ImageQuery { .. }
| Inst::ImageQueryLod { .. }
| Inst::Derivative { .. }
| Inst::Group { .. }
| Inst::Glsl { .. }
| Inst::IsHelperInvocation => true,
}
}
/// Whether `ptr` points into the invocation's own or its workgroup's memory. A pointer whose type
/// is not found is not.
fn local(m: &TypedModule, ptr: Value) -> bool {
let Ok(def) = m.value(ptr) else {
return false;
};
matches!(
m.types().get(def.ty),
Ok(Type::Pointer {
class: StorageClass::Function | StorageClass::Private | StorageClass::Workgroup,
..
})
)
}
+4 -1
View File
@@ -45,12 +45,14 @@
//!
//! A pass counts what it covered as it checks it, and that count is the module's public
//! [`ModuleStats`]: the verifier runs on every translation, so the statistics cost nothing beyond
//! it.
//! it. A last pass over every instruction decides whether the module is inert
//! ([`ModuleStats::inert`], `effects`).
//!
//! Work is linear in the module plus, per branch edge, the number of constructs it leaves; it is
//! metered on the per-attempt [`Meter`] and every table is charged to its ledger.
mod cfg;
mod effects;
mod rules;
#[cfg(test)]
@@ -299,6 +301,7 @@ fn check_in(
rules::check_places(m, &defs, meter)?;
rules::check_stage(m)?;
rules::check_derived(m)?;
report.inert = effects::inert(m, meter)?;
Ok(report)
}
@@ -0,0 +1,166 @@
//! Whether a kernel's module is inert (`ModuleStats::inert`, `spirv::verify::effects`): no loop,
//! and no write but to its invocations' own and its threadgroups' memory. A kernel that does
//! nothing, one that writes only threadgroup or private memory, and one that changes threadgroup
//! memory atomically are inert; one that stores or writes atomically to a device buffer is not,
//! and neither is one that loops, though it writes only threadgroup memory. The compiled artifact
//! states it and its encoding keeps it. `llvm-as` assembles the module; without it the test skips
//! visibly.
use crate::device::{Device, DevicePolicy};
use crate::library::CompiledFunction;
use crate::pipeline::testing::{
compile, description, link_and_validate, llvm_assemble, AssembleError, Scratch,
};
const PROFILES: [&str; 4] = [
"amd-rdna3-radv",
"nvidia-rtx5080-laptop",
"lavapipe",
"moltenvk-m3",
];
/// Each kernel and whether its module is inert.
const KERNELS: [(&str, bool); 7] = [
("inert_empty", true),
("inert_threadgroup_store", true),
("inert_private_store", true),
("inert_threadgroup_atomic", true),
("writes_device_store", false),
("writes_device_atomic", false),
("loops_threadgroup_only", false),
];
/// A kernel of the buffer `%0` and the thread's grid position `%1` whose body ends in `ret void`.
fn kernel(name: &str, body: &str) -> String {
format!(
"define void @{name}(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0, i32 noundef %1) {{
entry:
{body} ret void
}}
"
)
}
/// `%p`, the word of `@tg` the thread's position picks (modulo 64).
const TG_WORD: &str = " %i = and i32 %1, 63
%iw = zext i32 %i to i64
%p = getelementptr inbounds [64 x i32], ptr addrspace(3) @tg, i64 0, i64 %iw
";
fn module() -> String {
let mut s = String::from(
"target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n@tg = internal addrspace(3) global [64 x i32] undef, align 4\n\n",
);
s.push_str(&kernel("inert_empty", ""));
s.push_str(&kernel(
"inert_threadgroup_store",
&format!("{TG_WORD} store i32 %1, ptr addrspace(3) %p, align 4\n"),
));
s.push_str(&kernel(
"inert_private_store",
" %arr = alloca [4 x i32], align 4
%i = and i32 %1, 3
%iw = zext i32 %i to i64
%p = getelementptr inbounds [4 x i32], ptr %arr, i64 0, i64 %iw
store i32 %1, ptr %p, align 4
%v = load i32, ptr %p, align 4
%q = getelementptr inbounds [4 x i32], ptr %arr, i64 0, i64 0
store i32 %v, ptr %q, align 4
",
));
s.push_str(&kernel(
"inert_threadgroup_atomic",
&format!("{TG_WORD} %o = atomicrmw add ptr addrspace(3) %p, i32 1 monotonic, align 4\n"),
));
s.push_str(&kernel(
"writes_device_store",
" %iw = zext i32 %1 to i64
%p = getelementptr inbounds i32, ptr addrspace(1) %0, i64 %iw
store i32 %1, ptr addrspace(1) %p, align 4
",
));
s.push_str(&kernel(
"writes_device_atomic",
" %o = atomicrmw add ptr addrspace(1) %0, i32 1 monotonic, align 4\n",
));
s.push_str(
"define void @loops_threadgroup_only(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0, i32 noundef %1) {
entry:
%n = load i32, ptr addrspace(1) %0, align 4
%none = icmp eq i32 %n, 0
br i1 %none, label %done, label %body
body:
%i = phi i32 [ 0, %entry ], [ %i.next, %body ]
%k = and i32 %i, 63
%kw = zext i32 %k to i64
%p = getelementptr inbounds [64 x i32], ptr addrspace(3) @tg, i64 0, i64 %kw
store i32 %i, ptr addrspace(3) %p, align 4
%i.next = add nuw i32 %i, 1
%more = icmp ult i32 %i.next, %n
br i1 %more, label %body, label %done
done:
ret void
}
",
);
let refs: Vec<String> = (0..KERNELS.len()).map(|i| format!("!{}", 20 + i)).collect();
s.push_str(&format!(
"!llvm.module.flags = !{{!0, !1}}\n!air.kernel = !{{{}}}\n!air.version = !{{!17}}\n!air.language_version = !{{!18}}\n\n",
refs.join(", ")
));
s.push_str("!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n!1 = !{i32 7, !\"air.max_threadgroup_buffers\", i32 31}\n!10 = !{}\n!11 = !{!12, !13}\n!12 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"buf\"}\n!13 = !{i32 1, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"gid\"}\n!17 = !{i32 2, i32 8, i32 0}\n!18 = !{!\"Metal\", i32 4, i32 0, i32 0}\n");
for (i, (k, _)) in KERNELS.iter().enumerate() {
s.push_str(&format!("!{} = !{{ptr @{k}, !10, !11}}\n", 20 + i));
}
s
}
/// Assemble the module, or `None` (skipped visibly) without `llvm-as`.
fn assemble() -> Option<Vec<u8>> {
let scratch = Scratch::new("m2v-inert");
let ll = scratch.path().join("inert.ll");
std::fs::write(&ll, module()).expect("write");
match llvm_assemble(&ll) {
Ok(b) => Some(b),
Err(AssembleError::Missing(t)) => {
eprintln!("SKIPPED: {t}");
None
}
Err(AssembleError::Rejected(e)) => panic!("llvm-as rejected the module: {e}"),
}
}
/// Each kernel's module is inert exactly where it loops nowhere and writes no memory but its
/// invocations' own and its threadgroups': the artifact states it, its module links and validates,
/// and the encoded artifact decodes to the same answer.
#[test]
fn a_kernel_is_inert_where_it_loops_nowhere_and_writes_only_its_threadgroups_memory() {
let Some(bitcode) = assemble() else {
return;
};
for stem in PROFILES {
let device = Device::new(
description(stem).expect("description"),
DevicePolicy::default(),
)
.expect("device");
let p = device.profile();
for (entry, inert) in KERNELS {
let what = format!("{entry} on {stem}");
let a = compile(&bitcode, entry, p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(a.stats.inert, inert, "{what}: {:?}", a.stats);
assert_eq!(
a.stats.loops > 0,
entry.starts_with("loops"),
"{what}: {:?}",
a.stats
);
link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let bytes = CompiledFunction::new(a).to_bytes();
let decoded = CompiledFunction::from_bytes(&bytes, &device).expect("decode");
assert_eq!(decoded.module_stats().inert, inert, "{what}: decoded");
}
}
}
+1
View File
@@ -83,6 +83,7 @@ mod engine_image_shapes;
mod engine_imageblock;
mod engine_index_words;
mod engine_indirect_commands;
mod engine_inert;
mod engine_inline_asm;
mod engine_integer_median3;
mod engine_kernel_lod;
@@ -2813,6 +2813,7 @@ field metal2vulkan-runtime::WorkCounts.dispatch_used_resources_listed pub dispat
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
field metal2vulkan-runtime::WorkCounts.dispatches_settled_as_before pub dispatches_settled_as_before: u64
field metal2vulkan-runtime::WorkCounts.dispatches_skipped_inert pub dispatches_skipped_inert: u64
field metal2vulkan-runtime::WorkCounts.dma_buf_buffer_imports_dedicated pub dma_buf_buffer_imports_dedicated: u64
field metal2vulkan-runtime::WorkCounts.dma_buf_image_fallbacks pub dma_buf_image_fallbacks: u64
field metal2vulkan-runtime::WorkCounts.dma_buf_image_memories_live pub dma_buf_image_memories_live: u64
@@ -4961,6 +4962,7 @@ field metal2vulkan::pipeline::MeshRecords.vertices pub vertices: u32
field metal2vulkan::pipeline::ModuleStats.blocks pub blocks: u32
field metal2vulkan::pipeline::ModuleStats.constructs pub constructs: u32
field metal2vulkan::pipeline::ModuleStats.functions pub functions: u32
field metal2vulkan::pipeline::ModuleStats.inert pub inert: bool
field metal2vulkan::pipeline::ModuleStats.instructions pub instructions: u64
field metal2vulkan::pipeline::ModuleStats.loops pub loops: u32
field metal2vulkan::pipeline::ModuleStats.reachable_blocks pub reachable_blocks: u32
Can't render this file because it is too large.
+6
View File
@@ -788,6 +788,12 @@ assert!(stats.reachable_blocks <= stats.blocks);
produced, walk the entry `DeviceProfile::specialized_entry` gives, which is that AIR specialized
and canonicalized. A decoded function's `ir::InstKind::Call` sites give each callee's call
count, which is what turns its own blocks into the program inlining will make of it.
- `inert` says the module holds no loop and that no instruction of it writes memory other than an
invocation's own and its workgroup's (`Function`, `Private` and `Workgroup` storage), writes an
image, or emits or drops an output of its stage. Every invocation of such a module ends and
leaves nothing behind, so a dispatch of an inert kernel computes nothing anyone can read:
`metal2vulkan-runtime` records no Vulkan dispatch of it. An instruction the check does not
classify as reading or computing alone (an interlock, a ray query) makes a module not inert.
The counts are of the module `spirv` holds: the verifier counts the module it checked, and
serialization and relocation assign link numbers without adding or removing an instruction. They