diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 57ace1ac2..349096b86 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2572,8 +2572,11 @@ while the driver's exit handler waited on a lock, with every runtime thread alre whole number of threadgroups, runs the variant at its own size, every region but a ragged grid's unflagged, so one `VkPipeline` of a size runs them all (`Metrics::partial_variant_whole_grids` counts the dispatches of whole threadgroups). A dispatch runs the plain module where the variant - is refused, or where the threadgroup is not whole SIMD groups of a kernel that runs only whole - ones (below). The translator gives a kernel no order of the + is refused, where its threadgroup memory, the lengths set with the variant's own, passes the + device's `maxComputeSharedMemorySize` once the variant's predicated walk adds its 4-byte vote + word (a barrier in a loop; the plain module holds none), or where the threadgroup is not whole + SIMD groups of a kernel that runs only whole ones (below); a ragged grid of such a kernel is + refused as `Limit::ThreadgroupMemory`. The translator gives a kernel no order of the accesses Apple's SIMD-group lockstep orders (docs/API.md, accepted differences), so only the kernel's own barriers, fences, atomics of threadgroup or SIMD-group scope, SIMD-group and quad functions, threadgroup memory and builtins of the partition observe it. diff --git a/crates/metal2vulkan-runtime/src/counters.rs b/crates/metal2vulkan-runtime/src/counters.rs index 3aa0a50bb..ac0c66506 100644 --- a/crates/metal2vulkan-runtime/src/counters.rs +++ b/crates/metal2vulkan-runtime/src/counters.rs @@ -2262,8 +2262,8 @@ pub struct Metrics { /// Dispatches of whole threadgroups, `dispatchThreads` of a whole grid, `dispatchThreadgroups` /// or `dispatchThreadgroupsWithIndirectBuffer`, that ran a kernel's partial-threadgroups /// variant: a kernel that observes its threadgroup partition runs every dispatch on that one - /// module where the variant takes the threadgroup. No Metal counterpart: Metal compiles one - /// function. + /// module where the variant takes the threadgroup and its threadgroup memory, a predicated + /// walk's vote word with it. No Metal counterpart: Metal compiles one function. pub partial_variant_whole_grids: u64, /// Functions the translator lowered, each a module of a pipeline content the device did not /// hold compiled: of a compute content, one for a kernel that does not observe its threadgroup diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 9e3702711..e59379c65 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -1047,7 +1047,8 @@ impl ComputeCommandEncoder { &Grid::Direct(direct) => Some(direct), Grid::Indirect(..) => None, }; - let (choice, module, kernel) = decide(inner, direct, size)?; + let memory = (&self.threadgroup_lengths[..], limits.max_shared_memory); + let (choice, module, kernel) = decide(inner, direct, size, memory)?; let Choice { local, nominal, @@ -1284,21 +1285,25 @@ pub(crate) fn size_checked(interface: &Interface, size: [u32; 3]) -> Result<(), } /// What a dispatch at threadgroup size `size`, direct over `direct` or indirect, of the content -/// `compiled` runs, decided once for the dispatch and for +/// `compiled` runs, with the encoder's threadgroup memory lengths `set` against the device's +/// `max` bytes, decided once for the dispatch and for /// [`ComputePipelineState::prepare_dispatch`]: [`choose`]'s choice, then its module, an /// observer's partial-threadgroups variant for a ragged grid, and the emulated variant for a /// threadgroup that is not whole groups of a module that runs only whole ones (the /// partial-threadgroups variant has none), each lowered with the state. An observer's dispatch of /// a whole grid, of threadgroups, or indirect, that its whole module would run runs on the /// partial-threadgroups variant instead, unflagged, where the variant is lowered and takes the -/// threadgroup: one module, and one `VkPipeline` a size, runs every dispatch of it. An indirect -/// dispatch states no grid in its region, so the variant runs it in the single-region form, every -/// invocation live, as the translator's dispatch regions say (`lower::dispatch`). -pub(crate) fn decide( - compiled: &Compiled, +/// threadgroup and its threadgroup memory (the lengths `set` with the variant's own, a predicated +/// walk's vote word included, within `max`): one module, and one `VkPipeline` a size, runs every +/// dispatch of it the variant takes. An indirect dispatch states no grid in its region, so the +/// variant runs it in the single-region form, every invocation live, as the translator's dispatch +/// regions say (`lower::dispatch`). +pub(crate) fn decide<'a>( + compiled: &'a Compiled, direct: Option, size: [u32; 3], -) -> Result<(Choice, Module, &Kernel), Error> { + (set, max): (&[(u32, u32)], u32), +) -> Result<(Choice, Module, &'a Kernel), Error> { let choice = choose(&compiled.form, direct, size); let partial_threadgroups = || { Error::Unsupported(Gap::PartialThreadgroups { @@ -1320,7 +1325,9 @@ pub(crate) fn decide( let observes = matches!(compiled.form, Form::Sized { .. }); if observes && choice.module == Module::Whole && short(&compiled.whole).is_none() { if let Ok(partial) = compiled.variant_kernel(Which::Partial, partial_threadgroups) { - if short(partial).is_none() { + if short(partial).is_none() + && threadgroup_memory(partial, set, choice.local, max).is_ok() + { let choice = Choice { module: Module::Partial, ..choice diff --git a/crates/metal2vulkan-runtime/src/pipeline.rs b/crates/metal2vulkan-runtime/src/pipeline.rs index 48b264368..1229a4158 100644 --- a/crates/metal2vulkan-runtime/src/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/pipeline.rs @@ -390,7 +390,8 @@ pub(crate) enum Form { Square, /// The kernel observes its partition: a dispatch runs at its own threadgroup size, every one, /// direct or indirect, on the partial-threadgroups variant, lowered with the state where the - /// content has a function to lower it from (`encoder::decide`). + /// content has a function to lower it from, wherever the variant takes the dispatch's + /// threadgroup and threadgroup memory (`encoder::decide`). Sized { partial: Option> }, } @@ -811,10 +812,11 @@ impl crate::Device { /// variant, whose 256-wide tile's `VkPipeline`, or an image-only kernel's 16x16 workgroups' /// one, is made here too, and one that does as its plain module and its partial-threadgroups /// variant, with the one `VkPipeline` its dispatches run, whole grids, ragged and indirect - /// ones, at the descriptor's `requiredThreadsPerThreadgroup` where it sets one, or else at - /// `[N, 1, 1]` where the state declares a bound of threads (the descriptor's - /// `maxTotalThreadsPerThreadgroup`, or the - /// kernel's `[[max_total_threads_per_threadgroup(n)]]`), `N` the state's + /// ones (the plain module's where the variant's threadgroup memory, a predicated walk's vote + /// word with it, is past the device's), at the descriptor's `requiredThreadsPerThreadgroup` + /// where it sets one, or else at `[N, 1, 1]` where the state declares a bound of threads (the + /// descriptor's `maxTotalThreadsPerThreadgroup`, or the kernel's + /// `[[max_total_threads_per_threadgroup(n)]]`), `N` the state's /// `maxTotalThreadsPerThreadgroup`, and the kernel takes no threadgroup memory length from /// the encoder. A kernel whose tier runs only whole SIMD groups has its /// emulated-SIMD-group variant lowered here too. The translator answers whether the kernel @@ -1057,10 +1059,11 @@ impl Compiled { // below its 1024; the device's own limit is no declared bound. The `VkPipeline` its // dispatches of that size run is made, where the module takes no threadgroup memory length // from the encoder: the partial-threadgroups variant's, which runs whole grids, ragged and - // indirect ones alike, or the whole module's where the content has no such variant. A make - // that fails here is made again by the dispatch that needs it, which reports its own error; - // a make refused for the stage bound refuses the state's, which the consumer's helper then - // fills. + // indirect ones alike, or the whole module's where the content has no such variant or the + // variant's threadgroup memory, a predicated walk's vote word with it, is past the + // device's (`encoder::decide`). A make that fails here is made again by the dispatch that + // needs it, which reports its own error; a make refused for the stage bound refuses the + // state's, which the consumer's helper then fills. let interface = &compiled.whole.interface; let declared = descriptor.max_total_threads_per_threadgroup.is_some() || interface.metal_max_total_threads < METAL_MAX_THREADS; @@ -1940,11 +1943,12 @@ impl Compiled { if size_checked(interface, size).is_err() || !interface.has_effects { return None; } - let (choice, module, kernel) = decide(self, dispatch.direct(size), size).ok()?; + let max = self.core.limits.max_shared_memory; + let (choice, module, kernel) = + decide(self, dispatch.direct(size), size, (set, max)).ok()?; if (choice.direct).is_some_and(|(_, groups, _)| groups.contains(&0)) { return None; } - let max = self.core.limits.max_shared_memory; let lengths = threadgroup_memory(kernel, set, choice.local, max).ok()?; Some((kernel, module, choice.local, lengths)) } diff --git a/crates/metal2vulkan-runtime/src/tests/translate.rs b/crates/metal2vulkan-runtime/src/tests/translate.rs index 83027eed2..78ca9f381 100644 --- a/crates/metal2vulkan-runtime/src/tests/translate.rs +++ b/crates/metal2vulkan-runtime/src/tests/translate.rs @@ -15,8 +15,10 @@ //! allocate the buffer. A kernel that reads the stage-in region stores the region each dispatch //! was encoded under, and is refused where the encoder set none. A read of a texture the kernel's function constants removed takes zero, //! and a read through a buffer argument bound to nothing reads the nil buffer's zeros. -//! Threadgroup memory, a declared array's and a threadgroup argument's, reads zero until the -//! program writes it, in a dispatch's later threadgroups, in a second dispatch and on the +//! An observer whose partial-threadgroups variant's vote word takes its threadgroup memory past +//! the device's limit runs its whole grids, threadgroup dispatches and indirect ones on its plain +//! module. Threadgroup memory, a declared array's and a threadgroup argument's, reads zero until +//! the program writes it, in a dispatch's later threadgroups, in a second dispatch and on the //! emulated-SIMD-group module alike. Every module is lowered with the state, the variants //! included, so no dispatch makes a translation; an observing kernel's state made at its //! descriptor's `requiredThreadsPerThreadgroup` makes the pipelines its grids run at that size. A @@ -3535,6 +3537,251 @@ declare void @air.wg.barrier(i32, i32) }); } + /// A kernel of 64 threads that observes its threadgroups through two barriers in a loop of four + /// iterations over 64 words of threadgroup memory: each iteration, thread `t` stores its value + /// at word `t`, and past a barrier takes three times word `(t + 1) % 64` plus the iteration's + /// index as its next value, before another barrier; it writes its last to `out[g]`, `g` its + /// position in the grid. Its partial-threadgroups variant's predicated walk votes in the loop, + /// so the variant takes a 4-byte vote word of threadgroup memory the plain module does not. + /// `$NAME` and its region are filled by [`vote_kernel`]. + const VOTE_WORD: &str = 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" +$GLOBAL +define void @$NAME($PARAMSptr addrspace(1) %out, i32 %t, i32 %g) { +entry: + %pa = getelementptr inbounds i32, ptr addrspace(3) $BASE, i32 %t + %t1 = add i32 %t, 1 + %nb = and i32 %t1, 63 + %pn = getelementptr inbounds i32, ptr addrspace(3) $BASE, i32 %nb + br label %loop + +loop: + %i = phi i32 [ 0, %entry ], [ %i2, %loop ] + %acc = phi i32 [ %t, %entry ], [ %acc2, %loop ] + store i32 %acc, ptr addrspace(3) %pa, align 4 + tail call void @air.wg.barrier(i32 2, i32 1) + %x = load i32, ptr addrspace(3) %pn, align 4 + tail call void @air.wg.barrier(i32 2, i32 1) + %x3 = mul i32 %x, 3 + %acc2 = add i32 %x3, %i + %i2 = add i32 %i, 1 + %more = icmp ult i32 %i2, 4 + br i1 %more, label %loop, label %done + +done: + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %g + store i32 %acc2, ptr addrspace(1) %o, align 4 + ret void +} + +declare void @air.wg.barrier(i32, i32) + +!air.kernel = !{!0} +!air.version = !{!7} +!air.language_version = !{!8} +!0 = !{ptr @$NAME, !1, !2} +!1 = !{} +!2 = !{$REGION!4, !5, !6} +$REGION_META!4 = !{i32 $OUT, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!5 = !{i32 $T, !"air.thread_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"} +!6 = !{i32 $G, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"g"} +!7 = !{i32 2, i32 8, i32 0} +!8 = !{!"Metal", i32 4, i32 0, i32 0} +"#; + + /// [`VOTE_WORD`] as `vote_static`, over a declared array of `words` words, or with `None` as + /// `vote_length`, over its `[[threadgroup(0)]]` region, whose length the encoder sets. + fn vote_kernel(words: Option) -> String { + let region = r#"!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 3, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"a"} +"#; + let (name, global, params, base, meta) = match words { + Some(words) => ( + "vote_static", + format!("@tg = internal addrspace(3) global [{words} x i32] undef, align 4\n"), + "", + "@tg", + "", + ), + None => ( + "vote_length", + String::new(), + "ptr addrspace(3) %a, ", + "%a", + region, + ), + }; + let first = u32::from(words.is_none()); + VOTE_WORD + .replace("$NAME", name) + .replace("$GLOBAL", &global) + .replace("$PARAMS", params) + .replace("$BASE", base) + .replace("$REGION_META", meta) + .replace("$REGION", if words.is_some() { "" } else { "!3, " }) + .replace("$OUT", &first.to_string()) + .replace("$T", &(first + 1).to_string()) + .replace("$G", &(first + 2).to_string()) + } + + /// The word [`VOTE_WORD`] writes for each thread of a threadgroup, by its index. + fn vote_answers() -> Vec { + let mut values: Vec = (0..64).collect(); + for i in 0..4 { + values = (0..64) + .map(|t| values[(t + 1) % 64].wrapping_mul(3).wrapping_add(i)) + .collect(); + } + values + } + + /// Two observers whose threadgroup memory is within the device's `maxComputeSharedMemorySize` + /// on their plain module and past it by the 4-byte vote word on their partial-threadgroups + /// variant ([`VOTE_WORD`]): `vote_static`, whose declared array of the limit's bytes less 12 + /// Metal reports as the limit to the byte (`staticThreadgroupMemoryLength` rounds up to 16), and + /// `vote_length`, whose region the encoder sets at the limit. Each one's whole grid, + /// threadgroup dispatch and indirect dispatch run on its plain module, as no dispatch of the + /// variant can, uncounted in `Metrics::partial_variant_whole_grids`, and answer the program's + /// words; its ragged grid, which only the variant runs, is refused + /// (`Limit::ThreadgroupMemory`). `vote_static`'s state at `requiredThreadsPerThreadgroup` 64 + /// makes the plain module's pipeline with the state, which its three dispatches run, making + /// nothing and waiting for nothing. + #[test] + fn every_device_runs_an_observer_on_its_plain_module_where_the_vote_word_passes_the_limit() { + use crate::pipeline::Which; + + each_device("compute_vote_word_at_the_limit", |name, _, device| { + let limit = device.core().limits.max_shared_memory; + let answers = vote_answers(); + let want: Vec = (0..256).map(|g| answers[g % 64]).collect(); + for (declared, length) in [(Some(limit / 4 - 3), None), (None, Some(limit))] { + let bitcode = + match metal2vulkan_devtools::llvm_assemble_text(&vote_kernel(declared)) { + Ok(bitcode) => bitcode, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(error) => panic!("vote_word: {error:?}"), + }; + let kernel = match declared { + Some(_) => "vote_static", + None => "vote_length", + }; + let library = Library::from_air(&bitcode).expect("the library"); + let function = library.function(kernel).expect("the kernel"); + let mut descriptor = ComputePipelineDescriptor::new(StageSource::Function( + FunctionDescriptor::new(function), + )); + if declared.is_some() { + descriptor.required_threads_per_threadgroup = Some([64, 1, 1]); + } + let before = device.counters().metrics(); + let state = state(name, &device, &descriptor); + let made = device.counters().metrics(); + let compiled = &state.inner.compiled; + let partial = (compiled.variant_kernel(Which::Partial, || { + panic!("{name}: {kernel}: the partial-threadgroups variant is refused") + })) + .unwrap_or_else(|error| panic!("{name}: {kernel}: {error}")); + assert_eq!( + ( + compiled.whole.interface.memory.vote, + partial.interface.memory.vote, + ), + (0, 4), + "{name}: {kernel}: the vote word, the variant's alone" + ); + assert_eq!( + state.static_threadgroup_memory_length(), + if declared.is_some() { limit } else { 0 }, + "{name}: {kernel}" + ); + if declared.is_some() { + assert_eq!( + made.pipelines_created - before.pipelines_created, + 1, + "{name}: {kernel}: the plain module's pipeline, made with the state" + ); + } + let queue = device.new_command_queue(4).expect("a queue"); + let mut buffers = Buffers::new(&device, 1 << 16); + let arguments = buffers.buffer(16); + write(&arguments, 0, &le_bytes(&[4, 1, 1])); + for how in [How::Threads, How::Groups, How::Indirect] { + let out = buffers.buffer(4 * 256); + write(&out, 0, &le_bytes(&[0xEEEE_EEEE; 256])); + 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"); + if let Some(length) = length { + (encoder.set_threadgroup_memory_length(length, 0)).expect("a length"); + } + encoder.set_buffer(Some(&out), 0, 0).expect("a buffer"); + match how { + How::Threads => encoder.dispatch_threads([256, 1, 1], [64, 1, 1]), + How::Groups => encoder.dispatch_threadgroups([4, 1, 1], [64, 1, 1]), + How::Indirect => encoder.dispatch_threadgroups_with_indirect_buffer( + &arguments, + 0, + [64, 1, 1], + ), + } + .unwrap_or_else(|error| panic!("{name}: {kernel}: {how:?}: {error}")); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}: {kernel}: {how:?}"); + assert_eq!(words(&out, 0, 256), want, "{name}: {kernel}: {how:?}"); + } + let after = device.counters().metrics(); + assert_eq!( + after.partial_variant_whole_grids - made.partial_variant_whole_grids, + 0, + "{name}: {kernel}: whole threadgroups, direct and indirect, on the plain module" + ); + if declared.is_some() { + assert_eq!( + ( + after.pipelines_created - made.pipelines_created, + after.first_use_waits - made.first_use_waits, + ), + (0, 0), + "{name}: {kernel}: the dispatches made nothing and waited for nothing" + ); + } + 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"); + if let Some(length) = length { + (encoder.set_threadgroup_memory_length(length, 0)).expect("a length"); + } + let out = buffers.buffer(4 * 256); + encoder.set_buffer(Some(&out), 0, 0).expect("a buffer"); + match encoder.dispatch_threads([200, 1, 1], [64, 1, 1]) { + Err(Error::Limit(Limit::ThreadgroupMemory { length, max })) => { + assert_eq!( + (length, max), + (u64::from(limit) + 4, limit), + "{name}: {kernel}" + ) + } + answer => panic!("{name}: {kernel}: a ragged grid: {answer:?}"), + } + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + println!( + "{name}: {kernel}: at the limit of {limit} bytes, a whole grid, threadgroups \ + and an indirect dispatch ran on the plain module; a ragged grid refused" + ); + } + }); + } + /// A kernel that reads, through the argument buffer at buffer 0 (one `texture2d` /// member, its 8-byte resource ID), the texture's width, height and texel `(0, 0)`'s red bits /// into words 0 to 2 of `out` (buffer 1). diff --git a/docs/API.md b/docs/API.md index 3f36366af..9403d2d6a 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1442,7 +1442,8 @@ all of a kernel's direct dispatches. The runtime lowers a kernel that does not o partition once, as that variant, and runs every direct dispatch of it in its tiles; a kernel that observes its partition runs every dispatch, a whole grid, threadgroups, an indirect dispatch or a `dispatchThreads` grid that is not a whole number of threadgroups, on its partial-threadgroups -variant at its own threadgroup size; an indirect dispatch states no grid in its region and takes +variant at its own threadgroup size, where the variant takes the dispatch's threadgroup memory +(the variant's predicated walk may add a vote word); an indirect dispatch states no grid in its region and takes the single-region form, unflagged. A kernel that steps a stage-in attribute by thread position, or reads `[[grid_origin]]` or `[[grid_size]]`, needs the encoder's stage-in region: