From 131be007fa08190fb6a6c03e28ff6d063547a31c Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 10 Nov 2026 03:45:57 -0800 Subject: [PATCH] A half write through an argument buffer notes its NaN only where the heap can name a family the device stores its own way What: a `half` texel's write to a heap element recorded `PrecisionNote::DeviceNanEncoding` unconditionally ("a heap element may be any format"), so on MoltenVK on the M3 Max a write through an argument buffer into an RGBA32Float or RG11B10Float texture announced the note though the store is Metal's there (0 of 25 lanes differ, job 13458's lanes128.log). A new key, `SpecKey::HeapNanFamilies(Stage)`, gives from the command's heap members the families whose texels may hold a NaN a `half` write stores (`lower::texture::nan_family`, the same classes the slot path tests of a bound format: 1 a 16-bit float format, 2 a 32-bit one, 4 a packed small float one, 8 a float format of none of those; normalized, sRGB, extended-range, integer and stencil formats none). `half_write_nans` now records the heap write's note under one clause per family whose deviation the profile lacks (`MetalHalfTexelWrites`, `MetalNanMoves`, `MetalSmallFloatNans`) and the no-family bit, requiring the property of each family it takes, as a slot's write does. Measured, before the change (`runtime_lane::half_write_nans`, argument-buffer writes): - M3 Max, MoltenVK (job 13458): 16-bit float formats 15 of 25 lanes differ (signalling NaNs stored 0x7e00); 32-bit float and RG11B10Float 0 differ. The note now holds there only where the heap can name a 16-bit float texture (or one of no family). - lavapipe (job 13553): 16-bit 8 differ, 32-bit 15 differ, RG11B10Float 0 differ. lavapipe takes none of the three deviations, so its note keeps every family's clause. Runtime: `degrade_bound_values` reads the clause at each draw or dispatch (generic; no runtime code changed). The lane `half_write_nans` now holds argument-buffer writes to the measured rule as it holds slot writes: on a device with the family's property, 0 lanes differ and nothing is announced. Public API: `SpecKey` gains `HeapNanFamilies(Stage)` (a `#[non_exhaustive]` enum; no consumer breaks); api_signatures.tsv blessed. Tests: heap::a_heap_half_write_s_nan_note_follows_the_families_its_command_can_name (the clauses and required properties on every committed profile with a heap; plan values 1/2/4/0 for R16Float, RGBA32Float, RG11B10Float, RGBA8Unorm and R32Uint residents and the note held under them). SEMANTICS_VERSION 2019, ARTIFACT_FORMAT_VERSION 500 (a SpecKey tag; both renumbered at landing). (cherry picked from commit 8f6f24055459c9143f3473da8ab60e6532b30676) --- .../src/runtime_lane/half_write_nans.rs | 35 ++-- crates/metal2vulkan/src/bind/plan/slots.rs | 25 ++- crates/metal2vulkan/src/cache/codec.rs | 1 + crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/src/lower/select.rs | 5 +- crates/metal2vulkan/src/lower/texture/mod.rs | 96 +++++++++- crates/metal2vulkan/src/pipeline/artifact.rs | 8 +- crates/metal2vulkan/src/pipeline/sym.rs | 8 + .../src/tests/engine_extended_range/heap.rs | 172 ++++++++++++++++++ crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/API.md | 5 +- 11 files changed, 327 insertions(+), 31 deletions(-) diff --git a/crates/metal2vulkan-validation/src/runtime_lane/half_write_nans.rs b/crates/metal2vulkan-validation/src/runtime_lane/half_write_nans.rs index 1c4700b7e..3438b50ce 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/half_write_nans.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/half_write_nans.rs @@ -23,8 +23,9 @@ //! Metal's `0x7fc00000` on a device with `VkProperty::MetalNanMoves`, and a packed small float one //! Metal's on a device with `VkProperty::MetalSmallFloatNans`; elsewhere the NaN is the device's, //! and a pipeline whose stores differ announces `device-nan-encoding`. On a device with those -//! properties a texture slot's write into such a texture announces neither `device-nan-encoding` -//! nor `native-nan-encoding` (a heap element's, which may be any format, announces the first). +//! properties a write into such a texture, through a texture slot or an argument buffer whose +//! command makes no texture of another family resident (`SpecKey::HeapNanFamilies`), announces +//! neither `device-nan-encoding` nor `native-nan-encoding`. use super::degrade_notices::{counts, on_device_with}; use super::{at_plan, buffer_with, layer_reported_nothing, read_buffer, WAIT}; @@ -337,11 +338,13 @@ fn stored( /// Each format's stored words through `write`, `read_write` and `held`, printed with the lanes /// that differ from Metal's (the module docs): none in a 16-bit float channel on a device with /// `VkProperty::MetalHalfTexelWrites` whose pipeline records no `native-nan-encoding`, nor, -/// through a texture slot, announced or differing in a 32-bit float channel on a device with +/// through a texture slot or the argument buffer (whose dispatch makes that texture alone +/// resident), announced or differing in a 32-bit float channel on a device with /// `VkProperty::MetalNanMoves` or a packed small float one on a device with /// `VkProperty::MetalSmallFloatNans`; a pipeline whose stores differ announces /// `device-nan-encoding` (at its making, or at the dispatch that binds such a texture to a slot of -/// no declared format), or `native-nan-encoding` where each lane that differs is a NaN stored as +/// no declared format or makes one of such a family resident), or `native-nan-encoding` where each +/// lane that differs is a NaN stored as /// a NaN. #[test] fn half_writes_store_their_nans_as_metal_or_announce() { @@ -365,19 +368,17 @@ fn half_writes_store_their_nans_as_metal_or_announce() { let announced = counts(&messages.take_notices()); let properties = &device.compile_device().profile().enabled().properties; let keeps = properties.contains(&VkProperty::MetalHalfTexelWrites); - // The NaN a texture slot's write stores, Metal's on the device's measured - // deviation: a 32-bit float channel's where the widening is Metal's, a - // packed small float one's where its store is. - let measured = access != "held" - && match f.format { - PixelFormat::RG11B10Float => { - properties.contains(&VkProperty::MetalSmallFloatNans) - } - _ => { - f.word_bytes == 4 - && properties.contains(&VkProperty::MetalNanMoves) - } - }; + // The NaN a write stores, through a slot or the argument buffer, Metal's on + // the device's measured deviation: a 32-bit float channel's where the + // widening is Metal's, a packed small float one's where its store is. + let measured = match f.format { + PixelFormat::RG11B10Float => { + properties.contains(&VkProperty::MetalSmallFloatNans) + } + _ => { + f.word_bytes == 4 && properties.contains(&VkProperty::MetalNanMoves) + } + }; let mut differ = Vec::new(); // Whether every lane that differs is a NaN stored as a NaN. let mut nans_only = true; diff --git a/crates/metal2vulkan/src/bind/plan/slots.rs b/crates/metal2vulkan/src/bind/plan/slots.rs index cee3af372..466659cd6 100644 --- a/crates/metal2vulkan/src/bind/plan/slots.rs +++ b/crates/metal2vulkan/src/bind/plan/slots.rs @@ -272,8 +272,8 @@ pub(crate) fn record_specialized( /// Record in `resources`' template the value of each key a specialized note of `stages` tests that /// no constant and no push carries but the bound resources decide (`SpecKey::BoundSamplerWord`), -/// or what the command's handles can name (`SpecKey::HeapYCbCrTextures` and -/// `SpecKey::HeapRawTextures`, through `reach`, the stages a used resource's render stages reach, +/// or what the command's handles can name (`SpecKey::HeapYCbCrTextures`, +/// `SpecKey::HeapRawTextures` and `SpecKey::HeapNanFamilies`, through `reach`, the stages a used resource's render stages reach, /// as for the heap's members; `SpecKey::FilteringArgumentSampler`), which /// `BindingPlan::specialized_value` gives the runtime at /// each draw or dispatch, where it reads such a note (`StageModule::note_clauses_bound`). Nothing @@ -296,6 +296,7 @@ pub(crate) fn record_noted<'a>( SpecKey::BoundSamplerWord(_) | SpecKey::HeapYCbCrTextures(_) | SpecKey::HeapRawTextures(_) + | SpecKey::HeapNanFamilies(_) | SpecKey::FilteringArgumentSampler ) }) @@ -312,6 +313,7 @@ pub(crate) fn record_noted<'a>( let value = match key { SpecKey::HeapYCbCrTextures(stage) => u64::from(heap_ycbcr(shape, stage, reach)), SpecKey::HeapRawTextures(stage) => u64::from(heap_raw(shape, stage, reach)), + SpecKey::HeapNanFamilies(stage) => u64::from(heap_nan_families(shape, stage, reach)), // A sampler state of any listed shape may be the one an argument buffer names. SpecKey::FilteringArgumentSampler => u64::from( (shape.argument_samplers.shapes.iter()) @@ -373,6 +375,25 @@ fn heap_raw( bits } +/// The `SpecKey::HeapNanFamilies` of `stage` for `shape`: the bit of each family +/// (`lower::texture::nan_family`) of the heap members of `shape` that reach `stage` (as for +/// [`heap_ycbcr`]), whose texels a stage's `half` write may store a NaN in. +fn heap_nan_families( + shape: &BindShape, + stage: Stage, + reach: &dyn Fn(metal::RenderStages) -> Vec, +) -> u32 { + crate::bind::heap::members(shape, &[stage], reach) + .iter() + .map(|m| match m.shape { + TextureShape::Texture { pixel_format, .. } => { + crate::lower::texture::nan_family(pixel_format) + } + TextureShape::Buffer { .. } => 0, + }) + .fold(0, |bits, family| bits | family) +} + /// Whether `shape` binds anything at `slot`. fn present(shape: &BindShape, slot: SlotRef) -> bool { shape diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 4c631052d..90e064f32 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -867,6 +867,7 @@ codec_enum! { SamplerAnisotropy(f0), RangeAtBindOffset(f0), PlainHalfTexels(f0), NearestPixelSampler(f0), BoundSamplerWord(f0), HeapYCbCrTextures(f0), FilteringArgumentSampler, StageInReach, HeapRawTextures(f0), BorderTexels(f0), + HeapNanFamilies(f0), } PushField { RootTableAddress, ExecutionStatusAddress, DispatchRegion, BaseVertexInstance, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 531746e50..afe157c0a 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 2019; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 499; +pub const ARTIFACT_FORMAT_VERSION: u32 = 500; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index 6c8e8648c..5ff7939ba 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1775,7 +1775,8 @@ fn finish( /// constant carries (`SpecKey::BoundTexelFormat`), or the whole word of the sampler bound at a /// sampler slot, which none carries either (`SpecKey::BoundSamplerWord`), or whether a texture a /// stage's handles can name is two-plane YCbCr (`SpecKey::HeapYCbCrTextures`) or held by its raw -/// texels alone (`SpecKey::HeapRawTextures`), or whether a sampler state an argument buffer can +/// texels alone (`SpecKey::HeapRawTextures`), or the families of such textures whose texels may +/// hold a NaN (`SpecKey::HeapNanFamilies`), or whether a sampler state an argument buffer can /// name filters (`SpecKey::FilteringArgumentSampler`), which the plan gives. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub(crate) enum NoteOn { @@ -1786,6 +1787,7 @@ pub(crate) enum NoteOn { BoundSampler(u32), HeapYCbCr(Stage), HeapRaw(Stage), + HeapNan(Stage), ArgumentSamplers, } @@ -1860,6 +1862,7 @@ fn declared(families: &FamilyPlans, t: NoteTest) -> Option { // Given by the plan from what the command's handles can name, never a constant. NoteOn::HeapYCbCr(stage) => SpecKey::HeapYCbCrTextures(stage), NoteOn::HeapRaw(stage) => SpecKey::HeapRawTextures(stage), + NoteOn::HeapNan(stage) => SpecKey::HeapNanFamilies(stage), NoteOn::ArgumentSamplers => SpecKey::FilteringArgumentSampler, NoteOn::Sampler(index) => { let r = families.sampler.slots.get(&index)?; diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index e5836311c..04120ddbb 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -2286,6 +2286,73 @@ fn stored_where( ) } +/// The bit of `SpecKey::HeapNanFamilies` of a 16-bit float format: its written `half` NaN is +/// Metal's on a device of `DriverDeviation::MetalHalfTexelWrites`. +pub(crate) const NAN_SIXTEEN: u32 = 1; + +/// The bit of `SpecKey::HeapNanFamilies` of a 32-bit float format: its written `half` NaN is +/// Metal's on a device of `DriverDeviation::MetalNanMoves`. +pub(crate) const NAN_WIDE: u32 = 2; + +/// The bit of `SpecKey::HeapNanFamilies` of a packed small float format (`RG11B10Float`, +/// `RGB9E5Float`): its written NaN is Metal's on a device of `DriverDeviation::MetalSmallFloatNans`. +pub(crate) const NAN_SMALL: u32 = 4; + +/// The bit of `SpecKey::HeapNanFamilies` of a float format of none of those families whose texels +/// may hold a NaN: its written NaN is the device's. +pub(crate) const NAN_OTHER: u32 = 8; + +/// Each family a written texture may be of, by its bit of `SpecKey::HeapNanFamilies`, with the +/// deviation and property under which its stored NaN is Metal's (none for [`NAN_OTHER`]). +const NAN_FAMILIES: [( + u32, + Option<(DriverDeviation, crate::device::requirements::VkProperty)>, +); 4] = { + use crate::device::requirements::VkProperty; + [ + ( + NAN_SIXTEEN, + Some(( + DriverDeviation::MetalHalfTexelWrites, + VkProperty::MetalHalfTexelWrites, + )), + ), + ( + NAN_WIDE, + Some((DriverDeviation::MetalNanMoves, VkProperty::MetalNanMoves)), + ), + ( + NAN_SMALL, + Some(( + DriverDeviation::MetalSmallFloatNans, + VkProperty::MetalSmallFloatNans, + )), + ), + (NAN_OTHER, None), + ] +}; + +/// The bit of `SpecKey::HeapNanFamilies` of a texture of pixel format `pf`: its class's family +/// (`metal::texel_format::TexelFormat`, as [`half_write_nans`] tests a bound texture's), or 0 for +/// a format whose texels hold no NaN (normalized, sRGB, extended-range, another packed one) or +/// that a float texture does not view (integer, stencil). +pub(crate) fn nan_family(pf: crate::metal::PixelFormat) -> u32 { + use crate::metal::bicubic::BicubicTexels as B; + use crate::metal::texel_format::{PackedTexels, TexelFormat}; + if crate::metal::format::sampled_type(pf) != Some(SampledType::Float) { + return 0; + } + let class = crate::metal::format::bound_texel_format(pf); + let family = class & (B::LINEAR | B::HALF | TexelFormat::NAN_FREE); + match class & TexelFormat::PACKED_MASK { + p if p == PackedTexels::SmallFloat.class().0 => NAN_SMALL, + 0 if family == B::HALF => NAN_SIXTEEN, + 0 if family == B::LINEAR => NAN_WIDE, + 0 if family == 0 => NAN_OTHER, + _ => 0, + } +} + /// What a `half` texel's write to texture `image` records of its NaN. Metal stores a written /// half's NaN as the half's own bits in a 16-bit float channel and as its conversion of the /// canonical `0x7fc00000` in any other (the M3 Max under macOS 26.7, measured by the consumer; the @@ -2302,11 +2369,12 @@ fn stored_where( /// The write records `PrecisionNote::DeviceNanEncoding` where the stored NaN stays the device's: /// a 16-bit float channel's on a profile without `DriverDeviation::MetalHalfTexelWrites`, a 32-bit /// one's without `DriverDeviation::MetalNanMoves`, a packed small float one's without -/// `DriverDeviation::MetalSmallFloatNans`, and a heap element's, which may be any of them. A slot -/// whose choice declares no format (or a variant that states none) records it under the format -/// bound there (`m` charged for the clauses), which the runtime announces at a draw or dispatch -/// that binds such a texture: where the bound class is one of those three families on a profile -/// without its deviation, or of no family the classes name (a format that may hold a NaN). A +/// `DriverDeviation::MetalSmallFloatNans`, and a float channel's of none of those families (a +/// format that may hold a NaN). A slot whose choice declares no format (or a variant that states +/// none) records it under the format bound there (`m` charged for the clauses), and a heap +/// element's under the families of the textures the stage's handles can name +/// (`SpecKey::HeapNanFamilies`, [`nan_family`]), which the runtime announces at a draw or dispatch +/// that binds or makes resident such a texture of a family whose stored NaN is the device's. A /// normalized or integer channel stores no NaN. pub(super) fn half_write_nans( cx: &mut SelectCx<'_>, @@ -2341,8 +2409,23 @@ pub(super) fn half_write_nans( _ => Stored::Exact, } }; + let takes = |d| cx.profile.takes_driver_deviation(d); let stored = match image { - ImageRef::Heap { .. } => Stored::Device, + // An element of any family the stage's handles can name: the note holds where they can + // name one whose deviation the profile lacks (`SpecKey::HeapNanFamilies`). + ImageRef::Heap { .. } => { + let mut when: Vec = Vec::new(); + for (family, measured) in NAN_FAMILIES { + match measured { + Some((deviation, property)) if takes(deviation) => { + cx.families.texture.storage_properties.insert(property); + } + _ => when + .push([NoteTest::equal(NoteOn::HeapNan(cx.stage), family, family)].into()), + } + } + return cx.note_when(PrecisionNote::DeviceNanEncoding, when, m); + } ImageRef::Slot(index) => { let slot = slot_of(cx, index)?.slot; match cx.inputs.storage_images.get(&slot) { @@ -2357,7 +2440,6 @@ pub(super) fn half_write_nans( } } }; - let takes = |d| cx.profile.takes_driver_deviation(d); if let Stored::Bound(index) = stored { use crate::metal::bicubic::BicubicTexels as B; use crate::metal::texel_format::{PackedTexels, TexelFormat}; diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 1b18da0b8..21801b5ba 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -457,7 +457,7 @@ impl SpecClause { /// (`BindingPlan::specialized_value`): one the function reads as data /// (`SpecKey::read_as_data`), the word of the sampler bound at a slot /// (`SpecKey::BoundSamplerWord`), or what the stage's handles can name - /// (`SpecKey::HeapYCbCrTextures`, `SpecKey::HeapRawTextures`, + /// (`SpecKey::HeapYCbCrTextures`, `SpecKey::HeapRawTextures`, `SpecKey::HeapNanFamilies`, /// `SpecKey::FilteringArgumentSampler`). A runtime reads such /// a clause at each draw or dispatch, from the values its plan gives /// ([`StageModule::note_clauses_bound`]). @@ -469,6 +469,7 @@ impl SpecClause { SpecKey::BoundSamplerWord(_) | SpecKey::HeapYCbCrTextures(_) | SpecKey::HeapRawTextures(_) + | SpecKey::HeapNanFamilies(_) | SpecKey::FilteringArgumentSampler ) }) @@ -942,7 +943,10 @@ pub enum PrecisionNote { /// (lavapipe stores `0xffc00000` as `0xfe00`, ANV every NaN). Where the write's texture slot is /// declared without a format, the note is recorded under the format bound there (a /// [`SpecializedNote`] of `SpecKey::BoundTexelFormat`), which the runtime announces at a draw - /// or dispatch that binds such a texture. + /// or dispatch that binds such a texture; a `half` write to a heap element, under the families + /// of the textures the stage's handles can name (`SpecKey::HeapNanFamilies`), which the runtime + /// announces at a draw or dispatch whose command can name one of a family whose stored NaN is + /// the device's on that profile. /// Also recorded on a render pipeline's vertex stage where its vertex descriptor gives a float /// format narrower than 32 bits (a `half` format, `FloatRG11B10`) to an attribute that /// fixed-function vertex input fetches and the function reads as `float` diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 572437fd3..441034685 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -853,6 +853,14 @@ pub enum SpecKey { /// stage, as for [`HeapYCbCrTextures`](Self::HeapYCbCrTextures), and read by a specialized /// note's test alone, given by a plan, as that is. HeapRawTextures(Stage), + /// Four bits: the families of the float textures the stage's handles can name whose texel may + /// hold a NaN a `half` write stores (`lower::texture::half_write_nans`), each a bit of + /// `lower::texture::nan_family`: 1 a 16-bit float format, 2 a 32-bit float one, 4 a packed + /// small float one (`RG11B10Float`, `RGB9E5Float`), 8 a float format of none of those and + /// none whose texels hold no NaN (normalized, sRGB, extended-range); of the heap members of + /// the command reaching the stage, as for [`HeapYCbCrTextures`](Self::HeapYCbCrTextures), and + /// read by a specialized note's test alone, given by a plan, as that is. + HeapNanFamilies(Stage), /// Boolean: a sampler state an argument buffer's sampler handle can name filters: one of the /// bind state's argument samplers (`BindState::argument_samplers`, every live state, its /// shape in `BindShape`) has a linear minification, magnification or mip filter, anisotropy, diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs b/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs index 2b3e7cefe..c8ea2849c 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs @@ -722,6 +722,178 @@ fn a_heap_sample_s_filter_note_holds_where_its_command_can_name_a_filtered_raw_t assert!(planned > 0, "no committed profile has the sampled heap"); } +/// Synthetic AIR written for this test: kernel `k` writes buffer 0's `half4` at lane `gid` (its +/// bits) to texel `(gid, 0)` of the `texture2d` its argument buffer (buffer 2) holds. +const HALF_WRITE: &str = r#"define void @k(ptr addrspace(1) %v, ptr addrspace(2) %held, i32 %gid) { +entry: + %i = zext i32 %gid to i64 + %p = getelementptr <4 x i16>, ptr addrspace(1) %v, i64 %i + %w = load <4 x i16>, ptr addrspace(1) %p, align 8 + %h = bitcast <4 x i16> %w to <4 x half> + %at = insertelement <2 x i32> zeroinitializer, i32 %gid, i64 0 + %t = load ptr addrspace(1), ptr addrspace(2) %held, align 8 + tail call void @air.write_texture_2d.v4f16(ptr addrspace(1) %t, <2 x i32> %at, <4 x half> %h, i32 0, i32 2) + ret void +} + +declare void @air.write_texture_2d.v4f16(ptr addrspace(1), <2 x i32>, <4 x half>, i32, i32) + +!air.kernel = !{!0} +!air.version = !{!20} +!air.language_version = !{!21} +!0 = !{ptr @k, !1, !2} +!1 = !{} +!2 = !{!3, !4, !5} +!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"ushort4", !"air.arg_name", !"v"} +!4 = !{i32 1, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 2, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !6, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"Held", !"air.arg_name", !"held"} +!5 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"} +!6 = !{i32 0, i32 8, i32 0, !"texture2d", !"t", !"air.indirect_argument", !7} +!7 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!20 = !{i32 2, i32 8, i32 0} +!21 = !{!"Metal", i32 4, i32 0, i32 0} +"#; + +/// A `half` write through an argument buffer records `PrecisionNote::DeviceNanEncoding` under the +/// families of the textures its handles can name (`SpecKey::HeapNanFamilies`): on every committed +/// profile with a heap, one clause for each family whose stored NaN is the device's there (a +/// 16-bit float format without `DriverDeviation::MetalHalfTexelWrites`, a 32-bit one without +/// `DriverDeviation::MetalNanMoves`, a packed small float one without +/// `DriverDeviation::MetalSmallFloatNans`, and a float format of none of those), each family the +/// profile takes requiring its property. A plan gives the key from the command's resident textures +/// (`R16Float` 1, `RGBA32Float` 2, `RG11B10Float` 4, `RGBA8Unorm` and `R32Uint` 0), and the note +/// holds under the plan's values exactly where a resident texture is of a family of a clause: +/// on `moltenvk-m3`, which takes the 32-bit and small float deviations, an `RGBA32Float` or +/// `RG11B10Float` texture alone holds none. +#[test] +fn a_heap_half_write_s_nan_note_follows_the_families_its_command_can_name() { + use crate::bind::{ResourceClass, UsedResource}; + use crate::device::requirements::VkProperty; + use crate::error::DriverDeviation as D; + use crate::pipeline::{PrecisionNote, SpecClause}; + let note = PrecisionNote::DeviceNanEncoding; + let key = SpecKey::HeapNanFamilies(Stage::Kernel); + let Some(bc) = assemble("heap_half_write", HALF_WRITE) else { + return; + }; + // Each family's bit, and the deviation and property under which its stored NaN is Metal's. + let families = [ + ( + 1, + Some((D::MetalHalfTexelWrites, VkProperty::MetalHalfTexelWrites)), + ), + (2, Some((D::MetalNanMoves, VkProperty::MetalNanMoves))), + ( + 4, + Some((D::MetalSmallFloatNans, VkProperty::MetalSmallFloatNans)), + ), + (8, None), + ]; + // The families of the note's clauses: each a test of the key's own bit. + let noted = |specialized: &[crate::pipeline::SpecializedNote]| -> u32 { + let when: Vec<&SpecClause> = specialized + .iter() + .filter(|n| n.note == note) + .flat_map(|n| &n.when) + .collect(); + when.iter().fold(0, |bits, c| match &c.all[..] { + [t] if t.key == key && t.mask == t.bits && t.equal => bits | t.bits, + _ => panic!("a clause past the families: {c:?}"), + }) + }; + let consts = FunctionConstantValues::defaults(); + let entry = EntryRef::Name("k"); + let mut compiled = 0; + let mut quiet = 0; + for (stem, p) in committed_profiles().expect("profiles") { + let a = match compile_bitcode( + &bc, + entry, + &consts, + &p, + &LowerInputs::new(), + &mut meter(), + SPIRV_WORDS, + ) { + Ok(a) => a, + Err(Error::Unsupported(Unsupported { + feature: Feature::ArgumentBufferTextures, + .. + })) => continue, + Err(e) => panic!("{stem}: {e}"), + }; + let bits = noted(&a.specialized); + for (bit, measured) in families { + let takes = measured.is_some_and(|(d, _)| p.takes_driver_deviation(d)); + assert_eq!(bits & bit != 0, !takes, "{stem}: family {bit}: {bits}"); + if let Some((_, property)) = measured { + assert_eq!( + a.requirements.properties.contains(&property), + takes, + "{stem}: {property:?}" + ); + } + } + assert_eq!(a.precision.contains(¬e), bits != 0, "{stem}"); + quiet += usize::from(bits & 6 == 0); + compiled += 1; + } + assert!(compiled > 0, "no committed profile has the heap"); + assert!( + quiet > 0, + "no committed profile stores a 32-bit or small float NaN as Metal does" + ); + // A command making `formats` resident, at IDs of their own. + let state = |formats: &[PixelFormat]| BindState { + used_resources: (formats.iter().zip(1u32..)) + .map(|(&pf, token)| { + let mut facts = TextureFacts::new(TextureType::Type2D, pf); + facts.usage = metal::TextureUsage::SHADER_READ; + let mut u = UsedResource::new(ResourceClass::Texture(facts), token); + u.resource_id = Some(0x0000_0001_0000_0000 | u64::from(token) << 4); + u + }) + .collect(), + ..Default::default() + }; + let cases: [(&[PixelFormat], u64); 7] = [ + (&[PixelFormat::R16Float], 1), + (&[PixelFormat::RGBA32Float], 2), + (&[PixelFormat::RG11B10Float], 4), + (&[PixelFormat::RGBA8Unorm], 0), + (&[PixelFormat::R32Uint], 0), + (&[PixelFormat::RGBA32Float, PixelFormat::RGBA8Unorm], 2), + (&[], 0), + ]; + let mut planned = 0; + for (stem, dev) in devices() { + let lib = Library::from_air(&bc).expect("library"); + let f = lib.function("k").expect("function"); + let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); + let p = match dev.compile_compute_pipeline(&d, &Budget::standard()) { + Ok(p) => p, + Err(crate::error::Error::Unsupported(Unsupported { + feature: Feature::ArgumentBufferTextures, + .. + })) => continue, + Err(e) => panic!("{stem}: {e}"), + }; + let bits = u64::from(noted(&p.stage.specialized_notes)); + for (formats, value) in cases { + let what = format!("{formats:?} on {stem}"); + let plan = p + .plan(&dev, &state(formats).shape()) + .unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!(plan.specialized_value(key), Some(value), "{what}"); + let held = (p.stage) + .precision_notes_bound(&plan.specialization, &|k| plan.specialized_value(k)) + .contains(¬e); + assert_eq!(held, value & bits != 0, "{what}: noted families {bits}"); + planned += 1; + } + } + assert!(planned > 0, "no profile has the heap"); +} + /// A `half` read, nearest sample or gather of a texture an argument buffer holds rounds its texel /// through the device's conversion of the texel's `f32` value (`narrow::round_texel`): the /// fetched texel's, merged with the decode routine's texel of a form a heap reads. On diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 902bf25ad..a6b5d0a4c 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -14517,6 +14517,7 @@ variant metal2vulkan::pipeline::SpecKey::BoundTexelFormat BoundTexelFormat(SlotR variant metal2vulkan::pipeline::SpecKey::ConstantLanes ConstantLanes(SlotRef) variant metal2vulkan::pipeline::SpecKey::FilteringArgumentSampler FilteringArgumentSampler variant metal2vulkan::pipeline::SpecKey::FlatLocalSize FlatLocalSize +variant metal2vulkan::pipeline::SpecKey::HeapNanFamilies HeapNanFamilies(Stage) variant metal2vulkan::pipeline::SpecKey::HeapRawTextures HeapRawTextures(Stage) variant metal2vulkan::pipeline::SpecKey::HeapYCbCrTextures HeapYCbCrTextures(Stage) variant metal2vulkan::pipeline::SpecKey::ImageblockHeight ImageblockHeight diff --git a/docs/API.md b/docs/API.md index 5e3aa67dc..6a4573d91 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3696,7 +3696,10 @@ bound. a fragment function computes into a 16-bit float attachment through the pixel interlock: a NaN of the blend is the device's arithmetic's, which the storage image's store converts, where Metal stores every NaN of the blend as `0x7e00`. A texture write records it where the stored NaN is the - device's: a constant texel none of whose lanes is a NaN records nothing. So does a fragment + device's: a constant texel none of whose lanes is a NaN records nothing, and a `half` write + through an argument buffer is announced only at a draw or dispatch whose command can name a + texture of a format family whose stored NaN is the device's (on MoltenVK on the Apple M3 Max, + a 16-bit float one; a 32-bit float or `RG11B10Float` one stores Metal's). So does a fragment function's color output where the device's conversion stores its NaN, but one every return of which holds such a constant records nothing. **Exempt:** a `half` texel's write to a 32-bit float storage image on a profile that takes