From b42ef61b9badb29a5e6bb912c357b8bea150d64c Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 25 Nov 2026 19:05:48 -0800 Subject: [PATCH] Runtime: a buffer bound at a multiple of 4 below its argument's alignment runs the state's variant that holds it to 4 What: a dispatch's alignment check (check_alignments) no longer refuses a buffer whose argument's alignment is 8 or 16 (mask past 3) bound at a multiple of 4 below it: it answers the mask of those slots, bit i slot i. A non-empty mask picks the state's variant (PipelineInner::variant, srgbwrite's sRGB variant generalised to both masks): Compiled::of lowers the state's function with those slots in LoweringInputs::word_bound_buffers, kept in the device's bounded map of contents under KernelKey's new words mask (1,024 entries), held by the command buffer that dispatched it. The dispatch then checks the variant's own alignments strictly, so a buffer a 64-bit atomic may reach, which the variant holds to 8, is refused off a multiple of 8. A kernel the consumer compiled has no variant: its own module's strict check refuses the bind as before. One bit per slot: a second class (8 at a multiple of 8) would need a second mask in the key and the input. Still refused: an address off a multiple of 4 (off 2 for an alignment of 2), a 64-bit atomic's buffer off a multiple of 8, every draw's (render_encoder keeps the strict check_alignment: the draw side would need the render path's variant key), and a consumer-compiled kernel's. Refusal::BufferOffsetAlignment's doc says so; its message and `alignment` now name the alignment the function holds the address to, as the variant's 8 for a 16-aligned argument is not the argument's. The buffer-bind-off-alignment ledger row carries the new message; docs/CONFORMANCE-COVERAGE.md regenerated (unchanged); REFUSALS.md regenerated (unchanged: its row takes the doc's first words). Why: a guest's system texture-decode kernel (library db82b13f114fbeef #0) binds buffer 0 at offset 1871700 (4 mod 16) under a 16-byte argument alignment and met the refusal 60 and 72 times in two sessions; plain Metal runs it with each element at its own address. Only such a dispatch runs the variant: an empty mask keeps the state's key, hash and module. Tests (not yet run): translate.rs every_device_places_each_vector_access_at_its_own_address runs vwp_vec16 at VEC16_AT_WORDS too, holds Metal's words, and asserts a variant lowered exactly at the runs off a multiple of 16; every_device_keeps_a_word_bound_variant_in_the_bounded_map_of_contents (cap 2: one variant a mask, kept, the map at its cap, a forgotten one lowered again); an_argument_bound_off_its_alignment_is_refused binds vwp_vec16 2 and 3 bytes off (alignment 16). compute.rs's for_test kernel still refuses all 17 binds (no variant to lower). Docs: the runtime README's compute-encoder rule and a known gap of pipeline states (the relaxed form, with the unconditional build's 3090 constant_* rows), docs/API.md sections 1 and 10. --- .../known-gaps-rt.tsv | 2 +- crates/metal2vulkan-runtime/README.md | 12 +- crates/metal2vulkan-runtime/src/command.rs | 4 +- crates/metal2vulkan-runtime/src/encoder.rs | 70 ++++++--- crates/metal2vulkan-runtime/src/error.rs | 17 ++- crates/metal2vulkan-runtime/src/kernel_map.rs | 6 +- crates/metal2vulkan-runtime/src/pipeline.rs | 55 ++++--- crates/metal2vulkan-runtime/src/render.rs | 1 + .../metal2vulkan-runtime/src/tests/compute.rs | 4 +- .../src/tests/kernel_map.rs | 1 + .../src/tests/translate.rs | 134 ++++++++++++++++-- docs/API.md | 13 +- 12 files changed, 252 insertions(+), 67 deletions(-) diff --git a/crates/metal2vulkan-conformance/known-gaps-rt.tsv b/crates/metal2vulkan-conformance/known-gaps-rt.tsv index 40be702c8..58a8d1cf3 100644 --- a/crates/metal2vulkan-conformance/known-gaps-rt.tsv +++ b/crates/metal2vulkan-conformance/known-gaps-rt.tsv @@ -3232,7 +3232,7 @@ half-output-blends-rgba32f RX 550 divergent case/blended/sas-1msa 20 elements di # and no stream uses (a volume plane as an attachment, a resolve, an extended-range format), a # bind Metal's own validation refuses, and a getter of the consumer's. buffer-bind-off-alignment * refused case/outcome/dispatch_type Err(TheConsumers("an encoder's dispatchType is the argument it was made with: metal2vulkan-runtime keeps no getter and leaves it to its consumer")) refused: the consumer's own (dispatchType) -buffer-bind-off-alignment * refused case/outcome/step/3/dispatchThreadgroups Err(Error::Refused("the buffer at index 0, bound at offset 2, is not at a multiple of its argument's 4-byte alignment")) Metal itself refuses the bind: its API validation stops the pass ("Compute Function(vwp_words): the offset into the buffer src that is bound at Buffer index 0 must be a multiple of 4 but was set to 2", the recording's validated fact), where plain Metal ran it (Ok). rt refuses the dispatch as Metal's validation does (docs/API.md section 10, "A dispatch that reaches a buffer bound off its argument's alignment is refused"). +buffer-bind-off-alignment * refused case/outcome/step/3/dispatchThreadgroups Err(Error::Refused("the buffer at index 0, bound at offset 2, is not at a multiple of 4 bytes, the alignment its function holds it to")) Metal itself refuses the bind: its API validation stops the pass ("Compute Function(vwp_words): the offset into the buffer src that is bound at Buffer index 0 must be a multiple of 4 but was set to 2", the recording's validated fact), where plain Metal ran it (Ok). rt refuses the dispatch as Metal's validation does (docs/API.md section 10, "A dispatch that reaches a buffer bound off its argument's alignment is refused"). xr-clear-routes-bgr10xr * refused case/plain-16/target/0 Err(Error::Unsupported("no texture of BGR10XR is made on this device for the usage")) refused: no stream uses it yet (every-stream census 11-19, m3-max-51200..51246: 17 streams, no extended-range texture, drawable or layer). The translator holds `BGR10XR` raw in R32_UINT, its texels decoded and encoded in the shader (FormatEmulation::ExtendedRange), and rt's texture refuses that emulation (its identity domains make no extended-range conversion) before the device's format query is asked: the device is not asked about the integer format. xr-clear-routes-bgr10xr-srgb * refused case/plain-16/target/0 Err(Error::Unsupported("no texture of BGR10XRSRGB is made on this device for the usage")) refused: no stream uses it yet (every-stream census 11-19, m3-max-51200..51246: 17 streams, no extended-range texture, drawable or layer). The translator holds `BGR10XRSRGB` raw in R32_UINT, its texels decoded and encoded in the shader (FormatEmulation::ExtendedRange), and rt's texture refuses that emulation (its identity domains make no extended-range conversion) before the device's format query is asked: the device is not asked about the integer format. xr-clear-routes-bgra10xr * refused case/plain-16/target/0 Err(Error::Unsupported("no texture of BGRA10XR is made on this device for the usage")) refused: no stream uses it yet (every-stream census 11-19, m3-max-51200..51246: 17 streams, no extended-range texture, drawable or layer). The translator holds `BGRA10XR` raw in R16G16B16A16_UINT, its texels decoded and encoded in the shader (FormatEmulation::ExtendedRange), and rt's texture refuses that emulation (its identity domains make no extended-range conversion) before the device's format query is asked: the device is not asked about the integer format. diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index fc1fa0f84..ea1a0528b 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2742,7 +2742,13 @@ while the driver's exit handler waited on a lock, with every runtime thread alre offset, is not a multiple of the kernel argument's alignment (`air.arg_type_align_size`, at most 16) is refused (`Refusal::BufferOffsetAlignment`) before anything is recorded, as Metal's API validation refuses the bind offset. Plain Metal runs such a dispatch at addresses of its - own; `docs/API.md` section 10 says which. + own; `docs/API.md` section 10 says which. A function kernel's argument of 8- or 16-byte + alignment bound at a multiple of 4 is not refused: plain Metal reaches each element at its own + address there, and the dispatch runs the state's variant that holds those buffers to 4 + (`LoweringInputs::word_bound_buffers`), lowered at its first such dispatch and kept in the + device's map of contents under the state's key with the mask of those slots. The variant + holds a buffer a 64-bit atomic may reach to 8, and refuses it off a multiple of 8. A kernel the + consumer compiled has no variant and refuses such a bind; a draw refuses it too. - Parameters: fields in the push window, `[0, W)`, are pushed, `W` the device's `maxPushConstantsSize` up to 256 bytes (`DeviceProfile::push_window`: 256 on every lab device, 128 on a device that reports Vulkan's least): the dispatch region and up to 24 buffer addresses @@ -3563,6 +3569,10 @@ cache is answered compile-required on both. ### Known gaps of pipeline states +- A kernel bound below its argument's alignment (an argument of 8 or 16 bytes at a multiple of 4) + runs a relaxed form of the kernel, whose accesses of that buffer claim 4-byte alignment. A + build that took that form for every such argument, bound so or not, ran the harness's four + `constant_*` rows on an RTX 3090 in 234-252 us against 99-122 us (job 74651). - A driver's create of a state's main pipeline can fail after the state has answered, where Metal compiles the state before it answers and a program never meets a state it was given that cannot run. Vulkan lets `vkCreateComputePipelines` and `vkCreateGraphicsPipelines` fail with diff --git a/crates/metal2vulkan-runtime/src/command.rs b/crates/metal2vulkan-runtime/src/command.rs index a539a8fca..a38ff20f4 100644 --- a/crates/metal2vulkan-runtime/src/command.rs +++ b/crates/metal2vulkan-runtime/src/command.rs @@ -1480,8 +1480,8 @@ impl Building { self.gpu.kept.variants.hold(variant); } - /// Keeps `content`, a kernel's sRGB variant that a dispatch runs, until the command buffer - /// retires: no state holds it (`PipelineInner::srgb_variant`). + /// Keeps `content`, a kernel's variant that a dispatch runs, until the command buffer + /// retires: no state holds it (`PipelineInner::variant`). pub(crate) fn hold_content(&mut self, content: &Arc) { self.gpu.kept.contents.hold(content); } diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 23ed2e5bf..e9985eb50 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -303,10 +303,11 @@ struct DispatchFacts { /// ([`FieldValue::TextureLevels`], [`FieldValue::TextureLevelBase`]), found with the /// alignments. levels: bool, - /// The state's sRGB variant the dispatch runs, where a texture slot its kernel writes and - /// does not read is bound to an 8-bit sRGB texture's UNORM twin - /// ([`TextureObject::encodes`]), found with the alignments. - srgb: Option>, + /// The state's variant the dispatch runs, where a texture slot its kernel writes and does not + /// read is bound to an 8-bit sRGB texture's UNORM twin ([`TextureObject::encodes`]), or a + /// buffer slot at a multiple of 4 below its argument's alignment ([`check_alignments`]), + /// found with the alignments. + variant: Option>, } /// Which of its state's modules a dispatch runs. @@ -972,8 +973,10 @@ impl ComputeCommandEncoder { /// /// Err: [`Refusal::NoPipeline`]; [`Refusal::ThreadgroupSize`] past Metal's limit for the /// 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`]; + /// [`Refusal::BufferOffsetAlignment`] for a buffer the kernel reaches bound off the alignment + /// its function holds it to, which nothing records (a function kernel's argument of 8 or 16 + /// bound at a multiple of 4 runs on its kernel's variant that holds it to 4); + /// [`Gap::SwizzledReadWrite`]; [`Gap::BicubicTexels`]; /// [`Limit::LevelElements`] where no run of level elements holds a texture of several levels /// the kernel writes or reads at a level other than the constant 0; /// [`Limit::ThreadgroupMemory`], the imageblock's cells at the size @@ -1082,9 +1085,12 @@ impl ComputeCommandEncoder { let max = inner.whole.interface.max_total_threads; size_checked(&inner.whole.interface, size)?; // Every module of a state is the same function, with the same arguments and alignments, - // so the whole module answers this check and the next, once after each change. + // so the whole module answers this check and the next, once after each change; a buffer + // bound at a multiple of 4 below its argument's alignment is the variant's below. if !self.facts.aligned { - self.facts.nil = check_alignments(&self.core, &self.slots, &inner.whole.interface)?; + let (nil, words) = + check_alignments(&self.core, &self.slots, &inner.whole.interface, true)?; + self.facts.nil = nil; for &slot in &inner.whole.interface.storage_reads { if matches!(self.textures.get(slot as usize), Some(Some(t)) if t.swizzled()) { return Err(Error::Unsupported(Gap::SwizzledReadWrite { slot })); @@ -1137,11 +1143,24 @@ impl ComputeCommandEncoder { return Err(element(slot, gap)); } } - self.facts.srgb = match first { - None => None, - Some((slot, gap)) => match state.srgb_variant(srgb) { - Some(variant) => Some(variant?), - None => return Err(element(slot, gap)), + // The variant of those slots and of the buffers bound at a multiple of 4 below their + // argument's alignment, which holds each to what its accesses need, as it checks. A + // kernel the consumer compiled has none: its own module refuses such a buffer. + self.facts.variant = match (first, words) { + (None, 0) => None, + (first, words) => match state.variant(first.map_or(0, |_| srgb), words) { + Some(variant) => { + let variant = variant?; + check_alignments(&self.core, &self.slots, &variant.whole.interface, false)?; + Some(variant) + } + None => { + check_alignments(&self.core, &self.slots, interface, false)?; + match first { + Some((slot, gap)) => return Err(element(slot, gap)), + None => None, + } + } }, }; // A texture declared written with no storage element, which the kernel may reach @@ -1176,8 +1195,8 @@ impl ComputeCommandEncoder { }); self.facts.aligned = true; } - // An sRGB variant's content runs in place of the state's, kept by the command buffer. - let variant = self.facts.srgb.clone(); + // A variant's content runs in place of the state's, kept by the command buffer. + let variant = self.facts.variant.clone(); if let Some(variant) = &variant { recording(&mut self.building).hold_content(variant); } @@ -1676,13 +1695,17 @@ fn recording(building: &mut Option) -> &mut Building { /// [`check_alignment`] of each buffer bound in `slots` that `interface` reaches, the nil buffer's /// address where one it reaches is bound to nothing (`Ring::nil`), else 0, and the zero range's /// where it checks a load (`Ring::zero`), else 0. A `set_bytes` copy is at a multiple of 16 in the -/// ring, which every mask divides, and so is the nil buffer. +/// ring, which every mask divides, and so is the nil buffer. Where `words`, a buffer whose +/// argument's alignment is 8 or 16, bound at a multiple of 4 below it, is not refused: the mask +/// of those slots, bit `i` slot `i`, which plain Metal runs, each element at its own address +/// (`LoweringInputs::word_bound_buffers`). fn check_alignments( core: &Core, slots: &[Slot], interface: &Interface, -) -> Result<(u64, u64), Error> { - let (mut nil, mut zero) = (0, 0); + words: bool, +) -> Result<((u64, u64), u32), Error> { + let (mut nil, mut zero, mut bound) = (0, 0, 0); for field in &interface.fields { let (slot, mask) = match field.value { FieldValue::BufferAddress { slot, mask } => (slot, mask), @@ -1693,12 +1716,19 @@ fn check_alignments( _ => continue, }; match slots.get(slot as usize) { - Some(Slot::Buffer { buffer, offset }) => check_alignment(slot, mask, buffer, *offset)?, + Some(Slot::Buffer { buffer, offset }) => { + let at = buffer.gpu_address().wrapping_add(*offset); + if words && mask > 3 && at & mask != 0 && at & 3 == 0 { + bound |= 1 << slot; + } else { + check_alignment(slot, mask, buffer, *offset)?; + } + } Some(Slot::Bytes(..)) => {} Some(Slot::Empty) | None => nil = core.ring.nil(core)?, } } - Ok((nil, zero)) + Ok(((nil, zero), bound)) } /// A slot's [`FieldValue::BufferBounds`] for a buffer of `length` bytes bound at `offset`: the diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 6cdcbd3e6..6e57cd325 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -475,10 +475,15 @@ pub enum Refusal { }, /// 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 bind offset, is not a multiple - /// of the argument's alignment (`air.arg_type_align_size`, at most 16). Plain Metal runs such a dispatch at addresses of - /// its own: an Apple M3 Max reaches each element at its address rounded down to the smaller of - /// the element's alignment and 4 (`probes/misaligned_buffer_binds.m` in the conformance - /// crate). + /// of the alignment the function holds it to: the argument's (`air.arg_type_align_size`, at + /// most 16), but 4 for an argument of 8 or 16 that a dispatch of a function's kernel binds at + /// a multiple of 4, or 8 where a 64-bit atomic may reach that buffer. Plain Metal runs such a + /// dispatch at addresses of its own: an Apple M3 Max reaches each element at its address + /// rounded down to the smaller of the element's alignment and 4 + /// (`probes/misaligned_buffer_binds.m` in the conformance crate), which is not emulated. At a + /// multiple of 4 that is each element's own address, which the dispatch reaches through a + /// variant of its kernel that holds the buffer to 4 (`LoweringInputs::word_bound_buffers`); a + /// draw, and a kernel the consumer compiled, have no such variant. /// /// Basis: 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, @@ -488,7 +493,7 @@ pub enum Refusal { index: u32, /// The bind offset. offset: u64, - /// The argument's alignment in bytes. + /// The alignment in bytes the function holds the address to. alignment: u64, }, /// A grant of an index already granted ([`Device::grant_indices`](crate::Device::grant_indices)). @@ -2593,7 +2598,7 @@ impl fmt::Display for Refusal { alignment, } => write!( f, - "the buffer at index {index}, bound at offset {offset}, is not at a multiple of its argument's {alignment}-byte alignment" + "the buffer at index {index}, bound at offset {offset}, is not at a multiple of {alignment} bytes, the alignment its function holds it to" ), Refusal::IndicesGranted { class, index } => { write!(f, "{class:?} index {index} is granted already") diff --git a/crates/metal2vulkan-runtime/src/kernel_map.rs b/crates/metal2vulkan-runtime/src/kernel_map.rs index 5a2a03780..ce2a2a2c3 100644 --- a/crates/metal2vulkan-runtime/src/kernel_map.rs +++ b/crates/metal2vulkan-runtime/src/kernel_map.rs @@ -26,13 +26,15 @@ pub(crate) const KERNEL_ENTRIES: usize = 1024; /// functions keyed as a kernel is; neither key decodes a function), and a compute descriptor's /// `requiredThreadsPerThreadgroup`, which the state answers as its `maxTotalThreadsPerThreadgroup` /// and the translator's key leaves out (`None` for a render pipeline); and for a compute state's -/// sRGB variant, its texture slots that hold an 8-bit sRGB texture's UNORM twin, bit `i` slot `i` -/// (`PipelineInner::srgb_variant`), 0 for every other content. +/// variant, its texture slots that hold an 8-bit sRGB texture's UNORM twin and its buffer slots +/// bound at a multiple of 4 below their argument's alignment, bit `i` slot `i` in each +/// (`PipelineInner::variant`), 0 for every other content. #[derive(Clone, PartialEq, Eq, Hash)] pub(crate) struct KernelKey { pub(crate) pipeline: PipelineKey, pub(crate) required: Option<[u32; 3]>, pub(crate) srgb: u128, + pub(crate) words: u32, } /// What one content compiles to. diff --git a/crates/metal2vulkan-runtime/src/pipeline.rs b/crates/metal2vulkan-runtime/src/pipeline.rs index 2044c6624..33a3ae8ad 100644 --- a/crates/metal2vulkan-runtime/src/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/pipeline.rs @@ -164,8 +164,8 @@ pub(crate) struct PipelineInner { /// The samplers the state numbers and the indices the consumer gave them. pub(crate) numbered: Numbered, /// The descriptor of a state whose kernel is a function, and its content's key: what its - /// sRGB variants are lowered from and kept under ([`PipelineInner::srgb_variant`]). `None` - /// for a kernel the consumer compiled, which has none. + /// variants are lowered from and kept under ([`PipelineInner::variant`]). `None` for a + /// kernel the consumer compiled, which has none. source: Option<(ComputePipelineDescriptor, KernelKey)>, } @@ -868,7 +868,9 @@ pub(crate) enum FieldValue { /// offset, of the address of the slot's `set_bytes` copy, or of the nil buffer's address where /// nothing is bound. `mask` is the alignment the module takes that address to have, less 1 /// (`RuntimeFact::AddressAlignment`), 0 where it takes none: a dispatch whose bound buffer's - /// address it does not divide is refused (`Refusal::BufferOffsetAlignment`). + /// address it does not divide is refused (`Refusal::BufferOffsetAlignment`), but at a multiple + /// of 4 under a mask past 3, where it runs the variant that holds the slot to what its + /// accesses need (`LoweringInputs::word_bound_buffers`). BufferAddress { slot: u32, mask: u64 }, /// Two `u32`s: the bytes of the buffer bound at the slot before its bind offset, then its /// length (a `set_bytes` copy: 0 and its length; nothing bound: 0 and 0), which the module @@ -1072,11 +1074,12 @@ impl crate::Device { pipeline: core.translator.compute_pipeline_key(descriptor), required: descriptor.required_threads_per_threadgroup, srgb: 0, + words: 0, }; let compiled = match core.kernels.find(&key) { Some(compiled) => compiled, None => { - let compiled = Arc::new(Compiled::of(core, descriptor, 0)?); + let compiled = Arc::new(Compiled::of(core, descriptor, (0, 0))?); core.kernels.keep(key.clone(), compiled, &core.counters) } }; @@ -1096,11 +1099,13 @@ impl crate::Device { impl Compiled { /// The translation of `descriptor`, every variant lowered, with the `VkPipeline`s whose key /// the descriptor holds; a function kernel's under its texture slots of `srgb` (bit `i` slot - /// `i`) holding an 8-bit sRGB texture's UNORM twin (`LoweringInputs::srgb_storage`). + /// `i`) holding an 8-bit sRGB texture's UNORM twin (`LoweringInputs::srgb_storage`) and its + /// buffer slots of `words` bound at a multiple of 4 below their argument's alignment + /// (`LoweringInputs::word_bound_buffers`). fn of( core: &Arc, descriptor: &ComputePipelineDescriptor, - srgb: u128, + (srgb, words): (u128, u32), ) -> Result { let core = Arc::clone(core); let budget = Budget::standard(); @@ -1125,6 +1130,14 @@ impl Compiled { index, }) .collect(); + inputs.word_bound_buffers = (0..BUFFER_SLOTS) + .filter(|&index| words >> index & 1 == 1) + .map(|index| SlotRef { + stage: Stage::Kernel, + class: SlotClass::Buffer, + index, + }) + .collect(); let plain = translating(&core, || { translator.kernel_inputs_read(function, &inputs, &budget, entries) }) @@ -2311,37 +2324,41 @@ impl PipelineInner { /// The content of the state's kernel under its texture slots of `srgb` (bit `i` slot `i`) /// holding an 8-bit sRGB texture's UNORM twin, each write there encoded in the shader - /// (`LoweringInputs::srgb_storage`): the one the device's map of contents holds under the - /// state's key with `srgb`, else lowered now and kept there, so the map bounds how many live. - /// It numbers the state's samplers, as it lowers the same function. `None` for a kernel the - /// consumer compiled, which has no function to lower it from. + /// (`LoweringInputs::srgb_storage`), and its buffer slots of `words` bound at a multiple of 4 + /// below their argument's alignment, each held to what its accesses need + /// (`LoweringInputs::word_bound_buffers`): the one the device's map of contents holds under + /// the state's key with both, else lowered now and kept there, so the map bounds how many + /// live. It numbers the state's samplers, as it lowers the same function. `None` for a kernel + /// the consumer compiled, which has no function to lower it from. /// /// Err: the translator's errors of its lowering, as the state's creation reports them; /// [`Gap::KernelInput`] of a constexpr sampler where it samples one the state's module does /// not. - pub(crate) fn srgb_variant(&self, srgb: u128) -> Option, Error>> { + pub(crate) fn variant(&self, srgb: u128, words: u32) -> Option, Error>> { let core = self.core(); let (descriptor, key) = self.source.as_ref()?; let key = KernelKey { srgb, + words, ..key.clone() }; if let Some(compiled) = core.kernels.find(&key) { return Some(Ok(compiled)); } - let made = Compiled::of(core, descriptor, srgb).and_then(|compiled| { - match covers(&self.compiled.whole.interface, &compiled.whole.interface) { - true => Ok(core.kernels.keep(key, Arc::new(compiled), &core.counters)), - false => Err(gap(KernelInputKind::ConstexprSampler)), - } - }); + let made = + Compiled::of(core, descriptor, (srgb, words)).and_then(|compiled| { + match covers(&self.compiled.whole.interface, &compiled.whole.interface) { + true => Ok(core.kernels.keep(key, Arc::new(compiled), &core.counters)), + false => Err(gap(KernelInputKind::ConstexprSampler)), + } + }); Some(made) } } impl crate::kept::Handle for Arc { - /// The content itself: a command buffer that dispatched an sRGB variant keeps it - /// ([`PipelineInner::srgb_variant`]), which no state holds. + /// The content itself: a command buffer that dispatched a variant keeps it + /// ([`PipelineInner::variant`]), which no state holds. type Kept = Arc; fn object(&self) -> &Arc { diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index b32cbc1a7..ff7cfbaff 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -544,6 +544,7 @@ impl crate::Device { pipeline: core.translator.queried_render_descriptor_key(descriptor), required: None, srgb: 0, + words: 0, }; let compiled = match core.kernels.find_render(&key) { Some(compiled) => compiled, diff --git a/crates/metal2vulkan-runtime/src/tests/compute.rs b/crates/metal2vulkan-runtime/src/tests/compute.rs index e3424413d..4fd30f3ae 100644 --- a/crates/metal2vulkan-runtime/src/tests/compute.rs +++ b/crates/metal2vulkan-runtime/src/tests/compute.rs @@ -256,7 +256,9 @@ pub(crate) mod on_device { /// records nothing. At each alignment, 2, 4, 8 and 16, every bind 1, 3, 4, 8, 12 or 15 bytes /// past a multiple of 16 that is not a multiple of the alignment is refused (17 binds) and /// leaves every word as it was; the same buffer bound 16 bytes past one then runs, stepping - /// the 16 words from its address. + /// the 16 words from its address. This kernel has no function to lower a variant from, as a + /// kernel the consumer compiled has none, so its binds at a multiple of 4 under 8 and 16 are + /// refused too (`PipelineInner::variant`). #[test] fn every_device_refuses_a_bound_address_off_its_alignment() { each_device("compute_misaligned_address", |name, _, device| { diff --git a/crates/metal2vulkan-runtime/src/tests/kernel_map.rs b/crates/metal2vulkan-runtime/src/tests/kernel_map.rs index 87d1236c6..0655cb188 100644 --- a/crates/metal2vulkan-runtime/src/tests/kernel_map.rs +++ b/crates/metal2vulkan-runtime/src/tests/kernel_map.rs @@ -197,6 +197,7 @@ mod on_device { pipeline: core.translator.compute_pipeline_key(descriptor), required: descriptor.required_threads_per_threadgroup, srgb: 0, + words: 0, }; let held = (core.kernels.find(&key(&tiled))).expect("the tiled kernel"); let ours = (core.kernels.find(&key(&observing))).expect("the observing kernel"); diff --git a/crates/metal2vulkan-runtime/src/tests/translate.rs b/crates/metal2vulkan-runtime/src/tests/translate.rs index 810aa2f24..5b72e76cf 100644 --- a/crates/metal2vulkan-runtime/src/tests/translate.rs +++ b/crates/metal2vulkan-runtime/src/tests/translate.rs @@ -3382,14 +3382,18 @@ attributes #1 = { convergent nounwind willreturn } /// `vector_word_phases`'s kernels (`metal2vulkan_devtools::vector_word_phases`): with /// `vwp_words`'s two `uint` buffers bound at each word phase, 0, 4, 8 and 12, so its `uint4` /// and `float4` accesses through cast pointers land that far past a multiple of 16 whatever - /// the AIR's `align 16`, and `vwp_vec16`'s two `float4` buffers at multiples of 16, all four - /// buffers hold Metal's words afterwards, byte for byte from their first byte: the + /// the AIR's `align 16`, and `vwp_vec16`'s two `float4` buffers at multiples of 16, then with + /// `vwp_words`'s at 0 and `vwp_vec16`'s 4 and 8 bytes past a multiple of 16 + /// (`VEC16_AT_WORDS`: arguments of alignment 16 at multiples of 4 only, which plain Metal + /// runs, and which run on the state's variant that holds them to 4, lowered at that dispatch), + /// all four buffers hold Metal's words afterwards, byte for byte from their first byte: the /// conformance crate's `vector-word-phases-*` cases hold the answer an Apple M3 Max recorded /// equal to the same words. #[test] fn every_device_places_each_vector_access_at_its_own_address() { use metal2vulkan_devtools::vector_word_phases::{ - answer, inputs, vec16_offsets, FIXTURE, OFFSETS, THREADS, VEC16, WORDS, + answer_at, inputs, vec16_offsets, FIXTURE, OFFSETS, THREADS, VEC16, VEC16_AT_WORDS, + WORDS, }; let (Some(phased), Some(aligned)) = (descriptor_of(FIXTURE, WORDS), descriptor_of(FIXTURE, VEC16)) @@ -3408,11 +3412,16 @@ attributes #1 = { convergent nounwind willreturn } .map(|bytes| (buffers.buffer(bytes.len() as u64), bytes)) .collect(); let queue = device.new_command_queue(4).expect("a queue"); - for offset in OFFSETS { + let lowered = || device.counters().metrics().translations; + let runs: Vec<(u64, (u64, u64))> = (OFFSETS.into_iter()) + .map(|offset| (offset, vec16_offsets(offset))) + .chain([(0, VEC16_AT_WORDS)]) + .collect(); + for &(offset, (a_at, b_at)) in &runs { for (buffer, bytes) in &held { write(buffer, 0, bytes); } - let (a_at, b_at) = vec16_offsets(offset); + let start = lowered(); let command_buffer = queue.command_buffer().expect("a command buffer"); let mut encoder = command_buffer .compute_command_encoder(DispatchType::Serial) @@ -3435,7 +3444,13 @@ attributes #1 = { convergent nounwind willreturn } command_buffer.commit().expect("a commit"); finished(name, &command_buffer); assert_eq!(command_buffer.error(), None, "{name}"); - let want = answer(offset); + // Only the binds off a multiple of 16 run a variant, lowered at their dispatch. + assert_eq!( + lowered() > start, + a_at % 16 != 0, + "{name}: vec16 at {a_at} and {b_at}: a variant lowered" + ); + let want = answer_at(offset, (a_at, b_at)); for ((buffer, bytes), (which, want)) in held.iter().zip([ ("src", &want.src), ("dst", &want.dst), @@ -3452,11 +3467,101 @@ attributes #1 = { convergent nounwind willreturn } let first = got.iter().zip(&want).position(|(x, y)| x != y); assert_eq!( first, None, - "{name}: offset {offset}: {which} differs from Metal's words" + "{name}: offset {offset}, vec16 at {a_at} and {b_at}: {which} differs \ + from Metal's words" ); } } - println!("{name}: Metal's words at bind offsets {OFFSETS:?}"); + println!("{name}: Metal's words at bind offsets {runs:?}"); + }); + } + + /// A state's variants of buffers bound at a multiple of 4 below their argument's alignment + /// (`LoweringInputs::word_bound_buffers`) live in the device's bounded map of contents under + /// the state's key with their slots' mask (`KernelKey::words`): `vwp_vec16` with both its + /// `float4` buffers 4 and 8 bytes past a multiple of 16 lowers one variant at its first + /// dispatch and none at its second; with only `a` so bound, another. Filled past a cap of 2, + /// the map holds 2, and a variant it forgot lowers again at its next dispatch. + #[test] + fn every_device_keeps_a_word_bound_variant_in_the_bounded_map_of_contents() { + use metal2vulkan_devtools::vector_word_phases::{inputs, FIXTURE, THREADS, VEC16, WORDS}; + let (Some(aligned), Some(phased)) = + (descriptor_of(FIXTURE, VEC16), descriptor_of(FIXTURE, WORDS)) + else { + return; + }; + each_device("word-bound variants", |name, _, device| { + device.core().kernels.set_cap(2); + let counters = device.counters(); + let entries = || counters.gauges().kernel_entries; + let lowered = || counters.metrics().translations; + let before = inputs(); + let mut buffers = Buffers::new(&device, 64 * 1024); + let (a, b) = ( + buffers.buffer(before.a.len() as u64), + buffers.buffer(before.b.len() as u64), + ); + let queue = device.new_command_queue(4).expect("a queue"); + let vec16 = state(name, &device, &aligned); + let run = |binds: [u64; 2]| { + 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(&vec16).expect("a state"); + for (index, (buffer, at)) in [&a, &b].into_iter().zip(binds).enumerate() { + encoder + .set_buffer(Some(buffer), at, index as u32) + .expect("a buffer"); + } + (encoder.dispatch_threadgroups([1, 1, 1], [THREADS, 1, 1])) + .unwrap_or_else(|error| panic!("{name}: binds {binds:?}: {error}")); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}: binds {binds:?}"); + }; + let start = lowered(); + run([16, 64]); + assert_eq!( + lowered(), + start, + "{name}: binds at multiples of 16 run the state's own" + ); + assert_eq!(entries(), 1, "{name}: the state's content"); + run([4, 8]); + let each = lowered() - start; + assert!( + each > 0, + "{name}: the variant lowered at its first dispatch" + ); + run([4, 8]); + assert_eq!(lowered() - start, each, "{name}: one variant, kept"); + assert_eq!(entries(), 2, "{name}: the state's content and its variant"); + // Another mask is another variant: the map holds its cap, the state's content gone. + run([4, 64]); + assert_eq!( + lowered() - start, + 2 * each, + "{name}: a second variant lowered" + ); + assert_eq!(entries(), 2, "{name}: the map holds its cap"); + // Another kernel's content forgets the least recently used, the first variant. + let words = state(name, &device, &phased); + assert_eq!(entries(), 2, "{name}: the map holds its cap"); + let forgotten = lowered(); + run([4, 8]); + assert_eq!( + lowered() - forgotten, + each, + "{name}: a forgotten variant lowered again" + ); + assert_eq!(entries(), 2, "{name}: the map holds its cap"); + drop((vec16, words)); + println!( + "{name}: one variant a mask, kept in a map of 2 filled past its cap, a forgotten \ + one lowered again" + ); }); } @@ -4376,11 +4481,12 @@ define void @nil_read_kernel(ptr addrspace(1) %in, ptr addrspace(1) %out, i32 %t /// `vwp_vec16` takes its `float4 *` arguments' addresses to be multiples of 16 and `vwp_words` /// its `uint *` arguments' multiples of 4 (`RuntimeFact::AddressAlignment`). A dispatch with - /// either argument bound off that alignment (`vwp_words`'s 1 and 3 bytes past each word phase, - /// `vwp_vec16`'s 4 and 12 bytes past its multiples of 16) is refused, as Metal's API + /// either argument bound off a multiple of 4 (`vwp_words`'s 1 and 3 bytes past each word + /// phase, `vwp_vec16`'s 2 and 3 bytes past its multiples of 16) is refused, as Metal's API /// validation refuses the bind (`Refusal::BufferOffsetAlignment`, naming the index, the offset - /// and the alignment), and records nothing: the command buffer completes without error and - /// every buffer holds its bytes as they were. + /// and the argument's alignment), and records nothing: the command buffer completes without + /// error and every buffer holds its bytes as they were. Plain Metal reaches those elements at + /// addresses rounded down to a multiple of 4, which is not emulated. #[test] fn an_argument_bound_off_its_alignment_is_refused() { use metal2vulkan_devtools::vector_word_phases::{ @@ -4422,8 +4528,8 @@ define void @nil_read_kernel(ptr addrspace(1) %in, ptr addrspace(1) %out, i32 %t for (state, binds, off, alignment) in [ (&phased, [(0, offset + 1), (1, offset)], 0, 4), (&phased, [(0, offset), (1, offset + 3)], 1, 4), - (&aligned, [(2, a_at + 4), (3, b_at)], 0, 16), - (&aligned, [(2, a_at), (3, b_at + 12)], 1, 16), + (&aligned, [(2, a_at + 2), (3, b_at)], 0, 16), + (&aligned, [(2, a_at), (3, b_at + 3)], 1, 16), ] { encoder.set_compute_pipeline_state(state).expect("a state"); for (index, (buffer, at)) in binds.into_iter().enumerate() { diff --git a/docs/API.md b/docs/API.md index 5d0e0e108..b22483915 100644 --- a/docs/API.md +++ b/docs/API.md @@ -139,7 +139,13 @@ and so do the command line, the compile worker and every validation tool. It hol of its size is one `uvec2` or `uvec4`. The function states `RuntimeFact::AddressAlignment` with that alignment (at most 16), and the runtime refuses a dispatch whose bound address is not a multiple of it, as Metal's API validation refuses the bind offset (an accepted difference, - section 10). A slot whose argument states an alignment below 4, or none, is reached the same way where each of + section 10). Plain Metal reaches each element of an argument of 8- or 16-byte alignment bound at + a multiple of 4 exactly where the program put it (an Apple M3 Max, macOS 27.0.1, + `crates/metal2vulkan-conformance/probes/misaligned_buffer_binds.m`), so a function compiled with + such a slot in `LoweringInputs::word_bound_buffers` states the argument's alignment up to what + the slot's accesses need, 4, or 8 where a 64-bit atomic may reach it (any slot, where one goes + through a pointer loaded from memory), and its accesses through the address claim no more + `Aligned` than that; the runtime's dispatch of such a bind runs that variant. A slot whose argument states an alignment below 4, or none, is reached the same way where each of its accesses is one 1- or 2-byte unit no wider than that alignment (an `i8` access of a `uchar` buffer, an `i16` one of a `ushort` buffer) on a device with that width's storage access. Any other slot is reached from the word below each access, its offset sign-extended, so an access @@ -2759,6 +2765,11 @@ named states the rule in full. Without validation an Apple M3 Max (macOS 27.0.1) runs it, reaching each element at its address rounded down to the smaller of the element's alignment and 4, for loads, stores and pointers stored in a buffer alike (`crates/metal2vulkan-conformance/probes/misaligned_buffer_binds.m`). + A function kernel's argument of 8- or 16-byte alignment bound at a multiple of 4 below it is not + refused: that rule reaches each of its elements at its own address, and the dispatch runs a + variant of the kernel that reaches them there (section 1, `LoweringInputs::word_bound_buffers`), + though Metal's API validation refuses that bind offset too. Such a buffer that a 64-bit atomic + may reach off a multiple of 8, a draw's, and a consumer-compiled kernel's are still refused. - **A recursive call past the call stack yields zero**: the stack holds what Metal's byte model holds for the pipeline's `max_call_stack_depth`; a call that finds it full returns zero, where Metal's answer is corrupt.