diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 8a0179f59..be8a39fc9 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -410,13 +410,19 @@ that touch blocks first. - Every kernel is lowered first as its partial-threadgroups variant. A kernel that does not observe its threadgroup partition (it holds no threadgroup memory, barrier, fence or atomic of threadgroup or SIMD-group scope, SIMD-group or quad function, and reads no builtin of the - partition; the translator decides from its AIR) keeps that module alone: every direct dispatch - runs in tiles of 256 threads, 256 by 1 for a grid 256 threads wide or wider and, for a narrower - one, as wide as the grid rounded down to a power of two, so at most nine `VkPipeline`s; the - 256-wide one is made with the state. An indirect dispatch runs at its own threadgroup size. A - kernel that observes its partition is lowered a second time, plainly: its whole grids, - `dispatch_threadgroups` and indirect dispatches run that module at their own size, and a - `dispatch_threads` grid that is not a whole number of threadgroups runs the variant. + partition; the translator decides from its AIR) keeps that module alone, which runs its grid in + tiles: every direct dispatch runs in workgroups of 256 threads on one `VkPipeline`, made with the + state, each workgroup one tile of the grid. The translator's `pipeline::grid_tile` picks the + tile from the grid's extents alone: power-of-two sides whose product is 256, launching the fewest + threads past the grid, then with the fewest tiles partly past it, then the shallowest, then + (where the grid has two rows or more) the height nearest 2, then the widest. Each region carries + the tile, and a thread's position is the tile's origin plus its index masked and shifted by the + tile's sides, with no division. Where the tile does not divide the grid, an invocation past the + grid returns before the kernel's body. An indirect + dispatch runs at its own threadgroup size. A kernel that observes its partition is lowered a + second time, plainly: its whole grids, `dispatch_threadgroups` and indirect dispatches run that + module at their own size, and a `dispatch_threads` grid that is not a whole number of + threadgroups runs the variant. - 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. diff --git a/crates/metal2vulkan-rt/src/encoder.rs b/crates/metal2vulkan-rt/src/encoder.rs index 8ff6766f6..b7fe1dbe9 100644 --- a/crates/metal2vulkan-rt/src/encoder.rs +++ b/crates/metal2vulkan-rt/src/encoder.rs @@ -6,7 +6,7 @@ use crate::counters::Metric; use crate::error::{Error, Gap, Limit, Refusal}; use crate::hazard::Access; use crate::pipeline::{ - tile, ComputePipelineState, FieldValue, Form, Interface, Kernel, Place, Variant, PUSH_BYTES, + ComputePipelineState, FieldValue, Form, Interface, Kernel, Place, Variant, PUSH_BYTES, }; use crate::record::Reach; use crate::ring::CHUNK; @@ -14,7 +14,7 @@ use crate::sampler::SamplerState; use crate::texture::Texture; use ash::vk; use metal2vulkan::metal::format::integer_channels_word; -use metal2vulkan::pipeline::{nonuniform_region_bytes, region_bytes}; +use metal2vulkan::pipeline::{grid_tile, nonuniform_region_bytes, region_bytes, GRID_TILE_THREADS}; use std::ops::BitOr; use std::sync::Arc; @@ -169,6 +169,8 @@ pub struct ComputeCommandEncoder { enum Module { /// The state's whole module. Whole, + /// The whole module of a kernel that runs its grid in tiles, at `MultiRegion` 1. + Tiles, /// An observing kernel's partial-threadgroups variant. Partial, /// The emulated-SIMD-group variant. @@ -556,25 +558,28 @@ impl ComputeCommandEncoder { max: limits.max_group_size, })); } - // What runs: the module, which of the state's it is, its workgroup size, and for a - // direct dispatch Metal's grid, the workgroups, and whether the last along some axis is - // partial. + // What runs: the module, which of the state's it is, its workgroup size, the threadgroup + // size its regions carry, and for a direct dispatch Metal's grid, the workgroups, and + // whether the last along some axis is partial. let partial_threadgroups = |threads| { Error::Unsupported(Gap::PartialThreadgroups { threads_per_grid: threads, threads_per_threadgroup: size, }) }; - let (kernel, module, local, direct) = match (&grid, &inner.form) { - (Grid::Indirect(..), _) => (&inner.whole, Module::Whole, size, None), + let (kernel, module, local, nominal, direct) = match (&grid, &inner.form) { + (Grid::Indirect(..), _) => (&inner.whole, Module::Whole, size, size, None), + // A kernel's grid tiles: workgroups of `GRID_TILE_THREADS`, each one tile of the + // grid, which its region carries as the threadgroup size. (&Grid::Direct { threads, .. }, Form::Tiled) => { - let local = tile(threads); - let ragged = (0..3).any(|axis| !threads[axis].is_multiple_of(local[axis])); - let groups = std::array::from_fn(|axis| threads[axis].div_ceil(local[axis])); + let tile = grid_tile(threads); + let ragged = (0..3).any(|axis| !threads[axis].is_multiple_of(tile[axis])); + let groups = std::array::from_fn(|axis| threads[axis].div_ceil(tile[axis])); ( &inner.whole, - Module::Whole, - local, + Module::Tiles, + [GRID_TILE_THREADS, 1, 1], + tile, Some((threads, groups, ragged)), ) } @@ -589,6 +594,7 @@ impl ComputeCommandEncoder { &inner.whole, Module::Whole, size, + size, Some((threads, groups, false)), ), ( @@ -603,6 +609,7 @@ impl ComputeCommandEncoder { &**kernel, Module::Partial, size, + size, Some((threads, groups, true)), ), None => return Err(partial_threadgroups(threads)), @@ -641,6 +648,7 @@ impl ComputeCommandEncoder { .iter() .map(|&index| self.threadgroup_length(index)) .collect(), + tiles: module == Module::Tiles, }; let length = kernel .interface @@ -693,8 +701,8 @@ impl ComputeCommandEncoder { self.wrote |= wrote; let region = |base, threads, ragged| { match ragged { - true => nonuniform_region_bytes(base, threads, local), - false => region_bytes(base, threads, local), + true => nonuniform_region_bytes(base, threads, nominal), + false => region_bytes(base, threads, nominal), } .ok_or(Error::Refused(Refusal::ThreadgroupSize { size, max })) }; diff --git a/crates/metal2vulkan-rt/src/pipeline.rs b/crates/metal2vulkan-rt/src/pipeline.rs index 9a859b855..fae4db35d 100644 --- a/crates/metal2vulkan-rt/src/pipeline.rs +++ b/crates/metal2vulkan-rt/src/pipeline.rs @@ -2,9 +2,11 @@ //! //! The translator lowers every kernel first as its partial-threadgroups variant, through one //! decode and specialization of its entry. A kernel that does not observe its threadgroup -//! partition keeps that module alone: every direct dispatch runs in tiles of 256 threads, one -//! `VkPipeline` per tile shape ([`tile`]), the 256-wide tile made with the state; an indirect -//! dispatch runs at its own threadgroup size. A kernel that observes its partition is lowered +//! partition keeps that module alone, which runs its grid in tiles (`RuntimeFact::GridTiles`): +//! every direct dispatch runs in workgroups of 256 threads, each one tile of the grid whose sides +//! the translator's rule picks from the grid's extents (`grid_tile`) and its region carries, on +//! one `VkPipeline` made with the state; an indirect dispatch runs at its own threadgroup size. A +//! kernel that observes its partition is lowered //! once more, plainly: its whole grids, threadgroup dispatches and indirect dispatches run that //! module at their own threadgroup size, and a `dispatchThreads` grid that is not a whole number //! of threadgroups runs the partial-threadgroups variant at its size, where the translator made @@ -41,6 +43,7 @@ use metal2vulkan::pipeline::{ ComputePipelineDescriptor, DescriptorSetLayout, FunctionDescriptor, LoweringInputs, NumberedSampler, PrecisionNote, PushField, PushLoc, RuntimeFact, SamplerRef, SlotClass, SlotInterface, SlotRef, SpecKey, Stage, StageEntries, StageSource, TextureAccess, + GRID_TILE_THREADS, }; use metal2vulkan::vk::SamplerDesc; use metal2vulkan::Budget; @@ -53,23 +56,6 @@ use std::sync::{Arc, Mutex, OnceLock}; /// parameter ring, whose address is a field in the window. pub(crate) const PUSH_BYTES: u32 = crate::floor::PUSH_CONSTANT_BYTES; -/// The threads of a tile: a kernel that does not observe its threadgroup partition runs every -/// direct dispatch in tiles of this many threads. -pub(crate) const TILE_THREADS: u32 = 256; - -/// The tile a direct dispatch of a kernel that does not observe its threadgroup partition runs -/// over a grid of `threads`: 256 by 1 for a grid 256 threads wide or wider, and for a narrower -/// one the 256-thread tile whose width is the grid's width rounded down to a power of two, so at -/// most nine shapes per kernel. -pub(crate) fn tile(threads: [u32; 3]) -> [u32; 3] { - let width = match threads[0] { - 0 => TILE_THREADS, - wide if wide >= TILE_THREADS => TILE_THREADS, - narrow => 1 << narrow.ilog2(), - }; - [width, TILE_THREADS / width, 1] -} - /// `MTLComputePipelineState`. /// /// A cheap handle: clones share one state. A command buffer that dispatches with it keeps it until @@ -218,7 +204,9 @@ pub(crate) enum Lowered { /// How a state runs a direct dispatch. pub(crate) enum Form { /// The kernel does not observe its threadgroup partition: `whole`, its partial-threadgroups - /// variant, runs every direct dispatch in [`tile`]s, whatever the threadgroup size. + /// variant, runs its grid in tiles (`RuntimeFact::GridTiles`): every direct dispatch in + /// workgroups of `GRID_TILE_THREADS`, each a `grid_tile` tile of its grid, whatever the + /// threadgroup size. Tiled, /// The kernel observes its partition: a dispatch runs at its own threadgroup size, and a /// `dispatchThreads` grid that is not a whole number of threadgroups on the @@ -332,6 +320,10 @@ pub(crate) enum Constant { /// The length of the threadgroup memory argument at this position of /// [`Interface::threadgroups`]. ThreadgroupLength(usize), + /// `MultiRegion`: 1 for a kernel's grid tiles ([`Variant::tiles`]), whose regions carry the + /// 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, } /// A parameter and where it goes. @@ -373,12 +365,14 @@ pub(crate) enum FieldValue { DispatchRegion, } -/// A `VkPipeline`'s specialization: the threadgroup size and the threadgroup memory lengths in the -/// order of [`Interface::threadgroups`]. +/// A `VkPipeline`'s specialization: the threadgroup size, the threadgroup memory lengths in the +/// order of [`Interface::threadgroups`], and whether it runs a kernel's grid tiles. #[derive(Clone, PartialEq, Eq)] pub(crate) struct Variant { pub(crate) size: [u32; 3], pub(crate) threadgroup_lengths: Vec, + /// The launches are a kernel's grid tiles (`MultiRegion` 1). + pub(crate) tiles: bool, } impl crate::Device { @@ -465,12 +459,11 @@ impl crate::Device { } }; match variant { - Some(variant) if !variant.observes_threadgroup_partition() => ( - compiled(variant).map_err(Error::Translation)?, - None, - false, - Some(source), - ), + Some(variant) if !variant.observes_threadgroup_partition() => { + let pipeline = compiled(variant).map_err(Error::Translation)?; + let observes = !grid_tiles(&pipeline); + (pipeline, None, observes, Some(source)) + } Some(variant) => { let plain = lower(&plain).and_then(compiled); let variant = compiled(variant); @@ -488,22 +481,14 @@ impl crate::Device { } } // A kernel the consumer compiled: the variant it was compiled under. - StageSource::Compiled(function) => { + StageSource::Compiled(_) => { let pipeline = translator .compile_compute_pipeline(descriptor, &budget) .map_err(Error::Translation)?; - let partial = pipeline - .dependencies - .iter() - .any(|dependency| dependency.fact == RuntimeFact::PartialThreadgroups); - // Only a non-observer's partial variant runs every dispatch in tiles. It has no + // Only a non-observer's partial variant runs its grid in tiles. It has no // emulated variant: the kernel keeps the variant it was compiled under. - ( - pipeline, - None, - !(partial && !function.observes_threadgroup_partition()), - None, - ) + let observes = !grid_tiles(&pipeline); + (pipeline, None, observes, None) } }; let required = descriptor.required_threads_per_threadgroup; @@ -543,8 +528,9 @@ impl crate::Device { } if let Form::Tiled = inner.form { let variant = Variant { - size: [TILE_THREADS, 1, 1], + size: [GRID_TILE_THREADS, 1, 1], threadgroup_lengths: vec![0; inner.whole.interface.threadgroups.len()], + tiles: true, }; let made = inner.whole.make(&inner.core, &variant)?; lock(&inner.whole.variants).push((variant, made)); @@ -565,6 +551,15 @@ impl crate::Device { } } +/// Whether `pipeline`'s module runs its grid in tiles (`RuntimeFact::GridTiles`): the +/// partial-threadgroups variant of a kernel that does not observe its threadgroup partition. +fn grid_tiles(pipeline: &ComputePipeline) -> bool { + pipeline + .dependencies + .iter() + .any(|dependency| dependency.fact == RuntimeFact::GridTiles) +} + /// The kernel `function` lowered under `inputs`: the lowering a device kept in the cache directory /// under its key, which covers everything that changes the output, or one made now and kept. fn lower( @@ -652,6 +647,7 @@ fn interface( | RuntimeFact::DispatchGrid | RuntimeFact::IndirectGroupCount | RuntimeFact::PartialThreadgroups + | RuntimeFact::GridTiles | RuntimeFact::DeviceAddresses { .. } => {} // What a variant could relieve, which the module runs without: a predicated walk // that unit axes would make less divergent, and lockstep barriers a one-row region @@ -794,9 +790,7 @@ fn interface( .position(|&argument| argument == index) .ok_or_else(gap)?, ), - // Left at its default, 0: every launch's region states the pipeline's own threadgroup - // size, so the kernel takes `L` from its workgroup size and reads no decode. - SpecKey::MultiRegion => continue, + SpecKey::MultiRegion => Constant::MultiRegion, _ => return Err(gap()), }; constants.push((constant.id, set)); @@ -1102,6 +1096,7 @@ impl Kernel { Constant::Size(axis) => variant.size[axis], Constant::Threads => variant.size.iter().product(), Constant::ThreadgroupLength(at) => variant.threadgroup_lengths[at], + Constant::MultiRegion => u32::from(variant.tiles), }) .flat_map(u32::to_ne_bytes) .collect(); diff --git a/crates/metal2vulkan-rt/src/tests/translate.rs b/crates/metal2vulkan-rt/src/tests/translate.rs index 81190c05c..0895a04bf 100644 --- a/crates/metal2vulkan-rt/src/tests/translate.rs +++ b/crates/metal2vulkan-rt/src/tests/translate.rs @@ -1,7 +1,7 @@ //! Translated kernels, under a device cfg on every device of the cfg's kind. A kernel that does not -//! observe its threadgroup partition runs every direct dispatch in tiles, the 256-wide one made -//! with its state, and an indirect dispatch at its own threadgroup size; a precise one answers the -//! same words in a tile as at the app's shape. A kernel that does observe it runs whole grids at +//! observe its threadgroup partition runs every direct dispatch in tiles of 256 threads on the one +//! `VkPipeline` made with its state, and an indirect dispatch at its own threadgroup size; a +//! precise one answers the same words in a tile as at the app's shape. A kernel that does observe it runs whole grids at //! their own size, a `dispatchThreads` grid that is not a whole number of threadgroups on its //! partial-threadgroups variant, and a threadgroup count past the device's limit split. Each //! answer is checked against the program's, and each `VkPipeline` made after creation is a @@ -241,10 +241,9 @@ mod on_device { } /// `a1_bool_from_float`, which does not observe its threadgroup partition, translated: its - /// state made the 256-wide tile, which a wide `dispatchThreads` grid runs without a wait; a - /// narrow threadgroup dispatch runs a narrower tile and an indirect dispatch the app's own - /// size, each made by a first-use wait. Every answer is the program's, over buffers bound at - /// offsets. + /// state made the `VkPipeline` of its tiles, which a wide `dispatchThreads` grid and a narrow + /// threadgroup dispatch both run without a wait; an indirect dispatch runs the app's own size, + /// made by a first-use wait. Every answer is the program's, over buffers bound at offsets. #[test] fn every_device_tiles_a_kernel_that_does_not_observe_its_threadgroups() { let Some(descriptor) = descriptor("a1_bool_from_float") else { @@ -276,7 +275,7 @@ mod on_device { assert_eq!( created.pipelines_created - made.pipelines_created, 1, - "{name}: the 256-wide tile, made with the state" + "{name}: the tiles' pipeline, made with the state" ); assert_eq!(created.first_use_waits, made.first_use_waits, "{name}"); let queue = device.new_command_queue(4).expect("a queue"); @@ -327,7 +326,7 @@ mod on_device { let after = device.counters().metrics(); let waits = after.first_use_waits - created.first_use_waits; let nanos = after.first_use_wait_nanos - created.first_use_wait_nanos; - assert_eq!(waits, 2, "{name}: first-use waits"); + assert_eq!(waits, 1, "{name}: first-use waits"); assert!(nanos > 0, "{name}: first-use wait time"); assert!( after.first_use_wait_max_nanos >= nanos / 2, @@ -335,7 +334,7 @@ mod on_device { ); assert_eq!( after.pipelines_created - created.pipelines_created, - 2, + 1, "{name}: pipelines" ); println!( diff --git a/crates/metal2vulkan/src/bind/dispatch.rs b/crates/metal2vulkan/src/bind/dispatch.rs index b8e1db2d3..4ad78d3d9 100644 --- a/crates/metal2vulkan/src/bind/dispatch.rs +++ b/crates/metal2vulkan/src/bind/dispatch.rs @@ -20,7 +20,12 @@ //! with `MultiRegion = 1` and their `DispatchRegion` flagged `lower::dispatch::NONUNIFORM`: the //! kernel's last threadgroup along an axis answers Metal's partial threadgroup, so no edge is //! planned and one `VkPipeline` of the dispatch's size runs every such grid. A grid of whole -//! threadgroups takes the same regions there, unflagged: every thread is live. +//! threadgroups takes the same regions there, unflagged: every thread is live. On the plan of a +//! kernel's grid tiles (`LocalRules::grid_tiles`), `Threads` and `Threadgroups` both run their +//! threads in [`grid_tile`]'s tiles, one workgroup of [`GRID_TILE_THREADS`] each, per +//! group-count chunk, with `MultiRegion = 1`, the tile as the nominal size, and the +//! `DispatchRegion` flagged where the tile does not divide the grid; `ThreadgroupRange` runs at +//! its own size with `MultiRegion = 0`, its base in the push field. //! - A count above `maxComputeWorkGroupCount` on an axis is split into chunks, each a region //! with `MultiRegion = 1` and its base in the push field. At most [`MAX_REGIONS`] regions are //! planned; more is `Unsupported{GroupCount}`. @@ -108,7 +113,9 @@ use crate::cache::{SpecializationKey, VariantKey}; use crate::device::requirements::VkLimit; use crate::error::{BindError, Capability, Feature, LowerFamily, Unsupported}; use crate::indirect_commands::BINDING_COUNT; -use crate::lower::dispatch::{nonuniform_region_bytes, pack_nominal, region_bytes}; +use crate::lower::dispatch::{ + grid_tile, nonuniform_region_bytes, pack_nominal, region_bytes, GRID_TILE_THREADS, +}; use crate::metal::vertex::vertex_bytes; use crate::metal::{StepFunction, VertexFormat}; use crate::pipeline::interface::{AccessSet, BufferForm, PushLoc}; @@ -785,6 +792,30 @@ pub(crate) fn regions( } } let empty = |v: [u32; 3]| v.contains(&0); + // A kernel's grid tiles run a direct dispatch's threads in [`grid_tile`]'s tiles, one + // workgroup of `GRID_TILE_THREADS` each, with the tile as the nominal size (`MultiRegion` 1); + // a dispatch of a range of threadgroups runs at its own size (`MultiRegion` 0), from each + // region's base. + let tiled = |threads: [u32; 3]| -> Result { + let tile = grid_tile(threads); + let local = [GRID_TILE_THREADS, 1, 1]; + let fit = fit(rules, std::iter::once(local))?; + let pieces = std::array::from_fn(|i| { + Pieces::chunks( + 0, + threads[i].div_ceil(tile[i]), + local[i], + rules.max_count[i], + ) + }); + Ok(Planned { + emulated: fit == Fit::EmulatedSimdgroups, + regions: product(pieces, true)?, + grid: threads, + nominal: tile, + nonuniform: (0..3).any(|i| !threads[i].is_multiple_of(tile[i])), + }) + }; let planned = |regions: Regions, grid, emulated: bool| Planned { emulated: emulated && !regions.is_empty(), regions, @@ -799,6 +830,9 @@ pub(crate) fn regions( if empty(groups) { return Ok(planned(Regions::none(), grid, false)); } + if rules.grid_tiles { + return tiled(grid); + } let pieces = std::array::from_fn(|i| Pieces::chunks(0, groups[i], l[i], rules.max_count[i])); // A partial-threadgroups variant's regions read their region, as its `Threads` @@ -827,17 +861,21 @@ pub(crate) fn regions( let pieces = std::array::from_fn(|i| { Pieces::chunks(start[i], end[i] - start[i], l[i], rules.max_count[i]) }); - // Every region takes its first threadgroup from the push field. - Ok(planned( - product(pieces, true)?, - grid, - fit == Fit::EmulatedSimdgroups, - )) + // Every region takes its first threadgroup from the push field; a kernel's grid tiles + // read it at `MultiRegion` 0, where their threadgroup is the pipeline's. + let mut regions = product(pieces, true)?; + if rules.grid_tiles { + regions.multi = false; + } + Ok(planned(regions, grid, fit == Fit::EmulatedSimdgroups)) } Dispatch::Threads { threads, .. } => { if empty(threads) { return Ok(planned(Regions::none(), threads, false)); } + if rules.grid_tiles { + return tiled(threads); + } // A flat variant runs the whole grid in one region of the dispatch's own threadgroup // size: invocation `((wz · ny + wy) · nx + wx) · N + LocalInvocationIndex`, with // `N = l.x·l.y·l.z`, counts the grid's threads `x` fastest and takes the one it counts diff --git a/crates/metal2vulkan/src/bind/dispatch/tests.rs b/crates/metal2vulkan/src/bind/dispatch/tests.rs index 1243b1217..b3ec3c059 100644 --- a/crates/metal2vulkan/src/bind/dispatch/tests.rs +++ b/crates/metal2vulkan/src/bind/dispatch/tests.rs @@ -41,6 +41,7 @@ fn rules() -> LocalRules { unit_relief: 0, tile: false, tile_threadgroup: None, + grid_tiles: false, } } diff --git a/crates/metal2vulkan/src/bind/plan.rs b/crates/metal2vulkan/src/bind/plan.rs index 06adac2bf..e650b29ac 100644 --- a/crates/metal2vulkan/src/bind/plan.rs +++ b/crates/metal2vulkan/src/bind/plan.rs @@ -608,6 +608,10 @@ pub(crate) struct LocalRules { /// one deep. Every region of its dispatches carries it as the nominal threadgroup /// (`MultiRegion` 1) and the grid of its tiles, whatever threads per tile run. pub tile_threadgroup: Option<[u32; 3]>, + /// The kernel runs its grid in tiles (`RuntimeFact::GridTiles`): a direct dispatch's regions + /// are [`crate::pipeline::grid_tile`]'s tiles of its threads, one workgroup of + /// [`crate::pipeline::GRID_TILE_THREADS`] each. + pub grid_tiles: bool, } /// A region of `N` threads takes `fixed + ⌈N / 32⌉ · per_simdgroup` bytes of threadgroup memory, diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index cbe40c959..8d97a9d63 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -832,6 +832,10 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result Mechanism { RuntimeFact::RegionViewports => Mechanism::Variant, // A kernel compiled under the partial-threadgroups variant; its plans state it. RuntimeFact::PartialThreadgroups => Mechanism::Variant, + // The binder's regions carry the tile as the nominal size, under `MultiRegion` 1. + RuntimeFact::GridTiles => Mechanism::RegionSelected, // Keyed by the slots bound to a texture whose planes are read in place, on a profile that // reads them so (`ProfileFields::ycbcr_in_place`). RuntimeFact::YCbCrInPlace { .. } => Mechanism::Variant, diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index 52242f9de..7c1014d45 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -132,6 +132,12 @@ impl DeviceProfile { self.facts.identity_region } + /// How the partial-threadgroups variant of a kernel that does not observe its threadgroup + /// partition runs the threads past its grid. + pub(crate) fn oblivious_edge(&self) -> ObliviousEdge { + self.facts.oblivious_edge + } + /// The profile's fields: internal; the profile is opaque to consumers, who compare /// [`DeviceProfile::fingerprint`] and read its facts through the accessors. pub(crate) fn fields(&self) -> &ProfileFields { @@ -573,6 +579,9 @@ pub(crate) struct ProfileFacts { /// How a kernel under the identity domains reads its dispatch region's base and threadgroup /// size. pub(crate) identity_region: IdentityRegion, + /// How the partial-threadgroups variant of a kernel that does not observe its threadgroup + /// partition runs the threads past its grid. + pub(crate) oblivious_edge: ObliviousEdge, } impl ProfileFacts { @@ -586,6 +595,7 @@ impl ProfileFacts { push_window: PushWindow::Guaranteed, half_fma: HalfFma::Measured, identity_region: IdentityRegion::Grid, + oblivious_edge: ObliviousEdge::Partial, }; /// `Device::from_queries`': each fact the same on every device. @@ -598,6 +608,7 @@ impl ProfileFacts { push_window: PushWindow::Floor, half_fma: HalfFma::Native, identity_region: IdentityRegion::Sized, + oblivious_edge: ObliviousEdge::Grid, }; } @@ -641,6 +652,23 @@ pub(crate) enum IdentityRegion { Sized, } +/// How the partial-threadgroups variant (`LoweringInputs::partial_threadgroups`) of a kernel that +/// does not observe its threadgroup partition runs the threads a ragged grid's last threadgroups +/// leave over (`lower::dispatch`'s grid edge). Such a kernel reads only `thread_position_in_grid` +/// and `threads_per_grid`, so both forms run the same threads with the same answers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ObliviousEdge { + /// As any kernel's: where the region is flagged `NONUNIFORM`, the threadgroup runs Metal's + /// partial threadgroup, its position in the threadgroup `lin` divided over the threads left. + /// `Device::new`'s profile. + Partial, + /// Under the identity domains the variant runs its grid in tiles (`RuntimeFact::GridTiles`): + /// each workgroup one power-of-two tile of the grid that its region gives, its positions + /// masks and shifts of its local index, and an invocation past the grid returning before the + /// body. `Device::from_queries`' profile. + Grid, +} + /// Which `half` fused multiply-adds take the device's 16-bit `Fma` (`lower::arith::fma::half_route`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum HalfFma { diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 49a4d7b30..ec71c6ed6 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -168,6 +168,7 @@ fn every_fact() -> Vec { RuntimeFact::PrivateList, RuntimeFact::RegionViewports, RuntimeFact::PartialThreadgroups, + RuntimeFact::GridTiles, RuntimeFact::YCbCrInPlace { slot, samplers: 1, @@ -411,6 +412,7 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::TexelBufferParts { .. } => 102, RuntimeFact::OpenClLineTexture { .. } => 103, RuntimeFact::AddressAlignment { .. } => 104, + RuntimeFact::GridTiles => 105, } } @@ -418,7 +420,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..105).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..106).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -473,7 +475,8 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::RowLockstep => Mechanism::PlanTimeCheck, RuntimeFact::DispatchGrid | RuntimeFact::TileThreadgroup { .. } - | RuntimeFact::PartialObjectThreadgroups => Mechanism::RegionSelected, + | RuntimeFact::PartialObjectThreadgroups + | RuntimeFact::GridTiles => Mechanism::RegionSelected, RuntimeFact::IndirectGroupCount => { if f.limits.max_compute_work_group_count == [u32::MAX; 3] { Mechanism::None diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs index 61b4d214d..ea2acd467 100644 --- a/crates/metal2vulkan/src/lower/dispatch.rs +++ b/crates/metal2vulkan/src/lower/dispatch.rs @@ -113,6 +113,22 @@ //! variant's plan as the same regions unflagged: every invocation is live, and //! `threads_per_threadgroup` is the call's. //! +//! **Grid tiles** ([`DispatchPlan::grid_edge`], `RuntimeFact::GridTiles`). A kernel that does not +//! observe its threadgroup partition reads only `thread_position_in_grid` and `threads_per_grid`, +//! so neither Metal's threadgroups nor their partial edges reach it: only the set of positions +//! does. On `Device::from_queries`' profile under the identity domains (`ObliviousEdge::Grid`) +//! its partial-threadgroups variant runs its grid in tiles. Under `MultiRegion` 1 its workgroup of +//! [`GRID_TILE_THREADS`] is one tile, whose power-of-two sides the region's nominal size gives +//! ([`grid_tile`] picks them from the grid's extents): the invocation's position is the tile's +//! origin `(base + WorkgroupId) << s` plus `LocalInvocationIndex` masked and shifted by the sides, +//! `s` the bits of `L − 1` per axis, all of them uniform values, so nothing divides. Where the +//! region is flagged [`NONUNIFORM`] (the tile does not divide the grid) an invocation whose +//! position is past the region's grid on some axis returns before the body, behind a branch on +//! the flag, so a whole grid tests no lane. Under `MultiRegion` 0 (an indirect dispatch) it runs +//! at its pipeline's size, its position `(base + WorkgroupId) · (sx, sy, sz)` plus its position in +//! the workgroup, every invocation live. `Device::new`'s profile answers Metal's partial +//! threadgroup as above. +//! //! **Flat grids**. A flat variant (`LoweringInputs::flat_grid`, of a device replay or not) of a //! kernel that does not observe its threadgroup partition runs any grid in threadgroups of its own //! local size `N = sx·sy·sz`, dispatched `(nx, ny, nz)`: invocation `((wz · ny + wy) · nx + wx) · @@ -139,13 +155,13 @@ //! `ReplayRegionAddress` (base 0, `MultiRegion` 1). //! //! **Facts.** Every kernel depends on `ThreadsPerThreadgroup` and `LocalSizeLimits`, and on -//! `IndirectGroupCount` (any kernel may be dispatched indirectly, and the planner clamps GPU-written -//! counts); a flattened kernel on `LocalSizeConstraint{multiple}` (the tier's subgroup size); a -//! kernel reading grid builtins on `DispatchGrid`; a flat grid on `DispatchGrid` and `FlatGrid`; a -//! folded variant on `DispatchGrid` and `FoldedGroups`; a kernel's partial-threadgroups variant on -//! `DispatchGrid` and `PartialThreadgroups`. A threadgroup-memory length is a -//! `ThreadgroupMemoryLength{index}` specialization ([`threadgroup_length`]), which the arena -//! lowering declares through this module. +//! `IndirectGroupCount` (any kernel may be dispatched indirectly, and the planner clamps +//! GPU-written counts); a flattened kernel on `LocalSizeConstraint{multiple}` (the tier's subgroup +//! size); a kernel reading grid builtins on `DispatchGrid`; a flat grid on `DispatchGrid` and +//! `FlatGrid`; a folded variant on `DispatchGrid` and `FoldedGroups`; a kernel's +//! partial-threadgroups variant on `DispatchGrid` and `PartialThreadgroups`, and one that runs its +//! grid in tiles on `GridTiles`. A threadgroup-memory length is a `ThreadgroupMemoryLength{index}` +//! specialization ([`threadgroup_length`]), which the arena lowering declares through this module. //! //! Its hooks into `select` and `lower::emit`: the kernel's dispatch plan, made once the subgroup //! tier is known ([`plan_kernel`]); dispatch builtin parameters ([`select_param`], and @@ -154,7 +170,7 @@ use crate::air::abi::{Builtin, ParamBinding, ParamRole}; use crate::air::ir::{ArgIdx, Value}; -use crate::device::profile::IdentityRegion; +use crate::device::profile::{IdentityRegion, ObliviousEdge}; use crate::device::subgroup::{self, SimdClass, Tier}; use crate::error::{Error, Feature, LowerFamily, Unsupported}; use crate::lower::arith; @@ -171,6 +187,13 @@ use crate::spirv::ir::{ UnOp, }; +/// The builder's error for a value the declarations do not hold. +fn dangling_value() -> crate::spirv::error::BuildError { + crate::spirv::error::BuildError::Dangling(crate::spirv::error::Dangling::Value(SValue::new( + u32::MAX, + ))) +} + fn not_lowered() -> Error { Unsupported::not_implemented(Feature::Lowering(LowerFamily::Dispatch)).into() } @@ -493,6 +516,13 @@ 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, + /// Of `partial_groups`, a kernel that does not observe its threadgroup partition, on a profile + /// whose [`ObliviousEdge`] is `Grid` under the identity domains: under `MultiRegion` 1 its + /// workgroup is one tile of the grid whose power-of-two sides the region's nominal size gives + /// ([`grid_tile`]), and where the region is flagged [`NONUNIFORM`] an invocation past the + /// region's grid returns before the body; under `MultiRegion` 0 it runs at its pipeline's size + /// (the module docs' grid tiles). + pub grid_edge: bool, /// Under the identity domains a kernel tells a region from an indirect dispatch by the /// region's grid, and reads its base and `L` as the profile's form says /// ([`RegionSelect::Grid`], [`RegionSelect::Sized`]). `None` outside them. @@ -554,6 +584,20 @@ fn reads_region(b: KernelBuiltin, tile_sized: bool) -> bool { b.reads_grid() || (tile_sized && b.follows_tile()) } +/// Whether a kernel's partial-threadgroups variant runs its grid in tiles +/// ([`DispatchPlan::grid_edge`]): a kernel that does not observe its threadgroup partition +/// (`pipeline::compile::partition`, decided from its AIR) on a profile whose [`ObliviousEdge`] is +/// `Grid`, under the identity domains, whose regions state their base on every dispatch +/// ([`IdentityRegion::Sized`]). +fn grid_edge(cx: &SelectCx<'_>) -> bool { + use crate::pipeline::compile::partition::{partition, Partition}; + cx.stage == crate::pipeline::sym::Stage::Kernel + && cx.profile.oblivious_edge() == ObliviousEdge::Grid + && crate::lower::access::identity(cx.profile) + && cx.profile.identity_region() == IdentityRegion::Sized + && partition(cx.entry) == Partition::Oblivious +} + /// Plan the kernel's dispatch under subgroup tier `tier`: the local-size form (flattened in the /// Direct and Cluster32 tiers), the builtins it reads, and its facts. A kernel with compute /// derivatives is refused in the flattened tiers (`ComputeDerivativesWithSimd`): flattening @@ -668,6 +712,10 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result RuntimeFact::PartialObjectThreadgroups, }); } + let grid_edge = partial_groups && grid_edge(cx); + if grid_edge { + cx.facts.insert(RuntimeFact::GridTiles); + } Ok(DispatchPlan { local_size, builtins, @@ -683,6 +731,7 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result, fb: &mut FunctionBuilder<'_>) -> BResult< // A flat grid's invocation past the grid's last thread returns before the body. Its position // is derived here once, with the test, and is the `thread_position_in_grid` every parameter // reads: a second derivation would repeat the divisions in a construct of its own, which the - // driver does not merge with this one. - let mut flat_position = None; + // driver does not merge with this one. So is a grid edge's. + let mut tested_position = None; if plan.flat_grid { let decl: &crate::lower::emit::Declared = cx.decl; let Some(decl) = decl.families.dispatch.kernel.as_ref() else { @@ -723,7 +772,7 @@ pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult< }; let (pos, inside) = decl.flat(fb, &mut |fb| cx.push_field(fb, PushField::DispatchRegion))?; - flat_position = Some(pos); + tested_position = Some(pos); let past = fb.unary(UnOp::LogicalNot, inside)?; let leave: ArmFn<'_, ()> = Box::new(|fb, _| { fb.ret(None)?; @@ -747,14 +796,36 @@ pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult< }); fb.if_(&mut (), past, leave, None)?; } - // An invocation past a partial threadgroup's threads returns before the body, or, where the - // body is walked predicated for its barriers, walks it never live. + // An invocation past a partial threadgroup's threads, or past the grid on a grid edge, returns + // before the body, or, where the body is walked predicated for its barriers, walks it never + // live. if plan.partial_groups { let decl: &crate::lower::emit::Declared = cx.decl; let Some(decl) = decl.families.dispatch.kernel.as_ref() else { return Err(cx.fail("partial threadgroups without the kernel's declarations")); }; - if let Some(live) = decl.live(fb, &mut |fb| cx.push_field(fb, PushField::DispatchRegion))? { + let mut region = + |fb: &mut FunctionBuilder<'_>| cx.push_field(fb, PushField::DispatchRegion); + if plan.grid_edge { + // A grid tile's invocation past the grid returns where its region is flagged ragged + // (under `MultiRegion` 1): a test of uniform values first, so a tile inside the grid + // tests no lane. + let pos = decl.edge_position(fb, &mut region)?; + let (ragged, grid) = decl.edge_ragged(fb, &mut region)?; + tested_position = Some(pos); + let test: ArmFn<'_, ()> = Box::new(move |fb, _| { + let below = fb.binary(BinOp::ULessThan, pos, grid)?; + let inside = fb.unary(UnOp::All, below)?; + let past = fb.unary(UnOp::LogicalNot, inside)?; + let leave: ArmFn<'_, ()> = Box::new(|fb, _| { + fb.ret(None)?; + Ok(ArmEnd::Exits) + }); + fb.if_(&mut (), past, leave, None)?; + Ok(ArmEnd::FallThrough(Vec::new())) + }); + fb.if_(&mut (), ragged, test, None)?; + } else if let Some(live) = decl.live(fb, &mut region)? { let walked = cx .plan .families @@ -781,7 +852,7 @@ pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult< else { return Err(cx.fail(format!("dispatch parameter {} is out of range", p.param))); }; - let x = param_value(cx, fb, b, flat_position)?; + let x = param_value(cx, fb, b, tested_position)?; cx.hold(v, x); } Ok(()) @@ -793,7 +864,7 @@ fn param_value( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, b: &ParamBinding, - flat_position: Option, + tested_position: Option, ) -> BResult { let (plan, decl): (&Plan, &crate::lower::emit::Declared) = (cx.plan, cx.decl); let planned = plan @@ -809,8 +880,8 @@ fn param_value( if decl.flat_grid && !decl.flat_reads(p.builtin) { return Err(cx.fail(format!("parameter {} is not a flat grid's", b.param))); } - let raw = match (p.builtin, flat_position) { - (KernelBuiltin::ThreadPositionInGrid, Some(pos)) if decl.flat_grid => pos, + let raw = match (p.builtin, tested_position) { + (KernelBuiltin::ThreadPositionInGrid, Some(pos)) if decl.flat_grid || decl.grid_edge => pos, _ => decl.value(fb, p.builtin, &mut |fb| { cx.push_field(fb, PushField::DispatchRegion) })?, @@ -912,6 +983,9 @@ pub struct KernelDecl { object_grid: bool, /// A function whose threadgroup may be partial ([`DispatchPlan::partial_groups`]). partial_groups: bool, + /// Its threadgroups run whole, its invocations past the grid return + /// ([`DispatchPlan::grid_edge`]). + grid_edge: bool, } /// The threadgroup position and grid of a kernel whose entry wrapper computes them @@ -984,7 +1058,9 @@ impl Needs { }; } let has = |b| dp.builtins.contains(b); - let local_pos = has(K::ThreadPositionInThreadgroup) || has(K::ThreadPositionInGrid); + // A grid edge tests every invocation's position in the grid, whatever builtins it reads. + let local_pos = + has(K::ThreadPositionInThreadgroup) || has(K::ThreadPositionInGrid) || dp.grid_edge; // A partial object threadgroup counts its threads from its position and its own `lin`. let partial = dp.partial_groups; // A folded variant counts its threadgroup from its workgroup's position and the @@ -1035,6 +1111,74 @@ pub fn pack_nominal(l: [u32; 3]) -> Option { Some(out) } +/// The threads of a grid tile ([`grid_tile`]): the workgroup of a kernel's grid tiles +/// (`RuntimeFact::GridTiles`). +pub const GRID_TILE_THREADS: u32 = 256; + +/// 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 +/// in one total order: the fewest threads launched, `∏ ⌈threads_i / side_i⌉ · side_i`; then the +/// fewest tiles partly past the grid; then the shallowest (`z` side 1 first); then, where the grid +/// has two rows or more, the height nearest 2 (`|b - 1|` smallest); then the widest. A pure +/// function of the grid's extents. +/// +/// A side that divides its axis's extent launches nothing past it, so where the powers of two +/// that divide the extents reach 256 between them, the tile is the first of those that divide the +/// grid. A grid that one tile holds takes the first tile that holds it, each such tile being one +/// workgroup partly past the grid. Any other grid tries the 45 tiles in the order, passing over +/// the depths that cannot launch as few. A zero extent is divided by every power of two; such a +/// grid runs nothing. +pub fn grid_tile(threads: [u32; 3]) -> [u32; 3] { + const BITS: u32 = GRID_TILE_THREADS.trailing_zeros(); + let rows = threads[1] >= 2; + // The height nearest 2 of `lo..=hi` where the grid has rows, else the lowest (the widest). + let height = |lo: u32, hi: u32| if rows { 1.clamp(lo, hi) } else { lo }; + let [x, y, z] = threads.map(|n| n.trailing_zeros().min(BITS)); + if x + y + z >= BITS { + let c = BITS.saturating_sub(x + y); + let b = height(BITS - c - x.min(BITS - c), y.min(BITS - c)); + return [1 << (BITS - c - b), 1 << b, 1 << c]; + } + let [x, y, z] = threads.map(|n| u32::BITS - n.saturating_sub(1).leading_zeros()); + if x + y + z <= BITS { + let b = height(y, BITS - z - x); + return [1 << (BITS - z - b), 1 << b, 1 << z]; + } + // Every tile in the order: a later tile wins only by launching fewer threads, or as many with + // fewer tiles partly past the grid. The tiles `2^c` deep launch at least + // `⌈z / 2^c⌉ · ⌈x·y / 2^(8 - c)⌉` tiles, so a depth whose bound exceeds the fewest yet is + // passed over. + let counts = |n: u32, k: u32| (u64::from(n.div_ceil(1 << k)), u64::from(n >> k)); + let xy = u64::from(threads[0]) * u64::from(threads[1]); + let (mut best, mut fewest) = ([0; 3], (u128::MAX, u128::MAX)); + for c in 0..=BITS { + let (tz, wz) = counts(threads[2], c); + let rest = BITS - c; + if u128::from(tz) * u128::from(xy.div_ceil(1 << rest)) > fewest.0 { + continue; + } + // Heights 1, 0, 2, 3, ... where the grid has rows (nearest 2 first, the wider of two + // as near), else 0, 1, 2, ... (the widest first). + for step in 0..=rest { + let b = match step { + 0 | 1 if rows && rest > 0 => 1 - step, + _ => step, + }; + let ((tx, wx), (ty, wy)) = (counts(threads[0], rest - b), counts(threads[1], b)); + let tiles = u128::from(tx * ty) * u128::from(tz); + if tiles > fewest.0 { + continue; + } + let partly = tiles - u128::from(wx * wy) * u128::from(wz); + if (tiles, partly) < fewest { + (best, fewest) = ([rest - b, b, c], (tiles, partly)); + } + } + } + best.map(|k| 1 << k) +} + /// The `DispatchRegion` push field's bytes (two `uvec4`) for a region whose first threadgroup is /// `base`, of a Metal grid of `threads` threads with nominal threadgroup size `l`. pub fn region_bytes(base: [u32; 3], threads: [u32; 3], l: [u32; 3]) -> Option<[u8; 32]> { @@ -1123,8 +1267,9 @@ impl KernelDecl { // A flat grid counts its threads by `LocalInvocationIndex` in either form: it reads no // simdgroup. One of the call's threadgroups counts them by `lin`, its simdgroups' lanes. let by_index = dp.flat_grid && !dp.call_threadgroups; - let index = needs.lin && (!flat || by_index); - let subgroups = needs.lin && flat && !by_index; + // A grid tile counts by `LocalInvocationIndex` in either form too. + let index = needs.lin && (!flat || by_index || dp.grid_edge); + let subgroups = needs.lin && flat && !by_index && !dp.grid_edge; use crate::spv::BuiltIn as B; // A wrapper that computes the threadgroup's position and grid stores them into private // words, which the builtins read; it reads the dispatch's own. @@ -1177,6 +1322,7 @@ impl KernelDecl { wrapper, object_grid: dp.object_grid, partial_groups: dp.partial_groups, + grid_edge: dp.grid_edge, }) } @@ -1198,9 +1344,7 @@ impl KernelDecl { fn load(&self, fb: &mut FunctionBuilder<'_>, g: Option) -> BResult { let Some(g) = g else { - return Err(crate::spirv::error::BuildError::Dangling( - crate::spirv::error::Dangling::Value(SValue::new(u32::MAX)), - )); + return Err(dangling_value()); }; let p = fb.module().global_value(g)?; fb.load(p, MemAccess::default()) @@ -1283,8 +1427,12 @@ impl KernelDecl { fb.binary(BinOp::IAdd, q, extra) } - /// The linear local index `lin`. + /// The linear local index `lin`; a grid tile's is `LocalInvocationIndex` in either form (its + /// kernel reads no simdgroup). fn lin(&self, fb: &mut FunctionBuilder<'_>) -> BResult { + if self.grid_edge { + return self.load(fb, self.local_index); + } match self.form { LocalSizeForm::Spec => self.load(fb, self.local_index), LocalSizeForm::Flat => { @@ -1354,13 +1502,15 @@ impl KernelDecl { /// Whether the region says the draw's threadgroups may be partial ([`NONUNIFORM`] under /// `MultiRegion`), and the threads this threadgroup runs: `min(L, threads_per_grid − position · /// L)` per axis where it does (0 past the grid), `(sx, sy, sz)` where it does not. `None` but - /// for an object function of [`DispatchPlan::partial_groups`]. + /// for a function of [`DispatchPlan::partial_groups`] whose threadgroups run whole + /// ([`DispatchPlan::grid_edge`]). fn partial_threads( &self, fb: &mut FunctionBuilder<'_>, region: &mut RegionFn<'_>, ) -> BResult> { - let (true, Some(sel)) = (self.partial_groups, self.multi_region) else { + let (true, false, Some(sel)) = (self.partial_groups, self.grid_edge, self.multi_region) + else { return Ok(None); }; let mr = self.selected(fb, sel, region)?; @@ -1410,6 +1560,80 @@ impl KernelDecl { Ok(Some(fb.select(partial, below, yes)?)) } + /// Of [`DispatchPlan::grid_edge`], the invocation's position in the grid (a `uvec3`). Under + /// `MultiRegion` 1 its workgroup is one tile of the grid whose sides the region's nominal size + /// `L` gives, each a power of two whose product is the workgroup's threads: with `m = L − 1` + /// and `s` the bits set in `m` per axis, the position is `((base + WorkgroupId) << s) + (lin & + /// m.x, (lin >> s.x) & m.y, lin >> (s.x + s.y))`, masks and shifts by uniform values, where + /// `lin` is `LocalInvocationIndex`. Under `MultiRegion` 0 it is the uniform one at the + /// pipeline's size, `(base + WorkgroupId) · (sx, sy, sz)` plus the position in the workgroup, + /// which the driver keeps alone when it specializes either. + pub fn edge_position( + &self, + fb: &mut FunctionBuilder<'_>, + region: &mut RegionFn<'_>, + ) -> BResult { + let Some(RegionSelect::Sized(sized)) = self.multi_region else { + return Err(dangling_value()); + }; + let r = region(fb)?; + let r0 = fb.composite_extract(r, &[0])?; + let base = fb.vector_shuffle(r0, r0, &[0, 1, 2])?; + let packed = fb.composite_extract(r0, &[3])?; + let axis = Self::k(fb, (1 << NOMINAL_AXIS_BITS) - 1)?; + let mask_x = fb.binary(BinOp::BitwiseAnd, packed, axis)?; + let mut above = [mask_x; 2]; + for (i, mask) in (1..).zip(&mut above) { + let sh = Self::k(fb, NOMINAL_AXIS_BITS * i)?; + let bits = fb.binary(BinOp::ShiftRightLogical, packed, sh)?; + *mask = fb.binary(BinOp::BitwiseAnd, bits, axis)?; + } + let [mask_y, mask_z] = above; + let m = fb.composite_construct(self.uvec3, &[mask_x, mask_y, mask_z])?; + let s = fb.unary(UnOp::BitCount, m)?; + let sx = fb.composite_extract(s, &[0])?; + let sy = fb.composite_extract(s, &[1])?; + let lin = self.lin(fb)?; + let x = fb.binary(BinOp::BitwiseAnd, lin, mask_x)?; + let row = fb.binary(BinOp::ShiftRightLogical, lin, sx)?; + let y = fb.binary(BinOp::BitwiseAnd, row, mask_y)?; + let z = fb.binary(BinOp::ShiftRightLogical, row, sy)?; + let local = fb.composite_construct(self.uvec3, &[x, y, z])?; + let group = self.group_pos(fb, Some(base))?; + let first = fb.binary(BinOp::ShiftLeftLogical, group, s)?; + let tiled = fb.binary(BinOp::IAdd, first, local)?; + let size = self.size3(fb)?; + let first = fb.binary(BinOp::IMul, group, size)?; + let at = self.local_pos(fb, region)?; + let uniform = fb.binary(BinOp::IAdd, first, at)?; + let sized = fb.module().const_value(sized)?; + fb.select(sized, tiled, uniform) + } + + /// Of [`DispatchPlan::grid_edge`], whether the region may hold invocations past the grid (a + /// workgroup-uniform `bool`: `MultiRegion` 1 and the region flagged [`NONUNIFORM`]), and the + /// grid, `region[1].xyz`. + pub fn edge_ragged( + &self, + fb: &mut FunctionBuilder<'_>, + region: &mut RegionFn<'_>, + ) -> BResult<(SValue, SValue)> { + let Some(RegionSelect::Sized(sized)) = self.multi_region else { + return Err(dangling_value()); + }; + let r = region(fb)?; + let r1 = fb.composite_extract(r, &[1])?; + let grid = fb.vector_shuffle(r1, r1, &[0, 1, 2])?; + let flags = fb.composite_extract(r1, &[3])?; + let bit = Self::k(fb, NONUNIFORM)?; + let flag = fb.binary(BinOp::BitwiseAnd, flags, bit)?; + let zero = Self::k(fb, 0)?; + let flagged = fb.binary(BinOp::INotEqual, flag, zero)?; + let sized = fb.module().const_value(sized)?; + let ragged = fb.binary(BinOp::LogicalAnd, sized, flagged)?; + Ok((ragged, grid)) + } + /// A `bool` constant. fn flag(fb: &mut FunctionBuilder<'_>, v: bool) -> BResult { let ty = fb.module().ty(Type::Bool)?; @@ -2037,6 +2261,7 @@ impl KernelDecl { let (base, _) = self.region(fb, region)?; self.group_pos(fb, base) } + K::ThreadPositionInGrid if self.grid_edge => self.edge_position(fb, region), K::ThreadPositionInGrid => { let (base, l) = self.region(fb, region)?; let g = self.group_pos(fb, base)?; diff --git a/crates/metal2vulkan/src/lower/dispatch/tests.rs b/crates/metal2vulkan/src/lower/dispatch/tests.rs index a9f940e65..453641799 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, + grid_edge: false, identity_region: None, } } @@ -837,3 +838,108 @@ fn the_flat_variant_s_64_bit_division_is_exact() { ); } } + +/// [`grid_tile`]'s rule taken over every tile it may give: the sides `2^a, 2^b, 2^c` with +/// `a + b + c = 8`, the least of each tile's key in its total order: the tiles launched, then the +/// tiles partly past the grid, then the depth `c`, then where the grid has two rows or more the +/// height's distance `|b - 1|` from 2, then the narrower last (`-a`). +fn every_tile_rule(threads: [u32; 3]) -> [u32; 3] { + let rows = threads[1] >= 2; + let mut best: Option<([u32; 3], (u128, u128, u32, u32, i64))> = None; + for a in 0..=8u32 { + for b in 0..=8 - a { + let k = [a, b, 8 - a - b]; + let tiles: u128 = (0..3) + .map(|i| u128::from(threads[i].div_ceil(1 << k[i]))) + .product(); + let whole: u128 = (0..3).map(|i| u128::from(threads[i] >> k[i])).product(); + let height = if rows { b.abs_diff(1) } else { 0 }; + let key = (tiles, tiles - whole, k[2], height, -i64::from(a)); + if best.is_none_or(|(_, kept)| key < kept) { + best = Some((k, key)); + } + } + } + best.expect("a tile").0.map(|k| 1 << k) +} + +/// The tiles of grids the rule must place, in its total order over the 45 tiles: the fewest +/// threads launched, then the fewest tiles partly past the grid, then the shallowest, then where +/// the grid has two rows or more the height nearest 2, then the widest. Ragged rows of 8 x 8 +/// threadgroups (24x24x252 and 8x8x360 whole in 8x8x4, 8x8x22 in 8x8x4 at 24 planes for 22, +/// 304x304 whole in 16x16); whole grids, which take the first tile that divides them (128x2 for +/// square, wide and tall ones a 2-row tile divides, 64x4 for a cube of 64); ragged square, wide, +/// tall and deep grids, where 1000x30 launches as many threads in 256x1 as in 128x2 and takes +/// 128x2 for its fewer tiles partly past the grid; one-row grids, which take 256x1, and a column +/// and a pillar of 300 and 1000 threads along their axis; and grids one tile holds, which take +/// the first tile that holds them (8x8 in 32x8). +#[test] +fn grid_tiles_launch_the_fewest_threads_past_the_grid() { + let table: [([u32; 3], [u32; 3]); 25] = [ + ([24, 24, 252], [8, 8, 4]), + ([8, 8, 360], [8, 8, 4]), + ([8, 8, 22], [8, 8, 4]), + ([304, 304, 1], [16, 16, 1]), + ([1024, 1024, 1], [128, 2, 1]), + ([5600, 4200, 1], [32, 8, 1]), + ([64, 64, 64], [64, 4, 1]), + ([4096, 256, 1], [128, 2, 1]), + ([256, 4096, 1], [128, 2, 1]), + ([16, 16, 1], [16, 16, 1]), + ([100, 100, 1], [16, 16, 1]), + ([1000, 30, 1], [128, 2, 1]), + ([30, 1000, 1], [2, 128, 1]), + ([255, 4095, 1], [1, 256, 1]), + ([33, 33, 33], [8, 8, 4]), + ([300, 1, 1], [256, 1, 1]), + ([1000, 1, 1], [256, 1, 1]), + ([1, 1000, 1], [1, 256, 1]), + ([1, 1, 300], [1, 1, 256]), + ([7, 5, 3], [8, 8, 4]), + ([1, 1, 1], [256, 1, 1]), + ([33, 1, 1], [256, 1, 1]), + ([3, 3, 1], [64, 4, 1]), + ([8, 8, 1], [32, 8, 1]), + ([2, 2, 1], [128, 2, 1]), + ]; + for (threads, tile) in table { + assert_eq!(grid_tile(threads), tile, "{threads:?}"); + assert_eq!( + tile.iter().product::(), + GRID_TILE_THREADS, + "{threads:?}" + ); + } +} + +/// [`grid_tile`] gives the tile its rule takes over every tile, on every grid of extents 1 to 40 +/// per axis and on wide, tall and deep ones: its shortcuts, for grids its tile divides and grids +/// one tile holds, take the tile the rule takes. +#[test] +fn grid_tiles_match_the_rule_over_every_tile() { + let mut grids: Vec<[u32; 3]> = Vec::new(); + for x in 1..=40 { + for y in 1..=40 { + for z in [1, 2, 3, 5, 6, 8, 22, 40] { + grids.push([x, y, z]); + } + } + } + for n in [ + 255, + 256, + 257, + 1023, + 1366, + 1920, + 4097, + 65_535, + 1 << 20, + u32::MAX, + ] { + grids.extend([[n, 1, 1], [1, n, 1], [1, 1, n], [n, 768, 1], [n, 3, 5]]); + } + for threads in grids { + assert_eq!(grid_tile(threads), every_tile_rule(threads), "{threads:?}"); + } +} diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 263beeeed..0de2be577 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -18,7 +18,7 @@ pub(crate) mod color_group; mod entry; pub mod key; mod numbered; -mod partition; +pub(crate) mod partition; mod stage_bound; #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan/src/pipeline/compile/partition.rs b/crates/metal2vulkan/src/pipeline/compile/partition.rs index 334c0573a..af6426120 100644 --- a/crates/metal2vulkan/src/pipeline/compile/partition.rs +++ b/crates/metal2vulkan/src/pipeline/compile/partition.rs @@ -42,7 +42,7 @@ use crate::air::ir::{AddrSpace, Callee, InstKind, Type, Value}; /// How a kernel observes its threadgroup partition (see the module). #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub(super) enum Partition { +pub(crate) enum Partition { /// It does not observe it. Oblivious, /// It observes it through its simdgroups alone. @@ -53,7 +53,7 @@ pub(super) enum Partition { /// How kernel `e` observes its threadgroup partition (see the module). Any other stage, and an /// entry without a body, observes it. -pub(super) fn partition(e: &air::Entry) -> Partition { +pub(crate) fn partition(e: &air::Entry) -> Partition { if !matches!(e.ep.stage, AbiStage::Kernel { .. }) { return Partition::Observed; } diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 4809f437e..6b6c6e78e 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -882,6 +882,15 @@ pub enum RuntimeFact { /// that address as it is: no access rounds it to a word, and an 8- or 16-byte access at an /// offset proven a multiple of its size is one `uvec2` or `uvec4`. AddressAlignment { slot: SlotRef, align: u32 }, + /// The kernel's partial-threadgroups variant (`RuntimeFact::PartialThreadgroups`) runs its + /// grid in tiles: a kernel that does not observe its threadgroup partition, on a profile that + /// tiles such a kernel's grid (`Device::from_queries`') under the identity domains. Where its + /// region's `MultiRegion` is 1, its workgroup of `pipeline::GRID_TILE_THREADS` threads is one + /// tile of the grid, whose power-of-two sides the region's nominal size gives + /// (`pipeline::grid_tile`), and where the region is flagged `lower::dispatch::NONUNIFORM` an + /// invocation past the region's grid returns before the body; where it is 0, the kernel runs + /// at its pipeline's size. Its plans run a `dispatchThreads` grid in such tiles. + GridTiles, } /// What one compile made of a slot of a `RuntimeFact::UniformViewRange`. diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index 6bd926703..ad4e58b51 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -149,8 +149,10 @@ pub use compile::{ }; pub use facts::{Mechanism, RuntimeFact, UniformViewChoice}; // The `DispatchRegion` push field's bytes, which a consumer of the identity domains pushes with -// each dispatch. -pub use crate::lower::dispatch::{nonuniform_region_bytes, region_bytes, NONUNIFORM}; +// each dispatch, and the tile a kernel's grid tiles cover a grid with (`RuntimeFact::GridTiles`). +pub use crate::lower::dispatch::{ + grid_tile, nonuniform_region_bytes, region_bytes, 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. pub use crate::lower::simd::workgroup::arena_bytes; diff --git a/crates/metal2vulkan/src/tests/engine_identity.rs b/crates/metal2vulkan/src/tests/engine_identity.rs index 5e78ed66d..c2da5e0a3 100644 --- a/crates/metal2vulkan/src/tests/engine_identity.rs +++ b/crates/metal2vulkan/src/tests/engine_identity.rs @@ -22,6 +22,12 @@ //! - A kernel's partial-threadgroups variant (`partial`, generated) dispatched at its whole //! threadgroup size over a ragged grid, its pushed region flagged `NONUNIFORM`, answers each //! edge threadgroup's own size, and its invocations past the grid store nothing. +//! - The partial-threadgroups variant of a kernel that does not observe its threadgroup partition +//! (`edge`, generated) keeps Metal's partial threadgroups on `Device::new`'s profile; on +//! `Device::from_queries`' it runs its grid in tiles (`RuntimeFact::GridTiles`), its module holds +//! no division by a value the driver does not know, and over grids ragged along every axis, +//! along one, and whole, in `grid_tile`'s tiles, it stores each thread's Metal position once and +//! nothing past the grid; an indirect dispatch runs at its own size. //! - A kernel's texture slots (`tex`, generated: a read, a write, a width and an `is_null_texture`) //! are the elements of the two fixed set-1 arrays at the indices their pushed resource IDs hold, //! with no descriptor of their own. It passes L3 and, on the CPU interpreter, reads and writes @@ -1519,6 +1525,176 @@ fn a_partial_threadgroups_variant_answers_the_edge_threadgroups_of_a_ragged_grid } } +/// A kernel that does not observe its threadgroup partition, storing at its position in the grid +/// `(x, y, z)` of a grid `(gx, gy, gz)` the word `1 + x + (y << 10) + (z << 20)`, at +/// `(z · gy + y) · gx + x`. +fn edge_kernel() -> String { + "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 @edge(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0, <3 x i32> noundef %1, <3 x i32> noundef %2) {\n\ +entry:\n\ + %tx = extractelement <3 x i32> %1, i64 0\n\ + %ty = extractelement <3 x i32> %1, i64 1\n\ + %tz = extractelement <3 x i32> %1, i64 2\n\ + %gx = extractelement <3 x i32> %2, i64 0\n\ + %gy = extractelement <3 x i32> %2, i64 1\n\ + %plane = mul i32 %tz, %gy\n\ + %rows = add i32 %plane, %ty\n\ + %row = mul i32 %rows, %gx\n\ + %idx = add i32 %row, %tx\n\ + %hy = shl i32 %ty, 10\n\ + %hz = shl i32 %tz, 20\n\ + %xy = or i32 %tx, %hy\n\ + %xyz = or i32 %xy, %hz\n\ + %v = add i32 %xyz, 1\n\ + %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 @edge, !10, !11}\n!10 = !{}\n!11 = !{!12, !13, !14}\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\ +!17 = !{i32 2, i32 8, i32 0}\n!18 = !{!\"Metal\", i32 4, i32 0, i32 0}\n" + .to_string() +} + +/// The `OpUDiv`s and `OpUMod`s of disassembly `text` whose divisor is not a constant or a +/// specialization constant: a division the driver keeps once it specializes the module. +fn runtime_divisions(text: &str) -> usize { + let mut constants = BTreeSet::new(); + let mut count = 0; + for line in text.lines() { + let words: Vec<&str> = line.split_whitespace().collect(); + match words[..] { + [id, "=", op, ..] + if op.starts_with("OpConstant") || op.starts_with("OpSpecConstant") => + { + constants.insert(id); + } + [_, "=", "OpUDiv" | "OpUMod", _, _, divisor] if !constants.contains(divisor) => { + count += 1 + } + _ => {} + } + } + count +} + +/// The words [`edge_kernel`] stores over `grid` where each of its threads runs once: each +/// position's word at its index, and `len` words in all. +fn edge_words(grid: [u32; 3], len: usize) -> Vec { + let mut want = vec![0u8; 4 * len]; + for z in 0..grid[2] { + for y in 0..grid[1] { + for x in 0..grid[0] { + let at = 4 * ((z * grid[1] + y) * grid[0] + x) as usize; + let v = 1 + x + (y << 10) + (z << 20); + want[at..at + 4].copy_from_slice(&v.to_le_bytes()); + } + } + } + want +} + +/// On `Device::from_queries`' profile the partial-threadgroups variant of a kernel that does not +/// observe its threadgroup partition runs its grid in tiles (`RuntimeFact::GridTiles`): over +/// grids ragged along every axis, along one, and whole, each in `grid_tile`'s tile, one workgroup +/// of `GRID_TILE_THREADS` with the tile as the region's nominal size at `MultiRegion` 1, flagged +/// `NONUNIFORM` where the tile does not divide the grid, each of the grid's threads stores +/// Metal's position once and no invocation past the grid stores anything; an indirect dispatch at +/// `MultiRegion` 0 runs at its own size. Its module divides by no value the driver does not know +/// when it specializes it. On `Device::new`'s profile the same variant keeps Metal's partial +/// threadgroups, whose positions divide `lin` by the threads left. +#[test] +fn an_oblivious_kernels_partial_variant_runs_its_grid_in_tiles() { + use crate::lower::dispatch::{grid_tile, GRID_TILE_THREADS}; + let Some(bc) = assemble_text("edge", &edge_kernel()) else { + return; + }; + let mut inputs = LowerInputs::new(); + inputs.partial_threadgroups = true; + for stem in PROFILES { + let rows = profile(stem, identity()).unwrap_or_else(|e| panic!("{e}")); + let a = compile_with(&bc, "edge", &rows, &inputs).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert!(!a.facts.contains(&RuntimeFact::GridTiles), "{stem}"); + let (_, module_words) = + link_and_validate(&a, &rows).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); + assert!( + runtime_divisions(&spirv_dis(&module_words)) > 0, + "{stem}: Device::new" + ); + let desc = crate::pipeline::testing::description(stem).unwrap_or_else(|e| panic!("{e}")); + let device = Device::from_queries(desc, identity()).unwrap_or_else(|e| panic!("{e}")); + let p = device.profile(); + let a = compile_with(&bc, "edge", p, &inputs).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert!(a.facts.contains(&RuntimeFact::GridTiles), "{stem}"); + let (_, module_words) = + link_and_validate(&a, p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); + let text = spirv_dis(&module_words); + assert_eq!(runtime_divisions(&text), 0, "{stem}: from_queries\n{text}"); + let (plan, module) = + typed_module_with(&bc, "edge", p, &inputs).unwrap_or_else(|e| panic!("{stem}: {e}")); + // Ragged along every axis (each odd, so the tile takes no side for free), a grid of 8x8 + // threadgroups whole in 8x8x4, ragged along `z` alone, a row, and a pillar. + for grid in [[7, 5, 3], [24, 24, 8], [8, 8, 22], [300, 1, 1], [1, 1, 300]] { + let tile = grid_tile(grid); + let groups: [u32; 3] = std::array::from_fn(|i| grid[i].div_ceil(tile[i])); + let ragged = (0..3).any(|i| !grid[i].is_multiple_of(tile[i])); + // Every word a launched invocation could store at, so a store past the grid shows. + let len = ((groups[2] * tile[2] * grid[1] + groups[1] * tile[1]) * grid[0] + + groups[0] * tile[0]) as usize; + let mut region = region_bytes([0; 3], grid, tile).expect("packs"); + if ragged { + region[28..32].copy_from_slice(&NONUNIFORM.to_le_bytes()); + } + let mut spec = local_size3([GRID_TILE_THREADS, 1, 1]); + spec.insert(SpecKey::MultiRegion, 1); + let res = Resources { + buffers: vec![Buffer { + slot: None, + address: Some(OUT), + bytes: vec![0; 4 * len], + }], + push: grid_push(&plan, OUT, region), + spec, + }; + let cfg = Config { + workgroups: groups, + ..Config::default() + }; + let got = run(&module, &cfg, res).unwrap_or_else(|e| panic!("{stem} {grid:?}: {e}")); + assert_eq!( + got.buffers[0], + edge_words(grid, len), + "{stem} {grid:?} {tile:?}" + ); + } + // An indirect dispatch: 2 x 3 threadgroups of 4 x 2, its grid theirs. + let res = Resources { + buffers: vec![Buffer { + slot: None, + address: Some(OUT), + bytes: vec![0; 4 * 48], + }], + push: grid_push( + &plan, + OUT, + region_bytes([0; 3], [0; 3], [4, 2, 1]).expect("packs"), + ), + spec: local_size3([4, 2, 1]), + }; + let cfg = Config { + workgroups: [2, 3, 1], + ..Config::default() + }; + let got = run(&module, &cfg, res).unwrap_or_else(|e| panic!("{stem} indirect: {e}")); + assert_eq!(got.buffers[0], edge_words([8, 6, 1], 48), "{stem} indirect"); + } +} + /// The `OpControlBarrier`s of disassembly `text`: how many open a block that only a branch on /// `1 < N` (an `OpSpecConstantOp ULessThan` of the constant 1) enters, and how many others. fn barrier_guards(text: &str) -> (usize, usize) { diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 6544c8077..21bea9584 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1158,6 +1158,7 @@ const metal2vulkan::cache::SOURCE_DIGEST pub const SOURCE_DIGEST: &str const metal2vulkan::device::NVIDIA_AMPERE_GA10X pub const NVIDIA_AMPERE_GA10X: &[u32] const metal2vulkan::metal::sampler::NOT_MIPMAPPED_MAX_LOD pub const NOT_MIPMAPPED_MAX_LOD: f32 const metal2vulkan::metal::vertex::MAX_VERTEX_ALIGNMENT pub const MAX_VERTEX_ALIGNMENT: u32 +const metal2vulkan::pipeline::GRID_TILE_THREADS pub const GRID_TILE_THREADS: u32 const metal2vulkan::pipeline::NONUNIFORM pub const NONUNIFORM: u32 const-value metal2vulkan-air::bitstream::BLOCKINFO_BLOCK_ID 0 const-value metal2vulkan-air::bitstream::TOP_LEVEL_ABBREV_WIDTH 2 @@ -1252,6 +1253,7 @@ const-value metal2vulkan::cache::SOURCE_DIGEST env!("M2V_SOURCE_DIGEST") const-value metal2vulkan::device::NVIDIA_AMPERE_GA10X &[0x2200, 0x2203, 0x2204, 0x2205, 0x2206, 0x2207, 0x2208, 0x220a, 0x220d, 0x2216, 0x222b, 0x222f, 0x2230, 0x2231, 0x2232, 0x2233, 0x2235, 0x2236, 0x2237, 0x2238, 0x223f, 0x2414, 0x2420, 0x2438, 0x2460, 0x2480, 0x2482, 0x2483, 0x2484, 0x2486, 0x2487, 0x2488, 0x2489, 0x248a, 0x248c, 0x248d, 0x248e, 0x249c, 0x249d, 0x249f, 0x24a0, 0x24a4, 0x24ac, 0x24ad, 0x24af, 0x24b0, 0x24b1, 0x24b6, 0x24b7, 0x24b8, 0x24b9, 0x24ba, 0x24bb, 0x24bf, 0x24c0, 0x24c7, 0x24c8, 0x24c9, 0x24dc, 0x24dd, 0x24df, 0x24e0, 0x24fa, 0x2501, 0x2503, 0x2504, 0x2505, 0x2507, 0x2508, 0x2509, 0x2520, 0x2521, 0x2523, 0x252f, 0x2531, 0x2544, 0x2560, 0x2561, 0x2563, 0x2571, 0x2582, 0x2583, 0x2584, 0x25a0, 0x25a2, 0x25a3, 0x25a4, 0x25a5, 0x25a6, 0x25a7, 0x25a9, 0x25aa, 0x25ab, 0x25ac, 0x25ad, 0x25af, 0x25b0, 0x25b2, 0x25b5, 0x25b6, 0x25b8, 0x25b9, 0x25ba, 0x25bb, 0x25bc, 0x25bd, 0x25e0, 0x25e2, 0x25e5, 0x25ec, 0x25ed, 0x25f9, 0x25fa, 0x25fb] const-value metal2vulkan::metal::sampler::NOT_MIPMAPPED_MAX_LOD 0.25 const-value metal2vulkan::metal::vertex::MAX_VERTEX_ALIGNMENT 4 +const-value metal2vulkan::pipeline::GRID_TILE_THREADS 256 const-value metal2vulkan::pipeline::NONUNIFORM 1 enum metal2vulkan-air::abi::AbiHandle #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum AbiHandle enum metal2vulkan-air::abi::AbiInt #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum AbiInt @@ -6001,6 +6003,7 @@ fn metal2vulkan::metal::vertex::attribute_fetch pub fn attribute_fetch(format: V fn metal2vulkan::metal::vertex::vertex_alignment pub fn vertex_alignment(format: VertexFormat) -> Result fn metal2vulkan::metal::vertex::vk_vertex_format pub fn vk_vertex_format(format: VertexFormat) -> Result fn metal2vulkan::pipeline::arena_bytes pub fn arena_bytes(arena: Option, regions: u64) -> u64 +fn metal2vulkan::pipeline::grid_tile pub fn grid_tile(threads: [u32; 3]) -> [u32; 3] fn metal2vulkan::pipeline::heap_sampler_capacity pub fn heap_sampler_capacity(p: &DeviceProfile) -> u32 fn metal2vulkan::pipeline::heap_unused_while_pending pub fn heap_unused_while_pending(p: &DeviceProfile) -> bool fn metal2vulkan::pipeline::nonuniform_region_bytes pub fn nonuniform_region_bytes(base: [u32; 3], threads: [u32; 3], l: [u32; 3]) -> Option<[u8; 32]> @@ -16342,6 +16345,7 @@ variant metal2vulkan::pipeline::RuntimeFact::FoldedGroups FoldedGroups variant metal2vulkan::pipeline::RuntimeFact::FragmentImageblock FragmentImageblock { words: u32, writes: bool, master: Hash256, data_size: u32, alignment: u32 } variant metal2vulkan::pipeline::RuntimeFact::FramebufferFetch FramebufferFetch { color: u32 } variant metal2vulkan::pipeline::RuntimeFact::FunctionTableRange FunctionTableRange { addressed: bool } +variant metal2vulkan::pipeline::RuntimeFact::GridTiles GridTiles variant metal2vulkan::pipeline::RuntimeFact::HeapCrossClassNeutral HeapCrossClassNeutral { stage: Stage, class: ImageHandleClass, every_member: bool } variant metal2vulkan::pipeline::RuntimeFact::HeapNumericType HeapNumericType { class: ImageHandleClass } variant metal2vulkan::pipeline::RuntimeFact::HeapRawSamples HeapRawSamples { stage: Stage, sampler: Option } diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 421c50a72..b11d3bd22 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -337,6 +337,8 @@ surface! { fn region_bytes; fn nonuniform_region_bytes; const NONUNIFORM; + fn grid_tile; + const GRID_TILE_THREADS; struct ComputePipeline N; struct ComputePipelineMetalInfo N; struct CompileReport N; diff --git a/docs/API.md b/docs/API.md index 5d1d1acf7..4b3afc39a 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1862,6 +1862,13 @@ threads fill at the dispatch's threadgroup size instead, the last along an axis threadgroup, so every remainder takes the same `VkPipeline`; a kernel the variant cannot run exactly (a tile function, a stage-input region, compute derivatives, emulated simdgroups) is refused it, `Unsupported{GpuEncodedIndirectCommands, NotImplemented}`, and keeps the edges. On +`Device::from_queries`' profile under the identity domains the variant of a kernel that does not +observe its threadgroup partition (`KernelFacts::partition_oblivious`) runs its grid in tiles +instead (`RuntimeFact::GridTiles`): its plans run a direct dispatch's threads in +`pipeline::grid_tile`'s tiles, one workgroup of `pipeline::GRID_TILE_THREADS` each with the tile +as the region's nominal size (`MultiRegion` 1), the region flagged `NONUNIFORM` where the tile +does not divide the grid, and a range of threadgroups at its own size (`MultiRegion` 0); the +kernel runs the same positions with the same answers. On that plan a grid of whole threadgroups, of `Threads` or `Threadgroups`, takes the same regions unflagged (each `MultiRegion` 1, every thread live), so one `VkPipeline` of a threadgroup size runs all of a kernel's direct dispatches. `metal2vulkan-runtime` runs a kernel's whole grids there where