From 763965c85404a2bf325ceedbdbf8a5248519572e Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 2 Nov 2026 15:30:33 -0800 Subject: [PATCH] Record a texture write's NaN encoding only where its stored NaN is not measured to be Metal's reims-vgpu treats precision notes as fatal on Apple GPUs. A kernel's write of halves into a 32-bit float or RG11B10Float texture died with DeviceNanEncoding, and through NativeNanEncoding, on the M3 Max where the stored bytes are Metal's; a write of a constant texel with no NaN died the same way on every device. What: - A new DriverDeviation::MetalSmallFloatNans (VkProperty::MetalSmallFloatNans), taken by the APPLE9 MoltenVK row alone: the device stores a float's or a half's NaN written to a B10G11R11_UFLOAT_PACK32 storage image as Metal does. - half_write_nans (a half texel's write) classifies the slot's storage choice: a 16-bit float format takes MetalHalfTexelWrites as before, a 32-bit float one MetalNanMoves (the widened half's bits are Metal's 0x7fc00000), the packed small float one MetalSmallFloatNans; a taken deviation drops the note and requires its property. A slot declared without a format (every float storage choice on MoltenVK and lavapipe) records the note under the bound format's class (a SpecializedNote of BoundTexelFormat), one clause per class the profile does not cover, so the runtime announces it only when such a texture is bound. - half_storage_facts (a float texel's write) drops the small-float note the same way. - A texture write of a constant texel none of whose lanes is a NaN records neither note. - A new module side table, stored_texels, records each texture-family write's texel (kept through edit.rs's retain and the roll pass's check). narrow::moves_unfolded no longer counts a widened half's store as such a texel as an escape: the write's own DeviceNanEncoding accounts for its stored NaN under the format it stores. Verified on this M3 Max, byte for byte against plain Metal (an MSL probe): a float4 write of 33,792 words (16,446 NaNs) and a half4 write of all 65,536 halves (2,046 NaNs) into RG11B10Float, RGBA32Float, RG32Float and R32Float store Metal's bytes; into R16Float and RGBA16Float a half NaN's payload differs (the device stores 0x7e00), so those keep the note. - runtime_lane::half_write_nans on MoltenVK: half writes into rgba32f, r32f and rg11b10f announce nothing and 0 texels differ; rgba16f announces device-nan-encoding (2,045 NaNs differ). Without note_stored_texel the lane fails ("write r32f: ... native-nan-encoding true"). - New core tests: a_half_texel_write_s_nan_into_wide_and_small_float_images_is_metal_s_where_ measured (declared and formatless choices on moltenvk-m3 with and without each deviation, and lavapipe; the bound-class clauses evaluated per format) and a_constant_texel_without_a_nan_ records_no_nan_encoding (zero and 0x7e00 constants, every committed profile); the existing device-nan-encoding and half-storage-notes tests follow the deviations. Each fails with its change disabled (the NaN test forced true; the stored-texel exemption removed). - Notes of every public fixture on moltenvk-m3, lavapipe and nvidia-rtx5080-laptop before and after: DeviceNanEncoding leaves 65 moltenvk-m3 rows and 6 rows on each other profile (constant texels), 17 formatless rows per profile go from unconditional to specialized by bound format, 58 moltenvk-m3 rows lose their small-float clause, NativeNanEncoding leaves 11 moltenvk-m3 rows, and no row gains a note. Consumer AIR on moltenvk-m3: DeviceNanEncoding 33 entries to 21, NativeNanEncoding 9 to 5. Docs: API.md (device-nan-encoding and native-nan-encoding exemptions), HOWTO.md, the PrecisionNote, VkProperty and deviation rustdoc, the driver-facts measurement record. api_signatures gains the two variants. The versions bumped in the previous commit cover this one. (cherry picked from commit 05d96c61107989813c186961087ee70d573cf876) --- .../src/runtime_lane/half_write_nans.rs | 44 +++- crates/metal2vulkan/src/cache/codec.rs | 2 +- crates/metal2vulkan/src/device/derive.rs | 3 + .../metal2vulkan/src/device/driver_facts.rs | 14 ++ crates/metal2vulkan/src/device/profile.rs | 4 + .../metal2vulkan/src/device/requirements.rs | 8 + .../src/device/tests/driver_facts.rs | 11 +- crates/metal2vulkan/src/error/mod.rs | 9 + crates/metal2vulkan/src/lower/arith/narrow.rs | 25 +- crates/metal2vulkan/src/lower/texture/emit.rs | 3 + crates/metal2vulkan/src/lower/texture/mod.rs | 162 +++++++++--- .../metal2vulkan/src/lower/texture/slice.rs | 4 +- crates/metal2vulkan/src/pipeline/artifact.rs | 12 +- .../metal2vulkan/src/spirv/builder/module.rs | 13 + crates/metal2vulkan/src/spirv/ir/edit.rs | 1 + crates/metal2vulkan/src/spirv/ir/module.rs | 8 + crates/metal2vulkan/src/spirv/roll/mod.rs | 1 + .../src/tests/engine_half_storage_notes.rs | 19 +- .../metal2vulkan/src/tests/engine_texture.rs | 236 +++++++++++++++++- crates/metal2vulkan/tests/api_signatures.tsv | 2 + docs/API.md | 20 +- docs/HOWTO.md | 2 +- 22 files changed, 533 insertions(+), 70 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 0a79364ab..8dcd0aeea 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/half_write_nans.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/half_write_nans.rs @@ -15,8 +15,12 @@ //! format's stored words are printed with every lane that differs from Metal's (`in -> stored, //! Metal's`). The write stores the half widened, a NaN's payload in the significand's top bits: //! a 16-bit float channel stores Metal's on a device with `VkProperty::MetalHalfTexelWrites`, a -//! 32-bit or packed float channel's NaN is the device's, and a pipeline whose stores differ -//! announces `device-nan-encoding`. +//! 32-bit one the widened `float`'s bits, 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). use super::degrade_notices::{counts, on_device_with}; use super::{buffer_with, layer_reported_nothing, read_buffer, WAIT}; @@ -318,7 +322,9 @@ 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`; a pipeline whose stores differ announces +/// `VkProperty::MetalHalfTexelWrites`, nor, through a texture slot, 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). #[test] @@ -331,6 +337,7 @@ fn half_writes_store_their_nans_as_metal_or_announce() { on_device_with( |options| { options.announce_each.insert(Degradation::DeviceNanEncoding); + options.announce_each.insert(Degradation::NativeNanEncoding); }, |device, messages| { for access in ["write", "read_write", "held"] { @@ -339,12 +346,21 @@ fn half_writes_store_their_nans_as_metal_or_announce() { let state = kernel(device, access); let texels = stored(device, (&state, access), f); let announced = counts(&messages.take_notices()); - let keeps = device - .compile_device() - .profile() - .enabled() - .properties - .contains(&VkProperty::MetalHalfTexelWrites); + 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) + } + }; let mut differ = Vec::new(); for (x, words) in texels.iter().enumerate() { for (c, &got) in words.iter().enumerate() { @@ -380,6 +396,16 @@ fn half_writes_store_their_nans_as_metal_or_announce() { f.name, differ.len() ); + if measured { + let moved = announced.contains_key(&Degradation::NativeNanEncoding); + assert!( + differ.is_empty() && !noted && !moved, + "{access} {}: {} lanes differ from Metal's, device-nan-encoding \ + {noted}, native-nan-encoding {moved}", + f.name, + differ.len() + ); + } // A 16-bit float channel stores the half's bits where the device keeps // them. if keeps && f.word_bytes == 2 { diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index cc2346e4f..3514512f2 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1033,7 +1033,7 @@ codec_enum! { MetalDepth16Stores, MetalDepth16BiasedStores, MetalInterpolation, MetalFirstVertexIndices, MetalFullQuads, ProvokingVertexModePerPipeline, DepthImageKeepsValuesOutsideUnitRange, MetalNormalizedVertexFetch, MetalAlphaCoverage, InterpolateAtOffsetFromSevenSixteenths, - MetalNanMoves, MetalPackConversions, MetalHalfConversion, + MetalNanMoves, MetalPackConversions, MetalHalfConversion, MetalSmallFloatNans, } VkLimit { MaxComputeWorkGroupSize(f0), MaxComputeWorkGroupCount(f0), MaxComputeWorkGroupInvocations, diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index b7ac6d625..8872d59b9 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -818,6 +818,9 @@ fn enabled_caps(desc: &DeviceDescription, deviations: &BTreeSet if deviations.contains(&DriverDeviation::MetalHalfConversion) { properties.insert(VkProperty::MetalHalfConversion); } + if deviations.contains(&DriverDeviation::MetalSmallFloatNans) { + properties.insert(VkProperty::MetalSmallFloatNans); + } if desc .driver_facts() .contains(&crate::device::DriverFact::DepthImageKeepsValuesOutsideUnitRange) diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index 72f97a9d8..33bc64143 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -449,6 +449,16 @@ pub(crate) fn among( /// a function or an operation computed otherwise than by the conversion, so it stays noted /// (`narrow::rounds_unmeasured`). One row per GPU, as measured. /// +/// `MetalSmallFloatNans`: MoltenVK 1.4.2 hands a storage image write to Metal's own texture +/// write. On the M3 Max under macOS 27.0.1 (2026-11-03), byte for byte against plain Metal, a +/// kernel's `float4` write of 33,792 words (every top-13 payload pattern of a NaN of both signs, +/// 16,384 random words, the quiet and signalling edges and the infinities) and its `half4` write +/// of every one of the 65,536 `half`s (its 2,046 NaNs among them) into `RG11B10Float` store +/// Metal's bytes in every texel, as the same writes do into `RGBA32Float`, `RG32Float` and +/// `R32Float` (a `half` widened by Metal's own `float(half)`, `MetalNanMoves`). Into `R16Float` +/// and `RGBA16Float` a `half` NaN's payload differs (the device stores `0x7e00`), which +/// `MetalHalfTexelWrites` would state, so outside it. One row per GPU, as measured. +/// /// Another driver has none of them, as Vulkan states, and a listed driver on another vendor's GPU /// (or another GPU than a row's) is unmeasured: the profile then takes each one's route without /// it, which the deviation's docs name (`derive.rs`). @@ -647,6 +657,10 @@ pub(crate) const DEVIATIONS: &[Measured] = &[ device: Some(APPLE9), ..moltenvk_on_apple(DriverDeviation::MetalHalfConversion) }, + Measured { + device: Some(APPLE9), + ..moltenvk_on_apple(DriverDeviation::MetalSmallFloatNans) + }, ]; /// NVIDIA's `vendorID`. diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index 5785bc62a..87b8035b5 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -347,6 +347,10 @@ impl DeviceProfile { .enabled .properties .contains(&VkProperty::MetalHalfConversion), + DriverDeviation::MetalSmallFloatNans => f + .enabled + .properties + .contains(&VkProperty::MetalSmallFloatNans), } } diff --git a/crates/metal2vulkan/src/device/requirements.rs b/crates/metal2vulkan/src/device/requirements.rs index 5bb37fbd7..aa79e61e0 100644 --- a/crates/metal2vulkan/src/device/requirements.rs +++ b/crates/metal2vulkan/src/device/requirements.rs @@ -859,6 +859,14 @@ pub enum VkProperty { /// [`PrecisionNote::NativeHalfConversion`](crate::pipeline::PrecisionNote::NativeHalfConversion) /// and requires it. MetalHalfConversion, + /// The device stores a NaN a shader writes to a packed small float storage image + /// (`B10G11R11_UFLOAT_PACK32`) as Metal stores it, a `float`'s or a `half`'s widened (the + /// driver's measured deviation + /// [`DriverDeviation::MetalSmallFloatNans`](crate::error::DriverDeviation::MetalSmallFloatNans)). + /// Vulkan states no encoding for it. A module whose write may reach such an image records no + /// [`PrecisionNote::DeviceNanEncoding`](crate::pipeline::PrecisionNote::DeviceNanEncoding) + /// for it and requires it. + MetalSmallFloatNans, /// `GLSL.std.450 InterpolateAtOffset` at offset `v` reads Metal's `interpolate_at_offset` at /// `v + 7/16`, measured from the pixel's upper-left corner: a device whose description reports /// a MoltenVK driver, whose SPIRV-Cross hands the instruction to Metal so at any release diff --git a/crates/metal2vulkan/src/device/tests/driver_facts.rs b/crates/metal2vulkan/src/device/tests/driver_facts.rs index ac622f6c2..cfe457fa2 100644 --- a/crates/metal2vulkan/src/device/tests/driver_facts.rs +++ b/crates/metal2vulkan/src/device/tests/driver_facts.rs @@ -164,6 +164,10 @@ fn taken(p: &crate::device::DeviceProfile) -> Vec D::MetalHalfConversion, property(VkProperty::MetalHalfConversion), ), + ( + D::MetalSmallFloatNans, + property(VkProperty::MetalSmallFloatNans), + ), ] .into_iter() .inspect(|&(d, taken)| { @@ -178,7 +182,7 @@ fn taken(p: &crate::device::DeviceProfile) -> Vec /// at every release: every Apple GPU's (MoltenVK's lockstep, `float` functions, canonical NaNs, /// sampler, compute cube route and the rest of the seventeen), with the graphics cube route and the /// per-sample depth of macOS 27's Apple9 identity, that identity's normalized -/// storage writes, full quads, normalized vertex fetch, alpha to coverage, moved NaNs, pack conversions and half conversions, and every Apple GPU's 16-bit unorm depth stores, interpolation +/// storage writes, full quads, normalized vertex fetch, alpha to coverage, moved NaNs, pack conversions, half conversions and small-float NaN stores, and every Apple GPU's 16-bit unorm depth stores, interpolation /// and first-vertex indices; lavapipe's `float` color NaNs and half-float storage writes; RADV's on /// the Radeon 780M, ANV's on the Iris Xe of RPL-P and the UHD 770 of RPL-S, and NVIDIA's on the /// RTX 3090 and the RTX 5080 Laptop GPU, as measured there; the 8-bit linear filter's bound where @@ -236,14 +240,15 @@ fn the_profile_takes_the_deviations_its_driver_is_measured_with() { list.push(D::MetalFirstVertexIndices); } // macOS 27's full quads, measured on the M4's identity alone, and its normalized vertex - // fetch, alpha to coverage, moved NaNs, pack conversions and half conversions, measured on the - // M3 Max under it. + // fetch, alpha to coverage, moved NaNs, pack conversions, half conversions and small-float NaN + // stores, measured on the M3 Max under it. m4_measured.push(D::MetalFullQuads); m4_measured.push(D::MetalNormalizedVertexFetch); m4_measured.push(D::MetalAlphaCoverage); m4_measured.push(D::MetalNanMoves); m4_measured.push(D::MetalPackConversions); m4_measured.push(D::MetalHalfConversion); + m4_measured.push(D::MetalSmallFloatNans); let all_of = |d: &DeviceDescription| match d.device_id { crate::device::driver_facts::APPLE9 => m4_measured.clone(), _ => apple_all.clone(), diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index dbdf286cc..a1c59ca01 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -861,6 +861,15 @@ pub enum DriverDeviation { /// of the 65,536 `half`s otherwise than the nearest even `half` of its `float` `tanh`, which the /// device's conversion answers). Unmeasured, each records it. MetalHalfConversion, + /// The device stores the NaN a shader writes to a packed small float storage image + /// (`B10G11R11_UFLOAT_PACK32`, Metal's `RG11B10Float`) as Metal stores the same write: a + /// `float` texel's NaN, whatever its sign and payload, and a `half` texel's, handed to the + /// device widened (`VkProperty::MetalSmallFloatNans`). Where the profile takes it, a write that + /// may reach such an image records no `PrecisionNote::DeviceNanEncoding` for it and the module + /// requires the property; with [`DriverDeviation::MetalNanMoves`], whose widening of a `half` + /// answers Metal's, a widened `half` written there moves its NaN as measured + /// (`lower::arith::narrow::moves_unfolded`). Unmeasured, the write records the note. + MetalSmallFloatNans, } /// A defect of a device's driver in a command the runtime records for itself, never in a diff --git a/crates/metal2vulkan/src/lower/arith/narrow.rs b/crates/metal2vulkan/src/lower/arith/narrow.rs index fa0bf1cf8..f2535f2c3 100644 --- a/crates/metal2vulkan/src/lower/arith/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/narrow.rs @@ -1536,15 +1536,17 @@ fn has_bit(bits: &[u64], v: Value) -> bool { /// arithmetic or comparison instruction, a fused multiply-add, a derivative, a `GLSL.std.450` /// function other than `FrexpStruct`, `ModfStruct` and `Ldexp`, each of which computes a value /// whose NaN Metal answers from the widened value's or its own note records, and a store to a -/// buffer or to workgroup memory, which holds a `float` there; anything else (a store to another -/// class, a call, a return, an atomic, a group or image operation, or its bits read) carries the -/// widened `float` out of the registers or reads its bits before any narrowing. The -/// module holding a 32-bit float constant that is a NaN other than `0x7FC00000`, such as a `half` -/// NaN constant held widened with its payload, which no conversion of the device made, is unfolded -/// too. The measurement covers moves through the registers, and `half` values held as the device's -/// conversions made them. One pass over the constants, then a pass over the instructions per round -/// of the moves' closure and one more, with four bits per value of the module charged to `meter` -/// while it runs. +/// buffer or to workgroup memory, which holds a `float` there, and a texture write's store of it +/// as its texel (`TypedModule::stored_texels`), whose stored NaN the write's own notes account for +/// under the format it stores (`lower::texture::half_write_nans` and `half_storage_facts`); +/// anything else (a store to another class, a call, a return, an atomic, a group or another image +/// operation, or its bits read) carries the widened `float` out of the registers or reads its bits +/// before any narrowing. The module holding a 32-bit float constant that is a NaN other than +/// `0x7FC00000`, such as a `half` NaN constant held widened with its payload, which no conversion +/// of the device made, is unfolded too. The measurement covers moves through the registers, and +/// `half` values held as the device's conversions made them. One pass over the constants, then a +/// pass over the instructions per round of the moves' closure and one more, with four bits per +/// value of the module charged to `meter` while it runs. pub fn moves_unfolded(m: &TypedModule, meter: &mut Meter) -> Result { let float32 = |ty| matches!(m.types().get(ty), Ok(Type::Float { width: 32 })); let payload = m.consts().iter().any(|(_, c)| match &c.kind { @@ -1675,6 +1677,11 @@ pub fn moves_unfolded(m: &TypedModule, meter: &mut Meter) -> Result || (has_bit(&bits, *value) && !held_as_float(*ptr)) } Inst::Load { .. } => false, + Inst::ImageWrite { texel, .. } => { + read || (from + && !(has_bit(&widened, *texel) + && m.stored_texels().contains(texel))) + } Inst::AtomicStore { ptr, .. } => { from || has_bit(&widened, *ptr) || has_bit(&bits, *ptr) } diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index 017e6bf2b..c56a6322a 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -2836,6 +2836,8 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul (true, ImageRef::Heap { handle, .. }) => heap_alpha_in_red(cx, fb, handle, texel, false)?, _ => texel, }; + // The write's notes account for the texel's stored NaN (`moves_unfolded`). + fb.module().note_stored_texel(texel); let mem = texel_memory(cx, fb, &w.image)?; // A write to a sparse texture is dropped. let kept = sparse_writes_kept(cx, fb, &w.image)?; @@ -3021,6 +3023,7 @@ fn slice<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, s: &Slice) -> BR lanes: 4, }; let texel = to_image(fb, &decl, form, held)?; + fb.module().note_stored_texel(texel); let ty = vec(fb, u, dims)?; let delta = if dims == 2 { fb.composite_construct(ty, &[x, y])? diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index f358426e9..e68d7e855 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -2024,13 +2024,15 @@ pub const HEAP_CLASS_CENSUS: &str = "sampler.heap.texel_class"; /// property), else the device's encoding of it (`PrecisionNote::DeviceNanEncoding`). A write that /// may reach a packed small float image ([`small_float_storage`]) stores its NaN as the device /// converts it too: Metal stores every NaN there as its canonical one, and RADV and NVIDIA keep -/// another NaN's payload bits. A slot declared without a format records each note under the format -/// bound there (`m` charged for the clauses), which the runtime announces at a draw or dispatch -/// that binds such a texture. +/// another NaN's payload bits; a device of `DriverDeviation::MetalSmallFloatNans` stores Metal's +/// (the module requires its property). A texel that holds no NaN (`nans` false: a constant none +/// of whose lanes is one) records neither NaN's note. A slot declared without a format records each +/// note under the format bound there (`m` charged for the clauses), which the runtime announces at +/// a draw or dispatch that binds such a texture. pub(super) fn half_storage_facts( cx: &mut SelectCx<'_>, image: ImageRef, - (class, cross): (StorageImageClass, bool), + (class, cross, nans): (StorageImageClass, bool, bool), m: &mut Meter, ) -> Result<(), Error> { use crate::device::requirements::VkProperty; @@ -2051,7 +2053,8 @@ pub(super) fn half_storage_facts( } else { cx.note_when(PrecisionNote::DeviceColorConversion, half.clone(), m)?; } - if cx + if !nans { + } else if cx .profile .takes_driver_deviation(DriverDeviation::MetalHalfStorageNans) { @@ -2067,6 +2070,19 @@ pub(super) fn half_storage_facts( if cross { cx.note_when(PrecisionNote::DeviceColorConversion, small.clone(), m)?; } + if small.is_empty() || !nans { + return Ok(()); + } + if cx + .profile + .takes_driver_deviation(DriverDeviation::MetalSmallFloatNans) + { + cx.families + .texture + .storage_properties + .insert(VkProperty::MetalSmallFloatNans); + return Ok(()); + } cx.note_when(PrecisionNote::DeviceNanEncoding, small, m) } @@ -2118,31 +2134,51 @@ fn stored_where( /// M4 under macOS 27.0.1: every NaN class, both signs, `write` and `read_write`, `Shared` and /// `Private`). The write stores the half widened, its NaN's payload in the significand's top bits, /// which the device converts: a 16-bit float channel's NaN is Metal's on a device of -/// `DriverDeviation::MetalHalfTexelWrites` (the module requires its property), and every other -/// float channel's, a 32-bit one's among them, is the device's. +/// `DriverDeviation::MetalHalfTexelWrites` (the module requires its property); a 32-bit one's is +/// the widened `float`'s bits as written, Metal's `0x7fc00000` where the device's widening is +/// Metal's (`DriverDeviation::MetalNanMoves`, whose property the module then requires); a packed +/// small float one's is Metal's on a device of `DriverDeviation::MetalSmallFloatNans`, which +/// stores every `float` NaN there as Metal does (the module requires its property); and every +/// other float channel's is the device's. /// /// 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 -/// or packed small float channel's, a slot's whose choice declares no format, a texel buffer's -/// declaring none, and a heap element's, which may be any of them. A normalized or integer channel -/// stores no NaN. -pub(super) fn half_write_nans(cx: &mut SelectCx<'_>, image: ImageRef) -> Result<(), Error> { +/// 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 +/// normalized or integer channel stores no NaN. +pub(super) fn half_write_nans( + cx: &mut SelectCx<'_>, + image: ImageRef, + m: &mut Meter, +) -> Result<(), Error> { use crate::device::requirements::VkProperty; use crate::vk::NumericFormat as N; - // Whether the stored NaN is exact (`Exact`), a 16-bit float channel's (`Sixteen`, Metal's on - // the measured deviation), or the device's (`Device`). + // Whether the stored NaN is exact (`Exact`), a 16-bit float channel's (`Sixteen`), a 32-bit + // one's (`Wide`) or a packed small float one's (`Small`), each Metal's on its measured + // deviation, or the device's (`Device`). #[derive(PartialEq)] enum Stored { Exact, Sixteen, + Wide, + Small, Device, + Bound(u32), } let declared = |f: crate::vk::Format| -> Stored { + if f == crate::vk::Format::B10G11R11_UFLOAT_PACK32 { + return Stored::Small; + } let Some(b) = f.block() else { return Stored::Device; }; match (b.color, b.component_bits, b.packed_bits) { (Some(N::Sfloat), Some(16), None) => Stored::Sixteen, + (Some(N::Sfloat), Some(32), None) => Stored::Wide, (Some(N::Sfloat | N::Ufloat), _, _) => Stored::Device, _ => Stored::Exact, } @@ -2153,31 +2189,99 @@ pub(super) fn half_write_nans(cx: &mut SelectCx<'_>, image: ImageRef) -> Result< let slot = slot_of(cx, index)?.slot; match cx.inputs.storage_images.get(&slot) { Some(c) => match c.class { + StorageImageClass::Identity if c.vk_format == crate::vk::Format::UNDEFINED => { + Stored::Bound(index) + } StorageImageClass::Identity => declared(c.vk_format), _ => Stored::Exact, }, - None => Stored::Device, + None => Stored::Bound(index), } } }; - let measured = cx - .profile - .takes_driver_deviation(DriverDeviation::MetalHalfTexelWrites); - match stored { - Stored::Sixteen if measured => { - cx.families - .texture - .storage_properties - .insert(VkProperty::MetalHalfTexelWrites); + 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}; + let family = B::LINEAR | B::HALF | TexelFormat::NAN_FREE; + let packed = TexelFormat::PACKED_MASK; + let bound = |mask, bits| NoteTest::equal(NoteOn::Bound(index), mask, bits); + // Each family the bound class may name, its deviation and its property; and a class of no + // family, which may hold a NaN the device stores as it likes. + let families = [ + ( + [bound(family, B::HALF), bound(packed, 0)].into(), + Some(( + DriverDeviation::MetalHalfTexelWrites, + VkProperty::MetalHalfTexelWrites, + )), + ), + ( + [bound(family, B::LINEAR), bound(packed, 0)].into(), + Some((DriverDeviation::MetalNanMoves, VkProperty::MetalNanMoves)), + ), + ( + [bound(packed, PackedTexels::SmallFloat.class().0)].into(), + Some(( + DriverDeviation::MetalSmallFloatNans, + VkProperty::MetalSmallFloatNans, + )), + ), + ([bound(family, 0), bound(packed, 0)].into(), None), + ]; + let mut when = Vec::new(); + for (clause, measured) in families { + match measured { + Some((deviation, property)) if takes(deviation) => { + cx.families.texture.storage_properties.insert(property); + } + _ => when.push(clause), + } } - Stored::Sixteen | Stored::Device => { + return cx.note_when(PrecisionNote::DeviceNanEncoding, when, m); + } + let measured = match stored { + Stored::Sixteen => Some(( + DriverDeviation::MetalHalfTexelWrites, + VkProperty::MetalHalfTexelWrites, + )), + Stored::Wide => Some((DriverDeviation::MetalNanMoves, VkProperty::MetalNanMoves)), + Stored::Small => Some(( + DriverDeviation::MetalSmallFloatNans, + VkProperty::MetalSmallFloatNans, + )), + Stored::Exact | Stored::Device | Stored::Bound(_) => None, + }; + match measured { + Some((deviation, property)) if takes(deviation) => { + cx.families.texture.storage_properties.insert(property); + } + _ if stored == Stored::Exact => {} + _ => { cx.precision.insert(PrecisionNote::DeviceNanEncoding); } - Stored::Exact => {} } Ok(()) } +/// Whether texel `value` is a constant none of whose lanes is a NaN: a `half` or `float` scalar or +/// vector constant whose every lane's bits are not a NaN's. Its write stores no NaN, so no device's +/// encoding of one can show. An `undef` texel, a composite, and any computed value may hold one. +fn holds_no_nan(cx: &SelectCx<'_>, value: Value) -> bool { + use crate::lower::arith::legal::LoweredConst as C; + use crate::spirv::ids::ScalarTy; + let nan = |ty: ScalarTy, bits: u64| match ty { + ScalarTy::Float { bits: 16 } => bits & 0x7c00 == 0x7c00 && bits & 0x3ff != 0, + ScalarTy::Float { bits: 32 } => bits & 0x7f80_0000 == 0x7f80_0000 && bits & 0x7f_ffff != 0, + _ => true, + }; + match cx.constant(value) { + Some(C::Scalar { ty, bits }) => !nan(ty, bits), + Some(C::Vector { elem, lanes }) => lanes.iter().all(|&bits| !nan(elem, bits)), + _ => false, + } +} + /// Whether a storage read or write of a `float` or `half` texel (`texel`) through heap handle /// `image` of shape `shape` converts an `A8Unorm` member's texels: a heap access, not to a texture /// buffer (no heap class holds one), on a device that holds such a texture's alpha in @@ -3169,11 +3273,13 @@ fn select_write( mode_rounded_write(cx, image, texel, extended.is_some())?; // Its alpha in red where the class is `A8Unorm`'s and the device holds such a texture so. let heap_alpha_red = heap_alpha_in_red(cx, image, shape, texel.conv); + // A constant texel none of whose lanes is a NaN stores none, whatever the device's encoding. + let nans = !holds_no_nan(cx, value); if texel.conv == TexelConv::F32 { - half_storage_facts(cx, image, (class, cross.is_some()), m)?; + half_storage_facts(cx, image, (class, cross.is_some(), nans), m)?; } - if texel.conv == TexelConv::F16 && extended.is_none() { - half_write_nans(cx, image)?; + if texel.conv == TexelConv::F16 && extended.is_none() && nans { + half_write_nans(cx, image, m)?; } // A `half` texel's too, held widened: Metal stores its value by the same rule. if matches!(texel.conv, TexelConv::F32 | TexelConv::F16) && extended.is_none() { diff --git a/crates/metal2vulkan/src/lower/texture/slice.rs b/crates/metal2vulkan/src/lower/texture/slice.rs index 0fb9271bb..ecde8db84 100644 --- a/crates/metal2vulkan/src/lower/texture/slice.rs +++ b/crates/metal2vulkan/src/lower/texture/slice.rs @@ -299,13 +299,13 @@ pub(super) fn select( let guard = slot::write_guard(cx, false); let class = super::storage_class(cx, image)?; if conv == TexelConv::F32 { - super::half_storage_facts(cx, image, (class, false), m)?; + super::half_storage_facts(cx, image, (class, false, true), m)?; } if matches!(conv, TexelConv::F32 | TexelConv::F16) { super::norm_storage_facts(cx, image, t.image, TexelForm { conv, lanes })?; } if conv == TexelConv::F16 { - super::half_write_nans(cx, image)?; + super::half_write_nans(cx, image, m)?; } mark(cx, image, |u| u.write = true); // Every invocation shares the write where its guard selects local id 0 at a uniform point. diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 12c0150ac..3fc35d269 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -869,7 +869,12 @@ pub enum PrecisionNote { /// field the quiet NaN (`0x7e0`, `0x3f0`), and the device's copy keeps its bits. And for a /// plain color fill to a NaN of a half or small-float texture the device's clear writes: the /// device converts the NaN as it likes, where Metal's fill keeps a half NaN's sign and payload - /// and makes a small float's all ones. Validation derives no tolerance and no explanation from + /// and makes a small float's all ones. Not recorded by a texture write of a constant texel none + /// of whose lanes is a NaN, nor where the write's stored NaN is measured to be Metal's (MoltenVK + /// on the Apple M3 Max's macOS 27 identity): a `half` texel's write to a 32-bit float format on + /// a profile that takes `DriverDeviation::MetalNanMoves`, and a `float` or `half` texel's write + /// to `RG11B10Float` on one that takes `DriverDeviation::MetalSmallFloatNans` (the module then + /// requires the matching `VkProperty`). Validation derives no tolerance and no explanation from /// it, as for `DeviceDenormals`. DeviceNanEncoding, /// The device compares a depth texture's texels (a sample or a gather with comparison) on a @@ -1815,8 +1820,9 @@ pub enum PrecisionNote { /// on a device whose moves of a NaN are measured to be Metal's (MoltenVK on the Apple M3 Max's /// macOS 27 identity, `DriverDeviation::MetalNanMoves`), for a `float` `fneg` or `fabs`, a /// `half`'s widening to `float` or `fabs`, or a module's reads and encodes of a `half`'s bits - /// where it moves its `half` values through the registers alone. Validation derives no - /// tolerance from it. + /// where it moves its `half` values through the registers alone, or into a texture write's + /// texel, whose store the write's [`PrecisionNote::DeviceNanEncoding`] accounts for. + /// Validation derives no tolerance from it. NativeNanEncoding, /// Native device maths: Metal's `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` (its /// `clamp(x, +0, 1)`) on `float` or `half` is the device's `GLSL.std.450` `NMin`, `NMax` or diff --git a/crates/metal2vulkan/src/spirv/builder/module.rs b/crates/metal2vulkan/src/spirv/builder/module.rs index 247769d99..c3067a6ea 100644 --- a/crates/metal2vulkan/src/spirv/builder/module.rs +++ b/crates/metal2vulkan/src/spirv/builder/module.rs @@ -106,6 +106,11 @@ pub struct ModuleBuilder { /// (`ModuleBuilder::note_measured_rounding`). Nothing emitted depends on it: the compile /// reads it to decide `PrecisionNote::NativeHalfConversion`. pub(super) measured_roundings: BTreeSet, + /// The texels the texture family's writes store (`ModuleBuilder::note_stored_texel`), whose + /// stored NaN the write's own notes account for (`lower::texture::half_write_nans` and + /// `half_storage_facts`). Nothing emitted depends on it: the compile reads it to decide + /// `PrecisionNote::NativeNanEncoding` (`lower::arith::narrow::moves_unfolded`). + pub(super) stored_texels: BTreeSet, /// The `Function` variables the emitter holds workgroup uniform by construction /// (`FunctionBuilder::note_uniform_var`). Nothing emitted depends on it: a record for the /// checks of `spirv::testing::barriers`, kept only where they build. @@ -293,6 +298,12 @@ impl ModuleBuilder { self.measured_roundings.insert(narrowed); } + /// Record `texel`, a texel a texture write stores, whose stored NaN the write's own notes + /// account for (`lower::texture::emit`). + pub fn note_stored_texel(&mut self, texel: Value) { + self.stored_texels.insert(texel); + } + /// Whether the module's `half` rounding is the device's own /// ([`ModuleBuilder::set_native_half`]). pub fn native_half(&self) -> bool { @@ -355,6 +366,7 @@ impl ModuleBuilder { ) + tree_bytes(self.non_uniform.len(), std::mem::size_of::()) + tree_bytes(self.measured_roundings.len(), std::mem::size_of::()) + + tree_bytes(self.stored_texels.len(), std::mem::size_of::()) + map_bytes(&self.bits) + map_bytes(&self.lanes) + map_bytes(&self.inserts) @@ -1360,6 +1372,7 @@ impl ModuleBuilder { enabling: self.enabling, non_uniform: self.non_uniform, measured_roundings: self.measured_roundings, + stored_texels: self.stored_texels, #[cfg(test)] uniform_vars: self.uniform_vars, }) diff --git a/crates/metal2vulkan/src/spirv/ir/edit.rs b/crates/metal2vulkan/src/spirv/ir/edit.rs index 4f9df4b18..0b3ea69b4 100644 --- a/crates/metal2vulkan/src/spirv/ir/edit.rs +++ b/crates/metal2vulkan/src/spirv/ir/edit.rs @@ -406,6 +406,7 @@ impl TypedModule { let values = &self.values; self.non_uniform.retain(|v| !removed(v, values)); self.measured_roundings.retain(|v| !removed(v, values)); + self.stored_texels.retain(|v| !removed(v, values)); self.loops.retain(|l| at(&bmap, l.header.index()).is_some()); for l in &mut self.loops { l.header = block(l.header); diff --git a/crates/metal2vulkan/src/spirv/ir/module.rs b/crates/metal2vulkan/src/spirv/ir/module.rs index f815f1a62..5a8926bee 100644 --- a/crates/metal2vulkan/src/spirv/ir/module.rs +++ b/crates/metal2vulkan/src/spirv/ir/module.rs @@ -1438,6 +1438,9 @@ pub struct TypedModule { /// to answer Metal's where the driver takes `DriverDeviation::MetalHalfConversion` /// (`ModuleBuilder::measured_roundings`), recorded as the builder emits them. pub(in crate::spirv) measured_roundings: std::collections::BTreeSet, + /// The texels the texture family's writes store, whose stored NaN the write's own notes + /// account for (`ModuleBuilder::stored_texels`), recorded as the builder emits them. + pub(in crate::spirv) stored_texels: std::collections::BTreeSet, /// The `Function` variables the emitter holds workgroup uniform by construction: the `cont` /// flag of a predicated loop that iterates together, which the lowering's uniformity analysis /// proved. An in-memory record for checks (`spirv::testing::barriers`), kept only where they @@ -1469,6 +1472,11 @@ impl TypedModule { &self.measured_roundings } + /// The texels the texture family's writes store (`ModuleBuilder::note_stored_texel`). + pub fn stored_texels(&self) -> &std::collections::BTreeSet { + &self.stored_texels + } + /// The SSA value of a constant. pub fn const_value(&self, c: ConstId) -> BResult { self.const_values diff --git a/crates/metal2vulkan/src/spirv/roll/mod.rs b/crates/metal2vulkan/src/spirv/roll/mod.rs index 6c2e657b7..1d3a63ed7 100644 --- a/crates/metal2vulkan/src/spirv/roll/mod.rs +++ b/crates/metal2vulkan/src/spirv/roll/mod.rs @@ -1855,6 +1855,7 @@ fn verify( if m.value(x)?.ty != m.value(y)?.ty || m.non_uniform.contains(&x) != m.non_uniform.contains(&y) || m.measured_roundings.contains(&x) != m.measured_roundings.contains(&y) + || m.stored_texels.contains(&x) != m.stored_texels.contains(&y) { return Ok(None); } diff --git a/crates/metal2vulkan/src/tests/engine_half_storage_notes.rs b/crates/metal2vulkan/src/tests/engine_half_storage_notes.rs index c66a9ee18..02e930cc1 100644 --- a/crates/metal2vulkan/src/tests/engine_half_storage_notes.rs +++ b/crates/metal2vulkan/src/tests/engine_half_storage_notes.rs @@ -156,6 +156,7 @@ fn a_float_write_notes_the_device_s_half_conversion_under_the_bound_format() { let p = dev.profile(); let rounds = p.takes_driver_deviation(DriverDeviation::MetalHalfStorageWrites); let nans = p.takes_driver_deviation(DriverDeviation::MetalHalfStorageNans); + let small_nans = p.takes_driver_deviation(DriverDeviation::MetalSmallFloatNans); for (entry, buffer) in [ ("hsw_write", false), ("hsw_read_write", false), @@ -202,10 +203,20 @@ fn a_float_write_notes_the_device_s_half_conversion_under_the_bound_format() { continue; } // Metal stores a small float's every NaN as its canonical one, and RADV and - // NVIDIA keep another's payload bits; a 32-bit float or normalized channel takes - // no half's NaN. + // NVIDIA keep another's payload bits, where a device of `MetalSmallFloatNans` + // stores Metal's; a 32-bit float or normalized channel takes no half's NaN. let small = pf == PixelFormat::RG11B10Float; - assert_eq!(nan, small, "{what}: {:?}", stage.specialized_notes); + assert_eq!( + nan, + small && !small_nans, + "{what}: {:?}", + stage.specialized_notes + ); + // Required wherever the module may store into a small float, on the deviation. + let relies = relied.contains(&VkProperty::MetalSmallFloatNans); + assert!(small_nans || !relies, "{what}"); + assert!(!small || relies == small_nans, "{what}"); + measured += usize::from(small && small_nans); } // The module of no storage choice serves every format the device writes without one: // its NaN note holds of the half-float classes (where the device's NaN is not Metal's) @@ -219,7 +230,7 @@ fn a_float_write_notes_the_device_s_half_conversion_under_the_bound_format() { let small = matches!(pf, P::RG11B10Float | P::RGB9E5Float); assert_eq!( announced(&plain.stage, PrecisionNote::DeviceNanEncoding, pf), - (half && !nans) || small, + (half && !nans) || (small && !small_nans), "{entry} without a storage choice, bound as {pf:?}, on {stem}" ); } diff --git a/crates/metal2vulkan/src/tests/engine_texture.rs b/crates/metal2vulkan/src/tests/engine_texture.rs index c41a84b7f..bda684adf 100644 --- a/crates/metal2vulkan/src/tests/engine_texture.rs +++ b/crates/metal2vulkan/src/tests/engine_texture.rs @@ -428,9 +428,12 @@ const OP_IS_NAN: u16 = 156; /// `DriverDeviation::MetalHalfTexelWrites`, and requires `VkProperty::MetalHalfTexelWrites` on one /// with it (a choice of a class rounding to `half` is a 16-bit float format's, declared or not; /// such a device's own choice declares no format, so the test declares one there too); -/// bound in `RGBA8Unorm` it records none. Where the choice declares no format and no class, the -/// write records the note. A choice declaring `RGBA16Float` on every profile records the note or -/// requires the property as the profile's deviation says. +/// bound in `RGBA8Unorm` it records none; bound in `RGBA32Float` it records none on a profile +/// whose widening of a `half` is Metal's (`DriverDeviation::MetalNanMoves`), which it then +/// requires. Where the choice declares no format and no class, the write records the note under +/// the format bound there. A +/// choice declaring `RGBA16Float` on every profile records the note or requires the property as +/// the profile's deviation says. #[test] fn a_half_texel_write_records_the_device_nan_encoding_where_it_may_not_be_metal_s() { use crate::device::requirements::VkProperty; @@ -470,7 +473,12 @@ fn a_half_texel_write_records_the_device_nan_encoding_where_it_may_not_be_metal_ }; let what = format!("{stem}: {pf:?}: tests {}, noted {}", tests(&a), noted(&a)); if undeclared { - assert!(noted(&a), "{what}"); + // Noted under the bound format: a class of no family always may hold a NaN. + let specialized = a + .specialized + .iter() + .any(|n| n.note == PrecisionNote::DeviceNanEncoding); + assert!(noted(&a) && specialized, "{what}"); formatless += 1; continue; } @@ -487,7 +495,16 @@ fn a_half_texel_write_records_the_device_nan_encoding_where_it_may_not_be_metal_ measured += usize::from(keeps); } PixelFormat::RGBA32Float => { - assert!(!tests(&a) && noted(&a), "{what}"); + // The widened `half`'s bits as written: Metal's where the widening is. + let moves = p.takes_driver_deviation(DriverDeviation::MetalNanMoves); + assert!(!tests(&a) && noted(&a) == !moves, "{what}"); + assert_eq!( + a.requirements + .properties + .contains(&VkProperty::MetalNanMoves), + moves, + "{what}" + ); float += 1; } _ => assert!(!noted(&a), "{what}"), @@ -529,6 +546,215 @@ fn a_half_texel_write_records_the_device_nan_encoding_where_it_may_not_be_metal_ ); } +/// The NaN of a `half` texel a kernel loads from a buffer and writes (`fpv_srgb_write_half`): the +/// write's own `DeviceNanEncoding` accounts for it, so on a profile whose widening of a `half` is +/// Metal's (`DriverDeviation::MetalNanMoves`, `moltenvk-m3`) the module records no +/// `NativeNanEncoding` for the texel it stores, and records it with that deviation dropped and on +/// `lavapipe`. The write records `DeviceNanEncoding` where the store's NaN is the device's: under a +/// choice declaring a 32-bit float format but where the profile takes `MetalNanMoves` (the image +/// stores the widened `float`'s bits, Metal's `0x7fc00000`), declaring the packed small float one +/// but where it takes `DriverDeviation::MetalSmallFloatNans`, and declaring a 16-bit float one but +/// where it takes `DriverDeviation::MetalHalfTexelWrites`, each requiring its property; under a +/// formatless choice it records the note under the bound format's class for each of those +/// families whose deviation the profile lacks and for a class of no family. +#[test] +fn a_half_texel_write_s_nan_into_wide_and_small_float_images_is_metal_s_where_measured() { + use crate::device::requirements::VkProperty; + use crate::error::DriverDeviation; + use crate::metal::texel_format::texel_format; + use crate::pipeline::lower_inputs::StorageImageChoice; + use crate::vk::Format as F; + let Some(bc) = fixture("fpv_srgb_storage") else { + return; + }; + let slot = texture_slot(0); + let committed = |stem: &str, dropped: Option| { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/profiles") + .join(format!("{stem}.json")); + let text = std::fs::read_to_string(&path).expect("profile"); + let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); + match dropped { + Some(d) => Device::with_deviation(desc, DevicePolicy::default(), d, false), + None => Device::new(desc, DevicePolicy::default()), + } + .expect("device") + .profile() + .clone() + }; + // Whether the specialized note of `a` holds of a texture of `pf` bound at the slot. + let holds = |a: &FunctionArtifact, pf: PixelFormat| { + a.specialized + .iter() + .filter(|n| n.note == PrecisionNote::DeviceNanEncoding) + .flat_map(|n| &n.when) + .any(|c| { + c.all + .iter() + .all(|t| (texel_format(pf).0 & t.mask == t.bits) == t.equal) + }) + }; + let mut exempt = 0; + for (stem, dropped) in [ + ("moltenvk-m3", None), + ("moltenvk-m3", Some(DriverDeviation::MetalSmallFloatNans)), + ("moltenvk-m3", Some(DriverDeviation::MetalNanMoves)), + ("lavapipe", None), + ] { + let p = committed(stem, dropped); + let takes = |d| p.takes_driver_deviation(d); + let moves = takes(DriverDeviation::MetalNanMoves); + // Each format's family: its declared choice, its deviation and property. + let families = [ + ( + PixelFormat::RGBA32Float, + F::R32G32B32A32_SFLOAT, + DriverDeviation::MetalNanMoves, + VkProperty::MetalNanMoves, + ), + ( + PixelFormat::RG11B10Float, + F::B10G11R11_UFLOAT_PACK32, + DriverDeviation::MetalSmallFloatNans, + VkProperty::MetalSmallFloatNans, + ), + ( + PixelFormat::RGBA16Float, + F::R16G16B16A16_SFLOAT, + DriverDeviation::MetalHalfTexelWrites, + VkProperty::MetalHalfTexelWrites, + ), + ]; + let compiled = |format: F| { + let mut inputs = LowerInputs::new(); + inputs.storage_images.insert( + slot, + StorageImageChoice::new(format, StorageImageClass::Identity), + ); + let what = format!("{stem} without {dropped:?}: {format:?}"); + let a = ok( + with_inputs(&bc, "fpv_srgb_write_half", &p, &inputs), + &p, + &what, + ); + // The stored texel's moves are the write's to account for. + assert_eq!( + a.precision.contains(&PrecisionNote::NativeNanEncoding), + !moves, + "{what}: {:?}", + a.precision + ); + (a, what) + }; + for (_, format, deviation, property) in families { + let (a, what) = compiled(format); + let measured = takes(deviation); + assert_eq!( + a.precision.contains(&PrecisionNote::DeviceNanEncoding), + !measured, + "{what}: {:?}", + a.precision + ); + assert!(a.specialized.is_empty(), "{what}: {:?}", a.specialized); + assert!( + !measured || a.requirements.properties.contains(&property), + "{what}" + ); + exempt += usize::from(measured && moves); + } + let (a, what) = compiled(F::UNDEFINED); + for (pf, _, deviation, property) in families { + let measured = takes(deviation); + assert_eq!(holds(&a, pf), !measured, "{what}: bound as {pf:?}"); + assert!( + !measured || a.requirements.properties.contains(&property), + "{what}: bound as {pf:?}" + ); + } + assert!(!holds(&a, PixelFormat::RGBA8Unorm), "{what}: RGBA8Unorm"); + } + assert_eq!( + exempt, 3, + "the measured stores: two on moltenvk-m3, one without its small floats" + ); +} + +/// A constant texel none of whose lanes is a NaN stores no NaN, so its write records no +/// `DeviceNanEncoding` whatever the device's encoding: `storage_texture_write`'s `float4` constant +/// and `txt_level_write` with its texel made a `half4` constant, under a choice of each float +/// format and a formatless one, on every committed profile. The same writes of a computed or NaN +/// texel record it under the formatless choice. +#[test] +fn a_constant_texel_without_a_nan_records_no_nan_encoding() { + use crate::pipeline::lower_inputs::StorageImageChoice; + use crate::vk::Format as F; + let Some(computed) = fixture("txt_level_write") else { + return; + }; + let text = std::fs::read_to_string(engine_dir().join("txt_level_write.ll")).expect("fixture"); + let body: String = text + .lines() + .filter(|l| !l.starts_with("target ")) + .map(|l| format!("{l}\n")) + .collect(); + let texel = "<4 x half> %9, i16 %10"; + assert_eq!(body.matches(texel).count(), 1, "txt_level_write's write"); + let constant = |lanes: &str| body.replace(texel, &format!("<4 x half> <{lanes}>, i16 %10")); + let Some(zero) = assemble( + "half-constant", + &constant("half 0xH0000, half 0xH3C00, half 0xH8000, half 0xH7BFF"), + ) else { + return; + }; + let nan = assemble( + "half-nan", + &constant("half 0xH0000, half 0xH7E00, half 0xH0000, half 0xH3C00"), + ) + .expect("assembled"); + let Some(float) = fixture("storage_texture_write") else { + return; + }; + let slot = texture_slot(0); + let mut formatless = 0; + for (stem, p) in committed_profiles().expect("profiles") { + for format in [ + F::R16G16B16A16_SFLOAT, + F::R32G32B32A32_SFLOAT, + F::B10G11R11_UFLOAT_PACK32, + F::UNDEFINED, + ] { + let mut inputs = LowerInputs::new(); + inputs.storage_images.insert( + slot, + StorageImageChoice::new(format, StorageImageClass::Identity), + ); + for (bc, entry, constant) in [ + (&zero, "txt_level_write", true), + (&nan, "txt_level_write", false), + (&computed, "txt_level_write", false), + (&float, "storage_texture_write", true), + ] { + let what = format!("{stem}: {entry} under {format:?}, constant {constant}"); + let a = match with_inputs(bc, entry, &p, &inputs) { + Err(Error::NeedsInput(_) | Error::Unsupported(_)) => continue, + a => ok(a, &p, &what), + }; + let noted = a.precision.contains(&PrecisionNote::DeviceNanEncoding) + || a.specialized + .iter() + .any(|n| n.note == PrecisionNote::DeviceNanEncoding); + if constant { + assert!(!noted, "{what}: {:?}", a.precision); + } else if format == F::UNDEFINED && entry == "txt_level_write" { + assert!(noted, "{what}"); + formatless += 1; + } + } + } + } + assert!(formatless > 0, "no profile compiled the formatless writes"); +} + /// Cube reads by face use the binder's 2D-array view (`ImageViewShape`), and a cube array's /// array size is its layer count over six. #[test] diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index d4b2c9ab6..d5e89d663 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -13002,6 +13002,7 @@ variant metal2vulkan::device::VkProperty::MetalNormalizedVertexFetch MetalNormal variant metal2vulkan::device::VkProperty::MetalPackConversions MetalPackConversions variant metal2vulkan::device::VkProperty::MetalSampler MetalSampler variant metal2vulkan::device::VkProperty::MetalSmallFloatColorWrites MetalSmallFloatColorWrites +variant metal2vulkan::device::VkProperty::MetalSmallFloatNans MetalSmallFloatNans variant metal2vulkan::device::VkProperty::MetalVertexSimdgroups MetalVertexSimdgroups variant metal2vulkan::device::VkProperty::ProvokingVertexModePerPipeline ProvokingVertexModePerPipeline variant metal2vulkan::device::VkProperty::RequiredSubgroupSizeStage RequiredSubgroupSizeStage(Stage) @@ -13162,6 +13163,7 @@ variant metal2vulkan::error::DriverDeviation::MetalNormalizedVertexFetch MetalNo variant metal2vulkan::error::DriverDeviation::MetalPackConversions MetalPackConversions variant metal2vulkan::error::DriverDeviation::MetalSampler MetalSampler variant metal2vulkan::error::DriverDeviation::MetalSmallFloatColorWrites MetalSmallFloatColorWrites +variant metal2vulkan::error::DriverDeviation::MetalSmallFloatNans MetalSmallFloatNans variant metal2vulkan::error::DriverDeviation::MetalVertexSimdgroups MetalVertexSimdgroups variant metal2vulkan::error::DriverDeviation::SampleFragCoordDepth SampleFragCoordDepth variant metal2vulkan::error::DriverDeviation::SimdgroupLockstep SimdgroupLockstep diff --git a/docs/API.md b/docs/API.md index 73d02eca0..03dd783b3 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3079,7 +3079,15 @@ bound. Metal's fill keeps a half NaN's sign and payload and makes a small float's all ones. Also a blend 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`. + 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. **Exempt:** a `half` + texel's write to a 32-bit float storage image on a profile that takes + `DriverDeviation::MetalNanMoves` (the image stores the widened `float`'s bits, Metal's + `0x7fc00000`; the module requires `VkProperty::MetalNanMoves`), and a `float` or `half` texel's + write to a packed small float one (`RG11B10Float`) on a profile that takes + `DriverDeviation::MetalSmallFloatNans`, MoltenVK on Apple's GPUs of the Apple M3 Max's macOS 27 + identity, measured byte for byte against plain Metal over every `half` and 33,792 `float` words, + 16,446 NaNs among them (the module requires `VkProperty::MetalSmallFloatNans`). - `metal2vulkan-degrade-restricted-depth-range` (precision). `PrecisionNote::RestrictedDepthRange`: The device compares a depth texture's texels on a device without `VK_EXT_depth_range_unrestricted` enabled whose driver is not measured to keep depth values outside `[0, 1]` without it. @@ -3493,10 +3501,12 @@ bound. `fabs`, a `half`'s widening to `float`, a `half` `fabs`, and a module's reads and encodes of a `half`'s bits record no note and require `VkProperty::MetalNanMoves`. The exemption stops where the module carries a widened `half` out of the registers before narrowing it (a store to a stage - output or a variable other than a function's `float` one, a call, a return, a group, atomic or - image operation), reads its widened bits (a bitcast but to store them to memory, `frexp`, - `modf`, `ldexp`), or holds a `float` NaN constant other than `0x7fc00000`: such a module - records the note there too. A `half` `fneg` records it on every device. + output or a variable other than a function's `float` one, a call, a return, a group or atomic + operation, an image operation but a texture write of it, whose store the write's own + `PrecisionNote::DeviceNanEncoding` accounts for), reads its widened bits (a bitcast but to store + them to memory, `frexp`, `modf`, `ldexp`), or holds a `float` NaN constant other than + `0x7fc00000`: such a module records the note there too. A `half` `fneg` records it on every + device. - `metal2vulkan-degrade-native-min-max` (precision). `PrecisionNote::NativeMinMax`: Native device maths: Metal's `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` (its `clamp(x, +0, 1)`) on `float` or `half` is the device's `GLSL.std.450` `NMin`, `NMax` or `NClamp`, on a device not diff --git a/docs/HOWTO.md b/docs/HOWTO.md index c87c52ac3..656ab0b7e 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -56,7 +56,7 @@ UnpackHalf2x16` without it), and a `half` stored or reinterpreted as bits, unles bits it was loaded from, the device's narrowing (an `OpFConvert` to 16 bits, `GLSL.std.450 PackHalf2x16` without `shaderFloat16`); the pipeline records `NativeNanEncoding` (a NaN's bits; not on MoltenVK on the Apple M3 Max's macOS 27 identity, `DriverDeviation::MetalNanMoves`, where -the `half` moves through the registers alone) and, where that conversion is neither under the +the `half` moves through the registers alone or into a texture write's texel) and, where that conversion is neither under the float controls nor measured to be Metal's, `NativeHalfConversion` (a denormal the device may flush).