From 79166a74b19742aa7a6b63b1acffc03c2bd4b366 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 27 Oct 2026 18:28:03 +0200 Subject: [PATCH] Leave NaN bits and min/max picks to the device One work packet, landed as 6 commits (a6e97e7f93..3919c8c94a on archive/development-linear-2026-10-28), in order: * Leave NaN bits and min/max picks to the device On the owner's ruling to promise the GPU's native arithmetic with no exact emulation, delete the NaN and minimum/maximum switch and every form that only it, or Metal's NaN bits, kept. What goes: - DevicePolicy::nan_and_min_max and NanMinMaxPolicy (exact_answers line, serde, ExactFormsOverCompilerLimit::nan_and_min_max, the fit leg). - The module's selects of Metal's NaN: NanEncoding::Device, ArithStrategy::Nan and lower/arith/nan.rs down to its answer classes. A NaN Metal answers that the device is not measured to answer records NativeNanEncoding. - Metal's operand pick in fmin, fmax, min3, max3, clamp and saturate (metal_min_max, metal_saturate, MinMaxRoute): NMin, NMax and NClamp on every profile, NativeMinMax where MetalMinMax is not taken. - Metal's texel NaN rule (TexelNanRoute, the 0x7e00 keeps, the half texel NaN keep, the NaN classes of reads, samples and gathers). - NaN canonicalization before colour and storage writes: StorageImageClass::HalfQuietNan and SmallFloatQuietNan, the half write NaN classes (HalfNans), the quieted heap small floats, the colour lanes that chose 0x7fc00000, the 16-bit colour outputs (StageIo and StageModule half_bit_colors, IoType::bits, Degradation:: ShaderHalfColorBits), PushField::TextureHalfChannels, RuntimeFact::StorageTextureHalfChannels and the slot word behind it. Such writes record DeviceNanEncoding where the stored NaN may not be Metal's (heap and formatless writes, 32-bit and packed float channels). - The narrow-float vertex fetch's canonical NaN: noted instead. - The runtime's colour NaN clears (nan_clear::NanClears and its texel computation, the inline-first NaN clear refusal, WorkCounts:: passes_not_inline_actions_nan_clear): the device's clear, announced as DeviceNanEncoding. The depth NaN clear and the bit-exact copies stay. - FAST-PATHS rows for the switch, the half texel keep and the half from bits under float controls; the known gap of RADV's sampler NaN; the API.md passages and catalogue entries. Kept: the notes that describe the native answer (NativeNanEncoding, NativeMinMax, DeviceNanEncoding), the measured deviations they read, the copy and depth paths, keeps_nan_sign, the heap half-bits twin, the half rounding and the blended snorm NaN of other lanes. Versions: SEMANTICS_VERSION 1871, ARTIFACT_FORMAT_VERSION 454, RUNTIME_VERSION 1652. docs/REFUSALS.md regenerated. Verified: cargo clippy --workspace --all-targets --all-features -D warnings, plain and with --cfg m2v_gpu; RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps; nextest of metal2vulkan filtered to the touched modules, fast_paths, catalogue, degradation, api_surface and profile (see the report for counts), and of the runtime, validation and conformance unit tests touched. No device test was run. * Re-bless the API signatures after the NaN and min/max deletion The table loses the public items the previous commit removed: NanMinMaxPolicy and its variants, DevicePolicy::nan_and_min_max, ExactFormsOverCompilerLimit::nan_and_min_max, PushField:: TextureHalfChannels, RuntimeFact::StorageTextureHalfChannels, StorageImageClass::HalfQuietNan and SmallFloatQuietNan, StageModule::half_bit_colors, Degradation::ShaderHalfColorBits and WorkCounts::passes_not_inline_actions_nan_clear. Verified: python3 scripts/api-signatures/signatures.py --bless; nextest of the api_signatures, api_surface, refusal_surface and feature_vocabulary binaries (21 passed); the previous commit's filtered metal2vulkan run, 1056 passed, plus runtime (53), validation (83 of 84; the failing c3 venue-identity test names the Apple M4 and touches no file of this change) and conformance (38) filtered runs. * Fix the tests the rebase onto development left broken The rebase of the NaN and min/max deletion onto development left two test compile errors: the extended-range samples still round through `half_toward_zero`, which the resolution had dropped with the storage-slot test that used it, and the RGBX storage cases named `HalfQuietNan`, which both sides' deletions removed (a half-float twin is `Identity` now). Verified: cargo clippy --workspace --all-targets --all-features -D warnings, plain and with --cfg m2v_gpu; RUSTDOCFLAGS='-D warnings' cargo doc. * Drop a dead dot form and let formatless half slots note conversion twice select_float_fn still computed dot's scalar result form, which only the removed NaN canonicalization read. The half-float storage test asserted that a formatless slot notes DeviceColorConversion exactly when the profile does not round Metal's way; a formatless slot may also reach a normalized image, whose conversion is the device's on every profile, so the note is only required one way there. Verified: cargo check --workspace --all-targets --all-features is clean. * Leave the fast division's NaN to the device in its test The float-maths lane's a_fast_division_answers_metals_nans_on_every_profile asserted Metal's canonical NaN after the device's OpFDiv where the profile does not take MetalCanonicalNans. Under the native-arithmetic ruling the module selects no NaN: the fast division is the device's OpFDiv on every profile, noted NativeNanEncoding where the device is not measured to answer Metal's. The test, now a_fast_division_leaves_its_nans_to_the_device, checks that the module is the same on both sides of the fact, the note where the fact is absent, the device's arithmetic, division and denormal notes on every committed profile, never DeviceNanEncoding, a NaN for each NaN case and 6 / 3 exactly. Verified: cargo nextest -E 'test(/engine_arith::a_fast_division/)' passes (2 tests); the previous form failed on amd-780m-hawkpoint-radv for fast_one_by_negative_nan (0xffc00000, the device's). * Re-pin the runtime sources at the landing tip The landed packet changed a runtime-sources input, so the committed digest no longer described the sources and `the_runtime_sources_are_the_committed_ones` would fail. Recomputed over the same inputs and committed by land-pkt.sh. --- .../src/cases/half_output_blends.rs | 7 - .../examples/host_ab/runtime.rs | 4 - .../metal2vulkan-runtime/src/clear_value.rs | 438 +----------- crates/metal2vulkan-runtime/src/compute.rs | 2 +- .../metal2vulkan-runtime/src/degradation.rs | 100 +-- .../src/driver_defects.rs | 19 +- .../src/framebuffer_fetch.rs | 2 +- .../metal2vulkan-runtime/src/gpu_execute.rs | 3 +- crates/metal2vulkan-runtime/src/nan_clear.rs | 433 ++--------- crates/metal2vulkan-runtime/src/render.rs | 19 +- .../src/render/executions.rs | 2 +- .../src/render/inline_first.rs | 12 +- .../src/render/tile_dispatch.rs | 5 +- .../src/tests/fitted_variant_notice.rs | 1 - .../src/tests/nan_signs.rs | 9 +- .../metal2vulkan-runtime/src/work_counts.rs | 6 - .../runtime-sources.sha256 | 2 +- .../src/bin/corpus-draw-ab.rs | 10 +- .../src/runtime_lane/color_writes.rs | 83 +-- .../src/runtime_lane/degrade_notices.rs | 6 +- .../src/runtime_lane/driver_deviations.rs | 10 +- .../src/runtime_lane/frame_costs.rs | 3 +- .../src/runtime_lane/half_storage_writes.rs | 22 +- .../src/runtime_lane/half_texel_nans.rs | 64 +- .../src/runtime_lane/half_write_nans.rs | 22 +- .../src/runtime_lane/inline_reasons.rs | 33 +- .../src/runtime_lane/native_maths.rs | 115 +-- .../src/runtime_lane/renders.rs | 439 +----------- crates/metal2vulkan/src/bind/graphics.rs | 7 +- crates/metal2vulkan/src/bind/heap.rs | 14 +- crates/metal2vulkan/src/bind/instantiate.rs | 6 - crates/metal2vulkan/src/bind/plan.rs | 5 - crates/metal2vulkan/src/bind/plan/compute.rs | 7 +- .../metal2vulkan/src/bind/plan/resources.rs | 11 - crates/metal2vulkan/src/cache/codec.rs | 21 +- crates/metal2vulkan/src/cache/mod.rs | 6 +- crates/metal2vulkan/src/device/derive.rs | 28 +- crates/metal2vulkan/src/device/mechanism.rs | 2 - crates/metal2vulkan/src/device/mod.rs | 5 +- crates/metal2vulkan/src/device/policy.rs | 50 +- crates/metal2vulkan/src/device/profile.rs | 59 +- .../src/device/tests/mechanism.rs | 8 +- .../metal2vulkan/src/device/tests/profile.rs | 23 +- crates/metal2vulkan/src/lower/arith/chunk.rs | 45 +- .../src/lower/arith/color_write.rs | 75 +- .../metal2vulkan/src/lower/arith/contract.rs | 2 +- .../metal2vulkan/src/lower/arith/libm/mod.rs | 29 +- crates/metal2vulkan/src/lower/arith/math.rs | 147 +--- crates/metal2vulkan/src/lower/arith/mod.rs | 243 +++---- crates/metal2vulkan/src/lower/arith/nan.rs | 274 +------ crates/metal2vulkan/src/lower/arith/narrow.rs | 23 +- crates/metal2vulkan/src/lower/arith/ops.rs | 3 +- crates/metal2vulkan/src/lower/arith/tests.rs | 270 +------ .../src/lower/arith/tests/color_write.rs | 70 -- .../src/lower/arith/tests/narrow.rs | 25 +- .../src/lower/arith/tests/round_texel.rs | 81 +-- .../src/lower/arith/tests/specials.rs | 13 +- crates/metal2vulkan/src/lower/emit.rs | 1 - crates/metal2vulkan/src/lower/mesh/mod.rs | 2 - crates/metal2vulkan/src/lower/push.rs | 4 +- crates/metal2vulkan/src/lower/sampler/emit.rs | 25 +- .../metal2vulkan/src/lower/sampler/fetched.rs | 40 +- crates/metal2vulkan/src/lower/sampler/mod.rs | 9 +- .../metal2vulkan/src/lower/sampler/select.rs | 15 - crates/metal2vulkan/src/lower/select.rs | 23 - .../src/lower/stage_io/color_write.rs | 139 +--- .../src/lower/stage_io/extended_color.rs | 1 - .../metal2vulkan/src/lower/stage_io/fetch.rs | 28 +- .../src/lower/stage_io/fetch/tests.rs | 22 +- crates/metal2vulkan/src/lower/stage_io/mod.rs | 37 +- .../metal2vulkan/src/lower/stage_io/plan.rs | 40 +- .../src/lower/stage_io/stage_in.rs | 1 + .../src/lower/stage_io/word_color.rs | 1 - .../src/lower/tessellation/mod.rs | 1 - crates/metal2vulkan/src/lower/texture/emit.rs | 333 +-------- crates/metal2vulkan/src/lower/texture/mod.rs | 423 ++++------- .../metal2vulkan/src/lower/texture/slice.rs | 44 +- crates/metal2vulkan/src/lower/texture/slot.rs | 7 - crates/metal2vulkan/src/metal/format/mod.rs | 45 +- crates/metal2vulkan/src/metal/format/tests.rs | 73 +- crates/metal2vulkan/src/metal/texel_format.rs | 50 +- crates/metal2vulkan/src/pipeline/api_tests.rs | 2 - crates/metal2vulkan/src/pipeline/artifact.rs | 44 +- crates/metal2vulkan/src/pipeline/compile.rs | 9 +- .../metal2vulkan/src/pipeline/compile/api.rs | 1 - .../metal2vulkan/src/pipeline/compile/fit.rs | 4 +- .../src/pipeline/compile/fit/tests.rs | 14 +- crates/metal2vulkan/src/pipeline/facts.rs | 15 +- .../src/pipeline/link/contract.rs | 10 +- .../src/pipeline/link/geometry.rs | 1 - .../src/pipeline/link/graphics.rs | 11 +- crates/metal2vulkan/src/pipeline/link/mesh.rs | 1 - .../src/pipeline/link/tessellation/mod.rs | 1 - .../metal2vulkan/src/pipeline/link/tests.rs | 1 - .../metal2vulkan/src/pipeline/link/vertex.rs | 14 +- .../metal2vulkan/src/pipeline/lower_inputs.rs | 14 +- crates/metal2vulkan/src/pipeline/stage_io.rs | 23 +- crates/metal2vulkan/src/pipeline/sym.rs | 6 - crates/metal2vulkan/src/pipeline/testing.rs | 5 +- .../metal2vulkan/src/spirv/builder/module.rs | 22 +- crates/metal2vulkan/src/tests/engine_arith.rs | 516 ++++++-------- .../src/tests/engine_extended_range.rs | 188 +++-- .../src/tests/engine_half_moves.rs | 9 +- .../metal2vulkan/src/tests/engine_handles.rs | 40 +- .../src/tests/engine_imageblock.rs | 2 - crates/metal2vulkan/src/tests/engine_link.rs | 96 +-- .../src/tests/engine_metal_routines.rs | 61 +- .../src/tests/engine_native_half.rs | 143 +--- .../src/tests/engine_native_maths.rs | 217 ++---- .../src/tests/engine_rgbx_storage.rs | 9 +- .../src/tests/engine_stage_io_tail.rs | 1 - .../src/tests/engine_texel_nans.rs | 673 ------------------ .../metal2vulkan/src/tests/engine_texture.rs | 64 +- .../src/tests/engine_texture_interp.rs | 21 +- .../src/tests/engine_texture_levels.rs | 2 - .../src/tests/engine_vertex_fetch.rs | 38 +- crates/metal2vulkan/src/tests/fast_paths.rs | 10 +- crates/metal2vulkan/src/tests/mod.rs | 1 - crates/metal2vulkan/tests/api_signatures.tsv | 13 +- crates/metal2vulkan/tests/api_surface.rs | 52 +- docs/API.md | 39 +- docs/FAST-PATHS.md | 12 - docs/REFUSALS.md | 4 +- 123 files changed, 1409 insertions(+), 5787 deletions(-) delete mode 100644 crates/metal2vulkan/src/tests/engine_texel_nans.rs diff --git a/crates/metal2vulkan-conformance/src/cases/half_output_blends.rs b/crates/metal2vulkan-conformance/src/cases/half_output_blends.rs index bfab42bd2..941590581 100644 --- a/crates/metal2vulkan-conformance/src/cases/half_output_blends.rs +++ b/crates/metal2vulkan-conformance/src/cases/half_output_blends.rs @@ -453,12 +453,6 @@ impl Case for HalfOutputBlends { // written from it would be the suite overruling the contract it exists to test. Five of the // six formats are therefore left **divergent** on this round's MoltenVK, with the measured // counts in the module docs above. - // A half-float attachment also takes the stage's `half` through a 16-bit output on a - // device that does not store a 32-bit output's NaN as Metal does, announced as - // `shader-half-color-bits` on the three 16-bit formats of this family. It is the case's own - // shape again -- a stored `half` output into a half-float attachment -- so its code is - // declared, and it loosens no stored code either: the three rows stay divergent on the - // texels the module docs above measure, which is the finding and must not be laundered. // // Two more of the same shape are declared from the run that shows them: a device whose own // conversion into the attachment is not Metal's (`device-color-conversion`, lavapipe) and @@ -482,7 +476,6 @@ impl Case for HalfOutputBlends { .chain( [ Degradation::HalfOutputFastMathBlend, - Degradation::ShaderHalfColorBits, Degradation::DeviceColorConversion, Degradation::DeviceNanEncoding, ] diff --git a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs index 2a3983043..670c72b53 100644 --- a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs +++ b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs @@ -1675,10 +1675,6 @@ impl Gpu for Runtime { "passes_not_inline_actions_unequal_reach", c.passes_not_inline_actions_unequal_reach, ), - ( - "passes_not_inline_actions_nan_clear", - c.passes_not_inline_actions_nan_clear, - ), ( "passes_not_inline_actions_resolve", c.passes_not_inline_actions_resolve, diff --git a/crates/metal2vulkan-runtime/src/clear_value.rs b/crates/metal2vulkan-runtime/src/clear_value.rs index e54829ae1..b7e41b836 100644 --- a/crates/metal2vulkan-runtime/src/clear_value.rs +++ b/crates/metal2vulkan-runtime/src/clear_value.rs @@ -34,8 +34,8 @@ //! lies a hair below `k` for some `k` (1/65535 stored 0 there). A NaN of a `half` or small-float //! channel has no such value: Vulkan leaves its bits to the device, and RADV and lavapipe write //! other NaNs than Metal's canonical quiet one (a Metal probe, the M3 Max and an M4 alike: -//! `0x7e00`, and `0x7e0` and `0x3f0` for `RG11B10Float`, the sign dropped). [`nan_texel`] gives -//! such a texel's bits, which `nan_clear.rs` writes before the pass. A `float` NaN keeps its sign +//! `0x7e00`, and `0x7e0` and `0x3f0` for `RG11B10Float`, the sign dropped): the device's clear +//! writes its own, announced (`nan_clear::degrade_nan_clears`). A `float` NaN keeps its sign //! (`0x7fc00000`, `0xffc00000`), which every device measured writes. //! //! An **extended-range** attachment holds its raw texels in an unsigned integer format, so its @@ -308,133 +308,25 @@ pub(super) fn word( }) } -/// Where a `half` or small-float channel of `value`, the Vulkan clear value [`color`] gives an -/// attachment of `pf`, is a NaN, whose bits Vulkan leaves to the device's conversion -/// (`nan_clear.rs`): the unsigned-integer format of the texel's size and the clear value that -/// writes Metal's texel there, its bits from the texel's first byte. `None` for every other -/// clear, which converts exactly. -/// A `half` NaN is the canonical quiet NaN, `0x7e00`, where not `signed`; where `signed` (a -/// level Metal clears keeping them, `nan_clear::keeps_nan_sign`) it keeps the clear value's sign -/// and the top ten bits of its payload, quieted: `sign | 0x7e00 | payload`, the double's -/// mantissa's top ten bits (`0x7ffc...` stores `0x7f00`, `0x7fff...` `0x7fff`, -/// `0xffff...` `0xffff`, the signalling `0x7ff4...` `0x7f00`, `0x7ff0...01` `0x7e00`). -pub(super) fn nan_texel( - pf: PixelFormat, - value: &vk::ClearColorValue, - signed: bool, -) -> Option<(Format, vk::ClearColorValue)> { - let nan = match signed { - true => NanBits::Signed, - false => NanBits::Signless, - }; - small_float_texel(pf, value, nan) -} - -/// The texel Metal's resolve stores from samples that each hold [`nan_texel`]'s texel of -/// `value`, where it averages them: each NaN channel zero, as its resolve counts a NaN sample, in -/// the unsigned-integer format of the texel's size. `None` where `value` holds no `half` or -/// small-float NaN. -pub(super) fn resolved_nan_texel( - pf: PixelFormat, - value: &vk::ClearColorValue, -) -> Option<(Format, vk::ClearColorValue)> { - small_float_texel(pf, value, NanBits::Zero) -} - -/// Where a channel of `value`, the Vulkan clear value [`color`] gives an attachment of `pf` whose -/// channels are 32-bit floats, is a NaN: the unsigned-integer format of the texel's size and the -/// clear value that writes, where `kept`, the texel's bits, which the device's clear writes too (a -/// `float` converts nothing), else the texel Metal's resolve stores from samples that each hold -/// it, each NaN channel `0x7fc00000`; for a write of the texel elsewhere (`nan_clear.rs`'s -/// resolves). `None` for another format or a clear without a NaN. -pub(super) fn float_nan_texel( - pf: PixelFormat, - value: &vk::ClearColorValue, - kept: bool, -) -> Option<(Format, vk::ClearColorValue)> { +/// Whether a float channel of `value`, the Vulkan clear value [`color`] gives an attachment of +/// `pf`, is a NaN: `Some(true)` where a `half` or small-float one is, whose bits Vulkan leaves to +/// the device's conversion (`nan_clear::degrade_nan_clears`), `Some(false)` where only a 32-bit +/// float one is, which converts nothing. `None` for every other clear. +pub(super) fn nan_channels(pf: PixelFormat, value: &vk::ClearColorValue) -> Option { let channels = channels(pf)?; // SAFETY: every member of the union is four 32-bit values; any bits are a valid `f32`. let float32 = unsafe { value.float32 }; - let used: Vec = channels - .iter() - .zip(float32) - .filter(|(c, _)| !matches!(c, Channel::Unused)) - .map(|(c, v)| matches!(c, Channel::Float).then_some(v)) - .collect::>()?; - if !used.iter().any(|v| v.is_nan()) { - return None; - } - let bits = |v: &f32| match v.is_nan() && !kept { - true => 0x7fc0_0000, - false => v.to_bits(), - }; - let bytes: Vec = used.iter().flat_map(|v| bits(v).to_le_bytes()).collect(); - uint_texel(&bytes) -} - -/// What a NaN channel of a [`small_float_texel`] holds. -#[derive(Clone, Copy)] -enum NanBits { - /// The canonical quiet NaN, without a sign. - Signless, - /// The canonical quiet NaN with the clear value's sign, in a `half` channel. - Signed, - /// Zero. - Zero, -} - -/// The texel of `value` in `pf`, a format of `half` or small-float channels, each NaN channel as -/// `nan` says ([`nan_texel`]); `None` where no such channel is a NaN. -fn small_float_texel( - pf: PixelFormat, - value: &vk::ClearColorValue, - nan: NanBits, -) -> Option<(Format, vk::ClearColorValue)> { - let channels = channels(pf)?; - // SAFETY: every member of the union is four 32-bit values; any bits are a valid `f32`. - let float32 = unsafe { value.float32 }; - let small_float = |c: &Channel| matches!(c, Channel::Half | Channel::Ufloat(_)); - if !channels - .iter() - .zip(float32) - .any(|(c, v)| small_float(c) && v.is_nan()) - { - return None; - } - let mut bits = 0u64; - let mut at = 0; - for (&channel, v) in channels.iter().zip(float32) { - let (field, width) = match (channel, nan) { - (Channel::Half, NanBits::Zero) if v.is_nan() => (0, 16), - (Channel::Ufloat(mantissa), NanBits::Zero) if v.is_nan() => (0, mantissa + 5), - // The sign and the top ten payload bits, quieted ([`convert`] carries the clear - // value's in the `float`). - (Channel::Half, NanBits::Signed) if v.is_nan() => { - let bits = v.to_bits(); - let kept = ((bits >> 16) & 0x8000) | 0x7e00 | ((bits >> 13) & 0x3ff); - (u64::from(kept), 16) - } - (Channel::Half, _) => (u64::from(f32_to_f16(v)), 16), - (Channel::Ufloat(mantissa), _) => (ufloat_bits(v, mantissa), mantissa + 5), - (Channel::Unused, _) => continue, - // No format mixes small floats with other channels. - _ => return None, - }; - bits |= field << at; - at += width; - } - if at % 8 != 0 { - return None; - } - let bytes = bits.to_le_bytes(); - uint_texel(bytes.get(..at as usize / 8)?) + let nans = || channels.iter().zip(float32).filter(|(_, v)| v.is_nan()); + let narrow = nans().any(|(c, _)| matches!(c, Channel::Half | Channel::Ufloat(_))); + let float = nans().any(|(c, _)| matches!(c, Channel::Float)); + (narrow || float).then_some(narrow) } /// The unsigned-integer format of `texel`'s size (2, 4, 8 or 16 bytes: `R16_UINT`, `R32_UINT`, /// `R32G32_UINT`, `R32G32B32A32_UINT`) and the clear value whose conversion into it writes /// exactly `texel`'s bytes, its little-endian 16- or 32-bit words: a texel whose bits no clear /// of its own format controls is written so, then copied bit-wise into an image of its format -/// (`nan_clear.rs`, a new multisampled texture's pattern: `first_move::Pattern::Scratch`). +/// (a new multisampled texture's pattern: `first_move::Pattern::Scratch`). /// `None` for another size. pub(crate) fn uint_texel(texel: &[u8]) -> Option<(Format, vk::ClearColorValue)> { let format = match texel.len() { @@ -456,29 +348,6 @@ pub(crate) fn uint_texel(texel: &[u8]) -> Option<(Format, vk::ClearColorValue)> Some((format, vk::ClearColorValue { uint32 })) } -/// The bits of a small unsigned float of `mantissa` bits (and a 5-bit exponent) holding `v`, which -/// is one exactly ([`ufloat_value`]'s result): NaN is the canonical quiet NaN (the top mantissa -/// bit), as Metal writes it (a Metal probe on the M3 Max and an M4). -fn ufloat_bits(v: f32, mantissa: u32) -> u64 { - if v.is_nan() { - return (31 << mantissa) | (1 << (mantissa - 1)); - } - if v.is_infinite() { - return 31 << mantissa; - } - if v <= 0.0 { - return 0; - } - let steps = 1u64 << mantissa; - let exponent = binade(v).max(-14); - // Exact: `v` is a whole number of the binade's spacing. - let scaled = (f64::from(v) / 2f64.powi(exponent) * steps as f64) as u64; - match scaled < steps { - true => scaled, - false => (((exponent + 15) as u64) << mantissa) | (scaled - steps), - } -} - /// Each channel's texel under Metal's conversion of `color`. fn convert(channels: &[Channel; 4], color: [f64; 4]) -> [Texel; 4] { let shared = shared_exponent(channels, color); @@ -493,7 +362,8 @@ fn convert(channels: &[Channel; 4], color: [f64; 4]) -> [Texel; 4] { Channel::Uint(bits) => Texel::Uint(uint(x, bits)), Channel::Sint(bits) => Texel::Sint(sint(x, bits)), // A NaN is the quiet `float` NaN of the double's sign and top payload bits, which - // `nan_texel` keeps where Metal's clear does; every other value is the `half`'s. + // Metal's clear keeps where it keeps a `half` NaN's sign; every other value is the + // `half`'s. Channel::Half if x.is_nan() => { let bits = x.to_bits(); let sign = ((bits >> 32) & 0x8000_0000) as u32; @@ -724,6 +594,29 @@ pub(crate) mod tests { use super::*; use PixelFormat as P; + /// The bits of a small unsigned float of `mantissa` bits (and a 5-bit exponent) holding `v`, + /// which is one exactly ([`ufloat_value`]'s result): NaN is the canonical quiet NaN (the top + /// mantissa bit), as Metal writes it (a Metal probe on the M3 Max and an M4). + fn ufloat_bits(v: f32, mantissa: u32) -> u64 { + if v.is_nan() { + return (31 << mantissa) | (1 << (mantissa - 1)); + } + if v.is_infinite() { + return 31 << mantissa; + } + if v <= 0.0 { + return 0; + } + let steps = 1u64 << mantissa; + let exponent = binade(v).max(-14); + // Exact: `v` is a whole number of the binade's spacing. + let scaled = (f64::from(v) / 2f64.powi(exponent) * steps as f64) as u64; + match scaled < steps { + true => scaled, + false => (((exponent + 15) as u64) << mantissa) | (scaled - steps), + } + } + /// The bytes of the texel a clear of `color` writes into an attachment of `pf`: each channel /// converted as [`convert`] converts it, laid out as Metal lays out `pf`'s texel, /// little-endian, the fields from the texel's lowest bit in the order the format's name lists @@ -1062,263 +955,6 @@ pub(crate) mod tests { } } - /// A clear of a `half` or small-float NaN writes Metal's texel through an integer format of its - /// size (the bytes Metal wrote on the M3 Max and an M4), and no other clear does. - #[test] - fn nan_texels_are_metals() { - let n = f64::NAN; - let cases: &[(PixelFormat, [f64; 4], Format, &str)] = &[ - (P::R16Float, [n, 0.0, 0.0, 0.0], Format::R16_UINT, "007e"), - (P::R16Float, [-n, 0.0, 0.0, 0.0], Format::R16_UINT, "007e"), - (P::RG16Float, [n, 1.0, 0.5, n], Format::R32_UINT, "007e003c"), - ( - P::RG16Float, - [1.0, n, 2.0, 0.25], - Format::R32_UINT, - "003c007e", - ), - ( - P::RGBA16Float, - [-n, -n, -n, -n], - Format::R32G32_UINT, - "007e007e007e007e", - ), - ( - P::RGBA16Float, - [n, 1.0, 0.5, n], - Format::R32G32_UINT, - "007e003c0038007e", - ), - ( - P::RGBA16Float, - [1.0, n, 2.0, 0.25], - Format::R32G32_UINT, - "003c007e00400034", - ), - (P::RG11B10Float, [n, n, n, n], Format::R32_UINT, "e0073ffc"), - ( - P::RG11B10Float, - [-n, -n, -n, -n], - Format::R32_UINT, - "e0073ffc", - ), - ( - P::RG11B10Float, - [n, 1.0, 0.5, n], - Format::R32_UINT, - "e0071e70", - ), - ( - P::RG11B10Float, - [1.0, n, 2.0, 0.25], - Format::R32_UINT, - "c0033f80", - ), - ( - P::RG11B10Float, - [1e-6, n, f64::INFINITY, 0.0], - Format::R32_UINT, - "01003ff8", - ), - ]; - for &(pf, c, format, want) in cases { - let value = color(pf, c, ClearRoute::ThroughHalf).unwrap(); - let (got, bits) = nan_texel(pf, &value, false).unwrap(); - // SAFETY: `nan_texel` writes `uint32`. - let words = unsafe { bits.uint32 }; - let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - assert_eq!(got, format, "{pf:?} {c:?}"); - assert_eq!(hex(&bytes[..want.len() / 2]), want, "{pf:?} {c:?}"); - assert!(bytes[want.len() / 2..].iter().all(|&b| b == 0), "{pf:?}"); - } - for (pf, c) in [ - (P::RGBA16Float, [0.1, -2.5, 65504.0, 1e-5]), - (P::RG11B10Float, [0.1, -1.0, 70000.0, 0.0]), - (P::R32Float, [n, 0.0, 0.0, 0.0]), - (P::RGBA32Float, [-n, n, 1.0, 0.0]), - (P::RGB9E5Float, [n, 1.0, 0.5, n]), - (P::RGBA8Unorm, [n, n, n, n]), - (P::B5G6R5Unorm, [n, n, n, n]), - ] { - assert!( - nan_texel(pf, &color(pf, c, ClearRoute::ThroughHalf).unwrap(), false).is_none(), - "{pf:?}" - ); - assert!( - nan_texel(pf, &color(pf, c, ClearRoute::ThroughHalf).unwrap(), true).is_none(), - "{pf:?}" - ); - } - } - - /// Where Metal keeps a NaN clear's sign (a level of 16 or more texels a side), a `half` NaN is - /// `0x7e00` with the clear value's sign; the small floats, which have none, and every finite - /// channel are as without it. - #[test] - fn signed_nan_texels_keep_the_sign_of_a_half_nan() { - let n = f64::NAN; - let cases: &[(PixelFormat, [f64; 4], &str)] = &[ - (P::RGBA16Float, [-n, -n, -n, -n], "00fe00fe00fe00fe"), - (P::RGBA16Float, [n, 1.0, 0.5, -n], "007e003c003800fe"), - (P::RGBA16Float, [n, 1.0, 0.5, n], "007e003c0038007e"), - (P::R16Float, [-n, 0.0, 0.0, 0.0], "00fe"), - (P::RG16Float, [-n, -2.5, 0.0, 0.0], "00fe00c1"), - (P::RG11B10Float, [-n, -n, -n, -n], "e0073ffc"), - ]; - for &(pf, c, want) in cases { - let (_, bits) = - nan_texel(pf, &color(pf, c, ClearRoute::ThroughHalf).unwrap(), true).unwrap(); - // SAFETY: `nan_texel` writes `uint32`. - let words = unsafe { bits.uint32 }; - let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - assert_eq!(hex(&bytes[..want.len() / 2]), want, "{pf:?} {c:?}"); - } - } - - /// Metal's resolve of samples each holding a NaN clear's texel stores each NaN channel zero - /// and every other channel as the texel holds it (an M4: `RGBA16Float` (NaN, 1, 0.5, -NaN) - /// resolves to `0000 3c00 3800 0000`; `RG11B10Float` (NaN, 1, 0.5) to `701e0000`); a clear - /// without such a NaN has none. - #[test] - fn resolved_nan_texels_zero_each_nan_channel() { - let n = f64::NAN; - let cases: &[(PixelFormat, [f64; 4], &str)] = &[ - (P::RGBA16Float, [n, 1.0, 0.5, -n], "0000003c00380000"), - (P::RGBA16Float, [-n, -n, -n, -n], "0000000000000000"), - (P::R16Float, [-n, 0.0, 0.0, 0.0], "0000"), - (P::RG16Float, [-n, f64::INFINITY, 0.0, 0.0], "0000007c"), - (P::RG11B10Float, [n, 1.0, 0.5, n], "00001e70"), - (P::RG11B10Float, [n, n, n, n], "00000000"), - ]; - for &(pf, c, want) in cases { - let value = color(pf, c, ClearRoute::ThroughHalf).unwrap(); - let (format, bits) = resolved_nan_texel(pf, &value).unwrap(); - assert_eq!(format, nan_texel(pf, &value, false).unwrap().0, "{pf:?}"); - // SAFETY: `resolved_nan_texel` writes `uint32`. - let words = unsafe { bits.uint32 }; - let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - assert_eq!(hex(&bytes[..want.len() / 2]), want, "{pf:?} {c:?}"); - } - let finite = color( - P::RGBA16Float, - [0.1, 1.0, 0.5, 1.0], - ClearRoute::ThroughHalf, - ); - assert!(resolved_nan_texel(P::RGBA16Float, &finite.unwrap()).is_none()); - } - - /// A 32-bit float NaN clears to the double's sign and top payload bits, quieted, as Metal's - /// conversion (`0x7ff0000020000000` stores `0x7fc00001`, `0xfff8...` - /// `0xffc00000`, `0x7ffc...` `0x7fe00000`, the signalling `0x7ff0...01` `0x7fc00000`), and - /// `float_nan_texel` gives those bits where kept, and each NaN channel `0x7fc00000` where - /// not, Metal's resolve of them (its other channels as they are); a clear without a NaN, or of - /// another format, none. - #[test] - fn float_nan_texels_are_metal_s_conversion() { - let nan = f64::from_bits; - // The clear, its kept texel and its resolved one. - let cases: &[(PixelFormat, [f64; 4], &str, &str)] = &[ - ( - P::R32Float, - [nan(0x7ff0_0000_2000_0000), 0.0, 0.0, 0.0], - "0100c07f", - "0000c07f", - ), - ( - P::R32Float, - [nan(0xfff8_0000_0000_0000), 0.0, 0.0, 0.0], - "0000c0ff", - "0000c07f", - ), - ( - P::R32Float, - [nan(0x7ffc_0000_0000_0000), 0.0, 0.0, 0.0], - "0000e07f", - "0000c07f", - ), - ( - P::R32Float, - [nan(0x7ff0_0000_0000_0001), 0.0, 0.0, 0.0], - "0000c07f", - "0000c07f", - ), - ( - P::RG32Float, - [nan(0x7ff8_0000_0000_0000), 1.0, 0.0, 0.0], - "0000c07f0000803f", - "0000c07f0000803f", - ), - ( - P::RGBA32Float, - [ - 0.5, - nan(0xfff8_0000_0000_0000), - -2.0, - nan(0x7ffc_0000_0000_0000), - ], - "0000003f0000c0ff000000c00000e07f", - "0000003f0000c07f000000c00000c07f", - ), - ]; - for &(pf, c, kept, resolved) in cases { - let value = color(pf, c, ClearRoute::ThroughHalf).unwrap(); - for (keeps, want) in [(true, kept), (false, resolved)] { - let (format, bits) = float_nan_texel(pf, &value, keeps).unwrap(); - let format_for = |size: usize| uint_texel(&vec![0; size]).unwrap().0; - assert!(format == format_for(want.len() / 2), "{pf:?}"); - // SAFETY: `float_nan_texel` writes `uint32`. - let words = unsafe { bits.uint32 }; - let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - assert_eq!(hex(&bytes[..want.len() / 2]), want, "{pf:?} {c:?} {keeps}"); - } - } - let finite = color(P::R32Float, [0.5, 0.0, 0.0, 0.0], ClearRoute::ThroughHalf); - assert!(float_nan_texel(P::R32Float, &finite.unwrap(), true).is_none()); - let half = color(P::RGBA16Float, [f64::NAN; 4], ClearRoute::ThroughHalf); - assert!(float_nan_texel(P::RGBA16Float, &half.unwrap(), false).is_none()); - } - - /// Where Metal keeps a NaN clear's sign it keeps the top ten bits of the double's payload - /// too, quieted (an M4: `0x7ffc...` stores `0x7f00`, `0x7fff...` `0x7fff`, - /// `0xffff...` `0xffff`, the signalling `0x7ff4...` `0x7f00` and `0xfff0...01` `0xfe00`); - /// elsewhere every such NaN is `0x7e00`. - #[test] - fn signed_nan_texels_keep_a_half_nan_s_payload() { - let nan = f64::from_bits; - let payloads = [ - nan(0x7ffc_0000_0000_0000), - nan(0x7fff_ffff_ffff_ffff), - nan(0xffff_ffff_ffff_ffff), - nan(0x7ff4_0000_0000_0000), - ]; - let low = [nan(0xfff0_0000_0000_0001), 0.0, 0.0, 0.0]; - let cases: &[(PixelFormat, [f64; 4], &str, &str)] = &[ - ( - P::RGBA16Float, - payloads, - "007fff7fffff007f", - "007e007e007e007e", - ), - (P::R16Float, low, "00fe", "007e"), - ( - P::RG16Float, - [nan(0x7ff0_0000_2000_0000), 1.0, 0.0, 0.0], - "007e003c", - "007e003c", - ), - ]; - for &(pf, c, kept, dropped) in cases { - let value = color(pf, c, ClearRoute::ThroughHalf).unwrap(); - for (signed, want) in [(true, kept), (false, dropped)] { - let (_, bits) = nan_texel(pf, &value, signed).unwrap(); - // SAFETY: `nan_texel` writes `uint32`. - let words = unsafe { bits.uint32 }; - let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - assert_eq!(hex(&bytes[..want.len() / 2]), want, "{pf:?} {c:?} {signed}"); - } - } - } - /// The Vulkan clear value of each converted texel is one Vulkan's conversion maps back onto /// it: an exact value, or one within a hair of the normalized integer. #[test] diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 7b3ec7ef8..eb04b7302 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -2548,7 +2548,7 @@ fn record( }); } } - device.degrade_half_texel_writes(&variant.pipeline().dependencies, Some(formats)); + device.degrade_half_texel_writes(&variant.pipeline().dependencies); objects.degrade_bound_formats( std::slice::from_ref(&variant.pipeline().stage), Some(formats), diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 310518fc3..8bd74b3ec 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -529,13 +529,6 @@ degradations! { ShaderColorConversion = "shader-color-conversion", Performance, "the fragment function rounds each such channel to nearest even before it writes it: \ about 35 more instructions per channel"; - /// A fragment function writes a `half` to a half-float color attachment as the bits of - /// the half Metal stores, through a 16-bit output, on a device that does not store a - /// 32-bit output's NaN as Metal does (`StageModule::half_bit_colors`). - ShaderHalfColorBits = "shader-half-color-bits", Performance, - "the fragment function writes each such output as its half's bits through a 16-bit \ - output: about 20 more instructions per output, and the attachment takes no Vulkan \ - blend of one and zero"; /// A Metal render pass runs as several Vulkan render pass instances (`render.rs`): a /// framebuffer fetch through the pixel interlock keeps its attachment out of its draws' /// subpass, and the pass's draws leave different attachments out, or its last draws @@ -2158,18 +2151,16 @@ degradations! { /// infinity where Metal answers 65504; a NaN's encoding the device's. NativeHalfQuantize = "native-half-quantize"; /// Class: native device maths. The device's NaN answers a `float` or `half` operation's - /// NaN result where Metal's bits would be selected (`NanMinMaxPolicy::Native`, the - /// default on a device whose arithmetic is not measured to answer Metal's canonical NaN; - /// `Exact` keeps Metal's). Recorded bound: where Metal answers a NaN the device answers a + /// NaN result where Metal answers a NaN the device is not measured to answer (every NaN + /// but the canonical one on a device measured to answer Metal's canonical NaN). Recorded + /// bound: where Metal answers a NaN the device answers a /// NaN, its sign and payload the device's own, where Metal answers `0x7fc00000` /// (`0x7e00` as `half`), an operand's bits, or the canonical NaN with an operand's sign; /// every other result unchanged. NativeNanEncoding = "native-nan-encoding"; /// Class: native device maths. The device's `NMin`, `NMax` or `NClamp` answers Metal's /// `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` (its `clamp(x, +0, 1)`) on - /// `float` or `half` where the translation would select Metal's operand - /// (`NanMinMaxPolicy::Native`, the default on a device not measured to answer Metal's; - /// `Exact` keeps Metal's). Recorded bound: an operand, Metal's but at three ties: of two + /// `float` or `half` on a device not measured to answer Metal's operand. Recorded bound: an operand, Metal's but at three ties: of two /// NaNs a NaN (Metal: the second operand's bits), of `+0` and `-0` either zero (Metal: the /// second), and an `f32` denormal beside a zero or another denormal compared by its value /// where the device keeps denormals (Metal compares it as a zero and answers the second). @@ -2521,9 +2512,6 @@ impl Kinds { kinds.add(Degradation::YCbCrFilterNotExact); } } - if !stage.half_bit_colors.is_empty() { - kinds.add(Degradation::ShaderHalfColorBits); - } if !stage.rounded_colors.is_empty() { kinds.add(Degradation::ShaderColorConversion); } @@ -2620,12 +2608,10 @@ pub(crate) fn dropped_exact_forms( metal2vulkan::pipeline::RuntimeFact::ExactFormsOverCompilerLimit { sampling, texel_conversion, - nan_and_min_max, } => Some( [ (sampling, "exact sampling"), (texel_conversion, "exact texel conversion"), - (nan_and_min_max, "exact NaN and minimum and maximum"), ] .into_iter() .filter_map(|(dropped, name)| dropped.then_some(name)) @@ -3110,18 +3096,6 @@ impl Device { (object(), self.stage_note_reason(note, stage)) }); } - if !stage.half_bit_colors.is_empty() { - self.degrade_at(at, Degradation::ShaderHalfColorBits, || { - ( - object(), - format!( - "the device stores a 32-bit output's NaN to the half-float format of \ - color attachment(s) {:?} as another NaN than the `half`'s own bits", - stage.half_bit_colors - ), - ) - }); - } if !stage.rounded_colors.is_empty() { self.degrade_at(at, Degradation::ShaderColorConversion, || { ( @@ -3288,70 +3262,6 @@ impl Device { }); } - /// Announce `PrecisionNote::DeviceNanEncoding` at a draw or dispatch of a pipeline of - /// `dependencies` whose `half` texel writes to a texture slot read whether its texture's - /// channels are 16-bit floats (`RuntimeFact::StorageTextureHalfChannels`: the slot's storage - /// choice declares no format), where `formats` binds there a texture whose stored NaN the - /// device's conversion decides (`metal::format::half_write_nans_converted`: 16-bit - /// float channels, or a packed small float's), on a device without - /// `VkProperty::MetalHalfTexelWrites`; where the command's bound formats are not known - /// (`formats` `None`: an execution of indirect commands the GPU writes), at every such slot. - /// A 32-bit float, normalized or integer texture there stores Metal's answer and announces - /// nothing. The module records no note for such a write: this is its announcement. - pub(crate) fn degrade_half_texel_writes( - &self, - dependencies: &[metal2vulkan::pipeline::RuntimeDependency], - formats: Option>, - ) { - use metal2vulkan::pipeline::RuntimeFact; - self.degrade_heap_half_texel_writes(dependencies); - let mut slots = dependencies.iter().filter_map(|d| match d.fact { - RuntimeFact::StorageTextureHalfChannels { slot } => Some(slot), - _ => None, - }); - let Some(first) = slots.next() else { - return; - }; - if !self - .shared() - .announced - .pending(Degradation::DeviceNanEncoding) - || self - .compile_device() - .profile() - .enabled() - .properties - .contains(&metal2vulkan::device::VkProperty::MetalHalfTexelWrites) - { - return; - } - let converted = |slot: SlotRef| match formats { - Some(f) => f(slot).map(|pf| (slot, Some(pf))).filter(|(_, pf)| { - pf.is_some_and(metal2vulkan::metal::format::half_write_nans_converted) - }), - None => Some((slot, None)), - }; - let Some((slot, format)) = std::iter::once(first).chain(slots).find_map(converted) else { - return; - }; - self.degrade(Degradation::DeviceNanEncoding, || { - let bound = match format { - Some(pf) => format!("bound as {pf:?}"), - None => "of a format the GPU's commands bind".to_owned(), - }; - ( - format!("the {:?} function of a pipeline state", slot.stage), - format!( - "it writes `half` texels to texture {} {bound}, whose NaNs the device \ - stores as it converts them, not as Metal stores a written half (the \ - half's own bits in a 16-bit float channel, the format's canonical NaN in a \ - packed small float one)", - slot.index - ), - ) - }); - } - /// Announce `PrecisionNote::DeviceNanEncoding` at a draw or dispatch of a pipeline of /// `dependencies` whose writes through heap handles store half-float members' bits through /// the unsigned integer twin (`RuntimeFact::HeapHalfTexelWrites`), where the device's heap @@ -3359,7 +3269,7 @@ impl Device { /// (`heap_sets::NanResidue`: a half-float texture the twin does not hold, and for a `half` /// write a packed small float one). Every texture the device holds is at its resource ID for /// every command (`heap_sets.rs`), so any of them may be one the function's handles name. - fn degrade_heap_half_texel_writes( + pub(crate) fn degrade_half_texel_writes( &self, dependencies: &[metal2vulkan::pipeline::RuntimeDependency], ) { diff --git a/crates/metal2vulkan-runtime/src/driver_defects.rs b/crates/metal2vulkan-runtime/src/driver_defects.rs index 4080fbfb4..dd5a815c1 100644 --- a/crates/metal2vulkan-runtime/src/driver_defects.rs +++ b/crates/metal2vulkan-runtime/src/driver_defects.rs @@ -155,16 +155,15 @@ pub(super) struct Affected { /// and a multisampled copy is then a draw (`radv_gfx_copy_image`) that fetches each sample in /// that format and exports it: a NaN in a 16-bit float channel lands as `0xfe00`, its sign and /// payload lost, while a single-sampled copy kept them. Read in 26.2's source (2026-10-09), and -/// measured on 26.2.4 (driverVersion 0x6802004) on the Radeon 780M (`deviceID` 0x15bf; -/// `runtime_lane::renders::multisampled_nan_clears_store_metal_s_texel`: every NaN sample of a 4x -/// `R16Float` and `RGBA16Float` NaN clear, copied from its unsigned-integer scratch, held -/// `0xfe00`: a scratch not mutable to the attachment's format alike): known broken through -/// 26.2.4. The path is every RADV GPU's, so every device has it. Nothing is refused: the NaN -/// clear of a multisampled attachment is written through a view of its image in the -/// unsigned-integer format of its texel size (`nan_clear.rs`), which the runtime's multisampled -/// color render targets of such formats take there where it costs the image nothing -/// (`nan_clear::view_candidate`), and is the device's copy, announced (`device-nan-encoding`), -/// where the image takes no such view. +/// measured on 26.2.4 (driverVersion 0x6802004) on the Radeon 780M (`deviceID` 0x15bf: every +/// NaN sample of a 4x `R16Float` and `RGBA16Float` texel copied from an unsigned-integer scratch +/// held `0xfe00`, a scratch not mutable to the attachment's format alike): known broken through +/// 26.2.4. The path is every RADV GPU's, so every device has it. Nothing is refused: a blit copy +/// between multisampled images of such a format runs through views of them in the +/// unsigned-integer format of its texel size where both take one (`sample_planes::BitsCopy`), +/// which the runtime's multisampled color render targets of such formats take where it costs the +/// image nothing (`nan_clear::view_candidate`), and is the device's copy, announced +/// (`device-nan-encoding`), elsewhere. /// /// `ReadsCommandBuffersAfterTheirSignal`: /// - MoltenVK (`MOLTENVK`): on a device with `MTLSharedEvent` the GPU signals a timeline diff --git a/crates/metal2vulkan-runtime/src/framebuffer_fetch.rs b/crates/metal2vulkan-runtime/src/framebuffer_fetch.rs index c9ab44afc..59062a3d7 100644 --- a/crates/metal2vulkan-runtime/src/framebuffer_fetch.rs +++ b/crates/metal2vulkan-runtime/src/framebuffer_fetch.rs @@ -416,7 +416,7 @@ impl Device { /// size; then with the usage its framebuffer fetch's form /// needs ([`fetch_candidate`]), or a multisampled depth/stencil attachment's copies without /// colour copies need (`depth_stencil_scratch::sampled_candidate`), then the unsigned-integer - /// view a NaN clear writes a multisampled attachment through on a device whose copies + /// view a copy keeps a multisampled attachment's NaN bits through on a device whose copies /// convert its NaNs (`nan_clear::view_candidate`), then the input attachment usage the /// exact color resolve reads a multisampled color attachment through /// (`color_resolve::input_candidate`), and then the feedback loop usage a draw that reads the diff --git a/crates/metal2vulkan-runtime/src/gpu_execute.rs b/crates/metal2vulkan-runtime/src/gpu_execute.rs index b747fc6b5..5a38ac7ba 100644 --- a/crates/metal2vulkan-runtime/src/gpu_execute.rs +++ b/crates/metal2vulkan-runtime/src/gpu_execute.rs @@ -733,8 +733,7 @@ fn announce(device: &Device, p: &Prepared, objects: &VariantObjects) { [(®ion.specialization, None)], ); } - // The GPU's commands bind the textures: every slot whose `half` writes read its word. - device.degrade_half_texel_writes(&p.variant.pipeline().dependencies, None); + device.degrade_half_texel_writes(&p.variant.pipeline().dependencies); device.degrade_bound_formats(std::slice::from_ref(&p.variant.pipeline().stage), None); // The values the variant's plan pushes for the commands the GPU writes. for (n, region) in p.commands.regions.iter().enumerate() { diff --git a/crates/metal2vulkan-runtime/src/nan_clear.rs b/crates/metal2vulkan-runtime/src/nan_clear.rs index b0c692fe6..3281a79ba 100644 --- a/crates/metal2vulkan-runtime/src/nan_clear.rs +++ b/crates/metal2vulkan-runtime/src/nan_clear.rs @@ -1,69 +1,25 @@ -//! Clears of a NaN in a `half` or small-float channel, written as Metal writes them. +//! Clears of a NaN, and copies of NaN texels. //! -//! **Metal** writes the canonical quiet NaN: `0x7e00` for a `half` NaN of either sign, `0x7e0` and -//! `0x3f0` for the 11- and 10-bit channels of `RG11B10Float`, the sign dropped (a Metal probe, an -//! M4 on macOS 27.0.1 and the M3 Max on 26.7, alike, each plain and under the debug layer). -//! **Vulkan** converts a clear value to the attachment's format as the device likes, and the -//! devices measured differ there: RADV writes a `half` NaN as `0xfe00`, and lavapipe an -//! `RG11B10Float` NaN as `0x7c1` and `0x3e1` (lane `renders::clears_store_the_bytes_metal_stores`). -//! An integer clear converts nothing. -//! -//! So a color attachment whose `Clear` load holds such a NaN ([`clear_value::nan_texel`]) is -//! cleared before the pass instead: a scratch image of the unsigned-integer format of its texel -//! size (`R16Uint`, `R32Uint` or `RG32Uint`), of its samples and layers -//! (`attachment_stand_in::stand_in_as`), is cleared by `vkCmdClearColorImage` to the texel's -//! bits, which are copied into the attachment bit-wise (formats of one texel size) over the -//! clear's reach (`clear_reach.rs`), and the pass loads it. The scratch image is the pass's own, -//! held until its command buffer completes. -//! -//! **Kept sign**. Where Metal keeps the attachment's texture losslessly compressed, the -//! attachment's level is 16 texels or more a side, and the pass has no draw call -//! ([`keeps_nan_sign`]), its clear keeps a `half` NaN's sign, `0xfe00` for a negative one, in the -//! texel and every sample; elsewhere it drops it (an M4 under macOS 27.0.1, sizes 1 to 256, 1x and -//! 4x, `R16Float`, `RG16Float` and `RGBA16Float`; any draw call drops it, one wholly off the -//! target, of no area or whose fragments all discard too; the consumer's M3 Max alike at 4x4). The -//! scratch is mutable to the attachment's format (`stand_in_as`), so a device that copies between -//! formats through a view copies so: MoltenVK's copy of a multisampled image between formats that -//! take no such view goes through a buffer, which holds no samples, and left the NaN channels zero. -//! -//! **Resolves**. Metal's resolve of such a clear in a pass with no draw call stores the clear's -//! texel, its sign kept, where the sign is kept and Metal also keeps the resolve texture compressed -//! (at its level, of the attachment's extent); elsewhere it averages the samples, each NaN counted -//! zero ([`clear_value::resolved_nan_texel`]): a `PixelFormatView` or unoptimized resolve texture, -//! a level under 16 a side, a pass whose draw calls draw nothing (a draw call of no vertices drops -//! the sign as any draw call does), or a later pass that loads the attachment and resolves it, -//! alike. No device's resolve gives either (each keeps the NaN, or zeroes it where Metal keeps it: -//! MoltenVK after the copy), so in a pass whose draws reach no tile, every sample holding the -//! clear, the resolve texture's render area is written after the pass's resolve, its copies -//! included, the same way: a scratch image cleared to that texel's bits and copied in. A pass that -//! draws resolves by the device (`device-rounded-resolve`). -//! -//! **32-bit floats**. Metal clears a `float` NaN as the double's conversion, its sign and top -//! payload bits kept, at every level, as the devices' clears do ([`clear_value::color`] states the -//! bits), so such a clear needs nothing before the pass. Its resolve in a pass with no draw call -//! keeps the clear's texel where the `half` NaN's resolve keeps it, and makes `0x7fc00000` in each -//! NaN channel elsewhere, a pass whose draw calls draw nothing among them (the consumer's M3 Max: -//! `R32Float`, `RG32Float` and `RGBA32Float` at 2 and 4 samples, 16 a side, cleared to `-NaN`, a -//! draw call of no vertices: `0x7fc00000`). A device's resolve need give neither: MoltenVK's, which -//! is Metal's own resolve, keeps the sign where its pass records no draw. So in a pass whose draws -//! reach no tile the resolve is written after the pass as the `half` one's is, the kept texel or -//! Metal's resolve of it ([`clear_value::float_nan_texel`]), on every device alike: where the -//! device's resolve stored it already, the write stores the same bits. +//! **Color**. Metal writes the canonical quiet NaN for a `half` NaN clear (`0x7e00` of either +//! sign), and `0x7e0` and `0x3f0` for the 11- and 10-bit channels of `RG11B10Float`, the sign +//! dropped, but where it keeps the attachment's texture losslessly compressed, its level is 16 +//! texels or more a side, and the pass has no draw call ([`keeps_nan_sign`]), where it keeps a +//! `half` NaN's sign. Its resolve of such a clear in a pass with no draw call keeps the clear's +//! texel or averages the samples, each NaN counted zero, and makes `0x7fc00000` in each `float` +//! NaN channel. Vulkan converts a clear value to the attachment's format as the device likes, and +//! resolves its samples as the device likes: the pass clears and resolves by the device, announced +//! (`device-nan-encoding`, [`degrade_nan_clears`]). An integer clear converts nothing. //! //! **Copies that convert NaNs**. A device whose copy into a multisampled float image draws the //! samples through that image's format (`RuntimeDriverDefect::MultisampledCopiesConvertFloatNans`: -//! RADV, whose copies store every 16-bit float NaN as `0xfe00`) cannot copy the scratch's bits into -//! a multisampled attachment. There the clear is written through a view of the attachment's image -//! in the unsigned-integer format of its texel size instead: a render pass of that view alone, -//! loaded and stored, in which `vkCmdClearAttachments` clears the clear's reach to the texel's bits -//! (an integer clear converts nothing). A multisampled color render target the runtime makes of -//! such a format takes the view there where it costs the image nothing ([`view_candidate`]), as one -//! of `PixelFormatView` usage does; an image that takes none (a caller's, or one the view would -//! cost) is copied as elsewhere, announced once (`device-nan-encoding`). A resolve's write lands in -//! a single-sampled texture, whose copies keep the bits. The runtime's other copies into such an -//! image, a blit copy between textures and an attachment stand-in's, announce the same -//! ([`degrade_converting_copy`]); a blit copy between two images that both take the unsigned view -//! runs through it instead, exactly (`sample_planes::BitsCopy`). +//! RADV, whose copies store every 16-bit float NaN as `0xfe00`) does not copy a NaN's bits into a +//! multisampled image. A multisampled color render target the runtime makes of such a format takes +//! a view in the unsigned-integer format of its texel size where it costs the image nothing +//! ([`view_candidate`]), as one of `PixelFormatView` usage does, and a blit copy between two images +//! that both take the unsigned view runs through it, exactly (`sample_planes::BitsCopy`). Into an +//! image that takes none (a caller's, or one the view would cost) the device copies, announced once +//! (`device-nan-encoding`, [`degrade_converting_copy`]): a blit copy between textures and an +//! attachment stand-in's. //! //! **Depth** (our probe `nanclear`, the M3 Max under macOS 27.0.1, plain Metal): a `Clear` load //! whose `clearDepth` is a NaN of any sign or payload stores `0x7fc00000` in every texel and @@ -87,30 +43,20 @@ //! hands such a store to its driver (`render_target::DontCare::Discarded`, MoltenVK among them), //! where Metal keeps the texture's earlier texels, which the word would replace; and a //! multisampled depth on a device without either form of the write. -//! -//! Refused (`NotImplemented(Render)`): such a clear of a memoryless attachment (no image to copy -//! into), of one whose sample planes stand for it (`sample_planes.rs` clears the planes by the -//! device's conversion), of one whose resolve texture reaches past it (`resolve.rs` clears that -//! reach likewise), of a 3D or 1D attachment (`attachment_stand_in::stand_in_as`), and of an -//! attachment whose image takes no transfer writes. -use super::attachment_stand_in::{self, StandInCopies}; use super::blit::TRANSFER; use super::buffer::Buffer; -use super::clear_reach; use super::clear_value; use super::command_buffer::CommandBuffer; use super::degradation::Degradation; use super::depth_copy::{self, DepthDraw, Drawn}; use super::depth_stencil_scratch::colour_copies_refused; use super::encoder::EncoderCore; -use super::error::{internal, Error, RuntimeGap}; +use super::error::{internal, Error}; use super::framebuffer_fetch::views_in; use super::image_plan::{compatible, ImagePlan}; use super::render_pass::{PassLayout, Target}; -use super::render_target::{ - self, DontCare, FramebufferObject, RenderPassObject, ATTACHMENT_STAGES, -}; +use super::render_target::DontCare; use super::render_values::{LoadAction, StoreAction}; use super::resource::ResourceKey; use super::sample_copy::bits_image; @@ -128,301 +74,39 @@ use metal2vulkan::vk::{ Format, ImageAspectFlags, ImageCreateFlags, ImageUsageFlags, NumericFormat, }; -/// The clears before a pass of its attachments whose `Clear` load holds a `half` or small-float -/// NaN (the module docs), with the uses they make and the copies into the attachments. -pub(super) struct NanClears { - /// Each scratch image, its clear value and its layers. - clears: Vec<(vk::Image, vk::ClearColorValue, u32)>, - uses: Vec>, - copies: Option, - /// The scratch images, held until the command buffer completes. - scratch: Vec, - /// The clears through an unsigned-integer view of the attachment (the module docs), and the - /// uses they make. - views: Vec, - view_uses: Vec>, -} - -/// A NaN write through a view of the target's image in the unsigned-integer format of its texel -/// size: a render pass of that view alone, loaded and stored (`render_target::reach_pass`), in -/// which `vkCmdClearAttachments` clears `extent` from the origin, over `layers`, to `value`. -struct ViewClear { - pass: RenderPassObject, - framebuffer: FramebufferObject, - extent: [u32; 2], - layers: u32, - value: vk::ClearColorValue, -} - -impl NanClears { - /// The clears of `layout`'s attachments, a pass with a draw call where `called` - /// (`clear_reach::cleared`), each attachment cleared here then loaded in the pass; then, - /// in a pass whose draws reach no tile (`drew` false: no draw call, or draw calls that draw - /// nothing), the writes of their resolves after the pass (the module docs). `None` for either - /// when there is none; refused as the module docs say. - pub(super) fn plan( - maker: &CommandBuffer, - layout: &mut PassLayout, - (called, drew): (bool, bool), - ) -> Result<(Option, Option), Error> { - let mut before = Writes::default(); - let mut after = Writes::default(); - let mut cleared = Vec::new(); - for (index, color) in layout.colors.iter().enumerate() { - let Some(color) = color.as_ref().filter(|c| c.load == LoadAction::Clear) else { - continue; - }; - let pixel_format = color.target.texture.pixel_format(); - let signed = keeps_nan_sign(&color.target, called); - // The resolve texture's level and slice, where the pass's draws reach no tile, so - // every sample holds the clear. - let resolves = matches!( - color.store, - StoreAction::MultisampleResolve | StoreAction::StoreAndMultisampleResolve - ); - let to = color - .resolve - .as_ref() - .filter(|_| resolves && !drew && color.target.samples > 1) - .map(|r| r.copy_to.as_ref().unwrap_or(&r.attachment)); - let Some(texel) = clear_value::nan_texel(pixel_format, &color.clear, signed) else { - // A 32-bit float NaN, which the device clears as Metal does: its resolve written - // with the clear's texel where Metal keeps it, else with Metal's resolve of it, as - // below (the module docs). - if let Some(to) = to { - let kept = signed && keeps_nan_sign(to, called); - if let Some(texel) = - clear_value::float_nan_texel(pixel_format, &color.clear, kept) - { - after.add(maker, to, texel, layout.extent)?; - } - } - continue; - }; - let past_resolve = color.resolve.as_ref().is_some_and(|r| r.clear.is_some()); - if color.memoryless || color.planes.is_some() || past_resolve { - return Err(Error::NotImplemented(RuntimeGap::Render)); - } - let extent = match clear_reach::stores(color.store) { - true => clear_reach::cleared(layout, color.target.extent, called), - false => layout.extent, - }; - before.add(maker, &color.target, texel, extent)?; - cleared.push(index); - let Some(to) = to else { - continue; - }; - let texel = match signed && keeps_nan_sign(to, called) { - true => Some(texel), - false => clear_value::resolved_nan_texel(pixel_format, &color.clear), - }; - let texel = texel.ok_or_else(|| internal("a NaN clear without a resolved texel"))?; - after.add(maker, to, texel, layout.extent)?; - } - let before = before.finish()?; - for index in cleared { - if let Some(color) = layout.colors.get_mut(index).and_then(Option::as_mut) { - color.load = LoadAction::Load; - } - } - Ok((before, after.finish()?)) - } - - /// Record the clears and the copies in `core`'s command buffer, between barriers from - /// everything before and to everything after, and hold the scratch images until it - /// completes. - pub(super) fn record(self, core: &mut EncoderCore) { - let NanClears { - clears, - uses, - copies, - scratch, - views, - view_uses, - } = self; - core.barrier(Barrier::everything()); - core.command(TRANSFER, &uses, |device, raw| { - for (image, value, layers) in &clears { - let range = vk::ImageSubresourceRange { - aspect_mask: vk::ImageAspectFlags::COLOR, - base_mip_level: 0, - level_count: 1, - base_array_layer: 0, - layer_count: *layers, - }; - // SAFETY: the encoder's command buffer is recording outside a render pass; the - // scratch image is live until it completes (held below), rests in `GENERAL`, - // takes transfer writes (`stand_in_as` with copies), and has one level and - // `layers` layers of a color aspect; an unsigned-integer format takes `uint32`. - unsafe { - device.cmd_clear_color_image( - raw, - *image, - vk::ImageLayout::GENERAL, - value, - &[range], - ); - } - } - }); - if let Some(copies) = copies { - copies.record(core); - } - core.retain(scratch); - if views.is_empty() { - return; - } - core.barrier(Barrier::everything()); - core.command(ATTACHMENT_STAGES, &view_uses, |device, raw| { - for clear in &views { - let [width, height] = clear.extent; - let area = vk::Rect2D { - offset: vk::Offset2D { x: 0, y: 0 }, - extent: vk::Extent2D { width, height }, - }; - let begin = vk::RenderPassBeginInfo::default() - .render_pass(clear.pass.raw) - .framebuffer(clear.framebuffer.raw) - .render_area(area); - let attachments = [vk::ClearAttachment { - aspect_mask: vk::ImageAspectFlags::COLOR, - color_attachment: 0, - clear_value: vk::ClearValue { color: clear.value }, - }]; - let rects = [vk::ClearRect { - rect: area, - base_array_layer: 0, - layer_count: clear.layers, - }]; - // SAFETY: the encoder's command buffer is recording outside a render pass; the - // pass, its framebuffer and the attachment's image are live until it completes - // (held below, and the texture by the encoder); the image rests in `GENERAL`, the - // pass's layout; the area is the framebuffer's and the layers its own; the - // subpass's one color attachment is the one cleared, of an unsigned-integer - // format, which takes `uint32`. - unsafe { - device.cmd_begin_render_pass(raw, &begin, vk::SubpassContents::INLINE); - device.cmd_clear_attachments(raw, &attachments, &rects); - device.cmd_end_render_pass(raw); - } - } - }); - core.barrier(Barrier::everything()); - core.retain(views); - } -} - -/// A pass's NaN writes as they are planned ([`NanClears::plan`]): each a scratch image of an -/// unsigned-integer format, cleared to a texel's bits and copied into its target. -#[derive(Default)] -struct Writes { - /// Each scratch image, its clear value and its layers. - clears: Vec<(vk::Image, vk::ClearColorValue, u32)>, - uses: Vec>, - /// Each scratch image, the target it is copied into, and the extent from the origin copied. - pairs: Vec<(Target, Target, [u32; 2])>, - /// The writes through an unsigned-integer view of the target, and the uses they make. - views: Vec, - view_uses: Vec>, -} - -impl Writes { - /// Write `texel`, an unsigned-integer format of its size and the clear value of its bits - /// (`clear_value::nan_texel`), into `to` over `extent` from the origin; refused where `to`'s - /// image takes no copies (`attachment_stand_in::check_copies`). On a device whose - /// multisampled copies convert float NaNs, a multisampled `to` is written through its image's - /// view in that format where the image takes one, else by the copy, announced (the module - /// docs). - fn add( - &mut self, - maker: &CommandBuffer, - to: &Target, - (format, value): (metal2vulkan::vk::Format, vk::ClearColorValue), - extent: [u32; 2], - ) -> Result<(), Error> { - let device = maker.device(); - if to.samples > 1 && converts_nans(device) { - if views_in(to.texture.image_plan()?, format) - && renders_unsigned(device, format, to.samples)? - { - let viewed = Target { - format, - ..to.clone() - }; - let (pass, framebuffer, made) = - render_target::reach_pass(device, &viewed, false, extent)?; - self.view_uses.extend(made); - self.views.push(ViewClear { - pass, - framebuffer, - extent, - layers: to.layers, - value, - }); - return Ok(()); - } - device.degrade(Degradation::DeviceNanEncoding, || { - ( - format!( - "a multisampled {:?} attachment's NaN clear", - to.texture.pixel_format() - ), - "its image takes no view in the unsigned-integer format of its texel size \ - that the device renders at its sample count, and the device's copy into a \ - multisampled float image stores each NaN as it converts it \ - (`RuntimeDriverDefect::MultisampledCopiesConvertFloatNans`), not with the \ - sign and payload Metal's clear stores" - .to_owned(), - ) - }); - } - attachment_stand_in::check_copies(to)?; - let scratch = attachment_stand_in::stand_in_as(maker, to, true, format)?; - let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE); - self.uses.push( - scratch - .texture - .image_use(0..1, 0..scratch.layers, write, true)?, - ); - self.clears - .push((scratch.texture.raw_image()?, value, scratch.layers)); - self.pairs.push((scratch, to.clone(), extent)); - Ok(()) - } - - /// The writes' clears and copies; `None` when there is none. - fn finish(self) -> Result, Error> { - if self.pairs.is_empty() && self.views.is_empty() { - return Ok(None); - } - let pairs: Vec<_> = self - .pairs - .iter() - .map(|(from, to, extent)| (from, to, *extent)) - .collect(); - let copies = match pairs.is_empty() { - true => None, - false => Some( - StandInCopies::plan(&pairs, false)? - .ok_or_else(|| internal("NaN writes without copies"))?, - ), +/// Announce `PrecisionNote::DeviceNanEncoding` where a color attachment of `layout`, a pass whose +/// draws reach a tile where `drew`, clears to a NaN whose bits the device's conversion decides (the +/// module docs): a `half` or small-float channel's, or a resolve's of a pass whose draws reach no +/// tile, where every sample holds the clear. +pub(super) fn degrade_nan_clears(device: &Device, layout: &PassLayout, drew: bool) { + let held = layout.colors.iter().flatten().find_map(|color| { + let resolves = matches!( + color.store, + StoreAction::MultisampleResolve | StoreAction::StoreAndMultisampleResolve + ) && color.resolve.is_some() + && !drew + && color.target.samples > 1; + let pf = color.target.texture.pixel_format(); + let narrow = (color.load == LoadAction::Clear) + .then(|| clear_value::nan_channels(pf, &color.clear)) + .flatten()?; + (narrow || resolves).then_some((pf, narrow)) + }); + let Some((pf, narrow)) = held else { + return; + }; + device.degrade(Degradation::DeviceNanEncoding, || { + let what = match narrow { + true => "the device converts it to the format's NaN as it likes", + false => "the device's resolve of its samples keeps or drops the NaN as it likes", }; - let Writes { - clears, - uses, - pairs, - views, - view_uses, - } = self; - Ok(Some(NanClears { - clears, - uses, - copies, - scratch: pairs.into_iter().map(|(from, _, _)| from.texture).collect(), - views, - view_uses, - })) - } + ( + format!("a {pf:?} color attachment's NaN clear"), + format!( + "{what}, where Metal stores its canonical quiet NaN or the clear's sign and payload" + ), + ) + }); } /// Whether Metal's NaN clear of `target`, in a pass with a draw call where `called`, keeps a @@ -450,8 +134,7 @@ pub(super) fn keeps_nan_sign(target: &Target, called: bool) -> bool { } /// Whether `format` is a color format of floats narrower than 32 bits (a `half`'s, a packed -/// small float's): those whose NaN clear the runtime writes ([`clear_value::nan_texel`]), and -/// whose NaNs a device whose multisampled copies convert float NaNs converts +/// small float's): those whose NaNs a device whose multisampled copies convert float NaNs converts /// (`driver_defects.rs`: RADV's copy exports them through a conversion). pub(super) fn narrow_float(format: Format) -> bool { format.block().is_some_and(|block| { @@ -504,11 +187,11 @@ fn converts_nans(device: &Device) -> bool { } /// `plan` mutable with a view in the unsigned-integer format of its texel size, through which a -/// NaN clear writes its samples (the module docs), where the device's multisampled copies convert -/// float NaNs: a multisampled color attachment that is not transient, of a format whose NaN -/// clear the runtime writes, whose view format is of its compatibility class and one the device -/// renders at its sample count ([`renders_unsigned`]). `None` elsewhere, and where the plan -/// takes the view already. +/// copy of its samples keeps their bits (the module docs, `sample_planes::BitsCopy`), where the +/// device's multisampled copies convert float NaNs: a multisampled color attachment that is not +/// transient, of a format of floats narrower than 32 bits ([`narrow_float`]), whose view format +/// is of its compatibility class and one the device renders at its sample count +/// ([`renders_unsigned`]). `None` elsewhere, and where the plan takes the view already. pub(super) fn view_candidate( plan: &ImagePlan, device: &Device, diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index be3d60af0..1ac630111 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -301,7 +301,7 @@ use super::kept_bytes; use super::linear_attachment; use super::linear_merge::LinearMerge; use super::live_bind::{Emptied, LiveBind, Reshape}; -use super::nan_clear::{keeps_nan_sign, NanClears, NanDepthWrite}; +use super::nan_clear::{keeps_nan_sign, NanDepthWrite}; use super::owned_kernel::OwnedModule; use super::pipeline::Settled; use super::pipeline::{BufferForms, DrawPipeline}; @@ -4678,13 +4678,8 @@ impl RenderLowering { scratch(&|index, c| stored(c) && !merged.iter().any(|&(at, _)| at == index)); copied_back.extend(depth_stencil_copies(true)); let stand_ins_out = StandInCopies::plan_aspects(&copied_back, false)?; - // A clear holding a `half` or small-float NaN: written before the pass as Metal writes - // it, through a scratch image of an integer format, and loaded in the pass - // (`nan_clear.rs`). After the stand-ins' copies, which keep the attachment's own load. - // And, in a pass whose draws reach no tile, its resolves written after the pass as - // Metal's resolve stores them (`nan_clear.rs`). - let (nan_clears, nan_resolves) = - NanClears::plan(core.command_buffer(), &mut layout, (called, drew))?; + // A clear holding a NaN the device's conversion or resolve decides (`nan_clear.rs`). + super::nan_clear::degrade_nan_clears(core.device(), &layout, drew); // A depth whose `Clear` load held a NaN, loaded instead: Metal's word written into its // texture over the clear's reach before the pass, before anything copies the depth out // of it (`nan_clear.rs`). @@ -5060,9 +5055,6 @@ impl RenderLowering { for (_, merge) in &merged { merge.record_keep(&mut core); } - if let Some(clears) = nan_clears { - clears.record(&mut core); - } if let Some(clears) = reach_clears { clears.record(&mut core); } @@ -5486,9 +5478,6 @@ impl RenderLowering { if let Some(copies) = resolve_copies { copies.record(&mut core); } - if let Some(writes) = nan_resolves { - writes.record(&mut core); - } if let Some(results) = results { results.record(&mut core); } @@ -8526,7 +8515,7 @@ impl RenderLowering { }; // The formats the draw binds, which a specialized notice names. let formats = |slot| tables.bound_format(slot); - device.degrade_half_texel_writes(&variant.pipeline().dependencies, Some(&formats)); + device.degrade_half_texel_writes(&variant.pipeline().dependencies); (variant.objects()).degrade_bound_formats(&variant.pipeline().stages, Some(&formats)); // A variant whose notes test no bound value is quiet at every draw, and kept as none // (`Device::tests_bound_values`). diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index e3bf60b4d..7f67c5bd2 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -1942,7 +1942,7 @@ impl RenderLowering { let formats = |slot| tables.bound_format(slot); self.core .device() - .degrade_half_texel_writes(&variant.pipeline().dependencies, Some(&formats)); + .degrade_half_texel_writes(&variant.pipeline().dependencies); self.core .device() .degrade_bound_formats(&variant.pipeline().stages, Some(&formats)); diff --git a/crates/metal2vulkan-runtime/src/render/inline_first.rs b/crates/metal2vulkan-runtime/src/render/inline_first.rs index fad46aeab..0b4906278 100644 --- a/crates/metal2vulkan-runtime/src/render/inline_first.rs +++ b/crates/metal2vulkan-runtime/src/render/inline_first.rs @@ -134,7 +134,6 @@ use crate::clear_reach; use crate::device::Device; use crate::error::Error; use crate::linear_attachment; -use crate::nan_clear::keeps_nan_sign; use crate::render_pass::{ColorTarget, PassLayout}; use crate::render_target::{ self, Feedback, FramebufferObject, PassShape, Position, RenderPassObject, @@ -248,15 +247,8 @@ pub(super) fn opens_inline( // late. Else the first action ruled out. let loaded = match color.load { LoadAction::Load => (area != layout.extent).then_some(ActionsRefused::UnequalReach), - LoadAction::Clear => { - let signed = keeps_nan_sign(target, true); - let format = texture.pixel_format(); - match clear_reach::cleared(layout, target.extent, true) == area { - false => Some(ActionsRefused::UnequalReach), - true => crate::clear_value::nan_texel(format, &color.clear, signed) - .map(|_| ActionsRefused::NanClear), - } - } + LoadAction::Clear => (clear_reach::cleared(layout, target.extent, true) != area) + .then_some(ActionsRefused::UnequalReach), LoadAction::DontCare => Some(ActionsRefused::DontCareLoad), }; let refused = loaded diff --git a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs index 28e4abbfa..0923f7e8f 100644 --- a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs +++ b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs @@ -1113,10 +1113,7 @@ impl RenderLowering { .objects() .tested_formats(&|slot| tables.bound_format(slot)) }); - device.degrade_half_texel_writes( - &variant.pipeline().dependencies, - Some(&|slot| tables.bound_format(slot)), - ); + device.degrade_half_texel_writes(&variant.pipeline().dependencies); device.degrade_bound_formats( std::slice::from_ref(&variant.pipeline().stage), Some(&|slot| tables.bound_format(slot)), diff --git a/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs b/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs index 3dea8d5ef..c8709c912 100644 --- a/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs +++ b/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs @@ -77,7 +77,6 @@ fn fit_into(dependencies: &mut Vec) { RuntimeFact::ExactFormsOverCompilerLimit { sampling: true, texel_conversion: true, - nan_and_min_max: false, }, Mechanism::None, )); diff --git a/crates/metal2vulkan-runtime/src/tests/nan_signs.rs b/crates/metal2vulkan-runtime/src/tests/nan_signs.rs index 42e97e1f8..91f0730d0 100644 --- a/crates/metal2vulkan-runtime/src/tests/nan_signs.rs +++ b/crates/metal2vulkan-runtime/src/tests/nan_signs.rs @@ -114,10 +114,11 @@ fn a_draw_call_drops_a_half_nan_s_sign() { } /// On a device whose multisampled copies convert float NaNs (RADV), a multisampled render target -/// the runtime makes, of a format whose NaN clear it writes, takes a view in the unsigned-integer -/// format of its texel size, through which the clear is written (`nan_clear.rs`), wherever it -/// costs the image nothing; where the view would change the image's memory requirements, its -/// clear is announced instead. Elsewhere nothing asks for it. Each prints `NAN-CLEAR-VIEW`. +/// the runtime makes, of a format of floats narrower than 32 bits, takes a view in the +/// unsigned-integer format of its texel size, through which a copy keeps its samples' bits +/// (`nan_clear.rs`), wherever it costs the image nothing; where the view would change the image's +/// memory requirements, its copies are announced instead. Elsewhere nothing asks for it. Each +/// prints `NAN-CLEAR-VIEW`. #[test] fn a_nan_clear_target_takes_an_unsigned_view_where_copies_convert_and_it_is_free() { let scratch = Scratch::new(); diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 38dc57eb6..230a8a7d3 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -584,8 +584,6 @@ pub(crate) enum ActionsRefused { /// of whole tiles (`clear_reach.rs`) reaches another extent than another color's, or loaded, /// or a memoryless color smaller, where another's clear reaches past the render area. UnequalReach, - /// Cleared to a NaN whose bits the device's clear would not keep (`clear_value::nan_texel`). - NanClear, /// Resolved, into a resolve attachment or by a copy after the pass. Resolve, /// Stored other than by `Store`, or late (`storeActionOptions` set after the encoder). @@ -3739,9 +3737,6 @@ pub struct WorkCounts { /// smaller memoryless texture. A pass whose attachments share the reach records its first /// instance inline over it. pub passes_not_inline_actions_unequal_reach: u64, - /// Of those, the ones where it is a clear to a NaN whose bits the device's clear would not - /// keep. - pub passes_not_inline_actions_nan_clear: u64, /// Of those, the ones where it is a resolve, into a resolve attachment or by a copy after the /// pass. pub passes_not_inline_actions_resolve: u64, @@ -5012,7 +5007,6 @@ impl Device { .load(Ordering::Relaxed), passes_not_inline_actions_dont_care_load: actions(ActionsRefused::DontCareLoad), passes_not_inline_actions_unequal_reach: actions(ActionsRefused::UnequalReach), - passes_not_inline_actions_nan_clear: actions(ActionsRefused::NanClear), passes_not_inline_actions_resolve: actions(ActionsRefused::Resolve), passes_not_inline_actions_store: actions(ActionsRefused::Store), passes_not_inline_buffer_textures: not_inline(NotInline::BufferTextures), diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 3862e06b1..22f41bc00 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -3d4df3af6a75270a98fba273007ec0aa849a57a434bd7b5a61058b6ba89b9c39 +ba946094128fdce3aefe2b69a7e272da1ee6847dd4f21d40e05fd04b43e5094d diff --git a/crates/metal2vulkan-validation/src/bin/corpus-draw-ab.rs b/crates/metal2vulkan-validation/src/bin/corpus-draw-ab.rs index 2e143d31f..113995edf 100644 --- a/crates/metal2vulkan-validation/src/bin/corpus-draw-ab.rs +++ b/crates/metal2vulkan-validation/src/bin/corpus-draw-ab.rs @@ -110,8 +110,8 @@ //! `--policy NAMES` (`run` and `time`) opens the device with those `DevicePolicy` switches at their //! accurate forms, where it opens at the default policy otherwise: a comma-separated list of //! `exact-answers` (`DevicePolicy::exact_answers`) and field names (`sampling`, `ycbcr_filter`, -//! `texel_conversion`, `nan_and_min_max`), each set to its `Exact` form, so a making under an -//! application's exact forms is timed as it makes them. +//! `texel_conversion`), each set to its `Exact` form, so a making under an application's exact +//! forms is timed as it makes them. //! //! `--device-type` names the device the draw runs on, as validation's other device commands do //! (`cpu` matches only a CPU implementation such as lavapipe); the device opens through @@ -148,7 +148,7 @@ use metal2vulkan::bind::SamplerDescriptor; use metal2vulkan::device::{ - DevicePolicy, NanMinMaxPolicy, SamplingPolicy, TexelConversionPolicy, YCbCrFilterPolicy, + DevicePolicy, SamplingPolicy, TexelConversionPolicy, YCbCrFilterPolicy, }; use metal2vulkan::metal::state::DepthStencilDescriptor; use metal2vulkan::metal::CompareFunction; @@ -316,11 +316,9 @@ fn policy(options: &BTreeMap) -> Result { "sampling" => policy.sampling = SamplingPolicy::Exact, "ycbcr_filter" => policy.ycbcr_filter = YCbCrFilterPolicy::Exact, "texel_conversion" => policy.texel_conversion = TexelConversionPolicy::Exact, - "nan_and_min_max" => policy.nan_and_min_max = NanMinMaxPolicy::Exact, _ => { return Err(format!( - "--policy {name:?}: exact-answers, sampling, ycbcr_filter, texel_conversion \ - or nan_and_min_max" + "--policy {name:?}: exact-answers, sampling, ycbcr_filter or texel_conversion" )) } } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/color_writes.rs b/crates/metal2vulkan-validation/src/runtime_lane/color_writes.rs index 3e1ed76b3..48da0d5fb 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/color_writes.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/color_writes.rs @@ -36,14 +36,13 @@ //! Each case draws the same inputs into the format, every channel of a texel the same input, //! plain and through blending with factors one and zero, reads the attachment back, and compares //! every channel with the rule. One difference is the recorded near-equivalent -//! `DeviceNanEncoding`, not a failure, where the fragment stage records it: a NaN a half-float -//! channel stores as another NaN (ANV and RADV store `0xfe00`; lavapipe quiets or canonicalizes a -//! `half` NaN). Such channels are counted and printed apart, with the codes stored; where the -//! fragment stage does not record the note (the driver is measured to store Metal's NaN, -//! `DriverDeviation::MetalFloatColorNans` and `MetalHalfColorNans`, or to store a 16-bit output's -//! bits, `HalfColorOutputBits`, through which MoltenVK writes a `half` output), and for every other -//! channel, a NaN's class included, the lane is exact. A case written through a 16-bit output says -//! so. The fragment function writes the output as computed and the device converts it: where the +//! `DeviceNanEncoding`, not a failure, where the fragment stage records it: a NaN a half-float or +//! unsigned small float channel stores as another NaN (ANV and RADV store `0xfe00`; lavapipe +//! quiets or canonicalizes a `half` NaN; RADV and NVIDIA keep a small float NaN's payload). Such +//! channels are counted and printed apart, with the codes stored; where the fragment stage does +//! not record the note (the driver is measured to store Metal's NaN, +//! `DriverDeviation::MetalFloatColorNans` and `MetalHalfColorNans`), and for every other channel, a +//! NaN's class included, the lane is exact. The fragment function writes the output as computed and the device converts it: where the //! device is measured to convert the kind of channel as Metal does (MoltenVK on Apple's GPUs, //! `DriverDeviation::MetalColorWrites`; `MetalSmallFloatColorWrites`, a `float` output to a //! half-float or `RG11B10Float` channel; `MetalNorm16ColorWrites`, an output to a 16-bit unorm or @@ -57,7 +56,6 @@ use super::resolves::{lane, quiet, Lane}; use crate::candidate::runtime_samples::{library, shape}; use crate::runtime_lane::buffer_with; use metal2vulkan::bind::SRGB_RESOLVE_THRESHOLDS; -use metal2vulkan::error::DriverDeviation; use metal2vulkan::metal::format::WordAttachment; use metal2vulkan::metal::{ BlendFactor, ColorWriteMask, PixelFormat, PrimitiveType, TextureUsage, TextureWriteRoundingMode, @@ -74,10 +72,7 @@ use metal2vulkan_runtime::{ use std::collections::BTreeSet; /// The kinds [`pipeline_states_announce_the_shader_conversion_once`] takes. -pub(super) const COLOR_WRITES: [Degradation; 2] = [ - Degradation::ShaderColorConversion, - Degradation::ShaderHalfColorBits, -]; +pub(super) const COLOR_WRITES: [Degradation; 1] = [Degradation::ShaderColorConversion]; /// The texels of a row. const WIDTH: usize = 1024; @@ -694,9 +689,16 @@ pub(super) fn half_toward_zero(x: f32) -> u16 { sign | (exponent << 10) | ((bits >> 13) & 0x3ff) as u16 } -/// Whether `code`, of `channel`, is a NaN: a half with every exponent bit and a fraction. -fn half_nan(channel: Channel, code: u64) -> bool { - matches!(channel, Channel::Half) && code & 0x7c00 == 0x7c00 && code & 0x3ff != 0 +/// Whether `code`, of `channel`, is a NaN: a half, or an unsigned small float, with every +/// exponent bit and a fraction. +fn float_nan(channel: Channel, code: u64) -> bool { + let fraction = match channel { + Channel::Half => 10, + Channel::UnsignedFloat(bits) => bits, + _ => return false, + }; + let exponent = 0x1f << fraction; + code & exponent == exponent && code & ((1 << fraction) - 1) != 0 } /// The `bits` bits at `offset` of a texel. @@ -714,18 +716,11 @@ struct Drawn { stored: Vec, /// Whether the fragment stage records `PrecisionNote::DeviceNanEncoding`. noted: bool, - /// Whether the fragment stage declares the `StorageInputOutput16` capability: its color output - /// is written as the bits of the half Metal stores, through a 16-bit output. - sixteen: bool, /// Whether the fragment stage records `PrecisionNote::DeviceColorConversion`: the device's own /// conversion of the attachment's channels, printed against Metal's and not held to it. converted: bool, } -/// `OpCapability StorageInputOutput16`: the instruction's first word (two words, opcode 17) and -/// the capability (4436). -const IO16_CAPABILITY: [u32; 2] = [0x0002_0011, 4436]; - /// How a draw blends: not at all, with factors one and zero, or by premultiplied source-over (one /// and one minus the source alpha, added, for color and alpha). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -783,7 +778,6 @@ fn drawn( let noted = fragment .precision_notes .contains(&PrecisionNote::DeviceNanEncoding); - let sixteen = fragment.spirv.windows(2).any(|w| w == IO16_CAPABILITY); let converted = fragment .precision_notes .contains(&PrecisionNote::DeviceColorConversion); @@ -828,7 +822,6 @@ fn drawn( Ok(Drawn { stored, noted, - sixteen, converted, }) } @@ -863,7 +856,6 @@ fn draws_store_metals_codes() { let Drawn { stored, noted, - sixteen, converted, } = match drawn(&lane, case, &values, blend, None) { Ok(drawn) => drawn, @@ -886,7 +878,7 @@ fn draws_store_metals_codes() { channels += 1; let got = field(texel, offset, channel.bits()); let want = metal_of(channel, x, blended, case.output); - if got != want && noted && half_nan(channel, got) && half_nan(channel, want) { + if got != want && noted && float_nan(channel, got) && float_nan(channel, want) { nans += 1; if stores.len() < 4 { stores.insert(format!("{want:#06x} as {got:#06x}")); @@ -902,20 +894,17 @@ fn draws_store_metals_codes() { } } } - let output = if sixteen { ", a 16-bit output" } else { "" }; if nans > 0 { let stores = stores.into_iter().collect::>().join(", "); eprintln!( "color write {label} on {name}: {nans} NaN channels store another NaN \ - (DeviceNanEncoding, recorded{output}: {stores})" + (DeviceNanEncoding, recorded: {stores})" ); } else if noted { eprintln!( "color write {label} on {name}: DeviceNanEncoding recorded, no NaN channel \ - differs{output}" + differs" ); - } else if sixteen { - eprintln!("color write {label} on {name}: written through a 16-bit output"); } let recorded = match converted { true => " (DeviceColorConversion, recorded)", @@ -1183,9 +1172,8 @@ fn channel_lane(pf: PixelFormat, offset: u32) -> usize { /// announces `shader-color-conversion` on every device, its fragment stage listing the attachment /// as rounded (the one rounding the function makes: no device's conversion rounds a half to /// nearest even). One writing `half4` to an `RGBA16Float` attachment at Metal's default mode -/// announces `shader-half-color-bits` where the device writes it as the half's bits through a -/// 16-bit output (MoltenVK, `HalfColorOutputBits`), its stage listing the attachment as written so -/// exactly there and never as rounded. +/// announces no shader conversion, its stage never listing the attachment as rounded: the half is +/// stored as the device converts it. #[test] fn pipeline_states_announce_the_shader_conversion_once() { let (messages, _cache, lane) = lane(); @@ -1198,9 +1186,6 @@ fn pipeline_states_announce_the_shader_conversion_once() { .function_descriptor() }; let compile = device.compile_device(); - let bits = compile - .profile() - .takes_driver_deviation(DriverDeviation::HalfColorOutputBits); // Each kind is announced once per device: the second state's are those the first did not. let mut seen = BTreeSet::new(); for (fragment, rounding, kind, listed) in [ @@ -1213,8 +1198,8 @@ fn pipeline_states_announce_the_shader_conversion_once() { ( "rt6_fill_rgba16float", TextureWriteRoundingMode::TowardZero, - Degradation::ShaderHalfColorBits, - bits, + Degradation::ShaderColorConversion, + false, ), ] { let mut descriptor = @@ -1230,15 +1215,11 @@ fn pipeline_states_announce_the_shader_conversion_once() { compiled.stages.iter().map(list).collect::>() }; let rounded = lists(&|s| s.rounded_colors.as_slice()); - let half_bits = lists(&|s| s.half_bit_colors.as_slice()); - let (want_rounded, want_bits): (&[&[u32]], &[&[u32]]) = - match (kind == Degradation::ShaderColorConversion, listed) { - (true, true) => (&[&[], &[0]], &[&[], &[]]), - (false, true) => (&[&[], &[]], &[&[], &[0]]), - (_, false) => (&[&[], &[]], &[&[], &[]]), - }; + let want_rounded: &[&[u32]] = match listed { + true => &[&[], &[0]], + false => &[&[], &[]], + }; assert_eq!(rounded, want_rounded, "{fragment}"); - assert_eq!(half_bits, want_bits, "{fragment}"); let mut expected: BTreeSet = compiled .stages .iter() @@ -1298,8 +1279,10 @@ fn the_rules_give_metals_spot_answers() { assert_eq!(metal(f10, 1.0 + 1.0 / 32.0 - 1e-7, false), 15 << 5); assert_eq!(metal(f11, 2f32.powi(-20), false), 1); assert_eq!(metal(f11, 2f32.powi(-20) * 0.99, false), 0); - assert!(half_nan(HALF, 0x7e00) && half_nan(HALF, 0xfe00) && half_nan(HALF, 0x7c01)); - assert!(!half_nan(HALF, 0x7c00) && !half_nan(HALF, 0xfc00) && !half_nan(U16, 0x7e00)); + assert!(float_nan(HALF, 0x7e00) && float_nan(HALF, 0xfe00) && float_nan(HALF, 0x7c01)); + assert!(!float_nan(HALF, 0x7c00) && !float_nan(HALF, 0xfc00) && !float_nan(U16, 0x7e00)); + assert!(float_nan(f11, 0x7e0) && float_nan(f11, 0x7c1) && float_nan(f10, 0x3f0)); + assert!(!float_nan(f11, 0x7c0) && !float_nan(f10, 0x3e0)); for c in 0..0x7c0 { let x = unsigned_float_value(c, 6) as f32; assert_eq!(metal(f11, x, false), u64::from(c), "{c:#x}"); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index 36fd5e438..3081ab73d 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -1869,8 +1869,7 @@ fn a_creation_s_notices_and_messages_reach_the_sink_on_the_asking_thread() { /// every precision note a stage records that no specialization removes (a specialized one is /// announced where a draw or dispatch binds a variant keeping it), but /// `ArgumentPixelSamplerScaling`, which a draw or dispatch listing the state announces; -/// `shader-half-color-bits` where a stage writes a `half`'s bits to a color attachment, -/// `shader-color-conversion` where one rounds a color write to Metal's code; and reconvergence +/// `shader-color-conversion` where a stage rounds a color write to Metal's code; and reconvergence /// that is not Metal's. fn making_kinds<'a>(stages: impl IntoIterator) -> BTreeSet { let mut kinds = BTreeSet::new(); @@ -1881,9 +1880,6 @@ fn making_kinds<'a>(stages: impl IntoIterator) -> BTreeS kinds.insert(Degradation::from_precision_note(note)); } } - if !stage.half_bit_colors.is_empty() { - kinds.insert(Degradation::ShaderHalfColorBits); - } if !stage.rounded_colors.is_empty() { kinds.insert(Degradation::ShaderColorConversion); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs b/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs index acff74054..3e4c8cdb1 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs @@ -1190,10 +1190,10 @@ const MIN_MAX_CASES: [&str; 4] = [ "nan-model-min-max-at-zeros-and-denormals-under-fast-math", ]; -/// Every word of [`MIN_MAX_CASES`] is the Metal row's of the same chip on every profile: the -/// device's `NMin`, `NMax` and `NClamp` where the profile takes `DriverDeviation::MetalMinMax` -/// (the kernels then require `VkProperty::MetalMinMax`), else the operand the module picks -/// itself (`math::metal_min_max`). +/// Every word of [`MIN_MAX_CASES`] is the Metal row's of the same chip where the profile takes +/// `DriverDeviation::MetalMinMax`: the device's `NMin`, `NMax` and `NClamp` (the kernels then +/// require `VkProperty::MetalMinMax`). Elsewhere the module emits the same instructions and +/// records `native-min-max`, so a differing word is the device's answer, printed, not a failure. #[test] fn minimums_and_maximums_answer_as_metal() { let messages = Messages::default(); @@ -1227,7 +1227,7 @@ fn minimums_and_maximums_answer_as_metal() { differ.len(), metal.len() / 4 ); - if !differ.is_empty() { + if metals && !differ.is_empty() { failures.push(format!( "{case_name} on {name}: words differ from Metal (word, device, Metal): {:x?}", &differ[..differ.len().min(24)] diff --git a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs index d3b36607f..77194ea3b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs @@ -1822,7 +1822,7 @@ fn measure(runs: &[Run]) { "FRAME-COST {name} {label}: a frame's passes: {:.1} recorded their first instance \ inline; not inline for the encoder {:.1}, the layout {:.1}, a memoryless color {:.1}, \ a color's actions {:.1} (a DontCare load {:.1}, a reach not shared {:.1}, \ - a clear to a NaN {:.1}, a resolve {:.1}, a store {:.1}), a texture over a buffer \ + a resolve {:.1}, a store {:.1}), a texture over a buffer \ {:.1}, another attachment kind \ {:.1}, a storage color {:.1}, a stand-in {:.1}, a draw {:.1}; {:.1} split instances \ recorded inline, {:.1} instances ended unrun; the replays' {:.1} render pass begins \ @@ -1834,7 +1834,6 @@ fn measure(runs: &[Run]) { per_frame(|c| c.passes_not_inline_actions), per_frame(|c| c.passes_not_inline_actions_dont_care_load), per_frame(|c| c.passes_not_inline_actions_unequal_reach), - per_frame(|c| c.passes_not_inline_actions_nan_clear), per_frame(|c| c.passes_not_inline_actions_resolve), per_frame(|c| c.passes_not_inline_actions_store), per_frame(|c| c.passes_not_inline_buffer_textures), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/half_storage_writes.rs b/crates/metal2vulkan-validation/src/runtime_lane/half_storage_writes.rs index 5b9394836..fa96f099e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/half_storage_writes.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/half_storage_writes.rs @@ -19,17 +19,17 @@ //! stored as another NaN is counted apart, not as a failure, where the device announces //! `device-nan-encoding` (the recorded near-equivalent). //! -//! The product writes through the storage choice's class (`metal::format::half_storage_class`): -//! as computed on MoltenVK (`DriverDeviation::MetalHalfStorageNans`), and its NaN quieted to -//! `0x7fc00000` elsewhere (`HalfQuietNan`; ANV then stores `0xfe00` and announces the note), the -//! device's conversion rounding every other value; or, on a device not measured to store a -//! written `half`'s NaN as its bits, as the bits the shader rounds toward zero, through the -//! texture's unsigned integer alias (`StorageImageClass::HalfBits`). A case is held to Metal's -//! rounding where the device is measured to make it (`DriverDeviation::MetalHalfStorageWrites`: -//! RADV, ANV, NVIDIA's measured GPUs, lavapipe from Mesa 26.0.8 through 26.2.4 and MoltenVK), the -//! measurement of the deviation on that device; elsewhere the module records the device's -//! conversion (`PrecisionNote::DeviceColorConversion`), and the lane prints the channels that -//! differ without holding them. +//! The product writes through the storage choice's class (`metal::format::storage_choice`): +//! as computed, the device's conversion rounding every value and storing every NaN; or, on a device +//! not measured to store a written `half`'s NaN as its bits, as the bits the shader rounds toward +//! zero, through the texture's unsigned integer alias (`StorageImageClass::HalfBits`). A case is +//! held to Metal's rounding where the device is measured to make it +//! (`DriverDeviation::MetalHalfStorageWrites`: RADV, ANV, NVIDIA's measured GPUs, lavapipe from +//! Mesa 26.0.8 through 26.2.4 and MoltenVK), the measurement of the deviation on that device; +//! elsewhere the module records the device's conversion (`PrecisionNote::DeviceColorConversion`), +//! and the lane prints the channels that differ without holding them. A NaN is the device's, +//! announced as `device-nan-encoding` where the profile does not take `MetalHalfStorageNans` (ANV +//! stores `0xfe00`). use super::color_writes::{ half, half_toward_zero, specials, unsigned_float, unsigned_float_toward_zero, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/half_texel_nans.rs b/crates/metal2vulkan-validation/src/runtime_lane/half_texel_nans.rs index 2aceb1eb4..da6e0fb05 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/half_texel_nans.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/half_texel_nans.rs @@ -1,7 +1,6 @@ //! The NaNs of float texels read, sampled and gathered with `half` and `float` results, on the -//! device the cfg selects, under the validation layer, under the lane's exact policy, under the -//! default one (native device sampling and maths, what a consumer runs) and under the default one -//! with the NaN switch on (`NanMinMaxPolicy::Exact`). +//! device the cfg selects, under the validation layer, under the lane's exact policy and under the +//! default one (native device sampling and maths, what a consumer runs). //! //! What plain Metal answers (our own probe: an Apple M3 Max under macOS 26.7, //! safe and fast math alike, every NaN lane of the eight formats below): a lane is a NaN where a @@ -27,13 +26,11 @@ //! texel (native device sampling and texel conversion): its NaN lanes are printed on //! `HALF-TEXEL-RAW` lines, the device's decode itself. //! -//! What the switch guarantees on every device, and the test asserts: a `half` result's NaN is -//! `0x7e00` wherever Metal's rule does not keep the texel's own bits (a 32-bit float or small -//! float texel, a linear sample), printed on a `HALF-TEXEL-SWITCH-BREACH` line where it is not. -//! The one-texel accesses of a 16-bit float texel keep the device's decode, Metal's bits only -//! where the device widens a half exactly (NVIDIA), and whether a lane is a NaN at all is the -//! device's filter's (a zero-weight tap of an infinity or a NaN may make one); both are measured -//! and printed, not asserted. +//! A NaN's bits are the device's (`device-nan-encoding`, `native-nan-encoding`): Metal's only where +//! the device answers them (a 16-bit float texel's one-texel accesses where the device widens a +//! half exactly, NVIDIA), and whether a lane is a NaN at all is the device's filter's (a +//! zero-weight tap of an infinity or a NaN may make one); both are measured and printed, not +//! asserted. //! //! Under every policy a `half` lane whose value is a finite `float` beyond `half`'s range (the //! largest `float`, alone or filtered) is infinity of its sign, or 65504 where the device's @@ -47,7 +44,6 @@ use super::degrade_notices::{counts, on_device_with}; use super::{buffer_with, read_buffer, WAIT}; use crate::air_library::AirLibrary; use metal2vulkan::bind::SamplerDescriptor; -use metal2vulkan::device::NanMinMaxPolicy; use metal2vulkan::metal::{PixelFormat, SamplerAddressMode, SamplerMinMagFilter, TextureUsage}; use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; use metal2vulkan_devtools::llvm_assemble_text; @@ -516,10 +512,9 @@ fn is_nan(w: u32, half: bool) -> bool { /// The lanes of every access of [`OPS`], `half` and `float`, to every format of [`FORMATS`] on /// `device` that differ from Metal's NaN answers, printed; under the default policy (`raw`) also /// every NaN lane of a `float` result, the device's decode. Returns the count of differing lanes -/// of `half` results and of `float` results, of the `half` NaN lanes that are not `0x7e00` -/// where Metal's rule does not keep the texel's own bits (the switch's guarantee, the module -/// docs), and of the `half` lanes beyond `half`'s range that are neither infinity nor 65504. -fn measure(device: &Device, leg: &str, raw: bool) -> (usize, usize, usize, usize) { +/// of `half` results and of `float` results, and of the `half` lanes beyond `half`'s range that +/// are neither infinity nor 65504. +fn measure(device: &Device, leg: &str, raw: bool) -> (usize, usize, usize) { let sampler = |filter| { let mut d = SamplerDescriptor::new(); d.min_filter = filter; @@ -533,7 +528,7 @@ fn measure(device: &Device, leg: &str, raw: bool) -> (usize, usize, usize, usize sampler(SamplerMinMagFilter::Linear), ); let name = device.name(); - let mut totals = (0, 0, 0, 0); + let mut totals = (0, 0, 0); for half in [true, false] { let result = if half { "half" } else { "float" }; for op in OPS { @@ -547,7 +542,6 @@ fn measure(device: &Device, leg: &str, raw: bool) -> (usize, usize, usize, usize let texture = made(device, f); let got = dispatch(device, (&pipeline, op, half), &texture, s); let (mut nans, mut differ) = (0, 0); - let own = op.one_texel() && f.kind == Kind::Half; for (x, lanes) in got.iter().enumerate() { for (k, &g) in lanes.iter().enumerate() { let want = metal_nan(f, op, x, k, half); @@ -570,18 +564,9 @@ fn measure(device: &Device, leg: &str, raw: bool) -> (usize, usize, usize, usize shown(want) ); } - if half && !own && is_nan(g, true) && g != 0x7e00 { - totals.2 += 1; - if leg == "switch" { - eprintln!( - "HALF-TEXEL-SWITCH-BREACH {leg} {op:?} {:?} texel {x} lane {k}: {g:04x}", - f.format - ); - } - } if let (true, Some(sign)) = (half, overflows(f, op, x, k)) { if g != sign | 0x7c00 && g != sign | 0x7bff { - totals.3 += 1; + totals.2 += 1; eprintln!( "HALF-TEXEL-OVERFLOW {leg} {op:?} {:?} texel {x} lane {k}: {g:04x}", f.format @@ -611,30 +596,22 @@ fn measure(device: &Device, leg: &str, raw: bool) -> (usize, usize, usize, usize } /// Each device's NaN answers for float texels' reads, samples and gathers, `half` and `float`, -/// under the lane's exact policy, the default one, and the default one with the NaN switch on: -/// measured and printed, the differing lanes counted. Under the switch every `half` NaN Metal's -/// rule does not keep is `0x7e00`. +/// under the lane's exact policy and the default one: measured and printed, the differing lanes +/// counted. #[test] fn float_texel_nans_by_device_and_policy() { - for (leg, default, switch) in [ - ("exact", false, false), - ("default", true, false), - ("switch", true, true), - ] { + for (leg, default) in [("exact", false), ("default", true)] { on_device_with( |options| { if default { options.policy = DeviceOptions::default().policy; } - if switch { - options.policy.nan_and_min_max = NanMinMaxPolicy::Exact; - } }, |device, messages| { - let (h, f, breaches, overflows) = measure(device, leg, default); + let (h, f, overflows) = measure(device, leg, default); let announced = counts(&messages.take_notices()); eprintln!( - "HALF-TEXEL-TOTAL {} {leg}: {h} half lanes differ, {f} float lanes differ, {breaches} half NaNs not 0x7e00 outside a 16-bit one-texel access, {overflows} half lanes beyond half's range neither infinity nor 65504; announced {:?}", + "HALF-TEXEL-TOTAL {} {leg}: {h} half lanes differ, {f} float lanes differ, {overflows} half lanes beyond half's range neither infinity nor 65504; announced {:?}", device.name(), announced.keys().map(|k| k.code()).collect::>() ); @@ -643,13 +620,6 @@ fn float_texel_nans_by_device_and_policy() { 0, "a half beyond half's range is infinity or 65504 (the HALF-TEXEL-OVERFLOW lines)" ); - if switch { - assert_eq!( - breaches, - 0, - "under the NaN switch every half NaN Metal's rule does not keep is 0x7e00 (the HALF-TEXEL-SWITCH-BREACH lines)" - ); - } }, ); } 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 c8e24341d..0a79364ab 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/half_write_nans.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/half_write_nans.rs @@ -13,10 +13,10 @@ //! a heap element) each write the `half4` buffer 0 holds at lane `gid` (its bits, [`texel`]) at //! texel `(gid, 0)` of a [`N`] by 1 `Private` texture whose every byte was [`FILL`]. Each //! format's stored words are printed with every lane that differs from Metal's (`in -> stored, -//! Metal's`). A 32-bit float channel stores Metal's on every device (the write turns each NaN -//! into `0x7fc00000`); a 16-bit or packed float channel stores Metal's on a device with -//! `VkProperty::MetalHalfTexelWrites`; and a pipeline whose stores differ announces -//! `device-nan-encoding`. +//! 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`. use super::degrade_notices::{counts, on_device_with}; use super::{buffer_with, layer_reported_nothing, read_buffer, WAIT}; @@ -317,10 +317,10 @@ 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 32-bit float channel, none in a 16-bit -/// or packed float one on a device with `VkProperty::MetalHalfTexelWrites`; 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). +/// 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 +/// `device-nan-encoding` (at its making, or at the dispatch that binds such a texture to a slot of +/// no declared format). #[test] fn half_writes_store_their_nans_as_metal_or_announce() { let mut report = Vec::new(); @@ -380,9 +380,9 @@ fn half_writes_store_their_nans_as_metal_or_announce() { f.name, differ.len() ); - // A 32-bit float channel (not the packed word) takes `0x7fc00000` as it is. - let float32 = f.word_bytes == 4 && f.format != PixelFormat::RG11B10Float; - if float32 || keeps { + // A 16-bit float channel stores the half's bits where the device keeps + // them. + if keeps && f.word_bytes == 2 { assert!( differ.is_empty(), "{access} {}: {} lanes differ from Metal's", diff --git a/crates/metal2vulkan-validation/src/runtime_lane/inline_reasons.rs b/crates/metal2vulkan-validation/src/runtime_lane/inline_reasons.rs index d75356e9c..89230ee95 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/inline_reasons.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/inline_reasons.rs @@ -112,14 +112,13 @@ fn a_pass_that_does_not_record_inline_counts_the_first_check_that_ruled_it_out() } /// The counts of passes kept from recording inline by a color's actions, then by the first -/// action ruled out: a `DontCare` load, a reach past the render area not shared, a clear to a -/// NaN, a resolve, a store. -fn actions_counts(counts: &WorkCounts) -> [u64; 6] { +/// action ruled out: a `DontCare` load, a reach past the render area not shared, a resolve, a +/// store. +fn actions_counts(counts: &WorkCounts) -> [u64; 5] { [ counts.passes_not_inline_actions, counts.passes_not_inline_actions_dont_care_load, counts.passes_not_inline_actions_unequal_reach, - counts.passes_not_inline_actions_nan_clear, counts.passes_not_inline_actions_resolve, counts.passes_not_inline_actions_store, ] @@ -131,14 +130,14 @@ fn actions_counts(counts: &WorkCounts) -> [u64; 6] { /// area of half the texture's side, which Metal's clear of whole 32-pixel tiles reaches past, /// beside a second color loaded, whose texels past the render area Metal keeps (where it is /// alone, the pass records inline over the reach), and a larger texture cleared past a memoryless -/// color's side, which sets the render area; an `RGBA16Float` texture cleared to a NaN, -/// whose bits the device's clear would not keep; resolved, a single-sampled attachment's texels -/// copied into the resolve texture; and stored `DontCare`. +/// color's side, which sets the render area; resolved, a single-sampled attachment's texels +/// copied into the resolve texture; and stored `DontCare`. An `RGBA16Float` texture cleared to a +/// NaN, which the device's clear converts, records inline. #[test] fn a_pass_kept_by_a_color_s_actions_counts_the_first_action_ruled_out() { let (messages, _cache, lane) = lane(); let rgba16f = PixelFormat::RGBA16Float; - let ran = |descriptor: &RenderPassDescriptor, pf: PixelFormat| -> [u64; 6] { + let ran = |descriptor: &RenderPassDescriptor, pf: PixelFormat| -> [u64; 5] { let colors = descriptor .color_attachments .iter() @@ -155,16 +154,12 @@ fn a_pass_kept_by_a_color_s_actions_counts_the_first_action_ruled_out() { let stored = color_pass(&target, None, StoreAction::Store, (0, 0)); let mut undefined = stored.clone(); undefined.color_attachments[0].load_action = LoadAction::DontCare; - assert_eq!( - ran(&undefined, RGBA8), - [1, 1, 0, 0, 0, 0], - "loaded DontCare" - ); + assert_eq!(ran(&undefined, RGBA8), [1, 1, 0, 0, 0], "loaded DontCare"); let mut part = stored.clone(); (part.render_target_width, part.render_target_height) = (SIZE / 2, SIZE / 2); assert_eq!( ran(&part, RGBA8), - [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], "cleared past half its side, alone" ); let beside = lane.single(RGBA8); @@ -174,7 +169,7 @@ fn a_pass_kept_by_a_color_s_actions_counts_the_first_action_ruled_out() { loaded.store_action = StoreAction::Store; assert_eq!( ran(&part, RGBA8), - [1, 0, 1, 0, 0, 0], + [1, 0, 1, 0, 0], "cleared past half its side, beside a color loaded" ); // A 64x64 texture cleared over the 4x4 render area of a memoryless color beside it, loaded and @@ -200,13 +195,13 @@ fn a_pass_kept_by_a_color_s_actions_counts_the_first_action_ruled_out() { cleared.store_action = StoreAction::Store; assert_eq!( ran(&past, RGBA8), - [1, 0, 1, 0, 0, 0], + [1, 0, 1, 0, 0], "cleared past a memoryless color's side" ); let half = lane.single(rgba16f); let mut nan = color_pass(&half, None, StoreAction::Store, (0, 0)); nan.color_attachments[0].clear_color = ClearColor::new(f64::NAN, 0.0, 0.0, 1.0); - assert_eq!(ran(&nan, rgba16f), [1, 0, 0, 1, 0, 0], "cleared to a NaN"); + assert_eq!(ran(&nan, rgba16f), [0, 0, 0, 0, 0], "cleared to a NaN"); let resolve = lane.single(RGBA8); let resolved = color_pass( &target, @@ -214,9 +209,9 @@ fn a_pass_kept_by_a_color_s_actions_counts_the_first_action_ruled_out() { StoreAction::MultisampleResolve, (0, 0), ); - assert_eq!(ran(&resolved, RGBA8), [1, 0, 0, 0, 1, 0], "resolved"); + assert_eq!(ran(&resolved, RGBA8), [1, 0, 0, 1, 0], "resolved"); let unstored = color_pass(&target, None, StoreAction::DontCare, (0, 0)); - assert_eq!(ran(&unstored, RGBA8), [1, 0, 0, 0, 0, 1], "stored DontCare"); + assert_eq!(ran(&unstored, RGBA8), [1, 0, 0, 0, 1], "stored DontCare"); drop((target, beside, scratch, wide, half, resolve)); quiet(lane, &messages); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs b/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs index 885a933f1..f5ab22a7c 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs @@ -1,16 +1,14 @@ //! The device's forms of Metal's maths, through the runtime, on the device the cfg selects, under -//! the validation layer, with the NaN and minimum and maximum choice on and off. Every other lane -//! takes Metal's answers where a switch keeps them (`candidate::runtime_case::validated_options` -//! sets `DevicePolicy::exact_answers`); this one starts from those options. The maths functions, -//! divisions and fused multiply-adds (`PrecisionNote::NativeTranscendentals`, `NativeDivision`, -//! `NativeFma`) and `dot`, `mix` and `fast::sqrt` (`NativeDot`, `NativeMix`, and -//! `NativeTranscendentals` for `fast::sqrt`) are the device's on every device whose functions are -//! not Metal's own; the NaN and minimum and maximum (`NanMinMaxPolicy::Native`: -//! `NativeNanEncoding`, `NativeMinMax`) are where the choice is on. Under each setting the stage -//! records exactly the kinds of the forms it takes (where the device's answer is not Metal's own), -//! the pipeline state announces the kinds its stage records, and every thread's answers stay -//! within the bounds the kinds record; where the choice is off a NaN product is Metal's canonical -//! NaN `0x7fc00000`. +//! the validation layer. Every other lane takes Metal's answers where a switch keeps them +//! (`candidate::runtime_case::validated_options` sets `DevicePolicy::exact_answers`); this one +//! starts from those options. The maths functions, divisions and fused multiply-adds +//! (`PrecisionNote::NativeTranscendentals`, `NativeDivision`, `NativeFma`) and `dot`, `mix` and +//! `fast::sqrt` (`NativeDot`, `NativeMix`, and `NativeTranscendentals` for `fast::sqrt`) are the +//! device's on every device whose functions are not Metal's own, and the NaN and minimum and +//! maximum (`NativeNanEncoding`, `NativeMinMax`) on every device not measured to answer Metal's. +//! The stage records exactly the kinds of the forms it takes (where the device's answer is not +//! Metal's own), the pipeline state announces the kinds its stage records, and every thread's +//! answers stay within the bounds the kinds record. //! //! The kernel reads ten `float`s a thread and writes fourteen: `sin` and `cos` of an angle in //! `[-π, π]`, `exp2` of an exponent in `[-10, 10]`, `log2` of a value in `[2^-20, 2^20]`, a @@ -25,7 +23,7 @@ use super::degrade_notices::{counts, on_device_with}; use super::{buffer_with, read_buffer, Messages, WAIT}; use crate::air_library::AirLibrary; use metal2vulkan::cache::VariantKey; -use metal2vulkan::device::{FloatControl, FloatWidth, NanMinMaxPolicy, VkProperty}; +use metal2vulkan::device::{FloatControl, FloatWidth, VkProperty}; use metal2vulkan::error::DriverDeviation; use metal2vulkan::library::Library; use metal2vulkan::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, PrecisionNote}; @@ -315,75 +313,39 @@ const NATIVE: [PrecisionNote; 7] = [ PrecisionNote::NativeMix, ]; -/// Whether a setting turns the NaN and minimum and maximum choice on. -#[derive(Clone, Copy, Debug)] -struct Setting { - nan_min_max: bool, -} - -/// The choice off and on. -const SETTINGS: [Setting; 2] = [ - Setting { nan_min_max: false }, - Setting { nan_min_max: true }, -]; - /// `x` rounded to a `half` to nearest even (a normal `half`'s magnitude). fn to_half(x: f64) -> f64 { let ulp = half_ulp(x); (x / ulp).round_ties_even() * ulp } -/// Where a thread's answers are not Metal's under `setting` (Metal's own being known exactly where -/// the choice is off): Metal's canonical NaN for the product of a NaN. -fn not_metal_s(setting: Setting, x: &[f32; IN], r: &[f32; OUT]) -> Vec { - let n = x[9]; - let mut out = Vec::new(); - let mut want = |what: &str, got: f32, metal: f32| { - if got.to_bits() != metal.to_bits() { - out.push(format!("{what}: {got:e} for Metal's {metal:e}")); - } - }; - if !setting.nan_min_max && n.is_nan() { - want("n * b", r[9], f32::from_bits(0x7fc0_0000)); - } - out -} - -/// Under each setting, on a device whose `float` functions are not Metal's own, the stage records -/// exactly the kinds of the forms it takes: the maths functions `NativeTranscendentals` and -/// `NativeDivision` (and `NativeFma` where an `fma` takes the device's `Fma`), `NativeDot`, -/// `NativeMix` and `NativeTranscendentals` (`fast::sqrt`), and with the NaN and minimum and maximum -/// on `NativeNanEncoding` (on a device whose arithmetic is not measured to answer Metal's canonical -/// NaN) and `NativeMinMax`; the pipeline state announces each native kind of its stage once; every -/// thread's answers are within the bounds their kinds record, and Metal's where the choice is off. -/// On MoltenVK, whose functions, minimum and maximum, and NaNs are Metal's own, the stage records -/// none of them under any setting and announces none. The device announces -/// `float-tininess-after-rounding` as it is made, exactly off MoltenVK. +/// On a device whose `float` functions are not Metal's own, the stage records exactly the kinds of +/// the forms it takes: the maths functions `NativeTranscendentals` and `NativeDivision` (and +/// `NativeFma` where an `fma` takes the device's `Fma`), `NativeDot`, `NativeMix` and +/// `NativeTranscendentals` (`fast::sqrt`), and `NativeMinMax` where the device is not measured to +/// answer Metal's operand; and `NativeNanEncoding` wherever the device is not measured to answer +/// Metal's canonical NaN (on one measured to, it records the note where the kernel computes another +/// of Metal's NaNs). The pipeline state announces each native kind of its stage once, and every +/// thread's answers are within the bounds their kinds record. On MoltenVK, whose functions and +/// minimum and maximum are Metal's own, the stage records none of their kinds and announces none. +/// The device announces `float-tininess-after-rounding` as it is made, exactly off MoltenVK. #[test] -fn each_choice_answers_within_its_recorded_bounds_on_and_metal_s_off() { +fn native_maths_answers_within_its_recorded_bounds() { let bitcode = llvm_assemble_text(&kernel()).unwrap(); - for setting in SETTINGS { - on_device_with( - |options| { - if setting.nan_min_max { - options.policy.nan_and_min_max = NanMinMaxPolicy::Native; - } - }, - |device, messages| answers_under(device, messages, setting, &bitcode), - ); - } + on_device_with( + |_| {}, + |device, messages| answers_under(device, messages, &bitcode), + ); } -/// [`each_choice_answers_within_its_recorded_bounds_on_and_metal_s_off`] under `setting`, on -/// `device`, made with it. -fn answers_under(device: &Device, messages: &Messages, setting: Setting, bitcode: &[u8]) { - let name = format!("{} {setting:?}", device.name()); +/// [`native_maths_answers_within_its_recorded_bounds`] on `device`. +fn answers_under(device: &Device, messages: &Messages, bitcode: &[u8]) { + let name = device.name().to_string(); let expected = stage_kinds(device, bitcode); let compile = device.compile_device(); let takes = |d| compile.profile().takes_driver_deviation(d); let metals = takes(DriverDeviation::MetalFloatFunctions); eprintln!("{name}: Metal's own functions {metals}; native kinds {expected:?}"); - let Setting { nan_min_max } = setting; // The constructor checked the creation notices against `creation_kinds`: the device's // multiply and fused multiply-add, announced as it was made. assert_eq!( @@ -398,16 +360,16 @@ fn answers_under(device: &Device, messages: &Messages, setting: Setting, bitcode (PrecisionNote::NativeMix, !metals), ( PrecisionNote::NativeMinMax, - nan_min_max && !metals && !takes(DriverDeviation::MetalMinMax), - ), - ( - PrecisionNote::NativeNanEncoding, - nan_min_max && !takes(DriverDeviation::MetalCanonicalNans), + !metals && !takes(DriverDeviation::MetalMinMax), ), ] { let kind = Degradation::from_precision_note(note); assert_eq!(expected.contains(&kind), native, "{name}: {kind:?}"); } + if !takes(DriverDeviation::MetalCanonicalNans) { + let kind = Degradation::from_precision_note(PrecisionNote::NativeNanEncoding); + assert!(expected.contains(&kind), "{name}: {kind:?}"); + } let library = device.new_library_with_air(bitcode).unwrap(); let function = library.new_function_with_name("nm").unwrap(); @@ -470,17 +432,12 @@ fn answers_under(device: &Device, messages: &Messages, setting: Setting, bitcode .enumerate() { failures.extend(broken(x, r).into_iter().map(|f| format!("thread {i}: {f}"))); - failures.extend( - not_metal_s(setting, x, r) - .into_iter() - .map(|f| format!("thread {i}: {f}")), - ); let [_, _, _, a, b, ..] = x.map(f64::from); correctly_rounded += u32::from(r[4] == (a / b) as f32); } eprintln!( - "{name}: {} answers break a bound or Metal's; {correctly_rounded} of {COUNT} quotients \ - correctly rounded", + "{name}: {} answers break a bound; {correctly_rounded} of {COUNT} quotients correctly \ + rounded", failures.len() ); assert!( diff --git a/crates/metal2vulkan-validation/src/runtime_lane/renders.rs b/crates/metal2vulkan-validation/src/runtime_lane/renders.rs index 16ca22af7..d4f4c2795 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/renders.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/renders.rs @@ -26,8 +26,9 @@ //! A case with no current Metal row (one awaiting Metal qualification) goes the same way, and //! says so. //! - **Clears** write Metal's measured bytes: each color format, depth and stencil value an M4 was -//! measured with, the NaNs of half, small-float and float formats among them (a Metal probe, the -//! M3 Max alike). A format the device cannot render is counted. +//! measured with, the NaNs of float formats among them (a Metal probe, the M3 Max alike); a NaN +//! of a half-float or small-float format is the device's conversion, announced. A format the +//! device cannot render is counted. //! - **Load and store actions**, the encoder's late store action, the passes' order against blits //! in one command buffer, and Metal's refusals of passes and draws, typed. What a `DontCare` //! load or store leaves is printed: Metal leaves it undefined, and Apple's GPU keeps the old @@ -44,22 +45,19 @@ use crate::candidate::engine::{linked_modules, LinkedModule, ENGINE_EXECUTOR_ABI use crate::candidate::runtime_case::{ commit_render, render_pipeline_descriptor, render_pipeline_state, RenderInputs, TemplateState, }; -use crate::candidate::runtime_samples::encode as samples_of; use crate::candidate::tests::engine_render; use crate::case::{AuthoredCase, Stage}; use crate::check::interface::AirInterface; -use crate::executor_contract::multisample::{ReadbackView, SampleRead}; use crate::gpu::TEST_DEVICE; use crate::store::CorpusStore; use metal2vulkan::bind::StatusReport; -use metal2vulkan::error::RuntimeDriverDefect; -use metal2vulkan::metal::{IndexType, PixelFormat, PrimitiveType, TextureType, TextureUsage}; +use metal2vulkan::metal::{IndexType, PixelFormat, PrimitiveType, TextureUsage}; use metal2vulkan::pipeline::RenderPipelineDescriptor; use metal2vulkan_runtime::{ AppleOnly, Attachment, BlitOption, Buffer, ClearColor, CommandBuffer, CommandBufferStatus, - Device, DrawProblem, Error, Invalid, LoadAction, Origin, Problem, Region, RenderCommandEncoder, - RenderPassDescriptor, RenderPassProblem, ResourceOptions, Size, StoreAction, Texture, - TextureDescriptor, + Degradation, Device, DrawProblem, Error, Invalid, LoadAction, Origin, Problem, Region, + RenderCommandEncoder, RenderPassDescriptor, RenderPassProblem, ResourceOptions, Size, + StoreAction, Texture, TextureDescriptor, }; use std::collections::BTreeMap; use std::path::Path; @@ -835,15 +833,15 @@ pub(super) fn small_nan(channel: u32, exponent: u32, mantissa: u32) -> bool { (channel >> mantissa) & all == all && channel & ((1 << mantissa) - 1) != 0 } -/// Each channel of a `pf` texel (`RGBA16Float`'s four halves, `RG11B10Float`'s three fields) as -/// its bits, its exponent's width and its mantissa's. +/// Each channel of a `pf` texel (a half-float format's halves, `RG11B10Float`'s three fields) as +/// its bits, its exponent's width and its mantissa's; empty for another format. fn channels(pf: PixelFormat, texel: &[u8]) -> Vec<(u32, u32, u32)> { match pf { - PixelFormat::RGBA16Float => texel + PixelFormat::R16Float | PixelFormat::RG16Float | PixelFormat::RGBA16Float => texel .as_chunks::<2>() .0 .iter() - .map(|h| (u32::from(u16::from_le_bytes([h[0], h[1]])) & 0x7fff, 5, 10)) + .map(|h| (u32::from(u16::from_le_bytes([h[0], h[1]])), 5, 10)) .collect(), PixelFormat::RG11B10Float => { let word = u32::from_le_bytes([texel[0], texel[1], texel[2], texel[3]]); @@ -857,408 +855,29 @@ fn channels(pf: PixelFormat, texel: &[u8]) -> Vec<(u32, u32, u32)> { } } -/// A NaN clear: its format and color, the texel where Metal drops a `half` NaN's sign, and the -/// one where it keeps it ([`NAN_CLEARS`]). -type NanClear = (PixelFormat, [f64; 4], &'static [u8], &'static [u8]); - -/// Metal's NaN clears by format and clear color (an M4 under macOS 27.0.1; a Metal probe; the -/// consumer's M3 Max alike at 4x4): the texel a level stores in its texels or every sample where -/// Metal drops a `half` NaN's sign and payload (an uncompressed texture, or a level under 16 texels -/// a side), then where it keeps them. -const NAN_CLEARS: &[NanClear] = &[ - ( - PixelFormat::RGBA16Float, - [f64::NAN, 1.0, 0.5, f64::NAN], - &[0x00, 0x7e, 0x00, 0x3c, 0x00, 0x38, 0x00, 0x7e], - &[0x00, 0x7e, 0x00, 0x3c, 0x00, 0x38, 0x00, 0x7e], - ), - ( - PixelFormat::RGBA16Float, - [-f64::NAN, -f64::NAN, -f64::NAN, -f64::NAN], - &[0x00, 0x7e, 0x00, 0x7e, 0x00, 0x7e, 0x00, 0x7e], - &[0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe], - ), - ( - PixelFormat::RGBA16Float, - [f64::NAN, 1.0, 0.5, -f64::NAN], - &[0x00, 0x7e, 0x00, 0x3c, 0x00, 0x38, 0x00, 0x7e], - &[0x00, 0x7e, 0x00, 0x3c, 0x00, 0x38, 0x00, 0xfe], - ), - ( - PixelFormat::R16Float, - [-f64::NAN, 0.0, 0.0, 0.0], - &[0x00, 0x7e], - &[0x00, 0xfe], - ), - ( - PixelFormat::RGBA16Float, - [ - f64::from_bits(0x7ffc_0000_0000_0000), - 1.0, - f64::from_bits(0x7ff4_0000_0000_0000), - f64::from_bits(0xffff_ffff_ffff_ffff), - ], - &[0x00, 0x7e, 0x00, 0x3c, 0x00, 0x7e, 0x00, 0x7e], - &[0x00, 0x7f, 0x00, 0x3c, 0x00, 0x7f, 0xff, 0xff], - ), - ( - PixelFormat::RG11B10Float, - [f64::NAN, 1.0, 0.5, f64::NAN], - &[0xe0, 0x07, 0x1e, 0x70], - &[0xe0, 0x07, 0x1e, 0x70], - ), - ( - PixelFormat::RG11B10Float, - [f64::NAN, f64::NAN, f64::NAN, f64::NAN], - &[0xe0, 0x07, 0x3f, 0xfc], - &[0xe0, 0x07, 0x3f, 0xfc], - ), - ( - PixelFormat::R32Float, - [f64::from_bits(0x7ff0_0000_2000_0000), 0.0, 0.0, 0.0], - &[0x01, 0x00, 0xc0, 0x7f], - &[0x01, 0x00, 0xc0, 0x7f], - ), - ( - PixelFormat::R32Float, - [-f64::NAN, 0.0, 0.0, 0.0], - &[0x00, 0x00, 0xc0, 0xff], - &[0x00, 0x00, 0xc0, 0xff], - ), -]; - -/// `texel` with each NaN channel as Metal's 4x resolve makes it where it drops the clear's NaN -/// (a level whose clear drops a `half` NaN's sign): zero in a small-float channel, and -/// `0x7fc00000` in a 32-bit float one. -fn nans_resolved(pf: PixelFormat, texel: &[u8]) -> Vec { - match pf { - PixelFormat::R32Float => texel - .as_chunks::<4>() - .0 +/// Whether texel `got` of `pf` differs from `want` only by one NaN for another in a half-float or +/// small-float channel: the device's conversion of a NaN clear (`device-nan-encoding`). +fn nan_for_nan(pf: PixelFormat, got: &[u8], want: &[u8]) -> bool { + let (got, want) = (channels(pf, got), channels(pf, want)); + !want.is_empty() + && got.len() == want.len() + && got .iter() - .flat_map( - |f| match f32::from_le_bytes([f[0], f[1], f[2], f[3]]).is_nan() { - true => 0x7fc0_0000u32.to_le_bytes(), - false => [f[0], f[1], f[2], f[3]], - }, - ) - .collect(), - PixelFormat::RGBA16Float | PixelFormat::R16Float => texel - .as_chunks::<2>() - .0 - .iter() - .flat_map(|h| { - match small_nan(u32::from(u16::from_le_bytes([h[0], h[1]])) & 0x7fff, 5, 10) { - true => [0, 0], - false => [h[0], h[1]], - } - }) - .collect(), - PixelFormat::RG11B10Float => { - let word = u32::from_le_bytes([texel[0], texel[1], texel[2], texel[3]]); - let fields = [(0, 11, 6), (11, 11, 6), (22, 10, 5)]; - let kept = fields.iter().fold(0u32, |out, &(at, width, mantissa)| { - let field = (word >> at) & ((1 << width) - 1); - match small_nan(field, 5, mantissa) { - true => out, - false => out | (field << at), - } - }); - kept.to_le_bytes().to_vec() - } - _ => texel.to_vec(), - } -} - -/// A NaN `Clear` of a new `Private` attachment (`nan_clear.rs`) of 4x4, 16x16 and 64x64, 1x and -/// 4x, plain (a usage Metal compresses) and with `PixelFormatView` usage (kept uncompressed), -/// in a pass without a draw call, in one whose draw (`rt6_restart`, `clear_reach::Lane`) lies -/// wholly off the target, and in one whose only draw call draws no vertices, stores Metal's texel -/// ([`NAN_CLEARS`]): the one with a `half` NaN's sign where Metal keeps it, at a plain level of 16 -/// or more in a pass without a draw call, and without it elsewhere (a draw call of no vertices is -/// a draw call: the consumer's M3 Max, `R32Float`, `RG32Float` and `RGBA32Float` at 2 and 4 -/// samples, 16 a side, cleared to `-NaN`, resolves `0x7fc00000`). A 1x attachment is read whole by a blit. Each sample of a 4x one -/// is read through an unsigned view of its texel size where its format has one (`RGBA16Float`, -/// `R16Float` and `R32Float`, `runtime_samples::encode`): its own with `PixelFormatView` usage, -/// else a same-format copy's with it (Metal's and the devices' copies keep every sample's bits, but -/// for a device whose multisampled copies convert float NaNs, `MultisampledCopiesConvertFloatNans`, -/// on which a copy's samples are left unread). Every 4x one is resolved into a new plain 1x texture -/// read by a blit. In a pass without a draw call Metal's resolve keeps the texel where it keeps the -/// sign and stores zero in each small-float NaN channel and `0x7fc00000` in each 32-bit float one -/// elsewhere, which the runtime writes on every device (an `R32Float` clear is Metal's conversion -/// of the double at every level); so does one whose draw calls draw nothing, its resolve then -/// Metal's texel without the sign. In a pass with a draw Metal's resolve averages the samples, each -/// NaN zero: a device's resolve whose NaN channels differ only so is its resolve rule, printed -/// (`device-rounded-resolve`), not this clear's. A `BGR10_XR` NaN clear is printed beside them, or -/// the device's refusal of the format. Each prints `MSAA-NAN-CLEAR`. -#[test] -fn multisampled_nan_clears_store_metal_s_texel() { - let (messages, cache, lane) = super::clear_reach::lane(); - let device = &lane.device; - let name = device.name().to_owned(); - let xr: &[NanClear] = &[(PixelFormat::BGR10XR, [f64::NAN, 0.5, 1.0, 1.0], &[], &[])]; - // A triangle wholly off the target, the vertex function's positions. - let off: Vec = [2.0f32, 2.0, 3.0, 2.0, 2.0, 3.0] - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect(); - let off = buffer_with(device, &off).unwrap(); - let (mut wrong, mut checked) = (Vec::new(), 0usize); - // A device whose multisampled copies convert float NaNs (RADV) cannot copy the samples of an - // attachment without `PixelFormatView` usage out to be read. - let copies_convert = device - .properties() - .driver_defects - .contains(&RuntimeDriverDefect::MultisampledCopiesConvertFloatNans); - for &(pf, color, small, large) in NAN_CLEARS.iter().chain(xr) { - let bytes = match pf { - PixelFormat::RGBA16Float => 8, - PixelFormat::R16Float => 2, - _ => 4, - }; - let view = match pf { - PixelFormat::RGBA16Float => Some(ReadbackView::Rg32Uint), - PixelFormat::R16Float => Some(ReadbackView::R16Uint), - PixelFormat::R32Float => Some(ReadbackView::R32Uint), - _ => None, - }; - let measured = !small.is_empty(); - for (side, samples, viewed, drawn) in [4u32, 16, 64] - .into_iter() - .flat_map(|side| [(side, 1u64), (side, 2), (side, 4)]) - .flat_map(|(side, samples)| [(side, samples, false), (side, samples, true)]) - .flat_map(|(side, samples, viewed)| { - [Drawn::No, Drawn::OffTarget, Drawn::Nothing] - .map(|drawn| (side, samples, viewed, drawn)) - }) - .filter(|&(_, _, _, drawn)| measured || drawn == Drawn::No) - { - let usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - let new = |samples: u64, viewed: bool| { - let mut descriptor = - TextureDescriptor::texture_2d(pf, side.into(), side.into(), false); - if samples > 1 { - descriptor.texture_type = TextureType::Type2DMultisample; - descriptor.sample_count = samples; - } - descriptor.usage = match viewed { - true => usage | TextureUsage::PIXEL_FORMAT_VIEW, - false => usage, - }; - descriptor.resource_options = ResourceOptions::private(); - device.new_texture(&descriptor) - }; - let label = format!( - "{pf:?} {color:?} {samples}x {side}x{side}{}{}", - if viewed { " PixelFormatView" } else { "" }, - match drawn { - Drawn::No => "", - Drawn::OffTarget => " drawn off the target", - Drawn::Nothing => " a draw call of no vertices", - } - ); - let texture = match new(samples, viewed) { - Ok(texture) => texture, - Err(Error::Unsupported(why)) => { - println!("MSAA-NAN-CLEAR {label} on {name}: unsupported {why:?}"); - continue; - } - Err(error) => panic!("{label}: {error}"), - }; - let resolved = (samples > 1).then(|| { - attachment( - device, - pf, - [side.into(), side.into()], - ResourceOptions::private(), - ) - .unwrap() - }); - let mut pass = RenderPassDescriptor::new(); - let target = &mut pass.color_attachments[0]; - target.texture = Some(texture.clone()); - target.load_action = LoadAction::Clear; - target.store_action = match &resolved { - Some(resolved) => { - target.resolve_texture = Some(resolved.clone()); - StoreAction::StoreAndMultisampleResolve - } - None => StoreAction::Store, - }; - let [red, green, blue, alpha] = color; - target.clear_color = ClearColor::new(red, green, blue, alpha); - let pipeline = - (drawn != Drawn::No).then(|| lane.pipeline(&[pf], (None, None), samples)); - let command_buffer = lane.queue.command_buffer().unwrap(); - let encoded = command_buffer - .render_command_encoder(&pass) - .and_then(|mut encoder| { - if let Some(pipeline) = &pipeline { - encoder.set_render_pipeline_state(pipeline)?; - encoder.set_vertex_buffer(Some(&off), 0, 0)?; - let vertices = match drawn { - Drawn::Nothing => 0, - _ => 3, - }; - encoder.draw_primitives(PrimitiveType::Triangle, 0, vertices, 1, 0)?; - } - encoder.end_encoding() - }); - match encoded { - Ok(()) => {} - // A device that cannot render the format refuses the pass (`BGR10_XR` on x86 - // lavapipe and on MoltenVK). - Err(Error::Unsupported(why)) => { - println!("MSAA-NAN-CLEAR {label} on {name}: unsupported {why:?}"); - continue; - } - Err(error) => { - println!("MSAA-NAN-CLEAR {label} on {name}: refused {error:?}"); - wrong.push(format!("{label}: refused {error:?}")); - continue; - } - } - // The samples, through the unsigned view of a texture with `PixelFormatView` usage: - // the attachment's own, or a copy's. - let read = match (samples > 1, view) { - (true, Some(_)) if !viewed && copies_convert => None, - (true, Some(view)) => { - let readable = match viewed { - true => texture.clone(), - false => { - let copy = new(samples, true).unwrap(); - let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.copy_texture(&texture, ©).unwrap(); - blit.end_encoding().unwrap(); - copy - } - }; - Some( - samples_of( - device, - &command_buffer, - &readable, - SampleRead::Color(view), - [side, side], - samples as u32, - ) - .unwrap(), - ) - } - _ => None, - }; - run(&command_buffer); - let distinct = |all: &[u8]| { - let mut seen: Vec> = Vec::new(); - for texel in all.chunks_exact(bytes) { - if !seen.iter().any(|s| s == texel) { - seen.push(texel.to_vec()); - } - } - seen - }; - let stored = distinct(&blit_read( - device, - resolved.as_ref().unwrap_or(&texture), - bytes as u64, - )); - let sampled = read.map(|read| distinct(&read.bytes().unwrap())); - let sampled_line = match &sampled { - Some(sampled) => format!(" samples {sampled:02x?}"), - None if samples > 1 && view.is_some() => { - " samples unread (the device's copy converts NaNs)".to_owned() - } - None => String::new(), - }; - let what = if samples > 1 { "resolved" } else { "stored" }; - if !measured { - println!( - "MSAA-NAN-CLEAR {label} on {name}:{sampled_line} {what} {stored:02x?} \ - (printed: no measured Metal texel)" - ); - continue; - } - checked += 1; - let signed = side >= 16 && !viewed && drawn == Drawn::No; - let texel = if signed { large } else { small }; - let samples_exact = sampled.iter().flatten().all(|sample| sample == texel); - let verdict = if samples == 1 { - match stored.iter().all(|got| got == texel) { - true => Ok("Metal's texel".to_owned()), - false => Err(()), - } - } else { - let metal = match signed { - true => texel.to_vec(), - false => nans_resolved(pf, texel), - }; - // A resolve keeping or dropping a NaN, of any bits, beside Metal's other channels. - let resolve_rule = |got: &[u8]| { - nans_resolved(pf, got) == nans_resolved(pf, texel) - && channels(pf, got).iter().zip(channels(pf, texel)).all( - |(&(g, e, m), (t, _, _))| match small_nan(t, e, m) { - true => g == 0 || small_nan(g, e, m), - false => g == t, - }, - ) - }; - match (samples_exact, stored.iter().all(|got| *got == metal)) { - (true, true) => Ok("Metal's texel, Metal's resolve".to_owned()), - (true, false) - if drawn == Drawn::OffTarget - && stored.iter().all(|got| resolve_rule(got)) => - { - Ok(format!( - "Metal's texel; the device's resolve rule, Metal's resolve \ - {metal:02x?}" - )) - } - _ => Err(()), - } - }; - match verdict { - Ok(verdict) => println!( - "MSAA-NAN-CLEAR {label} on {name}:{sampled_line} {what} {stored:02x?}: {verdict}" - ), - Err(()) => { - println!( - "MSAA-NAN-CLEAR {label} on {name}:{sampled_line} {what} {stored:02x?}: \ - WRONG, Metal {texel:02x?}" - ); - wrong.push(format!( - "{label}:{sampled_line} {what} {stored:02x?}, Metal {texel:02x?}" - )); - } - } - } - } - println!("MSAA-NAN-CLEAR {checked} cases checked on {name}"); - drop(off); - drop(lane); - drop(cache); - let _ = messages.take_notices(); - assert!(wrong.is_empty(), "{wrong:#?}"); -} - -/// What a pass of [`multisampled_nan_clears_store_metal_s_texel`] draws. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Drawn { - /// No draw call. - No, - /// A triangle wholly off the target. - OffTarget, - /// A draw call of no vertices. - Nothing, + .zip(&want) + .all(|(&(g, e, m), &(w, _, _))| g == w || (small_nan(g, e, m) && small_nan(w, e, m))) } /// Each color clear Metal was measured with stores Metal's bytes, depth and stencil clears -/// included; a format the device cannot render to is counted, not run. +/// included, but a NaN of a half-float or small-float channel, which the device's clear converts as +/// it likes, announced (`device-nan-encoding`) and printed; a format the device cannot render to is +/// counted, not run. #[test] fn clears_store_the_bytes_metal_stores() { let messages = Messages::default(); let cache = ScratchCache::new().unwrap(); let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); let (mut checked, mut unsupported, mut wrong) = (0usize, Vec::new(), Vec::new()); + let mut announced = false; for &(pf, color, expected) in COLOR_CLEARS { let texture = match attachment(&device, pf, [1, 1], ResourceOptions::private()) { Ok(texture) => texture, @@ -1278,7 +897,15 @@ fn clears_store_the_bytes_metal_stores() { Err(error) => panic!("{pf:?}: {error}"), } let bytes = blit_read(&device, &texture, expected.len() as u64); - if bytes != expected { + announced |= super::degrade_notices::counts(&messages.take_notices()) + .contains_key(&Degradation::DeviceNanEncoding); + if bytes != expected && announced && nan_for_nan(pf, &bytes, expected) { + eprintln!( + "clear {pf:?} {color:?} on {}: {bytes:02x?}, Metal {expected:02x?} \ + (device-nan-encoding)", + device.name() + ); + } else if bytes != expected { wrong.push(format!( "{pf:?} {color:?}: {bytes:02x?}, Metal {expected:02x?}" )); diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 126ae0205..7a9863b0c 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -1718,11 +1718,10 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result return Err(not_implemented(Feature::TexelBuffer)), - // A storage texture's level count, and whether its channels are 16-bit floats, - // which the resource plan records; and a value the bound resources decide, which - // the plan records too (`slots::record_specialized`). + // A storage texture's level count and integer channel widths, which the resource + // plan records; and a value the bound resources decide, which the plan records too + // (`slots::record_specialized`). PushField::TextureLevels(_) - | PushField::TextureHalfChannels(_) | PushField::TextureIntegerChannels(_) | PushField::Specialized(_) => {} // A structure's instance count, which instantiation reads from the state. diff --git a/crates/metal2vulkan/src/bind/heap.rs b/crates/metal2vulkan/src/bind/heap.rs index 2b4e2d138..30c0c989e 100644 --- a/crates/metal2vulkan/src/bind/heap.rs +++ b/crates/metal2vulkan/src/bind/heap.rs @@ -434,18 +434,14 @@ fn member_view( // every access the device lets a heap make. let use_ = heap_storage_use(profile); let c = storage_choice(pixel_format, use_, profile).map_err(bind_error)?; - // The class's one formatless declaration cannot convert per element, but for a - // half-float format's NaN, which a heap write takes from the class its handle carries: - // such a member is viewed through its own format. + // The class's one formatless declaration cannot convert per element: a member is viewed + // through its own format. let per_element = matches!( c.class, - StorageImageClass::Identity - | StorageImageClass::HalfQuietNan - | StorageImageClass::SmallFloatQuietNan - | StorageImageClass::HalfBits + StorageImageClass::Identity | StorageImageClass::HalfBits ); - // A half-float member's writes take the class its handle carries, as before: the alias - // a slot only written takes (`StorageImageClass::HalfBits`) is a slot's alone. + // A half-float member's writes are the device's conversion's, as an `Identity` member's: + // the alias a slot only written takes (`StorageImageClass::HalfBits`) is a slot's alone. let aliased = c.alias.is_some() && c.class != StorageImageClass::HalfBits; // An `A8Unorm` texture held in red (`StorageImageClass::AlphaInRed`): its `R8_UNORM` // image, whose texels a heap access converts where the handle carries `A8Unorm`'s class diff --git a/crates/metal2vulkan/src/bind/instantiate.rs b/crates/metal2vulkan/src/bind/instantiate.rs index e2863e3ee..4c899a4c6 100644 --- a/crates/metal2vulkan/src/bind/instantiate.rs +++ b/crates/metal2vulkan/src/bind/instantiate.rs @@ -818,12 +818,6 @@ pub(crate) fn slot_field( .iter() .find(|(k, _)| *k == key) .map(|(_, value)| FieldBytes::of(&value.to_le_bytes())), - // Whether the texture the plan bound holds 16-bit float channels. - PushField::TextureHalfChannels(slot) => resources - .texture_half_channels - .iter() - .find(|(s, _)| *s == slot) - .map(|(_, half)| FieldBytes::of(&half.to_le_bytes())), // The integer channel widths of the texture the plan bound. PushField::TextureIntegerChannels(slot) => resources .texture_integer_channels diff --git a/crates/metal2vulkan/src/bind/plan.rs b/crates/metal2vulkan/src/bind/plan.rs index b21d7edc6..74304cd4d 100644 --- a/crates/metal2vulkan/src/bind/plan.rs +++ b/crates/metal2vulkan/src/bind/plan.rs @@ -454,11 +454,6 @@ pub(crate) struct ResourceTemplate { /// (`PushField::TextureLevels`): the bound texture's, 0 where a neutral stands in. #[cfg_attr(feature = "serde", serde(default))] pub texture_levels: Vec<(SlotRef, u32)>, - /// Whether the bound texture's channels are 16-bit floats, which the binder pushes for each - /// slot whose `half` writes read it (`PushField::TextureHalfChannels`): 1 or 0, 0 where a - /// neutral stands in. - #[cfg_attr(feature = "serde", serde(default))] - pub texture_half_channels: Vec<(SlotRef, u32)>, /// The integer channel widths of the bound texture, which the binder pushes for each slot /// whose integer writes read them (`PushField::TextureIntegerChannels`): /// `metal::format::integer_channels_word` of its format, 0 where a neutral stands in. diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index e4f89e2c7..4ca8b6b10 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -430,11 +430,10 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result return Err(not_implemented(Feature::TexelBuffer)), - // A storage texture's level count, and whether its channels are 16-bit floats, which - // the resource plan records; and a value the bound resources decide, which the plan - // records too (`slots::record_specialized`). + // A storage texture's level count and integer channel widths, which the resource plan + // records; and a value the bound resources decide, which the plan records too + // (`slots::record_specialized`). PushField::TextureLevels(_) - | PushField::TextureHalfChannels(_) | PushField::TextureIntegerChannels(_) | PushField::Specialized(_) => {} // A structure's instance count, which instantiation reads from the state. diff --git a/crates/metal2vulkan/src/bind/plan/resources.rs b/crates/metal2vulkan/src/bind/plan/resources.rs index f7f7c5786..16223140c 100644 --- a/crates/metal2vulkan/src/bind/plan/resources.rs +++ b/crates/metal2vulkan/src/bind/plan/resources.rs @@ -837,17 +837,6 @@ impl ResourcePlanner<'_> { }; self.template.texture_levels.push((slot, levels)); } - if self.has_fact(RuntimeFact::StorageTextureHalfChannels { slot }) { - let half = match (&write.0, self.texture_shape(slot)) { - (WriteSource::Texture { .. }, Some(TextureShape::Texture { pixel_format, .. })) => { - crate::metal::texel_format::half_channels(*pixel_format) - } - _ => false, - }; - self.template - .texture_half_channels - .push((slot, u32::from(half))); - } if self.has_fact(RuntimeFact::StorageTextureIntegerChannels { slot }) { let word = match (&write.0, self.texture_shape(slot)) { ( diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 626c0412e..d676b4d8d 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -879,7 +879,6 @@ codec_enum! { VertexDepthClamp, BlendColor, ShaderTestsState, - TextureHalfChannels(f0), CaptureAddress, CaptureLayout, CaptureIndexAddress, @@ -1128,12 +1127,11 @@ codec_struct! { StageIo { inputs, outputs, builtins, pulled, stage_in, multisampled, varyings_at_pixel, position_depth, coverage_loop, color_writes, rounded_colors, primitive_inputs, - early_fragment_tests, extended_range_colors, unattached_colors, half_bit_colors, - sample_mask, rotated_colors, rotated_factors, rotated_blends, srgb_fetches, - half_output_lanes, texture_write_rounding, uniform_outputs, uniform_inputs, - instanced_attributes, half_blend_colors, half_fast_colors, - float_blend_colors, zero_indices, color_group, word_colors, alpha_in_red_colors, - alpha_test, depth_compares, + early_fragment_tests, extended_range_colors, unattached_colors, sample_mask, + rotated_colors, rotated_factors, rotated_blends, srgb_fetches, half_output_lanes, + texture_write_rounding, uniform_outputs, uniform_inputs, instanced_attributes, + half_blend_colors, half_fast_colors, float_blend_colors, zero_indices, color_group, + word_colors, alpha_in_red_colors, alpha_test, depth_compares, } DepthCompares { samplers, clamped } ColorGroup { present, width, group } @@ -1143,7 +1141,7 @@ codec_struct! { StageInInput { index, ty, fetch } StageInFetch { format, buffer_index, offset, stride, step_function, step_rate, index } IoVariable { key, role, ty } - IoType { numeric, components, source_bits, bits } + IoType { numeric, components, source_bits } } codec_enum! { @@ -1255,7 +1253,6 @@ codec_enum! { CubicSampler { slot }, CubicArgumentSampler { stage }, ShaderTests { formatless, multisampled, planes }, - StorageTextureHalfChannels { slot }, CapturedPositions { form }, HeapRawSamples { stage, sampler }, ShaderStencilTest { formatless }, @@ -1273,8 +1270,7 @@ codec_enum! { ObjectThreadgroupArena { static_bytes, payload }, ExactFormsOverCompilerLimit { sampling, - texel_conversion, - nan_and_min_max + texel_conversion }, MergedDraws, QuadPrimitiveIds, @@ -1332,8 +1328,7 @@ codec_struct! { StageModule { stage, entry_point, spirv, specialization, required_subgroup_size, stage_flags, reconvergence, precision_notes, strategies, constant_blob, rounded_colors, - specialized_notes, half_bit_colors, own_pixel_textures, snapshot_textures, private_bytes, - stats, + specialized_notes, own_pixel_textures, snapshot_textures, private_bytes, stats, } SpecializedNote { note, when } SpecClause { all } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 57cc18a9c..7ed2a879b 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 1878; +pub const SEMANTICS_VERSION: u32 = 1879; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1878; /// 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 = 461; +pub const ARTIFACT_FORMAT_VERSION: u32 = 462; /// 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 @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 461; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1660; +pub const RUNTIME_VERSION: u32 = 1661; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index 9c2c4cba8..3e36907d5 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -13,14 +13,12 @@ use crate::device::description::{ use crate::device::function_storage; use crate::device::metal::MetalDeviceProperties; use crate::device::policy::{ - ContainmentPolicy, DevicePolicy, NanMinMaxPolicy, SamplingPolicy, Unorm8LinearFilterPolicy, - YCbCrFilterPolicy, + ContainmentPolicy, DevicePolicy, SamplingPolicy, Unorm8LinearFilterPolicy, YCbCrFilterPolicy, }; use crate::device::profile::{ BufferAccess, Containment, CubeGradientRoute, CubeGradients, DescriptorCaps, DeviceProfile, DriverWorkaround, EnabledCaps, FloatFunctions, FormatTable, FragmentCaps, GuestIsolation, - ImageCaps, Independence, LeafCaps, MinMaxRoute, NanEncoding, ProfileFields, Robustness, - TexelNanRoute, + ImageCaps, Independence, LeafCaps, NanEncoding, ProfileFields, Robustness, }; use crate::device::requirements::{ ApiVersion, FloatControl, FloatWidth, FormatUsage, ResolveMode, SubgroupOp, VkExtension, @@ -365,22 +363,12 @@ fn derive_fields( } else { FloatFunctions::Native }, - // The measured deviation; unmeasured, the device's NaN where the policy takes it, and the - // module selects Metal's NaN itself where it asks for Metal's. + // The measured deviation; unmeasured, the device's NaN, noted. nan_encoding: if deviates(DriverDeviation::MetalCanonicalNans) { NanEncoding::MetalCanonical - } else if policy.nan_and_min_max == NanMinMaxPolicy::Exact { - NanEncoding::Device } else { NanEncoding::Native }, - // Metal's NaN of a texel where the policy asks for Metal's, on every device: no device - // fact decides it. - texel_nans: if policy.nan_and_min_max == NanMinMaxPolicy::Exact { - TexelNanRoute::Metal - } else { - TexelNanRoute::Device - }, // Metal's filter of a two-plane YCbCr texture through the slot's variant where the policy // asks for it: on a device that samples through Metal's own sampler, under the YCbCr // filter's switch or Metal's sampling; on one that samples natively, under the switch. A @@ -401,16 +389,6 @@ fn derive_fields( desc.device_type, Some(vk::PhysicalDeviceType::INTEGRATED_GPU | vk::PhysicalDeviceType::CPU) ), - // Metal's picks where the device's minimum and maximum are measured to be Metal's or its - // functions are Metal's own; elsewhere the device's where the policy takes them. - min_max: if deviates(DriverDeviation::MetalMinMax) - || deviates(DriverDeviation::MetalFloatFunctions) - || policy.nan_and_min_max == NanMinMaxPolicy::Exact - { - MinMaxRoute::Metal - } else { - MinMaxRoute::Native - }, // The device's measured value, keyed on its identity as the workarounds are, or the floor. function_storage: function_storage::of(desc), // The measured deviations, one per pipeline kind (the graphics one per macOS release's diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index d75ede863..a79460c21 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -113,8 +113,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { RuntimeFact::BicubicTexels { .. } => Mechanism::Specialization, // The binder writes the bound texture's level count per draw or dispatch. RuntimeFact::StorageTextureLevels { .. } => Mechanism::PushConstant, - // The binder writes whether the bound texture's channels are 16-bit floats. - RuntimeFact::StorageTextureHalfChannels { .. } => Mechanism::PushConstant, // The binder writes the bound texture's integer channel widths. RuntimeFact::StorageTextureIntegerChannels { .. } => Mechanism::PushConstant, // The binder views each level of the bound texture at its element. diff --git a/crates/metal2vulkan/src/device/mod.rs b/crates/metal2vulkan/src/device/mod.rs index f2072e15f..e6bc4e1f7 100644 --- a/crates/metal2vulkan/src/device/mod.rs +++ b/crates/metal2vulkan/src/device/mod.rs @@ -67,9 +67,8 @@ pub(crate) use mechanism::mechanism; pub use metal::{MetalDeviceProperties, SimdSupport, StageSimd}; pub use policy::{ BatchOrderPolicy, CompletionPolicy, ContainmentPolicy, DecodedTexelsPolicy, DevicePolicy, - HeapCompressionPolicy, HostPageTexturePolicy, NanMinMaxPolicy, RenderLoweringPolicy, - SamplingPolicy, TexelConversionPolicy, Unorm8LinearFilterPolicy, VertexNormalizedPolicy, - YCbCrFilterPolicy, + HeapCompressionPolicy, HostPageTexturePolicy, RenderLoweringPolicy, SamplingPolicy, + TexelConversionPolicy, Unorm8LinearFilterPolicy, VertexNormalizedPolicy, YCbCrFilterPolicy, }; pub(crate) use profile::whole_point_size; pub use profile::{DeviceProfile, SpirvValidation}; diff --git a/crates/metal2vulkan/src/device/policy.rs b/crates/metal2vulkan/src/device/policy.rs index c67a97ade..6cba750c4 100644 --- a/crates/metal2vulkan/src/device/policy.rs +++ b/crates/metal2vulkan/src/device/policy.rs @@ -40,10 +40,6 @@ pub struct DevicePolicy { /// Whether a normalized vertex attribute's value is the device's fixed-function conversion of /// its codes (the default) or Metal's, divided exactly in the shader. pub vertex_normalized: VertexNormalizedPolicy, - /// Whether a NaN result's bits, and the operand Metal's minimum and maximum functions - /// (`fmin`, `fmax`, `min3`, `max3`, `clamp`, `saturate`) pick at a NaN or a signed zero, are - /// the device's own (the default) or Metal's. - pub nan_and_min_max: NanMinMaxPolicy, /// Whether a texture whose format the device lacks, held in a carrier (an ASTC LDR texture, /// or an EAC 11-bit one), samples a decoded twin of compact codes (the default) or of Metal's @@ -80,10 +76,10 @@ pub struct DevicePolicy { impl DevicePolicy { /// The untrusted-guest production policy: containment and isolation on, Metal's 8-bit linear /// filter emulated exactly where the emulation runs, native device sampling (a two-plane YCbCr texture's samples among them), - /// the device's own texel conversions, the device's NaN and minimum and maximum, compact - /// codes in a carried texture's decoded twin, the driver's compressed image of a heap's texture - /// Metal keeps compressed, command buffers ready together in one kernel submission, batches of - /// one queue ordered by their ends where the driver runs them one after another, and a sampled + /// the device's own texel conversions, compact codes in a carried texture's decoded twin, the + /// driver's compressed image of a heap's texture Metal keeps compressed, command buffers ready + /// together in one kernel submission, batches of one queue ordered by their ends where the + /// driver runs them one after another, and a sampled /// texture over host pages in place where the device's check passed. pub const UNTRUSTED: DevicePolicy = DevicePolicy { pointer_domain: PointerDomain::ResidentTable, @@ -95,7 +91,6 @@ impl DevicePolicy { ycbcr_filter: YCbCrFilterPolicy::Device, texel_conversion: TexelConversionPolicy::Device, vertex_normalized: VertexNormalizedPolicy::Device, - nan_and_min_max: NanMinMaxPolicy::Native, decoded_texels: DecodedTexelsPolicy::Compact, heap_compression: HeapCompressionPolicy::Compressed, completion: CompletionPolicy::Grouped, @@ -106,8 +101,7 @@ impl DevicePolicy { /// This policy with Metal's answer wherever the choices offer it: its texel conversions /// ([`TexelConversionPolicy::Exact`]), its normalized vertex attributes - /// ([`VertexNormalizedPolicy::Exact`]), its NaN and minimum and maximum - /// ([`NanMinMaxPolicy::Exact`]), its filter of a + /// ([`VertexNormalizedPolicy::Exact`]), its filter of a /// two-plane YCbCr texture /// ([`YCbCrFilterPolicy::Exact`]), its decode of a carried texture's texels /// ([`DecodedTexelsPolicy::Exact`]), a heap's texture whose bytes alias the heap's @@ -124,7 +118,6 @@ impl DevicePolicy { ycbcr_filter: YCbCrFilterPolicy::Exact, texel_conversion: TexelConversionPolicy::Exact, vertex_normalized: VertexNormalizedPolicy::Exact, - nan_and_min_max: NanMinMaxPolicy::Exact, decoded_texels: DecodedTexelsPolicy::Exact, heap_compression: HeapCompressionPolicy::Uncompressed, completion: CompletionPolicy::Exact, @@ -297,39 +290,6 @@ pub enum VertexNormalizedPolicy { Exact, } -/// Whose NaN a `float` or `half` result answers, and which operand Metal's minimum and maximum -/// functions (`fmin`, `fmax`, `min3`, `max3`, `clamp`, and `saturate`, Metal's -/// `clamp(x, +0, 1)`) pick at a NaN, a signed zero or an `f32` denormal, on a device not measured -/// to answer Metal's (the owner's "the bit pattern of NaN values, and min and max when NaN or -/// signed zero is involved" of 2026-10-11). A device measured to answer Metal's canonical NaN -/// (`DriverDeviation::MetalCanonicalNans`) keeps it, and one measured to compute Metal's minimum -/// and maximum (`DriverDeviation::MetalMinMax`) or whose functions are Metal's own -/// (`DriverDeviation::MetalFloatFunctions`, MoltenVK on an Apple GPU) keeps Metal's picks, under -/// either setting. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum NanMinMaxPolicy { - /// The device's own (the default): every NaN Metal answers is the device's (its sign and - /// payload; no select of Metal's bits), and those functions are the device's `NMin`, `NMax` - /// and `NClamp`. On a device that rounds a `half` through its conversion under the float - /// controls (ANV, RADV), a `half` read from its bits is the device's widening of them, and a - /// `half` texel takes that conversion's NaN. Such a module records - /// [`PrecisionNote::NativeNanEncoding`](crate::pipeline::PrecisionNote::NativeNanEncoding) - /// or [`NativeMinMax`](crate::pipeline::PrecisionNote::NativeMinMax), whose docs state the - /// bound. - #[default] - Native, - /// Metal's: the translation selects Metal's NaN where the device may answer another, and - /// Metal's operand where the device's instructions may pick another; a `half` widened to - /// `float` answers `0x7fc00000` for every NaN, as Metal does. A `half` texel read, sampled or - /// gathered keeps the NaN the device decoded through native half rounding too and through the - /// conversion under the float controls, and a - /// `half` read from its bits is decoded in integer arithmetic where the default takes the - /// device's widening (a `half` stored back unchanged keeps its bits under either). - Exact, -} - /// What texels the runtime holds in the decoded twin of a texture whose blocks it holds in a /// carrier on a device without the format (the runtime's `texture/decoded_twin.rs`), which the /// texture's samples, reads and gathers read: an ASTC LDR texture's (`bind::AstcDecode`), and an diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index 74e1757f3..f739e912b 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -536,14 +536,10 @@ pub struct ProfileFields { /// Metal's own, in the math mode Metal's compile of the module takes, or the device's. The /// module takes the device's instructions on either; the notes it records differ. pub float_functions: FloatFunctions, - /// Which NaN the device's `float` and `half` arithmetic answers: Metal's canonical NaN, so the - /// translation leaves it to the device, or the device's own, so the translation selects Metal's - /// where a result's bits are observed. + /// Which NaN the device's `float` and `half` arithmetic answers: Metal's canonical NaN, measured, + /// or the device's own, which the module records where Metal answers a NaN. Either way the + /// translation leaves every NaN's bits to the device. pub nan_encoding: NanEncoding, - /// Whose NaN a `half` read, sample or gather hands back for a NaN texel: Metal's, by the - /// class of the texture bound, where the policy's `NanMinMaxPolicy::Exact` asks for it, on - /// every device, or the device's decode (the default). - pub texel_nans: TexelNanRoute, /// Whether a linear sample the device's sampler answers (`DeviceProfile::device_samples`) /// takes Metal's filter of a two-plane YCbCr texture bound at its slot, through the slot's /// YCbCr variant (`RuntimeFact::YCbCrTexture`): under the policy's `YCbCrFilterPolicy::Exact`, @@ -560,11 +556,6 @@ pub struct ProfileFields { /// which its refresh reads across the bus once per encoder where the in-place form would read /// the planes there at every pass. Both forms read Metal's texels exactly. pub ycbcr_in_place: bool, - /// Whose operand Metal's minimum and maximum functions pick (`lower::arith::native_min_max`): - /// Metal's, or the device's `NMin`, `NMax` and `NClamp` as they are (the policy's - /// `NanMinMaxPolicy::Native`). Derived, so a device that keeps Metal's picks keys the same - /// under both policies. - pub min_max: MinMaxRoute, /// The Function storage a thread holds correctly (`device::function_storage`): a stage's /// private memory, its call stacks included, may take this much a thread /// (`VkLimit::FunctionStorageBytesPerThread`), and a vertex or fragment function on a device @@ -685,54 +676,20 @@ pub enum FloatFunctions { Native, } -/// Whose operand Metal's `fmin`, `fmax`, `min3`, `max3`, `clamp` and `saturate` on `float` and -/// `half` pick ([`ProfileFields::min_max`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum MinMaxRoute { - /// Metal's: the device's `NMin`, `NMax` and `NClamp` where they are measured to be Metal's - /// (`DriverDeviation::MetalMinMax`), else the translation's selects of Metal's operand, as on a - /// device whose functions are Metal's own (`DriverDeviation::MetalFloatFunctions`) or under - /// `NanMinMaxPolicy::Exact`. - Metal, - /// The device's `NMin`, `NMax` and `NClamp` as they are (`NanMinMaxPolicy::Native`, the - /// default), noted `PrecisionNote::NativeMinMax` with its bound. - Native, -} - /// Which NaN a device's `float` and `half` arithmetic answers ([`ProfileFields::nan_encoding`]), -/// decided by the driver's measured deviation [`DriverDeviation::MetalCanonicalNans`]. +/// decided by the driver's measured deviation [`DriverDeviation::MetalCanonicalNans`]. The +/// translation selects no NaN under either: every NaN's bits are the device's. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum NanEncoding { /// Metal's canonical NaN, `0x7FC00000` (`0x7E00` as `half`), for every NaN result of the - /// arithmetic and of the functions whose NaN Metal canonicalizes. + /// arithmetic and of the functions whose NaN Metal canonicalizes, measured: such a result + /// records nothing. MetalCanonical, - /// The device's own: an operand's bits, quieted or not, or another NaN, which the - /// translation answers Metal's in place of (the policy's `NanMinMaxPolicy::Exact`). - Device, - /// The device's own, taken as it is (`NanMinMaxPolicy::Native`, the default), noted - /// `PrecisionNote::NativeNanEncoding` with its bound. + /// The device's own, unmeasured, noted `PrecisionNote::NativeNanEncoding` with its bound. Native, } -/// Whose NaN a `half` texel access hands back for a NaN texel ([`ProfileFields::texel_nans`]). -/// A texel's NaN is the image's decode, which the access narrows itself, not a result of the -/// device's arithmetic, so [`ProfileFields::nan_encoding`] does not decide it: a device measured -/// to answer Metal's canonical NaN in its arithmetic (`NanEncoding::MetalCanonical`) need not -/// answer it for a texel, and MoltenVK on the Apple M3 Max does not (a 32-bit float texel's NaN -/// read as `half` keeps its payload's top bits). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum TexelNanRoute { - /// Metal's rule (`NanMinMaxPolicy::Exact`): a 16-bit float texel's own NaN where the access - /// reads one texel, and `0x7e00` for every other NaN, by the class of the texture bound - /// (`lower::texture::texel_nans_class`). - Metal, - /// The device's decode (`NanMinMaxPolicy::Native`, the default), noted - /// `PrecisionNote::DeviceNanEncoding`. - Device, -} - /// What the consumer enabled, as the capability vocabulary `Requirements` uses /// ([`DeviceProfile::enabled`]). Selection reads the typed caps above; the finalize check /// (`requirements ⊆ profile`) reads these. diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 9f25d23f0..935b944ba 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -189,7 +189,6 @@ fn every_fact() -> Vec { multisampled: true, planes: true, }, - RuntimeFact::StorageTextureHalfChannels { slot }, RuntimeFact::StorageTextureIntegerChannels { slot }, RuntimeFact::CapturedPositions { form: crate::pipeline::CaptureForm::Indexed(crate::metal::IndexType::UInt16), @@ -268,7 +267,6 @@ fn every_fact() -> Vec { RuntimeFact::ExactFormsOverCompilerLimit { sampling: true, texel_conversion: false, - nan_and_min_max: true, }, ] } @@ -348,7 +346,6 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::CubicSampler { .. } => 68, RuntimeFact::CubicArgumentSampler { .. } => 69, RuntimeFact::ShaderTests { .. } => 70, - RuntimeFact::StorageTextureHalfChannels { .. } => 71, RuntimeFact::CapturedPositions { .. } => 72, RuntimeFact::HeapRawSamples { .. } => 73, RuntimeFact::ShaderStencilTest { .. } => 74, @@ -371,7 +368,7 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::RotatedWeights => 91, RuntimeFact::PrivateList => 92, RuntimeFact::MeshLastFirst => 93, - RuntimeFact::YCbCrInPlace { .. } => 94, + RuntimeFact::YCbCrInPlace { .. } => 71, } } @@ -379,7 +376,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..95).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..94).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -510,7 +507,6 @@ fn mechanism_is_total_over_every_fact_and_profile() { RuntimeFact::StageInRegion | RuntimeFact::StageInStride { .. } | RuntimeFact::StorageTextureLevels { .. } - | RuntimeFact::StorageTextureHalfChannels { .. } | RuntimeFact::StorageTextureIntegerChannels { .. } | RuntimeFact::AccelerationStructureInstanceCount { .. } | RuntimeFact::ViewportCount diff --git a/crates/metal2vulkan/src/device/tests/profile.rs b/crates/metal2vulkan/src/device/tests/profile.rs index df2a752aa..075d3690d 100644 --- a/crates/metal2vulkan/src/device/tests/profile.rs +++ b/crates/metal2vulkan/src/device/tests/profile.rs @@ -307,12 +307,11 @@ fn below_1_2_and_contradictory_policies_are_refused() { } /// Each of the policy's choices between the device's answer and Metal's, with a function that -/// flips it alone: the texel conversions, a normalized vertex attribute's conversion, the NaN and -/// minimum and maximum, and the filter of a two-plane YCbCr texture. -fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 4] { +/// flips it alone: the texel conversions, a normalized vertex attribute's conversion, and the filter +/// of a two-plane YCbCr texture. +fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 3] { use crate::device::{ - NanMinMaxPolicy as N, TexelConversionPolicy as T, VertexNormalizedPolicy as V, - YCbCrFilterPolicy as Y, + TexelConversionPolicy as T, VertexNormalizedPolicy as V, YCbCrFilterPolicy as Y, }; [ ("texel_conversion", |p| DevicePolicy { @@ -329,13 +328,6 @@ fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 4] { }, ..p }), - ("nan_and_min_max", |p| DevicePolicy { - nan_and_min_max: match p.nan_and_min_max { - N::Native => N::Exact, - N::Exact => N::Native, - }, - ..p - }), ("ycbcr_filter", |p| DevicePolicy { ycbcr_filter: match p.ycbcr_filter { Y::Device => Y::Exact, @@ -346,11 +338,8 @@ fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 4] { ] } -/// On MoltenVK on the M3, whose functions, NaN, minimum and maximum are measured to be Metal's, -/// each choice still moves the key: the texel conversions' is the policy's own field there, the -/// NaN and minimum and maximum's moves the texel -/// NaN route (`TexelNanRoute`): a texel's NaN is the image's decode, which no arithmetic fact -/// covers, and the YCbCr filter's moves whether a two-plane YCbCr slot takes its variant +/// On MoltenVK on the M3, each choice still moves the key: the texel conversions' is the policy's +/// own field there, and the YCbCr filter's moves whether a two-plane YCbCr slot takes its variant /// (`ProfileFields::ycbcr_variant`), Metal's sampler filtering such a texture's converted texels /// otherwise. #[test] diff --git a/crates/metal2vulkan/src/lower/arith/chunk.rs b/crates/metal2vulkan/src/lower/arith/chunk.rs index 1dd2cb97b..064312db0 100644 --- a/crates/metal2vulkan/src/lower/arith/chunk.rs +++ b/crates/metal2vulkan/src/lower/arith/chunk.rs @@ -42,7 +42,7 @@ use crate::error::Error; use crate::lower::arith::legal::{self, chunk_lanes, not_lowered, Form, Held}; use crate::lower::arith::libm::Lib; use crate::lower::arith::math::{self, FloatFn}; -use crate::lower::arith::nan::{self, NanAnswer, NanTest}; +use crate::lower::arith::nan::NanTest; use crate::lower::arith::{denormal, fma}; use crate::lower::arith::{narrow, operands_of, ops, wide, ArithStrategy}; use crate::lower::emit::EmitCx; @@ -290,7 +290,7 @@ pub fn select( InstKind::Call(call) if is_math(call, MathFn::SinCos) => { super::select_sincos(cx, at, inst, call, m) } - InstKind::Call(call) if is_math(call, MathFn::Dot) => select_dot(cx, at, inst, call), + InstKind::Call(call) if is_math(call, MathFn::Dot) => select_dot(cx, inst, call), InstKind::Cast { op: CastOp::Bitcast, v, @@ -368,13 +368,8 @@ fn is_math(call: &Call, f: MathFn) -> bool { /// denormals the device's (`super::leave_denormals`). Elsewhere the sum of each chunk's dot /// product, rounded once to a narrow format: /// `dot`'s device precision (`DeviceArithmetic`) covers the order of the sum, which Vulkan leaves -/// to the device for `OpDot` too. Its NaN is Metal's. -fn select_dot( - cx: &mut SelectCx<'_>, - at: InstId, - inst: &Inst, - call: &Call, -) -> Result { +/// to the device for `OpDot` too. Its NaN is the device's. +fn select_dot(cx: &mut SelectCx<'_>, inst: &Inst, call: &Call) -> Result { let (Some(&a), Some(&b)) = (call.args.first(), call.args.get(1)) else { return Err(cx.invariant("air.dot without its operands")); }; @@ -404,7 +399,7 @@ fn select_dot( elem, fma, }; - return Ok(super::with_nan(cx, at, s, answer, elem)); + return Ok(super::with_nan(cx, s, answer)); } } super::note(cx, FloatFn::Dot.precision()); @@ -415,7 +410,7 @@ fn select_dot( elem, contract: super::contraction(call.fmf), }; - Ok(super::with_nan(cx, at, s, answer, elem)) + Ok(super::with_nan(cx, s, answer)) } /// The dot product of chunked vectors `a` and `b` of `lanes` lanes of `elem`: each chunk's `OpDot` @@ -490,30 +485,22 @@ pub fn dot_chain_words(lanes: u16, elem: Form, fma_words: u32) -> u32 { /// The sine and cosine of `x` of shape `s`: per chunk for a chunked vector, Metal's fast ones for /// `air.fast_sincos` on `float` (`fast`, [`sin_cos_fns`]), each the device's instruction as `lib` -/// reads it, with the entry's NaN `test` ([`math::float_fn`]), then Metal's -/// NaN `answers` of each selected ([`nan::select`]). +/// reads it, with the entry's NaN `test` ([`math::float_fn`]). pub fn sin_cos( fb: &mut FunctionBuilder<'_>, s: Shape, x: SValue, fast: bool, - answers: [Option; 2], test: NanTest, lib: &Lib, ) -> BResult<(SValue, SValue)> { let (sin, cos) = sin_cos_fns(fast); let one = |fb: &mut FunctionBuilder<'_>, f: Form, x: SValue| -> BResult<(SValue, SValue)> { let c = Contraction::Forbidden; - let mut r = [ + Ok(( math::float_fn(fb, sin, f, c, test, &[x], lib)?, math::float_fn(fb, cos, f, c, test, &[x], lib)?, - ]; - for (v, answer) in r.iter_mut().zip(answers) { - if let Some(answer) = answer { - *v = nan::select(fb, f, answer, test, *v, Some(x))?; - } - } - Ok((r[0], r[1])) + )) }; if !s.chunked { return one(fb, s.form(), x); @@ -549,19 +536,9 @@ pub fn sin_cos_fns(fast: bool) -> (FloatFn, FloatFn) { } /// The words of [`sin_cos`] on shape `s`. -pub fn sin_cos_words(s: Shape, fast: bool, answers: [Option; 2]) -> u32 { +pub fn sin_cos_words(s: Shape, fast: bool) -> u32 { let (sin, cos) = sin_cos_fns(fast); - let per = |f: Form| { - let selects = answers - .iter() - .flatten() - .map(|a| a.words(f)) - .fold(0u32, u32::saturating_add); - sin.words(f) - .saturating_add(cos.words(f)) - .saturating_add(8) - .saturating_add(selects) - }; + let per = |f: Form| sin.words(f).saturating_add(cos.words(f)).saturating_add(8); if !s.chunked { return per(s.form()); } diff --git a/crates/metal2vulkan/src/lower/arith/color_write.rs b/crates/metal2vulkan/src/lower/arith/color_write.rs index a673fd996..8280b5227 100644 --- a/crates/metal2vulkan/src/lower/arith/color_write.rs +++ b/crates/metal2vulkan/src/lower/arith/color_write.rs @@ -30,8 +30,8 @@ use crate::lower::arith::ops::{fsplat, splat, ty}; use crate::pipeline::lower_inputs::ChannelWrite; use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::{BResult, BuildError, OperandRule}; -use crate::spirv::ids::{TypeId, Value}; -use crate::spirv::ir::{BinOp, ConvOp, GlslOp, Type, UnOp}; +use crate::spirv::ids::Value; +use crate::spirv::ir::{BinOp, ConvOp, GlslOp, UnOp}; /// An upper estimate of the SPIR-V words of one channel's rounding by `rule`. pub fn channel_words(rule: ChannelWrite) -> u64 { @@ -59,77 +59,6 @@ pub fn words(rules: &[Option; 4]) -> u64 { + written.saturating_add(1).saturating_mul(6) } -/// An upper estimate of the SPIR-V words of [`half_bits`]: about 20 instructions on the whole -/// vector, its constants, 16-bit types and their capabilities included (192 words measured on four -/// lanes, two widening conversions with them). -pub const HALF_BITS_WORDS: u64 = 34 * 6; - -/// The `half` lanes whose bits hold `x` (float lanes of form `f`, a 32-bit container), each lane -/// a value a half holds exactly (a half widened, or a value [`round`] rounded to one), on a -/// profile whose conversion to 16 bits, of an operand its compiler cannot fold into the -/// instruction computing it, is Metal's `half(float)` (`DriverDeviation::MetalHalfConversion`, -/// `narrow::QuantizeForm::Converted`): that conversion of `x + -0.0` (an `OpFAdd` decorated -/// `NoContraction`, as `narrow` converts), exact for every value but a NaN, whose half the -/// conversion makes `0x7e00`; a NaN lane is [`nan_codes`]'s code instead, chosen as 16-bit -/// integers, and the lanes bitcast to `half` once (`Int16` and `Float16`), so no conversion on -/// the device chooses a NaN's encoding. -pub fn half_bits(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { - let lanes = |fb: &mut FunctionBuilder<'_>, elem: Type| -> BResult { - let elem = fb.module().ty(elem)?; - match f.lanes { - 1 => Ok(elem), - len => fb.module().ty(Type::Vector { elem, len }), - } - }; - let u16_ = lanes( - fb, - Type::Int { - width: 16, - signed: false, - }, - )?; - let h = lanes(fb, Type::Float { width: 16 })?; - let minus_zero = fsplat(fb, f.with(Held::Float(FloatFmt::F32)), -0.0)?; - let held = fb.binary_no_contraction(BinOp::FAdd, x, minus_zero)?; - let converted = fb.convert(ConvOp::FConvert, held, h)?; - let converted = fb.convert(ConvOp::Bitcast, converted, u16_)?; - let nan = nan_codes(fb, f, x)?; - let nan = fb.convert(ConvOp::UConvert, nan, u16_)?; - let is_nan = fb.unary(UnOp::IsNan, x)?; - let code = fb.select(is_nan, nan, converted)?; - fb.convert(ConvOp::Bitcast, code, h) -} - -/// The 16-bit `half` NaN codes (in `u32` lanes) of `x` (float lanes of form `f`, a 32-bit -/// container) where a lane is a NaN, by integer operations on the bits: the sign, every exponent -/// bit, and the top ten fraction bits, a widened half NaN's own payload, `0x200` where those are -/// zero (a NaN no half widens to). A lane that is not a NaN gives a code [`half_bits`] does not -/// choose. -pub fn nan_codes(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { - let u = f.with(Held::Int { - bits: 32, - container: 32, - }); - let k = |fb: &mut FunctionBuilder<'_>, bits: u32| splat(fb, u, u64::from(bits)); - let ut = ty(fb, u)?; - let bits = fb.convert(ConvOp::Bitcast, x, ut)?; - let k16 = k(fb, 16)?; - let sign = fb.binary(BinOp::ShiftRightLogical, bits, k16)?; - let sign_bit = k(fb, 0x8000)?; - let sign = fb.binary(BinOp::BitwiseAnd, sign, sign_bit)?; - let k13 = k(fb, 13)?; - let top = fb.binary(BinOp::ShiftRightLogical, bits, k13)?; - let payload_mask = k(fb, 0x3ff)?; - let top = fb.binary(BinOp::BitwiseAnd, top, payload_mask)?; - let zero = k(fb, 0)?; - let low = fb.binary(BinOp::IEqual, top, zero)?; - let quiet = k(fb, 0x200)?; - let payload = fb.select(low, quiet, top)?; - let infinity = k(fb, 0x7c00)?; - let special = fb.binary(BinOp::BitwiseOr, infinity, payload)?; - fb.binary(BinOp::BitwiseOr, sign, special) -} - fn malformed() -> BuildError { BuildError::Operand { op: crate::spv::Op::ExtInst, diff --git a/crates/metal2vulkan/src/lower/arith/contract.rs b/crates/metal2vulkan/src/lower/arith/contract.rs index 2da8536c3..74e71f1db 100644 --- a/crates/metal2vulkan/src/lower/arith/contract.rs +++ b/crates/metal2vulkan/src/lower/arith/contract.rs @@ -450,7 +450,7 @@ pub(super) fn select( negate: fusion.negate, inner: inner.into_boxed_slice(), }; - Ok(Some(super::with_nan(cx, at, s, nan, f))) + Ok(Some(super::with_nan(cx, s, nan))) } /// Whether `v` is a sum: the result of a float addition or subtraction (fused or not) or of a diff --git a/crates/metal2vulkan/src/lower/arith/libm/mod.rs b/crates/metal2vulkan/src/lower/arith/libm/mod.rs index 48fb1d756..6e281435b 100644 --- a/crates/metal2vulkan/src/lower/arith/libm/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/libm/mod.rs @@ -336,42 +336,19 @@ pub fn use_words(lanes: u8, arity: usize) -> u32 { } /// What an entry's calls take, as emission reads them: the mode Metal compiles the entry's -/// functions in where the device's are Metal's, the routine of precise `fmod` where the module -/// defines one, and whether Metal's minimum and maximum functions are the device's. +/// functions in where the device's are Metal's, and the routine of precise `fmod` where the module +/// defines one. #[derive(Clone, Copy, Debug)] pub struct Lib { metal: Option, fmod: Option, - /// Whether the device's `NMin`, `NMax` and `NClamp` are Metal's `fmin`, `fmax` and `clamp` - /// ([`Lib::with_min_max`]). - min_max: bool, } impl Lib { /// The library of an entry whose `float` functions are Metal's in mode `metal` (`None`: the /// device's), whose module defines precise `fmod`'s routine as `fmod` where it takes one. pub fn new(metal: Option, fmod: Option) -> Lib { - Lib { - metal, - fmod, - min_max: false, - } - } - - /// This library, where the device's `GLSL.std.450` `NMin`, `NMax` and `NClamp` are Metal's - /// own `fmin`, `fmax` and `clamp` if `device` (`ArithPlan::device_min_max`): Metal's minimum - /// and maximum family on `float` and `half` then takes those instructions - /// (`math::metal_min_max` otherwise). - pub fn with_min_max(self, device: bool) -> Lib { - Lib { - min_max: device, - ..self - } - } - - /// Whether the device's `NMin`, `NMax` and `NClamp` are Metal's ([`Lib::with_min_max`]). - pub fn device_min_max(&self) -> bool { - self.min_max + Lib { metal, fmod } } /// A library that leaves every function to its instruction (a unit test's view of the diff --git a/crates/metal2vulkan/src/lower/arith/math.rs b/crates/metal2vulkan/src/lower/arith/math.rs index acfeeb815..86d7190bc 100644 --- a/crates/metal2vulkan/src/lower/arith/math.rs +++ b/crates/metal2vulkan/src/lower/arith/math.rs @@ -710,20 +710,18 @@ pub enum FloatFn { FlaggedFract, /// Metal's `sign` (`metal_sign`), with and without fast math. Sign, - /// Metal's `saturate` (`metal_saturate`). + /// Metal's `saturate`, `clamp(x, +0, 1)`: the device's `NClamp(x, 0, 1)`. Saturate, /// `fmin` (`air.fmin`, `air.fast_fmin`, `air.min`; `llvm.minnum` where [`FloatFn::MinNum`] - /// refines to it): Metal's on `float` and `half` (`metal_min_max`), the device's `NMin` on the - /// other formats. + /// refines to it): the device's `NMin`. Min, - /// `fmax`, as [`FloatFn::Min`] with the order reversed. + /// `fmax`, as [`FloatFn::Min`] with the order reversed: the device's `NMax`. Max, - /// `clamp(x, lo, hi)`: `fmin(fmax(x, lo), hi)` with Metal's `fmin` and `fmax` on `float` and - /// `half`, the device's `NClamp` on the other formats. + /// `clamp(x, lo, hi)`: the device's `NClamp`. Clamp, - /// `min3(a, b, c)`: `fmin(fmin(a, b), c)`, Metal's on `float` and `half`. + /// `min3(a, b, c)`: the device's `NMin(NMin(a, b), c)`. Min3, - /// `max3(a, b, c)`: `fmax(fmax(a, b), c)`, Metal's on `float` and `half`. + /// `max3(a, b, c)`: the device's `NMax(NMax(a, b), c)`. Max3, /// `llvm.minnum`: LLVM's function, the device's `NMin`, on the formats other than `float`. /// Metal's compiler emits it for `a < b ? a : b` under fast math, with every flag; on `float` @@ -1005,10 +1003,13 @@ impl FloatFn { } /// Whether the lowering answers Metal at `f32` denormal operands and results itself, whatever - /// the device's denormal mode, so it records no `PrecisionNote::DeviceDenormals`: the functions - /// that read the operand's exponent field (`sign`, `saturate`, `fract`, `median3`, `fmin`, - /// `fmax`, `min3`, `max3`, and `clamp`, which compare a denormal as zero and return the - /// operand, and `atan2`, which also flushes a denormal generic result), `copysign` and `fabs` + /// the device's denormal mode, or records the device's answer under another note, so it records + /// no `PrecisionNote::DeviceDenormals`: the functions that read the operand's exponent field + /// (`sign`, `fract` and `median3`, which compare a denormal as zero and return the operand, and + /// `atan2`, which also flushes a denormal generic result), `fmin`, `fmax`, `min3`, `max3`, + /// `clamp` and `saturate`, the device's `NMin`, `NMax` and `NClamp`, whose comparison of a + /// denormal is Metal's where measured (`DriverDeviation::MetalMinMax`) and else + /// `PrecisionNote::NativeMinMax`'s bound, `copysign` and `fabs` /// (on `float`, [`sign_on_bits`]), which move bits, `ldexp` (on `float`, [`ldexp_bits`]), which /// reads a denormal operand as the zero of its sign and flushes a denormal result on the bits, /// and `fast::sqrt`, which selects the zero of a denormal operand's sign and has no denormal @@ -1102,12 +1103,13 @@ impl FloatFn { } /// Whether the lowering on lanes of format `fmt` answers Metal's NaN bit pattern itself, so it - /// records no `PrecisionNote::DeviceNanEncoding` and needs no select: the functions that select - /// their NaN (or answer a number for one: `sign`, `saturate`, `fast::sin`, `fast::cos`), - /// `median3`, and on `float` and `half` - /// `fmin`, `fmax`, `min3`, `max3`, and `clamp` (`metal_min_max`), which return an operand, - /// `copysign`, which moves bits, and `fabs` on `float`, which clears the sign bit on the bits - /// ([`sign_on_bits`]; a `half` `fabs` answers its canonical NaN by a select). + /// records no NaN note of its own: the functions that select their NaN (or answer a number for + /// one: `sign`, `saturate`, `fast::sin`, `fast::cos`), `median3`, and on `float` and `half` + /// `fmin`, `fmax`, `min3`, `max3`, and + /// `clamp`, which return an operand (two NaNs' answer is `PrecisionNote::NativeMinMax`'s where + /// the device is not measured to pick Metal's), `copysign`, which moves bits, and `fabs` on + /// `float`, which clears the sign bit on the bits ([`sign_on_bits`]; a `half` `fabs` answers + /// the device's NaN, noted `NativeNanEncoding`). pub fn metal_nans(self, fmt: FloatFmt) -> bool { use FloatFn as F; if self == F::Abs { @@ -1303,10 +1305,9 @@ impl FloatFn { /// Emit float function `op` on `args` (floats of form `f`; `Ldexp`'s exponent is a held `i32` and /// `Dot` gives the scalar), by the device's instructions, and precise `fmod` by `lib`'s routine -/// where the module defines it. Metal's operand-picking functions (`metal_min_max`, -/// `metal_median3`) test their operands for NaNs by `test`, the test the entry's float modes leave -/// exact ([`NanTest::for_modes`]). A `half` `fmod` answers Metal's zero remainder -/// (`half_fmod_zero`). +/// where the module defines it. Metal's `median3` (`metal_median3`) tests its operands for NaNs by +/// `test`, the test the entry's float modes leave exact ([`NanTest::for_modes`]). A `half` `fmod` +/// answers Metal's zero remainder (`half_fmod_zero`). pub fn float_fn( fb: &mut FunctionBuilder<'_>, op: FloatFn, @@ -1584,21 +1585,13 @@ fn float_fn_core( nonfinite_below_one(fb, f, a, r) } F::Sign => metal_sign(fb, f, a), - // Metal's `clamp(x, +0, 1)` at every operand: the device's `NClamp` where the minimum and - // maximum functions take it (measured to be Metal's, or the device's own, - // `PrecisionNote::NativeMinMax`). - F::Saturate if metal_picks(f.float_fmt()) && lib.device_min_max() => { + // Metal's `clamp(x, +0, 1)`: the device's `NClamp`, Metal's where measured + // (`DriverDeviation::MetalMinMax`), else noted `PrecisionNote::NativeMinMax`, as the + // minimum and maximum functions below. + F::Saturate => { let (z, one) = (fsplat(fb, f, 0.0)?, fsplat(fb, f, 1.0)?); glsl(fb, GlslOp::NClamp, &[a, z, one]) } - F::Saturate => metal_saturate(fb, f, a), - // The device's `NMin`, `NMax` and `NClamp` where they are measured to be Metal's, the arms - // below. - F::Min | F::Max | F::Clamp | F::Min3 | F::Max3 - if metal_picks(f.float_fmt()) && !lib.device_min_max() => - { - metal_min_max(fb, op, f, test, args) - } F::Min | F::MinNum => glsl(fb, GlslOp::NMin, &[a, arg(args, 1)?]), F::Max | F::MaxNum => glsl(fb, GlslOp::NMax, &[a, arg(args, 1)?]), F::Clamp => glsl(fb, GlslOp::NClamp, &[a, arg(args, 1)?, arg(args, 2)?]), @@ -2234,18 +2227,6 @@ fn metal_fract( fb.select(nan, n, r) } -/// Metal's `saturate(x)` (A1 case aed3faaa, precise and fast alike): `x` clamped to `[0, 1]`, -/// with `+0` for either zero, a NaN, and an `f32` denormal ([`flushed`]); a `half` denormal is -/// kept. `NClamp` leaves the sign of a zero result to the device. -fn metal_saturate(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { - let (z, one) = (fsplat(fb, f, 0.0)?, fsplat(fb, f, 1.0)?); - let lt = bin(fb, BinOp::FOrdLessThan, x, one)?; - let r = fb.select(lt, x, one)?; - let gt = bin(fb, BinOp::FOrdGreaterThan, x, z)?; - let r = fb.select(gt, r, z)?; - zero_where_flushed(fb, f, x, r) -} - /// An operand of [`metal_median3`] with the value it compares as. #[derive(Clone, Copy)] struct Compared { @@ -2305,79 +2286,15 @@ fn metal_median3( fb.select(both, b, r) } -/// Whether Metal's `fmin` and `fmax` family is measured on lanes of format `fmt`, so -/// `metal_min_max` emits it: `float` (`nan_minmax` without fast math, `nan_minmax_fast` with -/// every flag, and both at zeros and denormals) and `half` (`nan_half`, `nan_half_fast`). `bfloat` -/// and `double` keep the device's `NMin`, `NMax`, and `NClamp`. +/// Whether Metal's `fmin` and `fmax` family is measured on lanes of format `fmt`: `float` +/// (`nan_minmax` without fast math, `nan_minmax_fast` with every flag, and both at zeros and +/// denormals) and `half` (`nan_half`, `nan_half_fast`), where the device's `NMin`, `NMax` and +/// `NClamp`, which every format takes, record `PrecisionNote::NativeMinMax` unless measured to be +/// Metal's. On `bfloat` and `double` Metal's is not measured. pub fn metal_picks(fmt: Option) -> bool { matches!(fmt, Some(FloatFmt::F32 | FloatFmt::Half)) } -/// Metal's `fmin(p, q)` (`order` less) or `fmax(p, q)` (greater): `q` where `p` is NaN, else -/// [`pick`]'s `p` where `q` is NaN or `p` compares before `q`, else `q`. So two NaNs answer `q`'s -/// bits and a tie (`±0`, or an `f32` denormal beside a zero, which compares as one) answers `q`. -fn metal_fmin( - fb: &mut FunctionBuilder<'_>, - f: Form, - test: NanTest, - order: BinOp, - p: Compared, - q: Compared, -) -> BResult { - let p_nan = nan::is_nan(fb, f, test, p.value)?; - let r = pick(fb, f, test, order, p, q)?; - Ok(Compared { - value: fb.select(p_nan, q.value, r.value)?, - as_: fb.select(p_nan, q.as_, r.as_)?, - }) -} - -/// Metal's `fmin`, `fmax`, `min3`, `max3`, and `clamp` (`op`) of `args` on `float` or `half` -/// lanes of form `f` ([`metal_picks`]), the NaN tests by `test`. Measured on every lane of -/// `nan_minmax` and `nan_minmax_fast` (`float`, without fast math and with every flag, the same -/// answers), their zeros-and-denormals cases, and `nan_half` and `nan_half_fast`: the result is an -/// operand, bit for bit ([`metal_fmin`]: a NaN loses, two NaNs and a tie answer the second); -/// `min3(a, b, c)` is `fmin(fmin(a, b), c)`, `max3` likewise, and `clamp(x, lo, hi)` is -/// `fmin(fmax(x, lo), hi)`. `float` compares the operands [`flushed`] (an `f32` denormal compares -/// as a zero) but returns the operand itself. `NMin` and `NMax` leave two NaNs, a tie of zeros, -/// and a denormal's comparison to the device. -pub(super) fn metal_min_max( - fb: &mut FunctionBuilder<'_>, - op: FloatFn, - f: Form, - test: NanTest, - args: &[Value], -) -> BResult { - use FloatFn as F; - let compared = |fb: &mut FunctionBuilder<'_>, i: usize| -> BResult { - let x = arg(args, i)?; - Ok(Compared { - value: x, - as_: zero_where_flushed(fb, f, x, x)?, - }) - }; - let (less, greater) = (BinOp::FOrdLessThan, BinOp::FOrdGreaterThan); - let (a, b) = (compared(fb, 0)?, compared(fb, 1)?); - let r = match op { - F::Min => metal_fmin(fb, f, test, less, a, b)?, - F::Max => metal_fmin(fb, f, test, greater, a, b)?, - F::Min3 | F::Max3 => { - let order = if op == F::Min3 { less } else { greater }; - let ab = metal_fmin(fb, f, test, order, a, b)?; - let c = compared(fb, 2)?; - metal_fmin(fb, f, test, order, ab, c)? - } - F::Clamp => { - let low = metal_fmin(fb, f, test, greater, a, b)?; - let c = compared(fb, 2)?; - metal_fmin(fb, f, test, less, low, c)? - } - // Not one of Metal's minimum and maximum functions. - _ => return Err(BuildError::Type(TypeRule::FunctionSignature)), - }; - Ok(r.value) -} - /// The largest magnitude Metal's `fast::sin` and `fast::cos` evaluate: `float(π/2) · 2^22` /// (`0x4ac90fdb`), past which the quadrant index no longer fits in 22 bits. pub(super) const FAST_TRIG_LIMIT: f32 = 6_588_397.5; diff --git a/crates/metal2vulkan/src/lower/arith/mod.rs b/crates/metal2vulkan/src/lower/arith/mod.rs index 9590f2c58..8f34f84cb 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -60,12 +60,10 @@ //! `f32` denormals whatever the device's modes, and the normalized and sRGB `air.unpack`/`air.pack` //! conversions are exact integer sequences and Metal's tables. //! -//! A NaN result is Metal's ([`nan`]): `float` `+ - * /`, the fused multiply-add on `OpFmaKHR`, and -//! the functions whose NaN Metal canonicalizes answer `0x7FC00000`, and `half` `+`, `*`, fused -//! multiply-add, and a `float` narrowed to `half` the canonical `half` NaN `0x7E00`, which the -//! lowering selects where the result's bits are observed unless the profile's measured device fact -//! leaves it to the device (`NanEncoding::MetalCanonical`); the functions whose NaN carries an -//! operand's sign or bits answer it on every profile. +//! A NaN result's bits are the device's ([`nan`]): where Metal answers one the device is not +//! measured to answer (its canonical `0x7FC00000` or `0x7E00` on a device without +//! `NanEncoding::MetalCanonical`, and a NaN that carries an operand's sign or bits on every +//! device), the module records `PrecisionNote::NativeNanEncoding`. pub mod aggregate; pub mod chunk; @@ -104,7 +102,7 @@ use crate::air::ir::{ }; use crate::air::Entry; use crate::budget::Meter; -use crate::device::profile::{DriverWorkaround, FloatFunctions, MinMaxRoute, NanEncoding}; +use crate::device::profile::{DriverWorkaround, FloatFunctions, NanEncoding}; use crate::device::{DeviceProfile, FloatWidth}; use crate::error::Error; use crate::lower::access; @@ -397,10 +395,6 @@ pub enum ArithStrategy { /// `air.fast_sincos` on `float`: [`FloatFn::FastSin`] and [`FloatFn::FastCos`], which /// flush past the last evaluated quadrant as Metal's `fast::sincos` does. fast: bool, - /// Metal's NaN selected for the sine and for the cosine, where Metal answers one the - /// device may not: the answers of the `sin` and `cos` the call computes, as `with_nan` - /// selects them for those calls. - nan: [Option; 2], }, /// `air.dot` of chunked vectors of `lanes` lanes of `elem` ([`chunk::dot`]). ChunkedDot { @@ -417,13 +411,6 @@ pub enum ArithStrategy { elem: Form, fma: fma::Fma, }, - /// A float result with Metal's NaN selected where it is a NaN ([`nan`]): the value of `of`, a - /// result of `form`, then [`nan::select`] of `answer`. Named as `of`. - Nan { - of: Box, - answer: nan::NanAnswer, - form: Form, - }, /// An operation with a wide integer operand or result on a profile without `shaderInt64`, /// on the two words of each value ([`wide`]). Wide(wide::WideOp), @@ -454,12 +441,7 @@ pub enum ArithStrategy { impl FamilyStrategy for ArithStrategy { fn name(&self, _: &FamilyPlans) -> Cow<'static, str> { use ArithStrategy as S; - // The NaN select is its operation's: the census names the operation. - let mut s = self; - while let S::Nan { of, .. } = s { - s = of; - } - Cow::Borrowed(match s { + Cow::Borrowed(match self { S::Int { form, .. } | S::IntCompare { form, .. } if form.legalized() => { "arith.int.legalized" } @@ -549,8 +531,6 @@ impl FamilyStrategy for ArithStrategy { S::Forward(_) => "arith.aggregate.forward", S::Null(_) => "arith.aggregate.null", S::Member { .. } => "arith.aggregate.member", - // Named as its operation: unwrapped above. - S::Nan { .. } => "arith.nan", }) } @@ -642,12 +622,9 @@ impl FamilyStrategy for ArithStrategy { let lanes = u32::from(floats.lanes); 64 + srgb + 400 + 24 * lanes + narrow::round_words(*floats) } - S::SinCos { - shape, - store, - fast, - nan, - } => chunk::sin_cos_words(*shape, *fast, *nan).saturating_add(store.words()), + S::SinCos { shape, store, fast } => { + chunk::sin_cos_words(*shape, *fast).saturating_add(store.words()) + } S::ChunkedDot { lanes, elem, .. } => chunk::dot_words(*lanes, *elem), S::ChunkedChain { lanes, elem, fma } => { chunk::dot_chain_words(*lanes, *elem, fma.words()) @@ -681,7 +658,6 @@ impl FamilyStrategy for ArithStrategy { S::LaneShuffle { out, .. } => chunk::move_words(*out, chunk::LaneMove::Shuffle, false), S::WordBitcast { from, to } => chunk::bitcast_words(*from, *to), S::Wide(w) => w.words(), - S::Nan { of, answer, form } => of.words().saturating_add(answer.words(*form)), } } @@ -821,26 +797,18 @@ pub struct ArithPlan { /// Whether [`ArithPlan::quantize`] is the device's own rounding (native half rounding, /// [`narrow::native_rounding`]), decided with it by [`finish`]. pub native_half: bool, - /// Whether a `half` texel keeps the NaN the device decoded under that native rounding too - /// (`narrow::round_texel`): where the profile's NaN is the translation's to answer as Metal's - /// (`NanEncoding::Device`, the policy's `NanMinMaxPolicy::Exact`), decided by [`finish`]. - pub texel_nans: bool, /// Whether a `half`'s NaN bits are left to the device's conversion where the module rounds /// through the conversion under the float controls ([`QuantizeForm::Controlled`]): a `half` /// read from its bits is the device's widening of them (`narrow::from_bits`), and a `half` - /// texel takes the rounding's NaN (`narrow::round_texel`). Where the profile's NaN is the - /// device's own (`NanEncoding::Native`, the policy's `NanMinMaxPolicy::Native`, the default), - /// decided by [`finish`]. + /// texel takes the rounding's NaN (`narrow::round_texel`). Decided by [`finish`], on every + /// profile that rounds so. pub native_half_nans: bool, /// Whether Metal's `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` on `float` or `half` - /// takes the device's `NMin`, `NMax` or `NClamp`, measured to be Metal's + /// takes the device's `NMin`, `NMax` or `NClamp` measured to be Metal's /// (`DriverDeviation::MetalMinMax`), recorded at selection: the module then requires - /// `VkProperty::MetalMinMax`, and every such call in it takes those instructions. + /// `VkProperty::MetalMinMax`. Every such call takes those instructions on every profile; one + /// not measured so records `NativeMinMax` ([`native_min_max`]). pub device_min_max: bool, - /// Whether those functions take the device's `NMin`, `NMax` or `NClamp` as native device - /// maths ([`native_min_max`]), recorded at selection: the module records `NativeMinMax` and - /// requires no property. - pub native_min_max: bool, /// Whether a `half` `+`, `-` or `*` takes the device's 16-bit arithmetic /// ([`ArithStrategy::F16`]), measured to be Metal's (`DriverDeviation::MetalHalfArithmetic`), /// recorded at selection: the module then requires `VkProperty::MetalHalfArithmetic`. @@ -944,12 +912,8 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { cx.families.arith.quantize = narrow::quantize_form(cx.profile); cx.families.arith.native_half = narrow::native_rounding(cx.profile, cx.families.arith.quantize).is_some(); - // Where the NaN switch asks for Metal's NaN, a texel's NaN is its own through that rounding. - cx.families.arith.texel_nans = nan::encoding(cx.profile) == NanEncoding::Device; - // Under the float controls a `half`'s NaN is the device's conversion's where the profile - // leaves NaN bits to the device. - cx.families.arith.native_half_nans = cx.families.arith.quantize == QuantizeForm::Controlled - && nan::encoding(cx.profile) == NanEncoding::Native; + // Under the float controls a `half`'s NaN is the device's conversion's. + cx.families.arith.native_half_nans = cx.families.arith.quantize == QuantizeForm::Controlled; cx.families.arith.mask = if cx .profile .fields() @@ -1368,8 +1332,8 @@ pub fn float_binop_notes( p.fields().float_functions == FloatFunctions::Metal, )); } - // A `float` `+ - *` and remainder answer Metal's NaN: the device's, where the profile states - // it is, else selected ([`nan`]), and leave their denormals to the device: `+ - *` but where it + // A `float` `+ - *` and remainder answer the device's NaN, noted where the profile does not + // state it is Metal's ([`nan`]), and leave their denormals to the device: `+ - *` but where it // is measured to read them as Metal does ([`leave_denormals`]), a remainder on every device. // Metal's `half` and `bfloat` remainders are not measured. let answer = binop_answer(op, fmt); @@ -1383,8 +1347,9 @@ pub fn float_binop_notes( Some(OpNotes::everywhere(notes)) } -/// The NaN Metal answers for the float binary operator `op` on format `fmt` that its lowering -/// selects ([`with_nan`]): `float` `frem`'s canonical NaN beside [`nan::binary_answer`]'s. +/// The NaN Metal answers for the float binary operator `op` on format `fmt`, which its lowering +/// leaves to the device ([`with_nan`]): `float` `frem`'s canonical NaN beside +/// [`nan::binary_answer`]'s. fn binop_answer(op: AirBin, fmt: FloatFmt) -> Option { match (op, fmt) { (AirBin::FRem, FloatFmt::F32) => Some(nan::NanAnswer::Canonical), @@ -1392,36 +1357,22 @@ fn binop_answer(op: AirBin, fmt: FloatFmt) -> Option { } } -/// Strategy `s` of instruction `at`, a result of form `form`, with Metal's NaN `answer` selected -/// ([`nan`]): where Metal answers one the lowering does not, the profile does not leave it to the -/// device, and the result's NaN bits may be observed. Under native device maths -/// ([`NanEncoding::Native`]) every answer is left to the device, noted `NativeNanEncoding`. +/// Strategy `s`, whose result's NaN Metal answers as `answer` where the lowering does not answer +/// it itself, with that NaN left to the device ([`nan`]): noted `NativeNanEncoding` where the +/// device is not measured to answer it ([`nan::NanAnswer::device_answers`]). fn with_nan( cx: &mut SelectCx<'_>, - at: InstId, s: ArithStrategy, answer: Option, - form: Form, ) -> ArithStrategy { note_native_nan(cx, answer); - match answer { - Some(answer) - if !answer.left_to(nan::encoding(cx.profile)) && cx.nan_payload_observed(at) => - { - ArithStrategy::Nan { - of: Box::new(s), - answer, - form, - } - } - _ => s, - } + s } -/// Record `NativeNanEncoding` where Metal answers a NaN (`answer`) that native device maths -/// leaves to the device ([`NanEncoding::Native`]). +/// Record `NativeNanEncoding` where Metal answers a NaN (`answer`) the device is not measured to +/// answer ([`nan::NanAnswer::device_answers`]). fn note_native_nan(cx: &mut SelectCx<'_>, answer: Option) { - if answer.is_some() && nan::encoding(cx.profile) == NanEncoding::Native { + if answer.is_some_and(|a| !a.device_answers(nan::encoding(cx.profile))) { cx.precision.insert(PrecisionNote::NativeNanEncoding); } } @@ -1549,14 +1500,15 @@ fn select_in( // `x - y * trunc(x / y)` of its precise quotient, which the device's `OpFRem` is at // the device's precision, below. Held::Float(FloatFmt::F32) if *op == AirBin::FRem && every_flag(*fmf) => { - return select_float_fn(cx, at, (FloatFn::Fmod, true), *fmf, f); + return select_float_fn(cx, (FloatFn::Fmod, true), *fmf, f); } // Metal divides `float` without `arcp` correctly rounded, a denormal operand // read as a zero and a denormal quotient flushed (a probe cases 914cc4d2, 711cc190, // and c10cba13, every lane), and `half` under every flag set rounded once from the // exact quotient (4c363561, 54f0fe8e, every lane): the device's quotient, its - // divisor kept in Vulkan's range ([`divide::native`]), its NaN Metal's canonical - // one. No device is measured to read a quotient's denormals as Metal does. + // divisor kept in Vulkan's range ([`divide::native`]), its NaN the device's (Metal + // answers its canonical one). No device is measured to read a quotient's denormals + // as Metal does. Held::Float(fmt) if divide::precise(*op, fmt, *fmf) => { let notes = float_binop_notes(*op, fmt, *fmf, cx.profile); record(cx, notes.unwrap_or_default()); @@ -1564,7 +1516,7 @@ fn select_in( fp_env(cx, *fmf, f); leave_denormals(cx, f, denormal::Covered::Never); let s = S::NativeDivide { form: f }; - with_nan(cx, at, s, Some(nan::NanAnswer::Canonical), f) + with_nan(cx, s, Some(nan::NanAnswer::Canonical)) } Held::Float(fmt) if op.is_float() => { let notes = float_binop_notes(*op, fmt, *fmf, cx.profile); @@ -1586,15 +1538,15 @@ fn select_in( // (a probe cases 914cc4d2 and 711cc190, every flag set measured, every lane), // its reciprocal flushing past `2^126` and at a denormal `y`: the device's // `OpFDiv(x, y)`, Metal's own where the device's functions are Metal's in an - // entry Metal compiles with fast math. Its NaN is the device's where the - // profile leaves NaNs to it, else Metal's canonical one, selected; its `f32` - // denormals the device's ([`float_binop_notes`]). + // entry Metal compiles with fast math. Its NaN is the device's, noted where it + // is not measured to be Metal's canonical one; its `f32` denormals the + // device's ([`float_binop_notes`]). if *op == AirBin::FDiv && fmf.contains(FastMath::ARCP) && f.float_fmt() == Some(FloatFmt::F32) { let s = S::FastDivide { form: f, contract }; - with_nan(cx, at, s, Some(nan::NanAnswer::Canonical), f) + with_nan(cx, s, Some(nan::NanAnswer::Canonical)) } else if let Some(basis) = f16_arithmetic(cx.profile, *op, f) { // The device's own `half` arithmetic, Metal's in the forms that keep it // apart, which the AIR's flags allow whatever they are. Only the measured @@ -1602,7 +1554,7 @@ fn select_in( // its entry declares. cx.families.arith.f16_arith |= basis == F16Basis::Measured; let s = S::F16 { op: *op, form: f }; - with_nan(cx, at, s, nan::binary_answer(*op, fmt), f) + with_nan(cx, s, nan::binary_answer(*op, fmt)) } else { let s = S::Float { op: *op, @@ -1615,7 +1567,7 @@ fn select_in( if matches!(op, AirBin::FAdd | AirBin::FSub | AirBin::FMul) { leave_denormals(cx, f, denormal::Covered::Deviation); } - with_nan(cx, at, s, binop_answer(*op, fmt), f) + with_nan(cx, s, binop_answer(*op, fmt)) } } _ => return Err(cx.invariant("a binary operator on mismatched operands")), @@ -1631,7 +1583,7 @@ fn select_in( fp_env(cx, *fmf, f); // Metal's `half` `fneg` answers the canonical NaN. let nan = f.float_fmt().and_then(nan::fneg_answer); - with_nan(cx, at, S::FNeg { form: f, bits }, nan, f) + with_nan(cx, S::FNeg { form: f, bits }, nan) } InstKind::ICmp { pred, a, .. } => { let f = form_in(cx, *a, chunk)?; @@ -1654,7 +1606,7 @@ fn select_in( form: f, } } - InstKind::Cast { op, v } => select_cast(cx, at, *op, *v, inst, chunk)?, + InstKind::Cast { op, v } => select_cast(cx, *op, *v, inst, chunk)?, InstKind::Select { .. } => S::Select, InstKind::Freeze(v) => match cx.constant(*v) { Some(LoweredConst::Undef(_)) => S::Zero(result), @@ -1715,11 +1667,10 @@ fn select_in( }) } -/// Select the cast `op` of `v`, instruction `at`; with `chunk`, for one chunk (as +/// Select the cast `op` of `v`, instruction `inst`; with `chunk`, for one chunk (as /// [`select_in`]). fn select_cast( cx: &mut SelectCx<'_>, - at: InstId, op: CastOp, v: Value, inst: &Inst, @@ -1747,7 +1698,7 @@ fn select_cast( (Some(a), Some(b)) => nan::cast_answer(op, a, b), _ => None, }; - return Ok(with_nan(cx, at, s, answer, to)); + return Ok(with_nan(cx, s, answer)); } CastOp::FPToUI => CastKind::FpToUi, CastOp::FPToSI => CastKind::FpToSi, @@ -2057,7 +2008,7 @@ fn select_call( Callee::Air { op: AirIntrinsic::Convert(c), .. - } => return select_convert(cx, at, inst, call, c, chunk), + } => return select_convert(cx, inst, call, c, chunk), Callee::Air { op: AirIntrinsic::Pack(p), .. @@ -2097,16 +2048,14 @@ fn select_call( } ArithStrategy::IntFn { f: op, form: f } } - Fun::Float(op) => select_float_fn(cx, at, (op, fast), call.fmf, f)?, + Fun::Float(op) => select_float_fn(cx, (op, fast), call.fmf, f)?, }) } /// The strategy of float function `op` (`fast` its `fast_` variant) with fast-math flags `fmf` -/// on operands of form `f`, the result of instruction `at`: a math call's, or LLVM's `frem`'s, -/// which is `fmod`. +/// on operands of form `f`: a math call's, or LLVM's `frem`'s, which is `fmod`. fn select_float_fn( cx: &mut SelectCx<'_>, - at: InstId, (op, fast): (FloatFn, bool), fmf: FastMath, f: Form, @@ -2120,7 +2069,6 @@ fn select_float_fn( let arith = &mut cx.families.arith; arith.fmod_uses |= fmod; arith.device_min_max |= device_min_max(cx.profile, op, f); - arith.native_min_max |= native_min_max(cx.profile, op, f); } if let FloatLowering::Fma(fma) | FloatLowering::FastFmod(fma) @@ -2129,11 +2077,6 @@ fn select_float_fn( { cx.families.arith.take_fma(fma); } - // `dot`'s result is a scalar. - let result = match lowered.how { - FloatLowering::Fn(FloatFn::Dot) | FloatLowering::Dot(_) => f.scalar_form(), - _ => f, - }; let s = match lowered.how { FloatLowering::Fma(fma) => ArithStrategy::Fma(fma), FloatLowering::FastFmod(fma) => ArithStrategy::FastFmod { fma }, @@ -2150,7 +2093,7 @@ fn select_float_fn( if let Some(covered) = call_coverage(lowered.how, facts) { leave_denormals(cx, f, covered); } - Ok(with_nan(cx, at, s, lowered.nan, result)) + Ok(with_nan(cx, s, lowered.nan)) } /// Where the device reads the `f32` denormals of a float function call lowered as `how` on a @@ -2188,9 +2131,9 @@ fn coverage_left(how: FloatLowering, f: Form, facts: FloatFacts) -> bool { } /// Whether Metal's minimum and maximum function `op` on lanes of form `f` takes the device's -/// `NMin`, `NMax` or `NClamp`: `fmin`, `fmax`, `min3`, `max3`, `clamp` and `saturate` -/// ([`min_max_family`]) on `float` and `half` ([`math::metal_picks`]) where profile `p` takes -/// `DriverDeviation::MetalMinMax`. +/// `NMin`, `NMax` or `NClamp` measured to be Metal's: `fmin`, `fmax`, `min3`, `max3`, `clamp` and +/// `saturate` ([`min_max_family`]) on `float` and `half` ([`math::metal_picks`]) where profile `p` +/// takes `DriverDeviation::MetalMinMax`. fn device_min_max(p: &DeviceProfile, op: FloatFn, f: Form) -> bool { use crate::error::DriverDeviation; min_max_family(op) @@ -2215,13 +2158,13 @@ fn min_max_family(op: FloatFn) -> bool { } /// Whether Metal's minimum and maximum function `op` on lanes of form `f` takes the device's -/// `NMin`, `NMax` or `NClamp` as they are: one of [`device_min_max`]'s functions on a profile whose -/// picks are the device's (`MinMaxRoute::Native`: not measured to be Metal's, and the policy's -/// `NanMinMaxPolicy::Native`), noted `NativeMinMax`. -fn native_min_max(p: &DeviceProfile, op: FloatFn, f: Form) -> bool { - min_max_family(op) - && math::metal_picks(f.float_fmt()) - && p.fields().min_max == MinMaxRoute::Native +/// `NMin`, `NMax` or `NClamp` as they are, not measured to be Metal's, noted `NativeMinMax`: one of +/// [`device_min_max`]'s functions on a profile that does not take `DriverDeviation::MetalMinMax` +/// (`native_min_max`, [`FloatFacts::native_min_max`]), and `saturate` on every other float +/// format, which no device is measured to answer as Metal's `clamp(x, +0, 1)`. +fn native_min_max(op: FloatFn, f: Form, native_min_max: bool) -> bool { + let picks = math::metal_picks(f.float_fmt()); + min_max_family(op) && ((picks && native_min_max) || (op == FloatFn::Saturate && !picks)) } /// Why the device's 16-bit `+ - *` answers as Metal's `half` arithmetic ([`f16_arithmetic`]). @@ -2295,10 +2238,10 @@ struct FloatFacts { metal_functions: bool, /// Whether the device reads `f32` denormals as Metal does ([`denormal::device_flushes`]). device_denormals: bool, - /// Whether the profile leaves Metal's NaN to the device ([`NanEncoding::Native`]). - nan_native: bool, - /// Whether Metal's minimum and maximum functions are the device's as they are - /// (`MinMaxRoute::Native`, [`native_min_max`]). + /// Which NaN the device's arithmetic answers ([`nan::encoding`]). + nans: NanEncoding, + /// Whether Metal's minimum and maximum functions are the device's not measured to be Metal's: + /// the profile does not take `DriverDeviation::MetalMinMax` ([`native_min_max`]). native_min_max: bool, } @@ -2309,8 +2252,8 @@ impl FloatFacts { routes: fma::routes(p), metal_functions: p.fields().float_functions == FloatFunctions::Metal, device_denormals: denormal::device_flushes(p), - nan_native: nan::encoding(p) == NanEncoding::Native, - native_min_max: p.fields().min_max == MinMaxRoute::Native, + nans: nan::encoding(p), + native_min_max: !p.takes_driver_deviation(crate::error::DriverDeviation::MetalMinMax), } } } @@ -2439,10 +2382,10 @@ fn native_fma(fma: fma::Fma) -> OpNotes { /// The lowering of float function `op` called with the `fast_` prefix if `fast` and with /// fast-math flags `fmf`, on operands of form `f`, on a profile with float facts `facts` /// ([`FloatFacts`]); `None` where the form refuses the function (it is not a float, or a `double` -/// the function does not take). Where the profile leaves NaNs to the device a Metal NaN the call -/// answers is the device's, noted `NativeNanEncoding` (as [`with_nan`] records it), and where its -/// picks are the device's Metal's minimum and maximum functions are the device's -/// ([`native_min_max`]), noted `NativeMinMax`; the `f32` denormals the device reads where the +/// the function does not take). A Metal NaN the call answers is the device's, noted +/// `NativeNanEncoding` where the device is not measured to answer it (as [`with_nan`] records it), +/// and Metal's minimum and maximum functions are the device's, noted `NativeMinMax` where they are +/// not measured to be Metal's ([`native_min_max`]); the `f32` denormals the device reads where the /// table covers the call but the profile lacks the deviation are noted `DeviceDenormals` /// ([`coverage_left`]). fn float_call( @@ -2454,12 +2397,11 @@ fn float_call( ) -> Option { let mut call = float_call_of(op, fast, fmf, f, facts)?; let mut native = BTreeSet::new(); - if call.nan.is_some() && facts.nan_native { + if call.nan.is_some_and(|a| !a.device_answers(facts.nans)) { native.insert(PrecisionNote::NativeNanEncoding); } if let FloatLowering::Fn(op) = call.how { - let picks = min_max_family(op) && math::metal_picks(f.float_fmt()); - if picks && facts.native_min_max { + if native_min_max(op, f, facts.native_min_max) { native.insert(PrecisionNote::NativeMinMax); } } @@ -2496,9 +2438,9 @@ fn float_call_of( // `FastMathRewrites`. if matches!(op, FloatFn::Fma | FloatFn::MulAdd) { if let Some(fma) = fma::Fma::by(routes, f) { - // The device's `float` instruction answers the device's NaN, so Metal's is selected; a - // `half` result's rounding answers the device's `half` NaN on every route, so Metal's - // is selected where it is measured. + // The device's `float` instruction answers the device's NaN, noted; a `half` result's + // rounding answers the device's `half` NaN on every route, noted where Metal's is + // measured. let khr = fma.route.device_float(); let nan = match f.float_fmt() { Some(FloatFmt::Half) => { @@ -2516,7 +2458,7 @@ fn float_call_of( // Metal's `mix(x, y, t)` on `float` and `half` is `fma(t, y, fma(-t, x, x))`, with and without // fast-math flags. Where the device's functions are Metal's, and on `half` by the measured // 16-bit fused multiply-add, Metal's own form of its own fused multiply-adds answers it, whose - // NaN is the device's `float` instruction's, which is selected, and a `half` result's as the + // NaN is the device's `float` instruction's, which is noted, and a `half` result's as the // `half` `fma`'s. if op == FloatFn::Mix { if let Some(fma) = fma::Fma::by(routes, f) { @@ -2557,8 +2499,8 @@ fn float_call_of( // fast-math flags, `b * (a + c)` for `dot(float2(a, b), float2(b, c))`, `NativeDot`). Where the // profile's `float` functions are Metal's, a `float` `OpDot` reaches Metal's own `dot`, the // same chain; a `half` there would be summed in its `float` container, so it takes the chain, - // as a `half` one by the measured 16-bit fused multiply-add does. Metal's NaN is selected as - // for any function. + // as a `half` one by the measured 16-bit fused multiply-add does. Its NaN is the device's, + // noted as for any function. if op == FloatFn::Dot { if let Some(fma) = fma::Fma::by(routes, f.scalar_form()) { let nan = f @@ -2602,7 +2544,7 @@ fn float_call_of( }); } } - // The NaN Metal answers, selected where the lowering does not answer it itself. + // The NaN Metal answers, where the lowering does not answer it itself. let answer = f .float_fmt() .and_then(|fmt| nan::function_answer(op, fast, every_flag(fmf), fmt)); @@ -2746,14 +2688,11 @@ pub(super) fn select_sincos( ); let fast = symbol_fast && f.float_fmt() == Some(FloatFmt::F32); let (sin, cos) = chunk::sin_cos_fns(fast); - // Each result takes the NaN its function answers as a call of its own (`float_call`'s rule): - // Metal's `sincos` answers its `sin` and `cos`, word for word (cases 7b283404 and f6524207, - // every pair), so where Metal's answer is measured it is selected; otherwise the device's NaN - // is noted. The cosine is stored, so its bits are observed. Each records its notes as a call of - // its own (`function_notes`). + // Each result's NaN is the device's, noted as a call of its own's (`float_call`'s rule): Metal's + // `sincos` answers its `sin` and `cos`, word for word (cases 7b283404 and f6524207, every + // pair). Each records its notes as a call of its own (`function_notes`). let metal_functions = cx.profile.fields().float_functions == FloatFunctions::Metal; - let mut nans = [None; 2]; - for (slot, (op, stored)) in nans.iter_mut().zip([(sin, false), (cos, true)]) { + for op in [sin, cos] { let answer = f .float_fmt() .and_then(|fmt| nan::function_answer(op, symbol_fast, every_flag(call.fmf), fmt)); @@ -2766,9 +2705,7 @@ pub(super) fn select_sincos( (!op.metal_denormals(), !metal_nans && answer.is_none()), ); record(cx, notes); - let observed = stored || cx.nan_payload_observed(at); note_native_nan(cx, answer.filter(|_| !metal_nans)); - *slot = answer.filter(|a| !metal_nans && !a.left_to(nan::encoding(cx.profile)) && observed); } fp_env(cx, call.fmf, f); let align = cx @@ -2791,7 +2728,6 @@ pub(super) fn select_sincos( shape, store: Box::new(store), fast, - nan: nans, }) } @@ -2842,7 +2778,6 @@ fn select_pack( fn select_convert( cx: &mut SelectCx<'_>, - at: InstId, inst: &Inst, call: &crate::air::ir::Call, c: &Convert, @@ -2928,7 +2863,7 @@ fn select_convert( (ConvertKind::Float, Some(a), Some(b)) => nan::convert_answer(a, b), _ => None, }; - Ok(with_nan(cx, at, s, nan, to)) + Ok(with_nan(cx, s, nan)) } // ---- Emission ---- @@ -3001,16 +2936,11 @@ pub fn emit( } } S::IndexWord(w) => access::index::emit_word(cx, fb, w)?, - S::SinCos { - shape, - store, - fast, - nan, - } => { + S::SinCos { shape, store, fast } => { let p = nth(cx, &xs, 0)?; let test = nan::NanTest::for_modes(&cx.plan.families.arith.modes); let lib = lib(cx); - let (sin, cos) = chunk::sin_cos(fb, *shape, p, *fast, *nan, test, &lib)?; + let (sin, cos) = chunk::sin_cos(fb, *shape, p, *fast, test, &lib)?; // The access family's store reads the stored value as the call's result. cx.define(result, cos); access::emit(cx, fb, at, store)?; @@ -3026,7 +2956,6 @@ pub fn emit( pub(crate) fn lib(cx: &EmitCx<'_>) -> libm::Lib { let arith = &cx.plan.families.arith; libm::Lib::new(arith.metal_functions, cx.decl.families.arith.fmod) - .with_min_max(arith.device_min_max || arith.native_min_max) } /// The operands strategy `s` reads (a prefix of the instruction's; all when `None`). @@ -3062,7 +2991,6 @@ fn arity(s: &ArithStrategy) -> Option { | S::Member { .. } => Some(0), S::Chunked { parts, .. } => parts.first().and_then(|(_, p)| arity(p)), S::Wide(w) => w.arity(), - S::Nan { of, .. } => arity(of), _ => None, } } @@ -3093,11 +3021,6 @@ fn value( wide, result, } => chunk::emit_chunked(cx, fb, *lanes, parts, wide, result, xs)?, - S::Nan { of, answer, form } => { - let r = value(cx, fb, of, xs)?; - let test = nan::NanTest::for_modes(&cx.plan.families.arith.modes); - nan::select(fb, *form, *answer, test, r, xs.first().copied())? - } S::ChunkedDot { lanes, elem, diff --git a/crates/metal2vulkan/src/lower/arith/nan.rs b/crates/metal2vulkan/src/lower/arith/nan.rs index 73142354f..a89950d65 100644 --- a/crates/metal2vulkan/src/lower/arith/nan.rs +++ b/crates/metal2vulkan/src/lower/arith/nan.rs @@ -12,51 +12,35 @@ //! widened as `0x7FC00000`; its widening of a `half` NaN to `float`, and its `half` `fneg` and //! `fabs`, answer the canonical NaN too ([`NanAnswer::CanonicalExact`]). Its `float` `fneg` and //! `fabs` keep a NaN operand's payload, which the lowering moves on the bits -//! (`math::sign_on_bits`), no select needed. Vulkan states no NaN encoding, and the devices +//! (`math::sign_on_bits`). Vulkan states no NaN encoding, and the devices //! measured answer their own: //! an operand's bits, quieted or not, `0xFFC00000`, or `0x7FFFFFFF`, and for `half` `0xFE00`, the //! operand's payload, or `0x7FFF`. Each device answers a NaN on exactly the lanes Metal does for -//! these classes, so selecting Metal's NaN where the result is a NaN ([`select`]) is exact on -//! every device. +//! these classes. //! -//! The select is applied where the result's bits can be observed: a result whose every use -//! drops its operands' NaN bits ([`drops_payload`]: a float comparison, or an operation that -//! itself answers the canonical NaN) needs none, so a chain of arithmetic selects once, at its -//! end, and the device may still contract an `fmul` into the `fadd` that uses it -//! ([`observed_payloads`]). Where the profile states that the device's arithmetic answers Metal's -//! canonical NaN ([`NanEncoding::MetalCanonical`], a measured device fact), the canonical class -//! of its arithmetic is left to the device; the other classes, and the canonical NaN of an -//! operation the device computes exactly, are selected on every profile. +//! The module leaves every NaN's bits to the device, and records +//! `PrecisionNote::NativeNanEncoding` where Metal answers a NaN the device is not measured to +//! answer: every answer these tables give, but the canonical class of the arithmetic on a device +//! measured to answer Metal's canonical NaN ([`NanEncoding::MetalCanonical`], +//! [`NanAnswer::device_answers`]). //! -//! The NaN test is `OpIsNan` where the entry declares `SignedZeroInfNanPreserve` for 32-bit -//! floats, without which a device may assume that no operand is a NaN and fold the test; the -//! module then tests the bits instead (`(bits & 0x7FFFFFFF) > 0x7F800000`), which no float mode -//! reaches. The translation decorates no value `FPFastMathMode`. The select itself is a `float` -//! `OpSelect`, which such a device may still fold to its operand, since the condition holds -//! exactly where the operand is a NaN; where the answer is read bit for bit the module answers on -//! the bits alone instead ([`canonical_on_bits`]). +//! [`is_nan`] tests a value for a NaN, by `OpIsNan` where the entry declares +//! `SignedZeroInfNanPreserve` for the width, without which a device may assume that no operand is a +//! NaN and fold the test, and on the bits elsewhere (`(bits & 0x7FFFFFFF) > 0x7F800000`), which no +//! float mode reaches: the conversions and functions whose answer at a NaN is a number test so. -use crate::air::intrinsics::{AirIntrinsic, NumKind, Precision}; -use crate::air::ir::{ - BinOp as AirBin, Body, Callee, CastOp, FastMath, FuncId, Inst, InstKind, Type, TypeId, Value, -}; -use crate::air::Entry; -use crate::budget::Meter; +use crate::air::ir::{BinOp as AirBin, CastOp, FastMath}; use crate::device::profile::NanEncoding; use crate::device::DeviceProfile; -use crate::error::Error; use crate::lower::arith::legal::{FloatFmt, Form, Held}; use crate::lower::arith::math::FloatFn; use crate::lower::arith::narrow::u32_form; use crate::lower::arith::ops::{splat, ty}; use crate::spirv::builder::FunctionBuilder; -use crate::spirv::error::{BResult, BuildError, TypeRule}; +use crate::spirv::error::BResult; use crate::spirv::ids::Value as SValue; use crate::spirv::ir::{BinOp, ConvOp, UnOp}; -/// Metal's canonical `float` NaN. -pub const CANONICAL: u64 = 0x7FC0_0000; - /// Which NaN Metal answers where an operation's result is a NaN. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum NanAnswer { @@ -80,38 +64,20 @@ pub enum NanAnswer { } impl NanAnswer { - /// Whether the answer is left to the device under `encoding`: on a device whose arithmetic - /// answers Metal's canonical NaN ([`NanEncoding::MetalCanonical`]) the canonical class of the - /// arithmetic, which the device fact covers, and not [`NanAnswer::CanonicalExact`]; under - /// native device maths ([`NanEncoding::Native`]) every answer, the device's NaN noted - /// `PrecisionNote::NativeNanEncoding`. - pub fn left_to(self, encoding: NanEncoding) -> bool { + /// Whether the device is measured to answer this NaN under `encoding`: on a device whose + /// arithmetic answers Metal's canonical NaN ([`NanEncoding::MetalCanonical`]) the canonical + /// class of the arithmetic, which the device fact covers, and not + /// [`NanAnswer::CanonicalExact`]; nothing on another ([`NanEncoding::Native`]). The device's + /// NaN of an answer it is not measured to give is noted `PrecisionNote::NativeNanEncoding`. + pub fn device_answers(self, encoding: NanEncoding) -> bool { match encoding { NanEncoding::MetalCanonical => self == NanAnswer::Canonical, - NanEncoding::Native => true, - _ => false, + NanEncoding::Native => false, } } - - /// Whether the answer reads the first operand. - pub fn reads_operand(self) -> bool { - !matches!(self, NanAnswer::Canonical | NanAnswer::CanonicalExact) - } - - /// An upper estimate of the SPIR-V words of [`select`] on a result of form `f`: the bits tests, - /// the selects, and the constants' share. - pub fn words(self, f: Form) -> u32 { - let lanes = u32::from(f.lanes); - let base = match self { - NanAnswer::Canonical | NanAnswer::CanonicalExact => 32, - NanAnswer::Operand => 56, - NanAnswer::OperandSign | NanAnswer::DomainSign => 80, - }; - base + 4 * lanes - } } -/// How [`select`] tests a value for a NaN. +/// How [`is_nan`] tests a value for a NaN. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NanTest { /// `OpIsNan`: the entry declares `SignedZeroInfNanPreserve` for the width. @@ -216,8 +182,7 @@ fn precise_of(op: FloatFn) -> FloatFn { /// The answer Metal gives for a NaN result of `float` function `op` (refined as in /// [`function_answer`]) in the state measured: a precise symbol without fast-math flags /// (`nan_functions`), a `fast_` one (`fast`) with every flag (`nan_functions_fast`). Functions -/// whose lowering answers it itself ([`FloatFn::metal_nans`]) are listed too: their result drops -/// its operands' NaN bits ([`drops_payload`]). `None` where Metal answers a number for a NaN +/// whose lowering answers it itself ([`FloatFn::metal_nans`]) are listed too. `None` where Metal answers a number for a NaN /// operand (`sign`, `saturate`, `fast::sin`, `fast::cos`), where the result is an operand /// (`fmin`, `fmax`, `median3`, `copysign`, `fabs`, and precise `pow`, whose `pow(x, 1)` is `x`). /// `sinpi`, `cospi`, and `tanpi` answer the canonical NaN in both modes for an infinity or a NaN. @@ -408,76 +373,6 @@ pub fn convert_answer(from: FloatFmt, to: FloatFmt) -> Option { } } -/// `r` (a result of form `f`, `float` lanes) with Metal's NaN `answer` where it is a NaN; `a` -/// is the operation's first operand, which every answer but the canonical ones reads. -pub fn select( - fb: &mut FunctionBuilder<'_>, - f: Form, - answer: NanAnswer, - test: NanTest, - r: SValue, - a: Option, -) -> BResult { - let r_nan = is_nan(fb, f, test, r)?; - let canonical = splat(fb, f, CANONICAL)?; - let a = match (answer.reads_operand(), a) { - (false, _) => return fb.select(r_nan, canonical, r), - (true, Some(a)) => a, - (true, None) => return Err(BuildError::Type(TypeRule::FunctionSignature)), - }; - let a_nan = is_nan(fb, f, test, a)?; - match answer { - NanAnswer::Canonical | NanAnswer::CanonicalExact => fb.select(r_nan, canonical, r), - NanAnswer::Operand => { - let r = fb.select(r_nan, canonical, r)?; - fb.select(a_nan, a, r) - } - NanAnswer::OperandSign | NanAnswer::DomainSign => { - let u = u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let bits = fb.convert(ConvOp::Bitcast, a, ut)?; - let sign_bit = splat(fb, u, 0x8000_0000)?; - let sign = fb.binary(BinOp::BitwiseAnd, bits, sign_bit)?; - let zero = splat(fb, u, 0)?; - let sign = if answer == NanAnswer::OperandSign { - fb.select(a_nan, sign, zero)? - } else { - fb.select(a_nan, zero, sign)? - }; - let quiet = splat(fb, u, CANONICAL)?; - let nan = fb.binary(BinOp::BitwiseOr, sign, quiet)?; - let nan = fb.convert(ConvOp::Bitcast, nan, ft)?; - fb.select(r_nan, nan, r) - } - } -} - -/// `x`, 32-bit `float` lanes of form `f`, with Metal's canonical NaN `0x7FC00000` where a lane is -/// a NaN, on the bits alone: the test, the select and the answer are integer operations, and the -/// one float value is the result of an `OpBitcast`, which carries no float mode. -/// -/// [`select`] with [`NanAnswer::CanonicalExact`] answers the same value through a `float` -/// `OpSelect` whose condition holds exactly where its operand is a NaN: a compiler that assumes no -/// operand is a NaN may fold that select to its operand, and the module declares no -/// `SignedZeroInfNanPreserve` for it to rely on. This form leaves it nothing to fold, so a -/// widening whose answer is read bit for bit (the vertex and stage-in fetches, -/// `lower::stage_io::fetch`) uses it. -pub fn canonical_on_bits(fb: &mut FunctionBuilder<'_>, f: Form, x: SValue) -> BResult { - if f.float_fmt() != Some(FloatFmt::F32) { - return Err(BuildError::Type(TypeRule::FunctionSignature)); - } - let u = u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let bits = fb.convert(ConvOp::Bitcast, x, ut)?; - let magnitude = splat(fb, u, 0x7FFF_FFFF)?; - let infinity = splat(fb, u, 0x7F80_0000)?; - let m = fb.binary(BinOp::BitwiseAnd, bits, magnitude)?; - let is_nan = fb.binary(BinOp::UGreaterThan, m, infinity)?; - let canonical = splat(fb, u, CANONICAL)?; - let answered = fb.select(is_nan, canonical, bits)?; - fb.convert(ConvOp::Bitcast, answered, ft) -} - /// Whether lanes of `x` (form `f`) are NaNs, by `test`. The bits of a 64-bit container are read /// as two words per lane ([`is_nan_wide`]), so the test needs no 64-bit integers. pub fn is_nan(fb: &mut FunctionBuilder<'_>, f: Form, test: NanTest, x: SValue) -> BResult { @@ -541,77 +436,6 @@ fn is_nan_wide(fb: &mut FunctionBuilder<'_>, f: Form, x: SValue) -> BResult bool { - match &inst.kind { - InstKind::FCmp { .. } => true, - InstKind::FNeg { v, .. } => float_fmt_of(e, func, *v).and_then(fneg_answer).is_some(), - InstKind::BinOp { op, a, .. } => float_fmt_of(e, func, *a) - .and_then(|fmt| binary_answer(*op, fmt)) - .is_some(), - InstKind::Cast { op, v } => { - match (float_fmt_of(e, func, *v), float_fmt_of_ty(e, inst.ty)) { - (Some(from), Some(to)) => cast_answer(*op, from, to).is_some(), - _ => false, - } - } - InstKind::Call(call) => { - if let Callee::Air { - op: AirIntrinsic::Convert(c), - .. - } = &call.callee - { - let float = c.src_kind == NumKind::Float && c.dst_kind == NumKind::Float; - let from = call.args.first().and_then(|x| float_fmt_of(e, func, *x)); - return match ( - float && c.src_fp8.is_none(), - from, - float_fmt_of_ty(e, inst.ty), - ) { - (true, Some(from), Some(to)) => convert_answer(from, to).is_some(), - _ => false, - }; - } - let (op, fast) = match &call.callee { - Callee::Air { - op: AirIntrinsic::Math(m), - .. - } => (super::air_math(m.f).ok(), m.precision == Precision::Fast), - Callee::Llvm { op, .. } => (super::llvm_math(op).ok(), false), - _ => (None, false), - }; - let Some(super::Fun::Float(op)) = op else { - return false; - }; - let Some(first) = call.args.first() else { - return false; - }; - let Some(fmt) = float_fmt_of(e, func, *first) else { - return false; - }; - let f = Form { - held: Held::Float(fmt), - lanes: 1, - }; - // `air.fast_fmod` on `float` is Metal's fused multiply-add composition, whose NaN is - // the fused multiply-add's: canonical. - if fast && op == FloatFn::Fmod && fmt == FloatFmt::F32 { - return true; - } - // The reciprocal a refinement divides by does not decide its NaN. - let op = super::refine_float(op, fast, call.fmf, f); - matches!( - function_answer(op, fast, super::every_flag(call.fmf), fmt), - Some(NanAnswer::Canonical | NanAnswer::CanonicalExact) - ) - } - _ => false, - } -} - /// Whether precise `float` function `op` called with every fast-math flag is measured to answer /// the NaN it answers without them ([`measured`]'s precise state): `sin`, `cos` (and `sincos`'s /// two results), `tan`, `asin`, `acos`, `atan`, `asinh`, `atanh` and `atan2` at NaN operands of @@ -628,60 +452,6 @@ fn flagged_precise(op: FloatFn) -> bool { ) } -/// The float format of `v`'s scalar or vector type, if it is one. -fn float_fmt_of(e: &Entry, func: FuncId, v: Value) -> Option { - float_fmt_of_ty(e, e.module.value_ty(func, v)?) -} - -/// The float format of scalar or vector type `t`, if it is one. -fn float_fmt_of_ty(e: &Entry, mut t: TypeId) -> Option { - let types = e.module.types(); - if let Some(Type::Vector { elem, .. }) = types.get(t) { - t = *elem; - } - match types.get(t)? { - Type::Float => Some(FloatFmt::F32), - Type::Half => Some(FloatFmt::Half), - Type::BFloat => Some(FloatFmt::BFloat), - Type::Double => Some(FloatFmt::F64), - _ => None, - } -} - -/// Whether each instruction's result may carry its NaN's bits to an observation, by `InstId`: -/// read by an instruction or terminator that does not [`drops_payload`] (a phi, which moves the -/// value on, included). One pass over the body's instructions; the bitmap is charged to `m` and -/// released by the caller (`insts.len()` bytes). -pub fn observed_payloads( - e: &Entry, - func: FuncId, - body: &Body, - m: &mut Meter, -) -> Result, Error> { - let n = body.insts.len(); - m.charge(n)?; - let mut observed = vec![false; n]; - for (_, block) in body.blocks.iter() { - for id in block.inst_ids() { - m.tick(1)?; - let Some(inst) = body.insts.get(id) else { - continue; - }; - if drops_payload(e, func, inst) { - continue; - } - inst.kind.for_each_value(|v| { - if let Value::Inst(i) = v { - if let Some(o) = observed.get_mut(i.raw() as usize) { - *o = true; - } - } - }); - } - } - Ok(observed) -} - /// The profile's NaN encoding. pub fn encoding(p: &DeviceProfile) -> NanEncoding { p.fields().nan_encoding diff --git a/crates/metal2vulkan/src/lower/arith/narrow.rs b/crates/metal2vulkan/src/lower/arith/narrow.rs index 64a0fca02..95dd7efdd 100644 --- a/crates/metal2vulkan/src/lower/arith/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/narrow.rs @@ -342,15 +342,12 @@ pub fn round_texel_words(f: Form) -> u32 { /// `OpQuantizeToF16` may return another NaN; it is told by its bits, so the test holds whatever /// float modes the device compiles the module under. Under native half rounding /// ([`native_rounding`]) the rounding's own NaN stands instead: the note the module records bounds -/// a NaN's encoding to the device's, so the keep's four instructions a texel are left out, but -/// where the NaN switch asks for Metal's NaN (`NanMinMaxPolicy::Exact`; -/// `ModuleBuilder::texel_nans`), which keeps them. So too under the float controls -/// ([`QuantizeForm::Controlled`]) where the profile leaves a NaN's bits to the device -/// (`ModuleBuilder::native_half_nans`, `NanMinMaxPolicy::Native`): the conversion keeps a NaN a -/// NaN, its bits the device's, as the texel's decode is (`PrecisionNote::DeviceNanEncoding`, which -/// the access records). Another form is [`round`]ed. +/// a NaN's encoding to the device's, so the keep's four instructions a texel are left out. So too +/// under the float controls ([`QuantizeForm::Controlled`], `ModuleBuilder::native_half_nans`): the +/// conversion keeps a NaN a NaN, its bits the device's, as the texel's decode is +/// (`PrecisionNote::DeviceNanEncoding`, which the access records). Another form is [`round`]ed. pub fn round_texel(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { - let native = fb.module().native_half() && !fb.module().texel_nans(); + let native = fb.module().native_half(); match f.held { Held::Float(FloatFmt::Half) if native || fb.module().native_half_nans() => round(fb, f, x), Held::Float(FloatFmt::Half) => { @@ -983,9 +980,9 @@ fn f32_bits_to_half_bits(fb: &mut FunctionBuilder<'_>, u: Form, b: Value) -> BRe /// Under native half rounding through the device's conversion ([`native_decode`]) a `half`'s exact /// decode is offered the device's ([`native_from_bits`]) where no loop holds it /// (`FunctionBuilder::offer_outside_loops`): NVIDIA's compiler makes a module faster with the -/// device's widening outside loops and slower with it inside one. Under the float controls, where -/// the profile leaves a NaN's bits to the device (`ModuleBuilder::native_half_nans`), a `half` is -/// the device's widening of its bits wherever it is ([`device_from_bits`]); so is the `half` of a +/// device's widening outside loops and slower with it inside one. Under the float controls +/// (`ModuleBuilder::native_half_nans`), a `half` is the device's widening of its bits wherever it +/// is ([`device_from_bits`]); so is the `half` of a /// load whose uses read no NaN's bits, where the device's widening is Metal's /// (`ModuleBuilder::widens_halves`, [`widening`](super::widening)): exact, a NaN `0x7FC00000` as /// Metal widens it, the bits noted as for the integer decode. @@ -1063,8 +1060,8 @@ fn native_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult< /// `SignedZeroInfNanPreserve`. A NaN widens to a NaN whose bits are the device's (the SPIR-V /// spec's `SignedZeroInfNanPreserve`: "Bit patterns for NaNs might not be preserved"). Metal widens /// every `half` NaN to `0x7FC00000` and every other `half` to its value (the M3 Max, every bit -/// pattern, loaded from device and constant memory, safe and fast math), which the NaN switch -/// answers at the widening to `float` (`nan::cast_answer`) on [`half_bits_to_f32_bits`]'s decode. +/// pattern, loaded from device and constant memory, safe and fast math), which no form answers: the +/// device's NaN is noted (`PrecisionNote::NativeNanEncoding`). fn device_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult { let e = fb.module().ty(Type::Float { width: 16 })?; let pair = fb.module().ty(Type::Vector { elem: e, len: 2 })?; diff --git a/crates/metal2vulkan/src/lower/arith/ops.rs b/crates/metal2vulkan/src/lower/arith/ops.rs index 762048984..89bb3718d 100644 --- a/crates/metal2vulkan/src/lower/arith/ops.rs +++ b/crates/metal2vulkan/src/lower/arith/ops.rs @@ -287,8 +287,7 @@ pub fn f16_binary_words(f: Form) -> u32 { /// alternative, [`float_binary`]): `float`'s 24-bit significand is at least `2 · 11 + 2` bits, so /// rounding its correctly rounded sum, difference or product to `half` rounds the exact result once /// (the double rounding is innocuous). A NaN's bits are the device's, as the controlled rounding's -/// are; Metal's NaN, where the profile asks for it, is selected around the instruction -/// (`ArithStrategy::Nan`). +/// are. /// /// The instruction is always kept apart, whatever the AIR's flags allow: a sum or difference /// decorated `NoContraction` (SPIRV-Cross writes its `[[clang::optnone]]` `spvFAdd` or `spvFSub`), diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index 07b9d10f0..c8cda8785 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -1796,40 +1796,6 @@ fn median3_ref(b: [u64; 3], val: &dyn Fn(u64) -> f64, fast: bool) -> u64 { pick(pick(c, lo, false), hi, true) } -/// Metal's `fmin`, `fmax`, `min3`, `max3`, or `clamp` (`op`) of operand bits `b`: `fmin(p, q)` is -/// `q` for a NaN `p`, else `p` for a NaN `q` or `p < q`, else `q` (and `fmax` with `>`), comparing -/// the operands' values `val` (an `f32` denormal as zero) but returning their bits; `min3` and -/// `max3` nest it, and `clamp(x, lo, hi)` is `fmin(fmax(x, lo), hi)`. -fn metal_min_max_ref(op: FloatFn, b: &[u64], val: &dyn Fn(u64) -> f64) -> u64 { - let pick = |p: u64, q: u64, less: bool| { - let (vp, vq) = (val(p), val(q)); - if vp.is_nan() { - q - } else if vq.is_nan() || (less && vp < vq) || (!less && vp > vq) { - p - } else { - q - } - }; - match op { - FloatFn::Min => pick(b[0], b[1], true), - FloatFn::Max => pick(b[0], b[1], false), - FloatFn::Min3 => pick(pick(b[0], b[1], true), b[2], true), - FloatFn::Max3 => pick(pick(b[0], b[1], false), b[2], false), - FloatFn::Clamp => pick(pick(b[0], b[1], false), b[2], true), - _ => panic!("{op:?} is not a minimum or maximum"), - } -} - -/// An `f32` operand's value as Metal's `float` comparisons read it: a denormal as zero. -fn f32_compared(b: u64) -> f64 { - if b & 0x7F80_0000 == 0 { - 0.0 - } else { - f64::from(f32::from_bits(b as u32)) - } -} - fn float_ref(op: FloatFn, bits: u8, a: &[u64]) -> Option { let x = |i: usize| fval(bits, a[i]); // An `f32` zero or denormal, which Metal's `float` functions read as zero. @@ -1882,19 +1848,8 @@ fn float_ref(op: FloatFn, bits: u8, a: &[u64]) -> Option { -1.0 }) } - FloatFn::Saturate => { - let v = x(0); - r(if flushed(0) || v.is_nan() || v <= 0.0 { - 0.0 - } else { - v.min(1.0) - }) - } - FloatFn::Min | FloatFn::Max | FloatFn::Clamp | FloatFn::Min3 | FloatFn::Max3 - if bits == 32 => - { - Some(metal_min_max_ref(op, a, &f32_compared)) - } + // The device's `NClamp(x, 0, 1)`: a NaN answers 0, a denormal is the device's. + FloatFn::Saturate => r(min(max(x(0), 0.0), 1.0)), FloatFn::Min | FloatFn::MinNum => r(min(x(0), x(1))), FloatFn::Max | FloatFn::MaxNum => r(max(x(0), x(1))), FloatFn::Clamp => r(min(max(x(0), x(1)), x(2))), @@ -2049,15 +2004,18 @@ fn exact_float_functions_match_metal() { } c }; - // The device's `NMin` and `NMax` may give either zero; Metal's (`float`) gives the - // second operand. - let loose = match op { - FloatFn::MinNum | FloatFn::MaxNum => true, - FloatFn::Min | FloatFn::Max | FloatFn::Clamp | FloatFn::Min3 | FloatFn::Max3 => { - bits == 64 - } - _ => false, - }; + // The device's `NMin`, `NMax` and `NClamp` may give either zero. + let loose = matches!( + op, + FloatFn::MinNum + | FloatFn::MaxNum + | FloatFn::Min + | FloatFn::Max + | FloatFn::Clamp + | FloatFn::Min3 + | FloatFn::Max3 + | FloatFn::Saturate + ); check( &format!("{op:?} f{bits}"), &vec![f; arity], @@ -2109,176 +2067,6 @@ fn nan_operands() -> Vec { ] } -/// [`nan::select`] answers Metal's NaN bit for bit, by either test, on scalars and vectors: the -/// canonical NaN for every NaN result (`Canonical`, `CanonicalExact`); with a NaN operand's sign or `+` for a domain error -/// (`OperandSign`); `+` for a NaN operand and the operand's sign for a domain error -/// (`DomainSign`); the NaN operand itself, else the canonical NaN (`Operand`); and every other -/// result untouched. The kernel's first input is the operand, its second the result. -#[test] -fn nan_select_answers_metals_nan_exactly() { - use super::nan::{self, NanAnswer}; - let f32_nan = |b: u64| f32::from_bits(b as u32).is_nan(); - let vals = nan_operands(); - let cases = pairs(&vals, &vals); - for answer in [ - NanAnswer::Canonical, - NanAnswer::CanonicalExact, - NanAnswer::OperandSign, - NanAnswer::DomainSign, - NanAnswer::Operand, - ] { - for test in [NanTest::IsNan, NanTest::Bits] { - for lanes in [1, 3] { - let f = vec(float(32), lanes); - let lane_cases: Vec = cases - .iter() - .map(|c| c.iter().map(|o| vec![o[0]; usize::from(lanes)]).collect()) - .collect(); - check_accept( - &format!("{answer:?} {test:?} x{lanes}"), - &[f, f], - f, - &|fb, x| nan::select(fb, f, answer, test, x[1], Some(x[0])), - &lane_cases, - &|c| { - let (a, r) = (arg(c, 0), arg(c, 1)); - let sign = a & 0x8000_0000; - let want = match answer { - NanAnswer::Operand if f32_nan(a) => a, - _ if !f32_nan(r) => r, - NanAnswer::Canonical - | NanAnswer::CanonicalExact - | NanAnswer::Operand => nan::CANONICAL, - NanAnswer::OperandSign if f32_nan(a) => sign | nan::CANONICAL, - NanAnswer::OperandSign => nan::CANONICAL, - NanAnswer::DomainSign if f32_nan(a) => nan::CANONICAL, - NanAnswer::DomainSign => sign | nan::CANONICAL, - }; - Some(vec![want; usize::from(lanes)]) - }, - &|g, w| g == w, - ); - } - } - } -} - -/// Class B: on a `half` result, held widened, [`nan::select`] of the canonical answer gives Metal's -/// `half` NaN `0x7E00` for every NaN lane, quiet or signaling, of either sign and any payload, by -/// either test, and keeps every other lane, infinities and zeros included. -#[test] -fn nan_select_answers_metals_half_nan() { - use super::nan::{self, NanAnswer}; - let halves: [u64; 16] = [ - 0x7E00, 0xFE00, 0x7C01, 0xFC01, 0x7DFF, 0xFFFF, 0x7FFF, 0x7E55, 0x7C00, 0xFC00, 0, 0x8000, - 0x3C00, 0xBC00, 0x0001, 0x7BFF, - ]; - for test in [NanTest::IsNan, NanTest::Bits] { - for lanes in [1u8, 3] { - let f = vec(float(16), lanes); - let cases: Vec = halves - .iter() - .map(|&h| vec![vec![h; usize::from(lanes)]]) - .collect(); - check_accept( - &format!("half {test:?} x{lanes}"), - &[f], - f, - &|fb, x| nan::select(fb, f, NanAnswer::Canonical, test, x[0], None), - &cases, - &|c| { - let h = arg(c, 0); - let want = if is_nan(float(16), h) { 0x7E00 } else { h }; - Some(vec![want; usize::from(lanes)]) - }, - &|g, w| g == w, - ); - } - } -} - -/// Class F: Metal's `fmin`, `fmax`, `min3`, `max3`, and `clamp` on `float` and `half` -/// ([`math::metal_min_max`]) answer an operand bit for bit, by either NaN test, on scalars and -/// vectors: a NaN loses, two NaNs and a tie of zeros answer the second operand, and a `float` -/// denormal compares as zero but is returned itself (`fmin(2^-149, +0)` is `+0`, `fmin(+0, -/// 2^-149)` is `2^-149`), as `nan_minmax`, `nan_minmax_fast`, their zeros-and-denormals cases, -/// `nan_half`, and `nan_half_fast` read on every lane. -#[test] -fn min_max_answer_metals_operand_bit_for_bit() { - let mut floats = nan_operands(); - floats.extend([ - 0x8000_0001, - 0x007F_FFFF, - 0x0080_0000, - 0x8080_0000, - 0x4000_0000, - ]); - let halves: Vec = vec![ - 0x7E00, 0xFE00, 0x7C01, 0xFC01, 0x7E55, 0x7C00, 0xFC00, 0, 0x8000, 0x3C00, 0xBC00, 0x0001, - 0x8001, 0x03FF, 0x0400, - ]; - let half_compared = |b: u64| f16_to_f64(b as u16); - let formats: [(u8, Vec, &dyn Fn(u64) -> f64); 2] = - [(32, floats, &f32_compared), (16, halves, &half_compared)]; - for (bits, vals, val) in formats { - let few: Vec = vals.iter().copied().step_by(2).collect(); - let triples: Vec = few - .iter() - .flat_map(|&a| { - let few = &few; - few.iter() - .flat_map(move |&b| few.iter().map(move |&c| vec![vec![a], vec![b], vec![c]])) - }) - .collect(); - for op in [ - FloatFn::Min, - FloatFn::Max, - FloatFn::Min3, - FloatFn::Max3, - FloatFn::Clamp, - ] { - let arity = op.arity(); - let cases = if arity == 2 { - pairs(&vals, &vals) - } else { - triples.clone() - }; - for test in [NanTest::IsNan, NanTest::Bits] { - for lanes in [1u8, 3] { - let f = vec(float(bits), lanes); - let n = usize::from(lanes); - let lane_cases: Vec = cases - .iter() - .map(|c| c.iter().map(|o| vec![o[0]; n]).collect()) - .collect(); - check_accept( - &format!("{op:?} f{bits} {test:?} x{lanes}"), - &vec![f; arity], - f, - &|fb, x| { - math::float_fn( - fb, - op, - f, - Contraction::Forbidden, - test, - x, - &Lib::instructions(), - ) - }, - &lane_cases, - &|c| { - let b: Vec = c.iter().map(|l| l[0]).collect(); - Some(vec![metal_min_max_ref(op, &b, val); n]) - }, - &|g, w| g == w, - ); - } - } - } - } -} - /// Class H: Metal's `half` `fmod` answers `+0` for a zero remainder of a nonzero dividend and the /// dividend itself for a zero one (`fmod(-2, 0.5)` and `fmod(-65504, 65504)` are `+0`, `fmod(-0, /// 1)` and `fmod(-0, inf)` are `-0`), as `nan_fmod_zero` and `nan_fmod_zero_fast` read on every @@ -2494,14 +2282,11 @@ fn half_nan_answers_follow_the_measured_states() { assert_eq!(cast_answer(op, from, to), None, "{op:?} {from:?} {to:?}"); } use crate::device::profile::NanEncoding; - assert!(A::Canonical.left_to(NanEncoding::MetalCanonical)); + assert!(A::Canonical.device_answers(NanEncoding::MetalCanonical)); for a in [A::CanonicalExact, A::Operand, A::OperandSign, A::DomainSign] { - assert!(!a.left_to(NanEncoding::MetalCanonical), "{a:?}"); + assert!(!a.device_answers(NanEncoding::MetalCanonical), "{a:?}"); } - for a in [A::Canonical, A::CanonicalExact] { - assert!(!a.left_to(NanEncoding::Device), "{a:?}"); - } - // Native device maths leaves every answer to the device. + // A device not measured to answer Metal's canonical NaN answers none of Metal's NaNs. for a in [ A::Canonical, A::CanonicalExact, @@ -2509,7 +2294,7 @@ fn half_nan_answers_follow_the_measured_states() { A::OperandSign, A::DomainSign, ] { - assert!(a.left_to(NanEncoding::Native), "{a:?}"); + assert!(!a.device_answers(NanEncoding::Native), "{a:?}"); } } @@ -2522,7 +2307,7 @@ const KHR_FACTS: super::FloatFacts = super::FloatFacts { }, metal_functions: false, device_denormals: false, - nan_native: false, + nans: crate::device::profile::NanEncoding::Native, native_min_max: false, }; @@ -4140,16 +3925,15 @@ fn the_minimum_and_maximum_family_follows_the_profile() { assert!(taken >= 1, "the MoltenVK capture takes it"); } -/// Where the library says the device's `NMin`, `NMax` and `NClamp` are Metal's -/// (`Lib::with_min_max`), each of the family is those instructions alone, with no NaN test; -/// elsewhere it is `math::metal_min_max`'s picks, with NaN tests and no such instruction. +/// Each of the minimum and maximum family is the device's `NMin`, `NMax` and `NClamp` alone, with +/// no NaN test. #[test] -fn the_minimum_and_maximum_family_takes_the_device_instructions_where_measured() { +fn the_minimum_and_maximum_family_takes_the_device_instructions() { // SPIR-V `OpExtInst`, `OpIsNan`; GLSL.std.450 `NMin`, `NMax`, `NClamp`. const OP_EXT_INST: u32 = 12; const OP_IS_NAN: u32 = 156; const DEVICE: [u32; 3] = [79, 80, 81]; - let counts = |op: FloatFn, f: Form, device: bool| -> (usize, usize) { + let counts = |op: FloatFn, f: Form| -> (usize, usize) { let m = kernel(&vec![f; op.arity()], f, &|fb, a| { math::float_fn( fb, @@ -4158,7 +3942,7 @@ fn the_minimum_and_maximum_family_takes_the_device_instructions_where_measured() Contraction::Forbidden, NanTest::IsNan, a, - &Lib::instructions().with_min_max(device), + &Lib::instructions(), ) }) .expect("kernel"); @@ -4185,16 +3969,12 @@ fn the_minimum_and_maximum_family_takes_the_device_instructions_where_measured() FloatFn::Max3, ] { for f in [float(32), float(16), vec(float(32), 4)] { - let (ext, nan) = counts(op, f, true); let want = if matches!(op, FloatFn::Min3 | FloatFn::Max3) { 2 } else { 1 }; - assert_eq!((ext, nan), (want, 0), "{op:?} on {f:?}, the device's"); - let (ext, nan) = counts(op, f, false); - assert_eq!(ext, 0, "{op:?} on {f:?}, picked"); - assert!(nan > 0, "{op:?} on {f:?}, picked: no NaN test"); + assert_eq!(counts(op, f), (want, 0), "{op:?} on {f:?}"); } } } diff --git a/crates/metal2vulkan/src/lower/arith/tests/color_write.rs b/crates/metal2vulkan/src/lower/arith/tests/color_write.rs index 01c1cb6a8..2cb97464d 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/color_write.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/color_write.rs @@ -434,76 +434,6 @@ fn scalar_and_half_outputs_round() { ); } -/// `color_write::half_bits` writes each half's own bits: every `half` widened (every NaN payload of -/// either sign, the denormals, both zeros and infinities), each value but a NaN through the -/// conversion to 16 bits and each NaN as `nan_codes`' code; a NaN no half widens to (its top ten -/// fraction bits zero) is the quiet NaN of its sign; and `HALF_BITS_WORDS` bounds the emission. -#[test] -fn half_bits_are_each_halfs_bits() { - use crate::spirv::ir::{ConvOp, Type}; - use crate::spirv::serialize::serialize; - // `half_bits`' lanes as their codes, widened to 32-bit integers. - let codes = |fb: &mut FunctionBuilder<'_>, f: Form, x: Value| -> BResult { - let h = color_write::half_bits(fb, f, x)?; - let lanes = |fb: &mut FunctionBuilder<'_>, width: u8| -> BResult<_> { - let elem = fb.module().ty(Type::Int { - width, - signed: false, - })?; - fb.module().ty(Type::Vector { elem, len: f.lanes }) - }; - let u16_ = lanes(fb, 16)?; - let u32_ = lanes(fb, 32)?; - let narrow = fb.convert(ConvOp::Bitcast, h, u16_)?; - fb.convert(ConvOp::UConvert, narrow, u32_) - }; - let h = vec(float(16), 4); - let out = vec(int(32), 4); - let cases: Vec = (0u64..0x10000) - .step_by(4) - .map(|b| vec![vec![b, b + 1, b + 2, b + 3]]) - .collect(); - check_accept( - "every half", - &[h], - out, - &|fb, x| codes(fb, h, x[0]), - &cases, - &|c| Some(c[0].clone()), - &|g, w| g == w, - ); - let f = vec(float(32), 4); - let low_nans = [0x7f80_0001u32, 0xff80_0001, 0x7f80_1fff, 0xffc0_0000]; - let cases = vec![vec![low_nans.iter().map(|&b| u64::from(b)).collect()]]; - check_accept( - "NaNs without a half's payload", - &[f], - out, - &|fb, x| codes(fb, f, x[0]), - &cases, - &|_| Some(vec![0x7e00, 0xfe00, 0x7e00, 0xfe00]), - &|g, w| g == w, - ); - // The routine's words, with its codes' widening (two conversions) charged to it too. - let size = |with: bool| -> usize { - let m = kernel(&[f], out, &|fb, x| match with { - true => codes(fb, f, x[0]), - false => { - let u = crate::lower::arith::ops::ty(fb, out)?; - fb.convert(ConvOp::Bitcast, x[0], u) - } - }) - .expect("build"); - serialize(m).expect("serialize").words.len() - }; - let words = size(true) - size(false); - assert!( - words as u64 <= color_write::HALF_BITS_WORDS, - "half_bits is {words} words, bound {}", - color_write::HALF_BITS_WORDS - ); -} - /// A word attachment's encode (`stage_io::word_color::encode`) stores Metal's word for every /// packed 16-bit layout: each lane rounded to `half`, then its code rounded to even /// (`WordAttachment::output_word`, which the M3 Max's draws and clears matched on every texel), diff --git a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs index 9c320a2de..d70c24111 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs @@ -750,13 +750,16 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) { } c }; - // `bfloat` keeps the device's `NMin` and `NMax`, which may give either zero; `half` is - // Metal's, bit for bit. - let picks = matches!( + // The device's `NMin`, `NMax` and `NClamp`, which may give either zero. + let loose = matches!( op, - FloatFn::Min | FloatFn::Max | FloatFn::Clamp | FloatFn::Min3 | FloatFn::Max3 + FloatFn::Min + | FloatFn::Max + | FloatFn::Clamp + | FloatFn::Min3 + | FloatFn::Max3 + | FloatFn::Saturate ); - let loose = picks && !is_half; let flush = exact_ok(f); let accept = |g: u64, w: u64| flush(g, w) || (loose && is_zero(f, g) && is_zero(f, w)); check_accept( @@ -799,10 +802,6 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) { FloatFn::Sign => 0.0, FloatFn::Saturate if x(0) > 0.0 => x(0).min(1.0), FloatFn::Saturate => 0.0, - _ if picks && is_half => { - let b: Vec = c.iter().map(|l| l[0]).collect(); - return Some(vec![metal_min_max_ref(op, &b, &|v| nval(f, v))]); - } FloatFn::Min => x(0).min(x(1)), FloatFn::Max => x(0).max(x(1)), FloatFn::Clamp => x(0).max(x(1)).min(x(2)), @@ -2887,13 +2886,13 @@ fn half_arithmetic_on_the_device_is_one_16_bit_instruction() { } } -/// Under the float controls (`QuantizeForm::Controlled`), where the profile leaves a NaN's bits to -/// the device (`ModuleBuilder::native_half_nans`, `NanMinMaxPolicy::Native`), `from_bits` is the +/// Under the float controls (`QuantizeForm::Controlled`), where the module leaves a NaN's bits to +/// the device (`ModuleBuilder::native_half_nans`, every profile so rounding), `from_bits` is the /// device's widening of the bits as a 16-bit float, with no integer decode: every half bit /// pattern, with junk above its 16 bits, reads as its exact `f32` value but a NaN, which reads as /// a NaN, one lane at a time and four at once, and `narrow::widens_bits` finds the widening. -/// Without the flag (the NaN switch's `NanMinMaxPolicy::Exact`) the integer decode stands: every -/// pattern exact, NaN payloads included, and `widens_bits` finds none. +/// Without the flag the integer decode stands: every pattern exact, NaN payloads included, and +/// `widens_bits` finds none. #[test] fn a_half_decode_under_the_float_controls_is_the_devices_widening() { use super::super::narrow::{f32_of_half_bits, from_bits, widens_bits}; diff --git a/crates/metal2vulkan/src/lower/arith/tests/round_texel.rs b/crates/metal2vulkan/src/lower/arith/tests/round_texel.rs index e7236b50e..52ba181ef 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/round_texel.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/round_texel.rs @@ -179,85 +179,12 @@ fn unsigned_compares(m: &crate::spirv::ir::TypedModule) -> usize { .count() } -/// Under native half rounding where the NaN switch asks for Metal's NaN (`NanMinMaxPolicy::Exact`, -/// `ModuleBuilder::texel_nans`), a texel's `half` keeps the NaN the device decoded, as under a -/// rounding that is Metal's: every half bit pattern, widened as a device that decodes a half-float -/// texel exactly hands it over, reads back as itself, bit for bit (NaNs of every sign and payload, -/// signalling ones included), in both native forms, one lane at a time and four at once; a wider -/// value rounds as the form does, a NaN staying a NaN; and the module holds the keep's one test of -/// the texel's bits, which it leaves out where the switch is off (the default). -#[test] -fn a_texel_keeps_its_nan_under_native_half_rounding_where_the_nan_switch_asks() { - use crate::spirv::builder::QuantizeForm; - let halves: Vec = (0..=0xFFFFu16).map(|h| vec![vec![widened(h)]]).collect(); - let lanes: Vec = (0..0x1_0000u32) - .step_by(4) - .map(|h| vec![(h..h + 4).map(|x| widened(x as u16)).collect()]) - .collect(); - let wider: Vec = half_probe_bits() - .into_iter() - .map(|b| vec![vec![b]]) - .collect(); - for q in [QuantizeForm::Converted, QuantizeForm::Device] { - let mut compares = [0usize; 2]; - for keep in [false, true] { - let what = format!("{q:?} native, texel NaNs kept {keep}"); - let body = move |lanes: u8| { - move |fb: &mut FunctionBuilder<'_>, x: &[Value]| -> BResult { - fb.module().set_quantize_form(q); - fb.module().set_native_half(true); - fb.module().set_texel_nans(keep); - texel(lanes)(fb, x) - } - }; - let m = kernel_with(&[float(32)], half(), &body(1), true, false) - .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); - compares[usize::from(keep)] = unsigned_compares(&m); - if keep { - check_accept( - &what, - &[float(32)], - half(), - &body(1), - &halves, - &|c| Some(vec![want(arg(c, 0))]), - &|g, w| g == w, - ); - check_accept( - &format!("{what}, half4"), - &[vec(float(32), 4)], - vec(half(), 4), - &body(4), - &lanes, - &|c| Some(c[0].iter().map(|w| want(*w)).collect()), - &|g, w| g == w, - ); - } - check_accept( - &format!("{what}, wider"), - &[float(32)], - half(), - &body(1), - &wider, - &|c| { - Some(vec![u64::from(f64_to_f16(f64::from(f32::from_bits( - arg(c, 0) as u32, - ))))]) - }, - &|g, w| g == w || (is_nan(half(), g) && is_nan(half(), w)), - ); - } - // The keep's one test of the texel's bits, there only where the switch asks. - assert_eq!(compares[1], compares[0] + 1, "{q:?}"); - } -} - -/// Under the float controls (`QuantizeForm::Controlled`), where the profile leaves a NaN's bits to -/// the device (`ModuleBuilder::native_half_nans`, `NanMinMaxPolicy::Native`), a texel's `half` is +/// Under the float controls (`QuantizeForm::Controlled`), where the module leaves a NaN's bits to +/// the device (`ModuleBuilder::native_half_nans`, every profile so rounding), a texel's `half` is /// the conversion's own rounding: every half-float texel and every wider value but a NaN reads as /// with the keep, to nearest even with half subnormals kept, and a NaN stays a NaN, without the -/// keep's unsigned compare of the texel's bits. Without the flag (the NaN switch's -/// `NanMinMaxPolicy::Exact`) the keep stands, and every half bit pattern reads back as itself. +/// keep's unsigned compare of the texel's bits. Without the flag the keep stands, and every half +/// bit pattern reads back as itself. #[test] fn a_texel_under_the_float_controls_takes_the_conversions_nan_by_default() { use crate::spirv::builder::QuantizeForm; diff --git a/crates/metal2vulkan/src/lower/arith/tests/specials.rs b/crates/metal2vulkan/src/lower/arith/tests/specials.rs index d7e123bd4..543fbf06a 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/specials.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/specials.rs @@ -662,11 +662,14 @@ fn fract_and_saturate_answer_as_metal() { f32_, &rows(|r| [u64::from(r.0), u64::from(r.2)]), ); - metal_answers( - FloatFn::Saturate, - f32_, - &rows(|r| [u64::from(r.0), u64::from(r.3)]), - ); + // `saturate` is the device's `NClamp(x, 0, 1)`: an `f32` denormal operand is the device's + // (Metal flushes it to `+0`), every other lane Metal's. + let normal = |(x, _): &Row| x[0] & 0x7F80_0000 != 0 || x[0] & 0x007F_FFFF == 0; + let saturate: Vec = rows(|r| [u64::from(r.0), u64::from(r.3)]) + .into_iter() + .filter(normal) + .collect(); + metal_answers(FloatFn::Saturate, f32_, &saturate); metal_answers( FloatFn::Fract, half, diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index 141bc97b0..37c77e2b1 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -105,7 +105,6 @@ fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult { // And every `half` rounding's quantize the device's form. mb.set_quantize_form(plan.families.arith.quantize); mb.set_native_half(plan.families.arith.native_half); - mb.set_texel_nans(plan.families.arith.texel_nans); mb.set_native_half_nans(plan.families.arith.native_half_nans); let mut d = Declared::default(); let modes = &mut d.modes; diff --git a/crates/metal2vulkan/src/lower/mesh/mod.rs b/crates/metal2vulkan/src/lower/mesh/mod.rs index adcae37ee..bef8a72cf 100644 --- a/crates/metal2vulkan/src/lower/mesh/mod.rs +++ b/crates/metal2vulkan/src/lower/mesh/mod.rs @@ -711,7 +711,6 @@ fn data_element(ty: NumTy) -> Result<(Element, IoType), Error> { numeric, components: lanes, source_bits: bits, - bits: 32, }, )) } @@ -846,7 +845,6 @@ fn target_index(cx: &mut SelectCx<'_>, which: TargetIndex) -> Result FieldShape { PushField::SlotBindOffset(_) | PushField::VertexBufferStride(_) => FieldShape::U32, // A texture's mipmap level count, an acceleration structure's instance count, the render // encoder's viewport count, the render pass's array length, a kernel stage-in buffer's - // bound stride, whether a storage texture's channels are 16-bit floats, its integer - // channels' widths. + // bound stride, a storage texture's integer channels' widths. PushField::TextureLevels(_) - | PushField::TextureHalfChannels(_) | PushField::TextureIntegerChannels(_) | PushField::InstanceCount(_) | PushField::ViewportCount diff --git a/crates/metal2vulkan/src/lower/sampler/emit.rs b/crates/metal2vulkan/src/lower/sampler/emit.rs index 1e9de79db..16a47c2a2 100644 --- a/crates/metal2vulkan/src/lower/sampler/emit.rs +++ b/crates/metal2vulkan/src/lower/sampler/emit.rs @@ -1426,7 +1426,7 @@ pub(super) fn sampled_value( cx, fb, (s, key), - (texture, &p.fetch, super::fetched::classes(s), true), + (texture, &p.fetch, super::fetched::CLASSES, true), image, &|fb, texels| super::fetched::plain_value(fb, s, texels), &|fb, si| fb.gather(si, coord, component, &ops), @@ -2644,7 +2644,7 @@ pub(super) fn held_value( } _ => None, }; - let held = match (half, float) { + Ok(match (half, float) { (Some(h), _) => { let access = match s.op { SampleOp::Gather { .. } => HalfForm::Read, @@ -2670,26 +2670,7 @@ pub(super) fn held_value( held_texel(fb, image.texel, form, x)? } (None, None) => held_texel(fb, image.texel, form, texel)?, - }; - // Under the NaN switch, Metal's NaN: the texel's own where the sample reads one texel of a - // texture of 16-bit float channels, else `0x7e00`. - let Some(class) = s.half_nans else { - return Ok(held); - }; - use crate::lower::texture::{NanClass, OneTexel}; - let (class, one) = match (class, s.one_texel) { - (NanClass::Never, _) | (_, OneTexel::Never) => (NanClass::Never, None), - (class, OneTexel::Always) => (class, None), - (class, OneTexel::Word(n)) => { - let word = sampler_word(cx, fb, Pixel::Spec(n))?; - (class, Some(word_reads_one(fb, word)?)) - } - (class, OneTexel::Heap(h)) => { - let word = sampler_word(cx, fb, Pixel::Heap(h))?; - (class, Some(word_reads_one(fb, word)?)) - } - }; - crate::lower::texture::metal_texel_nans(cx, fb, (class, one), texel, held) + }) } /// Whether sampler word `word` states a sampler that reads one texel of one level: nearest min and diff --git a/crates/metal2vulkan/src/lower/sampler/fetched.rs b/crates/metal2vulkan/src/lower/sampler/fetched.rs index cf79bfa20..8286c19cb 100644 --- a/crates/metal2vulkan/src/lower/sampler/fetched.rs +++ b/crates/metal2vulkan/src/lower/sampler/fetched.rs @@ -238,8 +238,7 @@ pub(super) fn select( (image, shape): (ImageRef, ImageShape), operand: Option, ) -> Result, Error> { - let half_gather = half_gather(cx, op, form); - if form.map(|f| f.conv) != Some(TexelConv::F32) && !half_gather { + if form.map(|f| f.conv) != Some(TexelConv::F32) { return Ok(None); } let gather = match op { @@ -256,9 +255,7 @@ pub(super) fn select( }; if cx.profile.device_samples() { cx.families.sampler.device_sampling = true; - if !half_gather { - return Ok(None); - } + return Ok(None); } let fetch = match (stat.map(|(r, _)| r), argument) { (Some(SamplerRef::Constexpr(words)), _) => { @@ -284,34 +281,9 @@ pub(super) fn select( Ok(fetch.map(|fetch| Plain { image, fetch })) } -/// Whether `op` is a gather with a `half` result whose texels the shader fetches where the bound -/// class is a 16-bit float one: where the NaN switch asks for Metal's NaN -/// (`NanMinMaxPolicy::Exact`, the profile's `TexelNanRoute::Metal`) on a device without Metal's -/// own sampler. Metal's gather hands back a 16-bit float texel's own NaN; a device's gather need -/// not (NVIDIA's hands back every NaN as `0x7fffffff`), and its fetch does -/// where its read does. -fn half_gather(cx: &SelectCx<'_>, op: &SampleOp, form: Option) -> bool { - use crate::device::profile::TexelNanRoute; - use crate::device::requirements::VkProperty; - matches!(op, SampleOp::Gather { dref: None, .. }) - && form.map(|f| f.conv) == Some(TexelConv::F16) - && cx.profile.fields().texel_nans == TexelNanRoute::Metal - && !cx - .profile - .fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler) -} - -/// The format classes (`BicubicTexels` bits) whose texels the shader fetches for plain access -/// `s`: the 32-bit float class, or for a `half` gather ([`half_gather`]) the half-float one. -pub(super) fn classes(s: &Sampling) -> u32 { - match (&s.op, s.texel.map(|f| f.conv)) { - (SampleOp::Gather { .. }, Some(TexelConv::F16)) => BicubicTexels::HALF, - _ => BicubicTexels::LINEAR, - } -} +/// The format classes (`BicubicTexels` bits) whose texels the shader fetches for a plain access: +/// the 32-bit float class. +pub(super) const CLASSES: u32 = BicubicTexels::LINEAR; /// How the shader fetches the texels of `op` (a gather, a sample through a sampler that reads one /// texel, its comparison taken out, or a comparison through nearest filters under a linear mip @@ -569,7 +541,7 @@ pub(super) fn heap( (_, Some(pixel)) => Some(super::emit::sampler_word(cx, fb, pixel)?), (_, None) => return Err(cx.fail("a word-addressed heap fetch without its word")), }; - let take = bits.test(fb, &t, classes(s))?; + let take = bits.test(fb, &t, CLASSES)?; let take = match word { Some(w) => match word_reach(fb, &t, s, &p.fetch, w)? { Some(r) => fb.binary(BinOp::LogicalAnd, take, r)?, diff --git a/crates/metal2vulkan/src/lower/sampler/mod.rs b/crates/metal2vulkan/src/lower/sampler/mod.rs index d48f7a040..aeb8ae2d1 100644 --- a/crates/metal2vulkan/src/lower/sampler/mod.rs +++ b/crates/metal2vulkan/src/lower/sampler/mod.rs @@ -677,10 +677,6 @@ pub struct Sampling { /// A `float` texel of the slot converts by the bound format's class (`float_texel`), where /// [`one_texel`](Self::one_texel) holds. pub float_texel: bool, - /// Where the NaN switch asks for Metal's NaN, how the access's `half` texel answers a NaN - /// texel (`texture::half_texel_nans`): by the class of the bound texture it names, and - /// whether the access reads one texel ([`one_texel`](Self::one_texel)). - pub half_nans: Option, /// A [`centred`](Self::centred) sample through a runtime or argument buffer's sampler with a /// texel offset, on a device without `VkProperty::MetalSampler`, which adds the offset to the /// texel it reads before addressing it: the texel's centre moves back by the offset on an @@ -1290,10 +1286,7 @@ impl Sampling { } else { 0 } - + self.heap_raw.as_ref().map_or(0, heap_raw::HeapRaw::words) - + self - .half_nans - .map_or(0, crate::lower::texture::NanClass::words)) + + self.heap_raw.as_ref().map_or(0, heap_raw::HeapRaw::words)) // The code a sampling routine holds is the routine's, counted once in the module. .saturating_sub(self.routed_words()) } diff --git a/crates/metal2vulkan/src/lower/sampler/select.rs b/crates/metal2vulkan/src/lower/sampler/select.rs index 0d013dd6f..b5dd52677 100644 --- a/crates/metal2vulkan/src/lower/sampler/select.rs +++ b/crates/metal2vulkan/src/lower/sampler/select.rs @@ -2443,20 +2443,6 @@ fn select_one( // `half` texel's on every profile, a `float` one's where it converts. let half_converts = half && !raw && !matches!(op, SampleOp::Bicubic(_)) && !device; let converts = half_converts || float_texel; - // Under the NaN switch, Metal's NaN of a `half` texel: by the class of the texture bound and, - // where a runtime sampler's word decides, whether the word reads one texel. Not of an sRGB - // raw texel, which decodes exactly to no NaN (`held_value` takes it first). - let half_nans = match half && !raw { - true => crate::lower::texture::texel_nans_class(cx, image, shape, one_texel)?, - false => None, - }; - // A depth texture's NaN is `0x7e00` whatever the sampler. - let by_word = half_nans.is_some_and(|c| c != crate::lower::texture::NanClass::Never); - if let (crate::lower::texture::OneTexel::Word(n), true) = (one_texel, by_word) { - if let Some(s) = cx.families.sampler.slots.get_mut(&n) { - s.texels = true; - } - } if let (crate::lower::texture::OneTexel::Word(n), true, ImageRef::Slot(_)) = (one_texel, converts, image) { @@ -2833,7 +2819,6 @@ fn select_one( one_texel, half_texel: half_converts && !shape.depth, float_texel, - half_nans, centre_offset, unmapped, heap_raw: None, diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index ace0e372e..5ca8358f7 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -550,9 +550,6 @@ pub struct SelectCx<'a> { func: FuncId, /// Whether each instruction's result is observed, by `InstId` ([`observed_results`]). observed: Vec, - /// Whether each instruction's result may carry its NaN's bits to an observation, by `InstId` - /// (`arith::nan::observed_payloads`). - nan_payloads: Vec, } impl SelectCx<'_> { @@ -657,15 +654,6 @@ impl SelectCx<'_> { .copied() .unwrap_or(true) } - - /// Whether the result of instruction `id` may carry its NaN's bits to an observation: read - /// by an instruction or terminator that does not drop them (`arith::nan::drops_payload`). - pub fn nan_payload_observed(&self, id: InstId) -> bool { - self.nan_payloads - .get(id.raw() as usize) - .copied() - .unwrap_or(true) - } } /// Whether each instruction's result is observed, by `InstId`: read by an instruction or @@ -1208,15 +1196,6 @@ pub fn select( } }; let root_bytes = root_sets.charged(); - let nan_payloads = match arith::nan::observed_payloads(e, e.func, body, m) { - Ok(n) => n, - Err(err) => { - m.release(observed_bytes); - m.release(root_bytes); - return Err(err); - } - }; - let nan_bytes = nan_payloads.len(); let cx = SelectCx { entry: e, body, @@ -1250,12 +1229,10 @@ pub fn select( phis: access::phis::PhiFacts::default(), func: e.func, observed, - nan_payloads, }; let result = select_entry(cx, body, func.params.len(), m); m.release(observed_bytes); m.release(root_bytes); - m.release(nan_bytes); result } diff --git a/crates/metal2vulkan/src/lower/stage_io/color_write.rs b/crates/metal2vulkan/src/lower/stage_io/color_write.rs index 44f6cb507..98de63923 100644 --- a/crates/metal2vulkan/src/lower/stage_io/color_write.rs +++ b/crates/metal2vulkan/src/lower/stage_io/color_write.rs @@ -28,10 +28,9 @@ //! Metal's where the profile takes `DriverDeviation::MetalColorWrites`, and a lane's the function //! rounds to nearest even (its NaN `0x7fc00000`) where it takes `MetalFloatColorNans`; a `half` //! output's (held widened, its payload in the significand's top bits) where it takes -//! `MetalHalfColorNans`, or where the function writes it through a 16-bit output (below); -//! elsewhere the module records the note (`runtime_lane::color_writes`: ANV and RADV store -//! `0xfe00`, from a 16-bit output too, lavapipe quiets or canonicalizes a `half` NaN, MoltenVK -//! canonicalizes it from a 32-bit output). +//! `MetalHalfColorNans`; elsewhere the module records the note (`runtime_lane::color_writes`: +//! ANV and RADV store `0xfe00`, lavapipe quiets or canonicalizes a `half` NaN, MoltenVK +//! canonicalizes it). //! //! On a profile that stores Metal's codes itself (`VkProperty::MetalColorWrites`) the map holds //! only half-float channels (`pipeline::color_writes`): only the NaN note is recorded, and the @@ -48,31 +47,14 @@ //! as -1.0 (`DriverDeviation::MetalNorm16ColorWrites`: RADV on the Radeon 780M). //! //! An attachment no lane of which rounds is not listed as rounded: it keeps its Vulkan blend of -//! one and zero, through which the facts were measured too. A write in the storage form, or -//! through a 16-bit output, records the device's conversion: the facts are of the device's -//! conversion of an output variable. A storage write the shader blends into a 16-bit float -//! attachment gives every NaN as `0x7fc00000`, which the storage image's store converts: Metal's -//! `0x7e00` where the profile takes `DriverDeviation::MetalFloatStorageNans` (the module requires -//! its property), else the device's NaN, noted `PrecisionNote::DeviceNanEncoding` (ANV stores -//! `0xfe00`). -//! -//! Where the device does not store the output's NaN as Metal does, but is measured to store a -//! 16-bit output's bits unchanged (`DriverDeviation::HalfColorOutputBits`: MoltenVK 1.4.1 on the -//! M3 Max and the M4), its conversion to 16 bits is Metal's `half(float)` -//! (`DriverDeviation::MetalHalfConversion`), and the profile declares 16-bit outputs -//! (`storageInputOutput16`, with `shaderInt16` and `shaderFloat16`), an output to an attachment -//! whose every channel written is half-float is written as the bits of its half, through a 16-bit -//! output variable ([`half_output`]): each lane converted to 16 bits by that conversion, a NaN as -//! its own payload's code by integer operations (`arith::color_write::half_bits`), so no -//! conversion of the device's chooses the NaN, the NaN note is not recorded, and the module -//! requires `VkProperty::HalfColorOutputBits` and `VkProperty::MetalHalfConversion`. An attachment -//! a lane of which rounds is listed as rounded (`rounded_colors`), and one whose output is written -//! so but rounds nothing as written as a half's bits (`half_bit_colors`), its own notice; either -//! takes no Vulkan blend of one and zero. On a device not measured so the output stays 32-bit: ANV -//! and RADV store every NaN of a 16-bit output as `0xfe00` too, so the route would change nothing -//! there. +//! one and zero, through which the facts were measured too. A write in the storage form records +//! the device's conversion: the facts are of the device's conversion of an output variable. A +//! storage write the shader blends into a 16-bit float attachment gives every NaN as +//! `0x7fc00000`, which the storage image's store converts: Metal's `0x7e00` where the profile takes +//! `DriverDeviation::MetalFloatStorageNans` (the module requires its property), else the device's +//! NaN, noted `PrecisionNote::DeviceNanEncoding` (ANV stores `0xfe00`). An attachment a lane of +//! which rounds is listed as rounded (`rounded_colors`), and takes no Vulkan blend of one and zero. -use crate::air::abi::{AbiInt, OutputRole}; use crate::device::requirements::VkProperty; use crate::error::DriverDeviation; use crate::lower::arith::color_write; @@ -106,7 +88,6 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) { let metal = cx .profile .takes_driver_deviation(DriverDeviation::MetalColorWrites); - let half = half_output(cx, color, f); let storage = crate::lower::fragment::writes_through_storage(cx, color); // A storage write the shader blends into a 16-bit float attachment stores the blend's `half` // in every channel, which the device converts exactly, but for a NaN: no conversion of an @@ -122,7 +103,7 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) { let mut relied = BTreeSet::new(); for (slot, rule) in lanes.iter_mut().zip(rules).take(usize::from(f.lanes)) { let Some(rule) = rule else { continue }; - nans |= !shader_blended && color_writes::half_float(rule) && !nan_kept(cx, rule, f, half); + nans |= !shader_blended && color_writes::half_float(rule) && !nan_kept(cx, rule, f); if metal && rule == color_writes::HALF { continue; } @@ -144,7 +125,7 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) { (rule @ ChannelWrite::FloatNearestEven { .. }, Some(_)) => *slot = Some(rule), (ChannelWrite::BlendedNearestEven { .. }, _) => blended |= !shader_blended, (ChannelWrite::Device, _) => device |= !shader_blended, - (rule, Some(fmt)) => match conversion(cx, rule, fmt, half || storage, &mut relied) { + (rule, Some(fmt)) => match conversion(cx, rule, fmt, storage, &mut relied) { Conversion::Metal => {} Conversion::MetalButNan => nans |= !shader_blended, Conversion::Device => device |= !shader_blended, @@ -163,24 +144,13 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) { if nans { cx.precision.insert(PrecisionNote::DeviceNanEncoding); } - if half { - cx.families.stage_io.halves.insert(color); - relied.extend([ - VkProperty::HalfColorOutputBits, - VkProperty::MetalHalfConversion, - ]); - } cx.families.stage_io.color_properties.extend(relied); - let rounds = lanes.iter().any(Option::is_some); - let sp = &mut cx.families.stage_io; - if rounds { - sp.rounded.insert(color, lanes); + if !lanes.iter().any(Option::is_some) { + return; } - let listed = match (rounds, half) { - (true, _) => &mut sp.interface.rounded_colors, - (false, true) => &mut sp.interface.half_bit_colors, - (false, false) => return, - }; + let sp = &mut cx.families.stage_io; + sp.rounded.insert(color, lanes); + let listed = &mut sp.interface.rounded_colors; if let Err(at) = listed.binary_search(&color) { listed.insert(at, color); } @@ -217,8 +187,7 @@ enum Conversion { /// How the device converts a lane of an output of `fmt` to a channel of rule `rule` (`own`: the /// function writes the output otherwise than as a value of its output variable the device -/// converts, as a half's bits through a 16-bit output, [`half_output`], or as a texel of a storage -/// image, which no fact measures): as Metal does where the profile takes the deviation measuring +/// converts, as a texel of a storage image, which no fact measures): as Metal does where the profile takes the deviation measuring /// it, whose property the module then relies on (`relied`), else the device's own: /// /// - a `float` output to a half-float or unsigned small float channel where the profile takes @@ -254,14 +223,13 @@ fn conversion( } /// Whether the device stores the NaN a fragment function writes to a half-float channel of rule -/// `rule` from its output of form `f` as Metal does (the module docs; `half`: written as a half's -/// bits, [`half_output`]): a `float` output's where the profile takes +/// `rule` from its output of form `f` as Metal does (the module docs): a `float` output's where the +/// profile takes /// `DriverDeviation::MetalColorWrites`, or where the function rounds the lane /// (`color_writes::HALF_NEAREST`), whose NaN `0x7fc00000` it then stores as Metal's `0x7e00` /// under `MetalFloatColorNans` (the output's own NaN, unrounded, it is not measured to); a `half` -/// output's where it takes `MetalHalfColorNans`, or written as a half's bits. Another output stores -/// no NaN of its own there. -fn nan_kept(cx: &SelectCx<'_>, rule: ChannelWrite, f: Form, half: bool) -> bool { +/// output's where it takes `MetalHalfColorNans`. Another output stores no NaN of its own there. +fn nan_kept(cx: &SelectCx<'_>, rule: ChannelWrite, f: Form) -> bool { let takes = |d| cx.profile.takes_driver_deviation(d); match f.float_fmt() { Some(FloatFmt::F32) => { @@ -269,74 +237,11 @@ fn nan_kept(cx: &SelectCx<'_>, rule: ChannelWrite, f: Form, half: bool) -> bool || (rule == color_writes::HALF_NEAREST && takes(DriverDeviation::MetalFloatColorNans)) } - Some(FloatFmt::Half) => half || takes(DriverDeviation::MetalHalfColorNans), - _ => true, - } -} - -/// Whether the device stores the NaN of a fragment function's output of form `f` to a -/// half-float channel as Metal does, for [`half_output`]: a `float` output's where the profile -/// takes `DriverDeviation::MetalFloatColorNans` or `MetalColorWrites`, a `half` output's where it -/// takes `MetalHalfColorNans`. Another output stores no NaN of its own there. -fn metal_nans(cx: &SelectCx<'_>, f: Form) -> bool { - let takes = |d| cx.profile.takes_driver_deviation(d); - match f.float_fmt() { - Some(FloatFmt::F32) => { - takes(DriverDeviation::MetalColorWrites) || takes(DriverDeviation::MetalFloatColorNans) - } Some(FloatFmt::Half) => takes(DriverDeviation::MetalHalfColorNans), _ => true, } } -/// Whether a fragment function writes its output of form `f` (dual-source index 0) to color -/// attachment `color` as the bits of the half Metal stores, through a 16-bit output variable -/// (the module docs): the output is `float` or `half` and the device does not store its NaN as -/// Metal does, but stores a 16-bit output's bits unchanged -/// (`DriverDeviation::HalfColorOutputBits`); its conversion to 16 bits is Metal's `half(float)` -/// (`narrow::QuantizeForm::Converted`: `DriverDeviation::MetalHalfConversion` and `shaderFloat16`, -/// not native half rounding's conversion); every channel of the attachment it writes is half-float -/// (`color_writes::HALF`), none the device's; the profile declares 16-bit outputs -/// (`storageInputOutput16`) and the `Int16` arithmetic that builds a NaN's code (a channel that -/// rounds to nearest even, `color_writes::HALF_NEAREST`, is half-float too); and the -/// function writes the attachment through an output variable, with no dual-source second -/// output beside it. -pub(super) fn half_output(cx: &SelectCx<'_>, color: u32, f: Form) -> bool { - let Some(rules) = cx.inputs.color_writes.get(&color) else { - return false; - }; - let leaf = cx.profile.fields().leaf; - let written = || rules.iter().take(usize::from(f.lanes)); - let dual = cx.entry.ep.outputs.iter().any(|o| { - matches!( - o.role, - OutputRole::RenderTarget { - attachment: AbiInt::Const(a), - index: 1, - .. - } if a == color - ) - }); - cx.stage == Stage::Fragment - && matches!(f.float_fmt(), Some(FloatFmt::F32 | FloatFmt::Half)) - && !metal_nans(cx, f) - && cx - .profile - .takes_driver_deviation(DriverDeviation::HalfColorOutputBits) - && crate::lower::arith::narrow::quantize_form(cx.profile) - == crate::spirv::builder::QuantizeForm::Converted - // The measured conversion, not native half rounding's. - && cx - .profile - .takes_driver_deviation(DriverDeviation::MetalHalfConversion) - && leaf.input_output_16bit - && leaf.int16 - && written().any(Option::is_some) - && written().flatten().all(|&r| color_writes::half_float(r)) - && !dual - && !crate::lower::fragment::writes_through_storage(cx, color) -} - /// The words of the planned roundings, each emitted once per return. pub(super) fn words(rounded: impl IntoIterator; 4]>) -> u64 { rounded.into_iter().map(|r| color_write::words(&r)).sum() diff --git a/crates/metal2vulkan/src/lower/stage_io/extended_color.rs b/crates/metal2vulkan/src/lower/stage_io/extended_color.rs index dc15b383b..8a42b9d90 100644 --- a/crates/metal2vulkan/src/lower/stage_io/extended_color.rs +++ b/crates/metal2vulkan/src/lower/stage_io/extended_color.rs @@ -87,7 +87,6 @@ pub(super) fn plan( numeric: IoNumeric::Uint, components: e.form.raw_components() as u8, source_bits: 32, - bits: 32, })) } diff --git a/crates/metal2vulkan/src/lower/stage_io/fetch.rs b/crates/metal2vulkan/src/lower/stage_io/fetch.rs index 5cb742f56..c45dd7832 100644 --- a/crates/metal2vulkan/src/lower/stage_io/fetch.rs +++ b/crates/metal2vulkan/src/lower/stage_io/fetch.rs @@ -74,7 +74,7 @@ use crate::error::{DescriptorError, Error, Feature, LowerFamily, Unsupported}; use crate::lower::access::pulled::{self, SourceRead}; -use crate::lower::arith::{exact_division, nan, narrow, ops, FloatFmt, Form, Held}; +use crate::lower::arith::{exact_division, narrow, ops, FloatFmt, Form, Held}; use crate::lower::dispatch; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; @@ -472,6 +472,7 @@ pub(super) fn select( return Err(not_lowered()); } class_match(encoding, form.is_float(), attribute)?; + narrow_float_nans(cx, encoding, form); let s = slot(Stage::Vertex, buffer); let draw_parameters = cx.profile.fields().draw_parameters; // The indexed capture form's per-vertex element is the vertex its index names. @@ -773,6 +774,18 @@ fn components(fb: &mut FunctionBuilder<'_>, e: Encoding, raw: SValue) -> BResult Ok(out) } +/// Record `PrecisionNote::DeviceNanEncoding` for a read of an attribute of `encoding` as `float` +/// lanes of `form` where the encoding is a narrow float's ([`Encoding::widens_narrow_float`]): +/// Metal's fetch answers its canonical NaN, sign and payload dropped, where the decode carries the +/// 16-, 11- or 10-bit field's bits up into the payload. A `half` read keeps the field's own bits, +/// as Metal's does. +pub(super) fn narrow_float_nans(cx: &mut SelectCx<'_>, encoding: Encoding, form: Form) { + if encoding.widens_narrow_float() && form.float_fmt() == Some(FloatFmt::F32) { + cx.precision + .insert(crate::pipeline::artifact::PrecisionNote::DeviceNanEncoding); + } +} + /// The value of form `form` of the raw bytes `raw` of `encoding` (see the module docs). pub fn decode( fb: &mut FunctionBuilder<'_>, @@ -796,19 +809,6 @@ pub fn decode( *c = fb.convert(op, *c, ft)?; } } - // A narrow float's widening to `float` answers Metal's canonical NaN, sign and payload - // dropped (`nan::NanAnswer::CanonicalExact`, the widening class of Metal's NaN model), where - // ours carries the 16-, 11- or 10-bit field's bits up into the payload by construction and a - // device whose own widening the module takes may carry them too. Answered on the bits alone - // (`nan::canonical_on_bits`), which leaves no float operation for a driver that assumes no - // NaNs to fold: the answer here is read bit for bit. A `half` parameter is not widened at - // all: it keeps the fetched bits, as Metal's does, and for a field of another width - // `narrow::round` answers the canonical `half` NaN. - if encoding.widens_narrow_float() && form.float_fmt() == Some(FloatFmt::F32) { - for c in &mut comps { - *c = nan::canonical_on_bits(fb, f32_scalar(), *c)?; - } - } let scalar = Form { lanes: 1, ..form }; let exact_half = matches!(encoding, Encoding::Half { .. }) && form.float_fmt() == Some(FloatFmt::Half); diff --git a/crates/metal2vulkan/src/lower/stage_io/fetch/tests.rs b/crates/metal2vulkan/src/lower/stage_io/fetch/tests.rs index 0f0dd273b..b1927094f 100644 --- a/crates/metal2vulkan/src/lower/stage_io/fetch/tests.rs +++ b/crates/metal2vulkan/src/lower/stage_io/fetch/tests.rs @@ -723,18 +723,13 @@ fn every_ten_and_two_bit_code_is_correctly_rounded() { } } -/// A narrow float's widening to a `float` parameter answers Metal's canonical NaN, sign and -/// payload dropped, while a `half` parameter keeps the fetched `half`'s own bits. -/// -/// Metal's answer, from `vertex-format-float4`'s and `attribute-format-fetches`' recordings of -/// plain Metal on an M3 Max under macOS 27.0.1: the `half` codes `0x7E01` and `0xFE01` both reach -/// a `float` attribute as `0x7FC00000`, and so does a `FloatRG11B10` field whose 5-bit exponent -/// is all ones; the same `half` codes reach a `half` attribute as themselves +/// A narrow float's widening to a `float` parameter carries a NaN field's sign and payload up into +/// the `f32` NaN (the device's NaN encoding, `PrecisionNote::DeviceNanEncoding`, where Metal answers +/// `0x7FC00000`), while a `half` parameter keeps the fetched `half`'s own bits, as Metal's does /// (`vertex-format-half4`). Every finite, zero, subnormal and infinite code is bit-exact either /// way, which `every_format_decodes_exactly` holds. #[test] -fn a_narrow_floats_widening_answers_metals_canonical_nan() { - const CANONICAL: u32 = 0x7FC0_0000; +fn a_narrow_floats_widening_carries_the_fields_nan_bits() { /// The `f32` bits of a `half` whose exponent field is all ones, by the IEEE widening: the /// sign, an all-ones `f32` exponent, and the 10-bit mantissa in the top of the 23-bit one. fn widened(h: u16) -> u32 { @@ -754,11 +749,7 @@ fn a_narrow_floats_widening_answers_metals_canonical_nan() { let e = encoding(VertexFormat::Half4).expect("encoding"); let m = module(e, float(4), Elem::Constant, 0, check); let got = run(&m, &data, [0, 0, 0, 0], 4); - assert_eq!( - got, - [CANONICAL, CANONICAL, CANONICAL, f32::INFINITY.to_bits()], - "Half4 into float4 {check:?}" - ); + assert_eq!(got, halves.map(widened), "Half4 into float4 {check:?}"); // The same codes into a `half` parameter, held widened: their own bits, as Metal's // `half` attribute keeps them. let m = module(e, half_form(4), Elem::Constant, 0, check); @@ -767,9 +758,10 @@ fn a_narrow_floats_widening_answers_metals_canonical_nan() { let e = encoding(VertexFormat::FloatRG11B10).expect("encoding"); let m = module(e, float(4), Elem::Constant, 8, check); let got = run(&m, &data, [0, 0, 0, 0], 4); + // Each field's mantissa in the top of the `f32` one: six bits, six, then five. assert_eq!( got, - [CANONICAL, CANONICAL, CANONICAL, 1.0f32.to_bits()], + [0x7FFE_0000, 0x7FFE_0000, 0x7FFC_0000, 1.0f32.to_bits()], "FloatRG11B10 into float4 {check:?}" ); } diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index 6b30a1aca..4d0b8ce75 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -193,9 +193,6 @@ pub enum IoObject { numeric: IoNumeric, components: u8, deco: IoDecor, - /// Declared as 16-bit `half` lanes: a color output the function writes as the bits of - /// the half Metal stores (`color_write::half_output`). - half: bool, }, /// A builtin variable. Builtin { @@ -268,12 +265,6 @@ pub enum Source { /// the variable, declared `Flat`, read as Metal's interpolation returns such a value /// ([`metal_interpolated_constant`]). Uniform(Link), - /// A fixed-function vertex attribute of a narrow-float Metal format (a `half` format, or - /// `FloatRG11B10`; `VertexFetch::FixedFunction`'s `narrow_float`) read as `float`: the - /// variable, with Metal's canonical NaN where the device's own widening of the field left a - /// NaN, whose payload and sign Metal's fetch drops (`nan::canonical_on_bits`). Every finite, - /// zero, subnormal and infinite code the widening delivers passes through. - WidenedAttribute(Link), /// A fragment function's `[[primitive_id]]` under `LoweringInputs::quad_primitive_ids`: /// Vulkan's `PrimitiveId` (the variable) shifted right by one, the quad of the list's /// triangle, as Metal counts one primitive a quad of its private quads and quad strip. @@ -409,9 +400,6 @@ pub struct StageIoPlan { /// (`color_write`), through an output variable or in the storage form: each by its rule, a /// half-float channel's under `TextureWriteRoundingMode::NearestEven`. pub rounded: BTreeMap; 4]>, - /// The color attachments whose output the function writes as the bits of the half Metal - /// stores, through a 16-bit output variable (`color_write::half_output`). - pub halves: BTreeSet, /// The measured driver deviations, as their properties, a fragment function's color writes /// rely on: channels that record no device conversion because the device converts them as /// Metal does (`color_write`). The module requires them. @@ -1198,7 +1186,6 @@ pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult< | Source::CapturedBaseVertex(_) | Source::Merged { .. } | Source::Uniform(_) - | Source::WidenedAttribute(_) | Source::QuadPrimitive(_) => None, }) .collect(); @@ -1292,12 +1279,6 @@ pub fn param_value( let x = metal_interpolated_constant(fb, link.form, x)?; return narrow::round(fb, link.form, x); } - Some(Source::WidenedAttribute(link)) => { - let p = pointer(cx, fb, &link)?; - let x = fb.load(p, MemAccess::default())?; - let x = crate::lower::arith::nan::canonical_on_bits(fb, link.form, x)?; - return to_lowered(cx, fb, &link, x); - } Some(Source::QuadPrimitive(link)) => { let p = pointer(cx, fb, &link)?; let x = fb.load(p, MemAccess::default())?; @@ -2733,16 +2714,10 @@ fn io_elem(mb: &mut ModuleBuilder, numeric: IoNumeric) -> BResult { } /// Store output part `x` (in its lowered representation, which is the interface type, except a -/// `bool`, carried as `uint` 1 or 0, a 32-bit integer declared `int`, whose bits are stored by -/// `OpBitcast`, and a color output declared `half`, whose half's bits are stored) through `link`. +/// `bool`, carried as `uint` 1 or 0, and a 32-bit integer declared `int`, whose bits are stored by +/// `OpBitcast`) through `link`. fn store(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, link: &Link, x: SValue) -> BResult<()> { - let half = matches!( - cx.plan.families.stage_io.objects.get(link.object), - Some(IoObject::User { half: true, .. }) - ); - let x = if half { - crate::lower::arith::color_write::half_bits(fb, link.form, x)? - } else if bool_as_uint(cx, link) { + let x = if bool_as_uint(cx, link) { let one = ops::splat(fb, uint_lanes(link.form), 1)?; let zero = ops::splat(fb, uint_lanes(link.form), 0)?; fb.select(x, one, zero)? @@ -2818,12 +2793,8 @@ pub fn declare( numeric, components, deco, - half, } => { - let elem = match half { - true => mb.ty(SType::Float { width: 16 })?, - false => io_elem(mb, *numeric)?, - }; + let elem = io_elem(mb, *numeric)?; let ty = if *components == 1 { elem } else { diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index 495f87a69..da4d47dcf 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -171,7 +171,6 @@ pub(super) fn io_type(f: Form) -> IoType { }, components: f.lanes, source_bits: f.bits(), - bits: 32, } } @@ -206,7 +205,6 @@ fn user( numeric: ty.numeric, components: ty.components, deco, - half: ty.bits == 16, }; // One key per direction: a second, different declaration of the same key is not a Metal // interface. @@ -433,7 +431,6 @@ pub fn param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> { let mut at_loop_sample = false; let mut uniform = false; let mut quad_primitive = false; - let mut widened = false; let link = match (&b.role, stage) { // A merged draw's vertex reads its corner's command's draw values. ( @@ -486,15 +483,16 @@ pub fn param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> { return Ok(()); } // The device's fixed-function input widens a narrow-float format with a widening of - // its own, which carries the field's bits up into the `float` payload; Metal's fetch - // answers its canonical NaN. A `float` parameter's load is canonicalized - // (`Source::WidenedAttribute`); a `half` one keeps the fetched code's own bits, as - // Metal's `half` attribute does, so it is loaded as it is. + // its own, which may carry the field's bits up into the `float` payload; Metal's fetch + // answers its canonical NaN. A `float` parameter's NaN is the device's, noted; a + // `half` one keeps the fetched code's own bits, as Metal's `half` attribute does. let narrow_float = matches!( entry, Some(VertexFetch::FixedFunction { narrow_float: true }) ); - widened = narrow_float && f.float_fmt() == Some(FloatFmt::F32); + if narrow_float && f.float_fmt() == Some(FloatFmt::F32) { + cx.precision.insert(PrecisionNote::DeviceNanEncoding); + } let key = VaryingKey::attribute(index); let sp = &mut cx.families.stage_io; let object = user( @@ -845,9 +843,7 @@ pub fn param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> { }; cx.families.stage_io.params.push(PlannedParam { param: b.param, - source: if widened { - Source::WidenedAttribute(link) - } else if at_loop_sample { + source: if at_loop_sample { Source::AtLoopSample(link) } else if at_pixel { Source::PixelCenter(link) @@ -949,7 +945,6 @@ fn zeroed_output( numeric, components: 4, source_bits: 32, - bits: 32, }; if let Some(rules) = cx.inputs.color_writes.get(&color).copied() { cx.families @@ -1395,7 +1390,6 @@ fn selected_index(sp: &mut StageIoPlan, index: RawIndex) -> Result numeric: IoNumeric::Uint, components: 1, source_bits: 32, - bits: 32, }; let deco = IoDecor { packed: true, @@ -1453,7 +1447,6 @@ pub(super) fn window_depth(sp: &mut StageIoPlan, dir: IoDir) -> Result Result, o: &OutputBinding, ty: AirTypeId) -> Result IoType { bits: 16, ..io }, - false => io, - }; // An extended-range attachment's raw texel, through a variable of its raw components, // and a word attachment's word; the interface keeps the Metal output's type. let declared = match super::word_color::plan(cx, attachment, index, f)? { @@ -3177,9 +3163,6 @@ const UNIFORM_WORDS: u64 = 64; /// The words a use of a [`Source::QuadPrimitive`] parameter adds to a load: the shift and its /// constant. const QUAD_PRIMITIVE_WORDS: u64 = 8; -/// The words a use of a [`Source::WidenedAttribute`] parameter adds to a load: the NaN test on the -/// bits, the select, and their constants. -const CANONICAL_NAN_WORDS: u64 = 32; /// The per-stage interface limits and the size estimate. pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { @@ -3357,13 +3340,9 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { .values() .filter(|i| matches!(i.kind, crate::air::ir::InstKind::Ret(_))) .count() as u64; - // Each return also rounds every color output that rounds, writes the halves' bits, and encodes - // the extended-range colors' texels. + // Each return also rounds every color output that rounds, and encodes the extended-range + // colors' texels. let rounding = super::color_write::words(sp.rounded.values().copied()) - .saturating_add( - crate::lower::arith::color_write::HALF_BITS_WORDS - .saturating_mul(sp.halves.len() as u64), - ) .saturating_add(super::extended_color::WORDS.saturating_mul(sp.extended.len() as u64)) .saturating_add( (sp.words_written.values()) @@ -3461,7 +3440,6 @@ fn param_words(cx: &SelectCx<'_>) -> u64 { loaded.push((p.param, USE_WORDS + PIXEL_WORDS)) } Source::Uniform(_) => loaded.push((p.param, USE_WORDS + UNIFORM_WORDS)), - Source::WidenedAttribute(_) => loaded.push((p.param, USE_WORDS + CANONICAL_NAN_WORDS)), Source::Pulled(r) => fetch_words = fetch_words.saturating_add(u64::from(r.words())), } } diff --git a/crates/metal2vulkan/src/lower/stage_io/stage_in.rs b/crates/metal2vulkan/src/lower/stage_io/stage_in.rs index 2087b5301..602a2b539 100644 --- a/crates/metal2vulkan/src/lower/stage_io/stage_in.rs +++ b/crates/metal2vulkan/src/lower/stage_io/stage_in.rs @@ -116,6 +116,7 @@ fn select( if fetch::class_match(encoding, form.is_float(), attribute).is_err() { return Err(not_lowered()); } + fetch::narrow_float_nans(cx, encoding, form); let layout = f.buffer_index; let rate = |rate: u32| -> Result { match rate { diff --git a/crates/metal2vulkan/src/lower/stage_io/word_color.rs b/crates/metal2vulkan/src/lower/stage_io/word_color.rs index 2d7ff41ac..ed8cf75f0 100644 --- a/crates/metal2vulkan/src/lower/stage_io/word_color.rs +++ b/crates/metal2vulkan/src/lower/stage_io/word_color.rs @@ -96,7 +96,6 @@ pub(super) fn plan( numeric: IoNumeric::Uint, components: 1, source_bits: 32, - bits: 32, })) } diff --git a/crates/metal2vulkan/src/lower/tessellation/mod.rs b/crates/metal2vulkan/src/lower/tessellation/mod.rs index 94b8479a1..896932728 100644 --- a/crates/metal2vulkan/src/lower/tessellation/mod.rs +++ b/crates/metal2vulkan/src/lower/tessellation/mod.rs @@ -631,7 +631,6 @@ fn pulled_read( }, components: form.lanes, source_bits: form.bits(), - bits: 32, }; sp.interface .pulled diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index f871bb6a9..f5679a51a 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -21,7 +21,7 @@ use super::slice::Slice; use super::{ Coord, ImageDecl, ImageRef, QueryKind, QueryOp, Read, TexelClass, TexelConv, TexelForm, }; -use super::{HalfNans, NullArm, Prelude, Switch, TextureStrategy, Write}; +use super::{NullArm, Prelude, Switch, TextureStrategy, Write}; use crate::memory::handles::{HANDLE_ALPHA_ONE, NEUTRAL_ELEMENT, NULL_HANDLE}; /// Emit strategy `s` of instruction `at` into the open block. @@ -911,9 +911,7 @@ fn from_image( StorageImageClass::RotateArgb => rotate_argb(fb, x, true)?, StorageImageClass::AlphaInRed => alpha_in_red(fb, x, true)?, // A `YCbCrWrite` slot is only written (`StorageImageClass::YCbCrWrite`). - StorageImageClass::HalfQuietNan - | StorageImageClass::SmallFloatQuietNan - | StorageImageClass::YCbCrWrite => x, + StorageImageClass::YCbCrWrite => x, // A half-float texel's bits, through its unsigned integer alias: Metal's read, whole. StorageImageClass::HalfBits => return half_bits_texel(fb, decl, form, x), // An `RGB9E5Float` word, through its `R32_UINT` alias, decoded exactly. @@ -1692,8 +1690,7 @@ fn int_lanes(fb: &mut FunctionBuilder<'_>, elem: TypeId, lanes: &[u32]) -> BResu /// `x` (`f32` lanes of form `f`) rounded to nearest even onto `RG11B10Float`'s channels, as /// Metal's integer store rounds them: red and green to six fraction bits, blue to five, unsigned (a /// negative value to 0), a finite value that rounds past the largest finite one held there (65024, -/// 64512), an infinity kept and a NaN quieted, which the float class's write stores as Metal's NaN -/// code (`StorageImageClass::SmallFloatQuietNan`). +/// 64512), an infinity kept and a NaN quieted, whose store the device converts. fn small_floats_nearest( fb: &mut FunctionBuilder<'_>, f: crate::lower::arith::legal::Form, @@ -1794,13 +1791,6 @@ pub fn to_image( crate::spirv::error::TypeRule::FunctionSignature, )) } - StorageImageClass::HalfQuietNan | StorageImageClass::SmallFloatQuietNan => { - match form.conv { - TexelConv::F32 => half_write(fb, decl.class, form, x)?, - // A `half` texel, held widened, is a half already: the device stores it exactly. - _ => x, - } - } StorageImageClass::YCbCrWrite => ycbcr_write_texel(fb, form, x)?, StorageImageClass::HalfBits => half_bits(fb, form, x)?, StorageImageClass::SharedExponentBits => shared_exponent_word(fb, form, x)?, @@ -1867,9 +1857,9 @@ fn ycbcr_write_texel(fb: &mut FunctionBuilder<'_>, form: TexelForm, x: SValue) - /// `uvec4`: each channel of its format a half's bits, a channel it lacks the integer the device's /// read gives, 0 or alpha 1, and Metal's out-of-bounds texel's likewise): each channel's half /// widened exactly (`narrow::from_bits`), Metal's `half` read of the half stored, a NaN's sign -/// and payload kept; for a `float` result every NaN `0x7fc00000`, Metal's `float` read of a half -/// NaN (the M3 Max: every NaN, fast and safe math); a lane the format lacks its -/// integer converted (0.0, alpha 1.0). +/// and payload kept, a `float` result's too, where Metal's `float` read of a half NaN is +/// `0x7fc00000` (the M3 Max: every NaN, fast and safe math; `PrecisionNote::DeviceNanEncoding`); a +/// lane the format lacks its integer converted (0.0, alpha 1.0). fn half_bits_texel( fb: &mut FunctionBuilder<'_>, decl: &ImageDecl, @@ -1898,13 +1888,6 @@ fn half_bits_texel( let one = f32s(fb, 1, 1.0)?; v = fb.composite_insert(one, v, &[3])?; } - if form.conv == TexelConv::F32 { - let f = Form { - held: Held::Float(FloatFmt::F32), - lanes: 4, - }; - v = quiet_nans(fb, f, v)?; - } match form.lanes { 1 => fb.composite_extract(v, &[0]), _ => Ok(v), @@ -1916,7 +1899,7 @@ fn half_bits_texel( /// payload included). A `half` texel's lanes are halves already, widened exactly; a `float` /// texel's are first rounded to a half, which no conversion of the device's makes through the /// alias: toward zero, as Metal stores it (`color_write::small_float`: past 65504 to 65504, an -/// infinity kept, every NaN [`QUIET_NAN`], whose bits are Metal's `0x7e00`). An integer texel is +/// infinity kept, every NaN `0x7fc00000`, whose bits are Metal's `0x7e00`). An integer texel is /// not one a half-float slot takes. fn half_bits(fb: &mut FunctionBuilder<'_>, form: TexelForm, x: SValue) -> BResult { use crate::lower::arith::legal::{FloatFmt, Form, Held}; @@ -2070,77 +2053,6 @@ pub(crate) fn rgb9e5_word(fb: &mut FunctionBuilder<'_>, x: SValue) -> BResult, - f: crate::lower::arith::legal::Form, - x: SValue, -) -> BResult { - let is_nan = fb.unary(crate::spirv::ir::UnOp::IsNan, x)?; - let nan = crate::lower::arith::ops::splat(fb, f, u64::from(QUIET_NAN))?; - fb.select(is_nan, nan, x) -} - -/// The channels of written `float` texel `x` (`f32` lanes of `form`) to a half-float or small -/// float image by class `class`: under `HalfQuietNan` and `SmallFloatQuietNan` the value as -/// computed, which the device's conversion rounds, but a NaN as [`QUIET_NAN`]. The NaN stores as -/// the device's encoding of [`QUIET_NAN`] (Metal's `0x7e00` where measured, -/// `DriverDeviation::MetalFloatStorageNans`). -fn half_write( - fb: &mut FunctionBuilder<'_>, - class: StorageImageClass, - form: TexelForm, - x: SValue, -) -> BResult { - use crate::lower::arith::legal::{FloatFmt, Form, Held}; - let f = Form { - held: Held::Float(FloatFmt::F32), - lanes: form.lanes, - }; - match class { - StorageImageClass::HalfQuietNan | StorageImageClass::SmallFloatQuietNan => { - quiet_nans(fb, f, x) - } - _ => Ok(x), - } -} - -/// Whether the texel class heap handle `handle` carries (its index in -/// `metal::texel_format::heap_classes`) is a half-float format's (a `bool`): the index is one of -/// [`heap_half_indices`](crate::metal::texel_format::heap_half_indices), the half-float family -/// without a packed field (`R16Float`, `RG16Float`, `RGBA16Float`; a small float's class carries -/// the field, and a swizzled texture's is `OTHER`, whose write the device converts). The index -/// alone answers it, so the module needs no table of the classes. -fn heap_half_format( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - handle: ValueId, -) -> BResult { - let indices = crate::metal::texel_format::heap_half_indices(); - heap_class_among(cx, fb, handle, &indices) -} - -/// Whether the texel class heap handle `handle` carries is a small float's (a `bool`): its index -/// is one of [`heap_small_float_indices`](crate::metal::texel_format::heap_small_float_indices), -/// as [`heap_half_format`] tests the half-float ones. -fn heap_small_float_format( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - handle: ValueId, -) -> BResult { - let indices = crate::metal::texel_format::heap_small_float_indices(); - heap_class_among(cx, fb, handle, &indices) -} - /// Whether the texel class index heap handle `handle` carries is one of `indices` (a `bool`). fn heap_class_among( cx: &mut EmitCx<'_>, @@ -2170,183 +2082,13 @@ fn heap_class_among( among.ok_or_else(|| cx.fail("no heap class of the family")) } -/// Whether a `half` texel's write keeps its widened half (a `bool`) where `nans` reads it at run -/// time: a heap element's handle class is a half-float format's ([`heap_half_format`]), a slot's -/// `PushField::TextureHalfChannels` is not 0. `None` where `nans` decides alone. -fn half_kept( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - nans: HalfNans, - image: &ImageRef, -) -> BResult> { - match (nans, image) { - (HalfNans::HeapClass, ImageRef::Heap { handle, .. }) => { - Ok(Some(heap_half_format(cx, fb, *handle)?)) - } - (HalfNans::SlotWord(slot), _) => { - let word = cx.push_field( - fb, - crate::pipeline::sym::PushField::TextureHalfChannels(slot), - )?; - let zero = u32s(fb, 1, 0)?; - Ok(Some(fb.binary(BinOp::INotEqual, word, zero)?)) - } - _ => Ok(None), - } -} - -/// `texel` (`f32` lanes of `form`) as a `half` texel's write stores it under `nans`: every NaN lane -/// [`QUIET_NAN`] (`0x7fc00000`) under [`HalfNans::Canonical`], and under a runtime choice where -/// `kept` ([`half_kept`]) is false; as it is elsewhere, the half widened. -fn half_nan_texel( - fb: &mut FunctionBuilder<'_>, - (nans, kept): (HalfNans, Option), - form: TexelForm, - texel: SValue, -) -> BResult { - use crate::lower::arith::legal::{FloatFmt, Form, Held}; - let f = Form { - held: Held::Float(FloatFmt::F32), - lanes: form.lanes, - }; - match (nans, kept) { - (HalfNans::Canonical, _) => quiet_nans(fb, f, texel), - (HalfNans::HeapClass | HalfNans::SlotWord(_), Some(kept)) => { - let canonical = quiet_nans(fb, f, texel)?; - let cond = match form.lanes { - 1 => kept, - n => { - let b = fb.module().ty(SType::Bool)?; - let ty = vec(fb, b, n)?; - fb.composite_construct(ty, &vec![kept; usize::from(n)])? - } - }; - fb.select(cond, texel, canonical) - } - _ => Ok(texel), - } -} - -/// Held `half` texel `held` of image texel `x` (`f32` lanes: the device's value, one texel's or -/// filtered) with Metal's NaN wherever `x` is a NaN (`texture::half_texel_nans`): `x` itself, the -/// device's decode of the texel, where the access reads one texel (`one`: `None` where it always -/// does, else a `bool`) of a texture the class says holds 16-bit float channels (`class`: a slot's -/// `TexelFormat` class of the half-float family without a packed field, -/// `metal::texel_format::half_channels`, or `TexelFormat::OTHER`, a format whose -/// conversion is not measured, whose NaN stays the device's decode as the module notes, -/// `DeviceNanEncoding`; a heap handle's class index, [`heap_half_format`]); [`QUIET_NAN`] -/// elsewhere, the `half` `0x7e00` held. The NaN test reads -/// `x`'s bits, as `narrow::round_texel`'s does, so it holds whatever float modes the device -/// compiles the module under. A `held` of one lane takes `x`'s first. -pub(crate) fn metal_texel_nans( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - (class, one): (super::NanClass, Option), - x: SValue, - held: SValue, -) -> BResult { - use super::NanClass; - use crate::metal::bicubic::BicubicTexels; - use crate::metal::texel_format::TexelFormat; - let lanes_of = |fb: &mut FunctionBuilder<'_>, v: SValue| -> BResult { - let ty = fb.value_ty(v)?; - Ok(match fb.module().types().get(ty)? { - SType::Vector { len, .. } => *len, - _ => 1, - }) - }; - let lanes = lanes_of(fb, held)?; - let x = match lanes_of(fb, x)? { - n if n == lanes => x, - _ if lanes == 1 => fb.composite_extract(x, &[0])?, - _ => return Err(cx.fail("Metal's NaN of a texel of fewer lanes than its held value")), - }; - let u = u32_ty(fb)?; - let ut = vec(fb, u, lanes)?; - let bits = fb.convert(ConvOp::Bitcast, x, ut)?; - let abs = u32s(fb, lanes, 0x7FFF_FFFF)?; - let mag = fb.binary(BinOp::BitwiseAnd, bits, abs)?; - let inf = u32s(fb, lanes, 0x7F80_0000)?; - let nan = fb.binary(BinOp::UGreaterThan, mag, inf)?; - let f = f32_ty(fb)?; - let canonical = splat(fb, f, lanes, u64::from(QUIET_NAN))?; - let halves = match class { - NanClass::Slot(index) => { - let Some(c) = texel_format_const(cx, index) else { - return Err(cx.fail(format!("texture slot {index} has no texel class"))); - }; - let word = fb.module().const_value(c)?; - let mask = u32s(fb, 1, BicubicTexels::HALF | TexelFormat::PACKED_MASK)?; - let half = u32s(fb, 1, BicubicTexels::HALF)?; - let family = fb.binary(BinOp::BitwiseAnd, word, mask)?; - let halves = fb.binary(BinOp::IEqual, family, half)?; - // A class whose conversion is not measured keeps the device's decode, as before. - let other = u32s(fb, 1, TexelFormat::OTHER.0)?; - let other = fb.binary(BinOp::IEqual, word, other)?; - Some(fb.binary(BinOp::LogicalOr, halves, other)?) - } - NanClass::Heap(handle) => Some(heap_half_format(cx, fb, handle)?), - NanClass::Never => None, - }; - let own = match (halves, one) { - (None, _) => None, - (Some(h), None) => Some(h), - (Some(h), Some(o)) => Some(fb.binary(BinOp::LogicalAnd, h, o)?), - }; - let kept = match own { - None => canonical, - Some(own) => { - let cond = match lanes { - 1 => own, - n => { - let b = fb.module().ty(SType::Bool)?; - let ty = vec(fb, b, n)?; - fb.composite_construct(ty, &vec![own; usize::from(n)])? - } - }; - fb.select(cond, x, canonical)? - } - }; - fb.select(nan, kept, held) -} - -/// The words [`heap_half_format`] emits, at most: the field's shift and mask, and per half-float -/// class its constant, comparison and union. -pub(crate) fn heap_half_words() -> u32 { - let n = crate::metal::texel_format::heap_half_indices().len() as u32; - 20 + 14 * n -} - -/// `texel` (`f32` lanes of `form`), written through a heap handle whose class is a half-float -/// format's where `is_half` ([`heap_half_format`]), as [`half_write`] writes it by class -/// `class` there; as it is elsewhere. -fn heap_halves( - fb: &mut FunctionBuilder<'_>, - (is_half, class): (SValue, StorageImageClass), - form: TexelForm, - texel: SValue, -) -> BResult { - let written = half_write(fb, class, form, texel)?; - let cond = match form.lanes { - 1 => is_half, - n => { - let b = fb.module().ty(SType::Bool)?; - let ty = vec(fb, b, n)?; - fb.composite_construct(ty, &vec![is_half; usize::from(n)])? - } - }; - fb.select(cond, written, texel) -} - /// The estimated words of a write's conversion by storage class `class` on four lanes: an 8-bit -/// sRGB format's codes ([`srgb_codes`]), a half-float image's NaN ([`half_write`]), a half-float -/// texel's bits ([`half_bits`]), an `RGB9E5Float` word ([`shared_exponent_word`]), or a YCbCr +/// sRGB format's codes ([`srgb_codes`]), a half-float texel's bits ([`half_bits`]), an `RGB9E5Float` word ([`shared_exponent_word`]), or a YCbCr /// texel's bits and mark ([`ycbcr_write_texel`]), none for the other classes' swizzles, which the /// write's base estimate covers. pub(crate) fn class_write_words(class: StorageImageClass) -> u32 { use crate::lower::arith::color_write; match class { - StorageImageClass::HalfQuietNan | StorageImageClass::SmallFloatQuietNan => QUIET_NAN_WORDS, StorageImageClass::YCbCrWrite => YCBCR_WRITE_WORDS, StorageImageClass::SrgbEncode | StorageImageClass::SrgbEncodeBgra => SRGB_WRITE_WORDS, StorageImageClass::SharedExponentBits => SHARED_EXPONENT_WORDS, @@ -3296,12 +3038,7 @@ fn read(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult< } (_, float) => float, }; - let held = from_image(cx, fb, &decl, r.texel, texel, (half, float))?; - // Under the NaN switch, Metal's NaN: a read reads one texel. - match r.half_nans { - Some(class) => metal_texel_nans(cx, fb, (class, None), texel, held)?, - None => held, - } + from_image(cx, fb, &decl, r.texel, texel, (half, float))? } }; // A swizzled texture's swizzle at a storage slot, on the converted texel. @@ -3604,7 +3341,8 @@ fn heap_twin( Ok((is_bits, img)) } -/// The words [`heap_twin`]'s class test emits, at most, as [`heap_half_words`] counts its own. +/// The words [`heap_twin`]'s class test emits, at most: the field's shift and mask, and per +/// member class the twin holds its constant, comparison and union. pub(crate) fn heap_bits_words() -> u32 { let n = crate::metal::texel_format::heap_half_bits_indices().len() as u32; 20 + 14 * n @@ -3711,27 +3449,6 @@ 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, }; - // A `float` through a heap handle, rounded where the handle's class is a half-float - // format's. - let texel = match (w.heap_half, w.image) { - (Some(class), ImageRef::Heap { handle, .. }) => { - let is_half = heap_half_format(cx, fb, handle)?; - heap_halves(fb, (is_half, class), w.texel, texel)? - } - _ => texel, - }; - // And its NaNs quieted where the handle's class is a small float's. - let texel = match (w.heap_small_floats, w.image) { - (true, ImageRef::Heap { handle, .. }) => { - let is_small = heap_small_float_format(cx, fb, handle)?; - let class = StorageImageClass::SmallFloatQuietNan; - heap_halves(fb, (is_small, class), w.texel, texel)? - } - _ => texel, - }; - // A `half` texel's NaN, as Metal stores it in the texture's channels. - let kept = half_kept(cx, fb, w.half_nans, &w.image)?; - let texel = half_nan_texel(fb, (w.half_nans, kept), w.texel, texel)?; // A half-float member's bits through the group's unsigned integer twin, where the handle's // class names one: its image is the float element's, viewed through its integer alias. let twin = match (w.heap_bits, w.image) { @@ -3908,24 +3625,6 @@ fn slice<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, s: &Slice) -> BR let dims = coord_len(&decl); let s = *s; let mem = texel_memory(cx, fb, &s.image)?; - // A `float` slice through a heap handle rounds where the handle's class is a half-float - // format's: the class is read once, outside the loop. - let is_half = match (s.heap_half, s.image) { - (Some(class), ImageRef::Heap { handle, .. }) => { - Some((heap_half_format(cx, fb, handle)?, class)) - } - _ => None, - }; - // And whether its NaNs are quieted, a small float's class: read once too. - let is_small = match (s.heap_small_floats, s.image) { - (true, ImageRef::Heap { handle, .. }) => Some(( - heap_small_float_format(cx, fb, handle)?, - StorageImageClass::SmallFloatQuietNan, - )), - _ => None, - }; - // Whether a `half` element keeps its half, read once, outside the loop. - let kept = half_kept(cx, fb, s.half_nans, &s.image)?; // Whether the handle names a member the unsigned integer twin holds, and the twin's image, // read once, outside the loop. let twin = match (s.heap_bits, s.image) { @@ -3969,15 +3668,7 @@ fn slice<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, s: &Slice) -> BR }), None => None, }; - let texel = match is_half { - Some(half) => heap_halves(fb, half, form, texel)?, - None => texel, - }; - let texel = match is_small { - Some(small) => heap_halves(fb, small, form, texel)?, - None => texel, - }; - (half_nan_texel(fb, (s.half_nans, kept), form, texel)?, twin) + (texel, twin) } }; let ty = vec(fb, u, dims)?; diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index b4fc33ea5..4dc5f5cda 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -136,11 +136,11 @@ pub use atomic::TexAtomic; pub(crate) use emit::{ constant_lanes, constant_lanes_by, dispatch, extended_table, float_class, half_by_class, half_class, heap_element, heap_float_class, heap_half_class, heap_raw_form, heap_raw_image, - live_or_zero, metal_texel_nans, reinterpret, resident_access, rgb9e5_word, slot_image, - sparse_spec, srgb_filtered_texel, srgb_raw_gather, srgb_raw_tap, srgb_raw_texel, - swizzled_float, swizzled_gather, swizzled_held, texel_format_const, tile_map, tiled_word, - with_word, HalfClass, NullLeaf, TileLevel, RGB9E5_WORDS, SRGB_FILTERED_WORDS, SRGB_RAW_WORDS, - SRGB_TAP_WORDS, SRGB_TEXEL, + live_or_zero, reinterpret, resident_access, rgb9e5_word, slot_image, sparse_spec, + srgb_filtered_texel, srgb_raw_gather, srgb_raw_tap, srgb_raw_texel, swizzled_float, + swizzled_gather, swizzled_held, texel_format_const, tile_map, tiled_word, with_word, HalfClass, + NullLeaf, TileLevel, RGB9E5_WORDS, SRGB_FILTERED_WORDS, SRGB_RAW_WORDS, SRGB_TAP_WORDS, + SRGB_TEXEL, }; pub use emit::{emit, held_texel, to_image}; pub(crate) use slot::depth_comparison; @@ -320,9 +320,6 @@ pub struct Read { /// A `float` texel of the slot converts by the bound format's class (`float_texel`): its /// code recovered from the device's value and divided exactly. pub float_texel: bool, - /// Where the NaN switch asks for Metal's NaN, how the read's `half` texel answers a NaN - /// texel ([`texel_nans_class`]): by the class of the bound texture it names. - pub half_nans: Option, /// The read, of a slot's color texture on a profile whose sparse textures are sparse images /// (it enables `shaderResourceResidency`), sets the lanes Metal reads as constants (a channel /// the format lacks, through the swizzle) after it, from the slot's `ConstantLanes` @@ -393,9 +390,8 @@ fn read_words(r: &Read) -> u32 { r.texel.read_words() }; let declared = if r.declared.is_some() { 16 } else { 0 }; - let nans = r.half_nans.map_or(0, NanClass::words); let siblings: u32 = r.heap_cross.iter().map(|x| read_words(x) + 24).sum(); - own + declared + nans + siblings + own + declared + siblings } /// A Metal 4.1 `read(sampler s, ...)` through a constexpr clamp-to-edge sampler (MSL 4.1 @@ -430,16 +426,8 @@ pub struct Write { /// raw texel ([`extended_range::encode`](crate::lower::arith::extended_range::encode)). pub extended: Option, /// The slot's storage class ([`storage_class`]): a converting one moves or encodes the - /// written channels (`RotateArgb`'s rotation, `SrgbEncode`'s codes, `HalfQuietNan`'s NaN). + /// written channels (`RotateArgb`'s rotation, `SrgbEncode`'s codes). pub class: StorageImageClass, - /// A `float` written through a heap handle on a device not measured to store its NaN in a - /// half-float texture as Metal does ([`heap_write_class`]): the class (`HalfQuietNan`) the - /// write takes where the handle's texel class is a half-float format's (`emit::heap_halves`). - pub heap_half: Option, - /// A `float` written through a heap handle: its NaN lanes are quieted where the handle's - /// texel class is a small float's (`StorageImageClass::SmallFloatQuietNan`, - /// `emit::heap_small_float_format`). - pub heap_small_floats: bool, /// A `float` or `half` texel written through a heap handle stores its alpha in the image's /// red where the handle's class index is `A8Unorm`'s, on a device that holds such a texture's /// alpha in red ([`heap_alpha_in_red`]). @@ -448,8 +436,6 @@ pub struct Write { /// texture's swizzle on its held value, before converting it, under the slot's /// `TextureSwizzle` specialization (`emit::unswizzled`). pub swizzle: bool, - /// How a `half` texel's NaN is written ([`half_nans`]). - pub half_nans: HalfNans, /// The slot's variant binds a texture of another numeric class /// (`LoweringInputs::cross_class`): `texel` is that class's own form /// ([`native_write_form`]), into which the write first turns the declared lanes @@ -500,37 +486,6 @@ impl IntRange { } } -/// How a `half` texel's write stores a NaN as Metal does ([`half_nans`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum HalfNans { - /// Not a `half` texel's write, or one to channels that hold no NaN: the value as held. - Held, - /// The texture's channels are 16-bit floats: the half widened, its NaN the device's - /// conversion of the widening (the half's bits under `DriverDeviation::MetalHalfTexelWrites`). - Kept, - /// The texture's channels are other floats: every NaN lane `0x7fc00000`. - Canonical, - /// A heap element: [`HalfNans::Kept`] where its handle's texel class is a half-float - /// format's, else [`HalfNans::Canonical`]. - HeapClass, - /// A texture slot whose storage choice declares no format: [`HalfNans::Kept`] where its - /// `PushField::TextureHalfChannels` is 1, else [`HalfNans::Canonical`]. - SlotWord(SlotRef), -} - -impl HalfNans { - /// The words of the write's NaN handling: the test and select of `emit::quiet_nans`, and for a - /// runtime choice its class test or word load and select. - pub(crate) fn words(self) -> u32 { - match self { - HalfNans::Held | HalfNans::Kept => 0, - HalfNans::Canonical => 24, - HalfNans::HeapClass => 24 + 16 + emit::heap_half_words(), - HalfNans::SlotWord(_) => 24 + 32, - } - } -} - /// What a `get_*` query reads. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum QueryKind { @@ -888,17 +843,11 @@ impl TextureStrategy { 0 } + emit::class_write_words(w.class) - + w.heap_half.map_or(0, heap_half_write_words) - + match w.heap_small_floats { - true => heap_half_write_words(StorageImageClass::SmallFloatQuietNan), - false => 0, - } + if w.heap_alpha_red { emit::HEAP_ALPHA_IN_RED_WORDS } else { 0 } - + w.half_nans.words() + if w.cross.is_some() { 48 } else { 0 } + w.saturate.words() + if w.heap_bits { @@ -1441,13 +1390,6 @@ fn declare_heap_classes(mb: &mut ModuleBuilder) -> BResult { mb.plain_global(crate::spirv::ir::StorageClass::Private, arr, Some(init)) } -/// The words a heap texture's `float` write adds where its handle's class may be a half-float -/// format's, written by class `class`, at most: the test of the class index, the class's write, and -/// the choice between it and the texel as computed. -pub(crate) fn heap_half_write_words(class: StorageImageClass) -> u32 { - emit::heap_half_words() + emit::class_write_words(class) + 32 -} - /// The words a heap texture's `half` or `float` write adds where it stores a half-float member's /// bits through the unsigned integer twin, at most: the test of the class index, the bits, the /// twin's access chain and load, and the branch between the two writes. @@ -1737,75 +1679,6 @@ pub(crate) fn half_texel_nans( } } -/// How a `half` read, sample or gather of `image` (shape `shape`), which reads one texel where -/// `one` says, answers a NaN texel where the NaN switch asks for Metal's NaN -/// (`NanMinMaxPolicy::Exact`, the profile's `TexelNanRoute::Metal`, on every device: whatever -/// NaN the device's arithmetic answers, the texel's is the image's decode): by Metal's rule, a NaN -/// texel read, sampled or gathered one texel at a time from a texture of -/// 16-bit float channels is its own (the device's decode, which a device that widens a half -/// texel exactly decodes to its bits), and every other NaN `0x7e00`. The class of the texture -/// bound says which: a slot's `TexelFormat` class, which the binder pushes as data -/// ([`texel_format_spec`]); a heap element's, its handle's class index; a depth texture's never; an -/// access that never reads one texel needs none ([`NanClass::Never`]). `None` where the switch is -/// off, or where nothing tells the class (a heap's texture buffer, whose handle carries none: its -/// NaN stays the device's decode, noted by [`half_texel_nans`]). -pub(crate) fn texel_nans_class( - cx: &mut SelectCx<'_>, - image: ImageRef, - shape: ImageShape, - one: OneTexel, -) -> Result, Error> { - use crate::device::profile::TexelNanRoute; - if cx.profile.fields().texel_nans != TexelNanRoute::Metal { - return Ok(None); - } - Ok(Some(match image { - _ if shape.depth || one == OneTexel::Never => NanClass::Never, - ImageRef::Slot(_) => { - texel_format_spec(cx, image)?; - let ImageRef::Slot(index) = image else { - return Err(cx.invariant("a slot's class of a heap element")); - }; - NanClass::Slot(index) - } - ImageRef::Heap { .. } if shape.dim == ImageDim::Buffer => return Ok(None), - ImageRef::Heap { handle, .. } => { - cx.families.access.heap_class_index = true; - NanClass::Heap(handle) - } - })) -} - -/// How a `half` texel access tells whether the texture bound holds 16-bit float channels, whose -/// NaN texel Metal hands back as its own bits where the access reads one texel -/// ([`texel_nans_class`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum NanClass { - /// Slot `index`'s `TexelFormat` class (`RuntimeFact::TexelFormat`, read as data): the - /// half-float family's without a packed field (`metal::texel_format::half_channels`), or - /// `TexelFormat::OTHER`, whose conversion is not measured: the device's decode, as before. - Slot(u32), - /// The class index heap handle `handle` carries (`emit::heap_half_format`). - Heap(ValueId), - /// A depth texture: never 16-bit float channels, so every NaN is `0x7e00`. - Never, -} - -impl NanClass { - /// The estimated words of an access's answer of Metal's NaN: the texel's NaN test (the bitcast, - /// the mask, the compare and their constants), the canonical NaN, the class test (a slot's mask - /// and compare, a heap handle's [`emit::heap_half_words`]), a runtime sampler's filter test, - /// and the two selects. - pub(crate) fn words(self) -> u32 { - let class = match self { - NanClass::Slot(_) => 40, - NanClass::Heap(_) => emit::heap_half_words(), - NanClass::Never => 0, - }; - 64 + class + 48 - } -} - /// A read, gather, or sample of `image`, of shape `shape`, with a `float` result that may read /// one texel (`one` not [`OneTexel::Never`]): on a color texture slot, a texture buffer's included, /// on a profile without Metal's own sampler (`VkProperty::MetalSampler`, whose device value is @@ -2466,174 +2339,156 @@ pub fn routine_words( /// no other flag is carried, the masks of the heap handles. pub const HEAP_CLASS_CENSUS: &str = "sampler.heap.texel_class"; -/// The class a `float` written through a heap handle takes where the handle's texel class is a -/// half-float format's (`emit::heap_halves`): the class a slot bound in such a format takes -/// (`metal::format::half_write_class`), `None` where that is `Identity` (the device stores the -/// write's NaN as Metal does). -pub(crate) fn heap_write_class(cx: &SelectCx<'_>) -> Option { - match crate::metal::format::half_write_class(cx.profile) { - StorageImageClass::Identity => None, - class => Some(class), - } -} - -/// What a `float` write to texture `image` (a slot's storage class `class`; a heap write's class -/// where its handle's is a half-float format's, `heap_half`) relies on or records where it may -/// reach a half-float image, whose rounding of each channel to `half` the device makes (Metal -/// rounds toward zero, a finite value past 65504 to 65504): Metal's where the profile takes -/// `DriverDeviation::MetalHalfStorageWrites` (the module requires its property), else the device's -/// (`PrecisionNote::DeviceColorConversion`), but for a half-float member a heap's unsigned integer -/// twin holds (`heap_bits`), whose bits the shader writes. A write the shader quiets stores the NaN -/// `0x7fc00000`, Metal's `0x7e00` where the profile takes `DriverDeviation::MetalFloatStorageNans` -/// (the module requires its property), else the device's encoding of it -/// (`PrecisionNote::DeviceNanEncoding`); one left to the device's conversion whole, a heap write's -/// or a slot's whose choice declares a half-float format, requires -/// `VkProperty::MetalHalfStorageNans` too. +/// What a `float` write to texture `image` (of storage class `class`) relies on or records where it +/// may reach a half-float image ([`may_store_half`]), which the device converts whole. Its rounding of each channel to +/// `half` (Metal rounds toward zero, a finite value past 65504 to 65504) is Metal's where the +/// profile takes `DriverDeviation::MetalHalfStorageWrites` (the module requires its property), else +/// the device's (`PrecisionNote::DeviceColorConversion`), but for a half-float member a heap's +/// unsigned integer twin holds (`heap_bits`), whose bits the shader writes. Its NaN is Metal's +/// `0x7e00` where the profile takes `DriverDeviation::MetalHalfStorageNans` (the module requires its +/// property), else the device's encoding of it (`PrecisionNote::DeviceNanEncoding`), but for a +/// member the twin holds, which stores Metal's (the runtime announces the note where the heap holds +/// a half-float texture the twin does not: `RuntimeFact::HeapHalfTexelWrites`). A write that may +/// reach a packed small float image, a heap write's or a slot's whose choice declares such a format +/// or none ([`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. pub(super) fn half_storage_facts( cx: &mut SelectCx<'_>, image: ImageRef, class: StorageImageClass, - (heap_half, heap_bits): (Option, bool), + heap_bits: bool, ) -> Result<(), Error> { use crate::device::requirements::VkProperty; - let applied = match image { - ImageRef::Heap { .. } => heap_half.unwrap_or(StorageImageClass::Identity), - ImageRef::Slot(_) => class, - }; - let mut relied = Vec::new(); - let rounded = |cx: &mut SelectCx<'_>, relied: &mut Vec| { - let measured = cx + if class == StorageImageClass::Identity && may_store_half(cx, image)? { + let rounds = cx .profile .takes_driver_deviation(DriverDeviation::MetalHalfStorageWrites); - match (heap_bits, measured) { + match (heap_bits, rounds) { (true, _) => {} - (false, true) => relied.push(VkProperty::MetalHalfStorageWrites), + (false, true) => { + cx.families + .texture + .storage_properties + .insert(VkProperty::MetalHalfStorageWrites); + } (false, false) => { cx.precision.insert(PrecisionNote::DeviceColorConversion); } } - }; - match applied { - StorageImageClass::HalfQuietNan => { - rounded(cx, &mut relied); - if cx - .profile - .takes_driver_deviation(DriverDeviation::MetalFloatStorageNans) - { - relied.push(VkProperty::MetalFloatStorageNans); - } else if heap_bits { - // A member the twin holds stores Metal's `0x7e00`; the runtime announces the - // note where the heap holds a half-float texture the twin does not. - heap_half_texel_writes(cx, false); - } else { - cx.precision.insert(PrecisionNote::DeviceNanEncoding); - } + if cx + .profile + .takes_driver_deviation(DriverDeviation::MetalHalfStorageNans) + { + cx.families + .texture + .storage_properties + .insert(VkProperty::MetalHalfStorageNans); + } else if heap_bits { + heap_half_texel_writes(cx, false); + } else { + cx.precision.insert(PrecisionNote::DeviceNanEncoding); } - StorageImageClass::Identity if declared_half(cx, image)? => { - rounded(cx, &mut relied); - relied.push(VkProperty::MetalHalfStorageNans); - } - _ => {} } - cx.families.texture.storage_properties.extend(relied); + if small_float_storage(cx, image)? { + cx.precision.insert(PrecisionNote::DeviceNanEncoding); + } Ok(()) } -/// How a `half` texel's write to texture `image` stores a NaN as Metal does, and what it records. -/// 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 M4 under macOS 27.0.1: every NaN class, both signs, `write` -/// and `read_write`, `Shared` and `Private`): a 16-bit float channel takes the half widened -/// ([`HalfNans::Kept`]), which a device of `DriverDeviation::MetalHalfTexelWrites` stores as its -/// bits, and any other float channel every NaN as `0x7fc00000` ([`HalfNans::Canonical`]), which a -/// 32-bit float channel stores as it is. The texture's format decides: a slot's declared format, or -/// the class it writes by (`HalfQuietNan`: a 16-bit float format's); a heap -/// element's handle class ([`HalfNans::HeapClass`]); a texture slot's word where its choice -/// declares none ([`HalfNans::SlotWord`]). A normalized format's channel stores no NaN -/// ([`HalfNans::Held`]). +/// Whether a write to texture `image` may store into a packed small float format +/// (`RG11B10Float`, `RGB9E5Float`'s alias excepted: its word is Metal's): a heap element, whose +/// handle may name one, or a slot whose storage choice declares such a format or none. +fn small_float_storage(cx: &SelectCx<'_>, image: ImageRef) -> Result { + use crate::vk::Format as F; + let ImageRef::Slot(index) = image else { + return Ok(true); + }; + let slot = slot_of(cx, index)?.slot; + Ok(cx + .inputs + .storage_images + .get(&slot) + .is_some_and(|c| matches!(c.vk_format, F::B10G11R11_UFLOAT_PACK32 | F::UNDEFINED))) +} + +/// 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 +/// 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. /// /// The write records `PrecisionNote::DeviceNanEncoding` where the stored NaN stays the device's: -/// a 16-bit float channel's, and a packed small float's (the device converting -/// `0x7fc00000`), on a profile without `DriverDeviation::MetalHalfTexelWrites`, which states -/// both; a heap element's likewise; a texel buffer declaring no format always (it has no word, -/// so it keeps the half). A slot's word records nothing: the runtime announces the note at the -/// bind of a 16-bit or packed small float texture there on such a profile -/// (`RuntimeFact::StorageTextureHalfChannels`). A 32-bit float channel's `0x7fc00000` is -/// stored as it is: no note. Nor is a slot's whose choice writes the half's bits through the -/// texture's unsigned integer alias (`StorageImageClass::HalfBits`), which every device stores -/// exactly; the binder chooses it for a half-float texture a slot only writes on such a profile, so -/// that slot's word is not read. -pub(super) fn half_nans( +/// 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 a 32-bit float texture's (where the group's +/// unsigned integer twin holds its half-float members too, which states +/// `RuntimeFact::HeapHalfTexelWrites`). A normalized or integer channel stores no NaN; nor does a +/// slot whose choice writes the half's bits through the texture's unsigned integer alias +/// (`StorageImageClass::HalfBits`), which every device stores exactly. +pub(super) fn half_write_nans( cx: &mut SelectCx<'_>, image: ImageRef, - (buffer, heap_bits): (bool, bool), -) -> Result { + heap_bits: bool, +) -> Result<(), Error> { use crate::device::requirements::VkProperty; use crate::vk::NumericFormat as N; - // Each form, and whether the device's conversion decides the NaN stored (`Device`), and where - // a runtime choice lets the runtime narrow the note to the bind (`Bound`). + // 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`). #[derive(PartialEq)] enum Stored { Exact, + Sixteen, Device, - Bound, } - let declared = |f: crate::vk::Format| -> (HalfNans, Stored) { + let declared = |f: crate::vk::Format| -> Stored { let Some(b) = f.block() else { - return (HalfNans::Held, Stored::Exact); + return Stored::Device; }; match (b.color, b.component_bits, b.packed_bits) { - (Some(N::Sfloat), Some(16), None) => (HalfNans::Kept, Stored::Device), - (Some(N::Sfloat), Some(32), None) => (HalfNans::Canonical, Stored::Exact), - (Some(N::Sfloat | N::Ufloat), _, _) => (HalfNans::Canonical, Stored::Device), - _ => (HalfNans::Held, Stored::Exact), + (Some(N::Sfloat), Some(16), None) => Stored::Sixteen, + (Some(N::Sfloat | N::Ufloat), _, _) => Stored::Device, + _ => Stored::Exact, } }; - let (nans, stored) = match image { - // A half-float member the group's unsigned integer twin holds stores the half's bits; - // the runtime announces the note where the heap holds a texture it does not. - ImageRef::Heap { .. } if heap_bits => (HalfNans::HeapClass, Stored::Bound), - ImageRef::Heap { .. } => (HalfNans::HeapClass, Stored::Device), + let stored = match image { + ImageRef::Heap { .. } => { + if heap_bits { + heap_half_texel_writes(cx, true); + } + Stored::Device + } ImageRef::Slot(index) => { let slot = slot_of(cx, index)?.slot; match cx.inputs.storage_images.get(&slot) { Some(c) => match c.class { - StorageImageClass::HalfQuietNan => (HalfNans::Kept, Stored::Device), - StorageImageClass::SmallFloatQuietNan => (HalfNans::Canonical, Stored::Device), // The half's own bits, written through the unsigned integer alias. - StorageImageClass::HalfBits => (HalfNans::Kept, Stored::Exact), - StorageImageClass::Identity if c.vk_format != crate::vk::Format::UNDEFINED => { - declared(c.vk_format) - } - StorageImageClass::Identity if buffer => (HalfNans::Kept, Stored::Device), - StorageImageClass::Identity => (HalfNans::SlotWord(slot), Stored::Bound), - _ => (HalfNans::Held, Stored::Exact), + StorageImageClass::HalfBits => Stored::Exact, + StorageImageClass::Identity => declared(c.vk_format), + _ => Stored::Exact, }, - None if buffer => (HalfNans::Kept, Stored::Device), - None => (HalfNans::SlotWord(slot), Stored::Bound), + None => Stored::Device, } } }; let measured = cx .profile .takes_driver_deviation(DriverDeviation::MetalHalfTexelWrites); - if stored != Stored::Exact && measured { - cx.families - .texture - .storage_properties - .insert(VkProperty::MetalHalfTexelWrites); - } else if stored == Stored::Device { - cx.precision.insert(PrecisionNote::DeviceNanEncoding); + match stored { + Stored::Sixteen if measured => { + cx.families + .texture + .storage_properties + .insert(VkProperty::MetalHalfTexelWrites); + } + Stored::Sixteen | Stored::Device => { + cx.precision.insert(PrecisionNote::DeviceNanEncoding); + } + Stored::Exact => {} } - match nans { - HalfNans::HeapClass => cx.families.access.heap_class_index = true, - HalfNans::SlotWord(_) => mark(cx, image, |u| u.half_channels = true), - _ => {} - } - if heap_bits && !measured { - heap_half_texel_writes(cx, true); - } - Ok(nans) + Ok(()) } /// Whether a `half` or `float` write (`texel`) to texture `image` of shape `shape` stores a @@ -2785,8 +2640,7 @@ pub(super) fn norm_storage_facts( /// small-float one (unmeasured). Kernel, vertex, object, mesh and tile functions write alike at /// every mode. The write is built under the default's rule alone, so: a write that may be such /// records the mode in `StageIo::texture_write_rounding`, for link to match against the pipeline's; -/// under `NearestEven` one whose slot's storage choice declares such a format (or rounds as a -/// half-float one: `HalfQuietNan`) is refused +/// under `NearestEven` one whose slot's storage choice declares such a format is refused /// `NotImplemented(PrivateRenderState(TextureWriteRounding))`, and one whose bound texture /// decides (a slot or texture buffer whose choice declares no format; a heap handle) states /// `RuntimeFact::StorageTextureWriteRounding` or `RuntimeFact::HeapWriteRounding`, which the @@ -2822,14 +2676,6 @@ fn mode_rounded_write( match cx.inputs.storage_images.get(&slot) { None => Target::Slot(slot), Some(c) => match c.class { - StorageImageClass::HalfQuietNan => Target::Declared { - half: true, - small: false, - }, - StorageImageClass::SmallFloatQuietNan => Target::Declared { - half: false, - small: true, - }, StorageImageClass::Identity if c.vk_format == F::UNDEFINED => { Target::Slot(slot) } @@ -2883,8 +2729,9 @@ fn mode_rounded_write( } /// Whether a write to `image` left to the device's conversion may store a half-float texel: a -/// heap element's may, and a slot's whose storage choice declares a half-float format does. -fn declared_half(cx: &SelectCx<'_>, image: ImageRef) -> Result { +/// heap element's may, and so does a slot's whose storage choice declares a half-float format or +/// none (a formatless declaration views a half-float texture too). +fn may_store_half(cx: &SelectCx<'_>, image: ImageRef) -> Result { use crate::vk::Format as F; let ImageRef::Slot(index) = image else { return Ok(true); @@ -2893,15 +2740,14 @@ fn declared_half(cx: &SelectCx<'_>, image: ImageRef) -> Result { Ok(cx.inputs.storage_images.get(&slot).is_some_and(|c| { matches!( c.vk_format, - F::R16_SFLOAT | F::R16G16_SFLOAT | F::R16G16B16A16_SFLOAT + F::R16_SFLOAT | F::R16G16_SFLOAT | F::R16G16B16A16_SFLOAT | F::UNDEFINED ) })) } /// The class of texture slot `image`'s storage choice, where its variant states one, else /// `Identity`: a write through a converting class moves or encodes the written channels -/// (`RotateArgb`'s rotation, `SrgbEncode`'s codes, `HalfQuietNan`'s NaN). A heap element's is -/// `Identity`. +/// (`RotateArgb`'s rotation, `SrgbEncode`'s codes). A heap element's is `Identity`. pub(crate) fn storage_class( cx: &SelectCx<'_>, image: ImageRef, @@ -3434,10 +3280,18 @@ fn select_read_as( storage_class(cx, image)?, StorageImageClass::HalfBits | StorageImageClass::SharedExponentBits ); + // A `float` read of a half-float texel's own bits widens a NaN with its sign and payload, where + // Metal reads every half NaN as `0x7fc00000`. + if texel.conv == TexelConv::F32 + && half_bits + && storage_class(cx, image)? == StorageImageClass::HalfBits + { + cx.precision.insert(PrecisionNote::DeviceNanEncoding); + } let exact = raw || srgb_codes || half_bits; // An extended-range texel is decoded exactly to `f32`, which a `half` result rounds to // nearest even, as Metal answers. A read is one texel. - let half_nans = if texel.conv == TexelConv::F16 && !exact && extended.is_none() { + if texel.conv == TexelConv::F16 && !exact && extended.is_none() { half_texels( cx, image, @@ -3447,10 +3301,7 @@ fn select_read_as( m, )?; half_texel_nans(cx, image, shape, m)?; - texel_nans_class(cx, image, shape, OneTexel::Always)? - } else { - None - }; + } let float_texel = texel.conv == TexelConv::F32 && !exact && extended.is_none() @@ -3530,7 +3381,6 @@ fn select_read_as( heap_raw, heap_alpha_red, float_texel, - half_nans, constant_lanes, declared, heap_class: as_class, @@ -3695,15 +3545,6 @@ fn select_write( let extended = extended_range(cx, image)?; let class = storage_class(cx, image)?; mode_rounded_write(cx, image, texel, extended.is_some())?; - // A `float` written through a heap handle may reach a half-float texture, whose format only - // the handle's texel class tells: it rounds where the class is one. - let heap_half = match image.heap() && texel.conv == TexelConv::F32 { - true => heap_write_class(cx), - false => None, - }; - // Its NaNs quieted where the class is a small float's. - let heap_small_floats = image.heap() && texel.conv == TexelConv::F32; - cx.families.access.heap_class_index |= heap_half.is_some() || heap_small_floats; // 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 half-float member's bits through the group's unsigned integer twin, where the handle's @@ -3711,12 +3552,11 @@ fn select_write( let encoded = extended.is_some() || cross.is_some(); let heap_bits = heap_bits(cx, image, shape, (texel.conv, encoded)); if texel.conv == TexelConv::F32 { - half_storage_facts(cx, image, class, (heap_half, heap_bits))?; + half_storage_facts(cx, image, class, heap_bits)?; + } + if texel.conv == TexelConv::F16 && extended.is_none() { + half_write_nans(cx, image, heap_bits)?; } - let half_nans = match texel.conv == TexelConv::F16 && extended.is_none() { - true => half_nans(cx, image, (shape.dim == ImageDim::Buffer, heap_bits))?, - false => HalfNans::Held, - }; // 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() { norm_storage_facts(cx, image, shape, texel)?; @@ -3744,11 +3584,8 @@ fn select_write( guard, extended, class, - heap_half, - heap_small_floats, heap_alpha_red, swizzle, - half_nans, cross, saturate, heap_bits, diff --git a/crates/metal2vulkan/src/lower/texture/slice.rs b/crates/metal2vulkan/src/lower/texture/slice.rs index 37564fee7..1d535d1c3 100644 --- a/crates/metal2vulkan/src/lower/texture/slice.rs +++ b/crates/metal2vulkan/src/lower/texture/slice.rs @@ -88,17 +88,8 @@ pub struct Slice { /// The cell loads are contained. pub contained: bool, /// The slot's storage class (`super::storage_class`): a converting one moves or encodes each - /// texel's channels (`RotateArgb`'s rotation, `HalfQuietNan`'s NaN). + /// texel's channels (`RotateArgb`'s rotation, `SrgbEncode`'s codes). pub class: StorageImageClass, - /// A `float` slice through a heap handle on a device not measured to store its NaN in a - /// half-float texture as Metal does: the class each texel takes where the handle's texel - /// class is a half-float format's (`super::Write::heap_half`). - pub heap_half: Option, - /// A `float` slice through a heap handle: each texel's NaN lanes quieted where the handle's - /// texel class is a small float's (`super::Write::heap_small_floats`). - pub heap_small_floats: bool, - /// How a `half` element's NaN is written (`super::half_nans`). - pub half_nans: super::HalfNans, /// Each texel of a half-float member stores its bits through the heap group's unsigned /// integer twin where the handle's class names one (`super::Write::heap_bits`). pub heap_bits: bool, @@ -117,14 +108,6 @@ impl Slice { + if self.contained { 64 } else { 0 } + if self.guard { 48 } else { 0 } + super::emit::class_write_words(self.class) - + self.heap_half.map_or(0, |c| { - super::HEAP_CLASS_WORDS + super::emit::class_write_words(c) + 32 - }) - + match self.heap_small_floats { - true => super::heap_half_write_words(StorageImageClass::SmallFloatQuietNan), - false => 0, - } - + self.half_nans.words() + if self.heap_bits { super::heap_bits_write_words() } else { @@ -330,30 +313,20 @@ pub(super) fn select( }; let guard = slot::write_guard(cx, false); let class = super::storage_class(cx, image)?; - let heap_half = match image.heap() && conv == TexelConv::F32 { - true => super::heap_write_class(cx), - false => None, - }; - let heap_small_floats = image.heap() && conv == TexelConv::F32; - cx.families.access.heap_class_index |= heap_half.is_some() || heap_small_floats; // A half-float member's bits through the group's unsigned integer twin, where the handle's // class names one. let heap_bits = super::heap_bits(cx, image, t.image, (conv, false)); if conv == TexelConv::F32 { - super::half_storage_facts(cx, image, class, (heap_half, heap_bits))?; + super::half_storage_facts(cx, image, class, heap_bits)?; } if matches!(conv, TexelConv::F32 | TexelConv::F16) { super::norm_storage_facts(cx, image, t.image, TexelForm { conv, lanes })?; } - let half_nans = match conv == TexelConv::F16 { - true => super::half_nans(cx, image, (false, heap_bits))?, - false => super::HalfNans::Held, - }; - // A `half` element to a slot of half bits, its NaNs as held: the cells' bits as they are. - let bits = match conv == TexelConv::F16 - && class == StorageImageClass::HalfBits - && !image.heap() - && matches!(half_nans, super::HalfNans::Held | super::HalfNans::Kept) + if conv == TexelConv::F16 { + super::half_write_nans(cx, image, heap_bits)?; + } + // A `half` element to a slot of half bits: the cells' bits as they are. + let bits = match conv == TexelConv::F16 && class == StorageImageClass::HalfBits && !image.heap() { true => Some(Leaf { form: Form { @@ -396,9 +369,6 @@ pub(super) fn select( guard, contained: imageblock::contained(cx), class, - heap_half, - heap_small_floats, - half_nans, heap_bits, cooperative, bits, diff --git a/crates/metal2vulkan/src/lower/texture/slot.rs b/crates/metal2vulkan/src/lower/texture/slot.rs index 6bdcd829f..9a8b0c653 100644 --- a/crates/metal2vulkan/src/lower/texture/slot.rs +++ b/crates/metal2vulkan/src/lower/texture/slot.rs @@ -84,9 +84,6 @@ pub struct Uses { /// A cube's texels are fetched by face (an emulated linear cube sample): the slot is declared /// as the binder's 2D-array view of its faces. pub faces: bool, - /// A `half` texel's write reads whether the bound texture's channels are 16-bit floats - /// (`HalfNans::SlotWord`): the slot's storage choice declares no format. - pub half_channels: bool, /// An integer texel's write reads the widths of the bound texture's channels /// (`IntRange::SlotWord`): the slot's storage choice declares no format. pub int_channels: bool, @@ -1125,10 +1122,6 @@ fn declare_slot( }; let (format, class) = if storage { facts.push(RuntimeFact::StorageTextureFormat { slot: s.slot }); - if s.uses.half_channels { - facts.push(RuntimeFact::StorageTextureHalfChannels { slot: s.slot }); - push.push(PushField::TextureHalfChannels(s.slot)); - } if s.uses.int_channels { facts.push(RuntimeFact::StorageTextureIntegerChannels { slot: s.slot }); push.push(PushField::TextureIntegerChannels(s.slot)); diff --git a/crates/metal2vulkan/src/metal/format/mod.rs b/crates/metal2vulkan/src/metal/format/mod.rs index 23a8a927f..548d12530 100644 --- a/crates/metal2vulkan/src/metal/format/mod.rs +++ b/crates/metal2vulkan/src/metal/format/mod.rs @@ -2887,9 +2887,8 @@ pub fn storage_image_choice( /// `Identity` when the direct format supports the use's storage usage and the shader can declare /// it: with the format `Unknown` where the format serves the use without one /// ([`accessed_without_format`]; every such format of one numeric type shares one key, and -/// `StorageImageChoice::numeric` keeps the type), else with its SPIR-V image format. A half-float -/// format the use writes takes the class its writes need there instead (`half_storage_class`). -/// Otherwise an alias view of a `MUTABLE_FORMAT` image (or the same bytes viewed as the alias +/// `StorageImageChoice::numeric` keeps the type), else with its SPIR-V image format: the device +/// converts every write, a half-float format's included. Otherwise an alias view of a `MUTABLE_FORMAT` image (or the same bytes viewed as the alias /// format, for a texture buffer): bgra8 through an rgba8 view and bgr10a2 through an rgb10a2 view /// (`A2R10G10B10` through `A2B10G10R10`, which NVIDIA and lavapipe store where they do not store /// the former) with `SwizzleBgra`, the 8-bit sRGB formats through their UNORM twin with @@ -3013,13 +3012,12 @@ fn held_storage_choice( // device that stores the format. let word = matches!(alias, Some((_, StorageImageClass::SharedExponentBits))); if storage(image) && declarable(image) && !rotated && !srgb_x && !word { - let class = half_storage_class(pf, use_, profile); if !formatless(image) { - return Ok(StorageImageChoice::new(image, class)); + return Ok(StorageImageChoice::new(image, StorageImageClass::Identity)); } // The declaration names no format; the choice keeps the format's numeric type for a // function that depends on it. - let mut choice = StorageImageChoice::new(F::UNDEFINED, class); + let mut choice = StorageImageChoice::new(F::UNDEFINED, StorageImageClass::Identity); choice.numeric = crate::bind::neutral::numeric_type(image); return Ok(choice); } @@ -3196,29 +3194,6 @@ pub(crate) fn fetch_view_alias(format: vk::Format, profile: &DeviceProfile) -> O } } -/// The class of a storage choice that views `pf`'s own format for `use_`: for a half-float -/// format (`R16Float`, `RG16Float`, `RGBA16Float`, `RGBX16Float`) the function writes, -/// [`half_write_class`]. An `RG11B10Float` texture the function writes takes -/// `SmallFloatQuietNan` on every device. Otherwise `Identity`: the device converts the write. -pub(crate) fn half_storage_class( - pf: PixelFormat, - use_: StorageUse, - profile: &DeviceProfile, -) -> StorageImageClass { - let half = matches!( - pf, - PixelFormat::R16Float - | PixelFormat::RG16Float - | PixelFormat::RGBA16Float - | PixelFormat::RGBX16Float - ); - match (half, pf == PixelFormat::RG11B10Float, use_.write) { - (true, _, true) => half_write_class(profile), - (_, true, true) => StorageImageClass::SmallFloatQuietNan, - _ => StorageImageClass::Identity, - } -} - /// Whether `pf`'s alpha is a 1-bit unorm channel (`crate::metal::texel_format::PackedTexels::Rgb5A1`: /// `A1BGR5Unorm`, `BGR5A1Unorm`), whose `float` write Metal stores as 1 only above one half, where /// a device measured to store every other normalized channel as Metal does rounds the half up @@ -3239,18 +3214,6 @@ pub(crate) fn one_bit_storage(use_: StorageUse, profile: &DeviceProfile) -> bool .any(|&pf| storage_choice(pf, use_, profile).is_ok()) } -/// The class a `float` write to a half-float storage image takes on `profile` -/// ([`half_storage_class`]): the device rounds each channel to `half` (Metal's rule, toward zero, -/// where it takes `DriverDeviation::MetalHalfStorageWrites`), so `Identity` where it stores every -/// NaN as Metal does too (`MetalHalfStorageNans`), else `HalfQuietNan`, which writes a NaN as -/// `0x7fc00000`. -pub(crate) fn half_write_class(profile: &DeviceProfile) -> StorageImageClass { - match profile.takes_driver_deviation(DriverDeviation::MetalHalfStorageNans) { - true => StorageImageClass::Identity, - false => StorageImageClass::HalfQuietNan, - } -} - /// The SPIR-V `Image Format` a storage image of Vulkan format `format` is declared with (Vulkan /// spec "Compatibility Between SPIR-V Image Formats and Vulkan Formats"); `None` for formats only /// a formatless (`Unknown`) declaration can access. Crate-private: only the lowering and the diff --git a/crates/metal2vulkan/src/metal/format/tests.rs b/crates/metal2vulkan/src/metal/format/tests.rs index e76be5c4d..2a50f978f 100644 --- a/crates/metal2vulkan/src/metal/format/tests.rs +++ b/crates/metal2vulkan/src/metal/format/tests.rs @@ -1928,23 +1928,18 @@ fn storage_choices_on_committed_profiles_are_declarable() { } } -/// A half-float storage texture a function writes takes the class its `float` writes need, by -/// what the committed profile's device is measured to store for a NaN (and lavapipe's probes): -/// `Identity` on MoltenVK (Metal's every NaN), `HalfQuietNan` on every other profile, whose -/// device's own conversion rounds each value; a read-only use, and another float format, stay -/// `Identity`. On a profile not measured to store a written `half`'s NaN as its bits -/// (`DriverDeviation::MetalHalfTexelWrites`), a written use takes the unsigned integer alias -/// (`StorageImageClass::HalfBits`) wherever the alias serves it, an image of its own format alone -/// the measured class. +/// A half-float storage texture a function writes takes `Identity` on every committed profile: the +/// device converts each value and NaN (`lower::texture`'s `half_storage_facts` records what it +/// relies on or notes); so do a read-only use and another float format. On a profile not measured +/// to store a written `half`'s NaN as its bits (`DriverDeviation::MetalHalfTexelWrites`), a written +/// use takes the unsigned integer alias (`StorageImageClass::HalfBits`) wherever the alias serves +/// it, an image of its own format alone `Identity`. #[test] fn half_float_storage_writes_take_their_measured_class() { let mut seen = BTreeSet::new(); for (stem, dev) in committed_devices() { let p = dev.profile(); - let want = match stem.as_str() { - "moltenvk-m3" => StorageImageClass::Identity, - _ => StorageImageClass::HalfQuietNan, - }; + let want = StorageImageClass::Identity; for pf in [ PixelFormat::R16Float, PixelFormat::RG16Float, @@ -1986,59 +1981,7 @@ fn half_float_storage_writes_take_their_measured_class() { ); } } - assert_eq!(seen.len(), 3, "{seen:?}"); -} - -/// An `RG11B10Float` storage texture a function writes, or texture buffer, takes -/// `SmallFloatQuietNan` on every committed profile that writes it (its NaNs quieted to the -/// `0x7fc00000` every device measured stores as Metal's); a read-only use stays `Identity`; and a -/// heap write tests the small floats' class, `RG11B10Float`'s and `RGB9E5Float`'s alone. -#[test] -fn storage_choices_quiet_small_float_writes() { - let mut written = 0; - for (stem, dev) in committed_devices() { - let p = dev.profile(); - let pf = PixelFormat::RG11B10Float; - for use_ in [ - StorageUse::READ_WRITE_TEXTURE, - StorageUse::texture(false, true), - StorageUse::texel_buffer(false, true), - ] { - if let Ok(choice) = storage_choice(pf, use_, p) { - assert_eq!( - choice.class, - StorageImageClass::SmallFloatQuietNan, - "{stem} {use_:?}" - ); - written += 1; - } - } - if let Ok(read) = storage_choice(pf, StorageUse::texture(true, false), p) { - assert_eq!(read.class, StorageImageClass::Identity, "{stem} read"); - } - } - assert!(written > 0, "no committed profile writes RG11B10Float"); - // The small floats' classes are `RG11B10Float`'s and `RGB9E5Float`'s, and no other format's. - let classes = crate::metal::texel_format::heap_classes(); - let small: BTreeSet = crate::metal::texel_format::heap_small_float_indices() - .into_iter() - .map(|i| classes[i as usize]) - .collect(); - let class = |pf: PixelFormat| { - crate::metal::texel_format::heap_class(pf, crate::metal::TextureSwizzleChannels::DEFAULT).0 - }; - let want: BTreeSet = [PixelFormat::RG11B10Float, PixelFormat::RGB9E5Float] - .into_iter() - .map(class) - .collect(); - assert_eq!(small, want); - for &pf in PixelFormat::ALL { - assert_eq!( - small.contains(&class(pf)), - matches!(pf, PixelFormat::RG11B10Float | PixelFormat::RGB9E5Float), - "{pf:?}" - ); - } + assert_eq!(seen.len(), 2, "{seen:?}"); } /// A `BGR10A2Unorm` storage texture or texture buffer is stored through its own `A2R10G10B10` diff --git a/crates/metal2vulkan/src/metal/texel_format.rs b/crates/metal2vulkan/src/metal/texel_format.rs index 14d7ee1d1..421f8a5d4 100644 --- a/crates/metal2vulkan/src/metal/texel_format.rs +++ b/crates/metal2vulkan/src/metal/texel_format.rs @@ -851,22 +851,6 @@ pub fn heap_numeric(pf: PixelFormat) -> Option Vec { - use crate::metal::bicubic::BicubicTexels; - heap_classes() - .iter() - .enumerate() - .filter(|(_, &c)| { - c & (BicubicTexels::HALF | TexelFormat::PACKED_MASK) == BicubicTexels::HALF - }) - .filter_map(|(i, _)| u32::try_from(i).ok()) - .collect() -} - /// The half-float formats whose texture a heap's unsigned integer twin /// (`StorageFormatClass::HalfBits`) holds through its unsigned integer alias, in the own-view /// classes' order ([`heap_classes`]). `RGBX16Float` is not among them: no heap storage class @@ -900,20 +884,6 @@ pub fn heap_own_view_index(pf: PixelFormat, swizzle: TextureSwizzleChannels) -> reads_unswizzled(pf, swizzle).then_some(heap_layout().own_view + k) } -/// The indices in [`heap_classes`] of the small floats' class (`RG11B10Float`'s, which -/// `RGB9E5Float` shares; a swizzled texture's is `OTHER`): the classes whose `float` write -/// through a heap handle quiets its NaNs (`StorageImageClass::SmallFloatQuietNan`), which a write -/// tests by its handle's index alone. -pub fn heap_small_float_indices() -> Vec { - let small = (PackedTexels::SmallFloat as u32) << TexelFormat::PACKED; - heap_classes() - .iter() - .enumerate() - .filter(|(_, &c)| c & TexelFormat::PACKED_MASK == small) - .filter_map(|(i, _)| u32::try_from(i).ok()) - .collect() -} - /// The index in [`heap_classes`] of `A8Unorm`'s class, which no other format's texture carries: /// a storage read or write through a heap handle carrying it converts the member's texels where /// the device holds such a texture's alpha in red (`metal::format::alpha_in_red`), which a heap's @@ -925,9 +895,7 @@ pub fn heap_alpha_in_red_index() -> u32 { } /// Whether a texture of pixel format `pf` holds 16-bit float channels of its own: its class is -/// the half-float family's without a packed field ([`heap_half_indices`]' classes), so a written -/// `half` stores its NaN there as the half's own bits, and elsewhere as the conversion of -/// `0x7fc00000` (`PushField::TextureHalfChannels`). +/// the half-float family's without a packed field. pub fn half_channels(pf: PixelFormat) -> bool { use crate::metal::bicubic::BicubicTexels; texel_format(pf).0 & (BicubicTexels::HALF | TexelFormat::PACKED_MASK) == BicubicTexels::HALF @@ -1552,16 +1520,24 @@ mod tests { assert_ne!(heap_class_index(PixelFormat::A8Unorm, moved), a8); } - /// The half-float heap classes a float write tests by index are the unswizzled half-float - /// formats' and no other format's: `RGBX16Float`'s too, `RGBA16Float`'s texels with three - /// channels, whose writes take the half class as its twin's. + /// The heap classes of the half-float family without a packed field are the unswizzled + /// half-float formats' and no other format's: `RGBX16Float`'s too, `RGBA16Float`'s texels with + /// three channels. /// /// The own-view entries of `R16Float`, `RG16Float` and `RGBA16Float` are half classes too, and /// the twin's indices are exactly those formats' own: no other format's texture, swizzled or /// not, carries one, and none carries an own-view index. #[test] fn a_heap_write_finds_the_half_formats_by_index() { - let half = heap_half_indices(); + use crate::metal::bicubic::BicubicTexels; + let half: Vec = heap_classes() + .iter() + .enumerate() + .filter(|(_, &c)| { + c & (BicubicTexels::HALF | TexelFormat::PACKED_MASK) == BicubicTexels::HALF + }) + .filter_map(|(i, _)| u32::try_from(i).ok()) + .collect(); let wanted = [ PixelFormat::R16Float, PixelFormat::RG16Float, diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 5ac59eb6f..04b7ebbf3 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -44,7 +44,6 @@ fn stage_module_bytes_are_little_endian_words() { strategies: StrategyCensus::default(), constant_blob: None, rounded_colors: Vec::new(), - half_bit_colors: Vec::new(), own_pixel_textures: Vec::new(), snapshot_textures: Vec::new(), private_bytes: 0, @@ -95,7 +94,6 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() { strategies: StrategyCensus::default(), constant_blob: None, rounded_colors: Vec::new(), - half_bit_colors: Vec::new(), own_pixel_textures: Vec::new(), snapshot_textures: Vec::new(), private_bytes: 0, diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 1d4e9f4ee..cc110cb6d 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -127,7 +127,6 @@ fn stage_footprint(stage: &StageModule) -> u64 { + clauses + vector_bytes::( stage.rounded_colors.capacity() - + stage.half_bit_colors.capacity() + stage.own_pixel_textures.capacity() + stage.snapshot_textures.capacity(), ) @@ -196,12 +195,6 @@ pub struct StageModule { /// every note holds under every specialization. [`StageModule::precision_notes_under`] /// gives the notes of the module as a pipeline specializes it. pub specialized_notes: Vec, - /// The color attachments this fragment stage writes as the bits of the half Metal stores, - /// through a 16-bit output, rounding none of their channels (`StageIo::half_bit_colors`), - /// sorted: a `half` output to a half-float attachment on a device that stores a 16-bit - /// output's bits but not a 32-bit output's NaN as Metal does. Each such write costs the stage - /// a few instructions per output; empty for every other stage. - pub half_bit_colors: Vec, /// The texture slots this fragment stage reads only at the fragment's own pixel, sorted /// (`StageInterface::own_pixel_textures`): a draw's reads of such a slot lie inside the /// rectangle bounding its scissors, a pixel wider each way for its helper invocations, on a @@ -812,15 +805,22 @@ pub enum PrecisionNote { /// `0x7fc00000` for the NaN results of its float arithmetic and functions, and Vulkan states no /// encoding, so a device may answer another sign or payload (llvmpipe: `0xffc00000`). Recorded /// wherever the module leaves a `float` operation that can produce a NaN to the device; not by - /// the functions that select Metal's NaN themselves, nor by Metal's precise and fast `float` - /// divisions. Also recorded by every read, sample, gather, and pixel fetch of a `half` texel: - /// Metal hands back the texel's own NaN, sign and payload, and Vulkan states no encoding for a - /// 16-bit float texel's decode (MoltenVK answers the canonical NaN for every one); on a device - /// that rounds a `half` through its conversion under the float controls (ANV, RADV), the NaN - /// that conversion makes of the device's decode, by default (`NanMinMaxPolicy::Native`). Also - /// recorded by a `half` texel's write to a storage texture that may hold a float format: Metal - /// stores a 16-bit float texel's NaN as the half's own bits and a 32-bit one's as `0x7fc00000`, - /// and the device converts the half widened. Also recorded by a 16-bit float attachment's blend + /// Metal's precise and fast `float` divisions. Also recorded by every read, sample, gather, and + /// pixel fetch of a `half` texel: Metal hands back the texel's own NaN, sign and payload, and + /// Vulkan states no encoding for a 16-bit float texel's decode (MoltenVK answers the canonical + /// NaN for every one); on a device that rounds a `half` through its conversion under the float + /// controls (ANV, RADV), the NaN that conversion makes of the device's decode. Also recorded by + /// a `float` read of a 16-bit float texture through its unsigned integer alias. Also recorded + /// by a `half` texel's write to a storage texture that may hold a float format, a slot whose + /// storage choice declares none or a heap element: Metal stores a 16-bit float texel's NaN as + /// the half's own bits and a 32-bit or packed small float one's as its canonical NaN, and the + /// device converts the half widened. Also recorded by a `float` write to a storage texture that + /// may hold a half-float or packed small float format, and by a `float` color output written as + /// computed to such an attachment, where the device is not measured to store Metal's NaN there: + /// Metal stores every NaN as its canonical one, and RADV and NVIDIA keep a NaN's payload bits. + /// Also recorded by a fixed-function vertex attribute of a float format narrower than 32 bits + /// that the function reads as `float`: Metal widens its NaN to `0x7fc00000`, and the device's + /// widening need not. Also recorded by a 16-bit float attachment's blend /// the function computes in the storage form, on a device not measured to store `0x7fc00000` in /// a 16-bit float storage image as Metal's `0x7e00` (`DriverDeviation::MetalFloatStorageNans`): /// the blend gives every NaN as `0x7fc00000`, and the device's store converts it (ANV stores @@ -1766,8 +1766,11 @@ pub enum PrecisionNote { /// NaN's encoding is the device's. Validation derives no tolerance from it. NativeHalfQuantize, /// Native device maths: a `float` or `half` operation's NaN result is the device's, its sign - /// and payload unselected, on a device whose arithmetic is not measured to answer Metal's - /// canonical NaN, under `NanMinMaxPolicy::Native` (the default). **Recorded bound:** where + /// and payload unselected, where Metal answers a NaN the device is not measured to answer: + /// every NaN Metal answers on a device whose arithmetic is not measured to answer Metal's + /// canonical NaN, and every NaN but the canonical one (an operand's bits, or the canonical NaN + /// with an operand's sign) on a device measured to answer it (MoltenVK on an Apple GPU). + /// **Recorded bound:** where /// Metal answers a NaN the device answers a NaN (the module keeps /// `SignedZeroInfNanPreserve` where Metal's entry keeps NaNs), its sign and payload the /// device's own (llvmpipe: `0xffc00000`), where Metal answers its canonical `0x7fc00000` @@ -1781,8 +1784,9 @@ pub enum PrecisionNote { 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 - /// `NClamp`, not the translation's selects of Metal's operand, on a device not measured to - /// answer Metal's, under `NanMinMaxPolicy::Native` (the default). **Recorded bound:** the + /// `NClamp`, on a device not measured to answer Metal's operand; and a `saturate` of a format + /// whose operand Metal's other functions do not pick (`bfloat`, `double`) on every device. + /// **Recorded bound:** the /// result is one of the operands, the one Metal answers but at three ties: of two NaNs a NaN /// (its bits the device's), where Metal answers the second operand's; of `+0` and `-0` either /// zero, where Metal answers the second; and an `f32` denormal beside a zero or another diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 4f84bd36c..392dc2dd2 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -1842,7 +1842,7 @@ pub(crate) fn spec_request( /// parameters `lower::stage_io` plans). Each with the numeric class it is declared with and /// whether its declared form is a 32-bit `float` (`float`, `float2`, `float3`, `float4`), which is /// what the projection's `VertexFetch::FixedFunction::narrow_float` may hold of it: only a 32-bit -/// `float` read canonicalizes the device's widening (`lower::stage_io::plan`). Empty for any other +/// `float` read notes the device's widening's NaN (`lower::stage_io::plan`). Empty for any other /// stage. pub(crate) fn declared_attributes( spec: &air::Entry, @@ -2327,8 +2327,9 @@ fn lower_inputs( pull_every, )?; // `narrow_float` is key data only where the entry reads the attribute as a 32-bit - // `float`; a `half`-declared attribute compiles the same either way, so the bit must - // not key a variant of it (`link::vertex::narrow_float_of_f32_reads`). + // `float`, whose NaN the module notes; a `half`-declared attribute compiles the same + // either way, so the bit must not key a variant of it + // (`link::vertex::narrow_float_of_f32_reads`). crate::pipeline::link::vertex::narrow_float_of_f32_reads(&mut projection, |a| { declared.get(&a).is_some_and(|&(_, f32_read)| f32_read) }); @@ -2674,7 +2675,7 @@ fn compile_kept( // 16-bit arithmetic, which they make Metal's too, or read from its bits by the device's // widening, which they make exact but for a NaN's bits: the entry declares them, and so // requires the device's float-controls properties for them, and no fact. A module that widens - // so leaves a NaN's bits to the device, as the profile does (`NanMinMaxPolicy::Native`). + // so leaves a NaN's bits to the device, as every profile does. if plan.families.arith.quantize == crate::spirv::builder::QuantizeForm::Controlled { let widens = crate::lower::arith::narrow::widens_bits(&module, m)?; if widens diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index 399963ca7..432a99445 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -1507,7 +1507,6 @@ fn stage_module(c: &CompiledFunction, linked: &Linked, i: usize) -> Result sampled, ReducedForms::AllNative => DevicePolicy { texel_conversion: TexelConversionPolicy::Device, - nan_and_min_max: NanMinMaxPolicy::Native, ..sampled }, } @@ -316,7 +315,6 @@ fn dropped_forms( let fact = RuntimeFact::ExactFormsOverCompilerLimit { sampling: base.sampling != policy.sampling || base.ycbcr_filter != policy.ycbcr_filter, texel_conversion: base.texel_conversion != policy.texel_conversion, - nan_and_min_max: base.nan_and_min_max != policy.nan_and_min_max, }; RuntimeDependency { fact, diff --git a/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs b/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs index 520296c3b..bea72f08c 100644 --- a/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs @@ -65,13 +65,12 @@ fn device(stem: &str, policy: DevicePolicy) -> Device { /// The forms a fitted pipeline's `dependencies` record it dropped, in the fact's field order; /// `None` where it records none. -fn dropped(dependencies: &[RuntimeDependency]) -> Option<[bool; 3]> { +fn dropped(dependencies: &[RuntimeDependency]) -> Option<[bool; 2]> { dependencies.iter().find_map(|d| match d.fact { RuntimeFact::ExactFormsOverCompilerLimit { sampling, texel_conversion, - nan_and_min_max, - } => Some([sampling, texel_conversion, nan_and_min_max]), + } => Some([sampling, texel_conversion]), _ => None, }) } @@ -83,7 +82,6 @@ fn fitted_as(reduced: P, compiled: &P) -> P { let fact = RuntimeFact::ExactFormsOverCompilerLimit { sampling: true, texel_conversion: true, - nan_and_min_max: true, }; let mut reduced = reduced; reduced @@ -163,7 +161,7 @@ fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() { assert_eq!(largest(&pipe), w_fast, "reduced to the fast default"); assert_eq!( dropped(&pipe.dependencies), - Some([true; 3]), + Some([true; 2]), "every exact form dropped" ); @@ -174,7 +172,7 @@ fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() { assert_eq!(largest(&pipe), w_sampling_native); assert_eq!( dropped(&pipe.dependencies), - Some([true, false, false]), + Some([true, false]), "only sampling dropped" ); } @@ -226,7 +224,7 @@ fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() { .expect("fitted from the functions"); assert_eq!(fitted.key, keys.pipeline); assert_eq!(largest(&fitted), w_fast); - assert_eq!(dropped(&fitted.dependencies), Some([true; 3])); + assert_eq!(dropped(&fitted.dependencies), Some([true; 2])); } /// A mesh render pipeline is fitted as a vertex and fragment pipeline is: past the bound, its @@ -506,7 +504,7 @@ fn a_compute_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() { assert_eq!(pipe.stage, sampled.stage, "{stem}: native sampling"); assert_eq!( dropped(&pipe.dependencies), - Some([true, false, false]), + Some([true, false]), "{stem}: only sampling dropped" ); assert_eq!( diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 9ee1e1a30..e1ea4f3c8 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -597,13 +597,6 @@ pub enum RuntimeFact { multisampled: bool, planes: bool, }, - /// The function writes `half` texels to the storage texture bound to the slot, whose storage - /// choice declares no format, and reads whether its channels are 16-bit floats - /// (`PushField::TextureHalfChannels`): Metal stores a written half's NaN as the half's own - /// bits in a 16-bit float channel and as its conversion of `0x7fc00000` in any other. The - /// binder writes 1 for a bound `R16Float`, `RG16Float` or `RGBA16Float` texture - /// (`metal::format::half_channels`), and 0 for any other and a neutral. - StorageTextureHalfChannels { slot: SlotRef }, /// The vertex function was compiled in capture form `form` (`VariantKey::captured_positions`, /// `LoweringInputs::captured_positions`): each vertex it runs writes a 32-byte record of its /// clip position, point size and restart flag from `PushField::CaptureAddress`, at the slot @@ -727,9 +720,10 @@ pub enum RuntimeFact { /// device stores exactly. A member the twin does not hold stores the device's conversion of a /// NaN, not Metal's: a half-float texture that is swizzled or whose image takes no view in /// another format, and where `packed` a packed small float one (`RG11B10Float`, - /// `RGB9E5Float`); `bind::heap_write_nans_converted` names such a texture. The module records - /// no `PrecisionNote::DeviceNanEncoding` for these writes: the consumer announces it at a - /// draw or dispatch whose heap holds such a texture. + /// `RGB9E5Float`); `bind::heap_write_nans_converted` names such a texture, which the consumer + /// announces `PrecisionNote::DeviceNanEncoding` for at a draw or dispatch whose heap holds + /// one. The module records that note for these writes too: a 32-bit or packed small float + /// member's NaN is the device's. HeapHalfTexelWrites { stage: Stage, packed: bool }, /// The render pipeline draws through synthesized geometry stages, one per topology class, of /// which a draw runs its class's (`RenderPipeline::runs_stage`): its fragment function reads @@ -768,7 +762,6 @@ pub enum RuntimeFact { ExactFormsOverCompilerLimit { sampling: bool, texel_conversion: bool, - nan_and_min_max: bool, }, /// The render pipeline was compiled under `VariantKey::quad_primitive_ids`, and its fragment /// function reads `[[primitive_id]]` from Vulkan's `PrimitiveId` shifted right by one diff --git a/crates/metal2vulkan/src/pipeline/link/contract.rs b/crates/metal2vulkan/src/pipeline/link/contract.rs index 1946d9b5d..ae74b0fa8 100644 --- a/crates/metal2vulkan/src/pipeline/link/contract.rs +++ b/crates/metal2vulkan/src/pipeline/link/contract.rs @@ -122,8 +122,8 @@ fn invariant(detail: &str) -> Error { } /// Whether data type `ty` is the scalar or vector `want` declares (32-bit `float` or -/// unsigned-integer lanes; signed-integer lanes for a color output to a signed-integer attachment; -/// 16-bit `float` lanes for a color output written as a half's bits). +/// unsigned-integer lanes; signed-integer lanes for a color output to a signed-integer +/// attachment). fn io_type_matches(m: &TypedModule, ty: TypeId, want: IoType) -> Result { let types = m.types(); let (elem, lanes) = match types.get(ty)? { @@ -131,15 +131,15 @@ fn io_type_matches(m: &TypedModule, ty: TypeId, want: IoType) -> Result (ty, 1), }; let numeric = match types.get(elem)? { - Type::Float { width } if u32::from(*width) == u32::from(want.bits) => IoNumeric::Float, + Type::Float { width: 32 } => IoNumeric::Float, Type::Int { width: 32, signed: false, - } if want.bits == 32 => IoNumeric::Uint, + } => IoNumeric::Uint, Type::Int { width: 32, signed: true, - } if want.bits == 32 => IoNumeric::Sint, + } => IoNumeric::Sint, _ => return Ok(false), }; Ok(numeric == want.numeric && lanes == want.components) diff --git a/crates/metal2vulkan/src/pipeline/link/geometry.rs b/crates/metal2vulkan/src/pipeline/link/geometry.rs index bb707777a..2f5a4986a 100644 --- a/crates/metal2vulkan/src/pipeline/link/geometry.rs +++ b/crates/metal2vulkan/src/pipeline/link/geometry.rs @@ -387,7 +387,6 @@ impl GeometryStages { constant_blob: None, rounded_colors: Vec::new(), specialized_notes: Vec::new(), - half_bit_colors: Vec::new(), own_pixel_textures: Vec::new(), snapshot_textures: Vec::new(), private_bytes: 0, diff --git a/crates/metal2vulkan/src/pipeline/link/graphics.rs b/crates/metal2vulkan/src/pipeline/link/graphics.rs index 9221a9c27..08f5b0ffd 100644 --- a/crates/metal2vulkan/src/pipeline/link/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/link/graphics.rs @@ -9,10 +9,10 @@ //! `ColorAttachmentBlend` when blending), the write mask, and the blend state; at most //! `maxColorAttachments` of them. A blend of factors one and zero, added, for color and alpha, //! of an attachment whose format converts the fragment function's output -//! (`StageIo::color_writes`), or that the function rounds (`StageIo::rounded_colors`) or writes -//! as a half's bits (`StageIo::half_bit_colors`), takes no Vulkan blend: Metal's blend stores the -//! output as written, as no blend does, which a device's blend could still change (x86 lavapipe -//! adds the clear's `+0` to a `-0` source of an `R16Float` attachment, Metal keeps `-0`). An +//! (`StageIo::color_writes`), or that the function rounds (`StageIo::rounded_colors`), takes no +//! Vulkan blend: Metal's blend stores the output as written, as no blend does, which a device's +//! blend could still change (x86 lavapipe adds the clear's `+0` to a `-0` source of an +//! `R16Float` attachment, Metal keeps `-0`). An //! attachment that no first (index 0) output of the fragment function names (every attachment of //! a pipeline without a fragment function) gets an empty write mask, so the draw leaves it //! unmodified. That is what Metal does where measured: an unblended attachment the function reads @@ -388,14 +388,13 @@ pub fn graphics_state( // Metal's blend of one and zero stores the output as written, as no blend // does, so an attachment whose format converts the output (its channels // take a rule of Metal's, `StageIo::color_writes`), or one the function - // rounds or writes as a half's bits, takes no Vulkan blend there, nor the + // rounds, takes no Vulkan blend there, nor the // format's blend support. But not a 16-bit float attachment's from a module // without fast math, whose blend Metal computes keeping the destination's // product by zero: that one blends, announced (`color_writes::keeps_zero`). let stored = fs.is_some_and(|f| { let color = index as u32; f.io.rounded_colors.contains(&color) - || f.io.half_bit_colors.contains(&color) || f.io.color_writes.get(&color).is_some_and(|rules| { rules.iter().flatten().any(|r| { *r != crate::pipeline::lower_inputs::ChannelWrite::Device diff --git a/crates/metal2vulkan/src/pipeline/link/mesh.rs b/crates/metal2vulkan/src/pipeline/link/mesh.rs index 482ae4319..829c30167 100644 --- a/crates/metal2vulkan/src/pipeline/link/mesh.rs +++ b/crates/metal2vulkan/src/pipeline/link/mesh.rs @@ -151,7 +151,6 @@ pub fn synthesized_stage( constant_blob: None, rounded_colors: Vec::new(), specialized_notes: Vec::new(), - half_bit_colors: Vec::new(), own_pixel_textures: Vec::new(), snapshot_textures: Vec::new(), private_bytes: 0, diff --git a/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs b/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs index 7a7025441..e464cb2e5 100644 --- a/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs +++ b/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs @@ -384,7 +384,6 @@ pub fn synthesized_stages( constant_blob: None, rounded_colors: Vec::new(), specialized_notes: Vec::new(), - half_bit_colors: Vec::new(), own_pixel_textures: Vec::new(), snapshot_textures: Vec::new(), private_bytes: 0, diff --git a/crates/metal2vulkan/src/pipeline/link/tests.rs b/crates/metal2vulkan/src/pipeline/link/tests.rs index 7d6e7ea57..cc8fa7537 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests.rs @@ -45,7 +45,6 @@ pub(super) fn io_ty(numeric: IoNumeric, components: u8) -> IoType { numeric, components, source_bits: 32, - bits: 32, } } diff --git a/crates/metal2vulkan/src/pipeline/link/vertex.rs b/crates/metal2vulkan/src/pipeline/link/vertex.rs index 8a1e8fe67..e0b17f28d 100644 --- a/crates/metal2vulkan/src/pipeline/link/vertex.rs +++ b/crates/metal2vulkan/src/pipeline/link/vertex.rs @@ -358,11 +358,11 @@ pub fn vertex_fetch_projection_for( /// Clear `narrow_float` on every fixed-function attribute of `projection` that `f32_read` does /// not hold. /// -/// The bit asks the function to canonicalize the device's widening of a narrow-float format, and -/// `lower::stage_io::plan` emits that canonicalization only where the attribute's declared form is -/// a 32-bit `float`: a `half`-declared attribute keeps the fetched code's own bits, as Metal's -/// `half` attribute does, whatever the format was. So the bit changes no instruction of such a -/// stage, and carrying it in the compile key would make one program two keys +/// The bit asks the function to note the NaN of the device's widening of a narrow-float format +/// (`PrecisionNote::DeviceNanEncoding`), and `lower::stage_io::plan` records that note only where +/// the attribute's declared form is a 32-bit `float`: a `half`-declared attribute keeps the fetched +/// code's own bits, as Metal's `half` attribute does, whatever the format was. So the bit changes +/// nothing of such a stage, and carrying it in the compile key would make one program two keys /// (`tests::engine_vertex_variants`). Both sides of the key apply this: the compile /// (`pipeline::compile::lower_inputs`, from the specialized entry's parameter forms) and link's /// recomputation ([`vertex_input_state`], from the stage's own declared types), so a stage @@ -379,8 +379,8 @@ pub fn narrow_float_of_f32_reads( } /// The projection entry of a resolved attribute. A fixed-function entry carries whether the Metal -/// format's components are floats narrower than 32 bits, which the function canonicalizes after -/// the device's widening (`VertexFetch::FixedFunction`); the rest of the format is `VertexAttribute` +/// format's components are floats narrower than 32 bits, whose NaN after the device's widening +/// the function notes (`VertexFetch::FixedFunction`); the rest of the format is `VertexAttribute` /// state. fn fetch_of(r: &Resolved<'_>) -> Result { Ok(match r.fetch { diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index 2c7727106..4d844c7a1 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -1426,22 +1426,12 @@ pub enum StorageImageClass { /// texels and `read_write` access). AlphaInRed, /// A half-float image (`R16Float`, `RG16Float`, `RGBA16Float`) written by a device not - /// measured to store every NaN as Metal's `0x7e00`: the shader writes a `float` channel's NaN - /// as `0x7fc00000`, every other value as computed, which the device's conversion rounds. A - /// `half` texel is written as it is, and reads are `Identity`'s. - HalfQuietNan, /// A 4:4:4 two-plane YCbCr texture a slot only writes, through an `R32G32B32A32_UINT` image /// of the texture's own (the consumer's write shadow): the shader writes each texel as the /// bits of its red, green and blue `float` channels (a `half` texel's widened exactly) and a /// 1, the mark of a written texel, which the consumer then encodes into the planes as Metal /// stores it (`bind::ycbcr_write`). The slot is declared `Rgba32ui`; it has no reads. YCbCrWrite, - /// An `RG11B10Float` image written by `float` texels, on every device: the shader writes a - /// channel's NaN as `0x7fc00000`, which every device measured stores as Metal's `0x7e0` (and - /// `0x3f0` in the 10-bit field), every other value as computed, which each rounds toward zero - /// as Metal does; RADV and NVIDIA keep another NaN's payload bits. A `half` texel is written - /// as it is, and reads are `Identity`'s. - SmallFloatQuietNan, /// A half-float image (`R16Float`, `RG16Float`, `RGBA16Float`) a slot writes, and may read, /// on a device not measured to store a written `half`'s NaN as its bits /// (`DriverDeviation::MetalHalfTexelWrites`), viewed through its unsigned integer alias of @@ -1508,8 +1498,8 @@ pub enum VertexFetch { /// `narrow_float`: the Metal format's components are floats narrower than 32 bits (a `half` /// format, or `FloatRG11B10`), which the device's vertex input widens to a `float` attribute /// with a widening of its own, **and** the function reads the attribute as a 32-bit `float`. - /// Metal's fetch answers its canonical NaN there, so such a read canonicalizes the value it - /// loads (`lower::stage_io`); a `half`-declared attribute keeps the fetched code's own bits, + /// Metal's fetch answers its canonical NaN there, so such a read records the device's NaN + /// (`PrecisionNote::DeviceNanEncoding`, `lower::stage_io`); a `half`-declared attribute keeps the fetched code's own bits, /// as Metal's `half` attribute does, so the bit is clear for one whatever the format was /// (`link::vertex::narrow_float_of_f32_reads`) and no variant of it is keyed on the format. /// The attribute's own encoding is link-time state, and this bit is what the compile key diff --git a/crates/metal2vulkan/src/pipeline/stage_io.rs b/crates/metal2vulkan/src/pipeline/stage_io.rs index eb4ec2a4d..0fb8a1cf7 100644 --- a/crates/metal2vulkan/src/pipeline/stage_io.rs +++ b/crates/metal2vulkan/src/pipeline/stage_io.rs @@ -46,8 +46,7 @@ //! link; it reads the role here, never the bytes. //! //! Every interface variable is 32-bit (narrow varyings are widened at the interface, so no varying -//! needs `storageInputOutput16`) but a color output written as the bits of the half Metal stores, -//! 16-bit ([`IoType::bits`]); [`IoType::source_bits`] keeps the AIR element width for format +//! needs `storageInputOutput16`); [`IoType::source_bits`] keeps the AIR element width for format //! checks. An attribute or color takes one whole location; a user varying takes one location at //! component 0 unless link packs varyings into shared locations, for which the module decorates //! every varying with a relocatable `Component`. @@ -202,13 +201,6 @@ pub struct StageIo { /// (`StageModule::rounded_colors`). #[cfg_attr(feature = "serde", serde(default))] pub rounded_colors: Vec, - /// The attachments among `color_writes` whose output the function writes as the bits of the - /// half Metal stores, through a 16-bit output, rounding none of its channels (a `half` - /// output to a half-float attachment), sorted: the device's conversion of a 32-bit output - /// would not keep a NaN's payload (`StageModule::half_bit_colors`). Link gives these, as - /// `rounded_colors`, no Vulkan blend of one and zero. - #[cfg_attr(feature = "serde", serde(default))] - pub half_bit_colors: Vec, /// The extended-range attachments the fragment function writes a `float` or `half` output /// to through output variables of dual-source index 0 /// (`LoweringInputs::extended_range_colors`), by color index: each output variable there is @@ -556,8 +548,8 @@ impl StageIo { } /// The vertex attributes the function reads in fixed function as a 32-bit `float` (`float`, - /// `float2`, `float3`, `float4`), which is where a narrow-float format's widening is - /// canonicalized (`link::vertex::narrow_float_of_f32_reads`). A `half`-declared attribute is + /// `float2`, `float3`, `float4`), which is where a narrow-float format's widening's NaN is + /// noted (`link::vertex::narrow_float_of_f32_reads`). A `half`-declared attribute is /// not among them, and neither is a pulled attribute, whose decode the module holds whole. pub fn f32_attributes(&self) -> std::collections::BTreeSet { self.inputs @@ -590,7 +582,6 @@ impl StageIo { numeric: IoNumeric::Uint, components: 1, source_bits: 32, - bits: 32, }; } match self.extended_range_colors.get(&attachment) { @@ -598,7 +589,6 @@ impl StageIo { numeric: IoNumeric::Uint, components: e.form.raw_components() as u8, source_bits: 32, - bits: 32, }, None => v.ty, } @@ -735,7 +725,7 @@ pub struct IoVariable { pub enum IoRole { /// Vertex attribute `index`, fetched by fixed-function vertex input. `narrow_float` is the /// `VertexFetch::FixedFunction` bit the function was compiled under: the Metal format's - /// components are floats narrower than 32 bits, whose widening the function canonicalizes + /// components are floats narrower than 32 bits, whose widening's NaN the function notes /// where it reads the attribute as `float`. Attribute { index: u32, narrow_float: bool }, /// A vertex output or fragment input matched by its AIR user key. @@ -855,7 +845,7 @@ pub enum Sampling { } /// The declared type of an interface variable: `components` lanes (1–4) of `numeric`, each of -/// `bits` bits. +/// 32 bits. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -865,9 +855,6 @@ pub struct IoType { /// The AIR element width (8, 16, or 32; 16 for `half`; 1 for `bool`, carried as `uint` 0 or /// 1): narrower values are widened at the interface. pub source_bits: u8, - /// The declared lane width: 32, or 16 for a `float` color output written as the bits of the - /// half Metal stores into a half-float attachment (`storageInputOutput16`). - pub bits: u8, } /// The numeric class the variable is declared with. diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 70c68b7e5..5f5be5eb2 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -1100,12 +1100,6 @@ pub enum PushField { /// clip mode is `MTLDepthClipModeClamp` in bit 4; words 1 and 2 the bits of viewport 0's near /// and far depth (`f32`); word 3 is 0 (`bind::shader_tests_words`). ShaderTestsState, - /// Whether the storage texture bound to the slot holds 16-bit float channels (`u32`, 1 or 0; - /// 0 where the binder binds a neutral): a `half` texel's write keeps the half where it is 1 - /// and writes every NaN as `0x7fc00000` where it is 0, as Metal stores a written half - /// (`RuntimeFact::StorageTextureHalfChannels`, a slot whose storage choice declares no - /// format). - TextureHalfChannels(SlotRef), /// The draw's capture layout for a vertex function compiled under /// `LoweringInputs::captured_positions` (`RuntimeFact::CapturedPositions`), a `uvec4`. In the /// vertices form: the draw's first vertex, its vertex count, its first instance, and 0. In the diff --git a/crates/metal2vulkan/src/pipeline/testing.rs b/crates/metal2vulkan/src/pipeline/testing.rs index d002efd67..6ce616dcd 100644 --- a/crates/metal2vulkan/src/pipeline/testing.rs +++ b/crates/metal2vulkan/src/pipeline/testing.rs @@ -160,9 +160,8 @@ pub fn storage_buffers(a: &FunctionArtifact) -> u32 { .sum() } -/// The default policy with Metal's NaN and minimum and maximum (`NanMinMaxPolicy::Exact`): the -/// policy of the tests of those forms, which the device's forms, the defaults, leave off a device -/// whose functions are not Metal's. The texel conversions are the default's. +/// The default policy with Metal's answers wherever a choice still offers them +/// ([`DevicePolicy::exact_answers`]) but the texel conversions, which are the default's. pub fn exact_maths() -> DevicePolicy { let native = DevicePolicy::default(); DevicePolicy { diff --git a/crates/metal2vulkan/src/spirv/builder/module.rs b/crates/metal2vulkan/src/spirv/builder/module.rs index 129448ef2..495ccec1c 100644 --- a/crates/metal2vulkan/src/spirv/builder/module.rs +++ b/crates/metal2vulkan/src/spirv/builder/module.rs @@ -144,9 +144,6 @@ pub struct ModuleBuilder { /// Whether that rounding is the device's own rather than one measured to be Metal's /// ([`ModuleBuilder::native_half`]). native_half: bool, - /// Whether a `half` texel keeps the NaN the device decoded under native half rounding too - /// ([`ModuleBuilder::texel_nans`]). - texel_nans: bool, /// Whether a `half`'s NaN bits are the device's conversion's under the float controls /// ([`ModuleBuilder::native_half_nans`]). native_half_nans: bool, @@ -283,25 +280,10 @@ impl ModuleBuilder { self.native_half } - /// Whether a `half` texel keeps the NaN the device decoded even where the module's `half` - /// rounding is the device's own ([`ModuleBuilder::native_half`]): where the NaN switch asks - /// for Metal's NaN (`NanMinMaxPolicy::Exact`). Emission sets it with the form; a builder that - /// never sets it keeps the NaN wherever the rounding is Metal's, as before. - pub fn set_texel_nans(&mut self, keep: bool) { - self.texel_nans = keep; - } - - /// Whether a `half` texel keeps its decoded NaN under native half rounding - /// ([`ModuleBuilder::set_texel_nans`]). - pub fn texel_nans(&self) -> bool { - self.texel_nans - } - /// Whether a `half`'s NaN bits are left to the device's conversion where the module rounds /// through it under the float controls ([`QuantizeForm::Controlled`]): a `half` read from its - /// bits is the device's widening of them, and a `half` texel takes the rounding's NaN, where - /// the profile leaves NaN bits to the device (`NanMinMaxPolicy::Native`). Emission sets it - /// with the form; a builder that never sets it decodes in integer arithmetic and keeps a + /// bits is the device's widening of them, and a `half` texel takes the rounding's NaN. Emission + /// sets it with the form; a builder that never sets it decodes in integer arithmetic and keeps a /// texel's NaN, as before. pub fn set_native_half_nans(&mut self, native: bool) { self.native_half_nans = native; diff --git a/crates/metal2vulkan/src/tests/engine_arith.rs b/crates/metal2vulkan/src/tests/engine_arith.rs index 6fb680aa2..4c082f118 100644 --- a/crates/metal2vulkan/src/tests/engine_arith.rs +++ b/crates/metal2vulkan/src/tests/engine_arith.rs @@ -2175,21 +2175,21 @@ fn every_profile() -> Vec { out } -/// Metal's fast division answers `0x7FC00000` for a NaN divisor of either sign (RADV answered -/// `0xffc00000`, a probe cases 9496749c and 3921d3e2), a NaN numerator, `0 / 0` and `inf / inf`, -/// which the module selects after the device's `OpFDiv` where the profile does not leave NaNs to -/// the device (where it does, the device's `OpFDiv` answers it; `inf / 2^127`, Metal's `inf · 0` -/// of its flushed reciprocal, is the device's infinity); its `f32` -/// denormals are the device's on every committed profile. The operands are integer bits, so the -/// division is the kernel's only float operation, and it records the device's arithmetic, its -/// division and its denormals, and no NaN note. The interpreter keeps NaN payloads, so each NaN -/// answer is the lowering's. +/// Metal's fast division answers `0x7FC00000` for a NaN divisor of either sign, a NaN numerator, +/// `0 / 0` and `inf / inf`; the module leaves that NaN to the device's `OpFDiv` on every profile +/// (RADV answered `0xffc00000` for a negative NaN divisor, a probe cases 9496749c and 3921d3e2), +/// selecting none, so the module is the same on both sides of `MetalCanonicalNans`, and records +/// `PrecisionNote::NativeNanEncoding` where the device is not measured to answer Metal's. Its +/// `f32` denormals are the device's on every committed profile. The operands are integer bits, so +/// the division is the kernel's only float operation, and it records the device's arithmetic, its +/// division and its denormals, and never `DeviceNanEncoding`. The interpreter answers a NaN, its +/// bits the device's, and `6 / 3` exactly. #[test] -fn a_fast_division_answers_metals_nans_on_every_profile() { +fn a_fast_division_leaves_its_nans_to_the_device() { let bits = |name: &str, b: u32| { format!(" %{name}.i = call i32 @llvm.umin.i32(i32 {b}, i32 -1)\n %{name} = bitcast i32 %{name}.i to float\n") }; - let kernel = |name: &'static str, x: u32, y: u32, want: u32| Kernel { + let kernel = |name: &'static str, x: u32, y: u32, want: Option| Kernel { name, body: format!( "{}{} %r = fdiv arcp float %x, %y\n", @@ -2197,27 +2197,30 @@ fn a_fast_division_answers_metals_nans_on_every_profile() { bits("y", y) ), float: true, - want: Some(want), + want, needs: &[], note: None, }; - let nan = 0x7FC0_0000; let ks = [ - kernel("fast_one_by_nan", 0x3F80_0000, 0x7FC0_0000, nan), - kernel("fast_inf_by_nan", 0x7F80_0000, 0x7FC0_0000, nan), - kernel("fast_one_by_negative_nan", 0x3F80_0000, 0xFFC0_0000, nan), - kernel("fast_nan_by_two", 0x7FC0_0001, 0x4000_0000, nan), - kernel("fast_zero_by_zero", 0, 0, nan), - kernel("fast_inf_by_inf", 0x7F80_0000, 0x7F80_0000, nan), - kernel("fast_six_by_three", 0x40C0_0000, 0x4040_0000, 0x4000_0000), + kernel("fast_one_by_nan", 0x3F80_0000, 0x7FC0_0000, None), + kernel("fast_inf_by_nan", 0x7F80_0000, 0x7FC0_0000, None), + kernel("fast_one_by_negative_nan", 0x3F80_0000, 0xFFC0_0000, None), + kernel("fast_nan_by_two", 0x7FC0_0001, 0x4000_0000, None), + kernel("fast_zero_by_zero", 0, 0, None), + kernel("fast_inf_by_inf", 0x7F80_0000, 0x7F80_0000, None), + kernel( + "fast_six_by_three", + 0x40C0_0000, + 0x4040_0000, + Some(0x4000_0000), + ), ]; let Some(bitcode) = assemble("fast-divide-specials", &module(&ks)) else { return; }; + nans_are_the_device_s(&bitcode, &ks, false, &[], &|_, fact| !fact); for stem in every_profile() { let p = profile(&stem, exact_maths()).expect("profile"); - let metal_functions = - p.takes_driver_deviation(crate::error::DriverDeviation::MetalFloatFunctions); let device_nans = p.takes_driver_deviation(crate::error::DriverDeviation::MetalCanonicalNans); for kk in &ks { @@ -2235,22 +2238,22 @@ fn a_fast_division_answers_metals_nans_on_every_profile() { a.precision ); } + assert_eq!( + a.precision.contains(&PrecisionNote::NativeNanEncoding), + !device_nans, + "{what}: {:?}", + a.precision + ); assert!( !a.precision.contains(&PrecisionNote::DeviceNanEncoding), "{what}: {:?}", a.precision ); - // Where the device answers Metal's canonical NaN itself (the measured - // `MetalCanonicalNans`), the interpreter's NaN is no Metal's. - if device_nans && kk.want == Some(nan) { - continue; - } let got = interpret(&bitcode, kk.name, &p); - assert_eq!( - Some(got), - kk.want, - "{what} (Metal's functions: {metal_functions}): {got:#x}" - ); + match kk.want { + Some(want) => assert_eq!(got, want, "{what}: {got:#x}"), + None => assert!(stores_nan(got, false), "{what}: {got:#x}"), + } } } } @@ -3659,7 +3662,7 @@ fn decorates_fast_math(words: &[u32]) -> bool { } /// The kernels of the NaN-model tests: their declarations beside [`DECLS`]. -const NAN_DECLS: &str = "declare float @air.fast_round.f32(float)\ndeclare float @air.fast_asin.f32(float)\ndeclare float @air.fast_tan.f32(float)\ndeclare float @air.asin.f32(float)\n"; +const NAN_DECLS: &str = "declare float @air.fast_round.f32(float)\ndeclare float @air.fast_asin.f32(float)\ndeclare float @air.fast_tan.f32(float)\ndeclare float @air.asin.f32(float)\ndeclare float @air.sign.f32(float)\ndeclare float @air.fmedian3.f32(float, float, float)\n"; /// A kernel storing `%s`'s bits, `float` `%s` defined by `body`. fn nan_kernel(name: &'static str, body: String, want: Option) -> Kernel { @@ -3669,13 +3672,73 @@ fn nan_kernel(name: &'static str, body: String, want: Option) -> Kernel { } } -/// The canonical NaN of `float` arithmetic is left to the device exactly where the profile takes -/// its driver's deviation `MetalCanonicalNans`, that its arithmetic answers it, and selected -/// everywhere else; flipping the fact on either device flips that emission and nothing else. The -/// other classes are selected whatever the fact: `round` returns a NaN operand's own bits. The -/// interpreter keeps a NaN operand's payload, as such a device would. +/// Whether `bits` are a NaN of the stored format: a `half`'s, zero-extended, where `half`. +fn stores_nan(bits: u32, half: bool) -> bool { + match half { + true => bits <= 0xFFFF && bits & 0x7C00 == 0x7C00 && bits & 0x3FF != 0, + false => f32::from_bits(bits).is_nan(), + } +} + +/// Kernels `ks` of `bitcode` (each storing a NaN's bits, `half` ones zero-extended where `half`) +/// on `lavapipe` and `moltenvk-m3`, each with its driver's deviation `MetalCanonicalNans` taken +/// and not: the module selects no NaN, so it is the same word for word on both sides of the fact; +/// it records `PrecisionNote::NativeNanEncoding` exactly where `noted(kernel, fact)` and never +/// `DeviceNanEncoding`; and the interpreter's answer is the kernel's `want`, or a NaN, its bits the +/// device's, where it has none, but for the kernels `unread` names, whose device instruction the +/// interpreter does not evaluate. +fn nans_are_the_device_s( + bitcode: &[u8], + ks: &[Kernel], + half: bool, + unread: &[&str], + noted: &dyn Fn(&str, bool) -> bool, +) { + for stem in ["lavapipe", "moltenvk-m3"] { + for kk in ks { + let mut emitted = Vec::new(); + for fact in [false, true] { + let p = profile_with_canonical_nans(stem, fact); + let what = format!("{} on {stem}, MetalCanonicalNans {fact}", kk.name); + let a = compile(bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); + let (_, words) = + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + assert_eq!( + a.precision.contains(&PrecisionNote::NativeNanEncoding), + noted(kk.name, fact), + "{what}: {:?}", + a.precision + ); + assert!( + !a.precision.contains(&PrecisionNote::DeviceNanEncoding), + "{what}: {:?}", + a.precision + ); + if !unread.contains(&kk.name) { + let got = interpret(bitcode, kk.name, &p); + match kk.want { + Some(want) => assert_eq!(got, want, "{what}: {got:#x}"), + None => assert!(stores_nan(got, half), "{what}: {got:#x}"), + } + } + emitted.push(words); + } + assert!( + emitted[0] == emitted[1], + "{} on {stem}: the module changes with the fact", + kk.name + ); + } + } +} + +/// A NaN of `float` arithmetic is the device's on every profile: the module selects none, whatever +/// the profile's `MetalCanonicalNans` fact, and records `PrecisionNote::NativeNanEncoding` where +/// the device is not measured to answer Metal's: for `+`, whose canonical NaN the fact covers, +/// where the fact is absent, and for `round`, which returns a NaN operand's own bits on Metal, +/// whatever the fact. The interpreter keeps a NaN operand's payload, as such a device would. #[test] -fn the_canonical_nan_follows_the_device_fact() { +fn a_float_nan_is_the_device_s_on_every_profile() { let ks = [ nan_kernel( "nan_fadd", @@ -3688,44 +3751,15 @@ fn the_canonical_nan_follows_the_device_fact() { "{} %s = call float @air.round.f32(float %x)\n", ob("x", 0x7F80_0001) ), - Some(0x7F80_0001), + None, ), ]; - let text = module(&ks); - let Some(bitcode) = assemble("nan-fact", &text) else { + let Some(bitcode) = assemble("nan-fact", &module(&ks)) else { return; }; - for stem in ["moltenvk-m3", "lavapipe"] { - let mut emitted: Vec>> = Vec::new(); - for fact in [true, false] { - let p = profile_with_canonical_nans(stem, fact); - let mut per = Vec::new(); - for kk in &ks { - let what = format!("{} on {stem}, MetalCanonicalNans {fact}", kk.name); - let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let (_, words) = - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let got = interpret(&bitcode, kk.name, &p); - let (is_nan, bits) = nan_tests(&words); - if kk.name == "nan_fadd" { - assert!(f32::from_bits(got).is_nan(), "{what}: {got:#x}"); - assert_eq!(got == 0x7FC0_0000, !fact, "{what}: {got:#x}"); - assert_eq!(is_nan + bits, usize::from(!fact), "{what}"); - } else { - assert_eq!(Some(got), kk.want, "{what}: {got:#x}"); - } - assert!( - !a.precision.contains(&PrecisionNote::DeviceNanEncoding), - "{what}: {:?}", - a.precision - ); - per.push(words); - } - emitted.push(per); - } - assert_ne!(emitted[0][0], emitted[1][0], "nan_fadd on {stem}"); - assert_eq!(emitted[0][1], emitted[1][1], "nan_round on {stem}"); - } + nans_are_the_device_s(&bitcode, &ks, false, &[], &|name, fact| { + name == "nan_round" || !fact + }); // The committed profiles state the fact for the measured device only. for (stem, fact) in [("moltenvk-m3", true), ("lavapipe", false)] { let p = profile(stem, exact_maths()).expect("profile"); @@ -3937,12 +3971,11 @@ fn float_denormals_are_the_devices_and_noted_off_the_device_fact() { /// `air.sincos` answers the NaN its `sin` and `cos` answer as calls of their own, since Metal's /// `sincos` is its `sin` and `cos` word for word (cases 7b283404 and f6524207, every pair): precise -/// `sin` and `cos` without fast-math flags answer the canonical NaN, so each result selects it -/// where the device fact does not leave it to the device, and the call notes no -/// `DeviceNanEncoding`. The cosine is stored, so it is selected even where the sine is not read. -/// (The interpreter does not model `Sin`; the shape is the module's.) +/// `sin` and `cos` without fast-math flags answer the canonical NaN, which the device answers where +/// the profile takes `MetalCanonicalNans`; elsewhere either result, read or not, is noted +/// `PrecisionNote::NativeNanEncoding`, and neither is selected. #[test] -fn sincos_answers_the_nan_of_sin_and_cos() { +fn sincos_answers_the_device_s_nan() { let kernel = |name: &'static str, read: &str| { Kernel { name, @@ -3960,100 +3993,62 @@ fn sincos_answers_the_nan_of_sin_and_cos() { kernel("sincos_nan_sine", "%t"), kernel("sincos_nan_cosine", "%cv"), ]; - // The selects each kernel's results add where the fact leaves the NaN to the module: the - // sine's and the cosine's, then the cosine's alone (the sine is not read). - let selects = [2, 1]; - let text = module(&ks); - let Some(bitcode) = assemble("sincos-nan", &text) else { + let Some(bitcode) = assemble("sincos-nan", &module(&ks)) else { return; }; - for stem in ["moltenvk-m3", "lavapipe"] { - for (kk, selects) in ks.iter().zip(selects) { - let mut tests = Vec::new(); - for fact in [true, false] { - let p = profile_with_canonical_nans(stem, fact); - let what = format!("{} on {stem}, MetalCanonicalNans {fact}", kk.name); - let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let (_, words) = - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - assert!( - !a.precision.contains(&PrecisionNote::DeviceNanEncoding), - "{what}: {:?}", - a.precision - ); - let (is_nan, bits) = nan_tests(&words); - tests.push(is_nan + bits); - } - assert_eq!(tests[1], tests[0] + selects, "{} on {stem}", kk.name); - } - } + let unread = ["sincos_nan_sine", "sincos_nan_cosine"]; + nans_are_the_device_s(&bitcode, &ks, false, &unread, &|_, fact| !fact); } -/// A result whose every use drops its NaN's bits (a float comparison, or arithmetic that answers -/// the canonical NaN itself) needs no select, so a chain of `float` arithmetic tests once, at its -/// end, and a result only compared tests never. -#[test] -fn a_nan_is_selected_only_where_its_bits_are_observed() { - let xyz = format!( - "{}{}{}", - ob("x", 0xFFC0_1234), - ob("y", 0x4000_0000), - ob("z", 0x7F80_0001) - ); - let ks = [ - nan_kernel( - "nan_single", - format!("{xyz} %s = fadd float %x, %y\n"), - Some(0x7FC0_0000), - ), - nan_kernel( - "nan_chain", - format!("{xyz} %p = fmul float %x, %y\n %q = fsub float %p, %y\n %s = fadd float %q, %z\n"), - Some(0x7FC0_0000), - ), - k( - "nan_compared", - format!("{xyz} %p = fmul float %x, %y\n %c = fcmp olt float %p, 0.0\n %r = zext i1 %c to i32\n"), - 0, - ), - ]; - let Some(bitcode) = assemble("nan-observed", &module(&ks)) else { - return; - }; - let p = profile("lavapipe", exact_maths()).expect("profile"); - for (kk, tests) in ks.iter().zip([1, 1, 0]) { - let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{}: {e:?}", kk.name)); - let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{}: {e}", kk.name)); - let (is_nan, bits) = nan_tests(&words); - assert_eq!(is_nan + bits, tests, "{}", kk.name); - let got = interpret(&bitcode, kk.name, &p); - assert_eq!(Some(got), kk.want, "{}: {got:#x}", kk.name); - } -} - -/// The select's NaN test is `OpIsNan` only in an entry that declares `SignedZeroInfNanPreserve 32`; -/// where every float operation carries `nnan`/`ninf`/`nsz` the entry declares nothing, a device may -/// fold `OpIsNan`, and the test is the bits instead, which still answers Metal's NaN. No module +/// A NaN test (Metal's `median3`'s) is `OpIsNan` only in an entry that declares +/// `SignedZeroInfNanPreserve 32`; where every float operation carries `nnan`/`ninf`/`nsz` the entry +/// declares nothing, a device may fold `OpIsNan`, and the test is the bits instead, which still +/// answers Metal's NaN. No module /// decorates a value `FPFastMathMode`, so nothing tells a device a tested value is no NaN; nor do /// the NaN-model probes' fast-math fixtures. #[test] fn a_nan_test_no_float_mode_folds() { let x = ob("x", 0xFFC0_1234); let ks = [ + // A sum's NaN is the device's. nan_kernel( "strict_fadd", format!("{x} %s = fadd float %x, 1.0\n"), - Some(0x7FC0_0000), + None, ), nan_kernel( "fast_fadd", format!("{x} %s = fadd fast float %x, 1.0\n"), - Some(0x7FC0_0000), + None, ), nan_kernel( "fast_round", format!("{x} %s = call fast float @air.fast_round.f32(float %x)\n"), - Some(0xFFC0_1234), + None, + ), + // Metal's `median3` returns an operand, a NaN losing, and `sign` `+0` for a NaN, which + // the module tests for. + nan_kernel( + "strict_median3", + format!("{x} %s = call float @air.fmedian3.f32(float %x, float 1.0, float 2.0)\n"), + Some(0x3F80_0000), + ), + nan_kernel( + "fast_median3", + format!( + "{x} %s = call fast float @air.fmedian3.f32(float %x, float 1.0, float 2.0)\n" + ), + Some(0x3F80_0000), + ), + nan_kernel( + "strict_sign", + format!("{x} %s = call float @air.sign.f32(float %x)\n"), + Some(0), + ), + nan_kernel( + "fast_sign", + format!("{x} %s = call fast float @air.sign.f32(float %x)\n"), + Some(0), ), // The device's `asin` and `tan`, which the interpreter does not evaluate. nan_kernel( @@ -4109,10 +4104,7 @@ fn a_nan_test_no_float_mode_folds() { is_nan_tested += usize::from(is_nan > 0); if let Some(want) = kk.want { let got = interpret(&bitcode, kk.name, &p); - // moltenvk-m3 leaves a sum's NaN to its device; the interpreter is not one. - if stem != "moltenvk-m3" || kk.name == "fast_round" { - assert_eq!(got, want, "{what}: {got:#x}"); - } + assert_eq!(got, want, "{what}: {got:#x}"); } } } @@ -4163,59 +4155,57 @@ fn half_nan_kernel(name: &'static str, body: String, want: Option) -> Kerne /// Class B: Metal's `half` `+`, `*`, and `air.fma.f16`, with or without fast-math flags, and its /// narrowing of a `float` to `half` (`fptrunc`, and `air.convert` from class E's version) answer -/// the canonical `half` NaN `0x7E00`, which the lowering selects (one NaN test per result, none -/// where the device fact leaves the canonical class to the device); a chain selects once, at its -/// end. `half` `-` is class K's, selected the same way. The interpreter's `OpQuantizeToF16` answers -/// `0x7E00` itself, so the selects are counted against the same kernel compiled with the fact. +/// the canonical `half` NaN `0x7E00`, as `half` `-` (class K's) does. The NaN is the device's on +/// every profile, selected nowhere, and noted `PrecisionNote::NativeNanEncoding` where the profile +/// does not take `MetalCanonicalNans`. #[test] -fn half_nans_answer_metals_half_nan() { +fn half_nans_answer_the_device_s_nan() { let hx = oh("hx", 0xFE01); let x = ob("x", 0xFFC0_1234); let ks = [ half_nan_kernel( "half_fadd", format!("{hx} %s = fadd half %hx, 0xH3C00\n"), - Some(0x7E00), + None, ), half_nan_kernel( "half_fmul", format!("{hx} %s = fmul half %hx, 0xH4000\n"), - Some(0x7E00), + None, ), half_nan_kernel( "half_fma", format!("{hx} %s = call half @air.fma.f16(half %hx, half 0xH3C00, half 0xH0000)\n"), - Some(0x7E00), + None, ), half_nan_kernel( "narrow", format!("{x} %s = fptrunc float %x to half\n"), - Some(0x7E00), + None, ), half_nan_kernel( "narrow_then_add", format!("{x} %n = fptrunc float %x to half\n %s = fadd half %n, 0xH3C00\n"), - Some(0x7E00), + None, ), half_nan_kernel( "narrow_convert", format!( "{x} %v = insertelement <4 x float> , float %x, i32 2\n %w = call <4 x half> @air.convert.f.v4f16.f.v4f32(<4 x float> %v)\n %s = extractelement <4 x half> %w, i32 2\n" ), - Some(0x7E00), + None, ), half_nan_kernel( "half_fadd_fast", format!("{hx} %s = fadd fast half %hx, 0xH3C00\n"), - Some(0x7E00), + None, ), half_nan_kernel( "half_fsub", format!("{hx} %s = fsub half %hx, 0xH3C00\n"), - Some(0x7E00), + None, ), ]; - let selects = [1, 1, 1, 1, 1, 1, 1, 1]; let text = module(&ks).replace( DECLS, &format!("{DECLS}declare half @air.fma.f16(half, half, half)\ndeclare <4 x half> @air.convert.f.v4f16.f.v4f32(<4 x float>)\n"), @@ -4223,59 +4213,36 @@ fn half_nans_answer_metals_half_nan() { let Some(bitcode) = assemble("nan-half", &text) else { return; }; - for stem in ["lavapipe", "moltenvk-m3"] { - for (kk, n) in ks.iter().zip(selects) { - let mut tests = Vec::new(); - for fact in [false, true] { - let p = profile_with_canonical_nans(stem, fact); - let what = format!("{} on {stem}, MetalCanonicalNans {fact}", kk.name); - let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let (_, words) = - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let (is_nan, bits) = nan_tests(&words); - tests.push(is_nan + bits); - if let Some(want) = kk.want { - let got = interpret(&bitcode, kk.name, &p); - assert_eq!(got, want, "{what}: {got:#x}"); - } - } - assert_eq!(tests[0], tests[1] + n, "{} on {stem}", kk.name); - } - } + nans_are_the_device_s(&bitcode, &ks, true, &[], &|_, fact| !fact); } /// Class C: Metal widens a `half` NaN to the canonical `float` NaN `0x7FC00000`, sign and payload /// dropped, by `fpext` and by its intrinsic form `air.convert`. A `half` is held widened, so the /// widening emits no device operation and every device keeps the payload, MoltenVK included: the -/// select is emitted whatever the device fact states. The interpreter keeps the payload as a device -/// would, so the stored bits show the select. A widening only compared needs none. +/// module selects nothing and notes `PrecisionNote::NativeNanEncoding` whatever the device fact +/// states. The interpreter keeps the payload as a device would. #[test] -fn a_widened_half_nan_is_canonical_on_every_profile() { +fn a_widened_half_nan_keeps_its_payload_on_every_profile() { let hx = oh("hx", 0xFE01); let ks = [ nan_kernel( "widen", format!("{hx} %s = fpext half %hx to float\n"), - Some(0x7FC0_0000), + None, ), nan_kernel( "widen_vector", format!( "{hx} %v = insertelement <2 x half> , half %hx, i32 1\n %w = fpext <2 x half> %v to <2 x float>\n %s = extractelement <2 x float> %w, i32 1\n" ), - Some(0x7FC0_0000), + None, ), nan_kernel( "widen_convert", format!( "{hx} %v = insertelement <4 x half> , half %hx, i32 1\n %w = call <4 x float> @air.convert.f.v4f32.f.v4f16(<4 x half> %v)\n %s = extractelement <4 x float> %w, i32 1\n" ), - Some(0x7FC0_0000), - ), - k( - "widen_compared", - format!("{hx} %s = fpext half %hx to float\n %c = fcmp olt float %s, 0.0\n %r = zext i1 %c to i32\n"), - 0, + None, ), ]; let text = module(&ks).replace( @@ -4285,35 +4252,17 @@ fn a_widened_half_nan_is_canonical_on_every_profile() { let Some(bitcode) = assemble("nan-widen", &text) else { return; }; - for stem in ["lavapipe", "moltenvk-m3"] { - for fact in [false, true] { - let p = profile_with_canonical_nans(stem, fact); - for kk in &ks { - let what = format!("{} on {stem}, MetalCanonicalNans {fact}", kk.name); - let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let (_, words) = - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let (is_nan, bits) = nan_tests(&words); - let selects = usize::from(kk.name != "widen_compared"); - assert!(is_nan + bits >= selects, "{what}"); - if kk.name == "widen_compared" { - assert_eq!(is_nan + bits, 0, "{what}"); - } - let got = interpret(&bitcode, kk.name, &p); - assert_eq!(Some(got), kk.want, "{what}: {got:#x}"); - } - } - } + nans_are_the_device_s(&bitcode, &ks, false, &[], &|_, _| true); } /// Class D: Metal's `half` `fneg` and `fabs` answer the canonical `half` NaN `0x7E00`, with or -/// without fast-math flags. A device computes both exactly on the held value's sign, so the select -/// is emitted whatever the device fact states: one NaN test more than the same value stored -/// unchanged, on either profile and in either fact state. An `fadd` whose only use is the `fneg` -/// selects nothing of its own, and a `fneg` only compared none. The interpreter keeps a `half` NaN's payload through the held value, as a device does (the value -/// stored unchanged is `0xFE01`), so the stored bits show the select. +/// without fast-math flags. A device computes both exactly on the held value's sign, so a NaN's +/// payload is kept on every profile: the module selects nothing and notes +/// `PrecisionNote::NativeNanEncoding` whatever the device fact states, as for an `fadd` whose only +/// use is the `fneg`. The interpreter keeps a `half` NaN's payload through the held value, as a +/// device does (the value stored unchanged is `0xFE01`, and notes nothing). #[test] -fn half_sign_operations_answer_the_canonical_nan_on_every_profile() { +fn half_sign_operations_keep_a_nan_s_payload_on_every_profile() { let hx = oh("hx", 0xFE01); let ks = [ half_nan_kernel( @@ -4321,62 +4270,33 @@ fn half_sign_operations_answer_the_canonical_nan_on_every_profile() { format!("{hx} %s = freeze half %hx\n"), Some(0xFE01), ), - half_nan_kernel( - "half_fneg", - format!("{hx} %s = fneg half %hx\n"), - Some(0x7E00), - ), + half_nan_kernel("half_fneg", format!("{hx} %s = fneg half %hx\n"), None), half_nan_kernel( "half_fneg_fast", format!("{hx} %s = fneg fast half %hx\n"), - Some(0x7E00), + None, ), half_nan_kernel( "half_fabs", format!("{hx} %s = call half @air.fabs.f16(half %hx)\n"), - Some(0x7E00), + None, ), half_nan_kernel( "half_fabs_fast", format!("{hx} %s = call fast half @air.fabs.f16(half %hx)\n"), - Some(0x7E00), + None, ), half_nan_kernel( "half_fadd_then_fneg", format!("{hx} %n = fadd half %hx, 0xH3C00\n %s = fneg half %n\n"), - Some(0x7E00), - ), - k( - "half_fneg_compared", - format!("{hx} %n = fneg half %hx\n %c = fcmp olt half %n, 0xH0000\n %r = zext i1 %c to i32\n"), - 0, + None, ), ]; let text = module(&ks).replace(DECLS, &format!("{DECLS}declare half @air.fabs.f16(half)\n")); let Some(bitcode) = assemble("nan-half-sign", &text) else { return; }; - for stem in ["lavapipe", "moltenvk-m3"] { - for fact in [false, true] { - let p = profile_with_canonical_nans(stem, fact); - let mut tests = Vec::new(); - for kk in &ks { - let what = format!("{} on {stem}, MetalCanonicalNans {fact}", kk.name); - let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let (_, words) = - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let (is_nan, bits) = nan_tests(&words); - tests.push(is_nan + bits); - let got = interpret(&bitcode, kk.name, &p); - assert_eq!(Some(got), kk.want, "{what}: {got:#x}"); - } - let what = format!("on {stem}, MetalCanonicalNans {fact}: {tests:?}"); - for t in &tests[1..6] { - assert_eq!(*t, tests[0] + 1, "{what}"); - } - assert_eq!(tests[6], 0, "{what}"); - } - } + nans_are_the_device_s(&bitcode, &ks, true, &[], &|name, _| name != "half_kept"); } /// Class E: Metal's `float` `fneg` and `fabs` (`air.fabs`, `air.fast_fabs`, and `llvm.fabs`, which @@ -4480,15 +4400,15 @@ fn float_sign_operations_move_the_bits_on_every_profile() { /// Class F: Metal's `float` `fmin`, `fmax`, `min3`, `max3`, and `clamp`, precise and `fast_` alike, /// and `llvm.minnum`/`llvm.maxnum` with every flag (Metal's fast-math `a < b ? a : b`), with none -/// and with some, answer an operand bit for bit on every profile (`nan_minmax`, `nan_minmax_fast`, -/// and their zeros-and-denormals cases, every lane; for the other flag states): a NaN loses, two -/// NaNs and a tie answer the second operand, and a denormal compares as zero but is returned -/// itself. Off a profile that takes `DriverDeviation::MetalMinMax` no device `NMin`, `NMax`, or -/// `NClamp` decides it; on one those instructions do, measured to be Metal's (the interpreter -/// models them so), and the module requires `VkProperty::MetalMinMax`. No +/// and with some, answer an operand bit for bit (`nan_minmax`, `nan_minmax_fast`, and their +/// zeros-and-denormals cases, every lane; for the other flag states): a NaN loses, two NaNs and a +/// tie answer the second operand, and a denormal compares as zero but is returned itself. On every +/// profile the device's `NMin`, `NMax`, or `NClamp` decides it: where the profile takes +/// `DriverDeviation::MetalMinMax` measured to be Metal's (the interpreter models them so), and the +/// module requires `VkProperty::MetalMinMax`; elsewhere noted `PrecisionNote::NativeMinMax`. No /// device note is recorded. #[test] -fn float_min_max_answer_metals_operand_on_every_profile() { +fn float_min_max_are_the_device_s_on_every_profile() { let two = |a: u32, b: u32| format!("{}{}", ob("x", a), ob("y", b)); let three = |a: u32, b: u32, c: u32| format!("{}{}{}", ob("x", a), ob("y", b), ob("z", c)); let ks = [ @@ -4634,7 +4554,13 @@ fn float_min_max_answer_metals_operand_on_every_profile() { let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); let device = p.takes_driver_deviation(crate::error::DriverDeviation::MetalMinMax); - assert_eq!(device_pick(&words) > 0, device, "{what}"); + assert!(device_pick(&words) > 0, "{what}"); + assert_eq!( + a.precision.contains(&PrecisionNote::NativeMinMax), + !device, + "{what}: {:?}", + a.precision + ); assert_eq!( a.requirements .properties @@ -4651,7 +4577,7 @@ fn float_min_max_answer_metals_operand_on_every_profile() { // The interpreter reads a denormal operand of `NMin` by its value; Metal's reading, a // zero, is the device's, measured by the driver facts and the gate lane // (`runtime_lane::driver_deviations`). - if device && kk.name.contains("denormal") { + if kk.name.contains("denormal") { continue; } let got = interpret(&bitcode, kk.name, &p); @@ -4830,14 +4756,14 @@ fn mix_is_metals_fused_form_on_moltenvk_and_the_devices_fmix_elsewhere() { /// Class K: Metal's `half` functions answer the canonical `half` NaN `0x7E00` with and without /// fast-math flags (`nan_half`, `nan_half_fast`): `llvm.fmuladd`, `ldexp` (unlike `float`'s, which -/// returns the operand), and `sqrt` take one select more where the device fact does not leave the -/// canonical class to the device. `round` returns a NaN operand itself, a signaling one kept, and -/// `+0` for a zero result; `asin`'s domain error takes the operand's sign (a select whatever the -/// fact); and `fract` with every flag answers `0x3BFF` for an infinity, where without flags it -/// answers `+0`. The interpreter's `OpQuantizeToF16` answers `0x7E00` itself, so the canonical -/// selects are counted against the same kernel compiled with the fact. +/// returns the operand), and `sqrt`, which the device answers where the profile takes +/// `MetalCanonicalNans` and which are noted `PrecisionNote::NativeNanEncoding` elsewhere. `round` +/// returns a NaN operand itself on Metal, and `asin`'s domain error takes the operand's sign: both +/// the device's NaN on every profile, noted whatever the fact. None is selected. `round` answers +/// `+0` for a zero result, and `fract` with every flag answers `0x3BFF` for an infinity, where +/// without flags it answers `+0`. #[test] -fn half_functions_answer_metals_half_nan() { +fn half_functions_answer_the_device_s_nan() { let hx = oh("hx", 0xFE01); let snan = oh("hx", 0x7C01); let inf = oh("hx", 0x7C00); @@ -4848,22 +4774,22 @@ fn half_functions_answer_metals_half_nan() { format!( "{hx} %s = call half @llvm.fmuladd.f16(half %hx, half 0xH3C00, half 0xH0000)\n" ), - Some(0x7E00), + None, ), half_nan_kernel( "half_ldexp", format!("{hx} %s = call half @air.ldexp.f16(half %hx, i32 2)\n"), - Some(0x7E00), + None, ), half_nan_kernel( "half_sqrt_fast", format!("{hx} %s = call fast half @air.sqrt.f16(half %hx)\n"), - Some(0x7E00), + None, ), half_nan_kernel( "half_round_snan", format!("{snan} %s = call half @air.round.f16(half %hx)\n"), - Some(0x7C01), + None, ), half_nan_kernel( "half_round_to_zero", @@ -4886,8 +4812,6 @@ fn half_functions_answer_metals_half_nan() { None, ), ]; - // The canonical selects the device fact leaves to the device, per kernel. - let left = [1, 1, 1, 0, 0, 0, 0, 0]; let text = module(&ks).replace( DECLS, &format!( @@ -4897,29 +4821,9 @@ fn half_functions_answer_metals_half_nan() { let Some(bitcode) = assemble("nan-half-functions", &text) else { return; }; - for stem in ["lavapipe", "moltenvk-m3"] { - for (kk, n) in ks.iter().zip(left) { - let mut tests = Vec::new(); - for fact in [false, true] { - let p = profile_with_canonical_nans(stem, fact); - let what = format!("{} on {stem}, MetalCanonicalNans {fact}", kk.name); - let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let (_, words) = - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let (is_nan, bits) = nan_tests(&words); - tests.push(is_nan + bits); - if let Some(want) = kk.want { - let got = interpret(&bitcode, kk.name, &p); - assert_eq!(got, want, "{what}: {got:#x}"); - } - } - assert_eq!(tests[0], tests[1] + n, "{} on {stem}: {tests:?}", kk.name); - if kk.name == "half_asin" { - assert!( - tests[1] > 0, - "half_asin on {stem}: its domain sign is selected" - ); - } - } - } + nans_are_the_device_s(&bitcode, &ks, true, &["half_asin"], &|name, fact| { + name.starts_with("half_round") + || name == "half_asin" + || (!name.starts_with("half_fract") && !fact) + }); } diff --git a/crates/metal2vulkan/src/tests/engine_extended_range.rs b/crates/metal2vulkan/src/tests/engine_extended_range.rs index b84385cde..c36fa2a69 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range.rs @@ -10,8 +10,8 @@ //! - A read outside the texture is Metal's zero texel, alpha the format's (measured), on a profile //! whose device robustness would return the raw zero. //! - `ARGB8Unorm`'s storage slot rotates its bytes in the shader (`RotateArgb`), and a half-float -//! storage slot of `HalfQuietNan` quiets a written `float`'s NaN alone, the device rounding -//! every other value. +//! storage slot leaves each written `float` to the device's conversion, noting where it is not +//! measured to be Metal's. //! - The binder joins a slot bound in an extended-range format to the plan's variant, the //! variant's plan states the same key, and it views the image in the raw format. //! - Samples of such a texture are Metal's (`samples`), at Metal's level and through a linear @@ -662,18 +662,20 @@ fn argb8_storage_slots_rotate_their_bytes() { } } -/// A half-float storage slot of `HalfQuietNan` (formatless, and declared `Rgba16f`) writes each -/// `float` channel as computed but a NaN as `0x7fc00000`, the device's conversion rounding the -/// value: Metal's rounding toward zero where the profile takes -/// `DriverDeviation::MetalHalfStorageWrites` (the module requires its property), else the -/// device's own (`PrecisionNote::DeviceColorConversion`). The held lanes cover every tie between -/// neighbouring halves and its neighbours, past the largest, the infinities and NaNs. The NaN is -/// Metal's where the profile takes `DriverDeviation::MetalFloatStorageNans` (MoltenVK's and -/// lavapipe's: the module requires its property), else the device's (ANV's on the Iris Xe of -/// RPL-P: `PrecisionNote::DeviceNanEncoding`). +/// A half-float storage slot (formatless, and declared `Rgba16f`) writes each `float` channel as +/// computed, the device's conversion rounding it and storing its NaN. The rounding is Metal's +/// toward zero where the profile takes `DriverDeviation::MetalHalfStorageWrites` (the module +/// requires its property), else the device's own (`PrecisionNote::DeviceColorConversion`); the +/// NaN is Metal's `0x7e00` where it takes `DriverDeviation::MetalHalfStorageNans` (MoltenVK's: the +/// module requires its property), else the device's (`PrecisionNote::DeviceNanEncoding`). A +/// formatless slot may also reach a packed small float image, whose NaN is the device's on every +/// profile (noted too), or a normalized one, whose conversion is the device's on every profile +/// (noted too). The held lanes cover every tie between neighbouring halves and its +/// neighbours, past the largest, the infinities and NaNs. #[test] -fn half_float_storage_slots_quiet_their_nans() { +fn half_float_storage_slots_leave_their_writes_to_the_device() { use crate::device::requirements::VkProperty; + use crate::error::DriverDeviation; use crate::pipeline::artifact::PrecisionNote; let Some(bc) = assemble("halves", &kernel(Source::ReadWrite, false, 0)) else { return; @@ -705,94 +707,88 @@ fn half_float_storage_slots_quiet_their_nans() { } }; let held = move |n: u32| -> [u32; 4] { [0, 1, 2, 3].map(|c| value(n, c)) }; - { - let class = StorageImageClass::HalfQuietNan; - for choice in [ - StorageImageChoice { - numeric: Some(crate::pipeline::sym::SampledType::Float), - ..StorageImageChoice::new(crate::vk::Format::UNDEFINED, class) - }, - StorageImageChoice::new(crate::vk::Format::R16G16B16A16_SFLOAT, class), - ] { - let mut i = LowerInputs::new(); - i.storage_images.insert(TARGET, choice); - let anv = "intel-irisxe-rplp-anv"; - let anv = (anv, profile(anv, DevicePolicy::default()).expect("profile")); - for (stem, p) in profiles().into_iter().chain([anv]) { - let rounds = - p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfStorageWrites); - // The kernel reads both textures: without formatless reads, the target's choice - // declares its format and the source's `RGBA32Float`'s. - let mut i = i.clone(); - if !p.fields().images.storage_read_without_format { - if choice.vk_format == crate::vk::Format::UNDEFINED { - continue; - } - let held = crate::vk::Format::R32G32B32A32_SFLOAT; - let source = StorageImageChoice::new(held, StorageImageClass::Identity); - i.storage_images.insert(SOURCE, source); + let class = StorageImageClass::Identity; + let mut nans_seen = std::collections::BTreeSet::new(); + for choice in [ + StorageImageChoice { + numeric: Some(crate::pipeline::sym::SampledType::Float), + ..StorageImageChoice::new(crate::vk::Format::UNDEFINED, class) + }, + StorageImageChoice::new(crate::vk::Format::R16G16B16A16_SFLOAT, class), + ] { + let mut i = LowerInputs::new(); + i.storage_images.insert(TARGET, choice); + let anv = "intel-irisxe-rplp-anv"; + let anv = (anv, profile(anv, DevicePolicy::default()).expect("profile")); + for (stem, p) in profiles().into_iter().chain([anv]) { + // The kernel reads both textures: without formatless reads, the target's choice + // declares its format and the source's `RGBA32Float`'s. + let mut i = i.clone(); + if !p.fields().images.storage_read_without_format { + if choice.vk_format == crate::vk::Format::UNDEFINED { + continue; } - let what = format!("{stem} {class:?} {:?}", choice.vk_format); - let (plan, m) = - typed_module_with(&bc, "k", &p, &i).unwrap_or_else(|e| panic!("{what}: {e}")); - validate(&bc, &i, &p, &what); - let images = [image(0, held), image(1, |_| [0; 4])]; - let (_, images) = run(&m, &resources(&plan, 16, &[]), &images); - let target = texels_of(&images, 1); - let layout = image(1, |_| [0; 4]); - for n in 0..SIDE * SIDE { - let at = layout - .index(0, 0, 0, [n % SIDE, n / SIDE, 0]) - .expect("texel"); - let want = held(n).map(|x| match f32::from_bits(x) { - v if v.is_nan() => 0x7fc0_0000, - _ => x, - }); - assert_eq!(target[at], want, "{what}: texel {n}"); - } - let a = compile_bitcode( - &bc, - EntryRef::Name("k"), - &FunctionConstantValues::defaults(), - &p, - &i, - &mut meter(), - SPIRV_WORDS, - ) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let measured = - p.takes_driver_deviation(crate::error::DriverDeviation::MetalFloatStorageNans); - assert_eq!(measured, stem != "intel-irisxe-rplp-anv", "{what}"); - let relied = &a.requirements.properties; - assert_eq!( - relied.contains(&VkProperty::MetalFloatStorageNans), - measured, - "{what}" - ); - assert_eq!( - relied.contains(&VkProperty::MetalHalfStorageWrites), - rounds, - "{what}" - ); - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceColorConversion), - !rounds, - "{what}: {:?}", - a.precision - ); - assert!( - !relied.contains(&VkProperty::MetalHalfStorageNans), - "{what}" - ); - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceNanEncoding), - !measured, - "{what}: {:?}", - a.precision - ); + let held = crate::vk::Format::R32G32B32A32_SFLOAT; + let source = StorageImageChoice::new(held, StorageImageClass::Identity); + i.storage_images.insert(SOURCE, source); } + let what = format!("{stem} {:?}", choice.vk_format); + let (plan, m) = + typed_module_with(&bc, "k", &p, &i).unwrap_or_else(|e| panic!("{what}: {e}")); + validate(&bc, &i, &p, &what); + let images = [image(0, held), image(1, |_| [0; 4])]; + let (_, images) = run(&m, &resources(&plan, 16, &[]), &images); + let target = texels_of(&images, 1); + let layout = image(1, |_| [0; 4]); + for n in 0..SIDE * SIDE { + let at = layout + .index(0, 0, 0, [n % SIDE, n / SIDE, 0]) + .expect("texel"); + assert_eq!(target[at], held(n), "{what}: texel {n}"); + } + let a = compile_bitcode( + &bc, + EntryRef::Name("k"), + &FunctionConstantValues::defaults(), + &p, + &i, + &mut meter(), + SPIRV_WORDS, + ) + .unwrap_or_else(|e| panic!("{what}: {e}")); + let rounds = p.takes_driver_deviation(DriverDeviation::MetalHalfStorageWrites); + let nans = p.takes_driver_deviation(DriverDeviation::MetalHalfStorageNans); + nans_seen.insert(nans); + let relied = &a.requirements.properties; + assert_eq!( + relied.contains(&VkProperty::MetalHalfStorageWrites), + rounds, + "{what}" + ); + let formatless = choice.vk_format == crate::vk::Format::UNDEFINED; + let converted = a.precision.contains(&PrecisionNote::DeviceColorConversion); + assert!(converted || rounds, "{what}: {:?}", a.precision); + if !formatless { + assert_eq!(converted, !rounds, "{what}: {:?}", a.precision); + } + assert_eq!( + relied.contains(&VkProperty::MetalHalfStorageNans), + nans, + "{what}" + ); + assert!( + !relied.contains(&VkProperty::MetalFloatStorageNans), + "{what}" + ); + assert_eq!( + a.precision.contains(&PrecisionNote::DeviceNanEncoding), + !nans || formatless, + "{what}: {:?}", + a.precision + ); } } + assert_eq!(nans_seen.len(), 2, "both NaN facts: {nans_seen:?}"); } /// The value of a `half`'s bits (not a NaN). diff --git a/crates/metal2vulkan/src/tests/engine_half_moves.rs b/crates/metal2vulkan/src/tests/engine_half_moves.rs index a396f84f9..d6fdca34a 100644 --- a/crates/metal2vulkan/src/tests/engine_half_moves.rs +++ b/crates/metal2vulkan/src/tests/engine_half_moves.rs @@ -20,10 +20,10 @@ //! `DevicePolicy::exact_answers`. A module may leave a NaN's bits to the device, and then says so: //! a `half` read from its bits by the device's widening (`PrecisionNote::NativeHalfConversion`, //! wherever the module rounds to `half` through the device's conversion) or a NaN's bits left to -//! the device's arithmetic and conversions (`PrecisionNote::NativeNanEncoding`, the default -//! `NanMinMaxPolicy::Native`). There a NaN pattern need only come back a NaN (a move through the -//! select, the threadgroup array or a half-bits texel; a move straight to a buffer reuses the -//! loaded bits). No other pattern may change, nor any where the module records neither note. +//! the device's arithmetic and conversions (`PrecisionNote::NativeNanEncoding`, under either +//! policy). There a NaN pattern need only come back a NaN (a move through the select, the +//! threadgroup array or a half-bits texel; a move straight to a buffer reuses the loaded bits). No +//! other pattern may change, nor any where the module records neither note. //! //! The profiles and policies compile to a few distinct modules: each runs once, all at once on //! threads of their own. @@ -150,7 +150,6 @@ fn resources(plan: &Plan) -> Resources { ( PushField::SlotBindOffset(_) | PushField::DispatchRegion - | PushField::TextureHalfChannels(_) | PushField::Specialized(_), PushLoc::Push { .. }, ) => {} diff --git a/crates/metal2vulkan/src/tests/engine_handles.rs b/crates/metal2vulkan/src/tests/engine_handles.rs index ca5f64adf..7cb131191 100644 --- a/crates/metal2vulkan/src/tests/engine_handles.rs +++ b/crates/metal2vulkan/src/tests/engine_handles.rs @@ -1670,28 +1670,16 @@ declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32) assert_eq!(count(&a, OP_FUNCTION_CALL), 2, "{stem}"); assert_eq!(count(&a, OP_ULESS_THAN_EQUAL), 16, "{stem}"); assert_eq!(count(&a, OP_ARRAY_LENGTH), 1, "{stem}"); - // A heap write on a profile whose half-float storage class converts also tests - // the handle's class index and quiets the write's NaN: 1,652 words with - // `HalfQuietNan` (2,588 with word ids). - let half = match crate::metal::format::half_write_class(&p) { - crate::pipeline::lower_inputs::StorageImageClass::Identity => 0, - class => crate::lower::texture::heap_half_write_words(class) as usize, - }; - // And, on every profile, the test of the small floats' class and the quieted - // NaNs of its write (1,632 words on MoltenVK with `u64` ids). - let small = crate::lower::texture::heap_half_write_words( - crate::pipeline::lower_inputs::StorageImageClass::SmallFloatQuietNan, - ) as usize; // And a half-float member's bits through the unsigned integer twin, where the // profile takes it. let bits = match crate::metal::format::heap_half_bits(&p) { true => crate::lower::texture::heap_bits_write_words() as usize, false => 0, }; - let bound = half + small + bits + if p.fields().leaf.int64 { 1_600 } else { 2_300 }; + let bound = bits + if p.fields().leaf.int64 { 1_600 } else { 2_300 }; assert!( a.module.words.len() <= bound, - "{stem}: {}", + "{stem}: {} words over {bound} (bits {bits})", a.module.words.len() ); assert_eq!(uses(&a, "texture.write.heap"), 1, "{stem}"); @@ -1752,12 +1740,14 @@ declare void @air.write_texture_2d.{elem}(ptr addrspace(1), <2 x i32>, {ty}, i32 /// A `half` (or `float`) texel written through an argument buffer's texture, on a profile where /// every half-float format has its unsigned integer alias and the device is not measured to store /// a written `half`'s NaN as its bits (`metal::format::heap_half_bits`), declares the float -/// storage group's unsigned integer twin (`StorageFormatClass::HalfBits`) beside it, states -/// `RuntimeFact::HeapHalfTexelWrites` for the members the twin does not hold, and records no -/// `PrecisionNote::DeviceNanEncoding` for the write: a `half` write's fact counts packed small -/// floats too, a `float` write's is stated only where the device's conversion of `0x7fc00000` -/// is not measured to be Metal's (`DriverDeviation::MetalFloatStorageNans`). Elsewhere the module -/// declares one class and records the note as before (`half`), or relies on the measured property. +/// storage group's unsigned integer twin (`StorageFormatClass::HalfBits`) beside it and states +/// `RuntimeFact::HeapHalfTexelWrites` for the members the twin does not hold: a `half` write's fact +/// counts packed small floats too, a `float` write's is stated only where the device's conversion +/// of a NaN to a half-float texel is not measured to be Metal's +/// (`DriverDeviation::MetalHalfStorageNans`). +/// Elsewhere the module declares one class. Every such write records +/// `PrecisionNote::DeviceNanEncoding`: the heap may hold a 32-bit or packed small float texture, +/// whose NaN is the device's. #[test] fn a_heap_texel_write_stores_half_bits_through_the_unsigned_twin() { use crate::error::DriverDeviation; @@ -1790,20 +1780,14 @@ fn a_heap_texel_write_stores_half_bits_through_the_unsigned_twin() { packed, }) }; + assert!(noted, "{what}: {:?}", a.precision); if twin { twins += 1; - assert!(!noted, "{what}"); - let float_fact = !p.takes_driver_deviation(DriverDeviation::MetalFloatStorageNans) - && crate::metal::format::half_write_class(&p) - != crate::pipeline::lower_inputs::StorageImageClass::Identity; + let float_fact = !p.takes_driver_deviation(DriverDeviation::MetalHalfStorageNans); assert_eq!(fact(true), !float, "{what}"); assert_eq!(fact(false), float && float_fact, "{what}"); } else { assert!(!fact(true) && !fact(false), "{what}"); - let keeps = p.takes_driver_deviation(DriverDeviation::MetalHalfTexelWrites); - if !float { - assert_eq!(noted, !keeps, "{what}"); - } } } assert!(twins > 0, "no committed profile takes the twin"); diff --git a/crates/metal2vulkan/src/tests/engine_imageblock.rs b/crates/metal2vulkan/src/tests/engine_imageblock.rs index 47be78f96..5accc21a6 100644 --- a/crates/metal2vulkan/src/tests/engine_imageblock.rs +++ b/crates/metal2vulkan/src/tests/engine_imageblock.rs @@ -132,8 +132,6 @@ fn run( match (f.field, f.loc) { // One region, every buffer bound at its start. (PushField::SlotBindOffset(_) | PushField::DispatchRegion, PushLoc::Push { .. }) => {} - // 0: a `half` slice's NaN lanes `0x7fc00000`, every other texel as written. - (PushField::TextureHalfChannels(_), PushLoc::Push { .. }) => {} // A bound value read as data, which the interpreter writes from `spec`. (PushField::Specialized(_), PushLoc::Push { .. }) => {} // No slot's writes dropped: the word stays 0. diff --git a/crates/metal2vulkan/src/tests/engine_link.rs b/crates/metal2vulkan/src/tests/engine_link.rs index f499d1e82..e4f0f0f65 100644 --- a/crates/metal2vulkan/src/tests/engine_link.rs +++ b/crates/metal2vulkan/src/tests/engine_link.rs @@ -612,8 +612,8 @@ fn the_projection_of_the_fixture_is_fixed_function() { /// (`PrecisionNote::DeviceNanEncoding`) only where the profile's driver is not measured to store /// Metal's NaN: a `float` output's everywhere but MoltenVK, whose conversion is Metal's (the /// output's own NaN reaches the device's conversion, which no other driver is measured with), a -/// `half` output's everywhere but NVIDIA's measured GPUs and MoltenVK, which writes it through a -/// 16-bit output. A write to an `RGBA8Unorm` attachment records none. +/// `half` output's everywhere but NVIDIA's measured GPUs. A write to an `RGBA8Unorm` attachment +/// records none. #[test] fn half_float_writes_note_the_nan_encoding_where_the_device_rewrites_it() { use crate::pipeline::artifact::PrecisionNote; @@ -628,7 +628,7 @@ fn half_float_writes_note_the_nan_encoding_where_the_device_rewrites_it() { ("intel-irisxe-rplp-anv", true, true), ("nvidia-rtx50-linux", true, true), ("nvidia-rtx5080-laptop", true, false), - ("moltenvk-m3", false, false), + ("moltenvk-m3", false, true), ] { let p = prof(stem); let v = compile(&bc, "rt6_fill_vertex", &p).expect("vertex"); @@ -658,91 +658,10 @@ fn half_float_writes_note_the_nan_encoding_where_the_device_rewrites_it() { } } -/// Where the profile's driver is measured to store a 16-bit output's bits -/// (`DriverDeviation::HalfColorOutputBits`) and to convert to 16 bits as Metal does -/// (`MetalHalfConversion`), declares 16-bit outputs (with `Int16` and `Float16`), and does not -/// store the output's NaN as Metal does, an output to a half-float attachment is written through a -/// 16-bit output variable as the bits of the half Metal stores, valid and linked: on MoltenVK (the -/// M3 Max and the M4) a `half` output (it stores a `float`'s NaN as Metal does). Such an output -/// rounds nothing, so the attachment is listed as written as a half's bits, not as rounded, takes -/// no Vulkan blend of one and zero, and the module requires both properties. RADV and ANV, which -/// declare 16-bit outputs but store their NaNs as `0xfe00` too, keep the 32-bit output, as do -/// lavapipe and NVIDIA, which declare none. An `RGBA8Unorm` attachment keeps the 32-bit output. -#[test] -fn half_float_attachments_take_the_halfs_bits_through_a_16_bit_output() { - let Some(bc) = assemble("rt6_samples.ll") else { - return; - }; - for (stem, float_route, half_route) in [ - ("amd-rdna3-radv", false, false), - ("intel-irisxe-rplp-anv", false, false), - ("moltenvk-m3", false, true), - ("lavapipe", false, false), - ("nvidia-rtx5080-laptop", false, false), - ] { - let p = prof(stem); - let v = compile(&bc, "rt6_fill_vertex", &p).expect("vertex"); - for (entry, route) in [ - ("rt6_fill_rgba32float", float_route), - ("rt6_fill_rgba16float", half_route), - ] { - for (pf, want) in [ - (PixelFormat::RGBA16Float, route), - (PixelFormat::R16Float, route), - (PixelFormat::RGBA8Unorm, false), - ] { - let what = format!("{stem} {entry} {pf:?}"); - let mut r = RenderLinkInputs::new(); - r.color_attachments[0] = Some(ColorAttachmentDescriptor::new(pf)); - let f = compile_with(&bc, entry, &p, &fragment_inputs(&r, &p)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let l = link(&[&v, &f], &render(&r), &p).unwrap_or_else(|e| panic!("{what}: {e}")); - let words = validate_all(&l, &[&v, &f], &p); - let text = spirv_dis(&words[1]); - assert_eq!( - text.contains("OpCapability StorageInputOutput16"), - want, - "{what}\n{text}" - ); - if want { - assert!( - text.contains("%_ptr_Output_v4half = OpTypePointer Output %v4half"), - "{what}\n{text}" - ); - assert!(f.interface.io.half_bit_colors.contains(&0), "{what}"); - assert!(!f.interface.io.rounded_colors.contains(&0), "{what}"); - for property in [ - crate::device::requirements::VkProperty::HalfColorOutputBits, - crate::device::requirements::VkProperty::MetalHalfConversion, - ] { - assert!( - f.requirements.properties.contains(&property), - "{what}: {property:?}" - ); - } - let mut blended = r.clone(); - if let Some(a) = blended.color_attachments[0].as_mut() { - a.blending_enabled = true; - } - let b = compile_with(&bc, entry, &p, &fragment_inputs(&blended, &p)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let l = link(&[&v, &b], &render(&blended), &p) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let attachment = l.graphics.as_ref().expect("graphics").color_attachments[0] - .as_ref() - .expect("attachment"); - assert!(attachment.blend.is_none(), "{what} blended"); - } - } - } - } -} - /// Under `TextureWriteRoundingMode::NearestEven` a `float` output to a half-float attachment rounds /// to nearest even in the function on every profile, MoltenVK's included (listed as rounded, no /// device conversion noted, the device's blend of one and zero dropped), and the pipeline links -/// valid; a `half` output, already a half, rounds nothing (on MoltenVK it is written as a half's -/// bits). Under alpha-to-coverage the alpha rounds too, and a pipeline whose function rounds it +/// valid; a `half` output, already a half, rounds nothing. Under alpha-to-coverage the alpha rounds too, and a pipeline whose function rounds it /// records `PrecisionNote::CoverageReadsRoundedAlpha`. After a blend of other factors the device /// rounds the blend's result, which Metal rounds to nearest even: the channels are written as /// computed and the module announces `PrecisionNote::BlendedWriteRounding` (no device conversion @@ -887,14 +806,9 @@ fn mode_two_refuses_fragment_texture_writes_it_would_round() { choice(vk::Format::UNDEFINED, identity), Goes::Bound, ), - // The class the profile writes a half-float texture by (`Identity` where its device - // is measured to store Metal's halves). ( "tob_write", - choice( - vk::Format::R16G16B16A16_SFLOAT, - crate::metal::format::half_write_class(&p), - ), + choice(vk::Format::R16G16B16A16_SFLOAT, identity), Goes::Declared, ), ( diff --git a/crates/metal2vulkan/src/tests/engine_metal_routines.rs b/crates/metal2vulkan/src/tests/engine_metal_routines.rs index 51cb78498..34fd5b381 100644 --- a/crates/metal2vulkan/src/tests/engine_metal_routines.rs +++ b/crates/metal2vulkan/src/tests/engine_metal_routines.rs @@ -4,17 +4,16 @@ //! every input of our probe as Metal did (an M4, macOS 27.0.1, libraries compiled offline; //! every offline build, with and without fast math and `air.compile.denorms_disable`, answered //! alike). The tables are those answers: the input's bits, `frexp`'s mantissa bits and exponent, -//! and `ilogb`. Under the default NaN policy (`NanMinMaxPolicy::Native`) a module that records -//! `PrecisionNote::NativeNanEncoding` answers a `half` NaN's mantissa with a NaN whose bits are the -//! device's (on ANV and RADV a `half` read from its bits is the device's widening, which the -//! interpreter answers with the positive quiet NaN); `NanMinMaxPolicy::Exact` answers Metal's bits. +//! and `ilogb`. A module that records `PrecisionNote::NativeNanEncoding` answers a `half` NaN's +//! mantissa with a NaN whose bits are the device's (on ANV and RADV a `half` read from its bits is +//! the device's widening, which the interpreter answers with the positive quiet NaN). //! //! Each kernel loops over its input buffer (`[[buffer(0)]]`, one word or halfword an element) in //! groups of its lanes, and writes three words an element to `[[buffer(1)]]`: the mantissa's //! bits (zero-extended), the exponent, and `ilogb` (mode 0 in the scalar kernels, 3 in the vector //! ones). `llvm-as` assembles the module; without it the tests skip visibly. -use crate::device::{DevicePolicy, DeviceProfile, NanMinMaxPolicy}; +use crate::device::{DevicePolicy, DeviceProfile}; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; use crate::pipeline::testing::{ compile, link_and_validate, llvm_assemble, profile, typed_module, AssembleError, Scratch, @@ -420,48 +419,36 @@ fn half_nan(bits: u32) -> bool { bits <= 0xffff && bits & 0x7c00 == 0x7c00 && bits & 0x3ff != 0 } -/// Every kernel compiles, links and passes L3 on every profile under either NaN policy, and answers +/// Every kernel compiles, links and passes L3 on every profile, and answers /// every measured input as Metal did on the interpreter: `float` denormals flushed (`(+0, 0)`, /// `INT_MIN`), `half` denormals normalized, zeros `(+0, 0)` and `INT_MIN` whatever their sign, /// infinities and NaNs returned with their bits and exponent 0, `ilogb` `INT_MAX` for an infinity -/// and `INT_MIN` for a NaN, lane by lane. The one exception: by default -/// (`NanMinMaxPolicy::Native`) a module that records `NativeNanEncoding` answers a `half` NaN's -/// mantissa with a NaN of the device's bits; under `NanMinMaxPolicy::Exact` with Metal's. +/// and `INT_MIN` for a NaN, lane by lane. The one exception: a module that records +/// `NativeNanEncoding` answers a `half` NaN's mantissa with a NaN of the device's bits. #[test] fn frexp_and_ilogb_answer_as_metals_routines() { let Some(bc) = assemble() else { return; }; - let exact = DevicePolicy { - nan_and_min_max: NanMinMaxPolicy::Exact, - ..DevicePolicy::default() - }; for stem in PROFILES { - for policy in [DevicePolicy::default(), exact] { - let p = profile(stem, policy).expect("profile"); - for k in &KERNELS { - let what = format!("{} on {stem}, {:?}", k.name, policy.nan_and_min_max); - let a = compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let device_nans = a.precision.contains(&PrecisionNote::NativeNanEncoding); - assert!( - !device_nans || policy.nan_and_min_max == NanMinMaxPolicy::Native, - "{what}: {:?}", - a.precision - ); - let got = interpret(&bc, k, &p, &what); - for (i, &(x, mantissa, exponent, ilogb)) in k.inputs().iter().enumerate() { - let got = &got[3 * i..3 * i + 3]; - let want = [mantissa, exponent as u32, ilogb as u32]; - if k.half && device_nans && half_nan(x) { - assert!( - half_nan(got[0]) && got[1..] == want[1..], - "{what}: x = {x:#x}: got {got:#x?}" - ); - continue; - } - assert_eq!(got, want, "{what}: x = {x:#x}: got {got:#x?}"); + let p = profile(stem, DevicePolicy::default()).expect("profile"); + for k in &KERNELS { + let what = format!("{} on {stem}", k.name); + let a = compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + let device_nans = a.precision.contains(&PrecisionNote::NativeNanEncoding); + let got = interpret(&bc, k, &p, &what); + for (i, &(x, mantissa, exponent, ilogb)) in k.inputs().iter().enumerate() { + let got = &got[3 * i..3 * i + 3]; + let want = [mantissa, exponent as u32, ilogb as u32]; + if k.half && device_nans && half_nan(x) { + assert!( + half_nan(got[0]) && got[1..] == want[1..], + "{what}: x = {x:#x}: got {got:#x?}" + ); + continue; } + assert_eq!(got, want, "{what}: x = {x:#x}: got {got:#x?}"); } } } diff --git a/crates/metal2vulkan/src/tests/engine_native_half.rs b/crates/metal2vulkan/src/tests/engine_native_half.rs index 11ca9e9d5..839ce3d3a 100644 --- a/crates/metal2vulkan/src/tests/engine_native_half.rs +++ b/crates/metal2vulkan/src/tests/engine_native_half.rs @@ -431,57 +431,6 @@ fn a_native_conversion_converts_the_value_itself() { } } -/// Whether `entry`'s plan on `p` rounds `half` natively, and whether a `half` texel keeps its -/// decoded NaN through that rounding (`ArithPlan::native_half`, `ArithPlan::texel_nans`). -fn texel_nans(bitcode: &[u8], entry: &str, p: &DeviceProfile) -> (bool, bool) { - let mut m = meter(); - let decoded = air::decode(bitcode, &mut m).expect("decode"); - let req = SpecRequest { - call_stack_depth: 1, - entry: entry.to_owned(), - ..SpecRequest::default() - }; - let spec = air::specialize(decoded, &req, &mut m).expect("specialize"); - let memory = analyze_memory(&spec, p, &mut m).expect("memory"); - let plan = select(&spec, &memory, p, &LowerInputs::new(), &mut m).expect("select"); - let arith = &plan.families.arith; - (arith.native_half, arith.texel_nans) -} - -/// A `half` texel keeps the NaN the device decoded through native half rounding only where the NaN -/// switch asks for Metal's NaN (`NanMinMaxPolicy::Exact`: the profile's `NanEncoding::Device`); -/// under the default (`NanMinMaxPolicy::Native`) no committed profile's plan keeps it, so native -/// half rounding takes the form's NaN, byte for byte; and a profile measured to answer Metal's -/// canonical NaN keeps the default's plan under either setting. At least one profile rounds -/// natively and keeps the texel's NaN under the switch (lavapipe and the NVIDIA profiles). -#[test] -fn a_texels_nan_is_kept_under_native_half_rounding_only_where_the_nan_switch_asks() { - use crate::device::profile::NanEncoding; - use crate::device::NanMinMaxPolicy; - let Some(bc) = bitcode() else { - return; - }; - let switched = DevicePolicy { - nan_and_min_max: NanMinMaxPolicy::Exact, - ..DevicePolicy::default() - }; - let mut kept_natively = 0usize; - for (stem, p) in &committed_profiles().expect("profiles") { - let (native, kept) = texel_nans(&bc, "half_narrow", p); - assert!(!kept, "{stem}: the default keeps no texel NaN"); - let q = profile(stem, switched).expect("profile"); - let (native_q, kept_q) = texel_nans(&bc, "half_narrow", &q); - assert_eq!(native_q, native, "{stem}: the switch leaves the rounding"); - let device_nans = q.fields().nan_encoding == NanEncoding::Device; - assert_eq!(kept_q, device_nans, "{stem}: {:?}", q.fields().nan_encoding); - kept_natively += usize::from(native_q && kept_q); - } - assert!( - kept_natively > 0, - "a profile that rounds natively and keeps texel NaNs" - ); -} - /// What a module's words say of its `half` rounding: its execution modes with a float width, the /// conversions from 32- to 16-bit floats and back with how many carry `NoContraction`, its /// `OpQuantizeToF16`s, and its 16-bit float arithmetic. @@ -744,18 +693,14 @@ fn half_load_module() -> String { /// Where a profile rounds `half` through the conversion under the float controls (ANV, RADV), a /// kernel that reads a `half` from memory and rounds nothing widens its bits by the device's -/// conversion by default (`NanMinMaxPolicy::Native`, which leaves a NaN's bits to the device): the -/// module has that widening and no narrowing, its entry declares the controls +/// conversion, which leaves a NaN's bits to the device: the module has that widening and no +/// narrowing, its entry declares the controls /// (`narrow::controlled_modes`, so a half denormal widens exactly), it requires their properties, /// records `NativeNanEncoding`, selects no canonical NaN, and passes L3; on the interpreter a half -/// denormal, a zero's sign, `65504` and an infinity read as their values, and a NaN as a NaN. -/// Under `NanMinMaxPolicy::Exact` it decodes the bits in integer arithmetic (no conversion), -/// declares no 16-bit mode, records no such note, and widens every NaN to Metal's `0x7FC00000` -/// (a quiet and a signalling one of either sign; the decode alone keeps their payloads). Under -/// either the `half` stored back unchanged keeps its bits, NaNs included. +/// denormal, a zero's sign, `65504` and an infinity read as their values, and a NaN as a NaN; the +/// `half` stored back unchanged keeps its bits, NaNs included. #[test] fn a_half_read_from_memory_widens_by_the_conversion_under_the_float_controls() { - use crate::device::NanMinMaxPolicy; use crate::spv::ExecutionMode as M; let Some(bc) = assemble("native-half-load", &half_load_module()) else { return; @@ -766,55 +711,39 @@ fn a_half_read_from_memory_widens_by_the_conversion_under_the_float_controls() { continue; } controlled += 1; - let exact = profile( - stem, - DevicePolicy { - nan_and_min_max: NanMinMaxPolicy::Exact, - ..DevicePolicy::default() - }, - ) - .expect("profile"); - for (q, widened) in [(p, true), (&exact, false)] { - let what = format!("half_load on {stem}, widened {widened}"); - let a = compile(&bc, "half_load", q).unwrap_or_else(|e| panic!("{what}: {e:?}")); - link_and_validate(&a, q).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let r = rounding(&a.module.words); - assert_eq!(r.narrowings, 0, "{what}: {r:?}"); - assert_eq!(r.widenings > 0, widened, "{what}: {r:?}"); - for mode in [M::RoundingModeRTE, M::DenormPreserve] { - assert_eq!( - r.modes.contains(&(mode as u32, 16)), - widened, - "{what}: {mode:?} {r:?}" - ); - } - assert_eq!( - a.precision.contains(&PrecisionNote::NativeNanEncoding), - widened, - "{what}: {:?}", - a.precision + let what = format!("half_load on {stem}"); + let a = compile(&bc, "half_load", p).unwrap_or_else(|e| panic!("{what}: {e:?}")); + link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + let r = rounding(&a.module.words); + assert_eq!(r.narrowings, 0, "{what}: {r:?}"); + assert!(r.widenings > 0, "{what}: {r:?}"); + for mode in [M::RoundingModeRTE, M::DenormPreserve] { + assert!( + r.modes.contains(&(mode as u32, 16)), + "{what}: {mode:?} {r:?}" ); - assert_eq!(r.canonical_nans > 0, !widened, "{what}: {r:?}"); - let run = |h: u16| { - let mut bytes = vec![0; 16]; - bytes[..2].copy_from_slice(&h.to_le_bytes()); - let b = interpret_bytes(&bc, "half_load", q, bytes); - let wide = u32::from_le_bytes([b[8], b[9], b[10], b[11]]); - let kept = u16::from_le_bytes([b[12], b[13]]); - assert_eq!(kept, h, "{what}: {h:#06x} stored back"); - f32::from_bits(wide) - }; - assert_eq!(run(0x0001).to_bits(), 2f32.powi(-24).to_bits(), "{what}"); - assert_eq!(run(0x8000).to_bits(), (-0.0f32).to_bits(), "{what}"); - assert_eq!(run(0x7BFF), 65504.0, "{what}"); - assert_eq!(run(0xFC00), f32::NEG_INFINITY, "{what}"); - for h in [0x7E01, 0xFE00, 0x7C01, 0xFDFF] { - let x = run(h); - assert!(x.is_nan(), "{what}: {h:#06x}"); - if !widened { - assert_eq!(x.to_bits(), 0x7FC0_0000, "{what}: {h:#06x}"); - } - } + } + assert!( + a.precision.contains(&PrecisionNote::NativeNanEncoding), + "{what}: {:?}", + a.precision + ); + assert_eq!(r.canonical_nans, 0, "{what}: {r:?}"); + let run = |h: u16| { + let mut bytes = vec![0; 16]; + bytes[..2].copy_from_slice(&h.to_le_bytes()); + let b = interpret_bytes(&bc, "half_load", p, bytes); + let wide = u32::from_le_bytes([b[8], b[9], b[10], b[11]]); + let kept = u16::from_le_bytes([b[12], b[13]]); + assert_eq!(kept, h, "{what}: {h:#06x} stored back"); + f32::from_bits(wide) + }; + assert_eq!(run(0x0001).to_bits(), 2f32.powi(-24).to_bits(), "{what}"); + assert_eq!(run(0x8000).to_bits(), (-0.0f32).to_bits(), "{what}"); + assert_eq!(run(0x7BFF), 65504.0, "{what}"); + assert_eq!(run(0xFC00), f32::NEG_INFINITY, "{what}"); + for h in [0x7E01, 0xFE00, 0x7C01, 0xFDFF] { + assert!(run(h).is_nan(), "{what}: {h:#06x}"); } } assert!( diff --git a/crates/metal2vulkan/src/tests/engine_native_maths.rs b/crates/metal2vulkan/src/tests/engine_native_maths.rs index 755b4c35c..cf4a0612c 100644 --- a/crates/metal2vulkan/src/tests/engine_native_maths.rs +++ b/crates/metal2vulkan/src/tests/engine_native_maths.rs @@ -1,22 +1,19 @@ //! The device's forms of Metal's maths: on a device whose `float` functions are not Metal's own, //! the maths functions, divisions and fused multiply-adds (`NativeTranscendentals`, //! `NativeDivision`, `NativeFma`) and `dot`, `mix` and `fast::sqrt` (`NativeDot`, `NativeMix`, -//! `NativeTranscendentals`) are the device's instructions, each recording its kinds; and one of the -//! policy's choices takes the device's NaN and minimum and maximum (`NanMinMaxPolicy`: -//! `NativeNanEncoding`, `NativeMinMax`) where it is on, and Metal's selects of its NaN and operand -//! where it is off. +//! `NativeTranscendentals`) are the device's instructions, each recording its kinds; and on every +//! device not measured to answer Metal's, the NaN and the minimum and maximum are the device's +//! (`NativeNanEncoding`, `NativeMinMax`). //! //! The kernels read three `float`s from buffer 0 and store one result after them: a precise //! `sin`, `exp`, `atan2` and `pow`, a precise and an `arcp` division, a `half` `fma`, an addition, //! an `fmin`, a `saturate`, a `fast::sqrt`, a `dot` and a `float` and a `half` `mix`. On lavapipe -//! each records its kind, a choice's exactly where it is on, and a choice's is smaller there than -//! with it off; the interpreter's answers stay within the bound the kind's docs state, and are -//! Metal's on MoltenVK and with the choice off. `llvm-as` assembles the module; without it the -//! tests skip visibly. +//! each records its kind; the interpreter's answers stay within the bound the kind's docs state, +//! and are Metal's on MoltenVK. `llvm-as` assembles the module; without it the tests skip visibly. use crate::air::{self, SpecRequest}; -use crate::device::profile::{DeviceProfile, FloatFunctions, MinMaxRoute, NanEncoding}; -use crate::device::{DevicePolicy, NanMinMaxPolicy}; +use crate::device::profile::{DeviceProfile, FloatFunctions}; +use crate::device::DevicePolicy; use crate::lower::emit::emit_module; use crate::lower::select::{select, LowerInputs}; use crate::memory::static_root::analyze_memory; @@ -30,54 +27,12 @@ use crate::spirv::testing::{committed_profiles_with, is_moltenvk_capture}; const OP_FUNCTION: u32 = 54; -/// One of the policy's choices between the device's form and Metal's. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Choice { - /// The NaN and minimum and maximum (`NanMinMaxPolicy`). - NanMinMax, -} - -impl Choice { - const ALL: [Choice; 1] = [Choice::NanMinMax]; - - /// `policy` with this choice on (the device's form) or off (Metal's). - fn set(self, policy: DevicePolicy, on: bool) -> DevicePolicy { - match self { - Choice::NanMinMax => DevicePolicy { - nan_and_min_max: match on { - true => NanMinMaxPolicy::Native, - false => NanMinMaxPolicy::Exact, - }, - ..policy - }, - } - } - - /// The default policy with every choice on or off. - fn every(on: bool) -> DevicePolicy { - Choice::ALL - .iter() - .fold(DevicePolicy::default(), |p, c| c.set(p, on)) - } - - /// Whether profile `p` takes this choice's device forms. - fn taken(self, p: &DeviceProfile) -> bool { - let f = p.fields(); - match self { - Choice::NanMinMax => { - f.nan_encoding == NanEncoding::Native && f.min_max == MinMaxRoute::Native - } - } - } -} - -/// A kernel: its name, the body defining `%r` from `%a`, `%b` and `%c`, the note its device form -/// records, and the choice that takes it (`None`: every device but MoltenVK). +/// A kernel: its name, the body defining `%r` from `%a`, `%b` and `%c`, and the note its device +/// form records. struct Kernel { name: &'static str, body: &'static str, note: PrecisionNote, - choice: Option, } const KERNELS: [Kernel; 14] = [ @@ -85,85 +40,71 @@ const KERNELS: [Kernel; 14] = [ name: "native_sin", body: " %r = tail call float @air.sin.f32(float %a)\n", note: PrecisionNote::NativeTranscendentals, - choice: None, }, Kernel { name: "native_exp", body: " %r = tail call float @air.exp.f32(float %a)\n", note: PrecisionNote::NativeTranscendentals, - choice: None, }, Kernel { name: "native_atan2", body: " %r = tail call float @air.atan2.f32(float %a, float %b)\n", note: PrecisionNote::NativeTranscendentals, - choice: None, }, Kernel { name: "native_pow", body: " %r = tail call float @air.pow.f32(float %a, float %b)\n", note: PrecisionNote::NativeTranscendentals, - choice: None, }, Kernel { name: "native_fdiv", body: " %r = fdiv float %a, %b\n", note: PrecisionNote::NativeDivision, - choice: None, }, Kernel { name: "native_fdiv_arcp", body: " %r = fdiv arcp float %a, %b\n", note: PrecisionNote::NativeDivision, - choice: None, }, Kernel { name: "native_half_fma", body: " %ha = fptrunc float %a to half\n %hb = fptrunc float %b to half\n %hc = fptrunc float %c to half\n %hr = tail call half @air.fma.f16(half %ha, half %hb, half %hc)\n %r = fpext half %hr to float\n", note: PrecisionNote::NativeFma, - choice: None, }, Kernel { name: "native_fadd", body: " %r = fadd float %a, %b\n", note: PrecisionNote::NativeNanEncoding, - choice: Some(Choice::NanMinMax), }, Kernel { name: "native_fmin", body: " %r = tail call float @air.fmin.f32(float %a, float %b)\n", note: PrecisionNote::NativeMinMax, - choice: Some(Choice::NanMinMax), }, Kernel { name: "native_fast_sqrt", body: " %r = tail call fast float @air.fast_sqrt.f32(float %a)\n", note: PrecisionNote::NativeTranscendentals, - choice: None, }, Kernel { name: "native_dot", body: " %u0 = insertelement <2 x float> undef, float %a, i32 0\n %u = insertelement <2 x float> %u0, float %b, i32 1\n %v0 = insertelement <2 x float> undef, float %c, i32 0\n %v = insertelement <2 x float> %v0, float %a, i32 1\n %r = tail call float @air.dot.v2f32(<2 x float> %u, <2 x float> %v)\n", note: PrecisionNote::NativeDot, - choice: None, }, Kernel { name: "native_mix", body: " %r = tail call float @air.mix.f32(float %a, float %b, float %c)\n", note: PrecisionNote::NativeMix, - choice: None, }, Kernel { name: "native_saturate", body: " %r = tail call float @air.saturate.f32(float %a)\n", note: PrecisionNote::NativeMinMax, - choice: Some(Choice::NanMinMax), }, Kernel { name: "native_half_mix", body: " %ha = fptrunc float %a to half\n %hb = fptrunc float %b to half\n %hc = fptrunc float %c to half\n %hr = tail call half @air.mix.f16(half %ha, half %hb, half %hc)\n %r = fpext half %hr to float\n", note: PrecisionNote::NativeMix, - choice: None, }, ]; @@ -262,13 +203,10 @@ fn ulps(got: f32, want: f64) -> f64 { (f64::from(got) - want).abs() / ulp } -/// On every committed profile but the MoltenVK captures, whose functions, NaN and minimum and -/// maximum are Metal's own, the maths functions are the device's, and each choice takes its device -/// forms exactly where it is on, and moves the fingerprint; on the MoltenVK captures neither -/// setting takes them, and the NaN choice moves the fingerprint all the same: a texel's NaN, the -/// image's decode, follows it on every device (`TexelNanRoute`). +/// On every committed profile but the MoltenVK captures, whose functions are Metal's own, the maths +/// functions are the device's. #[test] -fn each_choice_takes_the_device_s_forms_where_it_is_on() { +fn the_maths_functions_are_the_device_s_but_on_moltenvk() { let profiles = committed_profiles_with(DevicePolicy::default()).expect("profiles"); assert!(profiles.len() >= 10, "{} profiles", profiles.len()); for (stem, p) in &profiles { @@ -278,71 +216,25 @@ fn each_choice_takes_the_device_s_forms_where_it_is_on() { "{stem}" ); } - for choice in Choice::ALL { - let base = Choice::every(true); - let on = committed_profiles_with(choice.set(base, true)).expect("profiles"); - let off = committed_profiles_with(choice.set(base, false)).expect("profiles"); - for ((stem, p), (_, q)) in on.iter().zip(&off) { - let metal = is_moltenvk_capture(stem); - assert_eq!(choice.taken(p), !metal, "{stem} {choice:?} on"); - assert!(!choice.taken(q), "{stem} {choice:?} off"); - assert_ne!(p.fingerprint(), q.fingerprint(), "{stem} {choice:?}"); - } - } } -/// On lavapipe each kernel of a choice records its kind exactly where its choice is on, and each -/// other kernel records its kind under every setting (all of them on and all of them off); where -/// a choice is on its kernel's module is smaller than where it is off, passes L3 either way, and -/// records no kind of a choice that is off. Each module is its entry alone (no routine). +/// On lavapipe each kernel records its kind, passes L3, and is its entry alone (no routine). #[test] -fn each_choice_records_its_kinds_only_when_on() { +fn each_kernel_records_its_kind() { let Some(bc) = bitcode() else { return; }; - for others in [true, false] { - let base = Choice::every(others); - for k in &KERNELS { - let words = |on: bool| { - let policy = k.choice.map_or(base, |c| c.set(base, on)); - let p = profile("lavapipe", policy).expect("profile"); - let what = format!("{} {:?} on {on}, others {others}", k.name, k.choice); - let a = compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - assert_eq!( - a.precision.contains(&k.note), - on || k.choice.is_none(), - "{what}: {:?}", - a.precision - ); - for c in Choice::ALL { - if Some(c) != k.choice && !others { - let theirs: Vec<_> = KERNELS - .iter() - .filter(|o| o.choice == Some(c) && o.note != k.note) - .map(|o| o.note) - .collect(); - assert!( - theirs.iter().all(|n| !a.precision.contains(n)), - "{what}: {:?}", - a.precision - ); - } - } - assert_eq!(functions(&a.module.words), 1, "{what}: no routine"); - a.module.words.len() - }; - if k.choice.is_none() { - words(true); - continue; - } - let (on, off) = (words(true), words(false)); - assert!( - on < off, - "{} others {others}: on {on} words, off {off}", - k.name - ); - } + let p = profile("lavapipe", DevicePolicy::default()).expect("profile"); + for k in &KERNELS { + let a = compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{}: {e:?}", k.name)); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{}: L3: {e}", k.name)); + assert!( + a.precision.contains(&k.note), + "{}: {:?}", + k.name, + a.precision + ); + assert_eq!(functions(&a.module.words), 1, "{}: no routine", k.name); } } @@ -374,50 +266,37 @@ fn the_maths_functions_are_within_their_bounds() { ); } -/// On lavapipe with the NaN and minimum and maximum on, an addition answers the device's NaN (a -/// NaN, here the operand's payload) where off selects Metal's canonical `0x7fc00000`, and `fmin` is -/// the device's `NMin` and `saturate` its `NClamp(x, 0, 1)`, answering the operand Metal does -/// beside a NaN and between two numbers either way. The maths functions' device divisions take the -/// same choice's NaN: Metal's canonical one off, selected (the routine they replace answers it), -/// the device's on. +/// On lavapipe an addition answers the device's NaN (a NaN, here the operand's payload), and so do +/// the maths functions' device divisions. `fmin` is the device's `NMin` and `saturate` its +/// `NClamp(x, 0, 1)`, answering the operand Metal does beside a NaN and between two numbers. #[test] -fn the_nan_and_min_max_are_the_device_s_on_and_metal_s_off() { +fn the_nan_and_min_max_are_the_device_s() { let Some(bc) = bitcode() else { return; }; - let base = Choice::every(true); - let on = profile("lavapipe", Choice::NanMinMax.set(base, true)).expect("on"); - let off = profile("lavapipe", Choice::NanMinMax.set(base, false)).expect("off"); + let p = profile("lavapipe", DevicePolicy::default()).expect("lavapipe"); let nan = f32::from_bits(0x7fc0_1234); for name in ["native_fadd", "native_fdiv", "native_fdiv_arcp"] { - let run = |p: &DeviceProfile| interpret(&bc, name, p, [nan, 1.0, 0.0]); - assert!(run(&on).is_nan(), "{name}"); - assert_eq!(run(&off).to_bits(), 0x7fc0_0000, "{name}"); + assert!(interpret(&bc, name, &p, [nan, 1.0, 0.0]).is_nan(), "{name}"); } - for p in [&on, &off] { - let min = |a: f32, b: f32| interpret(&bc, "native_fmin", p, [a, b, 0.0]); - assert_eq!(min(nan, 2.0), 2.0); - assert_eq!(min(2.0, nan), 2.0); - assert_eq!(min(1.0, -3.0), -3.0); - // `saturate` is Metal's `clamp(x, +0, 1)`, the device's `NClamp` on. - let saturate = |x: f32| interpret(&bc, "native_saturate", p, [x, 0.0, 0.0]); - for (x, want) in [ - (nan, 0.0f32), - (2.0, 1.0), - (-3.0, 0.0), - (0.25, 0.25), - (f32::INFINITY, 1.0), - (f32::NEG_INFINITY, 0.0), - ] { - assert_eq!(saturate(x), want, "saturate({x})"); - } - // Either zero on (`NativeMinMax`'s tie), `+0` off. - assert_eq!(saturate(-0.0), 0.0); + let min = |a: f32, b: f32| interpret(&bc, "native_fmin", &p, [a, b, 0.0]); + assert_eq!(min(nan, 2.0), 2.0); + assert_eq!(min(2.0, nan), 2.0); + assert_eq!(min(1.0, -3.0), -3.0); + // `saturate` is Metal's `clamp(x, +0, 1)`, the device's `NClamp`. + let saturate = |x: f32| interpret(&bc, "native_saturate", &p, [x, 0.0, 0.0]); + for (x, want) in [ + (nan, 0.0f32), + (2.0, 1.0), + (-3.0, 0.0), + (0.25, 0.25), + (f32::INFINITY, 1.0), + (f32::NEG_INFINITY, 0.0), + ] { + assert_eq!(saturate(x), want, "saturate({x})"); } - assert_eq!( - interpret(&bc, "native_saturate", &off, [-0.0, 0.0, 0.0]).to_bits(), - 0 - ); + // Either zero (`NativeMinMax`'s tie). + assert_eq!(saturate(-0.0), 0.0); } /// On lavapipe `dot` is the device's `OpDot` and `mix` its `FMix` (a `half` one rounded once), each diff --git a/crates/metal2vulkan/src/tests/engine_rgbx_storage.rs b/crates/metal2vulkan/src/tests/engine_rgbx_storage.rs index 348dc08f0..f97a40a12 100644 --- a/crates/metal2vulkan/src/tests/engine_rgbx_storage.rs +++ b/crates/metal2vulkan/src/tests/engine_rgbx_storage.rs @@ -4,8 +4,8 @@ //! 27.0.1). //! //! On the CPU interpreter, each kernel runs under the choice without the conversion and with it, -//! on the same image and values, for `float`, `half`, `uint` and `int` texels and the classes a -//! held RGBA twin takes (`Identity`; a half-float twin's `HalfQuietNan`): a `read_write` read +//! on the same image and values, for `float`, `half`, `uint` and `int` texels and the class a +//! held RGBA twin takes (`Identity`, a half-float twin's too): a `read_write` read //! is the plain read with alpha 1, in bounds and past the texture (whose alpha Metal reads 1 //! too); a write, `access::write` or `read_write`, stores the plain write's texel with its fourth //! lane the green lane's bits, after the class's conversion. An sRGB twin's `SrgbEncode`, and an @@ -77,10 +77,7 @@ impl Texel { match self { Texel::Float | Texel::Half => vec![ (vk::Format::R8G8B8A8_UNORM, StorageImageClass::Identity), - ( - vk::Format::R16G16B16A16_SFLOAT, - StorageImageClass::HalfQuietNan, - ), + (vk::Format::R16G16B16A16_SFLOAT, StorageImageClass::Identity), (vk::Format::R32G32B32A32_SFLOAT, StorageImageClass::Identity), ], Texel::Uint => vec![(vk::Format::R32G32B32A32_UINT, StorageImageClass::Identity)], diff --git a/crates/metal2vulkan/src/tests/engine_stage_io_tail.rs b/crates/metal2vulkan/src/tests/engine_stage_io_tail.rs index e28fe04c1..025bc9069 100644 --- a/crates/metal2vulkan/src/tests/engine_stage_io_tail.rs +++ b/crates/metal2vulkan/src/tests/engine_stage_io_tail.rs @@ -304,7 +304,6 @@ fn without_the_feature_the_weights_are_varyings() { numeric: IoNumeric::Float, components: 2, source_bits: 32, - bits: 32, }; for stem in ["lavapipe", "intel-irisxe-rplp-anv", "nvidia-pascal-linux"] { let p = prof(stem); diff --git a/crates/metal2vulkan/src/tests/engine_texel_nans.rs b/crates/metal2vulkan/src/tests/engine_texel_nans.rs deleted file mode 100644 index 475139bed..000000000 --- a/crates/metal2vulkan/src/tests/engine_texel_nans.rs +++ /dev/null @@ -1,673 +0,0 @@ -//! Metal's NaN of a `half` texel under the NaN switch: plain Metal (an Apple M3 Max -//! under macOS 26.7) hands back a 16-bit float texel's own bits, its sign, payload and signalling -//! bit kept, for a read, a nearest sample or a gather, and `0x7e00` for every other NaN: a 32-bit -//! float texel's, and every linear sample's. -//! -//! On the lavapipe profile (native half rounding and native device sampling; the device's own NaN -//! by default), a kernel reads, samples (nearest and linear, constexpr samplers) or gathers a -//! `texture2d` and stores the `half4`: -//! -//! - a read runs on the CPU interpreter over a uniform texture whose texels the device decodes -//! exactly (each `half` widened, as NVIDIA's texture unit decodes them): under -//! `NanMinMaxPolicy::Exact` every NaN lane is Metal's, the texel's own bits where the slot's -//! class (`TexelFormat`, read as data) is a 16-bit float format's and `0x7e00` where it is a -//! 32-bit float format's, every other lane the texel's value; under `NanMinMaxPolicy::Native`, -//! the default, the module reads no class, and a signalling NaN texel does not read back as -//! its bits; -//! - a sample or gather (the interpreter models no device sampler) is checked in its module: -//! under the switch a nearest sample and a gather read the class and hold `0x7e00`, a linear -//! sample holds `0x7e00` and reads no class; under the default none does. -//! -//! Every module validates, and the plan's word estimate bounds its emission. `llvm-as` assembles -//! the kernels; without it the tests skip visibly. - -use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU64, Ordering}; - -use crate::budget::SPIRV_WORDS; -use crate::device::profile::DeviceProfile; -use crate::device::{DevicePolicy, NanMinMaxPolicy}; -use crate::library::FunctionConstantValues; -use crate::lower::select::{LowerInputs, Plan}; -use crate::metal::texel_format::{texel_format, TexelFormat}; -use crate::metal::PixelFormat; -use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::{Axis, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage}; -use crate::pipeline::testing::{ - link_and_validate, llvm_assemble, meter, profile, typed_module_with, AssembleError, -}; -use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; -use crate::spirv::ir::{GlobalKind, Inst, TypedModule}; - -const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; - -/// The texture's side: 4 x 4 texels, one thread each. -const SIDE: u32 = 4; - -const TEXTURE: SlotRef = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 0, -}; - -/// Bitcode of the module `body` (after the AIR header), or `None` without `llvm-as`. -fn assemble(name: &str, body: &str) -> Option> { - static NEXT: AtomicU64 = AtomicU64::new(0); - let dir = std::env::temp_dir().join(format!( - "m2v-texel-nans-{}-{}-{}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed), - name.replace(' ', "-") - )); - std::fs::create_dir_all(&dir).expect("scratch"); - let ll = dir.join("k.ll"); - std::fs::write(&ll, format!("{HEADER}{body}")).expect("write"); - let r = llvm_assemble(&ll); - let _ = std::fs::remove_dir_all(&dir); - match r { - Ok(x) => Some(x), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("{name}: {why}"), - } -} - -/// How the kernel accesses `texture2d` slot 0 at its thread's texel `gid`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Access { - /// `t.read(gid)` of an `access::read` texture: one texel. - Read, - /// `t.sample(s, coord)` at the texel's centre through a nearest constexpr sampler: one texel. - Nearest, - /// `t.sample(s, coord)` at the texel's centre through a linear constexpr sampler: filtered. - Linear, - /// `t.gather(s, coord)` (component 0) through a nearest constexpr sampler: one texel a lane. - Gather, -} - -impl Access { - /// Whether Metal hands back a 16-bit float texel's own NaN for the access. - fn one_texel(self) -> bool { - self != Access::Linear - } -} - -/// The words of a constexpr sampler of normalized coordinates, every axis clamped to its edge, -/// no mip filter, min and mag filter `filter` (0 nearest, 1 linear). -fn sampler_words(filter: u64) -> u64 { - const BASE: u64 = 0x007b_ff00_0008_0000; - let edge = 1; - BASE | edge | edge << 3 | edge << 6 | filter << 9 | filter << 11 -} - -/// A kernel accessing slot 0 as `access` at thread `gid` of the `SIDE` x `SIDE` grid, storing -/// the `half4` to `out[gid.x + SIDE gid.y]` (buffer 0). -fn kernel(access: Access) -> String { - let (vec4, suffix) = ("<4 x half>", "v4f16"); - let (tex_access, call, decl) = match access { - Access::Read => ( - "read", - format!( - "%rs = call ptr addrspace(2) @air.get_read_sampler()\n %r = call {{ {vec4}, i8 }} @air.read_texture_2d.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) %rs, <2 x i32> %gid, <2 x i32> zeroinitializer, i32 0, i32 1)" - ), - format!( - "declare ptr addrspace(2) @air.get_read_sampler()\ndeclare {{ {vec4}, i8 }} @air.read_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32)" - ), - ), - Access::Nearest | Access::Linear => ( - "sample", - format!( - "%r = call {{ {vec4}, i8 }} @air.sample_texture_2d.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)" - ), - format!( - "declare {{ {vec4}, i8 }} @air.sample_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)" - ), - ), - Access::Gather => ( - "sample", - format!( - "%r = call {{ {vec4}, i8 }} @air.gather_texture_2d.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i32 0, i32 0)" - ), - format!( - "declare {{ {vec4}, i8 }} @air.gather_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i32, i32)" - ), - ), - }; - let filter = u64::from(access == Access::Linear); - let (state, states, state_md) = match access { - Access::Read => (String::new(), "", ""), - Access::Nearest | Access::Linear | Access::Gather => ( - format!( - "@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {}, i64 0], align 8\n\n", - sampler_words(filter) - ), - "!air.sampler_states = !{!6}\n", - "!6 = !{!\"air.sampler_state\", ptr addrspace(2) @__air_sampler_state}\n", - ), - }; - let scale = 1.0 / f64::from(SIDE); - format!( - r#"{state}define void @k(ptr addrspace(1) %t, ptr addrspace(1) %out, <2 x i32> %gid) {{ - %x = extractelement <2 x i32> %gid, i64 0 - %y = extractelement <2 x i32> %gid, i64 1 - %row = mul i32 %y, {SIDE} - %n = add i32 %x, %row - %i = zext i32 %n to i64 - %fx = uitofp i32 %x to float - %fy = uitofp i32 %y to float - %cx = fadd float %fx, 0.5 - %cy = fadd float %fy, 0.5 - %c0 = insertelement <2 x float> zeroinitializer, float %cx, i64 0 - %c1 = insertelement <2 x float> %c0, float %cy, i64 1 - %uv = fmul <2 x float> %c1, - {call} - %v = extractvalue {{ {vec4}, i8 }} %r, 0 - %q = getelementptr inbounds {vec4}, ptr addrspace(1) %out, i64 %i - store {vec4} %v, ptr addrspace(1) %q, align 8 - ret void -}} - -{decl} - -!air.kernel = !{{!0}} -{states}!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.{tex_access}", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"half4", !"air.arg_name", !"out"}} -!5 = !{{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"gid"}} -{state_md}"# - ) -} - -/// The `f32` bits of half `h` widened exactly, as a device that decodes a half-float texel -/// exactly hands it over: a NaN keeps its sign and its payload at the top of the significand. -fn widened(h: u16) -> u32 { - let sign = u32::from(h & 0x8000) << 16; - let exp = u32::from(h >> 10 & 0x1F); - let man = u32::from(h & 0x3FF); - match exp { - 0x1F => sign | 0x7F80_0000 | man << 13, - 0 if man == 0 => sign, - 0 => { - // A half subnormal: a normal `f32`. - let shift = man.leading_zeros() - 21; - sign | (113 - shift) << 23 | (man << shift & 0x3FF) << 13 - } - _ => sign | (exp + 112) << 23 | man << 13, - } -} - -/// Whether half bits `h` are a NaN. -fn is_nan(h: u16) -> bool { - h & 0x7C00 == 0x7C00 && h & 0x3FF != 0 -} - -/// The texels of the uniform texture, four channels each: quiet and signalling NaNs of both -/// signs and payload edges, among finite values and infinities (the probe's halves). -const TEXELS: [[u16; 4]; 4] = [ - [0x7e00, 0x7c01, 0x3c00, 0xfe00], - [0xfc01, 0x7dff, 0x7fff, 0x0001], - [0xffff, 0x7d55, 0x7c00, 0xfe01], - [0x7f00, 0x8000, 0xff00, 0x7bff], -]; - -/// The module's texture resource at slot 0 (a combined binding's, for a sampled slot). -fn resource(m: &TypedModule) -> ResourceSlot { - m.globals() - .iter() - .find_map(|g| match g.kind { - GlobalKind::Resource(s) - if s.index == 0 - && matches!( - s.kind, - ResourceKind::Texture | ResourceKind::CombinedTextureSampler(_) - ) => - { - Some(s) - } - _ => None, - }) - .expect("the texture's resource") -} - -/// Compile the kernel `bc` on `p`, check that the plan's word estimate bounds the emission, and -/// validate the linked module: the emitted words. -fn validate(bc: &[u8], p: &DeviceProfile, what: &str) -> u64 { - let consts = FunctionConstantValues::defaults(); - let entry = EntryRef::Name("k"); - let inputs = LowerInputs::new(); - let plan = plan_bitcode(bc, entry, &consts, p, &inputs, &mut meter()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let a = compile_bitcode(bc, entry, &consts, p, &inputs, &mut meter(), SPIRV_WORDS) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let words = a.module.words.len() as u64; - assert!( - plan.estimate.words >= words, - "{what}: estimate {} < emitted {words}", - plan.estimate.words - ); - link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}")); - words -} - -/// Resources of a dispatch of one-thread threadgroups over the grid, the slot's class `class`. -fn resources(plan: &Plan, class: u32) -> Resources { - let mut spec = BTreeMap::new(); - for axis in [Axis::X, Axis::Y, Axis::Z] { - spec.insert(SpecKey::LocalSize(axis), 1); - } - spec.insert(SpecKey::FlatLocalSize, 1); - spec.insert(SpecKey::TexelFormat(TEXTURE), u64::from(class)); - spec.insert( - SpecKey::PlainHalfTexels(TEXTURE), - u64::from(crate::metal::texel_format::TexelFormat(class).plain_on_metal_sampler()), - ); - let push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; - let out = Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 0, - }), - address: None, - bytes: vec![0xab; (8 * SIDE * SIDE) as usize], - }; - Resources { - buffers: vec![out], - push, - spec, - } -} - -/// The `half4` every thread of kernel `bc` on `p` stores over the uniform texture of `texel` -/// with the slot's class `class`, in both scheduling orders, which must agree. -fn run(bc: &[u8], p: &DeviceProfile, texel: [u16; 4], class: u32, what: &str) -> Vec<[u16; 4]> { - run_words(bc, p, texel.map(widened), class, what) -} - -/// [`run`] over a texture whose texel the device decodes to the `f32` words `texel`. -fn run_words( - bc: &[u8], - p: &DeviceProfile, - texel: [u32; 4], - class: u32, - what: &str, -) -> Vec<[u16; 4]> { - let (plan, m) = typed_module_with(bc, "k", p, &LowerInputs::new()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let mut img = Image::new(resource(&m), [SIDE, SIDE, 1], 1, 1, 1); - for n in 0..SIDE * SIDE { - let at = img.index(0, 0, 0, [n % SIDE, n / SIDE, 0]).expect("texel"); - img.texels[at] = texel; - } - let res = resources(&plan, class); - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups: [SIDE, SIDE, 1], - order, - ..Config::default() - }; - let (o, _) = run_with_images(&m, &cfg, res.clone(), vec![img.clone()]) - .unwrap_or_else(|e| panic!("{what}: interpreter: {e:?}")); - outs.push(o.buffers.into_iter().next().expect("out")); - } - assert_eq!(outs[0], outs[1], "{what}: the scheduling orders disagree"); - outs[0] - .as_chunks::<8>() - .0 - .iter() - .map(|t| { - let h = |i: usize| u16::from_le_bytes([t[2 * i], t[2 * i + 1]]); - [h(0), h(1), h(2), h(3)] - }) - .collect() -} - -/// The `half` lanes Metal hands back for `texel` through `access` from a texture whose channels -/// are 16-bit floats (`halves`) or 32-bit floats: a gather's lanes are each its texel's red. -fn metal(access: Access, texel: [u16; 4], halves: bool) -> [u16; 4] { - let lanes = match access { - Access::Gather => [texel[0]; 4], - _ => texel, - }; - lanes.map(|h| match is_nan(h) && !(halves && access.one_texel()) { - true => 0x7e00, - false => h, - }) -} - -/// The profiles of lavapipe under the NaN switch (`NanMinMaxPolicy::Exact`) and the default. -fn profiles() -> (DeviceProfile, DeviceProfile) { - let switched = DevicePolicy { - nan_and_min_max: NanMinMaxPolicy::Exact, - ..DevicePolicy::default() - }; - ( - profile("lavapipe", switched).expect("profile"), - profile("lavapipe", DevicePolicy::default()).expect("profile"), - ) -} - -/// Whether `plan` reads texture slot 0's class (`RuntimeFact::TexelFormat`, read as data). -fn reads_class(plan: &Plan) -> bool { - plan.facts - .contains(&RuntimeFact::TexelFormat { slot: TEXTURE }) -} - -/// The constants of module `m` that are `0x7fc00000` in every lane: Metal's `0x7e00` held. -fn canonical_nans(m: &TypedModule) -> usize { - use crate::spirv::ir::{ConstKind, Constant}; - let canonical = |bits: u64| bits == 0x7fc0_0000; - m.consts() - .iter() - .filter(|(_, c)| match &c.kind { - ConstKind::Plain(Constant::Composite { parts, .. }) => parts - .iter() - .all(|p| m.consts().scalar_bits(*p).is_some_and(|b| canonical(b.0))), - _ => false, - }) - .count() -} - -/// A read on the interpreter: under `NanMinMaxPolicy::Exact` every NaN texel of a 16-bit float -/// texture (or of a class whose conversion is not measured, `TexelFormat::OTHER`, the device's -/// decode) reads back as its own bits and of a 32-bit float texture as `0x7e00`, every other lane -/// its value; under the default (`NanMinMaxPolicy::Native`) the module reads no class and is -/// smaller, and a signalling NaN texel does not read back as its bits. -#[test] -fn a_half_texel_reads_metals_nan_under_the_nan_switch() { - let (exact, native) = profiles(); - let half16 = texel_format(PixelFormat::RGBA16Float).0; - let float32 = texel_format(PixelFormat::RGBA32Float).0; - let access = Access::Read; - let what = format!("{access:?}"); - let Some(bc) = assemble(&what, &kernel(access)) else { - return; - }; - let words_exact = validate(&bc, &exact, &format!("{what} exact")); - let words_native = validate(&bc, &native, &format!("{what} native")); - assert!( - words_native < words_exact, - "{what}: the default's {words_native} words, the switch's {words_exact}" - ); - let plan = |p: &DeviceProfile| { - typed_module_with(&bc, "k", p, &LowerInputs::new()) - .unwrap_or_else(|e| panic!("{what}: {e}")) - .0 - }; - assert!( - reads_class(&plan(&exact)), - "{what}: the switch reads no class" - ); - assert!( - !reads_class(&plan(&native)), - "{what}: the default reads a class" - ); - let mut native_differs = false; - for texel in TEXELS { - // A class whose conversion is not measured keeps the device's decode, here exact. - let other = TexelFormat::OTHER.0; - for (class, halves) in [(half16, true), (float32, false), (other, true)] { - let at = format!("{what} {texel:04x?} halves {halves}"); - let want = metal(access, texel, halves); - for got in run(&bc, &exact, texel, class, &at) { - assert_eq!(got, want, "{at}: got {got:04x?}, Metal {want:04x?}"); - } - if halves { - native_differs |= run(&bc, &native, texel, class, &at) - .iter() - .any(|got| *got != want); - } - } - } - assert!( - native_differs, - "{what}: the default answered Metal's NaNs too" - ); -} - -/// NaNs of a 32-bit float texel: signalling NaNs of the smallest payload, the quiet NaN, and -/// NaNs whose payload's top bits a narrowing to `half` would keep. -const FLOAT_NANS: [u32; 6] = [ - 0x7f80_0001, - 0x7fc0_0000, - 0xff80_0001, - 0x7fbf_ffff, - 0x7fc1_2345, - 0xffff_ffff, -]; - -/// A read of a 32-bit float texel on the interpreter, on lavapipe's and the RTX 5080's profiles: -/// under `NanMinMaxPolicy::Exact` its every NaN, in any lane, signalling NaNs of the smallest -/// payload included, reads back as `0x7e00`, beside a `1.0` and beside the largest `float`, which -/// rounds to infinity. (On the devices themselves the second differs: item 5.) -#[test] -fn a_32_bit_float_texels_nans_read_metals_canonical_nan_in_every_lane() { - let float32 = texel_format(PixelFormat::RGBA32Float).0; - let access = Access::Read; - let what = format!("{access:?}"); - let Some(bc) = assemble(&what, &kernel(access)) else { - return; - }; - let profiles = ["lavapipe", "nvidia-rtx5080-laptop"].map(|stem| { - let switched = DevicePolicy { - nan_and_min_max: NanMinMaxPolicy::Exact, - ..DevicePolicy::default() - }; - (stem, profile(stem, switched).expect("profile")) - }); - // Beside a `1.0`, and beside the largest `float`, which overflows a `half`. - for (beside, rounded) in [(0x3f80_0000, 0x3c00), (0x7f7f_ffff, 0x7c00)] { - for nan in FLOAT_NANS { - for lane in 0..4 { - let mut texel = [beside; 4]; - texel[lane] = nan; - let at = format!("{what} {texel:08x?}"); - for (stem, p) in &profiles { - for got in run_words(&bc, p, texel, float32, &at) { - let mut want = [rounded; 4]; - want[lane] = 0x7e00; - assert_eq!(got, want, "{stem} {at}: got {got:04x?}, Metal {want:04x?}"); - } - } - } - } - } -} - -/// The image fetches and gathers of module `m`. -fn fetches_and_gathers(m: &TypedModule) -> (usize, usize) { - let insts = || m.blocks().iter().flat_map(|b| b.insts.iter()); - let fetches = insts() - .filter(|n| matches!(n.inst, Inst::ImageFetch { .. })) - .count(); - let gathers = insts() - .filter(|n| matches!(n.inst, Inst::ImageGather { .. })) - .count(); - (fetches, gathers) -} - -/// A gather under the NaN switch: where the bound class is a 16-bit float one the shader fetches -/// the four texels Metal's gather reads, so each lane is its texel's own bits, NaNs included, on -/// the interpreter (which models fetches, not a device's gather); any other class keeps the -/// device's gather. Under the default the module fetches nothing. -#[test] -fn a_half_gather_fetches_its_16_bit_texels_under_the_nan_switch() { - let (exact, native) = profiles(); - let half16 = texel_format(PixelFormat::RGBA16Float).0; - let access = Access::Gather; - let what = format!("{access:?}"); - let Some(bc) = assemble(&what, &kernel(access)) else { - return; - }; - validate(&bc, &exact, &format!("{what} exact")); - validate(&bc, &native, &format!("{what} native")); - let module = |p: &DeviceProfile| { - typed_module_with(&bc, "k", p, &LowerInputs::new()) - .unwrap_or_else(|e| panic!("{what}: {e}")) - .1 - }; - let (fetches, gathers) = fetches_and_gathers(&module(&exact)); - assert_eq!( - (fetches, gathers), - (4, 1), - "{what}: the switch's fetches and gather" - ); - let (fetches, gathers) = fetches_and_gathers(&module(&native)); - assert_eq!( - (fetches, gathers), - (0, 1), - "{what}: the default's fetches and gather" - ); - for texel in TEXELS { - let at = format!("{what} {texel:04x?}"); - let want = metal(access, texel, true); - for got in run(&bc, &exact, texel, half16, &at) { - assert_eq!(got, want, "{at}: got {got:04x?}, Metal {want:04x?}"); - } - } -} - -/// Samples and gathers (the interpreter models no device sampler): under `NanMinMaxPolicy::Exact` a -/// nearest sample and a gather read the slot's class and hold Metal's `0x7e00`, a linear sample, -/// which never hands back a texel's own NaN, holds `0x7e00` and reads no class; under the default -/// each reads no class, holds no `0x7e00` and is smaller; every module validates and the plan's -/// estimate bounds it. -#[test] -fn a_half_texels_sample_and_gather_take_metals_nan_under_the_nan_switch() { - let (exact, native) = profiles(); - for access in [Access::Nearest, Access::Linear, Access::Gather] { - let what = format!("{access:?}"); - let Some(bc) = assemble(&what, &kernel(access)) else { - return; - }; - let words_exact = validate(&bc, &exact, &format!("{what} exact")); - let words_native = validate(&bc, &native, &format!("{what} native")); - assert!( - words_native < words_exact, - "{what}: the default's {words_native} words, the switch's {words_exact}" - ); - let typed = |p: &DeviceProfile| { - typed_module_with(&bc, "k", p, &LowerInputs::new()) - .unwrap_or_else(|e| panic!("{what}: {e}")) - }; - let (exact_plan, exact_module) = typed(&exact); - let (native_plan, native_module) = typed(&native); - assert_eq!( - reads_class(&exact_plan), - access.one_texel(), - "{what}: the switch's class" - ); - assert!( - !reads_class(&native_plan), - "{what}: the default reads a class" - ); - assert!( - canonical_nans(&exact_module) > 0, - "{what}: the switch holds no 0x7e00" - ); - assert_eq!( - canonical_nans(&native_module), - 0, - "{what}: the default holds 0x7e00" - ); - } -} - -/// On the MoltenVK captures, whose arithmetic answers Metal's canonical NaN -/// (`NanEncoding::MetalCanonical`), a texel's NaN is still the image's decode, which the access -/// narrows itself (through MoltenVK on the Apple M3 Max a 32-bit float texel's NaN read as `half` -/// kept its payload's top bits). So under `NanMinMaxPolicy::Exact` the access takes Metal's rule -/// there too (`TexelNanRoute::Metal`): a read, on the interpreter, hands back a 16-bit float -/// texel's NaN as its own bits and every NaN of a 32-bit float texel, in any lane, as `0x7e00` -/// (under the default a NaN is the device's conversion's, which the interpreter's makes `0x7e00` -/// too); a read, a nearest sample and a -/// gather read the slot's class, and every access holds more `0x7e00` than under the default (the -/// default's half texel conversion reads the class too, so its reading proves nothing there). -/// Every module validates and the plan's estimate bounds it. -#[test] -fn a_half_texels_nan_is_metals_under_the_nan_switch_where_the_arithmetic_answers_metals() { - use crate::device::profile::{NanEncoding, TexelNanRoute}; - let half16 = texel_format(PixelFormat::RGBA16Float).0; - let float32 = texel_format(PixelFormat::RGBA32Float).0; - let switched = DevicePolicy { - nan_and_min_max: NanMinMaxPolicy::Exact, - ..DevicePolicy::default() - }; - { - let stem = "moltenvk-m3"; - let exact = profile(stem, switched).expect("profile"); - let native = profile(stem, DevicePolicy::default()).expect("profile"); - for p in [&exact, &native] { - assert_eq!( - p.fields().nan_encoding, - NanEncoding::MetalCanonical, - "{stem}" - ); - } - assert_eq!(exact.fields().texel_nans, TexelNanRoute::Metal, "{stem}"); - assert_eq!(native.fields().texel_nans, TexelNanRoute::Device, "{stem}"); - for access in [ - Access::Read, - Access::Nearest, - Access::Linear, - Access::Gather, - ] { - let what = format!("{access:?} on {stem}"); - let Some(bc) = assemble(&what, &kernel(access)) else { - return; - }; - validate(&bc, &exact, &format!("{what} exact")); - validate(&bc, &native, &format!("{what} native")); - let typed = |p: &DeviceProfile| { - typed_module_with(&bc, "k", p, &LowerInputs::new()) - .unwrap_or_else(|e| panic!("{what}: {e}")) - }; - let (exact_plan, exact_module) = typed(&exact); - let (_, native_module) = typed(&native); - if access.one_texel() { - assert!( - reads_class(&exact_plan), - "{what}: the switch reads no class" - ); - } - let (held, held_by_default) = ( - canonical_nans(&exact_module), - canonical_nans(&native_module), - ); - assert!( - held > held_by_default, - "{what}: the switch holds {held} 0x7e00, the default {held_by_default}" - ); - if access != Access::Read { - continue; - } - for texel in TEXELS { - for (class, halves) in [(half16, true), (float32, false)] { - let at = format!("{what} {texel:04x?} halves {halves}"); - let want = metal(access, texel, halves); - for got in run(&bc, &exact, texel, class, &at) { - assert_eq!(got, want, "{at}: got {got:04x?}, Metal {want:04x?}"); - } - } - } - for nan in FLOAT_NANS { - for lane in 0..4 { - let mut texel = [0x3f80_0000; 4]; - texel[lane] = nan; - let at = format!("{what} {texel:08x?}"); - let mut want = [0x3c00; 4]; - want[lane] = 0x7e00; - for got in run_words(&bc, &exact, texel, float32, &at) { - assert_eq!(got, want, "{at}: got {got:04x?}, Metal {want:04x?}"); - } - } - } - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_texture.rs b/crates/metal2vulkan/src/tests/engine_texture.rs index 4a5473ed9..8b86ccc61 100644 --- a/crates/metal2vulkan/src/tests/engine_texture.rs +++ b/crates/metal2vulkan/src/tests/engine_texture.rs @@ -419,21 +419,20 @@ fn a_half_texel_read_notes_the_device_nan_encoding_where_the_bound_format_may_ho /// OpIsNan. const OP_IS_NAN: u16 = 156; -/// A `half` written to a storage texture stores a NaN as Metal does: the half's own bits in a -/// 16-bit float channel, `0x7fc00000` in a 32-bit one. `txt_level_write` writes halves no -/// arithmetic makes. Bound in `RGBA32Float` (where the choice declares it) its write turns every -/// NaN lane into `0x7fc00000` (an `OpIsNan` test) and records no `DeviceNanEncoding`; bound in -/// `RGBA16Float` it keeps the half and records the note on a profile without +/// A `half` written to a storage texture stores a NaN as the device converts the half widened, +/// noted where that need not be Metal's (the half's own bits in a 16-bit float channel, +/// `0x7fc00000` in a 32-bit one). `txt_level_write` writes halves no arithmetic makes. Bound in +/// `RGBA32Float` (where the choice declares it) its write tests no NaN and records +/// `DeviceNanEncoding`; bound in `RGBA16Float` it records the note on a profile without /// `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); +/// 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 reads the slot's `RuntimeFact::StorageTextureHalfChannels` word and records no note: the -/// runtime announces it at the bind (`Device::degrade_half_texel_writes`). A choice of the -/// `RGBA16Float` texture's unsigned integer alias (`StorageImageClass::HalfBits`, on a profile -/// without the deviation) writes the half's bits and records nothing; so does `RGBX16Float`'s, -/// whose image is `RGBA16Float`'s. +/// write records the note. A choice of the `RGBA16Float` texture's unsigned integer alias +/// (`StorageImageClass::HalfBits`, on a profile without the deviation) writes the half's bits and +/// records nothing; so does `RGBX16Float`'s, whose image is `RGBA16Float`'s. #[test] -fn a_half_texel_write_stores_metal_s_nans_or_records_the_device_nan_encoding() { +fn a_half_texel_write_records_the_device_nan_encoding_where_it_may_not_be_metal_s() { use crate::device::requirements::VkProperty; use crate::error::DriverDeviation; let Some(bc) = fixture("txt_level_write") else { @@ -460,10 +459,6 @@ fn a_half_texel_write_stores_metal_s_nans_or_records_the_device_nan_encoding() { } }; let noted = |a: &FunctionArtifact| a.precision.contains(&PrecisionNote::DeviceNanEncoding); - let word = |a: &FunctionArtifact| { - a.facts - .contains(&RuntimeFact::StorageTextureHalfChannels { slot }) - }; let tests = |a: &FunctionArtifact| opcodes(&a.module.words).contains(&OP_IS_NAN); for pf in [ PixelFormat::RGBA8Unorm, @@ -474,18 +469,12 @@ fn a_half_texel_write_stores_metal_s_nans_or_records_the_device_nan_encoding() { let Some((a, undeclared, bits)) = compiled(pf) else { continue; }; - let what = format!( - "{stem}: {pf:?}: word {}, tests {}, noted {}", - word(&a), - tests(&a), - noted(&a) - ); + let what = format!("{stem}: {pf:?}: tests {}, noted {}", tests(&a), noted(&a)); if undeclared { - assert!(word(&a) && tests(&a) && !noted(&a), "{what}"); + assert!(noted(&a), "{what}"); formatless += 1; continue; } - assert!(!word(&a), "{what}"); match pf { // Through the unsigned integer alias the half's bits are written as they are: // no note, no measured property. @@ -510,12 +499,37 @@ fn a_half_texel_write_stores_metal_s_nans_or_records_the_device_nan_encoding() { measured += usize::from(keeps); } PixelFormat::RGBA32Float => { - assert!(tests(&a) && !noted(&a), "{what}"); + assert!(!tests(&a) && noted(&a), "{what}"); float += 1; } _ => assert!(!noted(&a), "{what}"), } } + // A device of the deviation writes a half-float texture without a format, so its + // committed choice declares none; one that declares `RGBA16Float` stores Metal's NaN. + if keeps { + let declared = crate::pipeline::lower_inputs::StorageImageChoice::new( + crate::vk::Format::R16G16B16A16_SFLOAT, + StorageImageClass::Identity, + ); + let mut inputs = LowerInputs::new(); + inputs.storage_images.insert(slot, declared); + let what = format!("{stem}: a declared RGBA16Float choice"); + match with_inputs(&bc, "txt_level_write", &p, &inputs) { + Err(Error::NeedsInput(_) | Error::Unsupported(_)) => {} + a => { + let a = ok(a, &p, &what); + assert!(!noted(&a), "{what}"); + assert!( + a.requirements + .properties + .contains(&VkProperty::MetalHalfTexelWrites), + "{what}" + ); + measured += 1; + } + } + } } assert!( float > 0 && formatless > 0 && measured > 0 && aliased > 0, diff --git a/crates/metal2vulkan/src/tests/engine_texture_interp.rs b/crates/metal2vulkan/src/tests/engine_texture_interp.rs index c66053278..4845d7f03 100644 --- a/crates/metal2vulkan/src/tests/engine_texture_interp.rs +++ b/crates/metal2vulkan/src/tests/engine_texture_interp.rs @@ -613,11 +613,11 @@ fn half_reads_convert_by_the_bound_format() { } /// A `half` read keeps the texel's exact value: a half-float texel, which the device decodes to its -/// exact `f32` value, reads back bit for bit, every half subnormal, both zeros, both infinities, -/// `±65504`, and NaN payloads included; a 32-bit float texel rounds to nearest even onto the half -/// grid, subnormals kept, past `65504` to the infinity. The interpreter gives `OpQuantizeToF16`'s -/// result below the smallest normal half as the zero of the input's sign and its NaN as `0x7E00`, -/// so a bare quantize fails here. +/// exact `f32` value, reads back bit for bit, every half subnormal, both zeros, both infinities and +/// `±65504` included, and a NaN as a NaN, its bits the rounding's (`DeviceNanEncoding`); a 32-bit +/// float texel rounds to nearest even onto the half grid, subnormals kept, past `65504` to the +/// infinity. The interpreter gives `OpQuantizeToF16`'s result below the smallest normal half as the +/// zero of the input's sign, so a bare quantize fails here. #[test] fn half_reads_keep_subnormals_zeros_infinities_and_nans() { let Some(bc) = fixture() else { @@ -670,7 +670,16 @@ fn half_reads_keep_subnormals_zeros_infinities_and_nans() { .iter() .map(|c| u16::from_le_bytes([c[0], c[1]])) .collect(); - assert_eq!(got, want, "{stem}: texel {texel:08x?}"); + let nan = |h: u16| h & 0x7C00 == 0x7C00 && h & 0x3FF != 0; + let same = got.len() == want.len() + && got + .iter() + .zip(want) + .all(|(&g, &w)| g == w || (nan(g) && nan(w))); + assert!( + same, + "{stem}: texel {texel:08x?}: {got:04x?} for {want:04x?}" + ); } ran += 1; } diff --git a/crates/metal2vulkan/src/tests/engine_texture_levels.rs b/crates/metal2vulkan/src/tests/engine_texture_levels.rs index 5c0a0c212..2d0786c34 100644 --- a/crates/metal2vulkan/src/tests/engine_texture_levels.rs +++ b/crates/metal2vulkan/src/tests/engine_texture_levels.rs @@ -200,8 +200,6 @@ fn push_bytes(plan: &Plan, levels: &[(u32, u32)]) -> Vec { push[offset as usize..offset as usize + 4].copy_from_slice(&n.to_le_bytes()); } (PushField::SlotBindOffset(_) | PushField::DispatchRegion, PushLoc::Push { .. }) => {} - // 0: a `half` write's NaN lanes `0x7fc00000`; the kernels write none. - (PushField::TextureHalfChannels(_), PushLoc::Push { .. }) => {} // A bound value read as data, which the interpreter writes from `spec`. (PushField::Specialized(_), PushLoc::Push { .. }) => {} // No slot's writes dropped: the word stays 0. diff --git a/crates/metal2vulkan/src/tests/engine_vertex_fetch.rs b/crates/metal2vulkan/src/tests/engine_vertex_fetch.rs index c1657b187..c89469e3e 100644 --- a/crates/metal2vulkan/src/tests/engine_vertex_fetch.rs +++ b/crates/metal2vulkan/src/tests/engine_vertex_fetch.rs @@ -1255,8 +1255,8 @@ fn a_label_pipeline_reads_its_integer_attribute_as_float() { } } -/// A fixed-function vertex attribute of a narrow-float format read as `float` answers Metal's -/// canonical NaN, and one of any other format keeps the bits the device's input delivered. +/// A fixed-function vertex attribute read as `float` keeps the words the device's input delivered, +/// and one of a narrow-float format records that its NaNs are the device's. /// /// The owned `dsx_int_attributes` fixture's `int_attribute_to_float4` writes the one `float4` /// attribute it reads to `out[vid]`, so the module's answer is read bit for bit. The interpreter @@ -1268,14 +1268,15 @@ fn a_label_pipeline_reads_its_integer_attribute_as_float() { /// macOS 27.0.1: a `half` code and a `FloatRG11B10` field whose 5-bit exponent is all ones both /// reach a `float` attribute as `0x7FC00000`, payload and sign dropped. A device's widening /// carries the field's bits up into the payload instead (`0x7FC02000` for the `half` codes -/// `0x7E01` and `0xFE01`, `0x7FFE0000` for an all-ones `FloatRG11B10` field, measured on RADV). -/// Every finite, zero, subnormal and infinite word passes through, and a `Float4` attribute keeps -/// every word, NaNs included, as Metal's fetch of a 32-bit float does. +/// `0x7E01` and `0xFE01`, `0x7FFE0000` for an all-ones `FloatRG11B10` field, measured on RADV), +/// which the module keeps (`PrecisionNote::DeviceNanEncoding`). Every finite, zero, subnormal and +/// infinite word passes through, and a `Float4` attribute keeps every word, NaNs included, as +/// Metal's fetch of a 32-bit float does. #[test] -fn a_narrow_float_attribute_fetched_in_fixed_function_answers_metals_canonical_nan() { +fn a_fixed_function_vertex_attribute_keeps_the_words_the_device_delivers() { + use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::sym::VaryingKey; use crate::spirv::interp::run_with_inputs; - const CANONICAL: u32 = 0x7FC0_0000; let bc = match llvm_assemble(&engine_dir().join("dsx_int_attributes.ll")) { Ok(b) => b, Err(AssembleError::Missing(why)) => { @@ -1284,8 +1285,8 @@ fn a_narrow_float_attribute_fetched_in_fixed_function_answers_metals_canonical_n } Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected the fixture: {why}"), }; - // The words a device's fixed-function input delivers, and Metal's answer for each: three NaN - // payloads of either sign, an infinity, a subnormal, a zero and a finite value. + // The words a device's fixed-function input delivers: three NaN payloads of either sign, an + // infinity, a subnormal, a zero and a finite value. let delivered = [ 0x7FC0_2000u32, 0xFFC0_2000, @@ -1296,13 +1297,6 @@ fn a_narrow_float_attribute_fetched_in_fixed_function_answers_metals_canonical_n 0x8000_0000, 0x3F80_0000, ]; - let canonical: Vec = delivered - .iter() - .map(|w| match w & 0x7FFF_FFFF > 0x7F80_0000 { - true => CANONICAL, - false => *w, - }) - .collect(); let mut ran: BTreeMap> = BTreeMap::new(); for stem in [ "moltenvk-m3", @@ -1340,6 +1334,12 @@ fn a_narrow_float_attribute_fetched_in_fixed_function_answers_metals_canonical_n let a = compile_inputs_of(&bc, "int_attribute_to_float4", &p, &i) .unwrap_or_else(|e| panic!("{what}: {e}")); validate(&a, &p); + assert_eq!( + a.precision.contains(&PrecisionNote::DeviceNanEncoding), + narrow, + "{what}: {:?}", + a.precision + ); let (plan, m) = typed_module_with(&bc, "int_attribute_to_float4", &p, &i) .unwrap_or_else(|e| panic!("{what}: {e}")); // One vertex per set of four words the attribute delivers. @@ -1372,11 +1372,7 @@ fn a_narrow_float_attribute_fetched_in_fixed_function_answers_metals_canonical_n .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])), ); } - let want: Vec = match narrow { - true => canonical.clone(), - false => delivered.to_vec(), - }; - assert_eq!(got, want, "{what}"); + assert_eq!(got, delivered, "{what}"); ran.entry(format).or_default().push(stem); } } diff --git a/crates/metal2vulkan/src/tests/fast_paths.rs b/crates/metal2vulkan/src/tests/fast_paths.rs index bc3e7433f..71c4d8404 100644 --- a/crates/metal2vulkan/src/tests/fast_paths.rs +++ b/crates/metal2vulkan/src/tests/fast_paths.rs @@ -8,8 +8,8 @@ use crate::device::{ BatchOrderPolicy, CompletionPolicy, DecodedTexelsPolicy, DevicePolicy, HeapCompressionPolicy, - HostPageTexturePolicy, NanMinMaxPolicy, RenderLoweringPolicy, SamplingPolicy, - TexelConversionPolicy, Unorm8LinearFilterPolicy, VertexNormalizedPolicy, YCbCrFilterPolicy, + HostPageTexturePolicy, RenderLoweringPolicy, SamplingPolicy, TexelConversionPolicy, + Unorm8LinearFilterPolicy, VertexNormalizedPolicy, YCbCrFilterPolicy, }; use crate::pipeline::PrecisionNote; use std::collections::BTreeSet; @@ -64,7 +64,6 @@ fn choices() -> Vec { ycbcr_filter: _, texel_conversion: _, vertex_normalized: _, - nan_and_min_max: _, // The runtime's: the texels of a carried texture's decoded twin, a heap's compressed // texture's image, when the host sees a command buffer complete, how a batch begins after // the earlier ones of its queue, where a render encoder's calls are lowered, and what holds @@ -82,7 +81,6 @@ fn choices() -> Vec { choice!(p.ycbcr_filter: YCbCrFilterPolicy { Device, Exact }), choice!(p.texel_conversion: TexelConversionPolicy { Device, Exact }), choice!(p.vertex_normalized: VertexNormalizedPolicy { Device, Exact }), - choice!(p.nan_and_min_max: NanMinMaxPolicy { Native, Exact }), choice!(p.decoded_texels: DecodedTexelsPolicy { Compact, Exact }), choice!(p.heap_compression: HeapCompressionPolicy { Compressed, Uncompressed }), choice!(p.completion: CompletionPolicy { Grouped, Exact }), @@ -126,8 +124,6 @@ fn notes() -> Vec<(&'static str, Ledger)> { DeviceSampling, DeviceTexelConversion, HalfTexelConversion, - NativeNanEncoding, - NativeMinMax, ], NotBuilt: [ ExtendedRangeBlendSource, @@ -203,6 +199,8 @@ fn notes() -> Vec<(&'static str, Ledger)> { UnmeasuredGroupSpeculation, NotMipmappedAnisotropicFilter, DeviceSampleLevel, + NativeNanEncoding, + NativeMinMax, ], } } diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index cdd6cc394..71612cc8a 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -151,7 +151,6 @@ mod engine_swizzled_storage; mod engine_table_copies; mod engine_tables; mod engine_tessellation; -mod engine_texel_nans; mod engine_texture; mod engine_texture_atomic_unk; mod engine_texture_interp; diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 4a0661d11..85d593029 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1463,7 +1463,6 @@ enum metal2vulkan::device::HandleDomain #[cfg_attr(feature = "serde", derive(ser enum metal2vulkan::device::HeapCompressionPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum HeapCompressionPolicy enum metal2vulkan::device::HostPageTexturePolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum HostPageTexturePolicy enum metal2vulkan::device::Independence #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Independence -enum metal2vulkan::device::NanMinMaxPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum NanMinMaxPolicy enum metal2vulkan::device::PointerDomain #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum PointerDomain enum metal2vulkan::device::RenderLoweringPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum RenderLoweringPolicy enum metal2vulkan::device::ResolveMode #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ResolveMode @@ -2747,7 +2746,6 @@ field metal2vulkan-runtime::WorkCounts.owned_kernel_spirv_bytes pub owned_kernel field metal2vulkan-runtime::WorkCounts.owned_kernels_made pub owned_kernels_made: u64 field metal2vulkan-runtime::WorkCounts.passes_not_inline_actions pub passes_not_inline_actions: u64 field metal2vulkan-runtime::WorkCounts.passes_not_inline_actions_dont_care_load pub passes_not_inline_actions_dont_care_load: u64 -field metal2vulkan-runtime::WorkCounts.passes_not_inline_actions_nan_clear pub passes_not_inline_actions_nan_clear: u64 field metal2vulkan-runtime::WorkCounts.passes_not_inline_actions_resolve pub passes_not_inline_actions_resolve: u64 field metal2vulkan-runtime::WorkCounts.passes_not_inline_actions_store pub passes_not_inline_actions_store: u64 field metal2vulkan-runtime::WorkCounts.passes_not_inline_actions_unequal_reach pub passes_not_inline_actions_unequal_reach: u64 @@ -3714,7 +3712,6 @@ field metal2vulkan::device::DevicePolicy.handle_domain pub handle_domain: Handle field metal2vulkan::device::DevicePolicy.heap_compression pub heap_compression: HeapCompressionPolicy field metal2vulkan::device::DevicePolicy.host_page_textures pub host_page_textures: HostPageTexturePolicy field metal2vulkan::device::DevicePolicy.isolation pub isolation: GuestIsolation -field metal2vulkan::device::DevicePolicy.nan_and_min_max pub nan_and_min_max: NanMinMaxPolicy field metal2vulkan::device::DevicePolicy.pointer_domain pub pointer_domain: PointerDomain field metal2vulkan::device::DevicePolicy.render_lowering pub render_lowering: RenderLoweringPolicy field metal2vulkan::device::DevicePolicy.sampling pub sampling: SamplingPolicy @@ -4404,7 +4401,6 @@ field metal2vulkan::pipeline::StageInputLayoutDescriptor.step_rate pub step_rate field metal2vulkan::pipeline::StageInputLayoutDescriptor.stride pub stride: Option field metal2vulkan::pipeline::StageModule.constant_blob pub constant_blob: Option> field metal2vulkan::pipeline::StageModule.entry_point pub entry_point: String -field metal2vulkan::pipeline::StageModule.half_bit_colors pub half_bit_colors: Vec field metal2vulkan::pipeline::StageModule.own_pixel_textures pub own_pixel_textures: Vec field metal2vulkan::pipeline::StageModule.precision_notes pub precision_notes: Vec field metal2vulkan::pipeline::StageModule.private_bytes pub private_bytes: u64 @@ -5117,7 +5113,6 @@ macro-member metal2vulkan-runtime::Degradation::SeparateDepthStencil SeparateDep macro-member metal2vulkan-runtime::Degradation::SetPastLayoutSupport SetPastLayoutSupport = "set-past-layout-support", Validity, macro-member metal2vulkan-runtime::Degradation::ShaderCacheEntryNotWritten ShaderCacheEntryNotWritten = "shader-cache-entry-not-written", Performance, macro-member metal2vulkan-runtime::Degradation::ShaderColorConversion ShaderColorConversion = "shader-color-conversion", Performance, -macro-member metal2vulkan-runtime::Degradation::ShaderHalfColorBits ShaderHalfColorBits = "shader-half-color-bits", Performance, macro-member metal2vulkan-runtime::Degradation::ShaderResolve ShaderResolve = "shader-resolve", Performance, macro-member metal2vulkan-runtime::Degradation::ShaderSideDepthTest ShaderSideDepthTest = "shader-side-depth-test", Performance, macro-member metal2vulkan-runtime::Degradation::ShaderSideStencil ShaderSideStencil = "shader-side-stencil", Performance, @@ -12499,8 +12494,6 @@ variant metal2vulkan::device::HostPageTexturePolicy::Shadow Shadow variant metal2vulkan::device::Independence::All All variant metal2vulkan::device::Independence::None None variant metal2vulkan::device::Independence::Only32Bit Only32Bit -variant metal2vulkan::device::NanMinMaxPolicy::Exact Exact -variant metal2vulkan::device::NanMinMaxPolicy::Native Native variant metal2vulkan::device::PointerDomain::ResidentTable ResidentTable variant metal2vulkan::device::RenderLoweringPolicy::AtCall AtCall variant metal2vulkan::device::RenderLoweringPolicy::Worker Worker @@ -13652,7 +13645,6 @@ variant metal2vulkan::pipeline::PushField::TessellationChunk TessellationChunk variant metal2vulkan::pipeline::PushField::TessellationFactorInstanceStride TessellationFactorInstanceStride variant metal2vulkan::pipeline::PushField::TessellationFactorOffset TessellationFactorOffset variant metal2vulkan::pipeline::PushField::TessellationFactorScale TessellationFactorScale -variant metal2vulkan::pipeline::PushField::TextureHalfChannels TextureHalfChannels(SlotRef) variant metal2vulkan::pipeline::PushField::TextureIntegerChannels TextureIntegerChannels(SlotRef) variant metal2vulkan::pipeline::PushField::TextureLevels TextureLevels(SlotRef) variant metal2vulkan::pipeline::PushField::VertexBufferStride VertexBufferStride(u32) @@ -13712,7 +13704,7 @@ variant metal2vulkan::pipeline::RuntimeFact::DeviceAddresses DeviceAddresses { s variant metal2vulkan::pipeline::RuntimeFact::DispatchGrid DispatchGrid variant metal2vulkan::pipeline::RuntimeFact::DroppedColor DroppedColor { color: u32 } variant metal2vulkan::pipeline::RuntimeFact::EmulatedSimdgroups EmulatedSimdgroups -variant metal2vulkan::pipeline::RuntimeFact::ExactFormsOverCompilerLimit ExactFormsOverCompilerLimit { sampling: bool, texel_conversion: bool, nan_and_min_max: bool } +variant metal2vulkan::pipeline::RuntimeFact::ExactFormsOverCompilerLimit ExactFormsOverCompilerLimit { sampling: bool, texel_conversion: bool } variant metal2vulkan::pipeline::RuntimeFact::ExecutionStatus ExecutionStatus variant metal2vulkan::pipeline::RuntimeFact::ExtendedRangeInputBlend ExtendedRangeInputBlend { color: u32, blend: crate::pipeline::lower_inputs::BlendEquation, kept: crate::vk::ColorComponentFlags } variant metal2vulkan::pipeline::RuntimeFact::FlatGrid FlatGrid @@ -13757,7 +13749,6 @@ variant metal2vulkan::pipeline::RuntimeFact::SrgbTexture SrgbTexture { slot: Slo variant metal2vulkan::pipeline::RuntimeFact::StageInRegion StageInRegion variant metal2vulkan::pipeline::RuntimeFact::StageInStride StageInStride { layout: u32 } variant metal2vulkan::pipeline::RuntimeFact::StorageTextureFormat StorageTextureFormat { slot: SlotRef } -variant metal2vulkan::pipeline::RuntimeFact::StorageTextureHalfChannels StorageTextureHalfChannels { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::StorageTextureIntegerChannels StorageTextureIntegerChannels { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::StorageTextureLevelViews StorageTextureLevelViews { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::StorageTextureLevels StorageTextureLevels { slot: SlotRef } @@ -13857,11 +13848,9 @@ variant metal2vulkan::pipeline::StorageFormatClass::NotStorage NotStorage variant metal2vulkan::pipeline::StorageFormatClass::Unknown Unknown variant metal2vulkan::pipeline::StorageImageClass::AlphaInRed AlphaInRed variant metal2vulkan::pipeline::StorageImageClass::HalfBits HalfBits -variant metal2vulkan::pipeline::StorageImageClass::HalfQuietNan HalfQuietNan variant metal2vulkan::pipeline::StorageImageClass::Identity Identity variant metal2vulkan::pipeline::StorageImageClass::RotateArgb RotateArgb variant metal2vulkan::pipeline::StorageImageClass::SharedExponentBits SharedExponentBits -variant metal2vulkan::pipeline::StorageImageClass::SmallFloatQuietNan SmallFloatQuietNan variant metal2vulkan::pipeline::StorageImageClass::SrgbEncode SrgbEncode variant metal2vulkan::pipeline::StorageImageClass::SrgbEncodeBgra SrgbEncodeBgra variant metal2vulkan::pipeline::StorageImageClass::SwizzleBgra SwizzleBgra diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 9df7cb625..79d0467dd 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -229,7 +229,6 @@ surface! { enum YCbCrFilterPolicy N; enum TexelConversionPolicy N; enum VertexNormalizedPolicy N; - enum NanMinMaxPolicy N; enum DecodedTexelsPolicy N; enum HeapCompressionPolicy N; enum CompletionPolicy N; @@ -1046,7 +1045,7 @@ surface! { use metal2vulkan::bind::{BindState, BoundBuffer, Dispatch, DrawCall, StageTable}; use metal2vulkan::cache::{Hash256, PipelineArtifact, PipelineKey}; -use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy, FloatWidth, NanMinMaxPolicy}; +use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy, FloatWidth}; use metal2vulkan::library::{CompiledFunction, Library}; use metal2vulkan::metal::{PixelFormat, VertexFormat}; use metal2vulkan::pipeline::{ @@ -1334,9 +1333,8 @@ fn content_digests_name_what_a_pipeline_says_not_its_build() { } /// The precision contract is public: a fast `float` division records the device's arithmetic, -/// Metal's precise division records the device's division, its denormals and its NaN where the -/// policy takes the device's NaN (`NativeDivision`, `DeviceDenormals`, `NativeNanEncoding`), the -/// division and its denormals under `NanMinMaxPolicy::Exact`, an integer operator has no notes, and +/// Metal's precise division records the device's division, its denormals and its NaN +/// (`NativeDivision`, `DeviceDenormals`, `NativeNanEncoding`), an integer operator has no notes, and /// a fast `float` `tanh`, which the crate computes with a division of its own, records the device's /// arithmetic, on a profile whose `float` functions are the device's (lavapipe's); on one whose /// functions are Metal's own (MoltenVK's), both are Metal's own in a fast-math entry and record @@ -1361,39 +1359,21 @@ fn the_precision_contract_names_each_float_operations_notes() { assert!(fdiv(moltenvk, EntryMath::Precise) .expect("a float operator") .contains(&PrecisionNote::DeviceArithmetic)); - let mut policy = DevicePolicy::default(); - policy.nan_and_min_max = NanMinMaxPolicy::Native; - let native = device_under("lavapipe", policy); - policy.nan_and_min_max = NanMinMaxPolicy::Exact; - let metal_nans = device_under("lavapipe", policy); - for (p, notes) in [ - ( + let native = device_under("lavapipe", DevicePolicy::default()); + assert_eq!( + PrecisionNote::of_float_operator( + BinOp::FDiv, + FloatWidth::F32, + FastMath::NONE, native.profile(), - BTreeSet::from([ - PrecisionNote::DeviceDenormals, - PrecisionNote::NativeDivision, - PrecisionNote::NativeNanEncoding, - ]), + EntryMath::Precise ), - ( - metal_nans.profile(), - BTreeSet::from([ - PrecisionNote::DeviceDenormals, - PrecisionNote::NativeDivision, - ]), - ), - ] { - assert_eq!( - PrecisionNote::of_float_operator( - BinOp::FDiv, - FloatWidth::F32, - FastMath::NONE, - p, - EntryMath::Precise - ), - Some(notes) - ); - } + Some(BTreeSet::from([ + PrecisionNote::DeviceDenormals, + PrecisionNote::NativeDivision, + PrecisionNote::NativeNanEncoding, + ])) + ); assert_eq!( PrecisionNote::of_float_operator( BinOp::Add, diff --git a/docs/API.md b/docs/API.md index fc8c94cad..bbb2e5af1 100644 --- a/docs/API.md +++ b/docs/API.md @@ -85,13 +85,15 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: `robustBufferAccess`, buffer accesses and vertex input are left to it. (MoltenVK advertises the feature without implementing it; there such accesses are not contained, as on native Metal.) - **The device's arithmetic.** The device's own maths library, divisions, fused multiply-adds, - `float` denormals, and rounding order of `dot`/`mix`/`fast::sqrt`, on every device and with no - exact form. Each records a precision note with its bound; on MoltenVK on an Apple GPU, whose - `float` functions are Metal's own, they are Metal's answers. + `float` denormals, rounding order of `dot`/`mix`/`fast::sqrt`, NaN bits, and the operand of + `fmin`, `fmax`, `min3`, `max3`, `clamp` and `saturate`, on every device and with no exact form. + Each records a precision note with its bound; on MoltenVK on an Apple GPU, whose `float` + functions are Metal's own, they are Metal's answers, but for a NaN's bits where the device is + not measured to answer Metal's. - **Fast native forms off Apple's GPUs.** The device's own sampler (its filter of a two-plane - YCbCr texture among them), texel conversions, NaN bits and min/max. Each records a precision - note with its bound, and each has an exact switch. The device's own `half` rounding and its - blend of a `half` color have none: each records its note. + YCbCr texture among them) and texel conversions. Each records a precision note with its bound, + and each has an exact switch. The device's own `half` rounding and its blend of a `half` color + have none: each records its note. `DevicePolicy::exact_answers()` turns on every exact form but sampling's, Metal's filter of a two-plane YCbCr texture (`YCbCrFilterPolicy::Exact`) included; `sampling = SamplingPolicy::Exact` emulates Metal's sampler too. @@ -202,9 +204,9 @@ measured takes the conservative route. Metal semantics the translation keeps on every device, beyond Vulkan's: Metal's 32-lane simdgroups (including lockstep races on threadgroup memory within a barrier interval), and the -bit-exact `fneg`, `fabs` and `half`-to-`float` widening of NaNs and denormals. Under the exact -switches it also keeps Metal's canonical NaNs and Metal's operand choice in `fmin`, `fmax`, -`min3`, `max3` and `clamp`. +bit-exact `fneg`, `fabs` and `half`-to-`float` widening of NaNs and denormals. A NaN's bits and +the operand `fmin`, `fmax`, `min3`, `max3`, `clamp` and `saturate` pick beside a NaN or between +two zeros are the device's. What the runtime enables for itself outside the vocabulary enters no enable set, compile profile or fingerprint: among it the extensions of its dma-buf fallback for no-copy memory whose pointer @@ -1477,12 +1479,6 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. `TextureWriteRoundingMode::NearestEven`, whose rounding no device's conversion gives (`StageModule::rounded_colors`). Cost: the fragment function rounds each such channel to nearest even before it writes it: about 35 more instructions per channel. -- `metal2vulkan-degrade-shader-half-color-bits` (performance). `ShaderHalfColorBits`: A fragment - function writes a `half` to a half-float color attachment as the bits of the half Metal stores, - through a 16-bit output, on a device that does not store a 32-bit output's NaN as Metal does - (`StageModule::half_bit_colors`). Cost: the fragment function writes each such output as its - half's bits through a 16-bit output: about 20 more instructions per output, and the attachment - takes no Vulkan blend of one and zero. - `metal2vulkan-degrade-render-pass-split` (performance). `RenderPassSplit`: A Metal render pass runs as several Vulkan render pass instances: a framebuffer fetch through the pixel interlock keeps its attachment out of its draws' subpass, and the pass's draws leave different attachments @@ -3018,15 +3014,14 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. round as Metal's conversion does. - `metal2vulkan-degrade-native-nan-encoding` (precision). `PrecisionNote::NativeNanEncoding`: Native device maths: a `float` or `half` operation's NaN result is the device's, its sign and payload - unselected, on a device whose arithmetic is not measured to answer Metal's canonical NaN, under - `NanMinMaxPolicy::Native`. Also recorded where a `half` read from its bits is the device's - widening under the float controls (ANV, RADV): a NaN's bits the device's, where Metal widens - every `half` NaN to `0x7fc00000`. + unselected, where Metal answers a NaN the device is not measured to answer (every NaN but + Metal's canonical one on a device measured to answer that, MoltenVK on an Apple GPU). Also + recorded where a `half` read from its bits is the device's widening under the float controls + (ANV, RADV): a NaN's bits the device's, where Metal widens every `half` NaN to `0x7fc00000`. - `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`, not the translation's - selects of Metal's operand, on a device not measured to answer Metal's, under - `NanMinMaxPolicy::Native`. + `float` or `half` is the device's `GLSL.std.450` `NMin`, `NMax` or `NClamp`, on a device not + measured to answer Metal's operand. - `metal2vulkan-degrade-native-dot` (precision). `PrecisionNote::NativeDot`: Native device maths: Metal's `dot` on `float`, or on `half` where its fused multiply-add is not the measured 16-bit one, is the device's `OpDot` (a `half` one summed in `float` and rounded once to `half`), not diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 323e8810e..318e9e45c 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -31,9 +31,6 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X | A two-plane YCbCr texture's linear sample (`YCBCR8_420_2P` and its kin, over a surface's planes) is the device's filter of its texels, which hold Metal's reads exactly, as any other texture's is under native sampling: a draw binding one takes the pipeline a draw binding any other texture takes. Metal sums the texels' steps on the format's grid (`1/2048`, `1/8192`), each term truncated. Under native sampling, MoltenVK's included (Metal's own sampler filters the texels as an `RGBA16Float` or `RGBA32Float` texture's); with `sampling = SamplingPolicy::Exact` every module answers Metal's filter, MoltenVK's through the slot's variant. On a device whose memory is the host's, a sample that reads the planes in place is Metal's filter exactly under either value (the two-plane YCbCr bullet under **Costs of matching Metal**), so the row applies there only to the samples that form does not read. | `ycbcr_filter = YCbCrFilterPolicy::Device` | `ycbcr_filter = YCbCrFilterPolicy::Exact`: Metal's filter emulated in the slot's YCbCr variant, a pipeline the first draw binding such a texture makes | Linear filter within 1.183 codes (1/255) of Metal's filter of the format on NVIDIA (RTX 3090), 0.877 on RADV, 1.058 on ANV, 0.872 on lavapipe; within 0.498 at coordinates on the 1/256 grid. `DeviceSampling` (`device-sampling`). On MoltenVK within one step of the grid (0.125 codes on `1/2048`, 0.016 on `1/8192`), a `half` result within one `half` ulp; a `half` sample of one texel on the grid `8192` through a runtime sampler rounds to nearest even where Metal rounds ties away. `ycbcr-filter-not-exact`, `HalfTexelConversion` (`half-texel-conversion`), announced where a draw binds such a texture | One pipeline more, made at the first draw binding such a texture. A2X (`a2x-s96` with a `YCBCR8_420_2P` texture at fragment slot 3, on ANV, Iris Xe): 2 pipelines, 13.9 s at the state's creation and 37.8 s at the draw (52.3 s wall), against the creation's one drawn as made (14.3 s) | | A texel's `float` value is the device's conversion of its codes; a `half` result is the device's `float` texel rounded to nearest even. | `texel_conversion = TexelConversionPolicy::Device` | `texel_conversion = TexelConversionPolicy::Exact`: Metal's conversion by the bound format's class of every read; a sample's or gather's also with `sampling = SamplingPolicy::Exact` (under native sampling the device's sampler decodes it) | One `f32` ulp for 8- and 16-bit codes, 0.18 of a code for 5- and 6-bit packed channels; `half` within one ulp; NaN bits the device's. `DeviceTexelConversion` (`device-texel-conversion`), `HalfTexelConversion` (`half-texel-conversion`, also recorded for heap textures and unmeasured formats) | Exact reads (the same reads): Xgc14 0.88-0.89 → 0.90-0.93 s, GPU 0.039 → 0.046 ms; Xgc15 0.65-0.66 → 0.68 s, 0.090 → 0.094 ms; A2X unchanged (no affected read). Samples: with the sampling row | | A normalized vertex attribute (`UCharNormalized` through `Short4Normalized` of either sign, `UChar4Normalized_BGRA`, `Int1010102Normalized`, `UInt1010102Normalized`) is converted by fixed-function vertex input, through the attribute's own Vulkan `UNORM` or `SNORM` format, not pulled from its vertex buffer and divided in the shader. Vulkan states that conversion as Metal states it (`c / (2^b - 1)` unsigned, `max(c / (2^(b-1) - 1), -1)` signed, correctly rounded), so it is the driver's implementation of it that can differ, and nothing in the attribute's Vulkan format asks for a correction after the load. The whole format is then `VertexAttribute` state that no instruction of the module names, so every format the device fetches shares one module (`pipeline::link::vertex`, item 9). | `vertex_normalized = VertexNormalizedPolicy::Device` | `vertex_normalized = VertexNormalizedPolicy::Exact`: every such attribute is pulled and its codes divided by `lower::stage_io::fetch`'s integer sequence, one module per format | One `f32` ulp at some codes on a driver that multiplies by the reciprocal: measured on llvmpipe (Mesa 26.2.4), which reads 127/255 as `0x3EFEFF00` where Metal reads `0x3EFEFEFF`, over the five 8-bit unsigned sites of `vertex-format-float4` and four of `-instance-step` (`known-gaps.tsv`); the 16-bit and packed normalized formats are exact there, and the unsigned ones are exact on RADV. Every normalized format of `vertex-format-float4`, `-half4` and `-instance-step` is Metal's on MoltenVK (Apple M3 Max, macOS 27.0.1) under both values of this switch, each case `exact` at every site. The signed formats are **unaudited** off MoltenVK under the default: they were pulled on every device until this row existed, so llvmpipe's 8-bit sites are expected to read one ulp as their unsigned twins do, and no run has taken them. Not announced: no note names the device's normalized vertex conversion. `tests::engine_vertex_variants` tests both values | Not timed. The variant count is the cost, measured on an Apple M3 Max over `cases::vertex_formats`' 45-format sweep (`tests::engine_vertex_variants`): the `float4` entry compiles 2 modules under the default and 21 under the switch, the `half4` entry 1 against 20. Each extra module is a translation of ours and a shader the driver converts once more | -| A NaN result's bits are the device's (no select of Metal's NaN), and `fmin`, `fmax`, `min3`, `max3`, `clamp` and `saturate` are the device's `NMin`, `NMax` and `NClamp`. | `nan_and_min_max = NanMinMaxPolicy::Native` | `nan_and_min_max = NanMinMaxPolicy::Exact` | A NaN where Metal answers one, its bits the device's; the operand Metal picks but at two NaNs, `+0` against `-0`, and `f32` denormals. `NativeNanEncoding` (`native-nan-encoding`), `NativeMinMax` (`native-min-max`) | A2X 1.00-1.02 → 1.85-1.88 s, GPU 0.098 → 0.116 ms; Xgc14 0.88-0.89 → 1.59-1.63 s, 0.039 → 0.048 ms; Xgc15 0.65-0.66 → 1.25-1.28 s, 0.090 → 0.102 ms | -| A `half` texel's NaN is the rounding's own NaN, not the texel's bits (the keep's four instructions a texel are left out). | `nan_and_min_max = NanMinMaxPolicy::Native` | `nan_and_min_max = NanMinMaxPolicy::Exact` (the keep under native half rounding). The same switch also gives Metal's full rule: `0x7e00` for every NaN but a one-texel read, nearest sample or gather of a 16-bit float texture, by the slot's format class read as data, a heap handle's class index and a runtime sampler's filter. A gather with a `half` result fetches its four texels where the class is a half-float one, since NVIDIA's gather hands back every NaN as `0x7fffffff`. **Not yet exact:** a cube gather, bicubic and emulated linear, fetched or compared samples; and on ANV (Iris Xe, Mesa 26.2.4) every 16-bit float texel's NaN, which its image decode answers as `0xFFC00000` (`0xFE00` as a `half`) before any keep, and on RADV (the Radeon 780M and the RX 7900 XTX, Mesa 26.2.4) a 16-bit float texel's NaN through a **sampler**, which answers `0xFFC00000` the same way where its image loads keep the texel's bits (`half-texel-nans-r16f`'s `nearest-sample` site differs, its `read` sites are exact): reading the texel's bits through an unsigned integer view would answer Metal's. Possible, not built: the runtime sampler's filter read as push data rather than specialized, which would spare the remake below. Measured on the RTX 5080: under the switch no `half` lane of the runtime lane's texel reads, samples and gathers differs from Metal's (1,469 differ by default). Under the switch `DeviceNanEncoding` is still announced; the consumer logs notes, so no device fact is built to drop it | NaN bits the device's (`0x7FFF` on the RTX 5080), where Metal hands back a 16-bit float texel's own bits on a read, nearest sample or gather, and `0x7e00` for a 32-bit or small float texel's NaN and a linear sample's. `NativeHalfConversion` (`native-half-conversion`); the read also records `DeviceNanEncoding` (`device-nan-encoding`) | Measured on top of the NaN switch's own row (a probe with the keep against one without): A2X 341,299 → 347,519 words, 1.82-1.86 → 1.81-1.87 s, GPU 0.115-0.117 → 0.115-0.116 ms, within noise; Xgc14 and Xgc15 read no `half` texel (words unchanged). The full rule (a probe with it against the same tree without it): A2X 347,519 → 372,429 words (+7.2%), creation 1.85-1.88 → 1.99-2.04 s; where a linear runtime sampler is bound at the draw the sampler word's filter is now specialized, so the first draw remakes (1.94-1.96 s) and its GPU time rises 0.115-0.117 → 0.124-0.125 ms; with a nearest sampler GPU 0.115-0.116 → 0.115-0.117 ms; Xgc14 and Xgc15 words unchanged. On the RTX 3090 the same pair: A2X creation 2.91-3.06 → 3.17-3.23 s, the first draw's remake 3.0 s and its GPU time 0.17-0.18 → 0.79-1.15 ms, with a nearest sampler 0.17-0.18 ms both | -| On ANV and RADV, which round a `half` through the device's conversion under the float controls, a `half` read from its bits (a load, a reinterpretation, a texel's bits) is the device's widening of them as a 16-bit float, loops included, and a `half` texel takes that conversion's NaN (no keep): every value but a NaN is exact by the Vulkan spec. | `nan_and_min_max = NanMinMaxPolicy::Native` | `nan_and_min_max = NanMinMaxPolicy::Exact`: the integer decode and the texel's keep; a `half` widened to `float` then answers Metal's `0x7fc00000` for every NaN, read from memory, a texel or a select alike | A `half` NaN widened to `float` has the device's bits (ANV quiets a signalling NaN, RADV keeps it), where Metal answers `0x7fc00000`; a `half` stored back unchanged keeps its bits. `NativeNanEncoding` (`native-nan-encoding`); a texel's, `DeviceNanEncoding` (`device-nan-encoding`) | ANV (Iris Xe, Mesa 26.2.4), A2X: making 4.06-4.36 → 5.76-5.87 s, 269,828 → 280,070 words, peak RSS 0.35 → 0.51 GB, GPU 4.48 → 4.62 ms (warm); RADV (Radeon 780M, Mesa 26.2.4): 379-467 → 535-665 ms, GPU within its clock states' spread | | A computed `half` or `float` color blended into an extended-range attachment (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`) rounds the blend's source as a loaded one; Metal's compiler rounds it by how it computed it. Every device. | The in-shader blend's loaded rounding (no switch) | **Not built yet:** Metal's rounding per shape is probed, not modelled | One code. `ExtendedRangeBlendSource` (`extended-range-blend-source`), `ExtendedRangeFloatBlendSource` (`extended-range-float-blend-source`) | Not measured | | A blend into a packed 16-bit attachment the device renders through its word view (`A1BGR5Unorm`, `ABGR4Unorm` on the RTX 5080; `WordAttachment`), which the function computes in the interlocked storage form, reads the attachment's codes, where Metal's tile holds the pass's clear and each earlier blend's result as a `half`, finer; under fast math it also sums a few states otherwise than Metal. Every device rendering such an attachment. | The in-shader blend over the codes (no switch) | **Not built yet:** the extended-range attachments' `half` shadow (`render/extended_shadow.rs`, `VariantKey::extended_shadows`) taken by word attachments: the runtime's shadow start and end, its load of the codes and the clear's halves, and the word's shadowed variant in `lower::fragment::fetch`, for a single-sampled pass (a multisampled one keeps the codes, as an extended-range one does). Fast math's regrouped sums have no model | One code: without fast math exact over a loaded attachment (the 2,891 states of the M3 sweep, every channel), under fast math 3,527 of 94,732,288 channels a code apart; after a clear or an earlier blend in the pass, a code apart where the two readings store different codes. `DeviceColorConversion` (`device-color-conversion`) | Not measured. Expected from the shadow's form: an `R16G16B16A16_SFLOAT` image of the pass's extent per such color (8 bytes a pixel, 16.6 MB at 1920x1080), set at the draw it starts by a fill or a load dispatch, and an 8-byte storage read and write per blended fragment inside the interlock beside the word's | | A bicubic sample of an 8- or 16-bit normalized texture sums its taps exactly and rounds half up; Metal truncates its row terms, row sums and column terms first. Every device. | The exact sum (no switch) | **Not built yet:** Metal's datapath is pinned (17.75M lanes measured, no miss); its emitter is not written | One grid step (1/4080 at 8 bits) within about 2^-21 of a tie. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | Not measured (Metal's form is expected no larger) | @@ -852,15 +849,6 @@ driver's. Each is open work. Max, macOS 27.0.1. A plain-Metal answer that looks undefined is not one to pin as a conformance expectation, and a case of it would end a recording run. -- **A 16-bit float texel's NaN through RADV's sampler**: Metal answers the texel's own bits, - `0x7e00`, where a nearest sample answers `0xfe00` here (`half-texel-nans-r16f`, `-rg16f`, - `-rgba16f`, 515, 1025 and 2045 elements; the `read` and `read-through-sample` sites of the same - cases are **exact** on both RADV chips, where all three differ on MoltenVK). RADV's sampler hands - back its own negative quiet NaN, `0xFFC00000`, where Apple's hands back `0x7FC00000`, so the - device's decode destroys the bits before any keep of ours. Announced (`device-nan-encoding`); the - exact form, not built, is the read side of the `StorageImageClass::HalfBits` write path — read the - image through an unsigned-integer alias so no device decode sees the texel. The fetch half of this - difference is the first gap above, which is a different cause and needs its own fix. - **A blend's result on RADV, by 1 to 64 codes** (`half-output-blends-*`, `blend-sweep-operations`, `blend-interaction-format-unorm8` and `-srgb8`, `argb8-targets-*`, `a2c-on-*`; 24 cases). The diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index cf1b16750..0773b9199 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -202,7 +202,7 @@ Columns: | `AccelerationStructures` | Acceleration structures | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/binding.rs (unexpected)` | `rare`: ray tracing (out of scope by ruling) | | `FeatureEnable` | A feature a created device would enable that the runtime's feature chain has no member for, or whose structure no enabled extension exposes | devices without the feature or extension it names | `ours` | 1: `crates/metal2vulkan-runtime/src/enables.rs (of)` | `none`: device creation with a feature the runtime's chain lacks | | `ExtensionEnable` | An extension a created device would enable that the device lists under none of the names the runtime knows for it | devices without the feature or extension it names | `ours` | 1: `crates/metal2vulkan-runtime/src/enables.rs (of)` | `none`: device creation with an extension under an unknown name | -| `Render` | Render pipelines, passes and draws | every device (runtime piece not built) | `ours` | 27: `crates/metal2vulkan-runtime/src/attachment_stand_in.rs (check_copies)`, `crates/metal2vulkan-runtime/src/attachment_stand_in.rs (stand_in_as, 2 sites)` (+20) | `system`: render pass, resolve and attachment forms not built (20 sites: see the appendix) | +| `Render` | Render pipelines, passes and draws | every device (runtime piece not built) | `ours` | 26: `crates/metal2vulkan-runtime/src/attachment_stand_in.rs (check_copies)`, `crates/metal2vulkan-runtime/src/attachment_stand_in.rs (stand_in_as, 2 sites)` (+19) | `system`: render pass, resolve and attachment forms not built (20 sites: see the appendix) | | `TexelsPastBufferLength` | A texture over a buffer whose texels run past the buffer's length, which Metal makes over bytes its buffer's allocation has past the length (a 2D... | every device (runtime piece not built) | `ours` | 2: `crates/metal2vulkan-runtime/src/buffer_texture.rs (refusal_error)`, `crates/metal2vulkan-runtime/src/texture/surface_depth.rs (surface_depth_twin)` | `rare`: a texture over a buffer past its length | | `OverlappingSurfaceRows` | A texture of an IOSurface plane (`Buffer::new_texture_with_iosurface_plane`, the stand-in for `newTextureWithDescriptor:iosurface:plane:`) whose... | every device (runtime piece not built) | `ours` | 4: `crates/metal2vulkan-runtime/src/blit_plan.rs (plan_texels_rows_copy)`, `crates/metal2vulkan-runtime/src/blit_texture.rs (copy_from_buffer_to_texture)` (+2) | `rare`: an IOSurface plane whose rows overlap | | `MemorylessSurfacePlane` | A texture of an IOSurface plane (`Buffer::new_texture_with_iosurface_plane`, the stand-in for `newTextureWithDescriptor:iosurface:plane:`) whose... | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/buffer_texture.rs (refusal_error)` | `rare`: a memoryless texture over an IOSurface plane | @@ -699,7 +699,7 @@ Each refusal's sites, with the function that builds it. - `gap::AccelerationStructures`: `crates/metal2vulkan-runtime/src/binding.rs (unexpected)` - `gap::FeatureEnable`: `crates/metal2vulkan-runtime/src/enables.rs (of)` - `gap::ExtensionEnable`: `crates/metal2vulkan-runtime/src/enables.rs (of)` -- `gap::Render`: `crates/metal2vulkan-runtime/src/attachment_stand_in.rs (check_copies)`; `crates/metal2vulkan-runtime/src/attachment_stand_in.rs (stand_in_as, 2 sites)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (attachment_twin)`; `crates/metal2vulkan-runtime/src/color_resolve.rs (of_resolve)`; `crates/metal2vulkan-runtime/src/color_resolve.rs (plan, 2 sites)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs (check_sizes)`; `crates/metal2vulkan-runtime/src/kept_bytes.rs (settle)`; `crates/metal2vulkan-runtime/src/linear_attachment.rs (settle)`; `crates/metal2vulkan-runtime/src/nan_clear.rs (plan)`; `crates/metal2vulkan-runtime/src/pipeline/render.rs (imageblock_sample_length)`; `crates/metal2vulkan-runtime/src/render.rs (check_pipeline)`; `crates/metal2vulkan-runtime/src/render.rs (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs (next_instance)`; `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs (scratch)`; `crates/metal2vulkan-runtime/src/render_pass.rs (attachment_format)`; `crates/metal2vulkan-runtime/src/render_pass.rs (depth_stencil)`; `crates/metal2vulkan-runtime/src/render_pass.rs (layout)`; `crates/metal2vulkan-runtime/src/render_pass.rs (target, 2 sites)`; `crates/metal2vulkan-runtime/src/resolve.rs (attach)`; `crates/metal2vulkan-runtime/src/resolve.rs (color_copy)`; `crates/metal2vulkan-runtime/src/resolve.rs (destination, 3 sites)`; `crates/metal2vulkan-runtime/src/resolve.rs (keep_samples)` +- `gap::Render`: `crates/metal2vulkan-runtime/src/attachment_stand_in.rs (check_copies)`; `crates/metal2vulkan-runtime/src/attachment_stand_in.rs (stand_in_as, 2 sites)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (attachment_twin)`; `crates/metal2vulkan-runtime/src/color_resolve.rs (of_resolve)`; `crates/metal2vulkan-runtime/src/color_resolve.rs (plan, 2 sites)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs (check_sizes)`; `crates/metal2vulkan-runtime/src/kept_bytes.rs (settle)`; `crates/metal2vulkan-runtime/src/linear_attachment.rs (settle)`; `crates/metal2vulkan-runtime/src/pipeline/render.rs (imageblock_sample_length)`; `crates/metal2vulkan-runtime/src/render.rs (check_pipeline)`; `crates/metal2vulkan-runtime/src/render.rs (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs (next_instance)`; `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs (scratch)`; `crates/metal2vulkan-runtime/src/render_pass.rs (attachment_format)`; `crates/metal2vulkan-runtime/src/render_pass.rs (depth_stencil)`; `crates/metal2vulkan-runtime/src/render_pass.rs (layout)`; `crates/metal2vulkan-runtime/src/render_pass.rs (target, 2 sites)`; `crates/metal2vulkan-runtime/src/resolve.rs (attach)`; `crates/metal2vulkan-runtime/src/resolve.rs (color_copy)`; `crates/metal2vulkan-runtime/src/resolve.rs (destination, 3 sites)`; `crates/metal2vulkan-runtime/src/resolve.rs (keep_samples)` - `gap::TexelsPastBufferLength`: `crates/metal2vulkan-runtime/src/buffer_texture.rs (refusal_error)`; `crates/metal2vulkan-runtime/src/texture/surface_depth.rs (surface_depth_twin)` - `gap::OverlappingSurfaceRows`: `crates/metal2vulkan-runtime/src/blit_plan.rs (plan_texels_rows_copy)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (copy_from_buffer_to_texture)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (texel_copies)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (refusal_error)` - `gap::MemorylessSurfacePlane`: `crates/metal2vulkan-runtime/src/buffer_texture.rs (refusal_error)`