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.
This commit is contained in:
Anees Iqbal committed 2026-11-12 16:29:19 -08:00
1 parent 19e8c1a09b
commit 979efab2f1
22 files changed
+673 -111

No files matched your search

+18 -3
View File
@@ -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.
@@ -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<Option<(Arc<Variant>, Arc<BindingPlan>)>, 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),
@@ -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::<u64>() 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<u32>) {
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]);
}
@@ -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;
+6 -1
View File
@@ -857,11 +857,16 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
// A pipeline compiled as its one-row variant states it; a dispatch asks for it where every
// region is one row of a kernel with `RowLockstep` (`dispatch_variant`).
variant.one_row = p.dependencies.iter().any(|d| d.fact == RuntimeFact::OneRow);
// A pipeline compiled for a flat grid states its variant.
// A pipeline compiled for a flat grid states its variant, and one of the call's threadgroups
// states that too.
variant.flat_grid = p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::FlatGrid);
variant.call_threadgroups = p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::CallThreadgroups);
// And one compiled to fold its group counts.
variant.folded_groups = p
.dependencies
+2 -1
View File
@@ -1249,6 +1249,7 @@ codec_enum! {
RowLockstep,
OneRow,
FlatGrid,
CallThreadgroups,
SparseTextureWrites { slot, atomic },
TileThreadgroupMemory { index },
TextureSwizzle { slot },
@@ -1331,7 +1332,7 @@ codec_struct! {
TextureReferenceType { data_type, texture_type, access, depth }
KernelFacts {
max_total_threads, work_group_size, flat_local_size, static_threadgroup_bytes,
partition_oblivious,
partition_oblivious, partition_simdgroups,
}
StrategyCensus { entries }
StrategyUse { uses, words }
+10
View File
@@ -249,6 +249,13 @@ pub struct VariantKey {
/// `PushField::ReplayRegionAddress`. The plan of a pipeline compiled under it states it.
#[cfg_attr(feature = "serde", serde(default))]
pub flat_grid: bool,
/// With [`flat_grid`](Self::flat_grid), its dispatch's threadgroups are the call's
/// (`LoweringInputs::call_threadgroups`): a one-row grid in threadgroups of one row, so a
/// kernel that observes its partition through its simdgroups alone
/// (`KernelFacts::partition_simdgroups`) runs flat too. The plan of a pipeline compiled under
/// it states it.
#[cfg_attr(feature = "serde", serde(default))]
pub call_threadgroups: bool,
/// The kernel, or the render pipeline's vertex and fragment functions, are a device-replay
/// variant (`LoweringInputs::replay_bindings`): every buffer they read is at its device
/// address in the slot table a replay's preprocess writes for its command, so
@@ -557,6 +564,7 @@ impl VariantKey {
&& self.ycbcr_planes_sampled.is_empty()
&& self.address_maps.is_empty()
&& !self.flat_grid
&& !self.call_threadgroups
&& !self.replay_bindings
&& !self.merged_draws
&& self.amplification_draws.is_none()
@@ -623,6 +631,8 @@ impl VariantKey {
self.emulated_simdgroups && stage == crate::pipeline::sym::Stage::Kernel;
out.one_row = self.one_row && stage == crate::pipeline::sym::Stage::Kernel;
out.flat_grid = self.flat_grid && stage == crate::pipeline::sym::Stage::Kernel;
out.call_threadgroups =
self.call_threadgroups && stage == crate::pipeline::sym::Stage::Kernel;
out.folded_groups = self.folded_groups && stage == crate::pipeline::sym::Stage::Kernel;
out.replay_bindings = self.replay_bindings
&& matches!(
@@ -160,6 +160,7 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> 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,
@@ -133,6 +133,7 @@ fn every_fact() -> Vec<RuntimeFact> {
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<usize> = 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 { .. }
@@ -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,
}
+45 -14
View File
@@ -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<DispatchPlan, Er
cx.facts.insert(RuntimeFact::TileThreadgroup { tile_sized });
}
let flat_grid = cx.inputs.flat_grid;
let call_threadgroups = flat_grid && cx.inputs.call_threadgroups;
let folded_groups = cx.inputs.folded_groups;
cx.facts.insert(RuntimeFact::ThreadsPerThreadgroup);
cx.facts.insert(RuntimeFact::LocalSizeLimits);
@@ -574,6 +585,9 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result<DispatchPlan, Er
if flat_grid {
cx.facts.insert(RuntimeFact::FlatGrid);
}
if call_threadgroups {
cx.facts.insert(RuntimeFact::CallThreadgroups);
}
if folded_groups {
cx.facts.insert(RuntimeFact::FoldedGroups);
}
@@ -588,6 +602,7 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result<DispatchPlan, Er
tile: crate::lower::access::tile::is_tile(cx),
tile_sized,
flat_grid,
call_threadgroups,
keys: SpecKey::dispatch_keys(cx.stage),
folded_groups,
draw_pieces: folded_groups && cx.stage == crate::pipeline::sym::Stage::Object,
@@ -714,13 +729,8 @@ fn param_value(
let (Some(p), Some(decl)) = (planned, decl) else {
return Err(cx.fail(format!("parameter {} has no dispatch value", b.param)));
};
// A flat grid derives the grid's builtins alone.
if decl.flat_grid
&& !matches!(
p.builtin,
KernelBuiltin::ThreadPositionInGrid | KernelBuiltin::ThreadsPerGrid
)
{
// A flat grid derives the grid's builtins alone, and of the call's threadgroups the lanes'.
if decl.flat_grid && !decl.flat_reads(p.builtin) {
return Err(cx.fail(format!("parameter {} is not a flat grid's", b.param)));
}
let raw = match (p.builtin, flat_position) {
@@ -801,6 +811,8 @@ pub struct KernelDecl {
tile_sized: bool,
/// The kernel runs its grid flat ([`KernelDecl::flat`]).
flat_grid: bool,
/// Of the call's threadgroups ([`DispatchPlan::call_threadgroups`]).
call_threadgroups: bool,
/// The kernel folds Metal's group counts into its dispatch ([`KernelDecl::folded`]).
folded_groups: bool,
/// A folded object function's `DrawIndex`, its draw's piece ([`DispatchPlan::draw_pieces`]).
@@ -1020,9 +1032,10 @@ impl KernelDecl {
let needs = Needs::of(dp);
let flat = dp.local_size == LocalSizeForm::Flat;
// A flat grid counts its threads by `LocalInvocationIndex` in either form: it reads no
// simdgroup.
let index = needs.lin && (!flat || dp.flat_grid);
let subgroups = needs.lin && flat && !dp.flat_grid;
// simdgroup. One of the call's threadgroups counts them by `lin`, its simdgroups' lanes.
let by_index = dp.flat_grid && !dp.call_threadgroups;
let index = needs.lin && (!flat || by_index);
let subgroups = needs.lin && flat && !by_index;
use crate::spv::BuiltIn as B;
// A wrapper that computes the threadgroup's position and grid stores them into private
// words, which the builtins read; it reads the dispatch's own.
@@ -1055,6 +1068,7 @@ impl KernelDecl {
tile: dp.tile,
tile_sized: dp.tile_sized,
flat_grid: dp.flat_grid,
call_threadgroups: dp.call_threadgroups,
folded_groups: dp.folded_groups,
draw_index: var(dp.draw_pieces, B::DrawIndex, u32_)?,
uvec3,
@@ -1386,6 +1400,20 @@ impl KernelDecl {
fb.binary(BinOp::IAdd, base, within)
}
/// Whether a flat grid derives builtin `b`: the grid's position and size, and, of the call's
/// threadgroups ([`DispatchPlan::call_threadgroups`]), a lane's index in its simdgroup or
/// quadgroup and the simdgroup's width, which its `lin` answers as Metal's threadgroup does.
fn flat_reads(&self, b: KernelBuiltin) -> 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<SValue> {
@@ -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)?;
@@ -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,
+11
View File
@@ -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();
@@ -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),
+16 -6
View File
@@ -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<Planned
let spec = grouped_entry(spec, r.inputs, p)?;
let inputs = lower_inputs(&spec, r.inputs, p, m)?;
// A flat variant runs its grid in threadgroups of its own: only a kernel that does not observe
// its partition computes the same there.
let partition_oblivious = partition::oblivious(&spec);
if inputs.flat_grid && !partition_oblivious {
// its partition computes the same there; one of the call's threadgroups, also a kernel that
// observes it through its simdgroups alone.
let observed = partition::partition(&spec);
let flat_runs = match inputs.call_threadgroups {
false => 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<LinkedKey<'_>> = r.linked.iter().map(|s| s.key).collect();
@@ -2728,7 +2737,8 @@ fn plan_one(r: &Request<'_>, p: &DeviceProfile, m: &mut Meter) -> Result<Planned
} else {
memory.tg_metal_static
},
partition_oblivious,
partition_oblivious: observed == Partition::Oblivious,
partition_simdgroups: observed == Partition::Simdgroups,
};
Ok(Planned {
key,
@@ -321,6 +321,10 @@ pub fn function_key(
h.bytes(b"flat-grid");
}
// Appended only when set.
if inputs.call_threadgroups {
h.bytes(b"call-threadgroups");
}
// Appended only when set.
if inputs.render_target_array_index_varying {
h.bytes(b"render-target-array-index-varying");
}
@@ -1,5 +1,5 @@
//! Whether a kernel observes its threadgroup partition, decided from the specialized entry's AIR
//! alone: `KernelFacts::partition_oblivious`.
//! How a kernel observes its threadgroup partition, decided from the specialized entry's AIR
//! alone: `KernelFacts::partition_oblivious` and `KernelFacts::partition_simdgroups`.
//!
//! A kernel that does not observe it computes the same in every partition of its grid into
//! threadgroups, so the runtime may run an indirect command's dispatch in threadgroups of its own
@@ -22,7 +22,16 @@
//!
//! Any other operation is a thread's own: arithmetic, device and constant memory, textures,
//! samplers, device-scope atomics and fences, indirect commands, function constants and tables,
//! and `quad_is_helper_thread` and `simd_is_helper_thread`, which no kernel thread is.
//! `air.all` and `air.any` of a boolean vector (a thread's own vector), and `quad_is_helper_thread`
//! and `simd_is_helper_thread`, which no kernel thread is.
//!
//! A kernel observes it **through its simdgroups alone** when every observation is a simdgroup's:
//! a barrier of simdgroup execution scope, a fence or an atomic of simdgroup scope, a simdgroup or
//! quad function (`simd_*`, `quad_*`), `is_uniform`, the simdgroup size, and the builtins
//! `thread_index_in_simdgroup`, `thread_index_in_quadgroup` and `threads_per_simdgroup`. Such a
//! kernel computes the same in any partition that keeps its threadgroups, and with them their
//! simdgroups and quadgroups (each of a threadgroup's consecutive 32 or 4 threads): a flat grid of
//! the call's own threadgroups (`LoweringInputs::call_threadgroups`).
use std::collections::BTreeSet;
@@ -31,14 +40,25 @@ use crate::air::abi::{Builtin, ParamRole, Stage as AbiStage};
use crate::air::intrinsics::{AirIntrinsic, Fragment, Sync, ThreadScope};
use crate::air::ir::{AddrSpace, Callee, InstKind, Type, Value};
/// Whether kernel `e` does not observe its threadgroup partition (see the module). Any other
/// stage, and an entry without a body, does.
pub(super) fn oblivious(e: &air::Entry) -> 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<bool> {
/// How kernel `k`'s specialized entry observes its partition.
fn partition(name: &str, k: &Kernel<'_>) -> Option<Partition> {
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 true, i1 \
true>, 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}");
}
}
}
@@ -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", "")
@@ -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
@@ -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
@@ -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<ComputePipeline, Error>, 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
@@ -4178,6 +4178,7 @@ field metal2vulkan::cache::VariantKey.address_maps pub address_maps: BTreeMap<Sl
field metal2vulkan::cache::VariantKey.addressed_function_tables pub addressed_function_tables: bool
field metal2vulkan::cache::VariantKey.amplification_draws pub amplification_draws: Option<crate::pipeline::AmplificationDraws>
field metal2vulkan::cache::VariantKey.anisotropic_samplers pub anisotropic_samplers: BTreeSet<SlotRef>
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<SlotRef, crate::pipeline::sym::SampledType>
field metal2vulkan::cache::VariantKey.cubic_samplers pub cubic_samplers: BTreeMap<SlotRef, u32>
@@ -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<crate::metal::CompareFunction>
field metal2vulkan::pipeline::LoweringInputs.amplification_draws pub amplification_draws: Option<AmplificationDraws>
field metal2vulkan::pipeline::LoweringInputs.anisotropic_samplers pub anisotropic_samplers: BTreeSet<SlotRef>
field metal2vulkan::pipeline::LoweringInputs.call_threadgroups pub call_threadgroups: bool
field metal2vulkan::pipeline::LoweringInputs.color_group pub color_group: Option<ColorGroup>
field metal2vulkan::pipeline::LoweringInputs.color_writes pub color_writes: BTreeMap<u32, [Option<ChannelWrite>; 4]>
field metal2vulkan::pipeline::LoweringInputs.cross_class pub cross_class: BTreeMap<SlotRef, SampledType>
@@ -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 }
Can't render this file because it is too large.