diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 031a19f69..a7cf20e73 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2884,7 +2884,12 @@ while the driver's exit handler waited on a lock, with every runtime thread alre lengths. - A kernel whose SIMD groups run one per subgroup of 32 (pinned where the device lists compute in `requiredSubgroupSizeStages` with 32 between its sizes, or the device's own 32), or one per - 32-lane cluster of a 64- or 128-lane subgroup, runs only workgroups of whole subgroups. + 32-lane cluster of a 64- or 128-lane subgroup, runs only workgroups of whole subgroups. So does + a kernel whose every cross-lane operation is a quad operation, on a device that lists compute in + `requiredSubgroupSizeStages` and whose narrowest subgroup is below 32 lanes and at least 4: it + pins no size, takes its quads from the subgroup at the size the device gives + (`ALLOW_VARYING_SUBGROUP_SIZE`), and runs only workgroups of whole subgroups of + `maxSubgroupSize`. - Such a kernel also has an emulated-SIMD-group variant, whose SIMD groups exchange through threadgroup memory between workgroup barriers. A threadgroup that is not whole subgroups (one of 80 or of 1 thread, or of 32 on a device of 64-lane subgroups) runs it at its own size, the last diff --git a/crates/metal2vulkan-runtime/src/tests/translate.rs b/crates/metal2vulkan-runtime/src/tests/translate.rs index 129c94f40..31800d8b5 100644 --- a/crates/metal2vulkan-runtime/src/tests/translate.rs +++ b/crates/metal2vulkan-runtime/src/tests/translate.rs @@ -1842,6 +1842,127 @@ mod on_device { }); } + /// `quad_shuffle_rotate` of `quad_shuffle`, a quad-only kernel: each thread reads the next + /// lane of its quad, `(t & !3) | ((t + 1) & 3)` of thread `t`, Metal's answer for every whole + /// quad, in threadgroups of 64, 32, 40, 12 and 4 threads. Where the device's narrowest compute + /// subgroup is below 32 lanes and at least 4, compute can take a size + /// (`requiredSubgroupSizeStages`) and runs full subgroups, the kernel takes its quads from the + /// subgroup at the size the device gives: no pinned size, `ALLOW_VARYING_SUBGROUP_SIZE`, and + /// whole groups of the largest size; elsewhere it keeps the tier its class takes. A + /// threadgroup that is not whole groups of the module's runs the emulated-SIMD-group module. + /// Prints the dispatches each module ran. + #[test] + fn every_device_runs_a_quad_only_kernel_at_the_size_it_gives() { + use ash::vk; + + let Some(descriptor) = descriptor_of("quad_shuffle", "quad_shuffle_rotate") else { + return; + }; + const GROUPS: u32 = 2; + each_device("compute_quads", |name, _, device| { + let raw = device.raw(); + let mut vulkan13 = vk::PhysicalDeviceVulkan13Properties::default(); + let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut vulkan13); + // SAFETY: the physical device is the instance's, a Vulkan 1.3 one. + unsafe { + raw.instance + .get_physical_device_properties2(raw.physical_device, &mut properties) + }; + let mut features13 = vk::PhysicalDeviceVulkan13Features::default(); + let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut features13); + // SAFETY: as above. + unsafe { + raw.instance + .get_physical_device_features2(raw.physical_device, &mut features) + }; + let (min, max) = (vulkan13.min_subgroup_size, vulkan13.max_subgroup_size); + let quad_free = vulkan13 + .required_subgroup_size_stages + .contains(vk::ShaderStageFlags::COMPUTE) + && features13.subgroup_size_control == vk::TRUE + && features13.compute_full_subgroups == vk::TRUE + && (4..32).contains(&min); + let state = device + .new_compute_pipeline_state(&descriptor, crate::tests::no_constexpr_samplers) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let interface = &state.inner.compiled.whole.interface; + let varying = interface + .stage_flags + .contains(vk::PipelineShaderStageCreateFlags::ALLOW_VARYING_SUBGROUP_SIZE); + assert_eq!(varying, quad_free, "{name}: subgroups {min}..{max}"); + if quad_free { + assert_eq!( + (interface.required_subgroup_size, &interface.multiples[..]), + (None, &[max][..]), + "{name}: the quads at the size the device gives" + ); + assert!( + interface + .stage_flags + .contains(vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS), + "{name}" + ); + } + let queue = device.new_command_queue(4).expect("a queue"); + let made = device.counters().metrics().translations; + let (mut whole, mut emulated) = (0, 0); + for size in [64, 32, 40, 12, 4] { + let threads = GROUPS * size; + let mut buffers = Buffers::new(&device, 1 << 16); + let out = buffers.buffer(u64::from(threads) * 4); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer + .compute_command_encoder(DispatchType::Serial) + .expect("an encoder"); + encoder.set_compute_pipeline_state(&state).expect("a state"); + encoder.set_buffer(Some(&out), 0, 0).expect("a buffer"); + let count = || device.counters().metrics().emulated_simdgroup_dispatches; + let before = count(); + encoder + .dispatch_threadgroups([GROUPS, 1, 1], [size, 1, 1]) + .unwrap_or_else(|error| panic!("{name}: threadgroups of {size}: {error}")); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + let partial = (interface.multiples.iter()).any(|&width| size % width.max(1) != 0); + assert_eq!( + count() - before, + u64::from(partial), + "{name}: threadgroups of {size}, whole groups of {:?}: emulated dispatches", + interface.multiples + ); + if partial { + emulated += 1; + } else { + whole += 1; + } + let want: Vec = (0..size).map(|t| (t & !3) | ((t + 1) & 3)).collect(); + assert_eq!( + words(&out, 0, want.len()), + want, + "{name}: the quads in threadgroups of {size}" + ); + } + assert_eq!( + device.counters().metrics().translations, + made, + "{name}: no translation at a dispatch" + ); + println!( + "{name}: quad-only kernel, subgroups {min}..{max}: {} ({:?} pinned, whole groups of \ + {:?}); dispatches on that module {whole}, on the emulated module {emulated}", + if varying { + "quads at the size the device gives" + } else { + "the tier its class takes" + }, + interface.required_subgroup_size, + interface.multiples, + ); + }); + } + /// `simd_shape` of `pad_simd_shape`: each thread's simdgroup index, lane, the threads of its /// simdgroup (a simdgroup sum of 1) and its index in the threadgroup, in threadgroups of 80, /// 1, 32, 64 and 40 threads. Metal's answer, measured on an M3 Max (macOS 27.0.1) at those diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index fab9a8ce3..703d6eb0c 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -911,7 +911,7 @@ codec_struct! { api_version, spirv_capabilities, spirv_extensions, features, extensions, properties, limits, formats, stage_flags, denorm_independence, rounding_independence, } - SubgroupRequirement { size, full_subgroups, local_size_multiple } + SubgroupRequirement { size, full_subgroups, local_size_multiple, varying } } codec_enum! { diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 23a64f54d..cbcc04979 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2296; +pub const SEMANTICS_VERSION: u32 = 2297; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 2296; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 594; +pub const ARTIFACT_FORMAT_VERSION: u32 = 595; /// The version of what this crate gives a runtime for the runs of a compiled pipeline, beside the /// compile: the device a run opens and what it enables, the Vulkan and Metal vocabularies a runtime diff --git a/crates/metal2vulkan/src/device/subgroup.rs b/crates/metal2vulkan/src/device/subgroup.rs index 863e950e9..d67952c00 100644 --- a/crates/metal2vulkan/src/device/subgroup.rs +++ b/crates/metal2vulkan/src/device/subgroup.rs @@ -152,6 +152,9 @@ pub struct SubgroupRequirement { pub full_subgroups: bool, /// Every dispatch region's local size must be a multiple of this (1: no constraint). pub local_size_multiple: u32, + /// The subgroup size may vary (`ALLOW_VARYING_SUBGROUP_SIZE`): no size is pinned, and the + /// device runs the size it picks, one size over a dispatch (Vulkan 9.5.2). + pub varying: bool, } impl SubgroupRequirement { @@ -160,6 +163,7 @@ impl SubgroupRequirement { size: None, full_subgroups: false, local_size_multiple: 1, + varying: false, }; /// Add to `r` what this requirement of a `stage` function needs of the device beyond its @@ -170,9 +174,11 @@ impl SubgroupRequirement { /// `subgroupSizeControl`, the stage in `requiredSubgroupSizeStages`, and the size inside /// `[minSubgroupSize, maxSubgroupSize]`; /// - full subgroups (`REQUIRE_FULL_SUBGROUPS`) need the stage flag, whose feature is - /// `computeFullSubgroups`. + /// `computeFullSubgroups`; + /// - a varying size (`ALLOW_VARYING_SUBGROUP_SIZE`) needs the stage flag, whose feature is + /// `subgroupSizeControl`. /// - /// A requirement that pins nothing and needs no full subgroups adds nothing. A limit `r` + /// A requirement that pins nothing and needs neither flag adds nothing. A limit `r` /// already names keeps the stricter value. pub fn add_device_facts(&self, stage: Stage, r: &mut Requirements) { if let Some(size) = self.size { @@ -189,6 +195,10 @@ impl SubgroupRequirement { if self.full_subgroups { r.stage_flags.insert(StageCreateFlag::RequireFullSubgroups); } + if self.varying { + r.stage_flags + .insert(StageCreateFlag::AllowVaryingSubgroupSize); + } } } @@ -440,6 +450,51 @@ pub fn requirement(t: Tier, stage: Stage, model: &SubgroupModel) -> SubgroupRequ size: st.pinnable.then_some(size), full_subgroups: compute, local_size_multiple: if compute { size } else { 1 }, + varying: false, + } +} + +/// Whether a kernel of class `class` whose every cross-lane operation stays inside its quad +/// (`lower::simd::quad_only`) takes its quads from the subgroup at the size the device gives +/// (`Tier::Direct` under [`quad_requirement`]): the 32 lanes are needed only by operations that +/// read outside a quad, so the pin to 32 stays only where 32 is the stage's narrowest size. The +/// stage runs the class's operations with full subgroups, its narrowest size is below 32, and +/// every size it runs is a multiple of 4, so a quad is four aligned lanes of one subgroup (Vulkan +/// 9.27.9). Read from the size range and the operation classes alone. +pub fn quad_free(class: &SimdClass, stage: Stage, model: &SubgroupModel) -> bool { + if stage != Stage::Kernel { + return false; + } + let class = match class { + SimdClass::Quad => SimdClass::CrossLane(OpBits::QUAD), + SimdClass::CrossLane(ops) => SimdClass::CrossLane(*ops), + _ => return false, + }; + let st = model.stage(stage); + let (ops, _) = needed_ops(&class); + st.supported + && st.ops.contains(ops) + && st.full_subgroups + && st.sizes.min >= 4 + && st.sizes.min < 32 +} + +/// The subgroup requirement of a [`quad_free`] kernel: full subgroups, no pinned size, the size +/// varying where the stage can pin one (`subgroupSizeControl`), and a local size that is a +/// multiple of the largest size the stage may run, the only one that guarantees full subgroups of +/// a size the device picks (`VUID-VkPipelineShaderStageCreateInfo-flags-02758`); without +/// `subgroupSizeControl` the size is the API's, and the local size a multiple of it. +pub fn quad_requirement(stage: Stage, model: &SubgroupModel) -> SubgroupRequirement { + let st = model.stage(stage); + SubgroupRequirement { + size: None, + full_subgroups: true, + local_size_multiple: if st.pinnable { + st.sizes.max + } else { + st.api_size + }, + varying: st.pinnable, } } diff --git a/crates/metal2vulkan/src/device/tests/subgroup.rs b/crates/metal2vulkan/src/device/tests/subgroup.rs index d27082b60..d512d38ce 100644 --- a/crates/metal2vulkan/src/device/tests/subgroup.rs +++ b/crates/metal2vulkan/src/device/tests/subgroup.rs @@ -4,8 +4,8 @@ use super::profile::device; use super::*; use crate::device::requirements::VkProperty; use crate::device::subgroup::{ - requirement, tier, OpBits, SimdClass, StageSubgroup, SubgroupModel, SubgroupRequirement, - SubgroupSizes, Tier, + quad_free, quad_requirement, requirement, tier, OpBits, SimdClass, StageSubgroup, + SubgroupModel, SubgroupRequirement, SubgroupSizes, Tier, }; use crate::error::{Capability, Feature}; use crate::metal::{ArgumentBuffersTier, ReadWriteTextureTier}; @@ -189,6 +189,7 @@ fn fixed_wave64_is_cluster32_without_a_pin() { size: None, full_subgroups: true, local_size_multiple: 64, + varying: false, } ); assert_eq!(tier(&shuffle, Stage::Fragment, &m), Ok(Tier::Cluster32)); @@ -214,6 +215,7 @@ fn pinnable_ranges_prefer_32() { size: Some(32), full_subgroups: true, local_size_multiple: 32, + varying: false, } ); assert_eq!( @@ -222,6 +224,7 @@ fn pinnable_ranges_prefer_32() { size: Some(32), full_subgroups: false, local_size_multiple: 1, + varying: false, } ); // A range above 32 pins the smallest cluster size. @@ -250,6 +253,7 @@ fn a_subgroup_requirement_states_its_device_facts() { size: Some(32), full_subgroups: true, local_size_multiple: 32, + varying: false, }; let r = facts(pinned, Stage::Kernel); assert_eq!(r.features, [VkFeature::SubgroupSizeControl].into()); @@ -351,6 +355,122 @@ fn narrow_subgroups_partial_in_graphics_emulated_in_compute() { ); } +/// A quad-only kernel takes its quads from the subgroup at the size the device gives where the +/// kernel stage runs full subgroups of the class's operations and its narrowest size is below 32, +/// read from the size range alone: 8 to 32 takes it; 32 to 32 and 32 to 64 keep today's pin to 32; +/// a narrowest size below 4 is excluded by the guard, since a quad is four lanes of one subgroup. +/// No other stage takes it. A stage that pins no size runs the API's alone, with no varying flag. +#[test] +fn a_quad_only_kernel_reads_the_size_range_alone() { + let quad = SimdClass::CrossLane(OpBits::QUAD); + let range = |min, max| { + let mut st = fixed(32); + st.pinnable = true; + st.sizes = SubgroupSizes { min, max }; + model(st) + }; + let m = range(8, 32); + assert!(quad_free(&quad, Stage::Kernel, &m)); + assert!(quad_free(&SimdClass::Quad, Stage::Kernel, &m)); + assert_eq!( + quad_requirement(Stage::Kernel, &m), + SubgroupRequirement { + size: None, + full_subgroups: true, + local_size_multiple: 32, + varying: true, + } + ); + for stage in [Stage::Vertex, Stage::Fragment] { + assert!(!quad_free(&quad, stage, &m), "{stage:?}"); + } + for (min, max) in [(4, 4), (8, 8), (16, 64)] { + assert!( + quad_free(&quad, Stage::Kernel, &range(min, max)), + "{min}..{max}" + ); + } + // 32 is the narrowest size: the pin to 32 stays. + for (min, max) in [(32, 32), (32, 64), (64, 128)] { + assert!( + !quad_free(&quad, Stage::Kernel, &range(min, max)), + "{min}..{max}" + ); + } + // The guard: a subgroup narrower than 4 lanes cannot hold a whole quad. + for (min, max) in [(1, 32), (2, 32), (1, 1), (2, 2)] { + assert!( + !quad_free(&quad, Stage::Kernel, &range(min, max)), + "{min}..{max}" + ); + } + // Without full subgroups, or without the class's operations. + let mut m = range(8, 32); + m.kernel.full_subgroups = false; + assert!(!quad_free(&quad, Stage::Kernel, &m)); + let mut m = range(8, 32); + m.kernel.ops = OpBits(0xff & !OpBits::QUAD.0); + assert!(!quad_free(&quad, Stage::Kernel, &m)); + assert!(quad_free( + &SimdClass::CrossLane(OpBits::BALLOT.union(OpBits::SHUFFLE)), + Stage::Kernel, + &m + )); + // A stage that pins no size runs the API's. + let m = model(fixed(16)); + assert!(quad_free(&quad, Stage::Kernel, &m)); + assert_eq!( + quad_requirement(Stage::Kernel, &m), + SubgroupRequirement { + size: None, + full_subgroups: true, + local_size_multiple: 16, + varying: false, + } + ); + assert!(!quad_free(&quad, Stage::Kernel, &model(fixed(32)))); +} + +/// The committed profiles a quad-only kernel takes its quads from the subgroup at the device's +/// size on, with their kernel size ranges: none whose narrowest kernel size is 32 (NVIDIA, RDNA, +/// and `moltenvk-m3`, whose kernel stage pins no size and so runs the API's 32 alone). +#[test] +fn quad_free_on_the_committed_profiles() { + let quad = SimdClass::CrossLane(OpBits::QUAD); + let mut free = Vec::new(); + for (stem, _) in committed_profiles() { + let dev = device(&stem); + let model = &dev.profile().fields().subgroup; + if !quad_free(&quad, Stage::Kernel, model) { + continue; + } + let st = model.stage(Stage::Kernel); + assert_eq!( + quad_requirement(Stage::Kernel, model), + SubgroupRequirement { + size: None, + full_subgroups: true, + local_size_multiple: st.sizes.max, + varying: true, + }, + "{stem}" + ); + free.push(format!("{stem} {}..{}", st.sizes.min, st.sizes.max)); + } + assert_eq!( + free, + [ + "gate-lavapipe 4..4", + "gate-lavapipe-x86_64 8..8", + "intel-arl-anv 8..32", + "intel-irisxe-anv 8..32", + "intel-irisxe-rplp-anv 8..32", + "intel-uhd770-rpls-anv 8..32", + "lavapipe 8..8", + ] + ); +} + #[test] fn missing_stage_or_operations_are_named() { let mut st = fixed(32); diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs index fa400ea39..e27a1c726 100644 --- a/crates/metal2vulkan/src/lower/dispatch.rs +++ b/crates/metal2vulkan/src/lower/dispatch.rs @@ -673,7 +673,11 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result Some(dispatch::plan_kernel(&mut cx, tier)?), Stage::Vertex | Stage::Fragment => None, diff --git a/crates/metal2vulkan/src/lower/simd/mod.rs b/crates/metal2vulkan/src/lower/simd/mod.rs index 7993c2fb2..7935d2e3c 100644 --- a/crates/metal2vulkan/src/lower/simd/mod.rs +++ b/crates/metal2vulkan/src/lower/simd/mod.rs @@ -14,10 +14,11 @@ //! operation classes the emitted SPIR-V needs, and `device::subgroup::tier` maps it to the tier //! emission follows (`Plan::simd`): //! -//! - `Direct` (a 32-lane subgroup) and `PartialFragment` (a narrower fragment subgroup whose -//! upper Metal lanes are permanently inactive): the simdgroup is the subgroup, so reductions, -//! scans, votes, `is_first`, and `broadcast_first` are the whole-subgroup -//! `OpGroupNonUniform*` instructions, and the Metal lane is `SubgroupLocalInvocationId`. +//! - `Direct` (a 32-lane subgroup; for a quad-only kernel, the subgroup at the size the device +//! gives, below) and `PartialFragment` (a narrower fragment subgroup whose upper Metal lanes are +//! permanently inactive): the simdgroup is the subgroup, so reductions, scans, votes, +//! `is_first`, and `broadcast_first` are the whole-subgroup `OpGroupNonUniform*` instructions, +//! and the Metal lane is `SubgroupLocalInvocationId`. //! - `Cluster32` (a 64- or 128-lane subgroup): the simdgroup is the aligned 32-lane cluster of //! the calling lane, `base = L & ~31`, Metal lane `L & 31`. Reductions are `ClusteredReduce` //! with cluster size 32, votes and `is_first`/`broadcast_first` read the cluster's ballot word @@ -80,6 +81,23 @@ //! were the same bits on both tiers in every run. The estimate's own cost is linear in the body: //! 5 ms of a 3.4 s release translation of a 162,914-instruction kernel. //! +//! **Quad-only kernels.** The 32 lanes are needed only by operations that read outside a quad; a +//! kernel with none takes its quads from the subgroup at the size the device gives; the pin to 32 +//! stays where 32 is the device's narrowest size. A kernel whose every cross-lane operation is a +//! quad operation ([`quad_only`]: no simdgroup operation, multiply-add, or simdgroup barrier or +//! fence) takes the `Direct` tier with full subgroups and no required size where its kernel stage +//! runs full subgroups and its narrowest subgroup is below 32 lanes and at least 4 +//! (`device::subgroup::quad_free`, as ANV's 8 to 32 and lavapipe's 8): the size varies where the +//! stage can pin one (`ALLOW_VARYING_SUBGROUP_SIZE`), and the local size is a multiple of the +//! stage's largest size (`device::subgroup::quad_requirement`). A quad is four subgroup lanes +//! from a multiple of 4, all in one subgroup (Vulkan 9.27.9), and a dispatch runs one size +//! (Vulkan 9.5.2), so at every size of 4 lanes or more each quad is four lanes of one subgroup; +//! the kernel's simdgroup builtins derive from the linear index (`lower::dispatch`), whatever the +//! size. Such a kernel pins nothing, so the widest mode is not weighed for it. A threadgroup that +//! is not a multiple of the largest size runs the emulated variant, as a pinned kernel's does. A +//! kernel with compute derivatives keeps the tier its class takes: their quads need its +//! two-dimensional local size, which the flattened tiers do not keep. +//! //! **Partly live groups on subgroups**. On `Direct`, `PartialFragment` and `Cluster32`, an //! operation that reads another lane's value by its index (a matrix or AGX multiply-add's cells; a //! simdgroup or quad shuffle, shuffle-xor, relative shuffle, rotation, broadcast by lane, or fill, @@ -350,6 +368,41 @@ pub struct SimdPlan { /// depends on which invocations share the simdgroup ([`finish`]). A quad operation does not set /// it. pub simdgroup_members: bool, + /// A kernel whose every cross-lane operation stays inside its quad ([`quad_only`]) on a + /// device whose narrowest kernel subgroup is below 32 lanes (`subgroup::quad_free`): its + /// `Direct` tier pins no size and takes its quads from the subgroup at the size the device + /// gives (`subgroup::quad_requirement`). + pub quad_free: bool, +} + +/// Whether every cross-lane operation of a function stays inside its quad: some group operation, +/// each of quad scope, and no simdgroup-scope operation, multiply-add, barrier or fence. Such a +/// function needs no 32-lane group: its quads are four aligned subgroup lanes at any subgroup +/// size that is a multiple of 4 (Vulkan 9.27.9), and its simdgroup builtins derive from the +/// linear index (`lower::dispatch`), whatever the subgroup size. +pub fn quad_only(strategy: &[Option]) -> bool { + use crate::lower::sync::barrier::BarrierStrategy; + use crate::spirv::ir::Scope; + let mut quad = false; + for s in strategy.iter().flatten() { + match s { + Strategy::Simd(SimdStrategy::Group(g)) => { + if g.scope != GroupScope::Quad { + return false; + } + quad = true; + } + Strategy::Simd(SimdStrategy::Agx(_) | SimdStrategy::Matrix(_)) => return false, + Strategy::Barrier(BarrierStrategy::Barrier(b)) if b.scope == Scope::Subgroup => { + return false + } + Strategy::Barrier(BarrierStrategy::Fence(f)) if f.scope == Scope::Subgroup => { + return false + } + _ => {} + } + } + quad } /// Whether [`widest_pin`] weighs a kernel for the `Emulated` tier, or the kernel keeps the diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index 7d3e2f568..717c526f7 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -1499,6 +1499,9 @@ fn stage_module(c: &CompiledFunction, linked: &Linked, i: usize) -> Result panic!("{stem} {t:?}: {other:?}"), } } + let quad = subgroup::tier(&SimdClass::Quad, Stage::Kernel, &p.fields().subgroup); + if linear && quad.is_ok() { + match (compile(&with_quad, "store_const", &p), quad) { + (Ok(a), Ok(Tier::Emulated)) => { + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_eq!(a.subgroup, SubgroupRequirement::NONE, "{stem}"); + kept += 1; + } + (Err(Error::Unsupported(u)), Ok(Tier::Direct | Tier::Cluster32)) => { + assert_eq!(u.feature, Feature::ComputeDerivativesWithSimd, "{stem}"); + } + (other, t) => panic!("{stem} quad {t:?}: {other:?}"), + } + } } assert!( - ok > 0 && missing > 0 && flattened > 0, - "{ok} ok, {missing} missing, {flattened} flattened" + ok > 0 && missing > 0 && flattened > 0 && kept > 0, + "{ok} ok, {missing} missing, {flattened} flattened, {kept} kept beside a quad" ); } diff --git a/crates/metal2vulkan/src/tests/engine_quad_ops.rs b/crates/metal2vulkan/src/tests/engine_quad_ops.rs index ed37035a4..5ddde4ba6 100644 --- a/crates/metal2vulkan/src/tests/engine_quad_ops.rs +++ b/crates/metal2vulkan/src/tests/engine_quad_ops.rs @@ -2,9 +2,11 @@ //! //! The owned fixture `engine/gsm2_quad_ops` (Apple's compiler's AIR of our own MSL) goes //! through the whole pipeline and its kernels run on the CPU interpreter in every kernel tier: the -//! `Direct` tier at 32 lanes on `moltenvk-m3`, the `Cluster32` tier at 64 lanes on a wave64-only -//! device, and the `Emulated` tier on `lavapipe` at 8, 16, 32 and 64 lanes, in both scheduling -//! orders. Every word is checked against Metal's answers as measured on the M3 Max and the M4: +//! `Direct` tier at 32 lanes on `moltenvk-m3`, the `Direct` tier with no pinned size at the sizes +//! the device gives on `lavapipe` (8 lanes) and an Intel profile (8, 16 and 32 lanes), the +//! `Cluster32` tier at 64 lanes on a wave64-only device, and the emulated-simdgroups variant on +//! `lavapipe` at 8, 16, 32 and 64 lanes, in both scheduling orders. Every word is checked against +//! Metal's answers as measured on the M3 Max and the M4: //! - a quad is four aligned lanes; quad lane `q` of thread `t` is `t & 3`; //! - a quad fill is the simdgroup fill within the quad for a modulo of 2 or 4, the only moduli //! the cases use (the others: `tests::engine_fill_moduli`); rotate up by `d` reads quad lane @@ -32,8 +34,10 @@ use crate::device::{DevicePolicy, DeviceProfile}; use crate::lower::arith::legal::f64_to_f16; use crate::lower::select::Plan; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; -use crate::pipeline::testing::{engine_dir, llvm_assemble, profile, typed_module, AssembleError}; -use crate::pipeline::PrecisionNote; +use crate::pipeline::testing::{ + engine_dir, llvm_assemble, profile, typed_module_with, AssembleError, +}; +use crate::pipeline::{LoweringInputs, PrecisionNote}; use crate::spirv::interp::{run, Buffer, Config, Order, Resources, SubgroupSize}; use crate::spirv::ir::TypedModule; @@ -339,15 +343,16 @@ fn fixture() -> Option> { } } -/// Every kernel of the fixture under `p`, planned in `tier`, at each of `widths`, and -/// [`reductions_in_metal_s_order`]. -fn run_kernels(p: &DeviceProfile, tier: Tier, widths: &[SubgroupSize]) { +/// Every kernel of the fixture under `p` and lowering inputs `inputs`, planned in `tier`, at each +/// of `widths`, and [`reductions_in_metal_s_order`]. +fn run_kernels(p: &DeviceProfile, inputs: &LoweringInputs, tier: Tier, widths: &[SubgroupSize]) { let Some(bc) = fixture() else { return; }; - reductions_in_metal_s_order(&bc, p, tier, widths); + reductions_in_metal_s_order(&bc, p, inputs, tier, widths); for (entry, locals, pairs) in KERNELS { - let (plan, m) = typed_module(&bc, entry, p).unwrap_or_else(|e| panic!("{entry}: {e}")); + let (plan, m) = + typed_module_with(&bc, entry, p, inputs).unwrap_or_else(|e| panic!("{entry}: {e}")); assert_eq!(plan.simd.1, tier, "{entry}"); for &lanes in widths { for &local in locals { @@ -385,9 +390,16 @@ fn tree(xs: [Option; 4], op: fn(f32, f32) -> f32) -> f32 { /// [`ordered`] inputs, over full quads and a threadgroup of 42 whose last quad holds two threads: /// Metal's `(x0 + x1) + (x2 + x3)` (measured), bit for bit; so the module records no /// `ReductionOrder`. -fn reductions_in_metal_s_order(bc: &[u8], p: &DeviceProfile, tier: Tier, widths: &[SubgroupSize]) { +fn reductions_in_metal_s_order( + bc: &[u8], + p: &DeviceProfile, + inputs: &LoweringInputs, + tier: Tier, + widths: &[SubgroupSize], +) { let entry = "quad_float_scans"; - let (plan, m) = typed_module(bc, entry, p).unwrap_or_else(|e| panic!("{entry}: {e}")); + let (plan, m) = + typed_module_with(bc, entry, p, inputs).unwrap_or_else(|e| panic!("{entry}: {e}")); assert_eq!(plan.simd.1, tier, "{entry}"); assert!( !plan.precision.contains(&PrecisionNote::ReductionOrder), @@ -424,7 +436,12 @@ fn reductions_in_metal_s_order(bc: &[u8], p: &DeviceProfile, tier: Tier, widths: #[test] fn quad_operations_run_direct_at_32_lanes() { let p = profile("moltenvk-m3", DevicePolicy::RESIDENT_TABLES).expect("profile"); - run_kernels(&p, Tier::Direct, &[SubgroupSize::W32]); + run_kernels( + &p, + &LoweringInputs::new(), + Tier::Direct, + &[SubgroupSize::W32], + ); } /// Each 64-lane subgroup holds two Metal simdgroups; a quad is four aligned lanes in either. @@ -432,17 +449,38 @@ fn quad_operations_run_direct_at_32_lanes() { fn quad_operations_run_cluster32_at_64_lanes() { run_kernels( &super::engine_simd::wave64(), + &LoweringInputs::new(), Tier::Cluster32, &[SubgroupSize::W64], ); } -/// `lavapipe` cannot pin 32 lanes: the quads are emulated through workgroup memory. +/// Every kernel of the fixture is quad-only: where the kernel stage's narrowest subgroup is below +/// 32 lanes (`lavapipe`'s 8; the Intel profiles' 8 to 32) it takes its quads from the subgroup at +/// the size the device gives, the `Direct` tier with no pinned size, and one module computes +/// Metal's answers at every size the device may run. +#[test] +fn quad_operations_run_direct_at_the_size_the_device_gives() { + use SubgroupSize::{W16, W32, W8}; + for (stem, widths) in [ + ("lavapipe", &[W8][..]), + ("intel-irisxe-rplp-anv", &[W8, W16, W32][..]), + ] { + let p = profile(stem, DevicePolicy::RESIDENT_TABLES).expect("profile"); + run_kernels(&p, &LoweringInputs::new(), Tier::Direct, widths); + } +} + +/// A threadgroup that is not a multiple of `lavapipe`'s 8 lanes runs the emulated-simdgroups +/// variant: the quads are emulated through workgroup memory. #[test] fn quad_operations_run_emulated_at_every_width() { let p = profile("lavapipe", DevicePolicy::RESIDENT_TABLES).expect("profile"); + let mut inputs = LoweringInputs::new(); + inputs.emulated_simdgroups = true; run_kernels( &p, + &inputs, Tier::Emulated, &[ SubgroupSize::W8, diff --git a/crates/metal2vulkan/src/tests/engine_simd.rs b/crates/metal2vulkan/src/tests/engine_simd.rs index 3f24aa2ee..e03478244 100644 --- a/crates/metal2vulkan/src/tests/engine_simd.rs +++ b/crates/metal2vulkan/src/tests/engine_simd.rs @@ -421,6 +421,75 @@ fn quad_shuffle_matches_the_linear_thread_index() { } } +/// A quad-only kernel (`quad_shuffle_rotate`) takes its quads from the subgroup at the size the +/// device gives exactly where the kernel stage runs full subgroups and its narrowest size is below +/// 32 lanes (and at least 4): the `Direct` tier with full subgroups, no pinned size, the size +/// varying (`ALLOW_VARYING_SUBGROUP_SIZE`, so `subgroupSizeControl`), and a local size that is a +/// multiple of the stage's largest size. Elsewhere it keeps the requirement of the tier its class +/// takes: 32 lanes pinned where 32 is the narrowest size (NVIDIA's 32, RDNA's 32 to 64), the API's +/// size where the stage pins none (`moltenvk-m3`), and no subgroup where the stage has no quads +/// (`runtime-floor`). +#[test] +fn a_quad_only_kernel_takes_the_size_the_device_gives_below_32() { + let Some(bc) = assemble("quad_shuffle") else { + return; + }; + let entry = "quad_shuffle_rotate"; + let mut varying = Vec::new(); + for (stem, p) in committed_profiles().expect("profiles") { + let model = &p.fields().subgroup; + let st = model.kernel; + let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{stem}: {e}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: {e}")); + let (plan, _) = typed_module(&bc, entry, &p).unwrap_or_else(|e| panic!("{stem}: {e}")); + let flag = a + .requirements + .stage_flags + .contains(&StageCreateFlag::AllowVaryingSubgroupSize); + assert_eq!(flag, a.subgroup.varying, "{stem}"); + if a.subgroup.varying { + varying.push(stem.clone()); + assert_eq!(plan.simd.1, Tier::Direct, "{stem}"); + assert!((4..32).contains(&st.sizes.min), "{stem}: {st:?}"); + assert_eq!( + a.subgroup, + SubgroupRequirement { + size: None, + full_subgroups: true, + local_size_multiple: st.sizes.max, + varying: true, + }, + "{stem}" + ); + assert!(a.facts.contains(&RuntimeFact::LocalSizeConstraint { + multiple: st.sizes.max + })); + } else { + assert_eq!( + a.subgroup, + subgroup::requirement(plan.simd.1, Stage::Kernel, model), + "{stem}" + ); + if st.pinnable && st.sizes.min >= 32 { + assert_eq!(a.subgroup.size, Some(32), "{stem}"); + } + } + assert_eq!(p.check(&a.requirements), Ok(()), "{stem}"); + } + assert_eq!( + varying, + [ + "gate-lavapipe", + "gate-lavapipe-x86_64", + "intel-arl-anv", + "intel-irisxe-anv", + "intel-irisxe-rplp-anv", + "intel-uhd770-rpls-anv", + "lavapipe", + ] + ); +} + /// On every committed profile each kernel compiles, links, relocates, and passes L3 in its /// tier. A flattened kernel declares its subgroup requirement and local-size constraint. Where no /// subgroup tier runs a 32-lane simdgroup the kernel's simdgroups are emulated: it needs no @@ -444,10 +513,20 @@ fn simd_kernels_compile_or_refuse_with_the_tier() { link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem} {kernel}: {e}")); if a.interface.declares_spec(SpecKey::FlatLocalSize) { let multiple = a.subgroup.local_size_multiple; - assert!( - multiple >= 32 && a.subgroup.full_subgroups, - "{stem} {kernel}" - ); + assert!(a.subgroup.full_subgroups, "{stem} {kernel}"); + if a.subgroup.varying { + // A quad-only kernel at the size the device gives: whole subgroups + // of the stage's largest size. + assert!(kernel.starts_with("quad_"), "{stem} {kernel}"); + assert_eq!(a.subgroup.size, None, "{stem} {kernel}"); + assert_eq!( + multiple, + p.fields().subgroup.kernel.sizes.max, + "{stem} {kernel}" + ); + } else { + assert!(multiple >= 32, "{stem} {kernel}"); + } assert!(a .facts .contains(&RuntimeFact::LocalSizeConstraint { multiple })); diff --git a/docs/API.md b/docs/API.md index 932cf10e3..0c7d49426 100644 --- a/docs/API.md +++ b/docs/API.md @@ -455,7 +455,8 @@ gives the specialization constants' keys, and with the stage's `stage_flags` and declares from it, never one alone: a kernel that declares `DeepThreadgroup` takes its Vulkan workgroup from the `WorkgroupSize` parts only, so one given its `LocalSize` without them runs workgroups of the parts' defaults. A required subgroup size needs `subgroupSizeControl` and the stage in -`requiredSubgroupSizeStages`; full subgroups need `computeFullSubgroups`. A pipeline compiled for +`requiredSubgroupSizeStages`; full subgroups need `computeFullSubgroups`; a size that varies +(`ALLOW_VARYING_SUBGROUP_SIZE`) needs `subgroupSizeControl`. A pipeline compiled for one device pins only what that device can take; `DeviceProfile::check` tells whether another device can. @@ -496,6 +497,18 @@ faster; from 40 the pinned compile took 1.6 to 24 times the emulated one and its were the same bits on both tiers. The estimate costs time linear in the body: 5 ms of a 3.4 s release translation of a 162,914-instruction kernel. +The 32 lanes are needed only by operations that read outside a quad. A kernel whose every +cross-lane operation is a quad operation (no simdgroup operation, multiply-add, or simdgroup barrier +or fence) pins nothing where the kernel stage runs full subgroups, can take a size, and has a +narrowest size below 32 lanes and at least 4 (ANV's 8 to 32, lavapipe's 8): it takes its quads +from the subgroup at the size the device gives, with full subgroups, +`ALLOW_VARYING_SUBGROUP_SIZE` and a local size that is a multiple of `maxSubgroupSize`. A quad is +four lanes of one subgroup at every such size (Vulkan 9.27.9), so its answers do not change, and +the widest mode is not weighed for it. The pin to 32 stays where 32 is the device's narrowest size +(NVIDIA's 32, RDNA's 32 to 64); a device whose compute stage takes no size runs the API's +`subgroupSize`. A kernel with compute derivatives keeps the tier its class takes. + + On the emulated tier, a simdgroup operation or barrier in a block whose control flow differs between threads is walked predicated: each thread carries a live flag, the threads that do not run the block take part in its exchanges as inactive lanes, and a loop that holds one votes on its