diff --git a/crates/metal2vulkan-air/src/canon/mod.rs b/crates/metal2vulkan-air/src/canon/mod.rs index 2154e0d54..bf62cc6b8 100644 --- a/crates/metal2vulkan-air/src/canon/mod.rs +++ b/crates/metal2vulkan-air/src/canon/mod.rs @@ -296,6 +296,13 @@ pub struct Lockstep { /// make exact, left out because the device's lockstep orders their pairs as Apple's does. The /// module then requires the property. 0 elsewhere. pub device: u32, + /// Every inserted barrier orders only pairs whose threads meet where two threads of one + /// simdgroup share their position's `x`, a simdgroup spanning two rows of its threadgroup: + /// in a threadgroup whose simdgroups each lie within one row (a single row, or rows of a + /// multiple of 32 threads) no pair conflicts. Decided where a subgroup barrier keeps a 32-lane + /// tier (maximal reconvergence on 32-lane subgroups, without the device's own lockstep); + /// `false` elsewhere and where no barrier is inserted. + pub rows: bool, } impl Lockstep { diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 12c6ced64..bad233f71 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -483,7 +483,9 @@ degradations! { "one Vulkan dispatch per region (the interior and each partial edge, per chunk of \ group counts), each on its own specialized pipeline, a barrier between each two"; /// A dispatch whose threadgroups are not whole subgroups of the kernel's pinned - /// subgroup size runs on the kernel's emulated-simdgroups variant. + /// subgroup size runs on the kernel's emulated-simdgroups variant. A threadgroup of one + /// row of a kernel whose only simdgroup semantics are lockstep barriers that order pairs + /// meeting across rows (`RuntimeFact::RowLockstep`) runs on the kernel's own pipeline. EmulatedSimdgroups = "emulated-simdgroups", Performance, "a second compile of the kernel whose simdgroup operations go through threadgroup \ memory between barriers"; diff --git a/crates/metal2vulkan/src/bind/dispatch.rs b/crates/metal2vulkan/src/bind/dispatch.rs index 06f37d979..16e6a8732 100644 --- a/crates/metal2vulkan/src/bind/dispatch.rs +++ b/crates/metal2vulkan/src/bind/dispatch.rs @@ -39,7 +39,10 @@ //! emulated simdgroups, and instantiating it on the plan of another variant is //! `BindError::NeedsVariant`, before anything is written. Only the variant's scratch is left to the //! variant's own plan, since only its compile knows it. A dispatch of whole subgroups keeps the -//! flattened pipeline. +//! flattened pipeline, and so does a region of one row of a kernel whose only simdgroup semantics +//! are lockstep barriers that order pairs meeting across rows (`RuntimeFact::RowLockstep`): its +//! simdgroups lie within the row, where no pair meets, so it runs whatever its width, without +//! `REQUIRE_FULL_SUBGROUPS`. //! //! **Push bytes.** Each region's push write covers the stage's whole push range, so every //! statically used push byte is written (VUID-vkCmdDispatch-maintenance4-08602): the @@ -237,7 +240,7 @@ pub(crate) enum Fit { /// A flattened tier's region of local size `r` that is not whole subgroups of its size: every /// multiple of a flattened plan is its tier's subgroup size, since the flattened tiers refuse /// derivatives (`ComputeDerivativesWithSimd`). -fn partial(rules: &LocalRules, r: [u32; 3]) -> bool { +fn unwhole(rules: &LocalRules, r: [u32; 3]) -> bool { let n: u64 = r.iter().map(|&x| u64::from(x)).product(); rules.flat && rules @@ -246,6 +249,23 @@ fn partial(rules: &LocalRules, r: [u32; 3]) -> bool { .any(|&m| m > 0 && !n.is_multiple_of(u64::from(m))) } +/// A region that is not whole subgroups ([`unwhole`]) and needs emulated simdgroups: any but a +/// region of one row of a kernel whose simdgroup semantics need no simdgroup spanning two rows +/// (`LocalRules::rows`), whose simdgroups then lie within its row, where no pair meets. +fn partial(rules: &LocalRules, r: [u32; 3]) -> bool { + unwhole(rules, r) && !(rules.rows && r[1] == 1 && r[2] == 1) +} + +/// The stage flags of a region of local size `r` on the planned pipeline: the pipeline's, but +/// `REQUIRE_FULL_SUBGROUPS` for a region that is not whole subgroups, a row [`partial`] admits. +fn region_flags(rules: &LocalRules, r: [u32; 3]) -> vk::PipelineShaderStageCreateFlags { + if unwhole(rules, r) { + rules.stage_flags & !vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS + } else { + rules.stage_flags + } +} + /// The local-size rules of the kernel's emulated-simdgroups variant as the plan of its flattened /// variant knows them: the same device limits, a local size that is not flattened, and no whole /// subgroups (the flattened plan's multiples are all its tier's, [`partial`]). The variant's @@ -257,6 +277,7 @@ fn emulated_rules(rules: &LocalRules) -> LocalRules { required_subgroup_size: None, stage_flags: vk::PipelineShaderStageCreateFlags::empty(), scratch: None, + rows: false, ..rules.clone() } } @@ -1079,7 +1100,7 @@ fn instantiate( }] }, indirect, - stage_flags: t.local.stage_flags, + stage_flags: region_flags(&t.local, r.local), required_subgroup_size: t.local.required_subgroup_size, }); } diff --git a/crates/metal2vulkan/src/bind/dispatch/tests.rs b/crates/metal2vulkan/src/bind/dispatch/tests.rs index c8e71e61e..0e0197742 100644 --- a/crates/metal2vulkan/src/bind/dispatch/tests.rs +++ b/crates/metal2vulkan/src/bind/dispatch/tests.rs @@ -37,6 +37,7 @@ fn rules() -> LocalRules { required_subgroup_size: None, stage_flags: vk::PipelineShaderStageCreateFlags::empty(), scratch: None, + rows: false, tile: false, tile_threadgroup: None, } @@ -544,6 +545,58 @@ fn a_partial_simdgroup_asks_for_the_emulated_simdgroups_variant() { ); } +/// A flattened kernel whose simdgroup semantics are only lockstep barriers that order pairs +/// meeting across rows (`LocalRules::rows`, `RuntimeFact::RowLockstep`) runs a threadgroup of one +/// row on its planned pipeline whatever its width, that region without `REQUIRE_FULL_SUBGROUPS` +/// where it is not whole subgroups: its simdgroups lie within the row. A partial threadgroup of two +/// rows, or a `dispatchThreads` grid with such an edge, still asks for the emulated-simdgroups +/// variant, and whole subgroups keep the flag. +#[test] +fn a_row_of_a_row_lockstep_kernel_runs_on_the_planned_pipeline() { + let mut t = flat_template(); + t.local.rows = true; + let plan = compute_plan(&t, VariantKey::new()); + let mut emulated = VariantKey::new(); + emulated.emulated_simdgroups = true; + let full = vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS; + for (n, flags) in [ + (1, vk::PipelineShaderStageCreateFlags::empty()), + (16, vk::PipelineShaderStageCreateFlags::empty()), + (48, vk::PipelineShaderStageCreateFlags::empty()), + (32, full), + (64, full), + ] { + let d = groups([n, 1, 1]); + assert_eq!(plan.dispatch_variant(&d), Ok(VariantKey::new()), "{n}"); + let c = plan.instantiate_dispatch(&state(0), &d).expect("runs"); + assert_eq!(c.regions.len(), 1); + assert_eq!(c.regions[0].stage_flags, flags, "{n}"); + assert_eq!(c.regions[0].required_subgroup_size, Some(32), "{n}"); + } + // A grid of rows whose edge is one partial row: the whole rows keep the flag. + let edge = Dispatch::Threads { + threads: [100, 1, 1], + threads_per_group: [32, 1, 1], + }; + assert_eq!(plan.dispatch_variant(&edge), Ok(VariantKey::new())); + let c = plan.instantiate_dispatch(&state(0), &edge).expect("runs"); + let flags: Vec<_> = c.regions.iter().map(|r| r.stage_flags).collect(); + assert_eq!(flags, [full, vk::PipelineShaderStageCreateFlags::empty()]); + for d in [ + groups([8, 2, 1]), + groups([5, 3, 1]), + Dispatch::Threads { + threads: [16, 4, 1], + threads_per_group: [16, 3, 1], + }, + ] { + assert_eq!(plan.dispatch_variant(&d), Ok(emulated.clone()), "{d:?}"); + } + // Without the fact every partial region asks for the variant. + let plain = compute_plan(&flat_template(), VariantKey::new()); + assert_eq!(plain.dispatch_variant(&groups([16, 1, 1])), Ok(emulated)); +} + /// The plan of the emulated-simdgroups variant (its local size not flattened, no multiple) states /// the key and runs every threadgroup size with the local size as Metal gave it. #[test] diff --git a/crates/metal2vulkan/src/bind/plan.rs b/crates/metal2vulkan/src/bind/plan.rs index ef1c5c7e0..a5bfdc969 100644 --- a/crates/metal2vulkan/src/bind/plan.rs +++ b/crates/metal2vulkan/src/bind/plan.rs @@ -574,6 +574,8 @@ pub(crate) struct LocalRules { pub stage_flags: vk::PipelineShaderStageCreateFlags, /// The emulated simdgroups' scratch (`RuntimeFact::SimdgroupEmulation`). pub scratch: Option, + /// A region of one row needs no whole subgroups (`RuntimeFact::RowLockstep`). + pub rows: bool, /// The pipeline is a tile function (`RuntimeFact::TileFunction`): its threads take Metal's /// tile-dispatch layout, built for the threadgroups `dispatch::tile_layout_measured` takes, /// dispatched by threadgroups. diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index 7208d0948..fde0860e9 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -788,6 +788,10 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result Mechanism { // The mode a kernel was compiled in: the compile layer checks it against the pipeline's; // nothing on the device reads it. RuntimeFact::OpenClMode => Mechanism::None, + // The binder's local-size rules read it: a one-row region of the planned pipeline. + RuntimeFact::RowLockstep => Mechanism::PlanTimeCheck, // A pipeline compiled under the flat-grid variant; its plans state it. RuntimeFact::FlatGrid => Mechanism::Variant, // A sparse texture's writes are dropped under the slot's `SparseTexture` specialization; diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 1a5e00896..e9dedb810 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -129,6 +129,7 @@ fn every_fact() -> Vec { RuntimeFact::AliasedImageblock { data_size: 24 }, RuntimeFact::CallStackDepth { depth: 8 }, RuntimeFact::OpenClMode, + RuntimeFact::RowLockstep, RuntimeFact::FlatGrid, RuntimeFact::SparseTextureWrites { slot, @@ -372,6 +373,7 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::PartialObjectThreadgroups => 89, RuntimeFact::RotatedInputBlend { .. } => 90, RuntimeFact::OpenClMode => 91, + RuntimeFact::RowLockstep => 92, } } @@ -379,7 +381,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..92).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..93).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -426,7 +428,8 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::StorageTextureWriteRounding { .. } | RuntimeFact::HeapWriteRounding { .. } | RuntimeFact::HeapCrossClassNeutral { .. } - | RuntimeFact::ObjectThreadgroupArena { .. } => Mechanism::PlanTimeCheck, + | RuntimeFact::ObjectThreadgroupArena { .. } + | RuntimeFact::RowLockstep => Mechanism::PlanTimeCheck, RuntimeFact::DispatchGrid | RuntimeFact::TileThreadgroup { .. } | RuntimeFact::PartialObjectThreadgroups => Mechanism::RegionSelected, diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs index db109b3da..ee0bcac74 100644 --- a/crates/metal2vulkan/src/lower/dispatch.rs +++ b/crates/metal2vulkan/src/lower/dispatch.rs @@ -573,6 +573,9 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result Result { let p = cx.profile; let stage = cx.stage; + // The class of the lockstep pass's simdgroup barriers, beside the program's own. + sync::barrier::lockstep_class(&mut cx); // Each family completes its own plan and contributes its descriptors, facts, simd class, // and tangled instructions before the combined checks below. stage_io::finish(&mut cx)?; diff --git a/crates/metal2vulkan/src/lower/simd/lockstep.rs b/crates/metal2vulkan/src/lower/simd/lockstep.rs index b3c5a4223..6837e38f8 100644 --- a/crates/metal2vulkan/src/lower/simd/lockstep.rs +++ b/crates/metal2vulkan/src/lower/simd/lockstep.rs @@ -692,7 +692,7 @@ pub fn order(mut e: Entry, p: &DeviceProfile, m: &mut Meter) -> Result Result Result, Error> { +) -> Result, Error> { let Some(body) = e.module.func(e.func).and_then(|f| f.body.as_ref()) else { return Ok(None); }; @@ -738,7 +740,7 @@ fn decide( let u = Uniformity::under_barriers(e, body, Among::Workgroup, &loops, m)?; let us = Uniformity::under_barriers(e, body, Among::Simdgroup, &loops, m)?; let pdom = PostDomTree::compute(&e.cfg, m)?; - let mut af = AddrFacts::new(e, body, &layouts, &us, m)?; + let mut af = AddrFacts::new(e, body, &layouts, &us, false, m)?; let mut wants: BTreeSet = BTreeSet::new(); let mut flags = MemFlags::default(); for (space, acc) in &spaces { @@ -758,10 +760,38 @@ fn decide( if wants.is_empty() { return Ok(None); } + // The same pairs where each simdgroup lies within one row of its threadgroup, so that two of + // its threads' positions differ in `x` (`AddrFacts::new`'s `rows`): where none conflicts, a + // dispatch of such threadgroups needs none of the barriers. Only a kernel whose subgroup + // barriers keep a 32-lane tier asks (`tangle`, without the device's own lockstep). + drop(af); + let mut rows = tangle && !device; + if rows { + let mut rows_af = AddrFacts::new(e, body, &layouts, &us, true, m)?; + for (_, acc) in &spaces { + let mut found = BTreeSet::new(); + pairs( + e, + acc, + (&u, &us), + (&pdom, &loops), + &mut rows_af, + &mut found, + m, + )?; + if !found.is_empty() { + rows = false; + break; + } + } + } let term = spaces .first() .map_or(&[][..], |(_, acc)| acc.term.as_slice()); - Ok(Some(stab(&wants, flags, (device, tangle), term, m)?)) + Ok(Some(( + stab(&wants, flags, (device, tangle), term, m)?, + rows, + ))) } /// Collect into `wants` where barriers must order the conflicting pairs of `acc`, the accesses of diff --git a/crates/metal2vulkan/src/lower/simd/lockstep/facts.rs b/crates/metal2vulkan/src/lower/simd/lockstep/facts.rs index 14bb31f7b..ca57804b4 100644 --- a/crates/metal2vulkan/src/lower/simd/lockstep/facts.rs +++ b/crates/metal2vulkan/src/lower/simd/lockstep/facts.rs @@ -686,14 +686,20 @@ pub(super) struct AddrFacts<'a> { guards: BTreeMap, /// By PHI or select: the objects it may point into ([`AddrFacts::roots`]), once walked. merges: BTreeMap>>, + /// Each simdgroup lies within one row of its threadgroup (a single row, or rows of a multiple + /// of 32 threads), so two of its threads' positions differ in `x` ([`AddrFacts::builtin_inj`]). + rows: bool, } impl<'a> AddrFacts<'a> { + /// The facts of kernel `e`'s body, under uniformity `u` among a simdgroup's threads; `rows`: + /// of a threadgroup whose simdgroups each lie within one row. pub fn new( e: &'a Entry, body: &'a Body, layouts: &'a TypeLayouts, u: &'a Uniformity, + rows: bool, m: &mut Meter, ) -> Result, Error> { let n = body.insts.len(); @@ -721,6 +727,7 @@ impl<'a> AddrFacts<'a> { anchors: BTreeMap::new(), guards: BTreeMap::new(), merges: BTreeMap::new(), + rows, }) } @@ -2147,16 +2154,16 @@ impl<'a> AddrFacts<'a> { return Ok(None); }; Ok(match v { - Value::Arg(a) => self.builtin_inj(a.raw()).and_then(|i| i.truncated(w)), + // A scalar position is its `x`. + Value::Arg(a) => self.builtin_inj(a.raw(), true).and_then(|i| i.truncated(w)), Value::Const(_) => None, Value::Inst(_) => match self.kind(v) { // A component of a position vector. Some(InstKind::ExtractElement { vec: Value::Arg(a), - idx: Value::Const(_), - }) => self - .builtin_inj(a.raw()) - .filter(|i| i.same) + idx: Value::Const(c), + }) if self.is_position(a.raw()) => self + .builtin_inj(a.raw(), const_int(self.e, *c) == Some(0)) .and_then(|i| i.truncated(w)), Some(InstKind::BinOp { op: op @ (BinOp::Add | BinOp::Sub | BinOp::Or), @@ -2269,17 +2276,23 @@ impl<'a> AddrFacts<'a> { /// position, in the grid or in the threadgroup, is the threadgroup's origin, one for the /// simdgroup, plus the thread's position in the threadgroup, below 1024: two threads' differ by /// at most 1023, and may be equal (in a threadgroup narrower than 32, threads of a simdgroup - /// share an `x`). - fn builtin_inj(&self, param: u32) -> Option { + /// share an `x`). Where each simdgroup lies within one row of its threadgroup (`rows`), the + /// `x` of a position (`x`: the value is it) is the row's first plus the thread's place in the + /// row, so it differs by 1 to 31 between two threads of a simdgroup, as an index does. + fn builtin_inj(&self, param: u32, x: bool) -> Option { let role = &self.e.ep.params.iter().find(|p| p.param == param)?.role; + let index = Inj { + step: 1, + spread: 31, + same: false, + }; match role { ParamRole::Builtin( Builtin::ThreadIndexInSimdgroup | Builtin::ThreadIndexInThreadgroup, - ) => Some(Inj { - step: 1, - spread: 31, - same: false, - }), + ) => Some(index), + ParamRole::Builtin( + Builtin::ThreadPositionInGrid | Builtin::ThreadPositionInThreadgroup, + ) if self.rows && x => Some(index), ParamRole::Builtin( Builtin::ThreadPositionInGrid | Builtin::ThreadPositionInThreadgroup, ) => Some(Inj { @@ -2291,6 +2304,19 @@ impl<'a> AddrFacts<'a> { } } + /// Whether parameter `param` is a position in the grid or in the threadgroup. + fn is_position(&self, param: u32) -> bool { + self.e.ep.params.iter().any(|p| { + p.param == param + && matches!( + p.role, + ParamRole::Builtin( + Builtin::ThreadPositionInGrid | Builtin::ThreadPositionInThreadgroup + ) + ) + }) + } + /// The pointer index width of address `v`'s space. fn index_bits(&self, v: Value) -> Option { match self diff --git a/crates/metal2vulkan/src/lower/sync/barrier.rs b/crates/metal2vulkan/src/lower/sync/barrier.rs index d75998966..f379ef605 100644 --- a/crates/metal2vulkan/src/lower/sync/barrier.rs +++ b/crates/metal2vulkan/src/lower/sync/barrier.rs @@ -216,6 +216,13 @@ pub struct BarrierPlan { /// control flow do not. A program's barrier is not among them: it keeps the profile's /// reconvergence. pub uniform_placed: std::collections::BTreeSet, + /// `lower::simd::lockstep` inserted a simdgroup barrier: the simd class takes it at + /// [`lockstep_class`], once the program's own operations have set theirs. + pub lockstep_simdgroup: bool, + /// The inserted simdgroup barriers are the kernel's only simdgroup semantics, and they order + /// only pairs that meet where a simdgroup spans two rows of its threadgroup + /// (`air::Lockstep::rows`): on a flattened tier the kernel records `RuntimeFact::RowLockstep`. + pub rows_only: bool, } /// Whether tangled instruction `v` depends on how subgroups reconverge: every one but a threadgroup @@ -225,6 +232,20 @@ pub fn reconverges(plan: &BarrierPlan, v: ValueId) -> bool { !plan.uniform_placed.contains(&v) } +/// Raise the simd class of a function the lockstep pass gave simdgroup barriers, once selection +/// has set the class of the program's own operations, and record whether those barriers are its +/// only simdgroup semantics and order only pairs that meet across rows +/// ([`BarrierPlan::rows_only`]): the program's class is then none and it has no simdgroup +/// operation, whose class its family raises later. +pub fn lockstep_class(cx: &mut SelectCx<'_>) { + if !cx.families.barrier.lockstep_simdgroup { + return; + } + cx.families.barrier.rows_only = + cx.simd == SimdClass::None && !cx.families.simd.groups && cx.entry.lockstep.rows; + cx.simd = with_simdgroup_barrier(cx.simd); +} + /// Complete the barrier family's plan: a kernel with derivatives depends on a local size that is /// a multiple of 4 (one derivative group of four linear invocations). pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { @@ -338,6 +359,11 @@ fn select_barrier( let scope = match scope { ThreadScope::Threadgroup if cx.stage.has_workgroup() => Scope::Workgroup, ThreadScope::Threadgroup => return Err(tile_shading()), + // An inserted barrier's class is taken after selection ([`lockstep_class`]). + ThreadScope::Simdgroup if origin != Origin::Program => { + cx.families.barrier.lockstep_simdgroup = true; + Scope::Subgroup + } ThreadScope::Simdgroup => { cx.simd = with_simdgroup_barrier(cx.simd); Scope::Subgroup diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 0814e32a3..ed0040fa2 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -336,6 +336,12 @@ pub enum RuntimeFact { /// otherwise); a `Function` kernel is compiled under its pipeline's. Nothing on the device /// reads it. OpenClMode, + /// The kernel's only simdgroup semantics are the barriers its lockstep order took + /// (`lower::simd::lockstep`), on a flattened tier, and they order only pairs whose threads meet + /// where a simdgroup spans two rows of its threadgroup (`Lockstep::rows`). A dispatch region + /// of one row runs on the planned pipeline whatever its width, without whole subgroups, where + /// no pair meets; any other region keeps the tier's whole subgroups or emulated simdgroups. + RowLockstep, /// The kernel was compiled under `VariantKey::flat_grid` (`LoweringInputs::flat_grid`): it /// runs any grid in threadgroups of its own size, reading the grid from the 32-byte region /// record at its `PushField::ReplayRegionAddress`, which a preprocess writes beside the diff --git a/crates/metal2vulkan/src/tests/engine_simd_emulated.rs b/crates/metal2vulkan/src/tests/engine_simd_emulated.rs index c9c458927..7b532ff7b 100644 --- a/crates/metal2vulkan/src/tests/engine_simd_emulated.rs +++ b/crates/metal2vulkan/src/tests/engine_simd_emulated.rs @@ -2087,3 +2087,154 @@ fn an_emulated_exchange_reaches_a_word_with_one_access_chain() { } } } + +/// `kernel void name(device uint *b [[buffer(0)]], constant uint &n [[buffer(1)]], uint gid +/// [[thread_position_in_grid]], uint lane [[thread_index_in_simdgroup]])`: `if (gid < n) +/// b[index] = b[index] * 3 + extra`, `index` and `extra` the instructions `index` and `extra` +/// compute (`%x`, an `i64`, and `%e`, an `i32`) from `%gid` and `%lane`. The read and the write +/// of one word stand where only some threads of a simdgroup run, so the lockstep pass orders +/// them with a simdgroup barrier, a tangle barrier on the RTX 5080's maximal reconvergence. +fn row_kernel(name: &str, index: &str, extra: &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 @{name}(ptr addrspace(1) %b, ptr addrspace(2) %np, i32 %gid, i32 %lane) #0 {{ +entry: + %n = load i32, ptr addrspace(2) %np, align 4 + %in = icmp ult i32 %gid, %n + br i1 %in, label %then, label %end +then: + {index} + {extra} + %p = getelementptr inbounds i32, ptr addrspace(1) %b, i64 %x + %v = load i32, ptr addrspace(1) %p, align 4 + %m = mul i32 %v, 3 + %w = add i32 %m, %e + store i32 %w, ptr addrspace(1) %p, align 4 + br label %end +end: + ret void +}} + +attributes #0 = {{ convergent mustprogress nounwind willreturn }} + +!air.kernel = !{{!0}} +!air.version = !{{!7}} +!air.language_version = !{{!8}} + +!0 = !{{ptr @{name}, !1, !2}} +!1 = !{{}} +!2 = !{{!3, !4, !5, !6}} +!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", !"b"}} +!4 = !{{i32 1, !"air.buffer", !"air.buffer_size", i32 4, !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"n"}} +!5 = !{{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"}} +!6 = !{{i32 3, !"air.thread_index_in_simdgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"lane"}} +!7 = !{{i32 2, i32 8, i32 0}} +!8 = !{{!"Metal", i32 4, i32 0, i32 0}} +"# + ) +} + +/// Buffers 0 and 1 bound. +fn two_buffers() -> BindState { + let mut state = bind_state(None); + if let Some(table) = state.stages.get_mut(&Stage::Kernel) { + table.buffers.insert( + 1, + BoundBuffer::Buffer { + length: 4, + offset: 0, + gpu_address: 0x2_0000, + device_address: None, + attribute_stride: None, + }, + ); + } + state +} + +/// A kernel whose only simdgroup semantics are the barrier its lockstep order took, between a +/// read and a write of `b[gid]` that two threads of one simdgroup meet at only where the +/// simdgroup spans two rows of its threadgroup (the shape of OpenCL C's `if (i < n) b[i] *= k`), +/// keeps the RTX 5080's `Direct` tier, records `RowLockstep`, and runs a threadgroup of one row +/// (1, 16 or 48 threads) on its one compiled pipeline, without whole subgroups: no +/// emulated-simdgroups variant is compiled, so none is announced. A threadgroup of two rows that +/// is not whole subgroups still asks for the variant. The same kernel at `b[gid >> 1]` (two +/// threads of a row meet) or reading its simdgroup lane keeps every partial threadgroup on the +/// variant. +#[test] +fn a_row_of_a_lockstep_only_kernel_takes_one_compile() { + let x = "%x = zext i32 %gid to i64"; + let none = "%e = add i32 0, 0"; + let kernels = [ + ("row_scale", x, none, true), + ( + "row_scale_pairs", + "%h = lshr i32 %gid, 1\n %x = zext i32 %h to i64", + none, + false, + ), + ("row_scale_lane", x, "%e = add i32 %lane, 0", false), + ]; + let dev = device("nvidia-rtx5080-laptop"); + let p = dev.profile(); + let state = two_buffers(); + let shape = state.shape(); + for (name, index, extra, rows) in kernels { + let Some(bc) = assemble_text(name, &row_kernel(name, index, extra)) else { + return; + }; + let (own, _) = typed_module(&bc, name, p).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!(own.simd.1, Tier::Direct, "{name}"); + assert!( + own.facts + .contains(&RuntimeFact::LocalSizeConstraint { multiple: 32 }), + "{name}" + ); + assert_eq!( + own.facts.contains(&RuntimeFact::RowLockstep), + rows, + "{name}" + ); + let base = pipeline(&dev, &bc, name); + let plan = base.plan(&dev, &shape).expect("plan"); + for n in [1, 16, 48] { + let want = if rows { + VariantKey::new() + } else { + emulated_key() + }; + assert_eq!( + plan.dispatch_variant(&threads(n)), + Ok(want), + "{name} at {n}" + ); + } + let two_rows = Dispatch::Threadgroups { + groups: [1, 1, 1], + threads_per_group: [8, 2, 1], + }; + assert_eq!( + plan.dispatch_variant(&two_rows), + Ok(emulated_key()), + "{name}" + ); + if rows { + let c = plan + .instantiate_dispatch(&state, &threads(16)) + .expect("one row on the planned pipeline"); + assert_eq!( + c.regions[0].stage_flags, + vk::PipelineShaderStageCreateFlags::empty() + ); + assert_eq!(c.regions[0].required_subgroup_size, Some(32)); + let c = plan + .instantiate_dispatch(&state, &threads(32)) + .expect("whole subgroups"); + assert!(c.regions[0] + .stage_flags + .contains(vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS)); + } + } +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 1d00be1d2..3e483ed6b 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1581,6 +1581,7 @@ field metal2vulkan-air::LinkedSamplerGroup.states pub states: Vec field metal2vulkan-air::Lockstep.barriers pub barriers: Vec field metal2vulkan-air::Lockstep.device pub device: u32 field metal2vulkan-air::Lockstep.emulated pub emulated: bool +field metal2vulkan-air::Lockstep.rows pub rows: bool field metal2vulkan-air::SpecRequest.call_stack_depth pub call_stack_depth: u32 field metal2vulkan-air::SpecRequest.constants pub constants: BTreeMap field metal2vulkan-air::SpecRequest.entry pub entry: String @@ -14087,6 +14088,7 @@ variant metal2vulkan::pipeline::RuntimeFact::ReplayBindings ReplayBindings variant metal2vulkan::pipeline::RuntimeFact::ResourcePresence ResourcePresence { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::RotatedInputBlend RotatedInputBlend { color: u32, blend: crate::pipeline::lower_inputs::BlendEquation, kept: crate::vk::ColorComponentFlags } variant metal2vulkan::pipeline::RuntimeFact::RotatedWeights RotatedWeights +variant metal2vulkan::pipeline::RuntimeFact::RowLockstep RowLockstep variant metal2vulkan::pipeline::RuntimeFact::SampleCount SampleCount variant metal2vulkan::pipeline::RuntimeFact::SamplerCoordinates SamplerCoordinates { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::SamplerReduction SamplerReduction { slot: SlotRef } diff --git a/docs/API.md b/docs/API.md index 555b4ec8d..b60f31065 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1733,7 +1733,9 @@ bound. two. - `metal2vulkan-degrade-emulated-simdgroups` (performance). `EmulatedSimdgroups`: A dispatch whose threadgroups are not whole subgroups of the kernel's pinned subgroup size runs on the kernel's - emulated-simdgroups variant. Cost: a second compile of the kernel whose simdgroup operations go + emulated-simdgroups variant. A threadgroup of one row of a kernel whose only simdgroup semantics + are the barriers its lockstep order took, ordering pairs that meet only where a simdgroup spans + two rows, runs on the kernel's own pipeline instead. Cost: a second compile of the kernel whose simdgroup operations go through threadgroup memory between barriers. - `metal2vulkan-degrade-separate-depth-stencil` (performance). `SeparateDepthStencil`: A pass of separate depth and stencil textures, or of a stencil-only texture alone at custom sample