diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index e1f7b87e4..666dc1a5c 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -555,6 +555,12 @@ that touch blocks first. texture's format (`metal::format::integer_channels_word`); and for each constexpr sampler it samples through, the index the consumer gave it at the state's creation. Nothing is written into set 1 at bind or dispatch time, and every texture stays in its home layout. +- A dispatch of a kernel that writes no memory (the translator's `PipelineInterface::writes_memory`: + no store to a buffer or through a device address, no texture write and no atomic update, in the + kernel or any function it calls) records nothing, binds nothing and reads no indirect buffer, + once its threadgroup size is checked: it has no effect a program can observe. + `Metrics::dispatches_without_effects` counts them. Its GPU time and its command buffer's are + then shorter than Metal's. - Each dispatch records at once. What it touches is its pipeline's bound buffer and texture slots, with the access the translator states for each (a texture's sample and read are reads), the `use_resource` declarations, and an indirect dispatch's arguments buffer (a read). The diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index 390cc8f7a..2ed6892e1 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -17,6 +17,8 @@ pub(crate) enum Metric { PipelinesCreated, /// [`Metrics::blocks_made`]. BlocksMade, + /// [`Metrics::dispatches_without_effects`]. + DispatchesWithoutEffects, /// [`Metrics::translations`]. Translations, /// [`Metrics::translations_loaded`]. @@ -88,6 +90,7 @@ struct Atomics { first_use_wait_nanos: AtomicU64, first_use_wait_max_nanos: AtomicU64, blocks_made: AtomicU64, + dispatches_without_effects: AtomicU64, translations: AtomicU64, translations_loaded: AtomicU64, ring_writes: AtomicU64, @@ -136,6 +139,7 @@ impl Counters { Metric::Barriers => &a.barriers, Metric::PipelinesCreated => &a.pipelines_created, Metric::BlocksMade => &a.blocks_made, + Metric::DispatchesWithoutEffects => &a.dispatches_without_effects, Metric::Translations => &a.translations, Metric::TranslationsLoaded => &a.translations_loaded, Metric::RingWrites => &a.ring_writes, @@ -259,6 +263,7 @@ impl Counters { first_use_wait_nanos: a.first_use_wait_nanos.load(Relaxed), first_use_wait_max_nanos: a.first_use_wait_max_nanos.load(Relaxed), blocks_made: a.blocks_made.load(Relaxed), + dispatches_without_effects: a.dispatches_without_effects.load(Relaxed), translations: a.translations.load(Relaxed), translations_loaded: a.translations_loaded.load(Relaxed), cache_bytes_written: a.cache_bytes_written.load(Relaxed), @@ -328,6 +333,10 @@ pub struct Metrics { /// `VkDeviceMemory` allocations made: pooled blocks (the texture blocks among them) and /// dedicated ones, the zero source and the parameter ring's blocks. pub blocks_made: u64, + /// Dispatches of a kernel that writes no memory (`PipelineInterface::writes_memory`), + /// direct and indirect: each was checked as Metal checks it, and nothing was recorded, bound + /// or read for it, as it has no effect a program can observe. + pub dispatches_without_effects: u64, /// Kernels the translator lowered, each a module of a compute pipeline content the device did /// not hold compiled: one for a kernel that does not observe its threadgroup partition, two /// for one that does. A state of a content the device holds lowers nothing. diff --git a/crates/metal2vulkan-rt/src/encoder.rs b/crates/metal2vulkan-rt/src/encoder.rs index 006e26bee..f47d3214b 100644 --- a/crates/metal2vulkan-rt/src/encoder.rs +++ b/crates/metal2vulkan-rt/src/encoder.rs @@ -444,6 +444,11 @@ impl ComputeCommandEncoder { /// A count above the device's `maxComputeWorkGroupCount` is split into dispatches within it, /// each reading Metal's whole grid from its region. /// + /// A kernel that writes no memory (`PipelineInterface::writes_memory`) has no effect a program + /// can observe: once the threadgroup size is checked, its dispatch, direct or indirect, records + /// nothing, binds nothing and reads no indirect buffer + /// ([`Metrics::dispatches_without_effects`](crate::Metrics::dispatches_without_effects)). + /// /// A threadgroup that is not whole subgroups of a kernel whose tier runs only whole ones (32 /// threads where each SIMD group is a 32-lane cluster of a 64-lane subgroup included) runs /// the kernel's emulated-SIMD-group module, waiting for the reaper's lowering of it where @@ -531,7 +536,6 @@ impl ComputeCommandEncoder { length: buffer.length(), })); } - self.building().keep(buffer); self.dispatch(Grid::Indirect(buffer, offset), threads_per_threadgroup) } @@ -583,6 +587,16 @@ impl ComputeCommandEncoder { max: limits.max_group_size, })); } + // A kernel that writes no memory has no effect a program can observe: once checked as + // Metal checks it, the dispatch records nothing, binds nothing and reads no indirect + // buffer. Every module of a state is the same function, so the whole module answers. + if !inner.whole.interface.has_effects { + core.counters.count(Metric::DispatchesWithoutEffects); + return Ok(()); + } + if let Grid::Indirect(buffer, _) = &grid { + self.building().keep(buffer); + } // What runs: the module, which of the state's it is, its workgroup size, the threadgroup // size its regions carry, and for a direct dispatch Metal's grid, the workgroups, and // whether the last along some axis is partial. diff --git a/crates/metal2vulkan-rt/src/pipeline.rs b/crates/metal2vulkan-rt/src/pipeline.rs index 75b3a023b..747344342 100644 --- a/crates/metal2vulkan-rt/src/pipeline.rs +++ b/crates/metal2vulkan-rt/src/pipeline.rs @@ -259,6 +259,9 @@ pub(crate) struct Interface { pub(crate) reads_unbound: bool, /// Whether the kernel writes through an address that is not one of its bound slots. pub(crate) writes_unbound: bool, + /// Whether the kernel writes memory another invocation or a later command can read + /// (`PipelineInterface::writes_memory`): a dispatch of a kernel without it records nothing. + pub(crate) has_effects: bool, /// Bytes of the push window the fields use. pub(crate) push_len: u32, /// The length of the ring block of the fields past the window, a multiple of 16; 0 where @@ -889,6 +892,7 @@ fn interface( constexprs, reads_unbound: translated.reads_unbound_resources, writes_unbound: translated.writes_unbound_resources, + has_effects: translated.writes_memory, push_len, block_len, block_address, diff --git a/crates/metal2vulkan-rt/src/tests/compute.rs b/crates/metal2vulkan-rt/src/tests/compute.rs index 2457f3b8b..beb3caa4d 100644 --- a/crates/metal2vulkan-rt/src/tests/compute.rs +++ b/crates/metal2vulkan-rt/src/tests/compute.rs @@ -2,7 +2,7 @@ //! buffers and `set_bytes`, parameters past the push window //! through the ring, indirect dispatch, barriers only at hazards in a serial encoder and only on //! request in a concurrent one, end barriers that reach the host only after Shared writes and -//! signals, and Metal's refusals. +//! signals, a dispatch of a kernel without effects that records nothing, and Metal's refusals. #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { @@ -40,6 +40,7 @@ mod on_device { constexprs: Vec::new(), reads_unbound: false, writes_unbound: false, + has_effects: true, push_len, block_len: 0, block_address: 0, @@ -498,6 +499,54 @@ mod on_device { }); } + /// A dispatch of a kernel that writes no memory (`Interface::has_effects` false, from the + /// translator's `PipelineInterface::writes_memory`) records nothing: given the step kernel's + /// words under such an interface, a direct and an indirect dispatch leave its buffer as it was, + /// a third with no buffer bound owes no bind, and each is counted. + #[test] + fn every_device_records_nothing_for_a_dispatch_of_a_kernel_without_effects() { + each_device("compute_without_effects", |name, _, device| { + let mut arena = Arena::new(&device); + let (x, arguments) = (arena.buffer(), arena.buffer()); + write_words(&x, |index| index); + write_words(&arguments, |index| match index { + 0..=2 => 1, + _ => 0, + }); + let fields = vec![region(), address(0, Place::Push(32))]; + let mut quiet = interface(vec![(0, Access::ReadWrite)], fields, 40); + quiet.has_effects = false; + let state = ComputePipelineState::for_test(&device, &kernels::STEP, quiet) + .expect("the step kernel"); + let before = device.counters().metrics().dispatches_without_effects; + let queue = device.new_command_queue(4).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer + .compute_command_encoder(DispatchType::Serial) + .expect("an encoder"); + encoder.set_compute_pipeline_state(&state).expect("a state"); + encoder + .dispatch_threadgroups([1, 1, 1], [16, 1, 1]) + .expect("an unbound dispatch"); + encoder.set_buffer(Some(&x), 0, 0).expect("a buffer"); + encoder + .dispatch_threadgroups([4, 1, 1], [16, 1, 1]) + .expect("a dispatch"); + encoder + .dispatch_threadgroups_with_indirect_buffer(&arguments, 0, [16, 1, 1]) + .expect("an indirect dispatch"); + encoder.end_encoding(); + run(name, &command_buffer); + let expected: Vec = (0..WORDS as u32).collect(); + assert_eq!(words(&x), expected, "{name}: the words"); + assert_eq!( + device.counters().metrics().dispatches_without_effects - before, + 3, + "{name}: the dispatches counted" + ); + }); + } + /// An indirect dispatch after a write that no barrier since has ordered before indirect /// argument reads gets a barrier that does: a dispatch writes the arguments, a direct /// dispatch that reads them follows (its barrier reaches shader accesses alone), and the diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 1095ea775..0e4de59a3 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1405,7 +1405,8 @@ codec_struct! { PipelineInterface { slots, threadgroup, needs_pointer_translation, needs_handle_translation, push, reaches_command_buffers, command_writes, texture_writing_stages, - reads_unbound_resources, writes_unbound_resources, numbered_samplers, stage_in, + reads_unbound_resources, writes_unbound_resources, writes_memory, numbered_samplers, + stage_in, } PipelineLayout { sets, push_constants, push_descriptor_eligible } DescriptorSetLayout { set, bindings, flags } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 0c3db4fdd..d85adb499 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2169; +pub const SEMANTICS_VERSION: u32 = 2170; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2169; /// 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 = 533; +pub const ARTIFACT_FORMAT_VERSION: u32 = 534; /// 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 diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 7777cd39b..093be602d 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -769,6 +769,7 @@ mod serde_round_trips { texture_writing_stages: vec![Stage::Vertex, Stage::Fragment], reads_unbound_resources: true, writes_unbound_resources: false, + writes_memory: true, numbered_samplers: vec![ ( Stage::Fragment, diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index 59793698e..3b397dbe4 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -2873,6 +2873,78 @@ fn the_interface_states_whether_the_function_writes_memory() { assert!(!a.interface.writes_memory); } +/// A kernel over `out` (buffer 0, read-write) and `params` (buffer 1, read), with +/// `thread_position_in_grid` as `%2`; `body` holds the entry's instructions and its blocks, `extra` +/// any function it calls. +fn effects_kernel(name: &str, body: &str, extra: &str) -> String { + format!( + "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\ + {extra}\ + define void @{name}(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0, ptr addrspace(1) noundef \"air-buffer-no-alias\" %1, i32 noundef %2) {{\nentry:\n{body}}}\n\n\ + !air.kernel = !{{!9}}\n!air.version = !{{!17}}\n!air.language_version = !{{!18}}\n\ + !9 = !{{ptr @{name}, !10, !11}}\n!10 = !{{}}\n!11 = !{{!12, !13, !14}}\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\", !\"out\"}}\n\ + !13 = !{{i32 1, !\"air.buffer\", !\"air.location_index\", i32 1, i32 1, !\"air.read\", !\"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\", !\"params\"}}\n\ + !14 = !{{i32 2, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"t\"}}\n\ + !17 = !{{i32 2, i32 8, i32 0}}\n!18 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n" + ) +} + +/// A compute pipeline's interface states whether its kernel writes memory, which the runtime reads +/// to record nothing for a dispatch of a kernel that does not: a kernel that returns at once, one +/// that only reads its buffers, and one that writes only its own thread's array write none; one that +/// stores to its buffer behind a branch, and one whose callee (kept a call, `noinline`) stores +/// through the pointer it is passed, write memory. +#[test] +fn a_compute_pipeline_states_whether_its_kernel_writes_memory() { + let p = + crate::pipeline::testing::profile("lavapipe", DevicePolicy::default()).expect("profile"); + let callee = "define void @put(ptr addrspace(1) noundef %p, i32 noundef %v) #0 {\nentry:\n store i32 %v, ptr addrspace(1) %p, align 4\n ret void\n}\n\nattributes #0 = { noinline }\n\n"; + for (name, body, extra, writes) in [ + ("bare_return", " ret void\n", "", false), + ( + "only_reads", + " %p = load i32, ptr addrspace(1) %1, align 4\n %q = load i32, ptr addrspace(1) %0, align 4\n %s = add i32 %p, %q\n ret void\n", + "", + false, + ), + ( + "local_only", + " %a = alloca [4 x i32], align 4\n %i = and i32 %2, 3\n %ie = zext i32 %i to i64\n %e = getelementptr inbounds [4 x i32], ptr %a, i64 0, i64 %ie\n store i32 %2, ptr %e, align 4\n %j = xor i32 %i, 1\n %je = zext i32 %j to i64\n %f = getelementptr inbounds [4 x i32], ptr %a, i64 0, i64 %je\n %v = load i32, ptr %f, align 4\n ret void\n", + "", + false, + ), + ( + "branch_store", + " %p = load i32, ptr addrspace(1) %1, align 4\n %c = icmp ne i32 %p, 0\n br i1 %c, label %then, label %done\nthen:\n store i32 %2, ptr addrspace(1) %0, align 4\n br label %done\ndone:\n ret void\n", + "", + true, + ), + ( + "callee_store", + " call void @put(ptr addrspace(1) noundef %0, i32 noundef %2)\n ret void\n", + callee, + true, + ), + ] { + let Some(bc) = assemble_text(name, &effects_kernel(name, body, extra)) else { + return; + }; + let a = crate::pipeline::testing::compile(&bc, name, &p) + .unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!(a.interface.writes_memory, writes, "{name}"); + let linked = crate::pipeline::link::link( + &[&*a], + &crate::pipeline::link::LinkInputs::standalone(), + &p, + ) + .unwrap_or_else(|e| panic!("{name}: link: {e}")); + assert_eq!(linked.interface.writes_memory, writes, "{name}: pipeline"); + crate::pipeline::testing::link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); + } +} + /// The interface states whether the function takes an indirect command buffer, from the AIR's /// metadata: an argument buffer's `command_buffer` member the kernel never encodes through /// (`kernel_icb_declared_handle_is_inert`), and one it encodes compute commands through diff --git a/crates/metal2vulkan/src/pipeline/interface.rs b/crates/metal2vulkan/src/pipeline/interface.rs index 7f181c620..8fd37c470 100644 --- a/crates/metal2vulkan/src/pipeline/interface.rs +++ b/crates/metal2vulkan/src/pipeline/interface.rs @@ -55,6 +55,13 @@ pub struct PipelineInterface { /// pipeline. #[cfg_attr(feature = "serde", serde(default))] pub writes_unbound_resources: bool, + /// Some stage's function writes memory another invocation or a later command can read + /// (`StageInterface::writes_memory`): a store to a buffer or through a device address, a + /// texture write, or an atomic update, in the entry or any function it calls. `false` is proven + /// of every function of the pipeline: a compute pipeline's kernel without it has no effect a + /// program can observe, so a dispatch of it may run nothing. + #[cfg_attr(feature = "serde", serde(default))] + pub writes_memory: bool, /// The samplers a pipeline state numbers for each of its Metal functions /// (`StageInterface::numbered_samplers`, [`NumberedSampler`]), each function's in Metal's /// order, the functions in the pipeline's stage order: what the runtime gives sampler diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index 7b538c8b6..72614733b 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -1737,6 +1737,7 @@ fn pipeline_interface(ifaces: &[&StageInterface]) -> PipelineInterface { } out.reads_unbound_resources |= i.reads_unbound_resources; out.writes_unbound_resources |= i.writes_unbound_resources; + out.writes_memory |= i.writes_memory; out.numbered_samplers .push((i.stage, i.numbered_samplers.clone())); out.push.push(i.push.clone()); diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 792fb42c7..7609e3c82 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2286,6 +2286,7 @@ field metal2vulkan-rt::Metrics.bytes_copied pub bytes_copied: u64 field metal2vulkan-rt::Metrics.cache_bytes_written pub cache_bytes_written: u64 field metal2vulkan-rt::Metrics.commit_lock_wait_max_nanos pub commit_lock_wait_max_nanos: u64 field metal2vulkan-rt::Metrics.commit_lock_wait_nanos pub commit_lock_wait_nanos: u64 +field metal2vulkan-rt::Metrics.dispatches_without_effects pub dispatches_without_effects: u64 field metal2vulkan-rt::Metrics.first_use_wait_max_nanos pub first_use_wait_max_nanos: u64 field metal2vulkan-rt::Metrics.first_use_wait_nanos pub first_use_wait_nanos: u64 field metal2vulkan-rt::Metrics.first_use_waits pub first_use_waits: u64 @@ -5583,6 +5584,7 @@ field metal2vulkan::pipeline::PipelineInterface.slots pub slots: BTreeMap field metal2vulkan::pipeline::PipelineInterface.texture_writing_stages pub texture_writing_stages: Vec field metal2vulkan::pipeline::PipelineInterface.threadgroup pub threadgroup: Vec +field metal2vulkan::pipeline::PipelineInterface.writes_memory pub writes_memory: bool field metal2vulkan::pipeline::PipelineInterface.writes_unbound_resources pub writes_unbound_resources: bool field metal2vulkan::pipeline::PipelineLayout.push_constants pub push_constants: Vec field metal2vulkan::pipeline::PipelineLayout.push_descriptor_eligible pub push_descriptor_eligible: bool diff --git a/docs/API.md b/docs/API.md index d35046e4e..126b36055 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1675,6 +1675,10 @@ for dependency in &pipeline.dependencies { records they reach: the indirect-command operations they may call, and the primitive types their draws may pass (a draw's constant type, or all five where it is not a constant). A clear bit is proven. +- `interface.writes_memory` says, provably, whether a pipeline's functions write memory another + invocation or a later command can read: a store to a buffer or through a device address, a + texture write, or an atomic update. A compute pipeline without it has no effect a program can + observe, so a runtime may run nothing for its dispatches. - `interface.reads_unbound_resources` and `interface.writes_unbound_resources` say, provably, whether a pipeline's functions may read or write a resource through anything but their bound slots: through a pointer or texture they load from memory or make from an integer (an argument