diff --git a/crates/metal2vulkan-conformance/probes/imageblock_size_rules.m b/crates/metal2vulkan-conformance/probes/imageblock_size_rules.m new file mode 100644 index 000000000..0217ba0bc --- /dev/null +++ b/crates/metal2vulkan-conformance/probes/imageblock_size_rules.m @@ -0,0 +1,117 @@ +// Which sizes Metal takes in a compute encoder's `setImageblockWidth:height:`, and the extent a +// kernel reads with none set. +// +// ONE CASE PER PROCESS, chosen on the command line, run under MTL_DEBUG_LAYER=1: the validation +// layer stops the process at a size it does not take, so a case that prints "taken" was taken. +// Each dispatches four 8 by 8 threadgroups of a kernel whose explicit imageblock has 8-byte cells +// and prints the extent its first thread read (`get_width`, `get_height`). +// +// fine 16 by 16 +// width-24 24 by 16: a width of no power of two +// height-12 16 by 12: a height of no power of two +// zero 0 by 0 +// cells-2048 64 by 32: more than 1024 cells +// wide-1024 1024 by 1 +// tall-1024 1 by 1024 +// bounded-256 16 by 16 for a state whose maxTotalThreadsPerThreadgroup is 64: the cells' +// bound is not the state's threads +// before-state 32 by 32, set before setComputePipelineState +// never-set no call +// +// xcrun clang -fobjc-arc -framework Metal -framework Foundation \ +// -o imageblock_size_rules imageblock_size_rules.m +// for c in fine width-24 height-12 zero cells-2048 wide-1024 tall-1024 bounded-256 \ +// before-state never-set; do MTL_DEBUG_LAYER=1 ./imageblock_size_rules $c; done +// +// WHAT IT MEASURED: see the rt crate's `ComputeCommandEncoder::set_imageblock_size`, with the run +// it came from. + +#import +#import +#include + +static NSString *const SOURCE = + @"#include \n" + "using namespace metal;\n" + "struct Cell { float a; uint b; };\n" + "kernel void extent(imageblock img,\n" + " device uint *out [[buffer(0)]],\n" + " ushort2 lid [[thread_position_in_threadgroup]]) {\n" + " if (lid.x == 0 && lid.y == 0) { out[0] = img.get_width(); out[1] = img.get_height(); }\n" + "}\n" + "[[max_total_threads_per_threadgroup(64)]]\n" + "kernel void bounded(imageblock img,\n" + " device uint *out [[buffer(0)]],\n" + " ushort2 lid [[thread_position_in_threadgroup]]) {\n" + " if (lid.x == 0 && lid.y == 0) { out[0] = img.get_width(); out[1] = img.get_height(); }\n" + "}\n"; + +int main(int argc, const char **argv) { + @autoreleasepool { + if (argc != 2) { + printf("usage: imageblock_size_rules CASE\n"); + return 2; + } + const char *name = argv[1]; + struct { + const char *name; + NSUInteger width, height; + BOOL set, before, bounded; + } cases[] = { + {"fine", 16, 16, YES, NO, NO}, {"width-24", 24, 16, YES, NO, NO}, + {"height-12", 16, 12, YES, NO, NO}, {"zero", 0, 0, YES, NO, NO}, + {"cells-2048", 64, 32, YES, NO, NO}, {"wide-1024", 1024, 1, YES, NO, NO}, + {"tall-1024", 1, 1024, YES, NO, NO}, {"bounded-256", 16, 16, YES, NO, YES}, + {"before-state", 32, 32, YES, YES, NO}, {"never-set", 0, 0, NO, NO, NO}, + }; + int found = -1; + for (int i = 0; i < (int)(sizeof cases / sizeof cases[0]); i++) { + if (strcmp(cases[i].name, name) == 0) found = i; + } + if (found < 0) { + printf("no case %s\n", name); + return 2; + } + id device = MTLCreateSystemDefaultDevice(); + NSError *error = nil; + id library = [device newLibraryWithSource:SOURCE + options:[MTLCompileOptions new] + error:&error]; + if (!library) { + printf("library: %s\n", error.localizedDescription.UTF8String); + return 2; + } + NSString *entry = cases[found].bounded ? @"bounded" : @"extent"; + id state = + [device newComputePipelineStateWithFunction:[library newFunctionWithName:entry] + error:&error]; + if (!state) { + printf("state: %s\n", error.localizedDescription.UTF8String); + return 2; + } + id out = [device newBufferWithLength:16 options:MTLResourceStorageModeShared]; + memset(out.contents, 0xff, 16); + id queue = [device newCommandQueue]; + id cb = [queue commandBuffer]; + id encoder = [cb computeCommandEncoder]; + if (cases[found].set && cases[found].before) { + [encoder setImageblockWidth:cases[found].width height:cases[found].height]; + } + [encoder setComputePipelineState:state]; + [encoder setBuffer:out offset:0 atIndex:0]; + if (cases[found].set && !cases[found].before) { + [encoder setImageblockWidth:cases[found].width height:cases[found].height]; + } + [encoder dispatchThreadgroups:MTLSizeMake(2, 2, 1) + threadsPerThreadgroup:MTLSizeMake(8, 8, 1)]; + [encoder endEncoding]; + [cb commit]; + [cb waitUntilCompleted]; + const uint32_t *words = out.contents; + printf("%s: taken, status %ld, maxTotalThreadsPerThreadgroup %lu, read %u by %u%s%s\n", + name, (long)cb.status, (unsigned long)state.maxTotalThreadsPerThreadgroup, words[0], + words[1], cb.error ? ", error " : "", + cb.error ? cb.error.localizedDescription.UTF8String : ""); + } + return 0; +} diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 0443ab7cf..f551f0a8c 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -5,7 +5,7 @@ use crate::buffer::{Buffer, BufferInner, BufferObject}; use crate::command::{Building, CommandBuffer}; use crate::counters::Metric; use crate::device::Core; -use crate::error::{Error, Gap, KernelInputKind, Limit, Refusal, StageInKind}; +use crate::error::{Error, Gap, Limit, Refusal, StageInKind}; use crate::fence::Fence; use crate::floor; use crate::function_table::VisibleFunctionTable; @@ -15,7 +15,7 @@ use crate::kept::{Handle, Lent, Uncounted}; use crate::memory::BlockId; use crate::over::{self, Reached, Span}; use crate::pipeline::{ - address_word, gap, Compiled, ComputePipelineState, FieldValue, Form, Interface, Kernel, Place, + address_word, Compiled, ComputePipelineState, FieldValue, Form, Interface, Kernel, Place, Which, PUSH_STAGES, SQUARE, }; use crate::record::Reach; @@ -26,8 +26,7 @@ use ash::vk; use metal2vulkan::metal::format::{integer_channels_word, BICUBIC_TEXELS_UNBOUND}; use metal2vulkan::metal::PixelFormat; use metal2vulkan::pipeline::{ - grid_tile, nonuniform_region_bytes, region_bytes, RuntimeFact, DEEP_THREADGROUP, - GRID_TILE_THREADS, + grid_tile, nonuniform_region_bytes, region_bytes, DEEP_THREADGROUP, GRID_TILE_THREADS, }; use std::ops::BitOr; use std::sync::Arc; @@ -242,6 +241,9 @@ pub struct ComputeCommandEncoder { samplers: Vec>>, /// Threadgroup memory lengths by index, as set. threadgroup_lengths: Vec<(u32, u32)>, + /// The imageblock size set ([`ComputeCommandEncoder::set_imageblock_size`]): 1 by 1 until a + /// call sets one, the size Metal's dispatches of an encoder that never sets one run. + imageblock: [u32; 2], /// `use_resource` declarations. declared: Vec, /// A `use_resource` declaration writes a Shared buffer. @@ -249,8 +251,8 @@ pub struct ComputeCommandEncoder { /// The pixel format of the first texture a `use_resource` declaration writes that has no /// storage element ([`Texture::unstored`]). declared_unstored_write: Option, - /// The module, workgroup size and `VkPipeline` of the last dispatch, while the state and the - /// threadgroup memory lengths are unchanged. + /// The module, workgroup size and `VkPipeline` of the last dispatch, while the state, the + /// threadgroup memory lengths and the imageblock size are unchanged. last: Option, /// The parameters being filled, kept to reuse their bytes. parameters: Parameters, @@ -471,6 +473,7 @@ impl CommandBuffer { copied: 0, samplers: vec![None; SAMPLER_SLOTS as usize], threadgroup_lengths: Vec::new(), + imageblock: [1, 1], declared: Vec::new(), declared_shared_write: false, declared_unstored_write: None, @@ -752,6 +755,27 @@ impl ComputeCommandEncoder { Ok(()) } + /// `setImageblockWidth:height:`: the size of the explicit imageblock each threadgroup of a + /// later dispatch takes, `width` by `height` cells of its kernel's layout in its threadgroup + /// memory, which [`Limit::ThreadgroupMemory`] counts with the threadgroup memory lengths. An + /// encoder that never calls it runs 1 by 1, as Metal's does; a dispatch of a kernel that + /// reaches no imageblock does not read it. The size is a specialization constant of the + /// pipeline, as a threadgroup memory length is: a kernel's first dispatch at a size it has + /// not run makes its `VkPipeline` and waits for it + /// ([`Metrics::first_use_variant_waits`](crate::Metrics::first_use_variant_waits)), where + /// Metal's makes nothing. + /// + /// Err: [`Refusal::ImageblockSize`] for a width or a height that is not a power of two, or + /// more than 1024 cells. + pub fn set_imageblock_size(&mut self, width: u32, height: u32) -> Result<(), Error> { + imageblock_checked([width, height])?; + if self.imageblock != [width, height] { + self.imageblock = [width, height]; + self.last = None; + } + Ok(()) + } + /// `useResource:usage:` (`useResources:count:usage:` is a loop of it): the resource joins every /// later dispatch's accesses. The command buffer keeps the buffer or the texture until it /// retires. @@ -898,12 +922,10 @@ impl ComputeCommandEncoder { /// kernel; [`Limit::ThreadgroupThreads`] within it and past this device's; /// [`Refusal::BufferOffsetAlignment`] for a buffer the kernel reaches bound off its argument's /// alignment, which nothing records; [`Gap::SwizzledReadWrite`]; [`Gap::BicubicTexels`]; - /// [`Limit::ThreadgroupMemory`]; [`Gap::PartialSimdgroups`] for a threadgroup that is not - /// whole SIMD groups of a kernel whose tier needs them and that has no emulated module; - /// [`Gap::KernelInput`] naming `RuntimeFact::ImageblockSize` for a kernel that reaches an - /// explicit imageblock and writes memory: its extent is what Metal's - /// `setImageblockWidth:height:` sets, which this encoder does not have; - /// [`Limit::MemoryAllocations`] where the parameter ring needs a block past the device's + /// [`Limit::ThreadgroupMemory`], the imageblock's cells at the size + /// [`set_imageblock_size`](Self::set_imageblock_size) set counted with the lengths; + /// [`Gap::PartialSimdgroups`] for a threadgroup that is not whole SIMD groups of a kernel + /// whose tier needs them and that has no emulated module; [`Limit::MemoryAllocations`] where the parameter ring needs a block past the device's /// allocation count; [`Error::Vulkan`] where the pipeline's compile, the ring or recording /// fails. pub fn dispatch_threadgroups( @@ -1087,7 +1109,11 @@ impl ComputeCommandEncoder { &Grid::Direct(direct) => Some(direct), Grid::Indirect(..) => None, }; - let memory = (&self.threadgroup_lengths[..], limits.max_shared_memory); + let set = Sizes { + lengths: &self.threadgroup_lengths, + imageblock: self.imageblock, + }; + let memory = (set, limits.max_shared_memory); let (choice, module, kernel) = decide(inner, direct, size, memory)?; let Choice { local, @@ -1104,8 +1130,7 @@ impl ComputeCommandEncoder { let vk_pipeline = match self.last { Some(last) if last.module == module && last.local == local => last.pipeline, _ => { - let (set, max) = (&self.threadgroup_lengths, limits.max_shared_memory); - let lengths = threadgroup_memory(kernel, set, local, max)?; + let lengths = threadgroup_memory(kernel, set, local, limits.max_shared_memory)?; let variant = inner.dispatch_key(module, local, lengths); kernel.pipeline(core, variant, inner.first_use(variant))? } @@ -1326,8 +1351,8 @@ pub(crate) fn size_checked(interface: &Interface, size: [u32; 3]) -> Result<(), } /// What a dispatch at threadgroup size `size`, direct over `direct` or indirect, of the content -/// `compiled` runs, with the encoder's threadgroup memory lengths `set` against the device's -/// `max` bytes, decided once for the dispatch and for +/// `compiled` runs, with the encoder's threadgroup memory lengths and imageblock size `set` +/// against the device's `max` bytes, decided once for the dispatch and for /// [`ComputePipelineState::prepare_dispatch`]: [`choose`]'s choice, then its module, an /// observer's partial-threadgroups variant for a ragged grid, and the emulated variant for a /// threadgroup that is not whole groups of a module that runs only whole ones (the @@ -1339,19 +1364,13 @@ pub(crate) fn size_checked(interface: &Interface, size: [u32; 3]) -> Result<(), /// dispatch of it the variant takes. The variant is the state's module itself where its make /// lowered no plain module beside it (`pipeline::Partial::Alone`). An indirect dispatch states no /// grid in its region, so the variant runs it in the single-region form, every invocation live, -/// as the translator's dispatch regions say (`lower::dispatch`). A kernel that reaches an -/// explicit imageblock runs nothing: its extent is `setImageblockWidth:height:`'s, which the -/// encoder does not have ([`Gap::KernelInput`] naming `RuntimeFact::ImageblockSize`). +/// as the translator's dispatch regions say (`lower::dispatch`). pub(crate) fn decide<'a>( compiled: &'a Compiled, direct: Option, size: [u32; 3], - (set, max): (&[(u32, u32)], u32), + (set, max): (Sizes<'_>, u32), ) -> Result<(Choice, Module, &'a Kernel), Error> { - if let Some(cell_bytes) = compiled.whole.interface.imageblock { - let fact = RuntimeFact::ImageblockSize { cell_bytes }.name(); - return Err(gap(KernelInputKind::RuntimeFact { fact })); - } let choice = choose(&compiled.form, direct, size); let partial_threadgroups = || { Error::Unsupported(Gap::PartialThreadgroups { @@ -1404,13 +1423,40 @@ pub(crate) fn decide<'a>( } } -/// The threadgroup memory lengths of a kernel's threadgroup arguments, in the order of -/// `Interface::threadgroups`, held inline: a kernel takes at most [`BUFFER_SLOTS`], the indices -/// `setThreadgroupMemoryLength:atIndex:` takes, as its state's make refuses a module with more. +/// What an encoder sets that sizes its dispatches' threadgroup memory: the threadgroup memory +/// lengths by index (`setThreadgroupMemoryLength:atIndex:`), and the imageblock size +/// (`setImageblockWidth:height:`). +#[derive(Clone, Copy)] +pub(crate) struct Sizes<'a> { + pub(crate) lengths: &'a [(u32, u32)], + pub(crate) imageblock: [u32; 2], +} + +/// Metal's most cells of an imageblock (`setImageblockWidth:height:`), whatever the state. +const IMAGEBLOCK_CELLS: u64 = 1024; + +/// An imageblock size as Metal's `setImageblockWidth:height:` takes it: each side a power of two, +/// at most [`IMAGEBLOCK_CELLS`] cells; else [`Refusal::ImageblockSize`]. +pub(crate) fn imageblock_checked([width, height]: [u32; 2]) -> Result<(), Error> { + let cells = u64::from(width) * u64::from(height); + if width.is_power_of_two() && height.is_power_of_two() && cells <= IMAGEBLOCK_CELLS { + Ok(()) + } else { + Err(Error::Refused(Refusal::ImageblockSize { width, height })) + } +} + +/// What a kernel's `VkPipeline` specializes of its threadgroup memory beside its own: the lengths +/// of its threadgroup arguments, in the order of `Interface::threadgroups`, held inline (a kernel +/// takes at most [`BUFFER_SLOTS`], the indices `setThreadgroupMemoryLength:atIndex:` takes, as +/// its state's make refuses a module with more), and its explicit imageblock's size. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub(crate) struct Lengths { words: [u32; BUFFER_SLOTS as usize], count: u8, + /// The imageblock's width and height where the kernel reaches an explicit imageblock, else 0 + /// by 0: a kernel that reaches none has one pipeline whatever size the encoder set. + pub(crate) imageblock: [u32; 2], } impl Lengths { @@ -1419,6 +1465,7 @@ impl Lengths { Lengths { words: [0; BUFFER_SLOTS as usize], count: count.min(BUFFER_SLOTS as usize) as u8, + imageblock: [0; 2], } } @@ -1429,20 +1476,29 @@ impl Lengths { } /// The threadgroup memory lengths of `kernel`'s threadgroups, from the encoder's `set` (0 for an -/// index it set none at), checked at workgroup `local` against the device's `max` bytes. +/// index it set none at), with its imageblock's size where it reaches one, checked at workgroup +/// `local` against the device's `max` bytes, the imageblock's cells included. pub(crate) fn threadgroup_memory( kernel: &Kernel, - set: &[(u32, u32)], + set: Sizes<'_>, local: [u32; 3], max: u32, ) -> Result { let mut lengths = Lengths::default(); for (word, &index) in (lengths.words.iter_mut()).zip(&kernel.interface.threadgroups) { - *word = threadgroup_length(set, index); + *word = threadgroup_length(set.lengths, index); lengths.count += 1; } + let imageblock = match kernel.interface.imageblock { + Some(cell_bytes) => { + lengths.imageblock = set.imageblock; + let [width, height] = set.imageblock.map(u64::from); + width * height * u64::from(cell_bytes) + } + None => 0, + }; let threads = local.iter().map(|&axis| u64::from(axis)).product::(); - let length = kernel.interface.memory.bytes(lengths.as_slice(), threads); + let length = (kernel.interface.memory).bytes(lengths.as_slice(), imageblock, threads); if length > u64::from(max) { return Err(Error::Limit(Limit::ThreadgroupMemory { length, max })); } diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 84160b5ea..052883363 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -423,6 +423,23 @@ pub enum Refusal { /// The state's `maxTotalThreadsPerThreadgroup`. max: u32, }, + /// An imageblock size + /// ([`ComputeCommandEncoder::set_imageblock_size`](crate::ComputeCommandEncoder::set_imageblock_size)) + /// whose width or height is not a power of two, 0 included, or whose cells are more than 1024, + /// whatever the state's `maxTotalThreadsPerThreadgroup`. + /// + /// Basis: metal-measured (an Apple M3 Max, macOS 27.0.1, probe `imageblock_size_rules.m` in + /// the conformance crate, job m3-max-70002: Metal's validation layer stops each at the call, + /// `width(24) must be a power of 2.`, `height(12) must be a power of 2.`, + /// `width(0) must be a power of 2.` and + /// `width(64)*height(32) must be less than or equal to 1024`; it takes 16 by 16, 1024 by 1, + /// 1 by 1024, 16 by 16 for a state of 64 threads, and a size set before the pipeline state). + ImageblockSize { + /// The width asked for. + width: u32, + /// The height asked for. + height: u32, + }, /// An indirect dispatch's or draw's argument offset that is not a multiple of 4, which Metal's /// `indirectBufferOffset` must be /// ([`ComputeCommandEncoder::dispatch_threadgroups_with_indirect_buffer`](crate::ComputeCommandEncoder::dispatch_threadgroups_with_indirect_buffer) @@ -1069,19 +1086,16 @@ pub enum Gap { kind: IndirectCommandsKind, }, /// A kernel that reads something the compute encoder does not supply yet, `kind` naming what: - /// an intersection-function table, a visible-function table an argument buffer holds, an - /// explicit imageblock, a parameter the runtime does not fill, or a specialization the runtime - /// does not set, among others. Buffers, `setBytes` data, textures and sampler states by their - /// resource IDs, visible-function tables at buffer indices, constexpr samplers by their - /// indices, an integer write's channel widths, threadgroup memory lengths, the dispatch's grid, - /// the stage-in region, `[[stage_in]]` attributes of a fixed layout stride and a pinned - /// subgroup size are supplied. + /// an intersection-function table, a visible-function table an argument buffer holds, a + /// parameter the runtime does not fill, or a specialization the runtime does not set, among + /// others. Buffers, `setBytes` data, textures and sampler states by their resource IDs, + /// visible-function tables at buffer indices, constexpr samplers by their indices, an integer + /// write's channel widths, threadgroup memory lengths, an explicit imageblock's size, the + /// dispatch's grid, the stage-in region, `[[stage_in]]` attributes of a fixed layout stride + /// and a pinned subgroup size are supplied. /// Metal's counterpart is the compute pipeline state's make /// (`newComputePipelineStateWithDescriptor:options:reflection:error:` and its siblings), which - /// makes each. An explicit imageblock's extent is refused at the dispatch instead - /// (`dispatchThreadgroups:threadsPerThreadgroup:` and its siblings), the state being made: - /// Metal's dispatch runs the extent `setImageblockWidth:height:` set, which the encoder does - /// not have. + /// makes each. /// /// Basis: ours (the encoder supplies only those). KernelInput { @@ -1657,12 +1671,11 @@ pub enum KernelInputKind { StageFlags, /// A fact of the module the encoder does not supply: a `RuntimeFact` the runtime does not /// name, such as a resource's presence or a sampler's coordinates, or an address alignment of - /// a slot that is not a kernel's buffer or that is not a power of two, at the state's make; - /// an explicit imageblock's size (`RuntimeFact::ImageblockSize`) at a dispatch of the state. - /// Metal's counterpart is the dispatch's state the fact stands for: - /// `setImageblockWidth:height:`, or the bound resource's own state. + /// a slot that is not a kernel's buffer or that is not a power of two, at the state's make. + /// Metal's counterpart is the dispatch's state the fact stands for: the bound resource's own + /// state. RuntimeFact { - /// The fact's name (`RuntimeFact::name`), such as `"ImageblockSize"`. + /// The fact's name (`RuntimeFact::name`), such as `"ResourcePresence"`. fact: &'static str, }, /// An argument slot the encoder does not bind: an intersection function table at a buffer @@ -2413,6 +2426,10 @@ impl fmt::Display for Refusal { f, "a threadgroup of {size:?} threads is empty or past the state's {max}" ), + Refusal::ImageblockSize { width, height } => write!( + f, + "an imageblock of {width} by {height} is not powers of two of at most 1024 cells" + ), Refusal::IndirectOffset { offset, length } => write!( f, "indirect arguments at offset {offset} of a {length}-byte buffer are not at a multiple of 4" diff --git a/crates/metal2vulkan-runtime/src/error/basis.rs b/crates/metal2vulkan-runtime/src/error/basis.rs index 4b9eff191..a4d9b318c 100644 --- a/crates/metal2vulkan-runtime/src/error/basis.rs +++ b/crates/metal2vulkan-runtime/src/error/basis.rs @@ -40,6 +40,7 @@ impl Refusal { Refusal::SamplerIds { .. } => RefusalBasis::Ours, Refusal::NoBufferAtIndex { .. } => RefusalBasis::Ours, Refusal::ThreadgroupSize { .. } => RefusalBasis::MetalDocumented, + Refusal::ImageblockSize { .. } => RefusalBasis::MetalMeasured, Refusal::IndirectOffset { .. } => RefusalBasis::MetalDocumented, Refusal::IndirectArgumentsPastEnd { .. } => RefusalBasis::Ours, Refusal::BufferOffsetAlignment { .. } => RefusalBasis::MetalDocumented, diff --git a/crates/metal2vulkan-runtime/src/pipeline.rs b/crates/metal2vulkan-runtime/src/pipeline.rs index 27df1e6bf..e0f01cedd 100644 --- a/crates/metal2vulkan-runtime/src/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/pipeline.rs @@ -61,7 +61,8 @@ use crate::cache; use crate::counters::{Counters, FirstUse, Gauge, Metric, VariantMake, VariantStart}; use crate::device::{lock, Core}; use crate::encoder::{ - decide, size_checked, threadgroup_memory, Dispatch, Lengths, Module, BUFFER_SLOTS, + decide, imageblock_checked, size_checked, threadgroup_memory, Dispatch, Lengths, Module, Sizes, + BUFFER_SLOTS, }; use crate::error::{Error, Gap, IndirectCommandsKind, KernelInputKind, Refusal, StageInKind}; use crate::hazard::Access; @@ -107,8 +108,9 @@ pub struct ComputePipelineState { /// No Metal counterpart: the `VkPipeline` a dispatch of a compute state runs, as a key for a /// consumer's pre-pass beside [`ComputePipelineState::prepare_dispatch`] /// ([`ComputePipelineState::dispatch_variant`]). Two keys are equal exactly when their -/// dispatches run the same `VkPipeline`: of one compiled content, the same module, workgroup size -/// and threadgroup memory lengths. The states of one content share its `VkPipeline`s, so their +/// dispatches run the same `VkPipeline`: of one compiled content, the same module, workgroup size, +/// threadgroup memory lengths and, for a kernel that reaches an explicit imageblock, imageblock +/// size. The states of one content share its `VkPipeline`s, so their /// keys compare equal; keys of different contents never do, on any device, even once one content /// is gone, so one memo serves every state. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -122,11 +124,7 @@ pub struct DispatchVariant { impl DispatchVariant { /// Its `VkPipeline`'s key among its kernel's variants. fn key(&self) -> Key<'_> { - ( - self.local, - self.lengths.as_slice(), - self.module == Module::Tiles, - ) + (self.local, &self.lengths, self.module == Module::Tiles) } } @@ -476,8 +474,9 @@ impl More { } impl Variants { - /// The pipeline of the variant of `size`, threadgroup memory `lengths` and `tiles`, where its - /// cell holds it, read with no lock; `more`, the list past the cells, where they are all full. + /// The pipeline of the variant of `size`, threadgroup memory `lengths` (the imageblock's size + /// with them) and `tiles`, where its cell holds it, read with no lock; `more`, the list past + /// the cells, where they are all full. fn in_cells(&self, (size, lengths, tiles): Key<'_>) -> Result { for cell in &self.cells { match cell.get() { @@ -564,9 +563,9 @@ impl Drop for Pending<'_> { } } -/// A variant's key: its threadgroup size, its threadgroup memory lengths, whether it runs a -/// kernel's grid tiles. -pub(crate) type Key<'a> = ([u32; 3], &'a [u32], bool); +/// A variant's key: its threadgroup size, its threadgroup memory lengths and imageblock size, +/// whether it runs a kernel's grid tiles. +pub(crate) type Key<'a> = ([u32; 3], &'a Lengths, bool); /// What the runtime needs of a kernel, from the translator. pub(crate) struct Interface { @@ -616,9 +615,8 @@ pub(crate) struct Interface { /// dispatch of it takes the runtime's arena (`crate::arena`, [`FieldValue::PrivateArena`]). pub(crate) private_arena: Option, /// The bytes of each cell of the kernel's explicit imageblock (`RuntimeFact::ImageblockSize`), - /// where it reaches one. Its extent is what `setImageblockWidth:height:` sets, which the - /// encoder does not have: the state is made, and its dispatches are refused - /// (`encoder::decide`). + /// where it reaches one. Its extent is what `setImageblockWidth:height:` sets, which each + /// `VkPipeline` specializes (`Lengths::imageblock`). pub(crate) imageblock: Option, /// The kernel's specialization constants: each one's id and what sets it. pub(crate) constants: Vec<(u32, Constant)>, @@ -668,11 +666,12 @@ pub(crate) enum OwnMemory { impl Memory { /// The threadgroup memory a threadgroup of `threads` threads takes with the lengths `lengths` - /// set, each rounded up to 16 bytes. - pub(crate) fn bytes(&self, lengths: &[u32], threads: u64) -> u64 { - let regions = lengths - .iter() - .map(|&length| u64::from(length).next_multiple_of(16)) + /// set and an imageblock of `imageblock` bytes after them (0 where the kernel reaches none), + /// each rounded up to 16 bytes. + pub(crate) fn bytes(&self, lengths: &[u32], imageblock: u64, threads: u64) -> u64 { + let regions = (lengths.iter().map(|&length| u64::from(length))) + .chain([imageblock]) + .map(|bytes| bytes.next_multiple_of(16)) .sum::(); let own = match self.own { OwnMemory::Static(bytes) => u64::from(bytes) + regions, @@ -695,6 +694,9 @@ pub(crate) enum Constant { /// The length of the threadgroup memory argument at this position of /// [`Interface::threadgroups`]. ThreadgroupLength(usize), + /// The explicit imageblock's width (0) or height (1), as the encoder set it + /// (`Lengths::imageblock`). + Imageblock(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. @@ -811,18 +813,19 @@ pub(crate) enum FieldValue { } /// 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. +/// order of [`Interface::threadgroups`] with the imageblock's size, and whether it runs a kernel's +/// grid tiles. pub(crate) struct Variant { pub(crate) size: [u32; 3], - pub(crate) threadgroup_lengths: Vec, + pub(crate) lengths: Lengths, /// The launches are a kernel's grid tiles (`MultiRegion` 1). pub(crate) tiles: bool, } impl Variant { /// Whether this is the variant of `size`, threadgroup memory `lengths` and `tiles`. - fn is(&self, size: [u32; 3], lengths: &[u32], tiles: bool) -> bool { - self.size == size && self.threadgroup_lengths == lengths && self.tiles == tiles + fn is(&self, size: [u32; 3], lengths: &Lengths, tiles: bool) -> bool { + self.size == size && self.lengths == *lengths && self.tiles == tiles } } @@ -864,8 +867,8 @@ impl crate::Device { /// makes its main pipeline here (Err below). Where the device has a cache directory /// ([`DeviceOptions::pipeline_cache_dir`]), a lowering a device made before is read from it /// in place of lowering again, and every `VkPipeline` is made through the pipeline cache it - /// keeps there. The content's other `VkPipeline`s, of a threadgroup size and threadgroup - /// memory lengths only a dispatch gives, are made by a + /// keeps there. The content's other `VkPipeline`s, of a threadgroup size, threadgroup + /// memory lengths and an imageblock size only a dispatch gives, are made by a /// [`prepare_dispatch`](ComputePipelineState::prepare_dispatch) call or by the first encoding /// call of any of its states that needs each ([`ComputePipelineState`]), which waits for it. /// @@ -892,10 +895,7 @@ impl crate::Device { /// naming the kernel; [`Gap::IndirectCommandBuffers`] of /// [`IndirectCommandsKind::ComputeCommands`] for a descriptor that sets /// `supportIndirectCommandBuffers`; [`Gap::KernelInput`] for a kernel that reads what the - /// compute encoder does not supply yet, but for an explicit imageblock's extent: a kernel that - /// reaches one is made, and its dispatches are refused - /// ([`ComputeCommandEncoder::dispatch_threadgroups`](crate::ComputeCommandEncoder::dispatch_threadgroups)); - /// [`Gap::StageIn`] for a `[[stage_in]]` attribute the kernel reads through a layout of a + /// compute encoder does not supply yet; [`Gap::StageIn`] for a `[[stage_in]]` attribute the kernel reads through a layout of a /// dynamic stride ([`StageInKind::DynamicStride`]) or of an indexed step at a step rate past 1 /// ([`StageInKind::IndexedStepRate`]); [`Refusal::SamplerIds`] where /// `sampler_ids` answers another count; [`Refusal::IndicesNotGranted`] for a constexpr @@ -1162,8 +1162,8 @@ impl Compiled { /// partial-threadgroups variant's, which runs whole grids, ragged and indirect ones alike, or /// the whole module's where the content has no such variant or the variant's threadgroup /// memory, a predicated walk's vote word with it, is past the device's (`encoder::decide`); - /// none where the module takes a threadgroup memory length from the encoder, or where - /// `encoder::decide` refuses the dispatch (a kernel's explicit imageblock). + /// none where the module takes a threadgroup memory length or an imageblock size from the + /// encoder. fn main_key(&self, descriptor: &ComputePipelineDescriptor) -> Option { let (module, size) = match &self.form { Form::Tiled => (Module::Tiles, [GRID_TILE_THREADS, 1, 1]), @@ -1175,8 +1175,13 @@ impl Compiled { let bound = declared.then_some([interface.max_total_threads, 1, 1]); let size = descriptor.required_threads_per_threadgroup.or(bound)?; let dispatch = Dispatch::Threadgroups([1; 3]); - let (kernel, module, local, lengths) = self.dispatched(dispatch, size, &[])?; - return (kernel.interface.threadgroups.is_empty()) + let set = Sizes { + lengths: &[], + imageblock: [1, 1], + }; + let (kernel, module, local, lengths) = self.dispatched(dispatch, size, set)?; + let interface = &kernel.interface; + return (interface.threadgroups.is_empty() && interface.imageblock.is_none()) .then(|| self.dispatch_key(module, local, lengths)); } }; @@ -1342,12 +1347,15 @@ fn made( /// Whether an observing kernel's state keeps its plain module beside its partial-threadgroups /// variant, whose module's interface is `variant`: where the variant's predicated walk takes a /// vote word of threadgroup memory the plain module does not ([`Memory::vote`]), and the kernel -/// takes a threadgroup memory length from the encoder or its own memory with the word is past the -/// device's `max` bytes, so that a dispatch the plain module takes may find the variant past the -/// limit (`encoder::decide`). Every other dispatch either module takes, the variant takes. +/// takes a threadgroup memory length or an imageblock size from the encoder or its own memory +/// with the word is past the device's `max` bytes, so that a dispatch the plain module takes may +/// find the variant past the limit (`encoder::decide`). Every other dispatch either module takes, +/// the variant takes. fn keeps_plain(variant: &Interface, max: u32) -> bool { variant.memory.vote != 0 - && (!variant.threadgroups.is_empty() || variant.memory.bytes(&[], 0) > u64::from(max)) + && (!variant.threadgroups.is_empty() + || variant.imageblock.is_some() + || variant.memory.bytes(&[], 0, 0) > u64::from(max)) } /// The lowering of `FunctionCompileKey` digest `key` a device kept in the cache directory, where @@ -1515,7 +1523,7 @@ pub(crate) fn interface( // Each invocation's slot of the private arena, which the encoder places // (`FieldValue::PrivateArena`). RuntimeFact::PrivateArena { slot_bytes } => private_arena = Some(slot_bytes), - // The explicit imageblock's extent, which no dispatch supplies. + // The explicit imageblock's cells, whose extent the encoder sets. RuntimeFact::ImageblockSize { cell_bytes } => imageblock = Some(cell_bytes), // The emulated tier's arena and scratch, in place of Metal's static part. RuntimeFact::SimdgroupEmulation { @@ -1723,9 +1731,8 @@ pub(crate) fn interface( // (true) for every dispatch: one pipeline, whose fetch reads an element past the first // 2^32 bytes from its bind offset as zero. SpecKey::StageInReach => continue, - // The explicit imageblock's extent, kept at the module's default (0 by 0): no - // dispatch runs a module that reaches an imageblock (`encoder::decide`). - SpecKey::ImageblockWidth | SpecKey::ImageblockHeight => continue, + SpecKey::ImageblockWidth => Constant::Imageblock(0), + SpecKey::ImageblockHeight => Constant::Imageblock(1), _ => return Err(KernelInputKind::Specialization), }; constants.push((constant.id, set)); @@ -1910,14 +1917,18 @@ impl ComputePipelineState { /// `threadgroup_memory_lengths` is what /// [`set_threadgroup_memory_length`](crate::ComputeCommandEncoder::set_threadgroup_memory_length) /// set on the encoder before it, as (index, length) pairs, each index once, an index not - /// listed at 0. + /// listed at 0; `imageblock_size` is what + /// [`set_imageblock_size`](crate::ComputeCommandEncoder::set_imageblock_size) set on it before + /// the dispatch, `[1, 1]` where it set none, which only a kernel that reaches an explicit + /// imageblock reads. /// /// It decides what the dispatch runs as the dispatch decides it, then makes the `VkPipeline` - /// of the dispatch's module, workgroup size, threadgroup memory lengths and grid tiles. It - /// returns at once where that is made, or another thread is making it: a dispatch that needs - /// it then waits for that thread alone. It makes nothing where the dispatch would refuse its - /// threadgroup size, its variant, its threadgroup memory or its kernel's explicit imageblock, - /// or records nothing (a grid with no threads, a kernel that writes no memory), and it reports + /// of the dispatch's module, workgroup size, threadgroup memory lengths, imageblock size and + /// grid tiles. It returns at once where that is made, or another thread is making it: a + /// dispatch that needs it then waits for that thread alone. It makes nothing where the + /// dispatch would refuse its threadgroup size, its variant or its threadgroup memory, where + /// the encoder would refuse the imageblock size of a kernel that reaches one, or where it + /// records nothing (a grid with no threads, a kernel that writes no memory), and it reports /// no other error than a kernel's past the stage bound: every other is the dispatch's own. /// What the dispatch checks of the encoder's bindings is not checked here. A make that failed /// is made again by the next call or dispatch that needs it. @@ -1932,9 +1943,14 @@ impl ComputePipelineState { dispatch: Dispatch, threads_per_threadgroup: [u32; 3], threadgroup_memory_lengths: &[(u32, u32)], + imageblock_size: [u32; 2], ) -> Result<(), Error> { let compiled = &self.inner.compiled; - let (size, set) = (threads_per_threadgroup, threadgroup_memory_lengths); + let size = threads_per_threadgroup; + let set = Sizes { + lengths: threadgroup_memory_lengths, + imageblock: imageblock_size, + }; let Some((kernel, module, local, lengths)) = compiled.dispatched(dispatch, size, set) else { return Ok(()); @@ -1966,18 +1982,23 @@ impl ComputePipelineState { /// reads false until its [`finish_pipeline`](Self::finish_pipeline), a `prepare_dispatch` /// call or a dispatch has made it. The key does not move. /// - /// None where the dispatch would refuse its threadgroup size, its variant, its threadgroup - /// memory or its kernel's explicit imageblock, or records nothing (a grid with no threads, a - /// kernel that writes no memory): where `prepare_dispatch` makes nothing whatever was made - /// before. It makes nothing and allocates nothing where it answers a key. + /// None where the dispatch would refuse its threadgroup size, its variant or its threadgroup + /// memory, where the encoder would refuse the imageblock size of a kernel that reaches one, or + /// where it records nothing (a grid with no threads, a kernel that writes no memory): where + /// `prepare_dispatch` makes nothing whatever was made before. It makes nothing and allocates nothing where it answers a key. pub fn dispatch_variant( &self, dispatch: Dispatch, threads_per_threadgroup: [u32; 3], threadgroup_memory_lengths: &[(u32, u32)], + imageblock_size: [u32; 2], ) -> Option<(DispatchVariant, bool)> { let compiled = &self.inner.compiled; - let (size, set) = (threads_per_threadgroup, threadgroup_memory_lengths); + let size = threads_per_threadgroup; + let set = Sizes { + lengths: threadgroup_memory_lengths, + imageblock: imageblock_size, + }; let (kernel, module, local, lengths) = compiled.dispatched(dispatch, size, set)?; let variant = compiled.dispatch_key(module, local, lengths); Some((variant, kernel.is_made(variant.key()))) @@ -2236,20 +2257,24 @@ impl Compiled { } /// What a dispatch of `dispatch` at threadgroup size `size`, with the encoder's threadgroup - /// memory lengths `set`, runs, decided as the dispatch decides it: its kernel, its module, its - /// workgroup size and its kernel's threadgroup memory lengths. None where the dispatch refuses - /// its threadgroup size, its variant, its threadgroup memory or its kernel's explicit - /// imageblock, or records nothing (a grid with no threads, a kernel that writes no memory). + /// memory lengths and imageblock size `set`, runs, decided as the dispatch decides it: its + /// kernel, its module, its workgroup size and its kernel's threadgroup memory lengths and + /// imageblock size. None where the dispatch refuses its threadgroup size, its variant or its + /// threadgroup memory, where the encoder refuses the imageblock size of a kernel that reaches + /// one, or where it records nothing (a grid with no threads, a kernel that writes no memory). fn dispatched( &self, dispatch: Dispatch, size: [u32; 3], - set: &[(u32, u32)], + set: Sizes<'_>, ) -> Option<(&Kernel, Module, [u32; 3], Lengths)> { let interface = &self.whole.interface; if size_checked(interface, size).is_err() || !interface.has_effects { return None; } + if interface.imageblock.is_some() && imageblock_checked(set.imageblock).is_err() { + return None; + } let max = self.core.limits.max_shared_memory; let (choice, module, kernel) = decide(self, dispatch.direct(size), size, (set, max)).ok()?; @@ -2453,7 +2478,7 @@ impl Kernel { let (size, lengths, tiles) = variant.key(); let made = Variant { size, - threadgroup_lengths: lengths.to_vec(), + lengths: *lengths, tiles, }; let pipeline = self.make(core, &made)?; @@ -2477,7 +2502,8 @@ impl Kernel { .map(|&(_, set)| match set { Constant::Size(axis) => variant.size[axis], Constant::Threads => variant.size.iter().product(), - Constant::ThreadgroupLength(at) => variant.threadgroup_lengths[at], + Constant::ThreadgroupLength(at) => variant.lengths.as_slice()[at], + Constant::Imageblock(axis) => variant.lengths.imageblock[axis], Constant::MultiRegion => u32::from(variant.tiles), Constant::Deep => u32::from(variant.size[2] > DEEP_THREADGROUP), }) diff --git a/crates/metal2vulkan-runtime/src/tests/dispatch_tiles.rs b/crates/metal2vulkan-runtime/src/tests/dispatch_tiles.rs index 4ada43d77..1c666c7fd 100644 --- a/crates/metal2vulkan-runtime/src/tests/dispatch_tiles.rs +++ b/crates/metal2vulkan-runtime/src/tests/dispatch_tiles.rs @@ -383,7 +383,7 @@ mod on_device { ]; let keys: Vec<_> = (table.iter()) .map(|&(dispatch, size, pipeline)| { - (state.dispatch_variant(dispatch, size, &[])) + (state.dispatch_variant(dispatch, size, &[], [1, 1])) .map(|(variant, _)| variant) .unwrap_or_else(|| panic!("{name}: {pipeline}: {dispatch:?} by {size:?}")) }) @@ -395,7 +395,7 @@ mod on_device { } for &(dispatch, size, _) in &table { state - .prepare_dispatch(dispatch, size, &[]) + .prepare_dispatch(dispatch, size, &[], [1, 1]) .expect("made ahead"); } let after = counters.metrics(); @@ -442,7 +442,7 @@ mod on_device { state.finish_pipeline().expect("finished"); assert_eq!(form(&state), "tiled", "{name}: the form"); let made = |dispatch: Dispatch| { - (state.dispatch_variant(dispatch, REQUIRED, &[])) + (state.dispatch_variant(dispatch, REQUIRED, &[], [1, 1])) .map(|(_, made)| made) .unwrap_or_else(|| panic!("{name}: {dispatch:?}: a key")) }; @@ -456,7 +456,8 @@ mod on_device { ); let counters = device.counters(); let before = counters.metrics(); - (state.prepare_dispatch(Dispatch::Indirect, REQUIRED, &[])).expect("made ahead"); + (state.prepare_dispatch(Dispatch::Indirect, REQUIRED, &[], [1, 1])) + .expect("made ahead"); assert_eq!( counters.metrics().made_ahead_variants - before.made_ahead_variants, 1, diff --git a/crates/metal2vulkan-runtime/src/tests/imageblock.rs b/crates/metal2vulkan-runtime/src/tests/imageblock.rs new file mode 100644 index 000000000..0fe2e983e --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/imageblock.rs @@ -0,0 +1,216 @@ +//! A kernel's explicit imageblock, under a device cfg on every device of the cfg's kind: an +//! encoder that never sets its size runs it 1 by 1, as Metal's does; one encoder runs two sizes +//! it sets, each dispatch at its own, every one a pipeline of its own made at its first use; the +//! setter refuses the sizes Metal's validation refuses; and a pre-pass's key follows the size. + +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod on_device { + use crate::tests::command::on_device::{each_device, finished, Arena}; + use crate::{ + Buffer, ComputePipelineDescriptor, ComputePipelineState, Device, Dispatch, DispatchType, + Error, FunctionDescriptor, Gap, NumberedSampler, Refusal, StageSource, + }; + use metal2vulkan::library::Library; + use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError}; + + /// `a4_imageblock_extent`'s state, or None where `llvm-as` is missing: each thread stages its + /// cell at its position, then writes its right-hand neighbour's cell (wrapping at the + /// imageblock's width) and the extent it reads. + fn extent_state(device: &Device) -> Option { + let fixture = engine_dir().join("a4_imageblock_extent.ll"); + let bitcode = match llvm_assemble(&fixture) { + Ok(bitcode) => bitcode, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return None; + } + Err(error) => panic!("a4_imageblock_extent: {error:?}"), + }; + let library = Library::from_air(&bitcode).expect("the library"); + let function = library + .function("a4_imageblock_extent") + .expect("the kernel"); + let descriptor = ComputePipelineDescriptor::new(StageSource::Function( + FunctionDescriptor::new(function), + )); + let ids = |samplers: &[NumberedSampler]| Ok((0..samplers.len() as u32).collect()); + Some((device.new_compute_pipeline_state(&descriptor, ids)).expect("the state")) + } + + /// What `a4_imageblock_extent` writes for a `width` by `height` threadgroup over an imageblock + /// of its size: for thread `(x, y)`, the cell of `((x + 1) % width, y)` and the extent. + fn expected(width: u32, height: u32) -> Vec { + (0..height) + .flat_map(|y| { + (0..width).flat_map(move |x| { + let next = (x + 1) % width; + let value = (next as f32 + 100.0 * y as f32).to_bits(); + [value, next | (y << 16), width, height] + }) + }) + .collect() + } + + /// The first `count` words of `buffer`, whose work completed. + fn words(buffer: &Buffer, count: usize) -> Vec { + let contents = buffer.contents().expect("a Shared buffer").cast::(); + // SAFETY: the buffer is alive and 256 bytes long, `count` is at most 64, and its work + // completed. + (0..count) + .map(|index| unsafe { contents.as_ptr().add(index).read_volatile() }) + .collect() + } + + /// A kernel that reaches an explicit imageblock, dispatched by an encoder that never sets its + /// size, runs it 1 by 1: one thread's threadgroup reads its own cell and an extent of 1 by 1, + /// as Metal's does (job m3-max-70002, probe `imageblock_size_rules.m`'s `never-set`). + #[test] + fn an_imageblock_never_sized_runs_one_by_one() { + each_device("imageblock_never_sized", |name, _, device| { + let Some(state) = extent_state(&device) else { + return; + }; + let mut arena = Arena::new(&device); + let out = arena.buffer(); + let queue = device.new_command_queue(1).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = + (command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder"); + encoder + .set_compute_pipeline_state(&state) + .expect("the state"); + encoder.set_buffer(Some(&out), 0, 0).expect("the buffer"); + (encoder.dispatch_threadgroups([1, 1, 1], [1, 1, 1])) + .unwrap_or_else(|error| panic!("{name}: the dispatch: {error}")); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + assert_eq!( + words(&out, 4), + expected(1, 1), + "{name}: the 1 by 1 imageblock" + ); + println!("{name}: an imageblock never sized ran 1 by 1"); + }); + } + + /// One encoder sets two imageblock sizes, 4 by 2 and then 4 by 4, each before a dispatch of a + /// threadgroup of its size: each dispatch reads the size set before it, through a pipeline of + /// its own made at its first use (two first-use waits and two keys, the state having no main + /// pipeline, as a kernel that takes a threadgroup memory length from the encoder has none). + /// The state's imageblock length stays its typed gap. + #[test] + fn one_encoder_runs_each_imageblock_size_it_sets() { + each_device("imageblock_two_sizes", |name, _, device| { + let Some(state) = extent_state(&device) else { + return; + }; + let length = state.imageblock_memory_length_for_dimensions([8, 4, 3]); + assert!( + matches!(length, Err(Error::Unsupported(Gap::ImageblockLength))), + "{name}: the imageblock length {length:?}" + ); + state.finish_pipeline().expect("no main pipeline to make"); + let groups = Dispatch::Threadgroups([1, 1, 1]); + let key = |size: [u32; 2]| { + let threads = [size[0], size[1], 1]; + (state.dispatch_variant(groups, threads, &[], size)).expect("a key") + }; + let (small, large) = (key([4, 2]), key([4, 4])); + assert!(!small.1 && !large.1, "{name}: made before any dispatch"); + assert_ne!(small.0, large.0, "{name}: one key for two sizes"); + let wide = state.dispatch_variant(groups, [4, 2, 1], &[], [8, 2]); + assert_ne!( + wide.map(|(key, _)| key), + Some(small.0), + "{name}: one key for two sizes" + ); + let refused = state.dispatch_variant(groups, [4, 2, 1], &[], [3, 2]); + assert_eq!( + refused, None, + "{name}: a key for a size the encoder refuses" + ); + let before = device.counters().metrics(); + let mut arena = Arena::new(&device); + let (first, second) = (arena.buffer(), arena.buffer()); + let queue = device.new_command_queue(1).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = + (command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder"); + encoder + .set_compute_pipeline_state(&state) + .expect("the state"); + for (size, out) in [([4, 2], &first), ([4, 4], &second)] { + encoder.set_buffer(Some(out), 0, 0).expect("the buffer"); + encoder + .set_imageblock_size(size[0], size[1]) + .expect("a size"); + (encoder.dispatch_threadgroups([1, 1, 1], [size[0], size[1], 1])) + .unwrap_or_else(|error| panic!("{name}: the dispatch at {size:?}: {error}")); + } + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + assert_eq!( + words(&first, 32), + expected(4, 2), + "{name}: the 4 by 2 imageblock" + ); + assert_eq!( + words(&second, 64), + expected(4, 4), + "{name}: the 4 by 4 imageblock" + ); + let after = device.counters().metrics(); + let waits = |metrics: &crate::Metrics| { + ( + metrics.first_use_variant_waits, + metrics.first_use_unfinished_waits, + ) + }; + let ((variant, unfinished), (variant_before, unfinished_before)) = + (waits(&after), waits(&before)); + assert_eq!( + (variant - variant_before, unfinished - unfinished_before), + (2, 0), + "{name}: a pipeline made at each size's first use, and no main pipeline" + ); + assert!( + key([4, 2]).1 && key([4, 4]).1, + "{name}: each size's pipeline made" + ); + println!("{name}: one encoder ran its imageblock at 4 by 2 and at 4 by 4"); + }); + } + + /// The encoder refuses, as Metal's validation layer does (job m3-max-70002), an imageblock side + /// that is not a power of two, 0 included, and more than 1024 cells; it takes 1024 by 1 and 1 + /// by 1024. + #[test] + fn the_encoder_refuses_the_imageblock_sizes_metal_refuses() { + each_device("imageblock_refusals", |name, _, device| { + let queue = device.new_command_queue(1).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = + (command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder"); + for [width, height] in [[24, 16], [16, 12], [0, 0], [0, 4], [64, 32]] { + let refused = encoder.set_imageblock_size(width, height); + assert!( + matches!( + refused, + Err(Error::Refused(Refusal::ImageblockSize { width: w, height: h })) + if [w, h] == [width, height] + ), + "{name}: {width} by {height}: {refused:?}" + ); + } + for [width, height] in [[1024, 1], [1, 1024], [32, 32], [1, 1]] { + (encoder.set_imageblock_size(width, height)) + .unwrap_or_else(|error| panic!("{name}: {width} by {height}: {error}")); + } + encoder.end_encoding(); + }); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/kernel_input.rs b/crates/metal2vulkan-runtime/src/tests/kernel_input.rs deleted file mode 100644 index e04f3ddf6..000000000 --- a/crates/metal2vulkan-runtime/src/tests/kernel_input.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! A kernel that reads what the compute encoder does not supply is refused as `Gap::KernelInput` -//! of the kind the runtime found. The one kind an engine fixture's kernel meets on lavapipe is an -//! explicit imageblock's extent, whose state is made and whose dispatch is refused. No engine -//! fixture's kernel meets the other kinds there. - -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -mod on_device { - use crate::tests::command::on_device::each_device; - use crate::{ComputePipelineDescriptor, Error, FunctionDescriptor, Gap, KernelInputKind}; - use crate::{Dispatch, DispatchType, NumberedSampler, StageSource}; - use metal2vulkan::library::Library; - use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError}; - - /// The kernel `entry` of the engine fixture `fixture.ll`, or None where `llvm-as` is missing. - fn descriptor_of(fixture: &str, entry: &str) -> Option { - let bitcode = match llvm_assemble(&engine_dir().join(format!("{fixture}.ll"))) { - Ok(bitcode) => bitcode, - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - return None; - } - Err(error) => panic!("{fixture}: {error:?}"), - }; - let library = Library::from_air(&bitcode).expect("the library"); - let function = library.function(entry).expect("the kernel"); - Some(ComputePipelineDescriptor::new(StageSource::Function( - FunctionDescriptor::new(function), - ))) - } - - /// An index for each sampler the kernel numbers. - fn sampler_ids(samplers: &[NumberedSampler]) -> Result, Error> { - Ok((0..samplers.len() as u32).collect()) - } - - /// `a4_imageblock_extent`, a kernel over an explicit imageblock: its module states the - /// imageblock's size as a runtime fact, which the encoder does not supply (it has no - /// `setImageblockWidth:height:`). Its state is made, its imageblock length the typed gap; a - /// pre-pass gets no key of its dispatch, and the dispatch, one threadgroup of the kernel's 4 by - /// 2, is refused naming that fact. - #[test] - fn an_explicit_imageblock_kernel_is_made_and_its_dispatch_refused_as_its_named_runtime_fact() { - let Some(descriptor) = descriptor_of("a4_imageblock_extent", "a4_imageblock_extent") else { - return; - }; - let kind = KernelInputKind::RuntimeFact { - fact: "ImageblockSize", - }; - let (groups, threads) = ([1, 1, 1], [4, 2, 1]); - each_device("kernel_input_imageblock", |name, _, device| { - let state = (device.new_compute_pipeline_state(&descriptor, sampler_ids)) - .unwrap_or_else(|error| panic!("{name}: no state: {error}")); - let length = state.imageblock_memory_length_for_dimensions([8, 4, 3]); - assert!( - matches!(length, Err(Error::Unsupported(Gap::ImageblockLength))), - "{name}: the imageblock length {length:?}" - ); - let dispatch = Dispatch::Threadgroups(groups); - let key = state.dispatch_variant(dispatch, threads, &[]); - assert!(key.is_none(), "{name}: a pre-pass key {key:?}"); - let queue = device.new_command_queue(1).expect("a queue"); - let command_buffer = queue.command_buffer().expect("a command buffer"); - let mut encoder = - (command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder"); - encoder - .set_compute_pipeline_state(&state) - .expect("the state"); - match encoder.dispatch_threadgroups(groups, threads) { - Err(Error::Unsupported(Gap::KernelInput { kind: found })) => { - assert_eq!(found, kind, "{name}: the kind the dispatch found") - } - Ok(()) => panic!("{name}: a dispatch, where the encoder sets no imageblock extent"), - Err(error) => panic!("{name}: {error}, not Gap::KernelInput of {kind:?}"), - } - encoder.end_encoding(); - println!( - "{name}: the imageblock kernel's state made, its dispatch refused as {kind:?}" - ); - }); - } -} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 68e4718cb..9bd873e85 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -39,6 +39,7 @@ mod gpu_span; mod hazard; mod heap; mod image_reads; +mod imageblock; mod import; mod import_overs; mod import_time; @@ -46,7 +47,6 @@ mod imported_aliases; mod indirect; mod interpolation; mod kept; -mod kernel_input; mod kernel_map; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod kernels; diff --git a/crates/metal2vulkan-runtime/src/tests/sampling.rs b/crates/metal2vulkan-runtime/src/tests/sampling.rs index d8d77b961..60c6f868f 100644 --- a/crates/metal2vulkan-runtime/src/tests/sampling.rs +++ b/crates/metal2vulkan-runtime/src/tests/sampling.rs @@ -1012,7 +1012,7 @@ mod on_device { if prepared { let ahead = counters.metrics(); let threads = crate::Dispatch::Threads([grid[0], grid[1], depth]); - down.prepare_dispatch(threads, [4, 4, 1], &[]) + down.prepare_dispatch(threads, [4, 4, 1], &[], [1, 1]) .expect("made ahead"); let made = counters.metrics().made_ahead_variants - ahead.made_ahead_variants; assert_eq!( diff --git a/crates/metal2vulkan-runtime/src/tests/stage.rs b/crates/metal2vulkan-runtime/src/tests/stage.rs index 92a0a77aa..99a51fc45 100644 --- a/crates/metal2vulkan-runtime/src/tests/stage.rs +++ b/crates/metal2vulkan-runtime/src/tests/stage.rs @@ -480,15 +480,15 @@ mod on_device { // A later variant, an indirect dispatch's at its own threadgroup size, asks for a // fill of its own, and once filled is made from its entry, with a module of its own. let (dispatch, size) = (Dispatch::Indirect, [8, 1, 1]); - let later = match state.prepare_dispatch(dispatch, size, &[]) { + let later = match state.prepare_dispatch(dispatch, size, &[], [1, 1]) { Err(Error::StageUnfilled(later)) => later, other => panic!("{name}: {other:?}"), }; assert_ne!(later, request, "{name}: the later variant's pipeline"); fill(&later); - (state.prepare_dispatch(dispatch, size, &[])) + (state.prepare_dispatch(dispatch, size, &[], [1, 1])) .unwrap_or_else(|error| panic!("{name}: the later variant: {error}")); - let made = state.dispatch_variant(dispatch, size, &[]); + let made = state.dispatch_variant(dispatch, size, &[], [1, 1]); assert_eq!(made.map(|(_, made)| made), Some(true), "{name}"); let metrics = counters.metrics(); assert_eq!(metrics.stage_fills, 2, "{name}"); diff --git a/crates/metal2vulkan-runtime/src/tests/translate.rs b/crates/metal2vulkan-runtime/src/tests/translate.rs index 399fb27aa..ca286ad36 100644 --- a/crates/metal2vulkan-runtime/src/tests/translate.rs +++ b/crates/metal2vulkan-runtime/src/tests/translate.rs @@ -747,7 +747,7 @@ mod on_device { let lengths = [(0, length(size))]; let before = counters.metrics(); state - .prepare_dispatch(prepared, size, &lengths) + .prepare_dispatch(prepared, size, &lengths, [1, 1]) .expect("made ahead"); let ahead = counters.metrics(); assert_eq!( @@ -760,7 +760,7 @@ mod on_device { "{name}: {prepared:?} by {size:?}: what the call made" ); state - .prepare_dispatch(prepared, size, &lengths) + .prepare_dispatch(prepared, size, &lengths, [1, 1]) .expect("made ahead"); let again = counters.metrics(); assert_eq!( @@ -794,7 +794,7 @@ mod on_device { for ((grid, size, how), length, runs) in refusals { let before = counters.metrics(); state - .prepare_dispatch(Dispatch::Threads(grid), size, &[(0, length)]) + .prepare_dispatch(Dispatch::Threads(grid), size, &[(0, length)], [1, 1]) .expect("made ahead"); let ahead = counters.metrics(); assert_eq!( @@ -859,8 +859,9 @@ mod on_device { let from = next(&counters); let tiles = state(name, &device, &tiling); let make = one(name, counters.variant_makes(from), "the state's tiles"); - let key = (tiles.dispatch_variant(Dispatch::Threads([300, 1, 1]), [4, 1, 1], &[])) - .map(|(variant, _)| variant); + let key = + (tiles.dispatch_variant(Dispatch::Threads([300, 1, 1]), [4, 1, 1], &[], [1, 1])) + .map(|(variant, _)| variant); assert_eq!( (Some(make.variant), make.start, make.waits, make.first_wait), (key, VariantStart::Finish, 0, 0), @@ -873,10 +874,10 @@ mod on_device { let lengths = [(0, length(size))]; let from = next(&counters); state - .prepare_dispatch(Dispatch::Threads(grid), size, &lengths) + .prepare_dispatch(Dispatch::Threads(grid), size, &lengths, [1, 1]) .expect("made ahead"); let make = one(name, counters.variant_makes(from), "prepare_dispatch"); - let key = (state.dispatch_variant(Dispatch::Threads(grid), size, &lengths)) + let key = (state.dispatch_variant(Dispatch::Threads(grid), size, &lengths, [1, 1])) .map(|(variant, _)| variant); assert_eq!( (Some(make.variant), make.start, make.waits), @@ -897,8 +898,9 @@ mod on_device { .unwrap_or_else(|error| panic!("{name}: {error}")); let after = counters.metrics(); let make = one(name, counters.variant_makes(from), "the first use"); - let key = (state.dispatch_variant(Dispatch::Threadgroups(groups), size, &lengths)) - .map(|(variant, _)| variant); + let key = + (state.dispatch_variant(Dispatch::Threadgroups(groups), size, &lengths, [1, 1])) + .map(|(variant, _)| variant); assert_eq!( (Some(make.variant), make.start, make.waits), (key, VariantStart::FirstUse, 1), @@ -967,7 +969,7 @@ mod on_device { ) }; let tiles = |state: &ComputePipelineState| { - state.dispatch_variant(Dispatch::Threads([WIDE, 1, 1]), [GROUP, 1, 1], &[]) + state.dispatch_variant(Dispatch::Threads([WIDE, 1, 1]), [GROUP, 1, 1], &[], [1, 1]) }; // Every answer of the state, `dispatch_variant`'s key among them but not whether its // pipeline is made. @@ -1105,8 +1107,13 @@ mod on_device { }; // A preparation of a direct dispatch, which runs the tiles, the main pipeline. let prepare = |state: &ComputePipelineState, size: u32| { - (state.prepare_dispatch(Dispatch::Threads([WIDE, 1, 1]), [size, 1, 1], &[])) - .expect("prepared"); + (state.prepare_dispatch( + Dispatch::Threads([WIDE, 1, 1]), + [size, 1, 1], + &[], + [1, 1], + )) + .expect("prepared"); }; let state = unfinished(name, &device, &descriptor); @@ -1266,7 +1273,7 @@ mod on_device { let first = state(name, &device, &descriptor); type Entry<'a> = (Dispatch, [u32; 3], u32, &'a str); let key = |state: &ComputePipelineState, (dispatch, size, length, pipeline): Entry| { - (state.dispatch_variant(dispatch, size, &[(0, length)])) + (state.dispatch_variant(dispatch, size, &[(0, length)], [1, 1])) .map(|(variant, _)| variant) .unwrap_or_else(|| panic!("{name}: {pipeline}: {dispatch:?} by {size:?}")) }; @@ -1281,7 +1288,7 @@ mod on_device { for (&(dispatch, size, length, pipeline), variant) in table.iter().zip(&keys) { let before = counters.metrics(); first - .prepare_dispatch(dispatch, size, &[(0, length)]) + .prepare_dispatch(dispatch, size, &[(0, length)], [1, 1]) .expect("made ahead"); let after = counters.metrics(); let new = u64::from(met.insert(*variant)); @@ -1310,7 +1317,7 @@ mod on_device { ); let (dispatch, size, length, _) = entry; again - .prepare_dispatch(dispatch, size, &[(0, length)]) + .prepare_dispatch(dispatch, size, &[(0, length)], [1, 1]) .expect("made ahead"); } assert_eq!( @@ -1326,7 +1333,7 @@ mod on_device { let before = counters.metrics(); let (dispatch, at, bytes, _) = table[0]; other - .prepare_dispatch(dispatch, at, &[(0, bytes)]) + .prepare_dispatch(dispatch, at, &[(0, bytes)], [1, 1]) .expect("made ahead"); assert_eq!( counters.metrics().made_ahead_variants - before.made_ahead_variants, @@ -1340,7 +1347,7 @@ mod on_device { ]; for (dispatch, size, length) in refused { assert_eq!( - first.dispatch_variant(dispatch, size, &[(0, length)]), + first.dispatch_variant(dispatch, size, &[(0, length)], [1, 1]), None, "{name}: {dispatch:?} by {size:?} at {length}: no key" ); @@ -1371,13 +1378,13 @@ mod on_device { let mut keys = Vec::new(); for x in 1..=10 { let (size, lengths) = ([x, 1, 1], lengths(x)); - let (key, made) = (state.dispatch_variant(dispatch, size, &lengths)) + let (key, made) = (state.dispatch_variant(dispatch, size, &lengths, [1, 1])) .unwrap_or_else(|| panic!("{name}: {size:?}: no key")); assert!(!made, "{name}: {size:?}: made before its make"); state - .prepare_dispatch(dispatch, size, &lengths) + .prepare_dispatch(dispatch, size, &lengths, [1, 1]) .expect("made ahead"); - let answer = state.dispatch_variant(dispatch, size, &lengths); + let answer = state.dispatch_variant(dispatch, size, &lengths, [1, 1]); assert_eq!( answer, Some((key, true)), @@ -1389,7 +1396,7 @@ mod on_device { for (x, key) in (1..=10).zip(keys) { let (size, lengths) = ([x, 1, 1], lengths(x)); for state in [&state, &again] { - let answer = state.dispatch_variant(dispatch, size, &lengths); + let answer = state.dispatch_variant(dispatch, size, &lengths, [1, 1]); assert_eq!(answer, Some((key, true)), "{name}: {size:?}: all made"); } } @@ -1433,7 +1440,7 @@ mod on_device { let (groups, size) = ([3, 1, 1], [80, 1, 1]); let before = counters.metrics(); state - .prepare_dispatch(Dispatch::Threadgroups(groups), size, &[]) + .prepare_dispatch(Dispatch::Threadgroups(groups), size, &[], [1, 1]) .expect("made ahead"); let ahead = counters.metrics(); assert_eq!( @@ -1503,7 +1510,7 @@ mod on_device { How::Indirect => crate::Dispatch::Indirect, }; state - .prepare_dispatch(dispatch, size, &[(0, length)]) + .prepare_dispatch(dispatch, size, &[(0, length)], [1, 1]) .expect("made ahead"); } grid_template_run(name, device, &state, (grid, size, how), length) diff --git a/crates/metal2vulkan-validation/src/candidate/engine.rs b/crates/metal2vulkan-validation/src/candidate/engine.rs index b9c8e4107..640069d18 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine.rs @@ -132,6 +132,9 @@ pub struct ComputeCase { pub samplers: BTreeMap, /// `setThreadgroupMemoryLength:atIndex:`. pub threadgroup_lengths: BTreeMap, + /// `setImageblockWidth:height:`: the size of the case's explicit imageblock, none where it + /// sets none. + pub imageblock: Option<[u32; 2]>, pub dispatch: Dispatch, pub output: ComputeOutput, /// The case's out-of-bounds targets: each buffer target is allocated inside a guard of its @@ -389,6 +392,12 @@ pub fn compute_case(case: &AuthoredCase) -> Result { textures, samplers, threadgroup_lengths, + // An implicit imageblock's coverage is `KernelImageblock`, which the requirements refused + // above: what is left is an explicit imageblock's size. + imageblock: case + .imageblock + .as_ref() + .map(|imageblock| imageblock.dimensions), // `dispatch.grid` is in threads: the Metal oracle calls // `dispatchThreads:threadsPerThreadgroup:`. dispatch: Dispatch::Threads { diff --git a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs index bf0d403ac..612ee69f5 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs @@ -100,12 +100,19 @@ fn the_case_maps_or_names_the_gap() { case.fuel = Some(9); assert_eq!(map_kernel(&case).unwrap(), mapped); - // An explicit imageblock is the runtime's limit. + // An explicit imageblock's size is the run's; a tile pass's implicit one is the runtime's + // limit. let mut imageblock = kernel_case(); imageblock.imageblock = Some(crate::case::ImageblockResource { dimensions: [16, 8], implicit_coverage: None, }); + let sized = map_kernel(&imageblock).expect("an explicit imageblock's case"); + assert_eq!(sized.imageblock, Some([16, 8])); + if let Some(resource) = imageblock.imageblock.as_mut() { + resource.implicit_coverage = + Some(crate::case::ImplicitImageblockCoverage::FullSingleSample); + } assert_eq!( map_kernel(&imageblock), Err(NotSupported::Requirements( diff --git a/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs b/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs index d3c6c72a5..846717602 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs @@ -452,9 +452,11 @@ fn run( let state = made_within(|numbered| { device.new_compute_pipeline_state(&descriptor, |samplers| numbered(samplers)) })?; - // Every pipeline the dispatch runs, made before anything is submitted. + // Every pipeline the dispatch runs, made before anything is submitted, at the imageblock + // size the run sets, or Metal's 1 by 1 where it sets none. + let imageblock = case.imageblock.unwrap_or([1, 1]); state - .prepare_dispatch(dispatch, threads_per_group, &lengths) + .prepare_dispatch(dispatch, threads_per_group, &lengths, imageblock) .map_err(|error| ExecutorError::Failed(format!("the dispatch's pipeline: {error}")))?; let created = device .counters() @@ -1009,6 +1011,11 @@ fn dispatched( .set_threadgroup_memory_length(length, index) .map_err(fail("a threadgroup memory length"))?; } + if let Some([width, height]) = case.imageblock { + encoder + .set_imageblock_size(width, height) + .map_err(fail("the imageblock size"))?; + } match dispatch { rt::Dispatch::Threads(threads) => { encoder.dispatch_threads(threads, threads_per_group) diff --git a/crates/metal2vulkan-validation/src/candidate/tests/acceptance_pipelines.rs b/crates/metal2vulkan-validation/src/candidate/tests/acceptance_pipelines.rs index e0fe1ea92..378368e78 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/acceptance_pipelines.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/acceptance_pipelines.rs @@ -141,17 +141,15 @@ fn a_full_subgroup_kernel_row_is_made_through_the_runtime() { } } -/// A kernel with an explicit imageblock is the runtime's typed refusal at its dispatch, as a -/// guest's is: its compute encoder does not set an imageblock's extent -/// (`setImageblockWidth:height:`). +/// A kernel with an explicit imageblock is made and its representative threadgroup's pipeline +/// created, as a guest's is: a dispatch of an encoder that sets no imageblock size runs it 1 by 1, +/// as Metal's does. #[cfg(target_os = "linux")] #[test] -fn an_imageblock_kernel_row_is_the_runtimes_refusal() { - let made = made(&[("a4_imageblock_extent.ll", "a4_imageblock_extent")]).remove(0); - assert!( - matches!(&made, Acceptance::RuntimeRefused(why) if why.contains("mageblock")), - "{made:?}" - ); +fn an_imageblock_kernel_row_is_created_through_the_runtime() { + for made in made(&[("a4_imageblock_extent.ll", "a4_imageblock_extent")]) { + accepted(Ok(made)); + } } /// A post-tessellation vertex function's row is a tessellation pipeline (the synthesized vertex diff --git a/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs b/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs index cec7fb04d..e88c46368 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs @@ -90,6 +90,7 @@ pub(crate) fn case(entry: &str, buffer: Vec, dispatch: Dispatch) -> ComputeC textures: BTreeMap::new(), samplers: BTreeMap::new(), threadgroup_lengths: BTreeMap::new(), + imageblock: None, dispatch, output: ComputeOutput::Buffer { binding: 0, diff --git a/crates/metal2vulkan-validation/src/candidate/tests/engine_textures.rs b/crates/metal2vulkan-validation/src/candidate/tests/engine_textures.rs index 946c77d1e..6258b0950 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/engine_textures.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/engine_textures.rs @@ -76,6 +76,7 @@ fn kernel( .collect(), samplers: BTreeMap::new(), threadgroup_lengths: BTreeMap::new(), + imageblock: None, dispatch: Dispatch::Threads { threads, threads_per_group: [1, 1, 1], diff --git a/crates/metal2vulkan-validation/src/candidate/tests/gpu_fuzz.rs b/crates/metal2vulkan-validation/src/candidate/tests/gpu_fuzz.rs index 70997e11b..caeceb030 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/gpu_fuzz.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/gpu_fuzz.rs @@ -151,6 +151,7 @@ pub(super) mod device { textures: BTreeMap::new(), samplers: BTreeMap::new(), threadgroup_lengths: BTreeMap::new(), + imageblock: None, dispatch: Dispatch::Threads { threads: [kernel.threads, 1, 1], threads_per_group: [kernel.threads, 1, 1], diff --git a/crates/metal2vulkan-validation/src/candidate/tests/loop_exits.rs b/crates/metal2vulkan-validation/src/candidate/tests/loop_exits.rs index b5884db1b..be4970844 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/loop_exits.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/loop_exits.rs @@ -78,6 +78,7 @@ fn run(entry: &str, bitcode: &[u8], n: u32, limits: [u32; 2]) -> (Vec, usiz textures: BTreeMap::new(), samplers: BTreeMap::new(), threadgroup_lengths: BTreeMap::new(), + imageblock: None, dispatch: Dispatch::Threads { threads: [n, 1, 1], threads_per_group: [n, 1, 1], diff --git a/crates/metal2vulkan-validation/src/executor_contract.rs b/crates/metal2vulkan-validation/src/executor_contract.rs index 5ab091daa..7dc9f6edc 100644 --- a/crates/metal2vulkan-validation/src/executor_contract.rs +++ b/crates/metal2vulkan-validation/src/executor_contract.rs @@ -874,7 +874,9 @@ pub fn case_requirements(case: &AuthoredCase) -> BTreeSet { ToolingRequirement::SeparateDepthStencil, ), ( - kernel && case.imageblock.is_some(), + kernel + && (case.imageblock.as_ref()) + .is_some_and(|imageblock| imageblock.implicit_coverage.is_some()), ToolingRequirement::KernelImageblock, ), ( @@ -2940,8 +2942,8 @@ entry: assert_eq!(requirement.stops(), [Executor::EngineCandidate]); }; - // A kernel's imageblock, a tile function's implicit one or an explicit one, is the - // runtime's limit. + // A tile function's implicit imageblock is the runtime's limit; an explicit one, whose + // size the run sets, is none. let mut tile = kernel.clone(); tile.imageblock = Some(ImageblockResource { dimensions: [1, 1], @@ -2949,7 +2951,7 @@ entry: }); only(&tile, ToolingRequirement::KernelImageblock); tile.imageblock.as_mut().unwrap().implicit_coverage = None; - only(&tile, ToolingRequirement::KernelImageblock); + assert!(case_requirements(&tile).is_empty()); let opaque = IntersectionFunctionTableEntry::OpaqueTriangle { index: 0, diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/encoders.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/encoders.rs index fa5497399..e3c353ee5 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/encoders.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/encoders.rs @@ -344,6 +344,10 @@ impl NewRuntime { .encoder .set_threadgroup_memory_length(length, at) } + "setImageblockWidth:height:" => { + let (width, height) = (index(call, 0)?, index(call, 1)?); + self.compute(id).encoder.set_imageblock_size(width, height) + } "setStageInRegion:" => { let at = region(call, arg(call, 0)?)?; self.compute(id).encoder.set_stage_in_region(at); diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs index 81fc6ac1b..3ee0f5313 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs @@ -2548,7 +2548,8 @@ impl Backend for NewRuntime { AheadGrid::Threads(threads) => rt::Dispatch::Threads(threads), AheadGrid::Threadgroups(groups) => rt::Dispatch::Threadgroups(groups), }; - pool.give((state.clone(), grid, ahead.size, ahead.lengths)); + let (size, lengths) = (ahead.size, ahead.lengths); + pool.give((state.clone(), grid, size, lengths, ahead.imageblock)); } } diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/prepass.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/prepass.rs index 62950f208..205a77629 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/prepass.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/prepass.rs @@ -11,13 +11,14 @@ use std::sync::mpsc::{channel, Sender}; use std::sync::{Arc, Mutex, PoisonError}; use std::thread::JoinHandle; -/// A dispatch to prepare: its state, its grid, its threadgroup size and the encoder's threadgroup -/// memory lengths. +/// A dispatch to prepare: its state, its grid, its threadgroup size, the encoder's threadgroup +/// memory lengths and its imageblock size. pub(super) type Item = ( rt::ComputePipelineState, rt::Dispatch, [u32; 3], Vec<(u32, u32)>, + [u32; 2], ); /// The pre-pass's threads and their queue. @@ -43,7 +44,7 @@ impl Pool { let tally = Arc::clone(&tally); let run = move || loop { let next = (items.lock().unwrap_or_else(PoisonError::into_inner)).recv(); - let Ok((state, grid, size, lengths)) = next else { + let Ok((state, grid, size, lengths, imageblock)) = next else { return; }; if stop.load(Relaxed) { @@ -52,7 +53,7 @@ impl Pool { tally[0].fetch_add(1, SeqCst); // A kernel past the stage bound is refused at its dispatch too, which the // player reports as the dispatch's own error. - let _ = state.prepare_dispatch(grid, size, &lengths); + let _ = state.prepare_dispatch(grid, size, &lengths, imageblock); tally[1].fetch_add(1, SeqCst); }; let named = std::thread::Builder::new().name(format!("m2v-prepass-{at}")); diff --git a/crates/metal2vulkan-validation/src/replay/prepass.rs b/crates/metal2vulkan-validation/src/replay/prepass.rs index 97467ba51..351e0e8ae 100644 --- a/crates/metal2vulkan-validation/src/replay/prepass.rs +++ b/crates/metal2vulkan-validation/src/replay/prepass.rs @@ -1,24 +1,25 @@ //! The pre-pass a consumer that holds a whole command buffer runs before it encodes it, read -//! ahead: each compute dispatch's state, grid, threadgroup size and threadgroup memory lengths, -//! due at the stream position where such a consumer could first prepare it, once its command +//! ahead: each compute dispatch's state, grid, threadgroup size, threadgroup memory lengths and +//! imageblock size, due at the stream position where such a consumer could first prepare it, once its command //! buffer and its state are both made. The player hands each position's dispatches to the //! backend once that position's call has played (`Backend::prepare`), in stream order. A -//! dispatch the same as an earlier one of its state (the same grid, size and lengths) is not due -//! again: what it needs is prepared once. +//! dispatch the same as an earlier one of its state (the same grid, size, lengths and imageblock +//! size) is not due again: what it needs is prepared once. use super::stream::Call; use super::value::Value; use std::collections::{HashMap, HashSet}; /// A compute dispatch to prepare: its compute pipeline state's id, its grid as its call took it, -/// its threadgroup size, and the encoder's threadgroup memory lengths as (index, length) pairs, -/// each index once, in index order. +/// its threadgroup size, the encoder's threadgroup memory lengths as (index, length) pairs, each +/// index once, in index order, and the encoder's imageblock size (1 by 1 where it set none). #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Ahead { pub state: u64, pub grid: AheadGrid, pub size: [u32; 3], pub lengths: Vec<(u32, u32)>, + pub imageblock: [u32; 2], } /// A direct dispatch's grid, as its call took it. The player plays no indirect dispatch. @@ -54,6 +55,8 @@ struct Encoder { state: u64, /// The threadgroup memory lengths it set, as (index, length) pairs in index order. lengths: Vec<(u32, u32)>, + /// The imageblock size it set, 1 by 1 until it sets one. + imageblock: [u32; 2], } /// A size argument's three extents. @@ -93,6 +96,7 @@ impl Prepass { buffer, state: 0, lengths, + imageblock: [1, 1], }; self.encoders.insert(call.result, encoder); } @@ -120,6 +124,16 @@ impl Prepass { } } } + "setImageblockWidth:height:" => { + let get = |at: usize| { + (call.args.get(at)) + .and_then(Value::as_uint) + .and_then(|v| u32::try_from(v).ok()) + }; + if let (Some(width), Some(height)) = (get(0), get(1)) { + encoder.imageblock = [width, height]; + } + } "dispatchThreads:threadsPerThreadgroup:" | "dispatchThreadgroups:threadsPerThreadgroup:" => { let (Some(grid), Some(size)) = (size(call.args.first()), size(call.args.get(1))) @@ -127,7 +141,7 @@ impl Prepass { return; }; let (buffer, state) = (encoder.buffer, encoder.state); - let lengths = encoder.lengths.clone(); + let (lengths, imageblock) = (encoder.lengths.clone(), encoder.imageblock); let Some(&made) = self.states.get(&state) else { return; }; @@ -140,6 +154,7 @@ impl Prepass { grid, size, lengths, + imageblock, }; if self.seen.insert((made, ahead.clone())) { self.due.entry(buffer.max(made)).or_default().push(ahead); diff --git a/crates/metal2vulkan-validation/src/requirement.rs b/crates/metal2vulkan-validation/src/requirement.rs index ad291b650..78ae9127c 100644 --- a/crates/metal2vulkan-validation/src/requirement.rs +++ b/crates/metal2vulkan-validation/src/requirement.rs @@ -200,14 +200,10 @@ pub enum ToolingRequirement { /// structure, so no census row carries it. The Metal oracle draws it, so a case of it stays /// Metal-qualified ([`Self::qualifies_on_metal`]). SeparateDepthStencil, - /// A compute kernel's explicit imageblock (`executor_contract::case_requirements`), a tile - /// pass's tile size included. The runtime's compute encoder has no - /// `setImageblockWidth:height:`: it makes the pipeline state of a kernel that reaches an - /// imageblock, and refuses its dispatch as `metal2vulkan_runtime::Gap::KernelInput` of - /// `KernelInputKind::RuntimeFact` naming `ImageblockSize`, held on lavapipe by the runtime's - /// device test in `tests::kernel_input` - /// `an_explicit_imageblock_kernel_is_made_and_its_dispatch_refused_as_its_named_runtime_fact`; - /// it builds no tile function. Both are known gaps its README states. + /// A compute kernel's implicit imageblock, a tile pass's coverage of it + /// (`ImageblockResource::implicit_coverage`, `executor_contract::case_requirements`): the + /// runtime builds no tile function, a known gap its README states. An explicit imageblock is + /// none: the run sets its size (`ComputeCommandEncoder::set_imageblock_size`). KernelImageblock, /// A fragment function's imageblock, the case's cells of it /// (`executor_contract::case_requirements`). The runtime refuses a fragment function with an diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 0666a10fc..2d6fa59d2 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -5911,6 +5911,7 @@ method metal2vulkan-runtime::ComputeCommandEncoder::set_buffer pub fn set_buffer method metal2vulkan-runtime::ComputeCommandEncoder::set_buffer_offset pub fn set_buffer_offset(&mut self, offset: u64, index: u32) -> Result<(), Error> method metal2vulkan-runtime::ComputeCommandEncoder::set_bytes pub fn set_bytes(&mut self, bytes: &[u8], index: u32) -> Result<(), Error> method metal2vulkan-runtime::ComputeCommandEncoder::set_compute_pipeline_state pub fn set_compute_pipeline_state(&mut self, state: &ComputePipelineState) -> Result<(), Error> +method metal2vulkan-runtime::ComputeCommandEncoder::set_imageblock_size pub fn set_imageblock_size(&mut self, width: u32, height: u32) -> Result<(), Error> method metal2vulkan-runtime::ComputeCommandEncoder::set_sampler_state pub fn set_sampler_state(&mut self, sampler: Option<&SamplerState>, index: u32) -> Result<(), Error> method metal2vulkan-runtime::ComputeCommandEncoder::set_sampler_state_with_lod_clamps pub fn set_sampler_state_with_lod_clamps(&mut self, sampler: Option<&SamplerState>, lod_min_clamp: f32, lod_max_clamp: f32, index: u32) -> Result<(), Error> method metal2vulkan-runtime::ComputeCommandEncoder::set_stage_in_region pub fn set_stage_in_region(&mut self, region: Region) @@ -5927,14 +5928,14 @@ method metal2vulkan-runtime::ComputePipelineDescriptor::new pub fn new(kernel: S method metal2vulkan-runtime::ComputePipelineDescriptor::reflection pub fn reflection(&self, budget: &crate::Budget) -> Result method metal2vulkan-runtime::ComputePipelineDescriptor::slot_writes pub fn slot_writes(&self, budget: &crate::Budget) -> Result method metal2vulkan-runtime::ComputePipelineState::buffer_accesses pub fn buffer_accesses(&self) -> Vec<(u32, BindingAccess)> -method metal2vulkan-runtime::ComputePipelineState::dispatch_variant pub fn dispatch_variant(&self, dispatch: Dispatch, threads_per_threadgroup: [u32; 3], threadgroup_memory_lengths: &[(u32, u32)]) -> Option<(DispatchVariant, bool)> +method metal2vulkan-runtime::ComputePipelineState::dispatch_variant pub fn dispatch_variant(&self, dispatch: Dispatch, threads_per_threadgroup: [u32; 3], threadgroup_memory_lengths: &[(u32, u32)], imageblock_size: [u32; 2]) -> Option<(DispatchVariant, bool)> method metal2vulkan-runtime::ComputePipelineState::finish_pipeline pub fn finish_pipeline(&self) -> Result<(), Error> method metal2vulkan-runtime::ComputePipelineState::function_handle pub fn function_handle(&self, function: &LinkedFunction) -> Option method metal2vulkan-runtime::ComputePipelineState::imageblock_memory_length_for_dimensions pub fn imageblock_memory_length_for_dimensions(&self, _dimensions: [u32; 3]) -> Result method metal2vulkan-runtime::ComputePipelineState::max_total_threads_per_threadgroup pub fn max_total_threads_per_threadgroup(&self) -> u32 method metal2vulkan-runtime::ComputePipelineState::new_visible_function_table pub fn new_visible_function_table(&self, descriptor: &VisibleFunctionTableDescriptor) -> Result method metal2vulkan-runtime::ComputePipelineState::precision_notes pub fn precision_notes(&self) -> Vec -method metal2vulkan-runtime::ComputePipelineState::prepare_dispatch pub fn prepare_dispatch(&self, dispatch: Dispatch, threads_per_threadgroup: [u32; 3], threadgroup_memory_lengths: &[(u32, u32)]) -> Result<(), Error> +method metal2vulkan-runtime::ComputePipelineState::prepare_dispatch pub fn prepare_dispatch(&self, dispatch: Dispatch, threads_per_threadgroup: [u32; 3], threadgroup_memory_lengths: &[(u32, u32)], imageblock_size: [u32; 2]) -> Result<(), Error> method metal2vulkan-runtime::ComputePipelineState::required_threads_per_threadgroup pub fn required_threads_per_threadgroup(&self) -> [u32; 3] method metal2vulkan-runtime::ComputePipelineState::static_threadgroup_memory_length pub fn static_threadgroup_memory_length(&self) -> u32 method metal2vulkan-runtime::ComputePipelineState::support_indirect_command_buffers pub fn support_indirect_command_buffers(&self) -> bool @@ -8567,6 +8568,7 @@ variant metal2vulkan-runtime::Refusal::FillRange FillRange { start: u64, end: u6 variant metal2vulkan-runtime::Refusal::FunctionTableIndex FunctionTableIndex { index: u64, count: u32 } variant metal2vulkan-runtime::Refusal::HeapBufferPlace HeapBufferPlace { offset: u64, length: u64, heap_len: u64 } variant metal2vulkan-runtime::Refusal::HeapTexturePlace HeapTexturePlace { offset: u64, size: u64, align: u64, heap_len: u64 } +variant metal2vulkan-runtime::Refusal::ImageblockSize ImageblockSize { width: u32, height: u32 } variant metal2vulkan-runtime::Refusal::InScheduledHandler InScheduledHandler variant metal2vulkan-runtime::Refusal::IndexBufferOffset IndexBufferOffset { offset: u64, length: u64 } variant metal2vulkan-runtime::Refusal::IndicesGranted IndicesGranted { class: IndexClass, index: u32 } diff --git a/docs/METAL-COVERAGE.md b/docs/METAL-COVERAGE.md index 8e22702ae..f626d007d 100644 --- a/docs/METAL-COVERAGE.md +++ b/docs/METAL-COVERAGE.md @@ -10,12 +10,12 @@ Every public item of the macOS 27.2 SDK (Xcode 27.2, 27B52)'s Metal headers, by | Status | Items | Of which deprecated | |---|---|---| -| implemented | 636 | 29 | -| missing | 1075 | 34 | +| implemented | 637 | 29 | +| missing | 1074 | 34 | | out of scope | 424 | 5 | | all | 2135 | 68 | -Implemented by the runtime: 279; by the translator's values: 357. Missing by size: S 182, M 204, L 313, XL 376. +Implemented by the runtime: 280; by the translator's values: 357. Missing by size: S 182, M 203, L 313, XL 376. ## Missing, in build order @@ -33,7 +33,7 @@ Cheap items a plain app calls first, then medium pieces by how often a plain app | a buffer made with bytes | S | 1 | `MTLDevice.newBufferWithBytes:length:options:` | | pipeline creation forms (from a function, with a completion handler) | S | 6 | `MTLDevice.newRenderPipelineStateWithDescriptor:options:completionHandler:`, `MTLDevice.newComputePipelineStateWithFunction:error:`, `MTLDevice.newComputePipelineStateWithFunction:options:reflection:error:`, ... | | render pass descriptor fields | S/M/L | 8 | `MTLRenderPassAttachmentDescriptor.depthPlane`, `MTLRenderPassAttachmentDescriptor.storeActionOptions`, `MTLRenderPassDescriptor.imageblockSampleLength`, ... | -| encoder calls (stride setters, indirect draws, store action options, a render encoder's heap uses) | S/M/L | 24 | `MTLBlitCommandEncoder.synchronizeTexture:slice:level:`, `MTLBlitCommandEncoder.copyFromTexture:sourceSlice:sourceLevel:toTexture:destinationSlice:destinationLevel:sliceCount:levelCount:`, `MTLBlitCommandEncoder.copyFromTexture:toTexture:`, ... | +| encoder calls (stride setters, indirect draws, store action options, a render encoder's heap uses) | S/M/L | 23 | `MTLBlitCommandEncoder.synchronizeTexture:slice:level:`, `MTLBlitCommandEncoder.copyFromTexture:sourceSlice:sourceLevel:toTexture:destinationSlice:destinationLevel:sliceCount:levelCount:`, `MTLBlitCommandEncoder.copyFromTexture:toTexture:`, ... | | `textureBarrier` and queue-stage barriers | S/M | 2 | `MTLCommandEncoder.barrierAfterQueueStages:beforeStages:`, `MTLRenderCommandEncoder.textureBarrier` | | a pipeline state's reflection after creation | S | 2 | `MTLComputePipelineState.reflection`, `MTLRenderPipelineState.reflection` | | function handles by name, and a handle's type and ID | S | 6 | `MTLComputePipelineState.functionHandleWithName:`, `MTLFunctionHandle.functionType`, `MTLFunctionHandle.name`, ... | @@ -1243,7 +1243,7 @@ Cheap items a plain app calls first, then medium pieces by how often a plain app | `MTLComputeCommandEncoder.setSamplerState:lodMinClamp:lodMaxClamp:atIndex:` | method | implemented | `ComputeCommandEncoder::set_sampler_state` (runtime) | | `MTLComputeCommandEncoder.setSamplerStates:lodMinClamps:lodMaxClamps:withRange:` | method | implemented | `ComputeCommandEncoder::set_sampler_state_with_lod_clamps` (runtime): a loop of it | | `MTLComputeCommandEncoder.setThreadgroupMemoryLength:atIndex:` | method | implemented | `ComputeCommandEncoder::set_threadgroup_memory_length` (runtime) | -| `MTLComputeCommandEncoder.setImageblockWidth:height:` | method | missing | M: explicit imageblocks; a kernel that reaches one is made and its dispatch refused (`Gap::KernelInput`) | +| `MTLComputeCommandEncoder.setImageblockWidth:height:` | method | implemented | `ComputeCommandEncoder::set_imageblock_size` (runtime): a specialization: a new size makes a pipeline at its first dispatch | | `MTLComputeCommandEncoder.setStageInRegion:` | method | implemented | `ComputeCommandEncoder::set_stage_in_region` (runtime) | | `MTLComputeCommandEncoder.setStageInRegionWithIndirectBuffer:indirectBufferOffset:` | method | implemented | `ComputeCommandEncoder::set_stage_in_region_with_indirect_buffer` (runtime): always refused: a stage-in region the GPU reads is not built (`Gap::StageIn`) | | `MTLComputeCommandEncoder.dispatchThreadgroups:threadsPerThreadgroup:` | method | implemented | `ComputeCommandEncoder::dispatch_threadgroups` (runtime) | diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index bc03c3525..691520271 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -31,7 +31,7 @@ Columns: | Rate maps the compile layer does not compile | 5 | 5 | 0 | 0 | 4 | 1 | 0 | | The translation deadline | 1 | 1 | 0 | 0 | 0 | 1 | 0 | | Devices below the runtime's floor | 8 | 8 | 0 | 0 | 0 | 0 | 0 | -| The runtime's `Refusal` | 84 | 84 | 0 | 0 | 0 | 0 | 0 | +| The runtime's `Refusal` | 85 | 85 | 0 | 0 | 0 | 0 | 0 | | The runtime's `Limit` | 17 | 17 | 0 | 0 | 0 | 0 | 0 | | The runtime's `Gap` | 32 | 32 | 0 | 0 | 0 | 0 | 0 | @@ -44,7 +44,7 @@ Columns: | Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 5 | 0 | 0 | 0 | | The translation deadline | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | | Devices below the runtime's floor | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 0 | -| The runtime's `Refusal` | 22 | 25 | 0 | 0 | 37 | 0 | 0 | 0 | +| The runtime's `Refusal` | 23 | 25 | 0 | 0 | 37 | 0 | 0 | 0 | | The runtime's `Limit` | 0 | 0 | 0 | 13 | 4 | 0 | 0 | 0 | | The runtime's `Gap` | 0 | 0 | 0 | 3 | 29 | 0 | 0 | 0 | @@ -256,6 +256,7 @@ Columns: | `SamplerIds` | A consumer's answer to `Device::new_compute_pipeline_state`'s numbered samplers with another count of indices | every device (a public call's own check of its arguments) | `ours`: each numbered sampler takes one index | 1: `crates/metal2vulkan-runtime/src/pipeline.rs (number_samplers)` | `-` | | `NoBufferAtIndex` | `setBufferOffset` at an index where no buffer is bound, or a draw whose vertex descriptor reads a vertex buffer index where none is bound | every device (a public call's own check of its arguments) | `ours`: there is no buffer whose offset to change, and none whose vertices the draw reads; Metal's validation stops such a draw | 3: `crates/metal2vulkan-runtime/src/encoder.rs (set_buffer_offset)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (find)` (+1) | `-` | | `ThreadgroupSize` | A threadgroup of no threads, or of more than Metal's `maxTotalThreadsPerThreadgroup` for the kernel (a required size's threads, where the... | every device (a public call's own check of its arguments) | `metal-documented`: a threadgroup's threads total at most the state's `maxTotalThreadsPerThreadgroup` | 2: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)`, `crates/metal2vulkan-runtime/src/encoder.rs (size_checked)` | `-` | +| `ImageblockSize` | An imageblock size (`ComputeCommandEncoder::set_imageblock_size`) whose width or height is not a power of two, 0 included, or whose cells are more... | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1, probe `imageblock_size_rules.m` in the conformance crate, job m3-max-70002: Metal's validation layer stops each at the call, `width(24) must be a power of 2.`, `height(12) must be a power of 2.`, `width(0) must be a power of 2.` and `width(64)*height(32) must be less than or equal to 1024`; it takes 16 by 16, 1024 by 1, 1 by 1024, 16 by 16 for a state of 64 threads, and a size set before the pipeline state | 1: `crates/metal2vulkan-runtime/src/encoder.rs (imageblock_checked)` | `-` | | `IndirectOffset` | An indirect dispatch's or draw's argument offset that is not a multiple of 4, which Metal's `indirectBufferOffset` must be... | every device (a public call's own check of its arguments) | `metal-documented`: MTLComputeCommandEncoder.h for `dispatchThreadgroupsWithIndirectBuffer:indirectBufferOffset:threadsPerThreadgroup:`, and MTLRenderCommandEncoder.h for the indirect `drawPrimitives` and `drawIndexedPrimitives`: "indirectBufferOffset must be a multiple of 4"; Apple's page for the indirect `drawPatches` sends its offset to the feature set tables, whose minimum constant buffer offset alignment is 4 bytes | 2: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (indirect)` | `-` | | `IndirectArgumentsPastEnd` | An indirect dispatch's or draw's arguments, at an offset that is a multiple of 4, that run past the buffer's end | every device (a public call's own check of its arguments) | `ours`: `vkCmdDispatchIndirect`, `vkCmdDrawIndirect` and `vkCmdDrawIndexedIndirect` read their arguments inside the buffer, `VUID-vkCmdDispatchIndirect-offset-00407`, `VUID-vkCmdDrawIndirect-drawCount-00487` and `VUID-vkCmdDrawIndexedIndirect-drawCount-00539` | 2: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (indirect)` | `-` | | `BufferOffsetAlignment` | A dispatch whose kernel, or a draw whose vertex or fragment function, reaches a buffer bound where its address, the buffer's `gpuAddress` plus the... | every device (a public call's own check of its arguments) | `metal-documented`: Metal's API validation refuses the bind offset: "must be a multiple of 4 but was set to 2" for a `uint *` argument bound at offset 2, an Apple M3 Max, macOS 27.0.1, `probes/vector_access_placement.m` in the conformance crate | 1: `crates/metal2vulkan-runtime/src/encoder.rs (check_alignment)` | `-` | @@ -546,6 +547,7 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::SamplerIds`: `crates/metal2vulkan-runtime/src/pipeline.rs (number_samplers)` - `rt:Refusal::NoBufferAtIndex`: `crates/metal2vulkan-runtime/src/encoder.rs (set_buffer_offset)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (find)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_buffer_offset)` - `rt:Refusal::ThreadgroupSize`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)`; `crates/metal2vulkan-runtime/src/encoder.rs (size_checked)` +- `rt:Refusal::ImageblockSize`: `crates/metal2vulkan-runtime/src/encoder.rs (imageblock_checked)` - `rt:Refusal::IndirectOffset`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (indirect)` - `rt:Refusal::IndirectArgumentsPastEnd`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (indirect)` - `rt:Refusal::BufferOffsetAlignment`: `crates/metal2vulkan-runtime/src/encoder.rs (check_alignment)` diff --git a/scripts/metal-coverage/coverage.tsv b/scripts/metal-coverage/coverage.tsv index 4386c8556..49d8db9ef 100644 --- a/scripts/metal-coverage/coverage.tsv +++ b/scripts/metal-coverage/coverage.tsv @@ -932,7 +932,7 @@ MTLComputeCommandEncoder.h MTLComputeCommandEncoder method setSamplerStates:with MTLComputeCommandEncoder.h MTLComputeCommandEncoder method setSamplerState:lodMinClamp:lodMaxClamp:atIndex: I runtime ComputeCommandEncoder::set_sampler_state MTLComputeCommandEncoder.h MTLComputeCommandEncoder method setSamplerStates:lodMinClamps:lodMaxClamps:withRange: I runtime ComputeCommandEncoder::set_sampler_state_with_lod_clamps a loop of it MTLComputeCommandEncoder.h MTLComputeCommandEncoder method setThreadgroupMemoryLength:atIndex: I runtime ComputeCommandEncoder::set_threadgroup_memory_length -MTLComputeCommandEncoder.h MTLComputeCommandEncoder method setImageblockWidth:height: M explicit imageblocks; a kernel that reaches one is made and its dispatch refused (`Gap::KernelInput`) M encoder-calls +MTLComputeCommandEncoder.h MTLComputeCommandEncoder method setImageblockWidth:height: I runtime ComputeCommandEncoder::set_imageblock_size a specialization: a new size makes a pipeline at its first dispatch MTLComputeCommandEncoder.h MTLComputeCommandEncoder method setStageInRegion: I runtime ComputeCommandEncoder::set_stage_in_region MTLComputeCommandEncoder.h MTLComputeCommandEncoder method setStageInRegionWithIndirectBuffer:indirectBufferOffset: I runtime ComputeCommandEncoder::set_stage_in_region_with_indirect_buffer always refused: a stage-in region the GPU reads is not built (`Gap::StageIn`) MTLComputeCommandEncoder.h MTLComputeCommandEncoder method dispatchThreadgroups:threadsPerThreadgroup: I runtime ComputeCommandEncoder::dispatch_threadgroups