From 979efab2f15ece1d67680bf0addebce43ac17d6d Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 12 Nov 2026 16:13:25 -0800 Subject: [PATCH] A one-row ragged dispatch of a simdgroup-only kernel runs flat in the call's threadgroups A direct dispatchThreads: whose grid is not a whole number of threadgroups split into an interior and an edge region, each its own VkPipeline, for every kernel that observes its threadgroup partition. A kernel that observes it only through its simdgroups (simdgroup barriers, simdgroup and quad functions, lane builtins) computes the same in any partition that keeps its threadgroups, so for a one-row grid in threadgroups of one row it can run Metal's own single dispatch: the flat grid, in the call's threadgroups, with the last simdgroup's lanes past the grid returned before the body, as Metal's partial simdgroup lacks them. A guest's 4.5 M-word kernel that observes its partition only through simdgroup barriers took 116 s per VkPipeline on the RX 7900 XTX; its edge no longer compiles a second one. Translator: - partition.rs classifies a kernel as oblivious, simdgroups-only or observed. The decision uses structure only: barrier and fence/atomic scopes, simd_/quad_ functions, is_uniform, the simdgroup size, and the builtins thread_index_in_simdgroup, thread_index_in_quadgroup and threads_per_simdgroup. air.all/air.any of a boolean vector (BoolReduce) no longer counts as an observation: it is a thread's own vector reduction. - New KernelFacts::partition_simdgroups. - LoweringInputs, VariantKey::call_threadgroups and RuntimeFact::CallThreadgroups (Variant mechanism): with flat_grid, the invocations count their threads by lin (the flattened tiers' subgroup order), so workgroup w is Metal's threadgroup w with its simdgroups, and the lane builtins are derived. - The compile admits a simdgroups-only kernel under it. It refuses the input without flat_grid or with replay_bindings, and refuses a module that would hold a workgroup barrier (emulated tier, or a simdgroup barrier at workgroup scope where the subgroup is not the simdgroup). Runtime: flat_direct tries the flat variant of any threadgroups first. For a one-row grid in threadgroups of one row, it then tries the call's variant (settle_flat(.., call)), which keeps its own refusal flag and skips a threadgroup size that asks for emulated simdgroups. Indirect and replay paths still need an oblivious kernel. Tests: - partition classes: each builtin and feature, mixed cases, boolean reductions; - the artifact's two facts; - the input's key; - a_flat_grid_of_the_call_s_threadgroups_admits_a_kernel_of_simdgroups over every committed profile; - the device test flat_simdgroups. It covers: lanes in one row (1 VkPipeline); two rows and a threadgroup barrier (2, the split); a simdgroup barrier with simd_sum (1 where the tier asks for full subgroups, else 2). Every thread's word is checked against Metal's partition, including the partial simdgroup's sum. ARTIFACT_FORMAT_VERSION bump (KernelFacts gains a field) is main's. --- crates/metal2vulkan-runtime/src/compute.rs | 21 +- .../metal2vulkan-runtime/src/pipeline/mod.rs | 30 ++- .../src/tests/flat_simdgroups.rs | 189 ++++++++++++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + crates/metal2vulkan/src/bind/plan/compute.rs | 7 +- crates/metal2vulkan/src/cache/codec.rs | 3 +- crates/metal2vulkan/src/cache/mod.rs | 10 + crates/metal2vulkan/src/device/mechanism.rs | 1 + .../src/device/tests/mechanism.rs | 5 +- crates/metal2vulkan/src/library/compiled.rs | 9 + crates/metal2vulkan/src/lower/dispatch.rs | 59 ++++- .../metal2vulkan/src/lower/dispatch/tests.rs | 1 + crates/metal2vulkan/src/lower/select.rs | 11 + crates/metal2vulkan/src/pipeline/api_tests.rs | 2 + crates/metal2vulkan/src/pipeline/compile.rs | 22 +- .../metal2vulkan/src/pipeline/compile/key.rs | 4 + .../src/pipeline/compile/partition.rs | 245 ++++++++++++------ .../src/pipeline/compile/tests.rs | 10 + crates/metal2vulkan/src/pipeline/facts.rs | 5 + .../metal2vulkan/src/pipeline/lower_inputs.rs | 21 +- .../src/tests/engine_device_replay.rs | 124 +++++++++ crates/metal2vulkan/tests/api_signatures.tsv | 3 + 22 files changed, 673 insertions(+), 111 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/flat_simdgroups.rs diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 187d80a47..d170a4499 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -1843,7 +1843,7 @@ fn settle_indirect( if let Some(indirect) = call.indirect(pipeline) { let local = indirect.threads_per_threadgroup; let flat = flat_dispatch(local); - if let Some((variant, plan)) = pipeline.settle_flat(shape, local, &flat)? { + if let Some((variant, plan)) = pipeline.settle_flat(shape, local, &flat, false)? { return Ok(Some((variant, plan, indirect))); } } @@ -1867,9 +1867,18 @@ fn settle_indirect( /// call's size too: on a guest's run on an RX 7900 XTX, a kernel dispatched at 64 such widths /// made 185,566 `VkPipeline`s in 45 s while its variant kept 32 (`pipeline::REGION_PIPELINES`). /// +/// A kernel that observes its partition through its simdgroups alone +/// (`KernelFacts::partition_simdgroups`: a simdgroup barrier, function or lane builtin, and nothing +/// of its threadgroup) runs a one-row grid in threadgroups of one row on the flat variant of the +/// call's threadgroups (`VariantKey::call_threadgroups`): its workgroups are Metal's threadgroups, +/// its simdgroups Metal's, the last one's lanes past the grid returned before the body. So a +/// kernel compiled once does not compile a second `VkPipeline` for its ragged edge. +/// /// `None`, so the dispatch keeps its exact split, where its grid is already a whole number of /// threadgroups on every axis (the split is one region of the call's size, which the flat form -/// cannot better) or is empty, where the kernel observes its threadgroup partition or the device +/// cannot better) or is empty, where the kernel observes its threadgroup partition (through its +/// simdgroups alone, where the grid or its threadgroups are not one row, or where the module would +/// hold a workgroup barrier or emulate its simdgroups) or the device /// reaches no memory by device address /// (the compile layer's refusal, which the state remembers), where the flat form cannot cover the /// grid within the device's `maxComputeWorkGroupCount`, or in the large-buffer form, whose key @@ -1897,7 +1906,13 @@ fn flat_direct( if empty || (0..3).all(|i| threads[i] % threads_per_group[i] == 0) { return Ok(None); } - match pipeline.settle_flat(shape, threads_per_group, dispatch) { + // The variant of any threadgroups, else, for one row in threadgroups of one row, the call's. + let mut settled = pipeline.settle_flat(shape, threads_per_group, dispatch, false); + let one_row = threads[1..] == [1, 1] && threads_per_group[1..] == [1, 1]; + if one_row && matches!(settled, Ok(None)) { + settled = pipeline.settle_flat(shape, threads_per_group, dispatch, true); + } + match settled { Ok(settled) => Ok(settled), // A grid the flat form cannot cover within the device's group-count limits: the split // covers it exactly, region by region. diff --git a/crates/metal2vulkan-runtime/src/pipeline/mod.rs b/crates/metal2vulkan-runtime/src/pipeline/mod.rs index 12b025eae..8408e4fe9 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/mod.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/mod.rs @@ -348,6 +348,9 @@ pub(super) struct Program { /// The compile layer refused the kernel a flat variant ([`ComputePipelineState::settle_flat`]), /// so its indirect dispatches take the host step. flat_refused: AtomicBool, + /// The compile layer refused the kernel a flat variant of the call's threadgroups + /// ([`ComputePipelineState::settle_flat`]), so its direct dispatches of a ragged grid split. + call_flat_refused: AtomicBool, /// The state has no flat device-replay variant whose plan binds no descriptor /// ([`ComputePipelineState::replay_variant`]), so an execution of an indirect command /// buffer that may run it takes the host step. @@ -967,6 +970,7 @@ impl ComputePipelineState { stand_in, others: Mutex::new(Lru::counted(VARIANTS)), flat_refused: AtomicBool::new(false), + call_flat_refused: AtomicBool::new(false), replay_refused: AtomicBool::new(false), folded_refused: AtomicBool::new(false), added_unsupported, @@ -1654,17 +1658,27 @@ impl ComputePipelineState { /// `dispatch` is an indirect dispatch at the group counts a preprocess writes /// (`indirect_dispatch.rs`) or a direct `dispatchThreads:` whose grid the variant's one region /// covers (`compute::flat_direct`); the variant's plan must run that very dispatch, which the - /// check against `key` states. `None` where the compile layer refuses the kernel a flat - /// variant, `Unsupported{GpuEncodedIndirectCommands}`: the kernel observes its threadgroup - /// partition (`KernelFacts::partition_oblivious`), or the device reaches no memory by device - /// address. The state remembers that refusal, which no bind shape changes. + /// check against `key` states. With `call`, the variant of the call's threadgroups + /// (`VariantKey::call_threadgroups`), for a one-row grid in threadgroups of one row of a + /// direct dispatch. `None` where the compile layer refuses the kernel such a variant, + /// `Unsupported{GpuEncodedIndirectCommands}`: the kernel observes its threadgroup partition + /// (`KernelFacts::partition_oblivious`; with `call`, otherwise than through its simdgroups, + /// `KernelFacts::partition_simdgroups`, or its module would hold a workgroup barrier), or the + /// device reaches no memory by device address. The state remembers that refusal, which no + /// bind shape changes. With `call`, also `None` where `local` asks for emulated simdgroups, + /// which no flat variant runs, unremembered: another threadgroup size may not. pub(super) fn settle_flat( &self, shape: &BindShape, local: [u32; 3], dispatch: &Dispatch, + call: bool, ) -> Result, Arc)>, Error> { - if self.0.flat_refused.load(Ordering::Relaxed) { + let refused = match call { + false => &self.0.flat_refused, + true => &self.0.call_flat_refused, + }; + if refused.load(Ordering::Relaxed) { return Ok(None); } let plan = self.0.base.plan(&self.0.device, shape)?; @@ -1674,13 +1688,17 @@ impl ComputePipelineState { let mut key = plan .dispatch_variant(&flat_dispatch(local)) .map_err(Error::Bind)?; + if call && key.emulated_simdgroups { + return Ok(None); + } key.flat_grid = true; + key.call_threadgroups = call; let variant = match self.variant(&key) { Ok(variant) => variant, Err(Error::Unsupported(unsupported)) if unsupported.feature == Feature::GpuEncodedIndirectCommands => { - self.0.flat_refused.store(true, Ordering::Relaxed); + refused.store(true, Ordering::Relaxed); return Ok(None); } Err(error) => return Err(error), diff --git a/crates/metal2vulkan-runtime/src/tests/flat_simdgroups.rs b/crates/metal2vulkan-runtime/src/tests/flat_simdgroups.rs new file mode 100644 index 000000000..87811b087 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/flat_simdgroups.rs @@ -0,0 +1,189 @@ +//! A direct `dispatchThreads:` of a ragged one-row grid in threadgroups of one row, of a kernel +//! that observes its threadgroup partition through its simdgroups alone, runs on the flat variant +//! of the call's threadgroups (`compute.rs`'s `flat_direct`, `VariantKey::call_threadgroups`): one +//! `VkPipeline`, where the split makes one for its interior and one for its edge, every thread's +//! lane and simdgroup what Metal's threadgroups give it, the last simdgroup's lanes past the grid +//! left out of its reduction as Metal's partial simdgroup leaves them. A grid of two rows splits, +//! and so does a kernel with a threadgroup barrier. A kernel with a simdgroup barrier and a +//! reduction runs flat where its simdgroups are the device's subgroups (its tier asks for full +//! subgroups) and splits where they are not (lavapipe's 8-lane subgroups, which emulate them). +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The kernels are LLVM text written here +//! (`llvm-as`). + +use super::blit_holds::{device, Scratch, WAIT}; +use crate::{ + Buffer, CommandBufferStatus, ComputePipelineState, Device, PipelineOptions, ResourceOptions, + Size, +}; +use metal2vulkan::pipeline::{ + ComputePipelineDescriptor, FunctionDescriptor, LoweringInputs, StageSource, +}; + +/// The grid's threads along `x`: one threadgroup of [`GROUP`] and a ragged one of 36. +const THREADS: u64 = 100; +/// The call's threadgroup: one row of two simdgroups. +const GROUP: u64 = 64; + +/// A kernel `k` storing, for each thread at `out[p]` (`p` its position in the grid), its index in +/// its simdgroup (`l`), or what `body` computes from it into `%v`, after `before`, with the +/// module's `declarations`. +fn kernel(before: &str, body: &str, declarations: &str) -> String { + format!( + r#"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" +target triple = "air64_v28-apple-macosx26.0.0" + +define void @k(ptr addrspace(1) %out, i32 %p, i32 %l) {{ +{before} {body} + %i = zext i32 %p to i64 + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %i + store i32 %v, ptr addrspace(1) %o, align 4 + ret void +}} +{declarations} +!air.kernel = !{{!0}} +!air.version = !{{!11}} +!air.language_version = !{{!12}} +!0 = !{{ptr @k, !1, !2}} +!1 = !{{}} +!2 = !{{!3, !4, !5}} +!3 = !{{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"}} +!4 = !{{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"p"}} +!5 = !{{i32 2, !"air.thread_index_in_simdgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"l"}} +!11 = !{{i32 2, i32 8, i32 0}} +!12 = !{{!"Metal", i32 4, i32 0, i32 0}} +"# + ) +} + +/// Each thread's lane. +fn lanes() -> String { + kernel("", "%v = add i32 %l, 0", "") +} + +/// Each thread's lane, after a threadgroup barrier. +fn threadgroup_barrier() -> String { + kernel( + " call void @air.wg.barrier(i32 1, i32 1)\n", + "%v = add i32 %l, 0", + "declare void @air.wg.barrier(i32, i32)\n", + ) +} + +/// The sum of the lanes of each thread's simdgroup, after a simdgroup barrier. +fn simdgroup_sum() -> String { + kernel( + " call void @air.simdgroup.barrier(i32 1, i32 4)\n", + "%v = call i32 @air.simd_sum.u.i32(i32 %l)", + "declare void @air.simdgroup.barrier(i32, i32)\ndeclare i32 @air.simd_sum.u.i32(i32)\n", + ) +} + +/// What Metal's threadgroups of [`GROUP`] give thread `p` of a grid of [`THREADS`] along `x`: its +/// lane, and the sum of the lanes of its simdgroup, the last one's lanes those of the threads left. +fn metal(p: u64) -> (u32, u32) { + let index = p % GROUP; + let first = p - index % 32; + let live = (THREADS - first).min(32); + ((index % 32) as u32, (0..live).sum::() as u32) +} + +/// The compute state of kernel `text` on `device`. +fn state(device: &Device, text: &str) -> ComputePipelineState { + let air = metal2vulkan_devtools::llvm_assemble_text(text).unwrap(); + let library = metal2vulkan::library::Library::from_air(&air).unwrap(); + let function = device + .new_library_with_compile_library(library) + .new_function_with_name("k") + .unwrap(); + let descriptor = + ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())); + device + .new_compute_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() +} + +/// Whether kernel `text`'s simdgroups are `device`'s subgroups: its tier asks for full subgroups +/// (`Direct`, `Cluster32`), so its simdgroup barrier is a subgroup one. +fn full_subgroups(device: &Device, text: &str) -> bool { + let air = metal2vulkan_devtools::llvm_assemble_text(text).unwrap(); + let library = metal2vulkan::library::Library::from_air(&air).unwrap(); + let function = FunctionDescriptor::new(library.function("k").unwrap()); + device + .compile_device() + .compile_function( + &function, + &LoweringInputs::new(), + &metal2vulkan::Budget::standard(), + ) + .unwrap() + .requires_full_subgroups() +} + +/// Dispatch `state` over `rows` rows of [`THREADS`] in threadgroups of [`GROUP`], and the +/// `VkPipeline`s the dispatch made and the first row's words it wrote. +fn run(device: &Device, state: &ComputePipelineState, rows: u64) -> (u64, Vec) { + let out: Buffer = device + .new_buffer_with_bytes(&[0xff; 4 * THREADS as usize], ResourceOptions::shared()) + .unwrap(); + let made = device.work_counts().variant_pipelines_made; + 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_compute_pipeline_state(state).unwrap(); + encoder.set_buffer(Some(&out), 0, 0).unwrap(); + encoder + .dispatch_threads(Size::new(THREADS, rows, 1), Size::new(GROUP, 1, 1)) + .unwrap(); + 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!(command_buffer.error(), None); + let made = device.work_counts().variant_pipelines_made - made; + let contents = out.contents().unwrap(); + // SAFETY: the buffer's bytes, which the completed command buffer wrote. + let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), 4 * THREADS as usize) }; + let words = (bytes.as_chunks::<4>().0.iter()) + .map(|&word| u32::from_le_bytes(word)) + .collect(); + (made, words) +} + +#[test] +fn a_ragged_row_of_a_simdgroup_kernel_runs_flat_in_the_call_s_threadgroups() { + let scratch = Scratch::new("flat-simdgroups"); + let device = device(&scratch.0); + let lane = |p: u64| metal(p).0; + let sum = |p: u64| metal(p).1; + let cases: [(&str, String, u64, fn(u64) -> u32); 4] = [ + ("lanes", lanes(), 1, lane), + ("lanes over two rows", lanes(), 2, lane), + ("threadgroup barrier", threadgroup_barrier(), 1, lane), + ("simdgroup sum", simdgroup_sum(), 1, sum), + ]; + let mut made = Vec::new(); + for (name, text, rows, expected) in &cases { + let state = state(&device, text); + let (pipelines, words) = run(&device, &state, *rows); + for (p, &word) in words.iter().enumerate() { + assert_eq!(word, expected(p as u64), "{name}: thread {p}"); + } + made.push(pipelines); + } + let flat_sum = full_subgroups(&device, &simdgroup_sum()); + println!( + "FLAT-SIMDGROUPS {}: VkPipelines made {made:?} for {:?}; the sum's simdgroups are \ + subgroups: {flat_sum}", + device.name(), + cases.each_ref().map(|case| case.0), + ); + // One flat `VkPipeline`; the split's interior and edge; the split again; one where the + // simdgroups are subgroups, else the split's two. + let sum_made = match flat_sum { + true => 1, + false => 2, + }; + assert_eq!(made, [1, 2, 2, sum_made]); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index f69844e26..9691968d6 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -221,6 +221,8 @@ mod fill_waits_bench; mod first_host_texture; mod first_moves; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod flat_simdgroups; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod footprint_locks; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod framebuffer_fetch; diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index 3020250e1..d60bcef08 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -857,11 +857,16 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result Mechanism { RuntimeFact::OneRow => Mechanism::Variant, // A pipeline compiled under the flat-grid variant; its plans state it. RuntimeFact::FlatGrid => Mechanism::Variant, + RuntimeFact::CallThreadgroups => Mechanism::Variant, // A sparse texture's writes are dropped under the slot's `SparseTexture` specialization; // at a slot updated atomically the planner refuses one. RuntimeFact::SparseTextureWrites { atomic: false, .. } => Mechanism::Specialization, diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 82c94e370..691a9e72c 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -133,6 +133,7 @@ fn every_fact() -> Vec { RuntimeFact::RowLockstep, RuntimeFact::OneRow, RuntimeFact::FlatGrid, + RuntimeFact::CallThreadgroups, RuntimeFact::SparseTextureWrites { slot, atomic: false, @@ -384,6 +385,7 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::HeapResidency { .. } => 94, RuntimeFact::OneRow => 95, RuntimeFact::RegionViewports => 96, + RuntimeFact::CallThreadgroups => 97, } } @@ -391,7 +393,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..97).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..98).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -460,6 +462,7 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::SrgbTexture { .. } | RuntimeFact::CrossClassReads { .. } | RuntimeFact::FlatGrid + | RuntimeFact::CallThreadgroups | RuntimeFact::OneRow | RuntimeFact::AmplificationDraws { .. } | RuntimeFact::ViewportCompensation { .. } diff --git a/crates/metal2vulkan/src/library/compiled.rs b/crates/metal2vulkan/src/library/compiled.rs index 7ed8e137f..40db36d13 100644 --- a/crates/metal2vulkan/src/library/compiled.rs +++ b/crates/metal2vulkan/src/library/compiled.rs @@ -439,4 +439,13 @@ pub struct KernelFacts { /// threadgroup memory, no barrier, no fence or atomic of threadgroup or simdgroup scope, no /// simdgroup or quad function, and no builtin of the partition. pub partition_oblivious: bool, + /// The kernel observes its threadgroup partition through its simdgroups alone: its only + /// observations are barriers of simdgroup execution scope, fences and atomics of simdgroup + /// scope, simdgroup and quad functions, `is_uniform`, the simdgroup size, and the builtins + /// `thread_index_in_simdgroup`, `thread_index_in_quadgroup` and `threads_per_simdgroup`. It + /// computes the same in any partition that keeps its threadgroups, so a one-dimensional + /// dispatch of the call's threadgroups may run flat (`LoweringInputs::call_threadgroups`). + /// `false` for a kernel that does not observe its partition + /// ([`partition_oblivious`](Self::partition_oblivious)). Decided as that one is. + pub partition_simdgroups: bool, } diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs index a14de14b0..41488df97 100644 --- a/crates/metal2vulkan/src/lower/dispatch.rs +++ b/crates/metal2vulkan/src/lower/dispatch.rs @@ -89,7 +89,14 @@ //! region[1].xyz`, in 64 bits, and takes the position it counts to; one past the grid's last thread //! returns before the body ([`emit_entry`]). Such a kernel reads no builtin but //! `thread_position_in_grid` and `threads_per_grid` (the compile refuses any other kernel under the -//! input). +//! input). Of the call's threadgroups (`LoweringInputs::call_threadgroups`: a one-row grid in +//! threadgroups of one row), the invocation counts by `lin` in place of `LocalInvocationIndex`, +//! so in a flattened tier its thread is its simdgroup lane's, and workgroup `w` is Metal's +//! threadgroup `w` with its simdgroups and quadgroups: a kernel that observes its partition through +//! its simdgroups alone reads `thread_index_in_simdgroup`, `thread_index_in_quadgroup` and +//! `threads_per_simdgroup` too, and its simdgroup operations run on the lanes left live, as on +//! Metal's partial simdgroup. A module that would hold a workgroup barrier there is refused +//! (`select`). //! //! **Folded groups**. A folded variant (`LoweringInputs::folded_groups`) runs a threadgroup //! dispatch whose group counts are GPU data as one dispatch `(nx, ny, nz)` within the device's @@ -406,6 +413,9 @@ pub struct DispatchPlan { pub tile_sized: bool, /// The kernel runs its grid flat (`LoweringInputs::flat_grid`). pub flat_grid: bool, + /// With `flat_grid`, its threadgroups are the call's (`LoweringInputs::call_threadgroups`): + /// it counts its threads by `lin` and may read the lanes' builtins. + pub call_threadgroups: bool, /// The specialization keys of its threadgroup size and grid form: an object function's own, the /// kernel's for every other stage. pub keys: DispatchKeys, @@ -549,6 +559,7 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result, tier: Tier) -> Result, tier: Tier) -> Result bool { + use KernelBuiltin as K; + match b { + K::ThreadPositionInGrid | K::ThreadsPerGrid => true, + K::ThreadIndexInSimdgroup | K::ThreadIndexInQuadgroup | K::ThreadsPerSimdgroup => { + self.call_threadgroups + } + _ => false, + } + } + /// `thread_index_in_threadgroup`: `lin`, or a tile function's index of its position /// ([`Self::tile_index`]), but `lin` where its threadgroup is the tile. fn thread_index(&self, fb: &mut FunctionBuilder<'_>) -> BResult { @@ -1446,8 +1474,8 @@ impl KernelDecl { /// A flat grid's thread position in the grid (a `uvec3`) and whether the invocation is inside /// the grid: its index `((wz · ny + wy) · nx + wx) · N + LocalInvocationIndex` over the - /// dispatch, with `N = sx·sy·sz`, counted over `threads_per_grid` (`region[1].xyz`) `x` - /// fastest. Inside the grid each axis's position is below its size, so it fits its `u32`; + /// dispatch (`lin` for the call's threadgroups, [`Self::lin`]), with `N = sx·sy·sz`, counted + /// over `threads_per_grid` (`region[1].xyz`) `x` fastest. Inside the grid each axis's position is below its size, so it fits its `u32`; /// past it the position is unused. /// /// Three arms, each chosen by values uniform over the workgroup, so a workgroup takes one: @@ -1478,7 +1506,10 @@ impl KernelDecl { })?; let wg = self.load(fb, self.workgroup_id)?; let groups = self.load(fb, self.num_workgroups)?; - let lin = self.load(fb, self.local_index)?; + let lin = match self.call_threadgroups { + true => self.lin(fb)?, + false => self.load(fb, self.local_index)?, + }; let s = self.size3(fb)?; let n = Self::volume(fb, s)?; let r = region(fb)?; diff --git a/crates/metal2vulkan/src/lower/dispatch/tests.rs b/crates/metal2vulkan/src/lower/dispatch/tests.rs index 29bdd9080..018767a8c 100644 --- a/crates/metal2vulkan/src/lower/dispatch/tests.rs +++ b/crates/metal2vulkan/src/lower/dispatch/tests.rs @@ -31,6 +31,7 @@ fn plan(form: LocalSizeForm, multi_region: bool) -> DispatchPlan { tile: false, tile_sized: false, flat_grid: false, + call_threadgroups: false, keys: SpecKey::dispatch_keys(Stage::Kernel), folded_groups: false, draw_pieces: false, diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index b29109750..2c1440911 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1673,6 +1673,17 @@ fn finish( } else { subgroup::tier(&cx.simd, stage, model)? }; + // A flat grid of the call's threadgroups returns its invocations past the grid before the + // body (`dispatch::emit_entry`), so the rest of their workgroup cannot meet a workgroup + // synchronization: a module that would hold one (the emulated tier's exchanges, or a + // simdgroup barrier emitted at workgroup scope where the subgroup is not the simdgroup) is + // refused, and its dispatch runs split instead. + if cx.inputs.flat_grid && cx.inputs.call_threadgroups { + let set = simd::divergent::SyncSet::WorkgroupBarriers { stage, tier }; + if tier == Tier::Emulated || sel.strategy.iter().flatten().any(|s| set.holds(s)) { + return Err(Unsupported::not_implemented(Feature::GpuEncodedIndirectCommands).into()); + } + } if tier == Tier::Emulated { // The emulated tier's exchange carries its own active flags. cx.families.simd.partly_live.clear(); diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index a8a9d7c37..6dfd1fd4f 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -223,6 +223,7 @@ mod serde_round_trips { planes_sampler(), )]), flat_grid: true, + call_threadgroups: true, replay_bindings: true, merged_draws: true, amplification_draws: Some(AmplificationDraws::new(true, false)), @@ -369,6 +370,7 @@ mod serde_round_trips { max_call_stack_depth: Some(8), open_cl_mode: true, flat_grid: true, + call_threadgroups: true, render_target_array_index_varying: true, primitive_id_varying: true, primitive_id_indices: Some(crate::metal::IndexType::UInt16), diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 1e05e1dae..48d29f10a 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -26,6 +26,7 @@ use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::sync::Arc; +use self::partition::Partition; use crate::air::abi::{AbiInt, AirAbi, OutputRole, ParamRole, Stage as AbiStage}; use crate::air::container::{self, LibraryFunction}; use crate::air::{self, ConstValue, LinkedCode, LinkedModule, LinkedName, SpecRequest}; @@ -2690,14 +2691,22 @@ fn plan_one(r: &Request<'_>, p: &DeviceProfile, m: &mut Meter) -> Result observed == Partition::Oblivious, + true => observed <= Partition::Simdgroups, + }; + if inputs.flat_grid && !flat_runs { return Err(Unsupported::not_representable(Feature::GpuEncodedIndirectCommands).into()); } // A folded variant runs one threadgroup dispatch of its own threadgroup size: neither a flat - // grid nor a device replay's bindings. - if inputs.folded_groups && (inputs.flat_grid || inputs.replay_bindings) { + // grid nor a device replay's bindings. The call's threadgroups are a flat grid's alone, and + // not a device replay's, whose commands' threadgroups its preprocess reads. + if inputs.folded_groups && (inputs.flat_grid || inputs.replay_bindings) + || inputs.call_threadgroups && (!inputs.flat_grid || inputs.replay_bindings) + { return Err(Unsupported::not_implemented(Feature::GpuEncodedIndirectCommands).into()); } let linked: Vec> = r.linked.iter().map(|s| s.key).collect(); @@ -2728,7 +2737,8 @@ fn plan_one(r: &Request<'_>, p: &DeviceProfile, m: &mut Meter) -> Result bool { +/// How a kernel observes its threadgroup partition (see the module). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(super) enum Partition { + /// It does not observe it. + Oblivious, + /// It observes it through its simdgroups alone. + Simdgroups, + /// It observes it otherwise, or is not a kernel with a body. + Observed, +} + +/// How kernel `e` observes its threadgroup partition (see the module). Any other stage, and an +/// entry without a body, observes it. +pub(super) fn partition(e: &air::Entry) -> Partition { if !matches!(e.ep.stage, AbiStage::Kernel { .. }) { - return false; + return Partition::Observed; } let Some(body) = e.module.func(e.func).and_then(|f| f.body.as_ref()) else { - return false; + return Partition::Observed; }; if e.module .parts() @@ -46,17 +66,19 @@ pub(super) fn oblivious(e: &air::Entry) -> bool { .iter() .any(|(_, g)| partitioned(g.space)) { - return false; + return Partition::Observed; } let types = e.module.types(); + let mut seen = Partition::Oblivious; let mut read = BTreeSet::new(); for inst in body.insts.values() { if matches!(types.get(inst.ty), Some(Type::Ptr { space }) if partitioned(*space)) { - return false; + return Partition::Observed; } if let InstKind::Call(call) = &inst.kind { - if observes(&call.callee) { - return false; + seen = seen.max(observes(&call.callee)); + if seen == Partition::Observed { + return seen; } } inst.kind.for_each_value(|v| { @@ -65,10 +87,10 @@ pub(super) fn oblivious(e: &air::Entry) -> bool { } }); } - !e.ep - .params - .iter() - .any(|b| read.contains(&b.param) && partition_role(&b.role)) + let params = e.ep.params.iter().filter(|b| read.contains(&b.param)); + params + .map(|b| partition_role(&b.role)) + .fold(seen, Partition::max) } /// Whether `space` is memory one threadgroup shares. @@ -79,36 +101,36 @@ fn partitioned(space: AddrSpace) -> bool { ) } -/// Whether a parameter of `role` is the partition's. -fn partition_role(role: &ParamRole) -> bool { +/// How a parameter of `role`, read, observes the partition. +fn partition_role(role: &ParamRole) -> Partition { match role { - ParamRole::Threadgroup(_) | ParamRole::Imageblock(_) => true, + ParamRole::Threadgroup(_) | ParamRole::Imageblock(_) => Partition::Observed, ParamRole::Builtin(b) => partition_builtin(*b), - _ => false, + _ => Partition::Oblivious, } } -/// Whether builtin `b` reads the partition (see the module). -fn partition_builtin(b: Builtin) -> bool { +/// How builtin `b`, read, observes the partition (see the module). +fn partition_builtin(b: Builtin) -> Partition { match b { + Builtin::ThreadIndexInSimdgroup + | Builtin::ThreadIndexInQuadgroup + | Builtin::ThreadsPerSimdgroup => Partition::Simdgroups, Builtin::ThreadPositionInThreadgroup | Builtin::ThreadgroupPositionInGrid | Builtin::ThreadsPerThreadgroup | Builtin::ThreadgroupsPerGrid | Builtin::ThreadIndexInThreadgroup - | Builtin::ThreadIndexInSimdgroup - | Builtin::ThreadIndexInQuadgroup | Builtin::SimdgroupIndexInThreadgroup | Builtin::QuadgroupIndexInThreadgroup - | Builtin::ThreadsPerSimdgroup | Builtin::SimdgroupsPerThreadgroup | Builtin::QuadgroupsPerThreadgroup | Builtin::DispatchThreadsPerThreadgroup - | Builtin::DispatchSimdgroupsPerThreadgroup => true, + | Builtin::DispatchSimdgroupsPerThreadgroup => Partition::Observed, Builtin::ThreadPositionInGrid | Builtin::ThreadsPerGrid | Builtin::StageInGridSize - | Builtin::StageInGridOrigin => false, + | Builtin::StageInGridOrigin => Partition::Oblivious, // Other stages' builtins: no kernel reads them. Builtin::VertexId | Builtin::InstanceId @@ -127,32 +149,37 @@ fn partition_builtin(b: Builtin) -> bool { | Builtin::PostDepthCoverage | Builtin::BarycentricCoord(_) | Builtin::RenderTargetArrayIndex - | Builtin::ViewportArrayIndex => true, + | Builtin::ViewportArrayIndex => Partition::Observed, } } -/// Whether a call to `callee` observes the partition (see the module). -fn observes(callee: &Callee) -> bool { +/// How a call to `callee` observes the partition (see the module). +fn observes(callee: &Callee) -> Partition { let op = match callee { Callee::Air { op, .. } => op, - Callee::Llvm { .. } => return false, + Callee::Llvm { .. } => return Partition::Oblivious, // Canonicalization inlines every defined callee; what remains is not the kernel's own. Callee::Direct(_) | Callee::Indirect { .. } | Callee::UnknownIntrinsic(_) - | Callee::Unbound { .. } => return true, + | Callee::Unbound { .. } => return Partition::Observed, + }; + let scoped = |scope: ThreadScope| match scope { + ThreadScope::Simdgroup => Partition::Simdgroups, + ThreadScope::Threadgroup => Partition::Observed, + _ => Partition::Oblivious, }; - let scoped = - |scope: ThreadScope| matches!(scope, ThreadScope::Threadgroup | ThreadScope::Simdgroup); match op { - AirIntrinsic::Sync(Sync::Barrier { .. }) => true, + AirIntrinsic::Sync(Sync::Barrier { scope, .. }) => match scope { + ThreadScope::Simdgroup => Partition::Simdgroups, + _ => Partition::Observed, + }, AirIntrinsic::Sync(Sync::Fence { scope, .. }) => scoped(*scope), AirIntrinsic::Atomic(a) => scoped(a.scope), - AirIntrinsic::Group(_) - | AirIntrinsic::BoolReduce(_) - | AirIntrinsic::IsUniform(_) - | AirIntrinsic::SimdgroupSize(_) - | AirIntrinsic::SimdMatrix(_) + AirIntrinsic::Group(_) | AirIntrinsic::IsUniform(_) | AirIntrinsic::SimdgroupSize(_) => { + Partition::Simdgroups + } + AirIntrinsic::SimdMatrix(_) | AirIntrinsic::Imageblock(_) | AirIntrinsic::AsyncCopy(_) | AirIntrinsic::Derivative(_) @@ -162,8 +189,10 @@ fn observes(callee: &Callee) -> bool { | AirIntrinsic::Tensor(_) | AirIntrinsic::AccelerationStructure(_) | AirIntrinsic::Intersect(_) - | AirIntrinsic::Mesh(_) => true, - AirIntrinsic::Fragment(Fragment::IsHelperThread) + | AirIntrinsic::Mesh(_) => Partition::Observed, + // A reduction of a thread's own boolean vector. + AirIntrinsic::BoolReduce(_) + | AirIntrinsic::Fragment(Fragment::IsHelperThread) | AirIntrinsic::Interpolate(_) | AirIntrinsic::Math(_) | AirIntrinsic::Convert(_) @@ -175,9 +204,9 @@ fn observes(callee: &Callee) -> bool { | AirIntrinsic::Sampler(_) | AirIntrinsic::FunctionConstant(_) | AirIntrinsic::FunctionTable(_) - | AirIntrinsic::IndirectCommand(_) => false, + | AirIntrinsic::IndirectCommand(_) => Partition::Oblivious, // The dispatch's offset and dimension count, which every threadgroup reads alike. - AirIntrinsic::WorkItem(_) => false, + AirIntrinsic::WorkItem(_) => Partition::Oblivious, // A global built-in read canonicalization left a call (its lane is no constant, and // lowering refuses it) reads its built-in as the parameter would. AirIntrinsic::GlobalBuiltin(g) => partition_builtin(g.var.builtin()), @@ -186,6 +215,7 @@ fn observes(callee: &Callee) -> bool { #[cfg(test)] mod tests { + use super::Partition; use crate::budget::{Budget, Meter}; use crate::device::DevicePolicy; use crate::library::FunctionConstantValues; @@ -308,19 +338,20 @@ entry: ); } - /// Whether kernel `k`'s specialized entry is partition-oblivious. - fn oblivious(name: &str, k: &Kernel<'_>) -> Option { + /// How kernel `k`'s specialized entry observes its partition. + fn partition(name: &str, k: &Kernel<'_>) -> Option { let bc = k.bitcode(name)?; let mut m = Meter::new(&Budget::default()); let none = FunctionConstantValues::defaults(); let e = specialized_entry(&bc, "k", &lavapipe(), &none, &[], &mut m) .unwrap_or_else(|e| panic!("{name}: {e}")); - Some(super::oblivious(&e)) + Some(super::partition(&e)) } /// A kernel of the grid's builtins, a device-scope fence and a device-scope atomic does not /// observe its partition, nor one that asks whether its thread is a helper, which no kernel - /// thread is. The atomic updates the word after the one the kernel stores to: on the stored + /// thread is, nor one that reduces a boolean vector of its own (`air.any`, `air.all`). The + /// atomic updates the word after the one the kernel stores to: on the stored /// word itself, lanes of one simdgroup race, and the lockstep barrier that orders them observes /// the partition (`a_device_race_lockstep_orders_observes_the_partition`). #[test] @@ -332,6 +363,10 @@ entry: let atomic = "%w = getelementptr i32, ptr addrspace(1) %out, i64 1\n %o = call i32 \ @air.atomic.global.add.u.i32(ptr addrspace(1) %w, i32 1, i32 0, i32 2, i1 \ true)\n %v = add i32 %b, %o"; + let reduce = "%odd = trunc i32 %b to i1\n %p = insertelement <2 x i1> , i1 %odd, i32 0\n %a = call i1 @air.all.v2i1(<2 x i1> %p)\n %n = \ + call i1 @air.any.v2i1(<2 x i1> %p)\n %e = and i1 %a, %n\n %z = zext i1 \ + %e to i32\n %v = add i32 %b, %z"; for (name, k) in [ ("position in grid", PLAIN), ( @@ -367,11 +402,20 @@ entry: ..PLAIN }, ), + ( + "boolean vector reductions", + Kernel { + body: reduce, + declarations: "declare i1 @air.all.v2i1(<2 x i1>)\n\ + declare i1 @air.any.v2i1(<2 x i1>)", + ..PLAIN + }, + ), ] { - let Some(oblivious) = oblivious(name, &k) else { + let Some(partition) = partition(name, &k) else { return; }; - assert!(oblivious, "{name}"); + assert_eq!(partition, Partition::Oblivious, "{name}"); } } @@ -388,43 +432,47 @@ entry: i32, i1)", ..PLAIN }; - let Some(oblivious) = oblivious("device race", &k) else { + let Some(partition) = partition("device race", &k) else { return; }; - assert!(!oblivious); + assert_ne!(partition, Partition::Oblivious); } - /// Each builtin of the partition, read, makes a kernel observe it. + /// Each builtin of the partition, read, makes a kernel observe it: a lane's index in its + /// simdgroup or quadgroup and the simdgroup's width through its simdgroups alone. #[test] fn each_builtin_of_the_partition_is_observed() { - for builtin in [ - "thread_position_in_threadgroup", - "threadgroup_position_in_grid", - "threads_per_threadgroup", - "threadgroups_per_grid", - "thread_index_in_threadgroup", - "thread_index_in_simdgroup", - "thread_index_in_quadgroup", - "simdgroup_index_in_threadgroup", - "quadgroup_index_in_threadgroup", - "threads_per_simdgroup", - "simdgroups_per_threadgroup", - "quadgroups_per_threadgroup", - "dispatch_threads_per_threadgroup", - "dispatch_simdgroups_per_threadgroup", + use Partition::{Observed, Simdgroups}; + for (builtin, want) in [ + ("thread_position_in_threadgroup", Observed), + ("threadgroup_position_in_grid", Observed), + ("threads_per_threadgroup", Observed), + ("threadgroups_per_grid", Observed), + ("thread_index_in_threadgroup", Observed), + ("thread_index_in_simdgroup", Simdgroups), + ("thread_index_in_quadgroup", Simdgroups), + ("simdgroup_index_in_threadgroup", Observed), + ("quadgroup_index_in_threadgroup", Observed), + ("threads_per_simdgroup", Simdgroups), + ("simdgroups_per_threadgroup", Observed), + ("quadgroups_per_threadgroup", Observed), + ("dispatch_threads_per_threadgroup", Observed), + ("dispatch_simdgroups_per_threadgroup", Observed), ] { - let Some(oblivious) = oblivious(builtin, &Kernel { builtin, ..PLAIN }) else { + let Some(partition) = partition(builtin, &Kernel { builtin, ..PLAIN }) else { return; }; - assert!(!oblivious, "{builtin}"); + assert_eq!(partition, want, "{builtin}"); } } /// Threadgroup memory (an argument or a global), each barrier, a fence or an atomic of /// threadgroup or simdgroup scope, and a simdgroup or quad function each make a kernel observe - /// its partition. + /// its partition: a simdgroup barrier, fence or function and a quad function through its + /// simdgroups alone, unless the kernel observes it otherwise too. #[test] fn each_partition_feature_is_observed() { + use Partition::{Observed, Simdgroups}; let tg_param = ( ", ptr addrspace(3) %tg", r#"!5 = !{i32 2, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 3, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"tg"}"#, @@ -443,6 +491,7 @@ entry: %v = load i32, ptr addrspace(3) %tg, align 4", ..PLAIN }, + Observed, ), ( "threadgroup global", @@ -452,6 +501,7 @@ entry: %v = load i32, ptr addrspace(3) @g, align 4", ..PLAIN }, + Observed, ), ( "threadgroup barrier", @@ -460,6 +510,7 @@ entry: declarations: barrier, ..PLAIN }, + Observed, ), ( "simdgroup barrier", @@ -468,6 +519,7 @@ entry: declarations: simd_barrier, ..PLAIN }, + Simdgroups, ), ( "threadgroup fence", @@ -476,6 +528,7 @@ entry: declarations: fence, ..PLAIN }, + Observed, ), ( "simdgroup fence", @@ -484,6 +537,7 @@ entry: declarations: fence, ..PLAIN }, + Simdgroups, ), ( "threadgroup atomic", @@ -493,6 +547,7 @@ entry: declarations: atomic, ..PLAIN }, + Observed, ), ( "simdgroup function", @@ -502,6 +557,7 @@ entry: declarations: "declare i32 @air.simd_shuffle.u.i32(i32, i16)", ..PLAIN }, + Simdgroups, ), ( "quad function", @@ -510,36 +566,69 @@ entry: declarations: "declare i32 @air.quad_max.s.i32(i32)", ..PLAIN }, + Simdgroups, + ), + ( + "simdgroup and threadgroup barriers", + Kernel { + body: "call void @air.simdgroup.barrier(i32 1, i32 4)\n call void \ + @air.wg.barrier(i32 1, i32 1)\n %v = add i32 %b, 1", + declarations: "declare void @air.simdgroup.barrier(i32, i32)\n\ + declare void @air.wg.barrier(i32, i32)", + ..PLAIN + }, + Observed, + ), + ( + "simdgroup function and threadgroup builtin", + Kernel { + builtin: "thread_index_in_threadgroup", + body: "%s = call i32 @air.simd_shuffle.u.i32(i32 %b, i16 0)\n \ + %v = add i32 %s, 1", + declarations: "declare i32 @air.simd_shuffle.u.i32(i32, i16)", + ..PLAIN + }, + Observed, ), ]; - for (name, k) in cases { - let Some(oblivious) = oblivious(name, &k) else { + for (name, k, want) in cases { + let Some(partition) = partition(name, &k) else { return; }; - assert!(!oblivious, "{name}"); + assert_eq!(partition, want, "{name}"); } } - /// The compiled artifact carries the fact (`KernelFacts::partition_oblivious`). + /// The compiled artifact carries the facts (`KernelFacts::partition_oblivious`, + /// `KernelFacts::partition_simdgroups`). #[test] fn the_artifact_states_whether_the_kernel_observes_its_partition() { let p = lavapipe(); for (name, k, want) in [ - ("grid", PLAIN, true), + ("grid", PLAIN, (true, false)), + ( + "simdgroup", + Kernel { + builtin: "thread_index_in_simdgroup", + ..PLAIN + }, + (false, true), + ), ( "threadgroup", Kernel { builtin: "thread_position_in_threadgroup", ..PLAIN }, - false, + (false, false), ), ] { let Some(bc) = k.bitcode(name) else { return; }; let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name}: {e}")); - assert_eq!(a.kernel.partition_oblivious, want, "{name}"); + let facts = (a.kernel.partition_oblivious, a.kernel.partition_simdgroups); + assert_eq!(facts, want, "{name}"); } } } diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index a04101377..19c7112da 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -563,6 +563,15 @@ fn function_keys_cover_their_inputs() { flat.replay_bindings = true; flat.flat_grid = true; assert_ne!(replay, a.function_compile_key(&fd, &flat)); + // So is a flat variant of the call's threadgroups. + let mut plain_flat = LoweringInputs::new(); + plain_flat.flat_grid = true; + let mut call_flat = plain_flat.clone(); + call_flat.call_threadgroups = true; + assert_ne!( + a.function_compile_key(&fd, &plain_flat), + a.function_compile_key(&fd, &call_flat) + ); // So is the raw render target slice index's varying. let mut layer = LoweringInputs::new(); layer.render_target_array_index_varying = true; @@ -688,6 +697,7 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() { .replace(", max_call_stack_depth: None", "") .replace(", open_cl_mode: false", "") .replace(", flat_grid: false", "") + .replace(", call_threadgroups: false", "") .replace(", render_target_array_index_varying: false", "") .replace(", primitive_id_varying: false", "") .replace(", primitive_id_indices: None", "") diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 70c81c3da..8d9d74fc3 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -354,6 +354,11 @@ pub enum RuntimeFact { /// record at its `PushField::ReplayRegionAddress`, which a preprocess writes beside the /// dispatch's group counts. Its plans state the variant. FlatGrid, + /// The kernel was compiled under `VariantKey::call_threadgroups` + /// (`LoweringInputs::call_threadgroups`), with `FlatGrid`: it runs a one-row grid in the + /// call's threadgroups of one row, its invocations counting their threads in its simdgroups' + /// lane order. Its plans state the variant. + CallThreadgroups, /// The function writes texture slot `slot` (a `write` or an imageblock slice's copy), or, /// with `atomic`, updates it by a texture atomic. Metal drops every write a function makes to /// a sparse texture, its mapped tiles' included: the texture keeps its contents for the diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index d6a4e70a8..7b7adb46c 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -235,7 +235,9 @@ pub struct LoweringInputs { /// its pipeline, which only a kernel that does not observe its threadgroup partition /// (`KernelFacts::partition_oblivious`) allows: it reads no dispatch builtin but /// `thread_position_in_grid` and `threads_per_grid`. Any other function is - /// `Unsupported{GpuEncodedIndirectCommands, NotRepresentable}` under it. Under + /// `Unsupported{GpuEncodedIndirectCommands, NotRepresentable}` under it, but a kernel that + /// observes its partition through its simdgroups alone under + /// [`call_threadgroups`](Self::call_threadgroups). Under /// `replay_bindings` the replay's preprocess writes the record per command /// (`ReplayVariant::flat`); otherwise the kernel binds as any other, and a preprocess writes /// the record beside its dispatch's group counts. It needs device addresses, and refuses a @@ -243,6 +245,23 @@ pub struct LoweringInputs { /// (`Unsupported{GpuEncodedIndirectCommands, NotImplemented}`). #[cfg_attr(feature = "serde", serde(default))] pub flat_grid: bool, + /// With [`flat_grid`](Self::flat_grid), the dispatch's threadgroups are the call's + /// (`VariantKey::call_threadgroups`): the grid is one row along `x`, in threadgroups of the + /// variant's local size, one row along `x` too, so workgroup `w`, counted `x` fastest, is + /// Metal's threadgroup `w`, and its invocations count its threads in the order of its + /// simdgroups' lanes (`lin`, the flattened tiers' subgroups). A kernel that observes its + /// partition through its simdgroups alone (`KernelFacts::partition_simdgroups`) then computes + /// what Metal's dispatch computes, and may read `thread_index_in_simdgroup`, + /// `thread_index_in_quadgroup` and `threads_per_simdgroup` besides the grid's builtins. The + /// invocations past the grid's last thread return before the body, so its simdgroup + /// operations and barriers run on the live lanes of the last simdgroup, Metal's partial one; + /// a module that would hold a workgroup barrier (a simdgroup barrier or fence emitted at + /// workgroup scope, in a tier whose subgroup is not the simdgroup) is + /// `Unsupported{GpuEncodedIndirectCommands, NotImplemented}`, and so is the input without + /// `flat_grid` or with `replay_bindings`. The caller states the dispatch's shape: nothing in + /// the module checks it. + #[cfg_attr(feature = "serde", serde(default))] + pub call_threadgroups: bool, /// The fragment function's render pipeline has a vertex function that writes /// `[[render_target_array_index]]`. That function stores `Layer` as 0 for an index at or past /// the render pass's `renderTargetArrayLength`, where Metal renders the pass's first layer, and diff --git a/crates/metal2vulkan/src/tests/engine_device_replay.rs b/crates/metal2vulkan/src/tests/engine_device_replay.rs index 92b7354f7..b7c68e899 100644 --- a/crates/metal2vulkan/src/tests/engine_device_replay.rs +++ b/crates/metal2vulkan/src/tests/engine_device_replay.rs @@ -2207,6 +2207,130 @@ fn a_flat_read_modify_write_of_its_grid_index_has_no_flat_variant() { assert!(ran > 0, "no profile with device addresses"); } +/// `lanes(b0, p, l)`: each thread stores its index in its simdgroup (`thread_index_in_simdgroup`) +/// at `b0[p]`, `p` its position in the grid: it observes its threadgroup partition through its +/// simdgroups alone, with no subgroup operation (its lanes are counted from its thread's index). +const LANES: &str = r#"define void @lanes(ptr addrspace(1) noundef "air-buffer-no-alias" %b0, i32 noundef %p, i32 noundef %l) { +entry: + %i = zext i32 %p to i64 + %o = getelementptr inbounds i32, ptr addrspace(1) %b0, i64 %i + store i32 %l, ptr addrspace(1) %o, align 4 + ret void +} + +!air.kernel = !{!0} +!air.version = !{!20} +!air.language_version = !{!21} +!0 = !{ptr @lanes, !1, !2} +!1 = !{} +!2 = !{!3, !4, !5} +!3 = !{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", !"b0"} +!4 = !{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"p"} +!5 = !{i32 2, !"air.thread_index_in_simdgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"l"} +!20 = !{i32 2, i32 8, i32 0} +!21 = !{!"Metal", i32 4, i32 0, i32 0} +"#; + +/// [`LANES`] with a threadgroup barrier before its store: it observes its partition otherwise. +fn lanes_barrier() -> String { + LANES + .replace( + " store i32 %l,", + " call void @air.wg.barrier(i32 1, i32 1)\n store i32 %l,", + ) + .replace( + "\n!air.kernel", + "\ndeclare void @air.wg.barrier(i32, i32)\n\n!air.kernel", + ) +} + +/// A kernel that observes its threadgroup partition through its simdgroups alone has no flat +/// variant of any threadgroups, and has one of the call's (`VariantKey::call_threadgroups`): a +/// lane's index in its simdgroup ([`LANES`]) on every profile with device addresses, and +/// [`flat_rmw`]'s lockstep simdgroup barrier at least where the kernel's simdgroups are its +/// subgroups (full subgroups: `Direct`, `Cluster32`); elsewhere that barrier would be a workgroup +/// barrier or an emulated simdgroup's, and the variant is refused. The variant states +/// `RuntimeFact::FlatGrid` and `RuntimeFact::CallThreadgroups`. A kernel with a threadgroup +/// barrier has neither variant, and the input is refused without the flat grid and with the +/// replay's bindings. +#[test] +fn a_flat_grid_of_the_call_s_threadgroups_admits_a_kernel_of_simdgroups() { + let (Some(lanes), Some(barrier), Some(rmw)) = ( + assemble("lanes", LANES), + assemble("lanes_barrier", &lanes_barrier()), + assemble("flat_rmw", &flat_rmw()), + ) else { + return; + }; + let mut key = VariantKey::new(); + key.flat_grid = true; + let any = key.lowering_inputs(Stage::Kernel); + key.call_threadgroups = true; + let call = key.lowering_inputs(Stage::Kernel); + let mut alone = LoweringInputs::new(); + alone.call_threadgroups = true; + let mut replayed = call.clone(); + replayed.replay_bindings = true; + let stated = |pipe: &ComputePipeline| { + [RuntimeFact::FlatGrid, RuntimeFact::CallThreadgroups] + .map(|fact| pipe.dependencies.iter().any(|d| d.fact == fact)) + }; + let (mut ran, mut barriers) = (0, 0); + for (stem, dev) in devices() { + if dev.profile().fields().buffer_access != BufferAccess::Addressed { + continue; + } + ran += 1; + let refused = |r: Result, needs: Needs, what: &str| match r { + Err(Error::Unsupported(u)) => { + assert_eq!( + u.feature, + Feature::GpuEncodedIndirectCommands, + "{stem} {what}" + ); + assert_eq!(u.needs, needs, "{stem} {what}"); + } + other => panic!("{stem} {what}: {:?}", other.map(|_| ())), + }; + for (bc, entry) in [(&lanes, "lanes"), (&rmw, "flat")] { + refused( + pipeline(&dev, bc, entry, &any), + Needs::NotRepresentable, + entry, + ); + refused( + pipeline(&dev, bc, entry, &alone), + Needs::NotImplemented, + entry, + ); + refused( + pipeline(&dev, bc, entry, &replayed), + Needs::NotImplemented, + entry, + ); + } + let observed = pipeline(&dev, &barrier, "lanes", &call); + refused(observed, Needs::NotRepresentable, "barrier"); + let pipe = pipeline(&dev, &lanes, "lanes", &call).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_eq!(stated(&pipe), [true, true], "{stem}"); + let lib = Library::from_air(&rmw).expect("library"); + let f = FunctionDescriptor::new(lib.function("flat").expect("function")); + let base = dev + .compile_function(&f, &LoweringInputs::new(), &Budget::standard()) + .unwrap_or_else(|e| panic!("{stem}: {e}")); + match pipeline(&dev, &rmw, "flat", &call) { + Ok(pipe) => { + assert_eq!(stated(&pipe), [true, true], "{stem}"); + barriers += 1; + } + Err(e) if base.requires_full_subgroups() => panic!("{stem}: {e}"), + refusal => refused(refusal, Needs::NotImplemented, "lockstep barrier"), + } + } + assert!(ran > 0, "no profile with device addresses"); + assert!(barriers > 0, "no profile ran the lockstep barrier flat"); +} + /// The folded group counts of a threadgroup `dispatch` on `dev`, and its region record: the product /// of its group counts spread over `x` up to its limit, then `y`, then `z`, and the record of its /// grid in threads with its threadgroup size packed, as the flat-dispatch module's folded form diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 9ad74ad16..ad8da1406 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -4178,6 +4178,7 @@ field metal2vulkan::cache::VariantKey.address_maps pub address_maps: BTreeMap field metal2vulkan::cache::VariantKey.anisotropic_samplers pub anisotropic_samplers: BTreeSet +field metal2vulkan::cache::VariantKey.call_threadgroups pub call_threadgroups: bool field metal2vulkan::cache::VariantKey.color_group pub color_group: u32 field metal2vulkan::cache::VariantKey.cross_class pub cross_class: BTreeMap field metal2vulkan::cache::VariantKey.cubic_samplers pub cubic_samplers: BTreeMap @@ -4770,6 +4771,7 @@ field metal2vulkan::pipeline::LoweringInputs.alpha_in_red_colors pub alpha_in_re field metal2vulkan::pipeline::LoweringInputs.alpha_test pub alpha_test: Option field metal2vulkan::pipeline::LoweringInputs.amplification_draws pub amplification_draws: Option field metal2vulkan::pipeline::LoweringInputs.anisotropic_samplers pub anisotropic_samplers: BTreeSet +field metal2vulkan::pipeline::LoweringInputs.call_threadgroups pub call_threadgroups: bool field metal2vulkan::pipeline::LoweringInputs.color_group pub color_group: Option field metal2vulkan::pipeline::LoweringInputs.color_writes pub color_writes: BTreeMap; 4]> field metal2vulkan::pipeline::LoweringInputs.cross_class pub cross_class: BTreeMap @@ -14698,6 +14700,7 @@ variant metal2vulkan::pipeline::RuntimeFact::BicubicTexels BicubicTexels { slot: variant metal2vulkan::pipeline::RuntimeFact::BorderTexels BorderTexels { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::BufferRangeLimit BufferRangeLimit { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::CallStackDepth CallStackDepth { depth: u32 } +variant metal2vulkan::pipeline::RuntimeFact::CallThreadgroups CallThreadgroups variant metal2vulkan::pipeline::RuntimeFact::ConstantLanes ConstantLanes { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::ConstexprSampled ConstexprSampled { slot: SlotRef, modes: [crate::metal::SamplerAddressMode; 3] } variant metal2vulkan::pipeline::RuntimeFact::CrossClassReads CrossClassReads { slot: SlotRef }