From 50c5bd0fe16cd330e72e6c1576f824f7fdd34efc Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 17 Nov 2026 08:26:40 -0800 Subject: [PATCH] identity: every dispatch reads Metal's grid from its pushed region Under the identity domains a kernel that reads a grid builtin no longer declares the MultiRegion specialization constant. It tells a region from an indirect dispatch by the region's grid (RegionSelect::Grid in lower::dispatch): - Every dispatch the host knows (dispatchThreads, dispatchThreadgroups, and each piece of a split of either) pushes DispatchRegion with Metal's threads_per_grid in region[1].xyz and its piece's first threadgroup in region[0].xyz. So the pieces of a split read Metal's whole grid, and every compute pipeline takes the base offset. - An indirect dispatch pushes a zero grid. Its kernel then takes the single-region form, its grid NumWorkgroups times L, which needs its workgroup size to be Metal's threadgroup size. - One pipeline runs every dispatch of a threadgroup size, with no constant to specialize. A flat variant (LoweringInputs::flat_grid), bound as any other kernel, reads its grid from the same pushed field rather than from a record at ReplayRegionAddress (plan_replay, EmitCx::push_field). The consumer runs non-observing kernels in a fixed shape with it, and invocations past the grid return before the body. A replay or folded variant keeps its record and stays refused under the identity domains. The runtime lane takes this ABI as agreed: the zero grid marks an indirect dispatch, which runs the per-size pipeline. SEMANTICS_VERSION 2148: modules under the identity domains change. Tests (src/tests/engine_identity.rs), on lavapipe and moltenvk-m3: - every_dispatch_reads_metals_grid_from_its_pushed_region. A generated kernel reads thread_position_in_grid, threads_per_grid and threadgroups_per_grid. It declares no MultiRegion constant and passes L3. On the CPU interpreter, with L = (4, 2, 1) over an 8x6 grid, it stores the same answer at every position in three forms: one whole dispatch, a split into two pieces at region base (0, 1, 0), and an indirect dispatch with a zero grid. - a_flat_variant_reads_its_grid_from_its_pushed_region. Its flat variant reads a 7x5 grid from the pushed region in three workgroups of 16. The 13 invocations past the grid store nothing. - The buffer-kernel test runs once, with its region pushed. Verified: - m3-max-41225 (msi, check commit 7fe9bc780c: this tree's metal2vulkan files, which equal those here on 1bb5fe5bf8): clippy -p metal2vulkan --all-targets --all-features, rustdoc -D warnings, and nextest -p metal2vulkan --all-features, exit 0 (every test passed; the count's log was lost to the scratch path two of the lane's jobs shared, since fixed). - m3-max-41226 (msi, 7fe9bc780c): clippy under --cfg m2v_gpu and --cfg m2v_cpu_icd. --- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/src/lower/access/mod.rs | 13 +- crates/metal2vulkan/src/lower/dispatch.rs | 85 +++++-- .../metal2vulkan/src/lower/dispatch/tests.rs | 1 + crates/metal2vulkan/src/lower/emit.rs | 6 +- .../metal2vulkan/src/pipeline/lower_inputs.rs | 4 +- crates/metal2vulkan/src/pipeline/sym.rs | 6 +- .../metal2vulkan/src/tests/engine_identity.rs | 226 +++++++++++++++--- docs/API.md | 7 +- 9 files changed, 297 insertions(+), 53 deletions(-) diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 9d6cd7cba..df99a56b1 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,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 = 2147; +pub const SEMANTICS_VERSION: u32 = 2148; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index 8a670563b..5dc73fcc5 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -1730,7 +1730,8 @@ fn unwritten_slots( /// barrier may follow. A folded variant reads its group counts and every grid builtin's region /// from the record a preprocess writes for its dispatch, whatever builtins it reads; its /// workgroups past Metal's last threadgroup return early as wholes, so it runs emulated -/// simdgroups too. +/// simdgroups too. Under the identity domains a flat variant bound as any other kernel reads its +/// pushed `DispatchRegion` instead of a record. fn plan_replay(cx: &mut SelectCx<'_>, sources: &[SlotRef]) -> Result<(), Error> { let p = cx.profile; if p.fields().buffer_access != BufferAccess::Addressed { @@ -1769,9 +1770,15 @@ fn plan_replay(cx: &mut SelectCx<'_>, sources: &[SlotRef]) -> Result<(), Error> if cx.inputs.flat_grid && cx.inputs.emulated_simdgroups { return Err(Unsupported::not_implemented(Feature::GpuEncodedIndirectCommands).into()); } - // A folded variant reads its group counts from the record whatever builtins it reads. - if cx.push.remove(&PushField::DispatchRegion) || cx.inputs.flat_grid || cx.inputs.folded_groups + if identity(p) && !cx.inputs.replay_bindings && !cx.inputs.folded_groups { + // Under the identity domains a flat variant bound as any other kernel reads its grid from + // its own `DispatchRegion`, which the consumer pushes with the dispatch. + cx.push.insert(PushField::DispatchRegion); + } else if cx.push.remove(&PushField::DispatchRegion) + || cx.inputs.flat_grid + || cx.inputs.folded_groups { + // A folded variant reads its group counts from the record whatever builtins it reads. cx.push.insert(PushField::ReplayRegionAddress); } if !cx.inputs.replay_bindings { diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs index bf19a2b2c..71b092563 100644 --- a/crates/metal2vulkan/src/lower/dispatch.rs +++ b/crates/metal2vulkan/src/lower/dispatch.rs @@ -65,6 +65,15 @@ //! as Metal's object grid is (measured: an indirect draw runs every threadgroup and reports the //! grid its wrapped threads fill); it is `NumWorkgroups` wherever no axis wraps. //! +//! Under the identity domains no kernel declares `MultiRegion` ([`DispatchPlan::region_by_grid`]): +//! the region's grid selects the form. A dispatch the host knows (`dispatchThreads`, +//! `dispatchThreadgroups`, and each piece of a split of either) states its region with Metal's +//! `threads_per_grid` in `region[1].xyz`, and its first threadgroup in `region[0].xyz`, so the +//! pieces of a split read Metal's whole grid; an indirect dispatch states `region[1].xyz = 0` and +//! takes the single-region form, its grid `NumWorkgroups · L`, which needs its workgroup size to be +//! Metal's threadgroup size. So one pipeline runs every dispatch of a threadgroup size. A flat +//! variant reads its grid from the same pushed field, not from a record. +//! //! **Partial object threadgroups** ([`DispatchPlan::partial_groups`]). Metal's `drawMeshThreads` //! with an object function launches the object threadgroups its threads fill, rounded up, the //! last along an axis running only the threads left, as `dispatchThreads` runs a kernel's @@ -399,6 +408,20 @@ pub struct PlannedParam { pub projection: Projection, } +/// How a kernel that reads a grid builtin tells a region of a dispatch the host knows +/// (`dispatchThreads`, `dispatchThreadgroups`, or a split of either, whose region the +/// `DispatchRegion` push field states) from a whole dispatch whose grid the GPU holds (an +/// indirect one, whose grid is `NumWorkgroups · L`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RegionSelect { + /// The `MultiRegion` specialization constant. + Spec(ConstId), + /// Under the identity domains, the region's grid: `region[1].xyz` is Metal's + /// `threads_per_grid` for every dispatch the host knows, and all 0 for an indirect one. So one + /// pipeline runs both, with no constant to specialize. + Grid, +} + /// How a kernel's Vulkan workgroup size is expressed. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -457,6 +480,9 @@ pub struct DispatchPlan { /// threadgroup runs only the threads Metal's partial threadgroup has (the module docs). It /// declares `MultiRegion` and reads the region whatever builtins it reads. pub partial_groups: bool, + /// Under the identity domains a kernel tells a region from an indirect dispatch by the + /// region's grid, not by `MultiRegion`, which it does not declare ([`RegionSelect::Grid`]). + pub region_by_grid: bool, } /// The words a flat grid adds: its thread's index, position, and early return, derived once for the @@ -643,6 +669,7 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result, + /// How the kernel tells a region, when it reads a grid builtin. + multi_region: Option, local_id: Option, local_index: Option, workgroup_id: Option, @@ -1060,15 +1087,17 @@ impl KernelDecl { mb.workgroup_size(sn, one, one)?; } } - let multi_region = if dp.multi_region { - let b = mb.ty(Type::Bool)?; - Some(mb.spec( - keys.multi_region, - b, - ConstBits(u64::from(defaults.multi_region)), - )?) - } else { - None + let multi_region = match (dp.multi_region, dp.region_by_grid) { + (false, _) => None, + (true, true) => Some(RegionSelect::Grid), + (true, false) => { + let b = mb.ty(Type::Bool)?; + Some(RegionSelect::Spec(mb.spec( + keys.multi_region, + b, + ConstBits(u64::from(defaults.multi_region)), + )?)) + } }; let needs = Needs::of(dp); let flat = dp.local_size == LocalSizeForm::Flat; @@ -1312,10 +1341,10 @@ impl KernelDecl { fb: &mut FunctionBuilder<'_>, region: &mut RegionFn<'_>, ) -> BResult> { - let (true, Some(mr)) = (self.partial_groups, self.multi_region) else { + let (true, Some(sel)) = (self.partial_groups, self.multi_region) else { return Ok(None); }; - let mr = fb.module().const_value(mr)?; + let mr = self.selected(fb, sel, region)?; let r = region(fb)?; let r1 = fb.composite_extract(r, &[1])?; let flags = fb.composite_extract(r1, &[3])?; @@ -1506,10 +1535,10 @@ impl KernelDecl { region: &mut RegionFn<'_>, ) -> BResult<(Option, SValue)> { let s = self.size3(fb)?; - let Some(mr) = self.multi_region else { + let Some(sel) = self.multi_region else { return Ok((None, s)); }; - let mr = fb.module().const_value(mr)?; + let mr = self.selected(fb, sel, region)?; let r = region(fb)?; let r0 = fb.composite_extract(r, &[0])?; let base = fb.vector_shuffle(r0, r0, &[0, 1, 2])?; @@ -1536,15 +1565,37 @@ impl KernelDecl { fb: &mut FunctionBuilder<'_>, region: &mut RegionFn<'_>, ) -> BResult> { - let Some(mr) = self.multi_region else { + let Some(sel) = self.multi_region else { return Ok(None); }; - let mr = fb.module().const_value(mr)?; + let mr = self.selected(fb, sel, region)?; let r = region(fb)?; let r1 = fb.composite_extract(r, &[1])?; Ok(Some((mr, fb.vector_shuffle(r1, r1, &[0, 1, 2])?))) } + /// Whether the dispatch is a region (a `bool`): `MultiRegion`, or under the identity domains + /// whether the region's grid `region[1].xyz` is not all 0. + fn selected( + &self, + fb: &mut FunctionBuilder<'_>, + sel: RegionSelect, + region: &mut RegionFn<'_>, + ) -> BResult { + match sel { + RegionSelect::Spec(mr) => fb.module().const_value(mr), + RegionSelect::Grid => { + let r = region(fb)?; + let r1 = fb.composite_extract(r, &[1])?; + let [x, y, z] = [0, 1, 2].map(|i| fb.composite_extract(r1, &[i])); + let xy = fb.binary(BinOp::BitwiseOr, x?, y?)?; + let any = fb.binary(BinOp::BitwiseOr, xy, z?)?; + let zero = Self::k(fb, 0)?; + fb.binary(BinOp::INotEqual, any, zero) + } + } + } + /// A flat grid's thread position in the grid (a `uvec3`) and whether the invocation is inside /// the grid: its index `((wz · ny + wy) · nx + wx) · N + LocalInvocationIndex` over the /// dispatch (`lin` for the call's threadgroups, [`Self::lin`]), with `N = sx·sy·sz`, counted diff --git a/crates/metal2vulkan/src/lower/dispatch/tests.rs b/crates/metal2vulkan/src/lower/dispatch/tests.rs index 018767a8c..790ab60e9 100644 --- a/crates/metal2vulkan/src/lower/dispatch/tests.rs +++ b/crates/metal2vulkan/src/lower/dispatch/tests.rs @@ -38,6 +38,7 @@ fn plan(form: LocalSizeForm, multi_region: bool) -> DispatchPlan { wrapper_groups: false, object_grid: false, partial_groups: false, + region_by_grid: false, } } diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index 2971f7376..ed38a54d6 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -470,7 +470,11 @@ impl<'a> EmitCx<'a> { PushField::SlotGuestBase(slot) if self.plan.families.access.replay => { return access::replay_guest_base(self, fb, slot) } - PushField::DispatchRegion if self.plan.families.access.replay || flat => { + // Under the identity domains a flat variant's region is pushed. + PushField::DispatchRegion + if self.plan.families.access.replay + || (flat && !self.plan.families.access.identity) => + { return access::replay_region(self, fb) } _ => {} diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index d5a166b9f..601c81808 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -258,7 +258,9 @@ pub struct LoweringInputs { /// [`call_threadgroups`](Self::call_threadgroups). Under /// `replay_bindings` the replay's preprocess writes the record per command /// (`ReplayVariant::flat`); otherwise the kernel binds as any other, and a preprocess writes - /// the record beside its dispatch's group counts. It needs device addresses, and refuses a + /// the record beside its dispatch's group counts. Under the identity domains a variant bound + /// as any other reads its grid from `PushField::DispatchRegion` instead, which the consumer + /// pushes with the dispatch. It needs device addresses, and refuses a /// stage-input region, a tile function and `emulated_simdgroups` /// (`Unsupported{GpuEncodedIndirectCommands, NotImplemented}`). #[cfg_attr(feature = "serde", serde(default))] diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index b887c0e66..315f5702e 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -1044,7 +1044,11 @@ pub enum PushField { /// amplification fields, so the vertex window holds it, as a recording writes it before its /// draws. RegionBox, - /// Region base and grid of a multi-region dispatch. + /// Region base and grid of a multi-region dispatch (`lower::dispatch`'s module docs). Under + /// the identity domains every dispatch the host knows is a region: its first threadgroup in + /// Metal's grid (0 unless the consumer splits the dispatch), Metal's threadgroup size, and + /// Metal's `threads_per_grid`; an indirect dispatch states a zero grid, and its kernel takes + /// `NumWorkgroups` times its workgroup size. A flat variant reads its grid here too. DispatchRegion, /// Device address (`u64`) of the region record a device-replay variant's dispatch reads its /// `DispatchRegion` value from: the replay's preprocess writes one record per replayed command diff --git a/crates/metal2vulkan/src/tests/engine_identity.rs b/crates/metal2vulkan/src/tests/engine_identity.rs index b3344ddbc..70c276fb1 100644 --- a/crates/metal2vulkan/src/tests/engine_identity.rs +++ b/crates/metal2vulkan/src/tests/engine_identity.rs @@ -9,6 +9,11 @@ //! (`ArgumentTableAddress`), the addresses that fit after it, and reads the rest from the block //! at their placed offsets, with no descriptor; it passes L3 and computes its answer on the CPU //! interpreter. +//! - A kernel that reads grid builtins (`grid`, generated) declares no `MultiRegion` constant and +//! reads Metal's grid from its pushed `DispatchRegion` on every dispatch: whole, split in two +//! pieces at a base, and indirect (a zero grid, its grid `NumWorkgroups · L`) store the same +//! answers. Its flat variant (`grid_flat`) reads its grid from the same pushed field, and its +//! invocations past the grid store nothing. //! - A kernel that reads a texture (`engine/a2_dynamic_texel_offset`) is still refused as //! `Unsupported{IdentityDomains}`, not implemented, where the default domains compile it. //! @@ -21,10 +26,12 @@ use crate::device::profile::{HandleDomain, PointerDomain}; use crate::device::DevicePolicy; use crate::error::{Error, Feature, Needs}; use crate::lower::dispatch::region_bytes; +use crate::lower::select::{LowerInputs, Plan}; use crate::pipeline::interface::PushLoc; use crate::pipeline::sym::{Axis, PushField, SlotClass, SlotRef, SpecKey, Stage}; use crate::pipeline::testing::{ - compile, compile_kept, engine_dir, link_and_validate, llvm_assemble, profile, AssembleError, + compile, compile_kept, compile_with, engine_dir, link_and_validate, llvm_assemble, profile, + typed_module_with, AssembleError, }; use crate::spirv::interp::{run, Buffer, Config, Resources}; @@ -75,11 +82,16 @@ fn assemble_text(name: &str, text: &str) -> Option> { /// The spec map of a dispatch of `group` threads a threadgroup, in one dimension. fn local_size(group: u32) -> BTreeMap { + local_size3([group, 1, 1]) +} + +/// The spec map of a dispatch of threadgroups of size `l`. +fn local_size3(l: [u32; 3]) -> BTreeMap { BTreeMap::from([ - (SpecKey::LocalSize(Axis::X), u64::from(group)), - (SpecKey::LocalSize(Axis::Y), 1), - (SpecKey::LocalSize(Axis::Z), 1), - (SpecKey::FlatLocalSize, u64::from(group)), + (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])), ]) } @@ -185,28 +197,23 @@ fn a_buffer_kernel_reads_each_slot_at_its_pushed_device_address() { expected.extend_from_slice(&want(i).to_le_bytes()); } expected.extend_from_slice(&[0; 4]); - // The region read (`MultiRegion` 1) and not (0) give the same grid. - for multi in [0, 1] { - let mut spec = local_size(GROUP); - spec.insert(SpecKey::MultiRegion, multi); - let res = Resources { - buffers: vec![ - buffer(at[0], &bits), - buffer(at[1], &halves), - buffer(at[2], &out), - ], - push: push.clone(), - spec, - }; - let cfg = Config { - workgroups: [GROUPS, 1, 1], - ..Config::default() - }; - let got = run(&module, &cfg, res).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(got.buffers[2], expected, "{stem} {multi}: out"); - assert_eq!(got.buffers[0], bits, "{stem} {multi}: bits"); - assert_eq!(got.buffers[1], halves, "{stem} {multi}: halves"); - } + let res = Resources { + buffers: vec![ + buffer(at[0], &bits), + buffer(at[1], &halves), + buffer(at[2], &out), + ], + push, + spec: local_size(GROUP), + }; + let cfg = Config { + workgroups: [GROUPS, 1, 1], + ..Config::default() + }; + let got = run(&module, &cfg, res).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_eq!(got.buffers[2], expected, "{stem}: out"); + assert_eq!(got.buffers[0], bits, "{stem}: bits"); + assert_eq!(got.buffers[1], halves, "{stem}: halves"); } } @@ -357,3 +364,168 @@ fn slot_addresses_past_the_window_are_read_from_the_pushed_parameter_block() { ); } } + +/// A kernel storing, at its position in the grid `y · grid.x + x`, the grid's threads along `x` and +/// `y` (bits 0-7, 8-15) and, with `groups`, its threadgroups along `x` and `y` (bits 16-23, 24-31). +fn grid_kernel(name: &str, groups: bool) -> String { + let (param, read, arg) = match groups { + true => ( + ", <3 x i32> noundef %3", + " %nx = extractelement <3 x i32> %3, i64 0\n %ny = extractelement <3 x i32> %3, i64 1\n %hx = shl i32 %nx, 16\n %hn = shl i32 %ny, 24\n %v1 = or i32 %v0, %hx\n %v = or i32 %v1, %hn\n", + ", !15", + ), + false => ("", " %v = or i32 %v0, 0\n", ""), + }; + format!( + "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\"\n\ +target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ +define void @{name}(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0, <3 x i32> noundef %1, <3 x i32> noundef %2{param}) {{\n\ +entry:\n\ + %tx = extractelement <3 x i32> %1, i64 0\n\ + %ty = extractelement <3 x i32> %1, i64 1\n\ + %gx = extractelement <3 x i32> %2, i64 0\n\ + %gy = extractelement <3 x i32> %2, i64 1\n\ + %row = mul i32 %ty, %gx\n\ + %idx = add i32 %row, %tx\n\ + %hy = shl i32 %gy, 8\n\ + %v0 = or i32 %gx, %hy\n\ +{read}\ + %i = zext i32 %idx to i64\n\ + %p = getelementptr inbounds i32, ptr addrspace(1) %0, i64 %i\n\ + store i32 %v, ptr addrspace(1) %p, align 4\n\ + ret void\n\ +}}\n\n\ +!air.kernel = !{{!9}}\n!air.version = !{{!17}}\n!air.language_version = !{{!18}}\n\ +!9 = !{{ptr @{name}, !10, !11}}\n!10 = !{{}}\n!11 = !{{!12, !13, !14{arg}}}\n\ +!12 = !{{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"out\"}}\n\ +!13 = !{{i32 1, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint3\", !\"air.arg_name\", !\"tid\"}}\n\ +!14 = !{{i32 2, !\"air.threads_per_grid\", !\"air.arg_type_name\", !\"uint3\", !\"air.arg_name\", !\"grid\"}}\n\ +!15 = !{{i32 3, !\"air.threadgroups_per_grid\", !\"air.arg_type_name\", !\"uint3\", !\"air.arg_name\", !\"groups\"}}\n\ +!17 = !{{i32 2, i32 8, i32 0}}\n!18 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n" + ) +} + +/// The push bytes of a [`grid_kernel`]: its output at `out` and the region `region`. +fn grid_push(plan: &Plan, out: u64, region: [u8; 32]) -> Vec { + let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; + for f in &plan.push.fields { + let PushLoc::Push { offset } = f.loc else { + panic!("{f:?} spilled"); + }; + let o = offset as usize; + match f.field { + PushField::SlotGuestBase(s) if s == slot(0) => { + push[o..o + 8].copy_from_slice(&out.to_le_bytes()) + } + PushField::DispatchRegion => push[o..o + 32].copy_from_slice(®ion), + _ => panic!("unexpected push field {f:?}"), + } + } + push +} + +/// The output's address in the grid tests. +const OUT: u64 = 0x6_0000_0000; + +/// A kernel's grid builtins read Metal's grid from the pushed region on every dispatch: whole, +/// split in two pieces, and indirect. +#[test] +fn every_dispatch_reads_metals_grid_from_its_pushed_region() { + let Some(bc) = assemble_text("grid", &grid_kernel("grid", true)) else { + return; + }; + const L: [u32; 3] = [4, 2, 1]; + const GRID: [u32; 3] = [8, 6, 1]; + const GROUPS: [u32; 3] = [2, 3, 1]; + let threads = (GRID[0] * GRID[1]) as usize; + let value = GRID[0] | GRID[1] << 8 | GROUPS[0] << 16 | GROUPS[1] << 24; + let want: Vec = (0..threads).flat_map(|_| value.to_le_bytes()).collect(); + // Each form's dispatches: (region base, region grid, workgroups). + type Dispatch = ([u32; 3], [u32; 3], [u32; 3]); + let forms: [(&str, &[Dispatch]); 3] = [ + ("whole", &[([0; 3], GRID, GROUPS)]), + ( + "split", + &[([0; 3], GRID, [2, 1, 1]), ([0, 1, 0], GRID, [2, 2, 1])], + ), + ("indirect", &[([0; 3], [0; 3], GROUPS)]), + ]; + for stem in PROFILES { + let p = profile(stem, identity()).unwrap_or_else(|e| panic!("{e}")); + let (a, plan, module) = + compile_kept(&bc, "grid", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert!( + a.interface + .spec + .iter() + .all(|c| c.key != SpecKey::MultiRegion), + "{stem}" + ); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); + for (what, dispatches) in forms { + let mut out = vec![0u8; 4 * threads]; + for &(base, grid, workgroups) in dispatches { + let region = region_bytes(base, grid, L).expect("packs"); + let res = Resources { + buffers: vec![Buffer { + slot: None, + address: Some(OUT), + bytes: out, + }], + push: grid_push(&plan, OUT, region), + spec: local_size3(L), + }; + let cfg = Config { + workgroups, + ..Config::default() + }; + let got = run(&module, &cfg, res).unwrap_or_else(|e| panic!("{stem} {what}: {e}")); + out = got.buffers.into_iter().next().expect("out"); + } + assert_eq!(out, want, "{stem} {what}"); + } + } +} + +/// A flat variant reads its grid from its pushed region: its invocations count the grid's threads +/// and those past its last store nothing. +#[test] +fn a_flat_variant_reads_its_grid_from_its_pushed_region() { + let Some(bc) = assemble_text("grid_flat", &grid_kernel("grid_flat", false)) else { + return; + }; + const N: u32 = 16; + const GRID: [u32; 3] = [7, 5, 1]; + let threads = (GRID[0] * GRID[1]) as usize; + // Three workgroups of 16: 48 invocations, 13 past the grid. + let slots = 3 * N as usize; + let value = GRID[0] | GRID[1] << 8; + let mut want: Vec = (0..threads).flat_map(|_| value.to_le_bytes()).collect(); + want.resize(4 * slots, 0); + let mut inputs = LowerInputs::new(); + inputs.flat_grid = true; + for stem in PROFILES { + let p = profile(stem, identity()).unwrap_or_else(|e| panic!("{e}")); + let a = + compile_with(&bc, "grid_flat", &p, &inputs).unwrap_or_else(|e| panic!("{stem}: {e}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); + let (plan, module) = typed_module_with(&bc, "grid_flat", &p, &inputs) + .unwrap_or_else(|e| panic!("{stem}: {e}")); + let region = region_bytes([0; 3], GRID, [N, 1, 1]).expect("packs"); + let res = Resources { + buffers: vec![Buffer { + slot: None, + address: Some(OUT), + bytes: vec![0; 4 * slots], + }], + push: grid_push(&plan, OUT, region), + spec: local_size(N), + }; + let cfg = Config { + workgroups: [3, 1, 1], + ..Config::default() + }; + let got = run(&module, &cfg, res).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_eq!(got.buffers[0], want, "{stem}"); + } +} diff --git a/docs/API.md b/docs/API.md index 66461ba75..a37b5e58e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -114,8 +114,11 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: pushed as `PushField::SlotGuestBase`, with no root table, no descriptor and no containment, as Metal contains no device-address access. Fields past the 128-byte push window go to a parameter block in memory, read at the device address `PushField::ArgumentTableAddress`, which - the window always holds. So far they lower a kernel that reaches memory only through its buffer - slots; any other function is refused as `Unsupported{IdentityDomains}`. + the window always holds. A kernel that reads a grid builtin reads `PushField::DispatchRegion` on + every dispatch, with no `MultiRegion` constant: a dispatch the host knows states Metal's grid + and its piece's first threadgroup there, and an indirect dispatch a zero grid, whose kernel + takes `NumWorkgroups` times its workgroup size. So far they lower a kernel that reaches memory + only through its buffer slots; any other function is refused as `Unsupported{IdentityDomains}`. - **The model's linear sample of planes read in place** (`YCbCrInPlacePolicy::Model`, the default; changes emitted code). On an integrated GPU or a CPU device a function that only samples, gathers or sizes a `YCBCR8_420_2P` or `YCBCR10_420_2P` texture reads its planes' codes