diff --git a/crates/metal2vulkan-conformance/known-gaps.tsv b/crates/metal2vulkan-conformance/known-gaps.tsv index ac63c67bb..ef40d566a 100644 --- a/crates/metal2vulkan-conformance/known-gaps.tsv +++ b/crates/metal2vulkan-conformance/known-gaps.tsv @@ -755,6 +755,7 @@ norm-storage-codes-rgba8unorm llvmpipe divergent case/hsw_read_write/texels 128 norm-storage-codes-rgba8unorm llvmpipe divergent case/hsw_write/texels 128 elements differ (U32), the largest difference 16843009 A `float` the function writes to a normalized storage texture at a tie between two codes: Metal stores the exact product rounded with a tie away from zero, and this device rounds the tie to even, so each tie channel is a code apart (the report compares whole words, so its difference adds a word's channels together: Metal 0x01010101 against our 0x00000000 is four channels a code apart). Under the native-arithmetic contract the device's conversion is the answer: `device-color-conversion` records exactly this for a storage write the device converts, and validation derives no tolerance from it. Open: nothing. pass-bytes-half-tanh-regimes llvmpipe divergent case/output/half-tanh 1257 elements differ (U32), the largest difference 2180022768 Each word holds two `half` results of `tanh` over its regimes, which the device computes by its own `Tanh` (a `half` held as `float`, on every device) and rounds to `half` by its own conversion (`native-transcendentals`, `native-half-conversion`; a NaN's bits and a denormal are the device's, `native-nan-encoding`, `device-denormals`). The first differing element is one `half` ulp toward zero in each half (Metal 0x0C00 against our 0x0BFF), and the site's largest difference, 0x81F081F0, sets a sign bit in each half, so some lanes differ in sign too. `native-transcendentals` bounds `Tanh` as Vulkan does, inherited from `sinh / cosh` and so from `Exp`, and `native-half-conversion` the rounding at one `half` ulp; whether every differing word is within them is not established by this run, which reads the first and the largest. Validation derives no tolerance from them. Open: an element-by-element read of the site against the notes' recorded bounds. pass-bytes-half-tanh-regimes llvmpipe divergent case/output/fast-float-tanh 1428 elements differ (U32), the largest difference 2151546880 Each word holds `fast::tanh` of a `float` over its regimes, which the device computes by its own `Tanh` (`native-transcendentals`, on every device; a NaN's bits and a denormal are the device's, `native-nan-encoding`, `device-denormals`). The first differing element is Metal 0x38F218D9 against our 0x38F1F8DA, a result near 1.15e-4, 8,191 ulp apart, and the site's largest difference, 0x803E0000, is past the sign bit, so some lanes differ in sign too. `native-transcendentals` bounds `Tanh` as Vulkan does, inherited from `sinh / cosh` and so from `Exp`; whether every differing word is within it is not established by this run, which reads the first and the largest. Validation derives no tolerance from it. Open: an element-by-element read of the site against the note's recorded bound. +pass-bytes-half-tanh-regimes Apple M3 Max divergent case/output/fast-float-tanh 2623 elements differ (U32), the largest difference 2147483648 Each word holds `fast::tanh` of a `float` over its regimes, which the device computes by its own `Tanh` on every device; on MoltenVK that instruction is MSL's precise `tanh` in either math mode (SPIRV-Cross emits `precise::tanh`), where Metal's `fast::tanh` is MSL Table 8.2's formula `(t - 1) / (t + 1)` of `t = exp(2x)`, which is a NaN once `t` overflows where `Tanh` answers 1 (`device-transcendentals`, announced because the instruction is not Metal's fast function there; a NaN's bits and a denormal are the device's). The first differing element is Metal 0x357FFFF0 against our 0x35800000, one ulp, and the site's largest difference, 0x80000000, is a zero's sign. Measured: this case's replay on this M3 Max (macOS 27.0.1), 2026-10-29. Every other venue: expected, unaudited. Open: an element-by-element read of the site against the note's recorded bound. pass-bytes-srgb-decode-all-bytes llvmpipe divergent case/output/words 1153 elements differ (U32), the largest difference 16318464 Each thread holds four `float` and two words of two `half` results of an sRGB decode of a byte. Metal decodes through its twelve-bit table, answering the step `k / 4095` nearest the transfer; the module decodes by the MSL transfer function through the device's `Pow` (`device-pack-conversion`, on every device), and rounds a `half` result by the device's conversion (`native-half-conversion`). The first differing element is a `float` decode of byte 90, Metal's step 419/4095 (0x3DD18D19) against the transfer's 0.1022417 (0x3DD1641D); the site's largest difference, 0x00F90000, is a small `half` 249 of its ulps off. Read element by element on the validation crate's copy of the case (`srgb-decode-of-every-byte` on lavapipe), every `float` is within 1.221e-4 of Metal's, half a twelve-bit step, and every `half` within that and one `half` ulp, the alpha channels exact: within `device-pack-conversion`'s recorded bound. Validation derives no tolerance from it. Open: nothing. pass-bytes-srgb-decode-all-bytes Apple M3 Max divergent case/output/words 1136 elements differ (U32), the largest difference 16318465 Each thread holds four `float` and two words of two `half` results of an sRGB decode of a byte. Metal decodes through its twelve-bit table, answering the step `k / 4095` nearest the transfer; the module decodes by the MSL transfer function through the device's `Pow` (`device-pack-conversion`, on every device), and rounds a `half` result by the device's conversion. The first differing element is a `float` decode of byte 90, Metal's step 419/4095 (0x3DD18D19) against the transfer's 0x3DD1641F; the site's largest difference, 0x00F90001, is a word whose small `half` is 249 of its ulps off and whose other `half` is one. Read element by element off this replay's bytes against the committed recording, every `float` is within 1.2205e-4 of Metal's, under half a twelve-bit step (1/8190), and every `half` within that and one `half` ulp (at most 0.97 of it), the alpha channels exact: within `device-pack-conversion`'s recorded bound. Validation derives no tolerance from it. Open: nothing. pass-bytes-srgb-encode-sweep llvmpipe divergent case/output/words 772 elements differ (U32), the largest difference 65793 Each word holds an sRGB encode of a `float` or a `half` colour packed to four bytes. Metal encodes through its twelve-bit table; the module encodes by the MSL transfer function through the device's `Pow` and rounds it to a byte by `PackUnorm4x8` (`device-pack-conversion`, on every device), so a colour near a byte boundary lands a code from Metal's. The first differing element is one code in one channel (Metal 0x00020201 against our 0x00020101), and the site's largest difference, 0x00010101, is one code in each colour channel. Read element by element on the validation crate's copy of the case (`srgb-encode-of-every-half-and-a-2-14-float-grid` on lavapipe), every differing channel is one code from Metal's and no alpha differs: within `device-pack-conversion`'s recorded bound. Validation derives no tolerance from it. Open: nothing. diff --git a/crates/metal2vulkan-validation/src/c3/bound/tests.rs b/crates/metal2vulkan-validation/src/c3/bound/tests.rs index 96368025c..4b7ba0f71 100644 --- a/crates/metal2vulkan-validation/src/c3/bound/tests.rs +++ b/crates/metal2vulkan-validation/src/c3/bound/tests.rs @@ -299,11 +299,12 @@ fn every_operation_is_metals_air_and_the_product_lowers_it() { /// The near-equivalents are the product's own, as its lowering records them: its fast `float` /// division (Metal's precise division and every `half` division are a shared routine's correctly /// rounded quotient, which records nothing), fast `fmod`, and a function it computes with a -/// division of its own (fast `float` `tanh` and `atan2`). Its transcendentals are the device's, -/// fast `float` `sqrt` is Metal's `x * rsqrt(x)` on the device's `rsqrt`, a narrow or precise -/// `tanh` is the device's `tanh`, and precise `sqrt` and `fmod`, `float` and `half`, are the one -/// right value, which records nothing. On a device whose `float` functions are Metal's own, a fast -/// division and those functions are Metal's own under fast math and record nothing there either. +/// division of its own (fast `float` `atan2`). Its transcendentals are the device's: `tanh`, fast +/// or precise, `float` or `half`, is the device's `Tanh`, a transcendental, not a near-equivalent; +/// fast `float` `sqrt` is Metal's `x * rsqrt(x)` on the device's `rsqrt`, and precise `sqrt` and +/// `fmod`, `float` and `half`, are the one right value, which records nothing. On a device whose +/// `float` functions are Metal's own, a fast division and those functions are Metal's own under +/// fast math and record nothing there either. #[test] fn the_products_own_approximations_are_its_near_equivalents() { use msl::Prim; @@ -340,11 +341,20 @@ fn the_products_own_approximations_are_its_near_equivalents() { assert_eq!(note(Prim::Sqrt, format, math), None, "{format:?} {math:?}"); } } - for prim in [Prim::Tanh, Prim::Atan2] { - assert_eq!(note(prim, F32, Math::Fast), arithmetic, "{prim:?}"); - assert_eq!(note(prim, F32, Math::Precise), None, "{prim:?}"); - assert_eq!(note(prim, F16, Math::Fast), None, "{prim:?}"); - assert_eq!(note_on(prim, F32, Math::Fast, moltenvk()), None, "{prim:?}"); + assert_eq!(note(Prim::Atan2, F32, Math::Fast), arithmetic); + assert_eq!(note(Prim::Atan2, F32, Math::Precise), None); + assert_eq!(note(Prim::Atan2, F16, Math::Fast), None); + assert_eq!(note_on(Prim::Atan2, F32, Math::Fast, moltenvk()), None); + for format in [F32, F16] { + for math in [Math::Precise, Math::Fast] { + for profile in [lavapipe(), moltenvk()] { + assert_eq!( + note_on(Prim::Tanh, format, math, profile), + None, + "{format:?} {math:?}" + ); + } + } } for prim in [ Prim::Sin, @@ -359,7 +369,9 @@ fn the_products_own_approximations_are_its_near_equivalents() { } // Fast tanh(44): t + 1 is past 2^126, where Table 8.2 states no accuracy for the division. - // Metal answers 0, the device 1. With the product's division recorded, the word stays open. + // Metal answers 0, the device 1. The product's fast tanh is the device's `Tanh`, which records + // no division of its own, so the word stays Apple's unstated one even where the row records + // the device's arithmetic for another operation. let lanes = vec![BoundedLane { words: words(0, 1, 1), result: Part::F32, @@ -388,12 +400,12 @@ fn the_products_own_approximations_are_its_near_equivalents() { panic!("tanh(44) is stated"); }; assert!(why.contains("div"), "{why}"); - let open = judge(&[ + let device = judge(&[ PrecisionNote::DeviceArithmetic, PrecisionNote::DeviceTranscendentals, ]); - assert_eq!(open.label(), "near_equivalent"); - assert!(open.keeps_open(UnstatedWords::WithinPromise)); + assert_eq!(device.label(), "unstated", "{device:?}"); + assert!(!device.keeps_open(UnstatedWords::WithinPromise)); } /// Fast `atan2` with a divisor past `2^126` (case f6524207's lanes 351 and 26): Table 8.2's formula @@ -544,12 +556,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. The product answers Metal's NaN for every operation this -/// check reads on `float`, in either math mode (its calls carry no flags, or every flag, the -/// measured states): none records the note, 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. Fast `sin` answers -/// Metal's NaN itself. Two different answers, not both NaNs, are not the encoding's. +/// 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. #[test] fn a_nan_encoding_the_product_answers_is_not_a_near_equivalent() { let (metal, device) = (0x7fc0_0000, 0xffc0_0000); @@ -557,10 +572,15 @@ fn a_nan_encoding_the_product_answers_is_not_a_near_equivalent() { let infinity = f32::INFINITY.to_bits(); let nan = [PrecisionNote::DeviceNanEncoding]; for math in [Math::Precise, Math::Fast] { + let device_nans: &[msl::Prim] = match math { + Math::Precise => &[msl::Prim::Pow], + Math::Fast => &[msl::Prim::Sin, msl::Prim::Cos], + }; for prim in msl::Prim::ALL { let (op, notes) = lowering_notes(prim, F32, math, lavapipe()).unwrap(); - assert!( - !notes.contains(&PrecisionNote::DeviceNanEncoding), + assert_eq!( + notes.contains(&PrecisionNote::DeviceNanEncoding), + device_nans.contains(&prim), "{op} under {math:?}: {notes:?}" ); } @@ -585,12 +605,23 @@ fn a_nan_encoding_the_product_answers_is_not_a_near_equivalent() { &nan, ); assert_ne!(mul.label(), "near_equivalent", "{mul:?}"); - // Fast `sin` answers Metal's NaN itself: a row recording the note for another operation does - // not make this value the note's. - let (_, sin) = lowering_notes(msl::Prim::Sin, F32, Math::Fast, lavapipe()).unwrap(); - assert!(!sin.contains(&PrecisionNote::DeviceNanEncoding), "{sin:?}"); + // Fast `sin` is the device's `Sin`, whose NaN of an infinity is the device's: the note's, open. let sin = verdict_of("sin(a)", Math::Fast, &[infinity], (metal, device), &nan); - assert_eq!(sin.label(), "unstated", "{sin:?}"); + assert_eq!(sin.label(), "near_equivalent", "{sin:?}"); + assert!(sin.keeps_open(UnstatedWords::WithinPromise), "{sin:?}"); + // Precise `sin` records no `DeviceNanEncoding`: a row recording the note for another + // 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. + let pow = verdict_of( + "pow(a, b)", + Math::Precise, + &[(-1.0f32).to_bits(), 0.5f32.to_bits()], + (metal, device), + &nan, + ); + assert_eq!(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-validation/src/c3/tests.rs b/crates/metal2vulkan-validation/src/c3/tests.rs index dac4d4b41..78acf271c 100644 --- a/crates/metal2vulkan-validation/src/c3/tests.rs +++ b/crates/metal2vulkan-validation/src/c3/tests.rs @@ -1817,10 +1817,11 @@ fn a_signed_off_apple_reading_holds_only_while_every_differing_word_is_within_ap /// Where Apple states no accuracy, the device's answer is within Apple's promise, but not the /// product's approximation. A row whose modules record the product's lowering as a near-equivalent /// of Metal's (`DeviceArithmetic`) keeps the word open, so the report refuses the sign-off, -/// whatever the unstated-words flag says: fast `fmod` ("Undefined"), and fast `float` `tanh`, -/// which the product computes as `(t - 1) / (t + 1)` with its own division (its lowering of -/// `air.fast_tanh.f32` records `DeviceArithmetic`), whose divisor at `tanh(44)` is past the -/// `2^126` where Table 8.2 bounds the fast division. +/// whatever the unstated-words flag says: fast `fmod` ("Undefined"). Fast `float` `tanh` at +/// `tanh(44)`, whose formula's divisor is past the `2^126` where Table 8.2 bounds the fast +/// division, is unstated too, but the product's fast `tanh` is the device's `Tanh` (its lowering +/// of `air.fast_tanh.f32` records no `DeviceArithmetic`): the device's own answer, within the +/// promise, so the sign-off stands even where the row records the note for another operation. #[test] fn an_unstated_word_the_product_approximates_keeps_its_reading_open() { /// A one-word fast-math reading: the case's AIR tag, what the word computes of which bit @@ -1885,33 +1886,36 @@ fn an_unstated_word_the_product_approximates_keeps_its_reading_open() { let check = report.readings[0].bound.as_ref().unwrap(); assert_eq!(check.count("unstated"), 1, "{}", word.computes); assert!(report.refused.is_empty()); - - // The product's remainder or division, recorded as a near-equivalent: open, and the - // sign-off refused. - let report = report_of( - word, - &[ - PrecisionNote::DeviceArithmetic, - PrecisionNote::DeviceTranscendentals, - ], - ); - let check = report.readings[0].bound.as_ref().unwrap(); - assert_eq!(check.count("near_equivalent"), 1, "{}", word.computes); - assert_eq!(report.refused.len(), 1); - assert!( - report.refused[0].words[0].contains("near_equivalent") - && report.refused[0].words[0].contains("DeviceArithmetic"), - "{:?}", - report.refused - ); - assert!(!report.holds()); } - let report = report_of(&tanh, &[PrecisionNote::DeviceArithmetic]); + let recorded = [ + PrecisionNote::DeviceArithmetic, + PrecisionNote::DeviceTranscendentals, + ]; + // The product's remainder, recorded as a near-equivalent: open, and the sign-off refused. + let report = report_of(&fmod, &recorded); + let check = report.readings[0].bound.as_ref().unwrap(); + assert_eq!(check.count("near_equivalent"), 1); + assert_eq!(report.refused.len(), 1); assert!( - report.refused[0].words[0].contains("its lowering of air.fast_tanh.f32 (Metal's tanh)"), + report.refused[0].words[0].contains("near_equivalent") + && report.refused[0].words[0].contains("DeviceArithmetic"), "{:?}", report.refused ); + assert!(!report.holds()); + let report = report_of(&fmod, &[PrecisionNote::DeviceArithmetic]); + assert!( + report.refused[0].words[0].contains("its lowering of air.fast_fmod.f32 (Metal's fmod)"), + "{:?}", + report.refused + ); + // The device's `Tanh`: no near-equivalent of the product's, so the word stays unstated and + // the sign-off stands, whatever arithmetic notes the row records. + let report = report_of(&tanh, &recorded); + let check = report.readings[0].bound.as_ref().unwrap(); + assert_eq!(check.count("unstated"), 1); + assert_eq!(check.count("near_equivalent"), 0); + assert!(report.refused.is_empty(), "{:?}", report.refused); } /// A word within Apple's bound that shows a recorded near-equivalent's difference keeps its reading diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index eff61a4c1..77ddb6476 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 = 1918; +pub const SEMANTICS_VERSION: u32 = 1919; /// 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 edd19f371..9c417bce7 100644 --- a/crates/metal2vulkan/src/lower/arith/denormal.rs +++ b/crates/metal2vulkan/src/lower/arith/denormal.rs @@ -7,14 +7,7 @@ use crate::device::DeviceProfile; use crate::error::DriverDeviation; -use crate::lower::arith::legal::Form; use crate::lower::arith::math::FloatFn; -use crate::lower::arith::narrow::u32_form; -use crate::lower::arith::ops::{splat, ty}; -use crate::spirv::builder::FunctionBuilder; -use crate::spirv::error::BResult; -use crate::spirv::ids::Value; -use crate::spirv::ir::{BinOp, ConvOp}; /// Whether profile `p`'s device reads the denormals of the operations [`Covered::Deviation`] /// names as Metal does: an `f32` denormal operand as the zero of its sign, a denormal result @@ -75,25 +68,3 @@ pub fn coverage(op: FloatFn) -> Option { _ => return None, }) } - -/// An upper estimate of the SPIR-V words of one [`flush`] on form `f`: six instructions of at most -/// six words, and the three masks' share (a vector's constants carry their lanes). -pub fn flush_words(f: Form) -> u32 { - 36 + 4 * u32::from(f.lanes) -} - -/// `x` (`float` lanes of form `f`) with each denormal lane replaced by the zero of its sign, -/// decided on the exponent field, so the same on every device and in every float mode. -pub fn flush(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { - let u = u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let bits = fb.convert(ConvOp::Bitcast, x, ut)?; - let exponent = splat(fb, u, 0x7F80_0000)?; - let sign = splat(fb, u, 0x8000_0000)?; - let zero = splat(fb, u, 0)?; - let e = fb.binary(BinOp::BitwiseAnd, bits, exponent)?; - let denormal = fb.binary(BinOp::IEqual, e, zero)?; - let signed_zero = fb.binary(BinOp::BitwiseAnd, bits, sign)?; - let r = fb.select(denormal, signed_zero, bits)?; - fb.convert(ConvOp::Bitcast, r, ft) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/mod.rs b/crates/metal2vulkan/src/lower/arith/libm/mod.rs index 5cf3205c5..70dc2d7ba 100644 --- a/crates/metal2vulkan/src/lower/arith/libm/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/libm/mod.rs @@ -6,11 +6,16 @@ //! `2^-11` absolute, about what Metal's fast-math table allows, while Metal's precise functions are //! bounded at 4 to 6 ulp (MSL Table 8.1). Every call, on `float` and on a `half` held as `float`, //! takes the device's instruction where one is the function (`exp`, `log`, `pow`, `sinh`, `cosh` -//! and `tanh` among them), and a composition of the device's instructions only where none is -//! (`exp10`, `log10`, `sinpi`, `cospi`, `tanpi`, and the fast functions' formulas of MSL Table -//! 8.2), and records the device's precision where its functions are not Metal's own +//! and `tanh` among them, and the fast `sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh` and `atanh`, +//! whatever formula MSL Table 8.2 gives them), and a composition of the device's instructions only +//! where none is (`exp10`, `log10`, `sinpi`, `cospi`, `tanpi`, and the fast `exp`, `log`, `powr` +//! and `atan2`, which MSL Table 8.2 defines as compositions of `exp2`, `log2`, `atan` and a +//! division), and records the device's precision where its functions are not Metal's own //! (`PrecisionNote::NativeTranscendentals`). No routine computes Metal's answer where the device -//! has an instruction. Where the device is Metal's own +//! has an instruction, and no select reads a special operand as Metal does where the device's +//! instruction answers it: the selects around `pow`, `powr` and `atan2` give only the C99 and MSL +//! values `GLSL.std.450` leaves undefined, by the device's comparisons. Where the device is +//! Metal's own //! (`FloatFunctions::Metal`: MoltenVK on an Apple GPU), its instruction is Metal's function in the //! math mode Metal compiles the module with ([`module_mode`]), so a call in that mode is Metal's //! own answer there ([`Fun::device_answers`]), which the notes read. @@ -73,11 +78,21 @@ pub enum Fun { Cos, /// Metal's precise `tan` (within 6 ulp). Tan, - /// Metal's fast `sin` below its flush point, which is its precise `sin` inside `[-π, π]` - /// (Apple's `2^-13` bound, MSL Table 8.2). + /// Metal's fast `sin`, which is its precise `sin` inside `[-π, π]` (Apple's `2^-13` bound, MSL + /// Table 8.2) and `+0` past its flush point and for an infinity or NaN. FastSin, - /// Metal's fast `cos` below its flush point; as [`Fun::FastSin`]. + /// Metal's fast `cos`; as [`Fun::FastSin`]. FastCos, + /// Metal's fast `tan`, MSL Table 8.2's `sin(x) · (1 / cos(x))` of its fast `sin` and `cos`. + FastTan, + /// Metal's fast `sinh`, MSL Table 8.2's `(exp(x) - exp(-x)) · 0.5`. + FastSinh, + /// Metal's fast `cosh`, MSL Table 8.2's `(exp(x) + exp(-x)) · 0.5`. + FastCosh, + /// Metal's fast `tanh`, MSL Table 8.2's `(t - 1) / (t + 1)` of `t = exp(2x)`. + FastTanh, + /// Metal's fast `atanh`, MSL Table 8.2's `0.5 · log((1 + x) / (1 - x))`. + FastAtanh, /// Metal's `sinpi`, for a precise call (`air.sinpi`) or a fast one (`air.fast_sinpi`): Metal's /// fast function is its precise one, and only a device whose functions are Metal's tells them /// apart ([`Fun::device_answers`]). @@ -164,9 +179,11 @@ impl Fun { /// `module`: the instruction is Metal's function in that mode, and `atan2` is always the /// precise one (SPIRV-Cross emits `precise::atan2` whatever the flags). The precise-only /// functions (`sin`, `cos`, `tan`, `sqrt`, `rsqrt`, and `fmod`, whose fast calls are their own - /// functions) are Metal's only in a precise module. Metal's fast `sin` and `cos` are the - /// device's in either: its fast functions in a fast-math module, and in a precise one its - /// precise functions, which are the fast ones below the flush point. Metal's `sinpi`, `cospi`, + /// functions) are Metal's only in a precise module. Metal's fast `sin`, `cos`, `tan`, `sinh`, + /// `cosh` and `atanh` are the device's `Sin`, `Cos`, `Tan`, `Sinh`, `Cosh` and `Atanh` in a + /// fast-math module only (in a precise one those are Metal's precise functions, which differ: + /// `fast::sin` is `+0` past its flush point), and its fast `tanh` in none (SPIRV-Cross emits + /// `precise::tanh`, below). Metal's `sinpi`, `cospi`, /// and `tanpi` are none of the instructions SPIRV-Cross emits (it emits no `sinpi`), so the /// device's `Sin` and `Cos` of `float(π) r` answer a precise call otherwise than Metal (849, /// 922 and 637 of case 087758cb's 1,024 lanes matched); a fast call is that composition, in @@ -184,7 +201,13 @@ impl Fun { /// function, never Metal's `half` form. pub fn device_answers(self, module: Mode) -> bool { match self { - Fun::FastSin | Fun::FastCos => true, + Fun::FastSin + | Fun::FastCos + | Fun::FastTan + | Fun::FastSinh + | Fun::FastCosh + | Fun::FastAtanh => module == Mode::Fast, + Fun::FastTanh => false, Fun::SinPi(m) | Fun::CosPi(m) | Fun::TanPi(m) => m == Mode::Fast, Fun::Atan(m) | Fun::Asin(m) | Fun::Acos(m) => m == module, Fun::Sin @@ -303,8 +326,7 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] { FloatFn::Tan => &[Fun::Tan], FloatFn::FastSin => &[Fun::FastSin], FloatFn::FastCos => &[Fun::FastCos], - // Apple's formula `sin(x) · (1 / cos(x))` of Metal's fast functions. - FloatFn::FastTan => &[Fun::FastSin, Fun::FastCos], + FloatFn::FastTan => &[Fun::FastTan], FloatFn::SinPi => &[Fun::SinPi(Mode::Precise)], FloatFn::CosPi => &[Fun::CosPi(Mode::Precise)], FloatFn::TanPi => &[Fun::TanPi(Mode::Precise)], @@ -314,8 +336,8 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] { FloatFn::Sqrt => &[Fun::Sqrt], FloatFn::Rsqrt => &[Fun::Rsqrt], FloatFn::Fmod => &[Fun::Fmod], - // The precise functions, and the fast ones' formulas of Metal's `exp2` and `log2` (MSL - // Table 8.2). + // The precise functions, the fast ones the device's instructions, and the fast ones' + // compositions of Metal's `exp2` and `log2` (MSL Table 8.2). FloatFn::Exp2 => &[Fun::Exp2], FloatFn::Exp => &[Fun::Exp], FloatFn::Exp10 => &[Fun::Exp10], @@ -329,12 +351,12 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] { FloatFn::Asinh => &[Fun::Asinh], FloatFn::Acosh => &[Fun::Acosh], FloatFn::Atanh => &[Fun::Atanh], - FloatFn::FastExp - | FloatFn::FastExp10 - | FloatFn::FastSinh - | FloatFn::FastCosh - | FloatFn::FastTanh => &[Fun::Exp2], - FloatFn::FastLog | FloatFn::FastLog10 | FloatFn::FastAtanh => &[Fun::Log2], + FloatFn::FastSinh => &[Fun::FastSinh], + FloatFn::FastCosh => &[Fun::FastCosh], + FloatFn::FastTanh => &[Fun::FastTanh], + FloatFn::FastAtanh => &[Fun::FastAtanh], + FloatFn::FastExp | FloatFn::FastExp10 => &[Fun::Exp2], + FloatFn::FastLog | FloatFn::FastLog10 => &[Fun::Log2], FloatFn::FastAsinh => &[Fun::FastAsinh], FloatFn::FastAcosh => &[Fun::FastAcosh], FloatFn::FastPow | FloatFn::FastPowr => &[Fun::Exp2, Fun::Log2], @@ -360,40 +382,26 @@ pub fn use_words(lanes: u8, arity: usize) -> u32 { .saturating_add(8) } -/// What an entry's calls take, as emission reads them: the mode Metal compiles the entry's -/// functions in where the device's are Metal's, and the routine of precise `fmod` where the module -/// defines one. +/// What an entry's calls take, as emission reads them: the routine of precise `fmod` where the +/// module defines one. Every other function is the device's instruction, whichever mode Metal +/// compiles the entry in. #[derive(Clone, Copy, Debug)] pub struct Lib { - metal: Option, fmod: Option, } impl Lib { - /// The library of an entry whose `float` functions are Metal's in mode `metal` (`None`: the - /// device's), whose module defines precise `fmod`'s routine as `fmod` where it takes one. - pub fn new(metal: Option, fmod: Option) -> Lib { - Lib { metal, fmod } + /// The library of an entry whose module defines precise `fmod`'s routine as `fmod` where it + /// takes one. + pub fn new(fmod: Option) -> Lib { + Lib { fmod } } /// A library that leaves every function to its instruction (a unit test's view of the /// sequences around one). #[cfg(test)] pub fn instructions() -> Lib { - Lib::new(None, None) - } - - /// Whether the device's instructions are Metal's own functions in mode `mode`: MoltenVK in a - /// module Metal compiles in that mode ([`module_mode`]). - pub fn metal_in(&self, mode: Mode) -> bool { - self.metal == Some(mode) - } - - /// Whether the device's instructions are Metal's own functions in its fast mode: MoltenVK in a - /// module Metal compiles with fast math ([`module_mode`]), whose `Sin` and `Cos` are Metal's - /// `fast::sin` and `fast::cos` themselves, past their flush point too. - pub fn metal_fast(&self) -> bool { - self.metal_in(Mode::Fast) + Lib::new(None) } /// Metal's precise `fmod` of `x` and `y` (`float` lanes of form `f`) by its routine, one call diff --git a/crates/metal2vulkan/src/lower/arith/math.rs b/crates/metal2vulkan/src/lower/arith/math.rs index 63d7c3d55..90c7ad5fc 100644 --- a/crates/metal2vulkan/src/lower/arith/math.rs +++ b/crates/metal2vulkan/src/lower/arith/math.rs @@ -17,13 +17,13 @@ //! `FindUMsb`/`FindILsb` with the zero case, `rotate` and the funnel shifts with an in-range second //! shift (`(x >> 1) >> (N - 1 - s)`). A function no instruction is takes a composition of the //! device's instructions: `exp10` and `log10` of `Exp2` and `Log2`, `sinpi`, `cospi` and `tanpi` -//! by an exact period reduction around `Sin` and `Cos`, `ldexp` on the bits, and Metal's fast-math -//! formulas (MSL Table 8.2) for its `fast_` functions. The answers at special operands (a zero's -//! sign, a NaN's bits, an `f32` denormal) are the device's, recorded as precision notes at +//! by an exact period reduction around `Sin` and `Cos`, `ldexp` on the bits, and the fast-math +//! formulas (MSL Table 8.2) of `fast::exp`, `fast::log`, `fast::powr` and `fast::atan2`; every +//! other `fast_` function is the device's instruction for it. The answers at special operands (a +//! zero's sign, a NaN's bits, an `f32` denormal) are the device's, recorded as precision notes at //! selection, and so is every function whose Vulkan precision is looser than Metal's. use crate::air::intrinsics::PackFormat; -use crate::lower::arith::denormal; use crate::lower::arith::exact_division::{div_exact_lanes, per_lane}; use crate::lower::arith::legal::{FloatFmt, Form, Held}; use crate::lower::arith::libm::{self, Lib}; @@ -795,22 +795,17 @@ pub enum FloatFn { Sin, /// Metal's precise `cos`: within 4 ulp; as [`FloatFn::Sin`]. Cos, - /// `air.fast_sin` on `float`: [`FloatFn::Sin`], but `+0` past `float(π/2) · 2^22` and for an - /// infinity or NaN, as Metal answers (`fast_trig_flush`), of the device's `Sin`. Where its - /// functions are Metal's in its fast mode (`Lib::metal_fast`), the device's `Sin` is Metal's - /// `fast::sin` itself, which answers the flush, and no flush is added (every exponent's 4,096 - /// mantissas of both signs and the specials, 2,097,161 inputs, equal on an Apple M3 Max, macOS - /// 27.0.1). + /// `air.fast_sin` on `float`: the device's `Sin`, Metal's `fast::sin` itself where its + /// functions are Metal's in a fast-math module. Metal answers `+0` past `float(π/2) · 2^22` and + /// for an infinity or NaN; the device answers its `Sin` there. FastSin, - /// `air.fast_cos` on `float`: [`FloatFn::Cos`], but `+0` past `float(π/2) · 2^22` and for an - /// infinity or NaN, as Metal answers (`fast_trig_flush`); as [`FloatFn::FastSin`]. + /// `air.fast_cos` on `float`: the device's `Cos`; as [`FloatFn::FastSin`]. FastCos, /// Metal's precise `tan`: within 6 ulp; as [`FloatFn::Sin`]. Tan, - /// `air.fast_tan` on `float`: Metal's fast `tan`, the formula `sin(x) · (1 / cos(x))` of MSL - /// Table 8.2: the device's `Tan` where its functions are Metal's in a fast-math module, and - /// elsewhere the formula of [`FloatFn::FastSin`] and [`FloatFn::FastCos`] divided by the - /// device's division (`fast_tan`). + /// `air.fast_tan` on `float`: the device's `Tan`, Metal's `fast::tan` itself where its + /// functions are Metal's in a fast-math module (MSL Table 8.2 defines it as `sin(x) · (1 / + /// cos(x))`). FastTan, /// Metal's precise `asin`: within 4 ulp (MSL Table 8.1). The device's instruction, Metal's own /// where the device's functions are Metal's in a module compiled with precise functions @@ -829,21 +824,22 @@ pub enum FloatFn { FastAtan, /// Metal's precise `sinh`; as [`FloatFn::Exp`]. Sinh, - /// `air.fast_sinh` on `float`: `(exp(x) - exp(-x)) · 0.5` of Metal's fast `exp` (MSL Table - /// 8.2), or the device's `Sinh` where it is Metal's in a fast-math module. + /// `air.fast_sinh` on `float`: the device's `Sinh`, Metal's `fast::sinh` itself where its + /// functions are Metal's in a fast-math module (MSL Table 8.2 defines it as + /// `(exp(x) - exp(-x)) · 0.5`). FastSinh, /// Metal's precise `cosh`; as [`FloatFn::Exp`]. Cosh, - /// `air.fast_cosh` on `float`: `(exp(x) + exp(-x)) · 0.5`; as [`FloatFn::FastSinh`]. + /// `air.fast_cosh` on `float`: the device's `Cosh`; as [`FloatFn::FastSinh`]. FastCosh, /// Metal's precise `tanh` (within 5 ulp): the device's instruction, Metal's own where its /// functions are Metal's (SPIRV-Cross emits `precise::tanh` in either mode). Tanh, - /// `air.fast_tanh` on `float`: the MSL fast-math accuracy table defines it as the formula - /// `(t - 1) / (t + 1)` with `t = exp(2x)`, not as an accuracy bound, so it is a different - /// function from `tanh` (it is `NaN` once `t` overflows). Emitted as that formula with - /// `t = Exp2(x * 2 log2(e))` (`tanh_of_exp`), its quotient the device's division. Narrow - /// forms keep [`FloatFn::Tanh`]: the fast-math table is the single-precision one. + /// `air.fast_tanh` on `float`: the device's `Tanh`. MSL Table 8.2 defines Metal's as the + /// formula `(t - 1) / (t + 1)` with `t = exp(2x)`, which is `NaN` once `t` overflows, where the + /// device's `Tanh` answers `±1`; on a device whose functions are Metal's the instruction is + /// Metal's precise `tanh`. Narrow forms keep [`FloatFn::Tanh`]: the fast-math table is the + /// single-precision one. FastTanh, /// Metal's precise `asinh`; as [`FloatFn::Exp`]. Asinh, @@ -858,8 +854,9 @@ pub enum FloatFn { FastAcosh, /// Metal's precise `atanh`; as [`FloatFn::Exp`]. Atanh, - /// `air.fast_atanh` on `float`: `0.5 · log((1 + x) / (1 - x))` (MSL Table 8.2) with the - /// device's division, or the device's `Atanh` where it is Metal's in a fast-math module. + /// `air.fast_atanh` on `float`: the device's `Atanh`, Metal's `fast::atanh` itself where its + /// functions are Metal's in a fast-math module (MSL Table 8.2 defines it as + /// `0.5 · log((1 + x) / (1 - x))`). FastAtanh, /// Metal's `sinpi`: within 4 ulp (MSL Table 8.1). The exact reduction around the device's `Sin` /// and `Cos` (`pi_scaled`), as no instruction is it. @@ -878,20 +875,18 @@ pub enum FloatFn { Powr, /// `air.fast_powr` on `float`: `exp2(y · log2(x))` as Metal composes it, the product rounded. FastPowr, - /// Metal `pow`: C99 Annex F semantics (negative bases with integral exponents, the zero, - /// one, and infinity cases) around `GLSL.std.450 Pow` of the magnitude, as Metal answers - /// its special operands (`pow_special`). + /// Metal `pow`: C99 Annex F's special cases that `GLSL.std.450 Pow` leaves undefined (negative + /// bases with integral exponents, the zero, one, and NaN cases) around `Pow` of the magnitude + /// (`pow_special`). Pow, /// `air.fast_pow` on `float`: [`FloatFn::Pow`] around the magnitude `exp2(y · log2|x|)`, as - /// Metal composes it, except that a NaN base to the exponent one gives the canonical NaN - /// rather than itself. + /// Metal composes it. FastPow, - /// Metal `atan2(y, x)`: C99 Annex F's special values, as Metal answers them - /// (`atan2_special`), around the generic value, the device's `Atan2` (always `precise::atan2` - /// where its functions are Metal's). + /// Metal `atan2(y, x)`: C99 Annex F's special values (`atan2_special`) around the generic + /// value, the device's `Atan2` (always `precise::atan2` where its functions are Metal's). Atan2, - /// `air.fast_atan2` on `float`: `atan(y / x)` turned by `±π` when `x` is below zero, as Metal - /// answers it (`fast_atan2`): `0 / 0` and `inf / inf` are NaN, where `atan2` answers C99's + /// `air.fast_atan2` on `float`: `atan(y / x)` turned by `±π` when `x` is below zero, MSL Table + /// 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 @@ -1000,8 +995,7 @@ impl FloatFn { /// Whether the lowering answers Metal at `f32` denormal operands and results itself, whatever /// the device's denormal mode, or records the device's answer under another note, so it records - /// no `PrecisionNote::DeviceDenormals` of its own: `atan2`, which flushes a denormal generic - /// result, `ldexp` (on `float`, [`ldexp_bits`]), which reads a denormal operand as the zero of + /// no `PrecisionNote::DeviceDenormals` of its own: `ldexp` (on `float`, [`ldexp_bits`]), which reads a denormal operand as the zero of /// its sign and flushes a denormal result on the bits, `copysign`, which moves bits, and precise /// `fmod` on `float`, the remainder's routine, which reads a denormal divisor as a zero on the /// bits and computes the remainder in integers (`libm::fmod`), or on MoltenVK Metal's own; @@ -1012,15 +1006,12 @@ impl FloatFn { /// whose every denormal operand rounds to a zero, its sign the note's /// (`PrecisionNote::NativeTranscendentals`); and the device's instructions for Metal's /// functions: `fabs`, `sign`, `fract` and `fast::sqrt` ([`FloatFn::native_instruction`]), the - /// arc tangent family (`asin`, `acos`, and `atan`, both modes), precise `sin`, `cos`, and - /// `tan`, `sinpi`, `cospi`, and `tanpi`, and the second stage's functions, Metal's own where the - /// device's functions are Metal's, and elsewhere recording the device's denormals with their - /// precision (`PrecisionNote::NativeTranscendentals`). `fast::sin`, `fast::cos`, and - /// `fast::tan` keep a denormal operand as Metal does, where RADV, ANV, and NVIDIA flush it (case - /// cc234732), and the fast formulas' steps have no denormal intermediate on which their result - /// depends (`fast::sinh` of a denormal is `(1 - 1) · 0.5 = +0`, as Metal answers, case - /// f6524207). `fast::atan2` does not: its quotient is the device's division, whose operands - /// `denormal::coverage` reads. + /// trigonometric, hyperbolic and arc families in both modes, `sinpi`, `cospi`, and `tanpi`, + /// the exponentials and logarithms, and `pow`, `powr` and `atan2` with their special cases + /// (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. pub fn metal_denormals(self) -> bool { use FloatFn as F; matches!( @@ -1109,9 +1100,9 @@ impl FloatFn { self == FloatFn::Round } - /// Whether the lowering on lanes of format `fmt` records no NaN note of its own: the functions - /// that select their NaN (or answer a number for one: `saturate`, `fast::sin`, `fast::cos`), - /// `copysign`, which moves bits, `sign`, whose NaN answer is its instruction's + /// 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 /// ([`FloatFn::native_instruction`]), and the device's picks, `median3` and, on `float` and /// `half`, `fmin`, `fmax`, `min3`, `max3`, and `clamp`, which return an operand (two NaNs' /// answer is `PrecisionNote::NativeMinMax`'s where the device is not measured to pick @@ -1123,36 +1114,15 @@ impl FloatFn { } matches!( self, - F::Sign - | F::Saturate - | F::Median3 - | F::FastMedian3 - | F::CopySign - | F::Atan2 - | F::FastAtan2 { .. } - | F::Pow - | F::FastPow - | F::FastSin - | F::FastCos + F::Sign | F::Saturate | F::Median3 | F::FastMedian3 | F::CopySign ) } /// Whether the function divides by a device division besides its [`FloatFn::precision`] - /// class (`PrecisionNote::DeviceArithmetic`): `fast_tanh`'s quotient, whose divisor leaves - /// the range where Metal's fast division and Vulkan's `OpFDiv` bound their error (`2^-126` to - /// `2^126`) as `t` approaches overflow, `fast_atan2`'s `y / x` (the device's division), - /// `fast::tan`'s quotient of its sine by - /// its cosine, `fast::atanh`'s `(1 + x) / (1 - x)`, and `fast::tanpi`'s quotient where the - /// device's functions are Metal's. + /// class (`PrecisionNote::DeviceArithmetic`): `fast_atan2`'s `y / x` (the device's division) + /// and `fast::tanpi`'s quotient where the device's functions are Metal's. pub fn divides(self) -> bool { - matches!( - self, - FloatFn::FastTanh - | FloatFn::FastAtan2 { .. } - | FloatFn::FastTan - | FloatFn::FastAtanh - | FloatFn::FastTanPi - ) + matches!(self, FloatFn::FastAtan2 { .. } | FloatFn::FastTanPi) } /// Whether the function is lowered on 64-bit floats: `GLSL.std.450` offers the @@ -1210,8 +1180,8 @@ impl FloatFn { // And the infinite product's tests and select, on the same classification // (`fast_powr_special`). FloatFn::FastPowr => 208 + INFINITE_PRODUCT_WORDS, - // Metal's formulas of its fast `exp`, of two of the device's `exp2`. - FloatFn::FastSinh | FloatFn::FastCosh => 112, + // 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 @@ -1219,16 +1189,10 @@ impl FloatFn { // operand's flush test. FloatFn::Min | FloatFn::Max => 160, FloatFn::Clamp | FloatFn::Min3 | FloatFn::Max3 => 288, - // The device's remainder and, on `half`, the zero's tests and selects. - FloatFn::Fmod if f.float_fmt() == Some(FloatFmt::Half) => 192, // `|x|`, and C99's special cases around the magnitude (`pow_special`). FloatFn::Pow => 344, - // And `pow(x, 1)`'s flush of an `f32` denormal `x` (`pow_special`). - FloatFn::FastPow => 344 + INFINITE_PRODUCT_WORDS + denormal::flush_words(f), - // The magnitude's test against the last evaluated quadrant. - FloatFn::FastSin | FloatFn::FastCos => 48, - // Both flushes, the denormal operand's select, and the device's division. - FloatFn::FastTan => 176, + // And the infinite product's tests and select (`infinite_product`). + FloatFn::FastPow => 344 + INFINITE_PRODUCT_WORDS, // The special operands' tests and the selected constant's sign. FloatFn::Atan2 => 320, // The quotient, its special values and sign, and the turn. @@ -1244,11 +1208,6 @@ impl FloatFn { | FloatFn::FastTanPi => 384, // The tie correction of a bfloat fused multiply-add (`narrow::bf16_fma`). FloatFn::Fma if f.float_fmt() == Some(FloatFmt::BFloat) => 208, - // `t`, the quotient's operands, their `NoContraction` decorations, and the device's - // division. - FloatFn::FastTanh => 96, - // `1 ± x`, the device's division, and the halving. - FloatFn::FastAtanh => 112, // `exp10`'s composition of the device's `exp2` (`exp10`): five products and // sums, two fused ones, the device's `exp2`, and the ends' tests: 136 words on // `float4`. @@ -1261,21 +1220,12 @@ impl FloatFn { _ => 48, }; // Each function the call takes: the device's instruction, or precise `fmod`'s routine's - // calls, one per lane (the routine itself is the module's). A `half` function's zero - // select (`half_zero`), `half` `cospi`'s zero sign (`half_cospi_zero`), and `half` - // `asin`'s NaN sign (`half_signed_nan`). + // calls, one per lane (the routine itself is the module's). let base = base + libm::uses(self, f) .iter() .map(|r| libm::use_words(f.lanes, r.arity())) - .sum::() - + half_zero(self, f).map_or(0, |_| 24) - + if half && self == FloatFn::CosPi { - 96 - } else { - 0 - } - + if half_signed_nan(self, f) { 40 } else { 0 }; + .sum::(); let roundings = match self { _ if self.closed_on_narrow() => 0, FloatFn::Mix => 3, @@ -1288,8 +1238,9 @@ impl FloatFn { /// Emit float function `op` on `args` (floats of form `f`; `Ldexp`'s exponent is a held `i32` and /// `Dot` gives the scalar), by the device's instructions, and precise `fmod` by `lib`'s routine -/// where the module defines it. A `half` `fmod` answers Metal's zero remainder -/// (`half_fmod_zero`). +/// 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`). pub fn float_fn( fb: &mut FunctionBuilder<'_>, op: FloatFn, @@ -1313,20 +1264,7 @@ pub fn float_fn( } _ => narrow::round(fb, f, r)?, }; - let r = match half_zero(op, f) { - Some(zero) => half_zero_answer(fb, f, zero, arg(args, 0)?, r)?, - None => r, - }; - let r = if f.float_fmt() == Some(FloatFmt::Half) && op == F::CosPi { - half_cospi_zero(fb, f, arg(args, 0)?, r)? - } else { - r - }; - if half_signed_nan(op, f) { - half_signed_nan_answer(fb, f, arg(args, 0)?, r) - } else { - Ok(r) - } + Ok(r) } /// The `float` function a `half` call of `op` (form `f`, held in `float`) takes before its @@ -1345,100 +1283,6 @@ pub(crate) fn half_form(op: FloatFn, f: Form) -> FloatFn { } } -/// `r`, Metal's `half` `cospi(x)` (form `f`), with its zero's sign: at `x = n + 1/2` Metal -/// answers `-0` where `n = floor(x)` is even and `+0` where it is odd, the sign of -/// `-sinpi(x - 1/2)` of its `half` `sinpi`, whose zero at an odd integer is `-0` (each of the -/// 4,096 such `half` operands of our probes), where its `float` `cospi` answers -/// `+0`. `n` and `n / 2` are exact in the container. The zero is chosen in the bits: in a -/// fast-math entry (no `SignedZeroInfNanPreserve`) a float select between `-0` and `+0` may be -/// folded, and the RTX 3090 answered `-0` at the odd `n` of case 32931370. -fn half_cospi_zero(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, r: Value) -> BResult { - let u = u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let rb = fb.convert(ConvOp::Bitcast, r, ut)?; - let magnitude = splat(fb, u, 0x7FFF_FFFF)?; - let rm = bin(fb, BinOp::BitwiseAnd, rb, magnitude)?; - let uz = splat(fb, u, 0)?; - let zero = bin(fb, BinOp::IEqual, rm, uz)?; - let n = glsl(fb, GlslOp::Floor, &[x])?; - let half = fsplat(fb, f, 0.5)?; - let h = bin(fb, BinOp::FMul, n, half)?; - let hf = glsl(fb, GlslOp::Floor, &[h])?; - let even = bin(fb, BinOp::FOrdEqual, hf, h)?; - let minus = splat(fb, u, 0x8000_0000)?; - let signed = fb.select(even, minus, uz)?; - let b = fb.select(zero, signed, rb)?; - fb.convert(ConvOp::Bitcast, b, ft) -} - -/// Whether float function `op` on form `f` is Metal's `half` `asin`, whose NaN at `|x| > 1` has -/// `x`'s sign in both math modes (cases 48500c31 and 32931370), where its `float` precise `asin`'s, -/// which the routine and a device whose functions are Metal's answer, is the quiet NaN without a -/// sign (case 087758cb). -fn half_signed_nan(op: FloatFn, f: Form) -> bool { - f.float_fmt() == Some(FloatFmt::Half) && op == FloatFn::Asin -} - -/// `r`, the answer of a `half` function of `x` (form `f`), with `x`'s sign where `|x| > 1`. -fn half_signed_nan_answer( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - r: Value, -) -> BResult { - let ax = glsl(fb, GlslOp::FAbs, &[x])?; - let one = fsplat(fb, f, 1.0)?; - let domain = bin(fb, BinOp::FOrdGreaterThan, ax, one)?; - let signed = copysign(fb, f, r, x)?; - fb.select(domain, signed, r) -} - -/// Metal's answer for a zero operand of a `half` function where it is not its `float` -/// function's, which the device's instruction and the routines compute. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum HalfZero { - /// `+0`, whatever the zero's sign. - Positive, - /// The zero itself. - Operand, -} - -/// The [`HalfZero`] of float function `op` on form `f`, where it is measured: Metal's `half` -/// `sin`, `tan`, and `asin` of either zero are `+0`, and its `atan` of `-0` is `-0`, in both -/// math modes (the half probe, cases dc0fee8f and 3ef7c1c5), where its `float` `sin(-0)` and -/// `tan(-0)` are `-0`, precise `asin(-0)` is `-0`, and precise `atan(-0)` is `+0` (cases 087758cb -/// and cc234732); and its `half` `sinpi(-0)` is `-0`, where its `float` one is `+0`. `None` for any -/// other function or format. -fn half_zero(op: FloatFn, f: Form) -> Option { - if f.float_fmt() != Some(FloatFmt::Half) { - return None; - } - match op { - FloatFn::Sin | FloatFn::Tan | FloatFn::Asin => Some(HalfZero::Positive), - FloatFn::Atan | FloatFn::SinPi => Some(HalfZero::Operand), - _ => None, - } -} - -/// `r`, the answer of a `half` function of `x` (form `f`), with a zero operand's answer -/// `zero` selected (an operand is a zero when its widened value is: a `half` has no `f32` -/// denormal). -fn half_zero_answer( - fb: &mut FunctionBuilder<'_>, - f: Form, - zero: HalfZero, - x: Value, - r: Value, -) -> BResult { - let z = fsplat(fb, f, 0.0)?; - let at_zero = bin(fb, BinOp::FOrdEqual, x, z)?; - let answer = match zero { - HalfZero::Positive => z, - HalfZero::Operand => x, - }; - fb.select(at_zero, answer, r) -} - /// [`float_fn`] before the final rounding to a narrow format. fn float_fn_core( fb: &mut FunctionBuilder<'_>, @@ -1574,49 +1418,20 @@ fn float_fn_core( let c = wide_splat(fb, f, k)?; fb.binary_with(BinOp::FMul, l, c, Contraction::Forbidden) } - F::Sin => g1(fb, GlslOp::Sin), - F::Cos => g1(fb, GlslOp::Cos), - // Where the device's instruction is Metal's own `fast::sin` or `fast::cos` (a fast-math - // module on MoltenVK), it answers Metal's `+0` past the flush point and at an infinity or - // NaN itself: no flush is added. - F::FastSin | F::FastCos if lib.metal_fast() => { - let o = if op == F::FastSin { - GlslOp::Sin - } else { - GlslOp::Cos - }; - g1(fb, o) - } - F::FastSin => { - let r = g1(fb, GlslOp::Sin)?; - fast_trig_flush(fb, f, a, r) - } - F::FastCos => { - let r = g1(fb, GlslOp::Cos)?; - fast_trig_flush(fb, f, a, r) - } - F::Tan => g1(fb, GlslOp::Tan), - F::FastTan => fast_tan(fb, f, a, lib), + // The device's instructions in both modes, Metal's fast functions where its functions are + // Metal's in a fast-math module (`libm::Fun::device_answers`). + F::Sin | F::FastSin => g1(fb, GlslOp::Sin), + F::Cos | F::FastCos => g1(fb, GlslOp::Cos), + F::Tan | F::FastTan => g1(fb, GlslOp::Tan), F::Asin | F::FastAsin => g1(fb, GlslOp::Asin), F::Acos | F::FastAcos => g1(fb, GlslOp::Acos), F::Atan | F::FastAtan => g1(fb, GlslOp::Atan), - F::Sinh => g1(fb, GlslOp::Sinh), - F::Cosh => g1(fb, GlslOp::Cosh), - F::Tanh => g1(fb, GlslOp::Tanh), - F::Asinh => g1(fb, GlslOp::Asinh), - F::Acosh => g1(fb, GlslOp::Acosh), - F::Atanh => g1(fb, GlslOp::Atanh), - // A device whose functions are Metal's in a fast-math module: its instruction is Metal's - // fast function. Elsewhere Metal's formula (MSL Table 8.2). - F::FastSinh if lib.metal_in(libm::Mode::Fast) => g1(fb, GlslOp::Sinh), - F::FastCosh if lib.metal_in(libm::Mode::Fast) => g1(fb, GlslOp::Cosh), - F::FastSinh | F::FastCosh => fast_sinh_cosh(fb, op, f, a), - // The device's instructions, Metal's fast functions where its functions are Metal's in a - // fast-math module. - F::FastAsinh => g1(fb, GlslOp::Asinh), - F::FastAcosh => g1(fb, GlslOp::Acosh), - F::FastTanh => fast_tanh(fb, f, a), - F::FastAtanh => fast_atanh(fb, f, a, lib), + F::Sinh | F::FastSinh => g1(fb, GlslOp::Sinh), + F::Cosh | F::FastCosh => g1(fb, GlslOp::Cosh), + F::Tanh | F::FastTanh => g1(fb, GlslOp::Tanh), + F::Asinh | F::FastAsinh => g1(fb, GlslOp::Asinh), + F::Acosh | F::FastAcosh => g1(fb, GlslOp::Acosh), + F::Atanh | F::FastAtanh => g1(fb, GlslOp::Atanh), F::SinPi | F::CosPi | F::TanPi | F::FastSinPi | F::FastCosPi | F::FastTanPi => { let which = match op { F::SinPi | F::FastSinPi => PiScaled::Sin, @@ -1661,7 +1476,7 @@ fn float_fn_core( let r = exp2_of_product(fb, y, ax)?; infinite_product(fb, f, y, ax, r)? }; - pow_special(fb, f, a, y, magnitude, op == F::Pow) + pow_special(fb, f, a, y, magnitude) } F::Atan2 => { let x = arg(args, 1)?; @@ -1710,42 +1525,6 @@ fn wide_splat(fb: &mut FunctionBuilder<'_>, f: Form, k: f64) -> BResult { // ---- Metal's functions at their special operands ---- -/// Whether lanes of `x` (floats of form `f`) are zeros or denormals of an `f32`: Metal's `float` -/// functions read an operand whose exponent field is zero as a zero (its denormals are flushed, -/// A1 cases aed3faaa, 87d13612, and f9a12252). Decided on the exponent field, so the answer is -/// the same whatever the device's own denormal mode. `None` for another format: a widened `half` -/// is never an `f32` denormal, and whether Metal flushes `bfloat` denormals is not measured. -fn flushed(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult> { - if f.float_fmt() != Some(FloatFmt::F32) { - return Ok(None); - } - let u = u32_form(f); - let ut = ty(fb, u)?; - let bits = fb.convert(ConvOp::Bitcast, x, ut)?; - let exp = splat(fb, u, 0x7F80_0000)?; - let e = bin(fb, BinOp::BitwiseAnd, bits, exp)?; - let zero = splat(fb, u, 0)?; - Ok(Some(bin(fb, BinOp::IEqual, e, zero)?)) -} - -/// Whether lanes of `x` (floats of form `f`) are `f32` denormals: a nonzero magnitude whose -/// exponent field is zero, told by the bits whatever the device's own denormal mode. `None` for -/// another format, as [`flushed`]. -fn denormal_lanes(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult> { - if f.float_fmt() != Some(FloatFmt::F32) { - return Ok(None); - } - let u = u32_form(f); - let ut = ty(fb, u)?; - let bits = fb.convert(ConvOp::Bitcast, x, ut)?; - let magnitude = splat(fb, u, 0x7FFF_FFFF)?; - let a = bin(fb, BinOp::BitwiseAnd, bits, magnitude)?; - let one = splat(fb, u, 1)?; - let below = bin(fb, BinOp::ISub, a, one)?; - let largest = splat(fb, u, 0x007F_FFFF)?; - Ok(Some(bin(fb, BinOp::ULessThan, below, largest)?)) -} - /// Whether lanes of `x` (floats of form `f`, held in a 32-bit container) have the bits `bits`: /// an integer comparison, which no float mode lets a device fold. fn has_bits(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, bits: u64) -> BResult { @@ -1782,12 +1561,12 @@ fn half_fmod_zero(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, r: Value) -> } /// The classes of `powr`'s operands `x` and `y` (floats of form `f`, a `float` or a `half` in its -/// 32-bit container) that its special cases read, each told once from the bits and shared by -/// every rule that reads it: each operand's bits and magnitude's, whether it is a zero to Metal (an -/// `f32` denormal is one, [`metal_zero`]) and an infinity of either sign, and whether `x` is one. -/// Integer comparisons, which no float mode folds. +/// 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 +/// ([`is_zero`]: an `f32` denormal is one where the device reads it so), whether it is an infinity +/// of either sign and whether `x` is one, the last two by integer comparisons of the bits, which +/// no float mode folds. struct PowrOperands { - x_bits: Value, x_magnitude: Value, x_zero: Value, x_inf: Value, @@ -1807,14 +1586,7 @@ impl PowrOperands { let class = |fb: &mut FunctionBuilder<'_>, v: Value| -> BResult<[Value; 4]> { let b = fb.convert(ConvOp::Bitcast, v, ut)?; let m = bin(fb, BinOp::BitwiseAnd, b, magnitude)?; - let zero = match f.float_fmt() { - // The exponent field zero: the magnitude below the least normal's. - Some(FloatFmt::F32) => { - let normal = splat(fb, u, 0x0080_0000)?; - bin(fb, BinOp::ULessThan, m, normal)? - } - _ => metal_zero(fb, f, v)?, - }; + let zero = is_zero(fb, f, v)?; let is_inf = bin(fb, BinOp::IEqual, m, inf)?; Ok([b, m, zero, is_inf]) }; @@ -1823,7 +1595,6 @@ impl PowrOperands { let one = splat(fb, u, u64::from(1f32.to_bits()))?; let x_one = bin(fb, BinOp::IEqual, x_bits, one)?; Ok(Self { - x_bits, x_magnitude, x_zero, x_inf, @@ -1875,16 +1646,15 @@ impl PowrOperands { } } -/// `powr(x, y)`'s result `r` (floats of form `f`) with Metal's canonical NaN where Metal's -/// `exp2(y * log2(x))` is a NaN for finite or infinite operands: `x` below zero (`-inf` included), -/// `y` zero with `x` a zero or an infinity (`0 * inf`), and `y` infinite with `x` one (`inf * 0`). -/// Devices answer `0` or `1` there (`GLSL.std.450 Pow` leaves `x < 0` and `x = 0, y <= 0` -/// undefined). The operands' classes are read from the bits once ([`PowrOperands`]), and an `f32` -/// denormal operand is a zero ([`metal_zero`]) to the zero tests, as Metal reads it. Metal's -/// precise `powr` reads the sign from the bits: a negative denormal's is NaN (case 7b283404 and -/// f6524207's `powr(-2^-149, 0.5)`, the M3 and the M4); its `fast::powr` is [`fast_powr_special`]. -/// `float` and `half` (whose NaN lanes are the same rule's, `nan_half` and `nan_half_fast`, every -/// lane); `bfloat` keeps `r` (not measured). +/// `powr(x, y)`'s result `r` (floats of form `f`) with a quiet NaN where MSL's `powr`, `exp2(y * +/// log2(x))` for `x >= 0`, is a NaN for operands that are not NaNs: `x` below zero (`-inf` +/// included), `y` zero with `x` a zero or an infinity (`0 * inf`), and `y` infinite with `x` one +/// (`inf * 0`). Devices answer `0` or `1` there (`GLSL.std.450 Pow` leaves `x < 0` and `x = 0, +/// y <= 0` undefined), so the NaN is a capability the device lacks, not an answer it gives +/// otherwise. The operands are classed once ([`PowrOperands`]), by the device's comparisons: an +/// `f32` denormal is a zero, or below zero, as the device reads it (`PrecisionNote::DeviceDenormals` +/// where it is not measured to read it as Metal does). `float` and `half`; `bfloat` keeps `r` +/// (not measured). pub(super) fn powr_nan( fb: &mut FunctionBuilder<'_>, f: Form, @@ -1896,20 +1666,22 @@ pub(super) fn powr_nan( return Ok(r); } let c = PowrOperands::of(fb, f, x, y)?; - // The sign bit of a nonzero `x`, a denormal's and a NaN's included: the bits above `-0`'s. - let minus_zero = splat(fb, u32_form(f), 0x8000_0000)?; - let negative = bin(fb, BinOp::UGreaterThan, c.x_bits, minus_zero)?; + let negative = below_zero(fb, f, x)?; let log_infinite = c.log_infinite(fb)?; let nan = c.nan(fb, negative, log_infinite)?; let k = fsplat(fb, f, f64::NAN)?; fb.select(nan, k, r) } +/// Whether lanes of `x` (floats of form `f`) are below zero by the device's comparison. +fn below_zero(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { + let z = fsplat(fb, f, 0.0)?; + bin(fb, BinOp::FOrdLessThan, x, z) +} + /// Metal's `fast::powr(x, y)` around `r`, the composition's `exp2(y · log2(x))` -/// ([`exp2_of_product`]): [`powr_nan`]'s NaN where `x` is below zero as `fast::powr` reads it -/// (a negative `f32` denormal is a zero, so `fast::powr(-2^-149, 0.5)` is `+0`, case f6524207 on -/// the M3 and the M4), over [`infinite_product`]'s IEEE value, both on one classification of the -/// operands ([`PowrOperands`]). The infinite product is selected wherever `log2(x)` or `y` is +/// ([`exp2_of_product`]): [`powr_nan`]'s NaN, over [`infinite_product`]'s IEEE value, both on one +/// classification of the operands ([`PowrOperands`]). The infinite product is selected wherever `log2(x)` or `y` is /// infinite and neither operand is a NaN: the lanes of those where the product is `0 · inf`, and /// those of a negative `x`, are the NaN rule's, which overrides them. `float` and `half`; `bfloat` /// keeps `r` (not measured). @@ -1924,15 +1696,7 @@ pub(super) fn fast_powr_special( return Ok(r); } let c = PowrOperands::of(fb, f, x, y)?; - // `x` below zero and not a zero to Metal, compared as `fast::powr` compares: an `f32` at or - // below the negative least normal (so neither a denormal nor a zero), a `half` below zero. - let negative = if f.float_fmt() == Some(FloatFmt::F32) { - let least = fsplat(fb, f, -f64::from(f32::MIN_POSITIVE))?; - bin(fb, BinOp::FOrdLessThanEqual, x, least)? - } else { - let z = fsplat(fb, f, 0.0)?; - bin(fb, BinOp::FOrdLessThan, x, z)? - }; + let negative = below_zero(fb, f, x)?; let log_infinite = c.log_infinite(fb)?; let nan = c.nan(fb, negative, log_infinite)?; let infinite = bin(fb, BinOp::LogicalOr, log_infinite, c.y_inf)?; @@ -1944,17 +1708,6 @@ pub(super) fn fast_powr_special( fb.select(nan, k, r) } -/// `r`, with `+0` in the lanes where `x` is [`flushed`]. -fn zero_where_flushed(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, r: Value) -> BResult { - match flushed(fb, f, x)? { - Some(t) => { - let z = fsplat(fb, f, 0.0)?; - fb.select(t, z, r) - } - None => Ok(r), - } -} - /// Metal's `fract(x)`: the device's `Fract`, rounded once to a narrow format, then bounded below /// one, as Metal defines it (`fmin(x - floor(x), 0x1.fffffep-1)`): the largest value below one of /// the format wherever the difference reaches one (`-1e-10` gives `1 - 2^-24`, not `1`). The @@ -1992,125 +1745,6 @@ pub fn metal_picks(fmt: Option) -> bool { matches!(fmt, Some(FloatFmt::F32 | FloatFmt::Half)) } -/// The largest magnitude Metal's `fast::sin` and `fast::cos` evaluate: `float(π/2) · 2^22` -/// (`0x4ac90fdb`), past which the quadrant index no longer fits in 22 bits. -pub(super) const FAST_TRIG_LIMIT: f32 = 6_588_397.5; - -/// Metal's `fast::sin(x)` or `fast::cos(x)` from `r`, the device's `GLSL.std.450 Sin` or `Cos` of -/// `x` (or its routine), where the device's instruction is not Metal's own fast function -/// (`Lib::metal_fast`): `+0` where `|x|` is past [`FAST_TRIG_LIMIT`] or `x` is NaN (an unordered -/// compare), `r` elsewhere. Measured on Apple M3 Max: `fast::cos(6588397.5)` tracks -/// `precise::cos` and the next float answers `0` (the old engine's bisection), every lane of probe -/// case 08bc6611 past the limit (158, infinities and NaNs among them) answers `+0` for both, -/// whatever the sign, and A1 cases 179b6aa6, 3c92eb70, and 1f239ba7 read the flush. Below the -/// limit the two are the precise functions within a few ulp (the device's, -/// `PrecisionNote::DeviceTranscendentals`). -pub(super) fn fast_trig_flush( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - r: Value, -) -> BResult { - let ax = glsl(fb, GlslOp::FAbs, &[x])?; - let limit = wide_splat(fb, f, f64::from(FAST_TRIG_LIMIT))?; - let past = bin(fb, BinOp::FUnordGreaterThan, ax, limit)?; - let zero = wide_splat(fb, f, 0.0)?; - fb.select(past, zero, r) -} - -/// Metal's `fast::tanh(x)` ([`FloatFn::FastTanh`]) on `float` lanes `x` (form `f`): -/// [`tanh_of_exp`] of `t = exp2(x · 2 log2 e)`, the device's `Exp2`, its quotient the device's -/// division. -pub(super) fn fast_tanh(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { - // One operation to Metal: no step of it is fused or regrouped (`tanh_of_exp`). - let k = wide_splat(fb, f, 2.0 * std::f64::consts::LOG2_E)?; - let x = fb.binary_with(BinOp::FMul, x, k, Contraction::Forbidden)?; - let t = glsl(fb, GlslOp::Exp2, &[x])?; - tanh_of_exp(fb, f, &device_quotient, t) -} - -/// The device's `OpFDiv(n, d)`, rounded on its own: the quotient of Metal's fast formulas. -fn device_quotient(fb: &mut FunctionBuilder<'_>, n: Value, d: Value) -> BResult { - fb.binary_with(BinOp::FDiv, n, d, Contraction::Forbidden) -} - -/// Metal's `fast::atanh(x)` ([`FloatFn::FastAtanh`]) on `float` lanes `x` (form `f`): the -/// device's `Atanh` where `lib` says its functions are Metal's in a fast-math module; elsewhere -/// MSL Table 8.2's `0.5 · log((1 + x) · rcp(1 - x))`, the quotient the device's division and the -/// logarithm Metal's fast `log` of the device's `log2` ([`fast_log_of`]), each step its own. The -/// formula answers Metal's specials: a zero and a denormal give `+0`, `±1` gives `±inf`, and an -/// infinity gives NaN (`inf · 0`) (case f6524207's special lanes). -pub(super) fn fast_atanh( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - lib: &Lib, -) -> BResult { - if lib.metal_in(libm::Mode::Fast) { - return glsl(fb, GlslOp::Atanh, &[x]); - } - let exact = Contraction::Forbidden; - let one = wide_splat(fb, f, 1.0)?; - let num = fb.binary_with(BinOp::FAdd, one, x, exact)?; - let den = fb.binary_with(BinOp::FSub, one, x, exact)?; - let q = device_quotient(fb, num, den)?; - let l = fast_log_of(fb, f, q)?; - let half = wide_splat(fb, f, 0.5)?; - fb.binary_with(BinOp::FMul, half, l, exact) -} - -/// Metal's `fast::tan(x)` on `float` lanes `x` (form `f`, [`FloatFn::FastTan`]): the device's `Tan` -/// where `lib` says its functions are Metal's in a fast-math module; elsewhere Apple's formula -/// `sin(x) · (1 / cos(x))` (MSL Table 8.2) of Metal's fast sine and cosine, each the device's -/// instruction with Metal's flush past the last evaluated quadrant ([`fast_trig_flush`]), their -/// quotient the device's division. A denormal `x` is its own `fast::tan`, as Metal keeps it. -pub(super) fn fast_tan( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - lib: &Lib, -) -> BResult { - if lib.metal_in(libm::Mode::Fast) { - return glsl(fb, GlslOp::Tan, &[x]); - } - let fast = |fb: &mut FunctionBuilder<'_>, o: GlslOp| -> BResult { - let v = glsl(fb, o, &[x])?; - fast_trig_flush(fb, f, x, v) - }; - let sin = fast(fb, GlslOp::Sin)?; - let cos = fast(fb, GlslOp::Cos)?; - let r = device_quotient(fb, sin, cos)?; - match denormal_lanes(fb, f, x)? { - Some(d) => fb.select(d, x, r), - None => Ok(r), - } -} - -/// `(t - 1) / (t + 1)`: `tanh(x)` from `t = exp(2x)`, the MSL fast-math definition of -/// `fast::tanh`, divided by `divide` (the device's division): Metal's own fast division gives `0` -/// past `x ≈ 43.7`, where `t + 1` passes `2^126` and its reciprocal flushes (A1 case a919193f), -/// and `t = +inf` gives NaN past `x ≈ 44.4`, where the device's division may answer otherwise -/// (`PrecisionNote::NativeDivision`). -/// -/// `air.fast_tanh` is one operation to Metal, whatever the call's fast-math flags, so every step -/// here (and `x · 2 log2 e` before it) is `NoContraction`: the device rounds each on its own and -/// never fuses or regroups one with the caller's arithmetic. Mesa's `lower_flrp` rule (`1 + c · -/// (b - 1)` to `(1 - c) + b · c`) took a caller's `1 + tanh(x)` with the quotient's steps and -/// answered `t` for it, where Metal's `1 + tanh(-24.65)` is `0`: RC3 cases e72f550f and 2d5f3949's -/// `gelu(-8)` was `0.5 · x · t` on RADV and x86 lavapipe, not Metal's `-0`. -pub(super) fn tanh_of_exp( - fb: &mut FunctionBuilder<'_>, - f: Form, - divide: DivideOf<'_>, - t: Value, -) -> BResult { - let exact = Contraction::Forbidden; - let one = wide_splat(fb, f, 1.0)?; - let num = fb.binary_with(BinOp::FSub, t, one, exact)?; - let den = fb.binary_with(BinOp::FAdd, t, one, exact)?; - divide(fb, num, den) -} - /// A division of two values of one form: the device's (a unit test substitutes a reference). pub(super) type DivideOf<'a> = &'a dyn Fn(&mut FunctionBuilder<'_>, Value, Value) -> BResult; @@ -2387,66 +2021,30 @@ fn log10(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { fb.select(inside, close, far) } -/// Metal's `fast::sinh(x)` or `fast::cosh(x)` (`op`) on `float` lanes `x` (form `f`): MSL Table -/// 8.2's `(e(x) - e(-x)) · 0.5` and `(e(x) + e(-x)) · 0.5` of its fast `exp`, -/// `e(v) = exp2(v · log2 e)` (the device's `Exp2`; `-x · log2 e` is the product negated). One -/// operation to Metal: no step is fused with another or with the caller's arithmetic. On case -/// f6524207 the formula of correctly rounded `exp2` matches Metal on 768 and 822 of 1,024 lanes, -/// every special one among them (a zero and a denormal give `+0` and `1`, an infinity `±inf` and -/// `+inf`); the rest is Metal's `exp2`, which is not correctly rounded. -fn fast_sinh_cosh(fb: &mut FunctionBuilder<'_>, op: FloatFn, f: Form, x: Value) -> BResult { - let exact = Contraction::Forbidden; - let k = wide_splat(fb, f, std::f64::consts::LOG2_E)?; - let p = fb.binary_with(BinOp::FMul, x, k, exact)?; - let up = glsl(fb, GlslOp::Exp2, &[p])?; - let n = fb.unary(UnOp::FNegate, p)?; - let down = glsl(fb, GlslOp::Exp2, &[n])?; - let combine = if op == FloatFn::FastSinh { - BinOp::FSub - } else { - BinOp::FAdd - }; - let s = fb.binary_with(combine, up, down, exact)?; - let half = wide_splat(fb, f, 0.5)?; - fb.binary_with(BinOp::FMul, s, half, exact) -} - -/// Metal's fast `log(v)` of `float` lanes `v` (form `f`): `log2(v) · ln 2` of the device's -/// `Log2`, each step its own. -fn fast_log_of(fb: &mut FunctionBuilder<'_>, f: Form, v: Value) -> BResult { - let l = glsl(fb, GlslOp::Log2, &[v])?; - let c = wide_splat(fb, f, std::f64::consts::LN_2)?; - fb.binary_with(BinOp::FMul, l, c, Contraction::Forbidden) -} - /// The C99 Annex F (F.9.4.4) special cases of `pow(x, y)` around `magnitude`, the value -/// `GLSL.std.450 Pow(|x|, y)` gives, as Metal answers them (A1 case 116e052a, every lane of -/// precise `float`, fast `float`, and `half`). Later selects win: +/// `GLSL.std.450 Pow(|x|, y)` gives, which `Pow` leaves undefined (a negative base, a zero base to +/// `y <= 0`) or whose sign it cannot give (a negative base to an odd integer). Later selects win: /// /// - `pow(±0, y)` is `+inf` for `y < 0` and `+0` for `y > 0` (signed for odd integral `y`); -/// an `f32` denormal base is a zero ([`flushed`]); /// - `pow(-1, y)` is `1` for integral or infinite `y` (odd integers negate below); -/// - a negative base to an odd integer negates; a negative finite nonzero base (not an `f32` -/// denormal, which is `-0`) to a non-integral finite exponent is NaN; -/// - a NaN operand gives the canonical NaN (`0x7fc00000`, a `half` `0x7e00`), whatever its -/// payload or sign: this overrides the zero-base and `-1` results, because C99 makes -/// `pow(±0, NaN)` and `pow(-1, NaN)` NaN, and it does not trust `Pow` to propagate a NaN; -/// - `pow(x, 1)` is `x` for every other `x`, and precise `pow` on `float` (`precise`, not -/// `half`) keeps a NaN `x` itself, bit for bit (`pow(-NaN, 1)` is `0xffc00000`, where -/// `fast::pow` and `half` answer the canonical NaN); `fast::pow` reads an `f32` denormal `x` -/// as the zero of its sign there (`fast::pow(-2^-149, 1)` is `-0`), where precise `pow` -/// answers the denormal itself (the denormal probes' `pow` word, cases 638c7906 and -/// c9b6bacb, on the M3 Max and the M4); +/// - a negative base to an odd integer negates (the sign bit, so `-0` and `-inf` count); a +/// negative finite nonzero base to a non-integral finite exponent is a quiet NaN, which the +/// device's `Pow` does not define; +/// - a NaN operand gives a NaN, overriding the zero-base and `-1` results (C99 makes +/// `pow(±0, NaN)` and `pow(-1, NaN)` NaN, and `Pow` is not bound to propagate one): the device's +/// own NaN of the operands ([`device_nan`]), its sign and payload the device's; /// - `pow(+1, y)` is `1` for every `y`, even a NaN; -/// - `pow(x, ±0)` is `1` for every `x`, even a NaN, and so is `pow(x, y)` for an `f32` -/// denormal `y` ([`flushed`]). +/// - `pow(x, ±0)` is `1` for every `x`, even a NaN. +/// +/// Zeros and signs are the device's comparisons: an `f32` denormal is a zero, or below zero, as +/// the device reads it (`PrecisionNote::DeviceDenormals` where it is not measured to read it as +/// Metal does). Every other operand, `pow(x, 1)` included, is the device's `Pow`. pub(super) fn pow_special( fb: &mut FunctionBuilder<'_>, f: Form, x: Value, y: Value, magnitude: Value, - precise: bool, ) -> BResult { let c = |fb: &mut FunctionBuilder<'_>, k: f64| wide_splat(fb, f, k); let (zero, one, half) = (c(fb, 0.0)?, c(fb, 1.0)?, c(fb, 0.5)?); @@ -2455,13 +2053,6 @@ pub(super) fn pow_special( c(fb, f64::NEG_INFINITY)?, c(fb, f64::NAN)?, ); - // Whether an operand is a zero (an `f32` denormal is one to Metal). - let is_zero = |fb: &mut FunctionBuilder<'_>, v: Value| -> BResult { - match flushed(fb, f, v)? { - Some(t) => Ok(t), - None => bin(fb, BinOp::FOrdEqual, v, zero), - } - }; // y integral; y odd (an odd integer halves to a fraction of exactly one half). let ty_ = glsl(fb, GlslOp::Trunc, &[y])?; let yint = bin(fb, BinOp::FOrdEqual, ty_, y)?; @@ -2469,7 +2060,7 @@ pub(super) fn pow_special( let fr = glsl(fb, GlslOp::Fract, &[hy])?; let yodd = bin(fb, BinOp::FOrdEqual, fr, half)?; // Zero base. - let xz = is_zero(fb, x)?; + let xz = is_zero(fb, f, x)?; let yneg = bin(fb, BinOp::FOrdLessThan, y, zero)?; let zb = fb.select(yneg, inf, zero)?; let base = fb.select(xz, zb, magnitude)?; @@ -2478,66 +2069,47 @@ pub(super) fn pow_special( let x1 = bin(fb, BinOp::FOrdEqual, ax, one)?; let base = fb.select(x1, one, base)?; // The sign bit of x (so -0 and -inf count). - let u = narrow::u32_form(f); - let ut = ty(fb, u)?; - let xb = fb.convert(ConvOp::Bitcast, x, ut)?; - let k31 = splat(fb, u, 31)?; - let sb = bin(fb, BinOp::ShiftRightLogical, xb, k31)?; - let uz = splat(fb, u, 0)?; - let sneg = bin(fb, BinOp::INotEqual, sb, uz)?; + let sneg = sign_set(fb, f, x)?; let flip = bin(fb, BinOp::LogicalAnd, sneg, yodd)?; let nb = fb.unary(UnOp::FNegate, base)?; let r = fb.select(flip, nb, base)?; - // A negative finite nonzero base to a non-integral exponent (a negative `f32` denormal is - // `-0` to Metal, so `pow` of it answers as the zero base does). + // A negative finite nonzero base to a non-integral exponent. let xneg = bin(fb, BinOp::FOrdLessThan, x, zero)?; let xfin = bin(fb, BinOp::FOrdGreaterThan, x, ninf)?; let fractional = fb.unary(UnOp::LogicalNot, yint)?; - let nonzero = fb.unary(UnOp::LogicalNot, xz)?; let bad = bin(fb, BinOp::LogicalAnd, xneg, xfin)?; let bad = bin(fb, BinOp::LogicalAnd, bad, fractional)?; - let bad = bin(fb, BinOp::LogicalAnd, bad, nonzero)?; let r = fb.select(bad, nan, r)?; - // NaN operands give the canonical NaN (after the zero-base and -1 cases, which they + // NaN operands give the device's NaN (after the zero-base and -1 cases, which they // override). let ynan = fb.unary(UnOp::IsNan, y)?; let xnan = fb.unary(UnOp::IsNan, x)?; let any_nan = bin(fb, BinOp::LogicalOr, xnan, ynan)?; - let r = fb.select(any_nan, nan, r)?; - // pow(x, 1) = x, an `f32` denormal `x` flushed under `fast::pow`. - let y1 = bin(fb, BinOp::FOrdEqual, y, one)?; - let keep = if precise && f.float_fmt() != Some(FloatFmt::Half) { - y1 - } else { - let number = fb.unary(UnOp::LogicalNot, xnan)?; - bin(fb, BinOp::LogicalAnd, y1, number)? - }; - let kept = if !precise && f.float_fmt() == Some(FloatFmt::F32) { - denormal::flush(fb, f, x)? - } else { - x - }; - let r = fb.select(keep, kept, r)?; + let operand_nan = device_nan(fb, x, y)?; + let r = fb.select(any_nan, operand_nan, r)?; let xp1 = bin(fb, BinOp::FOrdEqual, x, one)?; let r = fb.select(xp1, one, r)?; - let y0 = is_zero(fb, y)?; + let y0 = is_zero(fb, f, y)?; fb.select(y0, one, r) } -/// Whether lanes of `v` (floats of form `f`) are zeros to Metal: either zero, and an `f32` -/// denormal ([`flushed`]). -fn metal_zero(fb: &mut FunctionBuilder<'_>, f: Form, v: Value) -> BResult { - match flushed(fb, f, v)? { - Some(t) => Ok(t), - None => { - let zero = wide_splat(fb, f, 0.0)?; - bin(fb, BinOp::FOrdEqual, v, zero) - } - } +/// Whether lanes of `v` (floats of form `f`) are zeros by the device's comparison, either sign: +/// an `f32` denormal is one where the device reads it as zero (`PrecisionNote::DeviceDenormals` +/// where it is not measured to read it as Metal does). +fn is_zero(fb: &mut FunctionBuilder<'_>, f: Form, v: Value) -> BResult { + let zero = wide_splat(fb, f, 0.0)?; + bin(fb, BinOp::FOrdEqual, v, zero) } -/// Whether the sign bit of `v` (floats of form `f`, held in an `f32` container) is set, so `-0`, -/// a negative denormal, and `-inf` count. +/// A NaN of the device's arithmetic from operands `a` and `b`, at least one of them a NaN: their +/// sum, whose NaN propagation (sign and payload) is the device's own +/// (`PrecisionNote::NativeNanEncoding` where it is not measured to be Metal's). +fn device_nan(fb: &mut FunctionBuilder<'_>, a: Value, b: Value) -> BResult { + fb.binary_with(BinOp::FAdd, a, b, Contraction::Forbidden) +} + +/// Whether the sign bit of `v` (floats of form `f`, held in an `f32` container) is set, so `-0` +/// and `-inf` count: the sign of a zero, which no comparison tells. fn sign_set(fb: &mut FunctionBuilder<'_>, f: Form, v: Value) -> BResult { let u = narrow::u32_form(f); let ut = ty(fb, u)?; @@ -2560,13 +2132,15 @@ fn sign_set(fb: &mut FunctionBuilder<'_>, f: Form, v: Value) -> BResult { /// - an infinite `y` gives `±π/4` toward `+inf`, `±3π/4` toward `-inf`, and `±π/2` otherwise; /// - a finite nonzero `y` gives `±π/2` over a zero `x`, `±0` toward `+inf`, and `±π` toward /// `-inf`; -/// - a NaN operand gives the canonical NaN (`0x7fc00000`, a `half` `0x7e00`). +/// - a NaN operand gives a NaN, the device's own of the operands ([`device_nan`]): `Atan2` is not +/// bound to propagate one. /// /// The constants are `π`, `π/2`, `π/4`, and `3π/4` correctly rounded to the format (Metal's /// answers: `0x40490fdb`, `0x3fc90fdb`, `0x3f490fdb`, `0x4016cbe4`; `half` `0x4248`, `0x3e48`, -/// `0x3a48`, `0x40b6`, which the final rounding gives from the `f32` constants). On `float` an -/// `f32` denormal operand is a zero and a generic answer of an `f32` denormal (or zero) is `+0`, -/// whatever its sign (`atan2(-1, FLT_MAX)` is `+0`); a `half` keeps its denormals. +/// `0x3a48`, `0x40b6`, which the final rounding gives from the `f32` constants). A zero is told by +/// the device's comparison, so an `f32` denormal operand is a zero where the device reads it so +/// (`PrecisionNote::DeviceDenormals` where it is not measured to read it as Metal does), and the +/// generic answer, a denormal among them, is the device's `Atan2`. pub(super) fn atan2_special( fb: &mut FunctionBuilder<'_>, f: Form, @@ -2578,9 +2152,7 @@ pub(super) fn atan2_special( let c = |fb: &mut FunctionBuilder<'_>, k: f64| wide_splat(fb, f, k); let (zero, half_pi, pi) = (c(fb, 0.0)?, c(fb, FRAC_PI_2)?, c(fb, PI)?); let (quarter, three_quarters) = (c(fb, FRAC_PI_4)?, c(fb, 3.0 * FRAC_PI_4)?); - let nan = c(fb, f64::NAN)?; - let r = zero_where_flushed(fb, f, generic, generic)?; - let (yz, xz) = (metal_zero(fb, f, y)?, metal_zero(fb, f, x)?); + 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 xneg = sign_set(fb, f, x)?; // The answer on the x axis: 0 toward +x, π toward -x. @@ -2595,10 +2167,11 @@ pub(super) fn atan2_special( let x_special = bin(fb, BinOp::LogicalOr, xz, xi)?; let special = bin(fb, BinOp::LogicalOr, y_special, x_special)?; let signed = copysign(fb, f, k, y)?; - let r = fb.select(special, signed, r)?; + let r = fb.select(special, signed, generic)?; let ynan = fb.unary(UnOp::IsNan, y)?; let xnan = fb.unary(UnOp::IsNan, x)?; let any_nan = bin(fb, BinOp::LogicalOr, ynan, xnan)?; + let nan = device_nan(fb, y, x)?; fb.select(any_nan, nan, r) } @@ -2608,15 +2181,19 @@ pub(super) type AtanOf<'a> = &'a dyn Fn(&mut FunctionBuilder<'_>, Value) -> BRes /// Metal `fast::atan2(y, x)` on `float` (probe case c11eb8cb, every lane of sixteen operands /// squared, in both of its compiles): `atan(q)` of the quotient `q = y / x`, turned by `π` when -/// `x` is below zero (by `-π` when `y` is, too), with Metal's special values: +/// `x` is below zero (by `-π` when `y` is, too), with the formula's special values, which the +/// device's `Atan` of an infinite or NaN quotient leaves undefined: /// -/// - an `f32` denormal operand is a zero, and a quotient that is an `f32` denormal is a zero; /// - the quotient's sign is the exclusive or of the operands' sign bits, so a zero quotient /// gives that signed zero and an infinite one (a zero `x`, an infinite `y`, or an overflow) /// `±π/2`; -/// - `0 / 0`, `inf / inf`, and a NaN operand give the canonical NaN (`0x7fc00000`); -/// - the turn reads `x < 0` and `y >= 0` as comparisons, after the flush: `fast::atan2(-0, -1)` -/// is `+π` (where `atan2` answers `-π`), and `fast::atan2(1, -0)` is `-π/2`. +/// - `0 / 0` and `inf / inf` give a quiet NaN, and a NaN operand the device's own NaN of the +/// operands ([`device_nan`]); +/// - the turn reads `x < 0` and `y >= 0` as comparisons: `fast::atan2(-0, -1)` is `+π` (where +/// `atan2` answers `-π`), and `fast::atan2(1, -0)` is `-π/2`. +/// +/// 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 @@ -2649,7 +2226,7 @@ pub(super) fn fast_atan2( let (pi, minus_pi) = (c(fb, std::f64::consts::PI)?, c(fb, -std::f64::consts::PI)?); let half_pi = c(fb, std::f64::consts::FRAC_PI_2)?; let nan = c(fb, f64::NAN)?; - let (yz, xz) = (metal_zero(fb, f, y)?, metal_zero(fb, f, x)?); + 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))?; @@ -2677,10 +2254,8 @@ pub(super) fn fast_atan2( let ft = ty(fb, f)?; let signed_zero = fb.convert(ConvOp::Bitcast, sb, ft)?; let signed_half_pi = copysign(fb, f, half_pi, signed_zero)?; - // A zero quotient: a zero y, an infinite x, or a quotient Metal flushes. - let q_flushed = metal_zero(fb, f, q)?; + // A zero quotient: a zero y or an infinite x. let qz = bin(fb, BinOp::LogicalOr, yz, xi)?; - let qz = bin(fb, BinOp::LogicalOr, qz, q_flushed)?; let qz = match beyond { Some(b) => bin(fb, BinOp::LogicalOr, qz, b)?, None => qz, @@ -2692,28 +2267,26 @@ pub(super) fn fast_atan2( let a = atan(fb, q)?; let a = fb.select(qz, signed_zero, a)?; let a = fb.select(qi, signed_half_pi, a)?; - // The turn, read after the flush: x below zero, by π when y is at least zero. - let below = bin(fb, BinOp::FOrdLessThan, x, zero)?; - let x_nonzero = fb.unary(UnOp::LogicalNot, xz)?; - let xneg = bin(fb, BinOp::LogicalAnd, below, x_nonzero)?; - let at_least = bin(fb, BinOp::FOrdGreaterThanEqual, y, zero)?; - let ynonneg = bin(fb, BinOp::LogicalOr, at_least, yz)?; + // The turn: x below zero, by π when y is at least zero. + let xneg = bin(fb, BinOp::FOrdLessThan, x, zero)?; + let ynonneg = bin(fb, BinOp::FOrdGreaterThanEqual, y, zero)?; 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, inf / inf (or an infinite y times a flushed reciprocal), and NaN operands. + // 0 / 0 and inf / inf (or an infinite y times a flushed reciprocal); 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 undefined = bin(fb, BinOp::LogicalOr, zeros, infs)?; + let r = fb.select(undefined, nan, r)?; let ynan = fb.unary(UnOp::IsNan, y)?; let xnan = fb.unary(UnOp::IsNan, x)?; - let undefined = bin(fb, BinOp::LogicalOr, zeros, infs)?; - let undefined = bin(fb, BinOp::LogicalOr, undefined, ynan)?; - let undefined = bin(fb, BinOp::LogicalOr, undefined, xnan)?; - fb.select(undefined, nan, r) + let any_nan = bin(fb, BinOp::LogicalOr, ynan, xnan)?; + let operand_nan = device_nan(fb, y, x)?; + fb.select(any_nan, operand_nan, r) } /// The container bits of the largest value below 1.0 of `f`'s format. diff --git a/crates/metal2vulkan/src/lower/arith/mod.rs b/crates/metal2vulkan/src/lower/arith/mod.rs index 46817d31f..1d87c11e7 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -1766,25 +1766,22 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result { /// are their own functions; the fast-math accuracy table is single precision, so a narrow `fast_` /// call keeps the precise function: /// -/// - `air.fast_tanh` is the MSL fast-math formula ([`FloatFn::FastTanh`]), divided by the -/// device's division; +/// - `air.fast_tanh`, `air.fast_sinh`, `air.fast_cosh`, `air.fast_atanh`, `air.fast_sin`, +/// `air.fast_cos` and `air.fast_tan` are the device's instructions, which a device whose +/// functions are Metal's answers as Metal's fast functions only in a fast-math module (and its +/// `Tanh` as Metal's precise `tanh` in every module): their own variants for their notes +/// ([`FloatFn::FastTanh`], [`FloatFn::FastSinh`], [`FloatFn::FastCosh`], +/// [`FloatFn::FastAtanh`], [`FloatFn::FastSin`], [`FloatFn::FastCos`], [`FloatFn::FastTan`]); /// - `air.fast_asinh` with every flag is MSL Table 8.2's formula, the canonical NaN at `-inf` /// ([`FloatFn::FastAsinh`]); -/// - `air.fast_sinh`, `air.fast_cosh`, `air.fast_acosh`, and `air.fast_atanh` are MSL Table -/// 8.2's formulas of Metal's fast `exp`, `log`, `sqrt`, and division ([`FloatFn::FastSinh`], -/// [`FloatFn::FastCosh`], [`FloatFn::FastAcosh`], [`FloatFn::FastAtanh`]), the last divided by -/// the device's division, where the device's instruction is not Metal's fast function; +/// - `air.fast_acosh` is MSL Table 8.2's formula of Metal's fast `log` and `sqrt` +/// ([`FloatFn::FastAcosh`]), the device's `Acosh`; /// - `air.fast_fract` is not bounded below one, and with every flag is the canonical NaN at an /// infinity ([`FloatFn::FastFract`]); /// - `air.fast_fmedian3` answers `b` for two NaN first operands ([`FloatFn::FastMedian3`]); -/// - `air.fast_pow` answers the canonical NaN for a NaN base to the exponent one -/// ([`FloatFn::FastPow`]); +/// - `air.fast_pow`'s magnitude is `exp2(y · log2|x|)` ([`FloatFn::FastPow`]); /// - `air.fast_atan2` is `atan(y / x)` turned by `±π`, NaN at `0 / 0` and `inf / inf` /// ([`FloatFn::FastAtan2`]); -/// - `air.fast_sin` and `air.fast_cos` answer `+0` past `float(π/2) · 2^22` and for an infinity -/// or NaN ([`FloatFn::FastSin`], [`FloatFn::FastCos`]); -/// - `air.fast_tan` is Metal's fast `tan` ([`FloatFn::FastTan`]), Apple's formula divided by the -/// device's division where the device's `Tan` is not it; /// - `air.fast_asin`, `air.fast_acos`, and `air.fast_atan` are Metal's fast functions, which a /// device that is Metal's own answers only in a fast-math module and which answer `fast::asin` /// of a zero and of a denormal as `+0` and `fast::atan` of one as its signed zero @@ -2792,8 +2789,7 @@ pub fn emit( /// What the entry being emitted's float function calls take ([`libm::Lib`]). pub(crate) fn lib(cx: &EmitCx<'_>) -> libm::Lib { - let arith = &cx.plan.families.arith; - libm::Lib::new(arith.metal_functions, cx.decl.families.arith.fmod) + libm::Lib::new(cx.decl.families.arith.fmod) } /// The operands strategy `s` reads (a prefix of the instruction's; all when `None`). diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index 5d5461ca1..e5f4b509d 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -2057,14 +2057,15 @@ fn exact_float_functions_answer_their_instructions() { } /// The functions the device has an instruction for are that instruction, on `float` and on a -/// `half` held in `float`, in every math mode of every library: `exp`, `log`, `pow` and `powr`'s -/// magnitude, `sinh`, `cosh`, `tanh` (`Exp`, `Log`, `Pow`, `Sinh`, `Cosh`, `Tanh`, with no `Exp2` -/// or `Log2` composition of Metal's), `fabs`, `sign`, `fract` and `fast::fract` (`FAbs`, `FSign`, -/// `Fract`, with no bit operation), `median3` (`NMin` and `NMax` alone), `mix` (`FMix`) and -/// `fast::sqrt` (`Sqrt`). `round` is C99's from the device's `Trunc`. +/// `half` held in `float`: `exp`, `log`, `pow` and `powr`'s magnitude, `sinh`, `cosh`, `tanh` +/// (`Exp`, `Log`, `Pow`, `Sinh`, `Cosh`, `Tanh`, with no `Exp2` or `Log2` composition of Metal's), +/// the fast `sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh` and `atanh` (the instruction alone, with no +/// flush past Metal's last evaluated quadrant and no MSL Table 8.2 formula), `fabs`, `sign`, +/// `fract` and `fast::fract` (`FAbs`, `FSign`, `Fract`, with no bit operation), `median3` (`NMin` +/// and `NMax` alone), `mix` (`FMix`) and `fast::sqrt` (`Sqrt`). `round` is C99's from the device's +/// `Trunc`. #[test] fn functions_with_an_instruction_are_that_instruction() { - use super::libm::Mode; use crate::spv::GlslStd450Op as G; const OP_EXT_INST: u32 = 12; const OP_BITCAST: u32 = 124; @@ -2086,7 +2087,14 @@ fn functions_with_an_instruction_are_that_instruction() { } (ext, bitcasts) }; - let cases: [(FloatFn, &[G]); 15] = [ + let cases: [(FloatFn, &[G]); 22] = [ + (FloatFn::FastSin, &[G::Sin]), + (FloatFn::FastCos, &[G::Cos]), + (FloatFn::FastTan, &[G::Tan]), + (FloatFn::FastSinh, &[G::Sinh]), + (FloatFn::FastCosh, &[G::Cosh]), + (FloatFn::FastTanh, &[G::Tanh]), + (FloatFn::FastAtanh, &[G::Atanh]), (FloatFn::Exp, &[G::Exp]), (FloatFn::Log, &[G::Log]), (FloatFn::Sinh, &[G::Sinh]), @@ -2103,16 +2111,25 @@ fn functions_with_an_instruction_are_that_instruction() { (FloatFn::FastSqrt, &[G::Sqrt]), (FloatFn::Round, &[G::Trunc]), ]; - for lib in [ - Lib::instructions(), - Lib::new(Some(Mode::Fast), None), - Lib::new(Some(Mode::Precise), None), - ] { + { + let lib = Lib::instructions(); for lane in [float(32), float(16)] { for lanes in [1u8, 3] { let f = vec(lane, lanes); for (op, want) in cases { - if op == FloatFn::FastSqrt && lane.float_fmt() == Some(FloatFmt::Half) { + // `refine_float` gives a narrow call no fast function. + let fast = matches!( + op, + FloatFn::FastSqrt + | FloatFn::FastSin + | FloatFn::FastCos + | FloatFn::FastTan + | FloatFn::FastSinh + | FloatFn::FastCosh + | FloatFn::FastTanh + | FloatFn::FastAtanh + ); + if fast && lane.float_fmt() == Some(FloatFmt::Half) { continue; } let what = format!("{op:?} on {f:?} ({lib:?})"); @@ -2130,6 +2147,13 @@ fn functions_with_an_instruction_are_that_instruction() { | FloatFn::Sinh | FloatFn::Cosh | FloatFn::Tanh + | FloatFn::FastSin + | FloatFn::FastCos + | FloatFn::FastTan + | FloatFn::FastSinh + | FloatFn::FastCosh + | FloatFn::FastTanh + | FloatFn::FastAtanh | FloatFn::Abs | FloatFn::Sign | FloatFn::FastFract @@ -2622,16 +2646,15 @@ fn nan_answers_follow_the_measured_flag_states() { } } -/// `powr(x, y)` is Metal's canonical NaN where Metal's `exp2(y * log2(x))` is a NaN for operands -/// that are not: `x < 0` (`-0` is not), `y = ±0` with `x = ±0` or `+inf`, -/// and `y = ±inf` with `x = 1`, an `f32` denormal read as a zero by the zero tests and, in -/// `fast::powr` only, by the sign test; every other lane keeps the device's result, which the -/// kernel's third input stands for, except that `fast::powr` answers IEEE's value where `y · -/// log2(x)` is infinite (`math::infinite_product`'s rule, on the same classification of the -/// operands). `half`'s NaN lanes are the same rule's (`nan_half`, `nan_half_fast`, every lane, -/// class K). +/// `powr(x, y)` is a NaN where MSL's `exp2(y * log2(x))` is a NaN for operands that are not: `x < +/// 0` (`-0` is not), `y = ±0` with `x = ±0` or `+inf`, and `y = ±inf` with `x = 1`, each by the +/// device's comparisons (the interpreter reads an `f32` denormal as a value, where Metal reads a +/// zero); every other lane keeps the device's result, which the kernel's third input stands for, +/// except that `fast::powr` answers IEEE's value where `y · log2(x)` is infinite +/// (`math::infinite_product`'s rule, on the same classification of the operands). `half`'s NaN +/// lanes are the same rule's (`nan_half`, `nan_half_fast`, every lane, class K). #[test] -fn powr_answers_metals_nan_at_its_special_operands() { +fn powr_answers_c99_nan_at_its_special_operands() { // The answer where `y · log2(x)` is infinite (`log2(x)` read as `-inf` at a zero), for // operands that are not NaNs nor in the NaN rule's lanes; `None` where it is finite. fn infinite(x: f64, y: f64, y_negative: bool) -> Option { @@ -2709,7 +2732,7 @@ fn powr_answers_metals_nan_at_its_special_operands() { -f32::NAN, f32::MIN_POSITIVE, -f32::MIN_POSITIVE, - // Denormals, which Metal reads as zeros. + // Denormals, which Metal reads as zeros and the device's comparisons as it reads them. f32::from_bits(1), -f32::from_bits(0x007F_FFFF), ] @@ -2738,17 +2761,8 @@ fn powr_answers_metals_nan_at_its_special_operands() { }, &cases, &|c| { - // A denormal is a zero to Metal's zero tests, and to `fast::powr`'s sign test; - // the precise sign is the bit's, a NaN's included. - let read = |v: f32| if v.is_subnormal() { 0.0 } else { v }; - let raw = f32v(arg(c, 0)); - let (x, y) = (read(raw), read(f32v(arg(c, 1)))); - let below = if fast { - x < 0.0 - } else { - raw.is_sign_negative() && raw != 0.0 - }; - let nan = below + let (x, y) = (f32v(arg(c, 0)), f32v(arg(c, 1))); + let nan = x < 0.0 || (y == 0.0 && (x == 0.0 || x == f32::INFINITY)) || (y.is_infinite() && x == 1.0); if nan { @@ -2763,7 +2777,7 @@ fn powr_answers_metals_nan_at_its_special_operands() { _ => device, }]) }, - &|g, w| g == w, + &|g, w| g == w || (is_nan(f, g) && is_nan(f, w)), ); } } @@ -2795,20 +2809,18 @@ fn pow_special_cases_match_c99() { ); } } - for precise in [true, false] { - check( - &format!("pow special cases f32 (precise {precise})"), - &[f, f, f], - f, - &|fb, a| math::pow_special(fb, f, a[0], a[1], a[2], precise), - &cases, - &|c| { - let r = f32v(arg(c, 0)).powf(f32v(arg(c, 1))); - Some(vec![u64::from(r.to_bits())]) - }, - false, - ); - } + check( + "pow special cases f32", + &[f, f, f], + f, + &|fb, a| math::pow_special(fb, f, a[0], a[1], a[2]), + &cases, + &|c| { + let r = f32v(arg(c, 0)).powf(f32v(arg(c, 1))); + Some(vec![u64::from(r.to_bits())]) + }, + false, + ); } /// The inputs of the authored case `pi-scaled-sine-and-cosine-are-exact-at-every-half-integer` @@ -3009,7 +3021,6 @@ fn pi_scaled_functions_reduce_exactly_to_metal_answers() { /// identity kernel is charged in full, its constants and the `GLSL.std.450` import included. #[test] fn pi_scaled_functions_stay_within_their_word_estimate() { - use super::libm::Mode; let module_words = |f: Form, body: Body<'_>| { let m = kernel(&[f], f, body).expect("kernel"); crate::spirv::serialize::serialize(m) @@ -3035,77 +3046,18 @@ fn pi_scaled_functions_stay_within_their_word_estimate() { precise.to_vec() }; for g in calls { - for metal in [None, Some(Mode::Fast), Some(Mode::Precise)] { - let used = module_words(f, &|fb, x| { - math::float_fn(fb, g, f, Contraction::Allowed, x, &Lib::new(metal, None)) - }); - let (emitted, bound) = (used - bare, g.words(f) as usize); - assert!( - emitted <= bound, - "{g:?} {f:?} with Metal's functions {metal:?}: {emitted} words over {bound}" - ); - } + let used = module_words(f, &|fb, x| { + math::float_fn(fb, g, f, Contraction::Allowed, x, &Lib::instructions()) + }); + let (emitted, bound) = (used - bare, g.words(f) as usize); + assert!( + emitted <= bound, + "{g:?} {f:?}: {emitted} words over {bound}" + ); } } } -/// `air.fast_tanh` on `float` is the MSL fast-math formula `(t - 1) / (t + 1)` of `t = exp(2x)`, -/// its quotient the device's division. The interpreter does not model `Exp2`, so the kernel takes -/// `t` as an input (`exp2(x * 2 log2 e)` in `f32` on the host) and runs the quotient. Where the -/// quotient does not depend on the last place of `t` it gives the Metal observation of the -/// authored case `fast-tanh-through-all-three-of-its-regimes` (M3 Max, ORACLE_ABI v32): `x = 0` is -/// 0, `x = 43` is 1, `x = 44.4` (where `t` overflows) is NaN, and `x = -100` (where `t` is 0) is -/// -1. At `x = 44`, where `t + 1` is above `2^126`, Metal's fast reciprocal flushes and answers 0; -/// the device's quotient answers 1 (`PrecisionNote::NativeDivision`). -#[test] -fn fast_tanh_is_the_fast_math_formula() { - let f = float(32); - let two_log2e = (2.0 * std::f64::consts::LOG2_E) as f32; - let t_of = |x: f32| (x * two_log2e).exp2(); - // (x, Metal's fast::tanh(x)). - let metal: [(f32, u32); 4] = [ - (0.0, 0x0000_0000), - (43.0, 0x3F80_0000), - (44.4, 0x7FC0_0000), - (-100.0, 0xBF80_0000), - ]; - let quotient = |t: f32| (t - 1.0) / (t + 1.0); - let mut xs: Vec = metal.iter().map(|m| m.0).collect(); - xs.extend([44.0, 0.5, -3.75, 5.0, 1e-3, -1e-3, 20.0, -44.4, 43.7]); - let cases: Vec = xs - .iter() - .map(|x| vec![vec![u64::from(t_of(*x).to_bits())]]) - .collect(); - check( - "fast tanh quotient f32", - &[f], - f, - &|fb, t| { - let divide = |fb: &mut FunctionBuilder<'_>, x: Value, y: Value| { - fb.binary_with(BinOp::FDiv, x, y, Contraction::Forbidden) - }; - math::tanh_of_exp(fb, f, ÷, t[0]) - }, - &cases, - &|c| { - let t = f32v(arg(c, 0)); - Some(vec![u64::from(quotient(t).to_bits())]) - }, - false, - ); - for (x, want) in metal { - let got = quotient(t_of(x)); - assert!( - got.to_bits() == want || (got.is_nan() && f32::from_bits(want).is_nan()), - "fast::tanh({x}) = {got} ({:#010x}), Metal {want:#010x}", - got.to_bits() - ); - } - // x = 44: t + 1 > 2^126, where Metal's reciprocal flushes and the device's quotient is 1. - assert!(t_of(44.0) + 1.0 > 2f32.powi(126)); - assert_eq!(quotient(t_of(44.0)), 1.0); -} - /// The function a call computes follows its `air` symbol's `fast_` variant, never a name: on /// `float`, `fast_tanh` is the fast-math formula, `fast_fract` is unbounded, `fast_fmedian3` /// records the device's pick of two NaNs, `fast_pow` the canonical NaN for a NaN base to the @@ -3184,8 +3136,11 @@ fn fast_variants_refine_float_functions() { assert_eq!(refine(op, false, fmf, bfloat()), op); } } - assert!(FloatFn::FastTanh.divides() && !FloatFn::Tanh.divides()); - assert!(FloatFn::FastTan.divides()); + // The fast `tanh`, `tan` and `atanh` are the device's instructions, which divide by nothing. + for op in [FloatFn::FastTanh, FloatFn::FastTan, FloatFn::FastAtanh] { + assert!(!op.divides(), "{op:?}"); + } + assert!(!FloatFn::Tanh.divides()); for reciprocal_flushed in [false, true] { assert!(FloatFn::FastAtan2 { reciprocal_flushed }.divides()); } diff --git a/crates/metal2vulkan/src/lower/arith/tests/atan2.rs b/crates/metal2vulkan/src/lower/arith/tests/atan2.rs index 388058c6a..3a9da3790 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/atan2.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/atan2.rs @@ -3,8 +3,10 @@ //! of both signs, denormals, the smallest normal, ordinary values, the largest finite values, //! infinities, and NaNs. The interpreter does not model `GLSL.std.450 Atan2` or `Atan`, so `atan2` //! takes its generic value as an input and `fast::atan2` a stand-in `atan`; every lane a special -//! value decides must equal Metal's answer bit for bit, and every other lane must be the generic -//! value (or the stand-in's), so the special values read neither. +//! value decides must equal Metal's answer bit for bit (a NaN any NaN, its bits the device's), and +//! every other lane must be the generic value (or the stand-in's), so the special values read +//! neither. An `f32` denormal operand is a value, as the interpreter reads it, where Metal reads a +//! zero (`PrecisionNote::DeviceDenormals` off a device measured to read it as Metal does). use super::*; @@ -356,9 +358,14 @@ const ATAN2_HALF: [[u16; 16]; 16] = [ const MARKER_F32: u32 = 0x3E00_0000; const MARKER_HALF: u16 = 0x3000; -/// Whether an `f32` operand is a zero to Metal (its exponent field is zero), infinite, or NaN. +/// Whether an `f32` operand is a zero, infinite, or NaN (its denormals are values). fn f32_special(b: u32) -> bool { - b & 0x7F80_0000 == 0 || b & 0x7F80_0000 == 0x7F80_0000 + b & 0x7FFF_FFFF == 0 || b & 0x7F80_0000 == 0x7F80_0000 +} + +/// Whether an `f32` operand is a denormal, which Metal reads as a zero. +fn f32_denormal(b: u32) -> bool { + b & 0x7F80_0000 == 0 && b & 0x007F_FFFF != 0 } /// Whether a `half` operand is a zero, infinite, or NaN (its denormals are values). @@ -368,19 +375,22 @@ fn half_special(b: u16) -> bool { /// `atan2` (`math::atan2_special` around its generic input, then the format's rounding): a lane /// with a zero, infinite, or NaN operand is Metal's answer whatever the generic value; any other -/// lane is the generic value, `+0` when it is an `f32` denormal. The generic input is the host's -/// correctly rounded `atan2` there and [`MARKER_F32`] elsewhere. Metal's own generic answers are -/// within one ulp of it (five `float` lanes differ by one, the device's precision); its `+0` for -/// a denormal `float` result is asserted on the lanes that have one. +/// lane is the generic value, a denormal one included (the device's `Atan2`, where Metal answers +/// `+0`). The generic input is the host's correctly rounded `atan2` there and [`MARKER_F32`] +/// elsewhere. Metal's own generic answers are within one ulp of it (five `float` lanes differ by +/// one, the device's precision). The `float` lanes with a denormal operand, which Metal reads as a +/// zero, are the device's reading and left out. #[test] -fn atan2_answers_as_metal_at_every_special_operand() { +fn atan2_answers_as_c99_at_every_special_operand() { for bits in [32u8, 16] { let f = float(bits); let mut cases: Vec = Vec::new(); let mut want = Vec::new(); - let mut flushed = 0; for j in 0..16 { for k in 0..16 { + if bits == 32 && (f32_denormal(F32_OPERANDS[j]) || f32_denormal(F32_OPERANDS[k])) { + continue; + } let (y, x, metal, special) = if bits == 32 { let (y, x) = (F32_OPERANDS[j], F32_OPERANDS[k]); let special = f32_special(y) || f32_special(x); @@ -415,20 +425,12 @@ fn atan2_answers_as_metal_at_every_special_operand() { let r = f16_to_f64(y as u16).atan2(f16_to_f64(x as u16)); u64::from(f64_to_f16(r)) }; - let tiny = bits == 32 && g & 0x7F80_0000 == 0; - if tiny { - flushed += 1; - assert_eq!(metal, 0, "Metal's tiny atan2({y:#x}, {x:#x})"); - } - (g, if tiny { 0 } else { g }) + (g, g) }; cases.push(vec![vec![y], vec![x], vec![generic]]); want.push(((y, x), expect)); } } - if bits == 32 { - assert_eq!(flushed, 6, "the float lanes with a denormal answer"); - } check_accept( &format!("atan2 f{bits} against Metal"), &[f, f, f], @@ -442,7 +444,7 @@ fn atan2_answers_as_metal_at_every_special_operand() { let key = (arg(c, 0), arg(c, 1)); want.iter().find(|(k, _)| *k == key).map(|(_, w)| vec![*w]) }, - &|g, w| g == w, + &|g, w| g == w || (is_nan(f, g) && is_nan(f, w)), ); } } @@ -456,9 +458,9 @@ fn metal_read(b: u32) -> f32 { } } -/// `fast::atan2(y, x)` with the stand-in `atan(q) = q + 1/8`, where Metal'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. +/// `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 { if f32_special(y) || f32_special(x) { return None; @@ -468,7 +470,7 @@ fn fast_generic(y: u32, x: u32, reciprocal_flushed: bool) -> Option { return None; } let q = (f64::from(yv) / f64::from(xv)) as f32; - if f32_special(q.to_bits()) { + if !q.is_finite() { return None; } let a = q + 0.125; @@ -482,11 +484,12 @@ fn fast_generic(y: u32, x: u32, reciprocal_flushed: bool) -> Option { } /// `fast::atan2` (`math::fast_atan2`) with a stand-in `atan(q) = q + 1/8` the interpreter runs: -/// every lane of the grid that Metal's special values decide is Metal's answer for the call's -/// flags (the quotient's sign, the flushed operands and quotient, `0 / 0` and `inf / inf`, the -/// turn's comparisons, and the flushed reciprocal beyond `2^126` of a call without every flag), -/// and every other lane is the stand-in of the correctly rounded quotient, turned; operands -/// beyond the grid check the scaled division near `2^126` and `FLT_MAX`. +/// 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. #[test] fn fast_atan2_answers_as_metal_at_every_special_operand() { let f = float(32); @@ -511,6 +514,9 @@ fn fast_atan2_answers_as_metal_at_every_special_operand() { 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 => { @@ -521,15 +527,16 @@ fn fast_atan2_answers_as_metal_at_every_special_operand() { want.push(((u64::from(y), u64::from(x)), u64::from(w))); } } - // The lanes with a finite normal quotient of finite normal operands, less the lanes a - // flushed reciprocal decides. + // 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`). assert_eq!( decided, if reciprocal_flushed { - 256 - 30 + 196 - 31 } else { - 256 - 34 - } + 196 - 45 + }, + "reciprocal flushed {reciprocal_flushed}" ); if !reciprocal_flushed { for (y, x) in extra { @@ -574,13 +581,13 @@ fn fast_atan2_answers_as_metal_at_every_special_operand() { let key = (arg(c, 0), arg(c, 1)); want.iter().find(|(k, _)| *k == key).map(|(_, w)| vec![*w]) }, - &|g, w| g == w, + &|g, w| g == w || (is_nan(f, g) && is_nan(f, w)), ); } } -/// [`FloatFn::words`] bounds what `atan2`, `fast::atan2`, `fast::sin`, and `fast::cos` emit on -/// every form they take (`fast::sin` and `fast::cos` on `float`), and is not more than twice it. +/// [`FloatFn::words`] bounds what `atan2` and `fast::atan2` emit on every form they take, and is +/// not more than twice it. /// The module's growth over an identity kernel is charged in full, its constants and the /// `GLSL.std.450` import included. #[test] @@ -600,17 +607,11 @@ fn special_value_functions_stay_within_their_word_estimate() { FloatFn::FastAtan2 { reciprocal_flushed: true, }, - FloatFn::FastSin, - FloatFn::FastCos, ]; let mut out = Vec::new(); for f in [float(32), vec(float(32), 4), float(16), vec(float(16), 4)] { let bare = module_words(f, &|_, x| Ok(x[0])); for g in fns { - // `fast::sin` and `fast::cos` are refined from `float` calls only. - if matches!(g, FloatFn::FastSin | FloatFn::FastCos) && f.is_narrow() { - continue; - } let used = module_words(f, &|fb, x| { math::float_fn(fb, g, f, Contraction::Allowed, x, &Lib::instructions()) }); diff --git a/crates/metal2vulkan/src/lower/arith/tests/fast.rs b/crates/metal2vulkan/src/lower/arith/tests/fast.rs index f169214c0..02dc790a8 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/fast.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/fast.rs @@ -5,7 +5,7 @@ use super::*; use crate::lower::arith::fma::{self, Fma, Route}; -use crate::lower::arith::libm::{Lib, Mode}; +use crate::lower::arith::libm::Lib; /// `(x, y, fast::fmod(x, y))`: the lanes of case 08bc6611 whose fast reciprocal of `y` is the /// correctly rounded `1 / y` (917 of 1,024; these are its special lanes and 44 others drawn at @@ -226,18 +226,12 @@ fn fast_functions_are_metals_compositions() { assert_eq!(ext, [0, 0, 0, 1, 1, 0, 0]); let (ext, _, _) = read(FloatFn::Pow); assert_eq!(ext, [1, 0, 0, 0, 0, 0, 0]); - for lib in [ - Lib::instructions(), - Lib::new(Some(Mode::Fast), None), - Lib::new(Some(Mode::Precise), None), + let (ext, _, _) = read(FloatFn::FastSqrt); + assert_eq!(ext, [0, 0, 0, 0, 0, 1, 0]); + for (op, want) in [ + (FloatFn::Exp, [0, 1, 0, 0, 0, 0, 0]), + (FloatFn::Log, [0, 0, 1, 0, 0, 0, 0]), ] { - let (ext, _, _) = read_in(FloatFn::FastSqrt, lib); - assert_eq!(ext, [0, 0, 0, 0, 0, 1, 0]); - for (op, want) in [ - (FloatFn::Exp, [0, 1, 0, 0, 0, 0, 0]), - (FloatFn::Log, [0, 0, 1, 0, 0, 0, 0]), - ] { - assert_eq!(read_in(op, lib).0, want, "{op:?}"); - } + assert_eq!(read(op).0, want, "{op:?}"); } } diff --git a/crates/metal2vulkan/src/lower/arith/tests/libm.rs b/crates/metal2vulkan/src/lower/arith/tests/libm.rs index 15b679ebb..d74ea756b 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/libm.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/libm.rs @@ -64,7 +64,7 @@ fn fmod_module(f: Form) -> TypedModule { f, Contraction::Forbidden, x, - &Lib::new(None, funcs.first().copied()), + &Lib::new(funcs.first().copied()), ) }, true, @@ -258,6 +258,8 @@ mod half_fmod_takes_the_routine { /// over a composition that answered `1`, as the RTX 5080 did without `SignedZeroInfNanPreserve`): /// Metal's word at case f6524207's special pairs and case 32931370's `half` /// ones, and the composition's own value where the product is finite, a NaN, or an operand is one. +/// An `f32` denormal base is a zero only where the device's comparison reads it so (the +/// interpreter does not, where Metal does): there the product is finite, the composition's. #[test] fn an_infinite_product_answers_ieee_whatever_the_composition_gave() { let (f, h) = (float(32), float(16)); @@ -267,9 +269,9 @@ fn an_infinite_product_answers_ieee_whatever_the_composition_gave() { let words: [(u64, u64, Option); 15] = [ (0x0000_0000, 0x3F80_0000, Some(0)), (0x8000_0000, 0x4000_0000, Some(0)), - (0x0000_0001, 0xBF80_0000, Some(0x7F80_0000)), - (0x8000_0001, 0x3F00_0000, Some(0)), - (0x0040_0000, 0x4100_0000, Some(0)), + (0x0000_0001, 0xBF80_0000, None), + (0x8000_0001, 0x3F00_0000, None), + (0x0040_0000, 0x4100_0000, None), (0x7F80_0000, 0xC000_0000, Some(0)), (0x7F80_0000, 0x4100_0000, Some(0x7F80_0000)), (0x3F00_0000, 0x7F80_0000, Some(0)), diff --git a/crates/metal2vulkan/src/lower/arith/tests/specials.rs b/crates/metal2vulkan/src/lower/arith/tests/specials.rs index 116d16666..37e61b31a 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/specials.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/specials.rs @@ -2,11 +2,10 @@ //! Metal's recorded answers (Apple M3 Max, ORACLE_ABI v34), bit for bit: every distinct lane of the //! A1 case `fract-saturate-and-median3-at-nan-infinity-and-signed-zero` (aed3faaa) but those whose //! answer is the device's instruction's (`median3`'s ties), and the lanes of -//! `pow-at-every-c99-special-operand` -//! (116e052a) with a NaN operand, the exponent one, a denormal exponent, or a negative denormal -//! base to a non-integral exponent. The operands are signed zeros, `f32` and `half` denormals, the -//! smallest normals, values beside the integers, the largest finite values, infinities, and NaNs -//! (quiet and signalling, both signs, with payloads). +//! `pow-at-every-c99-special-operand` (116e052a) that one of C99's special cases decides (a NaN +//! answer as any NaN, its bits the device's). The operands are signed zeros, `f32` and `half` +//! denormals, the smallest normals, values beside the integers, the largest finite values, +//! infinities, and NaNs (quiet and signalling, both signs, with payloads). use super::*; @@ -559,14 +558,31 @@ fn median3_answers_as_metal_but_at_its_recorded_ties() { metal_answers(FloatFn::Median3, float(16), &half); } -/// `pow`'s special cases (`math::pow_special`) at the lanes of [`POW`], each decided by a special -/// case: the magnitude operand (`GLSL.std.450 Pow(|x|, y)`, which the interpreter does not -/// model) is a constant no answer equals, so a lane that read it would fail. +/// `pow`'s C99 special cases (`math::pow_special`) at the lanes of [`POW`] one of them decides, +/// against Metal's answers: the magnitude operand (`GLSL.std.450 Pow(|x|, y)`, which the +/// interpreter does not model) is a constant no answer equals, so a lane that read it would fail. +/// Left out are the lanes the device answers: `pow(x, 1)` of a nonzero number `x` other than `±1` +/// (the device's `Pow`, which Metal answers `x` exactly), and an `f32` denormal operand, which +/// Metal reads as a zero and the device as it reads it (`PrecisionNote::DeviceDenormals`). A NaN +/// answer is any NaN: its bits are the device's (`PrecisionNote::NativeNanEncoding`). #[test] -fn pow_special_operands_answer_as_metal() { +fn pow_special_operands_answer_as_c99() { for (bits, precise) in [(32u8, true), (32, false), (16, true)] { let f = float(bits); let pi = if bits == 32 { 0x4049_0FDB } else { 0x4248 }; + let (one, nan_from, magnitude) = if bits == 32 { + (0x3F80_0000, 0x7F80_0000, 0x7FFF_FFFF) + } else { + (0x3C00, 0x7C00, 0x7FFF) + }; + // Decided by the device: `pow(x, 1)` of a number that is not a zero or `±1`, and an `f32` + // denormal operand. + let device = |x: u64, y: u64| { + let ax = x & magnitude; + let to_one = y == one && ax != 0 && ax != one && ax <= nan_from; + let denormal = |v: u64| bits == 32 && v & 0x7F80_0000 == 0 && v & 0x007F_FFFF != 0; + to_one || denormal(x) || denormal(y) + }; let rows: Vec = POW .iter() .map(|r| match (bits, precise) { @@ -574,6 +590,7 @@ fn pow_special_operands_answer_as_metal() { (32, false) => (vec![u64::from(r.0), u64::from(r.1), pi], u64::from(r.3)), _ => (vec![u64::from(r.4), u64::from(r.5), pi], u64::from(r.6)), }) + .filter(|(ops, _)| !device(ops[0], ops[1])) .collect(); let cases: Vec = rows .iter() @@ -584,7 +601,7 @@ fn pow_special_operands_answer_as_metal() { &[f, f, f], f, &|fb, a| { - let r = math::pow_special(fb, f, a[0], a[1], a[2], precise)?; + let r = math::pow_special(fb, f, a[0], a[1], a[2])?; crate::lower::arith::narrow::round(fb, f, r) }, &cases, @@ -594,96 +611,37 @@ fn pow_special_operands_answer_as_metal() { .find(|(o, _)| *o == ops) .map(|(_, want)| vec![*want]) }, - &|g, w| g == w, + &|g, w| g == w || (is_nan(f, g) && is_nan(f, w)), ); } } -/// `pow(x, 1)` of an `f32` denormal `x` (`math::pow_special`): Metal's precise `pow` answers `x` -/// itself and `fast::pow` the zero of its sign, at each denormal base of the denormal probes -/// (cases 638c7906 and c9b6bacb, the `pow` word at `y = 1`; the M3 Max and the M4 answer the -/// same). The magnitude operand is a constant no answer equals, so a lane that read it fails. +/// `pow(x, 1)` (`math::pow_special`) is the device's `Pow(|x|, 1)`, negated for a negative `x` +/// (one is odd), where Metal answers `x` itself: the magnitude operand is a constant no `x` +/// equals, so a lane that kept `x` fails. A zero and `±1` are C99's cases, a NaN its NaN. #[test] -fn pow_of_a_denormal_base_to_one_answers_as_metal() { +fn pow_of_a_number_to_one_is_the_device_pow() { let f = float(32); let magnitude = 0x4049_0FDBu64; let one = 0x3F80_0000u64; let bases = [ - 0x0000_0001u32, - 0x8000_0001, - 0x0000_0003, - 0x0040_0000, - 0x807F_FFFF, - 0x007F_FFFF, + 0x3F00_0000u32, + 0xBF00_0000, + 0x4040_0000, + 0xC040_0000, + 0x7F7F_FFFF, ]; - for precise in [true, false] { - let cases: Vec = bases - .iter() - .map(|x| vec![vec![u64::from(*x)], vec![one], vec![magnitude]]) - .collect(); - check_accept( - &format!("pow f32 of a denormal base to 1 (precise {precise}) against Metal"), - &[f, f, f], - f, - &|fb, a| math::pow_special(fb, f, a[0], a[1], a[2], precise), - &cases, - &|c| { - let x = c[0][0] as u32; - let want = if precise { x } else { x & 0x8000_0000 }; - Some(vec![u64::from(want)]) - }, - &|g, w| g == w, - ); - } -} - -/// Metal's `fast::sin` and `fast::cos` past the last evaluated quadrant (`math::fast_trig_flush`), -/// against Metal's answers: `+0` from the float after `float(π/2) · 2^22` on, for the infinities, -/// and for NaNs, whatever the sign; the device's `Sin`/`Cos` (here an input no answer equals) up to -/// and at the limit. The arguments are the bisected boundary, the two A1 cases' (`9424775`, `1e7`, -/// a NaN, 179b6aa6's `6588397.5`), and probe case 08bc6611's lanes. -#[test] -fn fast_sine_and_cosine_flush_past_the_last_quadrant_as_metal() { - let f = float(32); - let device = 0x3F12_3456u64; - let limit = math::FAST_TRIG_LIMIT; - assert_eq!(limit, std::f32::consts::FRAC_PI_2 * (1u32 << 22) as f32); - assert_eq!(limit.to_bits(), 0x4AC9_0FDB); - // (x, flushed): Metal answers +0 when flushed and its evaluated function otherwise. - let rows: [(u32, bool); 16] = [ - (limit.to_bits(), false), - ((-limit).to_bits(), false), - (0x4AC9_0FDC, true), - (0xCAC9_0FDC, true), - (9_424_775f32.to_bits(), true), - (1e7f32.to_bits(), true), - ((-1e7f32).to_bits(), true), - (f32::MAX.to_bits(), true), - (0x7F80_0000, true), - (0xFF80_0000, true), - (0x7FC0_0000, true), - (0xFFC0_0000, true), - (0x7F80_0001, true), - (0x3F80_0000, false), - (0x8000_0000, false), - (1e6f32.to_bits(), false), - ]; - let cases: Vec = rows + let cases: Vec = bases .iter() - .map(|(x, _)| vec![vec![u64::from(*x)], vec![device]]) + .map(|x| vec![vec![u64::from(*x)], vec![one], vec![magnitude]]) .collect(); check_accept( - "fast sin/cos flush f32 against Metal", - &[f, f], + "pow f32 of a number to 1", + &[f, f, f], f, - &|fb, a| math::fast_trig_flush(fb, f, a[0], a[1]), + &|fb, a| math::pow_special(fb, f, a[0], a[1], a[2]), &cases, - &|c| { - let x = arg(c, 0) as u32; - rows.iter() - .find(|(r, _)| *r == x) - .map(|(_, flushed)| vec![if *flushed { 0 } else { device }]) - }, + &|c| Some(vec![magnitude | (c[0][0] & 0x8000_0000)]), &|g, w| g == w, ); } diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 6aa8d7f45..abc0d5cbf 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -620,8 +620,8 @@ pub enum PrecisionNote { /// by `Sqrt`, `dot` of vectors of other than two to four lanes, whose chunks' products the /// device sums where Metal flushes each one below `2^-126`, beside their own notes, and a /// conversion to or from `double`, whose reading Metal's is not measured. The operations that - /// read a denormal on its bits answer Metal on every device: `ldexp`, `copysign` and `atan2`; - /// and so do the functions the device answers as Metal's own. Where the minimum and maximum functions + /// read a denormal on its bits answer Metal on every device: `ldexp` and `copysign`; and so do + /// the functions the device answers as Metal's own. Where the minimum and maximum functions /// (`llvm.minnum` and `llvm.maxnum` among them, with any flags) and `saturate` are the device's /// `NMin`, `NMax` and `NClamp`, their pick of a denormal is /// [`PrecisionNote::NativeMinMax`]'s. Validation derives no tolerance and no explanation from @@ -1575,11 +1575,19 @@ pub enum PrecisionNote { /// device's own `GLSL.std.450` instruction (`Exp`, `Log`, `Pow`, `Sinh`, `Cosh` and `Tanh` /// among them; a composition of the device's `Exp2` and `Log2` only for `exp10` and `log10`, /// which no instruction is) where Metal's function is not the device's own; `fast::sqrt` the - /// device's `Sqrt`; `fabs`, `sign` and `fract` the device's `FAbs`, `FSign` and `Fract`, their - /// special operands the instruction's (Metal's `sign` of a NaN, a zero and an `f32` denormal is - /// `+0`, its `fract` of an infinity `+0`, where `FSign` keeps a zero's sign and leaves a NaN's - /// answer undefined and `Fract` of an infinity is a NaN); and `round` C99's, from the - /// device's `Trunc`, on every device (`round(-0.3)` is `-0`, where Metal answers `+0`). + /// device's `Sqrt`; the fast `sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh` and `atanh` the + /// device's instructions, where MSL Table 8.2 defines Metal's by formulas (`fast::sin` and + /// `fast::cos` are `+0` past `float(π/2) · 2^22` and at an infinity or NaN, `fast::tanh` a NaN + /// once `exp(2x)` overflows); `fabs`, `sign` and `fract` the device's `FAbs`, `FSign` and + /// `Fract`, their special operands the instruction's (Metal's `sign` of a NaN, a zero and an + /// `f32` denormal is `+0`, its `fract` of an infinity `+0`, where `FSign` keeps a zero's sign + /// and leaves a NaN's answer undefined and `Fract` of an infinity is a NaN); 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 + /// `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 diff --git a/crates/metal2vulkan/src/tests/engine_arith.rs b/crates/metal2vulkan/src/tests/engine_arith.rs index 0b9c892c9..de3589365 100644 --- a/crates/metal2vulkan/src/tests/engine_arith.rs +++ b/crates/metal2vulkan/src/tests/engine_arith.rs @@ -1840,15 +1840,13 @@ fn a_division_without_arcp_is_the_devices_quotient() { } } -/// `air.fast_sincos` on `float` answers as `air.fast_sin` and `air.fast_cos` do (a probe cases -/// 9496749c and 3921d3e2, every lane): `+0` for both past `float(π/2) · 2^22` (`0x4AC90FDB`), which -/// the module compares against, while `air.sincos` keeps the device's functions there. On -/// MoltenVK a module Metal compiles with fast math (no `SignedZeroInfNanPreserve`) takes the -/// device's `Sin` and `Cos`, which are Metal's `fast::sin` and `fast::cos` and answer the flush -/// themselves, so it compares against no limit; elsewhere the flush stays. (The interpreter does -/// not model `Sin`; the shape is the module's.) +/// `air.fast_sincos` on `float`, like `air.sincos`, is the device's `Sin` and `Cos` on every +/// profile, in a fast-math module and out of one: the module compares against no limit (Metal's +/// `fast::sincos` answers `+0` for both past `float(π/2) · 2^22`, `0x4AC90FDB`, where the device +/// answers its functions, `PrecisionNote::NativeTranscendentals` off Metal's own). (The +/// interpreter does not model `Sin`; the shape is the module's.) #[test] -fn fast_sincos_flushes_past_the_last_quadrant() { +fn fast_sincos_is_the_devices_sine_and_cosine() { let body = |call: &str| { format!( " %c = alloca float, align 4\n{} %s = call float @{call}(float %a, ptr %c)\n %cv = load float, ptr %c, align 4\n %r = fadd float %s, %cv\n", @@ -1877,7 +1875,7 @@ fn fast_sincos_flushes_past_the_last_quadrant() { note: None, }; let ks = [ - kernel("fast_sincos_flushes", "air.fast_sincos.f32"), + kernel("fast_sincos_out_of_a_fast_module", "air.fast_sincos.f32"), kernel("sincos_keeps_the_device", "air.sincos.f32"), fast, ]; @@ -1900,12 +1898,7 @@ fn fast_sincos_flushes_past_the_last_quadrant() { && w.len() == 4 && w[3] == 0x4AC9_0FDB }); - let flushes = match kk.name { - "fast_sincos_flushes" => true, - "fast_sincos_in_a_fast_module" => stem != "moltenvk-m3", - _ => false, - }; - assert_eq!(limits > 0, flushes, "{what}: the flush limit"); + assert_eq!(limits, 0, "{what}: a flush limit"); } } } diff --git a/crates/metal2vulkan/src/tests/engine_metal_math.rs b/crates/metal2vulkan/src/tests/engine_metal_math.rs index 177aac630..b83502b42 100644 --- a/crates/metal2vulkan/src/tests/engine_metal_math.rs +++ b/crates/metal2vulkan/src/tests/engine_metal_math.rs @@ -3,14 +3,11 @@ //! device's instructions where none is. On every committed M1 profile each kernel compiles, links, //! and passes L3, and its module holds the instructions of the form it takes: //! -//! - `air.fast_tanh` on `float` is the MSL fast-math formula `(t - 1) / (t + 1)`, -//! `t = exp2(x * 2 log2 e)` of the device's `Exp2` (no `Tanh`), every step of it -//! `NoContraction`, its quotient the device's division (`OpFDiv`); the precise `air.tanh` is the -//! device's `Tanh`. A `half` `fast_tanh` is Metal's `half` `tanh` (Metal's `half` functions are -//! the same in both math modes, and MSL's fast-math formulas are its `float` ones), so it is the -//! device's `Tanh` too (no `Exp2`, no division), noted `NativeTranscendentals` wherever the -//! device's functions are not Metal's own, and on MoltenVK MSL's `float` `tanh` rounded to -//! `half` (`DeviceTranscendentals`); +//! - `air.fast_tanh` is the device's `Tanh` (no `Exp2`, no division) on `float` and `half`, as +//! the precise `air.tanh` is, where MSL Table 8.2 defines Metal's `float` one as the formula +//! `(t - 1) / (t + 1)` of `t = exp(2x)`: noted `NativeTranscendentals` wherever the device's +//! functions are not Metal's own, and on MoltenVK, whose `Tanh` is MSL's precise `tanh` (and a +//! `half` one that rounded to `half`), `DeviceTranscendentals`; //! - `air.sign` is the device's `FSign` with and without fast math (it keeps the sign of a zero //! where Metal answers `+0`), noted `NativeTranscendentals` wherever the device's functions are //! not Metal's own (on MoltenVK it is MSL's own `sign`), and both answer `-1` for `-3` on the @@ -63,33 +60,25 @@ struct Kernel { /// `GLSL.std.450` instructions the module must and must not contain. has: &'static [u32], lacks: &'static [u32], - /// Whether the module divides (`OpFDiv`): `fast::tanh`'s quotient. - divides: bool, /// Whether the module takes the device's instruction for a function Metal defines otherwise, /// recording `NativeTranscendentals` wherever the device's functions are not Metal's own. native: bool, + /// Whether the instruction on MoltenVK is not Metal's own function for the call + /// (`DeviceTranscendentals` there): MSL's precise `tanh` for `fast::tanh`, its `float` one + /// rounded for a `half` one. + off_metal: bool, /// The stored word on the interpreter, when it models the kernel. want: Option, } -const KERNELS: [Kernel; 8] = [ +const KERNELS: [Kernel; 7] = [ Kernel { name: "fast_tanh_float", body: " %a = fadd fast float 0x4046000000000000, -0.0\n %r = call fast float @air.fast_tanh.f32(float %a)\n", - has: &[EXP2], - lacks: &[TANH], - divides: true, - native: false, - want: None, - }, - // RC3 cases e72f550f and 2d5f3949's GELU tail at x = -8: 0.5 * x * (1 + tanh(...)). - Kernel { - name: FAST_TANH_IN_GELU, - body: " %a = fadd fast float 0xC038A66660000000, -0.0\n %x = fadd fast float 0xC020000000000000, -0.0\n %t = call fast float @air.fast_tanh.f32(float %a)\n %s = fadd fast float %t, 1.000000e+00\n %h = fmul fast float %x, 5.000000e-01\n %r = fmul fast float %h, %s\n", - has: &[EXP2], - lacks: &[TANH], - divides: true, - native: false, + has: &[TANH], + lacks: &[EXP2], + native: true, + off_metal: true, want: None, }, Kernel { @@ -97,8 +86,8 @@ const KERNELS: [Kernel; 8] = [ body: " %a = fadd fast float 0x4046000000000000, -0.0\n %r = call fast float @air.tanh.f32(float %a)\n", has: &[TANH], lacks: &[EXP2], - divides: false, native: false, + off_metal: false, want: None, }, Kernel { @@ -106,8 +95,8 @@ const KERNELS: [Kernel; 8] = [ body: " %a = fadd fast float 0x4000000000000000, -0.0\n %h = fptrunc float %a to half\n %t = call fast half @air.fast_tanh.f16(half %h)\n %r = fpext half %t to float\n", has: &[TANH], lacks: &[EXP2], - divides: false, native: true, + off_metal: true, want: None, }, Kernel { @@ -115,8 +104,8 @@ const KERNELS: [Kernel; 8] = [ body: " %a = fadd fast float 0xC008000000000000, -0.0\n %r = call fast float @air.sign.f32(float %a)\n", has: &[FSIGN], lacks: &[], - divides: false, native: true, + off_metal: false, want: Some(0xBF80_0000), }, Kernel { @@ -124,8 +113,8 @@ const KERNELS: [Kernel; 8] = [ body: " %a = fadd float 0xC008000000000000, -0.0\n %r = call float @air.sign.f32(float %a)\n", has: &[FSIGN], lacks: &[], - divides: false, native: true, + off_metal: false, want: Some(0xBF80_0000), }, Kernel { @@ -133,8 +122,8 @@ const KERNELS: [Kernel; 8] = [ body: " %a = fadd fast float 0x3FF0000000000000, -0.0\n %r = call fast float @air.sinpi.f32(float %a)\n", has: &[SIN, ROUND_EVEN], lacks: &[], - divides: false, native: false, + off_metal: false, want: None, }, Kernel { @@ -142,18 +131,12 @@ const KERNELS: [Kernel; 8] = [ body: " %a = fadd fast float 0x3FF0000000000000, -0.0\n %r = call fast float @air.fast_sinpi.f32(float %a)\n", has: &[SIN, ROUND_EVEN], lacks: &[], - divides: false, native: false, + off_metal: false, want: None, }, ]; -/// The kernel whose `fast::tanh` feeds the caller's `1 + tanh` ([`fast_tanh_is_one_operation`]). -const FAST_TANH_IN_GELU: &str = "fast_tanh_in_gelu"; - -/// The `GLSL.std.450 Fma` instruction number. -const FMA: u32 = 50; - fn module() -> String { let mut s = String::from( "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n", @@ -269,22 +252,10 @@ fn metal_math_variants_select_their_forms() { ); } let metal = p.fields().float_functions == FloatFunctions::Metal; - assert_eq!(div, k.divides, "{what}: OpFDiv"); - // The fast-math entry's `fast_tanh` notes its steps' precision (the device's - // `Exp2` and division), except where every step is Metal's own function on the device - // (`FloatFunctions::Metal`), which notes nothing in such an entry. - if k.divides { - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceArithmetic) - && a.precision.contains(&PrecisionNote::NativeTranscendentals), - !metal, - "{what}: {:?}", - a.precision - ); - } + assert!(!div, "{what}: OpFDiv"); // The device's instruction: noted `NativeTranscendentals` wherever the device's - // functions are not Metal's own. On MoltenVK `sign` is MSL's own; a `half` `tanh` is - // MSL's `float` one rounded to `half`, within Apple's bound. + // functions are not Metal's own. On MoltenVK `sign` is MSL's own; `fast::tanh` is + // MSL's precise `tanh`, and a `half` `tanh` MSL's `float` one rounded to `half`. if k.native { assert_eq!( a.precision.contains(&PrecisionNote::NativeTranscendentals), @@ -292,10 +263,9 @@ fn metal_math_variants_select_their_forms() { "{what}: {:?}", a.precision ); - let half = k.name.ends_with("_half"); assert_eq!( a.precision.contains(&PrecisionNote::DeviceTranscendentals), - metal && half, + metal && k.off_metal, "{what}: {:?}", a.precision ); @@ -308,96 +278,6 @@ fn metal_math_variants_select_their_forms() { } } -/// Each float arithmetic result of `words` (`OpFAdd`, `OpFSub`, `OpFMul`, `OpFDiv`, and -/// `GLSL.std.450 Fma`), as its opcode and whether it is decorated `NoContraction`. -fn float_arithmetic(words: &[u32]) -> Vec<(u32, bool)> { - let (mut results, mut exact) = (Vec::new(), Vec::new()); - let arith = [ - crate::spv::Op::FAdd, - crate::spv::Op::FSub, - crate::spv::Op::FMul, - crate::spv::Op::FDiv, - ] - .map(|op| op as u32); - let mut i = 5; - while i < words.len() { - let (len, op) = ((words[i] >> 16) as usize, words[i] & 0xFFFF); - assert!(len > 0 && i + len <= words.len(), "malformed module"); - if op == crate::spv::Op::Decorate as u32 - && words[i + 2] == crate::spv::Decoration::NoContraction as u32 - { - exact.push(words[i + 1]); - } - if arith.contains(&op) || (op == crate::spv::Op::ExtInst as u32 && words[i + 4] == FMA) { - results.push((op, words[i + 2])); - } - i += len; - } - results - .into_iter() - .map(|(op, id)| (op, exact.contains(&id))) - .collect() -} - -/// `air.fast_tanh` is one operation to Metal, so the device may not fuse or regroup any of its -/// steps with the caller's arithmetic. Every step is `NoContraction` whatever the call's flags: -/// `x · 2 log2 e` (in the profile's form: `GLSL.std.450 Fma(a, b, -0.0)` where its `float` -/// functions are Metal's, an `OpFMul` elsewhere), `t - 1`, `t + 1`, and the quotient. The caller's -/// `fast` arithmetic stays undecorated. Without the decorations, Mesa's `lower_flrp` rule turned -/// GELU's `1 + tanh` into `t` on RADV and x86 lavapipe (RC3 cases e72f550f and 2d5f3949, -/// `gelu(-8)`). -#[test] -fn fast_tanh_is_one_operation() { - let Some(bitcode) = assemble() else { - return; - }; - for stem in PROFILES.into_iter().chain(["amd-rdna3-radv", "lavapipe"]) { - let p = profile(stem, exact_maths()).expect("profile"); - let what = format!("{FAST_TANH_IN_GELU} on {stem}"); - let a = - compile(&bitcode, FAST_TANH_IN_GELU, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let ops = float_arithmetic(&words); - let count = |op: crate::spv::Op, exact: bool| { - ops.iter() - .filter(|(o, e)| *o == op as u32 && *e == exact) - .count() - }; - let fma = |exact: bool| { - ops.iter() - .filter(|(o, e)| *o == crate::spv::Op::ExtInst as u32 && *e == exact) - .count() - }; - // The tanh's product is in the profile's form. - let metal = usize::from(p.fields().float_functions == FloatFunctions::Metal); - assert_eq!( - ( - count(crate::spv::Op::FMul, true), - count(crate::spv::Op::FSub, true), - count(crate::spv::Op::FAdd, true), - count(crate::spv::Op::FDiv, true), - fma(true) - ), - (1 - metal, 1, 1, 1, metal), - "{what}: the tanh's steps, NoContraction: {ops:?}" - ); - assert_eq!( - ( - fma(false), - count(crate::spv::Op::FSub, false), - count(crate::spv::Op::FDiv, false), - count(crate::spv::Op::FMul, false), - ), - (0, 0, 0, 2), - "{what}: only the caller's multiplies are left free: {ops:?}" - ); - assert!( - count(crate::spv::Op::FAdd, false) >= 1, - "{what}: the caller's 1 + tanh stays free: {ops:?}" - ); - } -} - /// End to end: the sRGB fixtures through select, emit, and link on every profile above: L3 passes, /// and each module takes the MSL transfer functions by the device's `Pow` around the 8-bit /// instruction (`a1_srgb_decode_all_bytes`: `UnpackUnorm4x8`, its `float` and `half` results; diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 6d77121eb..1dd5b84df 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -1318,10 +1318,11 @@ fn content_digests_name_what_a_pipeline_says_not_its_build() { /// The precision contract is public: a fast `float` division records the device's arithmetic, /// Metal's precise division records the device's division, its denormals and its NaN /// (`NativeDivision`, `DeviceDenormals`, `NativeNanEncoding`), an integer operator has no notes, and -/// a fast `float` `tanh`, which the crate computes with a division of its own, records the device's -/// arithmetic, on a profile whose `float` functions are the device's (lavapipe's); on one whose -/// functions are Metal's own (MoltenVK's), both are Metal's own in a fast-math entry and record -/// nothing there, and the division records its note in an entry that keeps NaNs. +/// a fast `float` `tanh`, the device's `Tanh`, records the device's transcendental, on a profile +/// whose `float` functions are the device's (lavapipe's); on one whose functions are Metal's own +/// (MoltenVK's), a fast-math division is Metal's own and records nothing, the division records its +/// note in an entry that keeps NaNs, and a fast `tanh` records that its `Tanh` is Metal's precise +/// function, not the fast one (`DeviceTranscendentals`). #[test] fn the_precision_contract_names_each_float_operations_notes() { use metal2vulkan_air::intrinsics::AirIntrinsic; @@ -1372,10 +1373,16 @@ fn the_precision_contract_names_each_float_operations_notes() { }; let notes = PrecisionNote::of_math_call(tanh, fast, lavapipe, EntryMath::Fast) .expect("a float function"); - assert!(notes.contains(&PrecisionNote::DeviceArithmetic)); + assert!( + notes.contains(&PrecisionNote::NativeTranscendentals), + "{notes:?}" + ); let notes = PrecisionNote::of_math_call(tanh, fast, moltenvk, EntryMath::Fast) .expect("a float function"); - assert!(notes.is_empty(), "{notes:?}"); + assert!( + notes.contains(&PrecisionNote::DeviceTranscendentals), + "{notes:?}" + ); } /// A render pipeline with a signed-integer color attachment compiles its fragment function with the diff --git a/docs/API.md b/docs/API.md index 1bd082224..9b6a720dd 100644 --- a/docs/API.md +++ b/docs/API.md @@ -242,8 +242,9 @@ measured takes the route each deviation's docs name for it: the device's own ans precision note, or, where the answer decides a capability, its emulation or a refusal. Metal semantics the translation keeps on every device, beyond Vulkan's: Metal's 32-lane -simdgroups (including lockstep races on threadgroup memory within a barrier interval), and the -bit-exact `fneg` and `fabs` of a `float`, its NaNs and denormals included. A NaN's bits, the +simdgroups (including lockstep races on threadgroup memory within a barrier interval). `fneg` and +`fabs` are the device's `OpFNegate` and `FAbs`, so a NaN's payload and a denormal are the +device's (`native-nan-encoding`, `device-denormals`). A NaN's bits, the operand `fmin`, `fmax`, `min3`, `max3`, `clamp` and `saturate` pick beside a NaN or between two zeros, a `half` read from its bits, which is the device's widening on every device (a NaN's bits, and a denormal on a device that may flush 16-bit ones), and a `half` rounded from a value @@ -3170,11 +3171,17 @@ bound. Native device maths: the module computes a `float` or `half` math-library function by the device's own `GLSL.std.450` instruction (`exp`, `log`, `pow`, `sinh`, `cosh` and `tanh` among them; a composition of the device's `Exp2` and `Log2` only for `exp10` and `log10`, which no instruction - is) where Metal's function is not the device's own; `fast::sqrt` the device's `Sqrt`; `fabs`, - `sign` and `fract` the device's `FAbs`, `FSign` and `Fract`, their special operands the - instruction's (Metal's `sign` of a NaN, a zero and an `f32` denormal is `+0`, its `fract` of an - infinity `+0`); and `round` C99's from the device's `Trunc` on every device (`round(-0.3)` is - `-0`, where Metal answers `+0`). + is) where Metal's function is not the device's own; `fast::sqrt` the device's `Sqrt`; the fast + `sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh` and `atanh` the device's instructions, not MSL's + fast-math formulas (`fast::sin` of `1e7` is the device's sine, where Metal answers `+0`; + `fast::tanh(45)` is `1`, where Metal answers NaN); `fabs`, `sign` and `fract` the device's + `FAbs`, `FSign` and `Fract`, their special operands the instruction's (Metal's `sign` of a NaN, + a zero and an `f32` denormal is `+0`, its `fract` of an infinity `+0`); 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`). - `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 diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 5f17a13f2..3938b09ec 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -55,12 +55,12 @@ known. The rest of the differences are docs/API.md section 9's precision notes. | What it is | Why there is no switch | Note, code | |---|---|---| -| The maths library (`sin`, `exp`, `log`, `pow`, `sinh`, `cosh`, `tanh`, `atan2`...) on `float` and `half`, fast divisions and Metal's fast reciprocal, a `half` fused multiply-add, and a `float` one without `OpFmaKHR` are the device's instructions on every device whose `float` functions are not Metal's own (every device but MoltenVK, whose functions are Metal's in a fast-math entry; a `half` function is the `float` instruction rounded on every device); Metal's precise division (an `fdiv` without `arcp`, or on `half`) is the device's `OpFDiv` on every device. `fabs`, `sign` and `fract` are `FAbs`, `FSign` and `Fract`, their special operands (a NaN, an infinity, a signed zero, an `f32` denormal) the instruction's; `round` is C99's from `Trunc` on every device (`round(-0.3)` is `-0`, Metal's `+0`). | The device's arithmetic is the contract: no routine computes Metal's answer where the device has an instruction. | Vulkan's precision table (`Sin` 2^-11 absolute in [-π, π], `Exp` 3 + 2·\|x\| ulp, `Log` 3 ulp or 2^-21 absolute in [0.5, 2], `Pow` from `Exp2(y · Log2 x)`, `FAbs`, `FSign` and `Fract` correct or correctly rounded, `Atan` 4096 ulp) against Metal's 4-6 ulp; division 2.5 ulp; `fma` one `half` ulp (a `float` one may round twice). `NativeTranscendentals` (`native-transcendentals`), `NativeDivision` (`native-division`), `NativeFma` (`native-fma`) | +| 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`) | | `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`) | | Off MoltenVK a `float` multiply, and a fused multiply-add by `OpFmaKHR`, round before Metal's flush: Metal flushes a result whose exact value lies below `2^-126` before rounding it, so a result whose exact value lies within half a unit below `2^-126` answers `2^-126` of its sign where Metal answers the zero of its sign. | Every device measured off MoltenVK (RADV, ANV, NVIDIA, lavapipe) rounds first; its multiply is the contract. | Announced once per device as it is made: `float-tininess-after-rounding` | -| `f32` denormals in a `float` operation on a device not measured to read them as Metal does (`DriverDeviation::MetalFloatDenormals`: lavapipe, and every unmeasured device), in `floor`, `ceil` and `fneg` on every device, in the maths functions (`fabs`, `sign` and `fract` among them) and the device's order of the rows above, and in a conversion to or from `double`. Metal reads them as zero and flushes a denormal result. | The device's reading is the contract: Vulkan lets each device keep or flush them, and Metal runs no `double`, so its reading of a conversion is not measured. | `DeviceDenormals` (`device-denormals`) | +| `f32` denormals in a `float` operation on a device not measured to read them as Metal does (`DriverDeviation::MetalFloatDenormals`: lavapipe, and every unmeasured device), in `floor`, `ceil` and `fneg` on every device, in the maths functions (`fabs`, `sign` and `fract` among them, and the zero and sign tests of `pow`, `powr` and `atan2`) and the device's order of the rows above, and in a conversion to or from `double`. Metal reads them as zero and flushes a denormal result. | The device's reading is the contract: Vulkan lets each device keep or flush them, and Metal runs no `double`, so its reading of a conversion is not measured. | `DeviceDenormals` (`device-denormals`) | | Samples, gathers, depth comparisons and level queries are the device's own sampler's on every device whose sampler is not Metal's (every device but MoltenVK): its filter, footprint, level, anisotropy, sRGB decode and comparison, its level clamp (the descriptor's as given, which Metal holds on a `1/64` grid) and its reading of a subnormal coordinate (which Metal reads as the zero of its sign before addressing). A sample's or gather's residency on a device with `shaderResourceResidency` is the device's `OpImageSparse*` word and non-resident value (`SparseResidency`); Metal's footprint rule answers it only where the device has no residency and the slot's tile map does. A two-plane YCbCr texture's linear sample is the device's filter of its texels (the device's own Y′CbCr conversion's where it converts the format, next row; Metal's reads exactly elsewhere); where the device's memory is the host's, a sample that reads the planes in place is Metal's filter exactly. An 8-bit sRGB format the device cannot sample (`R8_SRGB` on lavapipe, `R8G8_SRGB` on lavapipe, ANV and NVIDIA) is held as its UNORM twin, the device lacking its decode: a read, a sample, a fetch, a gather and a bicubic tap decode what the twin's view reads (one texel's codes, or the device's filter of them) by the MSL transfer through the device's `Pow`. | The device's sampler is the contract. | Linear filter within one code (1/255) on the measured devices, sRGB within 1.83, a two-plane YCbCr texture's within 1.183; levels, anisotropy, cubes, 3D, gathers and comparisons unmeasured. A twin's texel: the transfer within the device's `Pow` (MoltenVK's within 1.83e-7 through a storage alias, `runtime_lane::srgb_storage`) where Metal's table rounds it to a twelve-bit step (up to 1/8190 apart); a filtered sample decodes the filtered codes, up to 0.286 off for a blend of codes 0 and 255 (`SrgbTexelDecode`). `DeviceSampling` (`device-sampling`) | | A pixel-coordinate sampler's sample, gather, comparison and level query is the device's sampler's at the coordinate divided by the texture's level-0 size in the shader, on every device, MoltenVK included: the device reads its texels from that coordinate in its own arithmetic, where Metal reads the coordinate as given (its nearest texel `floor(x)`, its filter's footprint from `x`). A constexpr pixel sampler that filters nearest and clamps to the edge fetches its texel (`sampler.pixel_fetch`), as does an argument buffer's sample without a comparison through a state that does. | The device's sampler is the contract. Vulkan's unnormalized samplers take no gather, offset, comparison, array, 3D image or level of detail, so the shader scales the coordinate; nothing reproduces Metal's position at a texel edge. | The device answers as its normalized sampler at a coordinate within one `f32` ulp of the quotient on MoltenVK (10 of 800 cells of each mirror-clamp configuration move by it; a nearest sample at a texel edge then reads the neighbouring texel) and at the quotient itself on lavapipe (`runtime_lane::pixel_samplers`: 800 coordinates at and around each texel edge of a 5x3 texture, every filter and address mode); a linear downscale by 8 of textures 1000 to 1920 texels wide within 1/255 of Metal's on MoltenVK and 2/255 on lavapipe (`runtime_lane::pixel_downscales`); other devices unmeasured. `PixelSamplerScaling` (`pixel-sampler-scaling`), `ArgumentPixelSamplerScaling` (`argument-pixel-sampler-scaling`) | | A two-plane YCbCr texture's texels are the device's own sampler Y′CbCr conversion of its planes where the device converts their format (`ycbcr_device.rs`): unpacked 8- or 10-bit codes of a 4:2:0, 4:2:2 or 4:4:4 layout over plane 0 that form one image (no chroma codes 0, no rows past the buffer; a 4:4:4 layout read as codes aside, whose identity conversion converts nothing), on a device that enables `samplerYcbcrConversion` (a 4:4:4 layout also needs Vulkan 1.3 or `VK_EXT_ycbcr_2plane_444_formats`), reports the multi-planar format's conversion and, for a 4:2:0 or 4:2:2 layout, Metal's reconstruction (midpoint chroma through a linear chroma filter), and has no defect in the format; the planes are copied into an image of it and sampled once per texel into the texture's image (`bind::ycbcr_sample_module`), through the refresh's indirect arguments. The conversion takes the surface's matrix and range (the identity model for the code-reading formats), and Metal's reconstruction of a subsampled layout; a device's cosited or nearest reconstruction would move what the codes mean to Metal (cosited, up to 1340/2048 of random planes on lavapipe), a capability it lacks, so such a layout converts through Metal's arithmetic. A render pass's load stays Metal's arithmetic, which our store inverts, so a loaded texel no draw changes keeps its codes, as `MTLLoadActionLoad` keeps the attachment's contents. lavapipe (Mesa 26.0.8) converts the 8-bit 4:4:4 layout (its 4:2:0 and 4:2:2 ones are cosited only, and it reads 10-bit codes as 16-bit words, `RuntimeDriverDefect::TenBitCodesReadAsWords`); MoltenVK 1.4.2 converts none (its 4:2:0 and 4:2:2 reconstruction is misplaced, `RuntimeDriverDefect::TwoPlaneChromaMisplaced`, and it reports no 4:4:4 two-plane format). RADV (Mesa 26.2.4) reads 10-bit codes as 16-bit words too (measured on a linear image of the 4:2:0 format on the Radeon 780M), so its 10-bit layouts convert through Metal's arithmetic. Elsewhere, and for packed codes, chroma codes 0 and plane 1, Metal's fixed-point conversion stays as capability (`WorkCounts::ycbcr_device_conversions`). | The device's conversion is the contract: Vulkan states the reconstruction's weights and the model's matrices, the precision of each step at least the format's, and the clamp of the result into `[0, 1]` the implementation's. | Each channel within 0.04/2048 of Vulkan's conversion past the `half` its image stores on lavapipe's 8-bit 4:4:4 layout; of Metal's read within 6/2048 where the result lies in `[0, 1]`, and unclamped outside it (random planes, every texel, `tests/ycbcr_device.rs`). `YCbCrFilterNotExact` (`ycbcr-filter-not-exact`) |