From 03c587b9ee079124f2d0c01a1b3d0b174aa2a839 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 12 Nov 2026 23:52:39 -0800 Subject: [PATCH] A large kernel's whole grids run on its partial-threadgroups variant A kernel that observes its threadgroup partition runs its ragged dispatchThreads grids on its partial-threadgroups variant, one VkPipeline of the call's threadgroup size (MultiRegion 1), while its whole grids took the plain pipeline (MultiRegion 0): two driver compiles of the same module. On a guest's run on an RX 7900 XTX the plain one, for a kernel of 2,415,531 words, was 26.9 s of a 39.8 s warm pass. Now a kernel whose base module holds compile_memory::COUNTED_WORDS (65,536) SPIR-V words or more runs every direct dispatch of a threadgroup size on that variant, every thread live, where its ragged grids of the same form run there (it observes its partition, and for a one-row grid in one-row threadgroups otherwise than through its simdgroups alone, whose such grids run flat). Where the variant is refused it falls back to the plain pipeline as before. Smaller kernels keep the plain pipeline. Both forms give the same answers, so there is no switch and no FAST-PATHS row. - Binder: on a partial-threadgroups plan, a whole Threads grid takes the same L-sized regions per group-count chunk, unflagged (no NONUNIFORM), and a Threadgroups dispatch's regions have MultiRegion 1, so one specialization of a threadgroup size runs all of them. - Translator API: CompiledFunction::observes_threadgroup_partition and observes_partition_through_simdgroups_alone state the two partition facts the compile already decides, so the runtime can decide at creation which form a kernel's ragged grids take. - Runtime: compute::partial_direct takes whole grids and dispatchThreadgroups of such a kernel (ComputePipelineState::whole_on_partial). WorkCounts::whole_dispatches_on_partial_variants counts each such dispatch. A creation's predicted region is not made for such a kernel's predicted dispatch, which would run on the variant, not the base. - GPU cost, measured once on the XTX (RADV) with the probe on steelbrain/uniform-partial-probe: 1,048,576 threads in 64, partial/plain 0.997 to 1.020 over four straight-line kernels, words equal. Stated at partial_direct and in docs/API.md's dispatch-regions paragraph. Tests: engine_partial_threadgroups's whole_grids_run_on_the_partial_plan_with_every_thread_live (whole Threads and Threadgroups dispatches on the partial plan give the split's and Metal's words, and every grid of a threadgroup size takes one specialization, on the CPU interpreter); the runtime's a_large_kernel_s_whole_grids_run_on_its_partial_variant (a large kernel makes one VkPipeline over whole grids of both forms and a ragged one, counting 3 whole dispatches, with the plain pipeline's words; a small kernel makes the plain pipeline's and the variant's, counting 0). heap_trimmed makes its two large makings at two threadgroup sizes, since its whole and ragged grids now share one. --- crates/metal2vulkan-runtime/src/compute.rs | 70 ++++++-- .../src/pipeline/carry.rs | 2 +- .../src/pipeline/dispatch_making.rs | 25 ++- .../src/pipeline/dispatch_record.rs | 5 +- .../metal2vulkan-runtime/src/pipeline/mod.rs | 46 ++++- .../src/tests/heap_trimmed.rs | 20 ++- .../src/tests/partial_threadgroups.rs | 110 ++++++++++-- .../metal2vulkan-runtime/src/work_counts.rs | 18 ++ crates/metal2vulkan/src/bind/dispatch.rs | 31 +++- crates/metal2vulkan/src/library/compiled.rs | 25 +++ crates/metal2vulkan/src/lower/dispatch.rs | 4 +- .../src/tests/engine_partial_threadgroups.rs | 164 ++++++++++++++---- crates/metal2vulkan/tests/api_signatures.tsv | 3 + docs/API.md | 16 +- 14 files changed, 445 insertions(+), 94 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 34f3e16f4..0a69adcf1 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -1940,31 +1940,56 @@ fn flat_direct( /// one `VkPipeline` beside its state's, and with no `Degradation::SplitDispatch` where its group /// counts fit the device's. /// -/// `None`, so the dispatch keeps its exact split, where its grid is a whole number of -/// threadgroups or empty, in the large-buffer form, where the variant would emulate its -/// simdgroups (`ComputePipelineState::settle_partial`), or where the compile layer refuses the -/// kernel the variant, which the state remembers. +/// **A large kernel's whole grids.** A kernel whose base module holds `compile_memory`'s +/// `COUNTED_WORDS` (65,536) SPIR-V words or more runs its whole grids there too, every thread live +/// (`ComputePipelineState::whole_on_partial`): a `dispatchThreads:` of a whole number of +/// threadgroups and a `dispatchThreadgroups:`, where its ragged grids of the same form run on the +/// variant (no flat variant runs them, [`flat_direct`]). So one `VkPipeline` of a threadgroup size +/// runs all its direct dispatches, where the plain pipeline's for its whole grids would be a second +/// driver compile of the module: on a guest's run on an RX 7900 XTX, the plain pipeline's compile +/// of a kernel of 2,415,531 words was 26.9 s of a 39.8 s warm pass. Its cost on the GPU, measured +/// once on the same GPU (RADV) over 1,048,576 threads in threadgroups of 64, the fastest of three +/// command buffers of eight dispatches each: 0.997 to 1.020 times the plain pipeline's time over +/// four straight-line kernels, three of 40,000 fused multiply-adds (behind a threadgroup barrier +/// and a simdgroup sum, a threadgroup barrier alone, or neither) and a light one, their words the +/// plain pipeline's. A smaller kernel's whole grids keep the plain pipeline and its speed: its +/// compile is cheap. Both forms give the same answers, so no switch chooses between them. +/// +/// `None`, so the dispatch keeps its exact split or its plain pipeline, where its grid is empty or, +/// but for such a kernel, a whole number of threadgroups, in the large-buffer form, where the +/// variant would emulate its simdgroups (`ComputePipelineState::settle_partial`), where the +/// compile layer refuses the kernel the variant, which the state remembers, or where the device's +/// limits cannot hold its threadgroups. fn partial_direct( pipeline: &ComputePipelineState, shape: &BindShape, dispatch: &Dispatch, forms: BufferForms, ) -> Result, Arc)>, Error> { - let Dispatch::Threads { - threads, - threads_per_group, - } = *dispatch - else { - return Ok(None); - }; if forms != BufferForms::Bound { return Ok(None); } - let empty = (0..3).any(|i| threads[i] == 0 || threads_per_group[i] == 0); - if empty || (0..3).all(|i| threads[i].is_multiple_of(threads_per_group[i])) { + let (grid, local) = match *dispatch { + Dispatch::Threads { + threads, + threads_per_group, + } => (threads, threads_per_group), + Dispatch::Threadgroups { + groups, + threads_per_group, + } => (groups, threads_per_group), + _ => return Ok(None), + }; + if (0..3).any(|i| grid[i] == 0 || local[i] == 0) { return Ok(None); } - match pipeline.settle_partial(shape, threads_per_group, dispatch) { + // A grid of one row in threadgroups of one row, which the call's flat variant runs for a + // kernel that observes its partition through its simdgroups alone (`flat_direct`). + let one_row = grid[1..] == [1, 1] && local[1..] == [1, 1]; + if whole_grid(dispatch) && !pipeline.whole_on_partial(one_row) { + return Ok(None); + } + match pipeline.settle_partial(shape, local, dispatch) { Ok(settled) => Ok(settled), // Threadgroups the device's limits cannot hold: the split's own refusal answers. Err(Error::Bind(BindError::Unsupported(_))) => Ok(None), @@ -1972,6 +1997,19 @@ fn partial_direct( } } +/// Whether `dispatch` is a direct dispatch of whole threadgroups: a `dispatchThreadgroups:`, or a +/// `dispatchThreads:` whose grid is a whole number of threadgroups on every axis. +fn whole_grid(dispatch: &Dispatch) -> bool { + match *dispatch { + Dispatch::Threadgroups { .. } => true, + Dispatch::Threads { + threads, + threads_per_group, + } => (0..3).all(|i| threads[i].is_multiple_of(threads_per_group[i])), + _ => false, + } +} + /// The variant a direct dispatch of a bind state of `shape` in `forms` runs on, and its plan for /// `shape`: its flat variant where it takes one ([`flat_direct`]), else its partial-threadgroups /// variant where it takes one ([`partial_direct`]), else `ComputePipelineState::settle`'s. A program's dispatch plans so ([`plan_now`]), and so does a @@ -2859,6 +2897,10 @@ fn record( let emulated = variant.emulates_simdgroups(); let split = (regions.len(), variant.runs_partial_threadgroups()); degrade_dispatch(&device, kernel, &dispatch, split, emulated); + // A large kernel's whole grid on its partial-threadgroups variant ([`partial_direct`]). + if variant.runs_partial_threadgroups() && whole_grid(&dispatch) { + core.counts().whole_dispatch_on_partial_variant(); + } if let Some(unlisted) = unlisted { heap_sets::degrade_unlisted( &device, diff --git a/crates/metal2vulkan-runtime/src/pipeline/carry.rs b/crates/metal2vulkan-runtime/src/pipeline/carry.rs index 7d7f118af..3af6a87bd 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/carry.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/carry.rs @@ -271,7 +271,7 @@ impl Program { let base = Variant::of(to, self.base.key.clone(), found, &self.function)?; let pieces = piece_holds::PieceHolds::new(); if let (Kernel::Compute(descriptor), false) = (&self.descriptor, self.stand_in) { - base.make_predicted(to, descriptor, &pieces, false); + base.make_predicted(to, (descriptor, &self.compiled), &pieces, false); } let interface = &base.shared_pipeline().interface; let at_bind_views = AtBindViews::new(to, interface, ReadSlots::every()); diff --git a/crates/metal2vulkan-runtime/src/pipeline/dispatch_making.rs b/crates/metal2vulkan-runtime/src/pipeline/dispatch_making.rs index 1df1311d0..e05aef400 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/dispatch_making.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/dispatch_making.rs @@ -40,7 +40,10 @@ //! variant and the device past the program's last drop, which Metal's never does. Its //! specialized notices wait for the first dispatch that takes it, which announces them naming //! what it binds. A creation inside a host step, a tile function's state and a stand-in compile -//! make nothing here. +//! make nothing here, nor does the creation of a large kernel's state whose dispatches of whole +//! threadgroups run on its partial-threadgroups variant (`compute::partial_direct`), which the +//! creation does not compile: no dispatch would take the base's region, and its first dispatch +//! hands the variant's making to the pool. //! - **Where the request states no threadgroup, the creation predicts nothing**, because nothing //! in the request answers what the dispatch will ask for. The local size is the dispatch's own //! call, and a size guessed from the state instead -- Apple's guide to threadgroup sizes @@ -75,7 +78,7 @@ use super::objects::RawPipeline; use super::piece_holds::PieceHolds; use super::pool::Place; use super::region_ledger; -use super::{ComputePipelineState, RegionKey, Variant}; +use super::{ComputePipelineState, Kernel, RegionKey, Variant}; use crate::degradation::{BoundFormats, Occurrence}; use crate::error::Error; use crate::Device; @@ -239,19 +242,21 @@ impl Variant { /// most (a recovery's making again of the state waits for none, `pipeline/carry.rs`); under /// `Exact` made on this thread. A descriptor that requires no threadgroup size predicts no /// region at all, and a prediction the plan refuses or that runs on another variant makes - /// nothing; a failed making is not kept and refuses nothing, its dispatch meeting it as - /// before. + /// nothing, the partial-threadgroups variant of a large kernel among them (`compiled`, the + /// creation's compile of the descriptor's kernel, says whether its kernel is such: + /// `ComputePipelineState::whole_on_partial`); a failed making is not kept and refuses + /// nothing, its dispatch meeting it as before. pub(super) fn make_predicted( self: &Arc, device: &Device, - descriptor: &ComputePipelineDescriptor, + (descriptor, compiled): (&ComputePipelineDescriptor, &Kernel), holds: &Arc>, waited: bool, ) { if crate::exit_guard::in_host_step() { return; } - let Some(key) = self.predicted_region(device, descriptor) else { + let Some(key) = self.predicted_region(device, descriptor, compiled) else { return; }; let Begun::Yours(ticket) = self.pipelines.begin(&key) else { @@ -288,15 +293,21 @@ impl Variant { /// (the module docs): one `dispatchThreadgroups:` threadgroup of [`predicted_threads`], /// planned for [`predicted_bindings`]. `None` where `descriptor` requires no threadgroup /// size, so the request names none to predict; and where it plans or instantiates no region, - /// or runs on another variant (a threadgroup the kernel's simd tier cannot run whole). + /// or runs on another variant (a threadgroup the kernel's simd tier cannot run whole, or a + /// large kernel's dispatch of whole threadgroups, on its partial-threadgroups variant). fn predicted_region( &self, device: &Device, descriptor: &ComputePipelineDescriptor, + compiled: &Kernel, ) -> Option { // The threadgroup first, before anything is planned: where the request states none there // is no region to predict, and the plan below would be built for a key nobody makes. let threads_per_group = predicted_threads(descriptor.required_threads_per_threadgroup)?; + // One threadgroup, a grid of one row where it is one row. + if super::whole_on_partial(self, compiled, threads_per_group[1..] == [1, 1]) { + return None; + } let state = predicted_bindings(&self.pipeline); let plan = self.plan(device, &state.shape()).ok()?; let dispatch = Dispatch::Threadgroups { diff --git a/crates/metal2vulkan-runtime/src/pipeline/dispatch_record.rs b/crates/metal2vulkan-runtime/src/pipeline/dispatch_record.rs index f66d5038e..cd4f68e33 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/dispatch_record.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/dispatch_record.rs @@ -20,8 +20,9 @@ //! plans its first one (nothing bound but Metal's default sampler at each runtime sampler slot //! that does not compare), with the recorded threadgroup memory lengths, settles its variant as //! the program's direct dispatch does (`compute::settle_direct`: a ragged grid's flat variant -//! where it takes one, else its partial-threadgroups variant where it takes that, compiled -//! where it is not the base), and makes each region's `VkPipeline` +//! where it takes one, else its partial-threadgroups variant where it takes that, as a large +//! kernel's whole grid does too, compiled where it is not the base), and makes each region's +//! `VkPipeline` //! on the pass's thread, below every other making: its translation lands in the shader cache and //! its driver data in its record, under the names a later dispatch of the same shape asks for. A //! dispatch whose bindings specialize its regions otherwise (a bound texture's format the diff --git a/crates/metal2vulkan-runtime/src/pipeline/mod.rs b/crates/metal2vulkan-runtime/src/pipeline/mod.rs index 6e27eaf41..d7388f172 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/mod.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/mod.rs @@ -436,6 +436,20 @@ pub(super) struct Program { dispatch_records: OnceLock, } +/// [`ComputePipelineState::whole_on_partial`] of a state whose base variant is `base` and whose +/// creation compiled its kernel as `compiled`: what its creation's prediction asks too +/// (`dispatch_making.rs`). +fn whole_on_partial(base: &Variant, compiled: &Kernel, one_row: bool) -> bool { + if base.pipeline().stage.spirv.len() < compile_memory::COUNTED_WORDS { + return false; + } + let StageSource::Compiled(kernel) = compiled.stage() else { + return false; + }; + kernel.observes_threadgroup_partition() + && !(one_row && kernel.observes_partition_through_simdgroups_alone()) +} + /// What a direct dispatch of a compute state planned (`compute::settle_dispatch`): the variant /// `dispatch` of a bind state of `shape` runs on in `forms`, and its plan for `shape`, as /// [`ComputePipelineState::settle`] answers them, a function of those three alone; and the @@ -972,7 +986,7 @@ impl ComputePipelineState { // stand-in compile is never dispatched. let pieces = piece_holds::PieceHolds::new(); if let (Kernel::Compute(descriptor), false) = (&kernel, stand_in) { - base.make_predicted(device, descriptor, &pieces, true); + base.make_predicted(device, (descriptor, &compiled), &pieces, true); } device.degrade_absent_reads(&base.shared_pipeline().dependencies, |_| { function.function.info().name.to_string() @@ -1849,19 +1863,20 @@ impl ComputePipelineState { Ok(Some((variant, plan))) } - /// Run the state's direct dispatches of a ragged grid split, as where the compile layer - /// refused it the partial-threadgroups variant ([`Self::settle_partial`]): what - /// `tests::partial_threadgroups` compares the variant's answers with. + /// Run the state's direct dispatches without its partial-threadgroups variant, as where the + /// compile layer refused it ([`Self::settle_partial`]): a ragged grid split and a whole one on + /// the plain pipeline, what `tests::partial_threadgroups` compares the variant's answers with. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn split_ragged_grids(&self) { self.0.partial_refused.store(true, Ordering::Relaxed); } /// The partial-threadgroups variant (`VariantKey::partial_threadgroups`) `dispatch`, a direct - /// `dispatchThreads:` of a ragged grid in threadgroups of `local` threads of a bind state of - /// `shape`, runs on, with its plan for `shape`: the variant the first plan names for a - /// threadgroup dispatch of `local` threads, with the partial threadgroups, compiled when first - /// needed (`compute::partial_direct`); the variant's plan must run that very dispatch, which + /// dispatch in threadgroups of `local` threads of a bind state of `shape` (a `dispatchThreads:` + /// of a ragged grid, or a large kernel's whole grid, [`Self::whole_on_partial`]), runs on, with + /// its plan for `shape`: the variant the first plan names for a threadgroup dispatch of `local` + /// threads, with the partial threadgroups, compiled when first needed + /// (`compute::partial_direct`); the variant's plan must run that very dispatch, which /// the check against `key` states. `None` where that variant has emulated simdgroups, which no /// partial-threadgroups variant runs, unremembered (another threadgroup size may not); and /// where the compile layer refuses the kernel the variant (a tile function, a stage-input @@ -1905,6 +1920,21 @@ impl ComputePipelineState { Ok(Some((variant, plan))) } + /// Whether the state runs its whole grids, direct dispatches of whole threadgroups, on its + /// partial-threadgroups variant too, every thread live (`compute::partial_direct`): where its + /// base module holds `compile_memory::COUNTED_WORDS` SPIR-V words or more, whose plain pipeline + /// beside the variant's would be a second large compile, and where its ragged grids of the + /// dispatch's form run on the variant, as no flat variant runs them (`compute::flat_direct`): + /// the kernel observes its threadgroup partition, and, where `one_row` (a grid of one row in + /// threadgroups of one row), otherwise than through its simdgroups alone, as the call's flat + /// variant runs such a grid of such a kernel. Decided from the state's creation alone: where a + /// flat variant the kernel would take is refused (a device that reaches no memory by device + /// address, a module that would hold a workgroup barrier there), its ragged grids run on the + /// variant and its whole grids keep the plain pipeline. + pub(super) fn whole_on_partial(&self, one_row: bool) -> bool { + whole_on_partial(&self.0.base, &self.0.compiled, one_row) + } + /// The variant of `key`: the first one where it is that one's (and not a stand-in's), else /// compiled when first needed. fn keyed(&self, key: &VariantKey) -> Result, Error> { diff --git a/crates/metal2vulkan-runtime/src/tests/heap_trimmed.rs b/crates/metal2vulkan-runtime/src/tests/heap_trimmed.rs index ba76f52d6..32f782562 100644 --- a/crates/metal2vulkan-runtime/src/tests/heap_trimmed.rs +++ b/crates/metal2vulkan-runtime/src/tests/heap_trimmed.rs @@ -1,7 +1,8 @@ //! The free heap a large making's compile leaves is handed back (`pipeline/compile_memory.rs`): a //! kernel of [`STEPS`] fused multiply-adds with [`WINDOW`] values live at once, past the registers, -//! made as three `VkPipeline`s (its state's, for a grid of whole threadgroups, and a ragged grid's -//! interior and edge regions), each a large making. glibc keeps what the driver's compile frees in +//! made as two `VkPipeline`s of its partial-threadgroups variant, which runs a large kernel's whole +//! and ragged grids alike (`compute::partial_direct`), one per threadgroup size, each a large +//! making. glibc keeps what the driver's compile frees in //! the compiling thread's arena; handed back after each, the process's resident set stays within //! [`BOUND_MIB`] of what it was before the first, and the device counts the trims. //! @@ -81,8 +82,8 @@ fn state(device: &Device) -> ComputePipelineState { .unwrap() } -/// Dispatch `n` threads in threadgroups of 128 and wait. -fn dispatch(device: &Device, state: &ComputePipelineState, n: u32) { +/// Dispatch `n` threads in threadgroups of `group` and wait. +fn dispatch(device: &Device, state: &ComputePipelineState, n: u32, group: u32) { let out = words_buffer(device, &[0; 256]); let queue = device.new_command_queue().unwrap(); let command_buffer = queue.command_buffer().unwrap(); @@ -90,7 +91,10 @@ fn dispatch(device: &Device, state: &ComputePipelineState, n: u32) { encoder.set_compute_pipeline_state(state).unwrap(); encoder.set_buffer(Some(&out), 0, 0).unwrap(); encoder - .dispatch_threads(Size::new(u64::from(n), 1, 1), Size::new(128, 1, 1)) + .dispatch_threads( + Size::new(u64::from(n), 1, 1), + Size::new(u64::from(group), 1, 1), + ) .unwrap(); encoder.end_encoding().unwrap(); command_buffer.commit().unwrap(); @@ -110,10 +114,10 @@ fn a_large_makings_free_heap_is_handed_back() { let before = resident_mib(); let trims = || device.work_counts().heap_trims; let state = state(&device); - dispatch(&device, &state, 128); + dispatch(&device, &state, 128, 128); idle(&device); let first = resident_mib(); - dispatch(&device, &state, 129); + dispatch(&device, &state, 129, 64); idle(&device); let second = resident_mib(); println!( @@ -125,6 +129,6 @@ fn a_large_makings_free_heap_is_handed_back() { assert!(trims() > 0, "no large making handed its free heap back"); assert!( second <= before + BOUND_MIB, - "the resident set grew from {before} MiB to {second} over three makings" + "the resident set grew from {before} MiB to {second} over two makings" ); } diff --git a/crates/metal2vulkan-runtime/src/tests/partial_threadgroups.rs b/crates/metal2vulkan-runtime/src/tests/partial_threadgroups.rs index d4aecf57b..f7c5e70ee 100644 --- a/crates/metal2vulkan-runtime/src/tests/partial_threadgroups.rs +++ b/crates/metal2vulkan-runtime/src/tests/partial_threadgroups.rs @@ -9,6 +9,12 @@ //! live lanes alone. Where they are not (lavapipe's 8-lane subgroups, which emulate them), that //! kernel is refused the variant and splits. //! +//! A kernel whose module holds `compile_memory::COUNTED_WORDS` SPIR-V words or more runs its whole +//! grids on the variant too, every thread live (`ComputePipelineState::whole_on_partial`): one +//! `VkPipeline` of the call's threadgroup size runs its whole grids of either dispatch form and its +//! ragged grid, with the plain pipeline's words and Metal's. A smaller kernel's whole grids take the +//! plain pipeline. +//! //! Under `m2v_gpu`, a kernel heavy enough that its driver's compile is the cost: its ragged grids' //! creation time on the variant and split, one run each. //! @@ -156,6 +162,16 @@ fn full_subgroups(device: &Device, text: &str) -> bool { /// Dispatch `state` over `threads` threads in threadgroups of [`GROUP`] and wait: the /// `VkPipeline`s the dispatch made and the words it wrote. fn run(device: &Device, state: &ComputePipelineState, threads: u32) -> (u64, Vec) { + run_as(device, state, threads, false) +} + +/// [`run`], as a `dispatchThreadgroups:` of `threads / GROUP` threadgroups where `groups`. +fn run_as( + device: &Device, + state: &ComputePipelineState, + threads: u32, + groups: bool, +) -> (u64, Vec) { let out: Buffer = device .new_buffer_with_bytes(&[0xff; 4 * WORDS], ResourceOptions::shared()) .unwrap(); @@ -165,12 +181,12 @@ fn run(device: &Device, state: &ComputePipelineState, threads: u32) -> (u64, Vec 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(u64::from(threads), 1, 1), - Size::new(u64::from(GROUP), 1, 1), - ) - .unwrap(); + let group = Size::new(u64::from(GROUP), 1, 1); + let dispatched = match groups { + true => encoder.dispatch_threadgroups(Size::new(u64::from(threads / GROUP), 1, 1), group), + false => encoder.dispatch_threads(Size::new(u64::from(threads), 1, 1), group), + }; + dispatched.unwrap(); encoder.end_encoding().unwrap(); command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); @@ -244,30 +260,98 @@ const STEPS: usize = 40_000; #[cfg(m2v_gpu)] const WINDOW: usize = 400; -/// The heavy body: `%x` the sign bit of the chain's last value, which is positive (every step's -/// operands are), so the words stay Metal's while no compiler can drop the chain. +/// The fused multiply-adds of a large kernel's chain: enough that its module holds +/// `compile_memory::COUNTED_WORDS` SPIR-V words or more, which its test checks. +const LARGE_STEPS: usize = 8_000; + +/// The heavy body: [`chain`] of [`STEPS`] steps, [`WINDOW`] values live at once. #[cfg(m2v_gpu)] fn heavy() -> String { + chain(STEPS, WINDOW) +} + +/// A body of `steps` fused multiply-adds, each step's operand `window` steps behind it: `%x` the +/// sign bit of the chain's last value, which is positive (every step's operands are), so the +/// words stay Metal's while no compiler can drop the chain. +fn chain(steps: usize, window: usize) -> String { use std::fmt::Write; let hex = |v: f32| format!("0x{:016X}", f64::from(v).to_bits()); let mut body = String::from(" %f0 = uitofp i32 %t to float\n"); - for i in 0..STEPS { + for i in 0..steps { let c = hex(1.0f32 + (i as f32 + 1.0) * 2f32.powi(-22)); - let (x, y) = match i < WINDOW { + let (x, y) = match i < window { true => ("%f0".to_owned(), hex((i % 1024) as f32 * 0.25)), - false => (format!("%f{i}"), format!("%f{}", i + 1 - WINDOW)), + false => (format!("%f{i}"), format!("%f{}", i + 1 - window)), }; - let a = match i < WINDOW { + let a = match i < window { true => format!("{x}, float {c}, float {y}"), false => format!("{x}, float {y}, float {c}"), }; writeln!(body, " %f{} = call float @llvm.fma.f32(float {a})", i + 1).unwrap(); } - writeln!(body, " %xb = bitcast float %f{STEPS} to i32").unwrap(); + writeln!(body, " %xb = bitcast float %f{steps} to i32").unwrap(); body.push_str(" %x = lshr i32 %xb, 31\n"); body } +/// A large kernel's whole grids, `dispatchThreads:` of one and two threadgroups and a +/// `dispatchThreadgroups:` of two, run on its partial-threadgroups variant, every thread live, and +/// its ragged grid too: one `VkPipeline` of [`GROUP`], three whole dispatches on the variant +/// (`WorkCounts::whole_dispatches_on_partial_variants`), their words the plain pipeline's (the same +/// kernel's state made to split, `ComputePipelineState::split_ragged_grids`) and Metal's. The +/// smaller kernel's whole grids take the plain pipeline, a `VkPipeline` beside the variant's, which +/// its ragged grid takes. +#[test] +fn a_large_kernel_s_whole_grids_run_on_its_partial_variant() { + let scratch = Scratch::new("partial-threadgroups-whole"); + let device = device(&scratch.0); + // (threads, as a `dispatchThreadgroups:`). + let dispatches = [(64, false), (128, false), (128, true), (100, false)]; + for large in [true, false] { + let extra = match large { + true => chain(LARGE_STEPS, 8), + false => String::new(), + }; + let text = kernel(false, &extra); + let partial = state(&device, &text); + assert_eq!( + partial.whole_on_partial(false), + large, + "large {large}: the rule" + ); + let plain = state(&device, &text); + plain.split_ragged_grids(); + let counted = || device.work_counts().whole_dispatches_on_partial_variants; + let before = counted(); + let mut made = 0; + for (threads, groups) in dispatches { + let want = metal(threads, false); + let tag = format!("large {large}: {threads} threads, threadgroups {groups}"); + let (n, got) = run_as(&device, &partial, threads, groups); + made += n; + assert_eq!(&got[..want.len()], &want[..], "{tag}: the state"); + let (_, got) = run_as(&device, &plain, threads, groups); + assert_eq!(&got[..want.len()], &want[..], "{tag}: the plain pipeline"); + } + let whole = counted() - before; + println!( + "PARTIAL-THREADGROUPS-WHOLE {}: large {large}: VkPipelines made over {} dispatches: \ + {made}; whole dispatches on the variant: {whole}", + device.name(), + dispatches.len(), + ); + let want = match large { + true => (1, 3), + false => (2, 0), + }; + assert_eq!( + (made, whole), + want, + "large {large}: made, whole on the variant" + ); + } +} + #[test] #[cfg(m2v_gpu)] fn a_heavy_kernel_s_ragged_grids_pay_one_creation() { diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 560650513..c43053870 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -740,6 +740,7 @@ struct CommandCounters { dispatch_used_resources_listed: AtomicU64, dispatches_settled_as_before: AtomicU64, dispatches_planned_as_before: AtomicU64, + whole_dispatches_on_partial_variants: AtomicU64, dispatches_pushing_set_zero: AtomicU64, baked_sampler_dispatches_apart: AtomicU64, argument_tables_retained: AtomicU64, @@ -1622,6 +1623,13 @@ impl Counting<'_> { self.0.add(|counts| &counts.dispatches_planned_as_before, 1); } + /// A direct dispatch of whole threadgroups that ran on a large kernel's partial-threadgroups + /// variant, every thread live (`compute::partial_direct`). + pub(crate) fn whole_dispatch_on_partial_variant(&self) { + self.0 + .add(|counts| &counts.whole_dispatches_on_partial_variants, 1); + } + /// A dispatch of a variant that bakes samplers, its pipelines made, recorded in a /// `VkCommandBuffer` of its own (`RuntimeDriverDefect::ImmutableSamplersLostAfterCopies`). pub(crate) fn baked_sampler_dispatch_apart(&self) { @@ -7853,6 +7861,13 @@ pub struct WorkCounts { /// encoder's first dispatch of a state dispatched before, for two. Not counted in /// `dispatches_settled_as_before`. pub dispatches_planned_as_before: u64, + /// Direct dispatches of whole threadgroups, a `dispatchThreadgroups:` or a `dispatchThreads:` + /// of a whole number of threadgroups, that ran on their kernel's partial-threadgroups variant + /// with every thread live: a kernel whose module holds 65,536 SPIR-V words or more and whose + /// ragged grids run on that variant, so one `VkPipeline` of a threadgroup size runs its whole + /// and ragged grids (`compute::partial_direct`). Zero for smaller kernels, whose whole grids + /// take the plain pipeline. + pub whole_dispatches_on_partial_variants: u64, /// Dispatches of a kernel's variant whose layout bakes immutable samplers (constexpr /// samplers'), their pipelines made, recorded in a `VkCommandBuffer` of their own, as a /// dispatch whose pipeline is still being made is (`pending_dispatch.rs`): on a device whose @@ -10344,6 +10359,9 @@ 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_planned_as_before: commands(|counts| &counts.dispatches_planned_as_before), + whole_dispatches_on_partial_variants: commands(|counts| { + &counts.whole_dispatches_on_partial_variants + }), baked_sampler_dispatches_apart: commands(|counts| { &counts.baked_sampler_dispatches_apart }), diff --git a/crates/metal2vulkan/src/bind/dispatch.rs b/crates/metal2vulkan/src/bind/dispatch.rs index 82e24592f..6181c3d28 100644 --- a/crates/metal2vulkan/src/bind/dispatch.rs +++ b/crates/metal2vulkan/src/bind/dispatch.rs @@ -5,7 +5,9 @@ //! //! - `Threadgroups` within `maxComputeWorkGroupCount`, and every `ThreadgroupsIndirect`, is one //! region with `MultiRegion = 0`: the grid comes from `NumWorkgroups`, so GPU-written counts -//! need no CPU read (an indirect region's group counts are never an input of the plan). +//! need no CPU read (an indirect region's group counts are never an input of the plan). On the +//! plan of a partial-threadgroups variant a `Threadgroups` region has `MultiRegion = 1`, as that +//! plan's `Threads` regions do, so one `VkPipeline` of a threadgroup size runs both. //! - `Threads` with a grid that is not a multiple of the threadgroup size becomes up to eight //! regions per group-count chunk: the interior, and per axis an edge of one threadgroup of the //! remaining threads, all with `MultiRegion = 1`, so the grid and the region base come from the @@ -17,7 +19,8 @@ //! its threads fill, rounded up, at the dispatch's threadgroup size, per group-count chunk, all //! with `MultiRegion = 1` and their `DispatchRegion` flagged `lower::dispatch::NONUNIFORM`: the //! kernel's last threadgroup along an axis answers Metal's partial threadgroup, so no edge is -//! planned and one `VkPipeline` of the dispatch's size runs every such grid. +//! planned and one `VkPipeline` of the dispatch's size runs every such grid. A grid of whole +//! threadgroups takes the same regions there, unflagged: every thread is live. //! - A count above `maxComputeWorkGroupCount` on an axis is split into chunks, each a region //! with `MultiRegion = 1` and its base in the push field. At most [`MAX_REGIONS`] regions are //! planned; more is `Unsupported{GroupCount}`. @@ -485,7 +488,8 @@ pub(crate) enum Ragged { Flat, /// The threadgroups its threads fill at the dispatch's threadgroup size, per group-count /// chunk, flagged `lower::dispatch::NONUNIFORM`, on a partial-threadgroups variant - /// ([`VariantKey::partial_threadgroups`]). + /// ([`VariantKey::partial_threadgroups`]). A whole grid takes the same regions unflagged, and + /// a `Threadgroups` dispatch's regions read the region too (`MultiRegion` 1). Partial, } @@ -577,7 +581,9 @@ fn spread(need: u64, max_count: [u32; 3]) -> Result<[u32; 3], BindError> { /// threadgroups in the form `ragged` names: an interior and its edges, one region of the /// dispatch's own threadgroup size on a flat variant ([`VariantKey::flat_grid`]), or the /// threadgroups its threads fill on a partial-threadgroups variant -/// ([`VariantKey::partial_threadgroups`]). +/// ([`VariantKey::partial_threadgroups`]). On the last, a whole `Threads` grid and a +/// `Threadgroups` dispatch take regions that read the region too (`MultiRegion` 1), so the +/// variant's one `VkPipeline` of a threadgroup size runs them as well. pub(crate) fn regions( rules: &LocalRules, dispatch: &Dispatch, @@ -620,8 +626,11 @@ pub(crate) fn regions( chunks(&mut p, 0, groups[i], l[i], rules.max_count[i]); p }); + // A partial-threadgroups variant's regions read their region, as its `Threads` + // regions do, so both run on its one `VkPipeline` of the dispatch's size. + let multi = tile_sized || ragged == Ragged::Partial; Ok(planned( - product(pieces, tile_sized)?, + product(pieces, multi)?, grid, fit == Fit::EmulatedSimdgroups, )) @@ -696,9 +705,10 @@ pub(crate) fn regions( // A partial-threadgroups variant runs the threadgroups the grid's threads fill, rounded // up, at the dispatch's threadgroup size, per chunk of group counts, each region // reading its base and the grid: the last threadgroup along an axis answers the - // threads left where the region is flagged. + // threads left where the region is flagged. A whole grid's regions are unflagged, so + // every thread is live, on the same `VkPipeline` of the dispatch's size. let nonuniform = (0..3).any(|i| !threads[i].is_multiple_of(l[i])); - if ragged == Ragged::Partial && nonuniform { + if ragged == Ragged::Partial { let pieces: [Vec; 3] = std::array::from_fn(|i| { let mut p = Vec::new(); chunks( @@ -716,7 +726,7 @@ pub(crate) fn regions( threads, fit == Fit::EmulatedSimdgroups, ); - out.nonuniform = true; + out.nonuniform = nonuniform; return Ok(out); } let mut edges = false; @@ -795,7 +805,10 @@ impl BindingPlan { /// `Threads` dispatch whose grid is not a whole number of threadgroups as the threadgroups its /// threads fill, rounded up, at the dispatch's threadgroup size, one region per chunk of group /// counts, each `MultiRegion` 1 with its `DispatchRegion` flagged - /// `lower::dispatch::NONUNIFORM`; any other dispatch as the plan of the pipeline without it. + /// `lower::dispatch::NONUNIFORM`; a `Threads` dispatch of a whole number of threadgroups as the + /// same regions unflagged, every thread live, and a `Threadgroups` dispatch as its regions, + /// each `MultiRegion` 1, so one `VkPipeline` of a threadgroup size runs all three; any other + /// dispatch as the plan of the pipeline without it. pub fn instantiate_dispatch( &self, state: &BindState, diff --git a/crates/metal2vulkan/src/library/compiled.rs b/crates/metal2vulkan/src/library/compiled.rs index 40db36d13..30aea871a 100644 --- a/crates/metal2vulkan/src/library/compiled.rs +++ b/crates/metal2vulkan/src/library/compiled.rs @@ -295,6 +295,31 @@ impl CompiledFunction { self.0.subgroup.full_subgroups } + /// Whether the function, a kernel, observes its threadgroup partition: it may compute + /// otherwise in another partition of its grid into threadgroups, as it holds threadgroup + /// memory, a barrier, a fence or atomic of threadgroup or simdgroup scope, a simdgroup or quad + /// function, or reads a builtin of the partition. Decided from its AIR alone. A kernel that + /// does not runs any grid in threadgroups of a consumer's choosing (`LoweringInputs`'s + /// `flat_grid`); one that does runs a grid that is not a whole number of threadgroups on its + /// partial-threadgroups variant (`partial_threadgroups`) or split. `true` for a function that + /// is not a kernel. + pub fn observes_threadgroup_partition(&self) -> bool { + !self.0.kernel.partition_oblivious + } + + /// Whether the function, a 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-row grid in threadgroups of one row may run flat in the call's threadgroups + /// (`LoweringInputs`'s `call_threadgroups`). `false` for a kernel that does not observe its + /// partition ([`observes_threadgroup_partition`](Self::observes_threadgroup_partition)). + /// Decided as that one is. + pub fn observes_partition_through_simdgroups_alone(&self) -> bool { + self.0.kernel.partition_simdgroups + } + /// The function's own `[[max_total_threads_per_threadgroup(n)]]` (`air.max_work_group_size`), /// `None` without one: the most threads Metal compiles a threadgroup of the function for. pub fn max_total_threads_attribute(&self) -> Option { diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs index f489b7d59..916c53a68 100644 --- a/crates/metal2vulkan/src/lower/dispatch.rs +++ b/crates/metal2vulkan/src/lower/dispatch.rs @@ -94,7 +94,9 @@ //! last one of a partial threadgroup is Metal's partial simdgroup: its lanes past the threads are //! inactive, and every lane read ballots its live lanes (`simd::partly_live`). One variant of //! the call's threadgroup size runs every ragged grid, where the split runs an edge region of each -//! remainder, a `VkPipeline` of its own. +//! remainder, a `VkPipeline` of its own. A whole grid, and a threadgroup dispatch, run on the +//! variant's plan as the same regions unflagged: every invocation is live, and +//! `threads_per_threadgroup` is the call's. //! //! **Flat grids**. A flat variant (`LoweringInputs::flat_grid`, of a device replay or not) of a //! kernel that does not observe its threadgroup partition runs any grid in threadgroups of its own diff --git a/crates/metal2vulkan/src/tests/engine_partial_threadgroups.rs b/crates/metal2vulkan/src/tests/engine_partial_threadgroups.rs index b899bcdbd..8f58a8a4d 100644 --- a/crates/metal2vulkan/src/tests/engine_partial_threadgroups.rs +++ b/crates/metal2vulkan/src/tests/engine_partial_threadgroups.rs @@ -6,9 +6,12 @@ //! splits it into its interior and edge regions (on the emulated-simdgroups variant where an edge //! is not whole subgroups, as the runtime runs it), and on the partial-threadgroups variant's, //! which runs the threadgroups its threads fill at the call's size, per chunk of group counts, -//! flagged `lower::dispatch::NONUNIFORM`. Each region runs on the interpreter under Vulkan's -//! barrier rule (`BarrierRule::Vulkan`: an invocation that returned while others wait at a barrier -//! traps), in both scheduling orders, at the subgroup width the region pins. Both give Metal's +//! flagged `lower::dispatch::NONUNIFORM`. A grid of whole threadgroups, of either dispatch form, +//! runs on the variant's plan as the same regions unflagged, every thread live, on the one +//! specialization its threadgroup size's ragged grids take. Each region runs on the interpreter +//! under Vulkan's barrier rule (`BarrierRule::Vulkan`: an invocation that returned while others +//! wait at a barrier traps), in both scheduling orders, at the subgroup width the region pins. +//! Both give Metal's //! words: the partial threadgroup's `threads_per_threadgroup`, its threads' positions and indices //! over its own size, its simdgroups' indices, and, behind a threadgroup barrier, a neighbour's //! threadgroup word and its simdgroup's sum over the live lanes alone. The variant's module passes @@ -282,21 +285,59 @@ fn partial_inputs(dev: &Device, bc: &[u8], entry: &str, l: [u32; 3]) -> Option Dispatch { + Dispatch::Threads { + threads, + threads_per_group: l, + } +} + +/// A `dispatchThreadgroups` of `groups` threadgroups of `l`. +fn groups(groups: [u32; 3], l: [u32; 3]) -> Dispatch { + Dispatch::Threadgroups { + groups, + threads_per_group: l, + } +} + +/// The grid and the threadgroup of a direct dispatch. +fn grid_of(d: &Dispatch) -> ([u32; 3], [u32; 3]) { + match *d { + Dispatch::Threads { + threads, + threads_per_group, + } => (threads, threads_per_group), + Dispatch::Threadgroups { + groups, + threads_per_group, + } => ( + std::array::from_fn(|i| groups[i] * threads_per_group[i]), + threads_per_group, + ), + _ => panic!("not a direct dispatch"), + } +} + /// Check the partial-threadgroups variant of `entry` on `stem` against the split and `metal` for -/// every grid of `grids` (threads, threadgroup, the split's regions, the variant's): both give -/// Metal's words, on the region counts given. The variant's module is valid, walks no workgroup -/// barrier in non-uniform control flow, is within its estimate and states its fact. `false` -/// where the variant is refused or its key would emulate simdgroups (the split stays). +/// every dispatch of `grids` (the dispatch, the split's regions, the variant's): both give +/// Metal's words, on the region counts given, and every region of the variant's plan of a +/// threadgroup size takes one specialization, whatever its grid. The variant's module is valid, +/// walks no workgroup barrier in non-uniform control flow, is within its estimate and states its +/// fact. `false` where the variant is refused or its key would emulate simdgroups (the split +/// stays). fn check( stem: &str, (bc, entry): (&[u8], &str), - grids: &[([u32; 3], [u32; 3], usize, usize)], + grids: &[(Dispatch, usize, usize)], metal: impl Fn([u32; 3], [u32; 3]) -> Vec, words_out: impl Fn([u32; 3]) -> usize, ) -> bool { let dev = device(stem, |d| d.limits.max_compute_work_group_count = [4, 4, 4]); let mut ran = false; - for &(threads, l, split_regions, partial_regions) in grids { + let mut specializations = Vec::new(); + for (d, split_regions, partial_regions) in grids { + let (threads, l) = grid_of(d); let Some(key) = partial_inputs(&dev, bc, entry, l) else { continue; }; @@ -331,29 +372,35 @@ fn check( ); ran = true; } - let d = Dispatch::Threads { - threads, - threads_per_group: l, - }; let n = words_out(threads); let want = metal(threads, l); - let (sc, split_words) = split(&dev, bc, entry, n, &d); + let (sc, split_words) = split(&dev, bc, entry, n, d); let (pc, partial_words) = - run_on(&dev, (&pipe, &m), n, &d).unwrap_or_else(|e| panic!("{stem} {entry}: {e:?}")); - let tag = format!("{stem} {entry} {threads:?} in {l:?}"); + run_on(&dev, (&pipe, &m), n, d).unwrap_or_else(|e| panic!("{stem} {entry}: {e:?}")); + let form = match d { + Dispatch::Threadgroups { .. } => "threadgroups", + _ => "threads", + }; + let tag = format!("{stem} {entry} {threads:?} in {l:?} ({form})"); assert_eq!(&split_words[..want.len()], &want[..], "{tag}: the split"); assert_eq!(&partial_words[..want.len()], &want[..], "{tag}: partial"); assert_eq!( sc.regions.len(), - split_regions, + *split_regions, "{tag}: the split's regions" ); - assert_eq!(pc.regions.len(), partial_regions, "{tag}: partial regions"); - // Every partial region runs the call's threadgroup size: one specialization. + assert_eq!(pc.regions.len(), *partial_regions, "{tag}: partial regions"); + // Every partial region runs the call's threadgroup size: one specialization, a whole + // grid's the ragged ones'. + let first = &pc.regions[0].specialization; assert!( - (pc.regions.iter()).all(|r| r.specialization == pc.regions[0].specialization), + (pc.regions.iter()).all(|r| r.specialization == *first), "{tag}: one specialization" ); + match specializations.iter().find(|(size, _)| *size == l) { + Some((_, kept)) => assert!(kept == first, "{tag}: its threadgroup size's"), + None => specializations.push((l, first.clone())), + } } ran } @@ -368,17 +415,17 @@ fn a_ragged_grid_runs_partial_threadgroups_as_the_split_runs_its_edges() { let Some(bc) = assemble_text("shape", &shape()) else { return; }; - // (threads, threadgroup, the split's regions, the variant's). + // (dispatch, the split's regions, the variant's). let grids = [ // 3 by 2 threadgroups of 8x8, the last column 5 wide and the last row 5 high. - ([21, 13, 1], [8, 8, 1], 4, 1), + (threads([21, 13, 1], [8, 8, 1]), 4, 1), // A grid narrower and shorter than one threadgroup: the split's corner alone. - ([5, 3, 1], [8, 4, 1], 1, 1), + (threads([5, 3, 1], [8, 4, 1]), 1, 1), // 10 threadgroups of 32 in chunks of at most 4, the last of 2 threads: the split's 9 // whole ones in 3 chunks and its edge. - ([290, 1, 1], [32, 1, 1], 4, 3), + (threads([290, 1, 1], [32, 1, 1]), 4, 3), // One row of 100 in threadgroups of 64. - ([100, 1, 1], [64, 1, 1], 2, 1), + (threads([100, 1, 1], [64, 1, 1]), 2, 1), ]; let mut ran = Vec::new(); for stem in PROFILES { @@ -411,11 +458,11 @@ fn a_barrier_and_a_simdgroup_sum_run_partial_threadgroups_as_metal() { ) else { return; }; - // (threads, threadgroup, the split's regions, the variant's). + // (dispatch, the split's regions, the variant's). let grids = [ - ([100, 1, 1], [64, 1, 1], 2, 1), - ([45, 1, 1], [32, 1, 1], 2, 1), - ([16, 1, 1], [64, 1, 1], 1, 1), + (threads([100, 1, 1], [64, 1, 1]), 2, 1), + (threads([45, 1, 1], [32, 1, 1]), 2, 1), + (threads([16, 1, 1], [64, 1, 1]), 1, 1), ]; for (bc, simd) in [(&sum, true), (&plain, false)] { let metal = |t: [u32; 3], l: [u32; 3]| metal_neighbour(t[0], l[0], simd); @@ -435,6 +482,65 @@ fn a_barrier_and_a_simdgroup_sum_run_partial_threadgroups_as_metal() { } } +/// A grid of whole threadgroups, of a `dispatchThreads` or a `dispatchThreadgroups`, runs on the +/// partial-threadgroups variant's plan as its ragged grids do, every thread live: as the same +/// regions unflagged, on the one specialization a ragged grid of its threadgroup size takes, with +/// the plain pipeline's words and Metal's. `metal2vulkan-runtime` runs a large kernel's whole +/// grids so. +#[test] +fn whole_grids_run_on_the_partial_plan_with_every_thread_live() { + let (Some(shape_bc), Some(neighbour_bc)) = ( + assemble_text("shape_whole", &shape()), + assemble_text("neighbour_whole", &neighbour(true)), + ) else { + return; + }; + // (dispatch, the split's regions, the variant's): a ragged grid, then whole ones of its + // threadgroup size; 10 threadgroups of 32 in chunks of at most 4. + let shapes = [ + (threads([21, 13, 1], [8, 8, 1]), 4, 1), + (threads([24, 16, 1], [8, 8, 1]), 1, 1), + (groups([3, 2, 1], [8, 8, 1]), 1, 1), + (threads([290, 1, 1], [32, 1, 1]), 4, 3), + (threads([320, 1, 1], [32, 1, 1]), 3, 3), + (groups([10, 1, 1], [32, 1, 1]), 3, 3), + ]; + let neighbours = [ + (threads([100, 1, 1], [64, 1, 1]), 2, 1), + (threads([128, 1, 1], [64, 1, 1]), 1, 1), + (groups([2, 1, 1], [64, 1, 1]), 1, 1), + ]; + let metal = |t: [u32; 3], l: [u32; 3]| metal_neighbour(t[0], l[0], true); + let mut ran = Vec::new(); + for stem in PROFILES { + let words = |t: [u32; 3]| 2 * (t[0] * t[1]) as usize; + let shape = check(stem, (&shape_bc, "shape"), &shapes, metal_shape, words); + let runs = tier_of(stem, &shape_bc, "shape") != Tier::Emulated; + assert_eq!(shape, runs, "{stem}: shape runs partial threadgroups"); + let words = |t: [u32; 3]| t[0] as usize; + let neighbour = check( + stem, + (&neighbour_bc, "neighbour"), + &neighbours, + metal, + words, + ); + let runs = tier_of(stem, &neighbour_bc, "neighbour") != Tier::Emulated; + assert_eq!( + neighbour, runs, + "{stem}: neighbour runs partial threadgroups" + ); + if shape && neighbour { + ran.push(stem); + } + } + println!("PARTIAL-THREADGROUPS whole grids: the variant ran on {ran:?}"); + assert!( + ran.len() >= 4, + "the subgroup profiles run the variant: {ran:?}" + ); +} + /// The simd tier `stem` compiles `bc`'s `entry` in. fn tier_of(stem: &str, bc: &[u8], entry: &str) -> Tier { let dev = device(stem, |_| {}); diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index c41342fb6..01b9ce27a 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3524,6 +3524,7 @@ field metal2vulkan-runtime::WorkCounts.wakes_handler_threads pub wakes_handler_t field metal2vulkan-runtime::WorkCounts.wakes_spared pub wakes_spared: u64 field metal2vulkan-runtime::WorkCounts.watchdog_timeouts pub watchdog_timeouts: u64 field metal2vulkan-runtime::WorkCounts.wedges_declared pub wedges_declared: u64 +field metal2vulkan-runtime::WorkCounts.whole_dispatches_on_partial_variants pub whole_dispatches_on_partial_variants: u64 field metal2vulkan-runtime::WorkCounts.ycbcr_conversion_scratch_buffers pub ycbcr_conversion_scratch_buffers: u64 field metal2vulkan-runtime::WorkCounts.ycbcr_conversion_scratch_bytes pub ycbcr_conversion_scratch_bytes: u64 field metal2vulkan-runtime::WorkCounts.ycbcr_device_conversions pub ycbcr_device_conversions: u64 @@ -9661,6 +9662,8 @@ method metal2vulkan::library::CompiledFunction::key pub fn key(&self) -> &Functi method metal2vulkan::library::CompiledFunction::max_total_threads_attribute pub fn max_total_threads_attribute(&self) -> Option method metal2vulkan::library::CompiledFunction::module_stats pub fn module_stats(&self) -> ModuleStats method metal2vulkan::library::CompiledFunction::numbered_samplers pub fn numbered_samplers(&self) -> &[crate::pipeline::NumberedSampler] +method metal2vulkan::library::CompiledFunction::observes_partition_through_simdgroups_alone pub fn observes_partition_through_simdgroups_alone(&self) -> bool +method metal2vulkan::library::CompiledFunction::observes_threadgroup_partition pub fn observes_threadgroup_partition(&self) -> bool method metal2vulkan::library::CompiledFunction::precision_notes pub fn precision_notes(&self) -> &[PrecisionNote] method metal2vulkan::library::CompiledFunction::reads_resident_roots pub fn reads_resident_roots(&self) -> bool method metal2vulkan::library::CompiledFunction::reconvergence pub fn reconvergence(&self) -> Reconvergence diff --git a/docs/API.md b/docs/API.md index 14e45cdba..337be1006 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1492,8 +1492,20 @@ which `LoweringInputs::partial_threadgroups` compiles) runs such a grid as the t threads fill at the dispatch's threadgroup size instead, the last along an axis Metal's partial threadgroup, so every remainder takes the same `VkPipeline`; a kernel the variant cannot run exactly (a tile function, a stage-input region, compute derivatives, emulated simdgroups) is -refused it, `Unsupported{GpuEncodedIndirectCommands, NotImplemented}`, and keeps the edges. A kernel that steps a stage-in attribute by thread position, or reads -`[[grid_origin]]` or `[[grid_size]]`, needs the encoder's stage-in region: +refused it, `Unsupported{GpuEncodedIndirectCommands, NotImplemented}`, and keeps the edges. On +that plan a grid of whole threadgroups, of `Threads` or `Threadgroups`, takes the same regions +unflagged (each `MultiRegion` 1, every thread live), so one `VkPipeline` of a threadgroup size runs +all of a kernel's direct dispatches. `metal2vulkan-runtime` runs a kernel's whole grids there where +its module holds 65,536 SPIR-V words or more and its ragged grids run there too: it observes its +threadgroup partition (`CompiledFunction::observes_threadgroup_partition`), and for a one-row grid +in threadgroups of one row otherwise than through its simdgroups alone +(`observes_partition_through_simdgroups_alone`, whose such grids run flat). That is one driver +compile of the module instead of two: on a guest's run on an RX 7900 XTX, the plain pipeline's +compile of a kernel of 2,415,531 words was 26.9 s of a 39.8 s warm pass. Measured once on that GPU +(RADV) over four straight-line kernels, the variant ran their whole grids at 0.997 to 1.020 times +the plain pipeline's GPU time. Smaller kernels keep the plain pipeline for whole grids. A kernel +that steps a stage-in attribute by thread position, or reads `[[grid_origin]]` or `[[grid_size]]`, +needs the encoder's stage-in region: ```rust match plan.instantiate_dispatch(&state, &dispatch) {