From 9afdb1e150f6280ee90c93044bbe9946fb18b85a Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 28 Oct 2026 07:23:19 +0200 Subject: [PATCH] Take the device's instruction for pack, dot, mix, sqrt, exp, log, sign, fract, median3, fneg and fabs One work packet, landed as 6 commits (3d6b2488ea..f1693ce8c4 on archive/development-linear-2026-10-28), in order: * Take the device's instruction for pack, dot, mix, sqrt, exp, log, sign, fract, median3, fneg and fabs Rule 1: where the device has a native form it is the only form. The translator still computed Metal's own bits for several functions the device has an instruction for. Each now takes the instruction, its difference from Metal recorded as a note: - air.pack/air.unpack: GLSL.std.450 Pack/Unpack Unorm4x8, Snorm4x8, Unorm2x16 and Snorm2x16; rgb10a2 and rgb565 by the device's NClamp, multiply, RoundEven, and multiply by the reciprocal; unorm4x8_srgb by the MSL transfer functions with the device's Pow around the 8-bit instruction (no table read, no NaN select). New note DevicePackConversion (device-pack-conversion), not recorded for a float conversion of the four named formats on MoltenVK. - dot, mix, fast::sqrt: OpDot, FMix and Sqrt on every device, MoltenVK included (the Mix/Dot/ChunkedChain strategies, Metal's fma chains and x * rsqrt(x) are deleted). NativeDot/NativeMix everywhere but a float one on MoltenVK; a chunked dot sums each chunk's OpDot. - precise exp/log and half exp/log/pow/powr/sinh/cosh/tanh: GLSL Exp, Log, Pow, Sinh, Cosh, Tanh (Metal's compositions, half_tanh and the half remaps deleted); half Fun kinds keep the notes honest on MoltenVK. - fract, sign, median3: Fract (bounded below one, the definition), FSign, NMin/NMax; their special-value fixes are deleted. median3 is NativeMinMax on every device (two NaNs, f32 denormals). - round keeps half-away-from-zero from Trunc without the +0 fix: C99's -0, NativeTranscendentals on every device. - float fneg/fabs: OpFNegate and FAbs, the NaN payload NativeNanEncoding and fneg's denormal DeviceDenormals. Kept: exp10/log10 compositions, fmod's routine, ldexp on bits, sinpi/cospi/tanpi, the fast_ formulas, pow/atan2 C99 specials, the saturating convert, round_integer. math::pack/unpack stay for the tile, attachment, fetch and texture callers. The interpreter models the normalized packs. SEMANTICS_VERSION 1920, ARTIFACT_FORMAT_VERSION 469 (a PrecisionNote variant). Verified so far: clippy -p metal2vulkan --all-targets --all-features -D warnings; rustdoc; nextest lower::arith (244 tests) and the engine_arith, engine_float_call_notes, engine_native_maths, engine_spirv_cross_forms, engine_native_half modules. * Delete the measured half quantize deviation; hold dot and median3 lanes to the device After the half follow-ups, no module requires VkProperty::MetalHalfQuantize: a module that rounds to half through OpQuantizeToF16 records NativeHalfQuantize on every profile, and nothing decides on DriverDeviation::MetalHalfQuantize. Delete it with its property, its derive and profile arms, its codec entry, its four measured rows (MoltenVK on Apple9, RADV on the 780M, ANV on the UHD 770 and the Iris Xe), the driver-facts test rows, and the lane assertions that it required nothing (engine_native_half, engine_arith, driver_deviations' half quantize and owned half edge lanes, native_maths' half rounding lane). Docs that named it (NativeHalfQuantize, narrow::quantizes, driver_facts) now say Vulkan leaves the quantize's rounding to the device. The lanes follow the previous commit's native forms: - driver_deviations' dot lane: dot is the device's OpDot on every device, so the half words (a dot of half lanes held as float) are no longer checked against Metal's fused 16-bit chain; the float words stay checked where the profile takes MetalFloatFunctions (MoltenVK, whose OpDot is MSL's own dot), and every kernel must record NativeDot. - driver_deviations' min/max lane: median3 is NMin/NMax on every device and records NativeMinMax, so its word (the seventh of each lane) is printed, not checked; every kernel must record NativeMinMax. - the denormal probe and native_maths docs name the device's OpDot and FMix. api_signatures re-blessed (DevicePackConversion added on both crates; the two MetalHalfQuantize variants removed). REFUSALS.md regenerated, unchanged. Verified: see the branch report. * Hold the sRGB pack bound and round's zero to what the devices answer The conformance replay on lavapipe and the MoltenVK lanes read the previous two commits' native forms against Metal: - sRGB unpack and pack: Metal decodes through its twelve-bit table (the step k / 4095 nearest the transfer) and encodes by that table's byte, where the module takes the MSL transfer by the device's Pow. DevicePackConversion's bound (artifact, runtime, API.md, FAST-PATHS.md) now says so: a decoded colour within half a twelve-bit step (1/8190) of Metal's step, beyond Pow's bound. Measured on the authored cases (lavapipe and MoltenVK): every float decode within 1.2205e-4 of Metal's, every half within that and one half ulp, every encoded channel within one code, no alpha differing; normalized packs a code apart at ties, a NaN channel the device's. - known-gaps.tsv: pass-bytes-srgb-decode-all-bytes's row takes the new answer (1153 elements, largest 0x00F90000) and names device-pack-conversion; a new row for pass-bytes-srgb-encode-sweep (772 elements, largest 0x00010101); pass-bytes-half-tanh-regimes's answer moves to 1257 elements (half tanh is the device's Tanh). CONFORMANCE-COVERAGE.md regenerated. - driver_deviations' denormal probe: round is C99's on every device (NativeTranscendentals), whose zero below zero is -0 where Metal answers +0, so its word (15) is printed, not checked. On MoltenVK it was the lane's only failing word (48 of 4096). Verified: conformance replay on lavapipe (arm64 gate container) exit 0, nothing unlisted or stale; driver_deviations' float_denormals, owned_dot and minimums lanes pass on lavapipe and on MoltenVK (M3 Max); conformance and degradation tests pass. * Hold the engine maths tests to the device's instructions engine_metal_math and engine_native_maths still asserted Metal's forms that the native change replaced; they skip without llvm-as, so the earlier focused runs missed them. - engine_metal_math: a half fast_tanh is Metal's half tanh (Metal's half functions are the same in both math modes, and MSL's fast-math formulas are its float ones), so it is the device's Tanh, no Exp2 and no division, as the code already lowers it; the float fast_tanh keeps the MSL formula and its assertions. sign is the device's FSign with and without fast math. Both record NativeTranscendentals wherever the device's functions are not Metal's own; on MoltenVK sign is MSL's own (no note) and a half tanh is MSL's float tanh rounded to half (DeviceTranscendentals). The sRGB fixtures now assert Pow beside UnpackUnorm4x8 / PackUnorm4x8, no table, and DevicePackConversion; the interpreter models no Pow, so the table reference values and the interpreter run go (their values are the device lanes'). The test is renamed metal_math_variants_select_their_forms. - engine_native_maths: dot, mix and fast::sqrt are OpDot, FMix and Sqrt with no Fma on lavapipe and on MoltenVK, a float dot and mix noting nothing on MoltenVK and a half mix NativeMix; the values hold their notes' bounds on both profiles' interpreter runs, where the test used to claim Metal's fused chains word for word on MoltenVK. - refine_float's doc: air.fast_sqrt is the device's Sqrt; engine_tiny_products' doc: the module's dot is the device's OpDot. Verified: with llvm-as set, every engine_ and lower::arith test passes (1610); clippy clean. * Number ARTIFACT_FORMAT_VERSION 473 and SEMANTICS_VERSION 1904, past development's The fast-math landing took ARTIFACT_FORMAT_VERSION 470 and the sampler-details landing 472 and SEMANTICS_VERSION 1903, so this series' encoding (the new DevicePackConversion note and the removed MetalHalfQuantize property in the codec) takes 473, and its translation changes 1904 (set in the series' first commit at the rebase onto 322dc6354d). * 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. --- .../metal2vulkan-conformance/known-gaps.tsv | 5 +- crates/metal2vulkan-conformance/src/replay.rs | 1 + .../metal2vulkan-runtime/src/degradation.rs | 25 +- .../runtime-sources.sha256 | 2 +- .../src/observation_contract/comparison.rs | 1 + .../src/runtime_lane/driver_deviations.rs | 122 ++- .../src/runtime_lane/native_maths.rs | 15 +- crates/metal2vulkan/src/cache/codec.rs | 3 +- crates/metal2vulkan/src/cache/mod.rs | 4 +- crates/metal2vulkan/src/device/derive.rs | 3 - .../metal2vulkan/src/device/driver_facts.rs | 30 - crates/metal2vulkan/src/device/profile.rs | 4 - .../metal2vulkan/src/device/requirements.rs | 8 - .../src/device/tests/driver_facts.rs | 8 - crates/metal2vulkan/src/error/mod.rs | 8 - crates/metal2vulkan/src/lower/arith/chunk.rs | 80 +- .../metal2vulkan/src/lower/arith/libm/mod.rs | 95 +-- crates/metal2vulkan/src/lower/arith/math.rs | 744 ++++-------------- crates/metal2vulkan/src/lower/arith/mod.rs | 367 +++------ crates/metal2vulkan/src/lower/arith/nan.rs | 45 +- crates/metal2vulkan/src/lower/arith/narrow.rs | 5 +- crates/metal2vulkan/src/lower/arith/pack.rs | 270 +++++++ crates/metal2vulkan/src/lower/arith/tests.rs | 525 ++++++------ .../src/lower/arith/tests/atan2.rs | 10 +- .../src/lower/arith/tests/fast.rs | 108 +-- .../src/lower/arith/tests/fused.rs | 362 +-------- .../src/lower/arith/tests/libm.rs | 1 - .../src/lower/arith/tests/narrow.rs | 106 +-- .../src/lower/arith/tests/pack.rs | 248 ++++++ .../src/lower/arith/tests/specials.rs | 362 ++------- crates/metal2vulkan/src/pipeline/artifact.rs | 91 ++- crates/metal2vulkan/src/spirv/interp/glsl.rs | 58 +- crates/metal2vulkan/src/tests/engine_arith.rs | 488 ++++-------- .../src/tests/engine_float_call_notes.rs | 12 +- .../src/tests/engine_metal_math.rs | 296 ++----- .../src/tests/engine_native_half.rs | 18 - .../src/tests/engine_native_maths.rs | 129 ++- .../src/tests/engine_tiny_products.rs | 3 +- crates/metal2vulkan/src/tests/fast_paths.rs | 1 + crates/metal2vulkan/tests/api_signatures.tsv | 4 +- docs/API.md | 52 +- docs/CONFORMANCE-COVERAGE.md | 7 +- docs/FAST-PATHS.md | 7 +- 43 files changed, 1864 insertions(+), 2869 deletions(-) create mode 100644 crates/metal2vulkan/src/lower/arith/pack.rs create mode 100644 crates/metal2vulkan/src/lower/arith/tests/pack.rs diff --git a/crates/metal2vulkan-conformance/known-gaps.tsv b/crates/metal2vulkan-conformance/known-gaps.tsv index 2d1d25879..e77c815b4 100644 --- a/crates/metal2vulkan-conformance/known-gaps.tsv +++ b/crates/metal2vulkan-conformance/known-gaps.tsv @@ -656,8 +656,9 @@ norm-storage-codes-rgba8unorm llvmpipe divergent case/hsw_buffer/texels 128 elem norm-storage-codes-rgba8unorm llvmpipe divergent case/hsw_held/texels 128 elements differ (U32), the largest difference 16843009 A `float` the function writes to a normalized storage texture at a tie between two codes: Metal stores the exact product rounded with a tie away from zero, and this device rounds the tie to even, so each tie channel is a code apart (the report compares whole words, so its difference adds a word's channels together: Metal 0x01010101 against our 0x00000000 is four channels a code apart). Under the native-arithmetic contract the device's conversion is the answer: `device-color-conversion` records exactly this for a storage write the device converts, and validation derives no tolerance from it. Open: nothing. norm-storage-codes-rgba8unorm llvmpipe divergent case/hsw_read_write/texels 128 elements differ (U32), the largest difference 16843009 A `float` the function writes to a normalized storage texture at a tie between two codes: Metal stores the exact product rounded with a tie away from zero, and this device rounds the tie to even, so each tie channel is a code apart (the report compares whole words, so its difference adds a word's channels together: Metal 0x01010101 against our 0x00000000 is four channels a code apart). Under the native-arithmetic contract the device's conversion is the answer: `device-color-conversion` records exactly this for a storage write the device converts, and validation derives no tolerance from it. Open: nothing. norm-storage-codes-rgba8unorm llvmpipe divergent case/hsw_write/texels 128 elements differ (U32), the largest difference 16843009 A `float` the function writes to a normalized storage texture at a tie between two codes: Metal stores the exact product rounded with a tie away from zero, and this device rounds the tie to even, so each tie channel is a code apart (the report compares whole words, so its difference adds a word's channels together: Metal 0x01010101 against our 0x00000000 is four channels a code apart). Under the native-arithmetic contract the device's conversion is the answer: `device-color-conversion` records exactly this for a storage write the device converts, and validation derives no tolerance from it. Open: nothing. -pass-bytes-half-tanh-regimes llvmpipe divergent case/output/half-tanh 1298 elements differ (U32), the largest difference 2180022768 Each word holds two `half` results of `tanh` over its regimes, which the device computes by its own functions and rounds to `half` by its own conversion (`native-transcendentals`, `native-division`, `native-half-conversion`; a NaN's bits and a denormal are the device's, `native-nan-encoding`, `device-denormals`). The first differing element is one `half` ulp toward zero in each half (Metal 0x0800 against our 0x07FF), and the site's largest difference, 0x81F081F0, sets a sign bit in each half, so some lanes differ in sign too. `native-transcendentals` bounds a hyperbolic function by its `Exp` and `Log` formulas and `native-half-conversion` the rounding at one `half` ulp; whether every differing word is within them is not established by this run, which reads the first and the largest. Validation derives no tolerance from them. Open: an element-by-element read of the site against the notes' recorded bounds. -pass-bytes-srgb-decode-all-bytes llvmpipe divergent case/output/words 214 elements differ (U32), the largest difference 65537 Each word holds two `half` results of an sRGB decode of a byte, and they differ by at most one `half` ulp in each half (the site's largest difference, 0x00010001; the first is Metal 0x3BEE against our 0x3BED). The module rounds the result to `half` by the device's conversion, and `native-half-conversion`'s recorded bound is one `half` ulp, lavapipe rounding toward zero; validation derives no tolerance from it. Open: nothing. +pass-bytes-half-tanh-regimes llvmpipe divergent case/output/half-tanh 1257 elements differ (U32), the largest difference 2180022768 Each word holds two `half` results of `tanh` over its regimes, which the device computes by its own `Tanh` (a `half` held as `float`, on every device) and rounds to `half` by its own conversion (`native-transcendentals`, `native-half-conversion`; a NaN's bits and a denormal are the device's, `native-nan-encoding`, `device-denormals`). The first differing element is one `half` ulp toward zero in each half (Metal 0x0C00 against our 0x0BFF), and the site's largest difference, 0x81F081F0, sets a sign bit in each half, so some lanes differ in sign too. `native-transcendentals` bounds `Tanh` as Vulkan does, inherited from `sinh / cosh` and so from `Exp`, and `native-half-conversion` the rounding at one `half` ulp; whether every differing word is within them is not established by this run, which reads the first and the largest. Validation derives no tolerance from them. Open: an element-by-element read of the site against the notes' recorded bounds. +pass-bytes-srgb-decode-all-bytes llvmpipe divergent case/output/words 1153 elements differ (U32), the largest difference 16318464 Each thread holds four `float` and two words of two `half` results of an sRGB decode of a byte. Metal decodes through its twelve-bit table, answering the step `k / 4095` nearest the transfer; the module decodes by the MSL transfer function through the device's `Pow` (`device-pack-conversion`, on every device), and rounds a `half` result by the device's conversion (`native-half-conversion`). The first differing element is a `float` decode of byte 90, Metal's step 419/4095 (0x3DD18D19) against the transfer's 0.1022417 (0x3DD1641D); the site's largest difference, 0x00F90000, is a small `half` 249 of its ulps off. Read element by element on the validation crate's copy of the case (`srgb-decode-of-every-byte` on lavapipe), every `float` is within 1.221e-4 of Metal's, half a twelve-bit step, and every `half` within that and one `half` ulp, the alpha channels exact: within `device-pack-conversion`'s recorded bound. Validation derives no tolerance from it. Open: nothing. +pass-bytes-srgb-encode-sweep llvmpipe divergent case/output/words 772 elements differ (U32), the largest difference 65793 Each word holds an sRGB encode of a `float` or a `half` colour packed to four bytes. Metal encodes through its twelve-bit table; the module encodes by the MSL transfer function through the device's `Pow` and rounds it to a byte by `PackUnorm4x8` (`device-pack-conversion`, on every device), so a colour near a byte boundary lands a code from Metal's. The first differing element is one code in one channel (Metal 0x00020201 against our 0x00020101), and the site's largest difference, 0x00010101, is one code in each colour channel. Read element by element on the validation crate's copy of the case (`srgb-encode-of-every-half-and-a-2-14-float-grid` on lavapipe), every differing channel is one code from Metal's and no alpha differs: within `device-pack-conversion`'s recorded bound. Validation derives no tolerance from it. Open: nothing. pixel-downscales-1000x1080 llvmpipe divergent case/output/frac/norm/digest the digest is 264ceee98d6179ad0db33d7a10d196da1c8db63673b939b97ad07d9f0dcb7716 on Metal and 5d64a9642dc61d423f57de864ce9146b20705bda466075d8184e60f995326fbe here The digest of a linear-filtered downscale's output, which differs wherever the site's `head` and `tail` elements do: the case samples through the device's own filter and texel conversion (`device-sampling`, `device-texel-conversion`), the native-arithmetic contract's answer, and validation derives no tolerance from either. The neighbouring `head` and `tail` rows carry the bound. Open: nothing. pixel-downscales-1000x1080 llvmpipe divergent case/output/frac/norm/head 996 elements differ (F32), the largest difference 0.0036765336990356445 A linear-filtered downscale through the device's own sampler: the site's elements differ by at most one code of 1/255 (0.00392, to an `f32` ulp). `device-sampling` records the device's filter, whose measured bound on lavapipe is a linear filter's largest difference of 1.0 code of 1/255 (2D textures of one level), which this site reaches and does not pass; validation derives no tolerance from it. Open: nothing. pixel-downscales-1000x1080 llvmpipe divergent case/output/frac/norm/tail 980 elements differ (F32), the largest difference 0.003676474094390869 A linear-filtered downscale through the device's own sampler: the site's elements differ by at most one code of 1/255 (0.00392, to an `f32` ulp). `device-sampling` records the device's filter, whose measured bound on lavapipe is a linear filter's largest difference of 1.0 code of 1/255 (2D textures of one level), which this site reaches and does not pass; validation derives no tolerance from it. Open: nothing. diff --git a/crates/metal2vulkan-conformance/src/replay.rs b/crates/metal2vulkan-conformance/src/replay.rs index 529c2b7d6..4665bcfc9 100644 --- a/crates/metal2vulkan-conformance/src/replay.rs +++ b/crates/metal2vulkan-conformance/src/replay.rs @@ -414,6 +414,7 @@ pub const NATIVE_NOTES: &[metal2vulkan_runtime::Degradation] = { D::NativeFma, D::NativeDot, D::NativeMix, + D::DevicePackConversion, D::NativeMinMax, D::NativeNanEncoding, D::DeviceTranscendentals, diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 837380198..514758a86 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2168,25 +2168,38 @@ degradations! { 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` on a device not measured to answer Metal's operand. 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, and `median3` of + /// them on every device. 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). NativeMinMax = "native-min-max"; - /// Class: native device maths. The device's `OpDot` answers Metal's `dot` on `float`, or on - /// `half` where its fused multiply-add is not the measured 16-bit one (summed in `float`, - /// rounded once to `half`), where Metal's is the fused chain of its products. Recorded + /// Class: native device maths. The device's `OpDot` answers Metal's `dot` on `float` and + /// `half` (summed in `float`, rounded once to `half`) on every device but for a `float` one + /// on MoltenVK, where Metal's is the fused chain of its products. Recorded /// bound: a `float` `dot` of `n` lanes within `(3n - 1) * 2^-24 * sum |a_i * b_i|` of /// Metal's chain, plus `n * 2^-126` where a product is an `f32` denormal the device keeps; /// a `half` one within `(n + 3) * 2^-11 * sum |a_i * b_i| + (n + 2) * 2^-25`. NativeDot = "native-dot"; /// Class: native device maths. The device's `FMix` answers Metal's `mix(x, y, t)` on - /// `float`, or on `half` where its fused multiply-add is not the measured 16-bit one - /// (computed in `float`, rounded once to `half`), where Metal's is + /// `float` and `half` (computed in `float`, rounded once to `half`) on every device but for + /// a `float` one on MoltenVK, where Metal's is /// `fma(t, y, fma(-t, x, x))`. Recorded bound: a `float` result within `2^-21 * (|x * /// (1 - t)| + |y * t|)` of Metal's; a `half` one within `3 * 2^-10 * (|x * (1 - t)| + |y * /// t|) + 2^-23`. NativeMix = "native-mix"; + /// Class: native device maths (a conversion). The device's conversion answers + /// `air.pack` and `air.unpack` of a normalized format: `GLSL.std.450`'s `Pack` and + /// `Unpack` instructions for `unorm4x8`, `snorm4x8`, `unorm2x16` and `snorm2x16`, their + /// definition by the device's clamp, multiply, `RoundEven` and reciprocal for `rgb10a2` + /// and `rgb565`, and the MSL transfer functions by the device's `Pow` for + /// `unorm4x8_srgb`'s colour, where Metal rounds the exact product, divides correctly + /// rounded and takes an sRGB colour through its twelve-bit table. Recorded bound: a packed + /// code within one of Metal's, apart only near a half-integer; an unpacked value within + /// 2.5 ulp of the correctly rounded quotient; a decoded sRGB colour within half a + /// twelve-bit step (`1 / 8190`) of Metal's step `k / 4095`, beyond its division's and + /// `Pow`'s bounds; a NaN channel's code the device's, where Metal's is 0. + DevicePackConversion = "device-pack-conversion"; /// A render pipeline whose color attachments the device draws in more than one group: /// each draw runs once per group, each group's variant over its own copy of the pass's /// depth and stencil. Recorded bound: groups past the first may differ at discard or diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index e3e591365..bd7213e7a 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -76a9fc3f3f8c0034a0863faf5ff0172cabf44f29990bd86cd25c47ab61fd1afa +9db3b9db239ab922e9d9abf177465bbabfa7ac33f4e0a6f2fe38a21c33502f44 diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs index 9c556231f..293821a1f 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs @@ -325,6 +325,7 @@ pub fn allowance(note: PrecisionNote) -> Allowance { | N::NativeMinMax | N::NativeDot | N::NativeMix + | N::DevicePackConversion | N::DiscardDropsSimdgroupStores | N::HelperBranchDropsSimdgroupStores => Allowance::Unbounded, } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs b/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs index 726643d52..ae4832ab6 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs @@ -48,11 +48,9 @@ //! product's flushed denormal and the fused pair's NaN. A checked NaN is Metal's canonical one //! where the profile takes `MetalCanonicalNans`, and a NaN of the device's bits elsewhere //! (`NativeNanEncoding`). -//! - **The `half` quantize** (`MetalHalfQuantize`): the NaN model's narrowing, conversion and -//! `half` cases. No kernel requires `VkProperty::MetalHalfQuantize`: a `half` rounding through -//! the device's `OpQuantizeToF16` (a profile without `shaderFloat16`) records -//! `NativeHalfQuantize` whether the profile takes the deviation or not, its result below the -//! smallest normal `half` the device's. Under the float controls a rounding is the device's +//! - **The `half` quantize**: the NaN model's narrowing, conversion and `half` cases. A `half` +//! rounding through the device's `OpQuantizeToF16` (a profile without `shaderFloat16`) records +//! `NativeHalfQuantize`, its answer the device's. Under the float controls a rounding is the device's //! conversion, Metal's by the Vulkan spec, which gives Metal's largest `half`, so those words //! are checked; elsewhere the device's own form rounds (`NativeHalfConversion` or //! `NativeHalfQuantize`), whose words the test prints. @@ -64,8 +62,13 @@ //! `max3`, `clamp` and `median3` cases, at NaN operands of every kind and at zeros and denormals, //! with and without fast math. Where the profile takes the deviation, Metal's minimum, maximum //! and clamp are the device's `NMin`, `NMax` and `NClamp` and the kernels require -//! `VkProperty::MetalMinMax`, and every word is checked; elsewhere the module emits the same -//! instructions and records `native-min-max`, and the test prints how many words match. +//! `VkProperty::MetalMinMax`, and every word but `median3`'s is checked; elsewhere the module +//! emits the same instructions and records `native-min-max`, and the test prints how many words +//! match. `median3` is the device's `NMin` and `NMax` on every device (`native-min-max`), its +//! words printed. +//! - **`dot`**: the owned `dot` fixtures. `dot` is the device's `OpDot` on every device +//! (`native-dot`, but `float` on MoltenVK, whose `OpDot` is Metal's own `dot`): the `float` +//! words are checked where the profile takes `MetalFloatFunctions`, the others printed. //! - **The `half` arithmetic** (`MetalHalfArithmetic`): the NaN model's narrowing and `half` //! arithmetic cases, with and without fast math, and the `half` denormal arithmetic case. Where //! the profile takes the deviation, a `half` `+`, `-` or `*` is the device's 16-bit instruction, @@ -787,13 +790,15 @@ const DENORMAL_PROBES: [&str; 2] = [ /// The words of a [`DENORMAL_PROBES`] thread whose operations read `float` denormals as Metal /// does on every profile: `a + b`, `a - b`, `a * b`, `0 - a`, `a < b`, `a == b`, `floor`, `ceil`, -/// `trunc`, `round`, `rint`, `ldexp`, `step`, `(a * b) * c`, `a < b ? a : b`, `-(a * b)` and +/// `trunc`, `rint`, `ldexp`, `step`, `(a * b) * c`, `a < b ? a : b`, `-(a * b)` and /// `fabs(a - b)`; and `sqrt` and `rsqrt` ([`DENORMAL_PROBE_ROOTS`]) where Metal answers a zero, an -/// infinity or a NaN. Not `floor` and `ceil` (12, 13), whose reading no device measured matches, -/// the quotients (3, 40, 44), the device's division, the fused multiply-adds (4, 5), `dot` and -/// `length` (36, 37) and `mix` (38), whose fused sums flush at the tininess edge before rounding -/// on Metal, which no device measured matches on every lane, nor the math library's functions. -const DENORMAL_PROBE_WORDS: &[usize] = &[0, 1, 2, 7, 10, 11, 14, 15, 16, 35, 39, 43, 45, 46, 47]; +/// infinity or a NaN. Not `round` (15), C99's on every device (`NativeTranscendentals`), whose +/// zero below zero is `-0` where Metal answers `+0`; not `floor` and `ceil` (12, 13), whose reading +/// no device measured matches, the quotients (3, 40, 44), the device's division, the fused +/// multiply-adds (4, 5), `dot` and `length` (36, 37) and `mix` (38), the device's `OpDot` and +/// `FMix`, whose sums Metal fuses and flushes at the tininess edge before rounding, nor the math +/// library's functions. +const DENORMAL_PROBE_WORDS: &[usize] = &[0, 1, 2, 7, 10, 11, 14, 16, 35, 39, 43, 45, 46, 47]; /// The `sqrt` and `rsqrt` words of a [`DENORMAL_PROBES`] thread: checked where Metal answers a /// zero, an infinity or a NaN (a zero, denormal or negative operand). Their other words are the @@ -947,9 +952,7 @@ const HALF_EDGE_CASES: [&str; 6] = [ /// chip where the kernel rounds as Metal does: the device's conversion to 16 bits and back under /// the float controls that make it Metal's where the profile has them (the kernels then declare /// them and require no fact). A kernel that rounds by the device's own form (`rounds_natively`: -/// its conversion, or its quantize, whether the profile takes `MetalHalfQuantize` or not) answers -/// the device's words, which the test prints, and no kernel requires -/// `VkProperty::MetalHalfQuantize`. +/// its conversion, or its quantize) answers the device's words, which the test prints. #[test] fn half_quantize_rounds_as_metal_at_the_edge() { let messages = Messages::default(); @@ -957,7 +960,6 @@ fn half_quantize_rounds_as_metal_at_the_edge() { { let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); let name = device.name().to_owned(); - let quantizes = takes(&device, DriverDeviation::MetalHalfQuantize); let word = |bytes: &[u8], i: usize| { u32::from_le_bytes(bytes[4 * i..4 * i + 4].try_into().unwrap()) }; @@ -972,10 +974,6 @@ fn half_quantize_rounds_as_metal_at_the_edge() { let case = public_case(case_name).unwrap(); let controlled = rounds_under_float_controls(&device, &case); let native = rounds_natively(&device, &case); - assert!( - !requires_property(&device, &case, VkProperty::MetalHalfQuantize), - "{case_name} on {name}: a kernel's quantize records its note and requires no fact" - ); let run = run_case(&device, &case).unwrap(); let metal = metal_row(&case, METAL_ENVIRONMENT); assert_eq!(run.output.len(), metal.len(), "{case_name} on {name}"); @@ -988,9 +986,8 @@ fn half_quantize_rounds_as_metal_at_the_edge() { .filter(|(_, a, b)| a != b) .collect(); eprintln!( - "half quantize {case_name} on {name} (measured quantize: {quantizes}, the \ - device's own rounding: {native}, under float controls: {controlled}): {} of {} \ - edge words differ from Metal", + "half quantize {case_name} on {name} (the device's own rounding: {native}, \ + under float controls: {controlled}): {} of {} edge words differ from Metal", differ.len(), edge.len() ); @@ -1048,8 +1045,7 @@ const DFL_TRIG_CASE: &str = "precise-trigonometric-functions-at-nan-operands-und /// prints how many words differ), the kernels requiring `VkProperty::MetalFloatDenormals` exactly /// where the profile takes the deviation; in the `half` /// edge cases every word where the kernel rounds as Metal does (under the float controls), the -/// device's words printed where it rounds by its own form (its conversion, or its quantize, for -/// which no kernel requires `VkProperty::MetalHalfQuantize`); +/// device's words printed where it rounds by its own form (its conversion, or its quantize); /// and in [`DFL_TRIG_CASE`] every word whose Metal answer is a NaN (the functions' other words are /// the math library's precision, not their NaNs). A NaN's bits are Metal's only where the profile /// takes `DriverDeviation::MetalCanonicalNans` and Metal answers its canonical NaN; elsewhere the @@ -1114,22 +1110,16 @@ fn owned_float_fixtures_answer_metal() { )); } } - let quantizes = takes(&device, DriverDeviation::MetalHalfQuantize); for case_name in DFL_HALF_EDGE_CASES { let case = public_case(case_name).unwrap(); let controlled = rounds_under_float_controls(&device, &case); let native = rounds_natively(&device, &case); - assert!( - !requires_property(&device, &case, VkProperty::MetalHalfQuantize), - "{case_name} on {name}: a kernel's quantize records its note and requires no fact" - ); let run = run_case(&device, &case).unwrap(); let metal = metal_row(&case, METAL_ENVIRONMENT); let differ = differing_of(&run.output, &metal, 16, &(0..16).collect::>()); eprintln!( - "owned half edge {case_name} on {name} (measured quantize: {quantizes}, own \ - rounding: {native}, under float controls: {controlled}): {} of {} words differ \ - from Metal", + "owned half edge {case_name} on {name} (own rounding: {native}, under float \ + controls: {controlled}): {} of {} words differ from Metal", differ.len(), metal.len() / 4 ); @@ -1191,7 +1181,7 @@ fn owned_float_fixtures_answer_metal() { } // --------------------------------------------------------------------------------------------- -// Metal's `dot`: the fused chain of its products. +// `dot`: the device's `OpDot`. /// The owned `dot` fixtures (`nan_dot`, `nan_dot_fast`): 512 threads of 8 words, `dot` on two, /// three and four `float` and `half` lanes and the shared-operand forms `dot(float2(a, b), @@ -1202,13 +1192,12 @@ const DOT_CASES: [&str; 2] = [ "dot-of-two-to-four-float-and-half-lanes-under-fast-math", ]; -/// Both `dot` cases answer Metal where the module keeps Metal's fused chain (by the multiply and -/// the profile's fused multiply-adds) or the device's `OpDot` is Metal's own `dot`: every `float` -/// word where the profile takes `DriverDeviation::MetalFloatFunctions` (MoltenVK), and every -/// `half` word there or where it takes `DriverDeviation::MetalHalfFma` (the chain of Metal's own -/// 16-bit fused multiply-add). Elsewhere `dot` is the device's `OpDot` and the test prints how -/// many words differ. The kernels leave their `float` denormals to the device exactly where the -/// profile takes `DriverDeviation::MetalFloatDenormals`. +/// `dot` is the device's `OpDot` on every device, and each kernel records +/// `PrecisionNote::NativeDot` (its `half` lanes', held as `float`, on every device). Both cases +/// answer Metal where the device's `OpDot` is Metal's own `dot`: every `float` word where the +/// profile takes `DriverDeviation::MetalFloatFunctions` (MoltenVK). The test prints how many of +/// the other words differ. The kernels leave their `float` denormals to the device exactly where +/// the profile takes `DriverDeviation::MetalFloatDenormals`. #[test] fn owned_dot_fixtures_answer_metal() { let messages = Messages::default(); @@ -1218,17 +1207,8 @@ fn owned_dot_fixtures_answer_metal() { let name = device.name().to_owned(); let denormals = takes(&device, DriverDeviation::MetalFloatDenormals); let metals = takes(&device, DriverDeviation::MetalFloatFunctions); - let half_chain = metals || takes(&device, DriverDeviation::MetalHalfFma); // Words 0 to 2, 6 and 7 are `float` sums, 3 to 5 `half` ones. - let checked: Vec = (0..8) - .filter(|w| { - if (3..6).contains(w) { - half_chain - } else { - metals - } - }) - .collect(); + let checked: Vec = (0..8).filter(|w| metals && !(3..6).contains(w)).collect(); let mut failures = Vec::new(); for case_name in DOT_CASES { let case = public_case(case_name).unwrap(); @@ -1238,6 +1218,10 @@ fn owned_dot_fixtures_answer_metal() { "{case_name} on {name}: the kernel leaves its denormals to the device exactly \ where the profile takes the deviation" ); + assert!( + case_notes(&device, &case).contains(&PrecisionNote::NativeDot), + "{case_name} on {name}: the device's dot, unrecorded" + ); let run = run_case(&device, &case).unwrap(); let metal = metal_row(&case, METAL_ENVIRONMENT); assert_eq!(run.output.len(), metal.len(), "{case_name} on {name}"); @@ -1245,8 +1229,8 @@ fn owned_dot_fixtures_answer_metal() { let differ: Vec<_> = all.iter().filter(|d| checked.contains(&d.1)).collect(); eprintln!( "owned dot {case_name} on {name} (the device's denormals: {denormals}, Metal's \ - float functions: {metals}, Metal's half chain: {half_chain}): {} of {} words \ - differ from Metal, {} of them in the words checked ({checked:?})", + float functions: {metals}): {} of {} words differ from Metal, {} of them in the \ + words checked ({checked:?})", all.len(), metal.len() / 4, differ.len() @@ -1270,7 +1254,7 @@ fn owned_dot_fixtures_answer_metal() { /// The NaN model's minimum and maximum cases: Metal's `fmin`, `fmax`, `min3`, `max3`, `clamp` and /// `median3` of `float` over NaN operands of every kind, and at zeros and denormals, without and -/// under fast math. +/// under fast math. Each lane writes eight words, `median3` its seventh ([`MEDIAN3_WORD`]). const MIN_MAX_CASES: [&str; 4] = [ "nan-model-min-max-of-nan-operands", "nan-model-min-max-of-nan-operands-under-fast-math", @@ -1278,10 +1262,16 @@ 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 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. +/// The word of a [`MIN_MAX_CASES`] lane that holds its `median3`. +const MEDIAN3_WORD: usize = 6; + +/// Every word of [`MIN_MAX_CASES`] but `median3`'s 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. `median3` is the device's `NMin` and `NMax` on every device, which records +/// `native-min-max` (of two NaNs and of an `f32` denormal, the device's pick), so its words are +/// printed. #[test] fn minimums_and_maximums_answer_as_metal() { let messages = Messages::default(); @@ -1299,21 +1289,27 @@ fn minimums_and_maximums_answer_as_metal() { "{case_name} on {name}: the kernel takes the device's NMin, NMax and NClamp \ exactly where the profile takes the deviation" ); + assert!( + case_notes(&device, &case).contains(&PrecisionNote::NativeMinMax), + "{case_name} on {name}: the device's median3, unrecorded" + ); let run = run_case(&device, &case).unwrap(); let metal = metal_row(&case, METAL_ENVIRONMENT); assert_eq!(run.output.len(), metal.len(), "{case_name} on {name}"); let word = |bytes: &[u8], i: usize| { u32::from_le_bytes(bytes[4 * i..4 * i + 4].try_into().unwrap()) }; - let differ: Vec<(usize, u32, u32)> = (0..metal.len() / 4) + let (median3, differ): (Vec<(usize, u32, u32)>, Vec<_>) = (0..metal.len() / 4) .map(|i| (i, word(&run.output, i), word(&metal, i))) .filter(|(_, a, b)| a != b) - .collect(); + .partition(|(i, _, _)| i % 8 == MEDIAN3_WORD); eprintln!( "min/max {case_name} on {name} (the device's: {metals}): {} of {} words differ \ - from Metal", + from Metal, and {} median3 words (the device's): {:x?}", differ.len(), - metal.len() / 4 + metal.len() / 4, + median3.len(), + &median3[..median3.len().min(8)] ); if metals && !differ.is_empty() { failures.push(format!( diff --git a/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs b/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs index a33e14462..5b991d0fc 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs @@ -2,8 +2,9 @@ //! the validation layer (`candidate::runtime_case::validated_options`, whose policy changes no //! translation: the device's forms are the only ones). 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 +//! `float` `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 (a +//! `half` `dot` or `mix` records its note on every device), 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 @@ -571,7 +572,7 @@ fn half_operands() -> Vec<[f32; 2]> { /// On a device whose float controls do not make its conversion to 16 bits Metal's, the stage /// records `NativeHalfConversion` (or `NativeHalfQuantize` without `shaderFloat16`, whose narrowing -/// and sum are the bare quantize, measured or not) and the pipeline state announces it, and each +/// and sum are the bare quantize) and the pipeline state announces it, and each /// `half` narrowing and sum is within the bound the note records: one unit in the last place of the /// `half`, 65504 where Metal answers infinity from 65520 up on a device that rounds toward zero, /// and the zero of its sign below `2^-14` on one that flushes 16-bit denormals (or whose quantize @@ -625,13 +626,9 @@ fn half_rounding_answers_within_its_recorded_bound() { .filter_map(|kind| kind.precision_note()) .filter(|note| kinds.contains(note)) .collect(); - // A rounding by the bare quantize leaves a result below the smallest normal `half` to - // the device, measured quantize or not: only the float controls answer Metal's. + // A rounding by the bare quantize is the device's: only the float controls answer + // Metal's. let metal_s = controlled; - assert!( - !required.contains(&VkProperty::MetalHalfQuantize), - "{name}: a quantize requires no fact" - ); eprintln!("{name}: float controls {controlled}; announced {announced:?}"); assert_eq!(announced.len(), usize::from(!metal_s), "{name}"); let operands = half_operands(); diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index db12de185..c7572cef9 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1023,7 +1023,7 @@ codec_enum! { DepthResolveMode(f0), StencilResolveMode(f0), IndependentResolveNone, IndependentResolve, VariableSampleLocations, SampleLocationSampleCount(f0), ColorAttachmentSampleCount(f0, f1), MetalColorWrites, MetalFloatColorNans, MetalHalfColorNans, - MetalHalfFma, MetalFloatDenormals, MetalHalfQuantize, + MetalHalfFma, MetalFloatDenormals, MetalCenterVaryings, MetalSmallFloatColorWrites, MetalNorm16ColorWrites, MetalMinMax, MetalHalfArithmetic, MetalHalfStorageWrites, MetalHalfStorageNans, MetalFloatStorageNans, MetalFragmentSimdgroups, MetalVertexSimdgroups, CenterFragCoordDepth, SampleFragCoordDepth, @@ -1438,6 +1438,7 @@ codec_enum! { NativeMinMax, NativeDot, NativeMix, + DevicePackConversion, ColorAttachmentGroups, TessellationTriangleOrder, UnmeasuredGroupSpeculation, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 4f9f954a4..55c4a133a 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 = 1903; +pub const SEMANTICS_VERSION: u32 = 1904; /// 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 = 1903; /// 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 = 472; +pub const ARTIFACT_FORMAT_VERSION: u32 = 473; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index 9561bc301..63c636891 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -747,9 +747,6 @@ fn enabled_caps(desc: &DeviceDescription, deviations: &BTreeSet if deviations.contains(&DriverDeviation::MetalFloatDenormals) { properties.insert(VkProperty::MetalFloatDenormals); } - if deviations.contains(&DriverDeviation::MetalHalfQuantize) { - properties.insert(VkProperty::MetalHalfQuantize); - } if deviations.contains(&DriverDeviation::MetalCenterVaryings) { properties.insert(VkProperty::MetalCenterVaryings); } diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index 12da7cbde..6c9b23ac6 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -133,17 +133,6 @@ pub(crate) fn among( /// `Ceil` keep a denormal, which the deviation does not cover: every profile leaves their /// denormals to the device, noted (`lower::arith::denormal`). One row per GPU, as measured. /// -/// `MetalHalfQuantize`: the device's `OpQuantizeToF16` rounds an `f32` below 65520 in magnitude to -/// nearest even, as Metal's conversion to `half` does, so 65504 to 65520 (`0x477FEFFF` among them) -/// is 65504, not infinity. The committed rows of the NaN model's narrow, convert and half cases -/// (`nan_narrow`, `nan_convert`, `nan_half` and their fast-math twins) match Metal's on every word -/// whose answer is the largest `half` on MoltenVK 1.4.1 on the M3 Max and the M4, RADV (Mesa 26.2.4 -/// on the Radeon 780M) and ANV (Mesa 26.2.4 on the UHD 770 of RPL-S); the gate lane -/// `half_quantize_*` and the owned fixture `dfl_half_edge` measure the Iris Xe of RPL-P likewise. -/// NVIDIA's 615.71.09 rounds `0x477FEFFF` to infinity, so it is not listed; lavapipe's rows match -/// at Mesa 26.0.8 alone, below the committed `lavapipe` profile's release, so it is not listed -/// either. One row per GPU, as measured. -/// /// `MetalCenterVaryings`: MoltenVK 1.4.1 hands Metal a smooth input decorated neither `Centroid` /// nor `Sample` with no interpolation qualifier (SPIRV-Cross `adec7acb`, `spirv_msl.cpp` /// 13664-13720), which Metal reads as `center_perspective` (`NoPerspective`: @@ -459,25 +448,6 @@ pub(crate) const DEVIATIONS: &[Measured] = &[ ), nvidia_on(DriverDeviation::MetalFloatDenormals, NVIDIA_RTX_3090), nvidia_on(DriverDeviation::MetalFloatDenormals, NVIDIA_RTX_5080_LAPTOP), - Measured { - device: Some(APPLE9), - ..moltenvk_on_apple(DriverDeviation::MetalHalfQuantize) - }, - mesa_on( - DriverDeviation::MetalHalfQuantize, - DriverId::MESA_RADV, - (AMD_VENDOR_ID, AMD_RADEON_780M), - ), - mesa_on( - DriverDeviation::MetalHalfQuantize, - DriverId::INTEL_OPEN_SOURCE_MESA, - (INTEL_VENDOR_ID, INTEL_UHD_770_RPL_S), - ), - mesa_on( - DriverDeviation::MetalHalfQuantize, - DriverId::INTEL_OPEN_SOURCE_MESA, - (INTEL_VENDOR_ID, INTEL_IRIS_XE_RPL_P), - ), Measured { device: Some(APPLE9), ..moltenvk_on_apple(DriverDeviation::MetalCenterVaryings) diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index 87b5fbe0f..5fa24d8a1 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -260,10 +260,6 @@ impl DeviceProfile { .enabled .properties .contains(&VkProperty::MetalFloatDenormals), - DriverDeviation::MetalHalfQuantize => f - .enabled - .properties - .contains(&VkProperty::MetalHalfQuantize), DriverDeviation::MetalCenterVaryings => f .enabled .properties diff --git a/crates/metal2vulkan/src/device/requirements.rs b/crates/metal2vulkan/src/device/requirements.rs index 26128cfc9..d03e3cf61 100644 --- a/crates/metal2vulkan/src/device/requirements.rs +++ b/crates/metal2vulkan/src/device/requirements.rs @@ -652,14 +652,6 @@ pub enum VkProperty { /// operation's denormals to the device, recording no `PrecisionNote::DeviceDenormals` for it, /// requires it; without it, they are the device's own, and the module records that note. MetalFloatDenormals, - /// The device's `OpQuantizeToF16` rounds as Metal's conversion to `half` does, to nearest - /// even below 65520 (the driver's measured deviation - /// [`DriverDeviation::MetalHalfQuantize`](crate::error::DriverDeviation::MetalHalfQuantize)). - /// No Vulkan query reports it: the quantize's rounding mode is the device's. No module - /// requires it: a module that rounds to `half` through the quantize records - /// `PrecisionNote::NativeHalfQuantize` on every profile, its result below the smallest normal - /// `half` the device's. - MetalHalfQuantize, /// The device reads a center-sampled varying of a multisampled pipeline at the pixel center /// in every fragment invocation, a sample-rate one's included, as Metal does (the driver's /// measured deviation diff --git a/crates/metal2vulkan/src/device/tests/driver_facts.rs b/crates/metal2vulkan/src/device/tests/driver_facts.rs index 02756be71..c124d2537 100644 --- a/crates/metal2vulkan/src/device/tests/driver_facts.rs +++ b/crates/metal2vulkan/src/device/tests/driver_facts.rs @@ -81,10 +81,6 @@ fn taken(p: &crate::device::DeviceProfile) -> Vec D::MetalFloatDenormals, property(VkProperty::MetalFloatDenormals), ), - ( - D::MetalHalfQuantize, - property(VkProperty::MetalHalfQuantize), - ), ( D::MetalCenterVaryings, property(VkProperty::MetalCenterVaryings), @@ -197,7 +193,6 @@ fn the_profile_takes_the_deviations_its_driver_is_measured_with() { D::MetalColorWrites, D::MetalHalfFma, D::MetalFloatDenormals, - D::MetalHalfQuantize, D::MetalCenterVaryings, D::MetalMinMax, D::MetalHalfArithmetic, @@ -273,7 +268,6 @@ fn the_profile_takes_the_deviations_its_driver_is_measured_with() { // `deviceID` and Hawk Point's alike. (false, "amd-780m-radv" | "amd-780m-hawkpoint-radv") => vec![ D::MetalFloatDenormals, - D::MetalHalfQuantize, D::MetalSmallFloatColorWrites, D::MetalNorm16ColorWrites, D::MetalHalfStorageWrites, @@ -286,14 +280,12 @@ fn the_profile_takes_the_deviations_its_driver_is_measured_with() { ], (false, "intel-irisxe-rplp-anv") => vec![ D::MetalFloatDenormals, - D::MetalHalfQuantize, D::MetalSmallFloatColorWrites, D::MetalHalfStorageWrites, D::MetalDepth16Stores, ], (false, "intel-uhd770-rpls-anv") => vec![ D::MetalFloatDenormals, - D::MetalHalfQuantize, D::MetalSmallFloatColorWrites, D::MetalHalfStorageWrites, D::MetalDepth16Stores, diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 6fd5fd664..f861848ed 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -617,14 +617,6 @@ pub enum DriverDeviation { /// `Ldexp`, `Sqrt`, `InverseSqrt`, `Trunc` and `RoundEven`. Unmeasured, such operands and /// results are the device's own, recorded as `PrecisionNote::DeviceDenormals`. MetalFloatDenormals, - /// The device's `OpQuantizeToF16` rounds an `f32` below 65520 in magnitude to nearest even, - /// as Metal's conversion to `half` does, so that a value from 65504 up to 65520 is 65504, not - /// infinity (`VkProperty::MetalHalfQuantize`). Vulkan leaves the quantize's rounding mode to - /// the device. A module that rounds to `half` through the quantize (`QuantizeForm::Device`, a - /// profile without `shaderFloat16`) records `PrecisionNote::NativeHalfQuantize` whether the - /// profile takes it or not, and requires no property: the measurement covers the quantize's - /// normal results, and its result below the smallest normal `half` is the device's. - MetalHalfQuantize, /// The device reads a center-sampled varying (a smooth input decorated neither `Centroid` /// nor `Sample`) of a multisampled pipeline at the pixel center in every fragment /// invocation, a sample-rate one's included, as Metal reads it diff --git a/crates/metal2vulkan/src/lower/arith/chunk.rs b/crates/metal2vulkan/src/lower/arith/chunk.rs index 064312db0..6c072b07c 100644 --- a/crates/metal2vulkan/src/lower/arith/chunk.rs +++ b/crates/metal2vulkan/src/lower/arith/chunk.rs @@ -27,10 +27,9 @@ //! move moves both words of the lane, a dynamic index of 64 bits reads its low word (an index of //! `2^32` or more is out of range), and a bitcast takes the lane's words as they are. //! -//! - **`dot`** of chunked vectors is Metal's fused chain over every lane ([`dot_chain`]) where -//! Metal's order is the profile's, else sums each chunk's `OpDot` (a product for a one-lane -//! chunk) in `f32` and rounds a narrow result once; **`sincos`** of one takes each chunk's sine -//! and cosine, and its cosine is stored as one chunked leaf (`memory::leaf`). +//! - **`dot`** of chunked vectors sums each chunk's `OpDot` (a product for a one-lane chunk) in +//! `f32` and rounds a narrow result once; **`sincos`** of one takes each chunk's sine and +//! cosine, and its cosine is stored as one chunked leaf (`memory::leaf`). //! //! Not lowered (`NotImplemented`): bitcasts whose lanes are `i1` or of another width, or whose //! total is not a whole number of words. @@ -42,8 +41,6 @@ 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::NanTest; -use crate::lower::arith::{denormal, fma}; use crate::lower::arith::{narrow, operands_of, ops, wide, ArithStrategy}; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; @@ -358,17 +355,10 @@ fn is_math(call: &Call, f: MathFn) -> bool { ) } -/// `air.dot` of two chunked float vectors. On `float` and `half` where the device's functions are -/// Metal's (MoltenVK), and on `half` by the measured 16-bit fused multiply-add, Metal's fused chain -/// over every lane, as on two to four lanes (`math::metal_chain`): on an Apple M3 Max -/// under macOS 27.0.1 every answer of `dot` on 5, 8 and 16 `float` lanes and on 8 and 16 `half` -/// lanes, with and without fast-math flags, is the chain's (16,384 rows of seeded -/// random lanes each, where the chain backwards, the chunks' sums added, and the exact sum rounded -/// once miss 6% to 70% of them; and our probe at `float` denormals on 8 lanes), its `float` -/// 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 the device's. +/// `air.dot` of two chunked float vectors, on every device: the sum of each chunk's dot product by +/// the device's `OpDot`, rounded once to a narrow format. Metal's `dot` is the products' fused +/// chain over every lane; `dot`'s device precision (`DeviceArithmetic`) covers the order of the +/// sum, which Vulkan leaves 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")); @@ -387,21 +377,6 @@ fn select_dot(cx: &mut SelectCx<'_>, inst: &Inst, call: &Call) -> Result u32 { .saturating_add(8 + narrow::round_words(elem)) } -/// Metal's `dot` of chunked vectors `a` and `b` of `lanes` lanes of `elem`: its fused chain over -/// every lane in order (`math::metal_chain`), each fused multiply-add `fma`. -pub fn dot_chain( - fb: &mut FunctionBuilder<'_>, - lanes: u16, - elem: Form, - [a, b]: [SValue; 2], - fma: math::FmaOf<'_>, -) -> BResult { - let chunks = chunk_lanes(u32::from(lanes)); - let lane = |fb: &mut FunctionBuilder<'_>, i: u32| -> BResult<(SValue, SValue)> { - let c = i / 4; - let size = chunks.get(c as usize).copied().ok_or_else(operand_error)?; - let at = [c, i % 4]; - let path = if size == 1 { &at[..1] } else { &at[..] }; - Ok(( - fb.composite_extract(a, path)?, - fb.composite_extract(b, path)?, - )) - }; - math::metal_chain(fb, elem, u32::from(lanes), &lane, fma) -} - -/// An upper estimate of the words of [`dot_chain`] on `lanes` lanes of `elem` whose fused -/// multiply-adds take `fma_words` each: two extractions per lane, the first product and its -/// rounding, and per later lane the fused multiply-add. -pub fn dot_chain_words(lanes: u16, elem: Form, fma_words: u32) -> u32 { - let lanes = u32::from(lanes); - 12u32 - .saturating_mul(lanes) - .saturating_add(5 + narrow::round_words(elem)) - .saturating_add(lanes.saturating_sub(1).saturating_mul(fma_words)) -} - /// 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`]). +/// reads it ([`math::float_fn`]). pub fn sin_cos( fb: &mut FunctionBuilder<'_>, s: Shape, x: SValue, fast: bool, - 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; Ok(( - math::float_fn(fb, sin, f, c, test, &[x], lib)?, - math::float_fn(fb, cos, f, c, test, &[x], lib)?, + math::float_fn(fb, sin, f, c, &[x], lib)?, + math::float_fn(fb, cos, f, c, &[x], lib)?, )) }; if !s.chunked { diff --git a/crates/metal2vulkan/src/lower/arith/libm/mod.rs b/crates/metal2vulkan/src/lower/arith/libm/mod.rs index 6e281435b..5cf3205c5 100644 --- a/crates/metal2vulkan/src/lower/arith/libm/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/libm/mod.rs @@ -4,10 +4,13 @@ //! //! Vulkan's precision table bounds `Atan`, `Asin`, and `Acos` at 4096 ulp and `Sin` and `Cos` at //! `2^-11` absolute, about what Metal's fast-math table allows, while Metal's precise functions are -//! bounded at 4 to 6 ulp (MSL Table 8.1). Every call takes the device's instruction, or Metal's -//! composition of the device's instructions where no instruction is the function (`exp10`, `log10`, -//! `sinpi`, `cospi`, `tanpi`), and records the device's precision where its functions are not -//! Metal's own (`PrecisionNote::NativeTranscendentals`). Where the device is Metal's own +//! bounded at 4 to 6 ulp (MSL Table 8.1). Every call, on `float` and on a `half` held as `float`, +//! takes the device's instruction where one is the function (`exp`, `log`, `pow`, `sinh`, `cosh` +//! and `tanh` among them), and a composition of the device's instructions only where none is +//! (`exp10`, `log10`, `sinpi`, `cospi`, `tanpi`, and the fast functions' formulas of MSL Table +//! 8.2), and records the device's precision where its functions are not Metal's own +//! (`PrecisionNote::NativeTranscendentals`). No routine computes Metal's answer where the device +//! has an instruction. Where the device is Metal's own //! (`FloatFunctions::Metal`: MoltenVK on an Apple GPU), its instruction is Metal's function in the //! math mode Metal compiles the module with ([`module_mode`]), so a call in that mode is Metal's //! own answer there ([`Fun::device_answers`]), which the notes read. @@ -138,6 +141,21 @@ pub enum Fun { HalfCos, /// Metal's `half` `asinh` before its rounding, its own form. HalfAsinh, + /// Metal's `half` `exp`, `log`, `powr` (and `pow`'s magnitude), `sinh`, `cosh` and `tanh` + /// before their rounding, which the device's `float` instruction on the widened operand + /// answers at its own precision: Metal's are its fast `float` functions rounded (`tanh` its own + /// formula), which no instruction SPIRV-Cross emits is in every module. + HalfExp, + /// See [`Fun::HalfExp`]. + HalfLog, + /// See [`Fun::HalfExp`]. + HalfPowr, + /// See [`Fun::HalfExp`]. + HalfSinh, + /// See [`Fun::HalfExp`]. + HalfCosh, + /// See [`Fun::HalfExp`]. + HalfTanh, } impl Fun { @@ -157,10 +175,10 @@ impl Fun { /// /// `exp2` and `log2` are Metal's in either mode (Metal's fast ones are its precise ones), and /// so is `tanh` (SPIRV-Cross emits `precise::tanh` whatever the flags); `powr` and the other - /// hyperbolic functions only in a precise module. No `GLSL.std.450` instruction reaches - /// Metal's `exp10` and `log10`, but Metal's own compositions of its `exp2` and `log2` do, in - /// either mode (`math::metal_exp`, `math::metal_log`), and so do they for its precise `exp` - /// and `log`. Its reciprocal is the device's `1 / y` in a fast-math module, where Metal + /// hyperbolic functions, `exp` and `log` only in a precise module. No `GLSL.std.450` + /// instruction reaches Metal's `exp10` and `log10`, but Metal's own compositions of its `exp2` + /// and `log2` do, in either mode (`math::exp10`, `math::log10`). Its reciprocal is the + /// device's `1 / y` in a fast-math module, where Metal /// compiles the division with its fast reciprocal, and not in a precise one, whose quotient is /// correctly rounded. The device's instruction on a `half` held as `float` is its `float` /// function, never Metal's `half` form. @@ -176,6 +194,8 @@ impl Fun { | Fun::Rsqrt | Fun::Fmod | Fun::Powr + | Fun::Exp + | Fun::Log | Fun::Sinh | Fun::Cosh | Fun::Asinh @@ -189,15 +209,14 @@ impl Fun { | Fun::HalfTan | Fun::HalfSin | Fun::HalfCos - | Fun::HalfAsinh => false, - Fun::Atan2 - | Fun::Exp2 - | Fun::Log2 - | Fun::Tanh - | Fun::Exp - | Fun::Exp10 - | Fun::Log - | Fun::Log10 => true, + | Fun::HalfAsinh + | Fun::HalfExp + | Fun::HalfLog + | Fun::HalfPowr + | Fun::HalfSinh + | Fun::HalfCosh + | Fun::HalfTanh => false, + Fun::Atan2 | Fun::Exp2 | Fun::Log2 | Fun::Tanh | Fun::Exp10 | Fun::Log10 => true, } } @@ -232,7 +251,7 @@ impl Fun { /// The function's operands. pub fn arity(self) -> usize { match self { - Fun::Atan2 | Fun::Fmod | Fun::Powr | Fun::HalfAtan2 => 2, + Fun::Atan2 | Fun::Fmod | Fun::Powr | Fun::HalfAtan2 | Fun::HalfPowr => 2, _ => 1, } } @@ -243,17 +262,23 @@ impl Fun { /// `float` and computed by a `float` function before their rounding: Metal's `half` functions are /// the same in both math modes (the half probe, cases dc0fee8f and 3ef7c1c5; every `half` of our /// probe), so `refine_float` refines only `float` calls, and the `float` function of a `half` one -/// is `math::metal_half`'s, whose `tanh` takes Metal's `exp2` and reciprocal (`math::half_tanh`); -/// its `atan`, `atan2`, `tan`, `sin`, `cos`, and `asinh` are Metal's own `half` forms -/// ([`Fun::HalfAtan`], [`Fun::HalfAtan2`], [`Fun::HalfTan`]; [`Fun::HalfSin`], [`Fun::HalfCos`], -/// [`Fun::HalfAsinh`]). Another format takes none. +/// is `math::half_form`'s (`exp10` and `log10` their fast formulas, which Metal's `half` ones +/// are); its `atan`, `atan2`, `tan`, `sin`, `cos`, `asinh`, `exp`, `log`, `pow`, `powr`, `sinh`, +/// `cosh` and `tanh` are Metal's own `half` forms, which the device's `float` instruction answers +/// at its precision ([`Fun::HalfAtan`], [`Fun::HalfAtan2`], [`Fun::HalfTan`], [`Fun::HalfSin`], +/// [`Fun::HalfCos`], [`Fun::HalfAsinh`], [`Fun::HalfExp`]). Another format takes none. pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] { if !matches!(f.float_fmt(), Some(FloatFmt::F32 | FloatFmt::Half)) { return &[]; } if f.float_fmt() == Some(FloatFmt::Half) { match op { - FloatFn::Tanh => return &[Fun::Exp2, Fun::Recip], + FloatFn::Exp => return &[Fun::HalfExp], + FloatFn::Log => return &[Fun::HalfLog], + FloatFn::Pow | FloatFn::Powr => return &[Fun::HalfPowr], + FloatFn::Sinh => return &[Fun::HalfSinh], + FloatFn::Cosh => return &[Fun::HalfCosh], + FloatFn::Tanh => return &[Fun::HalfTanh], FloatFn::Atan => return &[Fun::HalfAtan], FloatFn::Atan2 => return &[Fun::HalfAtan2], FloatFn::Tan => return &[Fun::HalfTan], @@ -263,7 +288,7 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] { _ => {} } } - match crate::lower::arith::math::metal_half(op, f) { + match crate::lower::arith::math::half_form(op, f) { FloatFn::Atan => &[Fun::Atan(Mode::Precise)], FloatFn::FastAtan => &[Fun::Atan(Mode::Fast)], FloatFn::Asin => &[Fun::Asin(Mode::Precise)], @@ -371,13 +396,6 @@ impl Lib { self.metal_in(Mode::Fast) } - /// Whether `mix` and `fast::sqrt` round in the device's order, its `FMix` and `Sqrt`: on every - /// device whose functions are not Metal's. Where they are (MoltenVK), Metal's own forms of its - /// own fused multiply-add and `rsqrt` are Metal's answer and stay. - pub fn orders_natively(&self) -> bool { - self.metal.is_none() - } - /// Metal's precise `fmod` of `x` and `y` (`float` lanes of form `f`) by its routine, one call /// per lane; `None` where the module takes the device's `OpFRem` ([`Fun::device_answers`]). pub fn fmod( @@ -434,10 +452,10 @@ pub(crate) fn split(v: f64) -> (f32, f32) { (hi, (v - f64::from(hi)) as f32) } -/// Metal's precise `log` or `log10` next to 1: for `x` strictly between the bits `low` and `end`, +/// Metal's precise `log10` next to 1: for `x` strictly between the bits `low` and `end`, /// `RN(f fma(p(f), f, lead))` of `f = x - 1` (exact there), `p` by Horner's rule with fused steps, /// `f32` coefficients by their bits, lowest first: Metal's word at every `float` of its range -/// (`math::metal_log`). +/// (`math::log10`). pub(crate) struct Near { pub low: u32, pub end: u32, @@ -445,17 +463,6 @@ pub(crate) struct Near { pub p: &'static [u32], } -/// `log`'s. -pub(crate) const LOG_NEAR: Near = Near { - low: 0x3F74_0000, - end: 0x3F88_0000, - lead: 0x3F80_0000, - p: &[0xBEFF_FFF4, 0x3EAA_AC4E, 0xBE80_449E, 0x3E47_04F8], -}; - -/// `RN(ln(2))`, by its bits: Metal's `log` away from 1 is its `log2` times it. -pub(crate) const LN_2_BITS: u32 = 0x3F31_7218; - /// `log10`'s: `(495/512, 543/512)`, `lead` `log10(e)` rounded down. pub(crate) const LOG10_NEAR: Near = Near { low: 0x3F77_8000, diff --git a/crates/metal2vulkan/src/lower/arith/math.rs b/crates/metal2vulkan/src/lower/arith/math.rs index 0ba875fc3..63d7c3d55 100644 --- a/crates/metal2vulkan/src/lower/arith/math.rs +++ b/crates/metal2vulkan/src/lower/arith/math.rs @@ -3,22 +3,24 @@ //! `llvm.abs`, `llvm.ct{l,t}z`), float functions (`air` float math, `llvm.{fma,fmuladd,fabs, //! minnum,maxnum}`), and `air.convert`. //! -//! Exact sequences are used wherever `GLSL.std.450` differs from Metal: `clz`/`ctz` from -//! `FindUMsb`/`FindILsb` with the zero case, `rotate` and the funnel shifts with an in-range -//! second shift (`(x >> 1) >> (N - 1 - s)`), `round` (half away from zero) from `Trunc`, `mix` -//! as Metal computes it where the device's functions are Metal's (on `float` and `half` -//! `fma(t, y, fma(-t, x, x))` by the profile's fused multiply-add route, `metal_mix`; on `bfloat` -//! and `double` `x * (1 - t) + y * t`), and saturating -//! float-to-integer `air.convert` (NaN to 0, out-of-range to the bound, measured on Apple GPUs) -//! with the clamp applied before the conversion so no conversion is out of range. `sign`, `fract`, -//! `saturate`, `median3`, and on `float` and `half` `fmin`, `fmax`, `min3`, `max3`, and `clamp` -//! answer as Metal does at their special operands (zeros, NaNs, infinities, `f32` denormals), which -//! `FSign`, `Fract`, `NClamp`, and `NMin`/`NMax` leave to the device. Where `GLSL.std.450` is a -//! different function from Metal's, Metal's is emitted: `sinpi`, `cospi`, and `tanpi` reduce their -//! argument exactly instead of scaling it by `float(π)`, `fast_tanh` on `float` is the MSL -//! fast-math formula, and the sRGB conversions go -//! through Metal's twelve-bit tables ([`srgb`]). Functions whose Vulkan precision is looser than -//! correct rounding record a `PrecisionNote` at selection. +//! Every float function takes the device's instruction where `GLSL.std.450` or SPIR-V has one: +//! `FAbs`, `FSign`, `Fract`, `NMin`/`NMax`/`NClamp`, `FMix`, `OpDot`, `Sqrt`, `Exp`, `Log`, `Pow`, +//! the trigonometric and hyperbolic families. Where the instruction leaves part of Metal's +//! *definition* open, the lowering states that part and nothing more: `round` rounds halfway cases +//! away from zero from `Trunc` (`GLSL.std.450 Round` leaves the direction to the device), `fract` +//! is bounded below one (Metal's `fmin(x - floor(x), 0x1.fffffep-1)`), `median3` is +//! `min(max(c, min(a, b)), max(a, b))` of `NMin` and `NMax`, `pow` and `atan2` answer C99 Annex +//! F's special cases around `Pow` and `Atan2` (which `GLSL.std.450` leaves undefined there), and +//! float-to-integer `air.convert` saturates (NaN to 0, out-of-range to the bound, measured on +//! Apple GPUs) with the clamp applied before the conversion so no conversion is out of range. +//! Exact integer sequences stand where `GLSL.std.450` differs from Metal: `clz`/`ctz` from +//! `FindUMsb`/`FindILsb` with the zero case, `rotate` and the funnel shifts with an in-range second +//! shift (`(x >> 1) >> (N - 1 - s)`). A function no instruction is takes a composition of the +//! device's instructions: `exp10` and `log10` of `Exp2` and `Log2`, `sinpi`, `cospi` and `tanpi` +//! by an exact period reduction around `Sin` and `Cos`, `ldexp` on the bits, and Metal's fast-math +//! formulas (MSL Table 8.2) for its `fast_` functions. The answers at special operands (a zero's +//! sign, a NaN's bits, an `f32` denormal) are the device's, recorded as precision notes at +//! selection, and so is every function whose Vulkan precision is looser than Metal's. use crate::air::intrinsics::PackFormat; use crate::lower::arith::denormal; @@ -696,19 +698,13 @@ pub enum FloatFn { Round, /// Round half to even. Rint, - /// `x - floor(x)`, below one (`metal_fract`). + /// Metal's `fract`: the device's `Fract`, bounded below one as Metal defines it + /// (`fmin(x - floor(x), 0x1.fffffep-1)`, [`fract_below_one`]). Fract, - /// `air.fast_fract` on `float`: [`FloatFn::Fract`] without the bound below one, and the - /// canonical NaN at an infinity where `infinite_nan` (a call with every fast-math flag), else - /// `+0` as `fract`. - FastFract { - infinite_nan: bool, - }, - /// `air.fract` on `half` with every fast-math flag (Metal has no `fast_` `half` function): - /// [`FloatFn::Fract`], but the largest `half` below one (`0x3BFF`) for a NaN and for an - /// infinity, where `fmin(x - floor(x), 0x3BFF)` loses its NaN to the bound. - FlaggedFract, - /// Metal's `sign` (`metal_sign`), with and without fast math. + /// `air.fast_fract` on `float`: the device's `Fract`, which Metal's fast function does not + /// bound (`fast::fract(-1e-10)` is `1.0`). + FastFract, + /// Metal's `sign`, with and without fast math: the device's `FSign`. Sign, /// Metal's `saturate`, `clamp(x, +0, 1)`: the device's `NClamp(x, 0, 1)`. Saturate, @@ -730,11 +726,14 @@ pub enum FloatFn { MinNum, /// `llvm.maxnum`, as [`FloatFn::MinNum`] for `a > b ? a : b` and [`FloatFn::Max`]. MaxNum, - /// Metal's `median3` (`metal_median3`). + /// Metal's `median3`: `min(max(c, min(a, b)), max(a, b))` of the device's `NMin` and `NMax` + /// ([`median3`]). Median3, - /// `air.fast_fmedian3` on `float`: [`FloatFn::Median3`], except that two NaN first operands - /// give the second. + /// `air.fast_fmedian3` on `float`: [`FloatFn::Median3`]'s form, where Metal's answers `b` for + /// two NaN first operands, which the device's picks leave to it. FastMedian3, + /// `mix(x, y, t)`: the device's `FMix` on `float` and `half`, and on `bfloat` and `double` + /// the blend `x * (1 - t) + y * t`. Mix, Ldexp, /// `llvm.fmuladd` on `bfloat` and `double`: fused or not, as the implementation chooses. @@ -754,6 +753,7 @@ pub enum FloatFn { /// Metal's precise `fmod`: exact (Table 8.1), `fmod(x, ±inf) = x`. On `float` and `half` its /// routine, but where the device's `OpFRem` is Metal's `fmod` ([`libm::Fun::device_answers`]). Fmod, + /// `dot`: the device's `OpDot`. Dot, // Device precision (`PrecisionNote::DeviceTranscendentals`). /// Metal's precise `rsqrt`: correctly rounded (Table 8.1); as [`FloatFn::Sqrt`]. @@ -761,25 +761,21 @@ pub enum FloatFn { /// `air.fast_rsqrt` on `float`: Metal's fast `rsqrt`, within 2 ulp (Table 8.2); the device's /// `InverseSqrt`. FastRsqrt, - /// `air.fast_sqrt` on `float`: `x · rsqrt(x)` as Metal composes it, with Metal's zeros and - /// `+inf` (`fast_sqrt_of`). + /// `air.fast_sqrt` on `float`: the device's `Sqrt`, where Metal's is `x · rsqrt(x)`. FastSqrt, - /// Metal's precise `exp`: within 4 ulp (MSL Table 8.1). On `float` and `half`, where the - /// device's functions are Metal's in a module compiled with precise functions, the device's - /// instruction; elsewhere Metal's own composition of the device's `exp2` (as - /// [`FloatFn::Exp10`], `metal_exp`). + /// Metal's precise `exp`: within 4 ulp (MSL Table 8.1). The device's `Exp`. Exp, /// `air.fast_exp` on `float`: `exp2(x · log2(e))` as Metal composes it, the product rounded, /// of Metal's `exp2` ([`FloatFn::Exp2`]). FastExp, /// Metal's `exp2`, the same function in both modes: the device's instruction. Exp2, - /// Metal's precise `exp10`: Metal's own composition of the device's `exp2` (`metal_exp`), as no + /// Metal's precise `exp10`: Metal's own composition of the device's `exp2` ([`exp10`]), as no /// instruction is it. Exp10, /// `air.fast_exp10` on `float`: `exp2(x · log2(10))` (MSL Table 8.2), the product rounded. FastExp10, - /// Metal's precise `log`; as [`FloatFn::Exp`]. + /// Metal's precise `log`: within 4 ulp. The device's `Log`. Log, /// `air.fast_log` on `float`: `log2(x) · ln(2)` as Metal composes it, the product rounded, /// of Metal's `log2` ([`FloatFn::Log2`]): every lane of case f6524207. @@ -1004,28 +1000,27 @@ impl FloatFn { /// Whether the lowering answers Metal at `f32` denormal operands and results itself, whatever /// 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 - /// result. The arc tangent family (`asin`, `acos`, and `atan`, both modes), precise `sin`, - /// `cos`, and `tan`, `sinpi`, `cospi`, and `tanpi`, and the second stage's functions are listed - /// where the device's instruction is Metal's own function; where it is not, the call records - /// the device's denormals with its precision (`PrecisionNote::NativeTranscendentals`). - /// `fast::sin`, `fast::cos`, and `fast::tan` keep a denormal operand as Metal does, where RADV, - /// ANV, and NVIDIA flush it (case cc234732), and the fast formulas' steps have no denormal - /// intermediate on which their result depends (`fast::sinh` of a denormal is - /// `(1 - 1) · 0.5 = +0`, as Metal answers, case f6524207). `fast::atan2` does not: its quotient - /// is the device's division, whose operands `denormal::coverage` reads. `round` answers `+0` - /// for every zero it reaches, whatever zero the device's `Trunc` gives a denormal, which - /// Metal's `round` of a denormal is (the denormal probes, both modes); precise `fmod` on - /// `float` is the remainder's routine, which reads a denormal divisor as a zero on the bits and - /// computes the remainder in integers (`libm::fmod`), or on MoltenVK Metal's own. + /// no `PrecisionNote::DeviceDenormals` of its own: `atan2`, which flushes a denormal generic + /// result, `ldexp` (on `float`, [`ldexp_bits`]), which reads a denormal operand as the zero of + /// its sign and flushes a denormal result on the bits, `copysign`, which moves bits, and precise + /// `fmod` on `float`, the remainder's routine, which reads a denormal divisor as a zero on the + /// bits and computes the remainder in integers (`libm::fmod`), or on MoltenVK Metal's own; + /// `fmin`, `fmax`, `min3`, `max3`, `clamp`, `saturate` and `median3`, the device's `NMin`, + /// `NMax` and `NClamp`, whose comparison of a denormal is Metal's where measured + /// (`DriverDeviation::MetalMinMax`, but in `median3`) and else `PrecisionNote::NativeMinMax`'s + /// bound; `round`, + /// whose every denormal operand rounds to a zero, its sign the note's + /// (`PrecisionNote::NativeTranscendentals`); and the device's instructions for Metal's + /// functions: `fabs`, `sign`, `fract` and `fast::sqrt` ([`FloatFn::native_instruction`]), the + /// arc tangent family (`asin`, `acos`, and `atan`, both modes), precise `sin`, `cos`, and + /// `tan`, `sinpi`, `cospi`, and `tanpi`, and the second stage's functions, Metal's own where the + /// device's functions are Metal's, and elsewhere recording the device's denormals with their + /// precision (`PrecisionNote::NativeTranscendentals`). `fast::sin`, `fast::cos`, and + /// `fast::tan` keep a denormal operand as Metal does, where RADV, ANV, and NVIDIA flush it (case + /// cc234732), and the fast formulas' steps have no denormal intermediate on which their result + /// depends (`fast::sinh` of a denormal is `(1 - 1) · 0.5 = +0`, as Metal answers, case + /// f6524207). `fast::atan2` does not: its quotient is the device's division, whose operands + /// `denormal::coverage` reads. pub fn metal_denormals(self) -> bool { use FloatFn as F; matches!( @@ -1038,8 +1033,7 @@ impl FloatFn { | F::FastSqrt | F::Saturate | F::Fract - | F::FastFract { .. } - | F::FlaggedFract + | F::FastFract | F::Median3 | F::FastMedian3 | F::Min @@ -1094,27 +1088,36 @@ impl FloatFn { ) } - /// Whether the device's order (`Lib::orders_natively`) answers the function by the device's - /// instruction where Metal's answer is computed around one: - /// `fast::sqrt`, the device's `Sqrt`, where Metal's is `x · rsqrt(x)` with its own answers at - /// a zero, a denormal and `+inf` ([`fast_sqrt_of`]). + /// Whether the call takes the device's instruction for one of Metal's functions that no + /// `libm::Fun` names, which is Metal's own function where the device's functions are Metal's + /// (SPIRV-Cross writes Metal's `fabs`, `sign`, `fract` and `sqrt`), and elsewhere answers its + /// special operands as the device does: `fabs` (`FAbs`), `sign` (`FSign`), `fract` and + /// `fast::fract` (`Fract`), and `fast::sqrt` (`Sqrt`, where Metal's is `x · rsqrt(x)`). pub fn native_instruction(self) -> bool { - matches!(self, FloatFn::FastSqrt) + matches!( + self, + FloatFn::FastSqrt | FloatFn::Abs | FloatFn::Sign | FloatFn::Fract | FloatFn::FastFract + ) } - /// Whether the lowering on lanes of format `fmt` answers Metal's NaN bit pattern itself, so it - /// 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`). + /// Whether the lowering composes the function of the device's instructions on every device, + /// Metal's own instruction left aside: `round`, half away from zero from the device's `Trunc` + /// (`GLSL.std.450 Round` leaves the direction to the device), whose zero is `-0` for a + /// negative operand that rounds to it (C99's), where Metal answers `+0` + /// (`PrecisionNote::NativeTranscendentals`). + pub fn composed_on_every_device(self) -> bool { + self == FloatFn::Round + } + + /// Whether the lowering on lanes of format `fmt` records no NaN note of its own: the functions + /// that select their NaN (or answer a number for one: `saturate`, `fast::sin`, `fast::cos`), + /// `copysign`, which moves bits, `sign`, whose NaN answer is its instruction's + /// ([`FloatFn::native_instruction`]), and the device's picks, `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). pub fn metal_nans(self, fmt: FloatFmt) -> bool { use FloatFn as F; - if self == F::Abs { - return sign_on_bits(Some(fmt)); - } if matches!(self, F::Min | F::Max | F::Clamp | F::Min3 | F::Max3) { return metal_picks(Some(fmt)); } @@ -1122,9 +1125,6 @@ impl FloatFn { self, F::Sign | F::Saturate - | F::Fract - | F::FastFract { .. } - | F::FlaggedFract | F::Median3 | F::FastMedian3 | F::CopySign @@ -1166,7 +1166,7 @@ impl FloatFn { /// rounding (it is an operand, a constant of the format, or an integral value of one). /// `fract` is not: `x - floor(x)` of a negative non-integral `x` can need more bits than /// the format has (half `-0.300048828125` gives `0.699951171875`), so it rounds once, before - /// its bound (`metal_fract`). + /// its bound ([`fract_below_one`]). pub fn closed_on_narrow(self) -> bool { use FloatFn as F; matches!( @@ -1196,27 +1196,14 @@ impl FloatFn { /// narrow form. pub fn words(self, f: Form) -> u32 { let half = f.float_fmt() == Some(FloatFmt::Half); - let base = match metal_half(self, f) { - // `half_tanh`: the quotient's operands and product, and the far operands' test and - // signed one. - FloatFn::Tanh if half => 160, - // Metal's other `half` functions by its fast compositions (`metal_half`), and a - // scalar's constants of the rounding. - FloatFn::FastExp - | FloatFn::FastExp10 - | FloatFn::FastLog - | FloatFn::FastLog2 - | FloatFn::FastLog10 - if half => - { - 128 - } - FloatFn::FastSinh | FloatFn::FastCosh if half => 144, - FloatFn::Sign | FloatFn::Saturate | FloatFn::Fract | FloatFn::FastFract { .. } => 96, - // `fract`, and the operand's exponent test and the bound's select. - FloatFn::FlaggedFract => 128, - // The steps and the `+0` of a zero result. - FloatFn::Round => 128, + let base = match half_form(self, f) { + // A `half` `exp10` and `log10` by the product with the device's `exp2` and `log2` + // (`half_form`), and a scalar's constants of the rounding. + FloatFn::FastExp10 | FloatFn::FastLog10 if half => 128, + // The device's `Fract`, the comparison with one and the bound's select. + FloatFn::Fract => 64, + // The truncation, the difference's test against one half and the step away from zero. + FloatFn::Round => 112, // The device's function and the operands' tests where Metal answers NaN, the precise // sign's on the bits, each operand classified once. FloatFn::Powr => 208, @@ -1225,9 +1212,8 @@ impl FloatFn { FloatFn::FastPowr => 208 + INFINITE_PRODUCT_WORDS, // Metal's formulas of its fast `exp`, of two of the device's `exp2`. FloatFn::FastSinh | FloatFn::FastCosh => 112, - // Two selects per step for the operand and its compared value, and each operand's - // flush test. - FloatFn::Median3 | FloatFn::FastMedian3 => 192, + // The device's four picks. + FloatFn::Median3 | FloatFn::FastMedian3 => 64, // Metal's pick: the operands' NaN tests (the bits, 6 instructions each, where the // entry does not preserve NaNs), the comparison, and two selects per step, and each // operand's flush test. @@ -1243,8 +1229,6 @@ impl FloatFn { FloatFn::FastSin | FloatFn::FastCos => 48, // Both flushes, the denormal operand's select, and the device's division. FloatFn::FastTan => 176, - // The product and Metal's zeros and infinity. - FloatFn::FastSqrt => 96, // The special operands' tests and the selected constant's sign. FloatFn::Atan2 => 320, // The quotient, its special values and sign, and the turn. @@ -1265,28 +1249,27 @@ impl FloatFn { FloatFn::FastTanh => 96, // `1 ± x`, the device's division, and the halving. FloatFn::FastAtanh => 112, - // Metal's composition where its `exp2` is the device's (`metal_exp`): five products - // and sums, two fused ones, the device's `exp2`, and the ends' tests: 136 words on + // `exp10`'s composition of the device's `exp2` (`exp10`): five products and + // sums, two fused ones, the device's `exp2`, and the ends' tests: 136 words on // `float4`. - FloatFn::Exp | FloatFn::Exp10 => 128, - // Metal's composition where its `log2` is the device's (`metal_log`): the device's - // `log2` and the product, the polynomial's fused steps, and the range test. - FloatFn::Log | FloatFn::Log10 => 200, + FloatFn::Exp10 => 128, + // `log10`'s composition of the device's `log2` (`log10`): the device's `log2` and + // the product, the polynomial's fused steps, and the range test. + FloatFn::Log10 => 200, // The exponent's clamp and the bits' fields, tests and selects (`ldexp_bits`). FloatFn::Ldexp => 160, _ => 48, }; // Each function the call takes: the device's instruction, or precise `fmod`'s routine's // calls, one per lane (the routine itself is the module's). A `half` function's zero - // select (`half_zero`), its operand below a magnitude (`half_small`), `half` `cospi`'s - // zero sign (`half_cospi_zero`), and `half` `asin`'s NaN sign (`half_signed_nan`). + // select (`half_zero`), `half` `cospi`'s zero sign (`half_cospi_zero`), and `half` + // `asin`'s NaN sign (`half_signed_nan`). let base = base + libm::uses(self, f) .iter() .map(|r| libm::use_words(f.lanes, r.arity())) .sum::() + half_zero(self, f).map_or(0, |_| 24) - + half_small(self, f).map_or(0, |_| 40) + if half && self == FloatFn::CosPi { 96 } else { @@ -1305,28 +1288,24 @@ 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 `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`). +/// where the module defines it. A `half` `fmod` answers Metal's zero remainder +/// (`half_fmod_zero`). pub fn float_fn( fb: &mut FunctionBuilder<'_>, op: FloatFn, f: Form, contract: Contraction, - test: NanTest, args: &[Value], lib: &Lib, ) -> BResult { use FloatFn as F; - let r = float_fn_core(fb, op, f, contract, test, args, lib)?; + let r = float_fn_core(fb, op, f, contract, args, lib)?; let r = match op { _ if op.closed_on_narrow() => r, - // The device's order: a `half` `mix`, the device's `FMix` in `float`, rounds once. - F::Mix if f.float_fmt() == Some(FloatFmt::Half) && lib.orders_natively() => { - narrow::round(fb, f, r)? - } + // A `half` `mix`, the device's `FMix` in `float`, rounds once. + F::Mix if f.float_fmt() == Some(FloatFmt::Half) => narrow::round(fb, f, r)?, // Rounded per step below. - F::Mix | F::MulAdd | F::Fract | F::FastFract { .. } | F::FlaggedFract => r, + F::Mix | F::MulAdd | F::Fract | F::FastFract => r, F::Dot => narrow::round(fb, f.scalar_form(), r)?, F::Fmod => { let r = narrow::round(fb, f, r)?; @@ -1338,10 +1317,6 @@ pub fn float_fn( Some(zero) => half_zero_answer(fb, f, zero, arg(args, 0)?, r)?, None => r, }; - let r = match half_small(op, f) { - Some(limit) => half_small_answer(fb, f, limit, arg(args, 0)?, r)?, - None => r, - }; let r = if f.float_fmt() == Some(FloatFmt::Half) && op == F::CosPi { half_cospi_zero(fb, f, arg(args, 0)?, r)? } else { @@ -1354,90 +1329,22 @@ pub fn float_fn( } } -/// The `float` function whose answer, rounded to `half`, is Metal's `half` function `op` on form -/// `f`, where that is not `op`'s own (`op` otherwise, and on another format): Metal's `half` -/// `exp`, `exp10`, `log`, `log2`, `log10`, `cosh`, `pow`, and `powr` are its fast `float` -/// functions of the widened operands, rounded, and so is its `sinh` from `2^-12` -/// (`half_small`). Each is Metal's word at every `half` operand of our probe (the M3; the -/// M4's words, are the same), `pow` and `powr` at each of 65,536 operand pairs, -/// and the precise function is not at 2 operands of `cosh`, 3 pairs of `pow` and `powr`, and 4 -/// operands of `sinh`, whose fast one is again Metal's with the translation's `exp2` and `log2` -/// in place of Metal's. Its `tanh` is `half_tanh`, and its `atan`, `atan2`, `tan`, `sin`, `cos`, -/// and `asinh` are its own `half` forms, which no `float` function rounds to: the device's `float` -/// function rounded answers them at the device's precision (`libm::uses`). -pub(crate) fn metal_half(op: FloatFn, f: Form) -> FloatFn { +/// The `float` function a `half` call of `op` (form `f`, held in `float`) takes before its +/// rounding, where that is not `op` itself (`op` otherwise, and on another format): `exp10` and +/// `log10`, which no instruction is, are the device's `exp2` and `log2` of the product with +/// `log2(10)` and `log10(2)` (`FastExp10`, `FastLog10`), as `float`'s fast forms are. Every other +/// `half` function is its `float` function's instruction (or composition), rounded. +pub(crate) fn half_form(op: FloatFn, f: Form) -> FloatFn { if f.float_fmt() != Some(FloatFmt::Half) { return op; } match op { - FloatFn::Exp => FloatFn::FastExp, FloatFn::Exp10 => FloatFn::FastExp10, - FloatFn::Log => FloatFn::FastLog, - FloatFn::Log2 => FloatFn::FastLog2, FloatFn::Log10 => FloatFn::FastLog10, - FloatFn::Sinh => FloatFn::FastSinh, - FloatFn::Cosh => FloatFn::FastCosh, - FloatFn::Pow => FloatFn::FastPow, - FloatFn::Powr => FloatFn::FastPowr, _ => op, } } -/// Metal's `half` `tanh(x)` on `half` lanes `x` (form `f`, held in `f32`) before its rounding: -/// `(t - 1) · rcp(t + 1)` of `t = exp2(x · RN(2 log2 e))`, MSL Table 8.2's `fast::tanh` of -/// Metal's `exp2` and reciprocal (the device's `Exp2` and division), and `±1` from `|x| = 16`, -/// where the answer rounds to `±1` (the quotient is a NaN past `x ≈ 44`, where Metal's `half` -/// `tanh` is `1`). Below `2^-13` the operand itself (`half_small`). Every `half` of our probes is -/// this, with the device's `exp2` and reciprocal in place of Metal's; Metal's precise `float` -/// `tanh`, rounded, is not at 7 of them, nor its fast one, rounded, below `2^-13` and past `44`. -fn half_tanh(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { - let exact = Contraction::Forbidden; - let k = wide_splat(fb, f, 2.0 * std::f64::consts::LOG2_E)?; - let p = fb.binary_with(BinOp::FMul, x, k, exact)?; - let t = glsl(fb, GlslOp::Exp2, &[p])?; - let one = wide_splat(fb, f, 1.0)?; - let num = fb.binary_with(BinOp::FSub, t, one, exact)?; - let den = fb.binary_with(BinOp::FAdd, t, one, exact)?; - let r = fb.binary_with(BinOp::FDiv, one, den, exact)?; - let q = fb.binary_with(BinOp::FMul, num, r, exact)?; - let ax = glsl(fb, GlslOp::FAbs, &[x])?; - let limit = wide_splat(fb, f, 16.0)?; - let far = bin(fb, BinOp::FOrdGreaterThanEqual, ax, limit)?; - let unit = copysign(fb, f, one, x)?; - fb.select(far, unit, q) -} - -/// The magnitude below which Metal's `half` function `op` (form `f`) answers its operand -/// itself, where the `float` function it rounds does not: `sinh` below `2^-12` and `tanh` below -/// `2^-13`, where `fast::sinh(x)` and `fast::tanh(x)`, of a difference of nearly equal -/// exponentials, lose the operand's low bits and the exact value rounds to the operand (every -/// such `half` of our probes). `None` for another function or format. -fn half_small(op: FloatFn, f: Form) -> Option { - if f.float_fmt() != Some(FloatFmt::Half) { - return None; - } - match op { - FloatFn::Sinh => Some(2f64.powi(-12)), - FloatFn::Tanh => Some(2f64.powi(-13)), - _ => None, - } -} - -/// `r`, the answer of a `half` function of `x` (form `f`), with `x` itself where `|x|` is below -/// `limit` (`half_small`). -fn half_small_answer( - fb: &mut FunctionBuilder<'_>, - f: Form, - limit: f64, - x: Value, - r: Value, -) -> BResult { - let ax = glsl(fb, GlslOp::FAbs, &[x])?; - let l = fsplat(fb, f, limit)?; - let small = bin(fb, BinOp::FOrdLessThan, ax, l)?; - fb.select(small, x, r) -} - /// `r`, Metal's `half` `cospi(x)` (form `f`), with its zero's sign: at `x = n + 1/2` Metal /// answers `-0` where `n = floor(x)` is even and `+0` where it is odd, the sign of /// `-sinpi(x - 1/2)` of its `half` `sinpi`, whose zero at an odd integer is `-0` (each of the @@ -1538,31 +1445,28 @@ fn float_fn_core( op: FloatFn, f: Form, contract: Contraction, - test: NanTest, args: &[Value], lib: &Lib, ) -> BResult { use FloatFn as F; let a = arg(args, 0)?; - // Metal's `half` functions, by the `float` function whose rounded answer each is. - if f.float_fmt() == Some(FloatFmt::Half) && op == F::Tanh { - return half_tanh(fb, f, a); - } - let op = metal_half(op, f); + let op = half_form(op, f); let g1 = |fb: &mut FunctionBuilder<'_>, o: GlslOp| glsl(fb, o, &[a]); let times = |fb: &mut FunctionBuilder<'_>, k: f64| -> BResult { let c = wide_splat(fb, f, k)?; bin(fb, BinOp::FMul, a, c) }; match op { - F::Abs if sign_on_bits(f.float_fmt()) => sign_bits(fb, f, a, SignBit::Clear), F::Abs => g1(fb, GlslOp::FAbs), F::Floor => g1(fb, GlslOp::Floor), F::Ceil => g1(fb, GlslOp::Ceil), F::Trunc => g1(fb, GlslOp::Trunc), F::Rint => g1(fb, GlslOp::RoundEven), F::Round => { - // t = trunc(x); |x - t| >= 0.5 ? t + (x < 0 ? -1 : 1) : t. `x - t` is exact. + // Metal's definition, halfway cases away from zero, which `GLSL.std.450 Round` leaves + // to the device: t = trunc(x); |x - t| >= 0.5 ? t + (x < 0 ? -1 : 1) : t. `x - t` is + // exact. A zero is the device's `Trunc`'s, `-0` below zero (C99's), where Metal + // answers `+0`. let t = g1(fb, GlslOp::Trunc)?; let d = bin(fb, BinOp::FSub, a, t)?; let d = glsl(fb, GlslOp::FAbs, &[d])?; @@ -1573,16 +1477,11 @@ fn float_fn_core( let (m1, p1) = (fsplat(fb, f, -1.0)?, fsplat(fb, f, 1.0)?); let step = fb.select(neg, m1, p1)?; let away = bin(fb, BinOp::FAdd, t, step)?; - let r = fb.select(up, away, t)?; - positive_zero(fb, f, r) + fb.select(up, away, t) } - F::Fract => metal_fract(fb, f, a, true, false), - F::FastFract { infinite_nan } => metal_fract(fb, f, a, false, infinite_nan), - F::FlaggedFract => { - let r = metal_fract(fb, f, a, true, false)?; - nonfinite_below_one(fb, f, a, r) - } - F::Sign => metal_sign(fb, f, a), + F::Fract => fract_below_one(fb, f, a), + F::FastFract => g1(fb, GlslOp::Fract), + F::Sign => g1(fb, GlslOp::FSign), // 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. @@ -1602,17 +1501,9 @@ fn float_fn_core( let r = glsl(fb, o, &[a, arg(args, 1)?])?; glsl(fb, o, &[r, arg(args, 2)?]) } - F::Median3 | F::FastMedian3 => { - let (b, c) = (arg(args, 1)?, arg(args, 2)?); - metal_median3(fb, f, test, [a, b, c], op == F::FastMedian3) - } - // `float` and `half` take Metal's fused form ([`metal_mix`]) where the device's functions - // are Metal's, a strategy of its own; the device's order takes the device's `FMix` - // (`PrecisionNote::NativeMix`). + F::Median3 | F::FastMedian3 => median3(fb, [a, arg(args, 1)?, arg(args, 2)?]), + // The device's `FMix` (`PrecisionNote::NativeMix`). F::Mix if matches!(f.float_fmt(), Some(FloatFmt::F32 | FloatFmt::Half)) => { - if !lib.orders_natively() { - return Err(BuildError::Type(TypeRule::FunctionSignature)); - } glsl(fb, GlslOp::FMix, &[a, arg(args, 1)?, arg(args, 2)?]) } F::Mix => { @@ -1654,29 +1545,15 @@ fn float_fn_core( F::Dot => bin(fb, BinOp::Dot, a, arg(args, 1)?), F::Rsqrt => g1(fb, GlslOp::InverseSqrt), F::FastRsqrt => g1(fb, GlslOp::InverseSqrt), - // The device's order: its `Sqrt`. - F::FastSqrt if lib.orders_natively() => g1(fb, GlslOp::Sqrt), - F::FastSqrt => { - let r = g1(fb, GlslOp::InverseSqrt)?; - fast_sqrt_of(fb, f, a, r) - } - // A device whose functions are Metal's answers precise `exp` in a precise module; - // elsewhere Metal's own composition of the device's `exp2` does. - F::Exp if f.float_fmt() == Some(FloatFmt::F32) && !lib.metal_in(libm::Mode::Precise) => { - metal_exp(fb, f, a, std::f64::consts::LOG2_E) - } + F::FastSqrt => g1(fb, GlslOp::Sqrt), F::Exp => g1(fb, GlslOp::Exp), F::Exp2 => g1(fb, GlslOp::Exp2), - // Likewise precise `log`: elsewhere Metal's composition of the device's `log2`. - F::Log if f.float_fmt() == Some(FloatFmt::F32) && !lib.metal_in(libm::Mode::Precise) => { - metal_log(fb, f, a, &libm::LOG_NEAR, libm::LN_2_BITS) - } F::Log => g1(fb, GlslOp::Log), F::Log2 | F::FastLog2 => g1(fb, GlslOp::Log2), // No instruction is Metal's `exp10` or `log10`: Metal's own compositions of the device's // `exp2` and `log2`. - F::Exp10 => metal_exp(fb, f, a, std::f64::consts::LOG2_10), - F::Log10 => metal_log(fb, f, a, &libm::LOG10_NEAR, libm::LOG10_2_BITS), + F::Exp10 => exp10(fb, f, a), + F::Log10 => log10(fb, f, a), // Metal's fast compositions of its `exp2` and `log2` (MSL Table 8.2). F::FastExp | F::FastExp10 => { let k = if op == F::FastExp { @@ -1821,47 +1698,6 @@ fn copysign(fb: &mut FunctionBuilder<'_>, f: Form, a: Value, b: Value) -> BResul fb.convert(ConvOp::Bitcast, r, ft) } -/// Whether `fneg` and `fabs` on lanes of format `fmt` move the sign as an integer on the bits -/// ([`sign_bits`]): on `float`, where Metal flips or clears the sign bit alone, a NaN keeping its -/// payload and a denormal kept, with and without fast-math flags (`nan_signbits`, -/// `nan_signbits_fast`, every lane). The devices' `OpFNegate` and `FAbs` differ there: RADV's -/// `fneg` keeps a NaN's sign, NVIDIA's `fabs` answers `0x7FFFFFFF`, and RADV and ANV flush a -/// denormal. A `half` is held widened and its `fneg` and `fabs` answer the canonical `half` NaN -/// (class D); `bfloat` and `double` are not measured. -pub fn sign_on_bits(fmt: Option) -> bool { - fmt == Some(FloatFmt::F32) -} - -/// What [`sign_bits`] does to the sign bit. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum SignBit { - /// `fneg`. - Flip, - /// `fabs`. - Clear, -} - -/// `x` (floats of form `f`, `f32` lanes) with its sign bit flipped or cleared as an integer on -/// the bits, whatever the device's float modes: Metal's `float` `fneg` and `fabs` -/// ([`sign_on_bits`]). -pub fn sign_bits(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, op: SignBit) -> BResult { - let u = u32_form(f); - let ut = ty(fb, u)?; - let bits = fb.convert(ConvOp::Bitcast, x, ut)?; - let r = match op { - SignBit::Flip => { - let sign = splat(fb, u, 0x8000_0000)?; - bin(fb, BinOp::BitwiseXor, bits, sign)? - } - SignBit::Clear => { - let magnitude = splat(fb, u, 0x7FFF_FFFF)?; - bin(fb, BinOp::BitwiseAnd, bits, magnitude)? - } - }; - let ft = ty(fb, f)?; - fb.convert(ConvOp::Bitcast, r, ft) -} - /// The constant `k` at the container's precision: an internal constant of a sequence that runs /// in the container (`f32` for a narrow form) before its final rounding. fn wide_splat(fb: &mut FunctionBuilder<'_>, f: Form, k: f64) -> BResult { @@ -1920,24 +1756,6 @@ fn has_bits(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, bits: u64) -> BResu bin(fb, BinOp::IEqual, b, k) } -/// `r` (`round`'s result, floats of form `f`) with `+0` for `-0` on `float` and `half`: Metal's -/// `round` never answers `-0` (`-0.3` and `-0` round to `+0`, precise and fast; `half` in both flag -/// states, `nan_half` and `nan_half_fast`), as `trunc(x)` plus a `+0` step does. Moved in the bits, -/// so no signed-zero mode folds it; `bfloat` keeps `r` (not measured). -fn positive_zero(fb: &mut FunctionBuilder<'_>, f: Form, r: Value) -> BResult { - if !matches!(f.float_fmt(), Some(FloatFmt::F32 | FloatFmt::Half)) { - return Ok(r); - } - let u = u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let b = fb.convert(ConvOp::Bitcast, r, ut)?; - let minus_zero = splat(fb, u, 0x8000_0000)?; - let zero = splat(fb, u, 0)?; - let is = bin(fb, BinOp::IEqual, b, minus_zero)?; - let b = fb.select(is, zero, b)?; - fb.convert(ConvOp::Bitcast, b, ft) -} - /// `r` (a `half` `fmod`'s remainder of `x`, floats of form `f`) with Metal's zero: a zero /// remainder of a nonzero dividend is `+0`, and a zero dividend's is the dividend itself /// (`fmod(-2, 0.5)` is `+0`, `fmod(-0, 1)` is `-0`), with or without fast-math flags @@ -1963,27 +1781,6 @@ fn half_fmod_zero(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, r: Value) -> fb.convert(ConvOp::Bitcast, b, ft) } -/// `r` (a `half` `fract` with every fast-math flag, floats of form `f`) with the largest `half` -/// below one where `x` is a NaN or an infinity, as Metal answers there under fast math -/// (`nan_half_fast`: `0x3BFF` on all 32 NaN and 7 infinite lanes): its `x - floor(x)` is a NaN, and -/// its bound `fmin` returns the other operand. Told by the exponent field, so no float mode folds -/// the test. -fn nonfinite_below_one( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - r: Value, -) -> BResult { - let u = u32_form(f); - let ut = ty(fb, u)?; - let b = fb.convert(ConvOp::Bitcast, x, ut)?; - let exp = splat(fb, u, 0x7F80_0000)?; - let e = bin(fb, BinOp::BitwiseAnd, b, exp)?; - let nonfinite = bin(fb, BinOp::IEqual, e, exp)?; - let bound = splat(fb, f, below_one_bits(f))?; - fb.select(nonfinite, bound, r) -} - /// The classes of `powr`'s operands `x` and `y` (floats of form `f`, a `float` or a `half` in its /// 32-bit container) that its special cases read, each told once from the bits and shared by /// every rule that reads it: each operand's bits and magnitude's, whether it is a zero to Metal (an @@ -2158,128 +1955,32 @@ fn zero_where_flushed(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, r: Value) } } -/// Metal's `sign(x)` (A1 cases 87d13612 and f9a12252, precise and fast alike): `1` above zero, -/// `-1` below it, and `+0` for either zero, a NaN, and an `f32` denormal ([`flushed`]). -/// `GLSL.std.450 FSign` keeps the sign of a zero and leaves a NaN's result undefined. -fn metal_sign(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { - let z = fsplat(fb, f, 0.0)?; - let (m1, p1) = (fsplat(fb, f, -1.0)?, fsplat(fb, f, 1.0)?); - let lt = bin(fb, BinOp::FOrdLessThan, x, z)?; - let r = fb.select(lt, m1, z)?; - let gt = bin(fb, BinOp::FOrdGreaterThan, x, z)?; - let r = fb.select(gt, p1, r)?; - zero_where_flushed(fb, f, x, r) -} - -/// Metal's `fract(x)` (A1 case aed3faaa): `x - floor(x)`, rounded once to a narrow format, then -/// bounded below one (`fmin` with the largest value below one) when `bounded`; `air.fast_fract` -/// on `float` is not bounded (`fast::fract(-1e-10)` is `1.0`). An infinity gives `+0`, or the -/// canonical NaN where `infinite_nan`, and an `f32` zero or denormal gives `+0` ([`flushed`]); a -/// NaN gives the canonical NaN `0x7fc00000` on `float` and itself, bit for bit, on `half` (`0x7c01` -/// stays `0x7c01`). A `bfloat` NaN takes `float`'s answer (not measured). `GLSL.std.450 Fract` of -/// an infinity is NaN. -/// -/// Unbounded, the one is selected outright where `x - floor(x) = 1 + x` rounds to it -/// ([`rounds_to_one_bits`]), not left to the subtraction: Mesa's NIR folds `x - floor(x)` into -/// its `ffract`, which RADV's `v_fract` bounds below one (`0x3f7fffff`). -fn metal_fract( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - bounded: bool, - infinite_nan: bool, -) -> BResult { - // The difference of a narrow value and its floor takes the device's rounding. - let fl = glsl(fb, GlslOp::Floor, &[x])?; - let d = bin(fb, BinOp::FSub, x, fl)?; +/// Metal's `fract(x)`: the device's `Fract`, rounded once to a narrow format, then bounded below +/// one, as Metal defines it (`fmin(x - floor(x), 0x1.fffffep-1)`): the largest value below one of +/// the format wherever the difference reaches one (`-1e-10` gives `1 - 2^-24`, not `1`). The +/// bound is an ordered comparison, so a NaN `Fract` is kept, the device's NaN. An infinity, a NaN +/// and an `f32` denormal answer as the device's `Fract` does (`PrecisionNote::NativeTranscendentals` +/// off Metal's own functions). +fn fract_below_one(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { + // `floor(x)` of a narrow value is a value of the format: the difference takes the device's + // rounding. + let d = glsl(fb, GlslOp::Fract, &[x])?; let d = narrow::round(fb, f, d)?; - let r = if bounded { - let below_one = splat(fb, f, below_one_bits(f))?; - glsl(fb, GlslOp::NMin, &[d, below_one])? - } else { - let (z, one) = (fsplat(fb, f, 0.0)?, fsplat(fb, f, 1.0)?); - let lo = splat(fb, f, rounds_to_one_bits(f))?; - let above = bin(fb, BinOp::FOrdGreaterThanEqual, x, lo)?; - let below = bin(fb, BinOp::FOrdLessThan, x, z)?; - let near = bin(fb, BinOp::LogicalAnd, above, below)?; - fb.select(near, one, d)? - }; - // An infinity's `fract` is `+0`; under every fast-math flag `fast::fract`'s is the canonical - // NaN, its `x - floor(x)`. - let at_inf = if infinite_nan { - fsplat(fb, f, f64::NAN)? - } else { - fsplat(fb, f, 0.0)? - }; - let inf = fb.unary(UnOp::IsInf, x)?; - let r = fb.select(inf, at_inf, r)?; - let r = zero_where_flushed(fb, f, x, r)?; - let nan = fb.unary(UnOp::IsNan, x)?; - let n = if f.float_fmt() == Some(FloatFmt::Half) { - x - } else { - fsplat(fb, f, f64::NAN)? - }; - fb.select(nan, n, r) + let one = fsplat(fb, f, 1.0)?; + let reaches = bin(fb, BinOp::FOrdGreaterThanEqual, d, one)?; + let below_one = splat(fb, f, below_one_bits(f))?; + fb.select(reaches, below_one, d) } -/// An operand of [`metal_median3`] with the value it compares as. -#[derive(Clone, Copy)] -struct Compared { - value: Value, - as_: Value, -} - -/// Metal's `min(p, q)` (`less`) or `max(p, q)` of [`metal_median3`]: `p` when `q` is NaN (by -/// `test`), else `p` when it compares `less` (or greater) than `q`, else `q`. -fn pick( - fb: &mut FunctionBuilder<'_>, - f: Form, - test: NanTest, - order: BinOp, - p: Compared, - q: Compared, -) -> BResult { - let q_nan = nan::is_nan(fb, f, test, q.value)?; - let before = bin(fb, order, p.as_, q.as_)?; - let keep = bin(fb, BinOp::LogicalOr, q_nan, before)?; - Ok(Compared { - value: fb.select(keep, p.value, q.value)?, - as_: fb.select(keep, p.as_, q.as_)?, - }) -} - -/// Metal's `median3(a, b, c)` (A1 case aed3faaa, every lane of precise `float`, fast `float`, -/// and `half`): `min(max(c, min(a, b)), max(a, b))` with Metal's `min` and `max` ([`pick`]), so -/// the result is always one of the operands, bit for bit (a zero keeps its sign, a NaN its -/// payload). `float` compares the operands [`flushed`] (an `f32` denormal compares as a zero) -/// but returns the operand itself. `air.fast_fmedian3` (`fast`) returns `b` when `a` and `b` -/// are both NaN. `NMin`/`NMax` order a NaN differently and may give either zero. -fn metal_median3( - fb: &mut FunctionBuilder<'_>, - f: Form, - test: NanTest, - [a, b, c]: [Value; 3], - fast: bool, -) -> BResult { - let compared = |fb: &mut FunctionBuilder<'_>, x: Value| -> BResult { - Ok(Compared { - value: x, - as_: zero_where_flushed(fb, f, x, x)?, - }) - }; - let (ca, cb, cc) = (compared(fb, a)?, compared(fb, b)?, compared(fb, c)?); - let lo = pick(fb, f, test, BinOp::FOrdLessThan, ca, cb)?; - let hi = pick(fb, f, test, BinOp::FOrdGreaterThan, ca, cb)?; - let m = pick(fb, f, test, BinOp::FOrdGreaterThan, cc, lo)?; - let r = pick(fb, f, test, BinOp::FOrdLessThan, m, hi)?.value; - if !fast { - return Ok(r); - } - let a_nan = nan::is_nan(fb, f, test, a)?; - let b_nan = nan::is_nan(fb, f, test, b)?; - let both = bin(fb, BinOp::LogicalAnd, a_nan, b_nan)?; - fb.select(both, b, r) +/// Metal's `median3(a, b, c)`: `min(max(c, min(a, b)), max(a, b))` of the device's `NMin` and +/// `NMax`, so the result is one of the operands, picked as the device's `NMin` and `NMax` pick +/// (`PrecisionNote::NativeMinMax` on every device: of two NaNs, and of an `f32` denormal, the +/// device's pick). +fn median3(fb: &mut FunctionBuilder<'_>, [a, b, c]: [Value; 3]) -> BResult { + let lo = glsl(fb, GlslOp::NMin, &[a, b])?; + let hi = glsl(fb, GlslOp::NMax, &[a, b])?; + let m = glsl(fb, GlslOp::NMax, &[c, lo])?; + glsl(fb, GlslOp::NMin, &[m, hi]) } /// Whether Metal's `fmin` and `fmax` family is measured on lanes of format `fmt`: `float` @@ -2437,83 +2138,6 @@ pub(super) fn fast_fmod( fma(fb, &[n, y, x]) } -/// Metal's precise `mix(x, y, t)` on `float` and `half`: `fma(t, y, fma(-t, x, x))`, each fused -/// multiply-add rounding once (`fma`, the profile's route), with and without fast-math flags. Every -/// lane of `nan_functions`, `nan_functions_fast`, `nan_half`, and `nan_half_fast` whose answer is a -/// number is this expression, where the blend `x * (1 - t) + y * t` misses lanes (`mix(inf, 1, 0)` -/// is NaN: `fma(-0, inf, inf)`; `mix(-0, -0, 0)` is `+0`; `half` `mix(-0.3, 0.7, 0.2)` is -/// `0xAE68`). `t` is negated on its bits, which no float mode changes. Each fused multiply-add -/// reads an `f32` denormal operand as the zero of its sign and flushes a denormal result (an Apple -/// M3 Max under macOS 27.0.1: every finite triple of 28 patterns, denormals among them, in both -/// modes). -pub(super) fn metal_mix( - fb: &mut FunctionBuilder<'_>, - f: Form, - [x, y, t]: [Value; 3], - fma: FmaOf<'_>, -) -> BResult { - let minus_t = sign_bits(fb, f, t, SignBit::Flip)?; - let rest = fma(fb, &[minus_t, x, x])?; - fma(fb, &[t, y, rest]) -} - -/// Metal's `dot(x, y)` on `float` or `half` vectors of form `f`: the products summed lane by lane -/// in one fused chain, `fma(x[n-1], y[n-1], ... fma(x[1], y[1], x[0] * y[0]))`, the first product -/// rounded to `f`'s format on its own and each later lane added by one fused multiply-add (`fma`, -/// the profile's route), with and without fast-math flags. On 4,096 lanes of two, three and four -/// lanes each, in both modes, every `float` and `half` answer of the M3 Max and the M4 is this -/// chain's (a `half` keeps its denormals). -pub(super) fn metal_dot( - fb: &mut FunctionBuilder<'_>, - f: Form, - [x, y]: [Value; 2], - fma: FmaOf<'_>, -) -> BResult { - let lane = |fb: &mut FunctionBuilder<'_>, i: u32| -> BResult<(Value, Value)> { - if f.lanes == 1 { - Ok((x, y)) - } else { - Ok(( - fb.composite_extract(x, &[i])?, - fb.composite_extract(y, &[i])?, - )) - } - }; - metal_chain(fb, f.scalar_form(), u32::from(f.lanes), &lane, fma) -} - -/// Lane `i`'s two operands of a dot product. -pub(super) type LaneOf<'a> = &'a dyn Fn(&mut FunctionBuilder<'_>, u32) -> BResult<(Value, Value)>; - -/// [`metal_dot`]'s fused chain over `lanes` lanes of scalar form `s`, lane `i`'s operands by -/// `lane`, each taken as the chain reaches it. -pub(super) fn metal_chain( - fb: &mut FunctionBuilder<'_>, - s: Form, - lanes: u32, - lane: LaneOf<'_>, - fma: FmaOf<'_>, -) -> BResult { - let (x0, y0) = lane(fb, 0)?; - // A `half` product is exact in its `float` container, and rounded once. - let p = fb.binary_no_contraction(BinOp::FMul, x0, y0)?; - let mut sum = narrow::round(fb, s, p)?; - for i in 1..lanes { - let (xi, yi) = lane(fb, i)?; - sum = fma(fb, &[xi, yi, sum])?; - } - Ok(sum) -} - -/// An upper estimate of the SPIR-V words of [`metal_dot`] on form `f` whose fused multiply-adds -/// take `fma_words` each: two extractions per lane, the product and its rounding, and per later -/// lane the fused multiply-add. -pub(super) fn metal_dot_words(f: Form, fma_words: u32) -> u32 { - let s = f.scalar_form(); - let lanes = u32::from(f.lanes); - (10 * lanes + 5 + narrow::round_words(s)).saturating_add(lanes.saturating_sub(1) * fma_words) -} - /// Which of Metal's pi-scaled functions [`pi_scaled`] computes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum PiScaled { @@ -2704,16 +2328,15 @@ pub(super) fn infinite_product( fb.select(infinite, answer, r) } -/// Metal's precise `exp10(x)` (`c` is `log2(10)`) or `exp(x)` (`log2(e)`) from the device's -/// `exp2` (floats of form `f` in a 32-bit container, the constants the container's), as Metal -/// composes it: `E = exp2(p)` of the rounded product `p = x c_hi`, `c_hi + c_lo = c`, corrected by -/// the product's error `d = fma(x, c_lo, fma(x, c_hi, -p))` as `fma(E, d ln 2, E)`, and `E` itself -/// where it is `+inf` or `+0` (where `x` is infinite `d` is a NaN). Every lane of case 7b283404 -/// on the M3 and the M4 is this of Metal's `exp2`, for both, and so is every normal answer of -/// magnitude `[2^-40, 2^9)` on the M4. Each step is its own: no device fuses or regroups it. -fn metal_exp(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, c: f64) -> BResult { +/// Metal's precise `exp10(x)`, which no instruction is, from the device's `exp2` (floats of form +/// `f` in a 32-bit container, the constants the container's): `E = exp2(p)` of the rounded +/// product `p = x c_hi`, `c_hi + c_lo = log2(10)`, corrected by the product's error +/// `d = fma(x, c_lo, fma(x, c_hi, -p))` as `fma(E, d ln 2, E)`, and `E` itself where it is `+inf` +/// or `+0` (where `x` is infinite `d` is a NaN). Every lane of case 7b283404 on the M3 and the M4 +/// is this of Metal's `exp2`. Each step is its own: no device fuses or regroups it. +fn exp10(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { let exact = Contraction::Forbidden; - let (hi, lo) = libm::split(c); + let (hi, lo) = libm::split(std::f64::consts::LOG2_10); let c_hi = wide_splat(fb, f, f64::from(hi))?; let c_lo = wide_splat(fb, f, f64::from(lo))?; let p = fb.binary_with(BinOp::FMul, x, c_hi, exact)?; @@ -2730,18 +2353,12 @@ fn metal_exp(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, c: f64) -> BResult fb.select(ends, big, r) } -/// Metal's precise `log(x)` or `log10(x)` from the device's `log2` (floats of form `f` in a -/// 32-bit container, the constants the container's), as Metal composes it: its `log2` times `RN(ln -/// 2)` or `RN(log10 2)` (the constant `c`, by its bits), and strictly inside `near`'s range next to -/// 1 its polynomial `RN(t fma(p(t), t, lead))` of `t = x - 1`, by fused steps. Each step is its -/// own: no device fuses or regroups it. -fn metal_log( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - near: &libm::Near, - c: u32, -) -> BResult { +/// Metal's precise `log10(x)`, which no instruction is, from the device's `log2` (floats of form +/// `f` in a 32-bit container, the constants the container's): the `log2` times `RN(log10 2)`, and +/// strictly inside [`libm::LOG10_NEAR`]'s range next to 1 its polynomial `RN(t fma(p(t), t, +/// lead))` of `t = x - 1`, by fused steps. Each step is its own: no device fuses or regroups it. +fn log10(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { + let (near, c) = (&libm::LOG10_NEAR, libm::LOG10_2_BITS); let exact = Contraction::Forbidden; let l = glsl(fb, GlslOp::Log2, &[x])?; let k = wide_splat(fb, f, f64::from(f32::from_bits(c)))?; @@ -2802,26 +2419,6 @@ fn fast_log_of(fb: &mut FunctionBuilder<'_>, f: Form, v: Value) -> BResult, - f: Form, - x: Value, - r: Value, -) -> BResult { - let p = bin(fb, BinOp::FMul, x, r)?; - let inf = wide_splat(fb, f, f64::INFINITY)?; - let at_inf = bin(fb, BinOp::FOrdEqual, x, inf)?; - let p = fb.select(at_inf, inf, p)?; - let zero = metal_zero(fb, f, x)?; - let z = wide_splat(fb, f, 0.0)?; - let signed = copysign(fb, f, z, x)?; - fb.select(zero, signed, p) -} - /// The C99 Annex F (F.9.4.4) special cases of `pow(x, y)` around `magnitude`, the value /// `GLSL.std.450 Pow(|x|, y)` gives, as Metal answers them (A1 case 116e052a, every lane of /// precise `float`, fast `float`, and `half`). Later selects win: @@ -3130,19 +2727,6 @@ fn below_one_bits(f: Form) -> u64 { f.const_bits(1.0 - 2f64.powi(-significand)) } -/// The bits of `-2^-(p + 1)` in `f`'s format of `p` significand bits: the least negative `x` -/// whose `1 + x` rounds to one rather than to the largest value below it (the tie rounds to one's -/// even significand), so every `x` in `[-2^-(p + 1), 0)` has `x - floor(x)` rounded to one. -fn rounds_to_one_bits(f: Form) -> u64 { - let significand = match f.float_fmt() { - Some(FloatFmt::F64) => 53, - Some(FloatFmt::F32) => 24, - Some(FloatFmt::Half) => 11, - _ => 8, - }; - f.const_bits(-(2f64.powi(-(significand + 1)))) -} - /// The (mantissa bits, exponent bias, all-ones exponent) of a float width. pub(super) fn float_layout(bits: u8) -> (u32, i64, i64) { match bits { diff --git a/crates/metal2vulkan/src/lower/arith/mod.rs b/crates/metal2vulkan/src/lower/arith/mod.rs index 42dbc47aa..feab97c7f 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -37,11 +37,10 @@ //! `dot`) or `PrecisionNote::DeviceTranscendentals` (the transcendental functions) to the plan. //! Float arithmetic is emitted in the AIR's order, one instruction per operation, each decorated by //! its own fast-math flags: one carrying both of LLVM's `contract` and `reassoc` is left -//! undecorated, so the device's compiler groups and fuses it as those flags allow; any other (and -//! `mix`'s multiply and add, unless its call carries both) is `NoContraction`, so no device fuses -//! or regroups operations that LLVM keeps apart. Arithmetic the flags let a compiler regroup or -//! fuse with its neighbour, and a `bfloat` or `double` `llvm.fmuladd`, add -//! `PrecisionNote::FastMathRewrites`: its value is any of those the flags allow, and Metal's +//! undecorated, so the device's compiler groups and fuses it as those flags allow; any other is +//! `NoContraction`, so no device fuses or regroups operations that LLVM keeps apart. Arithmetic +//! the flags let a compiler regroup or fuse with its neighbour, and a `bfloat` or `double` +//! `llvm.fmuladd`, add `PrecisionNote::FastMathRewrites`: its value is any of those the flags allow, and Metal's //! compiler may take another than the device's. Every other lowering is exact for every non-poison //! input within the device's floating-point environment: signed zeros, infinities, and NaNs are //! preserved by `SignedZeroInfNanPreserve` where an operation without `nnan`/`ninf`/`nsz` requires @@ -54,10 +53,11 @@ //! `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` for 16 bits and the modes the //! device's independence ties to them: `RoundingModeRTE` for 32 bits on a device whose rounding //! modes are not independent, Metal's own rounding of `float` arithmetic, and for 64 bits the -//! rounding and denormals IEEE 754 gives `double`. `sign`, -//! `fract`, `saturate`, `median3`, and `pow` answer as Metal does at zeros, NaNs, infinities, and -//! `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. +//! rounding and denormals IEEE 754 gives `double`. A function the device has an instruction for is +//! that instruction, its special operands the device's ([`math`]); the normalized and sRGB +//! `air.pack`/`air.unpack` conversions are GLSL.std.450's `Pack`/`Unpack` instructions where it has +//! one and the device's multiply, `RoundEven` and clamp elsewhere ([`pack`], +//! `PrecisionNote::DevicePackConversion`). //! //! 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 @@ -80,6 +80,7 @@ pub mod nan; pub mod narrow; pub mod ops; pub mod output_precision; +pub mod pack; pub mod srgb; pub mod texel_round; pub mod wide; @@ -202,11 +203,9 @@ pub enum ArithStrategy { op: AirBin, form: Form, }, - /// `fneg` on floats of `form`: the sign bit flipped on the bits where `bits` - /// ([`math::sign_on_bits`]: `float`), else the device's `OpFNegate`. + /// `fneg` on floats of `form`: the device's `OpFNegate`. FNeg { form: Form, - bits: bool, }, IntCompare { pred: IntPredicate, @@ -284,20 +283,6 @@ pub enum ArithStrategy { FastFmod { fma: fma::Fma, }, - /// `air.mix` on `float` or `half` where the device's functions are Metal's - /// (`FloatFunctions::Metal`), or on `half` where its fused multiply-add is the measured 16-bit - /// one ([`fma::Route::F16`], Metal's own `half` `fma`): Metal's `fma(t, y, fma(-t, x, x))` - /// (`math::metal_mix`) of those fused multiply-adds, both `fma`. - Mix { - fma: fma::Fma, - }, - /// `air.dot` on `half` vectors of form `form` where the device's functions are Metal's or its - /// fused multiply-add is the measured 16-bit one ([`fma::Route::F16`]): Metal's fused chain of - /// the products (`math::metal_dot`), each fused multiply-add `fma`, on one lane. - Dot { - fma: fma::Fma, - form: Form, - }, /// An `fdiv` carrying `arcp` on `float` lanes, Metal's fast division: the device's /// `OpFDiv(x, y)`, contracting as `contract` allows (`PrecisionNote::NativeDivision`). FastDivide { @@ -381,15 +366,6 @@ pub enum ArithStrategy { elem: Form, contract: Contraction, }, - /// `air.dot` of chunked vectors of `lanes` lanes of `elem` (`float` or `half`) where the - /// device's functions are Metal's, or of `half` where its fused multiply-add is the measured - /// 16-bit one ([`fma::Route::F16`]), as Metal's fused chain over every lane - /// ([`chunk::dot_chain`]), each fused multiply-add `fma`. - ChunkedChain { - lanes: u16, - elem: Form, - fma: fma::Fma, - }, /// 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), @@ -468,8 +444,6 @@ impl FamilyStrategy for ArithStrategy { }, S::Fma(f) => f.name(), S::FastFmod { .. } => FAST_FMOD, - S::Mix { .. } => MIX, - S::Dot { .. } => DOT, S::Convert { kind: ConvertKind::ToInt { .. }, .. @@ -479,16 +453,6 @@ impl FamilyStrategy for ArithStrategy { .. } => "arith.convert.fp8", S::Convert { .. } => "arith.convert", - // The sRGB conversions are named apart: they read Metal's table. - S::Pack { - dir: PackDir::Pack, - format: PackFormat::Unorm4x8Srgb, - .. - } => SRGB_PACK, - S::Pack { - format: PackFormat::Unorm4x8Srgb, - .. - } => SRGB_UNPACK, S::Pack { dir: PackDir::Pack, .. } => "arith.pack", @@ -497,7 +461,6 @@ impl FamilyStrategy for ArithStrategy { S::IndexWord(_) => "arith.index_word", S::SinCos { .. } => "arith.sincos", S::ChunkedDot { .. } => "arith.chunked.dot", - S::ChunkedChain { .. } => CHUNKED_DOT, S::Chunked { .. } => "arith.chunked", S::LaneExtract { .. } | S::LaneInsert { .. } => "arith.element.chunked", S::LaneShuffle { fragment: true, .. } => "arith.shuffle.fragment", @@ -537,7 +500,6 @@ impl FamilyStrategy for ArithStrategy { S::FastDivide { .. } => 16, S::NativeDivide { form } => divide::native_words(*form), // The bits' two conversions, the operation, and the mask's and its types' share. - S::FNeg { form, bits: true } => 24 + 4 * u32::from(form.lanes), S::FNeg { .. } | S::Select => 8, S::Cast { from, to, .. } => 64 + conversion_words(*from, *to), S::Bitcast { @@ -564,9 +526,6 @@ impl FamilyStrategy for ArithStrategy { S::Fma(f) => f.words(), // The device's division, the truncation, its negation, and the fused multiply-add. S::FastFmod { fma } => 80 + fma.words(), - // The negation of `t` on its bits and the two fused multiply-adds. - S::Mix { fma } => 32 + 2 * fma.words(), - S::Dot { fma, form } => math::metal_dot_words(*form, fma.words()), S::Convert { kind: ConvertKind::FromFp8(_), .. @@ -582,27 +541,11 @@ impl FamilyStrategy for ArithStrategy { dir, format, floats, - } => { - // Each sRGB color channel's search or step read; the table is the module's, - // charged once ([`routine_words`]). - let srgb = match (*format, *dir) { - (PackFormat::Unorm4x8Srgb, PackDir::Pack) => 3 * srgb::SEARCH_WORDS, - (PackFormat::Unorm4x8Srgb, PackDir::Unpack) => 3 * srgb::STEP_WORDS, - _ => 0, - }; - // One vector sequence of the exact products or exact divisions - // (`exact_division::div_exact`) with its per-lane constants, rounded once, and each - // channel's extract and placement. - let lanes = u32::from(floats.lanes); - 64 + srgb + 400 + 24 * lanes + narrow::round_words(*floats) - } + } => pack::words(*format, *dir, *floats), 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()) - } S::Chunked { lanes, parts, wide, .. } => { @@ -709,9 +652,10 @@ pub struct ArithPlan { /// The `half` additions, subtractions and products held at `float` precision, unrounded, /// between a chain's roundings on a device without `shaderFloat16` ([`half_chain`]). pub held_at_float: BTreeSet, - /// The direction of the first `air.pack`/`air.unpack` of `unorm4x8_srgb`, when one reads - /// Metal's sRGB table, which [`declare`] then declares once ([`srgb`]) and the census charges - /// once, to that direction's strategy ([`routine_words`]). + /// The direction of the first sRGB conversion that reads Metal's sRGB table (a tile's, a + /// color attachment's or a texture's), which [`declare`] then declares once ([`srgb`]) and the + /// census charges once, to that direction's name ([`routine_words`]). + /// `air.pack`/`air.unpack` of `unorm4x8_srgb` read none ([`pack`]). pub srgb: Option, /// Whether a call takes Metal's precise `fmod` on `float` or `half` lanes ([`libm::uses`]), /// recorded at selection; [`finish`] decides [`ArithPlan::fmod`] from it. @@ -838,18 +782,11 @@ pub fn routine_words(plan: &ArithPlan) -> impl Iterator { let f = form_in(cx, *v, chunk)?; - // A sign flip: it makes no NaN. Metal's `float` `fneg` flips the sign bit alone, - // keeping a NaN's payload and a denormal, whatever the flags, so it moves on the bits; - // elsewhere whether it keeps a denormal is the device's. - let bits = math::sign_on_bits(f.float_fmt()); - device_float(cx, f, !bits, false); + // The device's sign flip: it makes no NaN. Metal's `float` `fneg` flips the sign bit + // alone, keeping a NaN's payload and a denormal, whatever the flags; Vulkan lets + // `OpFNegate` flush a denormal (`DeviceDenormals`), and states no NaN's bits, noted + // `NativeNanEncoding` where Metal answers one ([`nan::fneg_answer`]). + device_float(cx, f, true, false); 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, S::FNeg { form: f, bits }, nan) + with_nan(cx, S::FNeg { form: f }, nan) } InstKind::ICmp { pred, a, .. } => { let f = form_in(cx, *a, chunk)?; @@ -1855,12 +1791,12 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result { /// ([`FloatFn::FastAsin`], [`FloatFn::FastAcos`], [`FloatFn::FastAtan`]); /// - `air.fast_rsqrt` is Metal's fast `rsqrt` ([`FloatFn::FastRsqrt`]), apart from the correctly /// rounded precise one; -/// - `air.fast_sqrt`, `air.fast_exp`, `air.fast_exp10`, `air.fast_log`, `air.fast_log10`, and -/// `air.fast_powr` are Metal's compositions `x · rsqrt(x)`, `exp2(x · log2 e)`, -/// `exp2(x · log2 10)`, `log2(x) · ln 2`, `log2(x) · log10 2`, and `exp2(y · log2 x)` -/// ([`FloatFn::FastSqrt`], [`FloatFn::FastExp`], [`FloatFn::FastExp10`], [`FloatFn::FastLog`], -/// [`FloatFn::FastLog10`], [`FloatFn::FastPowr`]); `air.fast_pow`'s magnitude is the last of -/// `|x|`; +/// - `air.fast_sqrt` is the device's `Sqrt` ([`FloatFn::FastSqrt`]); +/// - `air.fast_exp`, `air.fast_exp10`, `air.fast_log`, `air.fast_log10`, and `air.fast_powr` are +/// MSL Table 8.2's formulas `exp2(x · log2 e)`, `exp2(x · log2 10)`, `log2(x) · ln 2`, +/// `log2(x) · log10 2`, and `exp2(y · log2 x)` ([`FloatFn::FastExp`], [`FloatFn::FastExp10`], +/// [`FloatFn::FastLog`], [`FloatFn::FastLog10`], [`FloatFn::FastPowr`]); `air.fast_pow`'s +/// magnitude is the last of `|x|`; /// - `air.fast_log2` is Metal's `log2`, the precise one ([`FloatFn::FastLog2`]), which the fast /// formulas' `log2` is too; /// - `air.fast_sinpi`, `air.fast_cospi`, and `air.fast_tanpi` are Metal's precise functions, @@ -1873,22 +1809,15 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result { /// `a > b ? a : b` (with every flag), are Metal's `fmin` and `fmax` ([`FloatFn::Min`], /// [`FloatFn::Max`]), with any flags; on the other formats they stay LLVM's (`FloatFn::MinNum`). /// -/// `air.fract` on `half` with every flag, Metal's fast-math compile of a `half` `fract` (it has -/// no `fast_` `half` function), answers the largest `half` below one for a NaN and an infinity -/// ([`FloatFn::FlaggedFract`]); a `fast_` `half` symbol, not measured, keeps the precise function -/// as the other narrow `fast_` calls do. -/// /// A call's fast-math flags `fmf` do not change the function: Metal's `sign`, for one, answers /// `+0` for `-0` under fast math too (A1 case f9a12252). The exceptions measured are /// `fast_atan2`'s quotient beyond a divisor of `2^126`, which a call without every flag takes -/// from a flushed reciprocal (probe cases 6802ab13 and c11eb8cb), and `fast_fract` and `fast_asinh` -/// at infinities, which only a call with every flag answers as a NaN (A1 case aed3faaa without -/// flags, our probe with them), and `half` `fract`'s NaN and infinities. The other flag -/// combinations are not measured; they take the answer of a call without flags. +/// from a flushed reciprocal (probe cases 6802ab13 and c11eb8cb), and `fast_asinh` at +/// infinities, which only a call with every flag answers as a NaN (A1 case aed3faaa without +/// flags, our probe with them). The other flag combinations are not measured; they take the +/// answer of a call without flags. A function the device has an instruction for answers its +/// special operands as the instruction does in every combination (`fract`, `sign`). fn refine_float(op: FloatFn, fast: bool, fmf: FastMath, f: Form) -> FloatFn { - if f.float_fmt() == Some(FloatFmt::Half) && op == FloatFn::Fract && !fast && every_flag(fmf) { - return FloatFn::FlaggedFract; - } if f.float_fmt() != Some(FloatFmt::F32) { return op; } @@ -1914,9 +1843,7 @@ fn refine_float(op: FloatFn, fast: bool, fmf: FastMath, f: Form) -> FloatFn { FloatFn::Atanh => FloatFn::FastAtanh, FloatFn::Exp10 => FloatFn::FastExp10, FloatFn::Log10 => FloatFn::FastLog10, - FloatFn::Fract => FloatFn::FastFract { - infinite_nan: every_flag(fmf), - }, + FloatFn::Fract => FloatFn::FastFract, FloatFn::Median3 => FloatFn::FastMedian3, FloatFn::Pow => FloatFn::FastPow, FloatFn::Sin => FloatFn::FastSin, @@ -2034,18 +1961,12 @@ fn select_float_fn( arith.fmod_uses |= fmod; arith.device_min_max |= device_min_max(cx.profile, op, f); } - if let FloatLowering::Fma(fma) - | FloatLowering::FastFmod(fma) - | FloatLowering::Mix(fma) - | FloatLowering::Dot(fma) = lowered.how - { + if let FloatLowering::Fma(fma) | FloatLowering::FastFmod(fma) = lowered.how { cx.families.arith.take_fma(fma); } let s = match lowered.how { FloatLowering::Fma(fma) => ArithStrategy::Fma(fma), FloatLowering::FastFmod(fma) => ArithStrategy::FastFmod { fma }, - FloatLowering::Mix(fma) => ArithStrategy::Mix { fma }, - FloatLowering::Dot(fma) => ArithStrategy::Dot { fma, form: f }, FloatLowering::Fn(op) => ArithStrategy::FloatFn { f: op, form: f, @@ -2061,17 +1982,15 @@ fn select_float_fn( } /// Where the device reads the `f32` denormals of a float function call lowered as `how` on a -/// profile with float facts `facts` as Metal does ([`denormal::coverage`]): a fused multiply-add, -/// `mix` and `fast::fmod` by the device's own `float` instruction as `fma` (`OpFmaKHR`, or the -/// device's `Fma`), `dot`'s chain as `dot`, and the function's own row. Where the profile's +/// profile with float facts `facts` as Metal does ([`denormal::coverage`]): a fused multiply-add +/// and `fast::fmod` by the device's own `float` instruction as `fma` (`OpFmaKHR`, or the device's +/// `Fma`), and the function's own row. Where the profile's /// functions are Metal's, Metal's fast `sinpi`, `cospi` and `tanpi` are the device's form /// ([`FloatFn::FastSinPi`], `math::pi_scaled`), whose first multiply and difference read the /// operand, on the deviation. `None` for a lowering the table does not list. fn call_coverage(how: FloatLowering, facts: FloatFacts) -> Option { match how { - FloatLowering::Fma(fma) | FloatLowering::Mix(fma) | FloatLowering::FastFmod(fma) - if fma.route.device_float() => - { + FloatLowering::Fma(fma) | FloatLowering::FastFmod(fma) if fma.route.device_float() => { denormal::coverage(FloatFn::Fma) } FloatLowering::Fn(FloatFn::FastSinPi | FloatFn::FastCosPi | FloatFn::FastTanPi) @@ -2080,8 +1999,7 @@ fn call_coverage(how: FloatLowering, facts: FloatFacts) -> Option denormal::coverage(op), - FloatLowering::Dot(_) => denormal::coverage(FloatFn::Dot), - FloatLowering::Fma(_) | FloatLowering::Mix(_) | FloatLowering::FastFmod(_) => None, + FloatLowering::Fma(_) | FloatLowering::FastFmod(_) => None, } } @@ -2124,11 +2042,16 @@ 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, 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)`. +/// (`native_min_max`, [`FloatFacts::native_min_max`]), `saturate` on every other float format, +/// which no device is measured to answer as Metal's `clamp(x, +0, 1)`, and `median3` and +/// `fast::median3` on every device: `min(max(c, min(a, b)), max(a, b))` of the device's `NMin` and +/// `NMax` (`math::median3`), Metal's answer but where two operands are NaN, whose pick is the +/// device's (Metal's `fast::median3` answers `b` for two NaN first operands), and an `f32` +/// denormal, which Metal compares as a zero. 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)) + (min_max_family(op) && ((picks && native_min_max) || (op == FloatFn::Saturate && !picks))) + || matches!(op, FloatFn::Median3 | FloatFn::FastMedian3) } /// Why the device's 16-bit `+ - *` answers as Metal's `half` arithmetic ([`f16_arithmetic`]). @@ -2177,10 +2100,6 @@ enum FloatLowering { Fma(fma::Fma), /// `air.fast_fmod` on `float`, its quotient the device's. FastFmod(fma::Fma), - /// `air.mix` on `float` or `half` as Metal's two fused multiply-adds. - Mix(fma::Fma), - /// `air.dot` on `float` or `half`, Metal's fused chain by the fused multiply-add on one lane. - Dot(fma::Fma), /// The float function. Fn(FloatFn), } @@ -2265,8 +2184,10 @@ impl MetalOwn { /// The notes of a call of float function `op` (with the `fast_` prefix where `fast`) on form `f` /// lowered as the function itself, on a profile whose `float` functions are Metal's where /// `metal_functions`: where they are not, the device's precision where the call takes the device's -/// instruction for one of Metal's functions, `fast::sqrt`'s `Sqrt` included -/// (`NativeTranscendentals`), else the function's precision ([`FloatFn::precision`]), +/// instruction for one of Metal's functions, `fabs`, `sign`, `fract` and `fast::sqrt` included +/// ([`FloatFn::native_instruction`], `NativeTranscendentals`), else the function's precision +/// ([`FloatFn::precision`]); `round`'s zero, C99's, on every device +/// ([`FloatFn::composed_on_every_device`], `NativeTranscendentals`); /// and its division's (`DeviceArithmetic` for [`FloatFn::divides`], and `NativeDivision` where the /// functions are not Metal's), and its `f32` denormals' and NaNs' where they are left to the /// device (`denormals`, `nans`, [`device_float_notes`]). @@ -2302,6 +2223,10 @@ fn function_notes( } else if !exact { function.extend(precision_note(op.precision())); } + // `round`'s composition on every device: C99's `-0`, where Metal answers `+0`. + if op.composed_on_every_device() { + function.insert(PrecisionNote::NativeTranscendentals); + } if op.divides() { function.insert(PrecisionNote::DeviceArithmetic); if native { @@ -2319,21 +2244,6 @@ fn function_notes( .with(OpNotes::unless_own(environment, own == MetalOwn::Wholly)) } -/// Whether the device's instruction (`OpDot`, `FMix`) answers Metal's fused chain of `dot` or -/// `mix` with fused multiply-add `fma` on lanes of form `f`: on a profile whose `float` functions -/// are not Metal's own, a `float` chain, and a `half` one whose fused multiply-add is not the -/// measured 16-bit route ([`fma::Route::F16`], Metal's own `half` `fma`, which the chain keeps). -/// Where they are (MoltenVK), Metal's own forms of its own fused multiply-add are Metal's answer -/// and stay. -fn native_chain(facts: FloatFacts, fma: fma::Fma, f: Form) -> bool { - !facts.metal_functions - && match f.float_fmt() { - Some(FloatFmt::F32) => true, - Some(FloatFmt::Half) => fma.route != fma::Route::F16, - _ => false, - } -} - /// The note of fused multiply-add `fma`: `NativeFma` where it takes the device's `Fma` /// ([`fma::Route::Native`]), which [`finish`] records for every such route a family takes. fn native_fma(fma: fma::Fma) -> OpNotes { @@ -2419,77 +2329,38 @@ 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 noted, and a `half` result's as the - // `half` `fma`'s. - if op == FloatFn::Mix { - if let Some(fma) = fma::Fma::by(routes, f) { - // The device's order takes its `FMix`: on `float`, and on `half` where its fused - // multiply-add is not the measured 16-bit one, rounded once (`NativeMix`). - if native_chain(facts, fma, f) { - return Some(FloatCall { - how: FloatLowering::Fn(op), - notes: OpNotes::everywhere( - device_float_notes(f, true, false) - .chain([PrecisionNote::NativeMix]) - .collect(), - ), - nan: f.float_fmt().and_then(|fmt| match fmt { - FloatFmt::Half => { - nan::function_answer(op, fast, every_flag(fmf), FloatFmt::Half) - } - _ => Some(nan::NanAnswer::Canonical), - }), - }); - } - let khr = fma.route.device_float(); - let nan = match f.float_fmt() { - Some(FloatFmt::Half) => { - nan::function_answer(op, fast, every_flag(fmf), FloatFmt::Half) - } - _ => khr.then_some(nan::NanAnswer::Canonical), - }; - return Some(FloatCall { - how: FloatLowering::Mix(fma), - notes: native_fma(fma), - nan, - }); - } - } - // Metal's `dot` on `float` and `half` is the products' fused chain, with and without - // fast-math flags; the device's `OpDot` may sum otherwise (a tree, an unfused sum, or, under - // 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. Its NaN is the device's, + // `mix` and `dot` are the device's `FMix` and `OpDot` on every device. Metal's `mix(x, y, t)` + // on `float` and `half` is `fma(t, y, fma(-t, x, x))` and its `dot` the products' fused chain, + // with and without fast-math flags; the device's instructions may round or sum otherwise (a + // tree, an unfused sum, or, under fast-math flags, `b * (a + c)` for + // `dot(float2(a, b), float2(b, c))`), noted `NativeMix` and `NativeDot`, Vulkan's bounds + // inherited from `x * (1 - a) + y * a` and the sum of products. Where the profile's `float` + // functions are Metal's, a `float` one reaches Metal's own `mix` and `dot`; a `half` one is + // the instruction on its `float` container, rounded once, noted. Their 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 - .float_fmt() - .and_then(|fmt| nan::function_answer(op, fast, every_flag(fmf), fmt)); - // The device's order takes its `OpDot`: on `float`, and on `half` where its fused - // multiply-add is not the measured 16-bit one, rounded once (`NativeDot`). - if native_chain(facts, fma, f.scalar_form()) { - return Some(FloatCall { - how: FloatLowering::Fn(op), - notes: OpNotes::everywhere(BTreeSet::from([PrecisionNote::NativeDot])), - nan, - }); - } - let how = if metal_functions && f.float_fmt() == Some(FloatFmt::F32) { - FloatLowering::Fn(op) + if matches!(op, FloatFn::Mix | FloatFn::Dot) { + let fmt = f.float_fmt()?; + let own = metal_functions && fmt == FloatFmt::F32; + let mut notes = BTreeSet::new(); + if !own { + notes.insert(if op == FloatFn::Mix { + PrecisionNote::NativeMix } else { - FloatLowering::Dot(fma) - }; - return Some(FloatCall { - how, - notes: native_fma(fma), - nan, + PrecisionNote::NativeDot }); + if op == FloatFn::Mix { + notes.extend(device_float_notes(f, true, false)); + } } + let nan = match (op, fmt) { + (FloatFn::Mix, FloatFmt::F32) => Some(nan::NanAnswer::Canonical), + _ => nan::function_answer(op, fast, every_flag(fmf), fmt), + }; + return Some(FloatCall { + how: FloatLowering::Fn(op), + notes: OpNotes::everywhere(notes), + nan, + }); } // `air.fast_fmod` on `float` is Metal's composition around a fused multiply-add, of the // device's quotient; the fast-math table is single precision, so a narrow call keeps `fmod`. @@ -2729,9 +2600,15 @@ fn select_pack( if !floats.is_float() || usize::from(floats.lanes) != lanes || packed != word { return Err(cx.invariant("an air.pack whose types disagree with its format")); } - // Every conversion is exact: the sRGB ones read Metal's table. - if p.format == PackFormat::Unorm4x8Srgb { - cx.families.arith.srgb.get_or_insert(p.dir); + // The device's conversion: GLSL.std.450's instruction for the format, or its multiply, + // `RoundEven` and clamp, whose rounding Vulkan leaves to the device (`DevicePackConversion`). + // Where the profile's `float` functions are Metal's, a `float` one of the four formats + // GLSL.std.450 names reaches Metal's own `pack_float_to_*` or `unpack_*_to_float`. + let own = FloatFacts::on(cx.profile).metal_functions + && floats.float_fmt() == Some(FloatFmt::F32) + && pack::instruction(p.format, p.dir).is_some(); + if !own { + cx.precision.insert(PrecisionNote::DevicePackConversion); } Ok(ArithStrategy::Pack { dir: p.dir, @@ -2900,9 +2777,8 @@ pub fn emit( S::IndexWord(w) => access::index::emit_word(cx, fb, w)?, 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, test, &lib)?; + let (sin, cos) = chunk::sin_cos(fb, *shape, p, *fast, &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)?; @@ -2934,11 +2810,7 @@ fn arity(s: &ArithStrategy) -> Option { | S::SinCos { .. } | S::WordBitcast { .. } | S::LaneExtract { at: Some(_), .. } => Some(1), - S::InsertConst(_) - | S::LaneInsert { at: Some(_), .. } - | S::ChunkedDot { .. } - | S::ChunkedChain { .. } - | S::Dot { .. } => Some(2), + S::InsertConst(_) | S::LaneInsert { at: Some(_), .. } | S::ChunkedDot { .. } => Some(2), // An index word reads its operands itself (an index extension has no value). S::Zero(_) | S::Undef(_) @@ -2985,15 +2857,6 @@ fn value( elem, contract, } => chunk::dot(fb, *lanes, *elem, *contract, a(cx, 0)?, a(cx, 1)?)?, - S::ChunkedChain { - lanes, - elem, - fma: f, - } => { - let fma = |fb: &mut FunctionBuilder<'_>, args: &[SValue]| fma::emit(fb, *f, args); - let xy = [a(cx, 0)?, a(cx, 1)?]; - chunk::dot_chain(fb, *lanes, *elem, xy, &fma)? - } S::LaneExtract { src, at, index } => chunk::extract(fb, *src, *at, *index, xs)?, S::LaneInsert { dst, at, index } => chunk::insert(fb, *dst, *at, *index, xs)?, S::LaneShuffle { @@ -3038,13 +2901,9 @@ fn value( let (p, q) = (a(cx, 0)?, a(cx, 1)?); divide::native(fb, *form, p, q)? } - S::FNeg { form, bits } => { + S::FNeg { .. } => { let p = a(cx, 0)?; - if *bits { - math::sign_bits(fb, *form, p, math::SignBit::Flip)? - } else { - fb.unary(UnOp::FNegate, p)? - } + fb.unary(UnOp::FNegate, p)? } S::IntCompare { pred, form } => { let (p, q) = (a(cx, 0)?, a(cx, 1)?); @@ -3140,9 +2999,8 @@ fn value( wide::emit(fb, w, xs, routine)? } S::FloatFn { f, form, contract } => { - let test = nan::NanTest::for_modes(&cx.plan.families.arith.modes); let lib = lib(cx); - math::float_fn(fb, *f, *form, *contract, test, xs, &lib)? + math::float_fn(fb, *f, *form, *contract, xs, &lib)? } S::Fma(f) => fma::emit(fb, *f, xs)?, S::FastFmod { fma: f } => { @@ -3156,22 +3014,6 @@ fn value( }; math::fast_fmod(fb, x, y, ÷, &fma)? } - S::Mix { fma: f } => { - let xyt = match xs { - [x, y, t, ..] => [*x, *y, *t], - _ => return Err(cx.fail("a mix without its operands")), - }; - let fma = |fb: &mut FunctionBuilder<'_>, args: &[SValue]| fma::emit(fb, *f, args); - math::metal_mix(fb, f.form, xyt, &fma)? - } - S::Dot { fma: f, form } => { - let xy = match xs { - [x, y, ..] => [*x, *y], - _ => return Err(cx.fail("a dot without its operands")), - }; - let fma = |fb: &mut FunctionBuilder<'_>, args: &[SValue]| fma::emit(fb, *f, args); - math::metal_dot(fb, *form, xy, &fma)? - } S::Convert { kind, from, to } => { let p = a(cx, 0)?; // An 8-bit float source converts through `f32`. @@ -3185,14 +3027,9 @@ fn value( floats, } => { let p = a(cx, 0)?; - let table = cx.decl.families.arith.srgb; - if *format == PackFormat::Unorm4x8Srgb && table.is_none() { - return Err(cx.fail("an sRGB pack whose table is not declared")); - } - let test = nan::NanTest::for_modes(&cx.plan.families.arith.modes); match dir { - PackDir::Pack => math::pack(fb, *format, *floats, p, table, test)?, - PackDir::Unpack => math::unpack(fb, *format, *floats, p, table)?, + PackDir::Pack => pack::pack(fb, *format, *floats, p)?, + PackDir::Unpack => pack::unpack(fb, *format, *floats, p)?, } } }) diff --git a/crates/metal2vulkan/src/lower/arith/nan.rs b/crates/metal2vulkan/src/lower/arith/nan.rs index a89950d65..151671d93 100644 --- a/crates/metal2vulkan/src/lower/arith/nan.rs +++ b/crates/metal2vulkan/src/lower/arith/nan.rs @@ -11,8 +11,8 @@ //! `float` to `half` (`fptrunc` and `air.convert`), answer the canonical `half` NaN `0x7E00`, held //! 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`). Vulkan states no NaN encoding, and the devices +//! `fabs` keep a NaN operand's payload, the sign flipped or cleared, and its `half` `fract` a NaN +//! operand itself ([`NanAnswer::Operand`]). 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 @@ -58,8 +58,9 @@ pub enum NanAnswer { /// The canonical NaN, `+` for a NaN first operand and with the first operand's sign for a /// domain error: `fast::asin`. DomainSign, - /// A NaN first operand itself, bit for bit, and the canonical NaN for a NaN of another - /// origin: `round`, `ldexp`, `fast::tan`. + /// A NaN first operand itself, bit for bit (its sign flipped by `fneg` and cleared by `fabs`), + /// and the canonical NaN for a NaN of another origin: `round`, `ldexp`, `fast::tan`, `float` + /// `fneg` and `fabs`, and `half` `fract`. Operand, } @@ -156,7 +157,7 @@ fn precise_of(op: FloatFn) -> FloatFn { F::FastAtanh => F::Atanh, F::FastExp10 => F::Exp10, F::FastLog10 => F::Log10, - F::FastFract { .. } => F::Fract, + F::FastFract => F::Fract, F::FastMedian3 => F::Median3, F::FastPow => F::Pow, F::FastSin => F::Sin, @@ -182,9 +183,11 @@ 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. `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`). +/// 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 the device's picks or bit moves return (`fmin`, `fmax`, `median3`, +/// `copysign`, and precise `pow`, whose `pow(x, 1)` is `x`). `fabs` keeps its operand's payload +/// with the sign cleared ([`NanAnswer::Operand`]). /// `sinpi`, `cospi`, and `tanpi` answer the canonical NaN in both modes for an infinity or a NaN. /// The math-library branch's refinements of `fast_tan`, `fast_asin`, `fast_acos`, /// `fast_atan`, and `fast_rsqrt` answer as those calls were measured: a `fast_` symbol's state @@ -227,7 +230,7 @@ fn measured(op: FloatFn, fast: bool) -> Option { | F::Trunc | F::Rint | F::Fract - | F::FastFract { .. } + | F::FastFract | F::Atan2 | F::FastAtan2 { .. } | F::FastPow @@ -251,7 +254,7 @@ fn measured(op: FloatFn, fast: bool) -> Option { F::Atan | F::Asinh | F::Atanh if fast => A::Canonical, F::FastAtan => A::Canonical, F::Asin | F::Atan | F::Asinh | F::Atanh => A::OperandSign, - F::Round | F::Ldexp => A::Operand, + F::Round | F::Ldexp | F::Abs => A::Operand, _ => return None, }) } @@ -263,10 +266,11 @@ fn measured(op: FloatFn, fast: bool) -> Option { /// of `mix`, `dot`, `ldexp`, `fmod`, `sqrt`, `rsqrt`, `floor`, `ceil`, `trunc`, `rint`, `pow`, /// `powr`, and the transcendental functions but `asin` (`atan`, `asinh`, `atanh`, and `ldexp` /// unlike `float`'s), and of `fabs`, which the device computes exactly (class D); `asin`'s domain -/// error with the operand's sign (`0xFE00` below `-1`); and `round`'s NaN operand itself, a -/// signaling one kept. Metal has no `fast_` `half` function, so none is answered. `None` for the -/// functions that answer a number or an operand for a NaN (`fract`, `sign`, `saturate`, `fmin` and -/// its family, `median3`, `copysign`). `sinpi`, `cospi`, and `tanpi` answer the canonical `half` +/// error with the operand's sign (`0xFE00` below `-1`); and `round`'s and `fract`'s NaN operand +/// itself, a signaling one kept (`0x7c01` stays `0x7c01`). Metal has no `fast_` `half` function, +/// so none is answered. `None` for the functions that answer a number or an operand the device's +/// picks or bit moves return for a NaN (`sign`, `saturate`, `fmin` and its family, `median3`, +/// `copysign`). `sinpi`, `cospi`, and `tanpi` answer the canonical `half` /// NaN for an infinity or a NaN. fn half_function_answer(op: FloatFn, fast: bool) -> Option { use FloatFn as F; @@ -311,7 +315,7 @@ fn half_function_answer(op: FloatFn, fast: bool) -> Option { | F::CosPi | F::TanPi => A::Canonical, F::Asin => A::DomainSign, - F::Round => A::Operand, + F::Round | F::Fract => A::Operand, F::Abs => A::CanonicalExact, _ => return None, }) @@ -320,11 +324,14 @@ fn half_function_answer(op: FloatFn, fast: bool) -> Option { /// The answer Metal gives for a NaN result of `fneg` on lanes of format `fmt`: the canonical /// `half` NaN for `half`, with and without fast-math flags (`nan_narrow`, `nan_narrow_fast`, /// `nan_half`, `nan_half_fast`), which the device computes exactly, flipping the held value's -/// sign (class D). A `float` `fneg` keeps its operand's NaN with the sign flipped, which the -/// lowering moves on the bits (`math::sign_on_bits`, class E); the other formats are not -/// measured. +/// sign (class D). A `float` `fneg` keeps its operand's NaN with the sign flipped (class E, +/// [`NanAnswer::Operand`]); the other formats are not measured. pub fn fneg_answer(fmt: FloatFmt) -> Option { - (fmt == FloatFmt::Half).then_some(NanAnswer::CanonicalExact) + match fmt { + FloatFmt::Half => Some(NanAnswer::CanonicalExact), + FloatFmt::F32 => Some(NanAnswer::Operand), + FloatFmt::BFloat | FloatFmt::F64 => None, + } } /// The answer Metal gives for a NaN result of the float binary operator `op` on lanes of format diff --git a/crates/metal2vulkan/src/lower/arith/narrow.rs b/crates/metal2vulkan/src/lower/arith/narrow.rs index c6ae9466b..989425133 100644 --- a/crates/metal2vulkan/src/lower/arith/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/narrow.rs @@ -405,9 +405,8 @@ pub fn round_integer(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult /// Whether module `m` rounds to `half` through `OpQuantizeToF16` ([`round`] and [`round_texel`] /// in [`QuantizeForm::Device`]): the module then records `PrecisionNote::NativeHalfQuantize` -/// ([`native_rounding`]) on every profile, whose quantize's result below the smallest normal half -/// is the device's (`DriverDeviation::MetalHalfQuantize` measures its rounding of normal results -/// alone). +/// ([`native_rounding`]) on every profile: Vulkan leaves the quantize's rounding mode, and its +/// result below the smallest normal half, to the device. pub fn quantizes(m: &TypedModule) -> bool { m.blocks().iter().any(|b| { b.insts.iter().any(|n| { diff --git a/crates/metal2vulkan/src/lower/arith/pack.rs b/crates/metal2vulkan/src/lower/arith/pack.rs new file mode 100644 index 000000000..d76bc6747 --- /dev/null +++ b/crates/metal2vulkan/src/lower/arith/pack.rs @@ -0,0 +1,270 @@ +//! `air.pack` and `air.unpack` of the normalized formats by the device's arithmetic +//! (`PrecisionNote::DevicePackConversion`). +//! +//! A format `GLSL.std.450` names is its instruction: `unorm4x8`, `snorm4x8`, `unorm2x16` and +//! `snorm2x16` are `Pack`/`Unpack` `Unorm4x8`, `Snorm4x8`, `Unorm2x16` and `Snorm2x16`. The others +//! take the instruction's definition on their own fields: a pack clamps each channel by the +//! device's `NClamp` to `[0, 1]` (`[-1, 1]` signed), multiplies it by `2^N - 1` (`2^(N-1) - 1`), +//! rounds it by `RoundEven` and converts it (`unorm.rgb10a2`, `snorm.rgb10a2`, `unorm.rgb565`), and +//! an unpack multiplies each field's code by the scale's reciprocal, rounded to `float` (signed: +//! the code sign-extended, the product at least `-1`), as Metal's `snorm.rgb10a2` does. `unorm4x8_srgb`'s colour channels take the MSL transfer functions +//! around the 8-bit instruction, by the device's `Pow`: an encode `12.92 c` below `0.0031308` and +//! `1.055 c^(1/2.4) - 0.055` above, a decode `c / 12.92` up to `0.04045` and +//! `((c + 0.055) / 1.055)^2.4` above; alpha is the plain 8-bit channel. A NaN channel is the +//! device's instruction's answer. The packed float formats' unpack moves the fields' bits +//! (`math::unpack`, exact: every field is a `half` value). + +use crate::air::intrinsics::{PackDir, PackFormat}; +use crate::lower::arith::exact_division::per_lane; +use crate::lower::arith::legal::{FloatFmt, Form, Held}; +use crate::lower::arith::math; +use crate::lower::arith::narrow; +use crate::lower::arith::ops::{fsplat, ones, ty}; +use crate::spirv::builder::FunctionBuilder; +use crate::spirv::error::{BResult, BuildError, OperandRule}; +use crate::spirv::ids::Value; +use crate::spirv::ir::{BinOp, ConvOp, GlslOp}; + +/// The `GLSL.std.450` instruction that is `format`'s conversion in direction `dir`, where one is. +pub fn instruction(format: PackFormat, dir: PackDir) -> Option { + Some(match (format, dir) { + (PackFormat::Unorm4x8, PackDir::Pack) => GlslOp::PackUnorm4x8, + (PackFormat::Snorm4x8, PackDir::Pack) => GlslOp::PackSnorm4x8, + (PackFormat::Unorm2x16, PackDir::Pack) => GlslOp::PackUnorm2x16, + (PackFormat::Snorm2x16, PackDir::Pack) => GlslOp::PackSnorm2x16, + (PackFormat::Unorm4x8, PackDir::Unpack) => GlslOp::UnpackUnorm4x8, + (PackFormat::Snorm4x8, PackDir::Unpack) => GlslOp::UnpackSnorm4x8, + (PackFormat::Unorm2x16, PackDir::Unpack) => GlslOp::UnpackUnorm2x16, + (PackFormat::Snorm2x16, PackDir::Unpack) => GlslOp::UnpackSnorm2x16, + _ => return None, + }) +} + +/// The error of a conversion whose format or lanes the emission cannot take (a packed float +/// format to pack to, a lane count not the format's): selection rules both out. +fn unpackable() -> BuildError { + BuildError::Operand { + op: crate::spv::Op::ExtInst, + rule: OperandRule::Arity, + } +} + +/// The `float` container form of float lanes `f`, where the conversions compute. +fn container(f: Form) -> Form { + f.with(Held::Float(FloatFmt::F32)) +} + +/// `air.pack.`: float lanes `x` (form `f`, held in `float`) to the packed integer (a `u32`; +/// a `ushort` for `rgb565`, zero-extended). +pub fn pack(fb: &mut FunctionBuilder<'_>, format: PackFormat, f: Form, x: Value) -> BResult { + let Some((widths, snorm)) = math::pack_layout(format) else { + return Err(unpackable()); + }; + if usize::from(f.lanes) != widths.len() { + return Err(unpackable()); + } + let s = container(f); + if format == PackFormat::Unorm4x8Srgb { + let encoded = srgb_colour(fb, s, x, srgb_encode)?; + return fb.glsl(GlslOp::PackUnorm4x8, &[encoded]); + } + if let Some(op) = instruction(format, PackDir::Pack) { + return fb.glsl(op, &[x]); + } + // Each field: the clamped channel times its scale, rounded to nearest even, converted, and + // (signed) masked to its width, then placed at its offset. + let u = narrow::u32_form(s); + let lo = fsplat(fb, s, if snorm { -1.0 } else { 0.0 })?; + let one = fsplat(fb, s, 1.0)?; + let v = fb.glsl(GlslOp::NClamp, &[x, lo, one])?; + let scales: Vec = widths + .iter() + .map(|w| s.const_bits(f64::from(scale(*w, snorm)))) + .collect(); + let m = per_lane(fb, s, &scales)?; + let p = fb.binary(BinOp::FMul, v, m)?; + let p = fb.glsl(GlslOp::RoundEven, &[p])?; + let ut = ty(fb, u)?; + let op = if snorm { + ConvOp::ConvertFToS + } else { + ConvOp::ConvertFToU + }; + let r = fb.convert(op, p, ut)?; + let r = if snorm { + let m: Vec = widths.iter().map(|w| ones(*w as u8)).collect(); + let m = per_lane(fb, u, &m)?; + fb.binary(BinOp::BitwiseAnd, r, m)? + } else { + r + }; + let at = offsets(widths); + let sh = per_lane(fb, u, &at)?; + let r = fb.binary(BinOp::ShiftLeftLogical, r, sh)?; + let mut acc = fb.composite_extract(r, &[0])?; + for i in 1..widths.len() { + let field = fb.composite_extract(r, &[i as u32])?; + acc = fb.binary(BinOp::BitwiseOr, acc, field)?; + } + Ok(acc) +} + +/// `air.unpack.`: the packed integer `w` (a `u32`; a `ushort` for `rgb565`) to float +/// lanes of form `f`, a narrow form rounding each lane once. +pub fn unpack( + fb: &mut FunctionBuilder<'_>, + format: PackFormat, + f: Form, + w: Value, +) -> BResult { + if math::float_unpack_lanes(format).is_some() { + return math::unpack(fb, format, f, w, None); + } + let Some((widths, snorm)) = math::pack_layout(format) else { + return Err(unpackable()); + }; + if usize::from(f.lanes) != widths.len() { + return Err(unpackable()); + } + let s = container(f); + let q = if format == PackFormat::Unorm4x8Srgb { + let v = fb.glsl(GlslOp::UnpackUnorm4x8, &[w])?; + srgb_colour(fb, s, v, srgb_decode)? + } else if let Some(op) = instruction(format, PackDir::Unpack) { + fb.glsl(op, &[w])? + } else { + fields(fb, s, widths, snorm, w)? + }; + narrow::round(fb, f, q) +} + +/// The scale of a channel of `w` bits: `2^w - 1`, or `2^(w-1) - 1` signed. +fn scale(w: u32, snorm: bool) -> u32 { + if snorm { + (1 << (w - 1)) - 1 + } else { + (1 << w) - 1 + } +} + +/// The bit offset of each field of `widths`, low field first. +fn offsets(widths: &[u32]) -> Vec { + let mut at = Vec::with_capacity(widths.len()); + let mut next = 0u64; + for w in widths { + at.push(next); + next += u64::from(*w); + } + at +} + +/// The fields of word `w` (formats `widths`, signed where `snorm`) as `float` lanes of form `s`: +/// each code times its scale's reciprocal, the device's multiply, and a signed one at least `-1`. +fn fields( + fb: &mut FunctionBuilder<'_>, + s: Form, + widths: &[u32], + snorm: bool, + w: Value, +) -> BResult { + let u = narrow::u32_form(s); + let ut = ty(fb, u)?; + let spread = fb.composite_construct(ut, &vec![w; widths.len()])?; + let at = offsets(widths); + let sh = per_lane(fb, u, &at)?; + let v = fb.binary(BinOp::ShiftRightLogical, spread, sh)?; + let m: Vec = widths.iter().map(|n| ones(*n as u8)).collect(); + let m = per_lane(fb, u, &m)?; + let v = fb.binary(BinOp::BitwiseAnd, v, m)?; + let st = ty(fb, s)?; + let c = if snorm { + let up: Vec = widths.iter().map(|n| u64::from(32 - n)).collect(); + let up = per_lane(fb, u, &up)?; + let v = fb.binary(BinOp::ShiftLeftLogical, v, up)?; + let v = fb.binary(BinOp::ShiftRightArithmetic, v, up)?; + fb.convert(ConvOp::ConvertSToF, v, st)? + } else { + fb.convert(ConvOp::ConvertUToF, v, st)? + }; + let d: Vec = widths + .iter() + .map(|n| s.const_bits(f64::from(1.0 / scale(*n, snorm) as f32))) + .collect(); + let d = per_lane(fb, s, &d)?; + let q = fb.binary(BinOp::FMul, c, d)?; + if !snorm { + return Ok(q); + } + let m1 = fsplat(fb, s, -1.0)?; + fb.glsl(GlslOp::NMax, &[q, m1]) +} + +/// A transfer function on `float` lanes of form `s`. +type Transfer = fn(&mut FunctionBuilder<'_>, Form, Value) -> BResult; + +/// `x` (four `float` lanes of form `s`) with its colour lanes (red, green, blue) taken through +/// `transfer` and alpha kept. +fn srgb_colour( + fb: &mut FunctionBuilder<'_>, + s: Form, + x: Value, + transfer: Transfer, +) -> BResult { + let t = transfer(fb, s, x)?; + fb.vector_shuffle(t, x, &[0, 1, 2, 7]) +} + +/// The MSL linear-to-sRGB transfer of `c` (`float` lanes of form `s`): `12.92 c` below +/// `0.0031308`, `1.055 c^(1/2.4) - 0.055` elsewhere, by the device's `Pow`. A lane outside +/// `[0, 1]` is the 8-bit instruction's clamp's. +fn srgb_encode(fb: &mut FunctionBuilder<'_>, s: Form, c: Value) -> BResult { + let k = |fb: &mut FunctionBuilder<'_>, v: f64| fsplat(fb, s, v); + let slope = k(fb, 12.92)?; + let low = fb.binary(BinOp::FMul, c, slope)?; + let exponent = k(fb, 1.0 / 2.4)?; + let p = fb.glsl(GlslOp::Pow, &[c, exponent])?; + let gain = k(fb, 1.055)?; + let p = fb.binary(BinOp::FMul, p, gain)?; + let offset = k(fb, 0.055)?; + let high = fb.binary(BinOp::FSub, p, offset)?; + let knee = k(fb, 0.003_130_8)?; + let below = fb.binary(BinOp::FOrdLessThan, c, knee)?; + fb.select(below, low, high) +} + +/// The MSL sRGB-to-linear transfer of `c` (`float` lanes of form `s`, in `[0, 1]`): `c / 12.92` +/// up to `0.04045`, `((c + 0.055) / 1.055)^2.4` above, by the device's division and `Pow`. +fn srgb_decode(fb: &mut FunctionBuilder<'_>, s: Form, c: Value) -> BResult { + let k = |fb: &mut FunctionBuilder<'_>, v: f64| fsplat(fb, s, v); + let slope = k(fb, 12.92)?; + let low = fb.binary(BinOp::FDiv, c, slope)?; + let offset = k(fb, 0.055)?; + let t = fb.binary(BinOp::FAdd, c, offset)?; + let gain = k(fb, 1.055)?; + let t = fb.binary(BinOp::FDiv, t, gain)?; + let exponent = k(fb, 2.4)?; + let high = fb.glsl(GlslOp::Pow, &[t, exponent])?; + let knee = k(fb, 0.040_45)?; + let below = fb.binary(BinOp::FOrdLessThanEqual, c, knee)?; + fb.select(below, low, high) +} + +/// An upper estimate of the SPIR-V words of [`pack`] or [`unpack`] of `format` on `floats`: the +/// instruction, or the fields' clamp, product, rounding and placements (an unpack's shifts, masks, +/// conversion and division), the sRGB transfer's steps, and a narrow form's rounding. +pub fn words(format: PackFormat, dir: PackDir, floats: Form) -> u32 { + let lanes = u32::from(floats.lanes); + let body = if math::float_unpack_lanes(format).is_some() { + // The packed float formats' bit moves (`math::unpack`). + 400 + } else if instruction(format, dir).is_some() { + 16 + } else if format == PackFormat::Unorm4x8Srgb { + // The 8-bit instruction, the transfer's nine steps and their constants, the shuffle. + 16 + 9 * 6 + 5 * 8 + 12 + } else { + // The per-lane constants, each step, and each field's extract and placement. + 96 + 24 * lanes + }; + body + narrow::round_words(floats) +} diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index a5f6bf060..5d5461ca1 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -1778,22 +1778,17 @@ fn a_narrow_mask_after_a_signed_clamp_is_an_extract_under_the_workaround() { } } -/// Metal's `round`: halves away from zero, and on `float` and `half` (`positive_zero`) a zero -/// result is `+0` (`round(-0.3)` and `round(-0)` are `+0`). -fn metal_round(positive_zero: bool, x: f64) -> f64 { - let r = x.round(); - if positive_zero && r == 0.0 { - 0.0 - } else { - r - } +/// `round`'s composition: halves away from zero, a zero result the operand's sign (C99's +/// `round(-0.3)` is `-0`, where Metal answers `+0`: `PrecisionNote::NativeTranscendentals`). +fn c99_round(x: f64) -> f64 { + x.round() } -/// Metal's `median3` of operand bits `b` (A1 case aed3faaa): `min(max(c, min(a, b)), max(a, b))`, -/// where `min(p, q)` is `p` for a NaN `q`, else `p < q ? p : q` (and `max` with `>`), comparing the -/// operands' values `val` (an `f32` denormal as zero) but returning their bits; `fast` answers `b` -/// for two NaN first operands. -fn median3_ref(b: [u64; 3], val: &dyn Fn(u64) -> f64, fast: bool) -> u64 { +/// `median3(a, b, c)` of operand bits `b` as `min(max(c, min(a, b)), max(a, b))` of the device's +/// `NMin` and `NMax` as the interpreter answers them (Metal's `fmin` and `fmax`: a NaN `q` loses, +/// a tie answers the second operand), comparing the operands' values `val` but returning their +/// bits. +fn median3_ref(b: [u64; 3], val: &dyn Fn(u64) -> f64) -> u64 { let pick = |p: u64, q: u64, less: bool| { let (vp, vq) = (val(p), val(q)); if vq.is_nan() || (less && vp < vq) || (!less && vp > vq) { @@ -1803,18 +1798,17 @@ fn median3_ref(b: [u64; 3], val: &dyn Fn(u64) -> f64, fast: bool) -> u64 { } }; let [a, b, c] = b; - if fast && val(a).is_nan() && val(b).is_nan() { - return b; - } let lo = pick(a, b, true); let hi = pick(a, b, false); pick(pick(c, lo, false), hi, true) } +/// The answer of float function `op` on `bits`-bit operands `a` as its lowering's instructions +/// give it on the interpreter (one answer Vulkan allows): `fabs`, `sign`, `fract` and `median3` +/// the device's `FAbs`, `FSign`, `Fract`, `NMin` and `NMax`, `round` its composition. `None` where +/// the instruction's answer is undefined (`FSign` of a NaN). 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. - let flushed = |i: usize| bits == 32 && a[i] & 0x7F80_0000 == 0; // Compute in the operand width. let r = |v: f64| Some(fbits(bits, v)); let min = |p: f64, q: f64| p.min(q); @@ -1824,43 +1818,37 @@ fn float_ref(op: FloatFn, bits: u8, a: &[u64]) -> Option { FloatFn::Floor => r(x(0).floor()), FloatFn::Ceil => r(x(0).ceil()), FloatFn::Trunc => r(x(0).trunc()), - FloatFn::Round => r(metal_round(bits == 32, x(0))), + FloatFn::Round => r(c99_round(x(0))), FloatFn::Rint => r(x(0).round_ties_even()), - FloatFn::Fract | FloatFn::FastFract { .. } => { - if x(0).is_nan() { - return Some(fbits(bits, f64::NAN)); - } - // `fast::fract`'s `x - floor(x)` is NaN at an infinity under every fast-math flag. - if x(0).is_infinite() && op == (FloatFn::FastFract { infinite_nan: true }) { - return Some(fbits(bits, f64::NAN)); - } - if x(0).is_infinite() || flushed(0) { - return r(0.0); - } - let below = if bits == 32 { - f64::from(f32::from_bits(0x3F7F_FFFF)) - } else { - f64::from_bits(0x3FEF_FFFF_FFFF_FFFF) - }; + FloatFn::Fract | FloatFn::FastFract => { + // `Fract`'s `x - floor(x)`, rounded once: a NaN at a NaN or an infinity. let d = if bits == 32 { f64::from(f32v(a[0]) - f32v(a[0]).floor()) } else { x(0) - x(0).floor() }; - r(if op == FloatFn::Fract { - d.min(below) + let below = if bits == 32 { + f64::from(f32::from_bits(0x3F7F_FFFF)) + } else { + f64::from_bits(0x3FEF_FFFF_FFFF_FFFF) + }; + r(if op == FloatFn::Fract && d >= 1.0 { + below } else { d }) } FloatFn::Sign => { let v = x(0); - r(if flushed(0) || v.is_nan() || v == 0.0 { - 0.0 - } else if v > 0.0 { + if v.is_nan() { + return None; + } + r(if v > 0.0 { 1.0 - } else { + } else if v < 0.0 { -1.0 + } else { + v }) } // The device's `NClamp(x, 0, 1)`: a NaN answers 0, a denormal is the device's. @@ -1870,17 +1858,9 @@ fn float_ref(op: FloatFn, bits: u8, a: &[u64]) -> Option { FloatFn::Clamp => r(min(max(x(0), x(1)), x(2))), FloatFn::Min3 => r(min(min(x(0), x(1)), x(2))), FloatFn::Max3 => r(max(max(x(0), x(1)), x(2))), - FloatFn::Median3 | FloatFn::FastMedian3 => Some(median3_ref( - [a[0], a[1], a[2]], - &|b| { - if bits == 32 && b & 0x7F80_0000 == 0 { - 0.0 - } else { - fval(bits, b) - } - }, - op == FloatFn::FastMedian3, - )), + FloatFn::Median3 | FloatFn::FastMedian3 => { + Some(median3_ref([a[0], a[1], a[2]], &|b| fval(bits, b))) + } FloatFn::Mix | FloatFn::MulAdd => { // Rounded per operation in the operand width. if bits == 32 { @@ -1958,7 +1938,6 @@ fn copysign_moves_exactly_the_sign_bit() { FloatFn::CopySign, f, Contraction::Forbidden, - NanTest::IsNan, x, &Lib::instructions(), ) @@ -1987,7 +1966,6 @@ fn copysign_moves_exactly_the_sign_bit() { FloatFn::CopySign, half, Contraction::Forbidden, - NanTest::IsNan, x, &Lib::instructions(), ) @@ -1998,8 +1976,11 @@ fn copysign_moves_exactly_the_sign_bit() { ); } +/// The exactly specified float functions answer their instructions' answers: the device's own +/// for `fabs`, `sign`, `fract`, `median3` and `mix` (`FAbs`, `FSign`, `Fract`, `NMin`/`NMax`, +/// `FMix`), and C99's `round` of the device's `Trunc`. #[test] -fn exact_float_functions_match_metal() { +fn exact_float_functions_answer_their_instructions() { let fns = [ FloatFn::Abs, FloatFn::Floor, @@ -2008,10 +1989,7 @@ fn exact_float_functions_match_metal() { FloatFn::Round, FloatFn::Rint, FloatFn::Fract, - FloatFn::FastFract { - infinite_nan: false, - }, - FloatFn::FastFract { infinite_nan: true }, + FloatFn::FastFract, FloatFn::Sign, FloatFn::Saturate, FloatFn::Min, @@ -2032,10 +2010,6 @@ fn exact_float_functions_match_metal() { let f = float(bits); let few: Vec = vals.iter().copied().step_by(4).collect(); for op in fns { - // A `float` `mix` is its own strategy, Metal's fused form (`tests::fused`). - if op == FloatFn::Mix && bits == 32 { - continue; - } let arity = op.arity(); let cases: Vec = if arity == 1 { vals.iter().map(|v| vec![vec![*v]]).collect() @@ -2070,17 +2044,7 @@ fn exact_float_functions_match_metal() { &format!("{op:?} f{bits}"), &vec![f; arity], f, - &|fb, x| { - math::float_fn( - fb, - op, - f, - Contraction::Forbidden, - NanTest::IsNan, - x, - &Lib::instructions(), - ) - }, + &|fb, x| math::float_fn(fb, op, f, Contraction::Forbidden, x, &Lib::instructions()), &cases, &|c| { let a: Vec = c.iter().map(|l| l[0]).collect(); @@ -2092,6 +2056,116 @@ fn exact_float_functions_match_metal() { } } +/// The functions the device has an instruction for are that instruction, on `float` and on a +/// `half` held in `float`, in every math mode of every library: `exp`, `log`, `pow` and `powr`'s +/// magnitude, `sinh`, `cosh`, `tanh` (`Exp`, `Log`, `Pow`, `Sinh`, `Cosh`, `Tanh`, with no `Exp2` +/// or `Log2` composition of Metal's), `fabs`, `sign`, `fract` and `fast::fract` (`FAbs`, `FSign`, +/// `Fract`, with no bit operation), `median3` (`NMin` and `NMax` alone), `mix` (`FMix`) and +/// `fast::sqrt` (`Sqrt`). `round` is C99's from the device's `Trunc`. +#[test] +fn functions_with_an_instruction_are_that_instruction() { + use super::libm::Mode; + use crate::spv::GlslStd450Op as G; + const OP_EXT_INST: u32 = 12; + const OP_BITCAST: u32 = 124; + let read = |op: FloatFn, f: Form, lib: Lib| { + let m = kernel(&vec![f; op.arity()], f, &|fb, a| { + math::float_fn(fb, op, f, Contraction::Forbidden, a, &lib) + }) + .expect("kernel"); + let words = crate::spirv::serialize::serialize(m).expect("words").words; + let (mut ext, mut bitcasts) = (Vec::new(), 0); + let mut i = 5; + while i < words.len() { + let (n, code) = ((words[i] >> 16) as usize, words[i] & 0xFFFF); + if code == OP_EXT_INST { + ext.extend(words.get(i + 4).copied()); + } + bitcasts += usize::from(code == OP_BITCAST); + i += n.max(1); + } + (ext, bitcasts) + }; + let cases: [(FloatFn, &[G]); 15] = [ + (FloatFn::Exp, &[G::Exp]), + (FloatFn::Log, &[G::Log]), + (FloatFn::Sinh, &[G::Sinh]), + (FloatFn::Cosh, &[G::Cosh]), + (FloatFn::Tanh, &[G::Tanh]), + (FloatFn::Pow, &[G::Pow]), + (FloatFn::Powr, &[G::Pow]), + (FloatFn::Abs, &[G::FAbs]), + (FloatFn::Sign, &[G::FSign]), + (FloatFn::Fract, &[G::Fract]), + (FloatFn::FastFract, &[G::Fract]), + (FloatFn::Median3, &[G::NMin, G::NMax]), + (FloatFn::Mix, &[G::FMix]), + (FloatFn::FastSqrt, &[G::Sqrt]), + (FloatFn::Round, &[G::Trunc]), + ]; + for lib in [ + Lib::instructions(), + Lib::new(Some(Mode::Fast), None), + Lib::new(Some(Mode::Precise), None), + ] { + for lane in [float(32), float(16)] { + for lanes in [1u8, 3] { + let f = vec(lane, lanes); + for (op, want) in cases { + if op == FloatFn::FastSqrt && lane.float_fmt() == Some(FloatFmt::Half) { + continue; + } + let what = format!("{op:?} on {f:?} ({lib:?})"); + let (ext, bitcasts) = read(op, f, lib); + for g in want { + assert!(ext.contains(&(*g as u32)), "{what}: {ext:?}"); + } + for g in [G::Exp2, G::Log2, G::InverseSqrt] { + assert!(!ext.contains(&(g as u32)), "{what}: {g:?} in {ext:?}"); + } + let one_instruction = matches!( + op, + FloatFn::Exp + | FloatFn::Log + | FloatFn::Sinh + | FloatFn::Cosh + | FloatFn::Tanh + | FloatFn::Abs + | FloatFn::Sign + | FloatFn::FastFract + | FloatFn::Mix + | FloatFn::FastSqrt + ); + if one_instruction && lane.float_fmt() == Some(FloatFmt::F32) { + assert_eq!(ext, vec![want[0] as u32], "{what}"); + } + if matches!( + op, + FloatFn::Abs + | FloatFn::Sign + | FloatFn::Fract + | FloatFn::FastFract + | FloatFn::Median3 + ) && lane.float_fmt() == Some(FloatFmt::F32) + { + // No bitcast beyond the kernel's own loads and stores. + let m = kernel(&vec![f; op.arity()], f, &|_, a| Ok(a[0])).expect("kernel"); + let words = crate::spirv::serialize::serialize(m).expect("words").words; + let mut own = 0; + let mut i = 5; + while i < words.len() { + let (n, code) = ((words[i] >> 16) as usize, words[i] & 0xFFFF); + own += usize::from(code == OP_BITCAST); + i += n.max(1); + } + assert_eq!(bitcasts, own, "{what}: on the bits"); + } + } + } + } + } +} + // ---- Metal's NaN ---- /// The NaN operands of the NaN-model probes: quiet and signaling, of either sign, with and @@ -2163,7 +2237,6 @@ fn half_fmod_answers_metals_zero_remainder() { FloatFn::Fmod, f, Contraction::Forbidden, - NanTest::IsNan, x, &Lib::instructions(), ) @@ -2188,7 +2261,6 @@ fn half_fmod_answers_metals_zero_remainder() { FloatFn::Fmod, f, Contraction::Forbidden, - NanTest::IsNan, x, &Lib::instructions(), ) @@ -2218,7 +2290,6 @@ fn half_fmod_answers_metals_zero_remainder() { FloatFn::Fmod, f, Contraction::Allowed, - NanTest::IsNan, x, &Lib::instructions(), ) @@ -2236,8 +2307,9 @@ fn half_fmod_answers_metals_zero_remainder() { /// `fneg` and `fabs` (`nan_half`, `nan_half_fast`), answer the canonical NaN, computed exactly on /// the device; neither cast carries flags in either math mode. Its `half` functions answer the /// canonical `half` NaN, but `asin` (the operand's sign at a domain error) and `round` (the NaN -/// operand), and those that answer a number or an operand. `float` `+ - * /` answer the canonical -/// NaN in both states, and `frem` in neither; a `float` `fneg` is class E's. Only the canonical NaN +/// operand) and `fract` (the NaN operand), and those that answer a number or an operand the +/// device's picks return. `float` `+ - * /` answer the canonical NaN in both states, and `frem` in +/// neither; a `float` `fneg` and `fabs` keep the operand's payload (class E). Only the canonical NaN /// of rounding arithmetic is left to a device whose arithmetic answers it. #[test] fn half_nan_answers_follow_the_measured_states() { @@ -2266,7 +2338,12 @@ fn half_nan_answers_follow_the_measured_states() { function_answer(FloatFn::Abs, false, flagged, h), Some(A::CanonicalExact) ); - assert_eq!(function_answer(FloatFn::Abs, false, flagged, f), None); + // `float` `fabs` keeps its operand's payload, the sign cleared: the device's `FAbs` + // answers its own NaN, noted. + assert_eq!( + function_answer(FloatFn::Abs, false, flagged, f), + Some(A::Operand) + ); for op in [ FloatFn::MulAdd, FloatFn::Mix, @@ -2289,24 +2366,22 @@ fn half_nan_answers_follow_the_measured_states() { function_answer(FloatFn::Asin, false, flagged, h), Some(A::DomainSign) ); - assert_eq!( - function_answer(FloatFn::Round, false, flagged, h), - Some(A::Operand) - ); - for op in [ - FloatFn::Fract, - FloatFn::FlaggedFract, - FloatFn::Sign, - FloatFn::Min, - FloatFn::Median3, - ] { + for op in [FloatFn::Round, FloatFn::Fract] { + assert_eq!( + function_answer(op, false, flagged, h), + Some(A::Operand), + "{op:?}" + ); + } + for op in [FloatFn::Sign, FloatFn::Min, FloatFn::Median3] { assert_eq!(function_answer(op, false, flagged, h), None, "{op:?}"); } // Metal has no `fast_` `half` function. assert_eq!(function_answer(FloatFn::Exp, true, flagged, h), None); } assert_eq!(fneg_answer(h), Some(A::CanonicalExact)); - for fmt in [f, FloatFmt::BFloat, FloatFmt::F64] { + assert_eq!(fneg_answer(f), Some(A::Operand)); + for fmt in [FloatFmt::BFloat, FloatFmt::F64] { assert_eq!(fneg_answer(fmt), None, "{fmt:?}"); } assert_eq!(cast_answer(CastOp::FPTrunc, f, h), Some(A::Canonical)); @@ -2362,25 +2437,20 @@ const KHR_FACTS: super::FloatFacts = super::FloatFacts { }; /// Class E: Metal's `float` `fneg` and `fabs` flip or clear the sign bit alone, a NaN's payload and -/// a denormal kept, with and without fast-math flags (`nan_signbits`, `nan_signbits_fast`), so they -/// move on the bits on `float` only: such a `fabs` answers Metal's NaN itself and selects none, -/// records no device note, and leaves the operand's bits observed, while a `half` `fabs` still -/// selects its canonical NaN (class D). The bit operations are exact at every NaN, zero, and -/// denormal. +/// a denormal kept (`nan_signbits`, `nan_signbits_fast`). The lowering takes the device's +/// `OpFNegate` and `FAbs` on every format, whose NaN is the device's: a `float` `fabs` answers +/// Metal's operand NaN by none of its own, noted `NativeNanEncoding` (and a `half` one Metal's +/// canonical NaN, class D), and off Metal's own functions records the device's precision and +/// denormals. #[test] -fn float_sign_operations_move_the_bits() { - use super::math::{sign_on_bits, SignBit}; +fn float_sign_operations_are_the_device_instructions() { use super::nan::NanAnswer as A; use crate::air::ir::FastMath; + use crate::pipeline::artifact::PrecisionNote; let (h, f) = (FloatFmt::Half, FloatFmt::F32); - assert!(sign_on_bits(Some(f))); - for fmt in [h, FloatFmt::BFloat, FloatFmt::F64] { - assert!(!sign_on_bits(Some(fmt)), "{fmt:?}"); - } - assert!(!sign_on_bits(None)); - assert!(FloatFn::Abs.metal_nans(f)); + assert!(!FloatFn::Abs.metal_nans(f)); assert!(!FloatFn::Abs.metal_nans(h)); - assert!(FloatFn::Abs.metal_denormals()); + assert!(FloatFn::Abs.native_instruction()); let scalar = |fmt| Form { held: Held::Float(fmt), lanes: 1, @@ -2388,18 +2458,18 @@ fn float_sign_operations_move_the_bits() { let every = FastMath::ALL .iter() .fold(FastMath::NONE, |a, (b, _)| a.union(*b)); - // `float` `fabs` is `air.fabs` or `air.fast_fabs`, either with or without flags; a `half` one - // is `air.fabs.f16` (Metal has no `fast_` `half` function) with or without them. for fmf in [FastMath::NONE, every] { for fast in [false, true] { let call = super::float_call(FloatFn::Abs, fast, fmf, scalar(f), KHR_FACTS) .expect("float fabs"); - assert_eq!(call.nan, None, "fast {fast}, {fmf:?}"); - assert_eq!( - call.notes, - super::OpNotes::default(), - "fast {fast}, {fmf:?}" - ); + assert_eq!(call.nan, Some(A::Operand), "fast {fast}, {fmf:?}"); + for note in [ + PrecisionNote::NativeNanEncoding, + PrecisionNote::NativeTranscendentals, + PrecisionNote::DeviceDenormals, + ] { + assert!(call.notes.always.contains(¬e), "{note:?} {fmf:?}"); + } } let call = super::float_call(FloatFn::Abs, false, fmf, scalar(h), KHR_FACTS).expect("half fabs"); @@ -2418,20 +2488,54 @@ fn float_sign_operations_move_the_bits() { vec![v.collect()] }) .collect(); - for (op, apply) in [ - (SignBit::Flip, (|b: u64| b ^ 0x8000_0000) as fn(u64) -> u64), - (SignBit::Clear, |b: u64| b & 0x7FFF_FFFF), - ] { - check_accept( - &format!("{op:?} f32x{lanes}"), - &[form], - form, - &|fb, x| math::sign_bits(fb, form, x[0], op), - &cases, - &|c| Some(c[0].iter().map(|b| apply(*b)).collect()), - &|g, w| g == w, - ); - } + let words = |op: GlslOp| { + let m = kernel_with(&[form], form, &|fb, x| fb.glsl(op, &[x[0]]), true, false) + .expect("kernel"); + crate::spirv::serialize::serialize(m).expect("words").words + }; + // `fabs` is `FAbs` itself: its module is the instruction's. + let abs = kernel_with( + &[form], + form, + &|fb, x| { + math::float_fn( + fb, + FloatFn::Abs, + form, + Contraction::Forbidden, + x, + &Lib::instructions(), + ) + }, + true, + false, + ) + .expect("fabs"); + assert_eq!( + crate::spirv::serialize::serialize(abs) + .expect("words") + .words, + words(GlslOp::FAbs), + "fabs f32x{lanes}" + ); + check_accept( + &format!("fabs f32x{lanes}"), + &[form], + form, + &|fb, x| { + math::float_fn( + fb, + FloatFn::Abs, + form, + Contraction::Forbidden, + x, + &Lib::instructions(), + ) + }, + &cases, + &|c| Some(c[0].iter().map(|b| b & 0x7FFF_FFFF).collect()), + &|g, w| g == w, + ); } } @@ -2451,7 +2555,6 @@ fn nan_answers_follow_the_measured_flag_states() { use super::nan::{function_answer, NanAnswer as A}; use crate::air::ir::FastMath; let f32_ = FloatFmt::F32; - let fract = |infinite_nan| FloatFn::FastFract { infinite_nan }; for (op, fast, flagged, want) in [ (FloatFn::Exp, false, false, Some(A::Canonical)), (FloatFn::FastExp, true, true, Some(A::Canonical)), @@ -2459,8 +2562,8 @@ fn nan_answers_follow_the_measured_flag_states() { (FloatFn::Exp, false, true, Some(A::Canonical)), (FloatFn::Round, true, false, Some(A::Operand)), (FloatFn::Round, false, true, Some(A::Operand)), - (fract(false), true, false, Some(A::Canonical)), - (fract(true), true, true, Some(A::Canonical)), + (FloatFn::FastFract, true, false, Some(A::Canonical)), + (FloatFn::FastFract, true, true, Some(A::Canonical)), (FloatFn::Dot, false, true, Some(A::Canonical)), (FloatFn::Tan, true, true, Some(A::Operand)), (FloatFn::Tan, false, false, Some(A::Canonical)), @@ -2665,94 +2768,6 @@ fn powr_answers_metals_nan_at_its_special_operands() { } } -/// `fast::fract` answers one where `x - floor(x) = 1 + x` rounds to it, `x` in `[-2^-25, 0)` (A1 -/// case aed3faaa: `-2^-126`, `-2^-25`, and `-1e-10` give `1.0`), and the module selects that one -/// itself: a device whose `x - floor(x)` is a fract bounded below one (RADV's `v_fract`, which -/// Mesa's NIR folds the subtraction into) still answers Metal's one. -#[test] -fn an_unbounded_fract_selects_one_where_one_plus_x_rounds_to_it() { - let f = float(32); - let below_tie = f32::from_bits(0xB300_0001); - let xs = [ - -2f32.powi(-25), - below_tie, - -f32::MIN_POSITIVE, - -1e-10, - -2f32.powi(-24), - -1e-40, - -0.0, - ]; - let want = |x: f32| -> u64 { - let r = if x.to_bits() & 0x7F80_0000 == 0 { - 0.0 - } else if (-2f32.powi(-25)..0.0).contains(&x) { - 1.0 - } else { - x - x.floor() - }; - u64::from(r.to_bits()) - }; - assert_eq!(want(below_tie), 0x3F7F_FFFF); - assert_eq!(want(-1e-10), 0x3F80_0000); - let cases: Vec = xs - .iter() - .map(|x| vec![vec![u64::from(x.to_bits())]]) - .collect(); - check( - "fast fract near minus zero", - &[f], - f, - &|fb, x| { - math::float_fn( - fb, - FloatFn::FastFract { - infinite_nan: false, - }, - f, - Contraction::Forbidden, - NanTest::IsNan, - x, - &Lib::instructions(), - ) - }, - &cases, - &|c| Some(vec![want(f32::from_bits(c[0][0] as u32))]), - false, - ); - // The bound `-2^-25` is the module's own constant: the one does not come from the - // subtraction. - let has_bound = |op: FloatFn| { - let m = kernel(&[f], f, &|fb, x| { - math::float_fn( - fb, - op, - f, - Contraction::Forbidden, - NanTest::IsNan, - x, - &Lib::instructions(), - ) - }) - .expect("kernel"); - let words = crate::spirv::serialize::serialize(m).expect("words").words; - const OP_CONSTANT: u32 = 43; - let mut i = 5; - let mut found = false; - while i < words.len() { - let (n, op) = ((words[i] >> 16) as usize, words[i] & 0xFFFF); - if op == OP_CONSTANT && n == 4 && words.get(i + 3) == Some(&0xB300_0000) { - found = true; - } - i += n.max(1); - } - found - }; - assert!(has_bound(FloatFn::FastFract { - infinite_nan: false - })); - assert!(!has_bound(FloatFn::Fract)); -} - /// The C99 Annex F special cases of `pow` run on the interpreter against the host's `powf`. The /// interpreter does not model `GLSL.std.450 Pow`, so the kernel takes the magnitude /// `Pow(|x|, y)` as a third input (computed on the host) and runs only the selects around it. @@ -3022,15 +3037,7 @@ fn pi_scaled_functions_stay_within_their_word_estimate() { for g in calls { for metal in [None, Some(Mode::Fast), Some(Mode::Precise)] { let used = module_words(f, &|fb, x| { - math::float_fn( - fb, - g, - f, - Contraction::Allowed, - NanTest::IsNan, - x, - &Lib::new(metal, None), - ) + math::float_fn(fb, g, f, Contraction::Allowed, x, &Lib::new(metal, None)) }); let (emitted, bound) = (used - bare, g.words(f) as usize); assert!( @@ -3101,15 +3108,15 @@ fn fast_tanh_is_the_fast_math_formula() { /// The function a call computes follows its `air` symbol's `fast_` variant, never a name: on /// `float`, `fast_tanh` is the fast-math formula, `fast_fract` is unbounded, `fast_fmedian3` -/// answers the second of two NaNs, `fast_pow` the canonical NaN for a NaN base to the exponent one, -/// `fast_atan2` is the turned `atan` of the quotient, `fast_sin` and `fast_cos` flush past the last -/// evaluated quadrant, and `fast_sqrt`, `fast_exp`, `fast_log`, and `fast_powr` are Metal's -/// compositions; a narrow `fast_` call and the precise ones keep the precise function. The -/// fast-math flags change only `fast_atan2`'s quotient beyond `2^126` (a call with every flag -/// divides there, any other call flushes the reciprocal) and the infinities of `fast_fract` and -/// `fast_asinh` (a call with every flag answers a NaN; any other call is `fract`'s `+0` and the -/// precise `asinh`), and `llvm.minnum` and `llvm.maxnum` on `float`, which with every flag are -/// Metal's `fmin` and `fmax`. +/// records the device's pick of two NaNs, `fast_pow` the canonical NaN for a NaN base to the +/// exponent one, `fast_atan2` is the turned `atan` of the quotient, `fast_sin` and `fast_cos` flush +/// past the last evaluated quadrant, `fast_sqrt` is the device's `Sqrt`, and `fast_exp`, +/// `fast_log`, and `fast_powr` are Metal's formulas; a narrow `fast_` call and the precise ones +/// keep the precise function. The fast-math flags change only `fast_atan2`'s quotient beyond +/// `2^126` (a call with every flag divides there, any other call flushes the reciprocal) and the +/// infinities of `fast_asinh` (a call with every flag answers a NaN; any other call is the precise +/// `asinh`), and `llvm.minnum` and `llvm.maxnum` on `float`, which with every flag are Metal's +/// `fmin` and `fmax`. #[test] fn fast_variants_refine_float_functions() { use crate::air::ir::FastMath; @@ -3131,12 +3138,7 @@ fn fast_variants_refine_float_functions() { FloatFn::Asinh }, ), - ( - FloatFn::Fract, - FloatFn::FastFract { - infinite_nan: fmf == every, - }, - ), + (FloatFn::Fract, FloatFn::FastFract), (FloatFn::Median3, FloatFn::FastMedian3), (FloatFn::Pow, FloatFn::FastPow), (FloatFn::Sin, FloatFn::FastSin), @@ -3162,15 +3164,9 @@ fn fast_variants_refine_float_functions() { ] { assert_eq!(refine(op, true, fmf, f32_), fast); assert_eq!(refine(op, false, fmf, f32_), op); - // A precise `half` `fract` with every flag answers `0x3BFF` at a NaN and an infinity; a - // `fast_` `half` symbol is not measured and keeps `op`. - let half = if op == FloatFn::Fract && fmf == every { - FloatFn::FlaggedFract - } else { - op - }; + // A `fast_` `half` symbol is not measured and keeps `op`. assert_eq!(refine(op, true, fmf, float(16)), op); - assert_eq!(refine(op, false, fmf, float(16)), half); + assert_eq!(refine(op, false, fmf, float(16)), op); assert_eq!(refine(op, true, fmf, bfloat()), op); } for op in [FloatFn::Sign, FloatFn::Saturate] { @@ -3257,15 +3253,7 @@ fn device_precision_float_functions(part: usize, of: usize) { for op in device { checks.push(Box::new(move || { let m = kernel(&vec![f; op.arity()], f, &|fb, x| { - math::float_fn( - fb, - op, - f, - Contraction::Forbidden, - NanTest::IsNan, - x, - &Lib::instructions(), - ) + math::float_fn(fb, op, f, Contraction::Forbidden, x, &Lib::instructions()) }) .unwrap_or_else(|e| panic!("{op:?}: {e:?}")); assert_valid(m, &wide_profile()); @@ -3288,7 +3276,6 @@ fn device_precision_float_functions(part: usize, of: usize) { FloatFn::Ldexp, f, Contraction::Forbidden, - NanTest::IsNan, x, &Lib::instructions(), ) @@ -3371,7 +3358,6 @@ fn device_precision_float_functions(part: usize, of: usize) { FloatFn::Ldexp, f, Contraction::Forbidden, - NanTest::IsNan, x, &Lib::instructions(), ) @@ -3413,7 +3399,6 @@ fn device_precision_float_functions(part: usize, of: usize) { FloatFn::Ldexp, h, Contraction::Forbidden, - NanTest::IsNan, x, &Lib::instructions(), ) @@ -3450,7 +3435,6 @@ fn device_precision_float_functions(part: usize, of: usize) { FloatFn::Dot, v, Contraction::Forbidden, - NanTest::IsNan, x, &Lib::instructions(), ) @@ -3814,6 +3798,7 @@ mod fused; mod half_texel; mod libm; mod narrow; +mod pack; mod round_texel; mod snapshot_codes; mod specials; @@ -3983,15 +3968,7 @@ fn the_minimum_and_maximum_family_takes_the_device_instructions() { const DEVICE: [u32; 3] = [79, 80, 81]; let counts = |op: FloatFn, f: Form| -> (usize, usize) { let m = kernel(&vec![f; op.arity()], f, &|fb, a| { - math::float_fn( - fb, - op, - f, - Contraction::Forbidden, - NanTest::IsNan, - a, - &Lib::instructions(), - ) + math::float_fn(fb, op, f, Contraction::Forbidden, a, &Lib::instructions()) }) .expect("kernel"); let words = crate::spirv::serialize::serialize(m).expect("words").words; diff --git a/crates/metal2vulkan/src/lower/arith/tests/atan2.rs b/crates/metal2vulkan/src/lower/arith/tests/atan2.rs index 4c44df5db..388058c6a 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/atan2.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/atan2.rs @@ -612,15 +612,7 @@ fn special_value_functions_stay_within_their_word_estimate() { continue; } let used = module_words(f, &|fb, x| { - math::float_fn( - fb, - g, - f, - Contraction::Allowed, - NanTest::IsNan, - x, - &Lib::instructions(), - ) + math::float_fn(fb, g, f, Contraction::Allowed, x, &Lib::instructions()) }); let (emitted, bound) = (used - bare, g.words(f) as usize); if emitted > bound || 2 * emitted < bound { diff --git a/crates/metal2vulkan/src/lower/arith/tests/fast.rs b/crates/metal2vulkan/src/lower/arith/tests/fast.rs index cd78cb678..f169214c0 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/fast.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/fast.rs @@ -171,94 +171,12 @@ fn fast_fmod_answers_as_metal_on_every_route() { } } -/// `(x, rsqrt(x), fast::sqrt(x))`: Metal's fast `rsqrt` and `sqrt` at the special lanes of case -/// 08bc6611 and 40 others drawn at random. -const SQRT: [(u32, u32, u32); 52] = [ - (0x00000000, 0x7F800000, 0x00000000), - (0x00000001, 0x7F800000, 0x00000000), - (0x03EB9990, 0x5D3CB198, 0x21ADA837), - (0x0AD36389, 0x59C734EB, 0x25247E12), - (0x10BF38EE, 0x56D1729C, 0x281C7316), - (0x2813F70D, 0x4B285D4D, 0x33C2A01C), - (0x30125D7E, 0x47294838, 0x37C19205), - (0x3252A670, 0x460D1B6F, 0x38E8387D), - (0x382DB84C, 0x431B6233, 0x3BD2E272), - (0x392CDDDE, 0x429BC440, 0x3C525DB5), - (0x3CB5ECBD, 0x40D6BBAE, 0x3E189946), - (0x3CD3FD00, 0x40C6ECC3, 0x3E24B9BD), - (0x3CE1B503, 0x40C0C8DC, 0x3E29F8DA), - (0x3CFEE21B, 0x40B56A5C, 0x3E349FC2), - (0x3EB47B35, 0x3FD79713, 0x3F17FDFC), - (0x3F800000, 0x3F800000, 0x3F800000), - (0x3F800040, 0x3F7FFFC0, 0x3F800020), - (0x3FA97BAA, 0x3F5E79AD, 0x3F9349CB), - (0x3FB5E18D, 0x3F56C249, 0x3F989495), - (0x3FC90FDB, 0x3F4C422A, 0x3FA06C9A), - (0x3FCFB1F9, 0x3F48F861, 0x3FA30C8E), - (0x3FFFC4B1, 0x3F3519EF, 0x3FB4EFFA), - (0x4020E4ED, 0x3F217543, 0x3FCAF358), - (0x403F7694, 0x3F14023B, 0x3FDD6471), - (0x40490FDB, 0x3F106EBA, 0x3FE2DFC4), - (0x41A18EC6, 0x3E63DDE9, 0x408FCDA5), - (0x42B06B8F, 0x3DDA0EB3, 0x411645B9), - (0x46331409, 0x3C190A90, 0x42D61CBA), - (0x4A1C15F4, 0x3A23ED1A, 0x44C7E515), - (0x527736DD, 0x3602412F, 0x48FB919D), - (0x56A91948, 0x33DEBA5C, 0x4B131F06), - (0x71A27292, 0x26633DEC, 0x589032E3), - (0x7F7FFFFF, 0x1F800000, 0x5F7FFFFF), - (0x7F800000, 0x00000000, 0x7F800000), - (0x7FC00000, 0x7FC00000, 0x7FC00000), - (0x80000000, 0xFF800000, 0x80000000), - (0x80400000, 0xFF800000, 0x80000000), - (0xBDFF9977, 0x7FC00000, 0x7FC00000), - (0xBF20930B, 0x7FC00000, 0x7FC00000), - (0xBF46AC52, 0x7FC00000, 0x7FC00000), - (0xBF6EF8AD, 0x7FC00000, 0x7FC00000), - (0xBF800000, 0x7FC00000, 0x7FC00000), - (0xBF9B0F44, 0x7FC00000, 0x7FC00000), - (0xBF9E0E31, 0x7FC00000, 0x7FC00000), - (0xBFF56F61, 0x7FC00000, 0x7FC00000), - (0xC017738C, 0x7FC00000, 0x7FC00000), - (0xC0269500, 0x7FC00000, 0x7FC00000), - (0xC22E7F33, 0x7FC00000, 0x7FC00000), - (0xC36B16DC, 0x7FC00000, 0x7FC00000), - (0xC48E08E1, 0x7FC00000, 0x7FC00000), - (0xC59BB47B, 0x7FC00000, 0x7FC00000), - (0xFF800000, 0x7FC00000, 0x7FC00000), -]; - -/// `fast::sqrt` (`math::fast_sqrt_of`) from Metal's own `rsqrt` is Metal's answer bit for bit: -/// `x · rsqrt(x)`, with the zero of `x`'s sign for a zero or an `f32` denormal and `+inf` for -/// `+inf`, where the product is NaN. -#[test] -fn fast_sqrt_answers_as_metal_from_its_rsqrt() { - let f = float(32); - let cases: Vec = SQRT - .iter() - .map(|(x, r, _)| vec![vec![u64::from(*x)], vec![u64::from(*r)]]) - .collect(); - check_accept( - "fast sqrt f32 against Metal", - &[f, f], - f, - &|fb, a| math::fast_sqrt_of(fb, f, a[0], a[1]), - &cases, - &|c| { - let (x, r) = (arg(c, 0) as u32, arg(c, 1) as u32); - SQRT.iter() - .find(|(a, b, _)| *a == x && *b == r) - .map(|(_, _, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w || (is_nan(f, g) && is_nan(f, w)), - ); -} - /// The fast functions Metal composes are emitted as its compositions, read from the module: /// `fast::exp` is one `Exp2` of a product with `float(log2 e)`, `fast::log` one `Log2` times /// `float(ln 2)`, `fast::powr` and `fast::pow` one `Exp2` of a product with one `Log2`; none reads -/// `Exp`, `Log`, or `Pow`. `fast::sqrt` is the device's `Sqrt` where its functions are not Metal's, -/// and Metal's `x · rsqrt(x)` of one `InverseSqrt` where they are. +/// `Exp`, `Log`, or `Pow`. The functions the device has an instruction for are that instruction +/// alone, on every device and on `float` and `half`: precise `exp`, `log` and `pow` one `Exp`, +/// `Log` and `Pow`, and `fast::sqrt` one `Sqrt`, never Metal's `x · rsqrt(x)`. #[test] fn fast_functions_are_metals_compositions() { const OP_CONSTANT: u32 = 43; @@ -269,7 +187,7 @@ fn fast_functions_are_metals_compositions() { let f = float(32); let read_in = |op: FloatFn, lib: Lib| { let m = kernel(&vec![f; op.arity()], f, &|fb, a| { - math::float_fn(fb, op, f, Contraction::Forbidden, NanTest::IsNan, a, &lib) + math::float_fn(fb, op, f, Contraction::Forbidden, a, &lib) }) .expect("kernel"); let words = crate::spirv::serialize::serialize(m).expect("words").words; @@ -308,8 +226,18 @@ fn fast_functions_are_metals_compositions() { assert_eq!(ext, [0, 0, 0, 1, 1, 0, 0]); let (ext, _, _) = read(FloatFn::Pow); assert_eq!(ext, [1, 0, 0, 0, 0, 0, 0]); - let (ext, _, _) = read(FloatFn::FastSqrt); - assert_eq!(ext, [0, 0, 0, 0, 0, 1, 0]); - let (ext, _, _) = read_in(FloatFn::FastSqrt, Lib::new(Some(Mode::Fast), None)); - assert_eq!(ext, [0, 0, 0, 0, 0, 0, 1]); + for lib in [ + Lib::instructions(), + Lib::new(Some(Mode::Fast), None), + Lib::new(Some(Mode::Precise), None), + ] { + let (ext, _, _) = read_in(FloatFn::FastSqrt, lib); + assert_eq!(ext, [0, 0, 0, 0, 0, 1, 0]); + for (op, want) in [ + (FloatFn::Exp, [0, 1, 0, 0, 0, 0, 0]), + (FloatFn::Log, [0, 0, 1, 0, 0, 0, 0]), + ] { + assert_eq!(read_in(op, lib).0, want, "{op:?}"); + } + } } diff --git a/crates/metal2vulkan/src/lower/arith/tests/fused.rs b/crates/metal2vulkan/src/lower/arith/tests/fused.rs index a719fa794..c708f91c4 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/fused.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/fused.rs @@ -1,5 +1,5 @@ //! Fused multiply-add: every route against one rounding of the exact `a * b + c`, on the -//! interpreter, and Metal's `mix` and `dot` chains over them. +//! interpreter. //! //! The `float` reference is the host's `f32::mul_add` (one rounding, denormals kept); the `half` //! reference rounds the exact sum, formed as an integer multiple of `2^-48`, once to nearest @@ -599,363 +599,3 @@ fn the_fused_multiply_add_route_follows_the_profile() { assert!(f16 >= 1, "{f16} profiles take Metal's 16-bit Fma"); assert!(khr16 >= 2, "{khr16} profiles take OpFmaKHR on 16 bits"); } - -/// Run Metal's `mix` ([`math::metal_mix`]) through `fma`'s route over `cases` and compare with -/// `reference` per lane, as [`check_fma`] does. -fn check_mix( - what: &str, - fma: Fma, - cases: &[Case], - reference: &dyn Fn(u64, u64, u64) -> u64, - exact: bool, -) { - let f = fma.form; - check_accept( - what, - &[f, f, f], - f, - &|fb, x| { - let fused = |fb: &mut FunctionBuilder<'_>, args: &[Value]| fma::emit(fb, fma, args); - math::metal_mix(fb, f, [x[0], x[1], x[2]], &fused) - }, - cases, - &|c| { - Some( - (0..c[0].len()) - .map(|l| reference(c[0][l], c[1][l], c[2][l])) - .collect(), - ) - }, - &|g, w| if exact { g == w } else { same(f)(g, w) }, - ); -} - -/// Metal's recorded `float` `mix(x, y, t)` words, `(x, y, t, answer)`: `nan_functions`' -/// `mix(inf, 1, 0)` is NaN (`fma(-0, inf, inf)`) and `mix(-0, -0, 0)` is `+0`; `nu::mix` -/// (978cc308) at `t = 1` answers `y` where `x + (y - x) * t` loses it; `mix-an-infinite-endpoint` -/// (412028fc) answers NaN for an infinite or NaN endpoint weighted out, `+0` for `mix(1, -0, 1)`, -/// and the ordinary blends. -fn metal_float_mixes() -> Vec<[u64; 4]> { - let (inf, nan) = (f32::INFINITY, f32::NAN); - [ - (inf, 1.0, 0.0, nan), - (-0.0, -0.0, 0.0, 0.0), - (1e10, 1.0, 1.0, 1.0), - (0.0, 7.0, 1.0, 7.0), - (-1e10, 3.0, 1.0, 3.0), - (2.0, 5.0, 1.0, 5.0), - (inf, 5.0, 1.0, nan), - (5.0, inf, 0.0, nan), - (nan, 5.0, 1.0, nan), - (5.0, nan, 0.0, nan), - (inf, inf, 1.0, nan), - (1.0, -0.0, 1.0, 0.0), - (3.0, 7.0, 1.0, 7.0), - (3.0, 7.0, 0.0, 3.0), - (2.0, 4.0, 0.5, 3.0), - ] - .iter() - .map(|&(x, y, t, r): &(f32, f32, f32, f32)| { - let r = if r.is_nan() { 0x7FC0_0000 } else { r.to_bits() }; - [x, y, t] - .map(|v| u64::from(v.to_bits())) - .into_iter() - .chain([u64::from(r)]) - .collect::>() - .try_into() - .expect("four") - }) - .collect() -} - -/// Metal's `mix(x, y, t)` on `float` and `half` is `fma(t, y, fma(-t, x, x))` (MoltenVK's order, -/// and a `half` one's on the 16-bit `Fma`), each fused multiply-add rounding once on its route, on -/// scalars and vectors. Against the composition of each route's reference over the fused -/// multiply-add triples (as `(x, y, t)`), by value, a NaN for a NaN. And Metal's recorded words: -/// [`metal_float_mixes`] on `OpFmaKHR`, and `nan_half`'s `mix(-0.3, 0.7, 0.2)` (`0xB4CD`, `0x399A`, -/// `0x3266`), `0xAE68` where the blend gives `0xAE66`, and `mix(inf, 0, 0)` and `mix(inf, 1, 0.5)`, -/// NaN. -#[test] -fn mix_is_metals_two_fused_multiply_adds() { - let flip32 = |t: u64| t ^ 0x8000_0000; - let triples = float_triples(); - let pinned = metal_float_mixes(); - let reference = move |x: u64, y: u64, t: u64| fma32(t, y, fma32(flip32(t), x, x)); - for lanes in [1u8, 3] { - let fma = Fma { - form: floats(lanes), - route: Route::Khr, - }; - check_mix( - &format!("mix x{lanes}"), - fma, - &lane_cases(&triples, lanes), - &reference, - false, - ); - let rows: Vec<[u64; 3]> = pinned.iter().map(|r| [r[0], r[1], r[2]]).collect(); - let want = |x: u64, y: u64, t: u64| { - pinned - .iter() - .find(|r| [r[0], r[1], r[2]] == [x, y, t]) - .map_or(0, |r| r[3]) - }; - check_mix( - &format!("mix x{lanes}, Metal's words"), - fma, - &lane_cases(&rows, lanes), - &want, - false, - ); - } - let half_triples = half_triples(); - let reference = |x: u64, y: u64, t: u64| fma16(t, y, fma16(t ^ 0x8000, x, x)); - let pinned: [[u64; 4]; 3] = [ - [0xB4CD, 0x399A, 0x3266, 0xAE68], - [0x7C00, 0, 0, 0x7E00], - [0x7C00, 0x3C00, 0x3800, 0x7E00], - ]; - for lanes in [1u8, 2] { - let fma = Fma { - form: vec(float(16), lanes), - route: Route::F16, - }; - check_mix( - &format!("mix half x{lanes}"), - fma, - &lane_cases(&half_triples, lanes), - &reference, - false, - ); - let rows: Vec<[u64; 3]> = pinned.iter().map(|r| [r[0], r[1], r[2]]).collect(); - let want = |x: u64, y: u64, t: u64| { - pinned - .iter() - .find(|r| [r[0], r[1], r[2]] == [x, y, t]) - .map_or(0, |r| r[3]) - }; - check_mix( - &format!("mix half x{lanes}, Metal's words"), - fma, - &lane_cases(&rows, lanes), - &want, - false, - ); - } - // The blend misses Metal's `half` word, which the fused form answers. - let (x, y, t) = (f16_to_f64(0xB4CD), f16_to_f64(0x399A), f16_to_f64(0x3266)); - let q = |v: f64| f16_to_f64(f64_to_f16(v)); - assert_eq!(f64_to_f16(q(q(x * q(1.0 - t)) + q(y * t))), 0xAE66); -} - -/// Metal's recorded `float` `dot` words (a probe of 4,096 lanes; the M3 Max and the M4 answer every -/// word alike, with and without fast math): `x`, `y`, and the `dot` of their first two, three and -/// four lanes, at lanes where the fused chain alone gives all three (every other order of the -/// chain, the pairwise tree, the unfused sum and the exact sum miss one). -const METAL_FLOAT_DOTS: [([u32; 4], [u32; 4], [u32; 3]); 6] = [ - ( - [0xBF1DBDC5, 0xC128181E, 0x3F354B70, 0x3E3EE94D], - [0x40F04319, 0xBEE176DD, 0x3EDB66A8, 0xBFFC6F88], - [0xB599D686, 0x3E9B6015, 0xBD8382FE], - ), - ( - [0x3EF1628A, 0xBEB13510, 0xBFCD5931, 0x3F5BA54E], - [0xC1647CE8, 0xC19B9E64, 0xBF1335AB, 0xBE75DE97], - [0x34226900, 0x3F6C2A8A, 0x3F376D7E], - ), - ( - [0xBF176CF7, 0xBEE9DC9D, 0xBF412D4B, 0x3FEF20EF], - [0x41233C41, 0x41121529, 0xC13A10CB, 0x3F967F46], - [0xC1234799, 0xBFB70024, 0x3F445073], - ), - ( - [0x40E6B4B3, 0x41690D30, 0x3F8F6CD2, 0x3F2017B4], - [0xC10270AC, 0x40812091, 0x3ECD7C24, 0xBED2C469], - [0xB78A61F4, 0x3EE63D39, 0x3E44DDE7], - ), - ( - [0x414EAD1A, 0xBEFDED98, 0xC005B664, 0xC04BDDB4], - [0x41380482, 0x4395C65E, 0x40918EB8, 0xC0049177], - [0x37C39918, 0xC1180D9B, 0xC039EDCB], - ), - ( - [0x3F2121E3, 0xC1504426, 0x40D96C9D, 0x3EC6C559], - [0xBFD689B8, 0xC0608ADE, 0xC0D7159F, 0x402DE9ED], - [0x42327452, 0xBF87085A, 0x37A4C7B4], - ), -]; - -/// As [`METAL_FLOAT_DOTS`], on `half`: lanes where the chain, rounding each step to `half`, -/// gives all three words, and the `float` sum rounded once to `half` misses one. -const METAL_HALF_DOTS: [([u16; 4], [u16; 4], [u16; 3]); 6] = [ - ( - [0xC727, 0xC4B5, 0x44D4, 0xC26F], - [0xC15C, 0xB60C, 0xC3F0, 0x39C3], - [0x4D3D, 0x3F2A, 0xB835], - ), - ( - [0x47FB, 0xBA56, 0xC4DE, 0x322F], - [0xC570, 0xD2DA, 0xBF0B, 0xBB49], - [0x1CF0, 0x484A, 0x4833], - ), - ( - [0x3F28, 0x4464, 0xBE4B, 0xC32A], - [0xB34F, 0x2DF5, 0xB0E5, 0x323D], - [0x8130, 0x33B3, 0xB753], - ), - ( - [0x4B64, 0x42EF, 0x3E65, 0x481C], - [0xB8A4, 0xC01C, 0x4476, 0x3C2C], - [0xCBDA, 0xC849, 0x1680], - ), - ( - [0x3B64, 0x3CF3, 0xCACA, 0xC15F], - [0x4B0C, 0x3847, 0x3CDB, 0x302C], - [0x4AD8, 0xC197, 0xC24A], - ), - ( - [0xB3DD, 0xB0C3, 0xBB51, 0x3CD8], - [0xC76B, 0x4A20, 0x31C7, 0xBA80], - [0x0E80, 0xB145, 0xBC98], - ), -]; - -/// Run Metal's `dot` ([`math::metal_dot`]) of two vectors of `lanes` lanes through `fma`'s route -/// on one lane over `cases` and compare with `reference(x, y)`: bit for bit when `exact`, else any -/// NaN for a NaN. -fn check_dot( - what: &str, - fma: Fma, - lanes: u8, - cases: &[Case], - reference: &dyn Fn(&[u64], &[u64]) -> u64, - exact: bool, -) { - let s = fma.form; - let v = vec(s, lanes); - check_accept( - what, - &[v, v], - s, - &|fb, x| { - let fused = |fb: &mut FunctionBuilder<'_>, args: &[Value]| fma::emit(fb, fma, args); - math::metal_dot(fb, v, [x[0], x[1]], &fused) - }, - cases, - &|c| Some(vec![reference(&c[0], &c[1])]), - &|g, w| if exact { g == w } else { same(s)(g, w) }, - ); -} - -/// The cases of two vectors of `lanes` lanes: `x`'s lanes from the first column of `lanes` -/// consecutive `triples`, `y`'s from the second. -fn dot_cases(triples: &[[u64; 3]], lanes: u8) -> Vec { - let n = usize::from(lanes); - (0..triples.len()) - .step_by(n) - .map(|i| { - (0..2) - .map(|k| { - (0..n) - .map(|l| triples[(i + l) % triples.len()][k]) - .collect() - }) - .collect() - }) - .collect() -} - -/// Metal's `dot` on `float` and `half` is the products' fused chain, `fma(x[n-1], y[n-1], ... -/// fma(x[1], y[1], x[0] * y[0]))` (MoltenVK's order, and a `half` one's on the 16-bit `Fma`), on -/// two, three and four lanes: on `OpFmaKHR` against the chain of its fused multiply-add over the -/// fused multiply-add triples and against Metal's recorded words ([`METAL_FLOAT_DOTS`], bit for -/// bit); on the 16-bit `Fma` the same against the `half` chain and [`METAL_HALF_DOTS`]. -#[test] -fn dot_is_metals_fused_chain() { - let triples = float_triples(); - let reference = |x: &[u64], y: &[u64]| { - let mut sum = u64::from((f32v(x[0]) * f32v(y[0])).to_bits()); - for l in 1..x.len() { - sum = fma32(x[l], y[l], sum); - } - sum - }; - let fma = Fma { - form: floats(1), - route: Route::Khr, - }; - for lanes in [2u8, 3, 4] { - let what = format!("dot x{lanes}"); - let cases = dot_cases(&triples, lanes); - check_dot(&what, fma, lanes, &cases, &reference, false); - let n = usize::from(lanes); - let pinned: Vec = METAL_FLOAT_DOTS - .iter() - .map(|(x, y, _)| { - [x, y] - .map(|v| v[..n].iter().map(|b| u64::from(*b)).collect()) - .to_vec() - }) - .collect(); - let want = |x: &[u64], _: &[u64]| { - METAL_FLOAT_DOTS - .iter() - .find(|(mx, ..)| mx[..n].iter().map(|b| u64::from(*b)).eq(x.iter().copied())) - .map_or(0, |(.., w)| u64::from(w[n - 2])) - }; - check_dot( - &format!("{what}, Metal's words"), - fma, - lanes, - &pinned, - &want, - true, - ); - } - let half_triples = half_triples(); - let reference = |x: &[u64], y: &[u64]| { - let mut sum = fma16(x[0], y[0], 0x8000); - for l in 1..x.len() { - sum = fma16(x[l], y[l], sum); - } - sum - }; - let fma = Fma { - form: float(16), - route: Route::F16, - }; - for lanes in [2u8, 3, 4] { - let what = format!("dot half x{lanes}"); - check_dot( - &what, - fma, - lanes, - &dot_cases(&half_triples, lanes), - &reference, - false, - ); - let n = usize::from(lanes); - let pinned: Vec = METAL_HALF_DOTS - .iter() - .map(|(x, y, _)| { - [x, y] - .map(|v| v[..n].iter().map(|b| u64::from(*b)).collect()) - .to_vec() - }) - .collect(); - let want = |x: &[u64], _: &[u64]| { - METAL_HALF_DOTS - .iter() - .find(|(mx, ..)| mx[..n].iter().map(|b| u64::from(*b)).eq(x.iter().copied())) - .map_or(0, |(.., w)| u64::from(w[n - 2])) - }; - check_dot( - &format!("{what}, Metal's words"), - fma, - lanes, - &pinned, - &want, - true, - ); - } -} diff --git a/crates/metal2vulkan/src/lower/arith/tests/libm.rs b/crates/metal2vulkan/src/lower/arith/tests/libm.rs index 0df3d442c..15b679ebb 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/libm.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/libm.rs @@ -63,7 +63,6 @@ fn fmod_module(f: Form) -> TypedModule { FloatFn::Fmod, f, Contraction::Forbidden, - NanTest::IsNan, x, &Lib::new(None, funcs.first().copied()), ) diff --git a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs index 6e52f09e6..3cb6fac52 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs @@ -746,10 +746,6 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) { FloatFn::MulAdd, FloatFn::Sqrt, ] { - // A `half` `mix` is its own strategy, Metal's fused form (`tests::fused`). - if op == FloatFn::Mix && is_half { - continue; - } let arity = op.arity(); let cases: Vec = if arity == 1 { vals.iter().map(|v| vec![vec![*v]]).collect() @@ -784,17 +780,7 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) { &format!("{op:?} {f:?}"), &vec![f; arity], f, - &|fb, x| { - math::float_fn( - fb, - op, - f, - Contraction::Forbidden, - NanTest::IsNan, - x, - &Lib::instructions(), - ) - }, + &|fb, x| math::float_fn(fb, op, f, Contraction::Forbidden, x, &Lib::instructions()), &cases, &|c| { let x = |i: usize| nval(f, c[i][0]); @@ -805,17 +791,19 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) { FloatFn::Floor => x(0).floor(), FloatFn::Ceil => x(0).ceil(), FloatFn::Trunc => x(0).trunc(), - FloatFn::Round => metal_round(is_half, x(0)), + FloatFn::Round => c99_round(x(0)), FloatFn::Rint => x(0).round_ties_even(), - FloatFn::Fract if x(0).is_nan() => f64::NAN, - FloatFn::Fract if x(0).is_infinite() => 0.0, + // The device's `Fract`: a NaN at a NaN and an infinity. + FloatFn::Fract if !x(0).is_finite() => f64::NAN, FloatFn::Fract => { let below = 1.0 - 2f64.powi(if is_half { -11 } else { -8 }); q(x(0) - x(0).floor()).min(below) } + // The device's `FSign`, undefined at a NaN; a zero keeps its sign. + FloatFn::Sign if x(0).is_nan() => return None, FloatFn::Sign if x(0) > 0.0 => 1.0, FloatFn::Sign if x(0) < 0.0 => -1.0, - FloatFn::Sign => 0.0, + FloatFn::Sign => x(0), FloatFn::Saturate if x(0) > 0.0 => x(0).min(1.0), FloatFn::Saturate => 0.0, FloatFn::Min => x(0).min(x(1)), @@ -825,7 +813,12 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) { FloatFn::Max3 => x(0).max(x(1)).max(x(2)), FloatFn::Median3 => { let b = [c[0][0], c[1][0], c[2][0]]; - return Some(vec![median3_ref(b, &|v| nval(f, v), false)]); + return Some(vec![median3_ref(b, &|v| nval(f, v))]); + } + // A `half` one the device's `FMix` in `float`, rounded once. + FloatFn::Mix if is_half => { + let (p, y, t) = (x(0) as f32, x(1) as f32, x(2) as f32); + f64::from(p * (1.0 - t) + y * t) } FloatFn::Mix => q(x(0) * q(1.0 - x(2))) + q(x(1) * x(2)), FloatFn::MulAdd => q(q(x(0) * x(1)) + x(2)), @@ -838,58 +831,6 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) { } } -/// Class K: Metal's `half` `fract` with every fast-math flag (`nan_half_fast`) answers the largest -/// `half` below one, `0x3BFF`, for a NaN and for either infinity, where without flags (`nan_half`) -/// a NaN is a NaN (its bits the device's widening's) and an infinity `+0`; every finite lane is the -/// precise one's, its difference rounded once. -#[test] -fn flagged_half_fract_answers_below_one_at_nans_and_infinities() { - let mut halves: Vec = (0..0x10000u64).step_by(97).collect(); - halves.extend([ - 0, 0x8000, 0x7C00, 0xFC00, 0x7C01, 0xFE00, 0x7E00, 0x3BFF, 0xBC00, 0x8001, - ]); - for lanes in [1u8, 3] { - let f = vec(float(16), lanes); - let n = usize::from(lanes); - let cases: Vec = halves.iter().map(|&x| vec![vec![x; n]]).collect(); - let run = |op: FloatFn, c: &Case| { - let x = f16_to_f64(c[0][0] as u16); - let r = if x.is_nan() || x.is_infinite() { - match op { - FloatFn::FlaggedFract => 0x3BFF, - _ if x.is_nan() => c[0][0], - _ => 0, - } - } else { - let d = f16_to_f64(nbits(half(), x - x.floor()) as u16); - u64::from(f64_to_f16(d.min(1.0 - 2f64.powi(-11)))) - }; - Some(vec![r; n]) - }; - for op in [FloatFn::Fract, FloatFn::FlaggedFract] { - check_accept( - &format!("{op:?} x{lanes}"), - &[f], - f, - &|fb, x| { - math::float_fn( - fb, - op, - f, - Contraction::Forbidden, - NanTest::Bits, - x, - &Lib::instructions(), - ) - }, - &cases, - &|c| run(op, c), - &exact_ok(f), - ); - } - } -} - /// The `f32` operands [`converted_half_rounding_is_the_exactly_rounded_half`] rounds to `half`: /// every 17th half pattern and every denormal one, each exactly and at its exact ties with both /// neighbours, just inside and outside them, and the `f32` edge values (the ties at the smallest @@ -1517,7 +1458,6 @@ fn bfloat_fma_rounds_once() { FloatFn::Fma, f, Contraction::Forbidden, - NanTest::IsNan, x, &Lib::instructions(), ) @@ -2606,13 +2546,15 @@ fn a_vector_unpack_reads_every_field_value_of_every_channel() { } } -/// The census names the sRGB conversions apart from the other normalized formats, and charges the -/// module's table once, to the direction that first reads it: an output-size exception for the sRGB -/// conversions excuses no word of another pack or unpack. +/// `air.pack` and `air.unpack` of `unorm4x8_srgb` read no table: the census names them as the +/// other normalized formats, and charges Metal's sRGB table, which a tile's, attachment's or +/// texture's conversion reads, once, to the direction that first reads it. #[test] -fn srgb_conversions_are_named_apart_and_charge_their_table_once() { +fn srgb_packs_read_no_table_and_the_table_charges_once() { use crate::air::intrinsics::{PackDir, PackFormat as P}; - use crate::lower::arith::{routine_words, srgb, ArithPlan, ArithStrategy}; + use crate::lower::arith::{ + routine_words, srgb, ArithPlan, ArithStrategy, SRGB_PACK, SRGB_UNPACK, + }; use crate::lower::select::FamilyPlans; use crate::lower::strategy::FamilyStrategy; let name = |dir, format| { @@ -2624,11 +2566,11 @@ fn srgb_conversions_are_named_apart_and_charge_their_table_once() { .name(&FamilyPlans::default()) .into_owned() }; - assert_eq!(name(PackDir::Pack, P::Unorm4x8Srgb), "arith.pack.srgb"); - assert_eq!(name(PackDir::Unpack, P::Unorm4x8Srgb), "arith.unpack.srgb"); + assert_eq!(name(PackDir::Pack, P::Unorm4x8Srgb), "arith.pack"); + assert_eq!(name(PackDir::Unpack, P::Unorm4x8Srgb), "arith.unpack"); assert_eq!(name(PackDir::Pack, P::Unorm4x8), "arith.pack"); assert_eq!(name(PackDir::Unpack, P::UnormRgb10a2), "arith.unpack"); - for dir in [PackDir::Pack, PackDir::Unpack] { + for (dir, table) in [(PackDir::Pack, SRGB_PACK), (PackDir::Unpack, SRGB_UNPACK)] { let plan = ArithPlan { srgb: Some(dir), ..ArithPlan::default() @@ -2638,7 +2580,7 @@ fn srgb_conversions_are_named_apart_and_charge_their_table_once() { .collect(); assert_eq!( charged, - vec![(name(dir, P::Unorm4x8Srgb), u64::from(srgb::TABLE_WORDS))] + vec![(table.to_owned(), u64::from(srgb::TABLE_WORDS))] ); } assert_eq!(routine_words(&ArithPlan::default()).count(), 0); diff --git a/crates/metal2vulkan/src/lower/arith/tests/pack.rs b/crates/metal2vulkan/src/lower/arith/tests/pack.rs new file mode 100644 index 000000000..245d38320 --- /dev/null +++ b/crates/metal2vulkan/src/lower/arith/tests/pack.rs @@ -0,0 +1,248 @@ +//! `air.pack` and `air.unpack` of the normalized formats by the device's conversion +//! ([`super::super::pack`]): the four formats `GLSL.std.450` names are its `Pack` and `Unpack` +//! instruction alone; `rgb10a2` and `rgb565` the instruction's definition by the device's clamp, +//! multiply, `RoundEven` and division; `unorm4x8_srgb` the MSL transfer functions by `Pow` around +//! the 8-bit instruction. Values on the interpreter's model of each instruction, one answer Vulkan +//! allows (its `Round` ties to even). + +use super::*; +use crate::air::intrinsics::{PackDir, PackFormat as P}; +use crate::lower::arith::pack; +use crate::spv::GlslStd450Op as G; + +/// The `GLSL.std.450` instruction numbers module `m` uses, once per use, and its `OpFMul` count. +fn instructions(m: TypedModule) -> (Vec, usize) { + const OP_EXT_INST: u32 = 12; + const OP_FMUL: u32 = 133; + let words = crate::spirv::serialize::serialize(m).expect("words").words; + let (mut ext, mut fmul) = (Vec::new(), 0); + let mut i = 5; + while i < words.len() { + let (n, code) = ((words[i] >> 16) as usize, words[i] & 0xFFFF); + if code == OP_EXT_INST { + ext.extend(words.get(i + 4).copied()); + } + if code == OP_FMUL { + fmul += 1; + } + i += n.max(1); + } + ext.sort_unstable(); + (ext, fmul) +} + +/// The channel layout of `format`: each field's width, and whether it is signed. +fn layout(format: P) -> (Vec, bool) { + let (widths, snorm) = math::pack_layout(format).expect("lowered"); + (widths.to_vec(), snorm) +} + +/// The GLSL definition of a pack's field of `w` bits: `round(clamp(c) * s)`, the product rounded +/// to `float` and the tie to even, masked to the field. +fn code(c: f32, w: u32, snorm: bool) -> u64 { + let s = if snorm { + ((1u32 << (w - 1)) - 1) as f32 + } else { + ((1u32 << w) - 1) as f32 + }; + let lo = if snorm { -1.0 } else { 0.0 }; + let q = (c.clamp(lo, 1.0) * s).round_ties_even() as i32; + u64::from(q as u32) & ((1u64 << w) - 1) +} + +/// An unpack's field `f` of `w` bits: `f / s` correctly rounded by an instruction (`named`), else +/// `f` times `float(1 / s)`; a signed one sign-extended and at least `-1`. +fn value(f: u64, w: u32, snorm: bool, named: bool) -> f32 { + let (v, s) = if snorm { + ( + ((f << (64 - w)) as i64 >> (64 - w)) as f32, + ((1u32 << (w - 1)) - 1) as f32, + ) + } else { + (f as f32, ((1u32 << w) - 1) as f32) + }; + let q = if named { v / s } else { v * (1.0 / s) }; + if snorm { + q.max(-1.0) + } else { + q + } +} + +const VALUES: [f32; 18] = [ + 0.0, + -0.0, + 1.0, + -1.0, + 0.5, + -0.5, + 0.25, + 0.75, + 0.1, + -0.3, + 1.5, + -2.0, + 0.998, + 0.0019, + 0.501_960_8, + 0.498_039_2, + 1e-30, + -1e30, +]; + +/// A pack of the four named formats is its `GLSL.std.450` instruction alone, with no product of +/// its own; `rgb10a2` and `rgb565` take the device's `NClamp`, one product and `RoundEven`; an +/// unpack of the four named formats is the `Unpack` instruction, and of the others the device's +/// product with the scale's reciprocal. Every field answers the instruction's definition, on +/// `float` and `half` lanes. +#[test] +fn normalized_packs_are_the_device_instructions() { + let formats = [ + ( + P::Unorm4x8, + Some((GlslOp::PackUnorm4x8, GlslOp::UnpackUnorm4x8)), + ), + ( + P::Snorm4x8, + Some((GlslOp::PackSnorm4x8, GlslOp::UnpackSnorm4x8)), + ), + ( + P::Unorm2x16, + Some((GlslOp::PackUnorm2x16, GlslOp::UnpackUnorm2x16)), + ), + ( + P::Snorm2x16, + Some((GlslOp::PackSnorm2x16, GlslOp::UnpackSnorm2x16)), + ), + (P::UnormRgb10a2, None), + (P::SnormRgb10a2, None), + (P::UnormRgb565, None), + ]; + for (format, named) in formats { + let (widths, snorm) = layout(format); + let lanes = widths.len() as u8; + let word = int(math::packed_bits(format)); + assert_eq!( + pack::instruction(format, PackDir::Pack).is_some(), + named.is_some(), + "{format:?}" + ); + for lane in [float(32), float(16)] { + let f = vec(lane, lanes); + let half = lane.float_fmt() == Some(FloatFmt::Half); + let words = + |m: TypedModule| crate::spirv::serialize::serialize(m).expect("words").words; + let packed = + kernel(&[f], word, &|fb, x| pack::pack(fb, format, f, x[0])).expect("pack kernel"); + let unpacked = kernel(&[word], f, &|fb, x| pack::unpack(fb, format, f, x[0])) + .expect("unpack kernel"); + match named { + Some((p, u)) => { + // The instruction alone: the module is the bare instruction's (an unpack to + // `half` rounded once). + let bare = kernel(&[f], word, &|fb, x| fb.glsl(p, &[x[0]])).expect("bare pack"); + assert_eq!(words(packed), words(bare), "{format:?} {lane:?}"); + let bare = kernel(&[word], f, &|fb, x| { + let q = fb.glsl(u, &[x[0]])?; + crate::lower::arith::narrow::round(fb, f, q) + }) + .expect("bare unpack"); + assert_eq!(words(unpacked), words(bare), "{format:?} {lane:?}"); + } + None => { + let (pack_ext, pack_fmul) = instructions(packed); + for g in [G::NClamp, G::RoundEven] { + assert!(pack_ext.contains(&(g as u32)), "{format:?} {g:?}"); + } + if !half { + assert_eq!(pack_fmul, 1, "{format:?} {lane:?}"); + } + } + } + // A lane's bits in its format, and its value. + let bits = |c: f32| { + if half { + u64::from(f64_to_f16(f64::from(c))) + } else { + u64::from(c.to_bits()) + } + }; + let read = |b: u64| { + if half { + f16_to_f64(b as u16) as f32 + } else { + f32::from_bits(b as u32) + } + }; + let cases: Vec = (0..VALUES.len()) + .map(|i| { + vec![(0..usize::from(lanes)) + .map(|k| bits(VALUES[(i + 3 * k) % VALUES.len()])) + .collect()] + }) + .collect(); + check( + &format!("pack {format:?} from {lane:?}"), + &[f], + word, + &|fb, x| pack::pack(fb, format, f, x[0]), + &cases, + &|c| { + let mut at = 0; + let mut out = 0u64; + for (k, w) in widths.iter().enumerate() { + out |= code(read(c[0][k]), *w, snorm) << at; + at += w; + } + Some(vec![out]) + }, + false, + ); + let mut rng = Rng(0x5EED_0000 | u64::from(lanes)); + let words: Vec = (0..64) + .map(|_| vec![vec![rng.next() & mask(math::packed_bits(format))]]) + .chain([vec![vec![0]], vec![vec![mask(math::packed_bits(format))]]]) + .collect(); + check( + &format!("unpack {format:?} to {lane:?}"), + &[word], + f, + &|fb, x| pack::unpack(fb, format, f, x[0]), + &words, + &|c| { + let mut at = 0; + let mut out = Vec::new(); + for w in &widths { + let field = (c[0][0] >> at) & ((1u64 << w) - 1); + let v = value(field, *w, snorm, named.is_some()); + out.push(bits(v)); + at += w; + } + Some(out) + }, + false, + ); + } + } +} + +/// `unorm4x8_srgb`'s colour channels are the MSL transfer functions by the device's `Pow`, around +/// the 8-bit instruction, no table read: an encode takes one `Pow` and `PackUnorm4x8`, a decode +/// `UnpackUnorm4x8` and one `Pow`. (The interpreter models no `Pow`, so no value is run.) +#[test] +fn srgb_packs_are_the_transfer_functions_by_the_devices_pow() { + let f = vec(float(32), 4); + let word = int(32); + let packed = kernel(&[f], word, &|fb, x| { + pack::pack(fb, P::Unorm4x8Srgb, f, x[0]) + }) + .expect("pack"); + let (ext, _) = instructions(packed); + assert_eq!(ext, vec![G::Pow as u32, G::PackUnorm4x8 as u32]); + let unpacked = kernel(&[word], f, &|fb, x| { + pack::unpack(fb, P::Unorm4x8Srgb, f, x[0]) + }) + .expect("unpack"); + let (ext, _) = instructions(unpacked); + assert_eq!(ext, vec![G::Pow as u32, G::UnpackUnorm4x8 as u32]); +} diff --git a/crates/metal2vulkan/src/lower/arith/tests/specials.rs b/crates/metal2vulkan/src/lower/arith/tests/specials.rs index 325460860..116d16666 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/specials.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/specials.rs @@ -1,8 +1,8 @@ -//! Metal's `sign`, `fract`, `saturate`, `median3`, and `pow` at their special operands, on the -//! interpreter against Metal's recorded answers (Apple M3 Max, ORACLE_ABI v34), bit for bit: every -//! distinct lane of the A1 cases `fract-saturate-and-median3-at-nan-infinity-and-signed-zero` -//! (aed3faaa) and `sign-of-zero-and-division-range-{without,under}-fast-math` (87d13612, f9a12252, -//! whose `sign` answers agree lane for lane), and the lanes of `pow-at-every-c99-special-operand` +//! Metal's `saturate`, `median3`, and `pow` at their special operands, on the interpreter against +//! Metal's recorded answers (Apple M3 Max, ORACLE_ABI v34), bit for bit: every distinct lane of the +//! A1 case `fract-saturate-and-median3-at-nan-infinity-and-signed-zero` (aed3faaa) but those whose +//! answer is the device's instruction's (`median3`'s ties), and the lanes of +//! `pow-at-every-c99-special-operand` //! (116e052a) with a NaN operand, the exponent one, a denormal exponent, or a negative denormal //! base to a non-integral exponent. The operands are signed zeros, `f32` and `half` denormals, the //! smallest normals, values beside the integers, the largest finite values, infinities, and NaNs @@ -10,126 +10,48 @@ use super::*; -/// `(x, precise::fract, fast::fract, saturate, hx, half fract, half saturate)`: `float` then -/// `half` operands and answers (`precise::saturate` and `fast::saturate` agree on every lane). -const FRACT_SATURATE: [(u32, u32, u32, u32, u16, u16, u16); 39] = [ - ( - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x0000, 0x0000, 0x0000, - ), - ( - 0x80000000, 0x00000000, 0x00000000, 0x00000000, 0x8000, 0x0000, 0x0000, - ), - ( - 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x0001, 0x0001, 0x0001, - ), - ( - 0x80000001, 0x00000000, 0x00000000, 0x00000000, 0x8001, 0x3BFF, 0x0000, - ), - ( - 0x007FFFFF, 0x00000000, 0x00000000, 0x00000000, 0x03FF, 0x03FF, 0x03FF, - ), - ( - 0x807FFFFF, 0x00000000, 0x00000000, 0x00000000, 0x83FF, 0x3BFF, 0x0000, - ), - ( - 0x00800000, 0x00800000, 0x00800000, 0x00800000, 0x0400, 0x0400, 0x0400, - ), - ( - 0x80800000, 0x3F7FFFFF, 0x3F800000, 0x00000000, 0x8400, 0x3BFF, 0x0000, - ), - ( - 0xB3000000, 0x3F7FFFFF, 0x3F800000, 0x00000000, 0x8C00, 0x3BFF, 0x0000, - ), - ( - 0xB3800000, 0x3F7FFFFF, 0x3F7FFFFF, 0x00000000, 0x9000, 0x3BFF, 0x0000, - ), - ( - 0xAEDBE6FF, 0x3F7FFFFF, 0x3F800000, 0x00000000, 0x868E, 0x3BFF, 0x0000, - ), - ( - 0x3F000000, 0x3F000000, 0x3F000000, 0x3F000000, 0x3800, 0x3800, 0x3800, - ), - ( - 0xBF000000, 0x3F000000, 0x3F000000, 0x00000000, 0xB800, 0x3800, 0x0000, - ), - ( - 0x3FC00000, 0x3F000000, 0x3F000000, 0x3F800000, 0x3E00, 0x3800, 0x3C00, - ), - ( - 0xBFC00000, 0x3F000000, 0x3F000000, 0x00000000, 0xBE00, 0x3800, 0x0000, - ), - ( - 0x3F800000, 0x00000000, 0x00000000, 0x3F800000, 0x3C00, 0x0000, 0x3C00, - ), - ( - 0xBF800000, 0x00000000, 0x00000000, 0x00000000, 0xBC00, 0x0000, 0x0000, - ), - ( - 0x3F7FFFFF, 0x3F7FFFFF, 0x3F7FFFFF, 0x3F7FFFFF, 0x3BFF, 0x3BFF, 0x3BFF, - ), - ( - 0xBF7FFFFF, 0x33800000, 0x33800000, 0x00000000, 0xBBFF, 0x1000, 0x0000, - ), - ( - 0x3F800001, 0x34000000, 0x34000000, 0x3F800000, 0x3C01, 0x1400, 0x3C00, - ), - ( - 0xBF800001, 0x3F7FFFFE, 0x3F7FFFFE, 0x00000000, 0xBC01, 0x3BFE, 0x0000, - ), - ( - 0x4A800001, 0x3F000000, 0x3F000000, 0x3F800000, 0x6001, 0x3800, 0x3C00, - ), - ( - 0xCA800001, 0x3F000000, 0x3F000000, 0x00000000, 0xE001, 0x3800, 0x0000, - ), - ( - 0x4B800000, 0x00000000, 0x00000000, 0x3F800000, 0x6800, 0x0000, 0x3C00, - ), - ( - 0xCB800000, 0x00000000, 0x00000000, 0x00000000, 0xE800, 0x0000, 0x0000, - ), - ( - 0x7F7FFFFF, 0x00000000, 0x00000000, 0x3F800000, 0x7BFF, 0x0000, 0x3C00, - ), - ( - 0xFF7FFFFF, 0x00000000, 0x00000000, 0x00000000, 0xFBFF, 0x0000, 0x0000, - ), - ( - 0x7F800000, 0x00000000, 0x00000000, 0x3F800000, 0x7C00, 0x0000, 0x3C00, - ), - ( - 0xFF800000, 0x00000000, 0x00000000, 0x00000000, 0xFC00, 0x0000, 0x0000, - ), - ( - 0x7FC00000, 0x7FC00000, 0x7FC00000, 0x00000000, 0x7E00, 0x7E00, 0x0000, - ), - ( - 0xFFC00000, 0x7FC00000, 0x7FC00000, 0x00000000, 0xFE00, 0xFE00, 0x0000, - ), - ( - 0x7F800001, 0x7FC00000, 0x7FC00000, 0x00000000, 0x7C01, 0x7C01, 0x0000, - ), - ( - 0xFF800001, 0x7FC00000, 0x7FC00000, 0x00000000, 0xFC01, 0xFC01, 0x0000, - ), - ( - 0x7FBFFFFF, 0x7FC00000, 0x7FC00000, 0x00000000, 0x7DFF, 0x7DFF, 0x0000, - ), - ( - 0x40300000, 0x3F400000, 0x3F400000, 0x3F800000, 0x4180, 0x3A00, 0x3C00, - ), - ( - 0xC0300000, 0x3E800000, 0x3E800000, 0x00000000, 0xC180, 0x3400, 0x0000, - ), - ( - 0x3F8CCCCD, 0x3DCCCCD0, 0x3DCCCCD0, 0x3F800000, 0x3C66, 0x2E60, 0x3C00, - ), - ( - 0x40000000, 0x00000000, 0x00000000, 0x3F800000, 0x4000, 0x0000, 0x3C00, - ), - ( - 0x3E800000, 0x3E800000, 0x3E800000, 0x3E800000, 0x3400, 0x3400, 0x3400, - ), +/// `(x, saturate, hx, half saturate)`: `float` then `half` operands and answers +/// (`precise::saturate` and `fast::saturate` agree on every lane). +const SATURATE: [(u32, u32, u16, u16); 39] = [ + (0x00000000, 0x00000000, 0x0000, 0x0000), + (0x80000000, 0x00000000, 0x8000, 0x0000), + (0x00000001, 0x00000000, 0x0001, 0x0001), + (0x80000001, 0x00000000, 0x8001, 0x0000), + (0x007FFFFF, 0x00000000, 0x03FF, 0x03FF), + (0x807FFFFF, 0x00000000, 0x83FF, 0x0000), + (0x00800000, 0x00800000, 0x0400, 0x0400), + (0x80800000, 0x00000000, 0x8400, 0x0000), + (0xB3000000, 0x00000000, 0x8C00, 0x0000), + (0xB3800000, 0x00000000, 0x9000, 0x0000), + (0xAEDBE6FF, 0x00000000, 0x868E, 0x0000), + (0x3F000000, 0x3F000000, 0x3800, 0x3800), + (0xBF000000, 0x00000000, 0xB800, 0x0000), + (0x3FC00000, 0x3F800000, 0x3E00, 0x3C00), + (0xBFC00000, 0x00000000, 0xBE00, 0x0000), + (0x3F800000, 0x3F800000, 0x3C00, 0x3C00), + (0xBF800000, 0x00000000, 0xBC00, 0x0000), + (0x3F7FFFFF, 0x3F7FFFFF, 0x3BFF, 0x3BFF), + (0xBF7FFFFF, 0x00000000, 0xBBFF, 0x0000), + (0x3F800001, 0x3F800000, 0x3C01, 0x3C00), + (0xBF800001, 0x00000000, 0xBC01, 0x0000), + (0x4A800001, 0x3F800000, 0x6001, 0x3C00), + (0xCA800001, 0x00000000, 0xE001, 0x0000), + (0x4B800000, 0x3F800000, 0x6800, 0x3C00), + (0xCB800000, 0x00000000, 0xE800, 0x0000), + (0x7F7FFFFF, 0x3F800000, 0x7BFF, 0x3C00), + (0xFF7FFFFF, 0x00000000, 0xFBFF, 0x0000), + (0x7F800000, 0x3F800000, 0x7C00, 0x3C00), + (0xFF800000, 0x00000000, 0xFC00, 0x0000), + (0x7FC00000, 0x00000000, 0x7E00, 0x0000), + (0xFFC00000, 0x00000000, 0xFE00, 0x0000), + (0x7F800001, 0x00000000, 0x7C01, 0x0000), + (0xFF800001, 0x00000000, 0xFC01, 0x0000), + (0x7FBFFFFF, 0x00000000, 0x7DFF, 0x0000), + (0x40300000, 0x3F800000, 0x4180, 0x3C00), + (0xC0300000, 0x00000000, 0xC180, 0x0000), + (0x3F8CCCCD, 0x3F800000, 0x3C66, 0x3C00), + (0x40000000, 0x3F800000, 0x4000, 0x3C00), + (0x3E800000, 0x3E800000, 0x3400, 0x3400), ]; /// `(a, b, c, precise::median3, fast::median3, ha, hb, hc, half median3)`. @@ -286,48 +208,6 @@ const MEDIAN3: [(u32, u32, u32, u32, u32, u16, u16, u16, u16); 50] = [ ), ]; -/// `(x, sign(x))` of `float`, precise and fast alike. -const SIGN_F32: [(u32, u32); 17] = [ - (0x00000000, 0x00000000), - (0x80000000, 0x00000000), - (0x00000001, 0x00000000), - (0x80000001, 0x00000000), - (0x3F800000, 0x3F800000), - (0xBF800000, 0xBF800000), - (0x3F000000, 0x3F800000), - (0xBF000000, 0xBF800000), - (0x7F800000, 0x3F800000), - (0xFF800000, 0xBF800000), - (0x7FC00000, 0x00000000), - (0xFFC00000, 0x00000000), - (0x7F7FFFFF, 0x3F800000), - (0xFF7FFFFF, 0xBF800000), - (0x00800000, 0x3F800000), - (0x80800000, 0xBF800000), - (0x40000000, 0x3F800000), -]; - -/// `(x, sign(x))` of `half`. -const SIGN_HALF: [(u16, u16); 17] = [ - (0x0000, 0x0000), - (0x8000, 0x0000), - (0x0001, 0x3C00), - (0x8001, 0xBC00), - (0x3C00, 0x3C00), - (0xBC00, 0xBC00), - (0x3800, 0x3C00), - (0xB800, 0xBC00), - (0x7C00, 0x3C00), - (0xFC00, 0xBC00), - (0x7E00, 0x0000), - (0xFE00, 0x0000), - (0x7BFF, 0x3C00), - (0xFBFF, 0xBC00), - (0x0400, 0x3C00), - (0x8400, 0xBC00), - (0x4000, 0x3C00), -]; - /// `(x, y, precise::pow, fast::pow, hx, hy, half pow)`. const POW: [(u32, u32, u32, u32, u16, u16, u16); 90] = [ ( @@ -616,17 +496,7 @@ fn metal_answers(op: FloatFn, f: Form, rows: &[Row]) { &format!("{op:?} {f:?} against Metal"), &vec![f; op.arity()], f, - &|fb, x| { - math::float_fn( - fb, - op, - f, - Contraction::Forbidden, - NanTest::IsNan, - x, - &Lib::instructions(), - ) - }, + &|fb, x| math::float_fn(fb, op, f, Contraction::Forbidden, x, &Lib::instructions()), &cases, &|c| { let ops: Vec = c.iter().map(|l| l[0]).collect(); @@ -639,112 +509,54 @@ fn metal_answers(op: FloatFn, f: Form, rows: &[Row]) { } #[test] -fn fract_and_saturate_answer_as_metal() { - let rows = |x: fn(&(u32, u32, u32, u32, u16, u16, u16)) -> [u64; 2]| -> Vec { - FRACT_SATURATE - .iter() - .map(|r| { - let [x, want] = x(r); - (vec![x], want) - }) - .collect() - }; - let (f32_, half) = (float(32), float(16)); - metal_answers( - FloatFn::Fract, - f32_, - &rows(|r| [u64::from(r.0), u64::from(r.1)]), - ); - metal_answers( - // A1 case aed3faaa calls `fast::fract` without fast-math flags. - FloatFn::FastFract { - infinite_nan: false, - }, - f32_, - &rows(|r| [u64::from(r.0), u64::from(r.2)]), - ); +fn saturate_answers_as_metal() { // `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() + let f32_: Vec = SATURATE + .iter() + .map(|r| (vec![u64::from(r.0)], u64::from(r.1))) .filter(normal) .collect(); - metal_answers(FloatFn::Saturate, f32_, &saturate); - metal_answers( - FloatFn::Fract, - half, - &rows(|r| [u64::from(r.4), u64::from(r.5)]), - ); - metal_answers( - FloatFn::Saturate, - half, - &rows(|r| [u64::from(r.4), u64::from(r.6)]), - ); + metal_answers(FloatFn::Saturate, float(32), &f32_); + let half: Vec = SATURATE + .iter() + .map(|r| (vec![u64::from(r.2)], u64::from(r.3))) + .collect(); + metal_answers(FloatFn::Saturate, float(16), &half); } +/// `median3` is `min(max(c, min(a, b)), max(a, b))` of the device's `NMin` and `NMax`, which the +/// interpreter answers as Metal's `fmin` and `fmax`: Metal's own answer at every lane where fewer +/// than two operands are NaN and, on `float`, none is an `f32` denormal (the device's reading of +/// one, and its pick of two NaNs, are `PrecisionNote::NativeMinMax`'s; `fast::median3`'s `b` of two +/// NaN first operands among them). #[test] -fn median3_answers_as_metal() { - type M = (u32, u32, u32, u32, u32, u16, u16, u16, u16); - let rows = |x: fn(&M) -> [u64; 4]| -> Vec { - MEDIAN3 - .iter() - .map(|r| { - let [a, b, c, want] = x(r); - (vec![a, b, c], want) - }) - .collect() +fn median3_answers_as_metal_but_at_its_recorded_ties() { + let f32_nan = |b: u64| b & 0x7FFF_FFFF > 0x7F80_0000; + let f32_denormal = |b: u64| b & 0x7F80_0000 == 0 && b & 0x007F_FFFF != 0; + let half_nan = |b: u64| b & 0x7FFF > 0x7C00; + let keep = |ops: &[u64], nan: &dyn Fn(u64) -> bool, denormal: &dyn Fn(u64) -> bool| { + ops.iter().filter(|b| nan(**b)).count() < 2 && !ops.iter().any(|b| denormal(*b)) }; - metal_answers( - FloatFn::Median3, - float(32), - &rows(|r| { - [ - u64::from(r.0), - u64::from(r.1), - u64::from(r.2), - u64::from(r.3), - ] - }), - ); - metal_answers( - FloatFn::FastMedian3, - float(32), - &rows(|r| { - [ - u64::from(r.0), - u64::from(r.1), - u64::from(r.2), - u64::from(r.4), - ] - }), - ); - metal_answers( - FloatFn::Median3, - float(16), - &rows(|r| { - [ - u64::from(r.5), - u64::from(r.6), - u64::from(r.7), - u64::from(r.8), - ] - }), - ); -} - -#[test] -fn sign_answers_as_metal() { - let f: Vec = SIGN_F32 - .iter() - .map(|(x, s)| (vec![u64::from(*x)], u64::from(*s))) - .collect(); - metal_answers(FloatFn::Sign, float(32), &f); - let h: Vec = SIGN_HALF - .iter() - .map(|(x, s)| (vec![u64::from(*x)], u64::from(*s))) - .collect(); - metal_answers(FloatFn::Sign, float(16), &h); + let mut precise = Vec::new(); + let mut fast = Vec::new(); + let mut half = Vec::new(); + for r in MEDIAN3 { + let ops = vec![u64::from(r.0), u64::from(r.1), u64::from(r.2)]; + if keep(&ops, &f32_nan, &f32_denormal) { + precise.push((ops.clone(), u64::from(r.3))); + fast.push((ops, u64::from(r.4))); + } + let ops = vec![u64::from(r.5), u64::from(r.6), u64::from(r.7)]; + if keep(&ops, &half_nan, &|_| false) { + half.push((ops, u64::from(r.8))); + } + } + assert!(precise.len() > 20, "{} rows", precise.len()); + metal_answers(FloatFn::Median3, float(32), &precise); + metal_answers(FloatFn::FastMedian3, float(32), &fast); + metal_answers(FloatFn::Median3, float(16), &half); } /// `pow`'s special cases (`math::pow_special`) at the lanes of [`POW`], each decided by a special diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 404efbbf4..16502903f 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -615,13 +615,13 @@ pub enum PrecisionNote { /// operation's denormals to a device not measured to read them as Metal does: `+ - *`, the /// comparisons, `fma`, `dot`, `sqrt`, `rsqrt`, `trunc` and `rint` but on a device that takes /// the measured `DriverDeviation::MetalFloatDenormals`; and on every device the divisions and - /// the remainder, `floor` and `ceil`, the device's maths functions (`fast::fmod`'s fused - /// multiply-add among them), `mix` by `FMix`, `fast::sqrt` by `Sqrt`, `dot` of vectors of other - /// than two to four lanes, whose chunks' products the device sums where Metal flushes each one - /// below `2^-126`, beside their own notes, and a conversion to or from `double`, whose reading - /// Metal's is not measured. The operations that read a denormal on its bits answer Metal on - /// every device: `ldexp`, `sign`, `fract`, `copysign`, `fabs` and `atan2`; and so do the - /// functions the device answers as Metal's own. Where the minimum and maximum functions + /// the remainder, `floor`, `ceil` and `fneg`, the device's maths functions (`fast::fmod`'s + /// fused multiply-add, `fabs`, `sign` and `fract` among them), `mix` by `FMix`, `fast::sqrt` + /// by `Sqrt`, `dot` of vectors of other than two to four lanes, whose chunks' products the + /// device sums where Metal flushes each one below `2^-126`, beside their own notes, and a + /// conversion to or from `double`, whose reading Metal's is not measured. The operations that + /// read a denormal on its bits answer Metal on every device: `ldexp`, `copysign` and `atan2`; + /// and so do the functions the device answers as Metal's own. Where the minimum and maximum functions /// (`llvm.minnum` and `llvm.maxnum` among them, with any flags) and `saturate` are the device's /// `NMin`, `NMax` and `NClamp`, their pick of a denormal is /// [`PrecisionNote::NativeMinMax`]'s. Validation derives no tolerance and no explanation from @@ -1520,14 +1520,20 @@ pub enum PrecisionNote { /// Validation derives no tolerance from it. DeviceSampling, /// Native device maths: the module computes a `float` or `half` math-library function by the - /// device's own `GLSL.std.450` instruction (or Metal's composition of the device's `Exp2` and - /// `Log2`) where Metal's function is not the device's own; and `fast::sqrt` the device's - /// `Sqrt` on a device whose functions are not Metal's own. + /// device's own `GLSL.std.450` instruction (`Exp`, `Log`, `Pow`, `Sinh`, `Cosh` and `Tanh` + /// among them; a composition of the device's `Exp2` and `Log2` only for `exp10` and `log10`, + /// which no instruction is) where Metal's function is not the device's own; `fast::sqrt` the + /// device's `Sqrt`; `fabs`, `sign` and `fract` the device's `FAbs`, `FSign` and `Fract`, their + /// special operands the instruction's (Metal's `sign` of a NaN, a zero and an `f32` denormal is + /// `+0`, its `fract` of an infinity `+0`, where `FSign` keeps a zero's sign and leaves a NaN's + /// answer undefined and `Fract` of an infinity is a NaN); and `round` C99's, from the + /// device's `Trunc`, on every device (`round(-0.3)` is `-0`, where Metal answers `+0`). /// **Recorded bound:** Vulkan's precision table for the instruction, where Metal promises 4 to /// 6 ulp precise and its fast-math table fast (MSL Tables 8.1, 8.2): `Exp2` and `Exp` 3 + 2·|x| /// ulp; `Log2` and `Log` 3 ulp outside `[0.5, 2]` and `2^-21` absolute inside; `Pow` inherited /// from `Exp2(y · Log2(x))`; `Sqrt` inherited from `1 / InverseSqrt` (`fast::sqrt`'s too, where - /// Metal's is `x · rsqrt(x)`); `InverseSqrt` 2 ulp; `Sin` and `Cos` `2^-11` absolute in `[-π, + /// Metal's is `x · rsqrt(x)`); `FAbs` and `FSign` the correct result, `Fract` and `Trunc` + /// correctly rounded, `round`'s zero of either sign; `InverseSqrt` 2 ulp; `Sin` and `Cos` `2^-11` absolute in `[-π, /// π]` (both answers in `[-1, 1]` beyond); `Tan` inherited from `Sin / Cos`; `Asin`, `Acos`, /// `Atan` and `Atan2` 4096 ulp; the hyperbolic functions inherited from their `Exp` and `Log` /// formulas. A denormal operand and a NaN's encoding are the device's (`DeviceDenormals`, @@ -1656,13 +1662,11 @@ pub enum PrecisionNote { NativeHalfConversion, /// Native half rounding (a quantize): the module rounds a `half` result it computes in /// `float` (a `half` operation's, a function's, a conversion from `float`'s, a texel's) by the - /// device's `OpQuantizeToF16` alone, on every device without `shaderFloat16`, its quantize - /// measured or not (`DriverDeviation::MetalHalfQuantize` measures its rounding of normal - /// results alone). An integer's `half` is not this rounding: it rounds by integer arithmetic, - /// exactly, around NVIDIA's 615.71.09 keeping an integer conversion unrounded under the - /// quantize. Vulkan leaves the quantize's rounding mode to the device, and the SPIR-V - /// specification lets it answer a zero for a magnitude too small for a normal `half`. The - /// recorded bound, against Metal's `half(float)`: a finite result within one unit in the last + /// device's `OpQuantizeToF16` alone, on every device without `shaderFloat16`. An integer's + /// `half` is not this rounding: it rounds by integer arithmetic, exactly, around NVIDIA's + /// 615.71.09 keeping an integer conversion unrounded under the quantize. Vulkan leaves the + /// quantize's rounding mode to the device, and the SPIR-V specification lets it answer a zero + /// for a magnitude too small for a normal `half`. The recorded bound, against Metal's `half(float)`: a finite result within one unit in the last /// place of the `half`; a value from 65504 up to 65520 may be infinity where Metal's is 65504 /// (NVIDIA's 615.71.09 rounds `0x477FEFFF` to infinity); a value below the smallest normal /// `half` (`2^-14`) may round to a zero, of either sign, where Metal answers the half denormal, @@ -1680,8 +1684,9 @@ pub enum PrecisionNote { /// `SignedZeroInfNanPreserve` where Metal's entry keeps NaNs), its sign and payload the /// device's own (llvmpipe: `0xffc00000`), where Metal answers its canonical `0x7fc00000` /// (`0x7e00` as `half`), an operand's bits (`round`, `ldexp`, `fast::tan`), or the canonical - /// NaN with an operand's sign (`asin`, `atan`, `asinh`, `atanh`). Every non-NaN result is as - /// without it. Also recorded by every module that reads a `half` from its bits (a load, a + /// NaN with an operand's sign (`asin`, `atan`, `asinh`, `atanh`); a `float` `fneg` and `fabs` + /// keep a NaN operand's payload on Metal, and a `half` `fract` returns it. Every non-NaN result + /// is as without it. Also recorded by every module that reads a `half` from its bits (a load, a /// reinterpretation, a texel's bits), on every device: the read is the device's widening (an /// `OpFConvert` of the bits read as a 16-bit float with `shaderFloat16`, `UnpackHalf2x16` /// without it), and a NaN widens to a NaN whose bits are the device's, where Metal widens @@ -1693,8 +1698,11 @@ 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`, 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. + /// `NClamp`, on a device not measured to answer Metal's operand; a `saturate` of a format + /// whose operand Metal's other functions do not pick (`bfloat`, `double`) on every device; and + /// `median3` on every device, `min(max(c, min(a, b)), max(a, b))` of the device's `NMin` and + /// `NMax`, whose pick of two NaNs and of an `f32` denormal is the device's (Metal's + /// `fast::median3` answers `b` for two NaN first operands). /// **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 @@ -1702,25 +1710,46 @@ pub enum PrecisionNote { /// denormal compared by its value where the device keeps denormals, where Metal compares it as /// a zero and answers the second. Validation derives no tolerance from it. NativeMinMax, - /// 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 Metal's fused chain of its products, on a device whose - /// functions are not Metal's own. **Recorded bound:** a `float` `dot` of `n` + /// Native device maths: Metal's `dot` on `float` and `half` is the device's `OpDot` (a `half` + /// one summed in `float` and rounded once to `half`), not Metal's fused chain of its products, + /// on every device but for a `float` one where the device's functions are Metal's own + /// (MoltenVK, Metal's own `dot`). **Recorded bound:** a `float` `dot` of `n` /// lanes within `(3n - 1) * 2^-24 * sum |a_i * b_i|` of Metal's chain, plus `n * 2^-126` where /// a product is an `f32` denormal the device keeps (Vulkan's `OpDot` inherits `OpFMul`'s and /// `OpFAdd`'s rounding, `2n - 1` roundings, where Metal's chain rounds `n` times); a `half` /// one within `(n + 3) * 2^-11 * sum |a_i * b_i| + (n + 2) * 2^-25` of Metal's chain of `half` /// fused multiply-adds. Validation derives no tolerance from it. NativeDot, - /// Native device maths: Metal's `mix(x, y, t)` on `float`, or on `half` where its fused - /// multiply-add is not the measured 16-bit one, is the device's `FMix` (a `half` one computed - /// in `float` and rounded once to `half`), not Metal's `fma(t, y, fma(-t, x, x))`, on a device - /// whose functions are not Metal's own. **Recorded bound:** a `float` result within - /// `2^-21 * (|x * (1 - t)| + |y * t|)` of Metal's (Vulkan's `FMix` inherits + /// Native device maths: Metal's `mix(x, y, t)` on `float` and `half` is the device's `FMix` + /// (a `half` one computed in `float` and rounded once to `half`), not Metal's + /// `fma(t, y, fma(-t, x, x))`, on every device but for a `float` one where the device's + /// functions are Metal's own (MoltenVK, Metal's own `mix`). **Recorded bound:** a `float` + /// result within `2^-21 * (|x * (1 - t)| + |y * t|)` of Metal's (Vulkan's `FMix` inherits /// `x * (1 - t) + y * t`'s rounding, four roundings, where Metal's rounds twice); a `half` /// one within `3 * 2^-10 * (|x * (1 - t)| + |y * t|) + 2^-23`. Validation derives no /// tolerance from it. NativeMix, + /// Native device maths (a conversion): `air.pack` or `air.unpack` of a normalized format is + /// the device's: `GLSL.std.450`'s `PackUnorm4x8`, `PackSnorm4x8`, `PackUnorm2x16` and + /// `PackSnorm2x16` (and their `Unpack`s) for the four formats it names, and for `rgb10a2` and + /// `rgb565` those instructions' definition on each field, the device's `NClamp`, multiply, + /// `RoundEven` and conversion (a pack) or its multiply by the scale's reciprocal (an unpack); + /// `unorm4x8_srgb`'s colour channels take the MSL transfer functions by the device's multiply, + /// division and `Pow` around the 8-bit instruction. Metal rounds the exact product to its code + /// and divides correctly rounded, answers code 0 for a NaN channel, and takes an sRGB colour + /// through its twelve-bit table: a decode answers its step `k / 4095` nearest the transfer, an + /// encode the byte of that table's step. Recorded on every device but for + /// a `float` conversion of the four named formats on a device whose functions are Metal's own + /// (MoltenVK: Metal's own `pack_float_to_*` and `unpack_*_to_float`). **Recorded bound:** + /// Vulkan bounds the instructions by their definition (`round(clamp(c) * scale)` and + /// `c / scale`): a packed code within one of Metal's, apart only where `clamp(c) * scale` lies + /// within its `float` rounding of a half-integer (`Round` may tie either way); an unpacked + /// value within `OpFDiv`'s 2.5 ulp of the correctly rounded quotient; an sRGB code within one of + /// Metal's (the transfer's `Pow` inherited from `Exp2(y * Log2(x))`), and a decoded sRGB + /// colour within half a twelve-bit step (`1 / 8190`) of Metal's step, beyond its division's + /// and `Pow`'s bounds; a NaN channel's code, and a `half` result rounded once more to `half`, + /// the device's. Validation derives no tolerance from it. + DevicePackConversion, /// A render pipeline whose color attachments the device draws in more than one group /// (`GraphicsState::color_group`, the module docs of `pipeline::compile::color_group`): a /// device without Metal's eight color attachments draws each of its draws once per group, diff --git a/crates/metal2vulkan/src/spirv/interp/glsl.rs b/crates/metal2vulkan/src/spirv/interp/glsl.rs index 176f5b48f..bef4e8c87 100644 --- a/crates/metal2vulkan/src/spirv/interp/glsl.rs +++ b/crates/metal2vulkan/src/spirv/interp/glsl.rs @@ -1,5 +1,5 @@ //! The exact subset of `GLSL.std.450`: rounding, sign, min/max/clamp, `Fma`, `Sqrt`, `Length`, -//! `Ldexp`, `Modf`/`Frexp`, bit finding, `Cross`, and the half packs. Every float result is rounded once +//! `Ldexp`, `Modf`/`Frexp`, bit finding, `Cross`, the half packs and the normalized packs. Every float result is rounded once //! per IEEE operation; the transcendental and approximate instructions are [`Unmodelled`]. use crate::spirv::ids::Value; @@ -232,10 +232,66 @@ pub(super) fn eval(p: &Prog<'_>, op: GlslOp, args: &[Value], vals: &[Val]) -> IR let hi = float::from_f64(float::f16_to_f64((x >> 16) as u16), 32)?; Ok(Val::from_comps(vec![lo, hi])) } + GlslOp::PackUnorm4x8 => pack_norm(&comps(0)?, 8, false), + GlslOp::PackSnorm4x8 => pack_norm(&comps(0)?, 8, true), + GlslOp::PackUnorm2x16 => pack_norm(&comps(0)?, 16, false), + GlslOp::PackSnorm2x16 => pack_norm(&comps(0)?, 16, true), + GlslOp::UnpackUnorm4x8 => unpack_norm(&comps(0)?, 4, 8, false), + GlslOp::UnpackSnorm4x8 => unpack_norm(&comps(0)?, 4, 8, true), + GlslOp::UnpackUnorm2x16 => unpack_norm(&comps(0)?, 2, 16, false), + GlslOp::UnpackSnorm2x16 => unpack_norm(&comps(0)?, 2, 16, true), other => Err(Unmodelled::Glsl(other).err()), } } +/// The scale of a normalized field of `bits` bits: `2^bits - 1`, or `2^(bits-1) - 1` signed. +fn norm_scale(bits: u32, signed: bool) -> f32 { + let n = if signed { bits - 1 } else { bits }; + ((1u32 << n) - 1) as f32 +} + +/// `PackUnorm4x8` and its kin of the `float` components `c`: each `round(clamp(c, 0, 1) * s)` +/// (`[-1, 1]` signed), its product rounded to `float` and its tie to even (Vulkan leaves `Round`'s +/// tie to the implementation; this is one answer it allows), the first component in the low bits. +/// A NaN's clamp is undefined. +fn pack_norm(c: &[u64], bits: u32, signed: bool) -> IResult { + let s = norm_scale(bits, signed); + let lo = if signed { -1.0f32 } else { 0.0 }; + let mut out = 0u64; + for (i, x) in c.iter().enumerate() { + let v = f32::from_bits(*x as u32); + if v.is_nan() { + return Err(TrapKind::Undefined("a normalized pack of NaN").err()); + } + let code = (v.clamp(lo, 1.0) * s).round_ties_even() as i32; + out |= (u64::from(code as u32) & mask(bits as u8)) << (bits as usize * i); + } + Ok(Val::S(out & mask(32))) +} + +/// `UnpackUnorm4x8` and its kin of the word `w`'s first component: `n` fields of `bits` bits, low +/// first, each `f / s` correctly rounded (signed: sign-extended, `clamp(f / s, -1, 1)`). +fn unpack_norm(w: &[u64], n: u32, bits: u32, signed: bool) -> IResult { + let w = w + .first() + .copied() + .ok_or_else(|| malformed("unpack operand"))?; + let s = norm_scale(bits, signed); + let mut out = Vec::with_capacity(n as usize); + for i in 0..n { + let field = (w >> (bits * i)) & mask(bits as u8); + let code = if signed { + sext(field, bits as u8) as f32 + } else { + field as f32 + }; + let q = code / s; + let q = if signed { q.max(-1.0) } else { q }; + out.push(u64::from(q.to_bits())); + } + Ok(Val::from_comps(out)) +} + /// `v = m * 2^e` with `0.5 <= |m| < 1` (and `(0, 0)` for zero), exactly. fn frexp(v: f64) -> (f64, i32) { if v == 0.0 { diff --git a/crates/metal2vulkan/src/tests/engine_arith.rs b/crates/metal2vulkan/src/tests/engine_arith.rs index c4ac5bcc5..0b9c892c9 100644 --- a/crates/metal2vulkan/src/tests/engine_arith.rs +++ b/crates/metal2vulkan/src/tests/engine_arith.rs @@ -20,7 +20,6 @@ use crate::device::profile::{DeviceProfile, DriverWorkaround, FloatFunctions}; use crate::device::requirements::VkFeature; use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::{Capability, Error, Feature, LowerFamily, Needs}; -use crate::float16::f16_bits_to_f32; use crate::library::FunctionConstantValues; use crate::lower::emit::emit_module; use crate::lower::select::{select, LowerInputs}; @@ -468,16 +467,19 @@ fn kernels() -> Vec { needs: &[], note: Some(PrecisionNote::DeviceTranscendentals), }); - // `rgb565` rounds the float product with ties to even (0.5 * 63 = 31.5 -> 32, exact in f32), - // and `rg11b10f` unpacks the half with the field's bits (0x3C0 -> red 1.0). - v.push(k( - "rgb565_pack_rounds_the_exact_product", - format!( - "{} %v = insertelement <3 x float> , float %a, i32 0\n %p = call i16 @air.pack.unorm.rgb565.v3f32(<3 x float> %v)\n %r = zext i16 %p to i32\n", - of("a", 1.0) - ), - 31 | (32 << 5), - )); + // `rgb565` is the device's product rounded by `RoundEven` (0.5 * 63 = 31.5 -> 32, exact in + // f32), noted, and `rg11b10f` unpacks the half with the field's bits (0x3C0 -> red 1.0). + v.push(Kernel { + note: Some(PrecisionNote::DevicePackConversion), + ..k( + "rgb565_pack_rounds_the_float_product_to_even", + format!( + "{} %v = insertelement <3 x float> , float %a, i32 0\n %p = call i16 @air.pack.unorm.rgb565.v3f32(<3 x float> %v)\n %r = zext i16 %p to i32\n", + of("a", 1.0) + ), + 31 | (32 << 5), + ) + }); v.push(Kernel { name: "rg11b10f_unpacks_half_fields", body: format!( @@ -605,9 +607,8 @@ fn kernels() -> Vec { needs: &[], note: None, }); - // `dot` of chunked vectors is Metal's fused chain over every lane where the profile's `float` - // functions are Metal's, and each chunk's `OpDot` elsewhere - // (`wide_dot_is_metals_fused_chain_in_metals_order`), exact on these lanes; `sincos` of one + // `dot` of chunked vectors is each chunk's `OpDot` on every profile + // (`dot_is_the_devices_op_dot_on_every_profile`), exact on these lanes; `sincos` of one // computes per chunk and stores its cosine as one chunked leaf. v.push(Kernel { name: "chunked_dot_sums_every_chunk", @@ -793,16 +794,19 @@ fn kernels() -> Vec { want, )); } - // Metal's sRGB tables decode every byte to a step that encodes back to the byte (the alpha byte - // through `a / 255` and the exact product), exactly on every device. - v.push(k( - "srgb_unpack_and_pack_round_trip", - format!( + // The sRGB conversions are the MSL transfer functions by the device's `Pow` around the 8-bit + // instructions, noted on every device (the interpreter models no `Pow`). + v.push(Kernel { + name: "srgb_unpack_and_pack_take_the_transfer_functions", + body: format!( "{} %u = call <4 x float> @air.unpack.unorm4x8.srgb.v4f32(i32 %b)\n %r = call i32 @air.pack.unorm4x8.srgb.v4f32(<4 x float> %u)\n", oi("b", 0x8901_37FF) ), - 0x8901_37FF, - )); + float: false, + want: None, + needs: &[], + note: Some(PrecisionNote::DevicePackConversion), + }); v.push(Kernel { name: "double_needs_float64", body: format!( @@ -1348,54 +1352,39 @@ fn opaque_vector(name: &str, half: bool, vals: &[f32]) -> String { s } -/// Metal's `dot` on `float` and `half` is the products' fused chain, `fma(x[n-1], y[n-1], ... -/// fma(x[1], y[1], x[0] * y[0]))`, with and without fast math. On moltenvk-m3, whose `float` -/// functions are Metal's, `dot` on `float` is the device's `OpDot`, which reaches Metal's own -/// `dot`, and on `half` the chain of the device's 16-bit fused multiply-add, Metal's own: the words -/// are Metal's (a probe, the M3 Max and the M4 alike, at lanes where no other order, tree, unfused -/// or exact sum gives them), and fast math's zero signs where a device that regroups -/// `dot(float2(a, b), float2(b, c))` as `b * (a + c)` misses them (`nan_denormals_fast` with zeros -/// for its denormals; `nan_functions_fast`'s `dot((-0, +0), (+0, -0))`), with no -/// `DeviceArithmetic` or `DeviceDenormals`. Every other profile takes the device's `OpDot`, noted -/// `NativeDot`. +/// `dot` on `float` and `half` is the device's `OpDot` on every profile, with and without fast +/// math, on two to four lanes; of more, each chunk's `OpDot` summed. Metal's is the products' fused +/// chain: a `float` one on a profile whose `float` functions are Metal's (moltenvk-m3) reaches +/// Metal's own `dot`, with no note; every other records `NativeDot` (a `half` one summed in its +/// `float` container), and a chunked one `DeviceArithmetic`. No fused multiply-add is emitted. #[test] -fn dot_is_metals_fused_chain_on_moltenvk_and_the_devices_op_dot_elsewhere() { - let f = |b: u32| f32::from_bits(b); - let x = [0x3F2121E3, 0xC1504426, 0x40D96C9D, 0x3EC6C559].map(f); - let y = [0xBFD689B8, 0xC0608ADE, 0xC0D7159F, 0x402DE9ED].map(f); - let hx = [0xB3DD, 0xB0C3, 0xBB51, 0x3CD8].map(f16_bits_to_f32); - let hy = [0xC76B, 0x4A20, 0x31C7, 0xBA80].map(f16_bits_to_f32); +fn dot_is_the_devices_op_dot_on_every_profile() { + let vals = |n: usize, k: f32| (0..n).map(|i| k * (i as f32 + 1.5)).collect::>(); let mut ks = Vec::new(); - let names = [ + let float_names = [ ["dot2_float", "dot3_float", "dot4_float"], ["dot2_float_fast", "dot3_float_fast", "dot4_float_fast"], ]; - for (fast, row) in names.iter().enumerate() { - for (k, (name, want)) in row - .iter() - .copied() - .zip([0x42327452u32, 0xBF87085A, 0x37A4C7B4]) - .enumerate() - { + for (fast, row) in float_names.iter().enumerate() { + for (k, name) in row.iter().copied().enumerate() { let n = k + 2; let flag = if fast == 1 { "fast " } else { "" }; ks.push(Kernel { name, body: format!( "{}{} %d = call {flag}float @air.dot.v{n}f32(<{n} x float> %x, <{n} x float> %y)\n %r = bitcast float %d to i32\n", - opaque_vector("x", false, &x[..n]), - opaque_vector("y", false, &y[..n]) + opaque_vector("x", false, &vals(n, 0.75)), + opaque_vector("y", false, &vals(n, -1.25)) ), float: false, - want: Some(want), + want: None, needs: &[], note: None, }); } } - for (k, (name, want)) in ["dot2_half", "dot3_half", "dot4_half"] + for (k, name) in ["dot2_half", "dot3_half", "dot4_half"] .into_iter() - .zip([0x0E80u32, 0xB145, 0xBC98]) .enumerate() { let n = k + 2; @@ -1403,42 +1392,43 @@ fn dot_is_metals_fused_chain_on_moltenvk_and_the_devices_op_dot_elsewhere() { name, body: format!( "{}{} %d = call half @air.dot.v{n}f16(<{n} x half> %x, <{n} x half> %y)\n %u = bitcast half %d to i16\n %r = zext i16 %u to i32\n", - opaque_vector("x", true, &hx[..n]), - opaque_vector("y", true, &hy[..n]) + opaque_vector("x", true, &vals(n, 0.75)), + opaque_vector("y", true, &vals(n, -1.25)) ), float: false, - want: Some(want), + want: None, needs: &[], note: None, }); } - // fma(-2^-126, -0, +0 * -2^-126) is +0; `b * (a + c)` is -0. - let tiny = f(0x8080_0000); - ks.push(Kernel { - name: "dot_fast_zero_sign", - body: format!( - "{}{} %d = call fast float @air.dot.v2f32(<2 x float> %x, <2 x float> %y)\n %r = bitcast float %d to i32\n", - opaque_vector("x", false, &[0.0, tiny]), - opaque_vector("y", false, &[tiny, -0.0]) - ), - float: false, - want: Some(0), - needs: &[], - note: None, - }); - // fma(+0, -0, -0 * +0) is -0. - ks.push(Kernel { - name: "dot_fast_negative_zero", - body: format!( - "{}{} %d = call fast float @air.dot.v2f32(<2 x float> %x, <2 x float> %y)\n %r = bitcast float %d to i32\n", - opaque_vector("x", false, &[-0.0, 0.0]), - opaque_vector("y", false, &[0.0, -0.0]) - ), - float: false, - want: Some(0x8000_0000), - needs: &[], - note: None, - }); + for (name, n, half) in [ + ("dot8_float_chunked", 8usize, false), + ("dot16_half_chunked", 16, true), + ] { + let (ty, sym) = if half { + ("half", "f16") + } else { + ("float", "f32") + }; + let store = if half { + " %u = bitcast half %d to i16\n %r = zext i16 %u to i32\n" + } else { + " %r = bitcast float %d to i32\n" + }; + ks.push(Kernel { + name, + body: format!( + "{}{} %d = call {ty} @air.dot.v{n}{sym}(<{n} x {ty}> %x, <{n} x {ty}> %y)\n{store}", + opaque_vector("x", half, &vals(n, 0.75)), + opaque_vector("y", half, &vals(n, -1.25)) + ), + float: false, + want: None, + needs: &[], + note: None, + }); + } + // `DECLS` declares the dots of 5 and 8 `float` lanes. let decls: String = [2, 3, 4] .iter() .map(|n| { @@ -1446,11 +1436,18 @@ fn dot_is_metals_fused_chain_on_moltenvk_and_the_devices_op_dot_elsewhere() { "declare float @air.dot.v{n}f32(<{n} x float>, <{n} x float>)\ndeclare half @air.dot.v{n}f16(<{n} x half>, <{n} x half>)\n" ) }) + .chain(["declare half @air.dot.v16f16(<16 x half>, <16 x half>)\n".to_owned()]) .collect(); let text = module(&ks).replace(DECLS, &format!("{DECLS}{decls}")); - let Some(bitcode) = assemble("dot-chain", &text) else { + let Some(bitcode) = assemble("dot-native", &text) else { return; }; + let fma = |words: &[u32]| { + count_ops(words, |w| { + w[0] & 0xFFFF == crate::spv::Op::ExtInst as u32 + && w.get(4) == Some(&(crate::spv::GlslStd450Op::Fma as u32)) + }) + count_op(words, crate::spv::Op::FmaKHR) + }; for stem in [ "moltenvk-m3", "amd-rdna3-radv", @@ -1458,172 +1455,31 @@ fn dot_is_metals_fused_chain_on_moltenvk_and_the_devices_op_dot_elsewhere() { "vk12-floor", "lunarg-desktop-baseline-2023", ] { - let p = profile(stem, exact_maths()).expect("profile"); - let metal = p.fields().float_functions == FloatFunctions::Metal; - for kk in &ks { - let what = format!("{} on {stem}", 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}")); - if !metal { - assert!( - count_op(&words, crate::spv::Op::Dot) > 0 - && a.precision.contains(&PrecisionNote::NativeDot), - "{what}: OpDot, {:?}", - a.precision - ); - continue; - } - for n in [ - PrecisionNote::DeviceArithmetic, - PrecisionNote::DeviceDenormals, - ] { - assert!(!a.precision.contains(&n), "{what}: {:?}", a.precision); - } - let device_dot = !kk.name.ends_with("_half"); - assert_eq!( - count_op(&words, crate::spv::Op::Dot) > 0, - device_dot, - "{what}: OpDot" - ); - // The interpreter is no Metal: moltenvk-m3's `OpDot` is its device's. - if !device_dot { - let got = interpret(&bitcode, kk.name, &p); - assert_eq!(Some(got), kk.want, "{what}: {got:#x}"); - } - } - } -} - -/// Metal's `dot` of more than four lanes, on `float` and `half`, is the same fused chain over -/// every lane in order, with and without fast math: an Apple M3 Max under macOS -/// 27.0.1, 16,384 rows of seeded random lanes each on 5, 8 and 16 `float` lanes and 8 and 16 `half` -/// lanes, every answer the chain's. Each row here is one where the chain backwards, the chunks' -/// sums added and the exact sum rounded once all miss Metal's word. Where Metal's order is the -/// profile's (moltenvk-m3) it answers it by the chain ([`ArithStrategy::ChunkedChain`]): no -/// `OpDot`, no `DeviceArithmetic` and no `DeviceDenormals`. Every other profile keeps each chunk's -/// `OpDot`, noted `DeviceArithmetic`. -/// -/// [`ArithStrategy::ChunkedChain`]: crate::lower::arith::ArithStrategy::ChunkedChain -#[test] -fn wide_dot_is_metals_fused_chain_in_metals_order() { - let f = |b: &[u32]| b.iter().map(|&w| f32::from_bits(w)).collect::>(); - let h = |b: &[u16]| b.iter().map(|&w| f16_bits_to_f32(w)).collect::>(); - let x5 = f(&[0x3C4706A1, 0xC5D9EEB5, 0x3D6EA9B2, 0x3A2F23BF, 0xC603B91B]); - let y5 = f(&[0x40986206, 0xBE6B6C10, 0xBC124CDB, 0xB8E3B629, 0x3E3C8570]); - let x8 = f(&[ - 0xBFC457BC, 0xBD86A520, 0x35B57EFC, 0x43A8E94D, 0x3ABA1FAF, 0xBF68F7B9, 0x411A7DC7, - 0xC0010B78, - ]); - let y8 = f(&[ - 0xBAC18975, 0xB7E5CCAA, 0x3DCAA0D4, 0xB6B402AC, 0xC2D6EDAA, 0x397CD0F5, 0xC0DB6522, - 0xC2007DCD, - ]); - let x16 = f(&[ - 0x3E0AEC21, 0xBDE4C98F, 0x48F7CE82, 0xC74A1CB5, 0x3FEFB46A, 0xB8CDB9CA, 0x367C7539, - 0xB7A71EB2, 0xC8A058F0, 0x41F42DA4, 0xBC9A925A, 0xC66A6596, 0xC0E26B92, 0x42AA4631, - 0x433758BE, 0xB93AF022, - ]); - let y16 = f(&[ - 0x448360E6, 0xBC3FB11E, 0xBFED97A2, 0x3BBB547E, 0x3C051C11, 0xC4EE106E, 0x4521C04F, - 0x3B630B77, 0x3A529217, 0xC2FE1081, 0xC656A359, 0xC6FFF097, 0x3EB192E9, 0xC2147C43, - 0xC20B70CB, 0x40D2FDA7, - ]); - let hx8 = h(&[ - 0x32B2, 0xC743, 0xAD26, 0x36C6, 0xC7E3, 0xBFF2, 0x43C1, 0x4AA1, - ]); - let hy8 = h(&[ - 0xBD37, 0x321E, 0x3C57, 0x4039, 0xCC4E, 0x4F9E, 0xB7DC, 0xAC3B, - ]); - let hx16 = h(&[ - 0x4391, 0x403F, 0xBC34, 0xC571, 0xB6BC, 0xB7B3, 0xB7EF, 0x3BA4, 0x2FD5, 0xB227, 0xB58C, - 0x2AFB, 0xAACF, 0x357C, 0x4DB6, 0xB40F, - ]); - let hy16 = h(&[ - 0x2D47, 0xB043, 0xB15B, 0xAB19, 0x36CE, 0x3634, 0x45F8, 0x4F21, 0xAF75, 0xC50E, 0x2B33, - 0x2BFF, 0xCBB9, 0x3595, 0x3C83, 0xACEA, - ]); - let float = |name: &'static str, fast: bool, x: &[f32], y: &[f32], want: u32| { - let n = x.len(); - let flag = if fast { "fast " } else { "" }; - Kernel { - name, - body: format!( - "{}{} %d = call {flag}float @air.dot.v{n}f32(<{n} x float> %x, <{n} x float> %y)\n %r = bitcast float %d to i32\n", - opaque_vector("x", false, x), - opaque_vector("y", false, y) - ), - float: false, - want: Some(want), - needs: &[], - note: None, - } - }; - let half = |name: &'static str, x: &[f32], y: &[f32], want: u32| { - let n = x.len(); - Kernel { - name, - body: format!( - "{}{} %d = call half @air.dot.v{n}f16(<{n} x half> %x, <{n} x half> %y)\n %u = bitcast half %d to i16\n %r = zext i16 %u to i32\n", - opaque_vector("x", true, x), - opaque_vector("y", true, y) - ), - float: false, - want: Some(want), - needs: &[], - note: None, - } - }; - let ks = [ - float("dot5_float", false, &x5, &y5, 0x424D5858), - float("dot8_float", false, &x8, &y8, 0xBFCA9608), - float("dot8_float_fast", true, &x8, &y8, 0xBFCA9608), - float("dot16_float", false, &x16, &y16, 0x4DE9E2D2), - half("dot8_half", &hx8, &hy8, 0x547C), - half("dot16_half", &hx16, &hy16, 0x5284), - ]; - // `DECLS` declares the dots of 5 and 8 `float` lanes. - let decls = "declare float @air.dot.v16f32(<16 x float>, <16 x float>)\n\ - declare half @air.dot.v8f16(<8 x half>, <8 x half>)\n\ - declare half @air.dot.v16f16(<16 x half>, <16 x half>)\n"; - let text = module(&ks).replace(DECLS, &format!("{DECLS}{decls}")); - let Some(bitcode) = assemble("wide-dot-chain", &text) else { - return; - }; - let device = [ - PrecisionNote::DeviceArithmetic, - PrecisionNote::DeviceDenormals, - ]; - for stem in [ - "moltenvk-m3", - "amd-rdna3-radv", - "lavapipe", - "vk12-floor", - "lunarg-desktop-baseline-2023", - ] { - for (policy, exact) in [(exact_maths(), true), (DevicePolicy::default(), false)] { + for policy in [exact_maths(), DevicePolicy::default()] { let p = profile(stem, policy).expect("profile"); - let chain = p.fields().float_functions == FloatFunctions::Metal; + let metal = p.fields().float_functions == FloatFunctions::Metal; for kk in &ks { - let what = format!("{} on {stem} (exact forms: {exact})", kk.name); + let what = format!("{} on {stem}", 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 device_dot = count_op(&words, crate::spv::Op::Dot) > 0; - if chain { - assert!(!device_dot, "{what}: OpDot"); - for n in device { - assert!(!a.precision.contains(&n), "{what}: {:?}", a.precision); - } - let got = interpret(&bitcode, kk.name, &p); - assert_eq!(Some(got), kk.want, "{what}: {got:#x}"); - } else { - assert!(device_dot, "{what}: OpDot"); + assert!(count_op(&words, crate::spv::Op::Dot) > 0, "{what}: OpDot"); + assert_eq!(fma(&words), 0, "{what}: a fused chain"); + let chunked = kk.name.ends_with("_chunked"); + let float = kk.name.contains("_float"); + if chunked { assert!( a.precision.contains(&PrecisionNote::DeviceArithmetic), "{what}: {:?}", a.precision ); + } else { + assert_eq!( + a.precision.contains(&PrecisionNote::NativeDot), + !(metal && float), + "{what}: {:?}", + a.precision + ); } } } @@ -2057,8 +1913,9 @@ fn fast_sincos_flushes_past_the_last_quadrant() { /// `float` `+ - *`, a comparison and `OpFmaKHR` record `DeviceDenormals` exactly where the /// profile does not take `DriverDeviation::MetalFloatDenormals` (lavapipe), whose device keeps or /// flushes them by its own controls; a remainder, the device's `OpFRem`, records it on every -/// profile; `sign`, which answers Metal at denormals itself, and `half` arithmetic record it on -/// none; `fast::atan2`, whose quotient is the device's division, records it off the deviation. +/// profile; `sign`, the device's `FSign`, records it off Metal's own functions, and `half` +/// arithmetic on none; `fast::atan2`, whose quotient is the device's division, records it off the +/// deviation. /// None records `DeviceNanEncoding`: the NaN is Metal's, the device's where the profile states it /// and selected elsewhere. The operands come from bits (`llvm.umin` of constants, bitcast), not /// from `float` arithmetic. @@ -2088,7 +1945,7 @@ fn device_float_environment_notes_follow_the_operations() { let notes: [(&[PrecisionNote], &[PrecisionNote]); 7] = [ (none, dd), (dd, dd), - (none, none), + (none, dd), (none, dd), (none, none), (none, dd), @@ -2514,8 +2371,7 @@ fn narrow_float_module_growth_is_bounded() { /// `NoContraction`, in an entry declaring `RoundingModeRTE`, `DenormPreserve` and /// `SignedZeroInfNanPreserve` for 16 bits and the modes its independence ties to them /// (`narrow::controlled_modes`). No other module declares a 16-bit float mode or -/// `RoundingModeRTE` for it. No module requires `DriverDeviation::MetalHalfQuantize`'s fact: a -/// quantize records `NativeHalfQuantize` on every profile. +/// `RoundingModeRTE` for it. A quantize records `NativeHalfQuantize` on every profile. /// /// The chain: one `fptrunc`, eight `fadd`, and eight `fmul` on `half`, strict and `fast`. Nothing /// is fused: the `fast` chain's operations are the strict chain's, each in the AIR's order, so @@ -2638,13 +2494,6 @@ fn half_rounding_follows_the_operation() { (controlled, rte), "{what}: a 16-bit float mode and RoundingModeRTE" ); - // No module requires the quantize's measured fact, nor the conversion's. - assert!( - !a.requirements - .properties - .contains(&crate::device::requirements::VkProperty::MetalHalfQuantize), - "{what}" - ); } } } @@ -3604,7 +3453,7 @@ fn sincos_answers_the_device_s_nan() { nans_are_the_device_s(&bitcode, &ks, false, &unread, &|_, fact| !fact); } -/// A NaN test (Metal's `median3`'s) is `OpIsNan` only in an entry that declares +/// A NaN test (Metal's saturating conversion'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 @@ -3630,29 +3479,17 @@ fn a_nan_test_no_float_mode_folds() { format!("{x} %s = call fast float @air.fast_round.f32(float %x)\n"), 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), + // Metal's saturating conversion answers 0 for a NaN, which the module tests for; the + // `fabs` before it, with or without flags, decides the entry's mode. + k( + "strict_convert", + format!("{x} %a = call float @air.fabs.f32(float %x)\n %r = call i32 @air.convert.s.i32.f.f32(float %a)\n"), + 0, ), - 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), + k( + "fast_convert", + format!("{x} %a = call fast float @air.fast_fabs.f32(float %x)\n %r = call i32 @air.convert.s.i32.f.f32(float %a)\n"), + 0, ), // The device's `asin` and `tan`, which the interpreter does not evaluate. nan_kernel( @@ -3671,7 +3508,10 @@ fn a_nan_test_no_float_mode_folds() { None, ), ]; - let text = module(&ks).replace(DECLS, &format!("{DECLS}{NAN_DECLS}")); + let text = module(&ks).replace( + DECLS, + &format!("{DECLS}{NAN_DECLS}declare float @air.fabs.f32(float)\ndeclare float @air.fast_fabs.f32(float)\n"), + ); let Some(bitcode) = assemble("nan-test", &text) else { return; }; @@ -3906,13 +3746,13 @@ fn half_sign_operations_keep_a_nan_s_payload_on_every_profile() { /// Class E: Metal's `float` `fneg` and `fabs` (`air.fabs`, `air.fast_fabs`, and `llvm.fabs`, which /// takes `air.fabs`'s answer) flip or clear the sign bit alone, with and without fast-math flags: a -/// NaN keeps its payload, signaling or not, and a denormal stays. The lowering moves the sign as an -/// integer on the bits, so no device's `OpFNegate` or `FAbs` (RADV's `fneg` keeps a NaN's sign, -/// NVIDIA's `fabs` answers `0x7FFFFFFF`, RADV and ANV flush a denormal) decides it, on every -/// profile: no float negation or absolute value is emitted, no NaN is selected, and no device note -/// is recorded. +/// NaN keeps its payload, signaling or not, and a denormal stays. The lowering is the device's +/// `OpFNegate` and `FAbs` on every profile (RADV's `fneg` keeps a NaN's sign, NVIDIA's `fabs` +/// answers `0x7FFFFFFF`, RADV and ANV flush a denormal): no NaN is selected and nothing moves on +/// the bits, the NaN noted `NativeNanEncoding` and `fneg`'s denormal `DeviceDenormals`. The +/// interpreter keeps the payload and the denormal, as a device may. #[test] -fn float_sign_operations_move_the_bits_on_every_profile() { +fn float_sign_operations_are_the_devices_on_every_profile() { let snan = ob("x", 0x7F80_0001); let neg_snan = ob("x", 0xFF80_0001); let ks = [ @@ -3988,14 +3828,24 @@ fn float_sign_operations_move_the_bits_on_every_profile() { 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!(count_op(&words, crate::spv::Op::FNegate), 0, "{what}"); - assert_eq!(fabs(&words), 0, "{what}"); + let neg = kk.name.contains("fneg"); + let abs = kk.name.contains("fabs"); + assert_eq!(count_op(&words, crate::spv::Op::FNegate) > 0, neg, "{what}"); + assert_eq!(fabs(&words) > 0, abs, "{what}"); assert_eq!(nan_tests(&words), (0, 0), "{what}"); - for note in [ - PrecisionNote::DeviceDenormals, - PrecisionNote::DeviceNanEncoding, - ] { - assert!(!a.precision.contains(¬e), "{what}: {:?}", a.precision); + if neg || abs { + assert!( + a.precision.contains(&PrecisionNote::NativeNanEncoding), + "{what}: {:?}", + a.precision + ); + } + if neg { + assert!( + a.precision.contains(&PrecisionNote::DeviceDenormals), + "{what}: {:?}", + a.precision + ); } let got = interpret(&bitcode, kk.name, &p); assert_eq!(Some(got), kk.want, "{what}: {got:#x}"); @@ -4265,16 +4115,13 @@ fn half_fmod_answers_metals_zero_remainder_on_every_profile() { } /// Class I: Metal's `mix(x, y, t)` on `float` and `half` is `fma(t, y, fma(-t, x, x))`, with and -/// without fast-math flags. On a profile whose `float` functions are Metal's (moltenvk-m3), and on -/// `half` where its fused multiply-add is the measured 16-bit one, the module keeps that form: no -/// `FMix` is emitted, and the interpreter answers Metal's recorded words (`nan_functions`: -/// `mix(inf, 1, 0)` is the canonical NaN, `mix(-0, -0, 0)` is `+0`; `nan_half`: -/// `mix(-0.3, 0.7, 0.2)` is `0xAE68`, where the blend gives `0xAE66`). The driver's deviation -/// `MetalCanonicalNans` is not taken, so a device that leaves the NaN to `OpFmaKHR` (MoltenVK's, -/// whose arithmetic answers Metal's) shows the select here too. Every other profile takes the -/// device's `FMix`, noted `NativeMix`. +/// without fast-math flags (`nan_functions`: `mix(inf, 1, 0)` is the canonical NaN; `nan_half`: +/// `mix(-0.3, 0.7, 0.2)` is `0xAE68`, where the blend gives `0xAE66`). On every profile the module +/// takes the device's `FMix` and no fused multiply-add: a `float` one on a profile whose `float` +/// functions are Metal's (moltenvk-m3) reaches Metal's own `mix`, with no note; every other records +/// `NativeMix` (a `half` one the blend in its `float` container, rounded once). #[test] -fn mix_is_metals_fused_form_on_moltenvk_and_the_devices_fmix_elsewhere() { +fn mix_is_the_devices_fmix_on_every_profile() { let three = |a: u32, b: u32, c: u32| format!("{}{}{}", ob("x", a), ob("y", b), ob("z", c)); let halves = |a: u16, b: u16, c: u16| format!("{}{}{}", oh("hx", a), oh("hy", b), oh("hz", c)); let ks = [ @@ -4334,27 +4181,33 @@ fn mix_is_metals_fused_form_on_moltenvk_and_the_devices_fmix_elsewhere() { && w.get(4) == Some(&(crate::spv::GlslStd450Op::FMix as u32)) }) }; - for stem in PROFILES.iter().copied().chain(["lavapipe"]) { + let fma = |words: &[u32]| { + count_ops(words, |w| { + w[0] & 0xFFFF == crate::spv::Op::ExtInst as u32 + && w.get(4) == Some(&(crate::spv::GlslStd450Op::Fma as u32)) + }) + count_op(words, crate::spv::Op::FmaKHR) + }; + for stem in PROFILES + .iter() + .copied() + .chain(["lavapipe", "amd-rdna3-radv"]) + { let p = profile_with_canonical_nans(stem, false); let metal = p.fields().float_functions == FloatFunctions::Metal; - let f16 = crate::lower::arith::fma::half_route(&p) == crate::lower::arith::fma::Route::F16; for kk in &ks { let what = format!("{} on {stem}", 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 chain = metal || (kk.name.starts_with("half_") && f16); - if !chain { - assert!( - blend(&words) > 0 && a.precision.contains(&PrecisionNote::NativeMix), - "{what}: FMix, {:?}", - a.precision - ); - continue; - } - assert_eq!(blend(&words), 0, "{what}"); - let got = interpret(&bitcode, kk.name, &p); - assert_eq!(Some(got), kk.want, "{what}: {got:#x}"); + assert!(blend(&words) > 0, "{what}: FMix"); + assert_eq!(fma(&words), 0, "{what}: a fused form"); + let half = kk.name.starts_with("half_"); + assert_eq!( + a.precision.contains(&PrecisionNote::NativeMix), + !(metal && !half), + "{what}: {:?}", + a.precision + ); } } } @@ -4363,10 +4216,10 @@ fn mix_is_metals_fused_form_on_moltenvk_and_the_devices_fmix_elsewhere() { /// fast-math flags (`nan_half`, `nan_half_fast`): `llvm.fmuladd`, `ldexp` (unlike `float`'s, which /// 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`. +/// and `fract` return a NaN operand itself on Metal, and `asin`'s domain error takes the operand's +/// sign: each the device's NaN on every profile, noted whatever the fact. None is selected. +/// `round`'s zero is C99's (`-0` for `round(-0.3)`, where Metal answers `+0`), and `fract` of an +/// infinity the device's `Fract`'s NaN (Metal's: `+0`, and `0x3BFF` with every flag). #[test] fn half_functions_answer_the_device_s_nan() { let hx = oh("hx", 0xFE01); @@ -4399,17 +4252,17 @@ fn half_functions_answer_the_device_s_nan() { half_nan_kernel( "half_round_to_zero", format!("{tenth} %s = call fast half @air.round.f16(half %hx)\n"), - Some(0), + Some(0x8000), ), half_nan_kernel( "half_fract_flagged", format!("{inf} %s = call fast half @air.fract.f16(half %hx)\n"), - Some(0x3BFF), + None, ), half_nan_kernel( "half_fract", format!("{inf} %s = call half @air.fract.f16(half %hx)\n"), - Some(0), + None, ), half_nan_kernel( "half_asin", @@ -4428,7 +4281,8 @@ fn half_functions_answer_the_device_s_nan() { }; nans_are_the_device_s(&bitcode, &ks, true, &["half_asin"], &|name, fact| { name.starts_with("half_round") + || name.starts_with("half_fract") || name == "half_asin" - || (!name.starts_with("half_fract") && !fact) + || !fact }); } diff --git a/crates/metal2vulkan/src/tests/engine_float_call_notes.rs b/crates/metal2vulkan/src/tests/engine_float_call_notes.rs index 049e803f5..a5476cd76 100644 --- a/crates/metal2vulkan/src/tests/engine_float_call_notes.rs +++ b/crates/metal2vulkan/src/tests/engine_float_call_notes.rs @@ -584,8 +584,9 @@ fn call_kernel(name: &str, symbol: &str, arity: usize, fmf: FastMath) -> Kernel /// division, which is Metal's own there, nor for a call the device answers as Metal's own /// function, `fast::atan2` among them; an entry Metal compiles without fast math (a division /// without `nnan` and `ninf`, a call without flags) still records them, and `fast::sinpi`, the -/// device's near-equivalent, records its note in either. `mix` and `fast::sinpi` record no -/// `DeviceDenormals` there and require the measured fact. Off MoltenVK `mix` is the device's +/// device's near-equivalent, records its note in either. `fast::sinpi` records no +/// `DeviceDenormals` there and requires the measured fact; `mix` is the device's `FMix`, which +/// reaches Metal's own `mix` there, with no note and no fact. Off MoltenVK `mix` is the device's /// `FMix`, with or without Metal's denormals: noted `NativeMix` and `DeviceDenormals`, requiring /// no fact. #[test] @@ -699,10 +700,11 @@ fn a_fast_math_entry_on_moltenvk_records_no_note_for_metals_own_operations() { && requires, "sinpi_fast on {stem}: {sinpi:?}, requires the fact: {requires}" ); - let (mix, requires) = notes_of(p, "mix_fast"); + let (mix, _) = notes_of(p, "mix_fast"); assert!( - !mix.contains(&PrecisionNote::DeviceDenormals) && requires, - "mix_fast on {stem}: {mix:?}, requires the fact: {requires}" + !mix.contains(&PrecisionNote::DeviceDenormals) + && !mix.contains(&PrecisionNote::NativeMix), + "mix_fast on {stem}: {mix:?}" ); } // Without Metal's functions, with or without Metal's denormals, `mix` is the device's `FMix`, diff --git a/crates/metal2vulkan/src/tests/engine_metal_math.rs b/crates/metal2vulkan/src/tests/engine_metal_math.rs index 9441fa375..177aac630 100644 --- a/crates/metal2vulkan/src/tests/engine_metal_math.rs +++ b/crates/metal2vulkan/src/tests/engine_metal_math.rs @@ -1,25 +1,32 @@ -//! Metal's math where `GLSL.std.450` is a different function, end to end: a call's `air` symbol -//! variant and fast-math flags select what it computes. On every committed M1 profile each kernel -//! compiles, links, and passes L3, and its module holds the instructions of the function Metal -//! computes: +//! Metal's math functions end to end: a call's `air` symbol variant and fast-math flags select +//! what it computes, the device's instruction where one is the function and a definition of the +//! device's instructions where none is. On every committed M1 profile each kernel compiles, links, +//! and passes L3, and its module holds the instructions of the form it takes: //! //! - `air.fast_tanh` on `float` is the MSL fast-math formula `(t - 1) / (t + 1)`, //! `t = exp2(x * 2 log2 e)` of the device's `Exp2` (no `Tanh`), every step of it //! `NoContraction`, its quotient the device's division (`OpFDiv`); the precise `air.tanh` is the -//! device's `Tanh`, and a `half` `fast_tanh` Metal's `half` `tanh`, `(t - 1) · (1 / (t + 1))` of -//! the same `t` (no `Tanh`); -//! - `air.sign` is Metal's `sign` with and without fast math (no `FSign`, which keeps the sign -//! of a zero where Metal answers `+0`), and both answer `-1` for `-3` on the interpreter; +//! device's `Tanh`. A `half` `fast_tanh` is Metal's `half` `tanh` (Metal's `half` functions are +//! the same in both math modes, and MSL's fast-math formulas are its `float` ones), so it is the +//! device's `Tanh` too (no `Exp2`, no division), noted `NativeTranscendentals` wherever the +//! device's functions are not Metal's own, and on MoltenVK MSL's `float` `tanh` rounded to +//! `half` (`DeviceTranscendentals`); +//! - `air.sign` is the device's `FSign` with and without fast math (it keeps the sign of a zero +//! where Metal answers `+0`), noted `NativeTranscendentals` wherever the device's functions are +//! not Metal's own (on MoltenVK it is MSL's own `sign`), and both answer `-1` for `-3` on the +//! interpreter; //! - `air.sinpi` and `air.fast_sinpi` reduce their argument (`RoundEven`) and take the sine of the //! residue from the device's `Sin` on every profile. //! //! The values of these functions are the unit tests' (`lower::arith::tests`); no GPU is used. //! -//! The sRGB conversions of `unorm4x8_srgb` run end to end on the interpreter: A1's committed -//! fixtures `a1_srgb_decode_all_bytes` (every byte in every channel, `float` and `half` results) -//! and `a1_srgb_encode_sweep` (every multiple of 2⁻¹⁴ in `[0, 1.0078]` and every `half` up to 2.25) -//! compile on every profile above, declare Metal's twelve-bit table once per module, read no `Pow`, -//! note no device transcendentals, and write the table's word for every thread. +//! The sRGB conversions of `unorm4x8_srgb` compile end to end: A1's committed fixtures +//! `a1_srgb_decode_all_bytes` (every byte in every channel, `float` and `half` results) and +//! `a1_srgb_encode_sweep` (every multiple of 2⁻¹⁴ in `[0, 1.0078]` and every `half` up to 2.25) +//! compile on every profile above, take the MSL transfer functions by the device's `Pow` around +//! the 8-bit instruction, declare no table, and note `DevicePackConversion`. The interpreter models +//! no `Pow`, so their values are the device lanes' (the validation crate's authored cases of the +//! same fixtures). //! //! `llvm-as` assembles the modules; without it the tests skip visibly. @@ -29,8 +36,7 @@ use crate::lower::emit::emit_module; use crate::lower::select::{select, LowerInputs}; use crate::memory::static_root::analyze_memory; use crate::pipeline::artifact::PrecisionNote; -use crate::pipeline::interface::PushLoc; -use crate::pipeline::sym::{Axis, PushField, ResourceKind, ResourceSlot, SpecKey, Stage}; +use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; use crate::pipeline::testing::{ compile, engine_dir, exact_maths, link_and_validate, llvm_assemble, meter, profile, typed_module, AssembleError, Scratch, @@ -47,6 +53,8 @@ const TANH: u32 = 21; const EXP2: u32 = 29; const ROUND_EVEN: u32 = 2; const POW: u32 = 26; +const PACK_UNORM_4X8: u32 = 55; +const UNPACK_UNORM_4X8: u32 = 64; /// One kernel: its body defines `%r` (`float`), which it stores. struct Kernel { @@ -57,6 +65,9 @@ struct Kernel { lacks: &'static [u32], /// Whether the module divides (`OpFDiv`): `fast::tanh`'s quotient. divides: bool, + /// Whether the module takes the device's instruction for a function Metal defines otherwise, + /// recording `NativeTranscendentals` wherever the device's functions are not Metal's own. + native: bool, /// The stored word on the interpreter, when it models the kernel. want: Option, } @@ -68,6 +79,7 @@ const KERNELS: [Kernel; 8] = [ has: &[EXP2], lacks: &[TANH], divides: true, + native: false, want: None, }, // RC3 cases e72f550f and 2d5f3949's GELU tail at x = -8: 0.5 * x * (1 + tanh(...)). @@ -77,6 +89,7 @@ const KERNELS: [Kernel; 8] = [ has: &[EXP2], lacks: &[TANH], divides: true, + native: false, want: None, }, Kernel { @@ -85,30 +98,34 @@ const KERNELS: [Kernel; 8] = [ has: &[TANH], lacks: &[EXP2], divides: false, + native: false, want: None, }, Kernel { name: "fast_tanh_half", body: " %a = fadd fast float 0x4000000000000000, -0.0\n %h = fptrunc float %a to half\n %t = call fast half @air.fast_tanh.f16(half %h)\n %r = fpext half %t to float\n", - has: &[EXP2], - lacks: &[TANH], - divides: true, + has: &[TANH], + lacks: &[EXP2], + divides: false, + native: true, want: None, }, Kernel { name: "fast_sign", body: " %a = fadd fast float 0xC008000000000000, -0.0\n %r = call fast float @air.sign.f32(float %a)\n", - has: &[], - lacks: &[FSIGN], + has: &[FSIGN], + lacks: &[], divides: false, + native: true, want: Some(0xBF80_0000), }, Kernel { name: "precise_sign", body: " %a = fadd float 0xC008000000000000, -0.0\n %r = call float @air.sign.f32(float %a)\n", - has: &[], - lacks: &[FSIGN], + has: &[FSIGN], + lacks: &[], divides: false, + native: true, want: Some(0xBF80_0000), }, Kernel { @@ -117,6 +134,7 @@ const KERNELS: [Kernel; 8] = [ has: &[SIN, ROUND_EVEN], lacks: &[], divides: false, + native: false, want: None, }, Kernel { @@ -125,6 +143,7 @@ const KERNELS: [Kernel; 8] = [ has: &[SIN, ROUND_EVEN], lacks: &[], divides: false, + native: false, want: None, }, ]; @@ -225,7 +244,7 @@ fn interpret(bitcode: &[u8], entry: &str, stem: &str) -> u32 { } #[test] -fn metal_math_variants_select_metals_functions() { +fn metal_math_variants_select_their_forms() { let Some(bitcode) = assemble() else { return; }; @@ -254,17 +273,33 @@ fn metal_math_variants_select_metals_functions() { // The fast-math entry's `fast_tanh` notes its steps' precision (the device's // `Exp2` and division), except where every step is Metal's own function on the device // (`FloatFunctions::Metal`), which notes nothing in such an entry. - // A `half` one's division is its reciprocal, a function of its own. if k.divides { - let half = k.name.ends_with("_half"); assert_eq!( - (half || a.precision.contains(&PrecisionNote::DeviceArithmetic)) + a.precision.contains(&PrecisionNote::DeviceArithmetic) && a.precision.contains(&PrecisionNote::NativeTranscendentals), !metal, "{what}: {:?}", a.precision ); } + // The device's instruction: noted `NativeTranscendentals` wherever the device's + // functions are not Metal's own. On MoltenVK `sign` is MSL's own; a `half` `tanh` is + // MSL's `float` one rounded to `half`, within Apple's bound. + if k.native { + assert_eq!( + a.precision.contains(&PrecisionNote::NativeTranscendentals), + !metal, + "{what}: {:?}", + a.precision + ); + let half = k.name.ends_with("_half"); + assert_eq!( + a.precision.contains(&PrecisionNote::DeviceTranscendentals), + metal && half, + "{what}: {:?}", + a.precision + ); + } if let Some(want) = k.want { let got = interpret(&bitcode, k.name, stem); assert_eq!(got, want, "{what}: {got:#x} != {want:#x}"); @@ -363,137 +398,13 @@ fn fast_tanh_is_one_operation() { } } -/// The byte Metal's twelve-bit table encodes `x` to: the index `i = round(x * 4095)` of the exact -/// product, then the MSL transfer with the exponent `0.41666` (which reproduces every one of A1's -/// 4096 observed indices; `1/2.4` misses four), rounded to nearest even. -fn srgb_encode(x: f64) -> u32 { - let i = (x.clamp(0.0, 1.0) * 4095.0).round_ties_even(); - let c = i / 4095.0; - let v = if c < 0.0031308 { - 12.92 * c - } else { - 1.055 * c.powf(0.41666) - 0.055 - }; - (255.0 * v).round_ties_even() as u32 -} - -/// A linear (alpha) channel: the exact product `x * 255` rounded to nearest even. -fn unorm_encode(x: f64) -> u32 { - (x.clamp(0.0, 1.0) * 255.0).round_ties_even() as u32 -} - -/// Metal's decode of color byte `b`: the table step `k = round(decode(b / 255) * 4095)` of the MSL -/// transfer, answered as `k / 4095` correctly rounded. -fn srgb_decode(b: u32) -> f32 { - let c = f64::from(b) / 255.0; - let v = if c <= 0.04045 { - c / 12.92 - } else { - ((c + 0.055) / 1.055).powf(2.4) - }; - ((v * 4095.0).round_ties_even() / 4095.0) as f32 -} - -/// The `half` nearest `x` (ties to even), for `x` in `[0, 65504]`. -fn half_bits(x: f32) -> u32 { - let v = f64::from(x); - assert!((0.0..=65504.0).contains(&v), "{x}"); - if v < 2f64.powi(-14) { - // Subnormal: multiples of 2^-24 (1024 is the least normal, 0x400). - return (v * 2f64.powi(24)).round_ties_even() as u32; - } - let mut e = ((x.to_bits() >> 23) & 0xff) as i32 - 127; - let mut m = (v / 2f64.powi(e - 10)).round_ties_even() as u32; - if m == 2048 { - e += 1; - m = 1024; - } - (((e + 15) as u32) << 10) | (m - 1024) -} - -/// The value of `half` bit pattern `h` (finite, non-negative). -fn half_value(h: u32) -> f64 { - let (e, m) = ((h >> 10) & 0x1f, h & 0x3ff); - if e == 0 { - f64::from(m) * 2f64.powi(-24) - } else { - f64::from(1024 + m) * 2f64.powi(e as i32 - 25) - } -} - -/// The words fixture `entry` writes to `[[buffer(0)]]` over `threads` threads (32-lane -/// threadgroups), `per_thread` words each, on the interpreter. -fn run_fixture(bc: &[u8], entry: &str, stem: &str, threads: u32, per_thread: u32) -> Vec { - let p = profile(stem, exact_maths()).expect("profile"); - let (plan, m) = typed_module(bc, entry, &p).unwrap_or_else(|e| panic!("{entry}: {e}")); - // Zero push bytes: a zero bind residual and a dispatch region based at the origin. - for f in &plan.push.fields { - assert!( - matches!( - (f.field, f.loc), - ( - PushField::SlotBindOffset(_) - | PushField::DispatchRegion - | PushField::Specialized(crate::pipeline::sym::SpecKey::DroppedStoreSlots( - _ - )), - PushLoc::Push { .. } - ) - ), - "{entry}: {:?}", - f.field - ); - } - // One `Private` variable with an initializer: the table, declared once however many - // conversions read it (float and half). - let tables = m - .globals() - .iter() - .filter(|g| g.class == StorageClass::Private && g.init.is_some()) - .count(); - assert_eq!(tables, 1, "{entry} on {stem}: the sRGB table"); - let mut res = Resources { - buffers: vec![Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 0, - }), - address: None, - bytes: vec![0xab; 4 * (threads * per_thread) as usize], - }], - push: vec![0; plan.push.push_range.map_or(0, |(_, len)| len as usize)], - spec: Default::default(), - }; - for (axis, n) in [(Axis::X, 32u32), (Axis::Y, 1), (Axis::Z, 1)] { - res.spec.insert(SpecKey::LocalSize(axis), n.into()); - } - res.spec.insert(SpecKey::FlatLocalSize, 32u32.into()); - let config = Config { - workgroups: [threads / 32, 1, 1], - ..Config::default() - }; - let out = run(&m, &config, res).unwrap_or_else(|e| panic!("{entry} on {stem}: {e}")); - out.buffers[0] - .chunks(4) - .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect() -} - /// End to end: the sRGB fixtures through select, emit, and link on every profile above: L3 passes, -/// the module reads no `Pow` and notes no device transcendentals, and on the interpreter every -/// thread writes Metal's table words. -/// -/// - `a1_srgb_decode_all_bytes`: thread `t` unpacks the word of bytes `t`, `255 - t`, -/// `t ^ 0x5a`, `(7t + 3) & 255` and writes the four `float` results, then the four `half` -/// results (each rounded from the `float` quotient) as two words. Metal's own steps of bytes 1, -/// 137, and 255 (`0x39800801`, `0x3E800801`, `1.0`) are among them. -/// - `a1_srgb_encode_sweep`: thread `t` packs `3t`, `3t + 1`, `3t + 2` times 2⁻¹⁴ (alpha `3t` -/// times 2⁻¹⁴, linear), then the `half` patterns `3t`, `3t + 1`, `3t + 2` (alpha `3t`). +/// and each module takes the MSL transfer functions by the device's `Pow` around the 8-bit +/// instruction (`a1_srgb_decode_all_bytes`: `UnpackUnorm4x8`, its `float` and `half` results; +/// `a1_srgb_encode_sweep`: `PackUnorm4x8`, from `float` and `half` colours), declares no table +/// (no initialized `Private` variable), and records `DevicePackConversion`. #[test] -fn srgb_fixtures_answer_with_metals_tables_on_the_interpreter() { - const DECODE: u32 = 256; - const ENCODE: u32 = 5504; +fn srgb_fixtures_take_the_transfer_by_the_devices_pow() { let assembled = |stem: &str| match llvm_assemble(&engine_dir().join(format!("{stem}.ll"))) { Ok(b) => Some(b), Err(AssembleError::Missing(t)) => { @@ -508,76 +419,35 @@ fn srgb_fixtures_answer_with_metals_tables_on_the_interpreter() { ) else { return; }; - - let mut decoded = Vec::new(); - for t in 0..DECODE { - let bytes = [t, 255 - t, t ^ 0x5a, (7 * t + 3) & 255]; - let lanes = [ - srgb_decode(bytes[0]), - srgb_decode(bytes[1]), - srgb_decode(bytes[2]), - bytes[3] as f32 / 255.0, - ]; - decoded.extend(lanes.iter().map(|x| x.to_bits())); - decoded.push(half_bits(lanes[0]) | (half_bits(lanes[1]) << 16)); - decoded.push(half_bits(lanes[2]) | (half_bits(lanes[3]) << 16)); - } - // Metal's steps (authored case `srgb-transfer-and-its-twelve-bit-table`): bytes 1, 137, and - // 255 in the red channel of threads 1, 137, and 255. - for (t, want) in [ - (1usize, 0x3980_0801u32), - (137, 0x3E80_0801), - (255, 0x3F80_0000), - ] { - assert_eq!(decoded[6 * t], want, "byte {t}"); - } - let mut encoded = Vec::new(); - for t in 0..ENCODE { - let k = 3 * t; - let x = |j: u32| f64::from(k + j) * 2f64.powi(-14); - encoded.push( - srgb_encode(x(0)) - | (srgb_encode(x(1)) << 8) - | (srgb_encode(x(2)) << 16) - | (unorm_encode(x(0)) << 24), - ); - let h = |j: u32| half_value(k + j); - encoded.push( - srgb_encode(h(0)) - | (srgb_encode(h(1)) << 8) - | (srgb_encode(h(2)) << 16) - | (unorm_encode(h(0)) << 24), - ); - } - for stem in PROFILES { let p = profile(stem, exact_maths()).expect("profile"); - for (bc, entry, threads, per_thread, want) in [ - (&decode_bc, "a1_srgb_decode_all_bytes", DECODE, 6, &decoded), - (&encode_bc, "a1_srgb_encode_sweep", ENCODE, 2, &encoded), + for (bc, entry, instruction) in [ + (&decode_bc, "a1_srgb_decode_all_bytes", UNPACK_UNORM_4X8), + (&encode_bc, "a1_srgb_encode_sweep", PACK_UNORM_4X8), ] { let what = format!("{entry} on {stem}"); let a = compile(bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); let (ext, _) = ext_insts(&words); - assert!(!ext.contains(&POW), "{what}: reads Pow ({ext:?})"); + for i in [POW, instruction] { + assert!( + ext.contains(&i), + "{what}: GLSL.std.450 {i} missing ({ext:?})" + ); + } assert!( - !a.precision.contains(&PrecisionNote::DeviceTranscendentals), + a.precision.contains(&PrecisionNote::DevicePackConversion), "{what}: {:?}", a.precision ); - let got = run_fixture(bc, entry, stem, threads, per_thread); - for (i, (g, w)) in got.iter().zip(want.iter()).enumerate() { - assert_eq!( - g, - w, - "{what}: thread {} word {}: {g:#010x} != {w:#010x}", - i as u32 / per_thread, - i as u32 % per_thread - ); - } - assert_eq!(got.len(), want.len(), "{what}"); + let (_, m) = typed_module(bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e}")); + let tables = m + .globals() + .iter() + .filter(|g| g.class == StorageClass::Private && g.init.is_some()) + .count(); + assert_eq!(tables, 0, "{what}: a table"); } } } diff --git a/crates/metal2vulkan/src/tests/engine_native_half.rs b/crates/metal2vulkan/src/tests/engine_native_half.rs index 4519ab198..0272042e0 100644 --- a/crates/metal2vulkan/src/tests/engine_native_half.rs +++ b/crates/metal2vulkan/src/tests/engine_native_half.rs @@ -205,12 +205,6 @@ fn native_half_rounding_records_its_kind_and_requires_no_fact() { link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); let noted: Vec<_> = natives.iter().filter(|n| a.precision.contains(n)).collect(); assert_eq!(noted, note.iter().collect::>(), "{what}"); - assert!( - !a.requirements - .properties - .contains(&VkProperty::MetalHalfQuantize), - "{what}" - ); } } // Metal's `half(float)` on the interpreter's nearest-even conversion and quantize: a tie to @@ -264,12 +258,6 @@ fn a_half_below_the_smallest_normal_takes_the_devices_quantize() { "{what}: {:?}", a.precision ); - assert!( - !a.requirements - .properties - .contains(&VkProperty::MetalHalfQuantize), - "{what}" - ); } let run = |name: &str, x: [f32; 2]| interpret(&bc, name, p, x); // Two normal halves whose difference is the half denormal `3 * 2^-24`. @@ -777,12 +765,6 @@ fn a_controlled_conversion_rounds_half_where_the_float_controls_allow() { "{what}: {kind:?} {width:?}" ); } - assert!( - !a.requirements - .properties - .contains(&VkProperty::MetalHalfQuantize), - "{what}" - ); for note in [ PrecisionNote::NativeHalfConversion, PrecisionNote::NativeHalfQuantize, diff --git a/crates/metal2vulkan/src/tests/engine_native_maths.rs b/crates/metal2vulkan/src/tests/engine_native_maths.rs index cf4a0612c..739de5818 100644 --- a/crates/metal2vulkan/src/tests/engine_native_maths.rs +++ b/crates/metal2vulkan/src/tests/engine_native_maths.rs @@ -8,8 +8,10 @@ //! 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; 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. +//! each records its kind; the interpreter's answers stay within the bound the kind's docs state. +//! `dot`, `mix` and `fast::sqrt` are the device's instructions on MoltenVK too, where a `float` +//! one is MSL's own function and records no note. `llvm-as` assembles the module; without it the +//! tests skip visibly. use crate::air::{self, SpecRequest}; use crate::device::profile::{DeviceProfile, FloatFunctions}; @@ -299,55 +301,102 @@ fn the_nan_and_min_max_are_the_device_s() { 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 -/// within the bound its note states, and `fast::sqrt` the device's `Sqrt`, within Vulkan's -/// `1 / InverseSqrt` (4.5 ulp); on MoltenVK, whose functions are Metal's, `dot` is Metal's fused -/// chain and `mix` its `fma(t, y, fma(-t, x, x))`, word for word. +/// The `GLSL.std.450` instruction numbers and the opcodes of `words`' instructions. +fn instructions(words: &[u32]) -> (Vec, Vec) { + let (mut ext, mut ops) = (Vec::new(), Vec::new()); + let mut i = 5; + while i < words.len() { + let (len, op) = ((words[i] >> 16) as usize, words[i] & 0xFFFF); + assert!(len > 0 && i + len <= words.len(), "malformed module"); + if op == crate::spv::Op::ExtInst as u32 { + ext.push(words[i + 4]); + } + ops.push(op); + i += len; + } + (ext, ops) +} + +/// `dot` is the device's `OpDot` and `mix` its `FMix` (a `half` one rounded once), with no fused +/// multiply-add, and `fast::sqrt` the device's `Sqrt`, on lavapipe and on MoltenVK alike. On +/// lavapipe each records its note; on MoltenVK a `float` `dot` and `mix` are MSL's own and record +/// none, and a `half` `mix` records `NativeMix`. On the interpreter's model of the instructions each +/// answer is within the bound its note states (`fast::sqrt` within Vulkan's `1 / InverseSqrt`, 4.5 +/// ulp, on lavapipe). #[test] -fn dot_mix_and_fast_sqrt_are_the_device_s_and_metal_s_on_moltenvk() { +fn dot_mix_and_fast_sqrt_are_the_device_s_on_every_profile() { let Some(bc) = bitcode() else { return; }; let on = profile("lavapipe", DevicePolicy::default()).expect("lavapipe"); let metal = profile("moltenvk-m3", DevicePolicy::default()).expect("moltenvk-m3"); - for [a, b, c] in [ - [1.0f32, 3.0, 0.5], - [-3.0, 0.7, 1.9], - [0.75, -4.1, 2.5e-3], - [1e-3, 3e7, -0.25], - ] { - let (a64, b64, c64) = (f64::from(a), f64::from(b), f64::from(c)); - // `dot(float2(a, b), float2(c, a))`: two lanes, `(3n - 1) * 2^-24 * sum |a_i * b_i|`. - let sum = (a64 * c64).abs() + (b64 * a64).abs(); - let dot = interpret(&bc, "native_dot", &on, [a, b, c]); - assert!( - (f64::from(dot) - (a64 * c64 + b64 * a64)).abs() <= 5.0 * 2f64.powi(-24) * sum, - "dot({a}, {b}, {c}) = {dot}" - ); - assert_eq!( - interpret(&bc, "native_dot", &metal, [a, b, c]), - b.mul_add(a, a * c), - "Metal's dot({a}, {b}, {c})" - ); - // `mix(a, b, c)`: within `2^-21 * (|a * (1 - c)| + |b * c|)`. - let scale = (a64 * (1.0 - c64)).abs() + (b64 * c64).abs(); - let mix = interpret(&bc, "native_mix", &on, [a, b, c]); - assert!( - (f64::from(mix) - (a64 + c64 * (b64 - a64))).abs() <= 2f64.powi(-21) * scale, - "mix({a}, {b}, {c}) = {mix}" - ); - assert_eq!( - interpret(&bc, "native_mix", &metal, [a, b, c]), - c.mul_add(b, (-c).mul_add(a, a)), - "Metal's mix({a}, {b}, {c})" - ); + let (fma, fmix, sqrt) = ( + crate::spv::GlslStd450Op::Fma as u32, + crate::spv::GlslStd450Op::FMix as u32, + crate::spv::GlslStd450Op::Sqrt as u32, + ); + for (p, stem) in [(&on, "lavapipe"), (&metal, "moltenvk-m3")] { + let own = p.fields().float_functions == FloatFunctions::Metal; + for (name, note, float) in [ + ("native_dot", PrecisionNote::NativeDot, true), + ("native_mix", PrecisionNote::NativeMix, true), + ("native_half_mix", PrecisionNote::NativeMix, false), + ( + "native_fast_sqrt", + PrecisionNote::NativeTranscendentals, + true, + ), + ] { + let what = format!("{name} on {stem}"); + let a = compile(&bc, 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 (ext, ops) = instructions(&words); + assert!( + !ext.contains(&fma), + "{what}: a fused multiply-add ({ext:?})" + ); + match name { + "native_dot" => assert!(ops.contains(&(crate::spv::Op::Dot as u32)), "{what}"), + "native_fast_sqrt" => assert!(ext.contains(&sqrt), "{what}: {ext:?}"), + _ => assert!(ext.contains(&fmix), "{what}: {ext:?}"), + } + assert_eq!( + a.precision.contains(¬e), + !(own && float), + "{what}: {:?}", + a.precision + ); + } + } + for p in [&on, &metal] { + for [a, b, c] in [ + [1.0f32, 3.0, 0.5], + [-3.0, 0.7, 1.9], + [0.75, -4.1, 2.5e-3], + [1e-3, 3e7, -0.25], + ] { + let (a64, b64, c64) = (f64::from(a), f64::from(b), f64::from(c)); + // `dot(float2(a, b), float2(c, a))`: two lanes, `(3n - 1) * 2^-24 * sum |a_i * b_i|`. + let sum = (a64 * c64).abs() + (b64 * a64).abs(); + let dot = interpret(&bc, "native_dot", p, [a, b, c]); + assert!( + (f64::from(dot) - (a64 * c64 + b64 * a64)).abs() <= 5.0 * 2f64.powi(-24) * sum, + "dot({a}, {b}, {c}) = {dot}" + ); + // `mix(a, b, c)`: within `2^-21 * (|a * (1 - c)| + |b * c|)`. + let scale = (a64 * (1.0 - c64)).abs() + (b64 * c64).abs(); + let mix = interpret(&bc, "native_mix", p, [a, b, c]); + assert!( + (f64::from(mix) - (a64 + c64 * (b64 - a64))).abs() <= 2f64.powi(-21) * scale, + "mix({a}, {b}, {c}) = {mix}" + ); + } } // `half` `mix(0.5, 1.5, 0.25)` is exact: 0.75. for p in [&on, &metal] { assert_eq!(interpret(&bc, "native_half_mix", p, [0.5, 1.5, 0.25]), 0.75); } - // `fast::sqrt`'s zero and `+inf` are IEEE's, as Metal's (the interpreter leaves MoltenVK's - // `InverseSqrt` unmodelled). + // `fast::sqrt`'s zero and `+inf` are IEEE's, as Metal's. let sqrt = |x: f32| interpret(&bc, "native_fast_sqrt", &on, [x, 0.0, 0.0]); for x in [2.0f32, 0.75, 1e-30, 3e30] { assert!(ulps(sqrt(x), f64::from(x).sqrt()) <= 4.5, "fast::sqrt({x})"); diff --git a/crates/metal2vulkan/src/tests/engine_tiny_products.rs b/crates/metal2vulkan/src/tests/engine_tiny_products.rs index d07eb019b..7f90c7de3 100644 --- a/crates/metal2vulkan/src/tests/engine_tiny_products.rs +++ b/crates/metal2vulkan/src/tests/engine_tiny_products.rs @@ -1,6 +1,7 @@ //! Metal's `float` multiply flushes a product whose exact value lies below `2^-126` to the zero of //! its sign before rounding it (tininess before rounding), on vector and scalar lanes, with and -//! without fast math, and as the first product of `dot`'s fused chain: the owned fixtures +//! without fast math, and as the first product of its `dot` (the module's `dot` is the device's +//! `OpDot`): the owned fixtures //! `tiny_products_flush` and `tiny_products_flush_fast`, whose words on an Apple M3 Max under //! macOS 27.0.1 are `tiny_products_m3.txt` (the authored cases of the fixtures, //! `float-products-flushed-before-rounding` and its fast-math twin). diff --git a/crates/metal2vulkan/src/tests/fast_paths.rs b/crates/metal2vulkan/src/tests/fast_paths.rs index b1b8a7521..638b4dc6b 100644 --- a/crates/metal2vulkan/src/tests/fast_paths.rs +++ b/crates/metal2vulkan/src/tests/fast_paths.rs @@ -115,6 +115,7 @@ fn notes() -> Vec<(&'static str, Ledger)> { NativeFma, NativeDot, NativeMix, + DevicePackConversion, DeviceDenormals, DeviceSampling, DeviceTexelConversion, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 345f09e93..c980acb0b 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -4938,6 +4938,7 @@ macro-member metal2vulkan-runtime::Degradation::DeviceDenormals DeviceDenormals macro-member metal2vulkan-runtime::Degradation::DeviceFilteredMipmaps DeviceFilteredMipmaps = "device-filtered-mipmaps", Precision, macro-member metal2vulkan-runtime::Degradation::DeviceInterpolation DeviceInterpolation = "device-interpolation"; macro-member metal2vulkan-runtime::Degradation::DeviceNanEncoding DeviceNanEncoding = "device-nan-encoding"; +macro-member metal2vulkan-runtime::Degradation::DevicePackConversion DevicePackConversion = "device-pack-conversion"; macro-member metal2vulkan-runtime::Degradation::DevicePointSize DevicePointSize = "device-point-size"; macro-member metal2vulkan-runtime::Degradation::DeviceRayIntersection DeviceRayIntersection = "device-ray-intersection"; macro-member metal2vulkan-runtime::Degradation::DeviceRoundedResolve DeviceRoundedResolve = "device-rounded-resolve", Precision, @@ -12806,7 +12807,6 @@ variant metal2vulkan::device::VkProperty::MetalFullQuads MetalFullQuads variant metal2vulkan::device::VkProperty::MetalHalfArithmetic MetalHalfArithmetic variant metal2vulkan::device::VkProperty::MetalHalfColorNans MetalHalfColorNans variant metal2vulkan::device::VkProperty::MetalHalfFma MetalHalfFma -variant metal2vulkan::device::VkProperty::MetalHalfQuantize MetalHalfQuantize variant metal2vulkan::device::VkProperty::MetalHalfStorageNans MetalHalfStorageNans variant metal2vulkan::device::VkProperty::MetalHalfStorageWrites MetalHalfStorageWrites variant metal2vulkan::device::VkProperty::MetalHalfTexelWrites MetalHalfTexelWrites @@ -12962,7 +12962,6 @@ variant metal2vulkan::error::DriverDeviation::MetalFullQuads MetalFullQuads variant metal2vulkan::error::DriverDeviation::MetalHalfArithmetic MetalHalfArithmetic variant metal2vulkan::error::DriverDeviation::MetalHalfColorNans MetalHalfColorNans variant metal2vulkan::error::DriverDeviation::MetalHalfFma MetalHalfFma -variant metal2vulkan::error::DriverDeviation::MetalHalfQuantize MetalHalfQuantize variant metal2vulkan::error::DriverDeviation::MetalHalfStorageNans MetalHalfStorageNans variant metal2vulkan::error::DriverDeviation::MetalHalfStorageWrites MetalHalfStorageWrites variant metal2vulkan::error::DriverDeviation::MetalHalfTexelWrites MetalHalfTexelWrites @@ -13433,6 +13432,7 @@ variant metal2vulkan::pipeline::PrecisionNote::DeviceColorConversion DeviceColor variant metal2vulkan::pipeline::PrecisionNote::DeviceDenormals DeviceDenormals variant metal2vulkan::pipeline::PrecisionNote::DeviceInterpolation DeviceInterpolation variant metal2vulkan::pipeline::PrecisionNote::DeviceNanEncoding DeviceNanEncoding +variant metal2vulkan::pipeline::PrecisionNote::DevicePackConversion DevicePackConversion variant metal2vulkan::pipeline::PrecisionNote::DevicePointSize DevicePointSize variant metal2vulkan::pipeline::PrecisionNote::DeviceRayIntersection DeviceRayIntersection variant metal2vulkan::pipeline::PrecisionNote::DeviceSampleLevel DeviceSampleLevel diff --git a/docs/API.md b/docs/API.md index 8bc419dbf..36ea6ba9d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2596,12 +2596,12 @@ bound. measured to read them as Metal does: `+ - *`, the comparisons, `fma`, `dot`, `sqrt`, `rsqrt`, `trunc` and `rint` but on a device that takes the measured `DriverDeviation::MetalFloatDenormals`; and on every device the divisions and the remainder, - `floor` and `ceil`, the device's maths functions (`fast::fmod`'s fused multiply-add among them), - `mix` by `FMix`, `fast::sqrt` by `Sqrt`, `dot` of vectors of other than two to four lanes, whose - chunks' products the device sums where Metal flushes each one below `2^-126`, and a conversion - to or from `double`, where Metal's reading is not measured. The operations that read a denormal - on its bits answer Metal on every device: `ldexp`, `sign`, `fract`, `copysign`, `fabs` and - `atan2`; and so do the functions the device answers as Metal's own. Where the minimum and maximum + `floor`, `ceil` and `fneg`, the device's maths functions (`fast::fmod`'s fused multiply-add, + `fabs`, `sign` and `fract` among them), `mix` by `FMix`, `fast::sqrt` by `Sqrt`, `dot` of + vectors of other than two to four lanes, whose chunks' products the device sums where Metal + flushes each one below `2^-126`, and a conversion to or from `double`, where Metal's reading is + not measured. The operations that read a denormal on its bits answer Metal on every device: + `ldexp`, `copysign` and `atan2`; and so do the functions the device answers as Metal's own. Where the minimum and maximum functions and `saturate` are the device's `NMin`, `NMax` and `NClamp`, their pick of a denormal is `NativeMinMax`'s. Off MoltenVK the device's multiply and fused multiply-add round a result whose exact value is below `2^-126` up to `2^-126`, which Metal flushes @@ -2992,9 +2992,13 @@ bound. binding such a texture makes no pipeline of its own. - `metal2vulkan-degrade-native-transcendentals` (precision). `PrecisionNote::NativeTranscendentals`: Native device maths: the module computes a `float` or `half` math-library function by the device's - own `GLSL.std.450` instruction (or Metal's composition of the device's `Exp2` and `Log2`) where - Metal's function is not the device's own; and `fast::sqrt` the device's `Sqrt` on a device whose - functions are not Metal's own. + own `GLSL.std.450` instruction (`exp`, `log`, `pow`, `sinh`, `cosh` and `tanh` among them; a + composition of the device's `Exp2` and `Log2` only for `exp10` and `log10`, which no instruction + is) where Metal's function is not the device's own; `fast::sqrt` the device's `Sqrt`; `fabs`, + `sign` and `fract` the device's `FAbs`, `FSign` and `Fract`, their special operands the + instruction's (Metal's `sign` of a NaN, a zero and an `f32` denormal is `+0`, its `fract` of an + infinity `+0`); and `round` C99's from the device's `Trunc` on every device (`round(-0.3)` is + `-0`, where Metal answers `+0`). - `metal2vulkan-degrade-native-division` (precision). `PrecisionNote::NativeDivision`: Native device maths: a precise `float` or `half` division, or Metal's fast division or reciprocal, is the device's `OpFDiv` where the device's division is not Metal's own: within Vulkan's 2.5 ulp, where @@ -3042,7 +3046,9 @@ bound. - `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, 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 + Metal's canonical one on a device measured to answer that, MoltenVK on an Apple GPU): a `float` + `fneg` and `fabs`, which keep a NaN operand's payload on Metal, and a `half` `fract`, which + returns it, among them. Also recorded wherever a `half` is read from its bits, on every device, since the read is the device's widening (its conversion with `shaderFloat16`, `UnpackHalf2x16` without): a NaN's bits the device's, where Metal widens every `half` NaN to `0x7fc00000` and moves one it does not @@ -3050,15 +3056,27 @@ bound. - `metal2vulkan-degrade-native-min-max` (precision). `PrecisionNote::NativeMinMax`: Native device maths: Metal's `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` (its `clamp(x, +0, 1)`) on `float` or `half` is the device's `GLSL.std.450` `NMin`, `NMax` or `NClamp`, on a device not - measured to answer Metal's operand. + measured to answer Metal's operand; and `median3` on every device, `min(max(c, min(a, b)), + max(a, b))` of the device's `NMin` and `NMax`, whose pick of two NaNs and of an `f32` denormal is + the device's (Metal's `fast::median3` answers `b` for two NaN first operands). - `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 - Metal's fused chain of its products, on a device whose functions are not Metal's own. + Metal's `dot` on `float` and `half` is the device's `OpDot` (a `half` one summed in `float` and + rounded once to `half`), not Metal's fused chain of its products, on every device but for a + `float` one where the device's functions are Metal's own (MoltenVK). - `metal2vulkan-degrade-native-mix` (precision). `PrecisionNote::NativeMix`: Native device maths: - Metal's `mix(x, y, t)` on `float`, or on `half` where its fused multiply-add is not the measured - 16-bit one, is the device's `FMix` (a `half` one computed in `float` and rounded once to `half`), - not Metal's `fma(t, y, fma(-t, x, x))`, on a device whose functions are not Metal's own. + Metal's `mix(x, y, t)` on `float` and `half` is the device's `FMix` (a `half` one computed in + `float` and rounded once to `half`), not Metal's `fma(t, y, fma(-t, x, x))`, on every device but + for a `float` one where the device's functions are Metal's own (MoltenVK). +- `metal2vulkan-degrade-device-pack-conversion` (precision). `PrecisionNote::DevicePackConversion`: + Native device maths (a conversion): `air.pack` or `air.unpack` of a normalized format is the + device's: `GLSL.std.450`'s `Pack`/`Unpack` `Unorm4x8`, `Snorm4x8`, `Unorm2x16` and `Snorm2x16`, + their definition by the device's `NClamp`, multiply, `RoundEven` and reciprocal for `rgb10a2` and + `rgb565`, and the MSL transfer functions by the device's `Pow` for `unorm4x8_srgb`'s colour. Metal + rounds the exact product and divides correctly rounded, answers code 0 for a NaN channel, and + takes an sRGB colour through its twelve-bit table; a packed code is within one of Metal's, an + unpacked value within 2.5 ulp, a decoded sRGB colour within half a twelve-bit step (`1 / 8190`) + of Metal's step beyond its `Pow`'s bound. Not recorded for a + `float` conversion of the four named formats on MoltenVK, Metal's own there. - `metal2vulkan-degrade-color-attachment-groups` (precision). `PrecisionNote::ColorAttachmentGroups`: A render pipeline whose color attachments the device draws in more than one group (more than the lesser of its `maxColorAttachments` and diff --git a/docs/CONFORMANCE-COVERAGE.md b/docs/CONFORMANCE-COVERAGE.md index 65a3409dd..9282479cb 100644 --- a/docs/CONFORMANCE-COVERAGE.md +++ b/docs/CONFORMANCE-COVERAGE.md @@ -44,7 +44,7 @@ Its limits, measured rather than asserted: | committed recordings | 1122 | | distinct SDK items the Metal leg reaches, of any status | 800 | | of those, reached only where this cannot name the family | 2 | -| ledger rows (a case whose gap is recorded) | 936 | +| ledger rows (a case whose gap is recorded) | 937 | | declared crossings of the option space (pairs put to Metal at once) | 26 | | declared crossings that are no pair of it (a boolean or numeric field, or one type in two slots) | 30 | @@ -2770,8 +2770,9 @@ A case whose difference from Metal is recorded rather than compared away. The le | `norm-storage-codes-rgba8unorm` | A `float` the function writes to a normalized storage texture at a tie between two codes: Metal stores the exact product rounded with a tie away from zero, and … | | `norm-storage-codes-rgba8unorm` | A `float` the function writes to a normalized storage texture at a tie between two codes: Metal stores the exact product rounded with a tie away from zero, and … | | `norm-storage-codes-rgba8unorm` | A `float` the function writes to a normalized storage texture at a tie between two codes: Metal stores the exact product rounded with a tie away from zero, and … | -| `pass-bytes-half-tanh-regimes` | Each word holds two `half` results of `tanh` over its regimes, which the device computes by its own functions and rounds to `half` by its own conversion (`nativ… | -| `pass-bytes-srgb-decode-all-bytes` | Each word holds two `half` results of an sRGB decode of a byte, and they differ by at most one `half` ulp in each half (the site's largest difference, 0x0001000… | +| `pass-bytes-half-tanh-regimes` | Each word holds two `half` results of `tanh` over its regimes, which the device computes by its own `Tanh` (a `half` held as `float`, on every device) and round… | +| `pass-bytes-srgb-decode-all-bytes` | Each thread holds four `float` and two words of two `half` results of an sRGB decode of a byte. Metal decodes through its twelve-bit table, answering the step `… | +| `pass-bytes-srgb-encode-sweep` | Each word holds an sRGB encode of a `float` or a `half` colour packed to four bytes. Metal encodes through its twelve-bit table; the module encodes by the MSL t… | | `pixel-downscales-1000x1080` | The digest of a linear-filtered downscale's output, which differs wherever the site's `head` and `tail` elements do: the case samples through the device's own f… | | `pixel-downscales-1000x1080` | A linear-filtered downscale through the device's own sampler: the site's elements differ by at most one code of 1/255 (0.00392, to an `f32` ulp). `device-sampli… | | `pixel-downscales-1000x1080` | A linear-filtered downscale through the device's own sampler: the site's elements differ by at most one code of 1/255 (0.00392, to an `f32` ulp). `device-sampli… | diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 2c59ab2f0..b87544835 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -54,11 +54,12 @@ known. The rest of the differences are docs/API.md section 9's precision notes. | What it is | Why there is no switch | Note, code | |---|---|---| -| The maths library (`sin`, `exp`, `log`, `pow`, `atan2`...), fast divisions and Metal's fast reciprocal, a `half` fused multiply-add, and a `float` one without `OpFmaKHR` are the device's instructions on every device whose `float` functions are not Metal's own (every device but MoltenVK, whose functions are Metal's in a fast-math entry); Metal's precise division (an `fdiv` without `arcp`, or on `half`) is the device's `OpFDiv` on every device. | The device's arithmetic is the contract: no routine computes Metal's answer where the device has an instruction. | Vulkan's precision table (`Sin` 2^-11 absolute in [-π, π], `Exp` 3 + 2·\|x\| ulp, `Atan` 4096 ulp) against Metal's 4-6 ulp; division 2.5 ulp; `fma` one `half` ulp (a `float` one may round twice). `NativeTranscendentals` (`native-transcendentals`), `NativeDivision` (`native-division`), `NativeFma` (`native-fma`) | -| `dot`, `mix` and `fast::sqrt` are the device's `OpDot`, `FMix` and `Sqrt`, not Metal's fused chain, its two fused multiply-adds and `x · rsqrt(x)`, on every device but MoltenVK, which takes Metal's order; a `dot` of other than two to four lanes sums the `OpDot` of each chunk of up to four lanes. | The device's order is the contract. | `float` `dot` of n lanes within (3n − 1)·2^-24·Σ\|aᵢbᵢ\|, `mix` within 2^-21 of its two terms, `fast::sqrt` 4.5 ulp. `NativeDot` (`native-dot`), `NativeMix` (`native-mix`), `NativeTranscendentals` (`native-transcendentals`); a `dot` of other than two to four lanes within Vulkan's precision of its chunks' `OpDot` and sum, `DeviceArithmetic` (`device-arithmetic`) | +| The maths library (`sin`, `exp`, `log`, `pow`, `sinh`, `cosh`, `tanh`, `atan2`...) on `float` and `half`, fast divisions and Metal's fast reciprocal, a `half` fused multiply-add, and a `float` one without `OpFmaKHR` are the device's instructions on every device whose `float` functions are not Metal's own (every device but MoltenVK, whose functions are Metal's in a fast-math entry; a `half` function is the `float` instruction rounded on every device); Metal's precise division (an `fdiv` without `arcp`, or on `half`) is the device's `OpFDiv` on every device. `fabs`, `sign` and `fract` are `FAbs`, `FSign` and `Fract`, their special operands (a NaN, an infinity, a signed zero, an `f32` denormal) the instruction's; `round` is C99's from `Trunc` on every device (`round(-0.3)` is `-0`, Metal's `+0`). | The device's arithmetic is the contract: no routine computes Metal's answer where the device has an instruction. | Vulkan's precision table (`Sin` 2^-11 absolute in [-π, π], `Exp` 3 + 2·\|x\| ulp, `Log` 3 ulp or 2^-21 absolute in [0.5, 2], `Pow` from `Exp2(y · Log2 x)`, `FAbs`, `FSign` and `Fract` correct or correctly rounded, `Atan` 4096 ulp) against Metal's 4-6 ulp; division 2.5 ulp; `fma` one `half` ulp (a `float` one may round twice). `NativeTranscendentals` (`native-transcendentals`), `NativeDivision` (`native-division`), `NativeFma` (`native-fma`) | +| `dot`, `mix` and `fast::sqrt` are the device's `OpDot`, `FMix` and `Sqrt` on every device, not Metal's fused chain, its two fused multiply-adds and `x · rsqrt(x)`: a `float` one on MoltenVK reaches Metal's own `dot`, `mix` and `fast::sqrt`, a `half` one is the instruction on its `float` container, rounded once; a `dot` of other than two to four lanes sums the `OpDot` of each chunk of up to four lanes. | The device's order is the contract. | `float` `dot` of n lanes within (3n − 1)·2^-24·Σ\|aᵢbᵢ\|, `mix` within 2^-21 of its two terms, `fast::sqrt` 4.5 ulp. `NativeDot` (`native-dot`), `NativeMix` (`native-mix`), `NativeTranscendentals` (`native-transcendentals`); a `dot` of other than two to four lanes within Vulkan's precision of its chunks' `OpDot` and sum, `DeviceArithmetic` (`device-arithmetic`) | | Fast-math sums, differences and products group, and a multiply contracts into an addition, as the device's compiler groups and fuses them, on every device, MoltenVK included: each operation is emitted in the AIR's order, one carrying both `contract` and `reassoc` undecorated and any other `NoContraction`. Metal's compiler takes its own grouping (its rank order of a sum's leaves, its pairing of a product's lane-uniform factors) and its own fusion pairs. | The device's grouping is the contract: what the AIR's flags allow, the device's compiler chooses; nothing reproduces Metal's choice. | Unbounded relative to the result where a sum of mixed signs is grouped otherwise, or a multiply-add is fused on one side alone; each operation kept apart is exact as written. `FastMathRewrites` (`fast-math-rewrites`) | +| `air.pack` and `air.unpack` of a normalized format are the device's conversion: `GLSL.std.450`'s `Pack`/`Unpack` `Unorm4x8`, `Snorm4x8`, `Unorm2x16` and `Snorm2x16`, and for `rgb10a2` and `rgb565` their definition by the device's `NClamp`, multiply, `RoundEven` (a pack) and multiply by the reciprocal (an unpack); `unorm4x8_srgb`'s colour is the MSL transfer functions by the device's `Pow` around the 8-bit instruction. A `float` one of the four named formats on MoltenVK reaches Metal's own. | The device's conversion is the contract. | A packed code within one of Metal's, apart only where `clamp(c)·scale` lies within its rounding of a half-integer (`Round`'s tie is the device's); an unpacked value within 2.5 ulp of the correctly rounded quotient; a decoded sRGB colour within half a twelve-bit step (`1/8190`) of Metal's table step `k/4095`, beyond its `Pow`'s bound; a NaN channel's code the device's (Metal's: 0). `DevicePackConversion` (`device-pack-conversion`) | | Off MoltenVK a `float` multiply, and a fused multiply-add by `OpFmaKHR`, round before Metal's flush: Metal flushes a result whose exact value lies below `2^-126` before rounding it, so a result whose exact value lies within half a unit below `2^-126` answers `2^-126` of its sign where Metal answers the zero of its sign. | Every device measured off MoltenVK (RADV, ANV, NVIDIA, lavapipe) rounds first; its multiply is the contract. | Announced once per device as it is made: `float-tininess-after-rounding` | -| `f32` denormals in a `float` operation on a device not measured to read them as Metal does (`DriverDeviation::MetalFloatDenormals`: lavapipe, and every unmeasured device), in `floor` and `ceil` on every device, in the maths functions and the device's order of the rows above, and in a conversion to or from `double`. Metal reads them as zero and flushes a denormal result. | The device's reading is the contract: Vulkan lets each device keep or flush them, and Metal runs no `double`, so its reading of a conversion is not measured. | `DeviceDenormals` (`device-denormals`) | +| `f32` denormals in a `float` operation on a device not measured to read them as Metal does (`DriverDeviation::MetalFloatDenormals`: lavapipe, and every unmeasured device), in `floor`, `ceil` and `fneg` on every device, in the maths functions (`fabs`, `sign` and `fract` among them) and the device's order of the rows above, and in a conversion to or from `double`. Metal reads them as zero and flushes a denormal result. | The device's reading is the contract: Vulkan lets each device keep or flush them, and Metal runs no `double`, so its reading of a conversion is not measured. | `DeviceDenormals` (`device-denormals`) | | Samples, gathers, depth comparisons and level queries are the device's own sampler's on every device whose sampler is not Metal's (every device but MoltenVK): its filter, footprint, level, anisotropy, sRGB decode and comparison, its level clamp (the descriptor's as given, which Metal holds on a `1/64` grid) and its reading of a subnormal coordinate (which Metal reads as the zero of its sign before addressing). A sample's or gather's residency on a device with `shaderResourceResidency` is the device's `OpImageSparse*` word and non-resident value (`SparseResidency`); Metal's footprint rule answers it only where the device has no residency and the slot's tile map does. A two-plane YCbCr texture's linear sample is the device's filter of its texels (the device's own Y′CbCr conversion's where it converts the format, next row; Metal's reads exactly elsewhere); where the device's memory is the host's, a sample that reads the planes in place is Metal's filter exactly. An 8-bit sRGB format the device cannot sample (`R8_SRGB` on lavapipe, `R8G8_SRGB` on lavapipe, ANV and NVIDIA) is held as its UNORM twin, the device lacking its decode: a read, a nearest sample, a fetch, a gather and a bicubic tap decode the twin's codes through Metal's table, exactly, and a filtered sample is the device's filter of the codes, decoded through the table. | The device's sampler is the contract. | Linear filter within one code (1/255) on the measured devices, sRGB within 1.83, a two-plane YCbCr texture's within 1.183; levels, anisotropy, cubes, 3D, gathers and comparisons unmeasured. A twin's filtered sample: exact for one texel and for a blend of two adjacent codes, up to 0.286 off for a blend of codes 0 and 255 (`SrgbTexelDecode`). `DeviceSampling` (`device-sampling`) | | A two-plane YCbCr texture's texels are the device's own sampler Y′CbCr conversion of its planes where the device converts their format (`ycbcr_device.rs`): unpacked 8- or 10-bit codes of a 4:2:0, 4:2:2 or 4:4:4 layout over plane 0 that form one image (no chroma codes 0, no rows past the buffer; a 4:4:4 layout read as codes aside, whose identity conversion converts nothing), on a device that enables `samplerYcbcrConversion` (a 4:4:4 layout also needs Vulkan 1.3 or `VK_EXT_ycbcr_2plane_444_formats`), reports the multi-planar format's conversion and, for a 4:2:0 or 4:2:2 layout, Metal's reconstruction (midpoint chroma through a linear chroma filter), and has no defect in the format; the planes are copied into an image of it and sampled once per texel into the texture's image (`bind::ycbcr_sample_module`), through the refresh's indirect arguments. The conversion takes the surface's matrix and range (the identity model for the code-reading formats), and Metal's reconstruction of a subsampled layout; a device's cosited or nearest reconstruction would move what the codes mean to Metal (cosited, up to 1340/2048 of random planes on lavapipe), a capability it lacks, so such a layout converts through Metal's arithmetic. A render pass's load stays Metal's arithmetic, which our store inverts, so a loaded texel no draw changes keeps its codes, as `MTLLoadActionLoad` keeps the attachment's contents. lavapipe (Mesa 26.0.8) converts the 8-bit 4:4:4 layout (its 4:2:0 and 4:2:2 ones are cosited only, and it reads 10-bit codes as 16-bit words, `RuntimeDriverDefect::TenBitCodesReadAsWords`); MoltenVK 1.4.2 converts none (its 4:2:0 and 4:2:2 reconstruction is misplaced, `RuntimeDriverDefect::TwoPlaneChromaMisplaced`, and it reports no 4:4:4 two-plane format). Elsewhere, and for packed codes, chroma codes 0 and plane 1, Metal's fixed-point conversion stays as capability (`WorkCounts::ycbcr_device_conversions`). | The device's conversion is the contract: Vulkan states the reconstruction's weights and the model's matrices, the precision of each step at least the format's, and the clamp of the result into `[0, 1]` the implementation's. | Each channel within 0.04/2048 of Vulkan's conversion past the `half` its image stores on lavapipe's 8-bit 4:4:4 layout; of Metal's read within 6/2048 where the result lies in `[0, 1]`, and unclamped outside it (random planes, every texel, `tests/ycbcr_device.rs`). `YCbCrFilterNotExact` (`ycbcr-filter-not-exact`) | | A texel's `float` value is the device's conversion of its codes on every device whose texture unit is not Metal's (every device but MoltenVK), and a `half` result the device's `float` texel rounded to nearest even on every device: on MoltenVK the `float` texel is Metal's, whose `half` Metal rounds otherwise for a 32-bit float texel's sample (toward zero, saturating at `±65504`) and the 16-bit normalized grids (three steps round twice through `float`); a two-plane YCbCr field on the grid `8192` keeps Metal's ties away from zero in one texel's read, sample and gather. An sRGB texel (the 8-bit sRGB formats, and the sRGB forms of BC1 to BC3, BC7, PVRTC, ETC2, EAC and ASTC, a decoded twin's through its `R8G8B8A8_SRGB` view) is the device's sRGB decode through the texture's sRGB view, in every read, sample, gather, bicubic tap and input-attachment read, where Metal decodes each code through its twelve-bit table. | The device's conversion is the contract. | 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, but a 32-bit float texel's sample past `±65504` the infinity of its sign where Metal saturates (MoltenVK included); NaN bits the device's. An sRGB decode: lavapipe's within 5.25 steps of Metal's table (0.00128) at every code, MoltenVK's Metal's at every code (`runtime_lane::srgb_decode`); Vulkan sets no precision for it, and other devices are not measured. `DeviceTexelConversion` (`device-texel-conversion`), `HalfTexelConversion` (`half-texel-conversion`, also recorded for heap textures and unmeasured formats), `SrgbTexelDecode` (`srgb-texel-decode`, under the bound format) |