diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 43d786e3c..b74c0c9e5 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -348,9 +348,9 @@ pub(crate) struct Choice { /// partial-threadgroups variant ([`decide`] runs its whole grids and indirect dispatches there /// too). /// -/// A size deeper than `DEEP_THREADGROUP` runs as one row of its threads -/// ([`Constant::Deep`](crate::pipeline::Constant::Deep)), so every workgroup is within the -/// floor's `maxComputeWorkGroupSize`. +/// A size deeper than `DEEP_THREADGROUP` runs as one row of its threads (`DeepThreadgroup`, +/// [`Constant::Threadgroup`](crate::pipeline::Constant::Threadgroup)), so every workgroup is +/// within the floor's `maxComputeWorkGroupSize`. pub(crate) fn choose(form: &Form, direct: Option, size: [u32; 3]) -> Choice { let Some(direct) = direct else { return Choice { diff --git a/crates/metal2vulkan-runtime/src/pipeline.rs b/crates/metal2vulkan-runtime/src/pipeline.rs index 3d9977b6b..6ee4c3b88 100644 --- a/crates/metal2vulkan-runtime/src/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/pipeline.rs @@ -81,11 +81,11 @@ use metal2vulkan::error::{Error as TranslationError, Feature}; use metal2vulkan::library::{CompiledFunction, FunctionCompileKey}; use metal2vulkan::metal::{BindingAccess, BindingType}; use metal2vulkan::pipeline::{ - arena_bytes, AccessSet, Axis, BindingSource, BufferKind, CombinedSampler, ComputePipeline, - ComputePipelineDescriptor, DescriptorSetLayout, FunctionDescriptor, KernelVariant, - LinkedFunctions, LoweringInputs, NumberedSampler, PrecisionNote, PushField, PushLoc, - RuntimeFact, SamplerRef, SlotClass, SlotInterface, SlotRef, SpecKey, Stage, StageEntries, - StageSource, TextureAccess, DEEP_THREADGROUP, GRID_TILE_THREADS, + arena_bytes, threadgroup_constants, AccessSet, BindingSource, BufferKind, CombinedSampler, + ComputePipeline, ComputePipelineDescriptor, DescriptorSetLayout, FunctionDescriptor, + KernelVariant, LinkedFunctions, LoweringInputs, NumberedSampler, PrecisionNote, PushField, + PushLoc, RuntimeFact, SamplerRef, SlotClass, SlotInterface, SlotRef, SpecKey, Stage, + StageEntries, StageSource, TextureAccess, GRID_TILE_THREADS, }; use metal2vulkan::Budget; use std::ffi::CString; @@ -396,7 +396,7 @@ pub(crate) enum Form { /// (`CompiledFunction::is_image_only`): `whole` runs a direct dispatch at `MultiRegion` 0, /// whatever the threadgroup size, in workgroups of [`SQUARE`] over a grid one deep and of its /// `encoder::image_tile` over a deeper one, a tile deeper than `DEEP_THREADGROUP` as one row - /// ([`Constant::Deep`]). + /// (`DeepThreadgroup`, [`Constant::Threadgroup`]). Square, /// The kernel observes its partition: a dispatch runs at its own threadgroup size, every one, /// direct or indirect, on the partial-threadgroups variant (`partial`), wherever the variant @@ -771,10 +771,10 @@ impl Memory { /// What sets a specialization constant. #[derive(Clone, Copy)] pub(crate) enum Constant { - /// The threadgroup size on one axis, 0 to 2. - Size(usize), - /// The threadgroup's threads: the product of its size. - Threads, + /// A key the threadgroup's size decides (`LocalSize`, `FlatLocalSize`, `DeepThreadgroup`, + /// `WorkgroupSize`): the value the translator's `threadgroup_constants` gives it for the + /// threadgroup, the one source of all of them, so they are written together and agree. + Threadgroup(SpecKey), /// The length of the threadgroup memory argument at this position of /// [`Interface::threadgroups`]. ThreadgroupLength(usize), @@ -785,9 +785,6 @@ pub(crate) enum Constant { /// tile; 0 for every other launch, whose region states the pipeline's own threadgroup size, /// so the kernel takes `L` from its workgroup size and reads no decode. MultiRegion, - /// `DeepThreadgroup`: 1 where the threadgroup is deeper than `DEEP_THREADGROUP`, which then - /// runs as one row of its threads, 0 for every other, whose workgroup is the threadgroup. - Deep, } /// A parameter and where it goes. @@ -1804,10 +1801,9 @@ pub(crate) fn interface( return Err(KernelInputKind::Specialization); } let set = match constant.key { - SpecKey::LocalSize(Axis::X) => Constant::Size(0), - SpecKey::LocalSize(Axis::Y) => Constant::Size(1), - SpecKey::LocalSize(Axis::Z) => Constant::Size(2), - SpecKey::FlatLocalSize => Constant::Threads, + key if threadgroup_constants([1; 3]).iter().any(|&(k, _)| k == key) => { + Constant::Threadgroup(key) + } SpecKey::TgLength(index) => Constant::ThreadgroupLength( threadgroups .iter() @@ -1815,7 +1811,6 @@ pub(crate) fn interface( .ok_or(KernelInputKind::Specialization)?, ), SpecKey::MultiRegion => Constant::MultiRegion, - SpecKey::DeepThreadgroup => Constant::Deep, // A thread-position `[[stage_in]]` fetch's reach check, kept at the module's default // (true) for every dispatch: one pipeline, whose fetch reads an element past the first // 2^32 bytes from its bind offset as zero. @@ -1830,7 +1825,7 @@ pub(crate) fn interface( // buffers alone does not take. let flat = constants .iter() - .any(|(_, set)| matches!(set, Constant::Threads)); + .any(|(_, set)| matches!(set, Constant::Threadgroup(SpecKey::FlatLocalSize))); if !multiples.is_empty() && !flat { return Err(KernelInputKind::Workgroup); } @@ -1839,7 +1834,7 @@ pub(crate) fn interface( // that cannot (compute derivatives) does not declare. let deep = constants .iter() - .any(|(_, set)| matches!(set, Constant::Deep)); + .any(|(_, set)| matches!(set, Constant::Threadgroup(SpecKey::DeepThreadgroup))); if !flat && !deep { return Err(KernelInputKind::Workgroup); } @@ -2591,15 +2586,17 @@ impl Kernel { size: 4, }) .collect(); + let threadgroup = threadgroup_constants(variant.size); let values: Vec = constants .iter() .map(|&(_, set)| match set { - Constant::Size(axis) => variant.size[axis], - Constant::Threads => variant.size.iter().product(), + // Each value is a size of the threadgroup's, a count of its threads or 0 or 1. + Constant::Threadgroup(key) => (threadgroup.iter()) + .find(|&&(k, _)| k == key) + .map_or(0, |&(_, value)| u32::try_from(value).unwrap_or(u32::MAX)), Constant::ThreadgroupLength(at) => variant.lengths.as_slice()[at], Constant::Imageblock(axis) => variant.lengths.imageblock[axis], Constant::MultiRegion => u32::from(variant.tiles), - Constant::Deep => u32::from(variant.size[2] > DEEP_THREADGROUP), }) .flat_map(u32::to_ne_bytes) .collect(); diff --git a/crates/metal2vulkan-runtime/src/tests/compute.rs b/crates/metal2vulkan-runtime/src/tests/compute.rs index 1df4f4db7..e3424413d 100644 --- a/crates/metal2vulkan-runtime/src/tests/compute.rs +++ b/crates/metal2vulkan-runtime/src/tests/compute.rs @@ -18,6 +18,7 @@ pub(crate) mod on_device { Buffer, CommandBuffer, ComputeCommandEncoder, ComputePipelineState, Device, DispatchType, Error, Gap, HeapRange, Limit, MemoryClass, Refusal, RefusalBasis, }; + use metal2vulkan::pipeline::{Axis, SpecKey}; /// Words in each test buffer: 256 bytes. pub(crate) const WORDS: usize = 64; @@ -56,9 +57,9 @@ pub(crate) mod on_device { private_arena: None, imageblock: None, constants: vec![ - (0, Constant::Size(0)), - (1, Constant::Size(1)), - (2, Constant::Size(2)), + (0, Constant::Threadgroup(SpecKey::LocalSize(Axis::X))), + (1, Constant::Threadgroup(SpecKey::LocalSize(Axis::Y))), + (2, Constant::Threadgroup(SpecKey::LocalSize(Axis::Z))), ], threadgroups: Vec::new(), max_total_threads: 1024, diff --git a/crates/metal2vulkan-runtime/src/tests/deep_threadgroups.rs b/crates/metal2vulkan-runtime/src/tests/deep_threadgroups.rs index c031c5238..68a8a36b2 100644 --- a/crates/metal2vulkan-runtime/src/tests/deep_threadgroups.rs +++ b/crates/metal2vulkan-runtime/src/tests/deep_threadgroups.rs @@ -6,7 +6,14 @@ //! every device's limits. Each simdgroup is 32 consecutive threads, as Metal's are: thread `t` //! answers `1024 (t / 32) + 496 + 11200000`. //! -//! `llvm-as` assembles the fixture; without it the test skips visibly. +//! Also every thread of every workgroup writes its own word, deep or not: `grid_words` (an owned +//! kernel with no SIMD-group function, so its workgroup is its threadgroup, and which reads its +//! threadgroup's position and size, so it runs at its own size) stores `i + 1` at its index `i` in +//! the grid, over threadgroups of `[1, 1, 96]` (one row), `[8, 8, 1]` and `[4, 4, 4]`, several +//! of each. Each workgroup's size is its `WorkgroupSize` constants, which a driver reads from the +//! composite's parts as declared. +//! +//! `llvm-as` assembles the fixtures; without it the tests skip visibly. #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { @@ -15,7 +22,7 @@ mod on_device { ComputePipelineDescriptor, DispatchType, FunctionDescriptor, Library, MemoryClass, StageSource, }; - use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError}; + use metal2vulkan_devtools::{engine_dir, llvm_assemble, llvm_assemble_text, AssembleError}; /// The threadgroup's depth: past `DEEP_THREADGROUP`, the floor's z. const DEPTH: u32 = 96; @@ -85,4 +92,115 @@ mod on_device { println!("{name}: one threadgroup of [1, 1, {DEPTH}], Metal's simdgroup sums"); }); } + + /// The owned synthetic kernel: thread `group * size + pos` of a grid of `grid` threads stores + /// its index in the grid plus 1 at that index, `x` fastest. + const GRID_WORDS: &str = "; Owned synthetic kernel. +source_filename = \"grid_words.metal\" + +define void @grid_words(ptr addrspace(1) %out, <3 x i32> %group, <3 x i32> %size, <3 x i32> %pos, <3 x i32> %grid) { +entry: + %g = mul <3 x i32> %group, %size + %q = add <3 x i32> %g, %pos + %x = extractelement <3 x i32> %q, i64 0 + %y = extractelement <3 x i32> %q, i64 1 + %z = extractelement <3 x i32> %q, i64 2 + %gx = extractelement <3 x i32> %grid, i64 0 + %gy = extractelement <3 x i32> %grid, i64 1 + %zy = mul i32 %z, %gy + %row = add i32 %zy, %y + %rx = mul i32 %row, %gx + %i = add i32 %rx, %x + %v = add i32 %i, 1 + %w = zext i32 %i to i64 + %p = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %w + store i32 %v, ptr addrspace(1) %p, align 4 + ret void +} + +!air.kernel = !{!0} +!0 = !{ptr @grid_words, !1, !2} +!1 = !{} +!2 = !{!10, !11, !12, !13, !14} +!10 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.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\"} +!11 = !{i32 1, !\"air.threadgroup_position_in_grid\", !\"air.arg_type_name\", !\"uint3\", !\"air.arg_name\", !\"group\"} +!12 = !{i32 2, !\"air.threads_per_threadgroup\", !\"air.arg_type_name\", !\"uint3\", !\"air.arg_name\", !\"size\"} +!13 = !{i32 3, !\"air.thread_position_in_threadgroup\", !\"air.arg_type_name\", !\"uint3\", !\"air.arg_name\", !\"pos\"} +!14 = !{i32 4, !\"air.threads_per_grid\", !\"air.arg_type_name\", !\"uint3\", !\"air.arg_name\", !\"grid\"} +"; + + /// Every thread of every workgroup writes its own word, whether its threadgroup runs as one + /// row (`[1, 1, 96]`) or as its own workgroup (`[8, 8, 1]`, `[4, 4, 4]`), on every device. + #[test] + fn every_device_runs_every_thread_of_each_workgroup_deep_or_not() { + let bitcode = match llvm_assemble_text(GRID_WORDS) { + Ok(bitcode) => bitcode, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(error) => panic!("grid_words: {error:?}"), + }; + let library = Library::from_air(&bitcode).expect("the library"); + let function = library.function("grid_words").expect("the kernel"); + let descriptor = ComputePipelineDescriptor::new(StageSource::Function( + FunctionDescriptor::new(function), + )); + // Each threadgroup, and its grid of two or more of them on each axis it spans. + let cases: [([u32; 3], [u32; 3]); 3] = [ + ([1, 1, DEPTH], [2, 1, 2 * DEPTH]), + ([8, 8, 1], [16, 16, 1]), + ([4, 4, 4], [8, 8, 8]), + ]; + each_device("deep_threadgroups grid_words", |name, _, device| { + let state = device + .new_compute_pipeline_state(&descriptor, crate::tests::no_constexpr_samplers) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let queue = device.new_command_queue(4).expect("a queue"); + for (threadgroup, grid) in cases { + let words = grid.iter().product::(); + let len = u64::from(words * 4); + let block = (device.take_block(MemoryClass::Shared, len)).expect("a Shared block"); + let output = (device.new_buffer(block.id, 0, len, Some(0))).expect("the output"); + let contents = output.contents().expect("a Shared buffer"); + // SAFETY: the buffer is alive and nothing else reaches its bytes. + unsafe { std::ptr::write_bytes(contents.as_ptr(), 0xff, len as usize) }; + 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(&output), 0, 0).expect("a buffer"); + encoder + .dispatch_threads(grid, threadgroup) + .unwrap_or_else(|error| panic!("{name}: the dispatch: {error}")); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + let wrong: Vec = (0..words) + .filter(|&i| { + // SAFETY: the word lies in the buffer, which is alive, and its work + // completed. + let got = unsafe { + (contents.as_ptr().cast::()) + .add(i as usize) + .read_unaligned() + }; + got != i + 1 + }) + .collect(); + assert!( + wrong.is_empty(), + "{name}: {grid:?} in threadgroups of {threadgroup:?}: {} of {words} words \ + wrong, the first {:?}", + wrong.len(), + &wrong[..wrong.len().min(8)] + ); + println!("{name}: {grid:?} in threadgroups of {threadgroup:?}: {words} words"); + drop(output); + (device.release_block(block)).unwrap_or_else(|e| panic!("{name}: {e}")); + } + }); + } } diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 44e966ba6..1b53235fe 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -867,6 +867,7 @@ codec_enum! { ConstantLanes(f0), BoundTexelFormat(f0), OffsetBaseAxes(f0), SamplerAnisotropy(f0), NearestPixelSampler(f0), BoundSamplerWord(f0), StageInReach, HeapRawTextures(f0), BorderTexels(f0), HeapNanFamilies(f0), DeepThreadgroup, + WorkgroupSize(f0), } PushField { RootTableAddress, ExecutionStatusAddress, DispatchRegion, BaseVertexInstance, diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs index 7b1bd5690..fa400ea39 100644 --- a/crates/metal2vulkan/src/lower/dispatch.rs +++ b/crates/metal2vulkan/src/lower/dispatch.rs @@ -13,14 +13,19 @@ //! object and mesh threadgroups take separate sizes. //! //! **Deep threadgroups.** A kernel of the `Spec` form declares `SpecKey::DeepThreadgroup` ([`DispatchPlan::deep`]), under -//! which its `WorkgroupSize` is `(sn, 1, 1)`, `sn = sx·sy·sz` (each part an `OpSpecConstantOp` -//! select of the constants) and its position in the threadgroup `LocalInvocationIndex` +//! which its `WorkgroupSize` is `(sn, 1, 1)`, `sn = sx·sy·sz`, and its position in the threadgroup +//! `LocalInvocationIndex` //! unflattened over `(sx, sy, sz)`: Metal allows 1024 threads along `z`, where a device's //! `maxComputeWorkGroupSize[2]` may hold 64, and a threadgroup of at most 1024 threads in one row //! fits every device the profile serves. The linear index keeps its value, `x` fastest either //! way, and so does every builtin derived from it, the workgroup's and the grid's. The runtime //! sets it for a threadgroup deeper than [`DEEP_THREADGROUP`] alone, so a pipeline of any other -//! size specializes it away. +//! size specializes it away. Such a kernel's `WorkgroupSize` parts are the plain specialization +//! constants `SpecKey::WorkgroupSize`, which the runtime writes with every other key the +//! threadgroup decides from [`threadgroup_constants`]: no `WorkgroupSize` part of any form is an +//! `OpSpecConstantOp` +//! (`ModuleBuilder::workgroup_size`), so the size a driver reads from the composite's parts as +//! declared is the one the body computes with. //! //! **Builtins** ([`KernelBuiltin`]). Every Metal kernel builtin derives from a handful of Vulkan //! ones and the linear local index `lin`: @@ -189,13 +194,13 @@ use crate::lower::arith; use crate::lower::emit::EmitCx; use crate::lower::select::{Plan, SelectCx}; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::{DispatchKeys, PushField, SpecKey}; +use crate::pipeline::sym::{Axis, DispatchKeys, PushField, SpecKey}; use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::error::BResult; use crate::spirv::ids::{ConstId, DemoteTy, GlobalId, ScalarTy, TypeId, Value as SValue}; use crate::spirv::ir::{ - BinOp, ConstBits, Constant, ConvOp, ExecMode, GlslOp, IoDir, MemAccess, SpecOp, Type, UnOp, + BinOp, ConstBits, Constant, ConvOp, ExecMode, GlslOp, IoDir, MemAccess, Type, UnOp, }; /// The builder's error for a value the declarations do not hold. @@ -1125,6 +1130,35 @@ pub const GRID_TILE_THREADS: u32 = 256; /// of the devices that profile serves (Vulkan's own minimum). pub const DEEP_THREADGROUP: u32 = 64; +/// Every specialization constant a kernel's threadgroup of `size` decides, as `(key, value)`: +/// its `LocalSize` on each axis, its `FlatLocalSize` (`x·y·z`), its `DeepThreadgroup` (1 where it +/// is deeper than [`DEEP_THREADGROUP`], which then runs as one row of its threads) and the +/// `WorkgroupSize` part on each axis of the Vulkan workgroup it runs as, `[x·y·z, 1, 1]` where it +/// is deep, else `size`. A runtime writes each of these keys a kernel's stage declares from this +/// call, and none by hand: a kernel that declares `DeepThreadgroup` takes its workgroup from the +/// `WorkgroupSize` parts alone, plain specialization constants, so one given its `LocalSize` +/// without them would run at their defaults. An object function's threadgroup has keys of its own +/// (`SpecKey::ObjectLocalSize`), which this does not answer. +pub fn threadgroup_constants(size: [u32; 3]) -> [(SpecKey, u64); 8] { + let [x, y, z] = size; + let threads = x.saturating_mul(y).saturating_mul(z); + let deep = z > DEEP_THREADGROUP; + let [wx, wy, wz] = match deep { + true => [threads, 1, 1], + false => size, + }; + [ + (SpecKey::LocalSize(Axis::X), u64::from(x)), + (SpecKey::LocalSize(Axis::Y), u64::from(y)), + (SpecKey::LocalSize(Axis::Z), u64::from(z)), + (SpecKey::FlatLocalSize, u64::from(threads)), + (SpecKey::DeepThreadgroup, u64::from(deep)), + (SpecKey::WorkgroupSize(Axis::X), u64::from(wx)), + (SpecKey::WorkgroupSize(Axis::Y), u64::from(wy)), + (SpecKey::WorkgroupSize(Axis::Z), u64::from(wz)), + ] +} + /// The tile a kernel's grid tiles (`RuntimeFact::GridTiles`) cover a grid of `threads` with: sides /// `2^a, 2^b, 2^c` with `a + b + c = 8`, so that one workgroup of [`GRID_TILE_THREADS`] is one /// tile, dispatched as `⌈threads / tile⌉` workgroups per axis. Of every such tile it is the first @@ -1241,14 +1275,12 @@ impl KernelDecl { LocalSizeForm::Spec if dp.deep => { let b = mb.ty(Type::Bool)?; let one_row = mb.spec(SpecKey::DeepThreadgroup, b, ConstBits(0))?; - let row = mb.spec_op(SpecOp::IMul, u32_, &[size[0], size[1]])?; - let sn = mb.spec_op(SpecOp::IMul, u32_, &[row, size[2]])?; - let one = mb.constant(Constant::Scalar { - ty: u32_, - bits: ConstBits(1), - })?; - let [x, y, z] = [(sn, size[0]), (one, size[1]), (one, size[2])] - .map(|(deep, own)| mb.spec_op(SpecOp::Select, u32_, &[one_row, deep, own])); + // The workgroup's sides, which the runtime writes from `threadgroup_constants` + // beside `sx, sy, sz` and `one_row`: plain constants, at the threadgroup's + // defaults. + let [x, y, z] = [(Axis::X, dx), (Axis::Y, dy), (Axis::Z, dz)].map(|(axis, d)| { + mb.spec(SpecKey::WorkgroupSize(axis), u32_, ConstBits(u64::from(d))) + }); deep = Some(one_row); mb.workgroup_size(x?, y?, z?)? } diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index 35cd658b4..cd1d151b2 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -147,11 +147,12 @@ pub use compile::{ }; pub use facts::{Mechanism, RuntimeFact}; // The `DispatchRegion` push field's bytes, which a consumer of the identity domains pushes with -// each dispatch, the tile a kernel's grid tiles cover a grid with (`RuntimeFact::GridTiles`), and -// the depth past which a threadgroup runs as one row (`SpecKey::DeepThreadgroup`). +// each dispatch, the tile a kernel's grid tiles cover a grid with (`RuntimeFact::GridTiles`), the +// depth past which a threadgroup runs as one row (`SpecKey::DeepThreadgroup`), and every +// specialization constant a kernel's threadgroup size decides. pub use crate::lower::dispatch::{ - grid_tile, nonuniform_region_bytes, region_bytes, DEEP_THREADGROUP, GRID_TILE_THREADS, - NONUNIFORM, + grid_tile, nonuniform_region_bytes, region_bytes, threadgroup_constants, DEEP_THREADGROUP, + GRID_TILE_THREADS, NONUNIFORM, }; // The threadgroup memory of an emulated-simdgroup module's arena (`RuntimeFact::SimdgroupEmulation`), // which a consumer of the identity domains counts with each dispatch's scratch. diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 4703ab2d6..72e6776c5 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -717,7 +717,8 @@ pub enum SpecKey { /// `RuntimeFact::BorderTexels`). BorderTexels(SlotRef), /// Boolean: the kernel's threadgroup runs as one row (default false). Its workgroup is then - /// `(sx·sy·sz, 1, 1)`, and its position in the threadgroup is its `LocalInvocationIndex` + /// `(sx·sy·sz, 1, 1)` (its [`WorkgroupSize`](SpecKey::WorkgroupSize) constants), and its + /// position in the threadgroup is its `LocalInvocationIndex` /// unflattened over `(sx, sy, sz)`, `x` fastest, which is Metal's order, so its linear index /// and every other builtin keep their values. Declared on `Device::from_queries`' profile by /// a kernel whose workgroup is its threadgroup (`LocalSizeForm::Spec`), so a threadgroup @@ -725,6 +726,15 @@ pub enum SpecKey { /// device's `maxComputeWorkGroupSize`; where it is false the workgroup is `(sx, sy, sz)` and /// the pipeline is the one the kernel makes without it. DeepThreadgroup, + /// A kernel's Vulkan workgroup size on one axis, where it declares + /// [`DeepThreadgroup`](SpecKey::DeepThreadgroup) (default the axis's `LocalSize` default): + /// the threadgroup's own size, or `(sx·sy·sz, 1, 1)` where `DeepThreadgroup` is true, as + /// [`threadgroup_constants`](crate::pipeline::threadgroup_constants) answers for the + /// threadgroup with its other keys. Each + /// part of the module's `WorkgroupSize` is such a plain constant, never an + /// `OpSpecConstantOp`: the size a driver reads from the composite's parts as declared is the + /// one the body computes with. + WorkgroupSize(Axis), } impl SpecKey { diff --git a/crates/metal2vulkan/src/spirv/builder/module.rs b/crates/metal2vulkan/src/spirv/builder/module.rs index 1be26c91e..223b241d5 100644 --- a/crates/metal2vulkan/src/spirv/builder/module.rs +++ b/crates/metal2vulkan/src/spirv/builder/module.rs @@ -420,11 +420,13 @@ impl ModuleBuilder { Ok(id) } - /// Declare the module's local size as the constants `x`, `y`, `z` (positive `u32` scalars, at - /// least one a specialization constant from [`ModuleBuilder::spec`] and the others plain, as - /// in the flattened `(sn, 1, 1)`): an `OpSpecConstantComposite` decorated `BuiltIn - /// WorkgroupSize`. Valid under Vulkan 1.2 without `maintenance4`, unlike `LocalSizeId`. A - /// `GLCompute` entry declared after it needs no local-size mode. + /// Declare the module's local size as the constants `x`, `y`, `z` (positive `u32` scalars, + /// each a plain constant or a specialization constant from [`ModuleBuilder::spec`] and at + /// least one the latter, as in the flattened `(sn, 1, 1)`): an `OpSpecConstantComposite` + /// decorated `BuiltIn WorkgroupSize`. An `OpSpecConstantOp` part is + /// [`ConstRule::WorkgroupSizeOp`](crate::spirv::error::ConstRule::WorkgroupSizeOp). Valid + /// under Vulkan 1.2 without `maintenance4`, unlike `LocalSizeId`. A `GLCompute` entry declared + /// after it needs no local-size mode. pub fn workgroup_size(&mut self, x: ConstId, y: ConstId, z: ConstId) -> BResult { let u32_ = self.ty(Type::Int { width: 32, diff --git a/crates/metal2vulkan/src/spirv/error.rs b/crates/metal2vulkan/src/spirv/error.rs index 35a149e81..19ca1fdcb 100644 --- a/crates/metal2vulkan/src/spirv/error.rs +++ b/crates/metal2vulkan/src/spirv/error.rs @@ -167,6 +167,10 @@ pub enum ConstRule { /// An `OpSpecConstantOp` whose operands are not scalar constants of the types its operation /// requires, or none of which is specialization-dependent. SpecOpOperands, + /// A `WorkgroupSize` part that is an `OpSpecConstantOp`: each part is a plain constant or a + /// plain specialization constant, so the size a driver reads from the parts as declared is the + /// one the module's body computes with. + WorkgroupSizeOp, } /// A violated module-scope variable rule. diff --git a/crates/metal2vulkan/src/spirv/ir/constant.rs b/crates/metal2vulkan/src/spirv/ir/constant.rs index 9a601ba05..cac964ba9 100644 --- a/crates/metal2vulkan/src/spirv/ir/constant.rs +++ b/crates/metal2vulkan/src/spirv/ir/constant.rs @@ -375,9 +375,11 @@ impl Consts { } /// Declare the module's `WorkgroupSize` composite of `ty` (a `u32` 3-vector) from three - /// positive `u32` constants ([`Consts::positive`]), at least one of them a specialization - /// constant or an `OpSpecConstantOp` of them. Declaring it again with the same parts returns - /// the first declaration; different parts are a conflict. + /// positive `u32` constants ([`Consts::positive`]), each a plain constant or a plain + /// specialization constant and at least one the latter. An `OpSpecConstantOp` part is + /// [`ConstRule::WorkgroupSizeOp`]: a driver may size the workgroup from the parts as declared, + /// and read such a part as 1 whatever the body computes from it. Declaring it again with the + /// same parts returns the first declaration; different parts are a conflict. pub fn workgroup_size( &mut self, ty: TypeId, @@ -411,8 +413,12 @@ impl Consts { let mut specs = 0; for p in parts { let def = self.get(p)?; - if matches!(def.kind, ConstKind::Spec { .. } | ConstKind::SpecOp { .. }) { - specs += 1; + match def.kind { + ConstKind::Spec { .. } => specs += 1, + ConstKind::SpecOp { .. } => { + return Err(BuildError::Constant(ConstRule::WorkgroupSizeOp)) + } + _ => {} } // A local size of zero is invalid on every axis, so a part must be positive. if def.ty != u32_elem || !self.positive(p)? { @@ -432,26 +438,11 @@ impl Consts { } /// Whether constant `c` is positive at its defaults: a plain scalar or a specialization - /// constant's default above 0, or a product or select of such. An `OpSpecConstantOp` of any - /// other operation is not known to be. + /// constant's default above 0. fn positive(&self, c: ConstId) -> BResult { Ok(match &self.get(c)?.kind { ConstKind::Spec { default, .. } => default.0 != 0, ConstKind::Plain(Constant::Scalar { bits, .. }) => bits.0 != 0, - ConstKind::SpecOp { - op: SpecOp::IMul, - operands, - } => match **operands { - [a, b] => self.positive(a)? && self.positive(b)?, - _ => false, - }, - ConstKind::SpecOp { - op: SpecOp::Select, - operands, - } => match **operands { - [_, a, b] => self.positive(a)? && self.positive(b)?, - _ => false, - }, _ => false, }) } diff --git a/crates/metal2vulkan/src/spirv/serialize/tests.rs b/crates/metal2vulkan/src/spirv/serialize/tests.rs index a7efdf6cf..9cda125e0 100644 --- a/crates/metal2vulkan/src/spirv/serialize/tests.rs +++ b/crates/metal2vulkan/src/spirv/serialize/tests.rs @@ -787,6 +787,53 @@ fn a_workgroup_size_composite_needs_positive_u32_parts_and_a_spec_part() { assert_spirv_valid(b.finalize().expect("finalize")); } +/// A `WorkgroupSize` part that is an `OpSpecConstantOp` is refused, whatever its operation, the +/// deep threadgroup's former parts among them (a select over products of the size constants): a +/// driver may size the workgroup from the parts as declared and read such a part as 1, while the +/// body computes with its value. Plain specialization constants on every axis, the deep form's +/// parts, pass `spirv-val`. +#[test] +fn a_workgroup_size_part_is_never_a_spec_constant_op() { + use crate::pipeline::sym::Axis; + use crate::spirv::error::ConstRule; + use crate::spirv::ir::SpecOp; + let mut b = ModuleBuilder::new(); + let u32_ = int(&mut b, 32, false); + let bool_ = b.ty(Type::Bool).expect("bool"); + let [sx, sy, sz] = [Axis::X, Axis::Y, Axis::Z].map(|a| { + b.spec(SpecKey::LocalSize(a), u32_, ConstBits(1)) + .expect("spec") + }); + let one_row = b + .spec(SpecKey::DeepThreadgroup, bool_, ConstBits(0)) + .expect("spec"); + let row = b.spec_op(SpecOp::IMul, u32_, &[sx, sy]).expect("row"); + let sn = b.spec_op(SpecOp::IMul, u32_, &[row, sz]).expect("sn"); + let one = scalar(&mut b, u32_, 1); + let x = (b.spec_op(SpecOp::Select, u32_, &[one_row, sn, sx])).expect("x"); + let y = (b.spec_op(SpecOp::Select, u32_, &[one_row, one, sy])).expect("y"); + let z = (b.spec_op(SpecOp::Select, u32_, &[one_row, one, sz])).expect("z"); + let op = Err(BuildError::Constant(ConstRule::WorkgroupSizeOp)); + assert_eq!(b.workgroup_size(x, y, z), op); + assert_eq!(b.workgroup_size(sn, one, one), op); + assert_eq!(b.workgroup_size(sx, sy, row), op); + let [wx, wy, wz] = [Axis::X, Axis::Y, Axis::Z].map(|a| { + b.spec(SpecKey::WorkgroupSize(a), u32_, ConstBits(1)) + .expect("spec") + }); + b.workgroup_size(wx, wy, wz).expect("the deep form's parts"); + let out = ssbo(&mut b, 0, u32_, 4); + let main = compute(&mut b, |f| { + let i = gid_x(f); + let dst = elem_ptr(f, out, i); + let v = cval(f, u32_, 7); + f.store(dst, v, MemAccess::default()).expect("store"); + }); + b.entry(ExecModel::GLCompute, main, Vec::new()) + .expect("entry"); + assert_spirv_valid(b.finalize().expect("finalize")); +} + /// The resources a module declares `NonWritable`, by binding symbol, in relocation order. fn non_writable_resources(r: &RelocatableModule) -> Vec { let decorate = (3 << 16) | crate::spv::Op::Decorate as u32; diff --git a/crates/metal2vulkan/src/tests/engine_identity.rs b/crates/metal2vulkan/src/tests/engine_identity.rs index fe29427ec..45b6cf71d 100644 --- a/crates/metal2vulkan/src/tests/engine_identity.rs +++ b/crates/metal2vulkan/src/tests/engine_identity.rs @@ -206,14 +206,9 @@ fn local_size(group: u32) -> BTreeMap { local_size3([group, 1, 1]) } -/// The spec map of a dispatch of threadgroups of size `l`. +/// The spec map of a dispatch of threadgroups of size `l`: every key the size decides. fn local_size3(l: [u32; 3]) -> BTreeMap { - BTreeMap::from([ - (SpecKey::LocalSize(Axis::X), u64::from(l[0])), - (SpecKey::LocalSize(Axis::Y), u64::from(l[1])), - (SpecKey::LocalSize(Axis::Z), u64::from(l[2])), - (SpecKey::FlatLocalSize, u64::from(l[0] * l[1] * l[2])), - ]) + BTreeMap::from(crate::pipeline::threadgroup_constants(l)) } fn slot(index: u32) -> SlotRef { @@ -438,11 +433,14 @@ fn workloads() -> Option> { } /// Whether `key` is one of a dispatch's own specialization constants: its local size, its -/// `MultiRegion` and its `DeepThreadgroup`. +/// `MultiRegion`, its `DeepThreadgroup` and its `WorkgroupSize`. fn dispatch_key(key: SpecKey) -> bool { matches!( key, - SpecKey::LocalSize(_) | SpecKey::MultiRegion | SpecKey::DeepThreadgroup + SpecKey::LocalSize(_) + | SpecKey::MultiRegion + | SpecKey::DeepThreadgroup + | SpecKey::WorkgroupSize(_) ) } @@ -2988,16 +2986,12 @@ declare void @air.wg.barrier(i32, i32)\n\n\ } /// The workgroup `module` declares under `spec`: its `WorkgroupSize` composite, each part a -/// constant, a specialization constant or an operation of them, at those values. +/// constant or a specialization constant (never an operation of them), at those values. fn workgroup_of(module: &TypedModule, spec: &BTreeMap) -> [u32; 3] { fn value(module: &TypedModule, spec: &BTreeMap, c: ConstId) -> u64 { match &module.consts().get(c).expect("a constant").kind { ConstKind::Plain(crate::spirv::ir::Constant::Scalar { bits, .. }) => bits.0, ConstKind::Spec { key, default } => spec.get(key).copied().unwrap_or(default.0), - ConstKind::SpecOp { op, operands } => { - let values: Vec = (operands.iter()).map(|&o| value(module, spec, o)).collect(); - op.eval(32, &values).expect("an operation of its arity") - } other => panic!("a workgroup size part {other:?}"), } } @@ -3016,7 +3010,9 @@ fn workgroup_of(module: &TypedModule, spec: &BTreeMap) -> [u32; 3] /// threadgroup's threads and its threads' positions, linear indices and threadgroup memory are /// Metal's: [`deep_kernel`] over two threadgroups of 1 by 1 by 320, 2 by 3 by 100 and 1 by 4 by 256 /// stores what Metal's do, and so does one of 4 by 4 by 4, at its own workgroup with the key unset. -/// The device reports Metal's 1,024 threads along every axis, on a profile of 64 along `z` too. +/// Its `WorkgroupSize` parts are the plain specialization constants `SpecKey::WorkgroupSize`, +/// which `threadgroup_constants` writes. The device reports Metal's 1,024 threads along every axis, on a +/// profile of 64 along `z` too. #[test] fn a_deep_threadgroup_runs_as_one_row_on_from_queries() { use crate::pipeline::DEEP_THREADGROUP; @@ -3034,6 +3030,24 @@ fn a_deep_threadgroup_runs_as_one_row_on_from_queries() { .map(|c| c.default) .collect(); assert_eq!(declared, [0], "{stem}"); + let size = module + .consts() + .workgroup_size_const() + .expect("a WorkgroupSize"); + let ConstKind::WorkgroupSize { parts } = module.consts().get(size).expect("it").kind else { + panic!("{stem}: not a WorkgroupSize"); + }; + let keys = parts.map( + |part| match module.consts().get(part).expect("a part").kind { + ConstKind::Spec { key, .. } => key, + ref other => panic!("{stem}: a WorkgroupSize part {other:?}"), + }, + ); + assert_eq!( + keys, + [Axis::X, Axis::Y, Axis::Z].map(SpecKey::WorkgroupSize), + "{stem}" + ); link_and_validate(&a, p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); for size in [[1, 1, 320], [2, 3, 100], [1, 4, 256], [4, 4, 4]] { let n = size.iter().product::(); diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index f6ab216ed..a791887e7 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2862,6 +2862,7 @@ fn metal2vulkan::pipeline::heap_unused_while_pending pub fn heap_unused_while_pe fn metal2vulkan::pipeline::nonuniform_region_bytes pub fn nonuniform_region_bytes(base: [u32; 3], threads: [u32; 3], l: [u32; 3]) -> Option<[u8; 32]> fn metal2vulkan::pipeline::own_kernel pub fn own_kernel(kernel: OwnKernel, profile: &DeviceProfile) -> Result, Error> fn metal2vulkan::pipeline::region_bytes pub fn region_bytes(base: [u32; 3], threads: [u32; 3], l: [u32; 3]) -> Option<[u8; 32]> +fn metal2vulkan::pipeline::threadgroup_constants pub fn threadgroup_constants(size: [u32; 3]) -> [(SpecKey, u64); 8] macro-decl metal2vulkan-air::ir::ArgIdx ir_id! ArgIdx macro-decl metal2vulkan-air::ir::BlockId id_type! BlockId macro-decl metal2vulkan-air::ir::BlockId ir_id! BlockId @@ -10074,6 +10075,7 @@ variant metal2vulkan::pipeline::SpecKey::TgLength TgLength(u32) variant metal2vulkan::pipeline::SpecKey::TgOffset TgOffset(u32) variant metal2vulkan::pipeline::SpecKey::TileGridWidth TileGridWidth variant metal2vulkan::pipeline::SpecKey::TileThreadgroupLength TileThreadgroupLength +variant metal2vulkan::pipeline::SpecKey::WorkgroupSize WorkgroupSize(Axis) variant metal2vulkan::pipeline::Stage::Fragment Fragment variant metal2vulkan::pipeline::Stage::Kernel Kernel variant metal2vulkan::pipeline::Stage::Mesh Mesh diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index d4425268e..81d95be2b 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -307,6 +307,7 @@ surface! { fn grid_tile; const GRID_TILE_THREADS; const DEEP_THREADGROUP; + fn threadgroup_constants; const COMPILED_STAGE_WEIGHT; fn own_kernel; struct ExecutionCounts E; diff --git a/docs/API.md b/docs/API.md index a1f020bc6..8aa58b44f 100644 --- a/docs/API.md +++ b/docs/API.md @@ -184,7 +184,10 @@ and so do the command line, the compile worker and every validation tool. It hol threadgroup's threads, `(sx·sy·sz, 1, 1)`, each thread's position its `LocalInvocationIndex` unflattened in Metal's order, so a threadgroup deeper than a device's `maxComputeWorkGroupSize[2]` runs; a runtime sets it for a region deeper than - `pipeline::DEEP_THREADGROUP` (64) alone, so every other pipeline specializes it away. `MetalDeviceProperties::max_threads_per_threadgroup` is + `pipeline::DEEP_THREADGROUP` (64) alone, so every other pipeline specializes it away. Such a + kernel's `WorkgroupSize` parts are the plain constants `SpecKey::WorkgroupSize`, one an axis: + the threadgroup, or one row of it where it is deep (section 3 names the call that gives them); + no module's `WorkgroupSize` part is an `OpSpecConstantOp`. `MetalDeviceProperties::max_threads_per_threadgroup` is the capped `maxComputeWorkGroupInvocations` on every axis. A texture slot's `gpuResourceID` is pushed as its `PushField::SlotGuestBase`, and its texture is the element at the ID's index of set 1's two fixed arrays, the same layout for every pipeline ([RESOURCE-ID.md](RESOURCE-ID.md)); it binds no @@ -442,7 +445,12 @@ A `ComputePipeline` is immutable plain data: Do not create the compute `VkPipeline` from `stage` alone: its specialization defaults are placeholders (a kernel's local size is 1). Create each pipeline with the values its dispatch gives the specialization constants' keys, and with the stage's `stage_flags` and -`required_subgroup_size`. A required subgroup size needs `subgroupSizeControl` and the stage in +`required_subgroup_size`. Every key a kernel's threadgroup size decides comes from one call, +`pipeline::threadgroup_constants(size)`: `SpecKey::LocalSize` on each axis, `FlatLocalSize`, +`DeepThreadgroup` and the `WorkgroupSize` parts on each axis. Write each of them the stage +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 one device pins only what that device can take; `DeviceProfile::check` tells whether another device can.