From 9bd91540f4f6b06de2da43ebc9f79dafb646143b Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 29 Oct 2026 05:32:39 +0200 Subject: [PATCH] Take the device's answers for fast atan2, half fmod and precise pow's NaN; delete exact sRGB leftovers - fast::atan2 without every fast-math flag divides by the device's own reciprocal of x; past 2^126 the denormal it makes is the device's (DeviceDenormals through MetalFloatDenormals; NativeDivision as before). FastAtan2 { reciprocal_flushed } -> FastAtan2 { by_reciprocal }. - A half fmod answers its float remainder rounded; the Metal zero-sign select is gone and the call records NativeTranscendentals through FloatFn::half_zero_of_float. - Precise pow's NaN is classed BaseToExponentOne, so it records NativeNanEncoding like fast pow and atan2 (the measured() exclusion was left over from the removed pow(x,1) bit fix). Fast sin/cos keep DeviceNanEncoding on purpose: Metal answers +0 there, no NaN to stand for. - Delete the exact sRGB pack/unpack's dead code: ArithPlan::srgb, Declared::srgb, SRGB_PACK/SRGB_UNPACK, srgb::TABLE_WORDS, math::unpack's normalized and sRGB branches (UnpackRounding, unpack_rounding, mul_exact, unpackable), word::srgb_code. WordAttachment::output_word returns Option (None for Srgb8). With the mipmap filter on the transfer (c9dd35e8a4), srgb's declare/ word/step and SRGB_ENCODE_FIRST lost their last users and go too, with their texel_round test; SRGB_DECODE_STEPS stays for the ASTC and PVRTC decoders. - FAST-PATHS: row 58 names half fmod; known gaps lose the atan2 and half-fmod lines. API.md: native-transcendentals, native-nan-encoding. - SEMANTICS_VERSION + 1. Verified: fmt, clippy (all features, m2v_gpu), rustdoc; metal2vulkan arith/word/fast_paths 241/241, engine call notes + public fixture expectations 20/20, api_signatures+api_surface 15/15, runtime 29/29, validation c3 72/72; the atan2 tests FAIL on the old flushed reciprocal. No conformance case reaches atan2, fmod or pow. Golden hashes: 21 rows x 19 profiles move (fast_atan2.f32 and fmod.f16 fixtures), re-blessed on development. One work packet, landed as 2 commits on archive/development-linear-2026-10-29: abb2b3db6e, then f76cdba457 (the re-pin). --- .../metal2vulkan-runtime/src/clear_value.rs | 2 +- .../runtime-sources.sha256 | 2 +- .../src/c3/bound/tests.rs | 29 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- .../metal2vulkan/src/lower/arith/denormal.rs | 5 +- .../src/lower/arith/extended_range/blend.rs | 3 +- crates/metal2vulkan/src/lower/arith/math.rs | 341 +++--------------- crates/metal2vulkan/src/lower/arith/mod.rs | 38 +- crates/metal2vulkan/src/lower/arith/nan.rs | 14 +- crates/metal2vulkan/src/lower/arith/pack.rs | 6 +- crates/metal2vulkan/src/lower/arith/srgb.rs | 103 +----- crates/metal2vulkan/src/lower/arith/tests.rs | 98 ++++- .../src/lower/arith/tests/atan2.rs | 109 ++++-- .../src/lower/arith/tests/color_write.rs | 2 +- .../src/lower/arith/tests/libm.rs | 8 +- .../src/lower/arith/tests/narrow.rs | 272 +------------- .../src/lower/arith/tests/texel_round.rs | 32 -- .../src/lower/arith/texel_round.rs | 2 +- crates/metal2vulkan/src/metal/format/word.rs | 75 ++-- crates/metal2vulkan/src/pipeline/artifact.rs | 15 +- crates/metal2vulkan/src/tests/engine_arith.rs | 26 +- .../src/tests/engine_float_call_notes.rs | 12 +- .../metal2vulkan/src/tests/engine_texture.rs | 7 +- crates/metal2vulkan/tests/api_signatures.tsv | 2 +- docs/API.md | 15 +- docs/FAST-PATHS.md | 12 +- 26 files changed, 355 insertions(+), 877 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/clear_value.rs b/crates/metal2vulkan-runtime/src/clear_value.rs index 26ec47d3c..c89f82092 100644 --- a/crates/metal2vulkan-runtime/src/clear_value.rs +++ b/crates/metal2vulkan-runtime/src/clear_value.rs @@ -379,7 +379,7 @@ pub(super) fn word( word: WordAttachment, ) -> Option { if word == WordAttachment::Rgb9e5 { - let uint32 = [word.output_word(color.map(|c| c as f32)), 0, 0, 0]; + let uint32 = [word.output_word(color.map(|c| c as f32))?, 0, 0, 0]; return Some(vk::ClearColorValue { uint32 }); } let channels = channels(pf)?; diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index fa634450f..043b10bb4 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -db756e5e9f535a5db0789477407ec8cdda943d3008cc6747b2b4685d7b27a332 +63bcbd724e3bd5ed5c946c4b46a299fd8312abc3f3a1cd9923db71fe53229179 diff --git a/crates/metal2vulkan-validation/src/c3/bound/tests.rs b/crates/metal2vulkan-validation/src/c3/bound/tests.rs index 4b7ba0f71..090963226 100644 --- a/crates/metal2vulkan-validation/src/c3/bound/tests.rs +++ b/crates/metal2vulkan-validation/src/c3/bound/tests.rs @@ -557,14 +557,15 @@ const EVERY_ARITHMETIC_NOTE: [PrecisionNote; 4] = [ /// Metal answers the canonical NaN reproducibly, so where both answers are NaNs of an operation /// whose lowering leaves the encoding to the device, and the row records `DeviceNanEncoding`, the /// value stays open with the exact path. On lavapipe, which is not measured to answer Metal's NaN, -/// the product's `float` lowerings that leave a NaN's encoding to the device record the note: -/// precise `pow`, and fast `sin` and `cos` (the device's instructions, whose NaN over an infinity -/// is the device's). Every other operation this check reads answers a NaN whose encoding the -/// product states (`NativeNanEncoding`) or none, so a differing NaN of `div` or `mul` is not the -/// note's even where the row records it (another operation of the module may), and the verdict is -/// Apple's bound's; Metal's precise and fast divisions answer `0x7fc00000` themselves. A differing -/// NaN of fast `sin` is the note's; of precise `sin`, which does not record it, it is not. Two -/// different answers, not both NaNs, are not the encoding's. +/// the product's `float` lowerings that leave to the device a NaN Metal answers no NaN of record +/// the note: fast `sin` and `cos` (the device's instructions, whose NaN over an infinity is the +/// device's where Metal answers `+0`). Every other operation this check reads answers a NaN whose +/// encoding the product states (`NativeNanEncoding`: precise `pow`, whose NaNs Metal answers as +/// measured) or none, so a differing NaN of `div`, `mul` or precise `pow` is not the note's even +/// where the row records it (another operation of the module may), and the verdict is Apple's +/// bound's; Metal's precise and fast divisions answer `0x7fc00000` themselves. A differing NaN of +/// fast `sin` is the note's; of precise `sin`, which does not record it, it is not. Two different +/// answers, not both NaNs, are not the encoding's. #[test] fn a_nan_encoding_the_product_answers_is_not_a_near_equivalent() { let (metal, device) = (0x7fc0_0000, 0xffc0_0000); @@ -573,7 +574,7 @@ fn a_nan_encoding_the_product_answers_is_not_a_near_equivalent() { let nan = [PrecisionNote::DeviceNanEncoding]; for math in [Math::Precise, Math::Fast] { let device_nans: &[msl::Prim] = match math { - Math::Precise => &[msl::Prim::Pow], + Math::Precise => &[], Math::Fast => &[msl::Prim::Sin, msl::Prim::Cos], }; for prim in msl::Prim::ALL { @@ -613,7 +614,13 @@ fn a_nan_encoding_the_product_answers_is_not_a_near_equivalent() { // operation does not make this value the note's. let sin = verdict_of("sin(a)", Math::Precise, &[infinity], (metal, device), &nan); assert_ne!(sin.label(), "near_equivalent", "{sin:?}"); - // Precise `pow` of a negative base and a non-integer exponent: a NaN the device encodes. + // Precise `pow` of a negative base and a non-integer exponent: a NaN whose encoding the + // product states (`NativeNanEncoding`), not the note's. + let (_, notes) = lowering_notes(msl::Prim::Pow, F32, Math::Precise, lavapipe()).unwrap(); + assert!( + notes.contains(&PrecisionNote::NativeNanEncoding), + "{notes:?}" + ); let pow = verdict_of( "pow(a, b)", Math::Precise, @@ -621,7 +628,7 @@ fn a_nan_encoding_the_product_answers_is_not_a_near_equivalent() { (metal, device), &nan, ); - assert_eq!(pow.label(), "near_equivalent", "{pow:?}"); + assert_ne!(pow.label(), "near_equivalent", "{pow:?}"); let one = 1.0f32.to_bits(); let finite = verdict_of("div(a, b)", Math::Fast, &[one, one], (one, one + 1), &nan); assert_ne!(finite.label(), "near_equivalent", "{finite:?}"); diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 1abeb2a0c..6e8e0b658 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 = 1923; +pub const SEMANTICS_VERSION: u32 = 1924; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/arith/denormal.rs b/crates/metal2vulkan/src/lower/arith/denormal.rs index e6496e010..e82a6071c 100644 --- a/crates/metal2vulkan/src/lower/arith/denormal.rs +++ b/crates/metal2vulkan/src/lower/arith/denormal.rs @@ -47,8 +47,9 @@ pub enum Covered { /// /// `fast::atan2(y, x)` reads a denormal `y` or `x` as the zero of its sign and answers no denormal /// (an Apple M3 Max under macOS 27.0.1: every pair of 28 patterns, in entries with and without fast -/// math); its quotient is the device's division, whose operands are those two, and a denormal -/// quotient reaches the fast `atan`, which reads it as a zero. +/// math); its quotient is the device's division, whose operands are those two, or, in a call +/// without every fast-math flag, `y` times the device's reciprocal of `x`, a denormal Metal flushes +/// past `2^126`; a denormal quotient reaches the fast `atan`, which reads it as a zero. /// /// `ldexp` on `float` (`math::ldexp_bits`) reads a denormal operand and rounds a result below /// `2^-126` by the device's `float` multiply, which the deviation covers: a denormal operand times diff --git a/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs b/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs index 618f1a486..c4fbac079 100644 --- a/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs +++ b/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs @@ -2415,8 +2415,7 @@ pub fn blend_unorm8( /// Metal's blend `b` ([`Blend::srgb8`]) of a four-lane output `s` (a `vec4` of `f32`: a `half4` /// output's `half`s, or a `float4` one) over `decoded`, the 8-bit sRGB attachment's texel as a /// fetch reads it (a `vec4` of `f32`: each color byte's twelve-bit step over 4095 and the alpha -/// byte over 255, correctly rounded, `math::unpack` of `unorm4x8_srgb`; a channel the format lacks -/// 0, alpha 1), in `arith`: a `vec4` of `f32` holding each blended lane, a `half` +/// byte over 255, correctly rounded; a channel the format lacks 0, alpha 1), in `arith`: a `vec4` of `f32` holding each blended lane, a `half` /// (`BlendArith::Half`) or a `float` (`BlendArith::Float`), which the caller stores by Metal's /// sRGB encode. The output, and `s1`, the second source (the function's second output, where `b` /// reads it, [`Blend::reads_second`]), are clamped to `[0, 1]` first, a NaN to 0, and the diff --git a/crates/metal2vulkan/src/lower/arith/math.rs b/crates/metal2vulkan/src/lower/arith/math.rs index 745558917..043d360a6 100644 --- a/crates/metal2vulkan/src/lower/arith/math.rs +++ b/crates/metal2vulkan/src/lower/arith/math.rs @@ -24,16 +24,15 @@ //! selection, and so is every function whose Vulkan precision is looser than Metal's. use crate::air::intrinsics::PackFormat; -use crate::lower::arith::exact_division::{div_exact_lanes, per_lane}; +use crate::lower::arith::exact_division::per_lane; use crate::lower::arith::legal::{FloatFmt, Form, Held}; use crate::lower::arith::libm::{self, Lib}; use crate::lower::arith::nan::{self, NanTest}; use crate::lower::arith::narrow; use crate::lower::arith::ops::{fsplat, mask, ones, sext, splat, ty, CastKind}; -use crate::lower::arith::srgb; use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::{BResult, BuildError, TypeRule}; -use crate::spirv::ids::{GlobalId, Value}; +use crate::spirv::ids::Value; use crate::spirv::ir::{BinOp, Contraction, ConvOp, GlslOp, UnOp}; /// Whether an integer function reads its operands as signed. @@ -917,10 +916,10 @@ pub enum FloatFn { /// 8.2's formula (`fast_atan2`): `0 / 0` and `inf / inf` are NaN, where `atan2` answers C99's /// values, and the turn follows `y`'s comparison with zero, so `fast::atan2(-0, -1)` is `+π`. FastAtan2 { - /// The quotient is `y` times `x`'s reciprocal flushed to zero beyond `2^126`, as Metal - /// answers a call that does not carry every fast-math flag; a call that does divides - /// over the whole range. - reciprocal_flushed: bool, + /// The quotient is `y` times the device's reciprocal of `x`, as Metal composes a call that + /// does not carry every fast-math flag (past `2^126` that reciprocal is an `f32` denormal, + /// the device's to keep or flush); a call that does divides over the whole range. + by_reciprocal: bool, }, } @@ -1038,7 +1037,8 @@ impl FloatFn { /// (the device's comparisons around the device's instruction), Metal's own where the device's /// functions are Metal's, and elsewhere recording the device's denormals with their precision /// (`PrecisionNote::NativeTranscendentals`). `fast::atan2` does not: its quotient is the - /// device's division, whose operands `denormal::coverage` reads. + /// device's division or its product with the device's reciprocal, whose operands and + /// reciprocal `denormal::coverage` reads. pub fn metal_denormals(self) -> bool { use FloatFn as F; matches!( @@ -1126,6 +1126,16 @@ impl FloatFn { self == FloatFn::Round } + /// Whether a `half` call on form `f` answers a zero remainder of a nonzero dividend with its + /// `float` function's sign where Metal's `half` function answers another, on every device: + /// `fmod`, whose `float` remainder (the exact remainder's routine, or the device's where its + /// functions are Metal's) keeps the dividend's sign, as C's does, where Metal's `half` `fmod` + /// answers `+0` (`fmod(-2, 0.5)`; `nan_fmod_zero`, `nan_fmod_zero_fast`, with and without + /// fast-math flags) (`PrecisionNote::NativeTranscendentals`). + pub fn half_zero_of_float(self, f: Form) -> bool { + self == FloatFn::Fmod && f.float_fmt() == Some(FloatFmt::Half) + } + /// Whether the lowering on lanes of format `fmt` records no NaN note of its own: `saturate`, /// which answers a number for one, `copysign`, which moves bits, `sign`, whose NaN answer is /// its instruction's @@ -1206,8 +1216,6 @@ impl FloatFn { // And the infinite product's tests and select, on the same classification // (`fast_powr_special`). FloatFn::FastPowr => 208 + INFINITE_PRODUCT_WORDS, - // The device's remainder and, on `half`, the zero's tests and selects. - FloatFn::Fmod if f.float_fmt() == Some(FloatFmt::Half) => 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 @@ -1266,8 +1274,8 @@ 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. A `half` function is its `float` function rounded, its zeros' signs -/// and NaNs' signs that function's, but `fmod`, which answers Metal's zero remainder around the -/// exact remainder's routine (`half_fmod_zero`). +/// and NaNs' signs that function's: a `half` `fmod`'s zero remainder the dividend's sign, as the +/// `float` remainder keeps it ([`FloatFn::half_zero_of_float`]). pub fn float_fn( fb: &mut FunctionBuilder<'_>, op: FloatFn, @@ -1285,10 +1293,6 @@ pub fn float_fn( // Rounded per step below. 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)?; - half_fmod_zero(fb, f, arg(args, 0)?, r)? - } _ => narrow::round(fb, f, r)?, }; Ok(r) @@ -1510,14 +1514,14 @@ fn float_fn_core( let generic = glsl(fb, GlslOp::Atan2, &[a, x])?; atan2_special(fb, f, a, x, generic) } - F::FastAtan2 { reciprocal_flushed } => { + F::FastAtan2 { by_reciprocal } => { // Metal's fast `atan` of its fast quotient `y · rcp(x)`: the device's `Atan` and // division. let atan = |fb: &mut FunctionBuilder<'_>, q: Value| glsl(fb, GlslOp::Atan, &[q]); let divide = |fb: &mut FunctionBuilder<'_>, n: Value, d: Value| -> BResult { bin(fb, BinOp::FDiv, n, d) }; - fast_atan2(fb, f, a, arg(args, 1)?, reciprocal_flushed, &atan, ÷) + fast_atan2(fb, f, a, arg(args, 1)?, by_reciprocal, &atan, ÷) } } } @@ -1562,31 +1566,6 @@ fn has_bits(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, bits: u64) -> BResu bin(fb, BinOp::IEqual, b, k) } -/// `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 -/// (`nan_fmod_zero`, `nan_fmod_zero_fast`). A `float` remainder keeps the dividend's sign, as C's -/// `fmod` does, and so does Metal's: it and every other format keep `r`. Tested on the bits, so no -/// signed-zero mode folds it. -fn half_fmod_zero(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, r: Value) -> BResult { - if f.float_fmt() != Some(FloatFmt::Half) { - return Ok(r); - } - let u = u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let magnitude = splat(fb, u, 0x7FFF_FFFF)?; - let zero = splat(fb, u, 0)?; - let rb = fb.convert(ConvOp::Bitcast, r, ut)?; - let rm = bin(fb, BinOp::BitwiseAnd, rb, magnitude)?; - let r_zero = bin(fb, BinOp::IEqual, rm, zero)?; - let xb = fb.convert(ConvOp::Bitcast, x, ut)?; - let xm = bin(fb, BinOp::BitwiseAnd, xb, magnitude)?; - let x_zero = bin(fb, BinOp::IEqual, xm, zero)?; - let z = fb.select(x_zero, xb, zero)?; - let b = fb.select(r_zero, z, rb)?; - fb.convert(ConvOp::Bitcast, b, ft) -} - /// 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 and shared by every rule that /// reads it: `y`'s bits and each operand's magnitude's, whether it is a zero by the device's comparison @@ -2222,29 +2201,31 @@ pub(super) type AtanOf<'a> = &'a dyn Fn(&mut FunctionBuilder<'_>, Value) -> BRes /// Zeros are the device's comparisons, so an `f32` denormal operand is a zero where the device /// reads it so (`denormal::coverage`), and a denormal quotient is the device's `Atan` of it. /// -/// Beyond `2^126` the quotient follows the call's fast-math flags. A call that carries every -/// flag (case c11eb8cb, compiled with fast math) divides over the whole range -/// (`fast::atan2(FLT_MAX, FLT_MAX)` is `atan(1)`): the division is scaled by `1/4` when `|x|` is -/// at least `2^126`, an exact scaling that keeps the divisor in the range where Metal's fast -/// division and Vulkan's `OpFDiv` bound their error. Any other call (`reciprocal_flushed`; case -/// 6802ab13, compiled without fast math, measured with no flag) multiplies `y` by `x`'s -/// reciprocal flushed to zero beyond `2^126` (the reciprocal is an `f32` denormal there), so the -/// quotient is the signed zero, or NaN for an infinite `y` (`fast::atan2(FLT_MAX, FLT_MAX)` is -/// `+0`, `fast::atan2(inf, FLT_MAX)` is NaN). A call with only some of the flags is not -/// measured; it takes the second answer, which differs only where the divisor leaves the range +/// The quotient follows the call's fast-math flags. A call that carries every flag (case +/// c11eb8cb, compiled with fast math) divides over the whole range (`fast::atan2(FLT_MAX, +/// FLT_MAX)` is `atan(1)`): the division is scaled by `1/4` when `|x|` is at least `2^126`, an +/// exact scaling that keeps the divisor in the range where Metal's fast division and Vulkan's +/// `OpFDiv` bound their error. Any other call (`by_reciprocal`; case 6802ab13, compiled without +/// fast math, measured with no flag) multiplies `y` by the device's reciprocal of `x`, as Metal +/// composes it. Beyond `2^126` that reciprocal is an `f32` denormal, the device's to keep or +/// flush (`denormal::coverage`): Metal flushes it, so its quotient is the signed zero, or NaN for +/// an infinite `y` (`fast::atan2(FLT_MAX, FLT_MAX)` is `+0`, `fast::atan2(inf, FLT_MAX)` is NaN), +/// and so is the device's where it flushes; a device that keeps it answers `atan` of the product +/// (`±π/2` for an infinite `y`). A quotient the device's product makes NaN (an infinite `y` times +/// a flushed reciprocal) answers NaN, as `inf / inf` does. A call with only some of the flags is +/// not measured; it takes the second answer, which differs only where the divisor leaves the range /// MSL bounds the fast division in. /// /// Every finite normal pair of our probe (16.7 million, the M4) is `atan(q)` of Metal's fast /// `atan` and its fast quotient `q = y · rcp(x)`, and `RN(atan(q) ± RN(π))` toward a negative -/// `x`: `divide` gives `q` (Metal's reciprocal's routine, or the device's quotient where it is -/// Metal's), `atan` the arc tangent (Metal's fast `atan`'s routine, or the device's where it is -/// Metal's). Every special value above is exact. +/// `x`: `divide` gives the quotient or the reciprocal (the device's division), `atan` the arc +/// tangent (the device's `Atan`). Every special value above is exact. pub(super) fn fast_atan2( fb: &mut FunctionBuilder<'_>, f: Form, y: Value, x: Value, - reciprocal_flushed: bool, + by_reciprocal: bool, atan: AtanOf<'_>, divide: DivideOf<'_>, ) -> BResult { @@ -2255,15 +2236,18 @@ pub(super) fn fast_atan2( let nan = c(fb, f64::NAN)?; let (yz, xz) = (is_zero(fb, f, y)?, is_zero(fb, f, x)?); let (yi, xi) = (fb.unary(UnOp::IsInf, y)?, fb.unary(UnOp::IsInf, x)?); - let ax = glsl(fb, GlslOp::FAbs, &[x])?; - let limit = c(fb, 2f64.powi(126))?; - // The quotient, and where the reciprocal is flushed (`None` when it is not). - let (q, beyond) = if reciprocal_flushed { - let q = divide(fb, y, x)?; - (q, Some(bin(fb, BinOp::FOrdGreaterThan, ax, limit)?)) + let one = c(fb, 1.0)?; + // The quotient, and where the device's product makes it NaN (`None` for a division). + let (q, q_nan) = if by_reciprocal { + // `y` times the device's reciprocal of `x`, kept or flushed past 2^126 as the device does. + let r = divide(fb, one, x)?; + let q = bin(fb, BinOp::FMul, y, r)?; + (q, Some(fb.unary(UnOp::IsNan, q)?)) } else { // Both operands scaled by 1/4 when the divisor is at least 2^126. - let (one, quarter) = (c(fb, 1.0)?, c(fb, 0.25)?); + let ax = glsl(fb, GlslOp::FAbs, &[x])?; + let limit = c(fb, 2f64.powi(126))?; + let quarter = c(fb, 0.25)?; let big = bin(fb, BinOp::FOrdGreaterThanEqual, ax, limit)?; let s = fb.select(big, quarter, one)?; let ys = bin(fb, BinOp::FMul, y, s)?; @@ -2283,10 +2267,6 @@ pub(super) fn fast_atan2( let signed_half_pi = copysign(fb, f, half_pi, signed_zero)?; // A zero quotient: a zero y or an infinite x. let qz = bin(fb, BinOp::LogicalOr, yz, xi)?; - let qz = match beyond { - Some(b) => bin(fb, BinOp::LogicalOr, qz, b)?, - None => qz, - }; // An infinite quotient: a zero x, an infinite y, or a quotient that overflows. let q_inf = fb.unary(UnOp::IsInf, q)?; let qi = bin(fb, BinOp::LogicalOr, xz, yi)?; @@ -2300,14 +2280,14 @@ pub(super) fn fast_atan2( let turn = fb.select(ynonneg, pi, minus_pi)?; let turned = bin(fb, BinOp::FAdd, a, turn)?; let r = fb.select(xneg, turned, a)?; - // 0 / 0 and inf / inf (or an infinite y times a flushed reciprocal); then NaN operands. + // 0 / 0 and inf / inf (and a quotient the device's product makes NaN); then NaN operands. let zeros = bin(fb, BinOp::LogicalAnd, yz, xz)?; - let infinite_x = match beyond { - Some(b) => bin(fb, BinOp::LogicalOr, xi, b)?, - None => xi, - }; - let infs = bin(fb, BinOp::LogicalAnd, yi, infinite_x)?; + let infs = bin(fb, BinOp::LogicalAnd, yi, xi)?; let undefined = bin(fb, BinOp::LogicalOr, zeros, infs)?; + let undefined = match q_nan { + Some(n) => bin(fb, BinOp::LogicalOr, undefined, n)?, + None => undefined, + }; let r = fb.select(undefined, nan, r)?; let ynan = fb.unary(UnOp::IsNan, y)?; let xnan = fb.unary(UnOp::IsNan, x)?; @@ -2528,27 +2508,6 @@ pub fn pack_layout(format: PackFormat) -> Option<(&'static [u32], bool)> { }) } -/// How a normalized `air.unpack` format converts a channel code `c` to a float. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum UnpackRounding { - /// `c / d` correctly rounded ([`div_exact`]; snorm: of the magnitude clamped to `d`). - /// - /// [`div_exact`]: crate::lower::arith::exact_division::div_exact - Quotient, - /// `max(c * fl(1/d), -1)`, the product with the `f32` reciprocal rounded to nearest even - /// ([`mul_exact`]): Metal's `snorm` `rgb10a2` on every code of every field, where the quotient - /// differs on 267,279 of 1,049,600 measured words by one ULP. - ReciprocalProduct, -} - -/// The conversion of normalized unpack format `format`'s channels ([`UnpackRounding`]). -pub fn unpack_rounding(format: PackFormat) -> UnpackRounding { - match format { - PackFormat::SnormRgb10a2 => UnpackRounding::ReciprocalProduct, - _ => UnpackRounding::Quotient, - } -} - /// The float lanes of a packed float format this family unpacks (`rg11b10f`, `rgb9e5`: 3), or /// `None` for a normalized one. Packing to them is not lowered (Metal's rounding, overflow, and NaN /// rules for these encodings are not established). @@ -2568,15 +2527,6 @@ pub fn packed_bits(format: PackFormat) -> u8 { } } -/// The error of an `air.pack`/`air.unpack` whose format the emission cannot take (a packed float -/// format to pack to, or the sRGB format without the module's table): selection rules both out. -fn unpackable() -> crate::spirv::error::BuildError { - crate::spirv::error::BuildError::Operand { - op: crate::spv::Op::ExtInst, - rule: crate::spirv::error::OperandRule::Arity, - } -} - /// [`round_exact_product_lanes`] with one scale `m` for every lane. #[cfg(test)] pub fn round_exact_product( @@ -2674,109 +2624,6 @@ pub fn round_exact_product_lanes( fb.select(neg, nr, r) } -/// `air.unpack.`: the packed integer `w` (a `u32`; a `ushort` for `rgb565`) to float -/// lanes of form `f`. Each channel of a normalized format is converted as Metal converts a -/// normalized integer to a float: `c / (2^N - 1)` (snorm: `max(c / (2^(N-1) - 1), -1)`), the -/// quotient correctly rounded ([`div_exact`]), except the `snorm` `rgb10a2`, which multiplies by -/// the `f32` reciprocal ([`unpack_rounding`]); the sRGB format decodes the color channels through -/// Metal's twelve-bit table (`k / 4095` of the step [`srgb::step`]), which `srgb` (the module's -/// table) holds. A narrow form rounds each lane (so rounds twice, as Metal's `half` answers do). -/// The packed float formats decode exactly (`unpack_float`). -/// -/// Every channel runs one lane of one vector sequence, its field and divisor per-lane constants: -/// the instructions are lane-wise, so each lane computes exactly what it computed alone. Only the -/// sRGB table reads are per channel. -/// -/// [`div_exact`]: crate::lower::arith::exact_division::div_exact -pub fn unpack( - fb: &mut FunctionBuilder<'_>, - format: PackFormat, - f: Form, - w: Value, - srgb: Option, -) -> BResult { - if float_unpack_lanes(format).is_some() { - return unpack_float(fb, format, f, w); - } - let Some((widths, snorm)) = pack_layout(format) else { - return Err(unpackable()); - }; - if usize::from(f.lanes) != widths.len() { - return Err(unpackable()); - } - let s = f.with(Held::Float(FloatFmt::F32)); - let u = narrow::u32_form(s); - let ut = ty(fb, u)?; - // Lane `i` holds field `i`: the word shifted down to the field and masked to its width. - let mut at = Vec::with_capacity(widths.len()); - let mut next = 0u64; - for n in widths { - at.push(next); - next += u64::from(*n); - } - let spread = fb.composite_construct(ut, &vec![w; widths.len()])?; - let sh = per_lane(fb, u, &at)?; - let v = bin(fb, 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 = bin(fb, BinOp::BitwiseAnd, v, m)?; - let q = if format == PackFormat::Unorm4x8Srgb { - // The color channels' steps over 4095, the alpha channel's byte over 255. - let table = srgb.ok_or_else(unpackable)?; - let mut k = Vec::with_capacity(widths.len()); - for i in 0..widths.len() { - let b = fb.composite_extract(v, &[i as u32])?; - k.push(if i < 3 { srgb::step(fb, table, b)? } else { b }); - } - let k = fb.composite_construct(ut, &k)?; - let d: Vec = (0..widths.len()) - .map(|i| if i < 3 { 4095 } else { 255 }) - .collect(); - div_exact_lanes(fb, u, k, &d)? - } else if snorm { - let d: Vec = widths.iter().map(|n| (1u32 << (n - 1)) - 1).collect(); - let up: Vec = widths.iter().map(|n| u64::from(32 - n)).collect(); - let up = per_lane(fb, u, &up)?; - let v = bin(fb, BinOp::ShiftLeftLogical, v, up)?; - let v = bin(fb, BinOp::ShiftRightArithmetic, v, up)?; - let z = splat(fb, u, 0)?; - let neg = bin(fb, BinOp::SLessThan, v, z)?; - let minus = bin(fb, BinOp::ISub, z, v)?; - let mag = fb.select(neg, minus, v)?; - match unpack_rounding(format) { - UnpackRounding::Quotient => { - // The magnitude, clamped to the scale (the most negative code is -1 exactly). - let dk: Vec = d.iter().map(|d| u64::from(*d)).collect(); - let dk = per_lane(fb, u, &dk)?; - let mag = glsl(fb, GlslOp::UMin, &[mag, dk])?; - let q = div_exact_lanes(fb, u, mag, &d)?; - let nq = fb.unary(UnOp::FNegate, q)?; - fb.select(neg, nq, q)? - } - UnpackRounding::ReciprocalProduct => { - // `max(c * fl(1/d), -1)`: the magnitude's product with its lane's reciprocal, - // the code's sign, and the bound, which only the most negative code reaches - // (`-512 * fl(1/511)` is below -1). Comparing with -1 is exact on every device. - let r: Vec = d.iter().map(|d| (1.0f32 / *d as f32).to_bits()).collect(); - let p = mul_exact(fb, u, mag, &r)?; - let pb = fb.convert(ConvOp::Bitcast, p, ut)?; - let sign = splat(fb, u, 0x8000_0000)?; - let nb = bin(fb, BinOp::BitwiseOr, pb, sign)?; - let b = fb.select(neg, nb, pb)?; - let st = ty(fb, s)?; - let q = fb.convert(ConvOp::Bitcast, b, st)?; - let m1 = fsplat(fb, s, -1.0)?; - let below = bin(fb, BinOp::FOrdLessThan, q, m1)?; - fb.select(below, m1, q)? - } - } - } else { - let d: Vec = widths.iter().map(|n| (1u32 << n) - 1).collect(); - div_exact_lanes(fb, u, v, &d)? - }; - narrow::round(fb, f, q) -} - /// `air.unpack` of a packed float format (the field layouts are the old engine's, device-measured /// against Metal's `rg11b10f` and `rgb9e5` reads): /// @@ -2791,7 +2638,7 @@ pub fn unpack( /// widening where the module holds 16-bit floats, its NaN bits and a denormal as the module /// records), and the `rgb9e5` scale `2^(exponent - 24)` is a normal `f32` built from its bits, whose product with /// the mantissa is exact. -fn unpack_float( +pub fn unpack_float( fb: &mut FunctionBuilder<'_>, format: PackFormat, f: Form, @@ -2851,81 +2698,3 @@ fn unpack_float( let t = ty(fb, f)?; fb.composite_construct(t, &lanes) } - -/// `a * r` rounded to nearest even as an `f32`, for an integer `0 <= a < 2^10` (`u32` lanes of -/// form `u`) and a positive normal `f32` constant `r` per lane (its bits `r_bits[i]` for lane -/// `i`, at most `2^117`; a lane-wise sequence), with integer operations only, so it is exact on -/// every device whatever its rounding mode and under every fast-math mode (Metal's `snorm` -/// `rgb10a2` unpack multiplies by the reciprocal). -/// -/// With `r = m * 2^er` (`m` its 24-bit significand, leading one included), the product `p = a * -/// m` is below `2^34`: `UMulExtended` gives it as two words. Its leading one is at bit `b = 23 + -/// s` with `s` in `[0, 10]` (`m >= 2^23`), so the significand is `p >> s`, rounded to nearest -/// even on the `s` dropped bits (`s <= 10` keeps every shift below 32), and the biased exponent -/// is `s + er + 150`. As in [`div_exact`], the bits are `((s + er + 149) << 23) + q` plus the -/// rounding, which carries into the exponent when `q` is all ones. `a = 0` is `+0`. -/// -/// [`div_exact`]: crate::lower::arith::exact_division::div_exact -pub fn mul_exact( - fb: &mut FunctionBuilder<'_>, - u: Form, - a: Value, - r_bits: &[u32], -) -> BResult { - let c = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v); - let m: Vec = r_bits - .iter() - .map(|r| u64::from((r & 0x7F_FFFF) | 0x80_0000)) - .collect(); - // er + 149 = (biased exponent - 150) + 149. - let bias: Vec = r_bits - .iter() - .map(|r| u64::from(((r >> 23) & 0xFF).saturating_sub(1))) - .collect(); - let (z, one) = (c(fb, 0)?, c(fb, 1)?); - let zero = bin(fb, BinOp::IEqual, a, z)?; - let mk = per_lane(fb, u, &m)?; - let p = bin(fb, BinOp::UMulExtended, a, mk)?; - let lo = fb.composite_extract(p, &[0])?; - let hi = fb.composite_extract(p, &[1])?; - // The leading bit: 32 + msb(hi) when hi is nonzero, else msb(lo) (>= 23 unless a = 0). - let hi_set = bin(fb, BinOp::INotEqual, hi, z)?; - let hm = glsl(fb, GlslOp::FindUMsb, &[hi])?; - let k32 = c(fb, 32)?; - let hm = bin(fb, BinOp::IAdd, hm, k32)?; - let lm = glsl(fb, GlslOp::FindUMsb, &[lo])?; - let msb = fb.select(hi_set, hm, lm)?; - // s = msb - 23, in [0, 10]; t = max(s, 1) keeps the shifts below 32 when s = 0 (then hi = 0 - // and nothing is dropped). - let k23 = c(fb, 23)?; - let s = bin(fb, BinOp::ISub, msb, k23)?; - let k10 = c(fb, 10)?; - let s = glsl(fb, GlslOp::UMin, &[s, k10])?; - let t = glsl(fb, GlslOp::UMax, &[s, one])?; - let q = bin(fb, BinOp::ShiftRightLogical, lo, s)?; - let up_sh = bin(fb, BinOp::ISub, k32, t)?; - let top = bin(fb, BinOp::ShiftLeftLogical, hi, up_sh)?; - let q = bin(fb, BinOp::BitwiseOr, q, top)?; - let unit = bin(fb, BinOp::ShiftLeftLogical, one, s)?; - let below = bin(fb, BinOp::ISub, unit, one)?; - let rem = bin(fb, BinOp::BitwiseAnd, lo, below)?; - let t1 = bin(fb, BinOp::ISub, t, one)?; - let half = bin(fb, BinOp::ShiftLeftLogical, one, t1)?; - let some = bin(fb, BinOp::INotEqual, s, z)?; - let gt = bin(fb, BinOp::UGreaterThan, rem, half)?; - let eq = bin(fb, BinOp::IEqual, rem, half)?; - let lsb = bin(fb, BinOp::BitwiseAnd, q, one)?; - let odd = bin(fb, BinOp::INotEqual, lsb, z)?; - let tie_up = bin(fb, BinOp::LogicalAnd, eq, odd)?; - let up = bin(fb, BinOp::LogicalOr, gt, tie_up)?; - let up = bin(fb, BinOp::LogicalAnd, some, up)?; - let inc = fb.select(up, one, z)?; - let kb = per_lane(fb, u, &bias)?; - let be = bin(fb, BinOp::IAdd, s, kb)?; - let be = bin(fb, BinOp::ShiftLeftLogical, be, k23)?; - let bits = bin(fb, BinOp::IAdd, be, q)?; - let bits = bin(fb, BinOp::IAdd, bits, inc)?; - let bits = fb.select(zero, z, bits)?; - let ft = ty(fb, u.with(Held::Float(FloatFmt::F32)))?; - fb.convert(ConvOp::Bitcast, bits, ft) -} diff --git a/crates/metal2vulkan/src/lower/arith/mod.rs b/crates/metal2vulkan/src/lower/arith/mod.rs index 1d87c11e7..4b6220201 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -652,11 +652,6 @@ 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 sRGB conversion that reads Metal's sRGB table (a tile's or a - /// color attachment'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`, an sRGB storage texture's alias and a UNORM twin 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. pub fmod_uses: bool, @@ -752,13 +747,6 @@ impl ArithPlan { /// The words of the module-scope routines the plan's strategies call, each with the census name /// of the strategies that call it: counted once per module, not per use. pub fn routine_words(plan: &ArithPlan) -> impl Iterator + '_ { - let table = plan.srgb.map(|dir| { - let name = match dir { - PackDir::Pack => SRGB_PACK, - PackDir::Unpack => SRGB_UNPACK, - }; - (name, u64::from(srgb::TABLE_WORDS)) - }); // The extended-range sRGB table, once, and each padded `_sRGB` form's. let extended = plan.extended_range_srgb.then_some(( extended_range::CENSUS_NAME, @@ -777,18 +765,12 @@ pub fn routine_words(plan: &ArithPlan) -> impl Iterator) -> Result<(), Error> { pub struct Declared { /// The function of each of the plan's [`ArithPlan::divides`]. pub divides: BTreeMap, - /// The sRGB table, when [`ArithPlan::srgb`]. - pub srgb: Option, /// The extended-range sRGB table, when [`ArithPlan::extended_range_srgb`]. pub extended_range_srgb: Option, /// The table of each of the plan's [`ArithPlan::padded_srgb`]. @@ -892,9 +872,6 @@ pub fn declare( if plan.families.arith.fmod { decl.fmod = Some(libm::define_fmod(mb)?); } - if plan.families.arith.srgb.is_some() { - decl.srgb = Some(srgb::declare(mb)?); - } if plan.families.arith.extended_range_srgb { decl.extended_range_srgb = Some(extended_range::declare(mb)?); } @@ -1809,7 +1786,8 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result { /// 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_asinh` at +/// from Metal's reciprocal, flushed there (probe cases 6802ab13 and c11eb8cb), and the device's +/// reciprocal here (`FloatFn::FastAtan2`), 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 @@ -1856,7 +1834,7 @@ fn refine_float(op: FloatFn, fast: bool, fmf: FastMath, f: Form) -> FloatFn { FloatFn::Log2 => FloatFn::FastLog2, FloatFn::Powr => FloatFn::FastPowr, FloatFn::Atan2 => FloatFn::FastAtan2 { - reciprocal_flushed: !every_flag(fmf), + by_reciprocal: !every_flag(fmf), }, FloatFn::SinPi => FloatFn::FastSinPi, FloatFn::CosPi => FloatFn::FastCosPi, @@ -2190,7 +2168,9 @@ impl MetalOwn { /// device (`denormals`, `nans`, [`device_float_notes`]). /// /// A call of precise `fmod` by its routine, whose answer is the one right value, Metal's on every -/// device ([`libm::Fun::correctly_rounded`]), records no precision note. Where the profile's +/// device ([`libm::Fun::correctly_rounded`]), records no precision note, but on `half`, whose zero +/// remainder of a nonzero dividend is the `float` remainder's sign, where Metal answers `+0`, in +/// every entry on every device ([`FloatFn::half_zero_of_float`], `NativeTranscendentals`). Where the profile's /// `float` functions are Metal's, a call /// that is Metal's own in a fast-math entry ([`MetalOwn`]) records its function's and its /// division's notes only outside one, and, where it is wholly Metal's own, its denormals' and @@ -2237,8 +2217,14 @@ fn function_notes( } else { MetalOwn::No }; + // A `half` `fmod`'s zero, the `float` remainder's sign in either math mode. + let half_zero = BTreeSet::from_iter( + op.half_zero_of_float(f) + .then_some(PrecisionNote::NativeTranscendentals), + ); OpNotes::unless_own(function, own != MetalOwn::No) .with(OpNotes::unless_own(environment, own == MetalOwn::Wholly)) + .with(OpNotes::everywhere(half_zero)) } /// The note of fused multiply-add `fma`: `NativeFma` where it takes the device's `Fma` diff --git a/crates/metal2vulkan/src/lower/arith/nan.rs b/crates/metal2vulkan/src/lower/arith/nan.rs index cb282799e..eb3a55013 100644 --- a/crates/metal2vulkan/src/lower/arith/nan.rs +++ b/crates/metal2vulkan/src/lower/arith/nan.rs @@ -6,8 +6,9 @@ //! functions answer the canonical NaN `0x7FC00000`, sign and payload dropped //! ([`NanAnswer::Canonical`]); `asin`, `atan`, `asinh`, and `atanh` keep a NaN operand's sign //! ([`NanAnswer::OperandSign`]); `fast::asin` gives a domain error the operand's sign -//! ([`NanAnswer::DomainSign`]); and `round`, `ldexp`, and `fast::tan` return a NaN operand itself -//! ([`NanAnswer::Operand`]). Its `half` `+`, `*`, and fused multiply-add, and its narrowing of a +//! ([`NanAnswer::DomainSign`]); `round`, `ldexp`, and `fast::tan` return a NaN operand itself +//! ([`NanAnswer::Operand`]); and precise `pow` returns a NaN base to the exponent one itself +//! ([`NanAnswer::BaseToExponentOne`]). Its `half` `+`, `*`, and fused multiply-add, and its narrowing of a //! `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 @@ -62,6 +63,10 @@ pub enum NanAnswer { /// and the canonical NaN for a NaN of another origin: `round`, `ldexp`, `fast::tan`, `float` /// `fneg` and `fabs`, and `half` `fract`. Operand, + /// The canonical NaN, but a NaN base to the exponent one, which is the base itself, bit for + /// bit (`pow(-NaN, 1)` is `0xffc00000`): precise `pow` on `float` (A1 case 116e052a, every + /// lane; `fast::pow` answers the canonical NaN there). + BaseToExponentOne, } impl NanAnswer { @@ -180,8 +185,8 @@ fn precise_of(op: FloatFn) -> FloatFn { /// 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`]). +/// `copysign`). `fabs` keeps its operand's payload with the sign cleared ([`NanAnswer::Operand`]), +/// and precise `pow` a NaN base to the exponent one ([`NanAnswer::BaseToExponentOne`]). /// `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 @@ -249,6 +254,7 @@ fn measured(op: FloatFn, fast: bool) -> Option { F::FastAtan => A::Canonical, F::Asin | F::Atan | F::Asinh | F::Atanh => A::OperandSign, F::Round | F::Ldexp | F::Abs => A::Operand, + F::Pow if !fast => A::BaseToExponentOne, _ => return None, }) } diff --git a/crates/metal2vulkan/src/lower/arith/pack.rs b/crates/metal2vulkan/src/lower/arith/pack.rs index 64ac0788e..c1b3f3a07 100644 --- a/crates/metal2vulkan/src/lower/arith/pack.rs +++ b/crates/metal2vulkan/src/lower/arith/pack.rs @@ -12,7 +12,7 @@ //! `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). +//! (`math::unpack_float`, exact: every field is a `half` value). use crate::air::intrinsics::{PackDir, PackFormat}; use crate::lower::arith::exact_division::per_lane; @@ -118,7 +118,7 @@ pub fn unpack( w: Value, ) -> BResult { if math::float_unpack_lanes(format).is_some() { - return math::unpack(fb, format, f, w, None); + return math::unpack_float(fb, format, f, w); } let Some((widths, snorm)) = math::pack_layout(format) else { return Err(unpackable()); @@ -283,7 +283,7 @@ pub(crate) fn srgb_decode(fb: &mut FunctionBuilder<'_>, s: Form, c: Value) -> BR 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`). + // The packed float formats' bit moves (`math::unpack_float`). 400 } else if instruction(format, dir).is_some() { 16 diff --git a/crates/metal2vulkan/src/lower/arith/srgb.rs b/crates/metal2vulkan/src/lower/arith/srgb.rs index 75a4d2551..2bd8c0e07 100644 --- a/crates/metal2vulkan/src/lower/arith/srgb.rs +++ b/crates/metal2vulkan/src/lower/arith/srgb.rs @@ -1,25 +1,9 @@ -//! Metal's sRGB conversions of `air.pack`/`air.unpack` `unorm4x8_srgb`, exact on every device: both -//! go through Metal's twelve-bit tables, which A1 read in full, rather than the MSL transfer -//! functions (whose `GLSL.std.450 Pow` has the device's precision and misses Metal's table at bytes -//! where the transfer lands near a half step). -//! -//! The two tables are one `Private` array of 256 `u32` with its constant initializer, declared -//! once per module that uses it ([`declare`]): word `b` holds the decode step of byte `b` in its -//! low half and the first encode index of byte `b` in its high half. -//! -//! - Decoding byte `b` loads its step `k` ([`step`]), and `math::unpack` answers `k / 4095` -//! correctly rounded ([`div_exact`](crate::lower::arith::exact_division::div_exact)), as -//! Metal does. -//! - The high halves are Metal's encode thresholds: byte `b` encodes the indices from -//! `SRGB_ENCODE_FIRST[b]` of the exact product `x * 4095` rounded to nearest even. -//! -//! The quotients run once per vector in `math::unpack`, with a per-lane scale; only the table -//! reads are per channel, since a `Private` array is indexed by a scalar. - -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, Value}; -use crate::spirv::ir::{BinOp, ConstBits, Constant, MemAccess, StorageClass, Type}; +//! Metal's twelve-bit 8-bit sRGB decode steps, which A1 read in full: the step of every byte. +//! The texture decoders that answer Metal's decoded texels read them (`bind::astc_decode`, +//! `bind::pvrtc_decode`): the linear value of byte `b` is `k / 4095` for its step `k`. +//! `air.pack`/`air.unpack` of `unorm4x8_srgb`, a storage texture's alias, a UNORM twin and the +//! mipmap filter take the MSL transfer through the device's `Pow` instead +//! (`lower::arith::pack`). /// The decode step of every byte `b`: Metal's `unpack_unorm4x8_srgb_to_float` answers `k / 4095` /// (correctly rounded) for `k = SRGB_DECODE_STEPS[b]`, which is `round(decode(b / 255) * 4095)` @@ -44,78 +28,3 @@ pub(crate) const SRGB_DECODE_STEPS: [u16; 256] = [ 3501, 3535, 3568, 3602, 3636, 3670, 3705, 3739, 3774, 3809, 3844, 3879, 3915, 3950, 3986, 4022, 4059, 4095, ]; - -/// The first encode index of every byte `b >= 1` (`0` for `b = 0`, never read): Metal's -/// `pack_float_to_srgb_unorm4x8` encodes a color channel `x` (clamped to `[0, 1]`, NaN to 0) as -/// the byte `b` of the largest `SRGB_ENCODE_FIRST[b] <= i`, where `i` is the exact product -/// `x * 4095` rounded to the nearest even integer: its twelve-bit encode table. A1's -/// `srgb-encode-of-every-half-and-a-2-14-float-grid` (8f7708ff) observed a byte for every one of -/// the 4096 indices, consistently, and these are its thresholds; the MSL transfer -/// `1.055 c^(1/2.4) - 0.055` misses four of them (indices 804, 1371, 2121, and 2569). -pub(crate) const SRGB_ENCODE_FIRST: [u16; 256] = [ - 0, 1, 2, 4, 5, 6, 7, 9, 10, 11, 12, 14, 15, 16, 18, 19, 21, 23, 24, 26, 28, 30, 32, 34, 37, 39, - 42, 44, 47, 49, 52, 55, 58, 61, 64, 68, 71, 74, 78, 82, 85, 89, 93, 97, 102, 106, 110, 115, - 119, 124, 129, 134, 139, 144, 149, 154, 160, 165, 171, 177, 183, 189, 195, 201, 207, 214, 220, - 227, 234, 241, 248, 255, 262, 270, 277, 285, 293, 300, 308, 317, 325, 333, 342, 350, 359, 368, - 377, 386, 395, 405, 414, 424, 434, 444, 454, 464, 474, 485, 495, 506, 517, 528, 539, 550, 562, - 573, 585, 597, 609, 621, 633, 645, 658, 670, 683, 696, 709, 722, 736, 749, 763, 777, 790, 804, - 819, 833, 848, 862, 877, 892, 907, 922, 938, 953, 969, 985, 1001, 1017, 1033, 1049, 1066, 1083, - 1100, 1117, 1134, 1151, 1169, 1186, 1204, 1222, 1240, 1259, 1277, 1296, 1314, 1333, 1352, 1371, - 1391, 1410, 1430, 1450, 1470, 1490, 1510, 1531, 1552, 1572, 1593, 1615, 1636, 1657, 1679, 1701, - 1723, 1745, 1767, 1790, 1812, 1835, 1858, 1881, 1904, 1928, 1951, 1975, 1999, 2023, 2048, 2072, - 2097, 2121, 2146, 2172, 2197, 2222, 2248, 2274, 2300, 2326, 2352, 2379, 2406, 2433, 2460, 2487, - 2514, 2542, 2569, 2597, 2626, 2654, 2682, 2711, 2740, 2769, 2798, 2827, 2857, 2886, 2916, 2946, - 2977, 3007, 3038, 3068, 3099, 3130, 3162, 3193, 3225, 3257, 3289, 3321, 3354, 3386, 3419, 3452, - 3485, 3518, 3552, 3586, 3620, 3654, 3688, 3722, 3757, 3792, 3827, 3862, 3897, 3933, 3969, 4005, - 4041, 4077, -]; - -/// An upper estimate of the SPIR-V words of the table (its 256 constants, the composite, and the -/// variable), charged to every use. -pub const TABLE_WORDS: u32 = 256 * 4 + 262 + 8; - -/// Declare the module's sRGB table: a `Private` `u32[256]` initialized to the steps (low halves) -/// and thresholds (high halves). -pub fn declare(mb: &mut ModuleBuilder) -> BResult { - let u32_ = mb.ty(Type::Int { - width: 32, - signed: false, - })?; - let len = mb.constant(Constant::Scalar { - ty: u32_, - bits: ConstBits(256), - })?; - let arr = mb.ty(Type::Array { - elem: u32_, - len, - stride: None, - })?; - let mut parts = Vec::with_capacity(256); - for (step, first) in SRGB_DECODE_STEPS.iter().zip(SRGB_ENCODE_FIRST) { - parts.push(mb.constant(Constant::Scalar { - ty: u32_, - bits: ConstBits(u64::from(*step) | (u64::from(first) << 16)), - })?); - } - let init = mb.constant(Constant::Composite { - ty: arr, - parts: parts.into(), - })?; - mb.plain_global(StorageClass::Private, arr, Some(init)) -} - -/// Word `i` (a `u32` scalar below 256) of `table`. -fn word(fb: &mut FunctionBuilder<'_>, table: GlobalId, i: Value) -> BResult { - let base = fb.module().global_value(table)?; - let p = fb.access_chain(base, &[i])?; - fb.load(p, MemAccess::default()) -} - -/// The decode step `k` of sRGB byte `b` (a `u32` scalar below 256): the linear value is `k / -/// 4095`, correctly rounded. -pub fn step(fb: &mut FunctionBuilder<'_>, table: GlobalId, b: Value) -> BResult { - let w = word(fb, table, b)?; - let low = fb.u32_const(0xFFFF)?; - let low = fb.module().const_value(low)?; - fb.binary(BinOp::BitwiseAnd, w, low) -} diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index c3661701a..a3a05590e 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -2215,15 +2215,15 @@ fn nan_operands() -> Vec { ] } -/// Class H: Metal's `half` `fmod` answers `+0` for a zero remainder of a nonzero dividend and the -/// dividend itself for a zero one (`fmod(-2, 0.5)` and `fmod(-65504, 65504)` are `+0`, `fmod(-0, -/// 1)` and `fmod(-0, inf)` are `-0`), as `nan_fmod_zero` and `nan_fmod_zero_fast` read on every -/// lane; every other remainder is C's, with the dividend's sign, which the interpreter's `OpFRem` -/// answers. Scalars and vectors, bit for bit but for a NaN's payload (the canonical NaN is selected -/// beside the function), and within the word estimate. A `float` remainder keeps the dividend's -/// sign (`fmod(-2, 0.5)` is `-0`), as Metal's does. +/// Class H: a `half` `fmod` is its `float` remainder rounded, C's, with the dividend's sign, which +/// the interpreter's `OpFRem` answers: a zero remainder of a nonzero dividend is the zero of the +/// dividend's sign (`fmod(-2, 0.5)` and `fmod(-65504, 65504)` are `-0`), where Metal answers `+0` +/// (`nan_fmod_zero`, `nan_fmod_zero_fast`, every lane; `PrecisionNote::NativeTranscendentals`), +/// and a zero dividend's is the dividend itself (`fmod(-0, 1)` is `-0`), as Metal's is. Scalars +/// and vectors, bit for bit but for a NaN's payload, and within the word estimate. A `float` +/// remainder keeps the dividend's sign (`fmod(-2, 0.5)` is `-0`), as Metal's does. #[test] -fn half_fmod_answers_metals_zero_remainder() { +fn half_fmod_is_its_float_remainder_rounded() { let halves: Vec = vec![ 0, 0x8000, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4200, 0xC200, 0x3800, 0xB800, 0x3E00, 0xBE00, 0x3A00, 0xBA00, 0x7BFF, 0xFBFF, 0x0001, 0x8001, 0x0002, 0x8002, 0x03FF, 0x7C00, 0xFC00, @@ -2233,12 +2233,9 @@ fn half_fmod_answers_metals_zero_remainder() { let (a, b) = (c[0][0], c[1][0]); let (x, y) = (f16_to_f64(a as u16), f16_to_f64(b as u16)); let r = x % y; + // A zero remainder keeps the dividend's sign; `f64_to_f16` keeps a zero's sign too. let bits = if r == 0.0 { - if x == 0.0 { - a - } else { - 0 - } + a & 0x8000 } else { u64::from(f64_to_f16(r)) }; @@ -2432,7 +2429,13 @@ fn half_nan_answers_follow_the_measured_states() { } use crate::device::profile::NanEncoding; assert!(A::Canonical.device_answers(NanEncoding::MetalCanonical)); - for a in [A::CanonicalExact, A::Operand, A::OperandSign, A::DomainSign] { + for a in [ + A::CanonicalExact, + A::Operand, + A::OperandSign, + A::DomainSign, + A::BaseToExponentOne, + ] { assert!(!a.device_answers(NanEncoding::MetalCanonical), "{a:?}"); } // A device not measured to answer Metal's canonical NaN answers none of Metal's NaNs. @@ -2442,6 +2445,7 @@ fn half_nan_answers_follow_the_measured_states() { A::Operand, A::OperandSign, A::DomainSign, + A::BaseToExponentOne, ] { assert!(!a.device_answers(NanEncoding::Native), "{a:?}"); } @@ -2460,6 +2464,61 @@ const KHR_FACTS: super::FloatFacts = super::FloatFacts { native_min_max: false, }; +/// Precise `pow` on `float` leaves its NaNs to the device (the device's `Pow`, and the device's sum +/// of NaN operands), where Metal's NaN is measured: the canonical NaN, but a NaN base to the +/// exponent one, which is the base itself. It records `NativeNanEncoding` as fast `pow` and `atan2` +/// do, on a device whose arithmetic answers Metal's canonical NaN too (its sum of `pow(NaN, 1)`'s +/// operands is that NaN, not the base), and never `DeviceNanEncoding`, which is for a NaN Metal +/// answers no NaN of (fast `sin` and `cos`). +#[test] +fn precise_pow_notes_its_measured_nan_as_the_devices() { + use super::nan::NanAnswer as A; + use crate::air::ir::FastMath; + use crate::device::profile::NanEncoding; + use crate::pipeline::artifact::PrecisionNote; + let f = Form { + held: Held::Float(FloatFmt::F32), + lanes: 1, + }; + for nans in [NanEncoding::Native, NanEncoding::MetalCanonical] { + let facts = super::FloatFacts { nans, ..KHR_FACTS }; + let call = + super::float_call(FloatFn::Pow, false, FastMath::NONE, f, facts).expect("float pow"); + assert_eq!(call.nan, Some(A::BaseToExponentOne), "{nans:?}"); + assert!( + call.notes + .always + .contains(&PrecisionNote::NativeNanEncoding), + "{nans:?}: {:?}", + call.notes + ); + let every_note = call + .notes + .always + .iter() + .chain(&call.notes.unless_metal_fast); + assert!( + !every_note + .clone() + .any(|n| *n == PrecisionNote::DeviceNanEncoding), + "{nans:?}: {:?}", + call.notes + ); + let sin = + super::float_call(FloatFn::Sin, true, FastMath::NONE, f, facts).expect("fast sin"); + assert_eq!(sin.nan, None, "{nans:?}"); + assert!( + sin.notes + .always + .iter() + .chain(&sin.notes.unless_metal_fast) + .any(|n| *n == PrecisionNote::DeviceNanEncoding), + "{nans:?}: {:?}", + sin.notes + ); + } +} + /// Class E: Metal's `float` `fneg` and `fabs` flip or clear the sign bit alone, a NaN's payload and /// 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 @@ -2607,6 +2666,7 @@ fn nan_answers_follow_the_measured_flag_states() { (FloatFn::Sin, false, true, Some(A::Canonical)), (FloatFn::Cos, false, true, Some(A::Canonical)), (FloatFn::Atan2, false, true, Some(A::Canonical)), + (FloatFn::Pow, false, false, Some(A::BaseToExponentOne)), (FloatFn::Pow, false, true, None), (FloatFn::FastSin, true, true, None), (FloatFn::Sign, false, false, None), @@ -3107,7 +3167,7 @@ fn fast_variants_refine_float_functions() { ( FloatFn::Atan2, FloatFn::FastAtan2 { - reciprocal_flushed: fmf != every, + by_reciprocal: fmf != every, }, ), (FloatFn::SinPi, FloatFn::FastSinPi), @@ -3141,8 +3201,8 @@ fn fast_variants_refine_float_functions() { assert!(!op.divides(), "{op:?}"); } assert!(!FloatFn::Tanh.divides()); - for reciprocal_flushed in [false, true] { - assert!(FloatFn::FastAtan2 { reciprocal_flushed }.divides()); + for by_reciprocal in [false, true] { + assert!(FloatFn::FastAtan2 { by_reciprocal }.divides()); } assert!(!FloatFn::Atan2.divides()); } @@ -3195,10 +3255,10 @@ fn device_precision_float_functions(part: usize, of: usize) { FloatFn::FastPow, FloatFn::Atan2, FloatFn::FastAtan2 { - reciprocal_flushed: false, + by_reciprocal: false, }, FloatFn::FastAtan2 { - reciprocal_flushed: true, + by_reciprocal: true, }, FloatFn::Fmod, FloatFn::Fma, diff --git a/crates/metal2vulkan/src/lower/arith/tests/atan2.rs b/crates/metal2vulkan/src/lower/arith/tests/atan2.rs index 3a9da3790..565d1bbf2 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/atan2.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/atan2.rs @@ -460,36 +460,63 @@ fn metal_read(b: u32) -> f32 { /// `fast::atan2(y, x)` with the stand-in `atan(q) = q + 1/8`, where the formula's special values do /// not decide it (`None` where they do): the quotient (divided over the whole range, or `y` times -/// the flushed reciprocal), the stand-in, and the turn. A denormal operand or quotient is a value. -fn fast_generic(y: u32, x: u32, reciprocal_flushed: bool) -> Option { +/// the device's reciprocal of `x`, which the interpreter keeps where it is a denormal), the +/// stand-in, and the turn. A denormal operand or quotient is a value. +fn fast_generic(y: u32, x: u32, by_reciprocal: bool) -> Option { if f32_special(y) || f32_special(x) { return None; } let (yv, xv) = (f32::from_bits(y), f32::from_bits(x)); - if reciprocal_flushed && xv.abs() > 2f32.powi(126) { - return None; - } - let q = (f64::from(yv) / f64::from(xv)) as f32; + let q = if by_reciprocal { + yv * (1.0 / xv) + } else { + (f64::from(yv) / f64::from(xv)) as f32 + }; if !q.is_finite() { return None; } - let a = q + 0.125; + Some(turned(q + 0.125, yv, xv).to_bits()) +} + +/// `a` turned by `±π` where `x` is below zero, by `π` where `y` is at least zero. +fn turned(a: f32, y: f32, x: f32) -> f32 { let pi = std::f32::consts::PI; - let r = if xv < 0.0 { - a + if yv >= 0.0 { pi } else { -pi } + if x < 0.0 { + a + if y >= 0.0 { pi } else { -pi } } else { a + } +} + +/// `fast::atan2(y, x)` of an infinite `y` and a finite `x` beyond `2^126` in a call without every +/// flag, on the interpreter: `y` times the device's reciprocal, which the interpreter keeps as a +/// denormal, is an infinite quotient, so the answer is `±π/2` (the quotient's sign) turned, where +/// Metal, which flushes the reciprocal, answers NaN. `None` for any other pair. +fn kept_reciprocal_infinite(y: u32, x: u32) -> Option { + let (yv, xv) = (f32::from_bits(y), f32::from_bits(x)); + if !yv.is_infinite() || !xv.is_finite() || xv.abs() <= 2f32.powi(126) { + return None; + } + let half_pi = std::f32::consts::FRAC_PI_2; + let a = if (y ^ x) & 0x8000_0000 != 0 { + -half_pi + } else { + half_pi }; - Some(r.to_bits()) + Some(turned(a, yv, xv).to_bits()) } /// `fast::atan2` (`math::fast_atan2`) with a stand-in `atan(q) = q + 1/8` the interpreter runs: /// every lane of the grid that the formula's special values decide is Metal's answer for the -/// call's flags (the quotient's sign, `0 / 0` and `inf / inf`, the turn's comparisons, and the -/// flushed reciprocal beyond `2^126` of a call without every flag), a NaN any NaN, and every other -/// lane is the stand-in of the correctly rounded quotient, turned, a denormal quotient's included; -/// operands beyond the grid check the scaled division near `2^126` and `FLT_MAX`. The lanes with -/// a denormal operand, which Metal reads as a zero, are the device's reading and left out. +/// call's flags (the quotient's sign, `0 / 0` and `inf / inf`, the turn's comparisons), a NaN any +/// NaN, and every other lane is the stand-in of the quotient, turned, a denormal quotient's +/// included: the correctly rounded quotient with every flag, and without it `y` times the device's +/// reciprocal. Beyond `2^126` that reciprocal is an `f32` denormal, which the interpreter keeps +/// and Metal flushes: there a finite `y` takes the stand-in of the product and an infinite one +/// `±π/2` turned, where Metal answers a signed zero and NaN (`PrecisionNote::DeviceDenormals` off +/// a device measured to flush as Metal does). Operands beyond the grid check the scaled division +/// near `2^126` and `FLT_MAX`, and the reciprocal there. The lanes with a denormal operand, which +/// Metal reads as a zero, are the device's reading and left out. #[test] fn fast_atan2_answers_as_metal_at_every_special_operand() { let f = float(32); @@ -503,23 +530,32 @@ fn fast_atan2_answers_as_metal_at_every_special_operand() { (-5.0, -7.0), (6.5, 0.25), ]; - for reciprocal_flushed in [false, true] { - let table = if reciprocal_flushed { + for by_reciprocal in [false, true] { + let table = if by_reciprocal { &FAST_ATAN2_F32_NO_FLAGS } else { &FAST_ATAN2_F32 }; let mut want: Vec<((u64, u64), u64)> = Vec::new(); - let mut decided = 0; + let (mut decided, mut kept) = (0, 0); for j in 0..16 { for k in 0..16 { let (y, x) = (F32_OPERANDS[j], F32_OPERANDS[k]); if f32_denormal(y) || f32_denormal(x) { continue; } - let w = match fast_generic(y, x, reciprocal_flushed) { - Some(g) => g, - None => { + let device = if by_reciprocal { + kept_reciprocal_infinite(y, x) + } else { + None + }; + let w = match (fast_generic(y, x, by_reciprocal), device) { + (Some(g), _) => g, + (None, Some(d)) => { + kept += 1; + d + } + (None, None) => { decided += 1; table[j][k] } @@ -528,22 +564,21 @@ fn fast_atan2_answers_as_metal_at_every_special_operand() { } } // The 196 lanes of operands that are not denormals, less those with a finite quotient of - // finite nonzero operands (and, with a flushed reciprocal, less beyond `2^126`). + // finite nonzero operands (and, by the reciprocal, less the four of an infinite `y` over + // `±FLT_MAX`, whose kept reciprocal makes the quotient infinite). assert_eq!( - decided, - if reciprocal_flushed { - 196 - 31 + (decided, kept), + if by_reciprocal { + (196 - 45 - 4, 4) } else { - 196 - 45 + (196 - 45, 0) }, - "reciprocal flushed {reciprocal_flushed}" + "by reciprocal {by_reciprocal}" ); - if !reciprocal_flushed { - for (y, x) in extra { - let (y, x) = (y.to_bits(), x.to_bits()); - let w = fast_generic(y, x, false).expect("a generic lane"); - want.push(((u64::from(y), u64::from(x)), u64::from(w))); - } + for (y, x) in extra { + let (y, x) = (y.to_bits(), x.to_bits()); + let w = fast_generic(y, x, by_reciprocal).expect("a generic lane"); + want.push(((u64::from(y), u64::from(x)), u64::from(w))); } // Metal reads denormal operands as zeros: the answers of the grid's flushed operands are // the answers of the zeros of their sign. @@ -564,7 +599,7 @@ fn fast_atan2_answers_as_metal_at_every_special_operand() { .map(|((y, x), _)| vec![vec![*y], vec![*x]]) .collect(); check_accept( - &format!("fast atan2 f32 (reciprocal flushed {reciprocal_flushed}) against Metal"), + &format!("fast atan2 f32 (by reciprocal {by_reciprocal}) on the interpreter"), &[f, f], f, &|fb, a| { @@ -574,7 +609,7 @@ fn fast_atan2_answers_as_metal_at_every_special_operand() { }; let divide = |fb: &mut FunctionBuilder<'_>, n: Value, d: Value| fb.binary(BinOp::FDiv, n, d); - math::fast_atan2(fb, f, a[0], a[1], reciprocal_flushed, &atan, ÷) + math::fast_atan2(fb, f, a[0], a[1], by_reciprocal, &atan, ÷) }, &cases, &|c| { @@ -602,10 +637,10 @@ fn special_value_functions_stay_within_their_word_estimate() { let fns = [ FloatFn::Atan2, FloatFn::FastAtan2 { - reciprocal_flushed: false, + by_reciprocal: false, }, FloatFn::FastAtan2 { - reciprocal_flushed: true, + by_reciprocal: true, }, ]; let mut out = Vec::new(); diff --git a/crates/metal2vulkan/src/lower/arith/tests/color_write.rs b/crates/metal2vulkan/src/lower/arith/tests/color_write.rs index f440fb1a6..4d44ea3d0 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/color_write.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/color_write.rs @@ -463,7 +463,7 @@ fn word_attachments_store_metals_words() { for (out, b) in rgba.iter_mut().zip(&c[0]) { *out = f32::from_bits(*b as u32); } - Some(vec![u64::from(word.output_word(rgba))]) + word.output_word(rgba).map(|w| vec![u64::from(w)]) }, &|g, w| g == w, ); diff --git a/crates/metal2vulkan/src/lower/arith/tests/libm.rs b/crates/metal2vulkan/src/lower/arith/tests/libm.rs index d74ea756b..ba564dcd7 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/libm.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/libm.rs @@ -204,11 +204,12 @@ fn fmod_routine_reads_metals_denormal_operands() { } /// A `half` call of `fmod` takes the `float` routine before its rounding (Metal's `half` functions -/// are the same in both modes), so it is Metal's `half` `fmod` (MSL Table 8.3: exact) over a grid +/// are the same in both modes), so it is Metal's exact `half` remainder (MSL Table 8.3) over a grid /// of pairs: the remainder of two `half` values is one. The half reading: `fmod(x, ±inf) = x` /// (where lavapipe, RADV, and NVIDIA answer a NaN) and `fmod(1.5, -0.75) = 0` (RADV: 0.75). A zero -/// remainder is Metal's `half` one: `+0` for a nonzero dividend, the dividend itself for a zero -/// one. Part `part` of `of` of the runs of 4,096 pairs. +/// remainder is the `float` remainder's, with the dividend's sign, where Metal's `half` answers +/// `+0` for a nonzero dividend (`PrecisionNote::NativeTranscendentals`). Part `part` of `of` of +/// the runs of 4,096 pairs. fn half_fmod(part: usize, of: usize) { let h = float(16); let nan = |b: u64| b & 0x7C00 == 0x7C00 && b & 0x03FF != 0; @@ -240,7 +241,6 @@ fn half_fmod(part: usize, of: usize) { let x = f16_to_f64(c[0][0] as u16); let y = f16_to_f64(c[1][0] as u16); let r = (x as f32) % (y as f32); - let r = if r == 0.0 && x != 0.0 { 0.0 } else { r }; Some(vec![half_of(r)]) }, &|g, w| g == w || (nan(g) && nan(w)), diff --git a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs index fffc2fd1f..c389d7785 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs @@ -1855,106 +1855,6 @@ fn fp8_to_integer_converts_every_pattern_as_its_value() { } } -/// `air.unpack` follows Metal's normalized conversion: to a float by dividing, correctly rounded -/// (snorm clamped at -1). The sRGB format is `srgb_unpack_answers_with_metals_table`'. -#[test] -fn unpack_follows_the_normalized_conversions() { - use crate::air::intrinsics::PackFormat as P; - let formats = [ - P::Unorm4x8, - P::Snorm4x8, - P::Unorm2x16, - P::Snorm2x16, - P::UnormRgb10a2, - P::UnormRgb565, - ]; - for format in formats { - let (widths, snorm) = math::pack_layout(format).expect("lowered"); - let lanes = widths.len() as u8; - let word = int(math::packed_bits(format)); - for lane in [float(32), half()] { - let f = vec(lane, lanes); - let mut rng = Rng(7); - let cases: Vec = (0..24) - .map(|_| vec![vec![rng.next() & mask(math::packed_bits(format))]]) - .collect(); - let accept = exact_ok(f); - check_accept( - &format!("unpack {format:?} to {lane:?}"), - &[word], - f, - &|fb, x| math::unpack(fb, format, f, x[0], None), - &cases, - &|c| { - let mut at = 0; - let mut out = Vec::new(); - for n in widths { - let v = (c[0][0] >> at) & mask(*n as u8); - let x = if snorm { - let s = sext(v, *n as u8) as f32; - (s / ((1u32 << (n - 1)) - 1) as f32).max(-1.0) - } else { - v as f32 / ((1u32 << n) - 1) as f32 - }; - out.push(nbits(lane, f64::from(x))); - at += n; - } - Some(out) - }, - &accept, - ); - } - } - assert!(math::pack_layout(P::UnormRg11b10f).is_none()); - assert!(math::pack_layout(P::UnormRgb9e5).is_none()); -} - -/// Metal's `snorm` `rgb10a2` unpack, as measured on Apple M3 Max (macOS 26.7) by the probe over -/// every code of every field: `max(c * fl(1 / s), -1)` in `f32` (a `half` result rounds that -/// `f32`), `s` being 511 for the 10-bit fields and 1 for the 2-bit alpha. -fn snorm_10a2_unpack_ref(w: u64) -> [f32; 4] { - let mut out = [0.0f32; 4]; - for (k, (at, n)) in [(0u32, 10u32), (10, 10), (20, 10), (30, 2)] - .iter() - .enumerate() - { - let c = sext((w >> at) & mask(*n as u8), *n as u8) as f32; - out[k] = (c * (1.0 / ((1u32 << (n - 1)) - 1) as f32)).max(-1.0); - } - out -} - -/// `air.unpack.snorm.rgb10a2` computes Metal's measured rule ([`snorm_10a2_unpack_ref`]) on every -/// code of every field, unpacked to `float` and `half`. Metal's own word pins the rule: 65 unpacks -/// to `0x3E024120`, one ULP below the quotient `65 / 511`. -#[test] -fn snorm_rgb10a2_unpacks_as_metal_measures() { - use crate::air::intrinsics::PackFormat as P; - let word = int(32); - // Metal's words. - assert_eq!(snorm_10a2_unpack_ref(0x4411_0441)[0].to_bits(), 0x3E02_4120); - assert_eq!(snorm_10a2_unpack_ref(0x2008_0200), [-1.0, -1.0, -1.0, 0.0]); - // Unpack: every code of every field (r = g = b = k, a = k mod 4). - let codes: Vec = (0..1024u64) - .map(|k| vec![vec![k | k << 10 | k << 20 | (k & 3) << 30]]) - .collect(); - for lane in [float(32), half()] { - let f = vec(lane, 4); - check_accept( - &format!("unpack snorm rgb10a2 to {lane:?}"), - &[word], - f, - &|fb, x| math::unpack(fb, P::SnormRgb10a2, f, x[0], None), - &codes, - &|c| { - let v = snorm_10a2_unpack_ref(c[0][0]); - Some(v.iter().map(|x| nbits(lane, f64::from(*x))).collect()) - }, - &|g, w| g == w, - ); - } -} - /// `k / d` is correctly rounded (the host's IEEE `f32` division) for every `k` in `[0, d]` of every /// normalized scale and the sRGB step scale 4095, and for every 97th `k` and both ends of the /// 16-bit scales. @@ -1981,63 +1881,6 @@ fn normalized_division_is_correctly_rounded() { } } -/// `unorm4x8_srgb` unpacks through Metal's twelve-bit decode table, on the interpreter: every byte -/// in every lane gives, for a color byte `b`, the correctly rounded `round(decode(b / 255) * 4095) -/// / 4095` of the MSL transfer (every step at least `1.6e-4` from a half step), and for the alpha -/// byte `a / 255` correctly rounded; among them Metal's steps of the authored case -/// `srgb-transfer-and-its-twelve-bit-table` (M3 Max, ORACLE_ABI v32): byte 1 (`0.000303527`, 1.243 -/// steps) is step 1, `0x39800801`; byte 137 is step 1024, `0x3E800801`; byte 255 is `1.0`. -#[test] -fn srgb_unpack_answers_with_metals_table() { - use crate::air::intrinsics::PackFormat as P; - use crate::lower::arith::srgb; - let word = int(32); - let decode = |b: u64| { - let c = b as f64 / 255.0; - let v = if c <= 0.04045 { - c / 12.92 - } else { - ((c + 0.055) / 1.055).powf(2.4) - }; - let k = (v * 4095.0).round_ties_even(); - u64::from(((k / 4095.0) as f32).to_bits()) - }; - for lane in [float(32), half()] { - let f = vec(lane, 4); - let cases: Vec = (0..256u64) - .map(|b| { - let w = b | ((255 - b) << 8) | ((b ^ 0x5A) << 16) | (((7 * b + 3) & 255) << 24); - vec![vec![w]] - }) - .collect(); - check_accept( - &format!("unpack sRGB to {lane:?}"), - &[word], - f, - &|fb, x| { - let t = srgb::declare(fb.module())?; - math::unpack(fb, P::Unorm4x8Srgb, f, x[0], Some(t)) - }, - &cases, - &|c| { - let w = c[0][0]; - let mut out: Vec = (0..3).map(|k| decode((w >> (8 * k)) & 255)).collect(); - out.push(u64::from(((w >> 24) as f32 / 255.0).to_bits())); - Some( - out.iter() - .map(|b| nbits(lane, f64::from(f32::from_bits(*b as u32)))) - .collect(), - ) - }, - &exact_ok(f), - ); - } - let metal: [(u64, u64); 3] = [(1, 0x3980_0801), (137, 0x3E80_0801), (255, 0x3F80_0000)]; - for (b, want) in metal { - assert_eq!(decode(b), want, "byte {b}"); - } -} - /// A normalized pack rounds the exact product `x * m`, not `fl(x * m)`: the values where the `f32` /// multiply rounds onto a half-integer that the exact product is not (found by search next to every /// `k + 1/2`), and ordinary values, for every channel scale. @@ -2137,7 +1980,7 @@ fn packed_float_formats_unpack_exactly() { &format!("unpack {format:?} to {lane:?}"), &[word], f, - &|fb, x| math::unpack(fb, format, f, x[0], None), + &|fb, x| math::unpack_float(fb, format, f, x[0]), &cases, &|c| { let w = arg(c, 0); @@ -2161,105 +2004,13 @@ fn packed_float_formats_unpack_exactly() { } } -/// An `air.unpack` of a normalized format converts its channels as one vector, so its code does not -/// repeat a scalar sequence per channel. Previously a `float4` unpack was 779 words (955 snorm); -/// after, 297 (358). -#[test] -fn normalized_unpacks_convert_their_channels_as_one_vector() { - use crate::air::intrinsics::PackFormat as P; - use crate::lower::arith::ops::splat; - use crate::spirv::serialize::serialize; - let word = int(32); - let size = |ins: &[Form], out: Form, body: Body<'_>| -> usize { - let m = kernel(ins, out, body).expect("build"); - serialize(m).expect("serialize").words.len() - }; - for (format, unpack_most) in [ - (P::UnormRgb10a2, 310), - (P::Unorm4x8, 310), - (P::Snorm4x8, 370), - ] { - let fl = vec(float(32), 4); - let unpack = size(&[word], fl, &|fb, x| { - math::unpack(fb, format, fl, x[0], None) - }) - size(&[word], fl, &|fb, _| splat(fb, fl, 0)); - assert!(unpack <= unpack_most, "{format:?} unpack: {unpack} words"); - } -} - -/// A vector unpack divides each lane by its own channel's scale: every value of every field of up -/// to 10 bits in every lane (every 97th and both ends of a 16-bit field), against the host's -/// correctly rounded quotient, to `float` and to `half`. -#[test] -fn a_vector_unpack_reads_every_field_value_of_every_channel() { - use crate::air::intrinsics::PackFormat as P; - let word = int(32); - for format in [ - P::UnormRgb10a2, - P::UnormRgb565, - P::Unorm4x8, - P::Snorm4x8, - P::Unorm2x16, - P::Snorm2x16, - ] { - let (widths, snorm) = math::pack_layout(format).expect("lowered"); - let most = widths.iter().map(|n| 1u64 << n).max().unwrap_or(1); - let step = if most > 1024 { 97 } else { 1 }; - let vals: Vec = (0..most) - .step_by(step) - .chain([most - 2, most - 1]) - .collect(); - let cases: Vec = vals - .iter() - .map(|v| { - let mut w = 0u64; - let mut at = 0; - for (k, n) in widths.iter().enumerate() { - w |= ((v + 5 * k as u64) & mask(*n as u8)) << at; - at += n; - } - vec![vec![w]] - }) - .collect(); - for lane in [float(32), half()] { - let f = vec(lane, widths.len() as u8); - check_accept( - &format!("vector unpack {format:?} to {lane:?}"), - &[word], - f, - &|fb, x| math::unpack(fb, format, f, x[0], None), - &cases, - &|c| { - let mut at = 0; - let mut out = Vec::new(); - for n in widths { - let v = (c[0][0] >> at) & mask(*n as u8); - let x = if snorm { - let s = sext(v, *n as u8) as f32; - (s / ((1u32 << (n - 1)) - 1) as f32).max(-1.0) - } else { - v as f32 / ((1u32 << n) - 1) as f32 - }; - out.push(nbits(lane, f64::from(x))); - at += n; - } - Some(out) - }, - &exact_ok(f), - ); - } - } -} - /// `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. +/// other normalized formats, and a plan of no division, `fmod` routine or extended-range table +/// charges no routine. #[test] -fn srgb_packs_read_no_table_and_the_table_charges_once() { +fn srgb_packs_read_no_table() { use crate::air::intrinsics::{PackDir, PackFormat as P}; - use crate::lower::arith::{ - routine_words, srgb, ArithPlan, ArithStrategy, SRGB_PACK, SRGB_UNPACK, - }; + use crate::lower::arith::{routine_words, ArithPlan, ArithStrategy}; use crate::lower::select::FamilyPlans; use crate::lower::strategy::FamilyStrategy; let name = |dir, format| { @@ -2275,19 +2026,6 @@ fn srgb_packs_read_no_table_and_the_table_charges_once() { 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, table) in [(PackDir::Pack, SRGB_PACK), (PackDir::Unpack, SRGB_UNPACK)] { - let plan = ArithPlan { - srgb: Some(dir), - ..ArithPlan::default() - }; - let charged: Vec<(String, u64)> = routine_words(&plan) - .map(|(name, words)| (name.to_owned(), words)) - .collect(); - assert_eq!( - charged, - 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/texel_round.rs b/crates/metal2vulkan/src/lower/arith/tests/texel_round.rs index 91a61a049..8d574343c 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/texel_round.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/texel_round.rs @@ -363,35 +363,3 @@ fn ratio_to_half_rounds_once() { }; assert!(twice(65455, 65535) && twice(65519, 65535) && twice(32759, 32767)); } - -/// The sRGB table's step `k` of every code, divided exactly by 4095 (what texture reads and -/// samples answer for a color channel), is `k / 4095` correctly rounded. -#[test] -fn srgb_steps_read_the_twelve_bit_table() { - use crate::lower::arith::{exact_division, srgb}; - let u = int(32); - let decode = |b: u64| { - let c = b as f64 / 255.0; - let v = if c <= 0.04045 { - c / 12.92 - } else { - ((c + 0.055) / 1.055).powf(2.4) - }; - let k = (v * 4095.0).round_ties_even(); - u64::from(((k / 4095.0) as f32).to_bits()) - }; - let cases: Vec = (0..256u64).map(|b| vec![vec![b]]).collect(); - check( - "srgb_step", - &[u], - float(32), - &|fb, a| { - let t = srgb::declare(fb.module())?; - let k = srgb::step(fb, t, a[0])?; - exact_division::div_exact(fb, u, k, 4095) - }, - &cases, - &|c| Some(vec![decode(arg(c, 0))]), - false, - ); -} diff --git a/crates/metal2vulkan/src/lower/arith/texel_round.rs b/crates/metal2vulkan/src/lower/arith/texel_round.rs index 7f048f95a..6742f5661 100644 --- a/crates/metal2vulkan/src/lower/arith/texel_round.rs +++ b/crates/metal2vulkan/src/lower/arith/texel_round.rs @@ -20,7 +20,7 @@ //! - [`grid_value`]: a signed step's value `n / D` on a normalized format's grid exactly, the //! bicubic sums'. //! -//! Metal's texture reads and samples decode a raw sRGB code through its twelve-bit table, as +//! Metal's texture reads and samples decode a raw sRGB code through its twelve-bit table, as its //! `air.unpack` does: the step `k` of [`srgb`](crate::lower::arith::srgb), then `k / 4095` //! ([`div_exact`](crate::lower::arith::exact_division::div_exact); every code of the authored case //! `half-conversion-of-wider-texels-by-read-and-sample`, and every bicubic sum of diff --git a/crates/metal2vulkan/src/metal/format/word.rs b/crates/metal2vulkan/src/metal/format/word.rs index fcb73f9f9..368974a51 100644 --- a/crates/metal2vulkan/src/metal/format/word.rs +++ b/crates/metal2vulkan/src/metal/format/word.rs @@ -6,9 +6,9 @@ //! holds such a texture in its UNORM twin). Such a texture's image is made mutable, with extended //! usage, and its attachment is a view of the same bits as the unsigned integer format of its word //! ([`WordAttachment::word_format`]), which every Vulkan device renders. The fragment function -//! writes the word Metal stores for its output (`LoweringInputs::word_colors`), and a clear writes -//! the word of Metal's clear (the runtime's clear values): both are exact, and the texture's other -//! views read the same bits. +//! writes its output's word (`LoweringInputs::word_colors`): the word Metal stores, but an 8-bit +//! sRGB format's codes, which are the device's encode (below); and a clear writes the word of +//! Metal's clear (the runtime's clear values). The texture's other views read the same bits. //! //! Metal's store into a packed 16-bit format (measured on an Apple M3 Max under macOS 27.0.1: //! every texel of 65,536 `float` and `half` outputs and 4,096 clear colors into each of @@ -22,7 +22,9 @@ //! Metal's store into an 8-bit sRGB format (`R8Unorm_sRGB`, `RG8Unorm_sRGB`; the lane's rule, //! `runtime_lane::color_writes`, and its in-guest probe's clears and draws on the M3 Max): each //! channel's value clamped to `[0, 1]` (a NaN 0), times 4095 exactly, rounded to nearest, encoded -//! by Metal's twelve-bit table, as `pack_float_to_srgb_unorm4x8` encodes a color channel. A write +//! by Metal's twelve-bit table, as `pack_float_to_srgb_unorm4x8` encodes a color channel. The +//! fragment function encodes the channel by the MSL transfer through the device's `Pow`, as its +//! `pack_float_to_srgb_unorm4x8` does (`lower::arith::pack`, `PrecisionNote::DevicePackConversion`). A write //! of some of its channels merges the word into the texel's: in the pixel interlock //! (`color_writes::stored_word`), or over the attachment's input attachment on a device that orders //! fetch through rasterization-order input attachments (`color_writes::merged_word`). A blend of @@ -173,40 +175,29 @@ impl WordAttachment { .fold(0, |w, c| w | c) } - /// The word Metal stores for a `float` (or `half`) output `rgba`: a packed 16-bit format's - /// channel by `ChannelWrite::HalfUnorm`'s rule, an 8-bit sRGB format's by Metal's twelve-bit - /// encode (the module docs), a channel the format lacks ignored; `RGB9E5Float`'s word of a - /// `float` output (the module docs). The reference of the fragment function's encode. - pub fn output_word(self, rgba: [f32; 4]) -> u32 { - if self == WordAttachment::Rgb9e5 { - return rgb9e5_word([rgba[0], rgba[1], rgba[2]]); - } - let fields = self.fields(); - let mut codes = [0u32; 4]; - for (code, (f, x)) in codes.iter_mut().zip(fields.iter().zip(rgba)) { - if let Some(f) = f { - *code = match self { - WordAttachment::Packed16 { .. } => half_unorm_code(x, f.bits), - WordAttachment::Srgb8 { .. } => srgb_code(f64::from(x)), - WordAttachment::Rgb9e5 => 0, - }; + /// The word Metal stores for a `float` (or `half`) output `rgba`, which the fragment + /// function's encode stores too: a packed 16-bit format's channel by + /// `ChannelWrite::HalfUnorm`'s rule, a channel the format lacks ignored; `RGB9E5Float`'s word + /// of a `float` output (the module docs), which a clear stores as well. `None` for an 8-bit + /// sRGB format, whose codes the fragment function takes from the device's encode (the module + /// docs). + pub fn output_word(self, rgba: [f32; 4]) -> Option { + match self { + WordAttachment::Rgb9e5 => Some(rgb9e5_word([rgba[0], rgba[1], rgba[2]])), + WordAttachment::Srgb8 { .. } => None, + WordAttachment::Packed16 { fields } => { + let mut codes = [0u32; 4]; + for (code, (f, x)) in codes.iter_mut().zip(fields.iter().zip(rgba)) { + if let Some(f) = f { + *code = half_unorm_code(x, f.bits); + } + } + Some(self.pack(codes)) } } - self.pack(codes) } } -/// Metal's byte of an 8-bit sRGB channel's value `x`: clamped to `[0, 1]` (a NaN 0), the exact -/// product with 4095 rounded to nearest (no `float` meets a tie: 4095 is odd), and the byte of the -/// largest first index at most that (Metal's twelve-bit table, `lower::arith::srgb`'s, which its -/// render writes and clears share with `pack_float_to_srgb_unorm4x8`). -pub(crate) fn srgb_code(x: f64) -> u32 { - let x = if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) }; - let i = (x * 4095.0).round_ties_even() as u16; - let first = &crate::lower::arith::srgb::SRGB_ENCODE_FIRST; - (1..256).rev().find(|&b| first[b] <= i).unwrap_or(0) as u32 -} - /// The `RGB9E5Float` word Metal stores for `float` channels `rgb` (a draw's output, a clear's /// color through `float`, a kernel's write): each clamped to `[0, 65408]` (a NaN, a negative value /// and `-0` 0), the exponent `e = max(floor(log2 m), -16) + 16` of the largest clamped channel @@ -276,24 +267,18 @@ mod tests { // `half` 0.09998 times 15 is 1.4997: an ABGR4 alpha of 0.1 is 1. assert_eq!(half_unorm_code(0.1, 4), 1); let w = WordAttachment::layout(PixelFormat::A1BGR5Unorm).unwrap(); - assert_eq!(w.output_word([1.0, 0.0, 1.0, 0.5]), 0xf83e); + assert_eq!(w.output_word([1.0, 0.0, 1.0, 0.5]), Some(0xf83e)); } - /// The M3 Max's clears of the in-guest probe: an `R8Unorm_sRGB` clear of 0.2 stores 0x7c, an - /// `RG8Unorm_sRGB` one of (0.2, 0.4) 0x7c then 0xaa; NaN and negatives are 0, past one 0xff. + /// An 8-bit sRGB word's codes are the device's encode: no reference word. #[test] - fn srgb_words_take_metals_encode() { - assert_eq!(srgb_code(f64::from(0.2f32)), 0x7c); - assert_eq!(srgb_code(f64::from(0.4f32)), 0xaa); - assert_eq!(srgb_code(f64::NAN), 0); - assert_eq!(srgb_code(-1.0), 0); - assert_eq!(srgb_code(2.0), 0xff); + fn srgb_words_have_no_reference_word() { let r8 = WordAttachment::layout(PixelFormat::R8UnormSRGB).unwrap(); assert_eq!(r8.word_format(), vk::Format::R8_UINT); - assert_eq!(r8.output_word([0.2, 0.4, 0.6, 0.8]), 0x7c); + assert_eq!(r8.output_word([0.2, 0.4, 0.6, 0.8]), None); let rg8 = WordAttachment::layout(PixelFormat::RG8UnormSRGB).unwrap(); assert_eq!(rg8.word_format(), vk::Format::R16_UINT); - assert_eq!(rg8.output_word([0.2, 0.4, 0.6, 0.8]), 0xaa7c); + assert_eq!(rg8.output_word([0.2, 0.4, 0.6, 0.8]), None); } /// The format scout's draw on the M3 Max: (2.5, 0.375, -0.75) stores `0x88006140`; the @@ -303,7 +288,7 @@ mod tests { fn rgb9e5_words_truncate_under_the_largest_exponent() { let w = WordAttachment::layout(PixelFormat::RGB9E5Float).unwrap(); assert_eq!(w.word_format(), vk::Format::R32_UINT); - assert_eq!(w.output_word([2.5, 0.375, -0.75, 0.5]), 0x8800_6140); + assert_eq!(w.output_word([2.5, 0.375, -0.75, 0.5]), Some(0x8800_6140)); assert_eq!(rgb9e5_word([0.25, 0.0, 1.125]), 0x8480_0040); assert_eq!(rgb9e5_word([70000.0, f32::NAN, -0.0]), (31 << 27) | 511); assert_eq!(rgb9e5_word([0.0; 3]), 0); diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index ab8a06e7e..52f4a3553 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1584,17 +1584,19 @@ pub enum PrecisionNote { /// `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); a `half` /// function's zeros' and NaNs' signs its `float` instruction's (Metal's `half` `sin`, `tan` - /// and `asin` of `-0` are `+0`, its `half` `asin` NaN takes the operand's sign); `pow`, - /// `powr` and `atan2` C99's special values around the device's instruction, decided by the - /// device's comparisons, so `pow(x, 1)` is the device's `Pow` (Metal answers `x`) and an - /// `f32` denormal operand reads as the device reads it; and `round` C99's, from the device's + /// and `asin` of `-0` are `+0`, its `half` `asin` NaN takes the operand's sign), and on every + /// device a `half` `fmod`'s zero remainder its `float` remainder's, the dividend's sign + /// (`half` `fmod(-2, 0.5)` is `-0`, where Metal answers `+0`); `pow`, `powr` and `atan2` + /// C99's special values around the device's instruction, decided by the device's + /// comparisons, so `pow(x, 1)` is the device's `Pow` (Metal answers `x`) and an `f32` + /// denormal operand reads as the device reads it; 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)`); `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 `[-π, + /// correctly rounded, `round`'s and a `half` `fmod`'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`, @@ -1759,7 +1761,8 @@ pub enum PrecisionNote { /// Metal answers a NaN the device answers a NaN (the module keeps /// `SignedZeroInfNanPreserve` where Metal's entry keeps NaNs), its sign and payload the /// device's own (llvmpipe: `0xffc00000`), where Metal answers its canonical `0x7fc00000` - /// (`0x7e00` as `half`), an operand's bits (`round`, `ldexp`, `fast::tan`), or the canonical + /// (`0x7e00` as `half`), an operand's bits (`round`, `ldexp`, `fast::tan`, and precise `pow` + /// of a NaN base to the exponent one), or the canonical /// 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 diff --git a/crates/metal2vulkan/src/tests/engine_arith.rs b/crates/metal2vulkan/src/tests/engine_arith.rs index 5f5019b1f..3692d5cea 100644 --- a/crates/metal2vulkan/src/tests/engine_arith.rs +++ b/crates/metal2vulkan/src/tests/engine_arith.rs @@ -4032,14 +4032,15 @@ fn float_min_max_are_the_device_s_on_every_profile() { } } -/// Class H: Metal's `half` `fmod` answers `+0` for a zero remainder of a nonzero dividend and the -/// dividend itself for a zero one, with or without fast-math flags (`nan_fmod_zero`, -/// `nan_fmod_zero_fast`: `fmod(-2, 0.5)` is `+0`, `fmod(-0, 1)` is `-0`), on every profile; a -/// nonzero remainder keeps the dividend's sign, and a `float` zero remainder too (Metal's -/// `fmod(-2, 0.5)` on `float` is `-0`). The interpreter's `OpFRem` is C's `fmod`, the dividend's -/// sign, so the stored bits show the select. +/// Class H: a `half` `fmod` is its `float` remainder rounded on every profile, so a zero remainder +/// of a nonzero dividend keeps the dividend's sign, with or without fast-math flags, where Metal +/// answers `+0` (`nan_fmod_zero`, `nan_fmod_zero_fast`: Metal's `fmod(-2, 0.5)` is `+0`), noted +/// `NativeTranscendentals` in every entry; a zero dividend's is the dividend itself (`fmod(-0, 1)` +/// is `-0`) and a nonzero remainder keeps the dividend's sign, as Metal's do. A `float` zero +/// remainder keeps it too (Metal's `fmod(-2, 0.5)` on `float` is `-0`), with no note. The +/// interpreter's `OpFRem` is C's `fmod`, the dividend's sign. #[test] -fn half_fmod_answers_metals_zero_remainder_on_every_profile() { +fn half_fmod_is_its_float_remainder_on_every_profile() { let two = |a: u16, b: u16| format!("{}{}", oh("hx", a), oh("hy", b)); let ks = [ half_nan_kernel( @@ -4048,7 +4049,7 @@ fn half_fmod_answers_metals_zero_remainder_on_every_profile() { "{} %s = call half @air.fmod.f16(half %hx, half %hy)\n", two(0xC000, 0x3800) ), - Some(0), + Some(0x8000), ), half_nan_kernel( "half_fmod_negative_dividend_fast", @@ -4056,7 +4057,7 @@ fn half_fmod_answers_metals_zero_remainder_on_every_profile() { "{} %s = call fast half @air.fmod.f16(half %hx, half %hy)\n", two(0xFBFF, 0x7BFF) ), - Some(0), + Some(0x8000), ), half_nan_kernel( "half_fmod_of_negative_zero", @@ -4101,6 +4102,13 @@ fn half_fmod_answers_metals_zero_remainder_on_every_profile() { link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); let got = interpret(&bitcode, kk.name, &p); assert_eq!(Some(got), kk.want, "{what}: {got:#x}"); + // The `half` remainder's zero is the note's; the `float` one is Metal's. + assert_eq!( + a.precision.contains(&PrecisionNote::NativeTranscendentals), + kk.name.starts_with("half_"), + "{what}: {:?}", + a.precision + ); } } } diff --git a/crates/metal2vulkan/src/tests/engine_float_call_notes.rs b/crates/metal2vulkan/src/tests/engine_float_call_notes.rs index f34397178..631c45006 100644 --- a/crates/metal2vulkan/src/tests/engine_float_call_notes.rs +++ b/crates/metal2vulkan/src/tests/engine_float_call_notes.rs @@ -488,8 +488,10 @@ fn a_float_division_is_the_devices_arithmetic_unless_it_is_metals_precise_one() /// Metal's precise `fmod`, on `float` and `half`, answers the one right value /// (`libm::Fun::correctly_rounded`: exact by MSL Tables 8.1 and 8.3), which its routine computes -/// on every device: it records neither precision note on any profile class, in either mode, with -/// or without flags. Precise `sqrt` and `rsqrt`, which Metal documents correctly rounded, are the +/// on every device: it records no precision note of the function's value on any profile class, in +/// either mode, with or without flags; a `half` one records `NativeTranscendentals` for its zero +/// remainder's sign, its `float` remainder's, where Metal's `half` answers `+0` +/// (`FloatFn::half_zero_of_float`). Precise `sqrt` and `rsqrt`, which Metal documents correctly rounded, are the /// device's `Sqrt` and `InverseSqrt`: off Metal's own functions they record the device's precision /// (`NativeTranscendentals`), as precise `exp`, which Apple bounds by ulps, does. #[test] @@ -509,8 +511,12 @@ fn precise_fmod_records_no_precision_note_and_the_roots_the_devices() { for math in [EntryMath::Fast, EntryMath::Precise] { let notes = PrecisionNote::of_math_call(parse(name), fmf, &p, math) .unwrap_or_else(|| panic!("{name} is a float function")); + let half_zero = name.ends_with("f16"); assert!( - function_notes.iter().all(|note| !notes.contains(note)), + function_notes.iter().all(|note| { + notes.contains(note) + == (half_zero && *note == PrecisionNote::NativeTranscendentals) + }), "{name} under {fmf:?} on {stem}, {math:?}: {notes:?}" ); } diff --git a/crates/metal2vulkan/src/tests/engine_texture.rs b/crates/metal2vulkan/src/tests/engine_texture.rs index de38acdbc..c41a84b7f 100644 --- a/crates/metal2vulkan/src/tests/engine_texture.rs +++ b/crates/metal2vulkan/src/tests/engine_texture.rs @@ -243,11 +243,8 @@ fn bgra8_and_rgba8_storage_textures_compile_to_distinct_modules() { ); } } - let table = |a: &FunctionArtifact| { - a.strategies - .entries - .contains_key(crate::lower::arith::SRGB_PACK) - }; + let table = + |a: &FunctionArtifact| super::engine_fragment::holds_srgb_table(&a.module.words); let srgb_rgba = variant(PixelFormat::RGBA8UnormSRGB); if let Some((choice, s)) = &srgb_rgba { if choice.class == StorageImageClass::SrgbEncode { diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index de95060ab..254525d32 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -8834,7 +8834,7 @@ method metal2vulkan::metal::format::FormatMapping::direct pub fn direct(format: method metal2vulkan::metal::format::WordAttachment::fields pub fn fields(self) -> [Option; 4] method metal2vulkan::metal::format::WordAttachment::layout pub fn layout(pf: PixelFormat) -> Option method metal2vulkan::metal::format::WordAttachment::of pub fn of(pf: PixelFormat, p: &DeviceProfile) -> Option -method metal2vulkan::metal::format::WordAttachment::output_word pub fn output_word(self, rgba: [f32; 4]) -> u32 +method metal2vulkan::metal::format::WordAttachment::output_word pub fn output_word(self, rgba: [f32; 4]) -> Option method metal2vulkan::metal::format::WordAttachment::pack pub fn pack(self, codes: [u32; 4]) -> u32 method metal2vulkan::metal::format::WordAttachment::word_format pub fn word_format(self) -> vk::Format method metal2vulkan::metal::sampler::AddressModeMap::constexpr_mode pub fn constexpr_mode(&self, from: SamplerAddressMode) -> Option diff --git a/docs/API.md b/docs/API.md index f50cb1c32..cd1ab35da 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3190,10 +3190,12 @@ bound. `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`); a `half` function's signed zeros and NaN signs its `float` instruction's (`half` `sin(-0)` is `-0`, where Metal - answers `+0`); `pow`, `powr` and `atan2` C99's special values by the device's comparisons - around its instruction (`pow(x, 1)` the device's `Pow`, where Metal answers `x`; an `f32` - denormal operand as the device reads it); and `round` C99's from the device's `Trunc` on every - device (`round(-0.3)` is `-0`, where Metal answers `+0`). + answers `+0`), and on every device a `half` `fmod`'s zero remainder its `float` remainder's + (`half` `fmod(-2, 0.5)` is `-0`, where Metal answers `+0`); `pow`, `powr` and `atan2` C99's + special values by the device's comparisons around its instruction (`pow(x, 1)` the device's + `Pow`, where Metal answers `x`; an `f32` denormal operand as the device reads it); 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 @@ -3259,8 +3261,9 @@ bound. 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): a `float` - `fneg` and `fabs`, which keep a NaN operand's payload on Metal, and a `half` `fract`, which - returns it, among them. Also + `fneg` and `fabs`, which keep a NaN operand's payload on Metal, a `half` `fract`, which returns + it, and a precise `float` `pow` of a NaN base to the exponent one, which returns the base, 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 diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index e03b6b3f1..17886b3ac 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -55,7 +55,7 @@ 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`, `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; the fast `sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh` and `atanh` are `Sin`, `Cos`, `Tan`, `Sinh`, `Cosh`, `Tanh` and `Atanh`, not MSL Table 8.2's formulas (`fast::sin(1e7)` is the device's sine, Metal's `+0`; `fast::tanh(45)` is `1`, Metal's NaN); a `half` function's signed zeros and NaN signs are its `float` instruction's (`half` `sin(-0)` is `-0`, Metal's `+0`); `pow`, `powr` and `atan2` add only C99's special values that `GLSL.std.450` leaves undefined, by the device's comparisons (`pow(x, 1)` is the device's `Pow`, Metal's `x`; a NaN operand's NaN is the device's sum of the operands); `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, and no select reads a special operand as Metal does, 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`) | +| 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; the fast `sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh` and `atanh` are `Sin`, `Cos`, `Tan`, `Sinh`, `Cosh`, `Tanh` and `Atanh`, not MSL Table 8.2's formulas (`fast::sin(1e7)` is the device's sine, Metal's `+0`; `fast::tanh(45)` is `1`, Metal's NaN); a `half` function's signed zeros and NaN signs are its `float` instruction's (`half` `sin(-0)` is `-0`, Metal's `+0`), and on every device a `half` `fmod`'s zero remainder is its `float` remainder's (`fmod(-2, 0.5)` is `-0`, Metal's `+0`); `pow`, `powr` and `atan2` add only C99's special values that `GLSL.std.450` leaves undefined, by the device's comparisons (`pow(x, 1)` is the device's `Pow`, Metal's `x`; a NaN operand's NaN is the device's sum of the operands); `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, and no select reads a special operand as Metal does, 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, as is an 8-bit sRGB storage texture's write through its UNORM alias. A `float` one of the four named formats on MoltenVK reaches Metal's own. The same conversions serve an implicit imageblock access of a normalized attachment (a `half` load rounding the unpacked `float` once more), the interlocked storage form's 8-bit sRGB attachment and sRGB word, and a snapshot's normalized codes (`c` times the `f32` nearest `1/D`). | 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`) | @@ -903,12 +903,10 @@ else. read settles nothing. A rotated plane never reaches any of this: its `bytesPerRow` must be a multiple of 16, so its GPU rows lie at the pitch itself and share no byte. -- **A few maths and sampling paths still compute Metal's own answer where the device has one**: - `fast::atan2` flushes its reciprocal past 2^126 as Metal does (`FastAtan2` in - `lower/arith/math.rs`); a bicubic sample of an 8-bit sRGB format read through its UNORM twin - snaps each decoded tap to Metal's twelve-bit step (`lower/sampler/bicubic.rs`); and `half` - `fmod` gives a zero result Metal's sign on its exact remainder routine, where no note records the - device's yet. Each is open work toward the device's answer; none is announced. +- **A sampling path still computes Metal's own answer where the device has one**: a bicubic + sample of an 8-bit sRGB format read through its UNORM twin snaps each decoded tap to Metal's + twelve-bit step (`lower/sampler/bicubic.rs`). It is open work toward the device's answer; it is + not announced. - **A shadow's merge back to host pages stores each changed word alone after a command that leaves texels it does not write** (a kernel's or a blit's partial writes among them; a render pass that loads and stores its attachment inside its scissors, and a command that replaces