diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 071d46f30..310518fc3 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2018,18 +2018,16 @@ degradations! { VisibilityCountPerColor = "visibility-count-per-color", Precision, "the result is Metal's count multiplied by the colors the draw writes; a `Boolean` \ result is Metal's"; - /// A device whose policy takes native device maths (`FloatMathsPolicy::Native`, the - /// default) where its float functions are not Metal's own (not MoltenVK, + /// A device whose float functions are not Metal's own (not MoltenVK, /// `DriverDeviation::MetalFloatFunctions`): Metal flushes a `float` product or fused /// multiply-add whose exact value lies below `2^-126` to the zero of its sign, deciding /// tininess before rounding, and the device rounds before it decides (measured on RADV, /// ANV, NVIDIA and lavapipe, whether they flush denormals or keep them), so the device's /// multiply and fused multiply-add answer `2^-126` there (`device/float_tininess.rs`). - /// Announced once, as the device is made; the payload names the device and its policy. + /// Announced once, as the device is made; the payload names the device. FloatTininessAfterRounding = "float-tininess-after-rounding", Precision, "a `float` product or fused multiply-add 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; \ - `FloatMathsPolicy::Exact` computes Metal's"; + below `2^-126` answers `2^-126` of its sign where Metal answers the zero of its sign"; /// An entry of the device's shader cache directory was not written: the directory, a /// temporary file in it or the rename over the entry failed, on the device's cache thread /// or on the thread that handed the entry over past the queue's bound @@ -2113,29 +2111,23 @@ degradations! { /// selection, anisotropy, cube maps, 3D textures, gathers, comparisons and offsets are /// not measured. DeviceSampling = "device-sampling"; - /// Class: native device maths. The device's `GLSL.std.450` instruction answers a `float` - /// or `half` math-library call where Metal's answer would be computed by a routine - /// (`FloatMathsPolicy::Native`, the default on a device whose functions are not Metal's - /// own; `FloatMathsPolicy::Exact` keeps Metal's), and the device's `Sqrt` answers - /// `fast::sqrt` where Metal's `x · rsqrt(x)` would be computed - /// (`RoundingOrderPolicy::Native`, the default). Recorded bound: Vulkan's precision table - /// for the instruction: `Exp2` and `Exp` 3 + 2·|x| ulp; `Log2` and `Log` 3 ulp outside - /// `[0.5, 2]`, `2^-21` absolute inside; `Pow` from `Exp2(y · Log2(x))`; `Sqrt` from `1 / - /// InverseSqrt`; `InverseSqrt` 2 ulp; `Sin` and `Cos` `2^-11` absolute in `[-π, π]`; `Tan` - /// from `Sin / Cos`; `Asin`, `Acos`, `Atan` and `Atan2` 4096 ulp. + /// Class: native device maths. The device's `GLSL.std.450` instruction answers a `float` or + /// `half` math-library call that is not Metal's own function on the device, and the + /// device's `Sqrt` answers `fast::sqrt`, Metal's `x · rsqrt(x)`. Recorded bound: Vulkan's + /// precision table for the instruction: `Exp2` and `Exp` 3 + 2·|x| ulp; `Log2` and `Log` 3 + /// ulp outside `[0.5, 2]`, `2^-21` absolute inside; `Pow` from `Exp2(y · Log2(x))`; `Sqrt` + /// from `1 / InverseSqrt`; `InverseSqrt` 2 ulp; `Sin` and `Cos` `2^-11` absolute in + /// `[-π, π]`; `Tan` from `Sin / Cos`; `Asin`, `Acos`, `Atan` and `Atan2` 4096 ulp. NativeTranscendentals = "native-transcendentals"; /// Class: native device maths. The device's `OpFDiv` answers a precise or fast `float` or - /// `half` division where Metal's correctly rounded quotient or `x · RN(1 / y)` would be - /// computed (`FloatMathsPolicy::Native`, the default; `Exact` keeps Metal's). Recorded - /// bound: 2.5 ulp of the quotient (a precise division's operands past a divisor of - /// `2^126` scaled into Vulkan's range exactly); a `half` quotient within one unit in its - /// last place. + /// `half` division, where Metal's is its correctly rounded quotient or its `x` times its + /// fast reciprocal. Recorded bound: 2.5 ulp of the quotient (a precise division's operands + /// past a divisor of `2^126` scaled into Vulkan's range exactly); a `half` quotient within + /// one unit in its last place. NativeDivision = "native-division"; /// Class: native device maths. The device's `GLSL.std.450 Fma` answers a `half` fused - /// multiply-add on a device whose 16-bit `Fma` is not measured to be Metal's and that has - /// no 16-bit `OpFmaKHR` under the 16-bit float controls, on every policy, or a `float` one - /// on a device without `OpFmaKHR`, where the correctly rounded routine would - /// (`FloatMathsPolicy::Native`, the default; `Exact` keeps Metal's). Recorded bound: a `half` result within one unit in its last place of Metal's; a + /// multiply-add, or a `float` one on a device without `OpFmaKHR`, where Metal's rounds + /// once. Recorded bound: a `half` result within one unit in its last place of Metal's; a /// `float` one within half a unit in the last place of the product plus half a unit in /// the last place of the result. NativeFma = "native-fma"; @@ -2182,19 +2174,17 @@ degradations! { /// second), and an `f32` denormal beside a zero or another denormal compared by its value /// where the device keeps denormals (Metal compares it as a zero and answers the second). NativeMinMax = "native-min-max"; - /// Class: native device maths. The device's `OpDot` answers Metal's `dot` on `float`, or - /// on `half` where its fused multiply-add is not the measured 16-bit one (summed in - /// `float`, rounded once to `half`), where Metal's fused chain of its products would be - /// computed (`RoundingOrderPolicy::Native`, the default; `Exact` keeps Metal's). Recorded + /// Class: native device maths. The device's `OpDot` answers Metal's `dot` on `float`, or on + /// `half` where its fused multiply-add is not the measured 16-bit one (summed in `float`, + /// rounded once to `half`), where Metal's is the fused chain of its products. Recorded /// bound: a `float` `dot` of `n` lanes within `(3n - 1) * 2^-24 * sum |a_i * b_i|` of /// Metal's chain, plus `n * 2^-126` where a product is an `f32` denormal the device keeps; /// a `half` one within `(n + 3) * 2^-11 * sum |a_i * b_i| + (n + 2) * 2^-25`. NativeDot = "native-dot"; /// Class: native device maths. The device's `FMix` answers Metal's `mix(x, y, t)` on /// `float`, or on `half` where its fused multiply-add is not the measured 16-bit one - /// (computed in `float`, rounded once to `half`), where Metal's - /// `fma(t, y, fma(-t, x, x))` would be computed (`RoundingOrderPolicy::Native`, the - /// default; `Exact` keeps Metal's). Recorded bound: a `float` result within `2^-21 * (|x * + /// (computed in `float`, rounded once to `half`), where Metal's is + /// `fma(t, y, fma(-t, x, x))`. Recorded bound: a `float` result within `2^-21 * (|x * /// (1 - t)| + |y * t|)` of Metal's; a `half` one within `3 * 2^-10 * (|x * (1 - t)| + |y * /// t|) + 2^-23`. NativeMix = "native-mix"; @@ -2629,17 +2619,13 @@ pub(crate) fn dropped_exact_forms( dependencies.iter().find_map(|d| match d.fact { metal2vulkan::pipeline::RuntimeFact::ExactFormsOverCompilerLimit { sampling, - float_maths, texel_conversion, nan_and_min_max, - rounding_order, } => Some( [ (sampling, "exact sampling"), - (float_maths, "exact float maths"), (texel_conversion, "exact texel conversion"), (nan_and_min_max, "exact NaN and minimum and maximum"), - (rounding_order, "exact rounding order"), ] .into_iter() .filter_map(|(dropped, name)| dropped.then_some(name)) diff --git a/crates/metal2vulkan-runtime/src/device/float_tininess.rs b/crates/metal2vulkan-runtime/src/device/float_tininess.rs index d46c6f9bc..2a090da24 100644 --- a/crates/metal2vulkan-runtime/src/device/float_tininess.rs +++ b/crates/metal2vulkan-runtime/src/device/float_tininess.rs @@ -3,25 +3,19 @@ //! below `2^-126` to the zero of its sign, deciding tininess before rounding; every Vulkan device //! measured off MoltenVK (RADV, ANV, NVIDIA and lavapipe, whether they flush denormals or keep //! them) rounds before it decides, so an exact value within half a unit below `2^-126` answers -//! `2^-126`. -//! Under `FloatMathsPolicy::Exact` the translation computes Metal's answer (the multiply's check of -//! its operands' bits, the fused multiply-add's routine); under native device maths it takes the -//! device's, which every pipeline of a `float` multiply may meet, so the device announces it once, -//! as it is made, rather than each pipeline. +//! `2^-126`. The translation takes the device's, which every pipeline of a `float` multiply may +//! meet, so the device announces it once, as it is made, rather than each pipeline. use crate::degradation::Degradation; -use metal2vulkan::device::FloatMathsPolicy; use metal2vulkan::error::DriverDeviation; /// Whether `compile` takes the device's own `float` multiply and fused multiply-add where they -/// round a tiny result before flushing it: its policy takes native device maths -/// (`FloatMathsPolicy::Native`) and its float functions are not Metal's own +/// round a tiny result before flushing it: its float functions are not Metal's own /// (`DriverDeviation::MetalFloatFunctions`, MoltenVK). pub(crate) fn rounds_before_flushing(compile: &metal2vulkan::device::Device) -> bool { - compile.policy().float_maths == FloatMathsPolicy::Native - && !compile - .profile() - .takes_driver_deviation(DriverDeviation::MetalFloatFunctions) + !compile + .profile() + .takes_driver_deviation(DriverDeviation::MetalFloatFunctions) } impl super::Device { @@ -34,9 +28,7 @@ impl super::Device { self.degrade(Degradation::FloatTininessAfterRounding, || { ( format!("the device {}", self.name()), - "its policy takes native device maths (`FloatMathsPolicy::Native`), and its \ - `float` multiply and fused multiply-add round before they flush" - .to_owned(), + "its `float` multiply and fused multiply-add round before they flush".to_owned(), ) }); } diff --git a/crates/metal2vulkan-runtime/src/tests/device.rs b/crates/metal2vulkan-runtime/src/tests/device.rs index dff47b8cb..0b6ab2e09 100644 --- a/crates/metal2vulkan-runtime/src/tests/device.rs +++ b/crates/metal2vulkan-runtime/src/tests/device.rs @@ -817,40 +817,29 @@ fn a_binding_is_seen_complete_only_once_a_host_wait_returned_for_it() { assert_eq!(asked, [5, 5, 5]); } -/// `float-tininess-after-rounding`'s condition (`device/float_tininess.rs`): under native device -/// maths (`FloatMathsPolicy::Native`, the default) every committed profile's device but MoltenVK's, -/// whose float functions are Metal's own, takes the device's `float` multiply and fused -/// multiply-add, which round a tiny result before they flush it; under `FloatMathsPolicy::Exact` -/// none does. +/// `float-tininess-after-rounding`'s condition (`device/float_tininess.rs`): every committed +/// profile's device but MoltenVK's, whose float functions are Metal's own, takes the device's +/// `float` multiply and fused multiply-add, which round a tiny result before they flush it. #[test] -fn native_device_maths_rounds_a_tiny_product_before_its_flush_off_moltenvk() { +fn the_device_s_multiply_rounds_a_tiny_product_before_its_flush_off_moltenvk() { use crate::device::float_tininess::rounds_before_flushing; - use metal2vulkan::device::FloatMathsPolicy; let (mut rounding, mut metals) = (0, 0); for (path, description) in descriptions() { let moltenvk = path .file_stem() .is_some_and(|stem| stem.to_string_lossy().starts_with("moltenvk")); - for float_maths in [FloatMathsPolicy::Native, FloatMathsPolicy::Exact] { - let mut options = DeviceOptions::default(); - options.policy.float_maths = float_maths; - let set = enable_set(&description, &options); - let enabled = description - .clone() - .with_enabled(&set) - .unwrap_or_else(|error| panic!("{path:?}: {error:?}")); - let compile = metal2vulkan::device::Device::new(enabled, options.policy) - .unwrap_or_else(|error| panic!("{path:?}: {error:?}")); - let rounds = rounds_before_flushing(&compile); - let native = float_maths == FloatMathsPolicy::Native; - assert_eq!( - rounds, - native && !moltenvk, - "{path:?} under {float_maths:?}" - ); - rounding += usize::from(rounds); - metals += usize::from(native && moltenvk); - } + let options = DeviceOptions::default(); + let set = enable_set(&description, &options); + let enabled = description + .clone() + .with_enabled(&set) + .unwrap_or_else(|error| panic!("{path:?}: {error:?}")); + let compile = metal2vulkan::device::Device::new(enabled, options.policy) + .unwrap_or_else(|error| panic!("{path:?}: {error:?}")); + let rounds = rounds_before_flushing(&compile); + assert_eq!(rounds, !moltenvk, "{path:?}"); + rounding += usize::from(rounds); + metals += usize::from(moltenvk); } assert!( rounding > 0 && metals > 0, diff --git a/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs b/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs index 9f9def9bd..3dea8d5ef 100644 --- a/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs +++ b/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs @@ -71,15 +71,13 @@ fn library(name: &str) -> Library { Library::from_air(&bitcode).unwrap() } -/// Add to `dependencies` the fit's record of dropping exact sampling and exact float maths. +/// Add to `dependencies` the fit's record of dropping exact sampling and exact texel conversion. fn fit_into(dependencies: &mut Vec) { dependencies.push(RuntimeDependency::new( RuntimeFact::ExactFormsOverCompilerLimit { sampling: true, - float_maths: true, - texel_conversion: false, + texel_conversion: true, nan_and_min_max: false, - rounding_order: false, }, Mechanism::None, )); @@ -195,8 +193,8 @@ fn a_variant_fitted_while_its_base_was_not_still_announces() { let (object, reason) = &said[0]; assert_eq!(object, "a render pipeline state"); assert!( - reason.contains("exact sampling, exact float maths") - && !reason.contains("exact half blend"), + reason.contains("exact sampling, exact texel conversion") + && !reason.contains("exact NaN and minimum and maximum"), "{reason}" ); // Once per device: a later fitted variant adds no second notice. @@ -242,7 +240,7 @@ fn every_kind_of_fitted_pipeline_announces_its_state_kind() { assert_eq!(said.len(), 1, "{said:?}"); assert_eq!(said[0].0, "a compute pipeline state"); assert!( - said[0].1.contains("exact sampling, exact float maths"), + said[0].1.contains("exact sampling, exact texel conversion"), "{said:?}" ); diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index f1aafa5ba..3862e06b1 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -8dfdbe852e2042225ae5ecaa4677869e32417533984dbe01f946d00bbdc2bce9 +3d4df3af6a75270a98fba273007ec0aa849a57a434bd7b5a61058b6ba89b9c39 diff --git a/crates/metal2vulkan-validation/src/bin/corpus-draw-ab.rs b/crates/metal2vulkan-validation/src/bin/corpus-draw-ab.rs index 96f0f303f..2e143d31f 100644 --- a/crates/metal2vulkan-validation/src/bin/corpus-draw-ab.rs +++ b/crates/metal2vulkan-validation/src/bin/corpus-draw-ab.rs @@ -110,9 +110,8 @@ //! `--policy NAMES` (`run` and `time`) opens the device with those `DevicePolicy` switches at their //! accurate forms, where it opens at the default policy otherwise: a comma-separated list of //! `exact-answers` (`DevicePolicy::exact_answers`) and field names (`sampling`, `ycbcr_filter`, -//! `float_maths`, `texel_conversion`, `nan_and_min_max`, `rounding_order`), each set to its -//! `Exact` form, so a making under an application's exact forms is -//! timed as it makes them. +//! `texel_conversion`, `nan_and_min_max`), each set to its `Exact` form, so a making under an +//! application's exact forms is timed as it makes them. //! //! `--device-type` names the device the draw runs on, as validation's other device commands do //! (`cpu` matches only a CPU implementation such as lavapipe); the device opens through @@ -149,8 +148,7 @@ use metal2vulkan::bind::SamplerDescriptor; use metal2vulkan::device::{ - DevicePolicy, FloatMathsPolicy, NanMinMaxPolicy, RoundingOrderPolicy, SamplingPolicy, - TexelConversionPolicy, YCbCrFilterPolicy, + DevicePolicy, NanMinMaxPolicy, SamplingPolicy, TexelConversionPolicy, YCbCrFilterPolicy, }; use metal2vulkan::metal::state::DepthStencilDescriptor; use metal2vulkan::metal::CompareFunction; @@ -317,14 +315,12 @@ fn policy(options: &BTreeMap) -> Result { "exact-answers" => policy = policy.exact_answers(), "sampling" => policy.sampling = SamplingPolicy::Exact, "ycbcr_filter" => policy.ycbcr_filter = YCbCrFilterPolicy::Exact, - "float_maths" => policy.float_maths = FloatMathsPolicy::Exact, "texel_conversion" => policy.texel_conversion = TexelConversionPolicy::Exact, "nan_and_min_max" => policy.nan_and_min_max = NanMinMaxPolicy::Exact, - "rounding_order" => policy.rounding_order = RoundingOrderPolicy::Exact, _ => { return Err(format!( - "--policy {name:?}: exact-answers, sampling, ycbcr_filter, float_maths, \ - texel_conversion, nan_and_min_max or rounding_order" + "--policy {name:?}: exact-answers, sampling, ycbcr_filter, texel_conversion \ + or nan_and_min_max" )) } } diff --git a/crates/metal2vulkan-validation/src/c3/bound.rs b/crates/metal2vulkan-validation/src/c3/bound.rs index dd15bbbef..faede801f 100644 --- a/crates/metal2vulkan-validation/src/c3/bound.rs +++ b/crates/metal2vulkan-validation/src/c3/bound.rs @@ -421,8 +421,7 @@ impl Difference<'_> { /// `float` forms only). /// /// Each reason names the exact path that would close the value: the canonicalizing or flushing -/// select (or `DenormFlushToZero` where a profile offers it), which Metal's precise and fast float -/// divisions already take, so neither records these notes. +/// select (or `DenormFlushToZero` where a profile offers it). fn value_near_equivalent( recorded: &BTreeSet, expr: &Expr, diff --git a/crates/metal2vulkan-validation/src/c3/bound/tests.rs b/crates/metal2vulkan-validation/src/c3/bound/tests.rs index ece3fb95f..96368025c 100644 --- a/crates/metal2vulkan-validation/src/c3/bound/tests.rs +++ b/crates/metal2vulkan-validation/src/c3/bound/tests.rs @@ -454,8 +454,20 @@ fn fast_atan2_past_the_divisors_domain_is_unstated() { /// The verdict on one `float` word computing `computes` of the `float` bit patterns `operands` /// under `math`, where Metal answers `metal` and the device `device`, in a row recording -/// `recorded`. +/// `recorded`, on lavapipe. fn verdict_of( + computes: &str, + math: Math, + operands: &[u32], + answers: (u32, u32), + recorded: &[PrecisionNote], +) -> WordVerdict { + verdict_on(lavapipe(), computes, math, operands, answers, recorded) +} + +/// [`verdict_of`] on `profile`'s device. +fn verdict_on( + profile: &DeviceProfile, computes: &str, math: Math, operands: &[u32], @@ -480,7 +492,7 @@ fn verdict_of( &lanes, &[], &recorded.iter().copied().collect(), - lavapipe(), + profile, &metal.to_le_bytes(), &device.to_le_bytes(), ) @@ -588,10 +600,10 @@ fn a_nan_encoding_the_product_answers_is_not_a_near_equivalent() { /// in an operation whose lowering records `DeviceDenormals` and the row records the note, the value /// stays open even though section 8.5 lets a denormal be flushed or not. Fast `sinpi` is such an /// operation: its lowering is not among those that answer Metal at `float` denormals themselves -/// (`FloatFn::metal_denormals`; precise `fmod` is one). The product's `float` `+ - *` read and -/// flush denormals as Metal does on every profile (the device's where a measured fact states it, -/// else the module's flushes), and Metal's precise and fast divisions flush their own subnormals, -/// so none records the note and a product's or quotient's subnormal keeps Apple's verdict, even +/// (`FloatFn::metal_denormals`; precise `fmod` is one). The product's `float` `+ - *` and +/// divisions are the device's: on lavapipe, which is not measured to read denormals as Metal does, +/// each records the note, so a product's or quotient's subnormal stays open too; where the device +/// is measured to (MoltenVK), a product records none and its subnormal keeps Apple's verdict, even /// where the row records the note for another operation. A value no subnormal touches keeps its /// verdict. #[test] @@ -622,22 +634,33 @@ fn a_denormal_the_device_keeps_stays_open() { assert!(open.detail().contains(part), "{part}: {open:?}"); } assert_eq!(sinpi(&[]), WordVerdict::Within); - // `tiny * 1`: the product's multiply flushes on every profile, so the row's note is not its. - let product = verdict_of( - "mul(a, b)", - Math::Precise, - &[tiny, one], - (0, tiny), - &denormals, - ); - assert_eq!(product, WordVerdict::Within); + // `tiny * 1`: lavapipe's multiply keeps the subnormal, so the row's note is its; MoltenVK's + // reads it as Metal does, so the note is not its. + let product = |profile| { + verdict_on( + profile, + "mul(a, b)", + Math::Precise, + &[tiny, one], + (0, tiny), + &denormals, + ) + }; + let kept = product(lavapipe()); + assert_eq!(kept.label(), "near_equivalent", "{kept:?}"); + assert!(kept.detail().contains("(Metal's mul)"), "{kept:?}"); + assert_eq!(product(moltenvk()), WordVerdict::Within); // A quotient below the smallest normal (2^-100 / 2^30): Metal's +0, the device's 2^-130. let bits = |e| (pow2(e) as f32).to_bits(); let (num, den) = (bits(-100), bits(30)); let quotient = bits(-130); for math in [Math::Precise, Math::Fast] { let division = verdict_of("div(a, b)", math, &[num, den], (0, quotient), &denormals); - assert_eq!(division, WordVerdict::Within, "{math:?}"); + assert_eq!( + division.label(), + "near_equivalent", + "{math:?}: {division:?}" + ); } // A subnormal intermediate the next operation scales back up: fast::sinpi(2^-140) * 2^30, // +0 where the operand is read as zero, and the subnormal pi * 2^-140 scaled by 2^30 where @@ -652,16 +675,21 @@ fn a_denormal_the_device_keeps_stays_open() { &denormals, ); assert_eq!(scaled.label(), "near_equivalent", "{scaled:?}"); - // The same through two multiplies (2^-140 * 2^-1 * 2^30): the product flushes the - // intermediate as Metal does, so the row's note is not the multiplies'. - let multiplied = verdict_of( - "mul(mul(a, b), c)", - Math::Precise, - &[small, bits(-1), big], - (0, bits(-111)), - &denormals, - ); - assert_eq!(multiplied, WordVerdict::Within); + // The same through two multiplies (2^-140 * 2^-1 * 2^30): lavapipe keeps the intermediate, + // MoltenVK reads it as Metal does. + let multiplied = |profile| { + verdict_on( + profile, + "mul(mul(a, b), c)", + Math::Precise, + &[small, bits(-1), big], + (0, bits(-111)), + &denormals, + ) + }; + let kept = multiplied(lavapipe()); + assert_eq!(kept.label(), "near_equivalent", "{kept:?}"); + assert_eq!(multiplied(moltenvk()), WordVerdict::Within); // A product of normals one ulp off is outside the correctly rounded bound, as before. let two = 2.0f32.to_bits(); let normal = verdict_of( diff --git a/crates/metal2vulkan-validation/src/c3/tests.rs b/crates/metal2vulkan-validation/src/c3/tests.rs index f8658122e..d0fcde36a 100644 --- a/crates/metal2vulkan-validation/src/c3/tests.rs +++ b/crates/metal2vulkan-validation/src/c3/tests.rs @@ -1929,11 +1929,10 @@ fn an_unstated_word_the_product_approximates_keeps_its_reading_open() { /// sign-off stands, whatever arithmetic notes the row records. A fast `sinpi` of a subnormal: +0 /// where the operand is read as zero, as Metal reads it, the subnormal pi times it /// where the device keeps it (fast `sinpi`'s lowering records `DeviceDenormals`), and Table 8.2's -/// absolute 2^-13 admits both. A product whose result is a subnormal keeps Apple's verdict: the -/// product's multiply flushes it on every profile, so the note is not its. A product one rounding -/// away (toward zero, which "correctly rounded" admits) touches no subnormal. (Metal's divisions -/// flush their own subnormals and record no such note, and precise `fmod` answers Metal at -/// denormals itself.) +/// absolute 2^-13 admits both. A product whose result is a subnormal is open too: lavapipe's +/// multiply is the device's, not measured to flush as Metal does, and records the note. A product +/// one rounding away (toward zero, which "correctly rounded" admits) touches no subnormal. (Precise +/// `fmod` answers Metal at denormals itself.) #[test] fn a_word_within_apples_bound_that_shows_a_recorded_near_equivalent_keeps_its_reading_open() { let report_of = |computes: &str, @@ -1999,13 +1998,14 @@ fn a_word_within_apples_bound_that_shows_a_recorded_near_equivalent_keeps_its_re } assert!(!report.holds()); - // 2^-100 * 2^-30, Metal's +0 against a kept 2^-130: the multiply records no denormal note, - // so within, and the sign-off stands with every note recorded. + // 2^-100 * 2^-30, Metal's +0 against a kept 2^-130: the multiply records the denormal note, + // so open, and the sign-off refused. let (a, b) = (f32::from_bits(27 << 23), f32::from_bits((127 - 30) << 23)); // 2^-100, 2^-30 let report = report_of("mul(a, b)", Math::Precise, &[a, b], 0.0, tiny, &every); let check = report.readings[0].bound.as_ref().unwrap(); - assert_eq!(check.count("within"), 1); - assert!(report.refused.is_empty()); + assert_eq!(check.count("near_equivalent"), 1); + assert_eq!(report.refused.len(), 1); + assert!(report.refused[0].words[0].contains("(Metal's mul)")); // (1 / 3)^2 rounded toward zero against Metal's nearest: no subnormal, no NaN, so within, // and the sign-off stands with every note recorded. diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 385d9d3f8..a3c8046c6 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -1146,15 +1146,14 @@ pub(crate) const MOLTENVK_ARGUMENT_BUFFERS_READ: [u32; 2] = [10401, 10402]; /// driver lets no device turn its internal pipeline cache off and that cache is not Metal's own /// (MoltenVK's); /// `moltenvk-argument-buffers-unread` on a MoltenVK whose argument-buffer state the runtime does -/// not read; and `float-tininess-after-rounding` where the device's policy takes native device -/// maths and its profile's float functions are not Metal's own (MoltenVK's). +/// not read; and `float-tininess-after-rounding` where its profile's float functions are not +/// Metal's own (MoltenVK's). pub fn creation_kinds(device: &Device) -> BTreeSet { let mut kinds = BTreeSet::new(); let compile = device.compile_device(); - if compile.policy().float_maths == metal2vulkan::device::FloatMathsPolicy::Native - && !compile - .profile() - .takes_driver_deviation(metal2vulkan::error::DriverDeviation::MetalFloatFunctions) + if !compile + .profile() + .takes_driver_deviation(metal2vulkan::error::DriverDeviation::MetalFloatFunctions) { kinds.insert(Degradation::FloatTininessAfterRounding); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index bdec4a106..36fd5e438 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -310,8 +310,7 @@ pub(super) const POSITIONED: [Degradation; 1] = [Degradation::PositionsThroughSc /// The kinds a device announces as it is made, which the lane's constructor takes and checks /// exactly (`runtime_lane::creation_kinds`). -/// `float-tininess-after-rounding` is announced by the devices `native_maths` makes with native -/// device maths, on every venue but MoltenVK, and by none made with the lane's exact policy. +/// `float-tininess-after-rounding` is announced by every device on every venue but MoltenVK. pub(super) const CREATED: [Degradation; 2] = [ Degradation::DriverPipelineCacheKept, Degradation::FloatTininessAfterRounding, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs b/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs index 7c9d5bc18..acff74054 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs @@ -17,8 +17,8 @@ //! - **The float functions** (`MetalFloatFunctions`): the committed math-library probe cases, with //! and without fast math, run as their Metal oracle ran them. Where the profile takes the //! deviation, every word of a function the translation hands to the device's instruction is -//! Metal's (`PRECISE_DEVICE_WORDS`, `FAST_DEVICE_WORDS`). Elsewhere the translation's routines -//! answer within Apple's bound, and C3 compares them; the test prints how many words match. +//! Metal's (`PRECISE_DEVICE_WORDS`, `FAST_DEVICE_WORDS`). Elsewhere the device's instructions +//! answer within Vulkan's bounds (`NativeTranscendentals`); the test prints how many words match. //! - **The cube routes** (`GraphicsCubeGradientRoute`, `GraphicsCubeGradientTangents` and //! `CubeGradientRoute`): the owned fixture `rtl_cube_grad_fragment` samples a cube and a cube //! array with explicit gradients through an anisotropic constexpr sampler in a fragment function, @@ -34,19 +34,20 @@ //! `GraphicsCubeGradientRoute`. Elsewhere the sample is a near-equivalent //! (`CubeGradientFootprint`) or refused; the test prints which. //! - **The `half` fused multiply-add** (`MetalHalfFma`): the committed cases of a probe -//! (`fmx_fma_precise`, `fmx_fma_fast`), whose half word is a `half` `fma` and a `half` `a * b + -//! c` that Metal fuses, over 300 triples whose `float` sum lands on a `half` midpoint, 200 where -//! one rounding and two differ, the special values and random ones. Where the profile takes the -//! deviation, the kernels take the device's 16-bit `Fma` and require `VkProperty::MetalHalfFma`, -//! and every half word is the Metal row's of the same chip. Elsewhere the `half` routine rounds -//! the `float` sum and C3 compares it; the test prints how many half words match. +//! (`fmx_fma_precise`, `fmx_fma_fast`), whose half word is a `half` `fma` and a `half` +//! `a * b + c` that Metal fuses, over 300 triples whose `float` sum lands on a `half` midpoint, +//! 200 where one rounding and two differ, the special values and random ones. Where the profile +//! takes the deviation, the kernels take the device's 16-bit `Fma` and require +//! `VkProperty::MetalHalfFma`, and every half word is the Metal row's of the same chip. Elsewhere +//! the device's `Fma` answers (`NativeFma`, or `OpFmaKHR` on 16 bits under the float controls); +//! the test prints how many half words match. //! - **The `float` denormals** (`MetalFloatDenormals`): the NaN model's denormal probes, with and //! without fast math. Where the profile takes the deviation, the kernels leave `+ - *`, the //! comparisons, `ldexp`, `sqrt` and `rsqrt` to the device and require -//! `VkProperty::MetalFloatDenormals`; elsewhere the module reads such operands and flushes such -//! results itself. Both give Metal's answer, so every device is checked on those operations' -//! words; `floor` and `ceil` read their operand themselves on every device. a probe cases check -//! the fused pair's NaN and the lone product's flushed denormal on every device too. +//! `VkProperty::MetalFloatDenormals`, and those operations' words are checked; elsewhere the +//! denormals are the device's (`DeviceDenormals`) and the test prints how many words match. a +//! probe cases check the fused pair's NaN and, where the profile takes the deviation, the lone +//! product's flushed denormal. //! - **The `half` quantize** (`MetalHalfQuantize`): the NaN model's narrowing, conversion and //! `half` cases. Where the profile takes the deviation, a `half` rounding is the device's //! `OpQuantizeToF16` alone and the kernels require `VkProperty::MetalHalfQuantize`; elsewhere the @@ -116,7 +117,7 @@ use crate::observation::MetalObservation; use crate::store::CorpusStore; use base64::Engine as _; use metal2vulkan::cache::VariantKey; -use metal2vulkan::device::{DevicePolicy, FloatControl, FloatWidth, VkFeature, VkProperty}; +use metal2vulkan::device::{DevicePolicy, FloatControl, FloatWidth, VkProperty}; use metal2vulkan::error::{Capability, DriverDeviation, Error as CompileError, Feature, Needs}; use metal2vulkan::library::Library; use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; @@ -713,41 +714,20 @@ fn half_fused_multiply_adds_the_device_answers_are_metals() { /// The NaN model's denormal probe (`nan_denormals`, `nan_denormals_fast`): 256 threads of 48 /// words over operand triples rich in denormals of both signs and the smallest normals; the /// second is the first's program under fast math. -const DENORMAL_PROBES: [(&str, bool); 2] = [ - ("nan-model-float-denormals-per-operation", false), - ( - "nan-model-float-denormals-per-operation-under-fast-math", - true, - ), +const DENORMAL_PROBES: [&str; 2] = [ + "nan-model-float-denormals-per-operation", + "nan-model-float-denormals-per-operation-under-fast-math", ]; /// The words of a [`DENORMAL_PROBES`] thread whose operations read `float` denormals as Metal /// does on every profile: `a + b`, `a - b`, `a * b`, `0 - a`, `a < b`, `a == b`, `floor`, `ceil`, /// `trunc`, `round`, `rint`, `ldexp`, `step`, `(a * b) * c`, `a < b ? a : b`, `-(a * b)` and -/// `fabs(a - b)`; the quotients ([`DENORMAL_PROBE_QUOTIENTS`]); `sqrt` and `rsqrt` -/// ([`DENORMAL_PROBE_ROOTS`]) where Metal answers a zero, an infinity or a NaN; and `pow` and -/// `powr` ([`DENORMAL_PROBE_POWERS`]) where it answers a zero, a denormal, an infinity or a NaN. -/// Not the fused multiply-adds (4, 5), `dot` and `length` (36, 37) and `mix` (38): their fused -/// sums flush at the tininess edge before rounding on Metal, which no device measured matches on -/// every lane, nor the math library's functions. -const DENORMAL_PROBE_WORDS: &[usize] = &[ - 0, 1, 2, 7, 10, 11, 12, 13, 14, 15, 16, 35, 39, 43, 45, 46, 47, -]; - -/// The quotient words of a [`DENORMAL_PROBES`] thread: `a / b`, `smoothstep` and `(a / b) * c`. -/// Under fast math each divides by Metal's fast reciprocal, which a profile whose `float` -/// functions are not Metal's and that has no `OpFmaKHR` (`shaderFmaFloat32`) takes as the -/// device's `OpFDiv(1, y)`, within Vulkan's 2.5 ulp, not `RN(1 / y)` (the translator's -/// `divide::Reciprocal::Device`, recorded `PrecisionNote::DeviceArithmetic`): on such a profile -/// the fast probe's quotients are checked where Metal answers a zero, a denormal, an infinity or -/// a NaN, and everywhere else every word of them. -const DENORMAL_PROBE_QUOTIENTS: &[usize] = &[3, 40, 44]; - -/// The `pow` and `powr` words of a [`DENORMAL_PROBES`] thread: checked where Metal answers a -/// zero, a denormal, an infinity or a NaN, among them `pow(x, 1)` of a denormal `x`, which -/// precise `pow` answers as `x` and `fast::pow` as the zero of its sign. Their other words are the -/// math library's values at normal operands. -const DENORMAL_PROBE_POWERS: &[usize] = &[32, 33]; +/// `fabs(a - b)`; and `sqrt` and `rsqrt` ([`DENORMAL_PROBE_ROOTS`]) where Metal answers a zero, an +/// infinity or a NaN. Not `floor` and `ceil` (12, 13), whose reading no device measured matches, +/// the quotients (3, 40, 44), the device's division, the fused multiply-adds (4, 5), `dot` and +/// `length` (36, 37) and `mix` (38), whose fused sums flush at the tininess edge before rounding +/// on Metal, which no device measured matches on every lane, nor the math library's functions. +const DENORMAL_PROBE_WORDS: &[usize] = &[0, 1, 2, 7, 10, 11, 14, 15, 16, 35, 39, 43, 45, 46, 47]; /// The `sqrt` and `rsqrt` words of a [`DENORMAL_PROBES`] thread: checked where Metal answers a /// zero, an infinity or a NaN (a zero, denormal or negative operand). Their other words are the @@ -755,14 +735,11 @@ const DENORMAL_PROBE_POWERS: &[usize] = &[32, 33]; /// are an ulp below Metal's (the committed rows of 615.71.09, 16 lanes each). const DENORMAL_PROBE_ROOTS: &[usize] = &[20, 21]; -/// Both probes answer Metal's `float` denormals on every profile: the device's where the profile -/// takes the deviation (the kernels then require `VkProperty::MetalFloatDenormals`), the -/// module's own flushes elsewhere. Every word of [`DENORMAL_PROBE_WORDS`], each word of -/// [`DENORMAL_PROBE_QUOTIENTS`] (in the fast probe on a profile whose fast reciprocal is the -/// device's, where Metal answers a zero, a denormal, an infinity or a NaN), each word of -/// [`DENORMAL_PROBE_ROOTS`] where Metal answers a zero, an infinity or a NaN, and each word of -/// [`DENORMAL_PROBE_POWERS`] where it answers one of those or a denormal, is the Metal row's of -/// the same chip; the test prints how many of the other words differ. +/// Both probes answer Metal's `float` denormals where the profile takes the deviation (the kernels +/// then require `VkProperty::MetalFloatDenormals`): every word of [`DENORMAL_PROBE_WORDS`] and +/// each word of [`DENORMAL_PROBE_ROOTS`] where Metal answers a zero, an infinity or a NaN is the +/// Metal row's of the same chip; elsewhere the denormals are the device's and nothing is checked. +/// The test prints how many words differ. #[test] fn float_denormals_read_as_metal_reads_them() { let messages = Messages::default(); @@ -771,17 +748,8 @@ fn float_denormals_read_as_metal_reads_them() { let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); let name = device.name().to_owned(); let metals = takes(&device, DriverDeviation::MetalFloatDenormals); - // Whether Metal's fast reciprocal is the device's `OpFDiv(1, y)`: neither Metal's own - // float functions nor `OpFmaKHR`, whose refinement makes it `RN(1 / y)`. - let device_reciprocal = !takes(&device, DriverDeviation::MetalFloatFunctions) - && !device - .compile_device() - .profile() - .enabled() - .features - .contains(&VkFeature::ShaderFmaFloat32); let mut failures = Vec::new(); - for (case_name, fast) in DENORMAL_PROBES { + for case_name in DENORMAL_PROBES { let case = public_case(case_name).unwrap(); assert_eq!( requires_property(&device, &case, VkProperty::MetalFloatDenormals), @@ -796,18 +764,14 @@ fn float_denormals_read_as_metal_reads_them() { u32::from_le_bytes(bytes[4 * i..4 * i + 4].try_into().unwrap()) }; let special = |w: u32| w & 0x7FFF_FFFF == 0 || w & 0x7F80_0000 == 0x7F80_0000; - let edge = |w: u32| special(w) || w & 0x7F80_0000 == 0; let (mut checked, mut differ) = (0, Vec::new()); let mut by_word = std::collections::BTreeMap::::new(); for i in 0..metal.len() / 4 { let w = i % 48; let (got, want) = (word(&run.output, i), word(&metal, i)); - let quotient = DENORMAL_PROBE_QUOTIENTS.contains(&w); - if DENORMAL_PROBE_WORDS.contains(&w) - || (quotient && !(fast && device_reciprocal)) - || (quotient && edge(want)) - || (DENORMAL_PROBE_ROOTS.contains(&w) && special(want)) - || (DENORMAL_PROBE_POWERS.contains(&w) && edge(want)) + if metals + && (DENORMAL_PROBE_WORDS.contains(&w) + || (DENORMAL_PROBE_ROOTS.contains(&w) && special(want))) { checked += 1; if got != want { @@ -818,9 +782,9 @@ fn float_denormals_read_as_metal_reads_them() { } } eprintln!( - "float denormals {case_name} on {name} (the device's: {metals}; the device's \ - fast reciprocal: {device_reciprocal}): {} of {checked} checked words differ \ - from Metal; other words differing, by word: {by_word:?}", + "float denormals {case_name} on {name} (the device's, as Metal's: {metals}): {} of \ + {checked} checked words differ from Metal; other words differing, by word: \ + {by_word:?}", differ.len() ); if !differ.is_empty() { @@ -838,8 +802,10 @@ fn float_denormals_read_as_metal_reads_them() { } /// a probe cases ([`HALF_FMA_CASES`]): every word, `fma(a, b, c)`, `a * b + c`, the two `half` -/// results and the lone product `a * w`, is the Metal row's of the same chip on every profile: the -/// fused pair answers Metal's canonical NaN and the product Metal's flushed denormal (2.2). +/// results and the lone product `a * w`, is the Metal row's of the same chip where the profile +/// takes `DriverDeviation::MetalFloatDenormals`: the fused pair answers Metal's canonical NaN and +/// the product Metal's flushed denormal (2.2). Elsewhere the denormals are the device's and the +/// test prints how many words differ. #[test] fn fused_pairs_answer_metals_nans_and_denormals() { let messages = Messages::default(); @@ -847,6 +813,7 @@ fn fused_pairs_answer_metals_nans_and_denormals() { { let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); let name = device.name().to_owned(); + let metals = takes(&device, DriverDeviation::MetalFloatDenormals); let mut failures = Vec::new(); for case_name in HALF_FMA_CASES { let case = public_case(case_name).unwrap(); @@ -854,11 +821,12 @@ fn fused_pairs_answer_metals_nans_and_denormals() { let metal = metal_row(&case, METAL_ENVIRONMENT); let differ = differing_of(&run.output, &metal, 4, &[0, 1, 2, 3]); eprintln!( - "fused pairs {case_name} on {name}: {} of {} words differ from Metal", + "fused pairs {case_name} on {name} (the device's denormals, as Metal's: {metals}): \ + {} of {} words differ from Metal", differ.len(), metal.len() / 4 ); - if !differ.is_empty() { + if metals && !differ.is_empty() { failures.push(format!( "{case_name} on {name}: {} words differ from Metal (thread, word, device, \ Metal): {:x?}", @@ -968,15 +936,17 @@ const DFL_DENORMAL_CASES: [&str; 2] = [ "float-denormals-in-vector-arithmetic-comparisons-and-functions-under-fast-math", ]; -/// The rows of a [`DFL_DENORMAL_CASES`] thread checked on every lane: `a + b`, `a - b`, -/// `a * b`, `fma`, `a * b + c`, the six comparisons, `floor`, `ceil`, `ldexp`, `(a * b) * c`, -/// `float(n) * a - c`, the three comparisons of results, `fmin(a, b) * c` and `step`. The fused +/// The rows of a [`DFL_DENORMAL_CASES`] thread checked on every lane where the profile takes +/// `DriverDeviation::MetalFloatDenormals`: `a + b`, `a - b`, `a * b`, `fma`, `a * b + c`, the six +/// comparisons, `ldexp`, `(a * b) * c`, `float(n) * a - c`, the three comparisons of results, +/// `fmin(a, b) * c` and `step`. `floor` (6) and `ceil` (7) of a denormal are the device's own on +/// every profile (`denormal::Covered::Never`). The fused /// rows' lanes are clear of the tininess edge before rounding: Metal's rows are the operands /// flushed, one rounding, and the result flushed, on every lane (and under fast math `a * b + c` is /// two roundings, the product having other uses). `sqrt` (8) and `rsqrt` (9) are checked where /// Metal answers a zero, an infinity or a NaN, at a zero, denormal or negative operand /// ([`DFL_ROOT_ROWS`]). -const DFL_DENORMAL_ROWS: &[usize] = &[0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15]; +const DFL_DENORMAL_ROWS: &[usize] = &[0, 1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]; /// The `sqrt` and `rsqrt` rows of a [`DFL_DENORMAL_CASES`] thread: their other words are the /// device's roots' rounding, not their denormals. @@ -994,9 +964,11 @@ const DFL_HALF_EDGE_CASES: [&str; 2] = [ /// them. const DFL_TRIG_CASE: &str = "precise-trigonometric-functions-at-nan-operands-under-fast-math"; -/// The owned fixtures answer Metal on every profile: in the denormal cases every lane of -/// [`DFL_DENORMAL_ROWS`] and the special lanes of [`DFL_ROOT_ROWS`], the kernels requiring -/// `VkProperty::MetalFloatDenormals` exactly where the profile takes the deviation; in the `half` +/// The owned fixtures answer Metal: in the denormal cases every lane of [`DFL_DENORMAL_ROWS`] and +/// the special lanes of [`DFL_ROOT_ROWS`] where the profile takes +/// `DriverDeviation::MetalFloatDenormals` (elsewhere a denormal is the device's own, and the test +/// prints how many words differ), the kernels requiring `VkProperty::MetalFloatDenormals` exactly +/// where the profile takes the deviation; in the `half` /// edge cases every word, the kernels requiring `VkProperty::MetalHalfConversion` exactly where the /// profile takes that one, else neither where they round under the float controls, else /// `VkProperty::MetalHalfQuantize` exactly where the profile takes that one; @@ -1049,7 +1021,7 @@ fn owned_float_fixtures_answer_metal() { {others:?}", differ.len() ); - if !differ.is_empty() { + if denormals && !differ.is_empty() { failures.push(format!( "{case_name} on {name}: {} words differ from Metal (thread, word, device, \ Metal): {:x?}", @@ -1142,10 +1114,13 @@ const DOT_CASES: [&str; 2] = [ "dot-of-two-to-four-float-and-half-lanes-under-fast-math", ]; -/// Both `dot` cases answer Metal on every profile, every word: Metal's fused chain by the multiply -/// and the profile's fused multiply-adds, or on `float` the device's `OpDot` where it reaches -/// Metal's own `dot` (MoltenVK). The kernels leave their `float` denormals to the device exactly -/// where the profile takes `DriverDeviation::MetalFloatDenormals`. +/// Both `dot` cases answer Metal where the module keeps Metal's fused chain (by the multiply and +/// the profile's fused multiply-adds) or the device's `OpDot` is Metal's own `dot`: every `float` +/// word where the profile takes `DriverDeviation::MetalFloatFunctions` (MoltenVK), and every +/// `half` word there or where it takes `DriverDeviation::MetalHalfFma` (the chain of Metal's own +/// 16-bit fused multiply-add). Elsewhere `dot` is the device's `OpDot` and the test prints how +/// many words differ. The kernels leave their `float` denormals to the device exactly where the +/// profile takes `DriverDeviation::MetalFloatDenormals`. #[test] fn owned_dot_fixtures_answer_metal() { let messages = Messages::default(); @@ -1154,6 +1129,18 @@ fn owned_dot_fixtures_answer_metal() { let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); let name = device.name().to_owned(); let denormals = takes(&device, DriverDeviation::MetalFloatDenormals); + let metals = takes(&device, DriverDeviation::MetalFloatFunctions); + let half_chain = metals || takes(&device, DriverDeviation::MetalHalfFma); + // Words 0 to 2, 6 and 7 are `float` sums, 3 to 5 `half` ones. + let checked: Vec = (0..8) + .filter(|w| { + if (3..6).contains(w) { + half_chain + } else { + metals + } + }) + .collect(); let mut failures = Vec::new(); for case_name in DOT_CASES { let case = public_case(case_name).unwrap(); @@ -1166,12 +1153,15 @@ fn owned_dot_fixtures_answer_metal() { let run = run_case(&device, &case).unwrap(); let metal = metal_row(&case, METAL_ENVIRONMENT); assert_eq!(run.output.len(), metal.len(), "{case_name} on {name}"); - let differ = differing_of(&run.output, &metal, 8, &(0..8).collect::>()); + let all = differing_of(&run.output, &metal, 8, &(0..8).collect::>()); + let differ: Vec<_> = all.iter().filter(|d| checked.contains(&d.1)).collect(); eprintln!( - "owned dot {case_name} on {name} (the device's denormals: {denormals}): {} of {} \ - words differ from Metal", - differ.len(), - metal.len() / 4 + "owned dot {case_name} on {name} (the device's denormals: {denormals}, Metal's \ + float functions: {metals}, Metal's half chain: {half_chain}): {} of {} words \ + differ from Metal, {} of them in the words checked ({checked:?})", + all.len(), + metal.len() / 4, + differ.len() ); if !differ.is_empty() { failures.push(format!( diff --git a/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs b/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs index a22ad1016..885a933f1 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs @@ -1,17 +1,16 @@ //! The device's forms of Metal's maths, through the runtime, on the device the cfg selects, under -//! the validation layer, with each of the policy's three choices that split native device maths set -//! on alone, all of them on, and all of them off. Every other lane takes Metal's answers -//! (`candidate::runtime_case::validated_options` sets `DevicePolicy::exact_answers`); this one -//! starts from those options and turns choices on: the maths functions, divisions and fused -//! multiply-adds (`FloatMathsPolicy::Native`: `PrecisionNote::NativeTranscendentals`, -//! `NativeDivision`, `NativeFma`), the NaN and minimum and maximum (`NanMinMaxPolicy::Native`: -//! `NativeNanEncoding`, `NativeMinMax`), and the rounding order (`RoundingOrderPolicy::Native`: -//! `NativeDot`, `NativeMix`, and `NativeTranscendentals` for `fast::sqrt`). Under each setting the -//! stage records exactly the kinds of the choices that are on (where the device's answer is not -//! Metal's own), the pipeline state announces the kinds its stage records, and every thread's -//! answers stay within the bounds the kinds record; where a choice is off its answers are Metal's: -//! a correctly rounded quotient and `fma`, Metal's canonical NaN `0x7fc00000`, Metal's fused `dot` -//! and `mix`. +//! the validation layer, with the NaN and minimum and maximum choice on and off. Every other lane +//! takes Metal's answers where a switch keeps them (`candidate::runtime_case::validated_options` +//! sets `DevicePolicy::exact_answers`); this one starts from those options. The maths functions, +//! divisions and fused multiply-adds (`PrecisionNote::NativeTranscendentals`, `NativeDivision`, +//! `NativeFma`) and `dot`, `mix` and `fast::sqrt` (`NativeDot`, `NativeMix`, and +//! `NativeTranscendentals` for `fast::sqrt`) are the device's on every device whose functions are +//! not Metal's own; the NaN and minimum and maximum (`NanMinMaxPolicy::Native`: +//! `NativeNanEncoding`, `NativeMinMax`) are where the choice is on. Under each setting the stage +//! records exactly the kinds of the forms it takes (where the device's answer is not Metal's own), +//! the pipeline state announces the kinds its stage records, and every thread's answers stay +//! within the bounds the kinds record; where the choice is off a NaN product is Metal's canonical +//! NaN `0x7fc00000`. //! //! The kernel reads ten `float`s a thread and writes fourteen: `sin` and `cos` of an angle in //! `[-π, π]`, `exp2` of an exponent in `[-10, 10]`, `log2` of a value in `[2^-20, 2^20]`, a @@ -26,9 +25,7 @@ use super::degrade_notices::{counts, on_device_with}; use super::{buffer_with, read_buffer, Messages, WAIT}; use crate::air_library::AirLibrary; use metal2vulkan::cache::VariantKey; -use metal2vulkan::device::{ - FloatControl, FloatMathsPolicy, FloatWidth, NanMinMaxPolicy, RoundingOrderPolicy, VkProperty, -}; +use metal2vulkan::device::{FloatControl, FloatWidth, NanMinMaxPolicy, VkProperty}; use metal2vulkan::error::DriverDeviation; use metal2vulkan::library::Library; use metal2vulkan::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, PrecisionNote}; @@ -318,42 +315,16 @@ const NATIVE: [PrecisionNote; 7] = [ PrecisionNote::NativeMix, ]; -/// Which of the three choices a setting turns on: the maths functions, the NaN and minimum and -/// maximum, the rounding order. +/// Whether a setting turns the NaN and minimum and maximum choice on. #[derive(Clone, Copy, Debug)] struct Setting { - maths: bool, nan_min_max: bool, - rounding_order: bool, } -/// Each choice alone, all of them, and none. -const SETTINGS: [Setting; 5] = [ - Setting { - maths: false, - nan_min_max: false, - rounding_order: false, - }, - Setting { - maths: true, - nan_min_max: false, - rounding_order: false, - }, - Setting { - maths: false, - nan_min_max: true, - rounding_order: false, - }, - Setting { - maths: false, - nan_min_max: false, - rounding_order: true, - }, - Setting { - maths: true, - nan_min_max: true, - rounding_order: true, - }, +/// The choice off and on. +const SETTINGS: [Setting; 2] = [ + Setting { nan_min_max: false }, + Setting { nan_min_max: true }, ]; /// `x` rounded to a `half` to nearest even (a normal `half`'s magnitude). @@ -362,46 +333,31 @@ fn to_half(x: f64) -> f64 { (x / ulp).round_ties_even() * ulp } -/// Where a thread's answers are not Metal's under `setting` (Metal's own being known exactly for -/// the choices that are off): a correctly rounded quotient, `float` `fma` and `half` `fma` with -/// the maths functions off (the routines', on any device); Metal's canonical NaN for the product -/// of a NaN with the NaN and minimum and maximum off; and Metal's fused `dot` (its chain of the -/// products) and `mix` (`fma(t, y, fma(-t, x, x))`) with the rounding order and the maths -/// functions off (the `float` fused multiply-add then Metal's own, correctly rounded). +/// Where a thread's answers are not Metal's under `setting` (Metal's own being known exactly where +/// the choice is off): Metal's canonical NaN for the product of a NaN. fn not_metal_s(setting: Setting, x: &[f32; IN], r: &[f32; OUT]) -> Vec { - let [s, e, _, a, b, c, hx, hy, hz, n] = *x; + let n = x[9]; let mut out = Vec::new(); let mut want = |what: &str, got: f32, metal: f32| { if got.to_bits() != metal.to_bits() { out.push(format!("{what}: {got:e} for Metal's {metal:e}")); } }; - if !setting.maths { - want("a / b", r[4], (f64::from(a) / f64::from(b)) as f32); - want("fma", r[5], a.mul_add(b, c)); - let half = f64::from(hx) * f64::from(hy) + f64::from(hz); - want("half fma", r[6], to_half(half) as f32); - } if !setting.nan_min_max && n.is_nan() { want("n * b", r[9], f32::from_bits(0x7fc0_0000)); } - if !setting.rounding_order && !setting.maths { - want("dot", r[10], s.mul_add(c, c * e)); - want("mix", r[11], hx.mul_add(c, (-hx).mul_add(s, s))); - } out } -/// Under each setting of the three choices, on a device whose `float` functions are not Metal's -/// own, the stage records exactly the kinds of the choices that are on: the maths functions -/// `NativeTranscendentals` and `NativeDivision` (and `NativeFma` where an `fma` takes the device's -/// `Fma`), the NaN and minimum and maximum `NativeNanEncoding` (on a device whose arithmetic is not -/// measured to answer Metal's canonical NaN) and `NativeMinMax`, and the rounding order -/// `NativeDot`, `NativeMix` and `NativeTranscendentals` (`fast::sqrt`); the pipeline state -/// announces each native kind of its stage once; every thread's answers are within the bounds their -/// kinds record, and Metal's where their choice is off. On MoltenVK, whose functions, minimum and -/// maximum, and NaNs are Metal's own, the stage records none of them under any setting and -/// announces none. The device made with native device maths announces +/// Under each setting, on a device whose `float` functions are not Metal's own, the stage records +/// exactly the kinds of the forms it takes: the maths functions `NativeTranscendentals` and +/// `NativeDivision` (and `NativeFma` where an `fma` takes the device's `Fma`), `NativeDot`, +/// `NativeMix` and `NativeTranscendentals` (`fast::sqrt`), and with the NaN and minimum and maximum +/// on `NativeNanEncoding` (on a device whose arithmetic is not measured to answer Metal's canonical +/// NaN) and `NativeMinMax`; the pipeline state announces each native kind of its stage once; every +/// thread's answers are within the bounds their kinds record, and Metal's where the choice is off. +/// On MoltenVK, whose functions, minimum and maximum, and NaNs are Metal's own, the stage records +/// none of them under any setting and announces none. The device announces /// `float-tininess-after-rounding` as it is made, exactly off MoltenVK. #[test] fn each_choice_answers_within_its_recorded_bounds_on_and_metal_s_off() { @@ -409,15 +365,8 @@ fn each_choice_answers_within_its_recorded_bounds_on_and_metal_s_off() { for setting in SETTINGS { on_device_with( |options| { - let policy = &mut options.policy; - if setting.maths { - policy.float_maths = FloatMathsPolicy::Native; - } if setting.nan_min_max { - policy.nan_and_min_max = NanMinMaxPolicy::Native; - } - if setting.rounding_order { - policy.rounding_order = RoundingOrderPolicy::Native; + options.policy.nan_and_min_max = NanMinMaxPolicy::Native; } }, |device, messages| answers_under(device, messages, setting, &bitcode), @@ -434,26 +383,19 @@ fn answers_under(device: &Device, messages: &Messages, setting: Setting, bitcode let takes = |d| compile.profile().takes_driver_deviation(d); let metals = takes(DriverDeviation::MetalFloatFunctions); eprintln!("{name}: Metal's own functions {metals}; native kinds {expected:?}"); - let Setting { - maths, - nan_min_max, - rounding_order, - } = setting; + let Setting { nan_min_max } = setting; // The constructor checked the creation notices against `creation_kinds`: the device's - // multiply and fused multiply-add, taken under native device maths, announced as it was made. + // multiply and fused multiply-add, announced as it was made. assert_eq!( super::creation_kinds(device).contains(&Degradation::FloatTininessAfterRounding), - maths && !metals, + !metals, "{name}: float-tininess-after-rounding" ); for (note, native) in [ - ( - PrecisionNote::NativeTranscendentals, - !metals && (maths || rounding_order), - ), - (PrecisionNote::NativeDivision, !metals && maths), - (PrecisionNote::NativeDot, !metals && rounding_order), - (PrecisionNote::NativeMix, !metals && rounding_order), + (PrecisionNote::NativeTranscendentals, !metals), + (PrecisionNote::NativeDivision, !metals), + (PrecisionNote::NativeDot, !metals), + (PrecisionNote::NativeMix, !metals), ( PrecisionNote::NativeMinMax, nan_min_max && !metals && !takes(DriverDeviation::MetalMinMax), @@ -466,10 +408,6 @@ fn answers_under(device: &Device, messages: &Messages, setting: Setting, bitcode let kind = Degradation::from_precision_note(note); assert_eq!(expected.contains(&kind), native, "{name}: {kind:?}"); } - if !maths { - let kind = Degradation::from_precision_note(PrecisionNote::NativeFma); - assert!(!expected.contains(&kind), "{name}: {kind:?}"); - } let library = device.new_library_with_air(bitcode).unwrap(); let function = library.new_function_with_name("nm").unwrap(); diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index e3ba13b21..626c0412e 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1273,10 +1273,8 @@ codec_enum! { ObjectThreadgroupArena { static_bytes, payload }, ExactFormsOverCompilerLimit { sampling, - float_maths, texel_conversion, - nan_and_min_max, - rounding_order + nan_and_min_max }, MergedDraws, QuadPrimitiveIds, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index fe4e556a4..57cc18a9c 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 = 1874; +pub const SEMANTICS_VERSION: u32 = 1878; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1874; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 457; +pub const ARTIFACT_FORMAT_VERSION: u32 = 461; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 457; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1657; +pub const RUNTIME_VERSION: u32 = 1660; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index 05a22de5a..9c2c4cba8 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -13,14 +13,14 @@ use crate::device::description::{ use crate::device::function_storage; use crate::device::metal::MetalDeviceProperties; use crate::device::policy::{ - ContainmentPolicy, DevicePolicy, FloatMathsPolicy, NanMinMaxPolicy, RoundingOrderPolicy, - SamplingPolicy, Unorm8LinearFilterPolicy, YCbCrFilterPolicy, + ContainmentPolicy, DevicePolicy, NanMinMaxPolicy, SamplingPolicy, Unorm8LinearFilterPolicy, + YCbCrFilterPolicy, }; use crate::device::profile::{ BufferAccess, Containment, CubeGradientRoute, CubeGradients, DescriptorCaps, DeviceProfile, DriverWorkaround, EnabledCaps, FloatFunctions, FormatTable, FragmentCaps, GuestIsolation, ImageCaps, Independence, LeafCaps, MinMaxRoute, NanEncoding, ProfileFields, Robustness, - RoundingOrderRoute, TexelNanRoute, + TexelNanRoute, }; use crate::device::requirements::{ ApiVersion, FloatControl, FloatWidth, FormatUsage, ResolveMode, SubgroupOp, VkExtension, @@ -359,12 +359,9 @@ fn derive_fields( // so the extended dynamic states a pipeline makes are exactly what it requires. dynamic_vertex_stride: has(VkFeature::ExtendedDynamicState), enabled: enabled_caps(desc, deviations, policy), - // The measured deviation; unmeasured, the translation's own functions. Elsewhere native - // device maths unless the policy asks for Metal's answers. + // The measured deviation; unmeasured, the device's own functions. float_functions: if deviates(DriverDeviation::MetalFloatFunctions) { FloatFunctions::Metal - } else if policy.float_maths == FloatMathsPolicy::Exact { - FloatFunctions::Device } else { FloatFunctions::Native }, @@ -414,15 +411,6 @@ fn derive_fields( } else { MinMaxRoute::Native }, - // Metal's order where the device's functions are Metal's own; elsewhere the device's - // instructions where the policy takes them. - rounding_order: if deviates(DriverDeviation::MetalFloatFunctions) - || policy.rounding_order == RoundingOrderPolicy::Exact - { - RoundingOrderRoute::Metal - } else { - RoundingOrderRoute::Native - }, // The device's measured value, keyed on its identity as the workarounds are, or the floor. function_storage: function_storage::of(desc), // The measured deviations, one per pipeline kind (the graphics one per macOS release's diff --git a/crates/metal2vulkan/src/device/mod.rs b/crates/metal2vulkan/src/device/mod.rs index 802eef23d..f2072e15f 100644 --- a/crates/metal2vulkan/src/device/mod.rs +++ b/crates/metal2vulkan/src/device/mod.rs @@ -67,9 +67,9 @@ pub(crate) use mechanism::mechanism; pub use metal::{MetalDeviceProperties, SimdSupport, StageSimd}; pub use policy::{ BatchOrderPolicy, CompletionPolicy, ContainmentPolicy, DecodedTexelsPolicy, DevicePolicy, - FloatMathsPolicy, HeapCompressionPolicy, HostPageTexturePolicy, NanMinMaxPolicy, - RenderLoweringPolicy, RoundingOrderPolicy, SamplingPolicy, TexelConversionPolicy, - Unorm8LinearFilterPolicy, VertexNormalizedPolicy, YCbCrFilterPolicy, + HeapCompressionPolicy, HostPageTexturePolicy, NanMinMaxPolicy, RenderLoweringPolicy, + SamplingPolicy, TexelConversionPolicy, Unorm8LinearFilterPolicy, VertexNormalizedPolicy, + YCbCrFilterPolicy, }; pub(crate) use profile::whole_point_size; pub use profile::{DeviceProfile, SpirvValidation}; diff --git a/crates/metal2vulkan/src/device/policy.rs b/crates/metal2vulkan/src/device/policy.rs index 50959852b..c67a97ade 100644 --- a/crates/metal2vulkan/src/device/policy.rs +++ b/crates/metal2vulkan/src/device/policy.rs @@ -33,11 +33,6 @@ pub struct DevicePolicy { /// two-plane YCbCr texture is the device's own filter of its texels (the default) or Metal's /// filter of the format, emulated in a variant of the pipeline the draw binding it makes. pub ycbcr_filter: YCbCrFilterPolicy, - /// Whether the math library's functions (`sin`, `cos`, `exp`, `log`, `pow` and the rest), a - /// precise division and Metal's fast reciprocal, and a fused multiply-add are the device's - /// own instructions (native device maths, the default) or the translation's routines of - /// Metal's answers. - pub float_maths: FloatMathsPolicy, /// Whether a texel's `float` or `half` value is the device's conversion of its codes (native /// device sampling, the default off Apple's GPUs) or Metal's, converted exactly in the /// shader. @@ -49,10 +44,6 @@ pub struct DevicePolicy { /// (`fmin`, `fmax`, `min3`, `max3`, `clamp`, `saturate`) pick at a NaN or a signed zero, are /// the device's own (the default) or Metal's. pub nan_and_min_max: NanMinMaxPolicy, - /// Whether Metal's `dot`, `mix` and `fast::sqrt` round in Metal's order (its fused chain of - /// the products, its two fused multiply-adds, its `x · rsqrt(x)`) or are the device's single - /// instructions (the default). - pub rounding_order: RoundingOrderPolicy, /// Whether a texture whose format the device lacks, held in a carrier (an ASTC LDR texture, /// or an EAC 11-bit one), samples a decoded twin of compact codes (the default) or of Metal's @@ -89,8 +80,7 @@ pub struct DevicePolicy { impl DevicePolicy { /// The untrusted-guest production policy: containment and isolation on, Metal's 8-bit linear /// filter emulated exactly where the emulation runs, native device sampling (a two-plane YCbCr texture's samples among them), - /// native device maths, the device's own texel - /// conversions, the device's NaN and minimum and maximum, the device's rounding order, compact + /// the device's own texel conversions, the device's NaN and minimum and maximum, compact /// codes in a carried texture's decoded twin, the driver's compressed image of a heap's texture /// Metal keeps compressed, command buffers ready together in one kernel submission, batches of /// one queue ordered by their ends where the driver runs them one after another, and a sampled @@ -103,11 +93,9 @@ impl DevicePolicy { unorm8_linear_filter: Unorm8LinearFilterPolicy::Exact, sampling: SamplingPolicy::NativeDevice, ycbcr_filter: YCbCrFilterPolicy::Device, - float_maths: FloatMathsPolicy::Native, texel_conversion: TexelConversionPolicy::Device, vertex_normalized: VertexNormalizedPolicy::Device, nan_and_min_max: NanMinMaxPolicy::Native, - rounding_order: RoundingOrderPolicy::Native, decoded_texels: DecodedTexelsPolicy::Compact, heap_compression: HeapCompressionPolicy::Compressed, completion: CompletionPolicy::Grouped, @@ -116,12 +104,10 @@ impl DevicePolicy { host_page_textures: HostPageTexturePolicy::InPlace, }; - /// This policy with Metal's answer wherever the choices offer it: its maths functions, - /// divisions and fused multiply-adds ([`FloatMathsPolicy::Exact`]), its texel conversions + /// This policy with Metal's answer wherever the choices offer it: its texel conversions /// ([`TexelConversionPolicy::Exact`]), its normalized vertex attributes - /// ([`VertexNormalizedPolicy::Exact`]), its - /// NaN and minimum and maximum ([`NanMinMaxPolicy::Exact`]), its rounding order - /// ([`RoundingOrderPolicy::Exact`]), its filter of a + /// ([`VertexNormalizedPolicy::Exact`]), its NaN and minimum and maximum + /// ([`NanMinMaxPolicy::Exact`]), its filter of a /// two-plane YCbCr texture /// ([`YCbCrFilterPolicy::Exact`]), its decode of a carried texture's texels /// ([`DecodedTexelsPolicy::Exact`]), a heap's texture whose bytes alias the heap's @@ -136,11 +122,9 @@ impl DevicePolicy { pub const fn exact_answers(self) -> DevicePolicy { DevicePolicy { ycbcr_filter: YCbCrFilterPolicy::Exact, - float_maths: FloatMathsPolicy::Exact, texel_conversion: TexelConversionPolicy::Exact, vertex_normalized: VertexNormalizedPolicy::Exact, nan_and_min_max: NanMinMaxPolicy::Exact, - rounding_order: RoundingOrderPolicy::Exact, decoded_texels: DecodedTexelsPolicy::Exact, heap_compression: HeapCompressionPolicy::Uncompressed, completion: CompletionPolicy::Exact, @@ -246,32 +230,6 @@ pub enum YCbCrFilterPolicy { Exact, } -/// How the `float` and `half` maths functions, divisions and fused multiply-adds Metal answers -/// beyond Vulkan's precision table are computed on a device whose functions are not Metal's own -/// (the owner's "Maths functions" of 2026-10-11, native by default). On a device whose functions -/// are Metal's (MoltenVK on an Apple GPU, `DriverDeviation::MetalFloatFunctions`), the device's -/// instructions are Metal's own whatever the policy. A NaN such a function answers is -/// [`NanMinMaxPolicy`]'s, `dot`, `mix` and `fast::sqrt` are [`RoundingOrderPolicy`]'s, and a `half` -/// result's rounding is the device's own (`lower::arith::narrow`). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum FloatMathsPolicy { - /// Native device maths (the default): the math library's functions are the device's - /// `GLSL.std.450` instructions (or Metal's compositions of them), a precise division and - /// Metal's fast reciprocal the device's `OpFDiv`, and a fused multiply-add without - /// `OpFmaKHR` the device's `Fma`, each within Vulkan's precision table rather than Metal's - /// answer, and each recording its kind - /// ([`PrecisionNote::NativeTranscendentals`](crate::pipeline::PrecisionNote::NativeTranscendentals), - /// [`NativeDivision`](crate::pipeline::PrecisionNote::NativeDivision), - /// [`NativeFma`](crate::pipeline::PrecisionNote::NativeFma)) with the bound in its docs. - #[default] - Native, - /// The translation's routines, which answer as Metal does on every device: larger modules and - /// longer pipeline creation. - Exact, -} - /// How a texel's value reaches a read, sample or gather with a `float` or `half` result on a /// device that does not sample through Metal's own texture unit (`VkProperty::MetalSampler`). On /// such a device Metal's conversion of a texel is emulated by a routine that tells the bound @@ -372,29 +330,6 @@ pub enum NanMinMaxPolicy { Exact, } -/// The order in which Metal's `dot`, `mix` and `fast::sqrt` on `float` and `half` round, on a -/// device whose functions are not Metal's own (the owner's "rounding order in dot products, blends -/// between two values (mix) and fast square root" of 2026-10-11). On a device whose functions are -/// Metal's (MoltenVK on an Apple GPU, `DriverDeviation::MetalFloatFunctions`) they are Metal's -/// under either setting. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum RoundingOrderPolicy { - /// The device's single instructions (the default): `dot` the device's `OpDot`, `mix` its - /// `FMix` (a `half` result summed in `float` and rounded once), and `fast::sqrt` its `Sqrt`. - /// Such a module records - /// [`PrecisionNote::NativeDot`](crate::pipeline::PrecisionNote::NativeDot), - /// [`NativeMix`](crate::pipeline::PrecisionNote::NativeMix) or - /// [`NativeTranscendentals`](crate::pipeline::PrecisionNote::NativeTranscendentals) - /// (`fast::sqrt`, with `DeviceDenormals`), whose docs state the bound. - #[default] - Native, - /// Metal's order: `dot` the fused chain of its products, `mix` `fma(t, y, fma(-t, x, x))`, and - /// `fast::sqrt` `x · rsqrt(x)` with Metal's answers at a zero, a denormal and `+inf`. - Exact, -} - /// What texels the runtime holds in the decoded twin of a texture whose blocks it holds in a /// carrier on a device without the format (the runtime's `texture/decoded_twin.rs`), which the /// texture's samples, reads and gathers read: an ASTC LDR texture's (`bind::AstcDecode`), and an diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index 0a3a30461..74e1757f3 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -533,10 +533,8 @@ pub struct ProfileFields { /// The enabled capability sets `Requirements` are checked against. pub enabled: EnabledCaps, /// Which functions the device's `GLSL.std.450` instructions and `OpFDiv` of `float` compute: - /// Metal's own, so the translation leaves a function to the device where Metal's compile of the - /// module computes it in the call's math mode, and takes the fast reciprocal from the device's - /// division, or the device's, so the translation computes the functions whose device answer may - /// leave Apple's bound itself. + /// Metal's own, in the math mode Metal's compile of the module takes, or the device's. The + /// module takes the device's instructions on either; the notes it records differ. pub float_functions: FloatFunctions, /// Which NaN the device's `float` and `half` arithmetic answers: Metal's canonical NaN, so the /// translation leaves it to the device, or the device's own, so the translation selects Metal's @@ -567,10 +565,6 @@ pub struct ProfileFields { /// `NanMinMaxPolicy::Native`). Derived, so a device that keeps Metal's picks keys the same /// under both policies. pub min_max: MinMaxRoute, - /// In whose order Metal's `dot`, `mix` and `fast::sqrt` round: Metal's, or the device's - /// single instructions (the policy's `RoundingOrderPolicy::Native`). Derived, as - /// [`ProfileFields::min_max`] is. - pub rounding_order: RoundingOrderRoute, /// The Function storage a thread holds correctly (`device::function_storage`): a stage's /// private memory, its call stacks included, may take this much a thread /// (`VkLimit::FunctionStorageBytesPerThread`), and a vertex or fragment function on a device @@ -675,21 +669,19 @@ impl FunctionStorage { /// Which functions a device's `GLSL.std.450` instructions and `OpFDiv` of `float` compute /// ([`ProfileFields::float_functions`]), decided by the driver's measured deviation -/// [`DriverDeviation::MetalFloatFunctions`]. +/// [`DriverDeviation::MetalFloatFunctions`]. Either way the module takes the device's +/// instructions. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum FloatFunctions { /// Metal's own, in the math mode Metal compiles the module with: fast where the entry /// declares no `SignedZeroInfNanPreserve`, precise where it declares one, and precise /// `tanh` and `atan2` either way. The division likewise: Metal's fast division and - /// reciprocal in a fast-math module, its correctly rounded ones otherwise. + /// reciprocal in a fast-math module, its correctly rounded ones otherwise. A call that is + /// Metal's own in the entry's mode records no note there. Metal, - /// The device's, within Vulkan's precision table, which the translation does not take - /// where Metal answers beyond it: its routines of Metal's answers instead (the policy's - /// `FloatMathsPolicy::Exact`). - Device, - /// The device's, within Vulkan's precision table, taken as they are: native device maths - /// (`FloatMathsPolicy::Native`, the default), each kind recorded with its bound. + /// The device's, within Vulkan's precision table, taken as they are, each kind recorded with + /// its bound. Native, } @@ -707,20 +699,6 @@ pub enum MinMaxRoute { Native, } -/// In whose order Metal's `dot`, `mix` and `fast::sqrt` on `float` and `half` round -/// ([`ProfileFields::rounding_order`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum RoundingOrderRoute { - /// Metal's: its fused chain, its two fused multiply-adds, its `x · rsqrt(x)`, or the - /// device's own instruction where the device's functions are Metal's - /// (`DriverDeviation::MetalFloatFunctions`); under `RoundingOrderPolicy::Exact` everywhere. - Metal, - /// The device's `OpDot`, `FMix` and `Sqrt` (`RoundingOrderPolicy::Native`, the default), - /// noted `PrecisionNote::NativeDot`, `NativeMix` and `NativeTranscendentals` with their - /// bounds. - Native, -} - /// Which NaN a device's `float` and `half` arithmetic answers ([`ProfileFields::nan_encoding`]), /// decided by the driver's measured deviation [`DriverDeviation::MetalCanonicalNans`]. #[non_exhaustive] diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 77c8d6a30..9f25d23f0 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -267,10 +267,8 @@ fn every_fact() -> Vec { }, RuntimeFact::ExactFormsOverCompilerLimit { sampling: true, - float_maths: true, texel_conversion: false, nan_and_min_max: true, - rounding_order: false, }, ] } diff --git a/crates/metal2vulkan/src/device/tests/profile.rs b/crates/metal2vulkan/src/device/tests/profile.rs index 22669e4b6..df2a752aa 100644 --- a/crates/metal2vulkan/src/device/tests/profile.rs +++ b/crates/metal2vulkan/src/device/tests/profile.rs @@ -307,22 +307,14 @@ fn below_1_2_and_contradictory_policies_are_refused() { } /// Each of the policy's choices between the device's answer and Metal's, with a function that -/// flips it alone: the maths functions, the texel conversions, a normalized vertex attribute's -/// conversion, the NaN and minimum and maximum, the rounding order, and the filter of a two-plane -/// YCbCr texture. -fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 6] { +/// flips it alone: the texel conversions, a normalized vertex attribute's conversion, the NaN and +/// minimum and maximum, and the filter of a two-plane YCbCr texture. +fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 4] { use crate::device::{ - FloatMathsPolicy as F, NanMinMaxPolicy as N, RoundingOrderPolicy as R, - TexelConversionPolicy as T, VertexNormalizedPolicy as V, YCbCrFilterPolicy as Y, + NanMinMaxPolicy as N, TexelConversionPolicy as T, VertexNormalizedPolicy as V, + YCbCrFilterPolicy as Y, }; [ - ("float_maths", |p| DevicePolicy { - float_maths: match p.float_maths { - F::Native => F::Exact, - F::Exact => F::Native, - }, - ..p - }), ("texel_conversion", |p| DevicePolicy { texel_conversion: match p.texel_conversion { T::Device => T::Exact, @@ -344,13 +336,6 @@ fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 6] { }, ..p }), - ("rounding_order", |p| DevicePolicy { - rounding_order: match p.rounding_order { - R::Native => R::Exact, - R::Exact => R::Native, - }, - ..p - }), ("ycbcr_filter", |p| DevicePolicy { ycbcr_filter: match p.ycbcr_filter { Y::Device => Y::Exact, @@ -362,14 +347,14 @@ fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 6] { } /// On MoltenVK on the M3, whose functions, NaN, minimum and maximum are measured to be Metal's, -/// the maths functions' and the rounding order's choices change nothing, so each keys as the default does; the texel conversions' is the -/// policy's own field there, the NaN and minimum and maximum's moves the texel +/// each choice still moves the key: the texel conversions' is the policy's own field there, the +/// NaN and minimum and maximum's moves the texel /// NaN route (`TexelNanRoute`): a texel's NaN is the image's decode, which no arithmetic fact /// covers, and the YCbCr filter's moves whether a two-plane YCbCr slot takes its variant /// (`ProfileFields::ycbcr_variant`), Metal's sampler filtering such a texture's converted texels /// otherwise. #[test] -fn metal_s_own_answers_key_the_same_under_either_choice() { +fn each_choice_keys_apart_on_moltenvk() { let desc = profile("moltenvk-m3"); let fp = |p: DevicePolicy| { Device::new(desc.clone(), p) @@ -379,14 +364,7 @@ fn metal_s_own_answers_key_the_same_under_either_choice() { }; let base = DevicePolicy::default(); for (name, flip) in exactness_flips() { - assert_eq!( - fp(flip(base)) == fp(base), - !matches!( - name, - "texel_conversion" | "vertex_normalized" | "nan_and_min_max" | "ycbcr_filter" - ), - "{name}" - ); + assert_ne!(fp(flip(base)), fp(base), "{name}"); } } diff --git a/crates/metal2vulkan/src/lower/arith/chunk.rs b/crates/metal2vulkan/src/lower/arith/chunk.rs index 928013b7a..1dd2cb97b 100644 --- a/crates/metal2vulkan/src/lower/arith/chunk.rs +++ b/crates/metal2vulkan/src/lower/arith/chunk.rs @@ -39,7 +39,7 @@ use crate::air::intrinsics::{AirIntrinsic, MathFn}; use crate::air::ir::{Call, Callee, CastOp, Inst, InstId, InstKind, TypeId as AirTypeId, Value}; use crate::budget::Meter; use crate::error::Error; -use crate::lower::arith::legal::{self, chunk_lanes, not_lowered, FloatFmt, Form, Held}; +use crate::lower::arith::legal::{self, chunk_lanes, not_lowered, Form, Held}; use crate::lower::arith::libm::Lib; use crate::lower::arith::math::{self, FloatFn}; use crate::lower::arith::nan::{self, NanAnswer, NanTest}; @@ -358,16 +358,15 @@ fn is_math(call: &Call, f: MathFn) -> bool { ) } -/// `air.dot` of two chunked float vectors. On `float` and `half` where Metal's order is the -/// profile's (`RoundingOrderRoute::Metal`: `RoundingOrderPolicy::Exact`, or MoltenVK), Metal's -/// fused chain over every lane, as on two to four lanes (`math::metal_chain`): on an Apple M3 Max +/// `air.dot` of two chunked float vectors. On `float` and `half` where the device's functions are +/// Metal's (MoltenVK), and on `half` by the measured 16-bit fused multiply-add, Metal's fused chain +/// over every lane, as on two to four lanes (`math::metal_chain`): on an Apple M3 Max /// under macOS 27.0.1 every answer of `dot` on 5, 8 and 16 `float` lanes and on 8 and 16 `half` /// lanes, with and without fast-math flags, is the chain's (16,384 rows of seeded /// random lanes each, where the chain backwards, the chunks' sums added, and the exact sum rounded -/// once miss 6% to 70% of them; and our probe at `float` denormals on 8 lanes). It reads its -/// `float` operands and answers as Metal's `dot` of fewer lanes does: the lanes and the result -/// flushed where the device keeps denormals, and the chain's values as [`ArithStrategy::Dot`] -/// flushes them. Elsewhere the sum of each chunk's dot product, rounded once to a narrow format: +/// once miss 6% to 70% of them; and our probe at `float` denormals on 8 lanes), its `float` +/// denormals the device's (`super::leave_denormals`). Elsewhere the sum of each chunk's dot +/// product, rounded once to a narrow format: /// `dot`'s device precision (`DeviceArithmetic`) covers the order of the sum, which Vulkan leaves /// to the device for `OpDot` too. Its NaN is Metal's. fn select_dot( @@ -399,26 +398,11 @@ fn select_dot( super::record(cx, super::native_fma(fma)); cx.families.arith.take_fma(fma); super::fp_env(cx, call.fmf, elem); - let single = elem.float_fmt() == Some(FloatFmt::F32); - let (flush, reads) = if !single { - (false, denormal::Flush::NONE) - } else if denormal::device_flushes(cx.profile) { - cx.families.arith.device_denormals = true; - (false, denormal::Flush::NONE) - } else { - ( - fma.route.device_float(), - super::denormal_flush(cx, &[a, b], 0b11, true), - ) - }; - let tiny = denormal::tiny_check(cx.profile).filter(|_| single); + super::leave_denormals(cx, elem, denormal::Covered::Deviation); let s = ArithStrategy::ChunkedChain { lanes: shape.lanes, elem, fma, - flush, - reads, - tiny: cx.families.arith.take_tiny_check(tiny, elem), }; return Ok(super::with_nan(cx, at, s, answer, elem)); } @@ -471,17 +455,13 @@ pub fn dot_words(lanes: u16, elem: Form) -> u32 { } /// Metal's `dot` of chunked vectors `a` and `b` of `lanes` lanes of `elem`: its fused chain over -/// every lane in order (`math::metal_chain`), each fused multiply-add `fma`; where `flush`, the -/// chain's `float` values before the last read as Metal reads a denormal; each lane of the -/// operands `reads` names, and the result where it says so, read so too ([`denormal::flush`]). +/// every lane in order (`math::metal_chain`), each fused multiply-add `fma`. pub fn dot_chain( fb: &mut FunctionBuilder<'_>, lanes: u16, elem: Form, [a, b]: [SValue; 2], fma: math::FmaOf<'_>, - (flush, tiny): (bool, Option), - reads: denormal::Flush, ) -> BResult { let chunks = chunk_lanes(u32::from(lanes)); let lane = |fb: &mut FunctionBuilder<'_>, i: u32| -> BResult<(SValue, SValue)> { @@ -489,52 +469,28 @@ pub fn dot_chain( let size = chunks.get(c as usize).copied().ok_or_else(operand_error)?; let at = [c, i % 4]; let path = if size == 1 { &at[..1] } else { &at[..] }; - let mut xy = [ + Ok(( fb.composite_extract(a, path)?, fb.composite_extract(b, path)?, - ]; - for (k, v) in xy.iter_mut().enumerate() { - if reads.operand(k) { - *v = denormal::flush(fb, elem, *v)?; - } - } - Ok((xy[0], xy[1])) + )) }; - let sum = math::metal_chain(fb, elem, u32::from(lanes), &lane, fma, (flush, tiny))?; - if reads.result { - denormal::flush(fb, elem, sum) - } else { - Ok(sum) - } + math::metal_chain(fb, elem, u32::from(lanes), &lane, fma) } /// An upper estimate of the words of [`dot_chain`] on `lanes` lanes of `elem` whose fused -/// multiply-adds take `fma_words` each: two extractions per lane and the flushes of the lanes -/// `reads` names, the first product and its rounding, per later lane the fused multiply-add and, -/// where `flush`, the flush before it, and the result's flush. -pub fn dot_chain_words( - lanes: u16, - elem: Form, - fma_words: u32, - (flush, tiny): (bool, Option), - reads: denormal::Flush, -) -> u32 { +/// multiply-adds take `fma_words` each: two extractions per lane, the first product and its +/// rounding, and per later lane the fused multiply-add. +pub fn dot_chain_words(lanes: u16, elem: Form, fma_words: u32) -> u32 { let lanes = u32::from(lanes); - let flush_words = denormal::flush_words(elem); - let read = reads.operands.count_ones().saturating_mul(flush_words); - let step = fma_words + if flush { flush_words } else { 0 }; - let result = if reads.result { flush_words } else { 0 }; - let check = tiny.map_or(0, |check| denormal::tiny_product_words(elem, check)); - (12 + read) + 12u32 .saturating_mul(lanes) - .saturating_add(5 + narrow::round_words(elem) + check) - .saturating_add(lanes.saturating_sub(1).saturating_mul(step)) - .saturating_add(result) + .saturating_add(5 + narrow::round_words(elem)) + .saturating_add(lanes.saturating_sub(1).saturating_mul(fma_words)) } /// The sine and cosine of `x` of shape `s`: per chunk for a chunked vector, Metal's fast ones for -/// `air.fast_sincos` on `float` (`fast`, [`sin_cos_fns`]), each the device's instruction or the -/// math library's routine (`lib`), with the entry's NaN `test` ([`math::float_fn`]), then Metal's +/// `air.fast_sincos` on `float` (`fast`, [`sin_cos_fns`]), each the device's instruction as `lib` +/// reads it, with the entry's NaN `test` ([`math::float_fn`]), then Metal's /// NaN `answers` of each selected ([`nan::select`]). pub fn sin_cos( fb: &mut FunctionBuilder<'_>, @@ -543,7 +499,7 @@ pub fn sin_cos( fast: bool, answers: [Option; 2], test: NanTest, - lib: &Lib<'_>, + lib: &Lib, ) -> BResult<(SValue, SValue)> { let (sin, cos) = sin_cos_fns(fast); let one = |fb: &mut FunctionBuilder<'_>, f: Form, x: SValue| -> BResult<(SValue, SValue)> { diff --git a/crates/metal2vulkan/src/lower/arith/contract.rs b/crates/metal2vulkan/src/lower/arith/contract.rs index 5a708d191..2da8536c3 100644 --- a/crates/metal2vulkan/src/lower/arith/contract.rs +++ b/crates/metal2vulkan/src/lower/arith/contract.rs @@ -21,8 +21,8 @@ //! `fma(float(a), float(b), c)`, a product that is exact in `float`. Vectors of two to four lanes //! fuse lane-wise as scalars do. //! -//! A fused pair is one correctly rounded fused multiply-add ([`super::fma`]) by the profile's -//! route; the multiply (and its `fpext`) has no value of its own. An addition the rule leaves +//! A fused pair is one fused multiply-add ([`super::fma`]) by the profile's route; the multiply +//! (and its `fpext`) has no value of its own. An addition the rule leaves //! unfused whose operand is a `contract` multiply is `NoContraction`, so that no device fuses what //! Metal keeps apart. Where the rule cannot be read from the measured shapes, the pair stays two //! roundings and the plan notes `PrecisionNote::FastMathRewrites`: a product in another block than @@ -102,14 +102,12 @@ pub struct Link { pub negated: bool, } -/// A link of [`ArithStrategy::Fused`]: [`Link`] in value IDs, with the flushes of its factors -/// (bits 0 and 1) and of its value the module makes itself ([`denormal::Flush`]). +/// A link of [`ArithStrategy::Fused`]: [`Link`] in value IDs. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct FusedLink { pub a: ValueId, pub b: ValueId, pub negate: bool, - pub flush: denormal::Flush, } /// The contraction plan of a function. @@ -410,26 +408,16 @@ pub(super) fn select( reads.extend(fusion.inner.iter().flat_map(|l| [l.a, l.b])); super::check_operands(cx, &reads)?; cx.lowered_repr(Value::Inst(at), inst.ty)?; - // `OpFmaKHR` is the device's at denormals and NaNs; the routines are Metal's. Its - // denormals are Metal's where the device reads them so, else the module flushes them. Metal - // answers a fused pair's NaN as a written `fma`'s (the probe `e98b103f`'s `a * b + c` lanes - // under fast math, `float` and `half`): `OpFmaKHR` answers the device's `float` NaN and a - // `half` result's rounding the device's `half` NaN on every route, so Metal's is selected. + // The device's `float` instruction is the device's at denormals and NaNs: its denormals are + // Metal's where the device reads them so, else the device's own ([`super::leave_denormals`]). + // Metal answers a fused pair's NaN as a written `fma`'s (the probe `e98b103f`'s `a * b + c` + // lanes under fast math, `float` and `half`): the device's `float` instruction answers the + // device's `float` NaN and a `half` result's rounding the device's `half` NaN on every route, + // so Metal's is selected. let khr = fma.route.device_float(); - // A chain's links flush their factors and values as the outer pair does; `OpFmaKHR` checked - // ([`Fma::checked`]) answers no denormal, so only its factors and addend are read. - let flush_of = |cx: &mut SelectCx<'_>, operands: &[Value]| { - if khr { - let flush = super::fused_flush(cx, f, operands); - denormal::Flush { - result: flush.result && !fma.checked(), - ..flush - } - } else { - denormal::Flush::NONE - } - }; - let flush = flush_of(cx, &[fusion.a, fusion.b, fusion.c]); + if khr { + super::leave_denormals(cx, f, denormal::Covered::Deviation); + } let nan = match f.float_fmt() { Some(FloatFmt::Half) => nan::function_answer(FloatFn::Fma, false, false, FloatFmt::Half), _ => khr.then_some(nan::NanAnswer::Canonical), @@ -452,7 +440,6 @@ pub(super) fn select( a: id(cx, link.a)?, b: id(cx, link.b)?, negate: link.negated, - flush: flush_of(cx, &[link.a, link.b]), }); } let s = ArithStrategy::Fused { @@ -461,7 +448,6 @@ pub(super) fn select( b: id(cx, fusion.b)?, c: id(cx, fusion.c)?, negate: fusion.negate, - flush, inner: inner.into_boxed_slice(), }; Ok(Some(super::with_nan(cx, at, s, nan, f))) diff --git a/crates/metal2vulkan/src/lower/arith/denormal.rs b/crates/metal2vulkan/src/lower/arith/denormal.rs index 6312bbab8..edd19f371 100644 --- a/crates/metal2vulkan/src/lower/arith/denormal.rs +++ b/crates/metal2vulkan/src/lower/arith/denormal.rs @@ -1,88 +1,25 @@ -//! How Metal reads an `f32` denormal operand, per operation: the one table of the translation -//! (the denormal-operand model extends it). -//! -//! Metal flushes most `float` operands whose exponent field is zero to a zero of their sign, but -//! not every operation does, and the measured exceptions are per operation and per math mode: -//! precise `asin` answers a denormal operand itself, where `fast::asin` answers `+0` for it (cases -//! 087758cb and cc234732). A lowering that computes an operation itself, -//! rather than leaving it to a device that is Metal's own (`FloatFunctions::Metal`), reads the -//! operand as this table says, before its own special values. The table is decided on the exponent -//! field, so the answer is the same whatever the device's own denormal mode. Only `float` operands -//! are listed: a widened `half` is never an `f32` denormal, and Metal's `bfloat` and `double` -//! environments are not measured. +//! How Metal reads `f32` denormals, per operation, against the device: where the device reads them +//! as Metal does, an `f32` denormal operand as the zero of its sign and a denormal result flushed +//! to one (`DriverDeviation::MetalFloatDenormals`, a measured driver fact), the module leaves them +//! to it and requires the property; elsewhere they are the device's own, noted +//! (`PrecisionNote::DeviceDenormals`). Only `float` operations are listed: a widened `half` is +//! never an `f32` denormal, and Metal's `bfloat` and `double` environments are not measured. -use crate::device::profile::FloatFunctions; use crate::device::DeviceProfile; use crate::error::DriverDeviation; -use crate::lower::arith::fma; use crate::lower::arith::legal::Form; use crate::lower::arith::math::FloatFn; use crate::lower::arith::narrow::u32_form; -use crate::lower::arith::ops::{fsplat, splat, ty}; +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, Contraction, ConvOp, GlslOp}; - -/// How Metal reads an `f32` denormal operand of one operation. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Operand { - /// As the zero of its sign. - Flush, - /// As itself. - Keep, -} - -/// How Metal reads an `f32` denormal operand of float function `op`, where the table states it -/// (`None` for an operation it does not list yet). -/// -/// | operation | operand | Metal's answer for a denormal operand (cases 087758cb, cc234732) | -/// |---|---|---| -/// | `atan` | flushed | `+0`, whatever its sign (as `atan(-0)`) | -/// | `fast::atan` | flushed | the zero of its sign | -/// | `asin` | kept | the operand itself | -/// | `fast::asin` | flushed | `+0`, whatever its sign (as `fast::asin(-0)`) | -/// | `acos`, `fast::acos` | flushed | `π/2` (either reading gives it) | -/// | `atan2`, `fast::atan2` | flushed | as a zero operand | -/// | `sin`, `cos`, `tan` | kept | `sin` and `tan`: the operand itself; `cos`: 1 | -/// | `fast::sin`, `fast::cos`, `fast::tan` | kept | as `sin`, `cos`, and `tan` (case cc234732, where RADV, ANV, and NVIDIA flush it) | -/// | `sinpi`, `cospi`, `tanpi`, and their `fast::` forms | flushed | `sinpi` and `tanpi`: `+0`, whatever its sign; `cospi`: 1 (both modes) | -pub fn operand(op: FloatFn) -> Option { - use FloatFn as F; - Some(match op { - F::Asin | F::Sin | F::Cos | F::Tan | F::FastSin | F::FastCos | F::FastTan { .. } => { - Operand::Keep - } - F::Atan - | F::FastAtan - | F::FastAsin - | F::Acos - | F::FastAcos - | F::Atan2 - | F::FastAtan2 { .. } - | F::SinPi - | F::CosPi - | F::TanPi - | F::FastSinPi - | F::FastCosPi - | F::FastTanPi => Operand::Flush, - _ => return None, - }) -} - -/// `x` (`float` lanes of form `f`) as operation `op` reads it ([`operand`]): a denormal lane -/// replaced by the zero of its sign where the table flushes it; `x` itself otherwise. -pub fn read(fb: &mut FunctionBuilder<'_>, op: FloatFn, f: Form, x: Value) -> BResult { - if operand(op) != Some(Operand::Flush) { - return Ok(x); - } - flush(fb, f, x) -} +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 /// flushed to one (`DriverDeviation::MetalFloatDenormals`, a measured driver fact). Elsewhere -/// the module flushes them itself ([`Flush`]). +/// they are the device's own (`PrecisionNote::DeviceDenormals`). pub fn device_flushes(p: &DeviceProfile) -> bool { p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals) } @@ -90,267 +27,55 @@ pub fn device_flushes(p: &DeviceProfile) -> bool { /// Where an operation the device computes reads its `f32` denormals as Metal does. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Covered { - /// On a device with the measured deviation ([`device_flushes`]); elsewhere the module - /// flushes them itself. + /// On a device with the measured deviation ([`device_flushes`]); elsewhere they are the + /// device's own. Deviation, - /// On no device measured: the module flushes them itself on every profile. `Floor` and - /// `Ceil` of a denormal give `-1` and `1` on NVIDIA's 615.71.09 and on lavapipe, where Metal - /// reads the operand as a zero (`floor(-2^-149)` is `-0`, `ceil(2^-149)` is `+0`). + /// On no device measured: the device's own on every profile. `Floor` and `Ceil` of a denormal + /// give `-1` and `1` on NVIDIA's 615.71.09 and on lavapipe, where Metal reads the operand as a + /// zero (`floor(-2^-149)` is `-0`, `ceil(2^-149)` is `+0`). Never, } -/// How Metal reads the `f32` denormals of an operation the device computes, and where the -/// device reads them so ([`coverage`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Reading { - /// Where the device's reading is Metal's. - pub covered: Covered, - /// A bit per operand Metal reads as the zero of its sign where it is a denormal. - pub operands: u8, - /// Whether Metal flushes a denormal result. - pub result: bool, -} - -impl Reading { - /// `+ - *` and the comparisons (`result` false for a comparison, whose result is a `bool`): - /// both operands, on the deviation. - pub const fn binary(result: bool) -> Reading { - Reading { - covered: Covered::Deviation, - operands: 0b11, - result, - } - } -} - -/// How the device's instruction for float function `op` (on `float` lanes, where the lowering -/// leaves `op` to it) reads `f32` denormals against Metal, which reads each `float` operand of -/// these as the zero of its sign and flushes a denormal result (the denormal probes, -/// `nan_denormals` and `nan_denormals_fast`, every lane). `None` for a function whose lowering -/// reads its denormals as Metal does itself (`FloatFn::metal_denormals`) or whose reading is not -/// measured. +/// Where the device's instruction for float function `op` (on `float` lanes, where the lowering +/// leaves `op` to it) reads `f32` denormals as Metal, which reads each `float` operand of these +/// as the zero of its sign and flushes a denormal result (the denormal probes, `nan_denormals` +/// and `nan_denormals_fast`, every lane). `None` for a function whose lowering reads its +/// denormals as Metal does itself (`FloatFn::metal_denormals`) or whose reading is not measured. /// -/// | function | operands | result | where the device's reading is Metal's | -/// |---|---|---|---| -/// | `floor`, `ceil` | the operand | integral | no device measured | -/// | `trunc`, `rint` | the operand | integral | the deviation | -/// | `sqrt`, `rsqrt`, `fast::rsqrt` | the operand | never denormal | the deviation | -/// | `dot` | both vectors | flushed | the deviation | -/// | `fma`, `llvm.fmuladd` (`OpFmaKHR`) | all three | flushed | the deviation | -/// | `fast::atan2` | both | never denormal | the deviation | -/// -/// `dot` is Metal's fused chain of its products: the device's own `OpDot` where it reaches Metal's -/// `dot`, else the multiply and `OpFmaKHR`s the deviation also covers, or the routines, which read -/// as Metal does; where the profile lacks the deviation, the chain flushes its values between the -/// fused multiply-adds as well. +/// | function | where the device's reading is Metal's | +/// |---|---| +/// | `floor`, `ceil` | no device measured | +/// | `trunc`, `rint` | the deviation | +/// | `sqrt`, `rsqrt`, `fast::rsqrt` | the deviation | +/// | `dot` | the deviation | +/// | `fma`, `llvm.fmuladd` (`OpFmaKHR`) | the deviation | +/// | `fast::atan2` | the deviation | /// /// `fast::atan2(y, x)` reads a denormal `y` or `x` as the zero of its sign and answers no denormal /// (an Apple M3 Max under macOS 27.0.1: every pair of 28 patterns, in entries with and without fast -/// math); its quotient is the device's multiply or division, whose operands are those two, and a -/// denormal quotient reaches the fast `atan`, which reads it as a zero. Where native device maths -/// answers it, its denormals are the device's (the caller flushes nothing there). +/// math); its quotient is the device's division, whose operands are those two, and a denormal +/// quotient reaches the fast `atan`, which reads it as a zero. /// /// `trunc` and `rint` (`Trunc`, `RoundEven`) of a denormal answer the zero of its sign on every /// venue measured, as Metal does (the probes' words, both modes, all seven venues), but Vulkan -/// states no sign for a flushed denormal, so where the profile lacks the deviation the module -/// flushes the operand itself rather than trust the device's zero. -pub fn coverage(op: FloatFn) -> Option { +/// states no sign for a flushed denormal, so only the deviation covers them. +pub fn coverage(op: FloatFn) -> Option { use FloatFn as F; - let (covered, operands, result) = match op { - F::Floor | F::Ceil => (Covered::Never, 0b1, false), - F::Trunc | F::Rint => (Covered::Deviation, 0b1, false), - F::Sqrt | F::Rsqrt | F::FastRsqrt => (Covered::Deviation, 0b1, false), - F::Dot => (Covered::Deviation, 0b11, true), - F::Fma | F::MulAdd => (Covered::Deviation, 0b111, true), - F::FastAtan2 { .. } => (Covered::Deviation, 0b11, false), + Some(match op { + F::Floor | F::Ceil => Covered::Never, + F::Trunc + | F::Rint + | F::Sqrt + | F::Rsqrt + | F::FastRsqrt + | F::Dot + | F::Fma + | F::MulAdd + | F::FastAtan2 { .. } => Covered::Deviation, _ => return None, - }; - Some(Reading { - covered, - operands, - result, }) } -/// The `f32` denormals an operation flushes itself where the device may keep them -/// (`ArithStrategy::Denormals`): the operands whose bit is set in `operands`, read by [`flush`] -/// before the operation, and its result where `result`. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct Flush { - /// A bit per operand read as Metal reads it. - pub operands: u8, - /// Whether a denormal result is flushed. - pub result: bool, -} - -impl Flush { - /// Nothing flushed. - pub const NONE: Flush = Flush { - operands: 0, - result: false, - }; - - /// Whether operand `i` is flushed. - pub fn operand(self, i: usize) -> bool { - i < 8 && self.operands & (1 << i) != 0 - } - - /// Whether anything is flushed. - pub fn any(self) -> bool { - self.operands != 0 || self.result - } - - /// An upper estimate of the SPIR-V words of the flushes on lanes of form `f`: [`flush_words`] - /// each. - pub fn words(self, f: Form) -> u32 { - (self.operands.count_ones() + u32::from(self.result)) * flush_words(f) - } -} - -/// Whether profile `p` computes Metal's `float` product where the exact product lies below -/// `2^-126` and the device's rounding reaches `±2^-126` ([`tiny_product`]): where its functions -/// are to answer as Metal's (`FloatFunctions::Device`, the policy's `FloatMathsPolicy::Exact`). -/// Metal flushes such a product to the zero of its sign, deciding tininess before rounding; every -/// Vulkan device measured off MoltenVK rounds first, those that flush their denormals and those -/// that keep them (the authored tininess cases' rows on RADV, ANV, NVIDIA and lavapipe), and -/// Vulkan states no order. On MoltenVK the multiply is Metal's own (`FloatFunctions::Metal`); -/// under native device maths (`FloatFunctions::Native`, the default) the device's product is -/// taken, which the runtime announces once per device (`float-tininess-after-rounding`). -pub fn checks_tiny_products(p: &DeviceProfile) -> bool { - p.fields().float_functions == FloatFunctions::Device -} - -/// How a check of a `float` product at `±2^-126` decides whether the exact product lies below -/// `2^-126` ([`tiny_product`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum TinyCheck { - /// By one `OpFmaKHR` on the operands' magnitudes, one of them scaled: where the profile's - /// `float` fused multiply-add is `OpFmaKHR` (`fma::Route::Khr`). - Fused, - /// By the operands' bits, in integer operations of Vulkan 1.2's core alone. - Bits, -} - -/// The check of a `float` product at `±2^-126` profile `p` takes, where it checks one -/// ([`checks_tiny_products`]). -pub fn tiny_check(p: &DeviceProfile) -> Option { - if !checks_tiny_products(p) { - return None; - } - Some(match fma::float_route(p) { - fma::Route::Khr => TinyCheck::Fused, - _ => TinyCheck::Bits, - }) -} - -/// Metal's product of `float` lanes `a` and `b` (form `f`, each read as Metal reads a denormal) -/// from `r`, the device's product of them: the zero of `r`'s sign where `r` is `±2^-126` and the -/// exact product lies below `2^-126` in magnitude, else `r`, decided by `check`. Inline and -/// branchless: the device's compiler inlines any call, so a shared routine would not shrink what -/// it compiles at each product. -/// -/// Only a product whose exact value lies within half a unit of `2^-126` rounds to `±2^-126`, and -/// a zero, denormal, infinite or NaN operand gives no such `r` (a denormal operand is read as a -/// zero before the multiply, by the device or [`flush`]). So where `r` is `±2^-126` both operands -/// are normal, at most `1 + 2^-23` in magnitude (the other is at least `2^-126`), and with biased -/// exponent fields `ea` and `eb` and significands `ma` and `mb` (hidden bit set) the exact product -/// is `ma · mb · 2^(ea + eb - 300)`, with `ea + eb` 126, 127 or 128. -/// -/// - [`TinyCheck::Fused`]: `OpFmaKHR(|a| · 2^48, |b|, -2^-78)` is `2^48 · (|a · b| - 2^-126)` -/// rounded once (Vulkan's precision table: correctly rounded), negative exactly where the exact -/// product lies below `2^-126`. `|a| · 2^48` is exact and finite, an `OpFMul` decorated -/// `NoContraction` (rounded on its own, as it is exact); the difference is a multiple -/// of `2^-174` (`ea + eb` is at least 126), so scaled it is zero or at least `2^-126`, a normal -/// number no denormal mode changes and rounding keeps the sign of. Elsewhere the lane is not -/// `±2^-126` and the test is not taken. -/// - [`TinyCheck::Bits`]: below `2^-126` where `ea + eb <= 126`, or where `ea + eb == 127` and -/// `ma · mb < 2^47`, which the high word of `OpUMulExtended` tells (`hi < 2^15`). -/// -/// The test of `r` and its zero are on `r`'s bits, so the same in every float mode. -pub fn tiny_product( - fb: &mut FunctionBuilder<'_>, - f: Form, - [a, b]: [Value; 2], - r: Value, - check: TinyCheck, -) -> BResult { - let u = u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let rb = fb.convert(ConvOp::Bitcast, r, ut)?; - // `r` is `±2^-126`. - let magnitude = splat(fb, u, 0x7FFF_FFFF)?; - let least = splat(fb, u, 0x0080_0000)?; - let m = fb.binary(BinOp::BitwiseAnd, rb, magnitude)?; - let at_least = fb.binary(BinOp::IEqual, m, least)?; - let below = match check { - TinyCheck::Fused => fused_below(fb, f, [a, b])?, - TinyCheck::Bits => bits_below(fb, u, [a, b])?, - }; - let tiny = fb.binary(BinOp::LogicalAnd, at_least, below)?; - let sign = splat(fb, u, 0x8000_0000)?; - let signed_zero = fb.binary(BinOp::BitwiseAnd, rb, sign)?; - let out = fb.select(tiny, signed_zero, rb)?; - fb.convert(ConvOp::Bitcast, out, ft) -} - -/// Whether `|a · b|` lies below `2^-126` ([`TinyCheck::Fused`]), for normal `a` and `b` at most -/// `1 + 2^-23` in magnitude whose product rounds to `±2^-126`. -fn fused_below(fb: &mut FunctionBuilder<'_>, f: Form, [a, b]: [Value; 2]) -> BResult { - let x = fb.glsl(GlslOp::FAbs, &[a])?; - let y = fb.glsl(GlslOp::FAbs, &[b])?; - let scale = fsplat(fb, f, 2f64.powi(48))?; - // Exact, and `NoContraction` so that no device folds it into another operation. - let x = fb.binary_with(BinOp::FMul, x, scale, Contraction::Forbidden)?; - let edge = fsplat(fb, f, -(2f64.powi(-78)))?; - let d = fb.fma(x, y, edge)?; - let zero = fsplat(fb, f, 0.0)?; - fb.binary(BinOp::FOrdLessThan, d, zero) -} - -/// Whether the exact product of `a` and `b` lies below `2^-126` ([`TinyCheck::Bits`]), on `u32` -/// lanes of form `u`, for operands whose product rounds to `±2^-126`. -fn bits_below(fb: &mut FunctionBuilder<'_>, u: Form, [a, b]: [Value; 2]) -> BResult { - let ut = ty(fb, u)?; - let ab = fb.convert(ConvOp::Bitcast, a, ut)?; - let bb = fb.convert(ConvOp::Bitcast, b, ut)?; - // The exponent fields' sum, in place: at most 2 · 254 · 2^23, below 2^32. - let field = splat(fb, u, 0x7F80_0000)?; - let ea = fb.binary(BinOp::BitwiseAnd, ab, field)?; - let eb = fb.binary(BinOp::BitwiseAnd, bb, field)?; - let sum = fb.binary(BinOp::IAdd, ea, eb)?; - let below = splat(fb, u, 126 << 23)?; - let edge = splat(fb, u, 127 << 23)?; - let low = fb.binary(BinOp::ULessThanEqual, sum, below)?; - let at_edge = fb.binary(BinOp::IEqual, sum, edge)?; - // The significands' product below `2^47`: its high word below `2^15`. - let fraction = splat(fb, u, 0x007F_FFFF)?; - let hidden = splat(fb, u, 0x0080_0000)?; - let mut significand = |x: Value| -> BResult { - let m = fb.binary(BinOp::BitwiseAnd, x, fraction)?; - fb.binary(BinOp::BitwiseOr, m, hidden) - }; - let (ma, mb) = (significand(ab)?, significand(bb)?); - let product = fb.binary(BinOp::UMulExtended, ma, mb)?; - let hi = fb.composite_extract(product, &[1])?; - let limit = splat(fb, u, 0x8000)?; - let under = fb.binary(BinOp::ULessThan, hi, limit)?; - let edge_tiny = fb.binary(BinOp::LogicalAnd, at_edge, under)?; - fb.binary(BinOp::LogicalOr, low, edge_tiny) -} - -/// An upper estimate of the SPIR-V words of one [`tiny_product`] on form `f` by `check`: the test -/// of `r` and the zero, seven instructions; [`TinyCheck::Fused`]'s five more, three constants and -/// the scaling's decoration (three words), [`TinyCheck::Bits`]'s 16 more, six constants and the -/// extended product's struct type; each instruction of at most six words, and the constants' share -/// (a vector's constants carry their lanes). -pub fn tiny_product_words(f: Form, check: TinyCheck) -> u32 { - let lanes = u32::from(f.lanes); - match check { - TinyCheck::Fused => 93 + 7 * (7 + lanes), - TinyCheck::Bits => 160 + 10 * (7 + lanes), - } -} - /// 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 { diff --git a/crates/metal2vulkan/src/lower/arith/divide.rs b/crates/metal2vulkan/src/lower/arith/divide.rs index a4fb1bcff..f94247315 100644 --- a/crates/metal2vulkan/src/lower/arith/divide.rs +++ b/crates/metal2vulkan/src/lower/arith/divide.rs @@ -1,91 +1,26 @@ -//! Metal's precise division: the correctly rounded quotient on every profile. +//! Metal's precise division, by the device's `OpFDiv`. //! //! Metal's `float` division without `arcp` (a flagless `fdiv`, `precise::divide`, and the plain -//! operator under `-fno-fast-math`) answers the quotient rounded once to nearest even, with an -//! `f32` denormal operand read as a zero of its sign, a quotient below the smallest normal once -//! rounded to 24 bits (with an unbounded exponent) flushed to a zero of its sign, and -//! `0x7FC00000` for a NaN (a probe cases 914cc4d2 and 711cc190, every lane; A1 case 87d13612). The -//! flush follows the 24-bit rounding, not a rounding on the denormal grid: the quotient `(2^24 - 1) -//! · 2^-150`, which that grid rounds up to `2^-126`, is a zero (a probe case c10cba13, 64 lanes of -//! 512, every lane matched). Vulkan bounds `OpFDiv` at 2.5 ulp for a divisor in `[2^-126, 2^126]` -//! and not at all beyond, and devices use that latitude: RADV answers `3 / 3` with `0x3f7fffff` and -//! a divisor past `2^126` with a zero. -//! -//! Each profile calls one module-scope routine per lane count ([`Routine`], as the wide divisions -//! are), by one of two [`Path`]s: -//! -//! - [`Path::Integer`] (`quotient`), on every profile: the operands' significands `X` and `Y` -//! (24-bit integers) and the device's `OpFDiv` of the operands moved to `[1, 2)`, within 2.5 -//! ulp there, give a 24-bit integer quotient `Q` within three of `F = floor(X · 2^s / Y)` -//! (`s` = 23 or 24, so that `F` has 24 bits). The remainder `X · 2^s - Q · Y` is below `2^31` -//! in magnitude, so its low 32 bits, which 32-bit integer arithmetic computes, are exactly it -//! as a signed integer; three steps each way move `Q` to `F` and the remainder into `[0, Y)`. -//! Twice the remainder against `Y` then rounds `F` to nearest even. The exponent is the -//! operands' difference, with the rounding's carry; a result past the largest `float` is the -//! infinity of its sign, and one below the smallest normal is a zero of its sign. Zeros, -//! infinities, NaNs, and denormal operands are selected as Metal answers them. -//! - [`Path::Fused`] (`fused`), where the profile's `float` fused multiply-add is `OpFmaKHR` -//! ([`fma::Route::Khr`]): Markstein's sequence on the operands' significands moved to `[1, 2)`, -//! where no intermediate overflows or reaches a denormal, so the device's environment does not -//! enter. The device's reciprocal of the divisor's (within 2.5 ulp) takes two Newton steps, `r += -//! r · (1 - y · r)`, each fused, which make it `RN(1/y)` except at an all-ones significand, where -//! it is the even neighbor below and one ulp up corrects it (every significand, every estimate -//! within 2.5 ulp: the `markstein_reciprocal_is_correctly_rounded` test). `q = x · r` is within -//! two ulp of `x / y`; one fused step `q += r · (x - y · q)` brings it within one ulp, where `x - -//! y · q` is exact, and Markstein's theorem (P. Markstein, IBM J. Res. Develop. 34(1), 1990) -//! makes a second step the correctly rounded quotient. The quotient of the significands is in -//! `(1/2, 2)`, so its rounding is the exact quotient's 24-bit rounding; its exponent moved by the -//! operands' difference gives the result, with the overflow, the flush, and the special operands -//! as `quotient` answers them. Every lane takes this one path: a divisor far from one costs what -//! a divisor near it does (an earlier form ran the sequence on the operands themselves, in range -//! only for `|y|` in `[2^-31, 2^33)`, and sent any other lane through `quotient` as well, 17 -//! times `OpFDiv`'s GPU time on RADV for a divisor near `2^40`). -//! -//! Metal divides `half` the same way under every flag set, `arcp` included: the quotient rounded -//! once from the exact one, `half` denormals kept (a probe cases 4c363561 under fast math and -//! 54f0fe8e without, every lane). The device's `float` `OpFDiv` rounded to `half` is not that -//! quotient by Vulkan's contract: within 2.5 ulp, it may cross a `half` rounding midpoint, from -//! which a quotient of two `half` values can be as little as two `float` ulp away (1 / (2047 / -//! 1024) is 2.001 ulp from one). So every `half` division calls a routine, and its `float` -//! quotient of the operands (held in `float`) is rounded once to `half`. On the integer path and -//! the fused path that quotient is correctly rounded, and a quotient of two `half` values is never -//! within half a `float` ulp of a `half` rounding midpoint without being one, so the two roundings -//! are one. Where the fused path's profiles hold every `half` value exactly (not native half -//! rounding, whose device compiler may hand over an unrounded operand), a `half` division takes a -//! third path: -//! -//! - [`Path::Halves`] (`halves`): one fused correction `q + r · (x - y · q)` of `q = x · r`, `r` -//! the device's `1 / y`, on the operands themselves. That quotient is within `1/2 + 2^-18` ulp -//! of the exact one and is it wherever the exact one is a `float`, which suffices: the exact -//! quotient of two `half` values is a point of the 12-bit grid (every `half` value and every -//! `half` rounding midpoint, the overflow threshold 65520 and the denormal ones included) or at -//! least two `float` ulp from every such point, so both round to the same `half`. No step leaves -//! the normal range (the divisor is in `[2^-24, 65504]`, the quotient in `[2^-40, 2^40]`), so -//! the device's environment does not enter, and scaling an operand by a power of two scales -//! every step exactly: the `one_fused_correction_rounds_every_half_quotient` test runs every -//! pair of 11-bit significands with every estimate within 2.5 ulp. Zeros, infinities, and NaNs -//! are answered as `fused` answers them, by integer tests that fast math keeps. On an Apple M3 -//! Max through MoltenVK, the pipeline of a fragment function with 164 such divisions is created -//! in about 5.8 s instead of 6.5 s through `fused`. +//! operator under `-fno-fast-math`) answers the quotient rounded once to nearest even (a probe +//! cases 914cc4d2 and 711cc190, every lane), and its `half` division under every flag set the +//! quotient rounded once from the exact one (4c363561, 54f0fe8e). Vulkan bounds `OpFDiv` at 2.5 +//! ulp for a divisor in `[2^-126, 2^126]` and not at all beyond, and devices use that latitude: +//! RADV answers `3 / 3` with `0x3f7fffff` and a divisor past `2^126` with a zero. Every such +//! division takes the device's `OpFDiv` ([`native`]), its divisor kept in Vulkan's range, within +//! Vulkan's bound (`PrecisionNote::NativeDivision`). use crate::air::ir::{BinOp as AirBin, FastMath}; -use crate::device::profile::FloatFunctions; -use crate::device::DeviceProfile; -use crate::lower::arith::fma::{self, Route}; -use crate::lower::arith::legal::{FloatFmt, Form, Held}; -use crate::lower::arith::narrow::{self, u32_form}; -use crate::lower::arith::ops::{fsplat, splat, ty}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; +use crate::lower::arith::legal::{FloatFmt, Form}; +use crate::lower::arith::narrow; +use crate::lower::arith::ops::fsplat; +use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::{BResult, BuildError, TypeRule}; -use crate::spirv::ids::{FuncId, Value}; -use crate::spirv::ir::{BinOp, ConvOp, Type, UnOp}; - -/// The census name of a precise division ([`super::ArithStrategy::PreciseDivide`]). -pub const PRECISE: &str = "arith.fdiv.precise"; +use crate::spirv::ids::Value; +use crate::spirv::ir::BinOp; /// Whether the float binary operator `op` with fast-math flags `fmf` on format `fmt` is Metal's -/// precise division, which the shared routine computes: an `fdiv` on `float` without `arcp`, or -/// on `half` under every flag set (the module's comment). +/// precise division: an `fdiv` on `float` without `arcp`, or on `half` under every flag set (the +/// module's comment). pub fn precise(op: AirBin, fmt: FloatFmt, fmf: FastMath) -> bool { op == AirBin::FDiv && match fmt { @@ -95,124 +30,7 @@ pub fn precise(op: AirBin, fmt: FloatFmt, fmf: FastMath) -> bool { } } -/// How a precise division routine computes its quotient. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum Path { - /// `quotient`: 32-bit integer arithmetic from the device's estimate. Every profile. - Integer, - /// `fused`, Markstein's sequence on the significands: profiles whose `float` fused - /// multiply-add is `OpFmaKHR`. - Fused, - /// `halves`, one fused correction on `half` operands held in `float`: a `half` division on - /// those profiles where every `half` value is held exactly ([`Routine::on`]). - Halves, -} - -impl Path { - /// The path of a `float` division on profile `p`: [`Path::Fused`] where its `float` fused - /// multiply-add is `OpFmaKHR` ([`fma::float_route`]), else [`Path::Integer`]. - pub fn on(p: &DeviceProfile) -> Path { - match fma::float_route(p) { - Route::Khr => Path::Fused, - Route::Wide | Route::Soft | Route::F16 | Route::F16Khr | Route::Native => Path::Integer, - } - } -} - -/// The module-scope precise division routine on `float` lanes of `lanes` lanes by `path`. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct Routine { - pub lanes: u8, - pub path: Path, -} - -impl Routine { - /// The routine for a division of form `f` (`float` or `half` lanes) on profile `p`: the - /// profile's [`Path`], or [`Path::Halves`] for `half` lanes on the fused path where the - /// profile's `half` rounding is not the device's own (`narrow::native_rounding`), so that - /// every operand is a `half` value. - pub fn on(p: &DeviceProfile, f: Form) -> Routine { - let path = match Path::on(p) { - Path::Fused - if f.float_fmt() == Some(FloatFmt::Half) - && narrow::native_rounding(p, narrow::quantize_form(p)).is_none() => - { - Path::Halves - } - path => path, - }; - Routine { - lanes: f.lanes, - path, - } - } - - /// An upper estimate of the routine's SPIR-V words, with its constants and types. - pub fn words(self) -> u32 { - let lanes = u32::from(self.lanes); - match self.path { - Path::Integer => 640 + 48 * lanes, - Path::Fused => 420 + 40 * lanes, - Path::Halves => 240 + 24 * lanes, - } - } -} - -/// An upper estimate of the SPIR-V words per use of a precise division on form `f`: the call, -/// and a `half` quotient's rounding. -pub fn use_words(f: Form) -> u32 { - 24 + narrow::round_words(f) -} - -/// Define routine `r`: a function of two `float` values of `r.lanes` lanes returning Metal's -/// precise quotient. -pub fn define(mb: &mut ModuleBuilder, r: Routine) -> BResult { - define_with(mb, r, &device_division) -} - -/// [`define`] with `rough` the device's quotient (a test moves it within Vulkan's bound). -pub(super) fn define_with(mb: &mut ModuleBuilder, r: Routine, rough: Rough<'_>) -> BResult { - let f = f32_form(r.lanes); - let e = mb.ty(Type::Float { width: 32 })?; - let t = if r.lanes == 1 { - e - } else { - mb.ty(Type::Vector { - elem: e, - len: r.lanes, - })? - }; - let mut fb = mb.routine(t)?; - let (x, y) = (fb.param(t)?, fb.param(t)?); - let q = match r.path { - Path::Integer => quotient(&mut fb, f, x, y, rough)?, - Path::Fused => fused(&mut fb, f, x, y, rough)?, - Path::Halves => halves(&mut fb, f, x, y, rough)?, - }; - fb.ret(Some(q))?; - fb.finish() -} - -/// Metal's precise quotient of `x` and `y` (form `f`, `float` or `half` lanes) through -/// `routine`, the form's lane count's [`define`]. -pub fn emit( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - y: Value, - routine: FuncId, -) -> BResult { - let q = fb - .call(routine, &[x, y])? - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - match f.float_fmt() { - Some(FloatFmt::F32) => Ok(q), - Some(FloatFmt::Half) => narrow::round(fb, f, q), - _ => Err(BuildError::Type(TypeRule::FunctionSignature)), - } -} - -/// The census name of a precise division by native device maths ([`native`]). +/// The census name of a precise division ([`native`]). pub const NATIVE: &str = "arith.fdiv.native"; /// An upper estimate of the SPIR-V words of one [`native`] division on form `f`: the divisor's @@ -222,11 +40,11 @@ pub fn native_words(f: Form) -> u32 { 96 + 16 * u32::from(f.lanes) } -/// Metal's precise division `x / y` on `float` or `half` lanes (form `f`) by native device maths -/// (`FloatFunctions::Native`): the device's `OpFDiv`, within Vulkan's 2.5 ulp for a divisor in -/// `[2^-126, 2^126]`, the operands of a divisor past `2^126` first scaled by `2^-2` into that range -/// (exactly, but where the dividend becomes a denormal, whose quotient by such a divisor Metal -/// flushes to zero anyway); a `half` quotient rounded to `half` (`PrecisionNote::NativeDivision`). +/// Metal's precise division `x / y` on `float` or `half` lanes (form `f`): the device's `OpFDiv`, +/// within Vulkan's 2.5 ulp for a divisor in `[2^-126, 2^126]`, the operands of a divisor past +/// `2^126` first scaled by `2^-2` into that range (exactly, but where the dividend becomes a +/// denormal, whose quotient by such a divisor Metal flushes to zero anyway); a `half` quotient +/// rounded to `half` (`PrecisionNote::NativeDivision`). pub fn native(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, y: Value) -> BResult { let ay = fb.glsl(crate::spirv::ir::GlslOp::FAbs, &[y])?; let limit = fsplat(fb, f, 2f64.powi(126))?; @@ -242,409 +60,3 @@ pub fn native(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, y: Value) -> BRes _ => Err(BuildError::Type(TypeRule::FunctionSignature)), } } - -/// The device's quotient of two `float` lanes, the estimate `quotient` (of two lanes in -/// `[1, 2)`), `fused` (of one and a divisor in its range), `halves` (of one and a `half` divisor), -/// and [`Reciprocal::Rounded`] correct. -pub(super) type Rough<'a> = &'a dyn Fn(&mut FunctionBuilder<'_>, Value, Value) -> BResult; - -/// How Metal's fast reciprocal (`math::fast_reciprocal`, the reciprocal of an `arcp` division) is -/// rounded on a profile. Metal's own is within about 0.64 ulp of `1 / y` and not correctly rounded: -/// it differs from `RN(1 / y)` on 38 of a probe case 914cc4d2's 512 lanes, each near a rounding -/// midpoint, and no exact form of it is known. Off a device whose division is Metal's, either -/// reciprocal is therefore a near-equivalent (`PrecisionNote::DeviceArithmetic`); `RN(1 / y)` is -/// the nearer one, with the 38 lanes its residue. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum Reciprocal { - /// The device's `OpFDiv(1, y)`. On a profile whose float functions and division are - /// Metal's (`FloatFunctions::Metal`) that is Metal's own: its fast reciprocal where Metal - /// compiles the module with fast math, and `RN(1 / y)` where the module turns fast math off. - /// Elsewhere it is within Vulkan's 2.5 ulp: profiles whose `float` fused multiply-add is not - /// `OpFmaKHR`. - Device, - /// `RN(1 / y)`, the device's estimate refined by `OpFmaKHR` (`rounded_reciprocal_bits`): - /// the other profiles, whose `float` fused multiply-add is `OpFmaKHR` ([`fma::float_route`]). - Rounded, - /// Native device maths (`FloatFunctions::Native`): Metal's fast division is the device's - /// `OpFDiv(x, y)` itself, and its reciprocal the device's `OpFDiv(1, y)`, within Vulkan's - /// 2.5 ulp (`PrecisionNote::NativeDivision`). - Native, -} - -impl Reciprocal { - /// The reciprocal on profile `p`. The typed fact decides it, never the driver: where the - /// profile's float functions are Metal's, the device's `OpFDiv(1, y)` is Metal's own - /// reciprocal or `RN(1 / y)` by the module's math mode, so nothing nearer exists. Otherwise it - /// is the reciprocal beside the profile's `float` fused multiply-add. - pub fn on(p: &DeviceProfile) -> Reciprocal { - match p.fields().float_functions { - FloatFunctions::Metal => Reciprocal::Device, - FloatFunctions::Device => Reciprocal::of(fma::float_route(p)), - FloatFunctions::Native => Reciprocal::Native, - } - } - - /// The reciprocal beside a `float` fused multiply-add by `route`, on a profile whose float - /// functions are the device's. - pub fn of(route: Route) -> Reciprocal { - match route { - Route::Khr => Reciprocal::Rounded, - Route::Wide | Route::Soft | Route::F16 | Route::F16Khr | Route::Native => { - Reciprocal::Device - } - } - } - - /// An upper estimate of the SPIR-V words the reciprocal adds to the device's division on - /// form `f`: the high range's test and moves, `-y`, four fused multiply-adds, the all-ones - /// significand's test and ulp, and their constants. - pub fn words(self, f: Form) -> u32 { - match self { - Reciprocal::Device | Reciprocal::Native => 0, - Reciprocal::Rounded => 128 + 8 * u32::from(f.lanes), - } - } -} - -/// `RN(1 / y)` of `float` lanes `y` (form `f`), as their bits, from `r`, an estimate within 2.5 -/// ulp of it: two Newton steps `r += r · (1 - y · r)`, each by `OpFmaKHR`, give `RN(1 / y)` -/// except at an all-ones significand, where they give the even neighbor below and one ulp up is -/// `RN(1 / y)` (every significand, every estimate within 2.5 ulp: -/// `markstein_reciprocal_is_correctly_rounded`). `one` is `1.0`, `ny` is `-y`, and `yb` holds -/// `y`'s bits. Scaling `y` by a power of two scales every step exactly while `1 / y` and the -/// estimate are normal numbers, so the result is exact for every such `y`. -pub(super) fn rounded_reciprocal_bits( - fb: &mut FunctionBuilder<'_>, - f: Form, - one: Value, - ny: Value, - yb: Value, - mut r: Value, -) -> BResult { - let u = u32_form(f); - let ut = ty(fb, u)?; - for _ in 0..2 { - let t = fb.fma(ny, r, one)?; - r = fb.fma(t, r, r)?; - } - let mant_mask = splat(fb, u, 0x7F_FFFF)?; - let mant = fb.binary(BinOp::BitwiseAnd, yb, mant_mask)?; - let ones = fb.binary(BinOp::IEqual, mant, mant_mask)?; - let (k0, k1) = (splat(fb, u, 0)?, splat(fb, u, 1)?); - let bump = fb.select(ones, k1, k0)?; - let rb = fb.convert(ConvOp::Bitcast, r, ut)?; - fb.binary(BinOp::BitwiseOr, rb, bump) -} - -/// `OpFDiv`: within 2.5 ulp for a divisor in `[2^-126, 2^126]` (the Vulkan precision table). -fn device_division(fb: &mut FunctionBuilder<'_>, x: Value, y: Value) -> BResult { - fb.binary(BinOp::FDiv, x, y) -} - -fn f32_form(lanes: u8) -> Form { - Form { - held: Held::Float(FloatFmt::F32), - lanes, - } -} - -/// Markstein's correctly rounded quotient of `float` lanes `x` and `y` (form `f`) by -/// `OpFmaKHR`, on every lane: the significands moved to `[1, 2)`, inside the sequence's range -/// (`[2^-31, 2^33)`), divided from `rough`'s estimate of `1 / yn`, which must be within 2.5 ulp -/// of it, and the quotient's exponent moved by the operands' difference ([`assemble`], which also -/// answers zeros, infinities, and NaNs). The significands' quotient is in `(1/2, 2)`, so its -/// rounding is the exact quotient's 24-bit rounding with an unbounded exponent, which decides -/// Metal's flush and overflow. -fn fused( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - y: Value, - rough: Rough<'_>, -) -> BResult { - let u = u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let k = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v); - let bin = |fb: &mut FunctionBuilder<'_>, op: BinOp, a: Value, b: Value| fb.binary(op, a, b); - let p = Parts::of(fb, f, x, y)?; - - // The significands as floats in [1, 2). - let one_bits = k(fb, 0x3F80_0000)?; - let xn = bin(fb, BinOp::BitwiseOr, p.mx, one_bits)?; - let xn = fb.convert(ConvOp::Bitcast, xn, ft)?; - let ynb = bin(fb, BinOp::BitwiseOr, p.my, one_bits)?; - let yn = fb.convert(ConvOp::Bitcast, ynb, ft)?; - - // RN(1 / yn): two fused Newton steps from the estimate, then the all-ones significand's ulp. - let one = fsplat(fb, f, 1.0)?; - let ny = fb.unary(UnOp::FNegate, yn)?; - let r = rough(fb, one, yn)?; - let rb = rounded_reciprocal_bits(fb, f, one, ny, ynb, r)?; - let r = fb.convert(ConvOp::Bitcast, rb, ft)?; - - // q = RN(xn · r), then two fused steps; the second is Markstein's. - let minus_zero = fsplat(fb, f, -0.0)?; - let mut q = fb.fma(xn, r, minus_zero)?; - for _ in 0..2 { - let e = fb.fma(ny, q, xn)?; - q = fb.fma(e, r, q)?; - } - - // The quotient's biased exponent ex - ey + eq, and its significand field. - let qb = fb.convert(ConvOp::Bitcast, q, ut)?; - let (k23, exp_mask, mant_mask) = (k(fb, 23)?, k(fb, 0xFF)?, k(fb, 0x7F_FFFF)?); - let eq = bin(fb, BinOp::ShiftRightLogical, qb, k23)?; - let eq = bin(fb, BinOp::BitwiseAnd, eq, exp_mask)?; - let e = bin(fb, BinOp::IAdd, p.ex, eq)?; - let e = bin(fb, BinOp::ISub, e, p.ey)?; - let mant = bin(fb, BinOp::BitwiseAnd, qb, mant_mask)?; - assemble(fb, f, &p, e, mant) -} - -/// The `float` quotient of `half` lanes `x` and `y` held in `float` (form `f`) by `OpFmaKHR`, -/// whose rounding to `half` is Metal's `half` quotient ([`Path::Halves`]): `q = x · r` from -/// `rough`'s estimate `r` of `1 / y`, within 2.5 ulp of it, and one fused step -/// `q + r · (x - y · q)`, on every lane whose operands are both finite and nonzero. With `ε` and -/// `δ` the estimate's and the product's relative errors (`|ε| <= 2.5 · 2^-23`, `|δ| <= 2^-24`), -/// `q` is within `|x / y| · 3 · 2^-23` of `x / y`; the fused residual `x - y · q` is rounded -/// once at most (by `η`, `|η| <= 2^-24`), so the step's exact sum is within that times -/// `|ε + η + εη|`, below `2^-18` ulp, and its one rounding gives the quotient within -/// `1/2 + 2^-18` ulp, and exactly where the quotient is a `float`. Zeros, infinities, and NaNs, -/// which a `half` operand reaches only as itself (no `half` value is an `f32` denormal), are -/// answered as `fused` answers them: a NaN for a NaN operand, `0 / 0`, or `∞ / ∞`; the infinity -/// of the quotient's sign for an infinite dividend or a zero divisor; else its zero. -fn halves( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - y: Value, - rough: Rough<'_>, -) -> BResult { - let u = u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let k = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v); - let bin = |fb: &mut FunctionBuilder<'_>, op: BinOp, a: Value, b: Value| fb.binary(op, a, b); - - // q = x · r, then one fused step q + r · (x - y · q). - let one = fsplat(fb, f, 1.0)?; - let r = rough(fb, one, y)?; - let q = bin(fb, BinOp::FMul, x, r)?; - let ny = fb.unary(UnOp::FNegate, y)?; - let e = fb.fma(ny, q, x)?; - let q = fb.fma(e, r, q)?; - let qb = fb.convert(ConvOp::Bitcast, q, ut)?; - - // A lane is regular where both magnitudes are in [1, 0x7F7FFFFF]: finite and nonzero. - let xb = fb.convert(ConvOp::Bitcast, x, ut)?; - let yb = fb.convert(ConvOp::Bitcast, y, ut)?; - let (magnitude, sign_bit) = (k(fb, 0x7FFF_FFFF)?, k(fb, 0x8000_0000)?); - let ax = bin(fb, BinOp::BitwiseAnd, xb, magnitude)?; - let ay = bin(fb, BinOp::BitwiseAnd, yb, magnitude)?; - let xy = bin(fb, BinOp::BitwiseXor, xb, yb)?; - let sign = bin(fb, BinOp::BitwiseAnd, xy, sign_bit)?; - let (k0, k1, largest) = (k(fb, 0)?, k(fb, 1)?, k(fb, 0x7F7F_FFFF)?); - let xm = bin(fb, BinOp::ISub, ax, k1)?; - let ym = bin(fb, BinOp::ISub, ay, k1)?; - let xr = bin(fb, BinOp::ULessThan, xm, largest)?; - let yr = bin(fb, BinOp::ULessThan, ym, largest)?; - let regular = bin(fb, BinOp::LogicalAnd, xr, yr)?; - - // Elsewhere one operand is a zero, an infinity, or a NaN: equal magnitudes there are two - // zeros, two infinities, or NaNs. - let inf_bits = k(fb, 0x7F80_0000)?; - let xnan = bin(fb, BinOp::UGreaterThan, ax, inf_bits)?; - let ynan = bin(fb, BinOp::UGreaterThan, ay, inf_bits)?; - let same = bin(fb, BinOp::IEqual, ax, ay)?; - let nan = bin(fb, BinOp::LogicalOr, xnan, ynan)?; - let nan = bin(fb, BinOp::LogicalOr, nan, same)?; - let xi = bin(fb, BinOp::IEqual, ax, inf_bits)?; - let yz = bin(fb, BinOp::IEqual, ay, k0)?; - let to_inf = bin(fb, BinOp::LogicalOr, xi, yz)?; - let inf = bin(fb, BinOp::BitwiseOr, sign, inf_bits)?; - let special = fb.select(to_inf, inf, sign)?; - let qnan = k(fb, 0x7FC0_0000)?; - let special = fb.select(nan, qnan, special)?; - let res = fb.select(regular, qb, special)?; - fb.convert(ConvOp::Bitcast, res, ft) -} - -/// The fields of two `float` operands both paths read: their bits, the quotient's sign bit, the -/// biased exponent fields, and the significand fields. -struct Parts { - xb: Value, - yb: Value, - sign: Value, - ex: Value, - ey: Value, - mx: Value, - my: Value, -} - -impl Parts { - fn of(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, y: Value) -> BResult { - let u = u32_form(f); - let ut = ty(fb, u)?; - let (sign_bit, exp_mask, mant_mask, k23) = ( - splat(fb, u, 0x8000_0000)?, - splat(fb, u, 0xFF)?, - splat(fb, u, 0x7F_FFFF)?, - splat(fb, u, 23)?, - ); - let xb = fb.convert(ConvOp::Bitcast, x, ut)?; - let yb = fb.convert(ConvOp::Bitcast, y, ut)?; - let xy = fb.binary(BinOp::BitwiseXor, xb, yb)?; - let sign = fb.binary(BinOp::BitwiseAnd, xy, sign_bit)?; - let ex = fb.binary(BinOp::ShiftRightLogical, xb, k23)?; - let ex = fb.binary(BinOp::BitwiseAnd, ex, exp_mask)?; - let ey = fb.binary(BinOp::ShiftRightLogical, yb, k23)?; - let ey = fb.binary(BinOp::BitwiseAnd, ey, exp_mask)?; - let mx = fb.binary(BinOp::BitwiseAnd, xb, mant_mask)?; - let my = fb.binary(BinOp::BitwiseAnd, yb, mant_mask)?; - Ok(Parts { - xb, - yb, - sign, - ex, - ey, - mx, - my, - }) - } -} - -/// The quotient of the operands `p` whose 24-bit rounding has the biased exponent `e` (a signed -/// integer, unbounded) and the significand field `mant`: the infinity of its sign from 255 up, -/// the zero of its sign from 0 down (below the smallest normal once rounded to 24 bits, -/// c10cba13), and zeros (an `f32` denormal is one), infinities, and NaNs as Metal answers them. -fn assemble( - fb: &mut FunctionBuilder<'_>, - f: Form, - p: &Parts, - e: Value, - mant: Value, -) -> BResult { - let u = u32_form(f); - let ft = ty(fb, f)?; - let k = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v); - let bin = |fb: &mut FunctionBuilder<'_>, op: BinOp, a: Value, b: Value| fb.binary(op, a, b); - let (k0, k23) = (k(fb, 0)?, k(fb, 23)?); - let field = bin(fb, BinOp::ShiftLeftLogical, e, k23)?; - let normal = bin(fb, BinOp::BitwiseOr, p.sign, field)?; - let normal = bin(fb, BinOp::BitwiseOr, normal, mant)?; - let inf_bits = k(fb, 0x7F80_0000)?; - let inf = bin(fb, BinOp::BitwiseOr, p.sign, inf_bits)?; - let k255 = k(fb, 255)?; - let over = bin(fb, BinOp::SGreaterThanEqual, e, k255)?; - let under = bin(fb, BinOp::SLessThanEqual, e, k0)?; - let res = fb.select(over, inf, normal)?; - let res = fb.select(under, p.sign, res)?; - - // Zeros (an f32 denormal is one), infinities, and NaNs, as Metal answers them. - let magnitude = k(fb, 0x7FFF_FFFF)?; - let ax = bin(fb, BinOp::BitwiseAnd, p.xb, magnitude)?; - let ay = bin(fb, BinOp::BitwiseAnd, p.yb, magnitude)?; - let xz = bin(fb, BinOp::IEqual, p.ex, k0)?; - let yz = bin(fb, BinOp::IEqual, p.ey, k0)?; - let xi = bin(fb, BinOp::IEqual, ax, inf_bits)?; - let yi = bin(fb, BinOp::IEqual, ay, inf_bits)?; - let xnan = bin(fb, BinOp::UGreaterThan, ax, inf_bits)?; - let ynan = bin(fb, BinOp::UGreaterThan, ay, inf_bits)?; - let zz = bin(fb, BinOp::LogicalAnd, xz, yz)?; - let ii = bin(fb, BinOp::LogicalAnd, xi, yi)?; - let nan = bin(fb, BinOp::LogicalOr, xnan, ynan)?; - let nan = bin(fb, BinOp::LogicalOr, nan, zz)?; - let nan = bin(fb, BinOp::LogicalOr, nan, ii)?; - let to_inf = bin(fb, BinOp::LogicalOr, xi, yz)?; - let to_zero = bin(fb, BinOp::LogicalOr, xz, yi)?; - let res = fb.select(to_zero, p.sign, res)?; - let res = fb.select(to_inf, inf, res)?; - let qnan = k(fb, 0x7FC0_0000)?; - let res = fb.select(nan, qnan, res)?; - fb.convert(ConvOp::Bitcast, res, ft) -} - -/// Metal's precise quotient of `float` lanes `x` and `y` (form `f`), from `rough`'s estimate of -/// the quotient of their significands, which must be within 2.5 ulp of it. -fn quotient( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - y: Value, - rough: Rough<'_>, -) -> BResult { - let u = u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let k = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v); - let bin = |fb: &mut FunctionBuilder<'_>, op: BinOp, a: Value, b: Value| fb.binary(op, a, b); - let p = Parts::of(fb, f, x, y)?; - let (mx, my) = (p.mx, p.my); - let (mant_mask, hidden) = (k(fb, 0x7F_FFFF)?, k(fb, 0x80_0000)?); - let (k0, k1, k23) = (k(fb, 0)?, k(fb, 1)?, k(fb, 23)?); - - // The significands, as integers in [2^23, 2^24) and as floats in [1, 2). - let big_x = bin(fb, BinOp::BitwiseOr, mx, hidden)?; - let big_y = bin(fb, BinOp::BitwiseOr, my, hidden)?; - let one = k(fb, 0x3F80_0000)?; - let xn = bin(fb, BinOp::BitwiseOr, mx, one)?; - let xn = fb.convert(ConvOp::Bitcast, xn, ft)?; - let yn = bin(fb, BinOp::BitwiseOr, my, one)?; - let yn = fb.convert(ConvOp::Bitcast, yn, ft)?; - - // F = floor(X · 2^s / Y) has 24 bits: s = 23 where X >= Y, else 24. - let ge = bin(fb, BinOp::UGreaterThanEqual, big_x, big_y)?; - let s = { - let k24 = k(fb, 24)?; - fb.select(ge, k23, k24)? - }; - let q0 = rough(fb, xn, yn)?; - let scale = { - let (a, b) = (fsplat(fb, f, 8_388_608.0)?, fsplat(fb, f, 16_777_216.0)?); - fb.select(ge, a, b)? - }; - // `q0 · 2^s` is exact; truncation adds less than one to the estimate's 2.5. - let q0s = bin(fb, BinOp::FMul, q0, scale)?; - let mut q = fb.convert(ConvOp::ConvertFToU, q0s, ut)?; - // The remainder, below 2^31 in magnitude, exactly in the low 32 bits. - let xs = bin(fb, BinOp::ShiftLeftLogical, big_x, s)?; - let qy = bin(fb, BinOp::IMul, q, big_y)?; - let mut r = bin(fb, BinOp::ISub, xs, qy)?; - for _ in 0..3 { - let neg = bin(fb, BinOp::SLessThan, r, k0)?; - let r_up = bin(fb, BinOp::IAdd, r, big_y)?; - let q_down = bin(fb, BinOp::ISub, q, k1)?; - r = fb.select(neg, r_up, r)?; - q = fb.select(neg, q_down, q)?; - } - for _ in 0..3 { - let over = bin(fb, BinOp::SGreaterThanEqual, r, big_y)?; - let r_down = bin(fb, BinOp::ISub, r, big_y)?; - let q_up = bin(fb, BinOp::IAdd, q, k1)?; - r = fb.select(over, r_down, r)?; - q = fb.select(over, q_up, q)?; - } - - // Round to nearest even: up past the midpoint, and at it when F is odd. - let twice = bin(fb, BinOp::ShiftLeftLogical, r, k1)?; - let past = bin(fb, BinOp::UGreaterThan, twice, big_y)?; - let at = bin(fb, BinOp::IEqual, twice, big_y)?; - let low = bin(fb, BinOp::BitwiseAnd, q, k1)?; - let odd = bin(fb, BinOp::IEqual, low, k1)?; - let tie_up = bin(fb, BinOp::LogicalAnd, at, odd)?; - let up = bin(fb, BinOp::LogicalOr, past, tie_up)?; - let inc = fb.select(up, k1, k0)?; - let sig = bin(fb, BinOp::IAdd, q, inc)?; - let carry = { - let k24 = k(fb, 24)?; - bin(fb, BinOp::ShiftRightLogical, sig, k24)? - }; - let mant = bin(fb, BinOp::BitwiseAnd, sig, mant_mask)?; - - // The biased exponent ex - ey + 126 + [X >= Y] + carry, signed. - let k126 = k(fb, 126)?; - let e = bin(fb, BinOp::IAdd, p.ex, k126)?; - let e = bin(fb, BinOp::ISub, e, p.ey)?; - let gei = fb.select(ge, k1, k0)?; - let e = bin(fb, BinOp::IAdd, e, gei)?; - let e = bin(fb, BinOp::IAdd, e, carry)?; - assemble(fb, f, &p, e, mant) -} diff --git a/crates/metal2vulkan/src/lower/arith/fma.rs b/crates/metal2vulkan/src/lower/arith/fma.rs index ff7b68a27..601fa8936 100644 --- a/crates/metal2vulkan/src/lower/arith/fma.rs +++ b/crates/metal2vulkan/src/lower/arith/fma.rs @@ -1,62 +1,21 @@ -//! Correctly rounded fused multiply-add on `float` and `half`. +//! Fused multiply-add on `float` and `half`. //! //! Metal's `fma` (`air.fma`, `llvm.fma`) rounds the exact `a * b + c` once. Vulkan's //! `GLSL.std.450 Fma` does not promise that (its precision is inherited from an `OpFMul` -//! followed by an `OpFAdd`), so a `float` fused multiply-add takes one of three routes, by -//! what the profile offers ([`float_route`]): +//! followed by an `OpFAdd`), so a `float` fused multiply-add takes one of two routes, by what +//! the profile offers ([`float_route`]): //! //! - [`Route::Khr`]: `OpFmaKHR` (`SPV_KHR_fma`, `shaderFmaFloat32` of `VK_KHR_shader_fma`), -//! which the Vulkan precision table lists as correctly rounded; -//! - [`Route::Wide`]: in `double` (`shaderFloat64` and `shaderInt64`): the product of two -//! `float`s is exact in `double`, the sum rounds once, and its rounding error is exact -//! (FastTwoSum), so the sum is moved to the `double` neighbour of odd significand when it was -//! inexact (round to odd). One conversion to `float` then rounds the exact sum correctly, -//! because `double` keeps more than `24 + 2` significand bits (Boldo and Melquiond); -//! - [`Route::Soft`]: in 32-bit integers on every other profile: the 48-bit product of the -//! significands, the addend aligned to it with a sticky bit, one 64-bit sum or difference, and -//! one rounding to nearest even, with overflow to infinity. -//! -//! The two routes the translation computes itself answer as Metal's `fma` does (a probe cases -//! e98b103f and f7850ba7, every lane): an `f32` denormal operand is read as a zero of its sign, a -//! result whose exact value is below `2^-126` in magnitude is a zero of its sign, flushed before -//! it is rounded (Metal's `fma(-2^-126, 2^-126, 2^-126)` is `+0`, where the -//! correctly rounded sum is `2^-126`), and a NaN result is `0x7FC00000` (as Metal's functions read -//! their operands). `OpFmaKHR` keeps the device's denormal mode and NaN encoding, as the device's -//! other `float` arithmetic does; on MoltenVK it is Metal's own `fma`. Elsewhere it rounds before -//! it flushes, if it flushes: an exact value just below `2^-126` answers `2^-126`. Where the -//! profile asks Metal's answers (`FloatMathsPolicy::Exact`), a result of `OpFmaKHR` at most -//! `2^-126` in magnitude is answered by a routine ([`tiny_route`], [`checked`]); every larger one -//! is Metal's already. Where the profile has `double`, that routine decides only what such a -//! result needs, the exact sum's sign and whether it lies below `2^-126` ([`small`]), about 40 -//! instructions where the whole `double` route is about 90: the device's compiler inlines a call, -//! so each checked use compiles its copy. -//! -//! The wide and integer routes are one module-scope function per lane count ([`Routine`]), -//! which every use calls, so a module holds each once (as the wide divisions are). A module that -//! calls a route on one lane and on more holds the route's sequence once, on one lane: its routines -//! on more lanes call that one on each lane ([`complete`], [`define_per_lane`]), and so does one -//! that calls a route only on two or more vector lane counts where the sequences that saves -//! outweigh the per-lane routines. The sequence is lane-wise, so each lane's answer is the same -//! either way; only the module's size changes (the integer route's sequence is about 1,200 to 1,800 -//! words, a per-lane routine about 90 to 140). Both answer an infinite or NaN operand without their -//! core: the addend where the factors are finite (a finite product plus an infinity or NaN is -//! that), else the unfused `a * b + c` (an infinite or NaN product, and the sum IEEE's fused result -//! shares with it); and an exact zero sum or a zero factor with the unfused result, which rounds -//! nothing there. -//! -//! A `half` fused multiply-add takes the device's `float` `Fma` on its operands held in `float`, -//! its result rounded to `half` ([`Route::Native`], noted `NativeFma`), where the profile offers no -//! 16-bit route below: its product is exact in `float`, so only the sum's rounding and the rounding -//! to `half` differ from Metal's one rounding. A `bfloat` one keeps its own sequence -//! (`narrow::bf16_fma`): its product is exact in `float`, so the device's `Fma`, fused or not, -//! rounds the exact sum once, and its tie is corrected. +//! which the Vulkan precision table lists as correctly rounded, at the device's denormals and +//! NaN encoding (on MoltenVK Metal's own `fma`); +//! - [`Route::Native`]: the device's `GLSL.std.450 Fma`, within Vulkan's precision rather than +//! rounded once (`PrecisionNote::NativeFma`). //! //! Where the driver is measured to compute `GLSL.std.450 Fma` on 16-bit floats as Metal's own -//! `half` `fma` (`DriverDeviation::MetalHalfFma`: MoltenVK 1.4.1 on Apple's GPUs) and the profile -//! has `shaderFloat16`, a `half` one takes [`Route::F16`] instead: its operands, each a `half` held -//! in a `float`, convert to 16 bits exactly, the device's `Fma` rounds the exact sum once as Metal -//! does, and its result widens exactly; the module then requires `VkProperty::MetalHalfFma`. It is -//! a few instructions per use and no routine. +//! `half` `fma` (`DriverDeviation::MetalHalfFma`: MoltenVK on Apple's GPUs) and the profile has +//! `shaderFloat16`, a `half` one takes [`Route::F16`]: its operands, each a `half` held in a +//! `float`, convert to 16 bits exactly, the device's `Fma` rounds the exact sum once as Metal +//! does, and its result widens exactly; the module then requires `VkProperty::MetalHalfFma`. //! //! Where the profile has `shaderFmaFloat16` and rounds to `half` under the 16-bit float controls //! ([`QuantizeForm::Controlled`], [`narrow::controlled_modes`]), a `half` one takes @@ -66,49 +25,42 @@ //! under `DenormPreserve` and zero signs under `SignedZeroInfNanPreserve`, which the entry then //! declares (`narrow::computes_in_16_bits`): Metal's `half` `fma`, with no fact. A NaN's bits are //! the device's, as the controlled rounding's are; a fused pair's NaN is selected as on every route -//! (`super::contract`). It replaces the device's `float` `Fma` and its rounding to `half` -//! ([`Route::Native`], noted `NativeFma`) with one instruction whose conversions the device folds -//! into its neighbours'. +//! (`super::contract`). Every other `half` one takes [`Route::Native`]: the device's `float` `Fma` +//! of the operands held in `float`, whose product is exact there, rounded to `half`. +//! +//! An extended-range blend computes its own correctly rounded multiply-adds ([`half_sum`], +//! [`float_fma_exact`]): the blend the device cannot do, in plain arithmetic. -use crate::device::profile::FloatFunctions; use crate::device::DeviceProfile; use crate::error::DriverDeviation; use crate::lower::arith::legal::{FloatFmt, Form, Held}; use crate::lower::arith::narrow::{self, u32_form}; use crate::lower::arith::ops::{fsplat, splat, ty}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder, QuantizeForm}; +use crate::spirv::builder::{FunctionBuilder, QuantizeForm}; use crate::spirv::error::{BResult, BuildError, TypeRule}; -use crate::spirv::ids::{FuncId, Value}; -use crate::spirv::ir::{BinOp, Contraction, ConvOp, GlslOp, Type, UnOp}; -use std::collections::{BTreeMap, BTreeSet}; +use crate::spirv::ids::Value; +use crate::spirv::ir::{BinOp, Contraction, ConvOp, GlslOp, Type}; -/// How a fused multiply-add computes its exact result. +/// How a fused multiply-add computes its result. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Route { /// `OpFmaKHR` on `float`. Khr, - /// The `double` round-to-odd routine ([`Routine`]). - Wide, - /// The 32-bit integer routine ([`Routine`]). - Soft, /// A `half` fused multiply-add by the device's `Fma` on 16-bit floats, Metal's own /// ([`half_route`]). F16, /// A `half` fused multiply-add by `OpFmaKHR` on 16-bit floats under the 16-bit float /// controls, correctly rounded by the Vulkan spec ([`half_route`]). F16Khr, - /// The device's `GLSL.std.450 Fma` on the `float` lanes, within Vulkan's precision rather than - /// rounded once (`PrecisionNote::NativeFma`): a `float` one's under native device maths - /// (`FloatFunctions::Native`), a `half` one's wherever no 16-bit route is offered - /// ([`half_route`]: its operands held in `float`, its result rounded to `half`). + /// The device's `GLSL.std.450 Fma` on the `float` lanes (a `half`'s held in `float`, its + /// result rounded to `half`), within Vulkan's precision rather than rounded once + /// (`PrecisionNote::NativeFma`). Native, } impl Route { /// Whether the route is the device's own `float` instruction, at the device's denormals and - /// NaN encoding (`OpFmaKHR`, or native device maths' `Fma`), where the routines answer as - /// Metal does. + /// NaN encoding (`OpFmaKHR`, or the device's `Fma`). pub fn device_float(self) -> bool { matches!(self, Route::Khr | Route::Native) } @@ -116,12 +68,6 @@ impl Route { /// The census names of the fused multiply-add strategies (one per [`Route`]). pub const KHR: &str = "arith.fma.khr"; -/// See [`KHR`]: `OpFmaKHR` with the routine of its results at most `2^-126` ([`tiny_route`]). -pub const KHR_CHECKED: &str = "arith.fma.khr.checked"; -/// See [`KHR`]. -pub const WIDE: &str = "arith.fma.double"; -/// See [`KHR`]. -pub const SOFT: &str = "arith.fma.integer"; /// See [`KHR`]. pub const F16: &str = "arith.fma.f16"; /// See [`KHR`]. @@ -129,52 +75,21 @@ pub const F16_KHR: &str = "arith.fma.f16.khr"; /// See [`KHR`]. pub const NATIVE: &str = "arith.fma.native"; -/// Every route [`float_route`] answers, which the tests run each of. -#[cfg(test)] -pub const FLOAT_ROUTES: [Route; 3] = [Route::Khr, Route::Wide, Route::Soft]; - /// The `float` route profile `p` offers: `OpFmaKHR` where `shaderFmaFloat32` is enabled, else the -/// device's `Fma` under native device maths, else `double` where `shaderFloat64` and `shaderInt64` -/// are, else the integer routine. +/// device's `Fma`. pub fn float_route(p: &DeviceProfile) -> Route { - let leaf = &p.fields().leaf; - if leaf.fma32 { + if p.fields().leaf.fma32 { Route::Khr - } else if p.fields().float_functions == FloatFunctions::Native { + } else { Route::Native - } else if leaf.float64 && leaf.int64 { - Route::Wide - } else { - Route::Soft } } -/// The route of the routine that answers a `float` fused multiply-add by `OpFmaKHR` whose result -/// is at most `2^-126` in magnitude ([`checked`]), on profile `p`: where its `float` route is -/// [`Route::Khr`] and its functions are to answer as Metal's (`FloatFunctions::Device`, the -/// policy's `FloatMathsPolicy::Exact`), [`Route::Wide`] where `shaderFloat64` and `shaderInt64` are -/// enabled (the routine of those results alone, [`small`]), else [`Route::Soft`]. A device that reads `f32` denormals as Metal does -/// (`denormal::device_flushes`) is checked too: it rounds before it flushes, as every device off -/// MoltenVK does (`denormal::checks_tiny_products`). `None` elsewhere: `OpFmaKHR` is then Metal's -/// `fma` (MoltenVK), or the device's rounding before its flush is left to it (native device maths, -/// `docs/FAST-PATHS.md`). -pub fn tiny_route(p: &DeviceProfile) -> Option { - let fields = p.fields(); - if float_route(p) != Route::Khr || fields.float_functions != FloatFunctions::Device { - return None; - } - Some(if fields.leaf.float64 && fields.leaf.int64 { - Route::Wide - } else { - Route::Soft - }) -} - /// The `half` route profile `p` offers: [`Route::F16`] where the driver is measured to compute a /// 16-bit `Fma` as Metal's own `half` `fma` (`DriverDeviation::MetalHalfFma`) and `shaderFloat16` /// is enabled, else [`Route::F16Khr`] where `shaderFmaFloat16` is and the profile rounds to `half` /// under the 16-bit float controls (which need `shaderFloat16`), else the device's `float` `Fma` -/// rounded to `half` ([`Route::Native`]), under every policy. +/// rounded to `half` ([`Route::Native`]). pub fn half_route(p: &DeviceProfile) -> Route { if p.takes_driver_deviation(DriverDeviation::MetalHalfFma) && p.fields().leaf.float16 { Route::F16 @@ -192,9 +107,6 @@ pub struct Routes { pub float: Route, /// A `half` one's: [`half_route`]. pub half: Route, - /// The routine route a `float` one by [`Route::Khr`] recomputes its results at most `2^-126` - /// in magnitude by: [`tiny_route`]. - pub tiny: Option, } /// The routes profile `p` offers ([`float_route`], [`half_route`]). @@ -202,7 +114,6 @@ pub fn routes(p: &DeviceProfile) -> Routes { Routes { float: float_route(p), half: half_route(p), - tiny: tiny_route(p), } } @@ -211,9 +122,6 @@ pub fn routes(p: &DeviceProfile) -> Routes { pub struct Fma { pub form: Form, pub route: Route, - /// On [`Route::Khr`], the route of the routine that recomputes a result at most `2^-126` in - /// magnitude ([`tiny_route`], [`checked`]); `None` on every other route. - pub tiny: Option, } impl Fma { @@ -226,70 +134,29 @@ impl Fma { /// The fused multiply-add on `form` by `routes` (a profile's [`routes`]): `half` by its /// `half` route, `float` by its `float` route. `None` for any other form. pub fn by(routes: Routes, form: Form) -> Option { - let (route, tiny) = match form.float_fmt()? { - FloatFmt::Half => (routes.half, None), - FloatFmt::F32 => ( - routes.float, - routes.tiny.filter(|_| routes.float == Route::Khr), - ), + let route = match form.float_fmt()? { + FloatFmt::Half => routes.half, + FloatFmt::F32 => routes.float, FloatFmt::BFloat | FloatFmt::F64 => return None, }; - Some(Fma { form, route, tiny }) - } - - /// Whether it is `OpFmaKHR` whose results at most `2^-126` in magnitude its routine recomputes - /// ([`checked`]): on operands read as Metal reads them, Metal's `fma` exactly, never a - /// denormal. - pub fn checked(self) -> bool { - self.route == Route::Khr && self.tiny.is_some() - } - - /// This fused multiply-add without the check of its small results ([`checked`]), for a use - /// whose exact result is never below `2^-126` in magnitude but zero, where `OpFmaKHR` is - /// Metal's `fma` already, and which must stay in one block. - pub fn unchecked(self) -> Fma { - Fma { tiny: None, ..self } - } - - /// The shared routine the operation calls, if its route has one: the route's, or on - /// [`Route::Khr`] the routine of its small results ([`Fma::tiny`]): on [`Route::Wide`] the - /// one that decides only those ([`small`]), named by [`Route::Khr`]. - pub fn routine(self) -> Option { - let route = match (self.route, self.tiny) { - (Route::Wide | Route::Soft, _) => self.route, - (Route::Khr, Some(Route::Wide)) => Route::Khr, - (Route::Khr, Some(tiny)) => tiny, - (Route::Khr | Route::F16 | Route::F16Khr | Route::Native, _) => return None, - }; - Some(Routine { - route, - lanes: self.form.lanes, - }) + Some(Fma { form, route }) } /// The census name. pub fn name(self) -> &'static str { match self.route { - Route::Khr if self.checked() => KHR_CHECKED, Route::Khr => KHR, - Route::Wide => WIDE, - Route::Soft => SOFT, Route::F16 => F16, Route::F16Khr => F16_KHR, Route::Native => NATIVE, } } - /// An upper estimate of the SPIR-V words per use: the instruction or the call; on - /// [`Route::F16`] and [`Route::F16Khr`] the three conversions, the instruction and the - /// widening; checked - /// ([`checked`]), the instruction, the test of its magnitude, the selection, the call and the - /// merge. A routine's own words are the module's, charged once ([`Routine::words`]). + /// An upper estimate of the SPIR-V words per use: the instruction; on [`Route::F16`] and + /// [`Route::F16Khr`] the three conversions, the instruction and the widening. pub fn words(self) -> u32 { match self.route { - Route::Khr if self.checked() => 112, Route::Khr => 16, - Route::Wide | Route::Soft => 24, Route::F16 | Route::F16Khr => 32, // The instruction, and a `half` result's rounding. Route::Native => 64, @@ -297,213 +164,17 @@ impl Fma { } } -/// A module-scope fused multiply-add routine on `float` lanes: `route` is [`Route::Wide`] or -/// [`Route::Soft`]; or [`Route::Khr`], the routine of `OpFmaKHR`'s results at most `2^-126` in -/// magnitude through `double` ([`small`]), which takes that result too. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct Routine { - pub route: Route, - pub lanes: u8, -} - -impl Routine { - /// An upper estimate of the routine's SPIR-V words, with its constants and types, defined by - /// [`define`]. - pub fn words(self) -> u32 { - match self.route { - Route::Wide => 640, - // 43 instructions of at most six words, eight constants (a vector's carry their lanes), - // the `double` types, and the function's type, frame and four parameters. - Route::Khr => 340 + 25 * u32::from(self.lanes), - _ => 1800, - } - } - - /// An upper estimate of the routine's SPIR-V words defined per lane ([`define_per_lane`]): - /// its types, frame and three parameters, and per lane three extractions and a call (5 and - /// 7 words), and the result's construction. - pub fn per_lane_words(self) -> u32 { - 48 + 24 * u32::from(self.lanes) - } - - /// An upper estimate of the routine's SPIR-V words among a module's routines `fmas` - /// ([`complete`]): per lane where [`per_lane`] says so, else its sequence's. - pub fn words_among(self, fmas: &BTreeSet) -> u32 { - if per_lane(self, fmas) { - self.per_lane_words() - } else { - self.words() - } - } - - /// The float container widths the routine computes in: 32, and 64 for those in `double` - /// ([`Route::Wide`], and [`Route::Khr`]'s [`small`]). It answers Metal's zero of its sign - /// through float instructions at those widths (an exact zero sum by the device's `Fma` or the - /// unfused `a * b + c`, a `float` result below `2^-126` flushed to the zero of its sign), - /// whose zero signs Vulkan lets a device ignore without `SignedZeroInfNanPreserve`: where the - /// profile's functions answer as Metal's, the module keeps them at each width - /// (`ArithPlan::keep_zero_signs`). - pub fn widths(self) -> &'static [u8] { - match self.route { - Route::Wide | Route::Khr => &[32, 64], - _ => &[32], - } - } - - /// The routine of its route on one lane. - fn one_lane(self) -> Routine { - Routine { - route: self.route, - lanes: 1, - } - } - - /// The census name of the strategies that call it. - pub fn name(self) -> &'static str { - match self.route { - Route::Khr => KHR_CHECKED, - Route::Wide => WIDE, - _ => SOFT, - } - } -} - -/// Complete a module's routines `fmas`, each a route on a lane count its uses call, so that the -/// module holds a route's sequence once where that makes it smaller. A route the module calls on -/// one lane and on more already does: its routines on more lanes call the one-lane routine on each -/// lane ([`per_lane`]), each smaller than a sequence. A route called only on `k` (two or more) -/// vector lane counts holds `k` sequences, or one and `k` per-lane routines with its one-lane -/// routine, which it gets where the `k - 1` sequences that saves are, by their estimate, at least -/// twice the per-lane routines together: the estimates are upper bounds, and in a module a sequence -/// shares its constants and types, so a smaller margin grew modules, and weighing one sequence -/// where `k - 1` go grew those of the `double` route on two, three and four lanes. A route called -/// on one lane count keeps its one routine. -pub fn complete(fmas: &mut BTreeSet) { - let add: Vec = fmas - .iter() - .filter(|r| r.route != Route::Khr) - .map(|r| r.one_lane()) - .filter(|one| !fmas.contains(one)) - .filter(|one| { - let vectors: Vec = fmas - .iter() - .copied() - .filter(|r| r.route == one.route) - .collect(); - let per_lane: u32 = vectors.iter().map(|r| r.per_lane_words()).sum(); - let saved = vectors.len().saturating_sub(1) as u32; - saved > 0 && saved * one.words() >= 2 * per_lane - }) - .collect(); - fmas.extend(add); -} - -/// Whether routine `r`, among a module's routines `fmas` ([`complete`]), is defined per lane -/// ([`define_per_lane`]): it is on two or more lanes, and the module holds its route's routine -/// on one lane. The routine of small results ([`Route::Khr`], [`small`]) never is. -pub fn per_lane(r: Routine, fmas: &BTreeSet) -> bool { - r.lanes > 1 && r.route != Route::Khr && fmas.contains(&r.one_lane()) -} - -/// Define routine `r` among a module's routines `fmas` ([`complete`]), given the functions of -/// those `defined` before it, in `fmas`' order (a route's routine on one lane sorts before its -/// routines on more lanes): per lane where [`per_lane`] says so ([`define_per_lane`]), else its -/// sequence ([`define`]). -pub fn define_among( - mb: &mut ModuleBuilder, - r: Routine, - fmas: &BTreeSet, - defined: &BTreeMap, -) -> BResult { - if !per_lane(r, fmas) { - return define(mb, r); - } - let one_lane = defined - .get(&r.one_lane()) - .copied() - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - define_per_lane(mb, r, one_lane) -} - -/// Define routine `r`: a function of three `float` values of `r.lanes` lanes returning their -/// correctly rounded fused multiply-add; on [`Route::Khr`], of those three and their `OpFmaKHR`, -/// returning Metal's `fma` where that is at most `2^-126` in magnitude ([`small`]). -pub fn define(mb: &mut ModuleBuilder, r: Routine) -> BResult { - let f = f32_form(r.lanes); - let e = mb.ty(Type::Float { width: 32 })?; - let t = if r.lanes == 1 { - e - } else { - mb.ty(Type::Vector { - elem: e, - len: r.lanes, - })? - }; - let mut fb = mb.routine(t)?; - let (a, b, c) = (fb.param(t)?, fb.param(t)?, fb.param(t)?); - let v = match r.route { - Route::Khr => { - let fused = fb.param(t)?; - small(&mut fb, f, [a, b, c], fused)? - } - Route::Wide => wide(&mut fb, f, a, b, c)?, - Route::Soft => soft(&mut fb, f, a, b, c)?, - Route::F16 | Route::F16Khr | Route::Native => { - return Err(BuildError::Type(TypeRule::FunctionSignature)) - } - }; - fb.ret(Some(v))?; - fb.finish() -} - -/// Define routine `r`, on two or more lanes, per lane: a function of three `float` values of -/// `r.lanes` lanes that calls `one_lane`, its route's routine on one lane ([`define`]), on each -/// lane, and returns the lanes' answers. Each lane's answer is `one_lane`'s, which is the lane's -/// answer of [`define`]'s routine on `r.lanes` lanes (its sequence is lane-wise). -pub fn define_per_lane(mb: &mut ModuleBuilder, r: Routine, one_lane: FuncId) -> BResult { - let e = mb.ty(Type::Float { width: 32 })?; - let t = mb.ty(Type::Vector { - elem: e, - len: r.lanes, - })?; - let mut fb = mb.routine(t)?; - let params = [fb.param(t)?, fb.param(t)?, fb.param(t)?]; - let mut lanes = Vec::with_capacity(usize::from(r.lanes)); - for l in 0..u32::from(r.lanes) { - let xs = params - .iter() - .map(|p| fb.composite_extract(*p, &[l])) - .collect::>>()?; - let v = fb - .call(one_lane, &xs)? - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - lanes.push(v); - } - let v = fb.composite_construct(t, &lanes)?; - fb.ret(Some(v))?; - fb.finish() -} - -/// Emit `fma` on `args` (three floats of `fma.form`); `routine` is the declared function of -/// [`Fma::routine`] when it has one. The result is a value of the form's format. -pub fn emit( - fb: &mut FunctionBuilder<'_>, - fma: Fma, - args: &[Value], - routine: Option, -) -> BResult { +/// Emit `fma` on `args` (three floats of `fma.form`). The result is a value of the form's format. +pub fn emit(fb: &mut FunctionBuilder<'_>, fma: Fma, args: &[Value]) -> BResult { let [a, b, c] = *args else { return Err(BuildError::Type(TypeRule::FunctionSignature)); }; match (fma.route, fma.form.float_fmt()) { - (Route::Khr | Route::Wide | Route::Soft, Some(FloatFmt::F32)) => { - float(fb, fma, a, b, c, routine) - } + (Route::Khr, Some(FloatFmt::F32)) => fb.fma(a, b, c), (Route::F16, Some(FloatFmt::Half)) => f16(fb, fma.form.lanes, [a, b, c], false), (Route::F16Khr, Some(FloatFmt::Half)) => f16(fb, fma.form.lanes, [a, b, c], true), - // Native device maths: the device's `Fma`; on `half` operands held in `float` the product - // is exact, so only the sum's rounding and the rounding to `half` differ from Metal's one - // rounding. + // The device's `Fma`; on `half` operands held in `float` the product is exact, so only + // the sum's rounding and the rounding to `half` differ from Metal's one rounding. (Route::Native, Some(FloatFmt::F32)) => fb.glsl(GlslOp::Fma, &[a, b, c]), (Route::Native, Some(FloatFmt::Half)) => { let r = fb.glsl(GlslOp::Fma, &[a, b, c])?; @@ -543,93 +214,6 @@ fn f16( fb.convert(ConvOp::FConvert, r, w) } -/// The `float` lanes of `lanes` lanes. -fn f32_form(lanes: u8) -> Form { - Form { - held: Held::Float(FloatFmt::F32), - lanes, - } -} - -/// The correctly rounded fused multiply-add of `a`, `b`, `c` by `fma`'s route: `OpFmaKHR` -/// ([`checked`] where [`Fma::checked`]), or a call of the route's routine. -fn float( - fb: &mut FunctionBuilder<'_>, - fma: Fma, - a: Value, - b: Value, - c: Value, - routine: Option, -) -> BResult { - match (fma.route, fma.tiny, routine) { - (Route::Khr, None, _) => fb.fma(a, b, c), - (Route::Khr, Some(tiny), Some(r)) => { - checked(fb, fma.form, [a, b, c], (r, tiny == Route::Wide)) - } - (Route::Wide | Route::Soft, _, Some(r)) => fb - .call(r, &[a, b, c])? - .ok_or(BuildError::Type(TypeRule::FunctionSignature)), - _ => Err(BuildError::Type(TypeRule::FunctionSignature)), - } -} - -/// Metal's `fma` of `a`, `b` and `c` (`float` lanes of form `f`, each read as Metal reads it: no -/// denormal) by `OpFmaKHR`, its result `r` answered by `routine` ([`tiny_route`]) where any lane's -/// is at most `2^-126` in magnitude, zero included: where `small`, the routine of those results -/// ([`small`]), given `r`, on every lane; else Metal's `fma`, taken on those lanes. -/// -/// Every other lane's `r` is Metal's answer. `OpFmaKHR` is correctly rounded (Vulkan's precision -/// table), and the device may only replace a denormal it reads or answers by a zero (Vulkan's -/// float controls without `DenormPreserve`). Its operands are no denormal, so with `v` the exact -/// `a * b + c`, `r` is the correctly rounded `v`, or a zero. A finite `r` above `2^-126` in -/// magnitude is no flushed zero, so it is the correctly rounded `v` and at least the float after -/// `2^-126`, `2^-126 + 2^-149`. Rounding to nearest gives that only for `|v|` above the midpoint, -/// `2^-126 + 2^-150`, which is above `2^-126`. Metal flushes only an exact value below `2^-126`, -/// so it rounds `v` too and answers `r`. An infinite or NaN `r` is likewise kept: Metal's -/// infinity, and a NaN Metal's NaN answer replaces. The lanes at most `2^-126` are those the -/// device's rounding and its denormal mode decide: `v` just below `2^-126` rounded up to it, a -/// denormal kept or flushed, a zero whose sign the device's flush chose, and an exact zero. The -/// routine answers each of them as Metal does. The test is on `r`'s bits, so no float mode -/// changes it. -fn checked( - fb: &mut FunctionBuilder<'_>, - f: Form, - [a, b, c]: [Value; 3], - (routine, small): (FuncId, bool), -) -> BResult { - let r = fb.fma(a, b, c)?; - let u = u32_form(f); - let ut = ty(fb, u)?; - let bits = fb.convert(ConvOp::Bitcast, r, ut)?; - let magnitude = splat(fb, u, 0x7FFF_FFFF)?; - let least = splat(fb, u, 0x0080_0000)?; - let m = bin(fb, BinOp::BitwiseAnd, bits, magnitude)?; - let at_most = bin(fb, BinOp::ULessThanEqual, m, least)?; - let any = match f.lanes { - 1 => at_most, - _ => fb.unary(UnOp::Any, at_most)?, - }; - let lanes = f.lanes; - let recompute: ArmFn<'_, ()> = Box::new(move |fb, _| { - let all = [a, b, c, r]; - let args = if small { &all[..] } else { &all[..3] }; - let metal = fb - .call(routine, args)? - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - let v = match (small, lanes) { - (true, _) | (_, 1) => metal, - _ => fb.select(at_most, metal, r)?, - }; - Ok(ArmEnd::FallThrough(vec![v])) - }); - let keep: ArmFn<'_, ()> = Box::new(move |_, _| Ok(ArmEnd::FallThrough(vec![r]))); - let Merged(merged) = fb.if_(&mut (), any, recompute, Some(keep))?; - merged - .first() - .copied() - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) -} - fn bin(fb: &mut FunctionBuilder<'_>, op: BinOp, a: Value, b: Value) -> BResult { fb.binary(op, a, b) } @@ -807,41 +391,6 @@ fn veltkamp(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<(Value, Ok((hi, lo)) } -/// `x` (`float` lanes of form `f`) as Metal reads an operand: a denormal is a zero of its sign -/// (decided on the exponent field, whatever the device's denormal mode). -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 (exp, sign, z) = ( - splat(fb, u, 0x7F80_0000)?, - splat(fb, u, 0x8000_0000)?, - splat(fb, u, 0)?, - ); - let e = bin(fb, BinOp::BitwiseAnd, bits, exp)?; - let tiny = bin(fb, BinOp::IEqual, e, z)?; - let s = bin(fb, BinOp::BitwiseAnd, bits, sign)?; - let r = fb.select(tiny, s, bits)?; - fb.convert(ConvOp::Bitcast, r, ft) -} - -/// `x` (`float` lanes of form `f`, never a denormal) as Metal answers a result: every NaN -/// `0x7FC00000`. -fn metal_result(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 (mag, inf, quiet) = ( - splat(fb, u, 0x7FFF_FFFF)?, - splat(fb, u, 0x7F80_0000)?, - splat(fb, u, 0x7FC0_0000)?, - ); - let m = bin(fb, BinOp::BitwiseAnd, bits, mag)?; - let nan = bin(fb, BinOp::UGreaterThan, m, inf)?; - let r = fb.select(nan, quiet, bits)?; - fb.convert(ConvOp::Bitcast, r, ft) -} - /// Whether every lane of `float` values `xs` (form `f`) is finite, from their bits (exact /// whatever the device does with infinities and NaNs). fn all_finite(fb: &mut FunctionBuilder<'_>, f: Form, xs: &[Value]) -> BResult { @@ -860,425 +409,3 @@ fn all_finite(fb: &mut FunctionBuilder<'_>, f: Form, xs: &[Value]) -> BResult, - f: Form, - a: Value, - b: Value, - c: Value, -) -> BResult { - let p = exact_op(fb, BinOp::FMul, a, b)?; - let unfused = exact_op(fb, BinOp::FAdd, p, c)?; - let factors = all_finite(fb, f, &[a, b])?; - let addend = all_finite(fb, f, &[c])?; - let special = fb.select(factors, c, unfused)?; - let finite = bin(fb, BinOp::LogicalAnd, factors, addend)?; - Ok(Outside { - finite, - unfused, - special, - }) -} - -/// The `float` fused multiply-add through `double` ([`Route::Wide`]): `p = a * b` is exact in -/// `double` (48 bits, between `2^-298` and `2^256`), `s = p + c` with its exact error is -/// FastTwoSum's (no `double` denormal or overflow is reachable), [`to_odd`] in `u64` bits -/// makes it the round-to-odd sum, and its conversion to `float` is then the correctly rounded -/// result, overflow included. The round-to-odd sum is below `2^-126` in magnitude exactly where -/// the exact one is (it rounds no value onto `2^-126`, whose significand is even), and there the -/// result is a zero of its sign, as Metal flushes it before rounding. An exact zero sum takes the -/// unfused `float` result, which is the fused one there: it is of two exact zeros (signed as IEEE -/// adds them) or of a product that is a `float` cancelling `c` (`+0`), and needs no `double` -/// signed zero. Infinite and NaN operands take [`Outside::special`]. -fn wide(fb: &mut FunctionBuilder<'_>, f: Form, a: Value, b: Value, c: Value) -> BResult { - let d = f.with(Held::Float(FloatFmt::F64)); - let w = f.with(Held::Int { - bits: 64, - container: 64, - }); - let (td, tf) = (ty(fb, d)?, ty(fb, f)?); - let (a, b, c) = (flush(fb, f, a)?, flush(fb, f, b)?, flush(fb, f, c)?); - let out = outside(fb, f, a, b, c)?; - let x = fb.convert(ConvOp::FConvert, a, td)?; - let y = fb.convert(ConvOp::FConvert, b, td)?; - let z = fb.convert(ConvOp::FConvert, c, td)?; - let p = exact_op(fb, BinOp::FMul, x, y)?; - let (s, e) = two_sum(fb, p, z)?; - let odd = to_odd(fb, d, w, s, e)?; - let r = fb.convert(ConvOp::FConvert, odd, tf)?; - let magnitude = fb.glsl(GlslOp::FAbs, &[odd])?; - let normal = fsplat(fb, d, f64::from(f32::MIN_POSITIVE))?; - let tiny = bin(fb, BinOp::FOrdLessThan, magnitude, normal)?; - let u = u32_form(f); - let ut = ty(fb, u)?; - let bits = fb.convert(ConvOp::Bitcast, r, ut)?; - let sign = splat(fb, u, 0x8000_0000)?; - let signed_zero = bin(fb, BinOp::BitwiseAnd, bits, sign)?; - let bits = fb.select(tiny, signed_zero, bits)?; - let r = fb.convert(ConvOp::Bitcast, bits, tf)?; - let zd = fsplat(fb, d, 0.0)?; - let zero = bin(fb, BinOp::FOrdEqual, s, zd)?; - let r = fb.select(zero, out.unfused, r)?; - let r = fb.select(out.finite, r, out.special)?; - metal_result(fb, f, r) -} - -/// Metal's `fma` of `a`, `b` and `c` (`float` lanes of form `f`) from `r`, their `OpFmaKHR`, on -/// each lane where `r` is at most `2^-126` in magnitude, through `double`; `r` on every other lane -/// ([`checked`]'s rare path, [`Route::Khr`]'s routine). -/// -/// On such a lane every operand is finite, and with each read as Metal reads it (a denormal as a -/// zero of its sign) `r` is the device's rounding of the exact `v = a · b + c`: correctly rounded, -/// then kept, flushed to a zero of either sign, or flushed before rounding (Vulkan's float -/// controls), its zero's sign the device's to drop without `SignedZeroInfNanPreserve`. Metal -/// answers a zero where `v` is below `2^-126` in magnitude: of `v`'s sign where `v` is nonzero, -/// and where it is zero the sign IEEE 754-2008 (6.3) gives a fused multiply-add's exact zero -/// (`-0` only where the product's sign and `c`'s are both negative, [`zero_sign`]). Elsewhere it -/// answers the correctly rounded `v`, which there is `r`, `±2^-126` (`|v|` at least `2^-126` -/// rounds to no less, and `r` is no more). So only `v`'s sign and whether it lies below `2^-126` -/// are computed: `p = a · b` is exact in `double` (48 bits), `s = p + c` rounds once and Knuth's -/// TwoSum gives its error `e` exactly (no `double` overflow, and every value is a multiple of -/// `2^-298`, far above `double`'s denormals). `s` is zero only where `v` is and has its sign -/// elsewhere; rounding is monotone and `2^-126` a `double`, so `|v| < 2^-126` where -/// `|s| < 2^-126`, never where `|s| > 2^-126`, and where `|s| == 2^-126` exactly where `e` points -/// inward (`e · s < 0`, a normal `double`). The test of `r`, the zero's sign and the zero are on -/// bits, so no float mode changes the answer. -fn small(fb: &mut FunctionBuilder<'_>, f: Form, [a, b, c]: [Value; 3], r: Value) -> BResult { - let d = f.with(Held::Float(FloatFmt::F64)); - let u = u32_form(f); - let (ut, td, tf) = (ty(fb, u)?, ty(fb, d)?, ty(fb, f)?); - let rb = fb.convert(ConvOp::Bitcast, r, ut)?; - let magnitude = splat(fb, u, 0x7FFF_FFFF)?; - let least = splat(fb, u, 0x0080_0000)?; - let m = bin(fb, BinOp::BitwiseAnd, rb, magnitude)?; - let at_most = bin(fb, BinOp::ULessThanEqual, m, least)?; - // The operands as Metal reads them, in `double`: a denormal as a zero, its sign on its bits. - let exponent = splat(fb, u, 0x7F80_0000)?; - let zu = splat(fb, u, 0)?; - let zf = fsplat(fb, f, 0.0)?; - let mut read = |x: Value| -> BResult<(Value, Value)> { - let bits = fb.convert(ConvOp::Bitcast, x, ut)?; - let e = bin(fb, BinOp::BitwiseAnd, bits, exponent)?; - let denormal = bin(fb, BinOp::IEqual, e, zu)?; - let x = fb.select(denormal, zf, x)?; - Ok((bits, fb.convert(ConvOp::FConvert, x, td)?)) - }; - let ((ab, x), (bb, y), (cb, z)) = (read(a)?, read(b)?, read(c)?); - let p = exact_op(fb, BinOp::FMul, x, y)?; - let s = exact_op(fb, BinOp::FAdd, p, z)?; - // Knuth's TwoSum: `e = (p - (s - z)) + (z - (s - (s - z)))`, exactly `v - s`. - let sp = exact_op(fb, BinOp::FSub, s, z)?; - let sz = exact_op(fb, BinOp::FSub, s, sp)?; - let dp = exact_op(fb, BinOp::FSub, p, sp)?; - let dz = exact_op(fb, BinOp::FSub, z, sz)?; - let e = exact_op(fb, BinOp::FAdd, dp, dz)?; - let normal = fsplat(fb, d, f64::from(f32::MIN_POSITIVE))?; - let zd = fsplat(fb, d, 0.0)?; - let size = fb.glsl(GlslOp::FAbs, &[s])?; - let below = bin(fb, BinOp::FOrdLessThan, size, normal)?; - let at = bin(fb, BinOp::FOrdEqual, size, normal)?; - let es = exact_op(fb, BinOp::FMul, e, s)?; - let inward = bin(fb, BinOp::FOrdLessThan, es, zd)?; - let edge = bin(fb, BinOp::LogicalAnd, at, inward)?; - let under = bin(fb, BinOp::LogicalOr, below, edge)?; - let tiny = bin(fb, BinOp::LogicalAnd, at_most, under)?; - // The zero's sign: an exact zero sum's IEEE sign, else `v`'s. - let sign = splat(fb, u, 0x8000_0000)?; - let product = bin(fb, BinOp::BitwiseXor, ab, bb)?; - let both = bin(fb, BinOp::BitwiseAnd, product, cb)?; - let exact = bin(fb, BinOp::BitwiseAnd, both, sign)?; - let negative = bin(fb, BinOp::FOrdLessThan, s, zd)?; - let signed = fb.select(negative, sign, zu)?; - let cancelled = bin(fb, BinOp::FOrdEqual, s, zd)?; - let zero = fb.select(cancelled, exact, signed)?; - let out = fb.select(tiny, zero, rb)?; - fb.convert(ConvOp::Bitcast, out, tf) -} - -// ---- The integer routine ---- - -/// 64-bit shifts and tests on (high, low) `u32` word pairs of form `u`, every 32-bit shift in -/// range for an amount in `[0, 63]`. -struct Words { - u: Form, -} - -impl Words { - fn k(&self, fb: &mut FunctionBuilder<'_>, v: u32) -> BResult { - splat(fb, self.u, u64::from(v)) - } - - /// The amount's low five bits and whether it is at least 32. - fn split(&self, fb: &mut FunctionBuilder<'_>, n: Value) -> BResult<(Value, Value)> { - let (k31, k32) = (self.k(fb, 31)?, self.k(fb, 32)?); - let nl = bin(fb, BinOp::BitwiseAnd, n, k31)?; - let big = bin(fb, BinOp::UGreaterThanEqual, n, k32)?; - Ok((nl, big)) - } - - /// `(hi, lo) << n` for `n` in `[0, 63]`. - fn shl( - &self, - fb: &mut FunctionBuilder<'_>, - (hi, lo): (Value, Value), - n: Value, - ) -> BResult<(Value, Value)> { - let (nl, big) = self.split(fb, n)?; - let (one, k31, z) = (self.k(fb, 1)?, self.k(fb, 31)?, self.k(fb, 0)?); - let t_lo = bin(fb, BinOp::ShiftLeftLogical, lo, nl)?; - let t_hi = bin(fb, BinOp::ShiftLeftLogical, hi, nl)?; - // The bits of `lo` that cross into `hi`: `lo >> (32 - nl)`, as two in-range shifts. - let back = bin(fb, BinOp::ISub, k31, nl)?; - let cross = bin(fb, BinOp::ShiftRightLogical, lo, one)?; - let cross = bin(fb, BinOp::ShiftRightLogical, cross, back)?; - let t_hi = bin(fb, BinOp::BitwiseOr, t_hi, cross)?; - let hi = fb.select(big, t_lo, t_hi)?; - let lo = fb.select(big, z, t_lo)?; - Ok((hi, lo)) - } - - /// `(hi, lo) >> n` for `n` in `[0, 63]`. - fn shr( - &self, - fb: &mut FunctionBuilder<'_>, - (hi, lo): (Value, Value), - n: Value, - ) -> BResult<(Value, Value)> { - let (nl, big) = self.split(fb, n)?; - let (one, k31, z) = (self.k(fb, 1)?, self.k(fb, 31)?, self.k(fb, 0)?); - let t_hi = bin(fb, BinOp::ShiftRightLogical, hi, nl)?; - let t_lo = bin(fb, BinOp::ShiftRightLogical, lo, nl)?; - let back = bin(fb, BinOp::ISub, k31, nl)?; - let cross = bin(fb, BinOp::ShiftLeftLogical, hi, one)?; - let cross = bin(fb, BinOp::ShiftLeftLogical, cross, back)?; - let t_lo = bin(fb, BinOp::BitwiseOr, t_lo, cross)?; - let lo = fb.select(big, t_hi, t_lo)?; - let hi = fb.select(big, z, t_hi)?; - Ok((hi, lo)) - } - - /// Whether any bit of `(hi, lo)` below bit `n` (in `[0, 63]`) is set. - fn sticky( - &self, - fb: &mut FunctionBuilder<'_>, - (hi, lo): (Value, Value), - n: Value, - ) -> BResult { - let (nl, big) = self.split(fb, n)?; - let (one, z) = (self.k(fb, 1)?, self.k(fb, 0)?); - let unit = bin(fb, BinOp::ShiftLeftLogical, one, nl)?; - let below = bin(fb, BinOp::ISub, unit, one)?; - let lo_part = bin(fb, BinOp::BitwiseAnd, lo, below)?; - let lo_set = bin(fb, BinOp::INotEqual, lo_part, z)?; - let hi_part = bin(fb, BinOp::BitwiseAnd, hi, below)?; - let hi_set = bin(fb, BinOp::INotEqual, hi_part, z)?; - let lo_any = bin(fb, BinOp::INotEqual, lo, z)?; - let big_set = bin(fb, BinOp::LogicalOr, lo_any, hi_set)?; - fb.select(big, big_set, lo_set) - } - - /// The index of the highest set bit of `(hi, lo)` (all ones for zero, as `FindUMsb`). - fn msb(&self, fb: &mut FunctionBuilder<'_>, (hi, lo): (Value, Value)) -> BResult { - let (z, k32) = (self.k(fb, 0)?, self.k(fb, 32)?); - let hi_set = bin(fb, BinOp::INotEqual, hi, z)?; - let hm = fb.glsl(GlslOp::FindUMsb, &[hi])?; - let hm = bin(fb, BinOp::IAdd, hm, k32)?; - let lm = fb.glsl(GlslOp::FindUMsb, &[lo])?; - fb.select(hi_set, hm, lm) - } -} - -/// The `float` fused multiply-add in 32-bit integers ([`Route::Soft`]); exponents are held -/// biased by 512 so every compare is unsigned, except the rounding position, a signed count. -/// -/// For finite operands with a nonzero product: the significands `ma`, `mb` (hidden bit set for -/// a normal, exponent field 1 for a denormal) multiply exactly into 48 bits (`OpUMulExtended`), -/// normalized to bit 61 of a 64-bit pair; the addend's significand is placed at bit 61 too. -/// The larger magnitude is `big`, the other is shifted right to `big`'s exponent with the bits -/// shifted out kept as a sticky bit (below the 64 kept, where it cannot reach a rounding -/// decision), both are doubled so the sticky bit sits below the smaller one's last bit, and one -/// 64-bit sum or difference (of operands below `2^63`, so no carry is lost) holds the exact -/// result up to that sticky bit. It rounds to nearest even at the bit that keeps 24 significant -/// bits, into the exponent on a carry and to infinity past the largest finite `float`. An exact -/// cancellation is `+0`; a result whose exact value is below `2^-126` (its leading bit's, the -/// sticky bit keeping it below where the exact one is) is a zero of the sum's sign, as Metal -/// flushes it before rounding. A zero factor takes the unfused result, which is the -/// fused one there (`±0 + c`, no rounding); infinite and NaN operands take -/// [`Outside::special`]. -fn soft(fb: &mut FunctionBuilder<'_>, f: Form, a: Value, b: Value, c: Value) -> BResult { - use BinOp as B; - let u = u32_form(f); - let w = Words { u }; - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let (a, b, c) = (flush(fb, f, a)?, flush(fb, f, b)?, flush(fb, f, c)?); - let out = outside(fb, f, a, b, c)?; - let k = |fb: &mut FunctionBuilder<'_>, v: u32| splat(fb, u, u64::from(v)); - let (z, one, k23, k31) = (k(fb, 0)?, k(fb, 1)?, k(fb, 23)?, k(fb, 31)?); - let (fmask, emask, hidden, mag) = ( - k(fb, 0x7F_FFFF)?, - k(fb, 0xFF)?, - k(fb, 0x80_0000)?, - k(fb, 0x7FFF_FFFF)?, - ); - // Sign, biased exponent field, significand (hidden bit set for a normal), and the - // exponent of its last bit plus 150 (`max(e, 1)`). - let unpack = |fb: &mut FunctionBuilder<'_>, x: Value| -> BResult<[Value; 4]> { - let bits = fb.convert(ConvOp::Bitcast, x, ut)?; - let s = bin(fb, B::ShiftRightLogical, bits, k31)?; - let e = bin(fb, B::ShiftRightLogical, bits, k23)?; - let e = bin(fb, B::BitwiseAnd, e, emask)?; - let m = bin(fb, B::BitwiseAnd, bits, fmask)?; - let normal = bin(fb, B::INotEqual, e, z)?; - let h = fb.select(normal, hidden, z)?; - let m = bin(fb, B::BitwiseOr, m, h)?; - let e1 = fb.glsl(GlslOp::UMax, &[e, one])?; - Ok([bits, s, m, e1]) - }; - let [ab, sa, ma, ea] = unpack(fb, a)?; - let [bb, sb, mb, eb] = unpack(fb, b)?; - let [cb, sc, mc, ec] = unpack(fb, c)?; - let zero_mag = |fb: &mut FunctionBuilder<'_>, bits: Value| -> BResult { - let m = bin(fb, B::BitwiseAnd, bits, mag)?; - bin(fb, B::IEqual, m, z) - }; - let (za, zb, zc) = (zero_mag(fb, ab)?, zero_mag(fb, bb)?, zero_mag(fb, cb)?); - let sp = bin(fb, B::BitwiseXor, sa, sb)?; - - // The product, its leading bit moved to bit 61; its exponent `pe` (of bit 0, + 512). - let prod = bin(fb, B::UMulExtended, ma, mb)?; - let plo = fb.composite_extract(prod, &[0])?; - let phi = fb.composite_extract(prod, &[1])?; - let k61 = k(fb, 61)?; - let mp = w.msb(fb, (phi, plo))?; - let l = bin(fb, B::ISub, k61, mp)?; - let k63 = k(fb, 63)?; - let l = fb.glsl(GlslOp::UMin, &[l, k63])?; - let (phi, plo) = w.shl(fb, (phi, plo), l)?; - // pe = ea + eb - 300 - l + 512. - let pe = bin(fb, B::IAdd, ea, eb)?; - let k212 = k(fb, 212)?; - let pe = bin(fb, B::IAdd, pe, k212)?; - let pe = bin(fb, B::ISub, pe, l)?; - // The addend at bit 61 (a 24-bit significand: its pair's low word is zero); ce = ec - 150 - // - lc + 512. A zero addend shifts by a harmless 30 and is not used. - let mcm = fb.glsl(GlslOp::FindUMsb, &[mc])?; - let lc = bin(fb, B::ISub, k61, mcm)?; - let k32 = k(fb, 32)?; - let lc32 = bin(fb, B::ISub, lc, k32)?; - let k30 = k(fb, 30)?; - let lc32 = fb.glsl(GlslOp::UMin, &[lc32, k30])?; - let chi = bin(fb, B::ShiftLeftLogical, mc, lc32)?; - let k362 = k(fb, 362)?; - let ce = bin(fb, B::IAdd, ec, k362)?; - let ce = bin(fb, B::ISub, ce, lc)?; - - // The larger magnitude (the product when the addend is zero). - let pe_gt = bin(fb, B::UGreaterThan, pe, ce)?; - let pe_eq = bin(fb, B::IEqual, pe, ce)?; - let hi_ge = bin(fb, B::UGreaterThanEqual, phi, chi)?; - let tie = bin(fb, B::LogicalAnd, pe_eq, hi_ge)?; - let p_big = bin(fb, B::LogicalOr, pe_gt, tie)?; - let p_big = bin(fb, B::LogicalOr, p_big, zc)?; - let bhi = fb.select(p_big, phi, chi)?; - let blo = fb.select(p_big, plo, z)?; - let ebig = fb.select(p_big, pe, ce)?; - let sbig = fb.select(p_big, sp, sc)?; - let xhi = fb.select(p_big, chi, phi)?; - let xlo = fb.select(p_big, z, plo)?; - let es = fb.select(p_big, ce, pe)?; - let d = bin(fb, B::ISub, ebig, es)?; - let d = fb.glsl(GlslOp::UMin, &[d, k63])?; - let (shi, slo) = w.shr(fb, (xhi, xlo), d)?; - let st = w.sticky(fb, (xhi, xlo), d)?; - let shi = fb.select(zc, z, shi)?; - let slo = fb.select(zc, z, slo)?; - let nzc = fb.unary(UnOp::LogicalNot, zc)?; - let st = bin(fb, B::LogicalAnd, st, nzc)?; - - // Double both and jam the sticky bit below the smaller one. - let (bhi, blo) = w.shl(fb, (bhi, blo), one)?; - let (shi, slo) = w.shl(fb, (shi, slo), one)?; - let stb = fb.select(st, one, z)?; - let slo = bin(fb, B::BitwiseOr, slo, stb)?; - - // One 64-bit sum or difference (`big >= small`). - let lo_add = bin(fb, B::IAdd, blo, slo)?; - let carry = bin(fb, B::ULessThan, lo_add, blo)?; - let carry = fb.select(carry, one, z)?; - let hi_add = bin(fb, B::IAdd, bhi, shi)?; - let hi_add = bin(fb, B::IAdd, hi_add, carry)?; - let lo_sub = bin(fb, B::ISub, blo, slo)?; - let borrow = bin(fb, B::ULessThan, blo, slo)?; - let borrow = fb.select(borrow, one, z)?; - let hi_sub = bin(fb, B::ISub, bhi, shi)?; - let hi_sub = bin(fb, B::ISub, hi_sub, borrow)?; - let sub = bin(fb, B::INotEqual, sp, sc)?; - let rlo = fb.select(sub, lo_sub, lo_add)?; - let rhi = fb.select(sub, hi_sub, hi_add)?; - let er = bin(fb, B::ISub, ebig, one)?; - let r_any = bin(fb, B::BitwiseOr, rlo, rhi)?; - let cancelled = bin(fb, B::IEqual, r_any, z)?; - let m = w.msb(fb, (rhi, rlo))?; - // The exponent of the leading bit (+ 512); below 2^-126 the result is a signed zero, so a - // result kept is normal. - let emsb = bin(fb, B::IAdd, m, er)?; - let k386 = k(fb, 512 - 126)?; - let tiny = bin(fb, B::ULessThan, emsb, k386)?; - - // Bits to drop: k = m - 23, a signed count in [-23, 40]. - let kk = bin(fb, B::ISub, m, k23)?; - let pos = bin(fb, B::SGreaterThan, kk, z)?; - // k <= 0: the sum is below 2^24 and moves left by -k. - let nk = bin(fb, B::ISub, z, kk)?; - let nk = fb.glsl(GlslOp::SMax, &[nk, z])?; - let nk = fb.glsl(GlslOp::UMin, &[nk, k31])?; - let q_left = bin(fb, B::ShiftLeftLogical, rlo, nk)?; - // k > 0: shifted right by k, rounded to nearest even on the dropped bits. - let kp = fb.glsl(GlslOp::SMax, &[kk, one])?; - let kp = fb.glsl(GlslOp::UMin, &[kp, k63])?; - let (_, q_right) = w.shr(fb, (rhi, rlo), kp)?; - let kh = bin(fb, B::ISub, kp, one)?; - let (_, half_word) = w.shr(fb, (rhi, rlo), kh)?; - let half_bit = bin(fb, B::BitwiseAnd, half_word, one)?; - let half = bin(fb, B::INotEqual, half_bit, z)?; - let rest = w.sticky(fb, (rhi, rlo), kh)?; - let q_low = bin(fb, B::BitwiseAnd, q_right, one)?; - let q_odd = bin(fb, B::INotEqual, q_low, z)?; - let above = bin(fb, B::LogicalOr, rest, q_odd)?; - let up = bin(fb, B::LogicalAnd, half, above)?; - let inc = fb.select(up, one, z)?; - let q_right = bin(fb, B::IAdd, q_right, inc)?; - let q = fb.select(pos, q_right, q_left)?; - - // Pack: the leading bit lands on the exponent field's lowest bit, so the field is emsb + 126 - // (+ the carry of a rounding); a tiny result's wrapped field is selected away below. - let base = bin(fb, B::ISub, emsb, k386)?; - let base = bin(fb, B::ShiftLeftLogical, base, k23)?; - let bits = bin(fb, B::IAdd, base, q)?; - let inf = k(fb, 0x7F80_0000)?; - let over = bin(fb, B::UGreaterThanEqual, bits, inf)?; - let bits = fb.select(over, inf, bits)?; - let bits = fb.select(tiny, z, bits)?; - let sign = bin(fb, B::ShiftLeftLogical, sbig, k31)?; - let bits = bin(fb, B::BitwiseOr, bits, sign)?; - let bits = fb.select(cancelled, z, bits)?; - let r = fb.convert(ConvOp::Bitcast, bits, ft)?; - let zero_factor = bin(fb, B::LogicalOr, za, zb)?; - let r = fb.select(zero_factor, out.unfused, r)?; - let r = fb.select(out.finite, r, out.special)?; - metal_result(fb, f, r) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/atan.rs b/crates/metal2vulkan/src/lower/arith/libm/atan.rs deleted file mode 100644 index 439856a18..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/atan.rs +++ /dev/null @@ -1,576 +0,0 @@ -//! The arc tangent family: `atan`, `asin`, and `acos` in both of Metal's modes, and the generic -//! part of precise `atan2`. -//! -//! **Precise `atan`** is Metal's own form ([`PRECISE_ATAN_P`]): with `a = |x|`, `t = a` below -//! `RN(tan(π/8))`, `(a - 1) rcp(a + 1)` below `RN(tan(3π/8))`, and `-rcp(a)` from there, Metal's -//! reciprocal ([`E::recip`]); then `K + fma(t, RN(RN(t t) P), t)` with `K` zero, `RN(π/4)` and -//! `RN(π/2)`. -//! -//! **Precise `asin` and `acos`** are Metal's own forms, which follow Apple's runtime library and -//! match Metal's measured words: with `a = |x|`, `asin` is the operand below [`ASIN_TINY`], -//! polynomials of `a` below 0.1 ([`ASIN_NEAR`]) and 0.36 ([`ASIN_LOW`]), `a` times polynomials of -//! `a^2` below 0.62 ([`ASIN_MID`]) and 0.815 ([`ASIN_HIGH`]), and from there `RN(π/2) + w P(a)` -//! ([`ASIN_FAR`], fused) of Metal's root `w = z rsqrt(z)` of `z = 1 - a^2` (fused below 0.99, -//! `RN(1 - a) RN(1 + a)` from it), with `x`'s sign; `acos` is `RN(π/2 - a) - a^3 / 6` (fused) to -//! [`ACOS_NEAR_END`], a polynomial of `a` to 1/2 ([`ACOS_MID`]), and `P(u) w` of `u = 1 - a` and -//! Metal's root `w = u rsqrt(u)` above ([`ACOS_FAR`]), taken from `RN(π)` for a negative `x`. Each -//! polynomial is Horner's rule in fused steps from the highest coefficient, and the inverse root is -//! the hardware's model ([`E::fast_rsqrt`]). -//! -//! **Fast `asin` and `acos`** are Metal's own forms ([`FAST_ASIN_P`]): one polynomial below 0.7 and -//! the half-angle form with Metal's root of `(1 - |x|) / 2` from there. -//! -//! **Precise `atan2`** (finite nonzero operands; `math::atan2_special` answers the rest) is -//! Metal's precise `atan` of the correctly rounded quotient `y / x` ([`E::div`]), and that plus -//! `RN(π)` toward a negative `x` (minus it where `y` is negative too). -//! -//! Metal's values at the special operands (cases 087758cb and cc234732): `atan` and `asin` are -//! odd and `acos(±1)` is `+0` and `π`, as the reductions give; an infinite `atan` operand gives -//! `±π/2`; a denormal operand is read as [`denormal::operand`] says, and a zero then answers -//! `+0` for precise `atan` and `fast::asin` (whatever its sign) and the zero itself otherwise; -//! below `2^-12` in magnitude the precise `atan(x)` rounds to `x`, which is selected, so a device -//! that flushes the operand's cube answers it too. `|x| > 1` gives `asin` and `acos` Metal's NaN. - -use crate::lower::arith::denormal; -use crate::lower::arith::libm::{Fun, Mode, E, F32}; -use crate::spirv::error::{BResult, BuildError, TypeRule}; -use crate::spirv::ids::Value; -use crate::spirv::ir::{BinOp, UnOp}; - -/// Metal's precise `asin(a)` is `a` below this (`0x3a9285fe`, about `1.118e-3`). -pub(crate) const ASIN_TINY: u32 = 0x3A92_85FE; - -/// Metal's precise `asin(a)` below 0.1: a polynomial of degree 5 in `a` (`f32` bits, lowest -/// first). -pub(crate) const ASIN_NEAR: [u32; 6] = [ - 0xAD75_05AF, - 0x3F80_0000, - 0xB52F_1CE4, - 0x3E2A_B123, - 0xB9D6_2D9E, - 0x3D9F_092F, -]; - -/// Metal's precise `asin(a)` from 0.1 to 0.36: a polynomial of degree 6 in `a`. -pub(crate) const ASIN_LOW: [u32; 7] = [ - 0x35E8_9736, - 0x3F7F_FBDB, - 0x3A78_7C88, - 0x3E22_F112, - 0x3D0C_250A, - 0xBC47_34E4, - 0x3DE2_9FE7, -]; - -/// Metal's precise `asin(a)` from 0.36 to 0.62: `a Q(a^2)`, `Q` of degree 5. -pub(crate) const ASIN_MID: [u32; 6] = [ - 0x3F7F_FF08, - 0x3E2B_0F18, - 0x3D91_80AC, - 0x3D85_A0DD, - 0xBCD1_3BD9, - 0x3DBC_499F, -]; - -/// Metal's precise `asin(a)` from 0.62 to [`ASIN_FAR_START`]: `a Q(a^2)`, `Q` of degree 6. -pub(crate) const ASIN_HIGH: [u32; 7] = [ - 0x3F81_6B2F, - 0x3CC1_EB4C, - 0x3F58_74B5, - 0xC00B_91CD, - 0x406B_7509, - 0xC04E_468F, - 0x3FA2_2DD9, -]; - -/// Where Metal's precise `asin` takes its root form (`0x3f50a3d7`, about 0.815). -pub(crate) const ASIN_FAR_START: u32 = 0x3F50_A3D7; - -/// Metal's precise `asin(a)` from [`ASIN_FAR_START`]: `RN(π/2) + w P(a)`, `P` of degree 4. -pub(crate) const ASIN_FAR: [u32; 5] = [ - 0xBFC6_F7E7, - 0x3F65_16AB, - 0xBEFB_9783, - 0x3E3A_F607, - 0xBD01_89D6, -]; - -/// Metal's precise `acos(a)` is `RN(π/2 - a) - a^3 / 6` to this (`0x3d99a8ca`, about 0.075). -pub(crate) const ACOS_NEAR_END: u32 = 0x3D99_A8CA; - -/// Metal's precise `acos(a)` from [`ACOS_NEAR_END`] to 1/2: a polynomial of degree 8 in `a`. -pub(crate) const ACOS_MID: [u32; 9] = [ - 0x3FC9_0FD4, - 0xBF7F_FDCF, - 0xBA23_8B67, - 0xBE24_30FB, - 0xBD1D_272C, - 0x3D8D_89DA, - 0xBEA9_EE80, - 0x3ECA_14C3, - 0xBE8C_EF6E, -]; - -/// Metal's precise `acos(a)` above 1/2: `P(u) w` of `u = 1 - a`, `P` of degree 6. -pub(crate) const ACOS_FAR: [u32; 7] = [ - 0x3FB5_04F3, - 0x3DF1_5BE6, - 0x3CD9_3DAE, - 0x3C00_E404, - 0x3B38_D9E4, - 0x3A23_5EB2, - 0x3A5B_BFCA, -]; - -/// `x` as `fun` reads it ([`denormal::read`]). -pub(crate) fn read(e: &mut E<'_, '_>, fun: Fun, x: Value) -> BResult { - match fun.float_fn() { - Some(op) => denormal::read(e.fb, op, F32, x), - None => Ok(x), - } -} - -/// `Q(s)` of Metal's fast `atan(t) = t Q(t^2)` on `[0, 1]`, its `f32` coefficients by their bits, -/// read off Metal's words (clean-room fit): Horner's rule in `s = t t` (rounded), -/// each step one fused multiply-add, then `t Q` rounded. -pub(crate) const FAST_ATAN_Q: [u32; 8] = [ - 0x3F7F_FFFF, - 0xBEAA_A90B, - 0x3E4C_81C3, - 0xBE0F_A948, - 0x3DCB_A0B2, - 0xBD75_5EA6, - 0x3CC9_2C07, - 0xBB9C_A55F, -]; - -/// `RN(π/2)`, which Metal's fast `atan` subtracts from above 1. -const HALF_PI_BITS: u32 = 0x3FC9_0FDB; - -/// Metal's fast `atan(x)`: `t Q(t^2)` of [`FAST_ATAN_Q`] for `t = |x|` to 1, and `RN(π/2) - t -/// Q(t^2)` of Metal's reciprocal `t = rcp(|x|)` above (`E::recip`; an infinity and a magnitude past -/// `2^126`, whose reciprocal Metal flushes, give `RN(π/2)`), with `x`'s sign. A magnitude at or -/// below `2^-126` gives a zero: Metal flushes the product `t Q`, which is below `2^-126` there -/// before rounding. Metal's word on every `float` of `[2^-12, 1]` and every 256th of the others, -/// and above 1 wherever the reciprocal is Metal's. -fn fast_atan(e: &mut E<'_, '_>, x: Value) -> BResult { - let x = read(e, Fun::Atan(Mode::Fast), x)?; - let a = e.abs(x)?; - let one = e.c(1.0)?; - let above = e.gt(a, one)?; - let r = e.recip(a)?; - let t = e.sel(above, r, a)?; - let s = e.mul(t, t)?; - let (last, rest) = FAST_ATAN_Q - .split_last() - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - let mut q = e.c(f32::from_bits(*last))?; - for c in rest.iter().rev() { - let c = e.c(f32::from_bits(*c))?; - q = e.fused(q, s, c)?; - } - let core = e.mul(t, q)?; - let h = e.c(f32::from_bits(HALF_PI_BITS))?; - let far = e.sub(h, core)?; - let r = e.sel(above, far, core)?; - let least = e.c(f32::MIN_POSITIVE)?; - let flushed = e.le(a, least)?; - let zero = e.c(0.0)?; - let r = e.sel(flushed, zero, r)?; - e.copysign(r, x) -} - -/// `P(s)` of Metal's precise `atan(t) = t + t s P(s)`, `s = t t` (rounded), for `|t|` up to -/// `tan(π/8)`, its `f32` coefficients by their bits: the coefficients of the public Cephes `atanf` -/// (Moshier), which a clean-room fit of Metal's words converged on, rounded to -/// `float`. Horner's rule with one fused multiply-add per step. -pub(crate) const PRECISE_ATAN_P: [u32; 4] = [0xBEAA_AA2A, 0x3E4C_925F, 0xBE0E_1B85, 0x3DA4_F0D1]; - -/// `RN(tan(π/8))` and `RN(tan(3π/8))`, from which Metal's precise `atan` reduces its operand. -const TAN_PI_8_BITS: u32 = 0x3ED4_13CD; -const TAN_3PI_8_BITS: u32 = 0x401A_827A; - -/// `RN(π/4)`, which Metal's precise `atan` adds between [`TAN_PI_8_BITS`] and -/// [`TAN_3PI_8_BITS`]. -const QUARTER_PI_BITS: u32 = 0x3F49_0FDB; - -/// Metal's precise `atan(x)`: with `a = |x|`, `t = a` below `RN(tan(π/8))`, `(a - 1) rcp(a + 1)` -/// below `RN(tan(3π/8))`, and `-rcp(a)` from there, of Metal's reciprocal ([`E::recip`]; an -/// infinity and a magnitude past `2^126`, whose reciprocal Metal flushes, give `RN(π/2)`); then -/// `K + fma(t, RN(RN(t t) P(t t)), t)` of [`PRECISE_ATAN_P`] with `K` zero, `RN(π/4)` and `RN(π/2)` -/// there, and `x`'s sign. Below `2^-12` it is `x` (selected, so the emulated fused steps never take -/// products that small), and a zero gives `+0`, a flushed denormal too. Metal's word on every -/// `float` of `[0.25, 4)` and every 256th positive one elsewhere (the M3) wherever -/// the reciprocal is Metal's, which it is at all but 0.08% of them. -fn precise_atan(e: &mut E<'_, '_>, x: Value) -> BResult { - let x = read(e, Fun::Atan(Mode::Precise), x)?; - metal_atan(e, x) -} - -/// [`precise_atan`] of an operand already read as Metal reads it: also `atan2`'s. -fn metal_atan(e: &mut E<'_, '_>, x: Value) -> BResult { - let a = e.abs(x)?; - let low = e.c(f32::from_bits(TAN_PI_8_BITS))?; - let high = e.c(f32::from_bits(TAN_3PI_8_BITS))?; - let near = e.lt(a, low)?; - let middle = e.lt(a, high)?; - let one = e.c(1.0)?; - let up = e.add(a, one)?; - let down = e.sub(a, one)?; - let divisor = e.sel(middle, up, a)?; - let r = e.recip(divisor)?; - let quotient = e.mul(down, r)?; - let zero = e.c(0.0)?; - let far = e.sub(zero, r)?; - let t = e.sel(middle, quotient, far)?; - let t = e.sel(near, a, t)?; - let s = e.mul(t, t)?; - let (last, rest) = PRECISE_ATAN_P - .split_last() - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - let mut p = e.c(f32::from_bits(*last))?; - for c in rest.iter().rev() { - let c = e.c(f32::from_bits(*c))?; - p = e.fused(p, s, c)?; - } - let ps = e.mul(p, s)?; - let core = e.fused(t, ps, t)?; - let quarter = e.c(f32::from_bits(QUARTER_PI_BITS))?; - let half = e.c(f32::from_bits(HALF_PI_BITS))?; - let k = e.sel(middle, quarter, half)?; - let k = e.sel(near, zero, k)?; - let r = e.add(k, core)?; - let r = e.copysign(r, x)?; - let tiny = e.c(2f32.powi(-12))?; - let is_tiny = e.lt(a, tiny)?; - let r = e.sel(is_tiny, x, r)?; - // Precise `atan(-0)` is `+0` (a flushed denormal too). - let is_zero = e.fb.binary(BinOp::FOrdEqual, a, zero)?; - e.sel(is_zero, zero, r) -} - -/// Metal's `atan(x)` in mode `m`. -pub(crate) fn atan(e: &mut E<'_, '_>, m: Mode, x: Value) -> BResult { - match m { - Mode::Fast => fast_atan(e, x), - Mode::Precise => precise_atan(e, x), - } -} - -/// `P(s)` of Metal's fast `asin(x) = x P(x^2)` below 0.7, its `f32` coefficients by their bits, -/// read off Metal's words (clean-room fit): Horner's rule in `s = x x` (rounded), -/// each step one fused multiply-add. Its fast `acos` takes the same `P`, and both take it at `z = -/// (1 - |x|) / 2` from 0.7 on. -pub(crate) const FAST_ASIN_P: [u32; 7] = [ - 0x3F80_0001, - 0x3E2A_A575, - 0x3D9A_CEE0, - 0x3D1C_4BA7, - 0x3D81_F491, - 0xBD73_BDCF, - 0x3DD4_CDC2, -]; - -/// `RN(π)`, which Metal's fast `acos` of a negative operand from -0.7 down starts from. -const PI_BITS: u32 = 0x4049_0FDB; - -/// The pieces of Metal's fast `asin` and `acos` of magnitude `a`: whether `a` is below 0.7, -/// [`FAST_ASIN_P`] at `a^2` there and at `z = (1 - a) / 2` from 0.7 on, `z`, `z`'s inverse -/// root, and whether `z` is zero (`a = 1`, whose root is then `0`). -struct FastArcs { - near: Value, - p: Value, - z: Value, - rs: Value, - zero_z: Value, -} - -fn fast_arcs(e: &mut E<'_, '_>, a: Value) -> BResult { - let bound = e.c(0.7)?; - let near = e.lt(a, bound)?; - let s = e.mul(a, a)?; - let (one, half) = (e.c(1.0)?, e.c(0.5)?); - // `1 - a` is exact from `a = 1/2` on (Sterbenz), and so is its half. - let rest = e.sub(one, a)?; - let z = e.mul(rest, half)?; - let v = e.sel(near, s, z)?; - let (last, rest) = FAST_ASIN_P - .split_last() - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - let mut p = e.c(f32::from_bits(*last))?; - for c in rest.iter().rev() { - let c = e.c(f32::from_bits(*c))?; - p = e.fused(p, v, c)?; - } - // `z`'s inverse root where it is read (`z` is zero or at least `2^-25` from 0.7 on); 1/4 - // elsewhere, so no lane takes a denormal's. - let quarter = e.c(0.25)?; - let zr = e.sel(near, quarter, z)?; - let rs = e.fast_rsqrt(zr)?; - let zero = e.c(0.0)?; - let zero_z = e.fb.binary(BinOp::FOrdEqual, z, zero)?; - Ok(FastArcs { - near, - p, - z, - rs, - zero_z, - }) -} - -/// Metal's fast `asin(x)`: `|x| P(x^2)` of [`FAST_ASIN_P`] below 0.7, and from there `RN(π/2) - 2 w -/// P(z)` in one fused multiply-add, `z = (1 - |x|) / 2` and `w = z rsqrt(z)` (Metal's fast square -/// root), with `x`'s sign; `+0` at a zero (`fast::asin(-0)` is `+0`, a flushed denormal too) and -/// Metal's NaN, with `x`'s sign, past 1 in magnitude. Metal's `rsqrt` is the hardware's, which is -/// correctly rounded on 95.6% of significands; the routine takes its model ([`E::fast_rsqrt`]), and -/// so is Metal's word on every lane below 0.7 that its polynomial is and on 99.88 % of `[0.7, 1)` -/// (97.39 % with the correctly rounded root). -fn fast_asin(e: &mut E<'_, '_>, x: Value) -> BResult { - let x = read(e, Fun::Asin(Mode::Fast), x)?; - let a = e.abs(x)?; - let k = fast_arcs(e, a)?; - let near = e.mul(a, k.p)?; - let w = e.mul(k.z, k.rs)?; - let zero = e.c(0.0)?; - let w = e.sel(k.zero_z, zero, w)?; - let minus_two = e.c(-2.0)?; - let m2w = e.mul(minus_two, w)?; - let h = e.c(f32::from_bits(HALF_PI_BITS))?; - let far = e.fused(m2w, k.p, h)?; - let r = e.sel(k.near, near, far)?; - let r = e.copysign(r, x)?; - let is_zero = e.fb.binary(BinOp::FOrdEqual, a, zero)?; - let r = e.sel(is_zero, zero, r)?; - let one = e.c(1.0)?; - let domain = e.gt(a, one)?; - let nan = e.metal_nan(Some(x))?; - e.sel(domain, nan, r) -} - -/// Metal's fast `acos(x)`: `RN(π/2) - x P(x^2)` of [`FAST_ASIN_P`] below 0.7 in magnitude, in one -/// fused multiply-add; from there, with `z = (1 - |x|) / 2`, Metal's root `w` of `z`, `2 RN(w -/// P(z))` for `x > 0` and `RN(π) - 2 w P(z)` (fused) for `x < 0`; Metal's NaN past 1. The root is -/// `w1 = z r` refined once, `w1 + w1 RN(1/2 - w1 RN(r / 2))` (two fused steps), of the inverse root -/// `r` (Metal's hardware `rsqrt`'s model, as in [`fast_asin`]): Metal's word on every lane below -/// 0.7 that the polynomial is and on 99.94 % of `[0.7, 1)` and 99.99 % of `(-1, -0.7]` (99.05 % and -/// 99.82 % with the correctly rounded root). -fn fast_acos(e: &mut E<'_, '_>, x: Value) -> BResult { - let x = read(e, Fun::Acos(Mode::Fast), x)?; - let a = e.abs(x)?; - let k = fast_arcs(e, a)?; - let h = e.c(f32::from_bits(HALF_PI_BITS))?; - let minus_one = e.c(-1.0)?; - let nx = e.mul(minus_one, x)?; - let near = e.fused(nx, k.p, h)?; - let half = e.c(0.5)?; - let w1 = e.mul(k.z, k.rs)?; - let hr = e.mul(half, k.rs)?; - let nw1 = e.mul(minus_one, w1)?; - let t = e.fused(nw1, hr, half)?; - let w = e.fused(w1, t, w1)?; - let zero = e.c(0.0)?; - let w = e.sel(k.zero_z, zero, w)?; - let wp = e.mul(w, k.p)?; - let two = e.c(2.0)?; - let positive = e.mul(two, wp)?; - let minus_two = e.c(-2.0)?; - let m2w = e.mul(minus_two, w)?; - let pi = e.c(f32::from_bits(PI_BITS))?; - let negative = e.fused(m2w, k.p, pi)?; - let above = e.gt(x, zero)?; - let far = e.sel(above, positive, negative)?; - let r = e.sel(k.near, near, far)?; - let one = e.c(1.0)?; - let domain = e.gt(a, one)?; - let nan = e.metal_nan(None)?; - e.sel(domain, nan, r) -} - -/// `z rsqrt(z)` of `z >= 0`, Metal's root through its hardware's inverse root ([`E::fast_rsqrt`]), -/// and `0` at `z = 0` (whose inverse root is infinite). -fn metal_root(e: &mut E<'_, '_>, z: Value) -> BResult { - let r = e.fast_rsqrt(z)?; - let w = e.mul(z, r)?; - let zero = e.c(0.0)?; - let at_zero = e.fb.binary(BinOp::FOrdEqual, z, zero)?; - e.sel(at_zero, zero, w) -} - -/// Whether the magnitude `a` lies below the `float` of bits `bound` (by the bits). -fn below(e: &mut E<'_, '_>, a: Value, bound: u32) -> BResult { - let ab = e.bits(a)?; - let k = e.u(bound)?; - e.iop(BinOp::ULessThan, ab, k) -} - -/// Metal's `asin(x)` in mode `m`; the precise one Metal's form (the module's list), each region -/// computed and the operand's selected. -pub(crate) fn asin(e: &mut E<'_, '_>, m: Mode, x: Value) -> BResult { - if m == Mode::Fast { - return fast_asin(e, x); - } - let x = read(e, Fun::Asin(m), x)?; - let a = e.abs(x)?; - // From 0.815: `RN(π/2) + w P(a)`, `z = 1 - a^2` fused below 0.99. - let one = e.c(1.0)?; - let minus_a = e.fb.unary(UnOp::FNegate, a)?; - let fused = e.fused(minus_a, a, one)?; - let down = e.sub(one, a)?; - let up = e.add(a, one)?; - let product = e.mul(down, up)?; - let near_one = e.c(0.99)?; - let below_near_one = e.lt(a, near_one)?; - let z = e.sel(below_near_one, fused, product)?; - let w = metal_root(e, z)?; - let p = e.fused_poly(&ASIN_FAR, a)?; - let h = e.c(f32::from_bits(HALF_PI_BITS))?; - let r = e.fused(w, p, h)?; - // Below 0.815 and 0.62: `a Q(a^2)`. - let s = e.mul(a, a)?; - let q = e.fused_poly(&ASIN_HIGH, s)?; - let high = e.mul(q, a)?; - let in_high = below(e, a, ASIN_FAR_START)?; - let r = e.sel(in_high, high, r)?; - let q = e.fused_poly(&ASIN_MID, s)?; - let mid = e.mul(q, a)?; - let bound = e.c(0.62)?; - let in_mid = e.lt(a, bound)?; - let r = e.sel(in_mid, mid, r)?; - // Below 0.36 and 0.1: polynomials of `a`. - let low = e.fused_poly(&ASIN_LOW, a)?; - let bound = e.c(0.36)?; - let in_low = e.lt(a, bound)?; - let r = e.sel(in_low, low, r)?; - let near = e.fused_poly(&ASIN_NEAR, a)?; - let bound = e.c(0.1)?; - let in_near = e.lt(a, bound)?; - let r = e.sel(in_near, near, r)?; - let r = e.copysign(r, x)?; - // Below `ASIN_TINY`: the operand itself (a kept denormal included). - let tiny = below(e, a, ASIN_TINY)?; - let r = e.sel(tiny, x, r)?; - // `|x| > 1`: Metal's NaN. - let domain = e.gt(a, one)?; - let nan = e.metal_nan(None)?; - e.sel(domain, nan, r) -} - -/// Metal's `acos(x)` in mode `m`; the precise one Metal's form (the module's list), each region -/// computed and the operand's selected, then `RN(π - r)` for a negative `x`. -pub(crate) fn acos(e: &mut E<'_, '_>, m: Mode, x: Value) -> BResult { - if m == Mode::Fast { - return fast_acos(e, x); - } - let x = read(e, Fun::Acos(m), x)?; - let a = e.abs(x)?; - // Above 1/2: `P(u) w` of `u = 1 - a` (exact) and `w = u rsqrt(u)`; `+0` at `a = 1`. - let one = e.c(1.0)?; - let u = e.sub(one, a)?; - let w = metal_root(e, u)?; - let p = e.fused_poly(&ACOS_FAR, u)?; - let r = e.mul(p, w)?; - // To 1/2: a polynomial of `a`. - let mid = e.fused_poly(&ACOS_MID, a)?; - let half = e.c(0.5)?; - let in_mid = e.le(a, half)?; - let r = e.sel(in_mid, mid, r)?; - // To `ACOS_NEAR_END`: `RN(π/2 - a) - a^3 / 6`, fused. - let s = e.mul(a, a)?; - let cube = e.mul(a, s)?; - let h = e.c(f32::from_bits(HALF_PI_BITS))?; - let d = e.sub(h, a)?; - let sixth = e.c(f32::from_bits(0xBE2A_AAAB))?; - let near = e.fused(cube, sixth, d)?; - let end = e.c(f32::from_bits(ACOS_NEAR_END))?; - let in_near = e.le(a, end)?; - let r = e.sel(in_near, near, r)?; - // A negative `x`: `RN(π - r)`. - let pi = e.c(f32::from_bits(PI_BITS))?; - let turned = e.sub(pi, r)?; - let zero = e.c(0.0)?; - let negative = e.lt(x, zero)?; - let r = e.sel(negative, turned, r)?; - // `|x| > 1`: Metal's NaN. - let domain = e.gt(a, one)?; - let nan = e.metal_nan(None)?; - e.sel(domain, nan, r) -} - -/// The generic part of Metal's precise `atan2(y, x)` for finite nonzero normal operands (any -/// other lane's answer is `math::atan2_special`'s, a zero or denormal answer included): Metal's -/// precise `atan` ([`metal_atan`]) of the correctly rounded quotient `q = y / x` ([`E::div`]), and -/// `RN(atan(q) + RN(π))` toward a negative `x`, `RN(atan(q) - RN(π))` where `y` is negative too. -/// Metal's word on every finite normal pair of our probe (16.7 million, the M4) whose answer -/// is normal, wherever the reciprocal in its `atan` is Metal's, which it is at all but 0.012% of -/// them. -pub(crate) fn atan2(e: &mut E<'_, '_>, y: Value, x: Value) -> BResult { - let q = e.div(y, x)?; - let t = metal_atan(e, q)?; - turned(e, t, y, x) -} - -/// `t`, the arc tangent of `y / x`, turned to `atan2(y, x)`'s quadrant: `RN(t + RN(π))` toward a -/// negative `x`, `RN(t - RN(π))` where `y` is negative too, and `t` itself toward a positive -/// one. -fn turned(e: &mut E<'_, '_>, t: Value, y: Value, x: Value) -> BResult { - let pi = e.c(f32::from_bits(PI_BITS))?; - let up = e.add(t, pi)?; - let down = e.sub(t, pi)?; - let zero = e.c(0.0)?; - let below = e.lt(y, zero)?; - let turned = e.sel(below, down, up)?; - let behind = e.lt(x, zero)?; - e.sel(behind, turned, t) -} - -/// `P(s)` of Metal's `half` `atan(a) = a P(a a)` to 1 and `RN(π/2) - t P(t t)` of `t = 1 / a` -/// above, its `f32` coefficients by their bits: read off Metal's words at every `half` (the M3; the -/// M4's, are the same) by a clean-room fit. Horner's rule in `s` (rounded), each step a product and -/// a sum, both rounded. -pub(crate) const HALF_ATAN_P: [u32; 4] = [0x3F7F_F382, 0xBEA7_01E6, 0x3E20_517B, 0xBD38_2B03]; - -/// Metal's `half` `atan(x)` before its rounding to `half`, of a `half` `x` held as `float`: with -/// `a = |x|`, `a P(a a)` of [`HALF_ATAN_P`] to 1, and above it `RN(π/2) - t P(t t)` of the -/// correctly rounded `t = 1 / a` ([`E::div`]; `0` for an infinite `a`), with `x`'s sign, so a zero -/// gives itself. Rounded to `half`, Metal's word at every `half`, whatever the steps' fusion and -/// whether `t` is the quotient or Metal's reciprocal: the form is no closer to any word's rounding -/// edge than that. -pub(crate) fn half_atan(e: &mut E<'_, '_>, x: Value) -> BResult { - let a = e.abs(x)?; - let one = e.c(1.0)?; - let above = e.gt(a, one)?; - // The quotient's divisor is `a` above 1 and 1 elsewhere, so it is finite on every lane - // that reads it; an infinite `a` takes `t = 0`. - let divisor = e.sel(above, a, one)?; - let t = e.div(one, divisor)?; - let max = e.c(f32::MAX)?; - let infinite = e.gt(a, max)?; - let zero = e.c(0.0)?; - let t = e.sel(infinite, zero, t)?; - let t = e.sel(above, t, a)?; - let s = e.mul(t, t)?; - let p = half_atan_p(e, s)?; - let core = e.mul(t, p)?; - let h = e.c(f32::from_bits(HALF_PI_BITS))?; - let far = e.sub(h, core)?; - let r = e.sel(above, far, core)?; - e.copysign(r, x) -} - -/// [`HALF_ATAN_P`] at `s`. -fn half_atan_p(e: &mut E<'_, '_>, s: Value) -> BResult { - let c = HALF_ATAN_P.map(f32::from_bits); - e.horner(&c, s) -} - -/// Metal's `half` `atan2(y, x)` before its rounding to `half`, of finite nonzero `half` operands -/// held as `float` (any other lane's answer is `math::atan2_special`'s): [`half_atan`] of the -/// correctly rounded quotient `q = y / x` ([`E::div`], normal for every such pair), turned to the -/// quadrant as the precise `atan2` is (`RN(π)` added toward a negative `x`, subtracted where `y` is -/// negative too). Rounded to `half`, Metal's word at every such pair of our probe (65,536 -/// pairs; the M4's words are the same). -pub(crate) fn half_atan2(e: &mut E<'_, '_>, y: Value, x: Value) -> BResult { - let q = e.div(y, x)?; - let t = half_atan(e, q)?; - turned(e, t, y, x) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/exp.rs b/crates/metal2vulkan/src/lower/arith/libm/exp.rs deleted file mode 100644 index d97d16ee3..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/exp.rs +++ /dev/null @@ -1,247 +0,0 @@ -//! The exponentials: Metal's `exp2` of a `float`, its precise `exp` and `exp10` (MSL Table 8.1 -//! bounds each at 4 ulp), and the growth step they and `powr` share. -//! -//! **Metal's `exp2`** ([`exp2`]): what Metal's hardware computes, measured on every `float` operand -//! of the Apple M4 and on 2^24 of the M3, which answers alike. An operand below `2^-23` in -//! magnitude reads as 0, and a NaN gives `0x7fc00000`. Otherwise `k = floor(x 2^23)` exactly, -//! `n = k >> 23` and `f = k mod 2^23`, and the answer is `2^n (1 + T(f) 2^-23)`: `+0` where its -//! exponent field would be 0 or below (Metal flushes a denormal result: `exp2(-127)` is `+0`), -//! `+inf` from 255. `T` is the 23-bit fraction of a cubic per 32nd of `f`, which [`TABLE`] gives as -//! Horner's rule in fixed point with each product truncated: it answers Metal's `T` at 8,380,655 of -//! the 2^23 fractions (99.905 %), and its word is one unit of the last place off at the other -//! 7,953, which no fixed-point form tried reproduces (an open near-equivalent). -//! -//! **Metal's precise `exp` and `exp10`** ([`exp_base`]): Metal's own composition of its `exp2`, -//! measured on every lane of case 7b283404 on the M3 and the M4, and on every operand of -//! magnitude `[2^-40, 2^9)` whose answer is normal on the M4: `E = exp2(p)` -//! of the rounded product `p = x c_hi` (`c_hi + c_lo` the constant `log2(e)` or `log2(10)`), -//! corrected by the product's error `d = fma(x, c_lo, fma(x, c_hi, -p))` as the fused -//! `fma(E, RN(d ln 2), E)`, and `E` itself where it is `+inf`, `+0`, or a NaN. Each fused step is -//! exact on every device ([`E::fused`], [`fused_growth`]). -//! -//! **Metal's growth step** ([`grown`]): `fma(E, t, E)` of a power `E` of its `exp2` and a small -//! correction `t`, which its `exp`, `exp10`, and `powr` take, exact on every device. - -use crate::lower::arith::libm::pair::constant; -use crate::lower::arith::libm::E; -use crate::spirv::builder::ModuleBuilder; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, Value}; -use crate::spirv::ir::{BinOp, MemAccess}; -use std::f64::consts::{LN_2, LOG2_10, LOG2_E}; - -/// Metal's `exp2` table ([`exp2`]): for each 32nd `s` of the fraction `f`, the fixed-point -/// coefficients `[c0, c1, c2, c3]` of the cubic that gives `T(f)` of the offset `t = f mod 2^18`, -/// by Horner's rule with each product truncated: `u2 = c2 + (c3 t >> 18)`, -/// `u1 = c1 + (u2 t >> 18)`, `Y = c0 + (u1 t >> 18)`, and `T = Y >> 9`. Each `Y` is below `2^32` -/// (the largest is `0xfffffef0`, at the last fraction; every coefficient is positive, so `Y` grows -/// with `t`), `c3 t` below `2^32`, and `u2 t` and `u1 t` below `2^39` and `2^46`. Fitted to Metal's -/// `T` on every fraction: equal at 8,380,655 of 2^23. -pub(crate) const TABLE: [[u32; 4]; 32] = [ - [0x0000_01B8, 0x058B_90BC, 0x000F_5F93, 0x0000_1CF2], - [0x059B_0EF9, 0x05AA_A5FA, 0x000F_B693, 0x0000_1CF3], - [0x0B55_8879, 0x05CA_6A3A, 0x0010_0E12, 0x0000_1DF4], - [0x1130_1EB9, 0x05EA_E03B, 0x0010_678F, 0x0000_1EF6], - [0x172B_8599, 0x060C_0BB9, 0x0010_C495, 0x0000_1EF2], - [0x1D48_74D9, 0x062D_F1B8, 0x0011_2218, 0x0000_1FF0], - [0x2387_A898, 0x0650_9600, 0x0011_8189, 0x0000_20F8], - [0x29E9_E119, 0x0673_FBB9, 0x0011_E494, 0x0000_20F3], - [0x306F_E259, 0x0698_283F, 0x0012_4882, 0x0000_2200], - [0x371A_7539, 0x06BD_1FB8, 0x0012_AE97, 0x0000_22F1], - [0x3DEA_667A, 0x06E2_E632, 0x0013_1720, 0x0000_23ED], - [0x44E0_87D9, 0x0709_7FBC, 0x0013_8389, 0x0000_23FC], - [0x4BFD_AF19, 0x0730_F279, 0x0013_F091, 0x0000_24F7], - [0x5342_B718, 0x0759_4282, 0x0014_6000, 0x0000_2600], - [0x5AB0_7F98, 0x0782_7441, 0x0014_D204, 0x0000_26FC], - [0x6247_EC99, 0x07AC_8D76, 0x0015_461D, 0x0000_27ED], - [0x6A09_E819, 0x07D7_91B6, 0x0015_BD9F, 0x0000_28EA], - [0x71F7_6039, 0x0803_87B9, 0x0016_3713, 0x0000_29F4], - [0x7A11_48F9, 0x0830_7339, 0x0016_B514, 0x0000_29F3], - [0x8258_9B58, 0x085E_5B7E, 0x0017_340E, 0x0000_2AF5], - [0x8ACE_55D9, 0x088D_44F8, 0x0017_B615, 0x0000_2BF3], - [0x9373_7CD8, 0x08BD_34FF, 0x0018_3B07, 0x0000_2CFC], - [0x9C49_19F9, 0x08EE_31F9, 0x0018_C312, 0x0000_2DF5], - [0xA550_3CD9, 0x0920_41F8, 0x0019_4D95, 0x0000_2EF3], - [0xAE89_FB59, 0x0953_69FA, 0x0019_DB91, 0x0000_2FF5], - [0xB7F7_70F8, 0x0987_B0FD, 0x001A_6C8E, 0x0000_30F6], - [0xC199_BF79, 0x09BD_1D76, 0x001B_009E, 0x0000_31EB], - [0xCB72_0F79, 0x09F3_B576, 0x001B_969C, 0x0000_33EE], - [0xD581_8F78, 0x0A2B_7EFD, 0x001C_318D, 0x0000_34F7], - [0xDFC9_74F9, 0x0A64_80F5, 0x001C_D01F, 0x0000_35EC], - [0xEA4A_FBD9, 0x0A9E_C2F4, 0x001D_71A0, 0x0000_36EC], - [0xF507_6779, 0x0ADA_4B32, 0x001E_1727, 0x0000_37E6], -]; - -/// An upper estimate of the SPIR-V words of [`TABLE`] in a module: its 128 constants, the -/// composite, and the array, pointer, and variable. -pub(crate) const TABLE_WORDS: u32 = 128 * 4 + 131 + 24; - -/// Declare [`TABLE`] in the module: a `Private` `u32[128]` initialized to the coefficients, `s`'s -/// four from word `4 s`. -pub(crate) fn declare(mb: &mut ModuleBuilder) -> BResult { - super::declare_words(mb, TABLE.as_flattened()) -} - -/// The magnitude past which Metal's `exp2` is `+0` or `+inf`: [`exp2`] clamps its operand to it. -pub(crate) const LIMIT: f32 = 200.0; - -/// `(a b) >> 18` of `u32` values `a` and `b` whose product is below `2^50`. -fn product_shifted(e: &mut E<'_, '_>, a: Value, b: Value) -> BResult { - let (lo, hi) = e.umul(a, b)?; - let (k14, k18) = (e.u(14)?, e.u(18)?); - let hi = e.iop(BinOp::ShiftLeftLogical, hi, k14)?; - let lo = e.iop(BinOp::ShiftRightLogical, lo, k18)?; - e.iop(BinOp::BitwiseOr, hi, lo) -} - -/// Metal's `exp2(x)` (the module docs): the reduction exact on `float`s (`x 2^23` and its floor, -/// `n = floor(k 2^-23)`, and `f = k - n 2^23`, each exact; `x` clamped to `[-200, 200]` first, -/// where `n` is past the flush and the infinity both ways), and `T` of [`TABLE`] on `u32`s. -pub(crate) fn exp2(e: &mut E<'_, '_>, x: Value) -> BResult { - let table = e.exp2_table()?; - let nan = e.is_nan(x)?; - let zero = e.c(0.0)?; - let ax = e.abs(x)?; - let tiny = e.c(f32::EPSILON)?; - let tiny = e.lt(ax, tiny)?; - let x = e.sel(tiny, zero, x)?; - let x = e.sel(nan, zero, x)?; - let (x, _) = e.clamp(x, LIMIT)?; - let (up, down) = (e.c(8_388_608.0)?, e.c(1.0 / 8_388_608.0)?); - let k = e.mul(x, up)?; - let k = e.floor(k)?; - let n = e.mul(k, down)?; - let n = e.floor(n)?; - let whole = e.mul(n, up)?; - let f = e.sub(k, whole)?; - let f = e.utrunc(f)?; - // `n + 256`, in `[56, 456]`. - let offset = e.c(256.0)?; - let n = e.add(n, offset)?; - let n = e.utrunc(n)?; - let (k2, k9, k18, k23) = (e.u(2)?, e.u(9)?, e.u(18)?, e.u(23)?); - let s = e.iop(BinOp::ShiftRightLogical, f, k18)?; - let low = e.u(0x3_FFFF)?; - let t = e.iop(BinOp::BitwiseAnd, f, low)?; - let first = e.iop(BinOp::ShiftLeftLogical, s, k2)?; - let base = e.fb.module().global_value(table)?; - let coefficient = |e: &mut E<'_, '_>, j: u32| -> BResult { - let j = e.u(j)?; - let i = e.iop(BinOp::IAdd, first, j)?; - let p = e.fb.access_chain(base, &[i])?; - e.fb.load(p, MemAccess::default()) - }; - let c3 = coefficient(e, 3)?; - let p3 = e.iop(BinOp::IMul, c3, t)?; - let p3 = e.iop(BinOp::ShiftRightLogical, p3, k18)?; - let c2 = coefficient(e, 2)?; - let u2 = e.iop(BinOp::IAdd, c2, p3)?; - let p2 = product_shifted(e, u2, t)?; - let c1 = coefficient(e, 1)?; - let u1 = e.iop(BinOp::IAdd, c1, p2)?; - let p1 = product_shifted(e, u1, t)?; - let c0 = coefficient(e, 0)?; - let y = e.iop(BinOp::IAdd, c0, p1)?; - let fraction = e.iop(BinOp::ShiftRightLogical, y, k9)?; - // The exponent field `n + 127`: `+0` where it is 0 or below, `+inf` from 255. - let (bias, top) = (e.u(129)?, e.u(384)?); - let field = e.iop(BinOp::ISub, n, bias)?; - let field = e.iop(BinOp::ShiftLeftLogical, field, k23)?; - let r = e.iop(BinOp::BitwiseOr, field, fraction)?; - let under = e.iop(BinOp::ULessThanEqual, n, bias)?; - let over = e.iop(BinOp::UGreaterThanEqual, n, top)?; - let (inf, flushed, quiet) = (e.u(0x7F80_0000)?, e.u(0)?, e.u(super::METAL_NAN)?); - let r = e.sel(over, inf, r)?; - let r = e.sel(under, flushed, r)?; - let r = e.sel(nan, quiet, r)?; - e.float(r) -} - -/// `fma(m, t, m)`, `m (1 + t)` rounded once, for a positive normal `m` and `|t|` below `2^-8`, on -/// every device and without a fused operation: on `m`'s significand `M` in `[1, 2)`, the exact -/// product `M t = y + y_err` ([`E::two_prod`]) rounded to odd ([`E::odd`]), and `RN(M + o)`, -/// which is `RN(M + M t)`: `o` lies on a grid at least 2^-30 fine, so `M + o` is on the same side -/// of each midpoint of the result's grid as `M + M t`, and on none where that is not on one -/// (Boldo and Melquiond's rounding to odd). Then `m`'s exponent back on the bits: `+inf` past the -/// largest finite `float`, `+0` below `2^-126`. A product below `2^-100`, whose error -/// [`E::exact_error`] may not give exactly, leaves `M` unchanged either way. Unlike -/// [`E::fused`], the scaling keeps it exact where `m t` would underflow. -fn fused_growth(e: &mut E<'_, '_>, m: Value, t: Value) -> BResult { - let mb = e.bits(m)?; - let (fraction, one) = (e.u(0x007F_FFFF)?, e.u(0x3F80_0000)?); - let mm = e.iop(BinOp::BitwiseAnd, mb, fraction)?; - let mm = e.iop(BinOp::BitwiseOr, mm, one)?; - let mm = e.float(mm)?; - let (y, y_err) = e.two_prod(mm, t)?; - let o = e.odd(y, y_err)?; - let r = e.add(mm, o)?; - let rb = e.bits(r)?; - let k23 = e.u(23)?; - let mf = e.iop(BinOp::ShiftRightLogical, mb, k23)?; - let rf = e.iop(BinOp::ShiftRightLogical, rb, k23)?; - // The result's exponent field plus 127. - let sum = e.iop(BinOp::IAdd, mf, rf)?; - let scale = e.iop(BinOp::ShiftLeftLogical, mf, k23)?; - let bias = e.u(127 << 23)?; - let out = e.iop(BinOp::IAdd, rb, scale)?; - let out = e.iop(BinOp::ISub, out, bias)?; - let (top, bottom) = (e.u(382)?, e.u(127)?); - let over = e.iop(BinOp::UGreaterThanEqual, sum, top)?; - let under = e.iop(BinOp::ULessThanEqual, sum, bottom)?; - let (inf, zero) = (e.u(0x7F80_0000)?, e.u(0)?); - let out = e.sel(over, inf, out)?; - let out = e.sel(under, zero, out)?; - e.float(out) -} - -/// Metal's precise `exp(x)` (`ten` false) or `exp10(x)` (`ten` true), as Metal composes it of its -/// `exp2` (the module docs): `fma(E, RN(d ln 2), E)` of `d = fma(x, c_lo, fma(x, c_hi, -p))`, -/// both fused steps exact where they decide the answer (`x c_hi` above `2^-100`; below, `E` is 1 -/// and the answer 1). -pub(crate) fn exp_base(e: &mut E<'_, '_>, x: Value, ten: bool) -> BResult { - composed(e, x, ten, false) -} - -/// `e^x / 2` as Metal's `sinh` and `cosh` form it for `x` from 1.5 on: [`exp_base`]'s composition -/// of `E = exp2(p - 1)`, so it is finite up to 89.4. It is exactly half of [`exp_base`]'s answer -/// wherever that is finite (the composition scales exactly), and up to 89.4 it is an open -/// near-equivalent (Metal's word on 62 % of those operands, the rest one or two units of the last -/// place off). -pub(crate) fn exp_half(e: &mut E<'_, '_>, x: Value) -> BResult { - composed(e, x, false, true) -} - -/// [`exp_base`] and [`exp_half`]: `p - 1` is exact for every `p` from 1 on, where `exp_half`'s -/// answer is used. -fn composed(e: &mut E<'_, '_>, x: Value, ten: bool, halved: bool) -> BResult { - let (hi, lo) = constant(if ten { LOG2_10 } else { LOG2_E }); - let hi = e.c(hi)?; - let p = e.mul(x, hi)?; - let err = e.exact_error(x, hi, p)?; - let lo = e.c(lo)?; - let d = e.fused(x, lo, err)?; - let p = if halved { - let one = e.c(1.0)?; - e.sub(p, one)? - } else { - p - }; - let big = exp2(e, p)?; - let ln2 = e.c(LN_2 as f32)?; - let t = e.mul(d, ln2)?; - grown(e, big, t) -} - -/// `fma(E, t, E)` of a value `E` of Metal's [`exp2`] and `|t|` below `2^-8` (or any `t` where `E` -/// is `+inf` or `+0`), as Metal grows its `exp2` in its `exp`, `exp10`, and `powr` -/// ([`fused_growth`]), and `E` itself where it is `+inf`, `+0`, or a NaN. -pub(crate) fn grown(e: &mut E<'_, '_>, big: Value, t: Value) -> BResult { - let r = fused_growth(e, big, t)?; - let b = e.bits(big)?; - let (field, zero) = (e.u(0x7F80_0000)?, e.u(0)?); - let top = e.iop(BinOp::BitwiseAnd, b, field)?; - let top = e.iop(BinOp::IEqual, top, field)?; - let flushed = e.iop(BinOp::IEqual, b, zero)?; - let ends = e.iop(BinOp::LogicalOr, top, flushed)?; - e.sel(ends, big, r) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/fmod.rs b/crates/metal2vulkan/src/lower/arith/libm/fmod.rs index 9d026e0bf..28dc28b45 100644 --- a/crates/metal2vulkan/src/lower/arith/libm/fmod.rs +++ b/crates/metal2vulkan/src/lower/arith/libm/fmod.rs @@ -19,9 +19,7 @@ //! **Denormal operands**, as Metal reads them (case 087758cb): a denormal dividend as itself //! (`fmod(2^-149, -1) = 2^-149`, `fmod(2^-127, 8) = 2^-127`) and a denormal divisor as a zero //! (`fmod(2, 2^-149)` and `fmod(-6588397.5, 2^-149)` are NaN), decided on the divisor's exponent -//! field, so the answer is Metal's whatever the device's denormal mode. The reading is per -//! operand, so it lives here rather than in the per-operation table ([`denormal::operand`], which -//! has no `fmod` row). +//! field, so the answer is Metal's whatever the device's denormal mode. use crate::lower::arith::libm::E; use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec}; @@ -29,9 +27,6 @@ use crate::spirv::error::BResult; use crate::spirv::ids::Value; use crate::spirv::ir::{BinOp, MemAccess, Type, UnOp}; -#[cfg(doc)] -use crate::lower::arith::denormal; - /// The significand `M` and the biased exponent `E` (at least 1) of the magnitude bits `a` of a /// finite `float`. fn parts(e: &mut E<'_, '_>, a: Value) -> BResult<(Value, Value)> { @@ -115,7 +110,7 @@ pub(crate) fn fmod(e: &mut E<'_, '_>, x: Value, y: Value) -> BResult { let domain = e.iop(BinOp::LogicalOr, x_nonfinite, y_zero)?; let no_nan = e.fb.unary(UnOp::LogicalNot, any_nan)?; let domain = e.iop(BinOp::LogicalAnd, domain, no_nan)?; - let metal = e.metal_nan(None)?; + let metal = e.metal_nan()?; let nan = e.sel(domain, metal, nan)?; e.sel(nan_lane, nan, rem) } diff --git a/crates/metal2vulkan/src/lower/arith/libm/hyper.rs b/crates/metal2vulkan/src/lower/arith/libm/hyper.rs deleted file mode 100644 index 2d8998e68..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/hyper.rs +++ /dev/null @@ -1,438 +0,0 @@ -//! The hyperbolic functions and their inverses: Metal's precise `sinh`, `cosh`, `tanh`, `asinh`, -//! `acosh`, and `atanh` of a `float`, which MSL Table 8.1 bounds at 4, 4, 5, 4, 4, and 5 ulp. Each -//! is Metal's own form, which matches Metal's measured words and follows Apple's runtime library: -//! polynomials near zero and in the middle ranges, then compositions of Metal's precise `exp` -//! ([`exp::exp_base`]), `log2` ([`log::metal_log2`], with its table), and reciprocal -//! ([`E::recip`]). -//! -//! - `sinh` and `cosh` ([`hyper`]): polynomials below 1.5, `(E ∓ 1/E) / 2` of `E = e^a` to -//! `12 ln 2`, and `e^a / 2` past it; -//! - `tanh`: a polynomial of `s = a^2` below 0.35, one of `a` ([`TANH_MIDDLE`]) to 1.25, `(t - 1) -//! (1 / (t + 1))` of `t = e^(2a)` below `12 ln 2`, and 1 from it; -//! - `asinh` ([`arc`]): the operand below [`ASINH_TINY`], `a Q(a^2)` ([`ASINH_NEAR`]) below 0.35, -//! a polynomial of `a` ([`ASINH_MIDDLE`]) below 1.5, `RN(RN(log2(w)) RN(ln 2))` of `w = RN(a + -//! RN(z rsqrt(z)))` with `z = RN(a^2 + 1)` fused below 500, and `RN(RN(RN(log2(a)) RN(ln 2)) + -//! RN(ln 2))` from 500; -//! - `acosh`: `L + RN(err rcp(w))` of the same `w = RN(q + x)` with `q = RN(z rsqrt(z))` and `z = -//! RN(RN(x - 1) RN(x + 1))`, `err = q - (w - x)` the sum's rounding error, and `L` the -//! polynomial `t P(t)` of `t = w - 1` ([`ACOSH_LOG1P`]) for `w` in `[1.0154, 1.2811)`, else -//! `RN(RN(log2(w)) RN(ln 2))`; from [`ACOSH_LARGE`] on, the `log2(x)` form above; -//! - `atanh`: the operand to [`ATANH_TINY`], a polynomial of `a` ([`ATANH_NEAR`]) to 1/4, and -//! `RN(RN(log2(q)) RN(ln 2)) / 2` of `q = RN(RN(1 + a) rcp(RN(1 - a)))` above. -//! -//! The polynomials are Horner's rule from the highest coefficient, each step one fused -//! multiply-add, their `f32` coefficients by their bits, lowest first. Metal's word at every -//! operand where its hardware's primitives are the models': its `log2` and reciprocal are fitted -//! models (a unit off at a few lanes), and so is the hardware's inverse root that its `asinh` and -//! `acosh` take ([`E::fast_rsqrt`], Metal's word at 99.82 % of `[1, 4)`): with it `asinh` is -//! Metal's word at 99.86 % of `[1.5, 4)` and `acosh` at 99.87 % of `[1, 16)` (98.67 % and 98.81 % -//! with the correctly rounded root). -//! -//! Metal's precise functions return a denormal operand itself (case 7b283404), as `sinh` and -//! `tanh` do, and `cosh` of one is `1`. The odd functions take the operand's sign at the end. -//! Metal's values at the special operands (case 7b283404, every lane): `sinh(±inf) = ±inf`, -//! `cosh(±inf) = +inf`, `tanh(±inf) = ±1`, `asinh(±inf) = ±inf`, `acosh(+inf) = +inf`, `atanh(±1) -//! = ±inf`; `acosh` below 1 (a zero and a denormal among them) and `atanh` beyond 1 answer -//! Metal's NaN `0x7fc00000`, and a NaN operand a NaN. -//! -//! Metal's fast `asinh` and `acosh` ([`fast_arc`]) and its `half` `asinh` ([`half_asinh`]) are -//! their own shorter forms: `log2` of a sum the hardware's inverse root's product is fused into. - -use crate::lower::arith::libm::exp; -use crate::lower::arith::libm::log; -use crate::lower::arith::libm::E; -use crate::spirv::error::BResult; -use crate::spirv::ids::Value; -use crate::spirv::ir::{BinOp, UnOp}; - -/// Metal's polynomials near zero: `1 + s q(s)` of `s = x x` by Horner's rule, -/// each step one fused multiply-add, `q`'s `f32` coefficients by their bits. `sinh(x) = x (1 + s -/// q)` and `cosh(x) = 1 + s q` below 1.5 in magnitude, `tanh(x) = x (1 + s q)` below 0.35. -pub(crate) const SINH_Q: [u32; 4] = [0x3E2A_AAA8, 0x3C08_894C, 0x394F_C8DE, 0x3642_2719]; -pub(crate) const COSH_Q: [u32; 4] = [0x3EFF_FFF3, 0x3D2A_AC9E, 0x3AB5_B161, 0x37DC_86D5]; -pub(crate) const TANH_Q: [u32; 5] = [ - 0xBEAA_AAAB, - 0x3E08_8889, - 0xBD5D_0DD3, - 0x3CB3_280E, - 0xBC11_3C58, -]; - -/// Metal's `tanh(a)` from 0.35 to 1.25: a polynomial of degree 8 in `a`. -pub(crate) const TANH_MIDDLE: [u32; 9] = [ - 0xB95D_6161, - 0x3F80_668A, - 0xBCA5_F7E6, - 0xBE84_2FE5, - 0xBE33_C007, - 0x3ECC_0D09, - 0xBE80_CAEC, - 0x3D98_DFD6, - 0xBC13_2FA1, -]; - -/// Metal's `asinh(a)` from [`ASINH_TINY`] to 0.35: `a Q(a^2)`, `Q` of degree 3. -pub(crate) const ASINH_NEAR: [u32; 4] = [0x3F7F_FFFF, 0xBE2A_A75C, 0x3D98_9340, 0xBD1B_89C2]; - -/// Metal's `asinh(a)` from 0.35 to 1.5: a polynomial of degree 8 in `a`. -pub(crate) const ASINH_MIDDLE: [u32; 9] = [ - 0x39A6_3B75, - 0x3F7F_0E87, - 0x3C8F_A3F1, - 0xBE56_5E46, - 0x3D4C_6073, - 0x3D93_5FC0, - 0xBD83_E03D, - 0x3CB3_FAF1, - 0xBB3C_F9B9, -]; - -/// Metal's `log(w)` next to 1 in its `acosh`: `t P(t)` of `t = w - 1`, `P` of degree 5. -pub(crate) const ACOSH_LOG1P: [u32; 6] = [ - 0x3F7F_FFFE, - 0xBEFF_FEA0, - 0x3EAA_837C, - 0xBE7C_1408, - 0x3E33_542C, - 0xBDA9_125E, -]; - -/// Metal's `atanh(a)` from [`ATANH_TINY`] to 1/4: a polynomial of degree 7 in `a`. -pub(crate) const ATANH_NEAR: [u32; 8] = [ - 0xAEE6_1A7E, - 0x3F80_0000, - 0xB658_5560, - 0x3EAA_B74B, - 0xBAB8_927B, - 0x3E58_0007, - 0xBD36_5927, - 0x3E63_29B2, -]; - -/// To these magnitudes (bits) Metal's `sinh` and `tanh` are the operand and its `cosh` is 1. -pub(crate) const SINH_TINY: u32 = 0x3A85_2018; -pub(crate) const TANH_TINY: u32 = 0x3A38_9BA2; -pub(crate) const COSH_TINY: u32 = 0x3A35_04F2; - -/// Below 1.5 `sinh` and `cosh` are their polynomials; below 0.35 `tanh` is [`TANH_Q`]'s. -pub(crate) const POLY_END: u32 = 0x3FC0_0000; -pub(crate) const TANH_POLY_END: u32 = 0x3EB3_3333; - -/// Past 1.25 `tanh` is `(t - 1) / (t + 1)` of `t = e^(2a)`; to it, [`TANH_MIDDLE`]. -pub(crate) const TANH_QUOTIENT: u32 = 0x3FA0_0000; - -/// `12 ln 2`: past it `sinh` and `cosh` are `e^a / 2`, and from it `tanh` is 1. -pub(crate) const HALF_EXP: u32 = 0x4105_1592; - -/// Below this magnitude (bits) Metal's `asinh` is its operand. -pub(crate) const ASINH_TINY: u32 = 0x3A8F_950B; - -/// Below this magnitude (bits, the `float` below 0.35) `asinh` is [`ASINH_NEAR`]'s. -pub(crate) const ASINH_NEAR_END: u32 = 0x3EB3_3332; - -/// From this magnitude (bits, 1.5) `asinh` is its root form; below, [`ASINH_MIDDLE`]'s. -pub(crate) const ASINH_ROOT: u32 = 0x3FC0_0000; - -/// From this magnitude `asinh` is `log(a) + log(2)` of its `log2`. -pub(crate) const ASINH_LARGE: f32 = 500.0; - -/// From this operand (bits, 1750.2775) `acosh` is `log(x) + log(2)` of its `log2`. -pub(crate) const ACOSH_LARGE: u32 = 0x44DA_C8E0; - -/// `acosh`'s `w` from this (bits) below [`ACOSH_LOG1P_END`] takes [`ACOSH_LOG1P`]. -pub(crate) const ACOSH_LOG1P_START: u32 = 0x3F81_F7F1; -pub(crate) const ACOSH_LOG1P_END: u32 = 0x3FA3_FC0B; - -/// To this magnitude (bits) Metal's `atanh` is its operand. -pub(crate) const ATANH_TINY: u32 = 0x3A40_0000; - -/// Above this magnitude Metal's `atanh` is its form of its `log2` and reciprocal. -pub(crate) const ATANH_FORM: f32 = 0.25; - -/// Which hyperbolic function a routine answers. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Hyper { - Sinh, - Cosh, - Tanh, -} - -/// Which inverse hyperbolic function a routine answers. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Arc { - Asinh, - Acosh, - Atanh, -} - -/// Which of Metal's fast inverse hyperbolic functions [`fast_arc`] answers. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum FastArc { - Asinh, - Acosh, -} - -/// `1 + s q(s)` of [`SINH_Q`], [`COSH_Q`], or [`TANH_Q`]. -fn near_zero(e: &mut E<'_, '_>, q: &[u32], s: Value) -> BResult { - let acc = e.fused_poly(q, s)?; - let one = e.c(1.0)?; - e.fused(acc, s, one) -} - -/// Whether the magnitude's bits `ab` are below `bits` (`ab` of a NaN is above every bound). -fn below(e: &mut E<'_, '_>, ab: Value, bits: u32) -> BResult { - let b = e.u(bits)?; - e.iop(BinOp::ULessThan, ab, b) -} - -/// Metal's precise `which` of `x` (`tanh`'s middle range): -/// - `sinh` and `cosh`: the operand (`sinh`) or 1 (`cosh`) to [`SINH_TINY`] / [`COSH_TINY`], -/// their polynomials below 1.5, `(E - 1/E) / 2` and `(E + 1/E) / 2` of `E = e^a` to `12 ln 2`, -/// and past it `e^a / 2` ([`exp::exp_half`], so `2 h` is [`exp::exp_base`]'s `E`); -/// - `tanh`: the operand to [`TANH_TINY`], its polynomial below 0.35, [`TANH_MIDDLE`] to 1.25, -/// `(t - 1) (1 / (t + 1))` of `t = e^(2a)` below `12 ln 2`, and 1 from it. -/// -/// Each `1 / E` and `1 / (t + 1)` is Metal's reciprocal ([`E::recip`]). With Metal's own reciprocal -/// these forms are Metal's word at every operand of `[1.5, 8)` (`sinh`, `cosh`) and `(1.25, 12 ln -/// 2)` (`tanh`); with the model's they miss 520, 512, and 83,177 of those 20,971,520, 20,971,520, -/// and 23,401,873 operands (an open near-equivalent), where the correctly rounded reciprocal missed -/// 18,099, 17,989, and 2,390,824. -pub(crate) fn hyper(e: &mut E<'_, '_>, which: Hyper, x: Value) -> BResult { - let a = e.abs(x)?; - let ab = e.bits(a)?; - let s = e.mul(a, a)?; - let one = e.c(1.0)?; - let r = match which { - Hyper::Sinh | Hyper::Cosh => { - let sinh = which == Hyper::Sinh; - let h = exp::exp_half(e, a)?; - let big = e.add(h, h)?; - let inv = e.recip(big)?; - let mid = if sinh { - e.sub(big, inv)? - } else { - e.add(big, inv)? - }; - let half = e.c(0.5)?; - let mid = e.mul(half, mid)?; - let far = below(e, ab, HALF_EXP + 1)?; - let r = e.sel(far, mid, h)?; - let p = near_zero(e, if sinh { &SINH_Q } else { &COSH_Q }, s)?; - let (near, tiny, tiny_bits) = if sinh { - (e.mul(a, p)?, a, SINH_TINY) - } else { - (p, one, COSH_TINY) - }; - let poly = below(e, ab, POLY_END)?; - let r = e.sel(poly, near, r)?; - let small = below(e, ab, tiny_bits + 1)?; - e.sel(small, tiny, r)? - } - Hyper::Tanh => { - let top = e.c(f32::from_bits(HALF_EXP))?; - let over = e.gt(a, top)?; - let ac = e.sel(over, top, a)?; - let a2 = e.add(ac, ac)?; - let t = exp::exp_base(e, a2, false)?; - let tm = e.sub(t, one)?; - let tp = e.add(t, one)?; - let inv = e.recip(tp)?; - let quot = e.mul(tm, inv)?; - let ones = below(e, ab, HALF_EXP)?; - let r = e.sel(ones, quot, one)?; - let middle = e.fused_poly(&TANH_MIDDLE, a)?; - let quotient = below(e, ab, TANH_QUOTIENT + 1)?; - let r = e.sel(quotient, middle, r)?; - let p = near_zero(e, &TANH_Q, s)?; - let near = e.mul(a, p)?; - let poly = below(e, ab, TANH_POLY_END)?; - let r = e.sel(poly, near, r)?; - let small = below(e, ab, TANH_TINY + 1)?; - e.sel(small, a, r)? - } - }; - let r = if which == Hyper::Cosh { - r - } else { - e.copysign(r, x)? - }; - let nan = e.is_nan(x)?; - e.sel(nan, x, r) -} - -/// `RN(RN(log2(v)) RN(ln 2))`, and past the switch `large` `RN(that + RN(ln 2))` of `far` -/// instead: one `log2`, of the selected argument. -fn ln_or_twice(e: &mut E<'_, '_>, large: Value, v: Value, far: Value) -> BResult<(Value, Value)> { - let arg = e.sel(large, far, v)?; - let l2 = log::metal_log2(e, arg)?; - let ln2 = e.c(f32::from_bits(log::LN_2_BITS))?; - let m = e.mul(l2, ln2)?; - let twice = e.add(m, ln2)?; - Ok((m, twice)) -} - -/// Metal's precise `which` of `x`: see the module's list. -pub(crate) fn arc(e: &mut E<'_, '_>, which: Arc, x: Value) -> BResult { - let one = e.c(1.0)?; - let zero = e.c(0.0)?; - let a = e.abs(x)?; - let ab = e.bits(a)?; - match which { - Arc::Asinh => { - let z = e.fused(a, a, one)?; - let rz = e.fast_rsqrt(z)?; - let q = e.mul(z, rz)?; - let w = e.add(a, q)?; - let top = e.c(ASINH_LARGE)?; - let large = e.ge(a, top)?; - let (m, twice) = ln_or_twice(e, large, w, a)?; - let r = e.sel(large, twice, m)?; - let middle = e.fused_poly(&ASINH_MIDDLE, a)?; - let in_middle = below(e, ab, ASINH_ROOT)?; - let r = e.sel(in_middle, middle, r)?; - let s = e.mul(a, a)?; - let p = e.fused_poly(&ASINH_NEAR, s)?; - let near = e.mul(p, a)?; - let is_near = below(e, ab, ASINH_NEAR_END)?; - let r = e.sel(is_near, near, r)?; - let tiny = below(e, ab, ASINH_TINY)?; - let r = e.sel(tiny, a, r)?; - let r = e.copysign(r, x)?; - let nan = e.is_nan(x)?; - e.sel(nan, x, r) - } - Arc::Acosh => { - // `q = z rsqrt(z)` is `sqrt(z)`; at `x = 1` (`z = 0`) it is 0. - let down = e.sub(x, one)?; - let up = e.add(x, one)?; - let z = e.mul(down, up)?; - let rz = e.fast_rsqrt(z)?; - let q = e.mul(z, rz)?; - let at_one = e.fb.binary(BinOp::FOrdEqual, z, zero)?; - let q = e.sel(at_one, zero, q)?; - let w = e.add(q, x)?; - let back = e.sub(w, x)?; - let err = e.sub(q, back)?; - let top = e.c(f32::from_bits(ACOSH_LARGE))?; - let large = e.ge(x, top)?; - let (m, twice) = ln_or_twice(e, large, w, x)?; - let t = e.sub(w, one)?; - let p = e.fused_poly(&ACOSH_LOG1P, t)?; - let near = e.mul(t, p)?; - let wb = e.bits(w)?; - let start = e.u(ACOSH_LOG1P_START)?; - let offset = e.iop(BinOp::ISub, wb, start)?; - let span = e.u(ACOSH_LOG1P_END - ACOSH_LOG1P_START)?; - let is_near = e.iop(BinOp::ULessThan, offset, span)?; - let l = e.sel(is_near, near, m)?; - let rw = e.recip(w)?; - let tail = e.mul(err, rw)?; - let root = e.add(l, tail)?; - let r = e.sel(large, twice, root)?; - let below_one = e.lt(x, one)?; - let nan = e.metal_nan(None)?; - let r = e.sel(below_one, nan, r)?; - let x_nan = e.is_nan(x)?; - e.sel(x_nan, x, r) - } - Arc::Atanh => { - let half = e.c(0.5)?; - let up = e.add(one, a)?; - let down = e.sub(one, a)?; - let rd = e.recip(down)?; - let q = e.mul(up, rd)?; - let l2 = log::metal_log2(e, q)?; - let ln2 = e.c(f32::from_bits(log::LN_2_BITS))?; - let m = e.mul(l2, ln2)?; - let m = e.mul(m, half)?; - let near = e.fused_poly(&ATANH_NEAR, a)?; - let quarter = e.c(ATANH_FORM)?; - let formed = e.gt(a, quarter)?; - let r = e.sel(formed, m, near)?; - let inf = e.c(f32::INFINITY)?; - let at_one = e.fb.binary(BinOp::FOrdEqual, a, one)?; - let r = e.sel(at_one, inf, r)?; - let tiny = below(e, ab, ATANH_TINY + 1)?; - let r = e.sel(tiny, a, r)?; - let r = e.copysign(r, x)?; - let beyond = e.gt(a, one)?; - let nan = e.metal_nan(None)?; - let r = e.sel(beyond, nan, r)?; - let x_nan = e.is_nan(x)?; - e.sel(x_nan, x, r) - } - } -} - -/// Metal's fast `asinh` or `acosh` (`which`) of `x`: MSL Table 8.2's `log(x + sqrt(s))` of `s = -/// RN(RN(x x) ± 1)` in Metal's own form, `RN(RN(log2(v)) RN(ln 2))` of `v = fma(s, rsqrt(s), x)`: -/// its hardware's inverse root ([`E::fast_rsqrt`]) times `s` is the root, and the product is fused -/// into the sum, so where `x` is negative and large the sum keeps the root's error -/// (`fast::asinh(-6.84e13)` is 14.39, and NaN where the error is below zero). Where `s` is 0 or -/// `+inf` the root is `s` itself: `v = RN(x + s)`, so `asinh(-inf)` is NaN (`-inf + inf`) and -/// `asinh(-FLT_MAX)` and `acosh(-FLT_MAX)` are `+inf`. Below zero (`acosh` inside `(-1, 1)`) the -/// answer is Metal's NaN. On case f6524207's 1,024 lanes this is Metal's word on the M3 and the M4 -/// wherever its `log2`'s model ([`log::metal_log2`]) is (`v` outside `[0.996, 1.031)`) and its -/// inverse root's is: on every lane but 42 and 10 of `v` next to 1 and a single lane of the root -/// (host replay). -pub(crate) fn fast_arc(e: &mut E<'_, '_>, which: FastArc, x: Value) -> BResult { - let one = e.c(1.0)?; - let zero = e.c(0.0)?; - let inf = e.c(f32::INFINITY)?; - let sq = e.mul(x, x)?; - let s = match which { - FastArc::Asinh => e.add(sq, one)?, - FastArc::Acosh => e.sub(sq, one)?, - }; - let rs = e.fast_rsqrt(s)?; - // The product `s rsqrt(s)` as `(s 2^-64) (rsqrt(s) 2^64)`, the same product exactly, whose - // factors the emulated fused step splits without overflow (`s` reaches `2^128`). - let (down, up) = ( - e.c(f32::from_bits(0x1F80_0000))?, - e.c(f32::from_bits(0x5F80_0000))?, - ); - let s_down = e.mul(s, down)?; - let rs_up = e.mul(rs, up)?; - let v = e.fused(s_down, rs_up, x)?; - let at_zero = e.fb.binary(BinOp::FOrdEqual, s, zero)?; - let at_inf = e.fb.binary(BinOp::FOrdEqual, s, inf)?; - let ends = e.iop(BinOp::LogicalOr, at_zero, at_inf)?; - let plain = e.add(x, s)?; - let v = e.sel(ends, plain, v)?; - let l2 = log::metal_log2(e, v)?; - let ln2 = e.c(f32::from_bits(log::LN_2_BITS))?; - let r = e.mul(l2, ln2)?; - // Metal's inverse root of a negative operand is its magnitude's ([`E::fast_rsqrt`]). - let negative = e.lt(s, zero)?; - let nan = e.metal_nan(None)?; - e.sel(negative, nan, r) -} - -/// The `float` bits below which Metal's `half` `asinh(x)` is `x` (`2^-11`). -const HALF_ASINH_TINY: u32 = 0x3A00_0000; - -/// Metal's `half` `asinh` before its rounding to `half`, of a `half` `x` held as `float`: its own -/// form, which follows Apple's runtime library: `x` itself below `2^-11` in magnitude and at an -/// infinity, else `RN(RN(log2(v)) RN(ln 2))` with `x`'s sign of `v = fma(z, rsqrt(z), |x|)`, `z = -/// fma(x, x, 1)` and its hardware's inverse root ([`E::fast_rsqrt`]), the fast `asinh`'s sum of -/// `|x|` ([`fast_arc`]). -pub(crate) fn half_asinh(e: &mut E<'_, '_>, x: Value) -> BResult { - let one = e.c(1.0)?; - let z = e.fused(x, x, one)?; - let rz = e.fast_rsqrt(z)?; - let a = e.abs(x)?; - let v = e.fused(z, rz, a)?; - let l2 = log::metal_log2(e, v)?; - let ln2 = e.c(f32::from_bits(log::LN_2_BITS))?; - let l = e.mul(l2, ln2)?; - let minus_l = e.fb.unary(UnOp::FNegate, l)?; - let zero = e.c(0.0)?; - let negative = e.lt(x, zero)?; - let r = e.sel(negative, minus_l, l)?; - let ab = e.bits(a)?; - let tiny = below(e, ab, HALF_ASINH_TINY)?; - let inf = e.u(0x7F80_0000)?; - let at_inf = e.iop(BinOp::IEqual, ab, inf)?; - let itself = e.iop(BinOp::LogicalOr, tiny, at_inf)?; - e.sel(itself, x, r) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/log.rs b/crates/metal2vulkan/src/lower/arith/libm/log.rs deleted file mode 100644 index 6e5aec3c9..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/log.rs +++ /dev/null @@ -1,803 +0,0 @@ -//! The logarithms: Metal's `log`, `log2`, and `log10` of a `float`, which MSL Table 8.1 bounds at 4 -//! ulp, Metal's precise `powr` (16 ulp), and the core the inverse hyperbolic functions share. -//! -//! **The core** ([`ln_parts`]): a positive normal `x` is `2^e (1 + f)` with `1 + f` in -//! `[sqrt(1/2), sqrt(2)]` ([`reduce`]; `f = m - 1` is exact), and `log(1 + f) = 2 atanh(s)` with -//! `s = f / (2 + f)`, `|s| <= 0.1716`. `s` is the device's quotient and the low part from its -//! exact remainder ([`E::div_pair`]); `2s` is exact, `(2/3) s^3` is formed from exact products -//! (Dekker's, with `s`'s low part to the first order), and the rest `s^5 R(s^2)` in plain `float`, -//! `R` of degree 3 fitted to a relative error of `2e-8`. `e ln 2` is exact in its high part (`ln 2` -//! to 16 bits) and the terms are summed by exact two-term sums from the largest, so the pair is -//! accurate to about `2^-40` relative: enough for the exact value [`metal_log2`] rounds. -//! -//! **Metal's `log2`** ([`metal_log2`]): what Metal's hardware computes, read off every `float` of -//! the M4 (the M3 answers every one alike). It is the exponent plus `L(m)` of the significand, -//! rounded toward zero, and `L(m) - log2(m)` is a smooth error per 32nd of `m` (about `2^-26` at -//! most) under a noise of about `2^-31` the model does not reproduce: [`TABLE`] fits the smooth -//! part, so the routine is `RZ(log2(x) + eps(m))`, and next to 1 (`[1 - 2^-8, 1 + 2^-5)`), where -//! the hardware keeps a relative accuracy the model lacks, `RZ(log2(x))`. Metal's word at -//! 2,130,133,076 of the 2,130,706,432 positive normal operands (99.973 %); a word one unit off at -//! the others (an open near-equivalent), and within 3 ulp of the exact value everywhere, as -//! Metal's. Metal's fast `log2` is the same function, so `air.fast_log2` -//! and the fast functions' formulas take the same routine (before SEMANTICS 1262 they took the core -//! rounded toward zero without the table, Metal's word on 99.76 % of those operands). -//! -//! **Metal's precise `log` and `log10`** ([`log`]): its `log2` times `RN(ln 2)` or -//! `RN(log10(2))` (every `float` of the sweep's binades `2^-40` to `2^40`), and next to 1 its own -//! polynomials ([`LOG_NEAR`], [`LOG10_NEAR`]), Metal's word at every `float` of their ranges. -//! -//! **Metal's precise `powr`** ([`powr`]), its own form, which follows Apple's runtime library and -//! matches Metal's measured words: `log2(x)` as a pair of `float`s through a table of nine centres -//! of the significand ([`POWR_TABLE`]) and a polynomial of degree 5 in fused steps ([`POWR_P`]), -//! its product with `y` as a pair, and Metal's hardware `exp2` of the high part (`exp::exp2`, its -//! model) grown by the low part in one fused step (`exp::grown`). With Metal's measured `exp2` it -//! is Metal's word at every measured operand; through the model, wherever the model is Metal's -//! `exp2` (99.905 % of its fractions). -//! -//! **Special operands** (case 7b283404, every lane, both math modes): a zero or a denormal (read -//! as a zero) gives `-inf`, a negative number Metal's NaN (`0x7fc00000`), `+inf` `+inf`, and a -//! NaN a NaN. `powr`'s magnitude of a zero or denormal base is `+0` toward a positive exponent and -//! `+inf` toward a negative one, of an infinite base the reverse; its NaN cases and its zero -//! exponent are `math::powr_nan`'s and `math::pow_special`'s around it. - -use crate::lower::arith::libm::exp; -use crate::lower::arith::libm::pair::constant; -use crate::lower::arith::libm::E; -use crate::spirv::builder::ModuleBuilder; -use crate::spirv::error::{BResult, BuildError, TypeRule}; -use crate::spirv::ids::{GlobalId, Value}; -use crate::spirv::ir::{BinOp, MemAccess}; -use std::f64::consts::{LN_2, LOG2_E}; - -/// `R(z)` of `log((1 + s) / (1 - s)) = 2s + (2/3) s^3 + s^5 R(s^2)` on `[0, 0.0295]`. -const R: [f32; 4] = [0.4, 0.285_715_3, 0.222_046_78, 0.191_227_05]; - -/// The bits of the largest `float` below `sqrt(2)`'s rounding: a significand above it is halved. -const SQRT2_BITS: u32 = 0x3FB5_04F3; - -/// Metal's `log2` table ([`metal_log2`]): per 32nd of the significand `m` of `x`, the `f32` -/// coefficients (by their bits, lowest first) of the quintic in `t` (the offset in the 32nd, in -/// `[0, 1)`) that models the hardware's error `L(m) - log2(m)`, where Metal's `log2(x)` is `L(m)` -/// plus the exponent rounded toward zero. Fitted by least squares to the bounds Metal's words set -/// on `L(m)` at every significand (the binades `[1/2, 1)`, `[1, 2)`, `[2, 4)`; -/// the words of `[1, 1 + 1/32)` and `[1 - 1/64, 1)` left out, where the hardware keeps the relative -/// accuracy no such model gives). The first segment's constant is 0, so the powers of 2 are exact. -pub(crate) const TABLE: [[u32; 6]; 32] = [ - [ - 0x0000_0000, - 0xB3E1_5503, - 0x350D_60F3, - 0xB55F_52F0, - 0x34F6_A16A, - 0xB33B_CEFE, - ], - [ - 0x3200_A205, - 0xB403_237D, - 0x34F5_6DB3, - 0xB52B_3158, - 0x3493_6140, - 0x3259_3010, - ], - [ - 0x31EF_171D, - 0xB3E6_F706, - 0x34C2_0549, - 0xB4E8_A17E, - 0x33EF_7B7F, - 0x3382_A9BC, - ], - [ - 0xAF8C_3B2F, - 0xB399_4960, - 0x3497_04EF, - 0xB4B8_39BA, - 0x3368_BD46, - 0x339C_C268, - ], - [ - 0xB1D0_EEE3, - 0xB328_8A32, - 0x3476_6816, - 0xB4B4_59C9, - 0x33FE_9C95, - 0x330A_D5FC, - ], - [ - 0x3278_7D57, - 0xB3F8_71CA, - 0x34B1_0C55, - 0xB4CA_ED27, - 0x33FD_87E4, - 0x32D8_6AFC, - ], - [ - 0x321C_AC81, - 0xB3CA_8A2B, - 0x34AB_D3B9, - 0xB4CD_22B1, - 0x3411_93F7, - 0x31E8_3355, - ], - [ - 0x3235_26B5, - 0xB3CF_59CD, - 0x349B_9225, - 0xB4B9_37DF, - 0x3404_1A18, - 0x3259_FCED, - ], - [ - 0x3226_177F, - 0xB3F2_3D17, - 0x349B_8A38, - 0xB486_5353, - 0x31D1_C99F, - 0x3358_3A58, - ], - [ - 0x3208_AAA4, - 0xB391_BAB0, - 0x346E_AA13, - 0xB487_A4DD, - 0x338D_D500, - 0x32B6_7DDF, - ], - [ - 0x31A4_DA68, - 0xB3B7_48F3, - 0x3485_0421, - 0xB48E_1F2E, - 0x3397_D850, - 0x329D_4FA1, - ], - [ - 0xB092_988F, - 0xB2DC_B39D, - 0x340A_3A65, - 0xB43F_2DB8, - 0x3398_36BF, - 0x3236_3EAF, - ], - [ - 0xB21E_AB87, - 0x3193_9904, - 0x338C_A47A, - 0xB40F_AA7F, - 0x336C_6EFB, - 0x3286_AE63, - ], - [ - 0xB12C_6079, - 0xB239_CB47, - 0x338C_391B, - 0xB3C1_E86A, - 0x328C_A645, - 0x32DE_FB2D, - ], - [ - 0xB160_347D, - 0xB288_D371, - 0x33EB_A160, - 0xB424_44BD, - 0x336B_1948, - 0x3210_ECC6, - ], - [ - 0x320F_FEDF, - 0xB3AD_882C, - 0x3451_91B6, - 0xB42B_4D5E, - 0x3183_7957, - 0x32D7_0DBE, - ], - [ - 0x31F9_8607, - 0xB380_183C, - 0x3429_3C97, - 0xB41C_9839, - 0x32CC_416E, - 0x3296_3EAF, - ], - [ - 0x320F_8CE4, - 0xB348_3D19, - 0x340D_438A, - 0xB438_B378, - 0x339B_4CEE, - 0xB12B_21E9, - ], - [ - 0x3268_3BD7, - 0xB38F_0693, - 0x340A_8AE4, - 0xB3E9_2BA0, - 0x320F_2AA2, - 0x3296_CA96, - ], - [ - 0x320F_AD9D, - 0xB39C_87A8, - 0x3439_619A, - 0xB427_B4DF, - 0x3317_6254, - 0x31E8_2E9C, - ], - [ - 0x30C7_D330, - 0xB208_9D73, - 0x3343_37EE, - 0xB3BA_E63E, - 0x3357_8954, - 0xB063_F2D5, - ], - [ - 0x30BE_1221, - 0xB327_50E3, - 0x33D9_6E04, - 0xB3D3_3908, - 0x321C_F270, - 0x325F_24B9, - ], - [ - 0x312C_4836, - 0xB28F_336A, - 0x335C_CDB0, - 0xB3A3_99F0, - 0x3329_5877, - 0x30BC_7099, - ], - [ - 0x3223_44FE, - 0xB392_EA61, - 0x3432_EF2E, - 0xB41F_31D3, - 0x3314_E9F5, - 0x30D3_0DEE, - ], - [ - 0x3237_EDC2, - 0xB386_7642, - 0x3404_7D32, - 0xB3D6_EBC3, - 0x3291_7F87, - 0x31F1_04E6, - ], - [ - 0x3145_916D, - 0xB2E8_D3E6, - 0x33A3_FCC8, - 0xB393_2998, - 0x31BE_CD6E, - 0x322E_FDB5, - ], - [ - 0xB00E_B02A, - 0xB2BA_5507, - 0x3389_FD0C, - 0xB3A6_D06B, - 0x32ED_F541, - 0x303A_561D, - ], - [ - 0x2F9E_3183, - 0xB2D9_4D80, - 0x3385_6DD9, - 0xB360_917B, - 0xB053_D071, - 0x324D_9D1D, - ], - [ - 0xB186_950C, - 0xB28A_4992, - 0x338E_BB9D, - 0xB376_2A50, - 0x2E9F_DE63, - 0x3231_6D8E, - ], - [ - 0x31F1_16B8, - 0xB307_A725, - 0x3399_2D14, - 0xB35A_6910, - 0xB2CF_20D7, - 0x32AC_B86E, - ], - [ - 0x31F9_B76F, - 0xB3BC_C5AB, - 0x34A9_01D6, - 0xB53A_96D3, - 0x3558_BAB8, - 0xB4BC_8B62, - ], - [ - 0xB186_9558, - 0x32D5_CEF8, - 0xB397_760F, - 0x341E_A898, - 0xB446_D126, - 0x33BF_EEEA, - ], -]; - -/// The coefficients per segment of [`TABLE`]. -const COEFFICIENTS: u32 = 6; - -/// An upper estimate of the SPIR-V words of [`TABLE`] in a module: its 192 constants, the -/// composite, and the array, pointer, and variable. -pub(crate) const TABLE_WORDS: u32 = 192 * 4 + 195 + 24; - -/// Declare [`TABLE`] in the module: a `Private` `u32[192]` of the coefficients' bits, segment -/// `s`'s six from word `6 s`. -pub(crate) fn declare(mb: &mut ModuleBuilder) -> BResult { - super::declare_words(mb, TABLE.as_flattened()) -} - -/// From `PLAIN_LOW` to below `PLAIN_END` (`[1 - 2^-8, 1 + 2^-5)`, bits) Metal's `log2` is taken -/// as the exact value rounded toward zero: [`TABLE`]'s model is not there. -pub(crate) const PLAIN_LOW: u32 = 0x3F7F_0000; -pub(crate) const PLAIN_END: u32 = 0x3F84_0000; - -/// `RN(ln 2)` and `RN(log10(2))`, by their bits: Metal's precise `log` and `log10` away from 1 -/// are its `log2` times them. -pub(crate) const LN_2_BITS: u32 = 0x3F31_7218; -pub(crate) const LOG10_2_BITS: u32 = 0x3E9A_209B; - -/// Metal's precise `log` or `log10` next to 1: for `x` strictly between the -/// bits `low` and `end`, `RN(f fma(p(f), f, lead))` of `f = x - 1` (exact there), `p` by Horner's -/// rule with fused steps, `f32` coefficients by their bits, lowest first. Each is Metal's word at -/// every `float` of its range. -pub(crate) struct Near { - pub low: u32, - pub end: u32, - pub lead: u32, - pub p: &'static [u32], -} - -/// `log`'s: `(61/64, 17/16)`, `lead` 1. -pub(crate) const LOG_NEAR: Near = Near { - low: 0x3F74_0000, - end: 0x3F88_0000, - lead: 0x3F80_0000, - p: &[0xBEFF_FFF4, 0x3EAA_AC4E, 0xBE80_449E, 0x3E47_04F8], -}; - -/// `log10`'s: `(495/512, 543/512)`, `lead` `log10(e)` rounded down. -pub(crate) const LOG10_NEAR: Near = Near { - low: 0x3F77_8000, - end: 0x3F87_C000, - lead: 0x3EDE_5BD8, - p: &[0xBE5E_5CE8, 0x3E14_5662, 0xBDD5_5B94], -}; - -/// Which logarithm a routine answers. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Base { - E, - Ten, -} - -/// `c` to 16 significant bits and the `float` nearest the rest, so that `e c_hi` is exact for an -/// integer `e` of at most 8 bits. -fn short(c: f64) -> (f32, f32) { - let hi = (c * 65536.0).floor() / 65536.0; - (hi as f32, (c - hi) as f32) -} - -/// `x = 2^e (1 + f)` for a positive normal `x`: `e` (a `float`) and `f` in -/// `[sqrt(1/2) - 1, sqrt(2) - 1]`, both exact. -pub(crate) fn reduce(e: &mut E<'_, '_>, x: Value) -> BResult<(Value, Value)> { - let (ef, m) = significand(e, x)?; - let onef = e.c(1.0)?; - let f = e.sub(m, onef)?; - Ok((ef, f)) -} - -/// `x = 2^e m` for a positive normal `x`: `e` (a `float`) and `m` in `(sqrt(1/2), sqrt(2)]` -/// (bits up to [`SQRT2_BITS`]), both exact. -fn significand(e: &mut E<'_, '_>, x: Value) -> BResult<(Value, Value)> { - let b = e.bits(x)?; - let k23 = e.u(23)?; - let biased = e.iop(BinOp::ShiftRightLogical, b, k23)?; - let (fraction, one_bits) = (e.u(0x007F_FFFF)?, e.u(0x3F80_0000)?); - let m = e.iop(BinOp::BitwiseAnd, b, fraction)?; - let m = e.iop(BinOp::BitwiseOr, m, one_bits)?; - let bound = e.u(SQRT2_BITS)?; - let big = e.iop(BinOp::UGreaterThan, m, bound)?; - let lead = e.u(0x0080_0000)?; - let halved = e.iop(BinOp::ISub, m, lead)?; - let m = e.sel(big, halved, m)?; - let one = e.u(1)?; - let up = e.iop(BinOp::IAdd, biased, one)?; - let biased = e.sel(big, up, biased)?; - let bf = e.ufloat(biased)?; - let bias = e.c(127.0)?; - let ef = e.sub(bf, bias)?; - let m = e.float(m)?; - Ok((ef, m)) -} - -/// The core: `e ln 2 + log(1 + fh + fl)` as a pair, for an integral `e` of at most 8 bits, `fh` -/// in `[sqrt(1/2) - 1, sqrt(2) - 1]` (zero or at least `2^-25` in magnitude), and `fl` a low -/// part below an ulp of `fh`. -pub(crate) fn ln_parts( - e: &mut E<'_, '_>, - ef: Value, - fh: Value, - fl: Value, -) -> BResult<(Value, Value)> { - let two = e.c(2.0)?; - let (dh, dl) = e.fast_two_sum(two, fh)?; - let dl = e.add(dl, fl)?; - let (sh, sl) = e.div_pair((fh, fl), (dh, dl))?; - // `s^2` and `s^3` exactly, then `(2/3) s^3 + 2 s^2 sl`. - let (q, q_err) = e.two_prod(sh, sh)?; - let (c, c_err) = e.two_prod(q, sh)?; - let qe = e.mul(q_err, sh)?; - let c_err = e.add(c_err, qe)?; - let (tt_hi, tt_lo) = constant(2.0 / 3.0); - let tt = e.c(tt_hi)?; - let (t, t_err) = e.two_prod(c, tt)?; - let ttl = e.c(tt_lo)?; - let t1 = e.mul(c, ttl)?; - let t2 = e.mul(c_err, tt)?; - let t12 = e.add(t1, t2)?; - let t_err = e.add(t_err, t12)?; - let qs = e.mul(q, sl)?; - let qs = e.add(qs, qs)?; - let t_err = e.add(t_err, qs)?; - // `s^5 R(s^2)`. - let r = e.horner(&R, q)?; - let s5 = e.mul(c, q)?; - let s5 = e.mul(s5, r)?; - // `e ln 2`. - let (l2_hi, l2_lo) = short(LN_2); - let l2h = e.c(l2_hi)?; - let l2l = e.c(l2_lo)?; - let eh = e.mul(ef, l2h)?; - let el = e.mul(ef, l2l)?; - // `eh + 2 sh + t + (2 sl + t_err + s5 + el)`, from the largest (`|eh| >= 0.69 > |2 sh|` or - // `eh = 0`). - let s2 = e.add(sh, sh)?; - let (a, a_err) = e.fast_two_sum(eh, s2)?; - let (b, b_err) = e.two_sum(a, t)?; - let ab = e.add(a_err, b_err)?; - let sl2 = e.add(sl, sl)?; - let rest = e.add(sl2, t_err)?; - let tail = e.add(s5, el)?; - let rest = e.add(rest, tail)?; - let rest = e.add(ab, rest)?; - e.fast_two_sum(b, rest) -} - -/// `x` where it is a positive normal `float`, `1` elsewhere: the core's operand on every lane, -/// the special operands' answers selected after it. -pub(crate) fn positive_normal(e: &mut E<'_, '_>, x: Value) -> BResult<(Value, Value)> { - let b = e.bits(x)?; - let lead = e.u(0x0080_0000)?; - let offset = e.iop(BinOp::ISub, b, lead)?; - let span = e.u(0x7F00_0000)?; - let normal = e.iop(BinOp::ULessThan, offset, span)?; - let one = e.c(1.0)?; - let xs = e.sel(normal, x, one)?; - Ok((xs, normal)) -} - -/// `(h + l) c` as a pair for a split constant `c`, `h + l` a pair. -fn times(e: &mut E<'_, '_>, (h, l): (Value, Value), c: f64) -> BResult<(Value, Value)> { - let (c_hi, c_lo) = constant(c); - let ch = e.c(c_hi)?; - let (p, p_err) = e.two_prod(h, ch)?; - let cl = e.c(c_lo)?; - let a = e.mul(h, cl)?; - let b = e.mul(l, ch)?; - let ab = e.add(a, b)?; - let rest = e.add(p_err, ab)?; - e.fast_two_sum(p, rest) -} - -/// Metal's `log2` of `x`, in both modes (its fast `log2` is its precise one): `RZ(log2(x) + -/// eps(m))`, rounded toward zero, `eps` the hardware's error at the significand `m` of `x` -/// ([`TABLE`]), and `0` from [`PLAIN_LOW`] to below [`PLAIN_END`]. `log2(x)` is `ef + log2(1 + f)` -/// of [`reduce`]'s parts, the logarithm a pair (exact at the powers of 2, accurate to about -/// `2^-41`), so the sum with `ef` is exact and the one rounding is the last: where the exact -/// remainder's sign is not the sum's, the sum steps one unit toward zero. Metal's special operands -/// are [`specials`]'. -pub(crate) fn metal_log2(e: &mut E<'_, '_>, x: Value) -> BResult { - let (xs, _) = positive_normal(e, x)?; - let (ef, f) = reduce(e, xs)?; - let zero = e.c(0.0)?; - let ln = ln_parts(e, zero, f, zero)?; - let (h, l) = times(e, ln, LOG2_E)?; - let (s, r) = e.two_sum(ef, h)?; - let eps = fitted_error(e, xs)?; - let tail = e.add(l, eps)?; - let tail = e.add(r, tail)?; - let (s, r) = e.two_sum(s, tail)?; - // Toward zero: one unit down in magnitude where a nonzero remainder has the other sign. - let (sb, rb) = (e.bits(s)?, e.bits(r)?); - let (sign, magnitude, zero_u, one) = (e.u(0x8000_0000)?, e.u(0x7FFF_FFFF)?, e.u(0)?, e.u(1)?); - let differ = e.iop(BinOp::BitwiseXor, sb, rb)?; - let differ = e.iop(BinOp::BitwiseAnd, differ, sign)?; - let opposite = e.iop(BinOp::INotEqual, differ, zero_u)?; - let rm = e.iop(BinOp::BitwiseAnd, rb, magnitude)?; - let nonzero = e.iop(BinOp::INotEqual, rm, zero_u)?; - let step = e.iop(BinOp::LogicalAnd, opposite, nonzero)?; - let down = e.iop(BinOp::ISub, sb, one)?; - let v = e.sel(step, down, sb)?; - let v = e.float(v)?; - specials(e, x, v) -} - -/// [`TABLE`]'s `eps(m)` at the positive normal `xs`: segment `k >> 18` of its fraction `k`, at -/// `t = (k mod 2^18) 2^-18`, and `0` from [`PLAIN_LOW`] to below [`PLAIN_END`]. -fn fitted_error(e: &mut E<'_, '_>, xs: Value) -> BResult { - let table = e.log2_table()?; - let b = e.bits(xs)?; - let (fraction, low, k18) = (e.u(0x007F_FFFF)?, e.u(0x3_FFFF)?, e.u(18)?); - let k = e.iop(BinOp::BitwiseAnd, b, fraction)?; - let segment = e.iop(BinOp::ShiftRightLogical, k, k18)?; - let t = e.iop(BinOp::BitwiseAnd, k, low)?; - let t = e.ufloat(t)?; - let scale = e.c(1.0 / 262_144.0)?; - let t = e.mul(t, scale)?; - let width = e.u(COEFFICIENTS)?; - let first = e.iop(BinOp::IMul, segment, width)?; - let base = e.fb.module().global_value(table)?; - let coefficient = |e: &mut E<'_, '_>, j: u32| -> BResult { - let j = e.u(j)?; - let i = e.iop(BinOp::IAdd, first, j)?; - let p = e.fb.access_chain(base, &[i])?; - let w = e.fb.load(p, MemAccess::default())?; - e.float(w) - }; - // Horner's rule in plain `float`: `eps` is below `2^-25`, so its own rounding errors (about - // `2^-48`) move the result only where the sum lies that close to a `float`. - let mut eps = coefficient(e, COEFFICIENTS - 1)?; - for j in (0..COEFFICIENTS - 1).rev() { - let c = coefficient(e, j)?; - let p = e.mul(eps, t)?; - eps = e.add(p, c)?; - } - let plain_low = e.u(PLAIN_LOW)?; - let offset = e.iop(BinOp::ISub, b, plain_low)?; - let span = e.u(PLAIN_END - PLAIN_LOW)?; - let plain = e.iop(BinOp::ULessThan, offset, span)?; - let zero = e.c(0.0)?; - e.sel(plain, zero, eps) -} - -/// `RN(f q)` of `f = x - 1` and `q = fma(p(f), f, lead)`, `p` by Horner's rule with fused steps -/// ([`Near`]); exact where `x` lies in the near form's range. -fn near_one(e: &mut E<'_, '_>, x: Value, near: &Near) -> BResult { - let one = e.c(1.0)?; - let f = e.sub(x, one)?; - let (last, rest) = near - .p - .split_last() - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - let mut p = e.c(f32::from_bits(*last))?; - for c in rest.iter().rev() { - let c = e.c(f32::from_bits(*c))?; - p = e.fused(p, f, c)?; - } - let lead = e.c(f32::from_bits(near.lead))?; - let q = e.fused(p, f, lead)?; - e.mul(f, q) -} - -/// Metal's precise `log` or `log10` of `x`: the precise [`metal_log2`]'s product with `RN(ln 2)` or -/// `RN(log10(2))`, and inside their [`Near`] ranges next to 1 their own polynomials. -pub(crate) fn log(e: &mut E<'_, '_>, base: Base, x: Value) -> BResult { - let l2 = metal_log2(e, x)?; - let (c, near) = match base { - Base::E => (LN_2_BITS, &LOG_NEAR), - Base::Ten => (LOG10_2_BITS, &LOG10_NEAR), - }; - let c = e.c(f32::from_bits(c))?; - let far = e.mul(l2, c)?; - let b = e.bits(x)?; - let first = e.u(near.low + 1)?; - let offset = e.iop(BinOp::ISub, b, first)?; - let span = e.u(near.end - near.low - 1)?; - let inside = e.iop(BinOp::ULessThan, offset, span)?; - let r = near_one(e, x, near)?; - let r = e.sel(inside, r, far)?; - specials(e, x, r) -} - -/// `r` with Metal's answers at `x`'s special operands: `-inf` for a zero or denormal, its NaN for -/// a negative number, `+inf` for `+inf`, and a NaN `x` itself. -fn specials(e: &mut E<'_, '_>, x: Value, r: Value) -> BResult { - let b = e.bits(x)?; - let (sign, field) = (e.u(0x8000_0000)?, e.u(0x7F80_0000)?); - let zero = e.u(0)?; - let s = e.iop(BinOp::BitwiseAnd, b, sign)?; - let negative = e.iop(BinOp::INotEqual, s, zero)?; - let ex = e.iop(BinOp::BitwiseAnd, b, field)?; - let zero_or_denormal = e.iop(BinOp::IEqual, ex, zero)?; - let inf = e.iop(BinOp::IEqual, b, field)?; - let nan = e.metal_nan(None)?; - let r = e.sel(negative, nan, r)?; - let minus_inf = e.c(f32::NEG_INFINITY)?; - let r = e.sel(zero_or_denormal, minus_inf, r)?; - let plus_inf = e.c(f32::INFINITY)?; - let r = e.sel(inf, plus_inf, r)?; - let x_nan = e.is_nan(x)?; - e.sel(x_nan, x, r) -} - -/// [`powr`]'s reduction table, one row per centre `c` of the reduction (a significand `m` in -/// `(sqrt(1/2), sqrt(2)]` takes the row of its bits `20..24` less 3, whose centre is the left end -/// of its sixteenth (below 1) or eighth (from 1) of a binade, or 1 next to 1): `1 / c` and -/// `log2(c)` as pairs of `float`s by their bits, `[hi(1 / c), lo(1 / c), hi(log2 c), lo(log2 c)]`, each `hi` the -/// `float` nearest the value and `lo` the `float` nearest the rest (`libm::split` of the `f64` -/// value; `powr_table_is_the_centres_split`). With them the form is Metal's word at every -/// measured operand. -pub(crate) const POWR_TABLE: [[u32; 4]; 9] = [ - [0x3FBA_2E8C, 0xB33A_2E8C, 0xBF0A_62B0, 0xB2FE_68B0], - [0x3FAA_AAAB, 0xB32A_AAAB, 0xBED4_7FCC, 0x3267_EF5A], - [0x3F9D_89D9, 0xB344_EC4F, 0xBE99_5FF7, 0xB15C_3B9A], - [0x3F92_4925, 0xB35B_6DB7, 0xBE45_44C0, 0xB1AB_FBD3], - [0x3F80_0000, 0, 0, 0], - [0x3F80_0000, 0, 0, 0], - [0x3F63_8E39, 0xB1E3_8E39, 0x3E2E_00D2, 0xB140_852F], - [0x3F4C_CCCD, 0xB24C_CCCD, 0x3EA4_D3C2, 0x323C_D1B9], - [0x3F3A_2E8C, 0xB2BA_2E8C, 0x3EEB_3A9F, 0x2F4B_A83C], -]; - -/// An upper estimate of the SPIR-V words of [`POWR_TABLE`] in a module: its 36 constants (the -/// zeros shared), the composite, and the array, pointer, and variable. -pub(crate) const POWR_TABLE_WORDS: u32 = 36 * 4 + 39 + 24; - -/// Declare [`POWR_TABLE`] in the module: a `Private` `u32[36]`, row `k`'s four from word `4 k`. -pub(crate) fn declare_powr(mb: &mut ModuleBuilder) -> BResult { - super::declare_words(mb, POWR_TABLE.as_flattened()) -} - -/// `P(u)` of [`powr`]'s logarithm, `log2(1 + u) = u (log2(e) + u P(u))` for `|u|` up to `1/8`: -/// `f32` coefficients by their bits, lowest first, evaluated by Horner's rule in fused steps -/// (Metal's polynomial; its word at every measured operand). -pub(crate) const POWR_P: [u32; 6] = [ - 0xBF38_AA3B, - 0x3EF6_3846, - 0xBEB8_AB4B, - 0x3E93_D4FF, - 0xBE75_68A7, - 0x3E30_0BB9, -]; - -/// The bound `y` is clamped to before the product: past `2^31` every `y log2(x)` of `x` other -/// than 1 is beyond the exponential's range (`|log2(x)| >= 2^-24`), so the answer is the same, -/// and the products' exact errors stay in range. -const POWR_Y_BOUND: f32 = 2_147_483_648.0; - -/// `log2(x)` of a positive normal `x` as Metal's `powr` forms it, a pair `(h, l)`: `x = 2^n m` -/// ([`significand`]), `m = c (1 + u)` of the row's centre `c`, `u = m (1 / c) - 1` as a pair (the -/// product's error exact, the low part of `1 / c` in a fused step); `L = log2(1 + u)` as the pair -/// `(u_h + u_l) (q_h + q_l)` of `q = log2(e) + u_h P(u_h)`; then `n + L + log2(c)` by two-term -/// sums, the larger term first. -fn powr_log2(e: &mut E<'_, '_>, x: Value) -> BResult<(Value, Value)> { - let (ef, m) = significand(e, x)?; - // The row: bits 20 to 23 of `m`, less 3 (`m` from `0x3F35_04F4` up to `SQRT2_BITS`). - let mb = e.bits(m)?; - let (k20, nibble, three, four) = (e.u(20)?, e.u(15)?, e.u(3)?, e.u(4)?); - let row = e.iop(BinOp::ShiftRightLogical, mb, k20)?; - let row = e.iop(BinOp::BitwiseAnd, row, nibble)?; - let row = e.iop(BinOp::ISub, row, three)?; - let first = e.iop(BinOp::IMul, row, four)?; - let table = e.powr_table()?; - let base = e.fb.module().global_value(table)?; - let entry = |e: &mut E<'_, '_>, j: u32| -> BResult { - let j = e.u(j)?; - let i = e.iop(BinOp::IAdd, first, j)?; - let p = e.fb.access_chain(base, &[i])?; - let w = e.fb.load(p, MemAccess::default())?; - e.float(w) - }; - let (inv_hi, inv_lo) = (entry(e, 0)?, entry(e, 1)?); - let (log_hi, log_lo) = (entry(e, 2)?, entry(e, 3)?); - // `m / c` as a pair, `|p| >= |p_l|`, then `u = m / c - 1` (`m / c` is in `[15/16, 9/8)`, so - // the difference with 1 is exact). - let p = e.mul(m, inv_hi)?; - let p_err = e.exact_error(m, inv_hi, p)?; - let p_l = e.fused(m, inv_lo, p_err)?; - let (s, s_l) = e.fast_two_sum(p, p_l)?; - let minus_one = e.c(-1.0)?; - let u = e.add(s, minus_one)?; - let (uh, ul) = e.fast_two_sum(u, s_l)?; - // `q = log2(e) + t` of `t = u_h P(u_h)`, `|t|` below a tenth, so `log2(e)` leads. - let poly = e.fused_poly(&POWR_P, uh)?; - let t = e.mul(poly, uh)?; - let (l2e_hi, l2e_lo) = constant(LOG2_E); - let l2e = e.c(l2e_hi)?; - let q0 = e.add(t, l2e)?; - let d = e.sub(l2e, q0)?; - let d = e.add(t, d)?; - let l2e_lo = e.c(l2e_lo)?; - let q0_l = e.add(d, l2e_lo)?; - let (qh, ql) = e.fast_two_sum(q0, q0_l)?; - // `L = (u_h + u_l) (q_h + q_l)`: the high product's exact error, then the cross terms in - // fused steps. - let lp = e.mul(uh, qh)?; - let l_err = e.exact_error(qh, uh, lp)?; - let l_err = e.fused(qh, ul, l_err)?; - let l_err = e.fused(ql, uh, l_err)?; - let (lh, ll) = e.fast_two_sum(lp, l_err)?; - // `n + L`: `|n| >= 1 > |L|`, or `n = 0`. - let (a, a_l) = e.fast_two_sum(ef, lh)?; - let r = e.add(ll, a_l)?; - let (g, gl) = e.fast_two_sum(a, r)?; - // `+ log2(c)`: the larger of `log2(c)` and `g` first. - let s2 = e.add(log_hi, g)?; - let (h_abs, g_abs) = (e.abs(log_hi)?, e.abs(g)?); - let g_larger = e.lt(h_abs, g_abs)?; - let d1 = e.sub(log_hi, s2)?; - let d1 = e.add(g, d1)?; - let d1 = e.add(gl, d1)?; - let by_log = e.add(log_lo, d1)?; - let d2 = e.sub(g, s2)?; - let d2 = e.add(log_hi, d2)?; - let d2 = e.add(log_lo, d2)?; - let by_g = e.add(gl, d2)?; - let rest = e.sel(g_larger, by_g, by_log)?; - e.fast_two_sum(s2, rest) -} - -/// The magnitude of Metal's precise `powr(x, y)` (and of `pow`'s, of `|x|`), Metal's own form: `z = -/// y log2(x)` as a pair of [`powr_log2`]'s pair (the high product's error exact, the low part's -/// product in a fused step), one unit of the last place down where `z_h` is at least 128 and `z_l` -/// negative, and then Metal's `exp2` of `z_h` grown by `z_l ln 2` in one fused step (`exp::grown`). -/// With `|x|`'s zero (a denormal read as one) and infinity selected; a NaN operand gives a NaN. -pub(crate) fn powr(e: &mut E<'_, '_>, x: Value, y: Value) -> BResult { - let ax = e.abs(x)?; - let (xs, _) = positive_normal(e, ax)?; - let (gh, gl) = powr_log2(e, xs)?; - let (yc, _) = e.clamp(y, POWR_Y_BOUND)?; - let p = e.mul(gh, yc)?; - let p_err = e.exact_error(gh, yc, p)?; - let p_err = e.fused(gl, yc, p_err)?; - let (zh, zl) = e.fast_two_sum(p, p_err)?; - // From 128 with a negative low part, the high part one unit lower, so that its `exp2` is - // finite where the pair's value is below 128. - let (top, zero) = (e.c(128.0)?, e.c(0.0)?); - let at_top = e.ge(zh, top)?; - let below = e.lt(zl, zero)?; - let lower = e.iop(BinOp::LogicalAnd, at_top, below)?; - let zb = e.bits(zh)?; - let one = e.u(1)?; - let zb = e.iop(BinOp::ISub, zb, one)?; - let z1 = e.float(zb)?; - let step = e.sub(zh, z1)?; - let zl1 = e.add(zl, step)?; - let zh = e.sel(lower, z1, zh)?; - let zl = e.sel(lower, zl1, zl)?; - let big = exp::exp2(e, zh)?; - let ln2 = e.c(f32::from_bits(LN_2_BITS))?; - let growth = e.mul(zl, ln2)?; - let r = exp::grown(e, big, growth)?; - // `y = 1`: `|x|` itself, as Metal answers before its form (case 7b283404, where the form is a - // unit above at three of the nine such lanes). - let one_f = e.c(1.0)?; - let y_one = e.fb.binary(BinOp::FOrdEqual, y, one_f)?; - let r = e.sel(y_one, ax, r)?; - // `|x|` zero or denormal, or infinite: `+0` or `+inf` by `y`'s sign. - let b = e.bits(ax)?; - let field = e.u(0x7F80_0000)?; - let zero_u = e.u(0)?; - let ex = e.iop(BinOp::BitwiseAnd, b, field)?; - let x_zero = e.iop(BinOp::IEqual, ex, zero_u)?; - let x_inf = e.iop(BinOp::IEqual, b, field)?; - let inf = e.c(f32::INFINITY)?; - let y_pos = e.gt(y, zero)?; - let at_zero = e.sel(y_pos, zero, inf)?; - let at_inf = e.sel(y_pos, inf, zero)?; - let r = e.sel(x_zero, at_zero, r)?; - let r = e.sel(x_inf, at_inf, r)?; - let xy = e.add(x, y)?; - let x_nan = e.is_nan(x)?; - let y_nan = e.is_nan(y)?; - let any_nan = e.iop(BinOp::LogicalOr, x_nan, y_nan)?; - e.sel(any_nan, xy, r) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/mod.rs b/crates/metal2vulkan/src/lower/arith/libm/mod.rs index b5a935b7a..48fb1d756 100644 --- a/crates/metal2vulkan/src/lower/arith/libm/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/libm/mod.rs @@ -1,49 +1,23 @@ -//! The translation's own `float` functions: routines that answer within Apple's stated bound on -//! every device, for the functions whose `GLSL.std.450` instruction a device may answer outside it. +//! The `float` functions whose `GLSL.std.450` instruction a device may answer otherwise than +//! Metal, as the notes a call records read them, and the one of them the translation computes +//! itself: Metal's precise `fmod` ([`fmod`]). //! //! Vulkan's precision table bounds `Atan`, `Asin`, and `Acos` at 4096 ulp and `Sin` and `Cos` at -//! `2^-11` absolute, about what Metal's fast-math table allows, while Metal's precise functions -//! are bounded at 4 to 6 ulp (MSL Table 8.1) and Mesa's devices answer `atan` 3,528 ulp off -//! (on lavapipe, RADV, and ANV). 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 left to it, and a call in the other mode (a -//! `precise::` call in a fast-math module, or a `fast::` one in a module that keeps NaNs) takes the -//! routine. Elsewhere every such call takes the routine. Metal's `sinpi`, `cospi`, and `tanpi` are -//! no device's instruction, so every precise call of them takes their routines, and every fast one -//! but where the device's functions are Metal's. +//! `2^-11` absolute, about what Metal's fast-math table allows, while Metal's precise functions are +//! bounded at 4 to 6 ulp (MSL Table 8.1). Every call takes the device's instruction, or Metal's +//! composition of the device's instructions where no instruction is the function (`exp10`, `log10`, +//! `sinpi`, `cospi`, `tanpi`), and records the device's precision where its functions are not +//! Metal's own (`PrecisionNote::NativeTranscendentals`). Where the device is Metal's own +//! (`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. //! -//! A routine is one module-scope function of one `float` per [`Fun`] (as the wide divisions and -//! fused multiply-adds are), which a call of any lane count calls once per lane: GPU code runs a -//! lane per invocation anyway, and a scalar routine is defined once whatever the vector widths. Its -//! arithmetic is the device's correctly rounded `float` addition, subtraction, and multiplication, -//! each `NoContraction` so that no device fuses or regroups it, with comparisons, selects, and bit -//! operations, and its divisions and roots call the module's routines ([`Needs`], [`Helpers`]): -//! Metal's precise division (`divide.rs`) and Metal's inverse root ([`Fun::FastRsqrt`], from the -//! correctly rounded one). So its answer does not depend on the device. Before, a routine took the -//! device's `OpFDiv` and `Sqrt` (Vulkan allows 2.5 ulp and 3 ulp) and corrected their error where -//! it was found to reach the result; `tan`'s answers still differed among RADV, lavapipe and -//! NVIDIA. No intermediate is an `f32` denormal where the result depends on it, so a -//! device that flushes them answers the same. A routine reads a denormal operand as Metal does -//! ([`denormal`]), and answers Metal's values at its special operands where they are measured, -//! Metal's NaN at a domain error among them (`E::metal_nan`); a NaN operand's result is the -//! device's arithmetic's (`PrecisionNote::DeviceNanEncoding`). +//! Precise `fmod` keeps its routine: the device's form, `OpFRem` (`x - y · trunc(x / y)` at the +//! device's precision), Vulkan leaves unbounded once the quotient passes `2^24`, where Metal's is +//! exact. Where the device is Metal's own, a precise module's `OpFRem` is Metal's `fmod`, and takes +//! no routine ([`Fun::device_answers`]). -pub(crate) mod atan; -pub(crate) mod exp; -mod fmod; -pub(crate) mod hyper; -pub(crate) mod log; -mod pair; -mod pi; -pub(crate) mod quarter; -pub(crate) mod rcp; -mod root; -pub(crate) mod rsqrt; -pub(crate) mod sincos; -pub(crate) mod tan; -pub(crate) mod trig; - -use std::collections::BTreeMap; +pub(crate) mod fmod; use crate::lower::arith::legal::{FloatFmt, Form, Held}; use crate::lower::arith::math::FloatFn; @@ -51,15 +25,10 @@ use crate::lower::arith::narrow::u32_form; use crate::lower::arith::ops::{splat, ty}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::error::{BResult, BuildError, TypeRule}; -use crate::spirv::ids::{FuncId, GlobalId, Value}; -use crate::spirv::ir::{ - BinOp, ConstBits, Constant, Contraction, ConvOp, GlslOp, StorageClass, Type, UnOp, -}; +use crate::spirv::ids::{FuncId, Value}; +use crate::spirv::ir::{BinOp, Contraction, ConvOp, Type}; -#[cfg(doc)] -use crate::lower::arith::denormal; - -/// The quiet NaN Metal answers at the routines' functions' domain errors ([`E::metal_nan`]). +/// The quiet NaN Metal answers at precise `fmod`'s domain errors ([`E::metal_nan`]). pub(crate) const METAL_NAN: u32 = 0x7FC0_0000; /// A math mode: Metal's precise functions (MSL Table 8.1) or its fast ones (Table 8.2). @@ -81,7 +50,9 @@ pub fn module_mode(declared: &std::collections::BTreeSet) -> Mode { } } -/// A function a routine computes on `float` operands. +/// A function of Metal's math library on `float` operands, as a call of a float function takes it +/// ([`uses`]): one whose answer the device's instruction may give otherwise than Metal, beyond +/// Vulkan's precision table, or a part of one. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Fun { /// Metal's `atan` in a mode: within 5 ulp in both (Tables 8.1 and 8.2). @@ -93,51 +64,47 @@ pub enum Fun { /// The generic part of Metal's precise `atan2(y, x)` (within 6 ulp): finite nonzero normal /// operands, whose special values `math::atan2_special` answers around it. Atan2, - /// Metal's precise `sin` (within 4 ulp): its own form, `t S(t)` of its reduction's folded - /// quarter turns and its hardware's `sinc` through a model. + /// Metal's precise `sin` (within 4 ulp). Sin, - /// Metal's precise `cos` (within 4 ulp), as [`Fun::Sin`]. + /// Metal's precise `cos` (within 4 ulp). Cos, /// Metal's precise `tan` (within 6 ulp). Tan, - /// Metal's fast `sin` below its flush point, which is its precise `sin`: the device's `Sin` - /// inside `[-π, π]` (Apple's `2^-13` bound, MSL Table 8.2), [`Fun::Sin`]'s routine past it. + /// Metal's fast `sin` below its flush point, which is its precise `sin` inside `[-π, π]` + /// (Apple's `2^-13` bound, MSL Table 8.2). FastSin, /// Metal's fast `cos` below its flush point; as [`Fun::FastSin`]. FastCos, - /// Metal's `sinpi`, its own form of half turns and its hardware's `sinc` through a model, 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`]). + /// 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`]). SinPi(Mode), /// Metal's `cospi`, as [`Fun::SinPi`]. CosPi(Mode), - /// Metal's `tanpi`, as [`Fun::SinPi`], its quotient by Metal's reciprocal ([`Fun::Recip`]). + /// Metal's `tanpi`, as [`Fun::SinPi`]. TanPi(Mode), /// Metal's precise `sqrt`: correctly rounded (MSL Tables 8.1 and 8.3). Sqrt, /// Metal's precise `rsqrt`: correctly rounded (Tables 8.1 and 8.3). Rsqrt, - /// Metal's precise `fmod`: exact (0 ulp, Tables 8.1 and 8.3). + /// Metal's precise `fmod`: exact (0 ulp, Tables 8.1 and 8.3), the routine of [`fmod`]. Fmod, - /// Metal's `exp2` (within 4 ulp, Table 8.1), which is also its fast `exp2`: the two answer - /// alike on every lane of cases 7b283404 and f6524207. + /// Metal's `exp2` (within 4 ulp, Table 8.1), which is also its fast `exp2`. Exp2, /// Metal's precise `exp`: within 4 ulp. Exp, /// Metal's precise `exp10`: within 4 ulp. No `GLSL.std.450` instruction is it. Exp10, - /// Metal's `log2` (within 4 ulp), also its fast `log2`, as [`Fun::Exp2`], with Metal's error - /// table (its word on 99.97 % of the positive normal operands): the routine of `air.log2`, - /// `air.fast_log2`, and the fast functions' formulas. + /// Metal's `log2` (within 4 ulp), also its fast `log2`, as [`Fun::Exp2`]: the function of + /// `air.log2`, `air.fast_log2`, and the fast functions' formulas. Log2, /// Metal's precise `log`: within 4 ulp. Log, /// Metal's precise `log10`: within 4 ulp. No `GLSL.std.450` instruction is it. Log10, /// The magnitude of Metal's precise `powr(x, y)` and `pow(x, y)` (within 16 ulp): `|x|^y`, - /// Metal's own form (`log::powr`), whose NaN and zero-exponent cases `math::powr_nan` and - /// `math::pow_special` answer around it. + /// whose NaN and zero-exponent cases `math::powr_nan` and `math::pow_special` answer around + /// it. Powr, /// Metal's precise `sinh`: within 4 ulp. Sinh, @@ -151,343 +118,52 @@ pub enum Fun { Acosh, /// Metal's precise `atanh`: within 5 ulp. Atanh, - /// Metal's fast `asinh`, MSL Table 8.2's `log(x + sqrt(x x + 1))` in Metal's own form - /// (`hyper::fast_arc`): its hardware's inverse root, fused into the sum, and its `log2`. + /// Metal's fast `asinh`, MSL Table 8.2's `log(x + sqrt(x x + 1))`. FastAsinh, - /// Metal's fast `acosh`, `log(x + sqrt(x x - 1))`, as [`Fun::FastAsinh`]. + /// Metal's fast `acosh`, `log(x + sqrt(x x - 1))`. FastAcosh, - /// Metal's reciprocal `1 / y`: its fast division's, the one its precise `sinh`, `cosh`, and - /// `tanh` compose with, and its texture unit's (`rcp::metal_rcp`). The routine other routines - /// call for it (`E::recip`), and any lowering per lane ([`Lib::call`]). + /// Metal's reciprocal `1 / y`: its fast division's. Recip, - /// Metal's fast `rsqrt`, its hardware's inverse square root (`rsqrt::metal_rsqrt`): the one - /// Metal's `asin`, `acos`, `asinh`, and `acosh` in both modes take inside, the routine they - /// call for it (`E::fast_rsqrt`). A standalone `fast::rsqrt` keeps the device's `InverseSqrt`. - FastRsqrt, - /// `a b + c` rounded once, the fused multiply-add of Metal's polynomials, emulated: the routine - /// the others call for a fused step where the profile has no `OpFmaKHR` (`E::fused`), so - /// their many steps share one emulation. - Fused, /// Metal's `half` `atan` (both modes) before its rounding, of a `half` held as `float`: its own /// form, not its `float` function's. HalfAtan, /// The generic part of Metal's `half` `atan2(y, x)` before its rounding (finite nonzero /// operands; `math::atan2_special` answers the rest). HalfAtan2, - /// Metal's `half` `tan` before its rounding, its own form (`trig::half_tan`): its `half` - /// reduction and polynomial, and Metal's reciprocal in an odd quarter turn. + /// Metal's `half` `tan` before its rounding, its own form. HalfTan, - /// Metal's `half` `sin` before its rounding, its own form (`sincos::half_sin_cos`): a shorter - /// reduction than its `float` function's, and its hardware's `sinc`. + /// Metal's `half` `sin` before its rounding, its own form. HalfSin, /// Metal's `half` `cos` before its rounding, as [`Fun::HalfSin`]. HalfCos, - /// Metal's `half` `asinh` before its rounding, its own form (`hyper::half_asinh`). + /// Metal's `half` `asinh` before its rounding, its own form. HalfAsinh, } -/// What a routine calls or reads besides its own body ([`Fun::needs`]). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct Needs { - /// Metal's precise division, the precise division routine on one `float` lane (`divide.rs`). - pub division: bool, - /// Metal's `exp2` table (`exp::TABLE`). - pub exp2: bool, - /// Metal's `log2` table (`log::TABLE`). - pub log2: bool, - /// Metal's reciprocal table (`rcp::TABLE`). - pub rcp: bool, - /// Metal's reciprocal, [`Fun::Recip`]'s routine. - pub recip: bool, - /// Metal's precise inverse square root, [`Fun::Rsqrt`]'s routine. - pub inverse_root: bool, - /// Metal's fast inverse square root's table (`rsqrt::TABLE`). - pub rsqrt: bool, - /// Metal's fast inverse square root, [`Fun::FastRsqrt`]'s routine. - pub fast_inverse_root: bool, - /// The fused multiply-add, [`Fun::Fused`]'s routine where the profile has no `OpFmaKHR`. - pub fused: bool, - /// Metal's reduction table from `2^21` up (`quarter::QUARTER_TABLE`). - pub quarter: bool, - /// The model of Metal's hardware `sinc` (`sincos::SINC`). - pub sinc: bool, - /// Metal's `powr` reduction table (`log::POWR_TABLE`). - pub powr: bool, -} - -impl Needs { - /// What either needs. - pub fn or(self, other: Needs) -> Needs { - Needs { - division: self.division || other.division, - exp2: self.exp2 || other.exp2, - log2: self.log2 || other.log2, - rcp: self.rcp || other.rcp, - recip: self.recip || other.recip, - inverse_root: self.inverse_root || other.inverse_root, - rsqrt: self.rsqrt || other.rsqrt, - fast_inverse_root: self.fast_inverse_root || other.fast_inverse_root, - fused: self.fused || other.fused, - quarter: self.quarter || other.quarter, - sinc: self.sinc || other.sinc, - powr: self.powr || other.powr, - } - } -} - -/// The module's functions a routine calls and tables it reads for what it [`Needs`], each -/// defined once in the module before the routines that use them, so that no routine's answer -/// depends on the device's division or square root. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct Helpers { - /// The precise division routine on one `float` lane (`divide::define`). - pub division: Option, - /// Metal's `exp2` table (`exp::declare`). - pub exp2: Option, - /// Metal's `log2` table (`log::declare`). - pub log2: Option, - /// Metal's reciprocal table (`rcp::declare`). - pub rcp: Option, - /// [`Fun::Recip`]'s routine. - pub recip: Option, - /// [`Fun::Rsqrt`]'s routine. - pub inverse_root: Option, - /// Metal's fast inverse square root's table (`rsqrt::declare`). - pub rsqrt: Option, - /// [`Fun::FastRsqrt`]'s routine. - pub fast_inverse_root: Option, - /// [`Fun::Fused`]'s routine. - pub fused: Option, - /// Metal's reduction table from `2^21` up (`quarter::declare`). - pub quarter: Option, - /// The model of Metal's hardware `sinc` (`sincos::declare`). - pub sinc: Option, - /// Metal's `powr` reduction table (`log::declare_powr`). - pub powr: Option, -} - impl Fun { - /// The operand count. - pub fn arity(self) -> usize { - match self { - Fun::Fused => 3, - Fun::Atan2 | Fun::Fmod | Fun::Powr | Fun::HalfAtan2 => 2, - Fun::Atan(_) - | Fun::Asin(_) - | Fun::Acos(_) - | Fun::Sin - | Fun::Cos - | Fun::Tan - | Fun::FastSin - | Fun::FastCos - | Fun::SinPi(_) - | Fun::CosPi(_) - | Fun::TanPi(_) - | Fun::Sqrt - | Fun::Rsqrt - | Fun::Exp2 - | Fun::Exp - | Fun::Exp10 - | Fun::Log2 - | Fun::Log - | Fun::Log10 - | Fun::Sinh - | Fun::Cosh - | Fun::Tanh - | Fun::Asinh - | Fun::Acosh - | Fun::Atanh - | Fun::FastAsinh - | Fun::FastAcosh - | Fun::Recip - | Fun::FastRsqrt - | Fun::HalfAtan - | Fun::HalfTan - | Fun::HalfSin - | Fun::HalfCos - | Fun::HalfAsinh => 1, - } - } - - /// The module's routines `self`'s routine calls and tables it reads ([`Helpers`]): Metal's - /// precise division, its `exp2` table, which `exp2`, `exp`, `exp10`, `powr`, `sinh`, `cosh`, - /// and `tanh` read, its `powr` reduction table, which `powr` reads, its `log2` table, which - /// `log2`, `log`, `log10`, both modes' `asinh` and `acosh`, the `half` `asinh`, and the precise - /// `atanh` read, its reciprocal ([`Fun::Recip`]'s routine), which `sinh`, `cosh`, `tanh`, - /// `acosh`, `atanh`, both `atan`s, the precise `atan2`, `tanpi`, and the `half` `tan` call, - /// the reciprocal's table, which that routine reads, its fast inverse square root - /// ([`Fun::FastRsqrt`]'s routine), which `asin`, `acos`, both modes' `asinh` and `acosh`, and - /// the `half` `asinh` call, with its table and its precise inverse square root - /// ([`Fun::Rsqrt`]'s routine), which that routine reads and calls, the fused step - /// ([`Fun::Fused`]'s routine), which the routines with Metal's fused steps call where the - /// profile has no `OpFmaKHR`, Metal's reduction table from `2^21` up, which the precise `sin`, - /// `cos` and `tan` read (and the fast `sin` and `cos`, past `π`), and the model of its - /// hardware `sinc`, which `sin`, `cos`, `sinpi`, `cospi`, `tanpi`, and the `half` `sin` and - /// `cos` read. `sqrt` and `rsqrt` correct the device's own exactly, so they call neither. - pub fn needs(self) -> Needs { - let division = match self { - // Metal's `atan` takes its reciprocal, not a quotient; its `asin` and `acos` take a - // root of its inverse root, not a square root. - Fun::Atan(_) | Fun::Asin(_) | Fun::Acos(_) => false, - Fun::Atan2 - | Fun::Tan - | Fun::Log2 - | Fun::Log - | Fun::Log10 - | Fun::Asinh - | Fun::Acosh - | Fun::Atanh - | Fun::FastAsinh - | Fun::FastAcosh - | Fun::Recip - | Fun::HalfAtan - | Fun::HalfAtan2 - | Fun::HalfAsinh => true, - Fun::Sinh - | Fun::Cosh - | Fun::Tanh - | Fun::Sin - | Fun::Cos - | Fun::FastSin - | Fun::FastCos - | Fun::SinPi(_) - | Fun::CosPi(_) - | Fun::TanPi(_) - | Fun::Sqrt - | Fun::Rsqrt - | Fun::FastRsqrt - | Fun::Fused - | Fun::Fmod - | Fun::Exp2 - | Fun::Exp - | Fun::Exp10 - | Fun::Powr - | Fun::HalfTan - | Fun::HalfSin - | Fun::HalfCos => false, - }; - Needs { - division, - exp2: matches!( - self, - Fun::Exp2 | Fun::Exp | Fun::Exp10 | Fun::Powr | Fun::Sinh | Fun::Cosh | Fun::Tanh - ), - log2: matches!( - self, - Fun::Log2 - | Fun::Log - | Fun::Log10 - | Fun::Asinh - | Fun::Acosh - | Fun::Atanh - | Fun::FastAsinh - | Fun::FastAcosh - | Fun::HalfAsinh - ), - rcp: self == Fun::Recip, - recip: matches!( - self, - Fun::Sinh - | Fun::Cosh - | Fun::Tanh - | Fun::Atan(_) - | Fun::Atan2 - | Fun::Acosh - | Fun::Atanh - | Fun::TanPi(_) - | Fun::HalfTan - ), - inverse_root: self == Fun::FastRsqrt, - rsqrt: self == Fun::FastRsqrt, - fast_inverse_root: matches!( - self, - Fun::Asin(_) - | Fun::Acos(_) - | Fun::Asinh - | Fun::Acosh - | Fun::FastAsinh - | Fun::FastAcosh - | Fun::HalfAsinh - ), - fused: matches!( - self, - Fun::Atan(_) - | Fun::Asin(_) - | Fun::Acos(_) - | Fun::Atan2 - | Fun::Exp - | Fun::Exp10 - | Fun::Log - | Fun::Log10 - | Fun::Powr - | Fun::Sinh - | Fun::Cosh - | Fun::Tanh - | Fun::Asinh - | Fun::Acosh - | Fun::Atanh - | Fun::FastAsinh - | Fun::FastAcosh - | Fun::Tan - | Fun::HalfTan - | Fun::HalfSin - | Fun::HalfCos - | Fun::HalfAsinh - | Fun::Sin - | Fun::Cos - | Fun::FastSin - | Fun::FastCos - | Fun::TanPi(_) - ), - quarter: matches!( - self, - Fun::Tan | Fun::Sin | Fun::Cos | Fun::FastSin | Fun::FastCos - ), - sinc: matches!( - self, - Fun::Sin - | Fun::Cos - | Fun::HalfSin - | Fun::HalfCos - | Fun::FastSin - | Fun::FastCos - | Fun::SinPi(_) - | Fun::CosPi(_) - | Fun::TanPi(_) - ), - powr: self == Fun::Powr, - } - } - /// Whether a device whose `float` functions are Metal's answers `self` with its own - /// instruction in an entry whose functions Metal compiles in mode `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 the - /// device'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`, and `tanpi` are none of - /// the instructions SPIRV-Cross emits (it emits no `sinpi`), so no device answers a precise - /// call: the device's `Sin` and `Cos` of `float(π) r` matched Metal on 849, 922 and 637 of case - /// 087758cb's 1,024 lanes, where Metal's own forms through the `sinc`'s model - /// are its word at 99.5 % to 99.99 % of every measured range. A fast call is that composition, - /// in either mode: within Apple's fast bound (MSL Table 8.2), the near-equivalent the user's - /// fast-math sign-off accepts, at a third to a sixth of the routine's instructions per call - /// (the orchestrator's ruling of 2026-10-07). + /// instruction as Metal's function in an entry whose functions Metal compiles in mode + /// `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`, + /// 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 + /// either mode, within Apple's fast bound (MSL Table 8.2) and off Metal's own form + /// ([`Fun::device_near_equivalent`]). /// - /// Of the second stage's: `exp2` and `log2` are the device's in either mode (Metal's fast ones - /// are its precise ones), and so is `tanh` (SPIRV-Cross emits `precise::tanh` whatever the - /// flags); `powr` and the other hyperbolic functions only in a precise module. No - /// `GLSL.std.450` instruction reaches Metal's `exp10` and `log10`, but Metal's own compositions - /// of its `exp2` and `log2` do, in either mode (`math::metal_exp`, `math::metal_log`): its - /// precise `exp10` is `fma(E, d ln 2, E)` of `E = exp2(RN(x c))` and the product's error `d`, - /// `c = log2(10)` (every lane of case 7b283404 on the M3 and the M4), and its `log10` is - /// `log2(x) RN(log10(2))` with its own polynomial next to 1 (every `float` of our probe's - /// binades). Its precise `exp` and `log` are the device's own in a - /// precise module and the same compositions, with `log2(e)` and `RN(ln 2)` and `log`'s - /// polynomial, in a fast-math one. Its reciprocal is the device's `1 / y` in a fast-math - /// module, where Metal compiles the division with its fast reciprocal, and not in a precise - /// one, whose quotient is correctly rounded. + /// `exp2` and `log2` are Metal's in either mode (Metal's fast ones are its precise ones), and + /// so is `tanh` (SPIRV-Cross emits `precise::tanh` whatever the flags); `powr` and the other + /// hyperbolic functions only in a precise module. No `GLSL.std.450` instruction reaches + /// Metal's `exp10` and `log10`, but Metal's own compositions of its `exp2` and `log2` do, in + /// either mode (`math::metal_exp`, `math::metal_log`), and so do they for its precise `exp` + /// and `log`. Its reciprocal is the device's `1 / y` in a fast-math module, where Metal + /// compiles the division with its fast reciprocal, and not in a precise one, whose quotient is + /// correctly rounded. The device's instruction on a `half` held as `float` is its `float` + /// function, never Metal's `half` form. pub fn device_answers(self, module: Mode) -> bool { match self { Fun::FastSin | Fun::FastCos => true, @@ -505,18 +181,15 @@ impl Fun { | Fun::Asinh | Fun::Acosh | Fun::Atanh => module == Mode::Precise, - // Metal's fast `rsqrt` is the device's `InverseSqrt` in a fast-math module, and its - // fast `asinh` and `acosh` the device's `Asinh` and `Acosh`. - Fun::Recip | Fun::FastRsqrt | Fun::FastAsinh | Fun::FastAcosh => module == Mode::Fast, - // The device's instruction on a `half` held as `float` is its `float` function; the - // fused step is no float function. + // Metal's fast `asinh` and `acosh` are the device's `Asinh` and `Acosh` in a fast-math + // module. + Fun::Recip | Fun::FastAsinh | Fun::FastAcosh => module == Mode::Fast, Fun::HalfAtan | Fun::HalfAtan2 | Fun::HalfTan | Fun::HalfSin | Fun::HalfCos - | Fun::HalfAsinh - | Fun::Fused => false, + | Fun::HalfAsinh => false, Fun::Atan2 | Fun::Exp2 | Fun::Log2 @@ -528,23 +201,12 @@ impl Fun { } } - /// Whether native device maths (`FloatFunctions::Native`) takes the device's instruction for - /// the routine's function: every function but precise `fmod`, whose device form - /// (`OpFRem`, `x - y · trunc(x / y)` at the device's precision) Vulkan leaves unbounded - /// once the quotient passes `2^24`, where Metal's is exact, and the fused step, which only - /// the routines call. The rest are within Vulkan's precision table - /// (`PrecisionNote::NativeTranscendentals`). - pub fn native(self) -> bool { - !matches!(self, Fun::Fmod | Fun::Fused) - } - - /// Whether the device answers the routine's function, where it does - /// ([`Fun::device_answers`]), by a near-equivalent of Metal's function rather than by Metal's - /// function itself: Metal's fast `sinpi`, `cospi`, and `tanpi`, which the device answers by - /// its `Sin` and `Cos` of `float(π) r`, within Apple's fast bound but off Metal's own forms - /// (case f6524207 differs at 175, 102, and 264 of its 1, 024 lanes through MoltenVK). Every - /// other function the device answers is Metal's own, word for word - /// (`DriverDeviation::MetalFloatFunctions`). + /// Whether the device answers the function, where it does ([`Fun::device_answers`]), by a + /// near-equivalent of Metal's function rather than by Metal's function itself: Metal's fast + /// `sinpi`, `cospi`, and `tanpi`, which the device answers by its `Sin` and `Cos` of + /// `float(π) r`, within Apple's fast bound but off Metal's own forms (case f6524207 differs at + /// 175, 102, and 264 of its 1,024 lanes through MoltenVK). Every other function the device + /// answers is Metal's own, word for word (`DriverDeviation::MetalFloatFunctions`). pub fn device_near_equivalent(self) -> bool { matches!( self, @@ -552,204 +214,39 @@ impl Fun { ) } - /// Whether Metal's answer to the routine's function is the one right value at every operand, - /// so that the routine's answer, and the device's where it answers the function - /// ([`Fun::device_answers`]: Metal's own precise function), is Metal's on every device in - /// either math mode. Metal documents its precise `sqrt` and `rsqrt` correctly rounded and its - /// `fmod` exact (MSL Table 8.1 for `float`, Table 8.3 for `half`), and its `half` functions - /// answer so at every `half` operand: these routines, rounded to `half`, are Metal's word at - /// all 65,536. The routines compute that value, the correctly rounded root and inverse root and - /// the exact remainder. Case 7b283404's lanes, which match on every venue, are a check of it, - /// not its proof. Every other routine is a model of a function Apple bounds by ulps (its - /// reciprocal and fast inverse root among them), or the fused step the models call, which is no - /// call's function. + /// Whether the call takes the device's instruction for the function: every function but + /// precise `fmod`, whose routine computes Metal's exact remainder ([`fmod`]). Its + /// precision is Vulkan's (`PrecisionNote::NativeTranscendentals`). + pub fn native(self) -> bool { + self != Fun::Fmod + } + + /// Whether Metal's answer to the function is the one right value at every operand, so that + /// the routine's answer, and the device's where it is Metal's own ([`Fun::device_answers`]), is + /// Metal's on every device in either math mode: precise `fmod`, which Metal documents exact + /// (MSL Table 8.1 for `float`, Table 8.3 for `half`), and which its routine computes. pub fn correctly_rounded(self) -> bool { + self == Fun::Fmod + } + + /// The function's operands. + pub fn arity(self) -> usize { match self { - Fun::Sqrt | Fun::Rsqrt | Fun::Fmod => true, - Fun::Atan(_) - | Fun::Asin(_) - | Fun::Acos(_) - | Fun::Atan2 - | Fun::Sin - | Fun::Cos - | Fun::Tan - | Fun::FastSin - | Fun::FastCos - | Fun::SinPi(_) - | Fun::CosPi(_) - | Fun::TanPi(_) - | Fun::Exp2 - | Fun::Exp - | Fun::Exp10 - | Fun::Log2 - | Fun::Log - | Fun::Log10 - | Fun::Powr - | Fun::Sinh - | Fun::Cosh - | Fun::Tanh - | Fun::Asinh - | Fun::Acosh - | Fun::Atanh - | Fun::FastAsinh - | Fun::FastAcosh - | Fun::Recip - | Fun::FastRsqrt - | Fun::Fused - | Fun::HalfAtan - | Fun::HalfAtan2 - | Fun::HalfTan - | Fun::HalfSin - | Fun::HalfCos - | Fun::HalfAsinh => false, + Fun::Atan2 | Fun::Fmod | Fun::Powr | Fun::HalfAtan2 => 2, + _ => 1, } } - - /// The float function whose operand table ([`denormal::operand`]) the routine reads its - /// operands by; `None` for the reciprocal and the fast inverse square root, which answer a - /// denormal operand themselves (as a zero). - pub fn float_fn(self) -> Option { - Some(match self { - Fun::Atan(Mode::Precise) => FloatFn::Atan, - Fun::Atan(Mode::Fast) => FloatFn::FastAtan, - Fun::Asin(Mode::Precise) => FloatFn::Asin, - Fun::Asin(Mode::Fast) => FloatFn::FastAsin, - Fun::Acos(Mode::Precise) => FloatFn::Acos, - Fun::Acos(Mode::Fast) => FloatFn::FastAcos, - Fun::Atan2 => FloatFn::Atan2, - Fun::Sin => FloatFn::Sin, - Fun::Cos => FloatFn::Cos, - Fun::Tan => FloatFn::Tan, - Fun::FastSin => FloatFn::FastSin, - Fun::FastCos => FloatFn::FastCos, - Fun::SinPi(Mode::Precise) => FloatFn::SinPi, - Fun::CosPi(Mode::Precise) => FloatFn::CosPi, - Fun::TanPi(Mode::Precise) => FloatFn::TanPi, - Fun::SinPi(Mode::Fast) => FloatFn::FastSinPi, - Fun::CosPi(Mode::Fast) => FloatFn::FastCosPi, - Fun::TanPi(Mode::Fast) => FloatFn::FastTanPi, - Fun::Sqrt => FloatFn::Sqrt, - Fun::Rsqrt => FloatFn::Rsqrt, - Fun::Fmod => FloatFn::Fmod, - Fun::Exp2 => FloatFn::Exp2, - Fun::Exp => FloatFn::Exp, - Fun::Exp10 => FloatFn::Exp10, - Fun::Log2 => FloatFn::Log2, - Fun::Log => FloatFn::Log, - Fun::Log10 => FloatFn::Log10, - Fun::Powr => FloatFn::Powr, - Fun::Sinh => FloatFn::Sinh, - Fun::Cosh => FloatFn::Cosh, - Fun::Tanh => FloatFn::Tanh, - Fun::Asinh => FloatFn::Asinh, - Fun::Acosh => FloatFn::Acosh, - Fun::Atanh => FloatFn::Atanh, - Fun::FastAsinh => FloatFn::FastAsinh, - Fun::FastAcosh => FloatFn::FastAcosh, - // A `half` held as `float` is never an `f32` denormal. - Fun::Recip - | Fun::FastRsqrt - | Fun::Fused - | Fun::HalfAtan - | Fun::HalfAtan2 - | Fun::HalfTan - | Fun::HalfSin - | Fun::HalfCos - | Fun::HalfAsinh => return None, - }) - } - - /// An upper estimate of the routine's SPIR-V words, with its constants and types, without - /// the routines it calls ([`Fun::needs`]), which a module holds once and charges on their own. - pub fn words(self) -> u32 { - match self { - // The polynomial's fused steps (each one `OpFmaKHR`, or a call of the fused step's - // routine without it), the reduction's arms, and the selects (Metal's reciprocal and - // inverse root are their own routines): about 270, 240, 330, and 350 words; precise - // `asin`'s five polynomials about 660, precise `acos`'s three about 410. - Fun::Atan(_) => 300, - Fun::Asin(Mode::Precise) => 700, - Fun::Acos(Mode::Precise) => 450, - Fun::Asin(Mode::Fast) | Fun::Acos(Mode::Fast) => 400, - // Precise `atan`'s steps after the quotient (the precise division is its own - // routine). - Fun::Atan2 => 350, - // Metal's reduction in fused steps with its table (`quarter::TABLE_WORDS`), the fold, - // and the `sinc`'s model in integers with its table (`sincos::TABLE_WORDS`). - Fun::Sin | Fun::Cos => 600 + quarter::TABLE_WORDS + sincos::TABLE_WORDS, - // Metal's reduction in fused steps, its two polynomials, and the selects (the - // quotient is the precise division's routine): about 380 words, with its table - // (`quarter::TABLE_WORDS`). - Fun::Tan => 500 + quarter::TABLE_WORDS, - Fun::FastSin | Fun::FastCos => 700 + quarter::TABLE_WORDS + sincos::TABLE_WORDS, - // The half turns, the selects, and the `sinc`'s model in integers (twice for `tanpi`, - // with its fused step and the call of Metal's reciprocal) with its table - // (`sincos::TABLE_WORDS`). - Fun::SinPi(_) | Fun::CosPi(_) => 560 + sincos::TABLE_WORDS, - Fun::TanPi(_) => 750 + sincos::TABLE_WORDS, - Fun::Sqrt => 700, - Fun::Rsqrt => 900, - Fun::Fmod => 600, - // Metal's `exp2` and its table (`exp::TABLE_WORDS`), and its compositions. - Fun::Exp2 => 500 + exp::TABLE_WORDS, - Fun::Exp | Fun::Exp10 => 1300 + exp::TABLE_WORDS, - // Metal's `log2` and its table (`log::TABLE_WORDS`), and its products. - Fun::Log2 => 1900 + log::TABLE_WORDS, - Fun::Log | Fun::Log10 => 2100 + log::TABLE_WORDS, - // Metal's logarithm pair through its table (`log::POWR_TABLE_WORDS`), the product, - // its `exp2` with that table (`exp::TABLE_WORDS`), the growth, and the selects. - Fun::Powr => 1900 + exp::TABLE_WORDS + log::POWR_TABLE_WORDS, - // Their exponentials with `exp2`'s table; Metal's reciprocal is its own routine. - Fun::Sinh | Fun::Cosh => 1200 + exp::TABLE_WORDS, - Fun::Tanh => 1400 + exp::TABLE_WORDS, - // Metal's polynomials (fused steps: `OpFmaKHR`, or calls of the fused step's routine) - // and its forms, its `log2` inline with the table (`log::TABLE_WORDS`); the inverse - // root and Metal's reciprocal are their own routines. - Fun::Asinh => 2200 + log::TABLE_WORDS, - Fun::Acosh | Fun::Atanh => 2100 + log::TABLE_WORDS, - // The root's operand and its fused sum, the selects, and Metal's `log2` inline with - // its table (`log::TABLE_WORDS`); the inverse root is its own routine. - Fun::FastAsinh | Fun::FastAcosh => 2000 + log::TABLE_WORDS, - // Metal's reciprocal and its table (`rcp::TABLE_WORDS`). - Fun::Recip => 700 + rcp::TABLE_WORDS, - // Metal's fast inverse square root and its table (`rsqrt::TABLE_WORDS`); the - // precise inverse root is its own routine. - Fun::FastRsqrt => 900 + rsqrt::TABLE_WORDS, - // The emulated fused step: an exact product's splits, three exact sums, and the odd - // rounding, about 400 words. - Fun::Fused => 450, - // Their polynomials' products and sums and the selects (the precise division is its - // own routine): about 200 and 270 words. - Fun::HalfAtan => 300, - Fun::HalfAtan2 => 400, - // The reduction's three fused steps, the polynomial's three, and the selects (Metal's - // reciprocal is its own routine): about 180 words. - Fun::HalfTan => 200, - // The reduction's three fused steps, the fold, the selects, and the `sinc`'s model in - // integers (about 510 words) with its table (`sincos::TABLE_WORDS`). - Fun::HalfSin | Fun::HalfCos => 540 + sincos::TABLE_WORDS, - // Two fused steps, the selects, and Metal's `log2` inline with its table - // (`log::TABLE_WORDS`); the inverse root is its own routine. - Fun::HalfAsinh => 2000 + log::TABLE_WORDS, - } - } - - /// The census name of the strategies that call it: the float functions at the device's - /// precision class, whose answer it replaces. - pub fn name(self) -> &'static str { - "arith.float_fn.device_transcendental" - } } -/// The routines a call of float function `op` on form `f` may call: its own and those of the -/// functions it composes. `float` lanes take routines, and so do `half` lanes, which are held -/// as `float` and computed by a `float` function before their rounding: Metal's `half` functions -/// are the same in both math modes (the half probe, cases dc0fee8f and 3ef7c1c5; every `half` of -/// our probe), so `refine_float` refines only `float` calls, and the `float` function of a -/// `half` one is `math::metal_half`'s, whose `tanh` calls Metal's `exp2` and reciprocal -/// (`math::half_tanh`); its `atan`, `atan2`, `tan`, `sin`, `cos`, and `asinh` are Metal's own -/// `half` forms ([`Fun::HalfAtan`], [`Fun::HalfAtan2`], [`Fun::HalfTan`]; [`Fun::HalfSin`], -/// [`Fun::HalfCos`], [`Fun::HalfAsinh`]). Another format keeps the device's instruction. +/// The functions a call of float function `op` on form `f` takes: its own and those of the +/// functions it composes. `float` lanes take them, and so do `half` lanes, which are held as +/// `float` and computed by a `float` function before their rounding: Metal's `half` functions are +/// the same in both math modes (the half probe, cases dc0fee8f and 3ef7c1c5; every `half` of our +/// probe), so `refine_float` refines only `float` calls, and the `float` function of a `half` one +/// is `math::metal_half`'s, whose `tanh` takes Metal's `exp2` and reciprocal (`math::half_tanh`); +/// its `atan`, `atan2`, `tan`, `sin`, `cos`, and `asinh` are Metal's own `half` forms +/// ([`Fun::HalfAtan`], [`Fun::HalfAtan2`], [`Fun::HalfTan`]; [`Fun::HalfSin`], [`Fun::HalfCos`], +/// [`Fun::HalfAsinh`]). Another format takes none. pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] { if !matches!(f.float_fmt(), Some(FloatFmt::F32 | FloatFmt::Half)) { return &[]; @@ -782,7 +279,7 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] { 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::FastSin, Fun::FastCos], FloatFn::SinPi => &[Fun::SinPi(Mode::Precise)], FloatFn::CosPi => &[Fun::CosPi(Mode::Precise)], FloatFn::TanPi => &[Fun::TanPi(Mode::Precise)], @@ -792,8 +289,8 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] { FloatFn::Sqrt => &[Fun::Sqrt], FloatFn::Rsqrt => &[Fun::Rsqrt], FloatFn::Fmod => &[Fun::Fmod], - // The second stage: the precise functions' routines, and the fast ones' formulas of Metal's - // `exp2` and `log2` (MSL Table 8.2), the latter the fast `log2`'s routine. + // The precise functions, and the fast ones' formulas of Metal's `exp2` and `log2` (MSL + // Table 8.2). FloatFn::Exp2 => &[Fun::Exp2], FloatFn::Exp => &[Fun::Exp], FloatFn::Exp10 => &[Fun::Exp10], @@ -811,8 +308,8 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] { | FloatFn::FastExp10 | FloatFn::FastSinh | FloatFn::FastCosh - | FloatFn::FastTanh { .. } => &[Fun::Exp2], - FloatFn::FastLog | FloatFn::FastLog10 | FloatFn::FastAtanh { .. } => &[Fun::Log2], + | FloatFn::FastTanh => &[Fun::Exp2], + FloatFn::FastLog | FloatFn::FastLog10 | FloatFn::FastAtanh => &[Fun::Log2], FloatFn::FastAsinh => &[Fun::FastAsinh], FloatFn::FastAcosh => &[Fun::FastAcosh], FloatFn::FastPow | FloatFn::FastPowr => &[Fun::Exp2, Fun::Log2], @@ -820,8 +317,16 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] { } } -/// An upper estimate of the SPIR-V words per use of a routine of `arity` operands on `lanes` -/// lanes: each lane's operand extractions and call, and the result's construction. +/// The census name of precise `fmod`'s routine: the float functions at the device's precision +/// class, whose answer it replaces. +pub const FMOD_NAME: &str = "arith.float_fn.device_transcendental"; + +/// An upper estimate of precise `fmod`'s routine's SPIR-V words, with its constants and types. +pub const FMOD_WORDS: u32 = 600; + +/// An upper estimate of the SPIR-V words per use of a function of `arity` operands on `lanes` +/// lanes: each lane's operand extractions and call of a routine, and the result's construction, +/// which bounds the device's instruction for it too. pub fn use_words(lanes: u8, arity: usize) -> u32 { let arity = u32::try_from(arity).unwrap_or(u32::MAX); let lanes = u32::from(lanes); @@ -830,54 +335,26 @@ pub fn use_words(lanes: u8, arity: usize) -> u32 { .saturating_add(8) } -/// Which routines an entry's calls take, as emission reads them: the mode of the device's own -/// functions where they are Metal's, and the routines the module defines. +/// What an entry's calls take, as emission reads them: the mode Metal compiles the entry's +/// functions in where the device's are Metal's, the routine of precise `fmod` where the module +/// defines one, and whether Metal's minimum and maximum functions are the device's. #[derive(Clone, Copy, Debug)] -pub struct Lib<'a> { - answers: Answers, - funcs: &'a BTreeMap, +pub struct Lib { + metal: Option, + fmod: Option, /// Whether the device's `NMin`, `NMax` and `NClamp` are Metal's `fmin`, `fmax` and `clamp` /// ([`Lib::with_min_max`]). min_max: bool, - /// Whether `mix` and `fast::sqrt` are the device's `FMix` and `Sqrt` - /// ([`Lib::with_native_order`]). - native_order: bool, } -/// Which functions the device's instructions answer. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Answers { - /// Metal's, in the entry's mode ([`module_mode`]). - Metal(Mode), - /// The device's own: every [`Fun`] takes its routine. - Device, - /// Native device maths (`FloatFunctions::Native`): every function the device's instruction, - /// or Metal's composition of the device's instructions, whatever its mode - /// ([`Fun::native`]). - Native, - /// Every function, whatever its mode: the instruction itself, for unit tests of the - /// sequences around it. - #[cfg(test)] - Instructions, -} - -/// The routines of no module, for [`Lib::instructions`]. -#[cfg(test)] -static NO_ROUTINES: BTreeMap = BTreeMap::new(); - -impl<'a> Lib<'a> { - /// The routines of a module whose device functions are Metal's in mode `metal` (`None`: - /// the device's own), defined as `funcs`. - pub fn new(metal: Option, funcs: &'a BTreeMap) -> Lib<'a> { - let answers = match metal { - Some(m) => Answers::Metal(m), - None => Answers::Device, - }; +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 { - answers, - funcs, + metal, + fmod, min_max: false, - native_order: false, } } @@ -885,7 +362,7 @@ impl<'a> Lib<'a> { /// own `fmin`, `fmax` and `clamp` if `device` (`ArithPlan::device_min_max`): Metal's minimum /// and maximum family on `float` and `half` then takes those instructions /// (`math::metal_min_max` otherwise). - pub fn with_min_max(self, device: bool) -> Lib<'a> { + pub fn with_min_max(self, device: bool) -> Lib { Lib { min_max: device, ..self @@ -900,90 +377,43 @@ impl<'a> Lib<'a> { /// 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<'static> { - Lib { - answers: Answers::Instructions, - funcs: &NO_ROUTINES, - min_max: false, - native_order: false, - } + pub fn instructions() -> Lib { + Lib::new(None, None) } - /// The library of native device maths (`FloatFunctions::Native`): the device's instruction - /// for every function [`Fun::native`] gives it, `funcs`' routines for the rest. - pub fn native(funcs: &'a BTreeMap) -> Lib<'a> { - Lib { - answers: Answers::Native, - funcs, - min_max: false, - native_order: false, - } - } - - /// This library, where Metal's `mix` and `fast::sqrt` round in the device's order if - /// `native` (`ArithPlan::native_order`): a `float` or `half` `mix` is the device's `FMix` and - /// `fast::sqrt` its `Sqrt`. - pub fn with_native_order(self, native: bool) -> Lib<'a> { - Lib { - native_order: native, - ..self - } - } - - /// Whether `mix` and `fast::sqrt` round in the device's order ([`Lib::with_native_order`]). - pub fn orders_natively(&self) -> bool { - self.native_order - } - - /// Whether the device's instructions are Metal's functions in mode `m` (a unit test's - /// `Lib::instructions` are, in either). - pub fn metal_in(&self, m: Mode) -> bool { - match self.answers { - Answers::Metal(x) => x == m, - Answers::Device => false, - // Native device maths takes the device's instruction wherever Metal's in either mode - // would. - Answers::Native => true, - #[cfg(test)] - Answers::Instructions => true, - } + /// 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. Not native device maths, - /// whose instructions are the device's own. + /// `fast::sin` and `fast::cos` themselves, past their flush point too. pub fn metal_fast(&self) -> bool { - self.answers == Answers::Metal(Mode::Fast) + self.metal_in(Mode::Fast) } - /// Whether the device's instruction answers `fun` (no routine is called). - pub fn device(&self, fun: Fun) -> bool { - match self.answers { - Answers::Metal(m) => fun.device_answers(m), - Answers::Device => false, - Answers::Native => fun.native(), - #[cfg(test)] - Answers::Instructions => true, - } + /// Whether `mix` and `fast::sqrt` round in the device's order, its `FMix` and `Sqrt`: on every + /// device whose functions are not Metal's. Where they are (MoltenVK), Metal's own forms of its + /// own fused multiply-add and `rsqrt` are Metal's answer and stay. + pub fn orders_natively(&self) -> bool { + self.metal.is_none() } - /// `fun` of `args` (`float` lanes of form `f`): one call of its routine per lane. - pub fn call( + /// Metal's precise `fmod` of `x` and `y` (`float` lanes of form `f`) by its routine, one call + /// per lane; `None` where the module takes the device's `OpFRem` ([`Fun::device_answers`]). + pub fn fmod( &self, fb: &mut FunctionBuilder<'_>, - fun: Fun, f: Form, - args: &[Value], - ) -> BResult { - let func = *self - .funcs - .get(&fun) - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - if args.len() != fun.arity() { - return Err(BuildError::Type(TypeRule::FunctionSignature)); + x: Value, + y: Value, + ) -> BResult> { + match self.fmod { + Some(func) => per_lane(fb, func, f, &[x, y]).map(Some), + None => Ok(None), } - per_lane(fb, func, f, args) } } @@ -1009,161 +439,14 @@ fn per_lane(fb: &mut FunctionBuilder<'_>, func: FuncId, f: Form, args: &[Value]) fb.composite_construct(t, &lanes) } -/// Define the routine of `fun`: a function of [`Fun::arity`] `float` values returning one, which -/// calls the module's `helpers` for what it needs ([`Fun::needs`]; a missing one is an error). -/// `fma`: the profile's `float` fused multiply-add is `OpFmaKHR`, which the trigonometric and the -/// second stage's routines take for a product's exact error (`E::exact_error`). -pub fn define(mb: &mut ModuleBuilder, fun: Fun, fma: bool, helpers: Helpers) -> BResult { - define_with(mb, fun, false, fma, helpers) -} - -/// [`define`] with the helpers `fun` needs defined first in `mb`, the precise division by the -/// path a profile of `fma` takes (a unit test's module of one routine). -#[cfg(test)] -pub fn define_alone(mb: &mut ModuleBuilder, fun: Fun, fma: bool) -> BResult { - let helpers = define_helpers(mb, fun.needs(), false, fma)?; - define_with(mb, fun, false, fma, helpers) -} - -/// [`define_alone`], with the device's division and square root moved to the edge of what the -/// routines correct (a unit test's model of a device whose quotient and root are not correctly -/// rounded): a normal quotient 2 ulp and a normal root 3 ulp either way, by its bits, in the -/// routine and its helpers. -#[cfg(test)] -pub fn define_rough(mb: &mut ModuleBuilder, fun: Fun, fma: bool) -> BResult { - let helpers = define_helpers(mb, fun.needs(), true, fma)?; - define_with(mb, fun, true, fma, helpers) -} - -/// Define the helpers `needs` asks for (the reciprocal's own division included), rough or not. -#[cfg(test)] -pub fn define_helpers( - mb: &mut ModuleBuilder, - needs: Needs, - rough: bool, - fma: bool, -) -> BResult { - use crate::lower::arith::divide::{self, Path, Routine}; - let mut helpers = Helpers::default(); - if needs.fused && !fma { - helpers.fused = Some(define_with(mb, Fun::Fused, rough, fma, helpers)?); - } - let recip_needs = Fun::Recip.needs(); - if needs.division || (needs.recip && recip_needs.division) { - let r = Routine { - lanes: 1, - path: if fma { Path::Fused } else { Path::Integer }, - }; - let moved = |fb: &mut FunctionBuilder<'_>, a: Value, b: Value| -> BResult { - let mut e = E { - fb, - rough, - fma, - helpers: Helpers::default(), - }; - e.device_div(a, b) - }; - helpers.division = Some(if rough { - divide::define_with(mb, r, &moved)? - } else { - divide::define(mb, r)? - }); - } - if needs.exp2 { - helpers.exp2 = Some(exp::declare(mb)?); - } - if needs.log2 { - helpers.log2 = Some(log::declare(mb)?); - } - if needs.rcp || (needs.recip && recip_needs.rcp) { - helpers.rcp = Some(rcp::declare(mb)?); - } - if needs.recip { - helpers.recip = Some(define_with(mb, Fun::Recip, rough, fma, helpers)?); - } - let fast_root_needs = Fun::FastRsqrt.needs(); - if needs.inverse_root || (needs.fast_inverse_root && fast_root_needs.inverse_root) { - helpers.inverse_root = Some(define_with(mb, Fun::Rsqrt, rough, fma, helpers)?); - } - if needs.rsqrt || (needs.fast_inverse_root && fast_root_needs.rsqrt) { - helpers.rsqrt = Some(rsqrt::declare(mb)?); - } - if needs.quarter { - helpers.quarter = Some(quarter::declare(mb)?); - } - if needs.sinc { - helpers.sinc = Some(sincos::declare(mb)?); - } - if needs.powr { - helpers.powr = Some(log::declare_powr(mb)?); - } - if needs.fast_inverse_root { - helpers.fast_inverse_root = Some(define_with(mb, Fun::FastRsqrt, rough, fma, helpers)?); - } - Ok(helpers) -} - -fn define_with( - mb: &mut ModuleBuilder, - fun: Fun, - rough: bool, - fma: bool, - helpers: Helpers, -) -> BResult { +/// Define precise `fmod`'s routine: a function of two `float` values returning Metal's exact +/// remainder ([`fmod::fmod`]). +pub fn define_fmod(mb: &mut ModuleBuilder) -> BResult { let t = mb.ty(Type::Float { width: 32 })?; let mut fb = mb.routine(t)?; - let mut args = Vec::with_capacity(fun.arity()); - for _ in 0..fun.arity() { - args.push(fb.param(t)?); - } - let mut e = E { - fb: &mut fb, - rough, - fma, - helpers, - }; - let v = match (fun, args.as_slice()) { - (Fun::Atan(m), [x]) => atan::atan(&mut e, m, *x)?, - (Fun::Asin(m), [x]) => atan::asin(&mut e, m, *x)?, - (Fun::Acos(m), [x]) => atan::acos(&mut e, m, *x)?, - (Fun::Atan2, [y, x]) => atan::atan2(&mut e, *y, *x)?, - (Fun::Sin, [x]) => sincos::sin_cos(&mut e, trig::Trig::Sin, *x)?, - (Fun::Cos, [x]) => sincos::sin_cos(&mut e, trig::Trig::Cos, *x)?, - (Fun::Tan, [x]) => tan::tan(&mut e, *x)?, - (Fun::FastSin, [x]) => trig::fast(&mut e, trig::Trig::Sin, *x)?, - (Fun::FastCos, [x]) => trig::fast(&mut e, trig::Trig::Cos, *x)?, - (Fun::SinPi(_), [x]) => pi::pi(&mut e, fun, pi::Pi::Sin, *x)?, - (Fun::CosPi(_), [x]) => pi::pi(&mut e, fun, pi::Pi::Cos, *x)?, - (Fun::TanPi(_), [x]) => pi::pi(&mut e, fun, pi::Pi::Tan, *x)?, - (Fun::Sqrt, [x]) => root::root(&mut e, root::Root::Sqrt, *x)?, - (Fun::Rsqrt, [x]) => root::root(&mut e, root::Root::Rsqrt, *x)?, - (Fun::Fmod, [x, y]) => fmod::fmod(&mut e, *x, *y)?, - (Fun::Exp2, [x]) => exp::exp2(&mut e, *x)?, - (Fun::Exp, [x]) => exp::exp_base(&mut e, *x, false)?, - (Fun::Exp10, [x]) => exp::exp_base(&mut e, *x, true)?, - (Fun::Log2, [x]) => log::metal_log2(&mut e, *x)?, - (Fun::Log, [x]) => log::log(&mut e, log::Base::E, *x)?, - (Fun::Log10, [x]) => log::log(&mut e, log::Base::Ten, *x)?, - (Fun::Powr, [x, y]) => log::powr(&mut e, *x, *y)?, - (Fun::Sinh, [x]) => hyper::hyper(&mut e, hyper::Hyper::Sinh, *x)?, - (Fun::Cosh, [x]) => hyper::hyper(&mut e, hyper::Hyper::Cosh, *x)?, - (Fun::Tanh, [x]) => hyper::hyper(&mut e, hyper::Hyper::Tanh, *x)?, - (Fun::Asinh, [x]) => hyper::arc(&mut e, hyper::Arc::Asinh, *x)?, - (Fun::Acosh, [x]) => hyper::arc(&mut e, hyper::Arc::Acosh, *x)?, - (Fun::Atanh, [x]) => hyper::arc(&mut e, hyper::Arc::Atanh, *x)?, - (Fun::FastAsinh, [x]) => hyper::fast_arc(&mut e, hyper::FastArc::Asinh, *x)?, - (Fun::FastAcosh, [x]) => hyper::fast_arc(&mut e, hyper::FastArc::Acosh, *x)?, - (Fun::Recip, [y]) => rcp::metal_rcp(&mut e, *y)?, - (Fun::FastRsqrt, [y]) => rsqrt::metal_rsqrt(&mut e, *y)?, - (Fun::Fused, [a, b, c]) => e.fused_inline(*a, *b, *c)?, - (Fun::HalfAtan, [x]) => atan::half_atan(&mut e, *x)?, - (Fun::HalfAtan2, [y, x]) => atan::half_atan2(&mut e, *y, *x)?, - (Fun::HalfTan, [x]) => trig::half_tan(&mut e, *x)?, - (Fun::HalfSin, [x]) => sincos::half_sin_cos(&mut e, trig::Trig::Sin, *x)?, - (Fun::HalfCos, [x]) => sincos::half_sin_cos(&mut e, trig::Trig::Cos, *x)?, - (Fun::HalfAsinh, [x]) => hyper::half_asinh(&mut e, *x)?, - _ => return Err(BuildError::Type(TypeRule::FunctionSignature)), - }; + let (x, y) = (fb.param(t)?, fb.param(t)?); + let mut e = E { fb: &mut fb }; + let v = fmod::fmod(&mut e, x, y)?; fb.ret(Some(v))?; fb.finish() } @@ -1174,50 +457,39 @@ pub(crate) fn split(v: f64) -> (f32, f32) { (hi, (v - f64::from(hi)) as f32) } -/// The multiple of words every table's array is a whole number of ([`declare_words`]): 16 bytes. -pub(crate) const TABLE_ALIGN: usize = 4; - -/// Declare a table of `words` in the module: a `Private` `u32` array initialized to them (Metal's -/// `exp2` and `log2` tables), followed by zeros up to a multiple of [`TABLE_ALIGN`] words. -/// -/// The zeros keep every table a whole number of 16-byte rows, so a table declared after another -/// starts where a 16-byte load can reach it. NVIDIA's driver (615.71.09, RTX 5080 laptop) read -/// every word of the `powr` table one index low in case 7b283404, where that table followed the -/// 165 words of `quarter::QUARTER_TABLE` (the 1,221st word of the tables declared before it): -/// as if it reads the four words of a row as one 16-byte load from a 16-byte boundary, and the -/// tables lie end to end. A host replay of `powr` with every table word taken one index low is -/// that device's word at all 675 positive normal lanes; with the table itself, RADV's. -pub(crate) fn declare_words(mb: &mut ModuleBuilder, words: &[u32]) -> BResult { - let u32_ = mb.ty(Type::Int { - width: 32, - signed: false, - })?; - let padded = words.len().div_ceil(TABLE_ALIGN) * TABLE_ALIGN; - let len = u64::try_from(padded).map_err(|_| BuildError::Type(TypeRule::FunctionSignature))?; - let len = mb.constant(Constant::Scalar { - ty: u32_, - bits: ConstBits(len), - })?; - let arr = mb.ty(Type::Array { - elem: u32_, - len, - stride: None, - })?; - let mut parts = Vec::with_capacity(padded); - let zeros = std::iter::repeat_n(&0, padded - words.len()); - for w in words.iter().chain(zeros) { - parts.push(mb.constant(Constant::Scalar { - ty: u32_, - bits: ConstBits(u64::from(*w)), - })?); - } - let init = mb.constant(Constant::Composite { - ty: arr, - parts: parts.into(), - })?; - mb.plain_global(StorageClass::Private, arr, Some(init)) +/// Metal's precise `log` or `log10` next to 1: for `x` strictly between the bits `low` and `end`, +/// `RN(f fma(p(f), f, lead))` of `f = x - 1` (exact there), `p` by Horner's rule with fused steps, +/// `f32` coefficients by their bits, lowest first: Metal's word at every `float` of its range +/// (`math::metal_log`). +pub(crate) struct Near { + pub low: u32, + pub end: u32, + pub lead: u32, + pub p: &'static [u32], } +/// `log`'s. +pub(crate) const LOG_NEAR: Near = Near { + low: 0x3F74_0000, + end: 0x3F88_0000, + lead: 0x3F80_0000, + p: &[0xBEFF_FFF4, 0x3EAA_AC4E, 0xBE80_449E, 0x3E47_04F8], +}; + +/// `RN(ln(2))`, by its bits: Metal's `log` away from 1 is its `log2` times it. +pub(crate) const LN_2_BITS: u32 = 0x3F31_7218; + +/// `log10`'s: `(495/512, 543/512)`, `lead` `log10(e)` rounded down. +pub(crate) const LOG10_NEAR: Near = Near { + low: 0x3F77_8000, + end: 0x3F87_C000, + lead: 0x3EDE_5BD8, + p: &[0xBE5E_5CE8, 0x3E14_5662, 0xBDD5_5B94], +}; + +/// `RN(log10(2))`, by its bits: Metal's `log10` away from 1 is its `log2` times it. +pub(crate) const LOG10_2_BITS: u32 = 0x3E9A_209B; + /// The `float` scalar. const F32: Form = Form { held: Held::Float(FloatFmt::F32), @@ -1228,13 +500,6 @@ const F32: Form = Form { /// rounded arithmetic, each operation `NoContraction`. pub(crate) struct E<'f, 'm> { pub fb: &'f mut FunctionBuilder<'m>, - /// The device's division and square root moved (`define_rough`); `false` in the product. - rough: bool, - /// The profile's `float` fused multiply-add is `OpFmaKHR`: the trigonometric and the second - /// stage's routines take a product's exact error as one `OpFmaKHR` ([`E::exact_error`]). - fma: bool, - /// The module's functions [`E::div`] and [`E::rsqrt`] call. - helpers: Helpers, } impl E<'_, '_> { @@ -1243,76 +508,12 @@ impl E<'_, '_> { splat(self.fb, F32, u64::from(v.to_bits())) } - /// Metal's NaN at a domain error of a routine's function, the quiet NaN `0x7fc00000` by its - /// bits, with `x`'s sign where `signed`: an infinite operand of `sin`, `cos`, and `tan`, - /// `|x| > 1` of `asin` (`fast::asin`'s NaN has the operand's sign) and `acos`, a negative - /// normal or infinite operand of `sqrt` and `rsqrt`, and an infinite dividend or a zero or - /// denormal divisor of `fmod` (Metal's rows of cases 087758cb and cc234732, every such lane). - /// Selected as a constant, so no device's NaN encoding reaches it; a NaN operand's answer stays - /// the device's arithmetic's (`PrecisionNote::DeviceNanEncoding`). - pub fn metal_nan(&mut self, signed: Option) -> BResult { - let nan = self.c(f32::from_bits(METAL_NAN))?; - match signed { - Some(x) => self.copysign(nan, x), - None => Ok(nan), - } - } - - /// Metal's `exp2` table ([`Helpers::exp2`]); an error where the module has none. - pub fn exp2_table(&self) -> BResult { - self.helpers - .exp2 - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - /// Metal's `log2` table ([`Helpers::log2`]); an error where the module has none. - pub fn log2_table(&self) -> BResult { - self.helpers - .log2 - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - /// Metal's reciprocal table ([`Helpers::rcp`]); an error where the module has none. - pub fn rcp_table(&self) -> BResult { - self.helpers - .rcp - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - /// Metal's fast inverse square root's table ([`Helpers::rsqrt`]); an error where the module - /// has none. - pub fn rsqrt_table(&self) -> BResult { - self.helpers - .rsqrt - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - /// Metal's reduction table from `2^21` up ([`Helpers::quarter`]); an error where the module - /// has none. - pub fn quarter_table(&self) -> BResult { - self.helpers - .quarter - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - /// The model of Metal's hardware `sinc` ([`Helpers::sinc`]); an error where the module has - /// none. - pub fn sinc_table(&self) -> BResult { - self.helpers - .sinc - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - /// Metal's `powr` reduction table ([`Helpers::powr`]); an error where the module has none. - pub fn powr_table(&self) -> BResult { - self.helpers - .powr - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - /// The `float` integer at or below `a` (`GLSL.std.450 Floor`, exact). - pub fn floor(&mut self, a: Value) -> BResult { - self.fb.glsl(GlslOp::Floor, &[a]) + /// Metal's NaN at a domain error of precise `fmod` (an infinite dividend or a zero or denormal + /// divisor, Metal's rows of case 087758cb, every such lane): the quiet NaN `0x7fc00000` by + /// its bits, selected as a constant, so no device's NaN encoding reaches it; a NaN operand's + /// answer stays the device's arithmetic's (`PrecisionNote::DeviceNanEncoding`). + pub fn metal_nan(&mut self) -> BResult { + self.c(f32::from_bits(METAL_NAN)) } /// The `u32` constant `v`. @@ -1336,113 +537,6 @@ impl E<'_, '_> { self.op(BinOp::FMul, a, b) } - /// `a / b`, Metal's precise quotient: a call of the module's precise division routine - /// (`divide.rs`, correctly rounded on every profile), so that no routine's answer depends on - /// the device's division (Vulkan allows `OpFDiv` 2.5 ulp, and `tan` answered differently on - /// RADV and lavapipe). Its operands and quotient are normal wherever a routine's answer depends - /// on them, where Metal's precise division is the correctly rounded quotient. - pub fn div(&mut self, a: Value, b: Value) -> BResult { - let f = self - .helpers - .division - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - self.fb - .call(f, &[a, b])? - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - /// The device's quotient (within 2.5 ulp for a divisor in `[2^-126, 2^126]`): only for a - /// routine that corrects it exactly whatever its error (`root.rs`). - pub fn device_div(&mut self, a: Value, b: Value) -> BResult { - let q = self.op(BinOp::FDiv, a, b)?; - self.moved(q, 2) - } - - /// Metal's reciprocal of `a`: a call of the module's [`Fun::Recip`] routine. - pub fn recip(&mut self, a: Value) -> BResult { - let f = self - .helpers - .recip - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - self.fb - .call(f, &[a])? - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - /// Metal's precise inverse square root of `a` (correctly rounded): a call of the module's - /// [`Fun::Rsqrt`] routine, which Metal's fast one starts from (`rsqrt::metal_rsqrt`). - pub fn rsqrt(&mut self, a: Value) -> BResult { - let f = self - .helpers - .inverse_root - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - self.fb - .call(f, &[a])? - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - /// Metal's fast inverse square root of `a`, its hardware's: a call of the module's - /// [`Fun::FastRsqrt`] routine, which `asin` and `acos` in both modes and `asinh` and `acosh` in - /// both compose. - pub fn fast_rsqrt(&mut self, a: Value) -> BResult { - let f = self - .helpers - .fast_inverse_root - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - self.fb - .call(f, &[a])? - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - /// The device's square root: only for a routine that corrects it exactly whatever its error - /// (`root.rs`). - pub fn device_sqrt(&mut self, a: Value) -> BResult { - let s = self.fb.glsl(GlslOp::Sqrt, &[a])?; - self.moved(s, 3) - } - - /// `v`, or where the emission is `define_rough`'s, a normal `v` moved `ulps` units of its - /// last place up or down by one of its own bits. - fn moved(&mut self, v: Value, ulps: u32) -> BResult { - if !self.rough { - return Ok(v); - } - let b = self.bits(v)?; - let (field, low, inf) = ( - self.u(0x7F80_0000)?, - self.u(0x0100_0000)?, - self.u(0x7F00_0000)?, - ); - let e = self.iop(BinOp::BitwiseAnd, b, field)?; - let above = self.iop(BinOp::UGreaterThanEqual, e, low)?; - let below = self.iop(BinOp::ULessThan, e, inf)?; - let normal = self.iop(BinOp::LogicalAnd, above, below)?; - let (bit, zero) = (self.u(4)?, self.u(0)?); - let set = self.iop(BinOp::BitwiseAnd, b, bit)?; - let up = self.iop(BinOp::INotEqual, set, zero)?; - let (plus, minus) = (self.u(ulps)?, self.u(ulps.wrapping_neg())?); - let d = self.sel(up, plus, minus)?; - let d = self.sel(normal, d, zero)?; - let r = self.iop(BinOp::IAdd, b, d)?; - self.float(r) - } - - pub fn lt(&mut self, a: Value, b: Value) -> BResult { - self.fb.binary(BinOp::FOrdLessThan, a, b) - } - - pub fn le(&mut self, a: Value, b: Value) -> BResult { - self.fb.binary(BinOp::FOrdLessThanEqual, a, b) - } - - pub fn gt(&mut self, a: Value, b: Value) -> BResult { - self.fb.binary(BinOp::FOrdGreaterThan, a, b) - } - - pub fn ge(&mut self, a: Value, b: Value) -> BResult { - self.fb.binary(BinOp::FOrdGreaterThanEqual, a, b) - } - pub fn sel(&mut self, c: Value, t: Value, f: Value) -> BResult { self.fb.select(c, t, f) } @@ -1463,137 +557,9 @@ impl E<'_, '_> { self.fb.binary(op, a, b) } - /// `|a|`, by its bits (exact on every device, a denormal included). - pub fn abs(&mut self, a: Value) -> BResult { - let b = self.bits(a)?; - let m = self.u(0x7FFF_FFFF)?; - let r = self.iop(BinOp::BitwiseAnd, b, m)?; - self.float(r) - } - - /// `a`'s magnitude with `s`'s sign bit, by their bits. - pub fn copysign(&mut self, a: Value, s: Value) -> BResult { - let (ab, sb) = (self.bits(a)?, self.bits(s)?); - let (m, sign) = (self.u(0x7FFF_FFFF)?, self.u(0x8000_0000)?); - let ab = self.iop(BinOp::BitwiseAnd, ab, m)?; - let sb = self.iop(BinOp::BitwiseAnd, sb, sign)?; - let r = self.iop(BinOp::BitwiseOr, ab, sb)?; - self.float(r) - } - - /// `P(v)` of the coefficients `c` (`f32` bits, lowest first) by Horner's rule from the highest, - /// each step one fused multiply-add (Metal's polynomials). - pub fn fused_poly(&mut self, c: &[u32], v: Value) -> BResult { - let (last, rest) = c - .split_last() - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - let mut acc = self.c(f32::from_bits(*last))?; - for k in rest.iter().rev() { - let k = self.c(f32::from_bits(*k))?; - acc = self.fused(acc, v, k)?; - } - Ok(acc) - } - - /// The polynomial `c[0] + z (c[1] + z (...))` by Horner's rule. - pub fn horner(&mut self, c: &[f32], z: Value) -> BResult { - let (last, rest) = c - .split_last() - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - let mut q = self.c(*last)?; - for k in rest.iter().rev() { - let kz = self.mul(z, q)?; - let kc = self.c(*k)?; - q = self.add(kc, kz)?; - } - Ok(q) - } - - /// `a`'s two halves of at most 12 significant bits each, `hi + lo = a` exactly (Veltkamp's - /// split by `2^12 + 1`), for `|a|` below `2^115`. - fn split(&mut self, a: Value) -> BResult<(Value, Value)> { - let k = self.c(4097.0)?; - let c = self.mul(k, a)?; - let d = self.sub(c, a)?; - let hi = self.sub(c, d)?; - let lo = self.sub(a, hi)?; - Ok((hi, lo)) - } - - /// The rounding error of the product `p = a * b` (`a * b = p + e` exactly, Dekker's - /// product), where no partial product is an `f32` denormal: `|a|` and `|b|` below `2^115` - /// and their product above `2^-100` or zero. - pub fn product_error(&mut self, a: Value, b: Value, p: Value) -> BResult { - let (ah, al) = self.split(a)?; - let (bh, bl) = self.split(b)?; - let hh = self.mul(ah, bh)?; - let hl = self.mul(ah, bl)?; - let lh = self.mul(al, bh)?; - let ll = self.mul(al, bl)?; - let e = self.sub(hh, p)?; - let e = self.add(e, hl)?; - let e = self.add(e, lh)?; - self.add(e, ll) - } - - /// The rounding error of the product `p = a * b` where [`E::product_error`]'s is exact: one - /// `OpFmaKHR` of `a * b - p` where the profile has it ([`E::fma`]), else Dekker's product. - /// Both are that exact error: it is a normal `float` (above `2^-124`, or zero) for a product - /// above `2^-100`, so the fused operation rounds nothing and a device that flushes - /// denormals keeps it. - pub fn exact_error(&mut self, a: Value, b: Value, p: Value) -> BResult { - if !self.fma { - return self.product_error(a, b, p); - } - let minus_p = self.fb.unary(UnOp::FNegate, p)?; - self.fb.fma(a, b, minus_p) - } - - /// `a * b` of `u32` values as `(low word, high word)` (`OpUMulExtended`). - pub fn umul(&mut self, a: Value, b: Value) -> BResult<(Value, Value)> { - let p = self.fb.binary(BinOp::UMulExtended, a, b)?; - Ok(( - self.fb.composite_extract(p, &[0])?, - self.fb.composite_extract(p, &[1])?, - )) - } - - /// `a + b` of `u32` values as `(sum, carry)` (`OpIAddCarry`). - pub fn uadd(&mut self, a: Value, b: Value) -> BResult<(Value, Value)> { - let s = self.fb.binary(BinOp::IAddCarry, a, b)?; - Ok(( - self.fb.composite_extract(s, &[0])?, - self.fb.composite_extract(s, &[1])?, - )) - } - /// The `float` of the `u32` `a`, exact where `a` has at most 24 significant bits. pub fn ufloat(&mut self, a: Value) -> BResult { let ft = ty(self.fb, F32)?; self.fb.convert(ConvOp::ConvertUToF, a, ft) } - - /// The `u32` of the non-negative `float` `a`, truncated (`OpConvertFToU`). - pub fn utrunc(&mut self, a: Value) -> BResult { - let ut = ty(self.fb, u32_form(F32))?; - self.fb.convert(ConvOp::ConvertFToU, a, ut) - } - - /// `a + b` as the exact two-term sum `(s, e)`, for `|a| >= |b|` or `a = 0` (Fast2Sum). - pub fn fast_two_sum(&mut self, a: Value, b: Value) -> BResult<(Value, Value)> { - let s = self.add(a, b)?; - let d = self.sub(s, a)?; - let l = self.sub(b, d)?; - Ok((s, l)) - } - - /// The exact remainder `n - q * d` of a quotient `q` close to `n / d` (within a few ulp), - /// as one `float`: `n - p` is exact by Sterbenz's lemma, and the product's error is - /// [`E::product_error`]'s. - pub fn remainder(&mut self, n: Value, q: Value, d: Value) -> BResult { - let p = self.mul(q, d)?; - let e = self.product_error(q, d, p)?; - let r = self.sub(n, p)?; - self.sub(r, e) - } } diff --git a/crates/metal2vulkan/src/lower/arith/libm/pair.rs b/crates/metal2vulkan/src/lower/arith/libm/pair.rs deleted file mode 100644 index 2bc933f90..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/pair.rs +++ /dev/null @@ -1,137 +0,0 @@ -//! Unevaluated sums of two `float`s (`hi + lo`, `|lo|` at most about half an ulp of `hi`), the -//! arithmetic the second stage's routines carry their intermediate values in: each operation is -//! exact or rounds its low part only, so a value keeps about 44 significant bits through the -//! reductions, and only the routine's last addition rounds to the result. The device's division and -//! square root are corrected by their exact remainders, as stage 1's routines do, so their error -//! does not reach the low part. A product's exact error is [`E::exact_error`]'s: one `OpFmaKHR` -//! where the profile has it, Dekker's product elsewhere, the same normal `float` for every product -//! whose error an answer depends on (each lies above `2^-100`), so a routine answers the same with -//! and without it. - -use crate::lower::arith::libm::E; -use crate::spirv::error::{BResult, BuildError, TypeRule}; -use crate::spirv::ids::Value; -use crate::spirv::ir::BinOp; - -/// A `float` constant as `hi + lo`, `hi` the `float` nearest `v` and `lo` the `float` nearest the -/// rest. -pub(crate) fn constant(v: f64) -> (f32, f32) { - super::split(v) -} - -impl E<'_, '_> { - /// `a + b` as the exact two-term sum `(s, e)`, for any `a` and `b` whose sum does not overflow - /// (Knuth's TwoSum). - pub fn two_sum(&mut self, a: Value, b: Value) -> BResult<(Value, Value)> { - let s = self.add(a, b)?; - let bb = self.sub(s, a)?; - let aa = self.sub(s, bb)?; - let da = self.sub(a, aa)?; - let db = self.sub(b, bb)?; - let err = self.add(da, db)?; - Ok((s, err)) - } - - /// `a * b` as the exact two-term product `(p, e)` ([`E::exact_error`]'s range). - pub fn two_prod(&mut self, a: Value, b: Value) -> BResult<(Value, Value)> { - let p = self.mul(a, b)?; - let err = self.exact_error(a, b, p)?; - Ok((p, err)) - } - - /// `n - q d` exactly, for a quotient or root `q` of `n` by `d` correct to a few ulps - /// ([`E::exact_error`]'s range): `n - p` is exact by Sterbenz's lemma. - fn residual(&mut self, n: Value, q: Value, d: Value) -> BResult { - let p = self.mul(q, d)?; - let err = self.exact_error(q, d, p)?; - let r = self.sub(n, p)?; - self.sub(r, err) - } - - /// `(nh + nl) / (dh + dl)` as a pair: the device's quotient `q` of the high parts and the - /// correction `(nh - q dh + nl - q dl) / dh`, its first remainder exact. - pub fn div_pair( - &mut self, - (nh, nl): (Value, Value), - (dh, dl): (Value, Value), - ) -> BResult<(Value, Value)> { - let q = self.div(nh, dh)?; - let r = self.residual(nh, q, dh)?; - let qd = self.mul(q, dl)?; - let rest = self.sub(nl, qd)?; - let r = self.add(r, rest)?; - let lo = self.div(r, dh)?; - Ok((q, lo)) - } - - /// `s + err` rounded to odd, for a sum `s` and its exact residual `err` (`s = RN(s + err)`, as - /// [`E::two_sum`] and [`E::two_prod`] give them): `s` where `err` is zero, else whichever of `s` - /// and its neighbour toward zero has its last bit set, by its bits (Boldo and Melquiond's - /// rounding to odd). A zero `s` stays: its residual is zero but where an operand underflowed. - pub fn odd(&mut self, s: Value, err: Value) -> BResult { - let (sb, eb) = (self.bits(s)?, self.bits(err)?); - let (magnitude, zero) = (self.u(0x7FFF_FFFF)?, self.u(0)?); - let ea = self.iop(BinOp::BitwiseAnd, eb, magnitude)?; - let inexact = self.iop(BinOp::INotEqual, ea, zero)?; - let sa = self.iop(BinOp::BitwiseAnd, sb, magnitude)?; - let nonzero = self.iop(BinOp::INotEqual, sa, zero)?; - let adjust = self.iop(BinOp::LogicalAnd, inexact, nonzero)?; - // Toward zero by one unit where the residual's sign is not `s`'s. - let k31 = self.u(31)?; - let other = self.iop(BinOp::BitwiseXor, sb, eb)?; - let other = self.iop(BinOp::ShiftRightLogical, other, k31)?; - let down = self.iop(BinOp::ISub, sb, other)?; - let last = self.u(1)?; - let o = self.iop(BinOp::BitwiseOr, down, last)?; - let o = self.sel(adjust, o, sb)?; - self.float(o) - } - - /// `a b + c` rounded once, as a fused multiply-add rounds it: one `OpFmaKHR` where the profile - /// has it ([`E::exact_error`]'s route), else a call of the module's [`super::Fun::Fused`] - /// routine ([`E::fused_inline`]), so a routine's many fused steps share one emulation (an - /// error where the module has none). Exact where `a b` lies above `2^-100` and nothing - /// overflows. - pub fn fused(&mut self, a: Value, b: Value, c: Value) -> BResult { - if self.fma { - return self.fb.fma(a, b, c); - } - let f = self - .helpers - .fused - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - self.fb - .call(f, &[a, b, c])? - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - /// `a b + c` rounded once by Boldo and Melquiond's emulation, [`super::Fun::Fused`]'s body: `a - /// b = uh + ul` exactly, `c + uh = th + tl` exactly, and `RN(th + RO(tl + ul))`. Exact where - /// `a b` lies above `2^-100` ([`E::exact_error`]'s range) and nothing overflows. - pub fn fused_inline(&mut self, a: Value, b: Value, c: Value) -> BResult { - let (uh, ul) = self.two_prod(a, b)?; - let (th, tl) = self.two_sum(c, uh)?; - let (v, v_err) = self.two_sum(tl, ul)?; - let v = self.odd(v, v_err)?; - self.add(th, v) - } - - /// Whether `x` is a NaN, by its bits (no float mode folds an integer comparison). - pub fn is_nan(&mut self, x: Value) -> BResult { - let b = self.bits(x)?; - let (m, inf) = (self.u(0x7FFF_FFFF)?, self.u(0x7F80_0000)?); - let a = self.iop(BinOp::BitwiseAnd, b, m)?; - self.iop(BinOp::UGreaterThan, a, inf) - } - - /// `v` clamped to `[-bound, bound]` (a NaN stays a NaN), and whether it was clamped. - pub fn clamp(&mut self, v: Value, bound: f32) -> BResult<(Value, Value)> { - let (hi, lo) = (self.c(bound)?, self.c(-bound)?); - let over = self.gt(v, hi)?; - let under = self.lt(v, lo)?; - let r = self.sel(over, hi, v)?; - let r = self.sel(under, lo, r)?; - let clamped = self.iop(BinOp::LogicalOr, over, under)?; - Ok((r, clamped)) - } -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/pi.rs b/crates/metal2vulkan/src/lower/arith/libm/pi.rs deleted file mode 100644 index 98118ae9d..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/pi.rs +++ /dev/null @@ -1,109 +0,0 @@ -//! Metal's `sinpi`, `cospi` and `tanpi` of a `float`: Metal's own forms, which follow Apple's -//! runtime library, of half turns and its hardware's `sinc` (`sincos`), the same in both math -//! modes. With the hardware's measured `sinc` and reciprocal they are Metal's word at every -//! measured operand; through the models of both, at 99.5 % to 99.99 %. -//! -//! **Half turns.** `2x = 2n + t` with `n` the integer nearest `x` (ties to even) and `t` in -//! `[-1, 1]`, so `sin(π x) = ±sin(π t / 2)`: `s = RN(2x + b)` of `b = ±2^24` with `x`'s sign, -//! whose last bit is `n`'s, and `t = 2x + (b - s)`. Every step but `s` is exact (`2x` is a scaling, -//! `b - s` a difference of two floats within a factor of two, and `t` a multiple of `2x`'s unit -//! below 1), so the steps Metal fuses are plain sums here. From `2^23` in magnitude `2x + b` is -//! no longer within a unit of `s`, and `cospi` and `tanpi` take `b = 0` (`t = 0`, `s = 2x`). -//! -//! **The functions**, of `S` the hardware's `sinc` (`sin(π t / 2) = t S(t)`): -//! - `sinpi(x) = t S(t)`, `t` negated for an odd `n`; `+0` from `2^23`. -//! - `cospi(x) = u S(u)` of `u = RN(1 - |t|)`, negated for an odd `n`; 1 from `2^24`. -//! - `tanpi(x) = RN(a rcp(c'))` of `a = RN(t S(t))`, `c = S(RN(1 - |t|))` and -//! `c' = RN(c - c |t|)` in one fused step, by Metal's reciprocal ([`super::Fun::Recip`]); `+0` -//! from `2^24`. At a half-integer `c'` is `+0` and the reciprocal `+inf`. -//! -//! Metal reads a denormal `x` as the zero of its sign (`sinpi` and `tanpi` `+0`, `cospi` 1), and -//! answers its NaN, `0x7fc00000`, for an infinity or a NaN. - -use crate::lower::arith::libm::atan::read; -use crate::lower::arith::libm::sincos::sinc; -use crate::lower::arith::libm::{Fun, E}; -use crate::spirv::error::BResult; -use crate::spirv::ids::Value; -use crate::spirv::ir::{BinOp, UnOp}; - -/// Which of Metal's `π`-scaled functions [`pi`] computes. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Pi { - Sin, - Cos, - Tan, -} - -/// The `float` bits of `2^23`, from which `2x + 2^24` is not within a unit of its rounding. -const HALF_TURNS_EXACT_BELOW: u32 = 0x4B00_0000; - -/// The `float` bits of `2^24`, from which `cospi` is 1 and `tanpi` `+0`. -const WHOLE: u32 = 0x4B80_0000; - -/// Metal's `which` of `x` (the module's doc), the routine of `fun`, whose operand table it reads -/// `x` by. -pub(crate) fn pi(e: &mut E<'_, '_>, fun: Fun, which: Pi, x: Value) -> BResult { - let x = read(e, fun, x)?; - let ax = e.abs(x)?; - let bits = e.bits(ax)?; - // From `2^24` (and for an infinity or a NaN) every function's answer is selected below, so - // the steps take `+0` instead, where `2x` would overflow or `t` be NaN. - let whole = e.u(WHOLE)?; - let past = e.iop(BinOp::UGreaterThanEqual, bits, whole)?; - let zero = e.c(0.0)?; - let x = e.sel(past, zero, x)?; - let big = e.u(HALF_TURNS_EXACT_BELOW)?; - let large = e.iop(BinOp::UGreaterThanEqual, bits, big)?; - let unit = e.c(16_777_216.0)?; - let b = e.copysign(unit, x)?; - let b = match which { - // From `2^23` `sinpi` is `+0` whatever the steps give. - Pi::Sin => b, - Pi::Cos | Pi::Tan => e.sel(large, zero, b)?, - }; - let two = e.c(2.0)?; - let x2 = e.mul(x, two)?; - let s = e.add(x2, b)?; - let d = e.sub(b, s)?; - let t = e.add(x2, d)?; - let (one_u, zero_u) = (e.u(1)?, e.u(0)?); - let sb = e.bits(s)?; - let odd = e.iop(BinOp::BitwiseAnd, sb, one_u)?; - let odd = e.iop(BinOp::INotEqual, odd, zero_u)?; - let at = e.abs(t)?; - let one = e.c(1.0)?; - let rest = e.sub(one, at)?; - let negated = |e: &mut E<'_, '_>, v: Value| -> BResult { - let minus = e.fb.unary(UnOp::FNegate, v)?; - e.sel(odd, minus, v) - }; - let v = match which { - Pi::Sin => { - let t = negated(e, t)?; - let st = sinc(e, at)?; - let v = e.mul(t, st)?; - e.sel(large, zero, v)? - } - Pi::Cos => { - let u = negated(e, rest)?; - let su = sinc(e, rest)?; - let v = e.mul(u, su)?; - e.sel(past, one, v)? - } - Pi::Tan => { - let st = sinc(e, at)?; - let a = e.mul(t, st)?; - let c = sinc(e, rest)?; - let minus_at = e.fb.unary(UnOp::FNegate, at)?; - let den = e.fused(c, minus_at, c)?; - let q = e.recip(den)?; - let v = e.mul(a, q)?; - e.sel(past, zero, v)? - } - }; - let inf = e.u(0x7F80_0000)?; - let finite = e.iop(BinOp::ULessThan, bits, inf)?; - let nan = e.metal_nan(None)?; - e.sel(finite, v, nan) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/quarter.rs b/crates/metal2vulkan/src/lower/arith/libm/quarter.rs deleted file mode 100644 index de65ffdc0..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/quarter.rs +++ /dev/null @@ -1,212 +0,0 @@ -//! Metal's reduction of a `float` to quarter turns, which its precise `sin`, `cos` and `tan` share: -//! `x 2/π = k + r` with `k` an integer and `|r| <= 1/2` (about), in Metal's own arithmetic, so that -//! the reduced argument is Metal's word for word. -//! -//! Below `2^21` in magnitude, `k` is `x 2/π` rounded to an integer by adding and removing `2^23` -//! with `x`'s sign in a fused step, and `r` is three fused steps of `x` by `2/π` in three parts -//! ([`QUARTER`]). From `2^21` up, `x 2^-126` is multiplied by row `(|x| - 2^21) >> 24` of -//! [`QUARTER_TABLE`] (in bits; the bits of `2/π` that matter for that pair of binades, in three -//! `float`s `h`, `m`, `l`): `k0` is the first product rounded as above (itself from `2^23`), -//! `r0 = fma(h, x', -k0)`, `k1` is `fma(m, x', r0)` rounded half away from zero, `k = k0 + k1`, -//! and `r = fma(l, x', fma(m, x', r0 - k1))`, to which `tan` adds the rounding error of -//! `r0 - k1` ([`Error::Compensated`]) and `sin` and `cos` do not ([`Error::Dropped`]). -//! -//! Metal multiplies `x 2^-126` by the row; here `x 2^-102` by the row times `2^-24`, the same -//! products exactly (every factor stays normal), so that no factor of an emulated fused step -//! is too large to split. Both reductions run on every lane, each on an operand in its own range (0 -//! from `2^21`, `2^21` below it or for an infinity or a NaN), so that no integer conversion of a -//! lane selected away leaves its range. - -use crate::lower::arith::libm::E; -use crate::spirv::builder::ModuleBuilder; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, Value}; -use crate::spirv::ir::{BinOp, MemAccess, UnOp}; - -/// `2/π` in three parts (`f32` bits, the largest first), the reduction's below `2^21`. -pub(crate) const QUARTER: [u32; 3] = [0x3F22_F983, 0x32DC_9C88, 0x25A9_4FE1]; - -/// Metal's reduction from `2^21` up: per pair of binades (row `(|x| bits - 0x4a000000) >> 24`), -/// the bits of `2/π` that matter there, as three `float`s that multiply `x 2^-126` (`f32` bits). -/// The last row is never read. -pub(crate) const QUARTER_TABLE: [[u32; 3]; 55] = [ - [0x7E22_F983, 0x71DC_9C88, 0x64A9_4FE1], - [0x7E22_F983, 0x71DC_9C88, 0x64A9_4FE1], - [0xFDBA_0CF9, 0xF08D_8DDF, 0xE42D_603E], - [0xFCE8_33E5, 0x7064_E441, 0x63A5_3F85], - [0x7B3E_60DC, 0xEED8_DDF5, 0xE256_03D9], - [0xFA83_3E49, 0x6D9C_882A, 0x6127_F09D], - [0xF7CF_9236, 0xEADD_F56B, 0xDB76_2A0C], - [0xF7CF_9236, 0xEADD_F56B, 0xDB76_2A0C], - [0xF7CF_9236, 0xEADD_F56B, 0xDB76_2A0C], - [0x76C1_B727, 0x6988_2A54, 0xDB76_2A0C], - [0xF5F9_2363, 0xE96F_AB58, 0xDB76_2A0C], - [0x735B_9391, 0x64A9_4FE1, 0x57EA_FA3F], - [0x735B_9391, 0x64A9_4FE1, 0x57EA_FA3F], - [0xF211_B1BC, 0x64A9_4FE1, 0x57EA_FA3F], - [0x71DC_9C88, 0x64A9_4FE1, 0x57EA_FA3F], - [0xF08D_8DDF, 0xE42D_603E, 0x57EA_FA3F], - [0xEED8_DDF5, 0xE256_03D9, 0x55AF_A3EA], - [0xEED8_DDF5, 0xE256_03D9, 0x55AF_A3EA], - [0x6D9C_882A, 0x6127_F09D, 0x54BE_8FAA], - [0x6C64_4153, 0xDFC0_7B15, 0xD138_2B2D], - [0xEADD_F56B, 0xDB76_2A0C, 0x4EFA_9A6F], - [0xEADD_F56B, 0xDB76_2A0C, 0x4EFA_9A6F], - [0x6988_2A54, 0xDB76_2A0C, 0x4EFA_9A6F], - [0x6782_A540, 0xDB76_2A0C, 0x4EFA_9A6F], - [0x6782_A540, 0xDB76_2A0C, 0x4EFA_9A6F], - [0x64A9_4FE1, 0x57EA_FA3F, 0xCB32_C890], - [0x64A9_4FE1, 0x57EA_FA3F, 0xCB32_C890], - [0x64A9_4FE1, 0x57EA_FA3F, 0xCB32_C890], - [0x63A5_3F85, 0xD628_2E0B, 0x4953_7703], - [0x6294_FE14, 0xD628_2E0B, 0x4953_7703], - [0x6127_F09D, 0x54BE_8FAA, 0xC832_23F2], - [0xE0B0_1EC5, 0xD402_E0AD, 0x479B_B81B], - [0xDFC0_7B15, 0xD138_2B2D, 0x44EE_06DB], - [0x5EFE_13AC, 0xD138_2B2D, 0x44EE_06DB], - [0xDB76_2A0C, 0x4EFA_9A6F, 0xC17C_9276], - [0xDB76_2A0C, 0x4EFA_9A6F, 0xC17C_9276], - [0xDB76_2A0C, 0x4EFA_9A6F, 0xC17C_9276], - [0x591D_5F48, 0xCC2C_B224, 0x3E5B_6296], - [0x591D_5F48, 0xCC2C_B224, 0x3E5B_6296], - [0xD8C5_4170, 0xCC2C_B224, 0x3E5B_6296], - [0x57EA_FA3F, 0xCB32_C890, 0x3E5B_6296], - [0xD628_2E0B, 0x4953_7703, 0x3CDB_14AD], - [0x55AF_A3EA, 0x4953_7703, 0x3CDB_14AD], - [0x54BE_8FAA, 0xC832_23F2, 0xBB93_AD4D], - [0x53FA_3EA7, 0xC748_8FC9, 0xBA1D_6A67], - [0xD138_2B2D, 0x44EE_06DB, 0x3725_664F], - [0xD138_2B2D, 0x44EE_06DB, 0x3725_664F], - [0x508F_A9A7, 0xC30F_C927, 0xB6B5_3362], - [0x4EFA_9A6F, 0xC17C_9276, 0x34AC_C9E2], - [0x4EFA_9A6F, 0xC17C_9276, 0x34AC_C9E2], - [0xCC2C_B224, 0x3E5B_6296, 0xB1CD_8779], - [0xCC2C_B224, 0x3E5B_6296, 0xB1CD_8779], - [0x4BA6_9BB8, 0x3E5B_6296, 0xB1CD_8779], - [0x4A9A_6EE0, 0x3E5B_6296, 0xB1CD_8779], - [0x0000_0000, 0x0000_0000, 0x0000_0000], -]; - -/// An upper estimate of the SPIR-V words of [`QUARTER_TABLE`] in a module: its 165 constants and -/// a zero, the composite (168 words with its three zeros, `declare_words`), and the array, -/// pointer, and variable. -pub(crate) const TABLE_WORDS: u32 = 166 * 4 + 171 + 24; - -/// Declare [`QUARTER_TABLE`] in the module. -pub(crate) fn declare(mb: &mut ModuleBuilder) -> BResult { - super::declare_words(mb, QUARTER_TABLE.as_flattened()) -} - -/// The `float` bits from which the reduction reads [`QUARTER_TABLE`] (`2^21`). -const TABLE_FROM: u32 = 0x4A00_0000; - -/// Whether the reduction from `2^21` up adds the rounding error of `r0 - k1` to `r`. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum Error { - /// `tan`'s. - Compensated, - /// `sin`'s and `cos`'s. - Dropped, -} - -/// `c v` rounded to an integer-valued `float` (half to even): `fma(c, v, b) - b` of `b = 2^23` -/// with the sign of `like`, an approximation of `c v`. -fn rounded(e: &mut E<'_, '_>, c: Value, v: Value, like: Value) -> BResult { - let big = e.c(8_388_608.0)?; - let b = e.copysign(big, like)?; - let s = e.fused(c, v, b)?; - e.sub(s, b) -} - -/// The `u32` of the integer-valued `float` `k` modulo `2^32` (its magnitude below `2^32`). -fn integer(e: &mut E<'_, '_>, k: Value) -> BResult { - let ak = e.abs(k)?; - let n = e.utrunc(ak)?; - let zero = e.u(0)?; - let minus_n = e.iop(BinOp::ISub, zero, n)?; - let zero_f = e.c(0.0)?; - let negative = e.lt(k, zero_f)?; - e.sel(negative, minus_n, n) -} - -/// Metal's reduction of the `float` `x` (the module's doc): `(r, k)`, `r` the reduced argument -/// in quarter turns and `k` the quarter turns as a `u32` modulo `2^32`. For an infinity or a NaN -/// both are some finite values, which the callers select away. -pub(crate) fn turns(e: &mut E<'_, '_>, x: Value, error: Error) -> BResult<(Value, Value)> { - let ax = e.abs(x)?; - let bits = e.bits(ax)?; - let from = e.u(TABLE_FROM)?; - let below = e.iop(BinOp::ULessThan, bits, from)?; - let inf = e.u(0x7F80_0000)?; - let finite = e.iop(BinOp::ULessThan, bits, inf)?; - let zero = e.c(0.0)?; - let start = e.c(2_097_152.0)?; - let xn = e.sel(below, x, zero)?; - let xf = e.sel(finite, x, start)?; - let xf = e.sel(below, start, xf)?; - // Below 2^21: three fused steps. - let [c0, c1, c2] = QUARTER.map(f32::from_bits); - let (c0, c1, c2) = (e.c(c0)?, e.c(c1)?, e.c(c2)?); - let k = rounded(e, c0, xn, xn)?; - let minus_k = e.fb.unary(UnOp::FNegate, k)?; - let r = e.fused(c0, xn, minus_k)?; - let r = e.fused(c1, xn, r)?; - let near = e.fused(c2, xn, r)?; - let near_k = integer(e, k)?; - // From 2^21: the table's row for `x`'s binades. - let axf = e.abs(xf)?; - let fbits = e.bits(axf)?; - let offset = e.iop(BinOp::ISub, fbits, from)?; - let k24 = e.u(24)?; - let row = e.iop(BinOp::ShiftRightLogical, offset, k24)?; - let three = e.u(3)?; - let first = e.iop(BinOp::IMul, row, three)?; - let table = e.quarter_table()?; - let base = e.fb.module().global_value(table)?; - let part = |e: &mut E<'_, '_>, j: u32| -> BResult { - let j = e.u(j)?; - let i = e.iop(BinOp::IAdd, first, j)?; - let p = e.fb.access_chain(base, &[i])?; - let w = e.fb.load(p, MemAccess::default())?; - e.float(w) - }; - let down = e.c(1.0 / 16_777_216.0)?; - let (h, m, l) = (part(e, 0)?, part(e, 1)?, part(e, 2)?); - let (h, m, l) = (e.mul(h, down)?, e.mul(m, down)?, e.mul(l, down)?); - let scale = e.c(f32::from_bits(0x0C80_0000))?; - let xs = e.mul(xf, scale)?; - let p = e.mul(xs, h)?; - let k0 = rounded(e, h, xs, p)?; - let ap = e.abs(p)?; - let big = e.c(8_388_608.0)?; - let integral = e.ge(ap, big)?; - let k0 = e.sel(integral, p, k0)?; - let minus_k0 = e.fb.unary(UnOp::FNegate, k0)?; - let r0 = e.fused(h, xs, minus_k0)?; - let r1 = e.fused(m, xs, r0)?; - let half = e.c(0.5)?; - let half = e.copysign(half, r1)?; - let k1 = e.add(r1, half)?; - let k1 = e.fb.glsl(crate::spirv::ir::GlslOp::Trunc, &[k1])?; - let d = e.sub(r0, k1)?; - let r2 = e.fused(m, xs, d)?; - let r3 = e.fused(l, xs, r2)?; - let far = match error { - Error::Dropped => r3, - Error::Compensated => { - // `r0 - k1`'s rounding error. - let e1 = e.sub(d, r0)?; - let e2 = e.sub(d, e1)?; - let e3 = e.sub(r0, e2)?; - let minus_k1 = e.fb.unary(UnOp::FNegate, k1)?; - let e4 = e.sub(minus_k1, e1)?; - let err = e.add(e4, e3)?; - e.add(r3, err)? - } - }; - let (n0, n1) = (integer(e, k0)?, integer(e, k1)?); - let far_k = e.iop(BinOp::IAdd, n0, n1)?; - let r = e.sel(below, near, far)?; - let k = e.sel(below, near_k, far_k)?; - Ok((r, k)) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/rcp.rs b/crates/metal2vulkan/src/lower/arith/libm/rcp.rs deleted file mode 100644 index 3b5eeffa7..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/rcp.rs +++ /dev/null @@ -1,196 +0,0 @@ -//! Metal's reciprocal: the `1 / y` of Metal's fast division (`arcp`), of its precise `sinh`, -//! `cosh`, and `tanh`, which compose their exponentials with it, and of its texture unit's cube -//! face coordinate. [`metal_rcp`] is [`super::Fun::Recip`]'s routine, which the other routines call -//! ([`E::recip`]) and any lowering may per lane. -//! -//! Read off every `float` of the M4 (a library compiled at run time with -//! `mathMode` fast): Metal's reciprocal of a normal `y` whose reciprocal is normal is the -//! reciprocal `r(m)` of its significand `m` in `[1, 2)` with the exponent negated and the sign -//! kept, and `r(m)` is `1 / m` plus a smooth error per 64th of `m` (up to about a fifth of a -//! unit) under a noise of a few thousandths of a unit, rounded to nearest: it differs from -//! `RN(1 / m)` at 868,174 of the 8,388,608 significands, by one unit. [`TABLE`] fits the smooth -//! part, a cubic per 64th by its four `f32` coefficients (scaled by `2^-24`, least squares to the -//! bounds Metal's words set, each constant term then moved to the most words), so the routine is -//! `RN(1 / m + eps(m))`: Metal's word at 8,361,659 of the significands (99.68 %), one unit off at -//! the other 26,949 (an open near-equivalent). - -use crate::lower::arith::libm::E; -use crate::spirv::builder::ModuleBuilder; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, Value}; -use crate::spirv::ir::{BinOp, MemAccess}; - -/// Metal's reciprocal error per 64th of the significand: row `k >> 17` of the fraction field `k`, -/// `eps = c0 + t (c1 + t (c2 + t c3))` at `t = (k mod 2^17) 2^-17`, in units of `2^-24` already -/// (`f32` bits). -pub(crate) const TABLE: [[u32; 4]; 64] = [ - [0xB214_8996, 0x3406_49CA, 0xB47F_97D9, 0x3405_171E], - [0xB0FC_71E5, 0xB234_0DF9, 0x33D4_9DBE, 0xB3CB_D992], - [0xB227_87AA, 0x33EE_63DE, 0xB460_3011, 0x33E9_D938], - [0xB126_868E, 0xB1FF_9A1E, 0x33BB_75A6, 0xB3AF_2E82], - [0xB1C0_FDC3, 0x33C5_3972, 0xB43D_B71E, 0x33C9_14CE], - [0xAD07_6890, 0xB1D8_03F7, 0x33A5_F505, 0xB39E_28EF], - [0xB186_F82F, 0x33B6_A66E, 0xB428_525F, 0x33AF_B697], - [0x314F_E2CF, 0xB182_9ACB, 0x3382_BD4A, 0xB383_D414], - [0xB122_9A6A, 0x3371_209A, 0xB3FE_AC88, 0x338D_A07C], - [0xB0C1_A142, 0xAFDB_8FF3, 0x336F_237F, 0xB36B_FAB8], - [0xB148_D921, 0x337C_2C6E, 0xB3E4_9D7D, 0x3372_9779], - [0x316E_41C5, 0x3012_ACD3, 0x333F_B7C3, 0xB358_E276], - [0xB146_641A, 0x338E_6B8F, 0xB3F5_7A65, 0x3376_FEFF], - [0x319B_F8FC, 0xB186_7911, 0x332D_9920, 0xB325_8748], - [0x30F3_C936, 0x331C_00BD, 0xB3A1_4826, 0x3335_92CA], - [0x3168_FC4A, 0x301D_C599, 0x332D_5B3C, 0xB32E_9CC0], - [0x313D_5D28, 0x3309_8103, 0xB398_5D03, 0x3335_619C], - [0x3181_D0D7, 0x316E_2FCB, 0x3312_B202, 0xB311_F8F0], - [0x31E2_DB1E, 0x3313_E265, 0xB39B_6842, 0x3329_8F7C], - [0x31E0_7D3E, 0xB143_9D5C, 0x3301_6D0D, 0xB2F0_4595], - [0xB11D_A12E, 0x3348_BAB3, 0xB3A2_0B07, 0x3322_6770], - [0x31B4_B536, 0x30C7_DA56, 0x32CD_90FA, 0xB2A6_E469], - [0x3158_AF01, 0x32EB_414F, 0xB370_6A3F, 0x32FD_B1D1], - [0x313E_6377, 0xB178_465D, 0x32B7_57E1, 0xB2BE_AB31], - [0x31B3_AC90, 0x32D5_BB9A, 0xB355_0129, 0x32E0_B357], - [0x31BA_2713, 0xB104_C3F2, 0x328E_B66E, 0xB2A1_1332], - [0x31F1_EEFA, 0x3313_BD9A, 0xB37B_41A6, 0x32D9_970A], - [0x3212_AC4F, 0xB1CA_CFAD, 0x3298_A70A, 0xB289_75EC], - [0x3187_B6E7, 0x32B4_D559, 0xB329_AFA5, 0x32B0_4F61], - [0x31AD_C0DB, 0xB135_EFED, 0x327C_5986, 0xB295_6174], - [0x31E6_ECF4, 0x32BC_32C4, 0xB346_FD7E, 0x32C9_137A], - [0x31A1_C5B2, 0xB1B7_B003, 0x326B_FFDD, 0xB21C_A5E4], - [0x323C_7597, 0x322F_AEDB, 0xB2F1_E3F3, 0x3284_68AF], - [0x3206_5907, 0xB155_8FD5, 0x328C_F3C6, 0xB264_A7C7], - [0x31FD_CCD7, 0x328D_B75E, 0xB31F_438F, 0x32A3_9033], - [0x31AE_2EFF, 0xB199_5AED, 0x3282_C156, 0xB21B_92C1], - [0x31DC_3D10, 0x3186_B786, 0xB299_E438, 0x3244_DA0E], - [0x3154_B814, 0xB03C_D244, 0x321A_CA9C, 0xB25B_227F], - [0x31C6_0728, 0x325D_AD26, 0xB301_B452, 0x328C_BAB8], - [0x318B_2BBB, 0xB11F_FFED, 0x324B_06D1, 0xB1E8_8D5A], - [0x31DE_C4B9, 0x31CF_C5AD, 0xB286_B87C, 0x3234_F881], - [0x31E4_5B98, 0x314F_9841, 0x320D_867E, 0xB22E_97AF], - [0x3202_72D1, 0x320D_B866, 0xB26E_6A3A, 0x3207_42D1], - [0x321B_2903, 0x310B_7BAB, 0x3100_5DB6, 0xB226_E626], - [0x3146_FFE0, 0x323A_C1C5, 0xB2A6_9A7C, 0x321E_E006], - [0x3154_EC03, 0xB162_8C37, 0x315C_6263, 0xB206_52E8], - [0x3123_BE15, 0x320A_437D, 0xB257_2532, 0x31FC_1527], - [0x31AA_B487, 0x3108_9B7F, 0x31A3_6760, 0xB227_DF03], - [0x321D_9B42, 0xB1A4_2AAC, 0xB1E7_145D, 0x31E2_6E9C], - [0x3183_2E38, 0xB0CE_6720, 0x321B_10B6, 0xB211_A59F], - [0x322F_7BEF, 0x3242_26E2, 0xB2A0_63E3, 0x3205_64DE], - [0x3232_DA05, 0xB1BC_432D, 0x31B1_C95B, 0xB1D0_0858], - [0x3186_F10B, 0x2FFC_19A4, 0xB1E3_9A97, 0x31C0_7093], - [0x3151_D208, 0x313C_4297, 0x31EC_EC85, 0xB1BC_7069], - [0x31F1_D8A4, 0xB11E_B11A, 0xB1AC_503C, 0x318F_E554], - [0x3177_B355, 0xAF73_0117, 0x31CD_AA51, 0xB1B2_C583], - [0x3189_0398, 0x321D_EF92, 0xB260_648A, 0x31D7_2FED], - [0x31D2_5CF7, 0xAEC5_5547, 0x31A9_A37D, 0xB195_652F], - [0x31E0_C597, 0x3138_231B, 0xB0EB_AEA1, 0x30EC_BC02], - [0x3219_1B31, 0x3120_8F08, 0x312F_B150, 0xB20D_F155], - [0x31BC_D310, 0x324F_E2D4, 0xB287_661A, 0x31D8_FF8A], - [0x3208_CFBA, 0xB104_09DC, 0x3101_3BBB, 0xB11A_3291], - [0x31BC_6932, 0x30D8_C0FA, 0xB207_224F, 0x31AF_AEEA], - [0x317F_68FC, 0x31A4_1CE2, 0xB217_BC4F, 0x31FF_34D7], -]; - -/// The coefficients per row of [`TABLE`]. -const COEFFICIENTS: u32 = 4; - -/// An upper estimate of the SPIR-V words of [`TABLE`] in a module: its 256 constants, the -/// composite, and the array, pointer, and variable. -pub(crate) const TABLE_WORDS: u32 = 256 * 4 + 259 + 24; - -/// Declare [`TABLE`] in the module. -pub(crate) fn declare(mb: &mut ModuleBuilder) -> BResult { - super::declare_words(mb, TABLE.as_flattened()) -} - -/// Metal's reciprocal of `y`. For a normal `y` up to `2^126` in magnitude, `r = RN(1 / m + -/// eps(m))` of its significand `m`, the sum formed from `r0 = RN(1 / m)` (the module's precise -/// division) and its exact residual `1 - m r0` as `r0 + ((1 - m r0) r0 + eps)`, each step's -/// rounding far below the unit `r` rounds to; then `r`'s exponent field moved by `y`'s, and `y`'s -/// sign (Metal's reciprocal of `-y` is the negation of its reciprocal of `y`). Metal's flushes, -/// as measured: a zero or denormal `y` gives the infinity of its sign, and a -/// `y` past `2^126` (an infinity included), whose reciprocal would be denormal, the zero of its -/// sign. A NaN gives a NaN (`y`; Metal's NaN bits are its callers'). -pub(crate) fn metal_rcp(e: &mut E<'_, '_>, y: Value) -> BResult { - let table = e.rcp_table()?; - let b = e.bits(y)?; - let (fraction, one_bits) = (e.u(0x007F_FFFF)?, e.u(0x3F80_0000)?); - let k = e.iop(BinOp::BitwiseAnd, b, fraction)?; - let mb = e.iop(BinOp::BitwiseOr, k, one_bits)?; - let m = e.float(mb)?; - let one = e.c(1.0)?; - let r0 = e.div(one, m)?; - // `1 - m r0` exactly: `1 - p` by Sterbenz's lemma, less the product's exact error. - let p = e.mul(r0, m)?; - let error = e.exact_error(r0, m, p)?; - let residual = e.sub(one, p)?; - let residual = e.sub(residual, error)?; - let d = e.mul(residual, r0)?; - // `eps(m)`: row `k >> 17`, at `t = (k mod 2^17) 2^-17`. - let (low, k17) = (e.u(0x1_FFFF)?, e.u(17)?); - let row = e.iop(BinOp::ShiftRightLogical, k, k17)?; - let t = e.iop(BinOp::BitwiseAnd, k, low)?; - let t = e.ufloat(t)?; - let scale = e.c(1.0 / 131_072.0)?; - let t = e.mul(t, scale)?; - let width = e.u(COEFFICIENTS)?; - let first = e.iop(BinOp::IMul, row, width)?; - let base = e.fb.module().global_value(table)?; - let coefficient = |e: &mut E<'_, '_>, j: u32| -> BResult { - let j = e.u(j)?; - let i = e.iop(BinOp::IAdd, first, j)?; - let p = e.fb.access_chain(base, &[i])?; - let w = e.fb.load(p, MemAccess::default())?; - e.float(w) - }; - // Horner's rule in plain `float`: `eps` is below `2^-25`, so its own rounding errors (about - // `2^-49`) move the result only where the sum lies that close to a midpoint. - let mut eps = coefficient(e, COEFFICIENTS - 1)?; - for j in (0..COEFFICIENTS - 1).rev() { - let c = coefficient(e, j)?; - let p = e.mul(eps, t)?; - eps = e.add(p, c)?; - } - let tail = e.add(d, eps)?; - let r = e.add(r0, tail)?; - // `r` in `[1/2, 1]`: `2^(127 - n)` of `y`'s exponent field `n` by the field, and `y`'s sign. - let rb = e.bits(r)?; - let (exponent, sign) = (e.u(0x7F80_0000)?, e.u(0x8000_0000)?); - let n = e.iop(BinOp::BitwiseAnd, b, exponent)?; - let shift = e.iop(BinOp::ISub, one_bits, n)?; - let v = e.iop(BinOp::IAdd, rb, shift)?; - let s = e.iop(BinOp::BitwiseAnd, b, sign)?; - let v = e.iop(BinOp::BitwiseOr, v, s)?; - // The flushes, by the magnitude's bits: a zero exponent field, and past `2^126`. - let magnitude = e.u(0x7FFF_FFFF)?; - let a = e.iop(BinOp::BitwiseAnd, b, magnitude)?; - let zero = e.u(0)?; - let tiny = e.iop(BinOp::IEqual, n, zero)?; - let infinity = e.u(0x7F80_0000)?; - let inf = e.iop(BinOp::BitwiseOr, s, infinity)?; - let v = e.sel(tiny, inf, v)?; - let limit = e.u(0x7E80_0000)?; - let past = e.iop(BinOp::UGreaterThan, a, limit)?; - let v = e.sel(past, s, v)?; - let r = e.float(v)?; - let nan = e.is_nan(y)?; - e.sel(nan, y, r) -} - -/// Metal's reciprocal of a normal `float` `y` whose reciprocal is normal, as the model computes it -/// ([`TABLE`]) and the routine forms it: `r0 + ((1 - m r0) r0 + eps)` of its significand `m`, `r0 = -/// RN(1 / m)`, the residual exact, `eps` by Horner's rule in plain `float`; then `y`'s exponent -/// negated and its sign. -#[cfg(test)] -pub(crate) fn model(y: f32) -> f32 { - let b = y.to_bits(); - let k = b & 0x007F_FFFF; - let m = f32::from_bits(k | 0x3F80_0000); - let r0 = 1.0 / m; - let residual = (1.0 - f64::from(m) * f64::from(r0)) as f32; - let row = TABLE[(k >> 17) as usize].map(f32::from_bits); - let t = (k & 0x1_FFFF) as f32 / 131_072.0; - let eps = row.iter().rev().fold(0.0f32, |acc, c| acc * t + c); - let r = r0 + (residual * r0 + eps); - let shift = 0x3F80_0000u32.wrapping_sub(b & 0x7F80_0000); - f32::from_bits(r.to_bits().wrapping_add(shift) | (b & 0x8000_0000)) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/root.rs b/crates/metal2vulkan/src/lower/arith/libm/root.rs deleted file mode 100644 index 3aafb5dc3..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/root.rs +++ /dev/null @@ -1,204 +0,0 @@ -//! The square roots: Metal's precise `sqrt` and `rsqrt` of a `float`, which MSL Table 8.1 states as -//! correctly rounded, as the `half` table (8.3) does for its own. -//! -//! **Normal positive operands.** `x = y 2^(2k)` with `y` in `[1, 4)` (the significand with the -//! exponent's parity), so `sqrt(x) = sqrt(y) 2^k` and `rsqrt(x) = rsqrt(y) 2^-k`, each a normal -//! `float` whose rounding is `y`'s root's, scaled exactly. The device's `Sqrt` of `y`, or its -//! reciprocal by the device's division, is refined by one Newton step on its exact residual (`y - s^2`, or `1 - y r^2` from -//! Dekker's products), which leaves it within a little over half an ulp whatever the device's -//! error; the correctly rounded root is then that value or one of its neighbours, decided by -//! exact integer comparisons with the midpoints between them. With `Y = y 2^23` (an integer below -//! `2^25`) and the candidate `S = s 2^23`, `sqrt(y)` is above the midpoint `(2S + 1) 2^-24` when -//! `Y 2^25 > (2S + 1)^2`; with `R = r 2^24`, `rsqrt(y)` is above `(2R + 1) 2^-25` when `2^73 > -//! (2R + 1)^2 Y`. Both sides are integers and never equal, so there is no tie; the products are -//! two and three words of `OpUMulExtended`. -//! -//! **Every other operand** (a zero, a denormal, a negative value, an infinity, or a NaN) takes the -//! device's `Sqrt`, and `rsqrt` its reciprocal by the device's division: `sqrt(±0) = ±0`, -//! `rsqrt(±0) = ±inf`, `sqrt(+inf) = +inf`, `rsqrt(+inf) = +0`, a NaN for a negative operand or a -//! NaN, and a denormal read as the device reads it. How Metal reads a denormal operand of `sqrt` and `rsqrt` is the denormal model's -//! ([`denormal::operand`]), which hands the routine its operand. - -use crate::lower::arith::libm::atan::read; -use crate::lower::arith::libm::{Fun, E}; -use crate::spirv::error::BResult; -use crate::spirv::ids::Value; -use crate::spirv::ir::{BinOp, Contraction, GlslOp}; - -#[cfg(doc)] -use crate::lower::arith::denormal; - -/// Which root a routine answers. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Root { - Sqrt, - Rsqrt, -} - -/// Whether the 64-bit value `(alo, ahi)` is above `(blo, bhi)` (words low first). -fn above( - e: &mut E<'_, '_>, - (alo, ahi): (Value, Value), - (blo, bhi): (Value, Value), -) -> BResult { - let hi_above = e.iop(BinOp::UGreaterThan, ahi, bhi)?; - let hi_equal = e.iop(BinOp::IEqual, ahi, bhi)?; - let lo_above = e.iop(BinOp::UGreaterThan, alo, blo)?; - let tie_above = e.iop(BinOp::LogicalAnd, hi_equal, lo_above)?; - e.iop(BinOp::LogicalOr, hi_above, tie_above) -} - -/// The correctly rounded `S` from a candidate within one unit of it: `S + 1` where `up(2S + 1)` -/// holds, `S - 1` where `down(2S - 1)` does, `S` otherwise. -fn nearest( - e: &mut E<'_, '_>, - s: Value, - up: &dyn Fn(&mut E<'_, '_>, Value) -> BResult, - down: &dyn Fn(&mut E<'_, '_>, Value) -> BResult, -) -> BResult { - let one = e.u(1)?; - let twice = e.iop(BinOp::ShiftLeftLogical, s, one)?; - let odd_up = e.iop(BinOp::IAdd, twice, one)?; - let odd_down = e.iop(BinOp::ISub, twice, one)?; - let is_up = up(e, odd_up)?; - let is_down = down(e, odd_down)?; - let plus = e.iop(BinOp::IAdd, s, one)?; - let minus = e.iop(BinOp::ISub, s, one)?; - let r = e.sel(is_down, minus, s)?; - e.sel(is_up, plus, r) -} - -/// Metal's precise `which` of `x`. -pub(crate) fn root(e: &mut E<'_, '_>, which: Root, x: Value) -> BResult { - let fun = match which { - Root::Sqrt => Fun::Sqrt, - Root::Rsqrt => Fun::Rsqrt, - }; - let x = read(e, fun, x)?; - let bits = e.bits(x)?; - // A positive normal operand: bits from 0x0080_0000 below 0x7F80_0000. - let lead = e.u(0x0080_0000)?; - let offset = e.iop(BinOp::ISub, bits, lead)?; - let span = e.u(0x7F00_0000)?; - let normal = e.iop(BinOp::ULessThan, offset, span)?; - // The biased exponent `B`, the parity `p` of `B - 127`, and `y`'s bits: the fraction under the - // biased exponent `127 + p`. - let (k23, one) = (e.u(23)?, e.u(1)?); - let biased = e.iop(BinOp::ShiftRightLogical, bits, k23)?; - let b1 = e.iop(BinOp::IAdd, biased, one)?; - let p = e.iop(BinOp::BitwiseAnd, b1, one)?; - let (fraction, k127) = (e.u(0x007F_FFFF)?, e.u(127)?); - let f = e.iop(BinOp::BitwiseAnd, bits, fraction)?; - let yb = e.iop(BinOp::IAdd, k127, p)?; - let yb = e.iop(BinOp::ShiftLeftLogical, yb, k23)?; - let yb = e.iop(BinOp::BitwiseOr, f, yb)?; - let y = e.float(yb)?; - // `Y = y 2^23`, the significand shifted by the parity. - let m = e.iop(BinOp::BitwiseOr, f, lead)?; - let big_y = e.iop(BinOp::ShiftLeftLogical, m, p)?; - // `k + 127 = (B + 127 - p) / 2`. - let half_k = e.iop(BinOp::IAdd, biased, k127)?; - let half_k = e.iop(BinOp::ISub, half_k, p)?; - let k_biased = e.iop(BinOp::ShiftRightLogical, half_k, one)?; - let r = match which { - Root::Sqrt => { - // `s1 = s + (y - s^2) / (2s)`, the residual exact. - let s = e.device_sqrt(y)?; - let d = e.remainder(y, s, s)?; - let two_s = e.add(s, s)?; - let c = e.device_div(d, two_s)?; - let s1 = e.add(s, c)?; - let scale = e.c(8_388_608.0)?; - let s1 = e.mul(s1, scale)?; - let s1 = e.utrunc(s1)?; - // `Y 2^25` as two words, compared with `(2S ± 1)^2`. - let (k25, k7) = (e.u(25)?, e.u(7)?); - let ylo = e.iop(BinOp::ShiftLeftLogical, big_y, k25)?; - let yhi = e.iop(BinOp::ShiftRightLogical, big_y, k7)?; - let s = nearest( - e, - s1, - &|e, odd| { - let sq = e.umul(odd, odd)?; - above(e, (ylo, yhi), sq) - }, - &|e, odd| { - let sq = e.umul(odd, odd)?; - above(e, sq, (ylo, yhi)) - }, - )?; - // `S 2^(k - 23)`: an exact product, `S` at most `2^24`. - let sf = e.ufloat(s)?; - let shift = e.iop(BinOp::ISub, k_biased, k23)?; - let scale = e.iop(BinOp::ShiftLeftLogical, shift, k23)?; - let scale = e.float(scale)?; - e.mul(sf, scale)? - } - Root::Rsqrt => { - // `r1 = r + r h / 2` with `h = 1 - y r^2`, from the exact products `r^2 = th + tl` - // and `y th = uh + ul`; `r` is the device's `1 / sqrt(y)`. - let s = e.device_sqrt(y)?; - let one_f = e.c(1.0)?; - let r = e.device_div(one_f, s)?; - let th = e.mul(r, r)?; - let tl = e.product_error(r, r, th)?; - let uh = e.mul(y, th)?; - let ul = e.product_error(y, th, uh)?; - let v = e.mul(y, tl)?; - let half = e.c(0.5)?; - let h = e.sub(one_f, uh)?; - let h = e.sub(h, ul)?; - let h = e.sub(h, v)?; - let hh = e.mul(h, half)?; - let c = e.mul(r, hh)?; - let r1 = e.add(r, c)?; - let scale = e.c(16_777_216.0)?; - let r1 = e.mul(r1, scale)?; - let r1 = e.utrunc(r1)?; - // The third word of `(2R ± 1)^2 Y` against that of `2^73`, 512. - let k512 = e.u(512)?; - let top = |e: &mut E<'_, '_>, odd: Value| -> BResult { - let (plo, phi) = e.umul(odd, odd)?; - let (_, a1) = e.umul(plo, big_y)?; - let (b0, b1) = e.umul(phi, big_y)?; - let (_, carry) = e.uadd(a1, b0)?; - e.iop(BinOp::IAdd, b1, carry) - }; - let r = nearest( - e, - r1, - &|e, odd| { - let w = top(e, odd)?; - e.iop(BinOp::ULessThan, w, k512) - }, - &|e, odd| { - let w = top(e, odd)?; - e.iop(BinOp::UGreaterThanEqual, w, k512) - }, - )?; - // `R 2^(-k - 24)`, the exponent's bias `254 - (k + 127) - 24`. - let rf = e.ufloat(r)?; - let k230 = e.u(230)?; - let shift = e.iop(BinOp::ISub, k230, k_biased)?; - let scale = e.iop(BinOp::ShiftLeftLogical, shift, k23)?; - let scale = e.float(scale)?; - e.mul(rf, scale)? - } - }; - // The device's `Sqrt` of another operand, and its reciprocal by the device's division. - let device = e.fb.glsl(GlslOp::Sqrt, &[x])?; - let device = match which { - Root::Sqrt => device, - Root::Rsqrt => { - let one_f = e.c(1.0)?; - e.fb.binary_with(BinOp::FDiv, one_f, device, Contraction::Forbidden)? - } - }; - let r = e.sel(normal, r, device)?; - // A negative normal or infinite operand: Metal's NaN (a negative denormal is read as the - // device reads it). - let least = e.c(-f32::MIN_POSITIVE)?; - let domain = e.le(x, least)?; - let nan = e.metal_nan(None)?; - e.sel(domain, nan, r) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/rsqrt.rs b/crates/metal2vulkan/src/lower/arith/libm/rsqrt.rs deleted file mode 100644 index 497f5e12e..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/rsqrt.rs +++ /dev/null @@ -1,579 +0,0 @@ -//! Metal's fast `rsqrt`: its hardware's inverse square root, the one Metal's fast `rsqrt` answers -//! and its `asin` and `acos` in both modes and precise `asinh` and `acosh` take inside. -//! [`metal_rsqrt`] is [`super::Fun::FastRsqrt`]'s routine, which those routines call -//! ([`E::fast_rsqrt`]). A standalone `fast::rsqrt` or `fast::sqrt` keeps the device's -//! `InverseSqrt` (a recorded near-equivalent within Apple's bound, as the fast division keeps its -//! `RN(1 / b)`), so a small shader does not grow by the routine. -//! -//! Read off Metal's words (on the M3 Max, on the M4, the same at every operand): `fast::rsqrt` of -//! every `float` of `[1, 4)` and of every 256th positive `float`. Metal's root of `y = m 4^k`, `m` -//! in `[1, 4)`, is its root of `m` scaled by `2^-k`, and its root of `m` is the exact `1 / sqrt(m)` -//! plus a smooth error per 32nd of each binade of `m` (up to about a third of a unit), rounded to -//! nearest: it differs from the correctly rounded root at 725,821 of the 16,777,216 `float` values -//! of `[1, 4)`. [`TABLE`] fits the smooth part, a quartic per 32nd by its five `f32` coefficients -//! (in units of `2^-24`), so the routine is `RN(1 / sqrt(m) + eps(m))`: Metal's word at 16,746,537 -//! `float` values of `[1, 4)` (99.817 %) and 99.805 % of the sampled normal `float` values, one -//! unit off at the rest (an open near-equivalent). - -use crate::lower::arith::libm::E; -use crate::spirv::builder::ModuleBuilder; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, Value}; -use crate::spirv::ir::{BinOp, MemAccess}; - -/// Metal's inverse square root's error per 32nd of a binade of `m` in `[1, 4)`: row `(k >> 18) + -/// 32 b` of the fraction field `k` of `m` in binade `b` (0 for `[1, 2)`, 1 for `[2, 4)`), `eps = -/// c0 + t (c1 + t (c2 + t (c3 + t c4)))` at `t = (k mod 2^18) 2^-18`, in units of `2^-24` (`f32` -/// bits). -pub(crate) const TABLE: [[u32; 5]; 64] = [ - [ - 0x39D9_A548, - 0x3F8A_DE5A, - 0xC0B1_2C77, - 0x4111_27AC, - 0xC093_2A42, - ], - [ - 0x3C9F_B9B1, - 0x3F94_4437, - 0xC0A5_7EC3, - 0x40F0_C515, - 0xC061_7408, - ], - [ - 0xBB7E_3C94, - 0x3F48_60CE, - 0xC082_BD8A, - 0x40CB_F450, - 0xC048_125A, - ], - [ - 0xBD86_870F, - 0x3F7B_F8E7, - 0xC07F_2586, - 0x40BD_49D1, - 0xC030_5985, - ], - [ - 0x3DB0_FD94, - 0x3EFE_9CB4, - 0xC043_5A08, - 0x409F_B6D1, - 0xC01C_D405, - ], - [ - 0x3D87_842E, - 0x3E9B_0B75, - 0xC01B_ADA7, - 0x4085_4249, - 0xC006_BAA2, - ], - [ - 0xBC42_ABB3, - 0x3F0A_9035, - 0xC022_AF86, - 0x4081_A0F1, - 0xC007_22A9, - ], - [ - 0x3D4F_76AC, - 0xBC2C_CAC4, - 0xBFB6_6E80, - 0x4044_2648, - 0xBFDA_69E4, - ], - [ - 0x3DBF_5C77, - 0x3E90_9F4B, - 0xC00B_059B, - 0x4055_E04C, - 0xBFC5_D510, - ], - [ - 0xBB89_1985, - 0x3F48_1D44, - 0xC024_52B3, - 0x404D_A207, - 0xBFAE_8450, - ], - [ - 0xBD8C_2ECD, - 0x3F56_F550, - 0xC00F_6C14, - 0x4030_ED89, - 0xBF9B_89DC, - ], - [ - 0x3D9E_449A, - 0x3D09_F390, - 0xBF5F_38B3, - 0x3FF1_031B, - 0xBF8C_7C9D, - ], - [ - 0x3CAD_CCF2, - 0x3F0D_1232, - 0xBFF4_CBEE, - 0x401B_3C98, - 0xBF70_B150, - ], - [ - 0x3C5A_F741, - 0xBD58_057D, - 0xBEF8_F647, - 0x3FB9_B885, - 0xBF59_B990, - ], - [ - 0xBD5E_B8EC, - 0x3ED1_FEBC, - 0xBFC1_8926, - 0x4003_5BFA, - 0xBF5F_544E, - ], - [ - 0x3CB4_ADDD, - 0x3EA5_CF8A, - 0xBF91_EB2E, - 0x3FD6_A113, - 0xBF3B_4574, - ], - [ - 0xBDCE_901B, - 0x3F23_F497, - 0xBFCD_672F, - 0x3FD4_7A87, - 0xBF23_103E, - ], - [ - 0x3DA4_0977, - 0x3DBE_A274, - 0xBF1B_2170, - 0x3F83_EA4B, - 0xBF1E_DCE8, - ], - [ - 0x3DD1_408A, - 0x3E52_B163, - 0xBF86_B137, - 0x3F88_9830, - 0xBE8D_6290, - ], - [ - 0x3D25_83EE, - 0x3EAD_377D, - 0xBF8E_57D7, - 0x3FB3_7822, - 0xBF0E_A7A2, - ], - [ - 0xBC77_EE3A, - 0x3F1A_CD9E, - 0xBFA3_2322, - 0x3FA1_CB2F, - 0xBEF0_7009, - ], - [ - 0xBC91_EA98, - 0x3EF5_FA4B, - 0xBFB9_B80E, - 0x3FBB_70F2, - 0xBEF1_4999, - ], - [ - 0x3B53_7F7F, - 0x3D95_3A78, - 0xBEB9_9178, - 0x3F0C_213C, - 0xBEB6_0FC5, - ], - [ - 0x3CFC_3EDF, - 0x3E9E_2DA3, - 0xBF70_28A6, - 0x3F83_1ABD, - 0xBEB6_6013, - ], - [ - 0x3D8D_8A3B, - 0xBE3E_3877, - 0xBD02_F8E1, - 0x3F03_2B5E, - 0xBE9C_588C, - ], - [ - 0xBD8E_D5C8, - 0x3D63_077B, - 0x3D43_F066, - 0x3E7E_F632, - 0xBEA6_66F7, - ], - [ - 0xBD30_7445, - 0x3F17_B577, - 0xBF94_7BC5, - 0x3F5F_5A11, - 0xBE5E_5587, - ], - [ - 0x3D0E_4CB1, - 0xBD61_0726, - 0xBF0F_C52E, - 0x3F48_F2AB, - 0xBE83_CB68, - ], - [ - 0xBD5D_AADD, - 0x3EC3_B4A5, - 0xBF47_09C8, - 0x3F33_C738, - 0xBE71_AAA3, - ], - [ - 0x3C75_1580, - 0x3E74_B043, - 0xBF2B_0C91, - 0x3F48_2105, - 0xBE81_22FA, - ], - [ - 0xBC39_4794, - 0x3E7E_80BE, - 0xBF63_5C71, - 0x3F5B_3CD4, - 0xBE71_22B1, - ], - [ - 0x3DC0_F279, - 0xBE11_034E, - 0x3E62_AF3F, - 0x3AA5_DF59, - 0xBE67_3A63, - ], - [ - 0x3D8E_B56D, - 0x3F5C_518A, - 0xC082_43AF, - 0x40C1_B049, - 0xC037_C871, - ], - [ - 0x3D03_F11D, - 0x3F71_AA73, - 0xC083_9481, - 0x40BA_AAC8, - 0xC029_4C94, - ], - [ - 0xBDA0_5A60, - 0x3F6C_7EF7, - 0xC04A_A125, - 0x4093_5268, - 0xC011_232A, - ], - [ - 0x3C33_29F6, - 0x3EB0_BAE9, - 0xC005_3EE8, - 0x4068_BFE4, - 0xBFF6_1A57, - ], - [ - 0xBC8D_18C0, - 0x3F5F_F259, - 0xC038_AAC5, - 0x4074_A6D6, - 0xBFD6_0B2B, - ], - [ - 0xBBB2_6C38, - 0x3F1A_5B4A, - 0xC004_972B, - 0x403A_1508, - 0xBFB8_A1B1, - ], - [ - 0xBC2B_AA4D, - 0x3F1C_6D18, - 0xC009_2718, - 0x4037_81AD, - 0xBFA5_625E, - ], - [ - 0x3CEB_1182, - 0x3EFE_370E, - 0xBFFA_F7FF, - 0x4024_CC07, - 0xBF97_45E8, - ], - [ - 0xBD3B_6143, - 0x3E9D_48E1, - 0xBF77_7400, - 0x3FE9_8B67, - 0xBF8B_5784, - ], - [ - 0x3CEA_C677, - 0xB914_F100, - 0xBF13_12A4, - 0x3FBE_5ED0, - 0xBF70_87DF, - ], - [ - 0xBB2E_8F75, - 0x3D81_0130, - 0xBF7C_6316, - 0x3FE7_CE27, - 0xBF6D_0765, - ], - [ - 0x3DAC_F134, - 0x3DAA_880E, - 0xBF1B_BB32, - 0x3F99_BDE6, - 0xBF44_40F6, - ], - [ - 0xBBEE_FAB9, - 0x3E1F_E89A, - 0xBF37_1A0E, - 0x3F91_C795, - 0xBF34_AA63, - ], - [ - 0xBC2B_06C5, - 0x3D82_FBBD, - 0xBF29_3D90, - 0x3FAE_22AB, - 0xBF28_6AE4, - ], - [ - 0xBD05_6313, - 0xBD5D_9DBB, - 0xBDAB_48AA, - 0x3F41_C2E6, - 0xBF0F_5A2A, - ], - [ - 0x3CCE_9CD1, - 0x3E95_B1E9, - 0xBFA4_D4B5, - 0x3FBD_627C, - 0xBF08_0CAD, - ], - [ - 0xBC9F_5063, - 0x3E82_49FA, - 0xBF78_CAE9, - 0x3F9C_4B5A, - 0xBECE_1F1D, - ], - [ - 0x3DA3_18A3, - 0xBE1C_2771, - 0x3DF2_5CED, - 0x3EF8_2A55, - 0xBEE1_53F1, - ], - [ - 0xBD12_110B, - 0x3E8C_08B8, - 0xBF1E_E1F5, - 0x3F3E_960E, - 0xBED0_2000, - ], - [ - 0x3DA1_73DE, - 0x3E20_3934, - 0xBF65_D9F7, - 0x3F97_3811, - 0xBEBF_0D1F, - ], - [ - 0xBDD4_90BB, - 0x3EB6_C5F2, - 0xBECF_DE2B, - 0x3E80_3EB2, - 0xBDC8_7A82, - ], - [ - 0xBB67_0D8D, - 0x3DA1_62C8, - 0xBE1E_C4B3, - 0x3EC4_485D, - 0xBEA3_347E, - ], - [ - 0xBC87_0346, - 0x3E1C_B7E6, - 0x3C8E_8608, - 0x3E31_3918, - 0xBE99_B067, - ], - [ - 0x3CD4_D1FB, - 0x3F04_5C42, - 0xBFAC_7676, - 0x3F8C_C303, - 0xBE9F_5584, - ], - [ - 0x3DDF_71C6, - 0x3E0B_0763, - 0xBF5A_5BC6, - 0x3F6F_1D1C, - 0xBE6B_49B9, - ], - [ - 0x3DC3_F94C, - 0xBEDC_F690, - 0x3F03_9C3F, - 0x3D5B_6287, - 0xBE80_0515, - ], - [ - 0x3DDB_FEA9, - 0xBE7B_98D5, - 0x3E87_D9ED, - 0x3B02_0E39, - 0xBE16_937E, - ], - [ - 0xBCA1_5416, - 0x3E40_F303, - 0xBE50_234E, - 0x3E8A_044D, - 0xBE2E_B6D3, - ], - [ - 0x3D81_9004, - 0x3E1E_6115, - 0xBF06_AD9E, - 0x3F1C_92E1, - 0xBE5A_C76E, - ], - [ - 0xBD12_5845, - 0x3EB0_9C15, - 0xBF78_8C58, - 0x3F5F_B8B1, - 0xBE3D_DC2B, - ], - [ - 0x3E1A_0DA6, - 0xBE44_2A42, - 0xBD09_0233, - 0x3E94_A18A, - 0xBE4F_645A, - ], - [ - 0xBDDE_4A49, - 0x3EFC_1A0A, - 0xBEFD_384C, - 0xBD80_9F8E, - 0x3E5C_970A, - ], -]; - -/// The coefficients per row of [`TABLE`]. -const COEFFICIENTS: u32 = 5; - -/// An upper estimate of the SPIR-V words of [`TABLE`] in a module: its 320 constants, the -/// composite, and the array, pointer, and variable. -pub(crate) const TABLE_WORDS: u32 = 320 * 4 + 323 + 24; - -/// Declare [`TABLE`] in the module. -pub(crate) fn declare(mb: &mut ModuleBuilder) -> BResult { - super::declare_words(mb, TABLE.as_flattened()) -} - -/// Metal's inverse square root of `y`, for a positive normal `y`: `y = m 4^k` with `m` in `[1, -/// 4)` (`y`'s fraction field under an exponent field of 127 or 128), `r = RN(hi + RN(lo + eps(m) -/// 2^-24))` of `hi = RN(1 / sqrt(m))` (the module's correctly rounded `rsqrt`, [`E::rsqrt`]) and -/// `lo = RN(RN(hi d) / 2)` of `d = 1 - m hi^2` (formed from exact products, so `hi + lo` is the -/// exact root to a few units of `2^-48 hi`), then `r`'s exponent field moved by `-k`. Metal's -/// words at its special operands: a zero or denormal `y` gives `+inf`, `+inf` -/// gives `+0`, and a NaN gives a NaN (`y`; Metal's is `0x7fc00000`, its callers' NaN). Its -/// callers pass no negative operand, whose answer is its magnitude's. -pub(crate) fn metal_rsqrt(e: &mut E<'_, '_>, y: Value) -> BResult { - let table = e.rsqrt_table()?; - let b = e.bits(y)?; - let (fraction, field, k23) = (e.u(0x007F_FFFF)?, e.u(0xFF)?, e.u(23)?); - let k = e.iop(BinOp::BitwiseAnd, b, fraction)?; - let n = e.iop(BinOp::ShiftRightLogical, b, k23)?; - let n = e.iop(BinOp::BitwiseAnd, n, field)?; - // `b`: 0 for an odd exponent field (an even power of 2), 1 for an even one. - let one_u = e.u(1)?; - let odd = e.iop(BinOp::BitwiseAnd, n, one_u)?; - let binade = e.iop(BinOp::BitwiseXor, odd, one_u)?; - let one_bits = e.u(0x3F80_0000)?; - let shifted = e.iop(BinOp::ShiftLeftLogical, binade, k23)?; - let mb = e.iop(BinOp::IAdd, one_bits, shifted)?; - let mb = e.iop(BinOp::BitwiseOr, mb, k)?; - let m = e.float(mb)?; - let hi = e.rsqrt(m)?; - // `d = 1 - m hi^2`: `hi^2 = p + pe` and `m p = q + qe` exactly, `1 - q` exact (Sterbenz), - // and the rest far below `d`'s unit. - let p = e.mul(hi, hi)?; - let pe = e.exact_error(hi, hi, p)?; - let q = e.mul(m, p)?; - let qe = e.exact_error(m, p, q)?; - let w = e.mul(m, pe)?; - let one = e.c(1.0)?; - let d1 = e.sub(one, q)?; - let d2 = e.add(qe, w)?; - let d = e.sub(d1, d2)?; - let lo = e.mul(hi, d)?; - let half = e.c(0.5)?; - let lo = e.mul(lo, half)?; - // `eps(m)`: row `(k >> 18) + 32 b`, at `t = (k mod 2^18) 2^-18`. - let (low, k18, k5) = (e.u(0x3_FFFF)?, e.u(18)?, e.u(5)?); - let row = e.iop(BinOp::ShiftRightLogical, k, k18)?; - let upper = e.iop(BinOp::ShiftLeftLogical, binade, k5)?; - let row = e.iop(BinOp::IAdd, row, upper)?; - let t = e.iop(BinOp::BitwiseAnd, k, low)?; - let t = e.ufloat(t)?; - let scale = e.c(1.0 / 262_144.0)?; - let t = e.mul(t, scale)?; - let width = e.u(COEFFICIENTS)?; - let first = e.iop(BinOp::IMul, row, width)?; - let base = e.fb.module().global_value(table)?; - let coefficient = |e: &mut E<'_, '_>, j: u32| -> BResult { - let j = e.u(j)?; - let i = e.iop(BinOp::IAdd, first, j)?; - let p = e.fb.access_chain(base, &[i])?; - let w = e.fb.load(p, MemAccess::default())?; - e.float(w) - }; - // Horner's rule in plain `float`, as the table was fitted. - let mut eps = coefficient(e, COEFFICIENTS - 1)?; - for j in (0..COEFFICIENTS - 1).rev() { - let c = coefficient(e, j)?; - let p = e.mul(eps, t)?; - eps = e.add(p, c)?; - } - let unit = e.c(1.0 / 16_777_216.0)?; - let eps = e.mul(eps, unit)?; - let tail = e.add(lo, eps)?; - let r = e.add(hi, tail)?; - // `r` in `[1/2, 1]` scaled by `2^((127 + b - n) / 2)` of the exponent field `n` (an even - // difference), through `r`'s exponent field. - let rb = e.bits(r)?; - let bias = e.u(0x7F)?; - let s = e.iop(BinOp::IAdd, bias, binade)?; - let s = e.iop(BinOp::ISub, s, n)?; - let s = e.iop(BinOp::ShiftRightArithmetic, s, one_u)?; - let s = e.iop(BinOp::ShiftLeftLogical, s, k23)?; - let v = e.iop(BinOp::IAdd, rb, s)?; - // Metal's specials: a zero exponent field gives `+inf`, and `+inf` gives `+0`. - let zero = e.u(0)?; - let infinity = e.u(0x7F80_0000)?; - let tiny = e.iop(BinOp::IEqual, n, zero)?; - let v = e.sel(tiny, infinity, v)?; - let inf = e.iop(BinOp::IEqual, b, infinity)?; - let v = e.sel(inf, zero, v)?; - let r = e.float(v)?; - let nan = e.is_nan(y)?; - e.sel(nan, y, r) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/sincos.rs b/crates/metal2vulkan/src/lower/arith/libm/sincos.rs deleted file mode 100644 index 41d4be16f..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/sincos.rs +++ /dev/null @@ -1,444 +0,0 @@ -//! Metal's precise `sin` and `cos` of a `float`: Metal's own form, `t S(t)` of the folded -//! quarter-turn value `t` and its hardware's `sinc`, which follows Apple's runtime library; the -//! `sinc` through a model of the hardware's, read off directly. -//! -//! **Reduction** to quarter turns, `x 2/π = k + r`, by Metal's own reduction ([`quarter::turns`], -//! without the error term of its large operands). The quarter turns fold `r` into `t` in `[-1, 1]` -//! with `sin(x) = sin(π t / 2)`: `t = r` for an even `k` and `1 - |r|` for an odd one (`sin`), -//! `1 - |r|` and `-r` (`cos`), negated where `k`'s bit 1 is set. -//! -//! **The `sinc`.** Metal multiplies `t` by its hardware's `S(t)`, about `sin(π t / 2) / t` -//! within an ulp, and rounds the product. The hardware reads `|t|` as 23 fractional bits, -//! truncated (`m = floor(|t| 2^23)`; every word of the probe is constant on those cells), and is -//! a cubic in the offset `d` of `m` in each of 32 segments of `2^18` (its errors jump at the -//! segments' ends), with a residue of a few thousandths of an ulp that no cubic follows: the same -//! word on every run and on the M3 and the M4, so the hardware's own behaviour, unmodelled. The -//! model ([`SINC`]) is a cubic per segment by Horner's rule in integers, 12 bits below `S`'s ulp, -//! fitted to the hardware's words at every `m`: Metal's word at 8,377,984 of the 8,388,608 `m` -//! below 1 (99.873 %), and through it Metal's precise `sin` and `cos` at 99.86 % to 99.91 % of -//! the measured operands, where the correctly rounded value is at 45 % to 58 %. -//! `S(0)` is `RN(π/2)` and `S(1)` is 1, as the hardware answers. -//! -//! **Special operands**: below `2^-12` in magnitude or at it (a zero and a denormal included), -//! `sin(x)` is `x` and `cos(x)` is 1; an infinity or a NaN, Metal's NaN. -//! -//! **Metal's `half` `sin` and `cos`** ([`half_sin_cos`]) are its own form, which follows Apple's -//! runtime library: a shorter reduction (`2/π`'s first two parts, no table) with the same fold and -//! `sinc`, and `sin(x) = x` below `1/64`. Rounded to `half`, Metal's word at every `half`, the 6 -//! (`sin`) and 2 (`cos`) where that is not the correctly rounded value -//! among them. - -use crate::lower::arith::libm::atan::read; -use crate::lower::arith::libm::quarter::{self, Error}; -use crate::lower::arith::libm::trig::Trig; -use crate::lower::arith::libm::{Fun, E}; -use crate::spirv::builder::ModuleBuilder; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, Value}; -use crate::spirv::ir::{BinOp, MemAccess, UnOp}; - -/// The model of the hardware's `sinc`, per segment `j` of `2^18` cells `m = floor(|t| 2^23)`: the -/// bits of `S` at the segment's start (`0x3f800000` plus the constant term's whole ulps), the -/// constant term's 12 bits below the ulp, and the cubic's coefficients of `(d / 2^18)^1..3` in -/// units of `2^-12` ulp (`i32` as `u32`). -pub(crate) const SINC: [[u32; 5]; 32] = [ - [ - 0x3FC9_0FDA, - 0x0000_0794, - 0x0000_05DE, - 0xFEB5_3041, - 0x0000_17DB, - ], - [ - 0x3FC8_FB2F, - 0x0000_0595, - 0xFD6A_B5BE, - 0xFEB5_70B1, - 0x0000_3F85, - ], - [ - 0x3FC8_BD35, - 0x0000_0B8F, - 0xFAD6_5BFF, - 0xFEB6_280C, - 0x0000_67F5, - ], - [ - 0x3FC8_5604, - 0x0000_078B, - 0xF843_E80D, - 0xFEB7_5BF3, - 0x0000_9004, - ], - [ - 0x3FC7_C5C1, - 0x0000_0B97, - 0xF5B4_53AB, - 0xFEB9_08C7, - 0x0000_B782, - ], - [ - 0x3FC7_0CA2, - 0x0000_0E8F, - 0xF328_9001, - 0xFEBB_27F8, - 0x0000_E00C, - ], - [ - 0x3FC6_2AEC, - 0x0000_0792, - 0xF0A1_87C7, - 0xFEBD_C4AF, - 0x0001_077D, - ], - [ - 0x3FC5_20F1, - 0x0000_0C93, - 0xEE20_2FCC, - 0xFEC0_D483, - 0x0001_2FAB, - ], - [ - 0x3FC3_EF15, - 0x0000_0190, - 0xEBA5_69E6, - 0xFEC4_6840, - 0x0001_4FDA, - ], - [ - 0x3FC2_95C7, - 0x0000_048F, - 0xE932_2DE1, - 0xFEC8_6042, - 0x0001_77E1, - ], - [ - 0x3FC1_1587, - 0x0000_0A91, - 0xE6C7_5BC8, - 0xFECC_C892, - 0x0001_9FA1, - ], - [ - 0x3FBF_6EE3, - 0x0000_0E91, - 0xE465_CDCF, - 0xFED1_AC7B, - 0x0001_BFB2, - ], - [ - 0x3FBD_A277, - 0x0000_0892, - 0xE20E_6FA9, - 0xFED6_F105, - 0x0001_E742, - ], - [ - 0x3FBB_B0EC, - 0x0000_0099, - 0xDFC2_0B40, - 0xFEDC_AE08, - 0x0002_069C, - ], - [ - 0x3FB9_9AF7, - 0x0000_0F93, - 0xDD81_83BB, - 0xFEE2_C4B8, - 0x0002_2F83, - ], - [ - 0x3FB7_615F, - 0x0000_0794, - 0xDB4D_9D79, - 0xFEE9_4D70, - 0x0002_4F05, - ], - [ - 0x3FB5_04F3, - 0x0000_008E, - 0xD927_29D4, - 0xFEF0_3496, - 0x0002_6F90, - ], - [ - 0x3FB2_868F, - 0x0000_0E94, - 0xD70E_E999, - 0xFEF7_7CEE, - 0x0002_8F71, - ], - [ - 0x3FAF_E71F, - 0x0000_0493, - 0xD505_91C9, - 0xFEFF_3076, - 0x0002_A7BC, - ], - [ - 0x3FAD_2795, - 0x0000_0F92, - 0xD30B_ED89, - 0xFF07_2D5B, - 0x0002_C70B, - ], - [ - 0x3FAA_48F4, - 0x0000_008E, - 0xD122_9FBD, - 0xFF0F_88BB, - 0x0002_DF87, - ], - [ - 0x3FA7_4C44, - 0x0000_088A, - 0xCF4A_561C, - 0xFF18_2BA7, - 0x0003_004C, - ], - [ - 0x3FA4_329C, - 0x0000_0999, - 0xCD83_AD66, - 0xFF21_2976, - 0x0003_1712, - ], - [ - 0x3FA0_FD1B, - 0x0000_0690, - 0xCBCF_45BC, - 0xFF2A_6CA0, - 0x0003_2FA1, - ], - [ - 0x3F9D_ACE9, - 0x0000_0796, - 0xCA2D_AF77, - 0xFF33_F561, - 0x0003_4715, - ], - [ - 0x3F9A_4338, - 0x0000_048E, - 0xC89F_6FA7, - 0xFF3D_CD00, - 0x0003_574F, - ], - [ - 0x3F96_C141, - 0x0000_079B, - 0xC725_154A, - 0xFF47_D1AB, - 0x0003_6EF6, - ], - [ - 0x3F93_2846, - 0x0000_0D95, - 0xC5BF_0970, - 0xFF52_1D7B, - 0x0003_7F02, - ], - [ - 0x3F8F_7991, - 0x0000_049A, - 0xC46D_C522, - 0xFF5C_9E3C, - 0x0003_8E84, - ], - [ - 0x3F8B_B670, - 0x0000_0697, - 0xC331_AD68, - 0xFF67_4D67, - 0x0003_9F20, - ], - [ - 0x3F87_E03A, - 0x0000_008E, - 0xC20B_27CA, - 0xFF72_246B, - 0x0003_AFCE, - ], - [ - 0x3F83_F849, - 0x0000_0B94, - 0xC0FA_7D5C, - 0xFF7D_2DAB, - 0x0003_B6E7, - ], -]; - -/// An upper estimate of the SPIR-V words of [`SINC`] in a module: its 160 constants, the -/// composite, and the array, pointer, and variable. -pub(crate) const TABLE_WORDS: u32 = 160 * 4 + 163 + 24; - -/// Declare [`SINC`] in the module. -pub(crate) fn declare(mb: &mut ModuleBuilder) -> BResult { - super::declare_words(mb, SINC.as_flattened()) -} - -/// The `float` bits at or below which `sin(x)` is `x` and `cos(x)` is 1 (`2^-12`). -const TINY: u32 = 0x3980_0000; - -/// `floor(a d / 2^18)` of the `i32` `a` and the offset `d` (below `2^18`), as an `i32` (the -/// callers' values keep it in range): the 64-bit product's bits from 18 on. -fn scaled(e: &mut E<'_, '_>, a: Value, d: Value) -> BResult { - let p = e.fb.binary(BinOp::SMulExtended, a, d)?; - let lo = e.fb.composite_extract(p, &[0])?; - let hi = e.fb.composite_extract(p, &[1])?; - let (k18, k14) = (e.u(18)?, e.u(14)?); - let lo = e.iop(BinOp::ShiftRightLogical, lo, k18)?; - let hi = e.iop(BinOp::ShiftLeftLogical, hi, k14)?; - e.iop(BinOp::BitwiseOr, hi, lo) -} - -/// The model of the hardware's `sinc` of `|t| <= 1` (the module's doc), which Metal's `sinpi`, -/// `cospi` and `tanpi` take too (`pi`). -pub(super) fn sinc(e: &mut E<'_, '_>, at: Value) -> BResult { - let cells = e.c(8_388_608.0)?; - let scaled_t = e.mul(at, cells)?; - let m = e.utrunc(scaled_t)?; - let k18 = e.u(18)?; - let j = e.iop(BinOp::ShiftRightLogical, m, k18)?; - let last = e.u(31)?; - let past = e.iop(BinOp::UGreaterThan, j, last)?; - let j = e.sel(past, last, j)?; - let mask = e.u(0x3_FFFF)?; - let d = e.iop(BinOp::BitwiseAnd, m, mask)?; - let five = e.u(5)?; - let first = e.iop(BinOp::IMul, j, five)?; - let table = e.sinc_table()?; - let base = e.fb.module().global_value(table)?; - let word = |e: &mut E<'_, '_>, i: u32| -> BResult { - let i = e.u(i)?; - let i = e.iop(BinOp::IAdd, first, i)?; - let p = e.fb.access_chain(base, &[i])?; - e.fb.load(p, MemAccess::default()) - }; - let (start, low, c1, c2, c3) = ( - word(e, 0)?, - word(e, 1)?, - word(e, 2)?, - word(e, 3)?, - word(e, 4)?, - ); - let s = scaled(e, c3, d)?; - let t2 = e.iop(BinOp::IAdd, c2, s)?; - let s = scaled(e, t2, d)?; - let t1 = e.iop(BinOp::IAdd, c1, s)?; - let p = scaled(e, t1, d)?; - let w = e.iop(BinOp::IAdd, low, p)?; - let (half, k12) = (e.u(2048)?, e.u(12)?); - let w = e.iop(BinOp::IAdd, w, half)?; - let q = e.iop(BinOp::ShiftRightArithmetic, w, k12)?; - let bits = e.iop(BinOp::IAdd, start, q)?; - let v = e.float(bits)?; - // `S(0) = RN(π/2)`, `S(1) = 1`. - let zero = e.u(0)?; - let at_zero = e.iop(BinOp::IEqual, m, zero)?; - let half_pi = e.c(std::f32::consts::FRAC_PI_2)?; - let v = e.sel(at_zero, half_pi, v)?; - let one = e.c(1.0)?; - e.sel(past, one, v) -} - -/// Metal's precise `which` (`Sin` or `Cos`) of `x` (the module's doc). -pub(crate) fn sin_cos(e: &mut E<'_, '_>, which: Trig, x: Value) -> BResult { - let fun = match which { - Trig::Sin => Fun::Sin, - Trig::Cos => Fun::Cos, - }; - let x = read(e, fun, x)?; - let (r, k) = quarter::turns(e, x, Error::Dropped)?; - let (one_u, two_u, zero_u) = (e.u(1)?, e.u(2)?, e.u(0)?); - let odd = e.iop(BinOp::BitwiseAnd, k, one_u)?; - let odd = e.iop(BinOp::INotEqual, odd, zero_u)?; - let flip = e.iop(BinOp::BitwiseAnd, k, two_u)?; - let flip = e.iop(BinOp::INotEqual, flip, zero_u)?; - let ar = e.abs(r)?; - let one = e.c(1.0)?; - let rest = e.sub(one, ar)?; - let t = match which { - Trig::Sin => e.sel(odd, rest, r)?, - Trig::Cos => { - let minus_r = e.fb.unary(UnOp::FNegate, r)?; - e.sel(odd, minus_r, rest)? - } - }; - let minus_t = e.fb.unary(UnOp::FNegate, t)?; - let t = e.sel(flip, minus_t, t)?; - let at = e.abs(t)?; - let s = sinc(e, at)?; - let v = e.mul(t, s)?; - // At or below 2^-12: `x` or 1; an infinity or a NaN: Metal's NaN. - let ax = e.abs(x)?; - let bits = e.bits(ax)?; - let tiny = e.u(TINY + 1)?; - let is_tiny = e.iop(BinOp::ULessThan, bits, tiny)?; - let small = match which { - Trig::Sin => x, - Trig::Cos => one, - }; - let v = e.sel(is_tiny, small, v)?; - let inf = e.u(0x7F80_0000)?; - let finite = e.iop(BinOp::ULessThan, bits, inf)?; - let nan = e.metal_nan(None)?; - e.sel(finite, v, nan) -} - -/// The `float` bits below which Metal's `half` `sin(x)` is `x` (`1/64`). -const HALF_SIN_TINY: u32 = 0x3C80_0000; - -/// Metal's `half` `sin` or `cos` (`which`) before its rounding to `half`, of a `half` `x` held as -/// `float`: its own form, which follows Apple's runtime library. The quarter turns `k` are the low -/// bits of `s = fma(x, c0, m)`, `m = 1.5 2^23` (`1.5 2^23 + 1` for `cos`, a quarter turn on), and -/// `r = fma(x, c1, fma(x, c0, m - s))` of `2/π`'s first two parts ([`quarter::QUARTER`]; the -/// `float` routine adds a third), folded and signed as the `float` routine's (`t = r` for an even -/// `k` and `1 - |r|` for an odd one, negated where `k`'s bit 1 is set), and `t S(t)` of the -/// hardware's `sinc` ([`sinc`]). `sin(x)` is `x` below `1/64` in magnitude; an infinity or a NaN -/// gives Metal's NaN. -pub(crate) fn half_sin_cos(e: &mut E<'_, '_>, which: Trig, x: Value) -> BResult { - let ax = e.abs(x)?; - let bits = e.bits(ax)?; - let inf = e.u(0x7F80_0000)?; - let finite = e.iop(BinOp::ULessThan, bits, inf)?; - let zero = e.c(0.0)?; - // An infinity or a NaN reduces 0 instead, so that no value selected away reaches the `sinc`'s - // integer conversion. - let xr = e.sel(finite, x, zero)?; - let [c0, c1, _] = quarter::QUARTER.map(f32::from_bits); - let magic = match which { - Trig::Sin => 12_582_912.0, - Trig::Cos => 12_582_913.0, - }; - let (c0, c1, m) = (e.c(c0)?, e.c(c1)?, e.c(magic)?); - let s = e.fused(xr, c0, m)?; - let k = e.bits(s)?; - let minus_k = e.sub(m, s)?; - let r = e.fused(xr, c0, minus_k)?; - let r = e.fused(xr, c1, r)?; - let (one_u, two_u, zero_u) = (e.u(1)?, e.u(2)?, e.u(0)?); - let odd = e.iop(BinOp::BitwiseAnd, k, one_u)?; - let odd = e.iop(BinOp::INotEqual, odd, zero_u)?; - let flip = e.iop(BinOp::BitwiseAnd, k, two_u)?; - let flip = e.iop(BinOp::INotEqual, flip, zero_u)?; - let ar = e.abs(r)?; - let one = e.c(1.0)?; - let rest = e.sub(one, ar)?; - let t = e.sel(odd, rest, r)?; - let minus_t = e.fb.unary(UnOp::FNegate, t)?; - let t = e.sel(flip, minus_t, t)?; - let at = e.abs(t)?; - let st = sinc(e, at)?; - let v = e.mul(t, st)?; - let v = match which { - Trig::Sin => { - let tiny = e.u(HALF_SIN_TINY)?; - let is_tiny = e.iop(BinOp::ULessThan, bits, tiny)?; - e.sel(is_tiny, x, v)? - } - Trig::Cos => v, - }; - let nan = e.metal_nan(None)?; - e.sel(finite, v, nan) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/tan.rs b/crates/metal2vulkan/src/lower/arith/libm/tan.rs deleted file mode 100644 index 231851fc7..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/tan.rs +++ /dev/null @@ -1,72 +0,0 @@ -//! Metal's precise `tan` of a `float`: its own form, which follows Apple's runtime library and -//! matches Metal's measured words (the M3 Max: every `float` of `[0.25, 4)`, every -//! 16th from `2^-11`, every 256th from 4, and every 4096th from `2^21`). -//! -//! **Reduction** to quarter turns, `r = x 2/π - k`, by Metal's own reduction -//! ([`quarter::turns`], with the rounding error of its large operands' difference added). -//! -//! **Quotient.** With `s = r^2`, `N = r P(s)` ([`TAN_P`]) and `D = Q(s)` ([`TAN_Q`]), each by -//! Horner's rule in fused steps from the highest coefficient. `tan(x)` is `N / D` for an even -//! `k` and `-D / N` for an odd one, correctly rounded: Metal's reciprocal with two fused -//! corrections gives the correctly rounded quotient at every measured operand, so the module's -//! precise division routine ([`E::div`]) answers it on every device. -//! -//! **Special operands**: below `2^-11` in magnitude (a zero and a denormal included) `x` itself; -//! an infinity or a NaN, Metal's NaN. - -use crate::lower::arith::libm::atan::read; -use crate::lower::arith::libm::quarter::{self, Error}; -use crate::lower::arith::libm::{Fun, E}; -use crate::spirv::error::BResult; -use crate::spirv::ids::Value; -use crate::spirv::ir::{BinOp, UnOp}; - -/// `P(s)` of `N = r P(s)` (`f32` bits, lowest first). -pub(crate) const TAN_P: [u32; 5] = [ - 0x3FC9_0FDB, - 0xBF25_5DE7, - 0x3DA3_35DD, - 0xBB99_67FB, - 0x3927_F34F, -]; - -/// `Q(s)`, the denominator `D` (`f32` bits, lowest first). -pub(crate) const TAN_Q: [u32; 6] = [ - 0x3F80_0000, - 0xBF9D_E9E6, - 0x3E81_E0F7, - 0xBCAA_E925, - 0x3A70_B770, - 0xB7C9_C073, -]; - -/// The `float` bits below which `tan(x)` is `x` (`2^-11`). -const TINY: u32 = 0x3A00_0000; - -/// Metal's precise `tan(x)` (the module's doc). -pub(crate) fn tan(e: &mut E<'_, '_>, x: Value) -> BResult { - let x = read(e, Fun::Tan, x)?; - let (r, k) = quarter::turns(e, x, Error::Compensated)?; - // `N / D` or `-D / N`. - let s = e.mul(r, r)?; - let pn = e.fused_poly(&TAN_P, s)?; - let n = e.mul(r, pn)?; - let d = e.fused_poly(&TAN_Q, s)?; - let (one_u, zero_u) = (e.u(1)?, e.u(0)?); - let odd = e.iop(BinOp::BitwiseAnd, k, one_u)?; - let odd = e.iop(BinOp::INotEqual, odd, zero_u)?; - let minus_d = e.fb.unary(UnOp::FNegate, d)?; - let num = e.sel(odd, minus_d, n)?; - let den = e.sel(odd, n, d)?; - let q = e.div(num, den)?; - // Below 2^-11: `x`; an infinity or a NaN: Metal's NaN. - let ax = e.abs(x)?; - let bits = e.bits(ax)?; - let tiny = e.u(TINY)?; - let is_tiny = e.iop(BinOp::ULessThan, bits, tiny)?; - let q = e.sel(is_tiny, x, q)?; - let inf = e.u(0x7F80_0000)?; - let finite = e.iop(BinOp::ULessThan, bits, inf)?; - let nan = e.metal_nan(None)?; - e.sel(finite, q, nan) -} diff --git a/crates/metal2vulkan/src/lower/arith/libm/trig.rs b/crates/metal2vulkan/src/lower/arith/libm/trig.rs deleted file mode 100644 index af4316b4e..000000000 --- a/crates/metal2vulkan/src/lower/arith/libm/trig.rs +++ /dev/null @@ -1,116 +0,0 @@ -//! The trigonometric functions' other routines: Metal's fast `sin` and `cos`, and Metal's `half` -//! `tan`. Its precise `sin` and `cos` are Metal's own form (`libm::sincos`), its precise `tan` too -//! (`libm::tan`), and its `sinpi`, `cospi` and `tanpi` (`libm::pi`). -//! -//! **Metal's fast `sin` and `cos`** below their flush point (`math::fast_trig_flush` answers -//! past it) are its precise functions: they agree on 864 of the 865 such lanes of cases 087758cb -//! and cc234732 (the one apart, `fast::sin(-2^-12)`, is an ulp below), and on every `float` of -//! `[0.25, 1)`, within 2.2 ulp of the exact value inside and outside `[-π, π]`. Inside `[-π, π]`, -//! where Apple bounds them by `2^-13` absolute (MSL Table 8.2) and every device measured meets it, -//! the device's `Sin` or `Cos` answers; past `π`, where the table states no bound and the devices -//! are up to 1.8 off (ANV; RADV 0.21, NVIDIA 0.56), the precise routine does, per lane under a -//! branch, so a wave whose lanes all lie inside `[-π, π]` runs the device's instruction alone. A -//! denormal operand joins the branch too: Metal keeps it (`fast::sin(x) = x`, `fast::cos(x) = 1`, -//! case cc234732) where RADV, ANV, and NVIDIA flush it, and the routine's selects answer it -//! ([`denormal::operand`]). - -use crate::lower::arith::libm::atan::read; -use crate::lower::arith::libm::{quarter, sincos, Fun, E}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; -use crate::spirv::error::{BResult, BuildError, TypeRule}; -use crate::spirv::ids::Value; -use crate::spirv::ir::{BinOp, GlslOp, UnOp}; - -#[cfg(doc)] -use crate::lower::arith::denormal; - -/// Which function a routine answers. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Trig { - Sin, - Cos, -} - -/// Metal's fast `which` (`Sin` or `Cos`) of `x` below its flush point: the device's instruction -/// where `|x| < float(π)` (or `x` is NaN, whose answer the flush selects), the precise routine -/// from `float(π)` up, which is past `π`, and for a denormal `x`, which Metal keeps -/// ([`denormal::operand`]) where a device that flushes it answers its zero, under a branch on the -/// lane's `|x|`. So the device answers only inside `[-π, π]`, where Apple bounds its answer -/// (MSL Table 8.2) and the user accepts it; at `±float(π)` it was outside that bound on RADV, ANV -/// and the RTX 5080, where the routine is Metal's word. The denormal is told by its -/// bits, so a device that flushes in comparisons tells it too. -pub(crate) fn fast(e: &mut E<'_, '_>, which: Trig, x: Value) -> BResult { - let (op, fun) = match which { - Trig::Sin => (GlslOp::Sin, Fun::FastSin), - Trig::Cos => (GlslOp::Cos, Fun::FastCos), - }; - let x = read(e, fun, x)?; - let ax = e.abs(x)?; - let pi = e.c(std::f32::consts::PI)?; - let past = e.ge(ax, pi)?; - let bits = e.bits(ax)?; - let one = e.u(1)?; - let below = e.iop(BinOp::ISub, bits, one)?; - let largest = e.u(0x007F_FFFF)?; - let denormal = e.iop(BinOp::ULessThan, below, largest)?; - let past = e.iop(BinOp::LogicalOr, past, denormal)?; - let (rough, fma, helpers) = (e.rough, e.fma, e.helpers); - let routine: ArmFn<'_, ()> = Box::new(move |fb, _| { - let mut e = E { - fb, - rough, - fma, - helpers, - }; - let v = sincos::sin_cos(&mut e, which, x)?; - Ok(ArmEnd::FallThrough(vec![v])) - }); - let inside: ArmFn<'_, ()> = Box::new(move |fb, _| { - let device = fb.glsl(op, &[x])?; - Ok(ArmEnd::FallThrough(vec![device])) - }); - let merged = e.fb.if_(&mut (), past, routine, Some(inside))?; - merged - .0 - .first() - .copied() - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) -} - -/// `P(s)` of Metal's `half` `tan(x) = r P(r r)` on the reduced argument `r` in quarter turns, -/// its `f32` coefficients by their bits, lowest first (the values Metal's form takes). Horner's -/// rule in `s` (rounded), each step one fused multiply-add. -pub(crate) const HALF_TAN_P: [u32; 4] = [0x3FC9_0D3B, 0x3FA6_963B, 0x3F8C_CDD0, 0x400F_C280]; - -/// Metal's `half` `tan(x)` before its rounding to `half`, of a `half` `x` held as `float`: its own -/// form, which follows Apple's runtime library. The quarter turns `k` are the low bits of `s = -/// fma(x, c0, m)`, `m = 1.5 2^23`, and `r = fma(x, c1, fma(x, c0, m - s))` of `2/π`'s first two -/// parts ([`quarter::QUARTER`]), `t = r P(r r)` of [`HALF_TAN_P`], and `t` for an even `k`, Metal's -/// reciprocal of `-t` ([`E::recip`]) for an odd one. A zero gives `+0`, and an infinity or a NaN -/// Metal's NaN. Rounded to `half`, Metal's word at every `half`. -pub(crate) fn half_tan(e: &mut E<'_, '_>, x: Value) -> BResult { - let ax = e.abs(x)?; - let bits = e.bits(ax)?; - let inf = e.u(0x7F80_0000)?; - let finite = e.iop(BinOp::ULessThan, bits, inf)?; - let zero = e.c(0.0)?; - let xr = e.sel(finite, x, zero)?; - let [c0, c1, _] = quarter::QUARTER.map(f32::from_bits); - let (c0, c1, m) = (e.c(c0)?, e.c(c1)?, e.c(12_582_912.0)?); - let s = e.fused(xr, c0, m)?; - let k = e.bits(s)?; - let minus_k = e.sub(m, s)?; - let r = e.fused(xr, c0, minus_k)?; - let r = e.fused(xr, c1, r)?; - let r2 = e.mul(r, r)?; - let p = e.fused_poly(&HALF_TAN_P, r2)?; - let t = e.mul(r, p)?; - let minus_t = e.fb.unary(UnOp::FNegate, t)?; - let cot = e.recip(minus_t)?; - let (one_u, zero_u) = (e.u(1)?, e.u(0)?); - let odd = e.iop(BinOp::BitwiseAnd, k, one_u)?; - let odd = e.iop(BinOp::INotEqual, odd, zero_u)?; - let v = e.sel(odd, cot, t)?; - let nan = e.metal_nan(None)?; - e.sel(finite, v, nan) -} diff --git a/crates/metal2vulkan/src/lower/arith/math.rs b/crates/metal2vulkan/src/lower/arith/math.rs index 37837bfaf..acfeeb815 100644 --- a/crates/metal2vulkan/src/lower/arith/math.rs +++ b/crates/metal2vulkan/src/lower/arith/math.rs @@ -6,22 +6,22 @@ //! Exact sequences are used wherever `GLSL.std.450` differs from Metal: `clz`/`ctz` from //! `FindUMsb`/`FindILsb` with the zero case, `rotate` and the funnel shifts with an in-range //! second shift (`(x >> 1) >> (N - 1 - s)`), `round` (half away from zero) from `Trunc`, `mix` -//! as Metal computes it (on `float` and `half` `fma(t, y, fma(-t, x, x))` by the profile's fused -//! multiply-add route, `metal_mix`; elsewhere `x * (1 - t) + y * t`), and saturating +//! as Metal computes it where the device's functions are Metal's (on `float` and `half` +//! `fma(t, y, fma(-t, x, x))` by the profile's fused multiply-add route, `metal_mix`; on `bfloat` +//! and `double` `x * (1 - t) + y * t`), and saturating //! float-to-integer `air.convert` (NaN to 0, out-of-range to the bound, measured on Apple GPUs) //! with the clamp applied before the conversion so no conversion is out of range. `sign`, `fract`, //! `saturate`, `median3`, and on `float` and `half` `fmin`, `fmax`, `min3`, `max3`, and `clamp` //! answer as Metal does at their special operands (zeros, NaNs, infinities, `f32` denormals), which //! `FSign`, `Fract`, `NClamp`, and `NMin`/`NMax` leave to the device. Where `GLSL.std.450` is a -//! different function from Metal's, Metal's is emitted: `sinpi`, `cospi`, and `tanpi` are Metal's -//! own forms (`libm`) and elsewhere reduce their argument exactly instead of scaling it by -//! `float(π)`, `fast_tanh` on `float` is the MSL fast-math formula, and the sRGB conversions go +//! different function from Metal's, Metal's is emitted: `sinpi`, `cospi`, and `tanpi` reduce their +//! argument exactly instead of scaling it by `float(π)`, `fast_tanh` on `float` is the MSL +//! fast-math formula, and the sRGB conversions go //! through Metal's twelve-bit tables ([`srgb`]). Functions whose Vulkan precision is looser than //! correct rounding record a `PrecisionNote` at selection. use crate::air::intrinsics::PackFormat; use crate::lower::arith::denormal; -use crate::lower::arith::divide::{self, Reciprocal, Rough}; 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}; @@ -29,10 +29,10 @@ use crate::lower::arith::nan::{self, NanTest}; use crate::lower::arith::narrow; use crate::lower::arith::ops::{fsplat, mask, ones, sext, splat, ty, CastKind}; use crate::lower::arith::srgb; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; +use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::{BResult, BuildError, TypeRule}; -use crate::spirv::ids::{FuncId, GlobalId, Value}; -use crate::spirv::ir::{BinOp, Contraction, ConvOp, GlslOp, Type, UnOp}; +use crate::spirv::ids::{GlobalId, Value}; +use crate::spirv::ir::{BinOp, Contraction, ConvOp, GlslOp, UnOp}; /// Whether an integer function reads its operands as signed. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -746,14 +746,15 @@ pub enum FloatFn { /// of the `f32` container, so exact for NaNs and zeros on every device. Not on `double`. CopySign, // Device precision (`PrecisionNote::DeviceArithmetic`). - /// Metal's precise `sqrt`: correctly rounded (MSL Table 8.1). On `float` and `half`, the - /// device's instruction where it is Metal's own in a module compiled with precise functions, - /// the translation's routine otherwise ([`libm`]). + /// Metal's precise `sqrt`: correctly rounded (MSL Table 8.1). The device's `Sqrt`, Metal's own + /// where the device's functions are Metal's in a module compiled with precise functions + /// ([`libm`]). Sqrt, /// `fma` on `double` (`GLSL.std.450 Fma`) and `bfloat` (`narrow::bf16_fma`). `float` and `half` /// select the correctly rounded [`super::fma`]. Fma, - /// Metal's precise `fmod`: exact (Table 8.1), `fmod(x, ±inf) = x`; as [`FloatFn::Sqrt`]. + /// Metal's precise `fmod`: exact (Table 8.1), `fmod(x, ±inf) = x`. On `float` and `half` its + /// routine, but where the device's `OpFRem` is Metal's `fmod` ([`libm::Fun::device_answers`]). Fmod, Dot, // Device precision (`PrecisionNote::DeviceTranscendentals`). @@ -766,18 +767,17 @@ pub enum FloatFn { /// `+inf` (`fast_sqrt_of`). FastSqrt, /// Metal's precise `exp`: within 4 ulp (MSL Table 8.1). On `float` and `half`, where the - /// device's functions are Metal's, the device's instruction in a module compiled with precise - /// functions and Metal's own composition of the device's `exp2` in a fast-math one (as - /// [`FloatFn::Exp10`]); the translation's routine elsewhere ([`libm`]). + /// device's functions are Metal's in a module compiled with precise functions, the device's + /// instruction; elsewhere Metal's own composition of the device's `exp2` (as + /// [`FloatFn::Exp10`], `metal_exp`). Exp, /// `air.fast_exp` on `float`: `exp2(x · log2(e))` as Metal composes it, the product rounded, /// of Metal's `exp2` ([`FloatFn::Exp2`]). FastExp, - /// Metal's `exp2`, the same function in both modes: the device's instruction where it is - /// Metal's own, the translation's routine otherwise. + /// Metal's `exp2`, the same function in both modes: the device's instruction. Exp2, - /// Metal's precise `exp10`: Metal's own composition of the device's `exp2` where that is - /// Metal's, the translation's routine on `float` and `half` otherwise, as no instruction is it. + /// Metal's precise `exp10`: Metal's own composition of the device's `exp2` (`metal_exp`), as no + /// instruction is it. Exp10, /// `air.fast_exp10` on `float`: `exp2(x · log2(10))` (MSL Table 8.2), the product rounded. FastExp10, @@ -788,25 +788,22 @@ pub enum FloatFn { FastLog, /// Metal's `log2`, the same function in both modes; as [`FloatFn::Exp2`]. Log2, - /// `air.fast_log2` on `float`: Metal's `log2` ([`FloatFn::Log2`]), the device's instruction - /// where it is Metal's own, elsewhere the translation's routine of it (`libm::Fun::Log2`). + /// `air.fast_log2` on `float`: Metal's `log2` ([`FloatFn::Log2`]), the device's instruction. FastLog2, /// Metal's precise `log10`; as [`FloatFn::Exp10`]. Log10, /// `air.fast_log10` on `float`: `log2(x) · log10(2)` (MSL Table 8.2), the product rounded: /// every lane of case f6524207. FastLog10, - /// Metal's precise `sin`: within 4 ulp (MSL Table 8.1). On `float` and `half`, the device's - /// instruction where it is Metal's own in a module compiled with precise functions, the - /// translation's routine otherwise ([`libm`]). + /// Metal's precise `sin`: 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 + /// ([`libm`]). 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`). The device's `Sin` where its - /// functions are Metal's, in either mode; elsewhere the device's `Sin` inside `[-π, π]` - /// (Apple's `2^-13` bound) and the translation's precise routine past it ([`libm`]). Where - /// they are Metal's in its fast mode (`Lib::metal_fast`), the device's `Sin` is Metal's + /// 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). @@ -818,15 +815,12 @@ pub enum FloatFn { 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 Metal's - /// fast division (`fast_tan`), a call of its [`FastDivision`] routine. - FastTan { - /// The fast division's reciprocal on the profile. - reciprocal: Reciprocal, - }, - /// Metal's precise `asin`: within 4 ulp (MSL Table 8.1). On `float`, the device's - /// instruction where it is Metal's own in a module compiled with precise functions, the - /// translation's routine otherwise ([`libm`]). + /// elsewhere the formula of [`FloatFn::FastSin`] and [`FloatFn::FastCos`] divided by the + /// device's division (`fast_tan`). + 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 + /// ([`libm`]). Asin, /// `air.fast_asin` on `float`: within 5 ulp (Table 8.2); as [`FloatFn::Asin`], in Metal's /// fast mode. @@ -848,24 +842,21 @@ pub enum FloatFn { Cosh, /// `air.fast_cosh` on `float`: `(exp(x) + exp(-x)) · 0.5`; as [`FloatFn::FastSinh`]. FastCosh, - /// Metal's precise `tanh` (within 5 ulp): the device's instruction where its functions are - /// Metal's (SPIRV-Cross emits `precise::tanh` in either mode), the routine otherwise. + /// 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`). Narrow forms keep [`FloatFn::Tanh`]: the - /// fast-math table is the single-precision one. - FastTanh { - /// The fast division's reciprocal on the profile. - reciprocal: Reciprocal, - }, + /// `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. + FastTanh, /// Metal's precise `asinh`; as [`FloatFn::Exp`]. Asinh, /// `air.fast_asinh` on `float` with every flag: Metal's fast formula - /// `log(x + sqrt(x * x + 1))` (MSL Table 8.2) in Metal's own form (`libm::Fun::FastAsinh`), - /// which is the canonical NaN at `-inf` (`-inf + inf`), or the device's `Asinh` where it is - /// Metal's in a fast-math module. + /// `log(x + sqrt(x * x + 1))` (MSL Table 8.2), which is the canonical NaN at `-inf` + /// (`-inf + inf`): the device's `Asinh`, Metal's own in a fast-math module where its functions + /// are Metal's. FastAsinh, /// Metal's precise `acosh`; as [`FloatFn::Exp`]. Acosh, @@ -873,24 +864,18 @@ 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 Metal's - /// fast division, or the device's `Atanh` where it is Metal's in a fast-math module. - FastAtanh { - /// The fast division's reciprocal on the profile. - reciprocal: Reciprocal, - }, - /// Metal's `sinpi`: within 4 ulp (MSL Table 8.1). On `float` and `half`, Metal's own form, - /// the translation's routine ([`libm`]); on a `bfloat` the exact reduction around the device's - /// `Sin` and `Cos` (`pi_scaled`). + /// `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. + 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. SinPi, /// Metal's `cospi`; as [`FloatFn::SinPi`]. CosPi, /// Metal's `tanpi`: within 6 ulp; as [`FloatFn::SinPi`]. TanPi, /// `air.fast_sinpi` on `float`: Metal's fast `sinpi`, which is its precise one - /// ([`FloatFn::SinPi`]): the routine, but where the device's functions are Metal's, the exact - /// reduction around its `Sin` and `Cos` (`pi_scaled`), within Apple's `2^-13` bound on - /// `[-1, 1]` (MSL Table 8.2). + /// ([`FloatFn::SinPi`]), the same reduction. FastSinPi, /// `air.fast_cospi` on `float`; as [`FloatFn::FastSinPi`]. FastCosPi, @@ -908,9 +893,8 @@ pub enum FloatFn { /// rather than itself. FastPow, /// Metal `atan2(y, x)`: C99 Annex F's special values, as Metal answers them - /// (`atan2_special`), around the generic value: on `float`, the device's `Atan2` where its - /// functions are Metal's (always `precise::atan2` there), the translation's routine - /// otherwise ([`libm`]). + /// (`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 @@ -985,7 +969,7 @@ impl FloatFn { | F::FastSin | F::FastCos | F::Tan - | F::FastTan { .. } + | F::FastTan | F::Asin | F::FastAsin | F::Acos @@ -997,13 +981,13 @@ impl FloatFn { | F::Cosh | F::FastCosh | F::Tanh - | F::FastTanh { .. } + | F::FastTanh | F::Asinh | F::FastAsinh | F::Acosh | F::FastAcosh | F::Atanh - | F::FastAtanh { .. } + | F::FastAtanh | F::SinPi | F::CosPi | F::TanPi @@ -1029,22 +1013,18 @@ impl FloatFn { /// reads a denormal operand as the zero of its sign and flushes a denormal result on the bits, /// and `fast::sqrt`, which selects the zero of a denormal operand's sign and has no denormal /// result. The arc tangent family (`asin`, `acos`, and `atan`, both modes), precise `sin`, - /// `cos`, and `tan`, and `sinpi`, `cospi`, and `tanpi` do too on `float`: each is either the - /// device's instruction where that is Metal's own function, or the translation's routine, which - /// reads a denormal operand as Metal does (`denormal::operand`) and has no denormal result for - /// a normal operand (where llvmpipe's `atan(2^-126)` is `0x007fff52`); and + /// `cos`, and `tan`, `sinpi`, `cospi`, and `tanpi`, and the second stage's functions are listed + /// where the device's instruction is Metal's own function; where it is not, the call records + /// the device's denormals with its precision (`PrecisionNote::NativeTranscendentals`). /// `fast::sin`, `fast::cos`, and `fast::tan` keep a denormal operand as Metal does, where RADV, - /// ANV, and NVIDIA flush it (case cc234732). `fast::atan2` does not: its quotient is the - /// device's division, whose operands `denormal::coverage` reads as Metal does. The second stage's - /// functions do: their routines read a denormal operand as Metal does (`exp` and the hyperbolic - /// functions as itself below `2^-12`, the logarithms and `pow`'s base as a zero) and flush a - /// denormal result, 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). `round` answers `+0` for every zero it reaches, whatever zero the device's - /// `Trunc` gives a denormal, which Metal's `round` of a denormal is (the denormal probes, both - /// modes); precise `fmod` on `float` is the remainder's routine, which reads a denormal divisor - /// as a zero on the bits and computes the remainder in integers (`libm::fmod`), or on MoltenVK - /// Metal's own. + /// ANV, and NVIDIA flush it (case cc234732), and the fast formulas' steps have no denormal + /// intermediate on which their result depends (`fast::sinh` of a denormal is + /// `(1 - 1) · 0.5 = +0`, as Metal answers, case f6524207). `fast::atan2` does not: its quotient + /// is the device's division, whose operands `denormal::coverage` reads. `round` answers `+0` + /// for every zero it reaches, whatever zero the device's `Trunc` gives a denormal, which + /// Metal's `round` of a denormal is (the denormal probes, both modes); precise `fmod` on + /// `float` is the remainder's routine, which reads a denormal divisor as a zero on the bits and + /// computes the remainder in integers (`libm::fmod`), or on MoltenVK Metal's own. pub fn metal_denormals(self) -> bool { use FloatFn as F; matches!( @@ -1073,7 +1053,7 @@ impl FloatFn { | F::Tan | F::FastSin | F::FastCos - | F::FastTan { .. } + | F::FastTan | F::SinPi | F::CosPi | F::TanPi @@ -1099,13 +1079,13 @@ impl FloatFn { | F::Cosh | F::FastCosh | F::Tanh - | F::FastTanh { .. } + | F::FastTanh | F::Asinh | F::FastAsinh | F::Acosh | F::FastAcosh | F::Atanh - | F::FastAtanh { .. } + | F::FastAtanh | F::Pow | F::FastPow | F::Powr @@ -1113,8 +1093,8 @@ impl FloatFn { ) } - /// Whether the device's order (`RoundingOrderRoute::Native`) answers the function by the - /// device's instruction where Metal's answer is computed around one without a routine: + /// Whether the device's order (`Lib::orders_natively`) answers the function by the device's + /// instruction where Metal's answer is computed around one: /// `fast::sqrt`, the device's `Sqrt`, where Metal's is `x · rsqrt(x)` with its own answers at /// a zero, a denormal and `+inf` ([`fast_sqrt_of`]). pub fn native_instruction(self) -> bool { @@ -1124,7 +1104,7 @@ impl FloatFn { /// Whether the lowering on lanes of format `fmt` answers Metal's NaN bit pattern itself, so it /// records no `PrecisionNote::DeviceNanEncoding` and needs no select: the functions that select /// their NaN (or answer a number for one: `sign`, `saturate`, `fast::sin`, `fast::cos`), - /// `fast::tanh`, whose result is Metal's fast quotient, `median3`, and on `float` and `half` + /// `median3`, and on `float` and `half` /// `fmin`, `fmax`, `min3`, `max3`, and `clamp` (`metal_min_max`), which return an operand, /// `copysign`, which moves bits, and `fabs` on `float`, which clears the sign bit on the bits /// ([`sign_on_bits`]; a `half` `fabs` answers its canonical NaN by a select). @@ -1148,7 +1128,6 @@ impl FloatFn { | F::CopySign | F::Atan2 | F::FastAtan2 { .. } - | F::FastTanh { .. } | F::Pow | F::FastPow | F::FastSin @@ -1159,17 +1138,17 @@ impl FloatFn { /// 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 · rcp(x)` (Metal's reciprocal's - /// model, or the device's division where it is Metal's), `fast::tan`'s quotient of its sine by + /// `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. pub fn divides(self) -> bool { matches!( self, - FloatFn::FastTanh { .. } + FloatFn::FastTanh | FloatFn::FastAtan2 { .. } - | FloatFn::FastTan { .. } - | FloatFn::FastAtanh { .. } + | FloatFn::FastTan + | FloatFn::FastAtanh | FloatFn::FastTanPi ) } @@ -1217,7 +1196,7 @@ impl FloatFn { let half = f.float_fmt() == Some(FloatFmt::Half); let base = match metal_half(self, f) { // `half_tanh`: the quotient's operands and product, and the far operands' test and - // signed one (its routines' calls are counted below). + // signed one. FloatFn::Tanh if half => 160, // Metal's other `half` functions by its fast compositions (`metal_half`), and a // scalar's constants of the rounding. @@ -1230,22 +1209,20 @@ impl FloatFn { { 128 } - FloatFn::FastSinh | FloatFn::FastCosh if half => 128 + libm::use_words(f.lanes, 1), + FloatFn::FastSinh | FloatFn::FastCosh if half => 144, FloatFn::Sign | FloatFn::Saturate | FloatFn::Fract | FloatFn::FastFract { .. } => 96, // `fract`, and the operand's exponent test and the bound's select. FloatFn::FlaggedFract => 128, // The steps and the `+0` of a zero result. FloatFn::Round => 128, // The device's function and the operands' tests where Metal answers NaN, the precise - // sign's on the bits, each operand classified once: 226 words with the routine's calls - // on `float4`. + // sign's on the bits, each operand classified once. FloatFn::Powr => 208, // 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` (two calls of `exp2`'s routine, the second - // counted here). - FloatFn::FastSinh | FloatFn::FastCosh => 96 + libm::use_words(f.lanes, 1), + // Metal's formulas of its fast `exp`, of two of the device's `exp2`. + FloatFn::FastSinh | FloatFn::FastCosh => 112, // Two selects per step for the operand and its compared value, and each operand's // flush test. FloatFn::Median3 | FloatFn::FastMedian3 => 192, @@ -1256,41 +1233,36 @@ impl FloatFn { 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`): 390 words - // with the routine's calls on `float4`. + // `|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 (the routine's calls are - // counted below). + // The magnitude's test against the last evaluated quadrant. FloatFn::FastSin | FloatFn::FastCos => 48, - // Both flushes, the denormal operand's select, and the call of the fast division's - // routine ([`FastDivision`], whose words are the module's). - FloatFn::FastTan { .. } => 160 + FAST_DIVISION_CALL_WORDS, + // Both flushes, the denormal operand's select, and the device's division. + FloatFn::FastTan => 176, // The product and Metal's zeros and infinity. FloatFn::FastSqrt => 96, // The special operands' tests and the selected constant's sign. FloatFn::Atan2 => 320, // The quotient, its special values and sign, and the turn. FloatFn::FastAtan2 { .. } => 400, - // Where no routine answers them (a `bfloat`), the period reduction, the exact axis - // arms, both quadrant selections, `tanpi`'s quarter turns, and the finiteness guard around - // the device's `Sin` and `Cos` (`pi_scaled`); the routines' calls are counted below. - FloatFn::SinPi | FloatFn::CosPi | FloatFn::TanPi if libm::uses(self, f).is_empty() => { - 384 - } - // Through the routine: its call, counted below, and Metal's NaN's select. - FloatFn::SinPi | FloatFn::CosPi | FloatFn::TanPi => 112, - // The routine's call, or where the device's functions are Metal's the reduction - // around its `Sin` and `Cos`, which the routine's words do not cover. - FloatFn::FastSinPi | FloatFn::FastCosPi | FloatFn::FastTanPi => 384, + // The period reduction, the exact axis arms, both quadrant selections, `tanpi`'s + // quarter turns, and the finiteness guard around the device's `Sin` and `Cos` + // (`pi_scaled`). + FloatFn::SinPi + | FloatFn::CosPi + | FloatFn::TanPi + | FloatFn::FastSinPi + | FloatFn::FastCosPi + | 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 call of - // the fast division's routine ([`FastDivision`], whose words are the module's). - FloatFn::FastTanh { .. } => 80 + FAST_DIVISION_CALL_WORDS, - // `1 ± x`, the call of the fast division's routine, and the halving. - FloatFn::FastAtanh { .. } => 96 + FAST_DIVISION_CALL_WORDS, + // `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, // Metal's composition where its `exp2` is the device's (`metal_exp`): five products // and sums, two fused ones, the device's `exp2`, and the ends' tests: 136 words on // `float4`. @@ -1302,8 +1274,9 @@ impl FloatFn { FloatFn::Ldexp => 160, _ => 48, }; - // A routine's calls, one per lane; the routine itself is the module's. A `half` function's - // zero select (`half_zero`), its operand below a magnitude (`half_small`), `half` `cospi`'s + // Each function the call takes: the device's instruction, or precise `fmod`'s routine's + // calls, one per lane (the routine itself is the module's). A `half` function's zero + // select (`half_zero`), its operand below a magnitude (`half_small`), `half` `cospi`'s // zero sign (`half_cospi_zero`), and `half` `asin`'s NaN sign (`half_signed_nan`). let base = base + libm::uses(self, f) @@ -1328,11 +1301,12 @@ impl FloatFn { } } -/// Emit float function `op` on `args` (floats of form `f`; `Ldexp`'s exponent is a held `i32` -/// and `Dot` gives the scalar), calling `lib`'s routines where the device's instruction does not -/// answer the function. Metal's operand-picking functions (`metal_min_max`, `metal_median3`) test -/// their operands for NaNs by `test`, the test the entry's float modes leave exact -/// ([`NanTest::for_modes`]). A `half` `fmod` answers Metal's zero remainder (`half_fmod_zero`). +/// Emit float function `op` on `args` (floats of form `f`; `Ldexp`'s exponent is a held `i32` and +/// `Dot` gives the scalar), by the device's instructions, and precise `fmod` by `lib`'s routine +/// where the module defines it. Metal's operand-picking functions (`metal_min_max`, +/// `metal_median3`) test their operands for NaNs by `test`, the test the entry's float modes leave +/// exact ([`NanTest::for_modes`]). A `half` `fmod` answers Metal's zero remainder +/// (`half_fmod_zero`). pub fn float_fn( fb: &mut FunctionBuilder<'_>, op: FloatFn, @@ -1340,7 +1314,7 @@ pub fn float_fn( contract: Contraction, test: NanTest, args: &[Value], - lib: &Lib<'_>, + lib: &Lib, ) -> BResult { use FloatFn as F; let r = float_fn_core(fb, op, f, contract, test, args, lib)?; @@ -1390,8 +1364,8 @@ pub fn float_fn( /// and the precise function is not at 2 operands of `cosh`, 3 pairs of `pow` and `powr`, and 4 /// operands of `sinh`, whose fast one is again Metal's with the translation's `exp2` and `log2` /// in place of Metal's. Its `tanh` is `half_tanh`, and its `atan`, `atan2`, `tan`, `sin`, `cos`, -/// and `asinh` are its own `half` forms, which no `float` function rounds to: `libm::uses` gives -/// them their routines. +/// and `asinh` are its own `half` forms, which no `float` function rounds to: the device's `float` +/// function rounded answers them at the device's precision (`libm::uses`). pub(crate) fn metal_half(op: FloatFn, f: Form) -> FloatFn { if f.float_fmt() != Some(FloatFmt::Half) { return op; @@ -1412,35 +1386,20 @@ pub(crate) fn metal_half(op: FloatFn, f: Form) -> FloatFn { /// Metal's `half` `tanh(x)` on `half` lanes `x` (form `f`, held in `f32`) before its rounding: /// `(t - 1) · rcp(t + 1)` of `t = exp2(x · RN(2 log2 e))`, MSL Table 8.2's `fast::tanh` of -/// Metal's `exp2` and reciprocal (the routines `libm::Fun::Exp2` and `libm::Fun::Recip`, or the -/// device's instructions where they are Metal's), and `±1` from `|x| = 16`, where the answer -/// rounds to `±1` (the quotient is a NaN past `x ≈ 44`, where Metal's `half` `tanh` is `1`). -/// Below `2^-13` the operand itself (`half_small`). Every `half` of our probes is -/// this, with the translation's `exp2` and reciprocal in place of Metal's (and with a correctly -/// rounded reciprocal or quotient in place of the reciprocal); Metal's precise `float` `tanh`, -/// rounded, is not at 7 of them, nor its fast one, rounded, below `2^-13` and past `44`. -fn half_tanh(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, lib: &Lib<'_>) -> BResult { +/// Metal's `exp2` and reciprocal (the device's `Exp2` and division), and `±1` from `|x| = 16`, +/// where the answer rounds to `±1` (the quotient is a NaN past `x ≈ 44`, where Metal's `half` +/// `tanh` is `1`). Below `2^-13` the operand itself (`half_small`). Every `half` of our probes is +/// this, with the device's `exp2` and reciprocal in place of Metal's; Metal's precise `float` +/// `tanh`, rounded, is not at 7 of them, nor its fast one, rounded, below `2^-13` and past `44`. +fn half_tanh(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { let exact = Contraction::Forbidden; let k = wide_splat(fb, f, 2.0 * std::f64::consts::LOG2_E)?; let p = fb.binary_with(BinOp::FMul, x, k, exact)?; - let t = routine_or( - fb, - lib, - FloatFn::Tanh, - f, - libm::Fun::Exp2, - GlslOp::Exp2, - &[p], - )?; + let t = glsl(fb, GlslOp::Exp2, &[p])?; let one = wide_splat(fb, f, 1.0)?; let num = fb.binary_with(BinOp::FSub, t, one, exact)?; let den = fb.binary_with(BinOp::FAdd, t, one, exact)?; - let recip = libm::Fun::Recip; - let r = if libm::uses(FloatFn::Tanh, f).contains(&recip) && !lib.device(recip) { - lib.call(fb, recip, f, &[den])? - } else { - fb.binary_with(BinOp::FDiv, one, den, exact)? - }; + let r = fb.binary_with(BinOp::FDiv, one, den, exact)?; let q = fb.binary_with(BinOp::FMul, num, r, exact)?; let ax = glsl(fb, GlslOp::FAbs, &[x])?; let limit = wide_splat(fb, f, 16.0)?; @@ -1582,25 +1541,16 @@ fn float_fn_core( contract: Contraction, test: NanTest, args: &[Value], - lib: &Lib<'_>, + lib: &Lib, ) -> BResult { use FloatFn as F; let a = arg(args, 0)?; // Metal's `half` functions, by the `float` function whose rounded answer each is. if f.float_fmt() == Some(FloatFmt::Half) && op == F::Tanh { - return half_tanh(fb, f, a, lib); + return half_tanh(fb, f, a); } let op = metal_half(op, f); - // The device's instruction `o`, or `op`'s routine where the device does not answer it. - let lib1 = |fb: &mut FunctionBuilder<'_>, o: GlslOp, x: Value| -> BResult { - match libm::uses(op, f) { - [r] if !lib.device(*r) => lib.call(fb, *r, f, &[x]), - _ => glsl(fb, o, &[x]), - } - }; let g1 = |fb: &mut FunctionBuilder<'_>, o: GlslOp| glsl(fb, o, &[a]); - // The device's instruction answers `op` itself (`lib1` calls no routine). - let by_device = !matches!(libm::uses(op, f), [r] if !lib.device(*r)); let times = |fb: &mut FunctionBuilder<'_>, k: f64| -> BResult { let c = wide_splat(fb, f, k)?; bin(fb, BinOp::FMul, a, c) @@ -1635,7 +1585,7 @@ fn float_fn_core( } F::Sign => metal_sign(fb, f, a), // Metal's `clamp(x, +0, 1)` at every operand: the device's `NClamp` where the minimum and - // maximum functions take it (measured to be Metal's, or native device maths, + // maximum functions take it (measured to be Metal's, or the device's own, // `PrecisionNote::NativeMinMax`). F::Saturate if metal_picks(f.float_fmt()) && lib.device_min_max() => { let (z, one) = (fsplat(fb, f, 0.0)?, fsplat(fb, f, 1.0)?); @@ -1665,8 +1615,8 @@ fn float_fn_core( let (b, c) = (arg(args, 1)?, arg(args, 2)?); metal_median3(fb, f, test, [a, b, c], op == F::FastMedian3) } - // `float` and `half` take Metal's fused form ([`metal_mix`]), a strategy of its own with - // its fused multiply-adds' routines; the device's order takes the device's `FMix` + // `float` and `half` take Metal's fused form ([`metal_mix`]) where the device's functions + // are Metal's, a strategy of its own; the device's order takes the device's `FMix` // (`PrecisionNote::NativeMix`). F::Mix if matches!(f.float_fmt(), Some(FloatFmt::F32 | FloatFmt::Half)) => { if !lib.orders_natively() { @@ -1699,20 +1649,20 @@ fn float_fn_core( let r = bin(fb, BinOp::FAdd, p, arg(args, 2)?)?; narrow::round_exact_below_normal(fb, f, r) } - F::Sqrt => lib1(fb, GlslOp::Sqrt, a), + F::Sqrt => g1(fb, GlslOp::Sqrt), F::Fma if f.float_fmt() == Some(FloatFmt::BFloat) => { narrow::bf16_fma(fb, f, a, arg(args, 1)?, arg(args, 2)?) } F::Fma => glsl(fb, GlslOp::Fma, &[a, arg(args, 1)?, arg(args, 2)?]), F::Fmod => { let y = arg(args, 1)?; - match libm::uses(op, f) { - [r] if !lib.device(*r) => lib.call(fb, *r, f, &[a, y]), + match lib.fmod(fb, f, a, y)? { + Some(r) if libm::uses(op, f).contains(&libm::Fun::Fmod) => Ok(r), _ => bin(fb, BinOp::FRem, a, y), } } F::Dot => bin(fb, BinOp::Dot, a, arg(args, 1)?), - F::Rsqrt => lib1(fb, GlslOp::InverseSqrt, a), + F::Rsqrt => g1(fb, GlslOp::InverseSqrt), F::FastRsqrt => g1(fb, GlslOp::InverseSqrt), // The device's order: its `Sqrt`. F::FastSqrt if lib.orders_natively() => g1(fb, GlslOp::Sqrt), @@ -1720,32 +1670,23 @@ fn float_fn_core( let r = g1(fb, GlslOp::InverseSqrt)?; fast_sqrt_of(fb, f, a, r) } - // A device whose functions are Metal's answers precise `exp` in a precise module; in a - // fast-math one, Metal's own composition of its `exp2` does. - F::Exp => match libm::uses(op, f) { - [r] if !lib.device(*r) => lib.call(fb, *r, f, &[a]), - [_] if !lib.metal_in(libm::Mode::Precise) => { - metal_exp(fb, f, a, std::f64::consts::LOG2_E) - } - _ => g1(fb, GlslOp::Exp), - }, - F::Exp2 => lib1(fb, GlslOp::Exp2, a), - // Likewise precise `log`: in a fast-math module Metal's composition of its `log2`. - F::Log => match libm::uses(op, f) { - [r] if !lib.device(*r) => lib.call(fb, *r, f, &[a]), - [_] if !lib.metal_in(libm::Mode::Precise) => { - metal_log(fb, f, a, &libm::log::LOG_NEAR, libm::log::LN_2_BITS) - } - _ => g1(fb, GlslOp::Log), - }, - F::Log2 | F::FastLog2 => lib1(fb, GlslOp::Log2, a), - // No instruction is Metal's `exp10` or `log10`: their routines, or Metal's own - // compositions of the device's `exp2` and `log2` where those are Metal's. - F::Exp10 | F::Log10 => match libm::uses(op, f) { - [r] if !lib.device(*r) => lib.call(fb, *r, f, &[a]), - _ if op == F::Exp10 => metal_exp(fb, f, a, std::f64::consts::LOG2_10), - _ => metal_log(fb, f, a, &libm::log::LOG10_NEAR, libm::log::LOG10_2_BITS), - }, + // A device whose functions are Metal's answers precise `exp` in a precise module; + // elsewhere Metal's own composition of the device's `exp2` does. + F::Exp if f.float_fmt() == Some(FloatFmt::F32) && !lib.metal_in(libm::Mode::Precise) => { + metal_exp(fb, f, a, std::f64::consts::LOG2_E) + } + F::Exp => g1(fb, GlslOp::Exp), + F::Exp2 => g1(fb, GlslOp::Exp2), + // Likewise precise `log`: elsewhere Metal's composition of the device's `log2`. + F::Log if f.float_fmt() == Some(FloatFmt::F32) && !lib.metal_in(libm::Mode::Precise) => { + metal_log(fb, f, a, &libm::LOG_NEAR, libm::LN_2_BITS) + } + F::Log => g1(fb, GlslOp::Log), + F::Log2 | F::FastLog2 => g1(fb, GlslOp::Log2), + // No instruction is Metal's `exp10` or `log10`: Metal's own compositions of the device's + // `exp2` and `log2`. + F::Exp10 => metal_exp(fb, f, a, std::f64::consts::LOG2_10), + F::Log10 => metal_log(fb, f, a, &libm::LOG10_NEAR, libm::LOG10_2_BITS), // Metal's fast compositions of its `exp2` and `log2` (MSL Table 8.2). F::FastExp | F::FastExp10 => { let k = if op == F::FastExp { @@ -1754,10 +1695,10 @@ fn float_fn_core( std::f64::consts::LOG2_10 }; let x = times(fb, k)?; - routine_or(fb, lib, op, f, libm::Fun::Exp2, GlslOp::Exp2, &[x]) + glsl(fb, GlslOp::Exp2, &[x]) } F::FastLog | F::FastLog10 => { - let l = routine_or(fb, lib, op, f, libm::Fun::Log2, GlslOp::Log2, &[a])?; + let l = g1(fb, GlslOp::Log2)?; let k = if op == F::FastLog { std::f64::consts::LN_2 } else { @@ -1766,12 +1707,12 @@ fn float_fn_core( let c = wide_splat(fb, f, k)?; fb.binary_with(BinOp::FMul, l, c, Contraction::Forbidden) } - F::Sin => lib1(fb, GlslOp::Sin, a), - F::Cos => lib1(fb, GlslOp::Cos, a), + 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() && by_device => { + F::FastSin | F::FastCos if lib.metal_fast() => { let o = if op == F::FastSin { GlslOp::Sin } else { @@ -1780,78 +1721,66 @@ fn float_fn_core( g1(fb, o) } F::FastSin => { - let r = lib1(fb, GlslOp::Sin, a)?; + let r = g1(fb, GlslOp::Sin)?; fast_trig_flush(fb, f, a, r) } F::FastCos => { - let r = lib1(fb, GlslOp::Cos, a)?; + let r = g1(fb, GlslOp::Cos)?; fast_trig_flush(fb, f, a, r) } - F::Tan => lib1(fb, GlslOp::Tan, a), - // A device whose functions are Metal's in a fast-math module: its `Tan` is `fast::tan`. - F::FastTan { .. } if lib.metal_in(libm::Mode::Fast) => g1(fb, GlslOp::Tan), - // Its quotient is a call of the fast division's routine, which the caller declares: - // [`fast_tan`]. - F::FastTan { .. } => Err(BuildError::Type(TypeRule::FunctionSignature)), - F::Asin | F::FastAsin => lib1(fb, GlslOp::Asin, a), - F::Acos | F::FastAcos => lib1(fb, GlslOp::Acos, a), - F::Atan | F::FastAtan => lib1(fb, GlslOp::Atan, a), - F::Sinh => lib1(fb, GlslOp::Sinh, a), - F::Cosh => lib1(fb, GlslOp::Cosh, a), - F::Tanh => lib1(fb, GlslOp::Tanh, a), - F::Asinh => lib1(fb, GlslOp::Asinh, a), - F::Acosh => lib1(fb, GlslOp::Acosh, a), - F::Atanh => lib1(fb, GlslOp::Atanh, a), + F::Tan => g1(fb, GlslOp::Tan), + F::FastTan => fast_tan(fb, f, a, lib), + 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, lib), - // Metal's own forms of its fast `asinh` and `acosh` (`libm::hyper::fast_arc`), or the - // device's instructions where they are Metal's fast functions. - F::FastAsinh => lib1(fb, GlslOp::Asinh, a), - F::FastAcosh => lib1(fb, GlslOp::Acosh, a), - // Their quotients are calls of the fast division's routine, which the caller declares: - // [`fast_tanh`], [`fast_atanh`]. - F::FastTanh { .. } | F::FastAtanh { .. } => { - Err(BuildError::Type(TypeRule::FunctionSignature)) - } + 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::SinPi | F::CosPi | F::TanPi | F::FastSinPi | F::FastCosPi | F::FastTanPi => { let which = match op { F::SinPi | F::FastSinPi => PiScaled::Sin, F::CosPi | F::FastCosPi => PiScaled::Cos, _ => PiScaled::Tan, }; - // Metal's own form, the routine; where none answers (a `bfloat`, a fast call where the - // device's functions are Metal's, or a unit test that leaves them to the device), the - // device's `Sin` and `Cos` of `float(π) r`. - match libm::uses(op, f) { - [fun] if !lib.device(*fun) => lib.call(fb, *fun, f, &[a]), - _ => pi_scaled( - fb, - f, - which, - a, - &|fb, residue| { - let pi = wide_splat(fb, f, std::f64::consts::PI)?; - let angle = bin(fb, BinOp::FMul, pi, residue)?; - Ok(( - glsl(fb, GlslOp::Sin, &[angle])?, - glsl(fb, GlslOp::Cos, &[angle])?, - )) - }, - &|fb, num, den| bin(fb, BinOp::FDiv, num, den), - ), - } + // The device's `Sin` and `Cos` of `float(π) r`. + pi_scaled( + fb, + f, + which, + a, + &|fb, residue| { + let pi = wide_splat(fb, f, std::f64::consts::PI)?; + let angle = bin(fb, BinOp::FMul, pi, residue)?; + Ok(( + glsl(fb, GlslOp::Sin, &[angle])?, + glsl(fb, GlslOp::Cos, &[angle])?, + )) + }, + &|fb, num, den| bin(fb, BinOp::FDiv, num, den), + ) } F::Powr => { let y = arg(args, 1)?; - let r = routine_or(fb, lib, op, f, libm::Fun::Powr, GlslOp::Pow, &[a, y])?; + let r = glsl(fb, GlslOp::Pow, &[a, y])?; powr_nan(fb, f, a, y, r) } F::FastPowr => { let y = arg(args, 1)?; - let r = exp2_of_product(fb, lib, op, f, y, a)?; + let r = exp2_of_product(fb, y, a)?; fast_powr_special(fb, f, a, y, r) } // C99 Annex F's special cases around the magnitude of `|x|`, which `GLSL.std.450 Pow` @@ -1860,43 +1789,24 @@ fn float_fn_core( let y = arg(args, 1)?; let ax = glsl(fb, GlslOp::FAbs, &[a])?; let magnitude = if op == F::Pow { - routine_or(fb, lib, op, f, libm::Fun::Powr, GlslOp::Pow, &[ax, y])? + glsl(fb, GlslOp::Pow, &[ax, y])? } else { - let r = exp2_of_product(fb, lib, op, f, y, ax)?; + 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) } F::Atan2 => { let x = arg(args, 1)?; - let generic = match libm::uses(op, f) { - [r] if !lib.device(*r) => lib.call(fb, *r, f, &[a, x])?, - _ => glsl(fb, GlslOp::Atan2, &[a, x])?, - }; + let generic = glsl(fb, GlslOp::Atan2, &[a, x])?; atan2_special(fb, f, a, x, generic) } F::FastAtan2 { reciprocal_flushed } => { - // Metal's fast `atan` of its fast quotient `y · rcp(x)`: each the device's where it is - // Metal's in the module's mode, the routines otherwise. - let atan = |fb: &mut FunctionBuilder<'_>, q: Value| { - routine_or( - fb, - lib, - op, - f, - libm::Fun::Atan(libm::Mode::Fast), - GlslOp::Atan, - &[q], - ) - }; + // Metal's fast `atan` of its fast quotient `y · rcp(x)`: the device's `Atan` and + // division. + let atan = |fb: &mut FunctionBuilder<'_>, q: Value| glsl(fb, GlslOp::Atan, &[q]); let divide = |fb: &mut FunctionBuilder<'_>, n: Value, d: Value| -> BResult { - let recip = libm::Fun::Recip; - if libm::uses(op, f).contains(&recip) && !lib.device(recip) { - let r = lib.call(fb, recip, f, &[d])?; - fb.binary_with(BinOp::FMul, n, r, Contraction::Forbidden) - } else { - bin(fb, BinOp::FDiv, n, d) - } + bin(fb, BinOp::FDiv, n, d) }; fast_atan2(fb, f, a, arg(args, 1)?, reciprocal_flushed, &atan, ÷) } @@ -2494,40 +2404,33 @@ pub(super) fn fast_trig_flush( fb.select(past, zero, r) } -/// Metal's `fast::tanh(x)` (`op`, [`FloatFn::FastTanh`]) on `float` lanes `x` (form `f`): -/// [`tanh_of_exp`] of `t = exp2(x · 2 log2 e)`, Metal's `exp2` ([`routine_or`]), its quotient by -/// `divide` (a call of its [`FastDivision`] routine). -pub(super) fn fast_tanh( - fb: &mut FunctionBuilder<'_>, - op: FloatFn, - f: Form, - x: Value, - lib: &Lib<'_>, - divide: DivideOf<'_>, -) -> BResult { +/// 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 = routine_or(fb, lib, op, f, libm::Fun::Exp2, GlslOp::Exp2, &[x])?; - tanh_of_exp(fb, f, divide, t) + let t = glsl(fb, GlslOp::Exp2, &[x])?; + tanh_of_exp(fb, f, &device_quotient, t) } -/// Metal's `fast::atanh(x)` (`op`, [`FloatFn::FastAtanh`]) on `float` lanes `x` (form `f`): the +/// 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 by `divide` (a call of its -/// [`FastDivision`] routine, Metal's fast division) and the logarithm Metal's fast `log` -/// ([`fast_log_of`]), each step its own. The formula answers Metal's specials itself: a zero and a -/// denormal give `+0`, `±1` gives `±inf`, an infinity gives NaN (`inf · 0`), and `±FLT_MAX` gives -/// `-inf`, the reciprocal of `∓FLT_MAX` flushed (case f6524207, every special lane). On that case -/// the formula of correctly rounded `log2` and reciprocal matches Metal on 871 of 1,024 lanes; the -/// rest is Metal's `log2`. +/// 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<'_>, - op: FloatFn, f: Form, x: Value, - lib: &Lib<'_>, - divide: DivideOf<'_>, + lib: &Lib, ) -> BResult { if lib.metal_in(libm::Mode::Fast) { return glsl(fb, GlslOp::Atanh, &[x]); @@ -2536,8 +2439,8 @@ pub(super) fn fast_atanh( 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 = divide(fb, num, den)?; - let l = fast_log_of(fb, lib, op, f, q)?; + 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) } @@ -2545,31 +2448,24 @@ pub(super) fn fast_atanh( /// 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 or its routine with Metal's flush past the last evaluated quadrant -/// ([`fast_trig_flush`]), their quotient by `divide` (a call of its [`FastDivision`] routine). A -/// denormal `x` is its own `fast::tan`, as Metal keeps it, where the quotient's product reads a -/// denormal sine as a zero (`denormal::operand`). +/// 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<'_>, - divide: DivideOf<'_>, + lib: &Lib, ) -> BResult { if lib.metal_in(libm::Mode::Fast) { return glsl(fb, GlslOp::Tan, &[x]); } - let fast = |fb: &mut FunctionBuilder<'_>, r: libm::Fun, o: GlslOp| -> BResult { - let v = if lib.device(r) { - glsl(fb, o, &[x])? - } else { - lib.call(fb, r, f, &[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, libm::Fun::FastSin, GlslOp::Sin)?; - let cos = fast(fb, libm::Fun::FastCos, GlslOp::Cos)?; - let r = divide(fb, sin, cos)?; + 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), @@ -2577,9 +2473,10 @@ pub(super) fn fast_tan( } /// `(t - 1) / (t + 1)`: `tanh(x)` from `t = exp(2x)`, the MSL fast-math definition of -/// `fast::tanh`, divided as Metal's fast division does (`divide`, [`fast_divide`]): past `x ≈ -/// 43.7`, where `t + 1` passes `2^126`, the flushed reciprocal gives `0` (Metal's answer at `x = -/// 44`, A1 case a919193f), and `t = +inf` gives `inf · 0 = NaN`, as Metal does past `x ≈ 44.4`. +/// `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 @@ -2600,282 +2497,20 @@ pub(super) fn tanh_of_exp( divide(fb, num, den) } -/// Metal's fast reciprocal of `y` (floats of form `f`): `1 / y` by `reciprocal`, the device's -/// division or `RN(1 / y)` (Metal's own is neither on every lane, so both are -/// `PrecisionNote::DeviceArithmetic`), with the two ranges where Metal's answer is a flush, -/// measured on Apple M3 Max (probe case 08bc6611's `1 / y` lanes): past `2^126` the reciprocal is -/// an `f32` denormal, which Metal flushes to the zero of `y`'s sign (an infinity included), and an -/// `f32` denormal `y` is a zero to Metal, whose reciprocal is the infinity of `y`'s sign. Vulkan -/// bounds `OpFDiv` only for a divisor in `[2^-126, 2^126]`, so both ranges are selected rather than -/// left to the device. -pub(super) fn fast_reciprocal( - fb: &mut FunctionBuilder<'_>, - f: Form, - y: Value, - contract: Contraction, - reciprocal: Reciprocal, -) -> BResult { - let device = move |fb: &mut FunctionBuilder<'_>, a: Value, b: Value| { - fb.binary_with(BinOp::FDiv, a, b, contract) - }; - fast_reciprocal_with(fb, f, y, reciprocal, &device) -} - -/// [`fast_reciprocal`] with `rough` the device's division (a test moves it within Vulkan's -/// bound). -pub(super) fn fast_reciprocal_with( - fb: &mut FunctionBuilder<'_>, - f: Form, - y: Value, - reciprocal: Reciprocal, - rough: Rough<'_>, -) -> BResult { - let one = wide_splat(fb, f, 1.0)?; - let r = match reciprocal { - Reciprocal::Device | Reciprocal::Native => rough(fb, one, y)?, - Reciprocal::Rounded => rounded_reciprocal(fb, f, one, y, rough)?, - }; - let ay = glsl(fb, GlslOp::FAbs, &[y])?; - let limit = wide_splat(fb, f, 2f64.powi(126))?; - let past = bin(fb, BinOp::FOrdGreaterThan, ay, limit)?; - let zero = wide_splat(fb, f, 0.0)?; - let signed_zero = copysign(fb, f, zero, y)?; - let r = fb.select(past, signed_zero, r)?; - match flushed(fb, f, y)? { - Some(z) => { - let inf = wide_splat(fb, f, f64::INFINITY)?; - let signed_inf = copysign(fb, f, inf, y)?; - fb.select(z, signed_inf, r) - } - None => Ok(r), - } -} - -/// `RN(1 / y)` of `f32` lanes `y` (form `f`) whose magnitude is in `[2^-126, 2^126]`, from -/// `rough`'s estimate ([`divide::rounded_reciprocal_bits`]); the other lanes are -/// [`fast_reciprocal`]'s flushes, or a NaN's. A `y` past `2^125`, whose estimate may fall below -/// `2^-126`, is halved first and its reciprocal halved after, each by its exponent field: both -/// moves are exact there, and the result is at least `2^-126`. `one` is `1.0`. -fn rounded_reciprocal( - fb: &mut FunctionBuilder<'_>, - f: Form, - one: Value, - y: Value, - rough: Rough<'_>, -) -> BResult { - let u = u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let yb = fb.convert(ConvOp::Bitcast, y, ut)?; - let magnitude = splat(fb, u, 0x7FFF_FFFF)?; - let ay = bin(fb, BinOp::BitwiseAnd, yb, magnitude)?; - // `|y|` in `(2^125, 2^126]`: one less in the exponent field. - let low = splat(fb, u, 0x7E00_0001)?; - let span = splat(fb, u, 0x80_0000)?; - let off = bin(fb, BinOp::ISub, ay, low)?; - let high = bin(fb, BinOp::ULessThan, off, span)?; - let zero = splat(fb, u, 0)?; - let shift = fb.select(high, span, zero)?; - let sb = bin(fb, BinOp::ISub, yb, shift)?; - let ys = fb.convert(ConvOp::Bitcast, sb, ft)?; - let ny = fb.unary(UnOp::FNegate, ys)?; - let r = rough(fb, one, ys)?; - let rb = divide::rounded_reciprocal_bits(fb, f, one, ny, yb, r)?; - let rb = bin(fb, BinOp::ISub, rb, shift)?; - fb.convert(ConvOp::Bitcast, rb, ft) -} - -/// An upper estimate of the SPIR-V words of `fast_divide` on form `f` by `reciprocal`: the -/// reciprocal, its two flushes' tests and selects, the product, and Metal's answers at denormals -/// and NaNs (`metal_fast_product`), with their constants, types, and the `GLSL.std.450` import. -pub fn fast_divide_words(f: Form, reciprocal: Reciprocal) -> u32 { - match reciprocal { - // The device's `OpFDiv` alone. - Reciprocal::Native => 16, - _ => 320 + 48 * u32::from(f.lanes) + reciprocal.words(f), - } -} - -/// Metal's fast division of two values of one form: a call of its [`FastDivision`] routine, or -/// (a unit test) [`fast_divide`] itself. +/// 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; -/// The module-scope routine of Metal's fast division (`fast_divide`) on `float` lanes of -/// `lanes` lanes, by `reciprocal`, its device division `NoContraction` where `exact`. Every `arcp` -/// division, `fast::tanh`, `fast::fmod`, and `fast::tan` on those lanes calls it, so a module holds -/// it once, as it holds the precise division's routines; expanded at every use, Metal's answers at -/// denormals and NaNs made each use about 330 to 570 words. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct FastDivision { - pub lanes: u8, - pub reciprocal: Reciprocal, - pub exact: bool, -} - -impl FastDivision { - /// The routine of a fast division of form `f` (`float` lanes) by `reciprocal`, whose device - /// division contracts as `contract` allows. - pub fn new(f: Form, reciprocal: Reciprocal, contract: Contraction) -> FastDivision { - FastDivision { - lanes: f.lanes, - reciprocal, - exact: contract == Contraction::Forbidden, - } - } - - /// The routine's operand form. - fn form(self) -> Form { - Form { - held: Held::Float(FloatFmt::F32), - lanes: self.lanes, - } - } - - /// The contraction of the routine's device division. - fn contract(self) -> Contraction { - if self.exact { - Contraction::Forbidden - } else { - Contraction::Allowed - } - } - - /// An upper estimate of the routine's SPIR-V words: `fast_divide`'s, and the function's - /// type, parameters, and frame. - pub fn words(self) -> u32 { - fast_divide_words(self.form(), self.reciprocal) + 32 - } -} - -/// An upper estimate of the SPIR-V words of one call of a [`FastDivision`] routine. -pub const FAST_DIVISION_CALL_WORDS: u32 = 24; - -/// Define routine `r`: a function of two `float` values of `r.lanes` lanes returning Metal's -/// fast quotient (`fast_divide`). -pub fn define_fast_division(mb: &mut ModuleBuilder, r: FastDivision) -> BResult { - let e = mb.ty(Type::Float { width: 32 })?; - let t = if r.lanes == 1 { - e - } else { - mb.ty(Type::Vector { - elem: e, - len: r.lanes, - })? - }; - let mut fb = mb.routine(t)?; - let (x, y) = (fb.param(t)?, fb.param(t)?); - let q = fast_divide(&mut fb, r.form(), x, y, r.contract(), r.reciprocal)?; - fb.ret(Some(q))?; - fb.finish() -} - -/// Metal's fast quotient of `x` and `y` through `routine`, a [`define_fast_division`]. -pub fn call_fast_division( - fb: &mut FunctionBuilder<'_>, - routine: FuncId, - x: Value, - y: Value, -) -> BResult { - fb.call(routine, &[x, y])? - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) -} - -/// Metal's fast quotient `x / y` as the device's own `OpFDiv(x, y)`, contracting as routine `r`'s -/// device division does: the form of an `arcp` division whose quotient is the device's -/// (`ArithPlan::device_quotient`), where no routine is called. -pub fn device_fast_division( - fb: &mut FunctionBuilder<'_>, - r: FastDivision, - x: Value, - y: Value, -) -> BResult { - fb.binary_with(BinOp::FDiv, x, y, r.contract()) -} - -/// Metal's fast division `x / y`: `x` times its fast reciprocal of `y` ([`fast_reciprocal`] by -/// `reciprocal`), two roundings, as Metal computes it (every lane of probe case 08bc6611's fast `x -/// / y` equals `x` times its fast `1 / y`), with Metal's answers at `f32` denormals and NaNs -/// ([`metal_fast_product`]). -pub(super) fn fast_divide( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - y: Value, - contract: Contraction, - reciprocal: Reciprocal, -) -> BResult { - // Native device maths: the device's quotient itself. - if reciprocal == Reciprocal::Native { - return fb.binary_with(BinOp::FDiv, x, y, contract); - } - let r = fast_reciprocal(fb, f, y, contract, reciprocal)?; - if f.float_fmt() != Some(FloatFmt::F32) { - return fb.binary_with(BinOp::FMul, x, r, contract); - } - metal_fast_product(fb, f, x, r) -} - -/// `x · r`, the product that ends Metal's fast division, as Metal answers it on `f32` lanes -/// (form `f`) whatever the device's denormal mode and NaN encoding: a denormal `x` is a zero of its -/// sign ([`flushed`]); a product whose 24-bit rounding, with an unbounded exponent, is below -/// `2^-126` is a zero of its sign (Metal's precise quotient flushes by that rounding, a probe case -/// c10cba13; the product scaled by `2^24` is a normal there, so its rounding decides, and the -/// device's own rounding of a denormal result, or its flush, does not); and a NaN is `0x7FC00000`. -/// Metal answered `0x7fc00000` for every NaN fast quotient measured (a probe cases 914cc4d2 and -/// 711cc190, 155 and 62 lanes, probe case 08bc6611, A1 case a919193f), where RADV answered -/// `0xffc00000` for `0 / 0` and a NaN divisor, and a denormal numerator over a denormal divisor -/// `NaN` (`0 · inf`, A1 case f9a12252), where lavapipe kept the numerator and answered `+inf`. No -/// step is fused or regrouped (`NoContraction`), and the selects keep the device from fusing the -/// product into its user. The NaN is told by the bits, which no float mode folds. -fn metal_fast_product(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, r: Value) -> BResult { - let exact = Contraction::Forbidden; - let zero = wide_splat(fb, f, 0.0)?; - let x = match flushed(fb, f, x)? { - Some(z) => { - let signed_zero = copysign(fb, f, zero, x)?; - fb.select(z, signed_zero, x)? - } - None => x, - }; - let q = fb.binary_with(BinOp::FMul, x, r, exact)?; - // The same product `2^24` larger: exact up to its rounding, which is the 24-bit one. - let up = wide_splat(fb, f, 2f64.powi(24))?; - let xs = fb.binary_with(BinOp::FMul, x, up, exact)?; - let s = fb.binary_with(BinOp::FMul, xs, r, exact)?; - let abs_s = glsl(fb, GlslOp::FAbs, &[s])?; - let tiny_limit = wide_splat(fb, f, 2f64.powi(-102))?; - let tiny = bin(fb, BinOp::FOrdLessThan, abs_s, tiny_limit)?; - // A 24-bit rounding of at least `2^-126` (`s` is a number: not `inf · 0`), which the device - // answered below it (a flush before rounding): `2^-126`. - let rounds_normal = bin(fb, BinOp::FOrdGreaterThanEqual, abs_s, tiny_limit)?; - let abs_q = glsl(fb, GlslOp::FAbs, &[q])?; - let least = wide_splat(fb, f, 2f64.powi(-126))?; - let below = bin(fb, BinOp::FOrdLessThan, abs_q, least)?; - let raised = bin(fb, BinOp::LogicalAnd, rounds_normal, below)?; - let signed_least = copysign(fb, f, least, s)?; - let q = fb.select(raised, signed_least, q)?; - let signed_zero = copysign(fb, f, zero, s)?; - let q = fb.select(tiny, signed_zero, q)?; - // Told by the bits: the routine runs in entries of every float mode, and one without - // `SignedZeroInfNanPreserve` lets a device fold `OpIsNan`. - let nan = nan::is_nan(fb, f, NanTest::Bits, q)?; - let canonical = fsplat(fb, f, f64::NAN)?; - fb.select(nan, canonical, q) -} - -/// A fused multiply-add of three floats (`super::fma::emit` with its routine; a unit test -/// substitutes a reference). +/// A fused multiply-add of three floats (`super::fma::emit`; a unit test substitutes a +/// reference). pub(super) type FmaOf<'a> = &'a dyn Fn(&mut FunctionBuilder<'_>, &[Value]) -> BResult; -/// Metal's `fast::fmod(x, y)` on `float`: `fma(-trunc(q), y, x)` of its fast quotient -/// `q = x / y` (`divide`, a call of its [`FastDivision`] routine), the fused multiply-add -/// rounding once (`fma`; Metal's answers for `f32` denormals and NaNs are its). Every lane of -/// probe case 08bc6611 (1,024, specials among them) is this expression on Metal's own quotient; the -/// quotient's reciprocal is a near-equivalent of Metal's (`PrecisionNote::DeviceArithmetic`), so -/// `fmod(1e10, 3)` is Metal's `-512` exactly where that reciprocal of `3` is Metal's. Metal reads a -/// denormal `x` or `y` as the zero of its sign and answers no denormal, with and without fast math -/// (every pair of 28 patterns): the caller flushes the operands and the result where -/// the fused multiply-add is the device's and the profile asks Metal's functions; under native -/// device maths they are the device's (`PrecisionNote::DeviceDenormals`). +/// Metal's `fast::fmod(x, y)` on `float`: `fma(-trunc(q), y, x)` of the quotient `q = x / y` +/// (`divide`, the device's division), the fused multiply-add `fma`. Every lane of probe case +/// 08bc6611 (1,024, specials among them) is this expression on Metal's own quotient; the device's +/// quotient is a near-equivalent of it (`PrecisionNote::DeviceArithmetic`), so `fmod(1e10, 3)` is +/// Metal's `-512` exactly where the device's quotient is Metal's. Metal reads a denormal `x` or `y` +/// as the zero of its sign and answers no denormal, with and without fast math (every pair of 28 +/// patterns); the device's are its own (`PrecisionNote::DeviceDenormals`). pub(super) fn fast_fmod( fb: &mut FunctionBuilder<'_>, x: Value, @@ -2889,27 +2524,6 @@ pub(super) fn fast_fmod( fma(fb, &[n, y, x]) } -/// Metal's LLVM `frem` on `float` without every fast-math flag: `x - y * trunc(q)` of its precise -/// quotient `q = x / y` (`divide`, a call of the shared routine, which reads a denormal operand as -/// a zero and flushes a denormal quotient), the product and the difference each rounded on its own -/// (`NoContraction`), the product read as Metal reads an `f32` denormal where `flush` (the caller -/// flushes the operands and the result). Not the exact remainder: on the M3 Max -/// `frem(1, 0.1)` is `+0` where `fmod` gives `0x3dcccccb`, and this expression is Metal's answer on -/// all 49,753 measured pairs, every class of operand. -pub(super) fn metal_frem( - fb: &mut FunctionBuilder<'_>, - f: Form, - (x, y): (Value, Value), - divide: DivideOf<'_>, - flush: bool, -) -> BResult { - let q = divide(fb, x, y)?; - let t = glsl(fb, GlslOp::Trunc, &[q])?; - let p = fb.binary_no_contraction(BinOp::FMul, y, t)?; - let p = if flush { denormal::flush(fb, f, p)? } else { p }; - fb.binary_no_contraction(BinOp::FSub, x, p) -} - /// Metal's precise `mix(x, y, t)` on `float` and `half`: `fma(t, y, fma(-t, x, x))`, each fused /// multiply-add rounding once (`fma`, the profile's route), with and without fast-math flags. Every /// lane of `nan_functions`, `nan_functions_fast`, `nan_half`, and `nan_half_fast` whose answer is a @@ -2917,24 +2531,16 @@ pub(super) fn metal_frem( /// is NaN: `fma(-0, inf, inf)`; `mix(-0, -0, 0)` is `+0`; `half` `mix(-0.3, 0.7, 0.2)` is /// `0xAE68`). `t` is negated on its bits, which no float mode changes. Each fused multiply-add /// reads an `f32` denormal operand as the zero of its sign and flushes a denormal result (an Apple -/// M3 Max under macOS 27.0.1: every finite triple of 28 patterns, denormals -/// among them, in both modes); where `flush`, the inner one's result is read so -/// ([`denormal::flush`]), for a device whose `OpFmaKHR` may keep one; the operands and the result -/// are the caller's to flush. +/// M3 Max under macOS 27.0.1: every finite triple of 28 patterns, denormals among them, in both +/// modes). pub(super) fn metal_mix( fb: &mut FunctionBuilder<'_>, f: Form, [x, y, t]: [Value; 3], fma: FmaOf<'_>, - flush: bool, ) -> BResult { let minus_t = sign_bits(fb, f, t, SignBit::Flip)?; let rest = fma(fb, &[minus_t, x, x])?; - let rest = if flush { - denormal::flush(fb, f, rest)? - } else { - rest - }; fma(fb, &[t, y, rest]) } @@ -2943,17 +2549,12 @@ pub(super) fn metal_mix( /// rounded to `f`'s format on its own and each later lane added by one fused multiply-add (`fma`, /// the profile's route), with and without fast-math flags. On 4,096 lanes of two, three and four /// lanes each, in both modes, every `float` and `half` answer of the M3 Max and the M4 is this -/// chain's (a `half` keeps its denormals). Where `flush`, each of the chain's `float` values before -/// the last is read as Metal reads a denormal ([`denormal::flush`]), for a device whose multiply -/// and `OpFmaKHR` may keep one; the operands and the result are the caller's to flush. Where -/// `tiny` (`float` lanes), the first product is Metal's where the device's rounding of a product -/// below `2^-126` reaches `±2^-126`, by that check ([`denormal::tiny_product`]). +/// chain's (a `half` keeps its denormals). pub(super) fn metal_dot( fb: &mut FunctionBuilder<'_>, f: Form, [x, y]: [Value; 2], fma: FmaOf<'_>, - (flush, tiny): (bool, Option), ) -> BResult { let lane = |fb: &mut FunctionBuilder<'_>, i: u32| -> BResult<(Value, Value)> { if f.lanes == 1 { @@ -2965,46 +2566,26 @@ pub(super) fn metal_dot( )) } }; - metal_chain( - fb, - f.scalar_form(), - u32::from(f.lanes), - &lane, - fma, - (flush, tiny), - ) + metal_chain(fb, f.scalar_form(), u32::from(f.lanes), &lane, fma) } /// Lane `i`'s two operands of a dot product. pub(super) type LaneOf<'a> = &'a dyn Fn(&mut FunctionBuilder<'_>, u32) -> BResult<(Value, Value)>; /// [`metal_dot`]'s fused chain over `lanes` lanes of scalar form `s`, lane `i`'s operands by -/// `lane`, each taken as the chain reaches it; its first product Metal's at `2^-126` where `tiny`. +/// `lane`, each taken as the chain reaches it. pub(super) fn metal_chain( fb: &mut FunctionBuilder<'_>, s: Form, lanes: u32, lane: LaneOf<'_>, fma: FmaOf<'_>, - (flush, tiny): (bool, Option), ) -> BResult { - let step = |fb: &mut FunctionBuilder<'_>, v: Value| -> BResult { - if flush { - denormal::flush(fb, s, v) - } else { - Ok(v) - } - }; let (x0, y0) = lane(fb, 0)?; // A `half` product is exact in its `float` container, and rounded once. let p = fb.binary_no_contraction(BinOp::FMul, x0, y0)?; - let p = match tiny { - Some(check) => denormal::tiny_product(fb, s, [x0, y0], p, check)?, - None => p, - }; let mut sum = narrow::round(fb, s, p)?; for i in 1..lanes { - sum = step(fb, sum)?; let (xi, yi) = lane(fb, i)?; sum = fma(fb, &[xi, yi, sum])?; } @@ -3012,18 +2593,12 @@ pub(super) fn metal_chain( } /// An upper estimate of the SPIR-V words of [`metal_dot`] on form `f` whose fused multiply-adds -/// take `fma_words` each: two extractions per lane, the product, its check where `tiny` and its -/// rounding, and per later lane the fused multiply-add and, where `flush`, the flush before it. -pub(super) fn metal_dot_words( - f: Form, - fma_words: u32, - (flush, tiny): (bool, Option), -) -> u32 { +/// take `fma_words` each: two extractions per lane, the product and its rounding, and per later +/// lane the fused multiply-add. +pub(super) fn metal_dot_words(f: Form, fma_words: u32) -> u32 { let s = f.scalar_form(); let lanes = u32::from(f.lanes); - let step = fma_words + if flush { denormal::flush_words(s) } else { 0 }; - let check = tiny.map_or(0, |check| denormal::tiny_product_words(s, check)); - (10 * lanes + 5 + narrow::round_words(s) + check).saturating_add(lanes.saturating_sub(1) * step) + (10 * lanes + 5 + narrow::round_words(s)).saturating_add(lanes.saturating_sub(1) * fma_words) } /// Which of Metal's pi-scaled functions [`pi_scaled`] computes. @@ -3166,24 +2741,17 @@ pub(super) fn pi_scaled( /// The words of `infinite_product` on a scalar: about 23 instructions and their constants. const INFINITE_PRODUCT_WORDS: u32 = 128; -/// `exp2(y · log2(x))` with the product rounded, of Metal's `exp2` and `log2` ([`routine_or`]): -/// Metal's `fast::powr(x, y)`, and its `fast::pow`'s magnitude of `|x|` (`op`, on form `f`). +/// `exp2(y · log2(x))` with the product rounded, of the device's `Exp2` and `Log2`: Metal's +/// `fast::powr(x, y)`, and its `fast::pow`'s magnitude of `|x|`. /// Every lane of probe case 08bc6611 (1,024, specials among them) gives Metal's `fast::powr` as /// this expression of Metal's own `exp2` and `log2`, and its `fast::pow` at a base that is not /// negative. Where the product is infinite the callers select IEEE's answer by the operands' bits /// ([`infinite_product`], [`fast_powr_special`]), so a device's arithmetic on the infinite /// intermediates cannot move it. -fn exp2_of_product( - fb: &mut FunctionBuilder<'_>, - lib: &Lib<'_>, - op: FloatFn, - f: Form, - y: Value, - x: Value, -) -> BResult { - let l = routine_or(fb, lib, op, f, libm::Fun::Log2, GlslOp::Log2, &[x])?; +fn exp2_of_product(fb: &mut FunctionBuilder<'_>, y: Value, x: Value) -> BResult { + let l = glsl(fb, GlslOp::Log2, &[x])?; let p = bin(fb, BinOp::FMul, y, l)?; - routine_or(fb, lib, op, f, libm::Fun::Exp2, GlslOp::Exp2, &[p]) + glsl(fb, GlslOp::Exp2, &[p]) } /// `r`, the value of `exp2(y · log2(x))` (floats of form `f`, `x` not negative where it @@ -3223,25 +2791,6 @@ pub(super) fn infinite_product( fb.select(infinite, answer, r) } -/// `fun` of `args` (floats of form `f`) where float function `op` calls it: `fun`'s routine -/// where `op` takes it ([`libm::uses`]) and the device's instruction does not answer it, the -/// device's instruction `o` otherwise. -fn routine_or( - fb: &mut FunctionBuilder<'_>, - lib: &Lib<'_>, - op: FloatFn, - f: Form, - fun: libm::Fun, - o: GlslOp, - args: &[Value], -) -> BResult { - if libm::uses(op, f).contains(&fun) && !lib.device(fun) { - lib.call(fb, fun, f, args) - } else { - glsl(fb, o, args) - } -} - /// Metal's precise `exp10(x)` (`c` is `log2(10)`) or `exp(x)` (`log2(e)`) from the device's /// `exp2` (floats of form `f` in a 32-bit container, the constants the container's), as Metal /// composes it: `E = exp2(p)` of the rounded product `p = x c_hi`, `c_hi + c_lo = c`, corrected by @@ -3277,7 +2826,7 @@ fn metal_log( fb: &mut FunctionBuilder<'_>, f: Form, x: Value, - near: &libm::log::Near, + near: &libm::Near, c: u32, ) -> BResult { let exact = Contraction::Forbidden; @@ -3310,24 +2859,18 @@ fn metal_log( /// 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)` ([`routine_or`]; `-x · log2 e` is the product negated). One +/// `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, - lib: &Lib<'_>, -) -> BResult { +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 = routine_or(fb, lib, op, f, libm::Fun::Exp2, GlslOp::Exp2, &[p])?; + let up = glsl(fb, GlslOp::Exp2, &[p])?; let n = fb.unary(UnOp::FNegate, p)?; - let down = routine_or(fb, lib, op, f, libm::Fun::Exp2, GlslOp::Exp2, &[n])?; + let down = glsl(fb, GlslOp::Exp2, &[n])?; let combine = if op == FloatFn::FastSinh { BinOp::FSub } else { @@ -3338,16 +2881,10 @@ fn fast_sinh_cosh( fb.binary_with(BinOp::FMul, s, half, exact) } -/// Metal's fast `log(v)` of `float` lanes `v` (form `f`) where float function `op` calls it: -/// `log2(v) · ln 2` ([`routine_or`]), each step its own. -fn fast_log_of( - fb: &mut FunctionBuilder<'_>, - lib: &Lib<'_>, - op: FloatFn, - f: Form, - v: Value, -) -> BResult { - let l = routine_or(fb, lib, op, f, libm::Fun::Log2, GlslOp::Log2, &[v])?; +/// 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) } diff --git a/crates/metal2vulkan/src/lower/arith/mod.rs b/crates/metal2vulkan/src/lower/arith/mod.rs index 696f89f1b..9590f2c58 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -29,8 +29,10 @@ //! by the Vulkan spec ([`narrow::controlled_modes`]). //! //! Precision: a `half` rounding keeps half denormals, as Metal does; a `float` or `half` fused -//! multiply-add (`air.fma`, `llvm.fma`, and `llvm.fmuladd`, which Metal fuses) rounds once on every -//! profile ([`fma`]); operations whose Vulkan precision is looser than correct rounding add +//! multiply-add (`air.fma`, `llvm.fma`, and `llvm.fmuladd`, which Metal fuses) rounds once where +//! the profile has `OpFmaKHR` or the device's 16-bit `Fma` is Metal's, and is the device's `Fma` +//! elsewhere (`PrecisionNote::NativeFma`, [`fma`]); operations whose Vulkan precision is looser +//! than correct rounding add //! `PrecisionNote::DeviceArithmetic` (`fdiv`, `frem`, `sqrt`, a `double` or `bfloat` `fma`, `fmod`, //! `dot`) or `PrecisionNote::DeviceTranscendentals` (the transcendental functions) to the plan. //! Float arithmetic without both of LLVM's `contract` and `reassoc` fast-math flags (and `mix`'s @@ -44,10 +46,10 @@ //! compiler may take another than the device's. Every other lowering is exact for every non-poison //! input within the device's floating-point environment: signed zeros, infinities, and NaNs are //! preserved by `SignedZeroInfNanPreserve` where an operation without `nnan`/`ninf`/`nsz` requires -//! it, or a check or a fused multiply-add routine answers Metal's zero of its sign -//! ([`ArithPlan::keep_zero_signs`]), and the profile supports it (else -//! `PrecisionNote::DeviceSignedZeroInfNan`), while denormal flushing and the rounding mode are the -//! device default (the rounding mode decides the inexact `FConvert` narrowings and integer-to-float +//! it and the profile supports it (else `PrecisionNote::DeviceSignedZeroInfNan`), while denormal +//! flushing and the rounding mode are the device default (`f32` denormals noted +//! `PrecisionNote::DeviceDenormals` where the device is not measured to read them as Metal does, +//! [`denormal`]; the rounding mode decides the inexact `FConvert` narrowings and integer-to-float //! conversions, which Vulkan leaves to the device without `RoundingModeRTE`), but in an entry that //! rounds to `half` under the float controls ([`narrow::controlled_modes`]), which declares //! `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` for 16 bits and the modes the @@ -102,9 +104,7 @@ use crate::air::ir::{ }; use crate::air::Entry; use crate::budget::Meter; -use crate::device::profile::{ - DriverWorkaround, FloatFunctions, MinMaxRoute, NanEncoding, RoundingOrderRoute, -}; +use crate::device::profile::{DriverWorkaround, FloatFunctions, MinMaxRoute, NanEncoding}; use crate::device::{DeviceProfile, FloatWidth}; use crate::error::Error; use crate::lower::access; @@ -113,7 +113,7 @@ use crate::lower::select::{FamilyPlans, Plan, SelectCx}; use crate::lower::strategy::FamilyStrategy; use crate::pipeline::artifact::{EntryMath, PrecisionNote}; use crate::spirv::builder::{FunctionBuilder, MaskForm, ModuleBuilder, ProductForm, QuantizeForm}; -use crate::spirv::error::{BResult, BuildError, TypeRule}; +use crate::spirv::error::BResult; use crate::spirv::ids::{DemoteTy, FuncId, GlobalId, TypeId, Value as SValue}; use crate::spirv::ir::{Contraction, ExecMode, UnOp}; use std::borrow::Cow; @@ -282,64 +282,40 @@ pub enum ArithStrategy { form: Form, contract: Contraction, }, - /// A correctly rounded fused multiply-add on `float` or `half` lanes ([`fma`]): `OpFmaKHR`, a - /// shared `double` or integer routine, or `half`'s exact `float` sum. + /// A fused multiply-add on `float` or `half` lanes ([`fma`]): `OpFmaKHR`, the device's 16-bit + /// `Fma` or `OpFmaKHR`, or the device's `Fma`. Fma(fma::Fma), - /// `air.fast_fmod` on `float`: Metal's `fma(-trunc(x / y), y, x)` of its fast quotient - /// (`math::fast_fmod`), the fused multiply-add `fma` and the quotient's reciprocal `reciprocal` - /// ([`divide::Reciprocal::on`]). + /// `air.fast_fmod` on `float`: Metal's `fma(-trunc(x / y), y, x)` of the device's quotient + /// (`math::fast_fmod`), the fused multiply-add `fma`. FastFmod { fma: fma::Fma, - reciprocal: divide::Reciprocal, }, - /// `air.mix` on `float` or `half`, with or without fast-math flags: Metal's - /// `fma(t, y, fma(-t, x, x))` (`math::metal_mix`), both fused multiply-adds `fma`; where - /// `flush`, the inner one's `float` result read as Metal reads a denormal. + /// `air.mix` on `float` or `half` where the device's functions are Metal's + /// (`FloatFunctions::Metal`), or on `half` where its fused multiply-add is the measured 16-bit + /// one ([`fma::Route::F16`], Metal's own `half` `fma`): Metal's `fma(t, y, fma(-t, x, x))` + /// (`math::metal_mix`) of those fused multiply-adds, both `fma`. Mix { fma: fma::Fma, - flush: bool, }, - /// `air.dot` on `float` or `half` vectors of form `form`: Metal's fused chain of the - /// products (`math::metal_dot`), each fused multiply-add `fma`, on one lane; where `flush`, the - /// chain's `float` values before the last read as Metal reads a denormal; where `tiny`, the - /// first product Metal's where the device's rounding reaches `±2^-126`, by that check - /// ([`denormal::tiny_product`]). + /// `air.dot` on `half` vectors of form `form` where the device's functions are Metal's or its + /// fused multiply-add is the measured 16-bit one ([`fma::Route::F16`]): Metal's fused chain of + /// the products (`math::metal_dot`), each fused multiply-add `fma`, on one lane. Dot { fma: fma::Fma, form: Form, - flush: bool, - tiny: Option, }, - /// An `fdiv` carrying `arcp` on `float` lanes: Metal's fast division, `x` times its fast - /// reciprocal of `y` with that reciprocal's two flushes, answered as Metal answers at - /// denormals and NaNs (`math::fast_divide`), by a call of the shared `routine`; or, where the - /// quotient is the device's ([`ArithPlan::device_quotient`]), its `OpFDiv(x, y)`. + /// An `fdiv` carrying `arcp` on `float` lanes, Metal's fast division: the device's + /// `OpFDiv(x, y)`, contracting as `contract` allows (`PrecisionNote::NativeDivision`). FastDivide { form: Form, - routine: math::FastDivision, + contract: Contraction, }, - /// An `fdiv` without `arcp` on `float` lanes, or any `fdiv` on `half` lanes: Metal's - /// precise division, the correctly rounded quotient, by a call of the shared `routine` - /// ([`divide`]). - PreciseDivide { - form: Form, - routine: divide::Routine, - }, - /// Metal's precise division on `float` or `half` lanes by native device maths - /// (`FloatFunctions::Native`): the device's `OpFDiv`, its divisor kept in Vulkan's range - /// ([`divide::native`]). + /// Metal's precise division on `float` or `half` lanes (an `fdiv` without `arcp` on `float`, + /// any `fdiv` on `half`): the device's `OpFDiv`, its divisor kept in Vulkan's range + /// ([`divide::native`], `PrecisionNote::NativeDivision`). NativeDivide { form: Form, }, - /// An `frem` on `float` lanes without every fast-math flag: Metal's `x - y * trunc(x / y)` - /// of its precise quotient (the shared `routine`'s), the product and the difference each - /// rounded on its own (`math::metal_frem`); the product read as Metal reads an `f32` denormal - /// where `flush` (the operands and the result are [`ArithStrategy::Denormals`]'). - Remainder { - form: Form, - routine: divide::Routine, - flush: bool, - }, /// A `contract` multiply (or its `fpext` to `float`) fused into every addition that uses it /// ([`contract`]), or an addition of a tree Metal regroups folded into a chain: no value of its /// own. @@ -354,9 +330,6 @@ pub enum ArithStrategy { b: ValueId, c: ValueId, negate: contract::Negate, - /// The `f32` denormals of `a`, `b` and `c` (bits 0 to 2) and of the result the module - /// flushes itself where `OpFmaKHR` may keep them ([`denormal::Flush`]). - flush: denormal::Flush, /// A chain's fused multiply-adds inside the outer one, outermost first. inner: Box<[contract::FusedLink]>, }, @@ -435,19 +408,14 @@ pub enum ArithStrategy { elem: Form, contract: Contraction, }, - /// `air.dot` of chunked vectors of `lanes` lanes of `elem` (`float` or `half`) as Metal's fused - /// chain over every lane ([`chunk::dot_chain`]), each fused multiply-add `fma`; where `flush`, - /// the chain's `float` values before the last read as Metal reads a denormal, and the lanes of - /// the operands `reads` names and the result, where it says so; where `tiny`, the first product - /// Metal's where the device's rounding reaches `±2^-126`, by that check - /// ([`denormal::tiny_product`]). + /// `air.dot` of chunked vectors of `lanes` lanes of `elem` (`float` or `half`) where the + /// device's functions are Metal's, or of `half` where its fused multiply-add is the measured + /// 16-bit one ([`fma::Route::F16`]), as Metal's fused chain over every lane + /// ([`chunk::dot_chain`]), each fused multiply-add `fma`. ChunkedChain { lanes: u16, elem: Form, fma: fma::Fma, - flush: bool, - reads: denormal::Flush, - tiny: Option, }, /// A float result with Metal's NaN selected where it is a NaN ([`nan`]): the value of `of`, a /// result of `form`, then [`nan::select`] of `answer`. Named as `of`. @@ -456,26 +424,6 @@ pub enum ArithStrategy { answer: nan::NanAnswer, form: Form, }, - /// A `float` operation whose `f32` denormals the device may read otherwise than Metal, which - /// reads a denormal operand as the zero of its sign and flushes a denormal result - /// ([`denormal`]): the operands `flush` names, of form `form`, read by - /// [`denormal::flush`], then `of`, then its result, of form `out`, flushed where `flush` - /// says. Named as `of`. - Denormals { - of: Box, - form: Form, - out: Form, - flush: denormal::Flush, - }, - /// A `float` multiply `of` (lanes of form `form`) whose device product may round up to - /// `±2^-126` where Metal flushes the exact product, below it, to the zero of its sign - /// ([`denormal::tiny_product`]): `of`'s product, then that zero where `check` finds the exact - /// product below `2^-126`. - TinyProduct { - of: Box, - form: Form, - check: denormal::TinyCheck, - }, /// An operation with a wide integer operand or result on a profile without `shaderInt64`, /// on the two words of each value ([`wide`]). Wide(wide::WideOp), @@ -508,7 +456,7 @@ impl FamilyStrategy for ArithStrategy { use ArithStrategy as S; // The NaN select is its operation's: the census names the operation. let mut s = self; - while let S::Nan { of, .. } | S::Denormals { of, .. } = s { + while let S::Nan { of, .. } = s { s = of; } Cow::Borrowed(match s { @@ -524,9 +472,7 @@ impl FamilyStrategy for ArithStrategy { S::F16 { .. } => ops::F16, S::Float { .. } | S::FNeg { .. } | S::FloatCompare { .. } => "arith.float", S::FastDivide { .. } => FAST_DIVIDE, - S::PreciseDivide { .. } => divide::PRECISE, S::NativeDivide { .. } => divide::NATIVE, - S::Remainder { .. } => REMAINDER, S::Cast { .. } => "arith.cast", S::Bitcast { plan: BitcastPlan::Packed { .. }, @@ -605,8 +551,6 @@ impl FamilyStrategy for ArithStrategy { S::Member { .. } => "arith.aggregate.member", // Named as its operation: unwrapped above. S::Nan { .. } => "arith.nan", - S::Denormals { .. } => "arith.denormals", - S::TinyProduct { .. } => "arith.float.tiny", }) } @@ -631,21 +575,9 @@ impl FamilyStrategy for ArithStrategy { S::Bool { .. } | S::BoolCompare { .. } | S::FloatCompare { .. } => 32, S::Float { form, .. } => 8 + narrow::round_words(*form), S::F16 { form, .. } => ops::f16_binary_words(*form), - // The call; the routine's own words are the module's ([`routine_words`]). - S::FastDivide { .. } => math::FAST_DIVISION_CALL_WORDS, - S::PreciseDivide { form, .. } => divide::use_words(*form), + // The device's division. + S::FastDivide { .. } => 16, S::NativeDivide { form } => divide::native_words(*form), - // The quotient's call, its truncation, the product, the difference, and the product's - // flush. - S::Remainder { form, flush, .. } => { - divide::use_words(*form) - + 16 - + if *flush { - denormal::flush_words(*form) - } else { - 0 - } - } // The bits' two conversions, the operation, and the mask's and its types' share. S::FNeg { form, bits: true } => 24 + 4 * u32::from(form.lanes), S::FNeg { .. } | S::Select => 8, @@ -672,32 +604,15 @@ impl FamilyStrategy for ArithStrategy { S::IntFn { f, form } => f.words(form.bits()), S::FloatFn { f, form, .. } => f.words(*form), S::Fma(f) => f.words(), - // The fused multiply-add, a negation, and the flushes, for the pair and each link. - S::Fused { - fma, flush, inner, .. - } => inner + // The fused multiply-add and a negation, for the pair and each link. + S::Fused { fma, inner, .. } => inner .iter() - .fold(fma.words() + 8 + flush.words(fma.form), |w, l| { - w.saturating_add(fma.words() + 8 + l.flush.words(fma.form)) - }), - // The call of the fast division's routine, the truncation, its negation, and the - // fused multiply-add. - S::FastFmod { fma, .. } => 64 + fma.words() + math::FAST_DIVISION_CALL_WORDS, + .fold(fma.words() + 8, |w, _| w.saturating_add(fma.words() + 8)), + // The device's division, the truncation, its negation, and the fused multiply-add. + S::FastFmod { fma } => 80 + fma.words(), // The negation of `t` on its bits and the two fused multiply-adds. - S::Mix { fma, flush } => { - 32 + 2 * fma.words() - + if *flush { - denormal::flush_words(fma.form) - } else { - 0 - } - } - S::Dot { - fma, - form, - flush, - tiny, - } => math::metal_dot_words(*form, fma.words(), (*flush, *tiny)), + S::Mix { fma } => 32 + 2 * fma.words(), + S::Dot { fma, form } => math::metal_dot_words(*form, fma.words()), S::Convert { kind: ConvertKind::FromFp8(_), .. @@ -734,14 +649,9 @@ impl FamilyStrategy for ArithStrategy { nan, } => chunk::sin_cos_words(*shape, *fast, *nan).saturating_add(store.words()), S::ChunkedDot { lanes, elem, .. } => chunk::dot_words(*lanes, *elem), - S::ChunkedChain { - lanes, - elem, - fma, - flush, - reads, - tiny, - } => chunk::dot_chain_words(*lanes, *elem, fma.words(), (*flush, *tiny), *reads), + S::ChunkedChain { lanes, elem, fma } => { + chunk::dot_chain_words(*lanes, *elem, fma.words()) + } S::Chunked { lanes, parts, wide, .. } => { @@ -772,26 +682,6 @@ impl FamilyStrategy for ArithStrategy { S::WordBitcast { from, to } => chunk::bitcast_words(*from, *to), S::Wide(w) => w.words(), S::Nan { of, answer, form } => of.words().saturating_add(answer.words(*form)), - S::TinyProduct { of, form, check } => of - .words() - .saturating_add(denormal::tiny_product_words(*form, *check)), - S::Denormals { - of, - form, - out, - flush, - } => of.words().saturating_add( - denormal::Flush { - result: false, - ..*flush - } - .words(*form) - .saturating_add(if flush.result { - denormal::flush_words(*out) - } else { - 0 - }), - ), } } @@ -850,9 +740,7 @@ fn leaves(d: &DemoteTy) -> u32 { #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct ArithPlan { /// The float container widths whose operations must keep signed zeros, infinities, and NaNs: - /// those LLVM requires it of (an operation without all of `nnan`, `ninf`, and `nsz`), and - /// those of a check or a fused multiply-add routine that answers Metal's zero of its sign - /// ([`ArithPlan::keep_zero_signs`]). + /// those LLVM requires it of (an operation without all of `nnan`, `ninf`, and `nsz`). pub preserve: BTreeSet, /// The widths whose `SignedZeroInfNanPreserve` execution mode the entry declares: those of /// `preserve` the profile supports. @@ -862,19 +750,6 @@ pub struct ArithPlan { pub wide: bool, /// The shared division routines the wide divisions call, each defined once by [`declare`]. pub divides: BTreeSet, - /// The shared fused multiply-add routines the plan's `float` fused multiply-adds call, each - /// defined once by [`declare`]. - pub fmas: BTreeSet, - /// The shared precise division routines the plan's `float` divisions call, each defined - /// once by [`declare`]. - pub precise: BTreeSet, - /// The shared fast division routines the plan's `arcp` divisions, `fast::tanh`, - /// `fast::fmod`, and `fast::tan` call, each defined once by [`declare`]. - pub fast: BTreeSet, - /// The fast division routines the plan's `arcp` divisions call unless their quotient is the - /// device's own ([`ArithPlan::device_quotient`]), recorded at selection; [`finish`] adds them - /// to [`ArithPlan::fast`] where it is not. - pub arcp: BTreeSet, /// The value each forwarding `extractvalue` reads ([`aggregate::forwarded`]), and the /// member-wise phi each member extraction reads. pub forwards: BTreeMap, @@ -895,27 +770,20 @@ pub struct ArithPlan { /// Metal's sRGB table, which [`declare`] then declares once ([`srgb`]) and the census charges /// once, to that direction's strategy ([`routine_words`]). pub srgb: Option, - /// The math-library routines the plan's `float` calls may take ([`libm::uses`]), recorded at - /// selection; [`finish`] keeps in [`ArithPlan::libm`] those the device's instruction does not - /// answer. - pub libm_uses: BTreeSet, - /// The math-library routines the module defines, each once ([`declare`]). - pub libm: BTreeSet, + /// Whether a call takes Metal's precise `fmod` on `float` or `half` lanes ([`libm::uses`]), + /// recorded at selection; [`finish`] decides [`ArithPlan::fmod`] from it. + pub fmod_uses: bool, + /// Whether the module defines precise `fmod`'s routine ([`declare`]): where a call takes it + /// and the device's `OpFRem` is not Metal's `fmod` in the entry's mode + /// ([`libm::Fun::device_answers`]), decided by [`finish`]. + pub fmod: bool, /// The mode of the device's own `float` functions where the profile's are Metal's /// (`FloatFunctions::Metal`): the mode Metal compiles this entry in ([`libm::module_mode`], /// decided by [`finish`]). `None` on any other profile. pub metal_functions: Option, - /// Whether the profile takes native device maths (`FloatFunctions::Native`), decided by - /// [`finish`]: the math library's functions are the device's instructions ([`libm::Lib::native`]) - /// and an `arcp` division's quotient the device's ([`ArithPlan::device_quotient`]). - pub native: bool, - /// Whether a selected fused multiply-add takes native device maths' `Fma` - /// ([`fma::Route::Native`]), whose note [`finish`] records. + /// Whether a selected fused multiply-add takes the device's `Fma` ([`fma::Route::Native`]), + /// whose note [`finish`] records. pub native_fma: bool, - /// Whether the profile rounds `mix` and `fast::sqrt` in the device's order - /// (`RoundingOrderRoute::Native`), decided by [`finish`]: they are its `FMix` and `Sqrt` - /// ([`libm::Lib::with_native_order`]). - pub native_order: bool, /// How the module emits a multiply the device must round on its own, decided by [`finish`] from /// the same fact as [`ArithPlan::metal_functions`]: a device whose `float` functions are /// Metal's reaches Metal through SPIRV-Cross, which loses a `-0` product of a `NoContraction` @@ -927,13 +795,6 @@ pub struct ArithPlan { /// `OpBitFieldUExtract` on a driver whose compiler drops the mask after a signed clamp /// (`DriverWorkaround::NarrowMaskAfterSignedClamp`), else the mask. pub mask: MaskForm, - /// The profile's `float` fused multiply-add is `OpFmaKHR` ([`fma::float_route`]), decided by - /// [`finish`]: the trigonometric routines take a product's exact error as one `OpFmaKHR`. - pub libm_fma: bool, - /// The precise division routine the math-library routines call (`libm::Helpers`), on one - /// `float` lane, when one of [`ArithPlan::libm`] divides; decided by [`finish`], which adds it - /// to [`ArithPlan::precise`]. - pub libm_division: Option, /// Whether a function reads or writes a texture slot bound in an `_sRGB` extended-range /// format (`LoweringInputs::extended_range`), through Metal's tables, which [`declare`] then /// declares once ([`extended_range::declare`]). @@ -989,8 +850,9 @@ pub struct ArithPlan { /// the module then requires `VkProperty::MetalHalfArithmetic`. pub widened: BTreeSet, /// The precision notes the plan's operations record unless their entry's quotient and - /// functions are Metal's own ([`ArithPlan::device_quotient`]), recorded at selection - /// ([`OpNotes::unless_metal_fast`]); [`finish`] records them where they are not. + /// functions are Metal's own (the profile's `float` functions are Metal's and Metal compiles + /// the entry with fast math), recorded at selection ([`OpNotes::unless_metal_fast`]); + /// [`finish`] records them where they are not. pub unless_metal_fast: BTreeSet, } @@ -1006,64 +868,16 @@ impl ArithPlan { } } - /// Record fused multiply-add `fma`, selected: its routine, which [`declare`] defines once - /// (and whose widths [`finish`] keeps zero signs of), or the device's 16-bit `Fma` - /// ([`ArithPlan::f16_fma`]). + /// Record fused multiply-add `fma`, selected: the device's 16-bit `Fma` + /// ([`ArithPlan::f16_fma`]), or the device's `Fma` ([`ArithPlan::native_fma`]). pub fn take_fma(&mut self, fma: fma::Fma) { - if let Some(r) = fma.routine() { - self.fmas.insert(r); - } self.f16_fma |= fma.route == fma::Route::F16; self.native_fma |= fma.route == fma::Route::Native; } - - /// Record a check of a `float` product at `±2^-126` on lanes of form `f` - /// ([`denormal::tiny_product`]), selected where `check` is one: it answers Metal's zero of - /// the product's sign, so its width keeps zero signs ([`ArithPlan::keep_zero_signs`]). - pub fn take_tiny_check( - &mut self, - check: Option, - f: Form, - ) -> Option { - if check.is_some() { - self.keep_zero_signs(f.container()); - } - check - } - - /// Record that a check or routine computed by the translation answers Metal's zero of its - /// sign on floats of container width `width`: a fused multiply-add routine where the profile's - /// functions answer as Metal's ([`fma::Routine::widths`]: in `double`, in integers, a `half` - /// one, or a checked `OpFmaKHR`'s small results), a product flushed at `±2^-126` - /// ([`denormal::tiny_product`]). Vulkan lets a device take a zero of either sign from any - /// float operation of an entry without `SignedZeroInfNanPreserve` at its width (it assumes - /// `NSZ` there: the Vulkan specification's "Precision and Operation of SPIR-V Instructions"), - /// whatever the AIR's flags: NVIDIA's 615.71.09 on the RTX 3090 answered `-0` for a checked - /// `fma(+0, 100, +0)` whose answer is `+0`, in a fast-math entry. So the width joins - /// [`ArithPlan::preserve`], which [`finish`] declares where the profile supports it, else - /// notes `PrecisionNote::DeviceSignedZeroInfNan`. - pub fn keep_zero_signs(&mut self, width: u8) { - self.preserve.insert(width); - } - - /// Whether an `arcp` division's quotient is the device's `OpFDiv(x, y)`: where the profile's - /// float functions and division are Metal's and Metal compiles the entry with fast math - /// ([`ArithPlan::metal_functions`] is [`libm::Mode::Fast`]: the entry declares no - /// `SignedZeroInfNanPreserve`). That instruction reaches Metal's compiler as the AIR's own fast - /// `x / y`, which it compiles as it compiles Metal's, folds included. Where the entry declares - /// the mode, Metal compiles `x / y` as the correctly rounded quotient, not as its fast - /// division, so the quotient stays `x` times the device's `OpFDiv(1, y)`. The same fact decides - /// which operations are Metal's own and record no note ([`OpNotes`]). - pub fn device_quotient(&self) -> bool { - // Native device maths takes the device's quotient too. - metal_fast(self.metal_functions) || self.native - } } /// The words of the module-scope routines the plan's strategies call, each with the census name -/// of the strategies that call it: counted once per module, not per use. The fast division's -/// routine is charged to [`FAST_DIVIDE`], whether an `arcp` division, `fast::tanh`, `fast::fmod`, -/// or `fast::tan` calls it. +/// of the strategies that call it: counted once per module, not per use. pub fn routine_words(plan: &ArithPlan) -> impl Iterator + '_ { let table = plan.srgb.map(|dir| { let name = match dir { @@ -1083,25 +897,13 @@ pub fn routine_words(plan: &ArithPlan) -> impl Iterator impl Iterator) -> Result<(), Error> { cx.families.arith.wide = legal::holds_wide(cx.profile); cx.families.arith.quantize = narrow::quantize_form(cx.profile); @@ -1167,21 +960,6 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { } else { MaskForm::And }; - // Where the profile's functions answer as Metal's (`FloatMathsPolicy::Exact`), a fused - // multiply-add routine answers Metal's zero of its sign: every width it computes in keeps - // zero signs. Every family selected its fused multiply-adds by now. - if cx.profile.fields().float_functions == FloatFunctions::Device { - let arith = &mut cx.families.arith; - let kept: BTreeSet = arith - .fmas - .iter() - .flat_map(|r| r.widths()) - .copied() - .collect(); - for w in kept { - arith.keep_zero_signs(w); - } - } let fc = cx.profile.fields().float_controls; let widths: Vec = cx.families.arith.preserve.iter().copied().collect(); for w in widths { @@ -1196,18 +974,13 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { cx.precision.insert(PrecisionNote::DeviceSignedZeroInfNan); } } - cx.families.arith.libm_fma = fma::float_route(cx.profile) == fma::Route::Khr; let arith = &mut cx.families.arith; - // Every family selected its fused multiply-adds by now (a cube position's at selection). - fma::complete(&mut arith.fmas); // The measured device fact, never the driver's name. arith.metal_functions = match cx.profile.fields().float_functions { FloatFunctions::Metal => Some(libm::module_mode(&arith.modes)), - _ => None, + FloatFunctions::Native => None, }; - arith.native = cx.profile.fields().float_functions == FloatFunctions::Native; - arith.native_order = cx.profile.fields().rounding_order == RoundingOrderRoute::Native; - let native = arith.native; + // Every family selected its fused multiply-adds by now (a cube position's at selection). if arith.native_fma { cx.precision.insert(PrecisionNote::NativeFma); } @@ -1217,71 +990,30 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { Some(_) => ProductForm::NegativeZeroFma, None => ProductForm::Multiply, }; - arith.libm = arith - .libm_uses - .iter() - .copied() - .filter(|r| !metal.is_some_and(|m| r.device_answers(m)) && !(native && r.native())) - .collect(); - // The routines' division is the module's precise one (`libm::Helpers`): the precise division - // routine on one lane; and Metal's reciprocal's routine, its fast `rsqrt`'s, the precise - // `rsqrt`'s (which the fast one calls), and the fused step's where a routine calls them. - let needs = arith - .libm - .iter() - .fold(libm::Needs::default(), |n, r| n.or(r.needs())); - if needs.fast_inverse_root { - arith.libm.insert(libm::Fun::FastRsqrt); - } - // The emulated fused step where the profile has no `OpFmaKHR`: one routine the others call. - if needs.fused && !arith.libm_fma { - arith.libm.insert(libm::Fun::Fused); - } - let needs = arith.libm.iter().fold(needs, |n, r| n.or(r.needs())); - if needs.recip { - arith.libm.insert(libm::Fun::Recip); - } - if needs.inverse_root { - arith.libm.insert(libm::Fun::Rsqrt); - } - let needs = arith.libm.iter().fold(needs, |n, r| n.or(r.needs())); - arith.libm_division = needs.division.then(|| divide::Routine { - lanes: 1, - path: divide::Path::on(cx.profile), - }); - arith.precise.extend(arith.libm_division); - // An `arcp` division calls the fast division's routine unless its quotient is the - // device's, and an operation that is Metal's own in such an entry records its notes only - // outside one. - if !arith.device_quotient() { - arith.fast.extend(arith.arcp.iter().copied()); - } + // Precise `fmod` takes its routine but where the device's `OpFRem` is Metal's `fmod`. + arith.fmod = arith.fmod_uses && !metal.is_some_and(|m| libm::Fun::Fmod.device_answers(m)); + // An operation that is Metal's own in a fast-math entry records its notes only outside one. if !metal_fast(arith.metal_functions) { cx.precision.extend(arith.unless_metal_fast.iter().copied()); } Ok(()) } -/// The arith family's module-scope objects: the shared wide division routines (the -/// `GLSL.std.450` import is the serializer's, and constants are interned where they are used). +/// The arith family's module-scope objects: the shared wide division routines, precise `fmod`'s +/// routine, and the tables (the `GLSL.std.450` import is the serializer's, and constants are +/// interned where they are used). #[derive(Clone, Debug, Default)] pub struct Declared { /// The function of each of the plan's [`ArithPlan::divides`]. pub divides: BTreeMap, - /// The function of each of the plan's [`ArithPlan::fmas`]. - pub fmas: BTreeMap, - /// The function of each of the plan's [`ArithPlan::precise`]. - pub precise: BTreeMap, - /// The function of each of the plan's [`ArithPlan::fast`]. - pub fast: BTreeMap, /// The sRGB table, when [`ArithPlan::srgb`]. pub srgb: Option, /// The extended-range sRGB table, when [`ArithPlan::extended_range_srgb`]. pub extended_range_srgb: Option, /// The table of each of the plan's [`ArithPlan::padded_srgb`]. pub padded_srgb: BTreeMap, - /// The function of each of the plan's [`ArithPlan::libm`]. - pub libm: BTreeMap, + /// Precise `fmod`'s routine, when [`ArithPlan::fmod`]. + pub fmod: Option, } /// Declare the arith family's module-scope objects and entry execution modes: one function per @@ -1299,16 +1031,8 @@ pub fn declare( for d in &plan.families.arith.divides { decl.divides.insert(*d, wide::define_divide(mb, *d)?); } - let fmas = &plan.families.arith.fmas; - for r in fmas { - let id = fma::define_among(mb, *r, fmas, &decl.fmas)?; - decl.fmas.insert(*r, id); - } - for r in &plan.families.arith.precise { - decl.precise.insert(*r, divide::define(mb, *r)?); - } - for r in &plan.families.arith.fast { - decl.fast.insert(*r, math::define_fast_division(mb, *r)?); + if plan.families.arith.fmod { + decl.fmod = Some(libm::define_fmod(mb)?); } if plan.families.arith.srgb.is_some() { decl.srgb = Some(srgb::declare(mb)?); @@ -1321,83 +1045,6 @@ pub fn declare( decl.padded_srgb.insert(form, table); } } - let arith = &plan.families.arith; - let mut helpers = libm::Helpers { - division: match arith.libm_division { - Some(r) => Some( - *decl - .precise - .get(&r) - .ok_or(BuildError::Type(TypeRule::FunctionSignature))?, - ), - None => None, - }, - exp2: None, - log2: None, - rcp: None, - recip: None, - inverse_root: None, - rsqrt: None, - fast_inverse_root: None, - fused: None, - quarter: None, - sinc: None, - powr: None, - }; - if arith.libm.iter().any(|r| r.needs().exp2) { - helpers.exp2 = Some(libm::exp::declare(mb)?); - } - if arith.libm.iter().any(|r| r.needs().log2) { - helpers.log2 = Some(libm::log::declare(mb)?); - } - if arith.libm.iter().any(|r| r.needs().rcp) { - helpers.rcp = Some(libm::rcp::declare(mb)?); - } - if arith.libm.iter().any(|r| r.needs().rsqrt) { - helpers.rsqrt = Some(libm::rsqrt::declare(mb)?); - } - if arith.libm.iter().any(|r| r.needs().quarter) { - helpers.quarter = Some(libm::quarter::declare(mb)?); - } - if arith.libm.iter().any(|r| r.needs().sinc) { - helpers.sinc = Some(libm::sincos::declare(mb)?); - } - if arith.libm.iter().any(|r| r.needs().powr) { - helpers.powr = Some(libm::log::declare_powr(mb)?); - } - // The fused step's first: the routines with fused steps call it. - if arith.libm.contains(&libm::Fun::Fused) { - let id = libm::define(mb, libm::Fun::Fused, arith.libm_fma, helpers)?; - decl.libm.insert(libm::Fun::Fused, id); - helpers.fused = Some(id); - } - // Metal's reciprocal's next: `sinh`, `cosh`, and `tanh` call it. - if arith.libm.contains(&libm::Fun::Recip) { - let id = libm::define(mb, libm::Fun::Recip, arith.libm_fma, helpers)?; - decl.libm.insert(libm::Fun::Recip, id); - helpers.recip = Some(id); - } - // The precise `rsqrt`'s next: Metal's fast one calls it. - if arith.libm.contains(&libm::Fun::Rsqrt) { - let id = libm::define(mb, libm::Fun::Rsqrt, arith.libm_fma, helpers)?; - decl.libm.insert(libm::Fun::Rsqrt, id); - helpers.inverse_root = Some(id); - } - // Metal's fast `rsqrt`'s next: `asin`, `acos`, and both modes' `asinh` and `acosh` call it. - if arith.libm.contains(&libm::Fun::FastRsqrt) { - let id = libm::define(mb, libm::Fun::FastRsqrt, arith.libm_fma, helpers)?; - decl.libm.insert(libm::Fun::FastRsqrt, id); - helpers.fast_inverse_root = Some(id); - } - for r in arith.libm.iter().filter(|r| { - !matches!( - r, - libm::Fun::Fused | libm::Fun::Recip | libm::Fun::Rsqrt | libm::Fun::FastRsqrt - ) - }) { - decl.libm - .insert(*r, libm::define(mb, *r, arith.libm_fma, helpers)?); - } Ok(decl) } @@ -1587,8 +1234,8 @@ fn device_float_notes(f: Form, denormals: bool, nans: bool) -> impl Iterator) -> bool { metal == Some(libm::Mode::Fast) } @@ -1658,18 +1305,20 @@ fn record(cx: &mut SelectCx<'_>, notes: OpNotes) { /// The precision notes the lowering of the float binary operator `op` with fast-math flags `fmf` /// on operands of format `fmt` records for the operator itself on profile `p`: a division or -/// remainder is the device's arithmetic, and a `float` operator leaves denormals to the device -/// (Metal flushes `f32` denormals); a `float` remainder also leaves the NaN encoding to it, where -/// `+ - *` answer Metal's `0x7fc00000`. Metal's precise division ([`divide::precise`]: an `fdiv` on -/// `float` without `arcp`, or on `half`) records none: a shared routine computes Metal's quotient -/// apart from the device's division and its environment. Metal's fast division (an `fdiv` on -/// `float` with `arcp`) selects Metal's answers at denormals and NaNs itself (`math::fast_divide`), -/// so its reciprocal alone is the device's arithmetic; where the profile's `float` functions are -/// Metal's, the quotient of an entry Metal compiles with fast math is the device's `OpFDiv(x, y)`, -/// Metal's own fast division ([`ArithPlan::device_quotient`]), and the note holds only outside one. -/// Beside these, an addition, subtraction, or multiply whose flags let the device fuse or regroup -/// it with an operand's definition records `FastMathRewrites`, which the operands decide -/// (`note_rewrites`). `None` for an integer operator. +/// remainder is the device's arithmetic, and a `float` operator leaves its denormals to the device +/// where it is not measured to read them as Metal does (Metal flushes `f32` denormals, +/// [`leave_denormals`]); a `float` remainder also leaves the NaN encoding to it, where `+ - *` +/// answer Metal's `0x7fc00000`. Metal's precise division ([`divide::precise`]: an `fdiv` on +/// `float` without `arcp`, or on `half`) is the device's `OpFDiv` (`NativeDivision`), whose +/// denormals no device is measured to read as Metal does. Metal's fast division (an `fdiv` on +/// `float` with `arcp`) is the device's `OpFDiv(x, y)` too; where the profile's `float` functions +/// are Metal's, the quotient of an entry Metal compiles with fast math is Metal's own fast +/// division, and the notes hold only outside one. LLVM's `frem` on `float` without every +/// fast-math flag is the device's `OpFRem`, `x - y · trunc(x / y)` at its precision, as Metal +/// computes it of its precise quotient. Beside these, an addition, subtraction, or multiply whose +/// flags let the device fuse or regroup it with an operand's definition records +/// `FastMathRewrites`, which the operands decide (`note_rewrites`). `None` for an integer +/// operator. /// /// [`select`] records exactly these for such an operator (a `half` result's rounding is noted from /// the emitted module); validation reads them to tell which operations the product computes as a @@ -1683,54 +1332,49 @@ pub fn float_binop_notes( if !op.is_float() { return None; } - // Native device maths divides by the device's `OpFDiv`, and leaves the NaN Metal answers to the - // device. - let native = p.fields().float_functions == FloatFunctions::Native; + // The device leaves the NaN Metal answers to the device where the profile does. let native_nan = |answers: bool| { (answers && nan::encoding(p) == NanEncoding::Native) .then_some(PrecisionNote::NativeNanEncoding) }; if divide::precise(op, fmt, fmf) { - return Some(match native { - true => OpNotes::everywhere( - [Some(PrecisionNote::NativeDivision), native_nan(true)] - .into_iter() - .flatten() - .collect(), - ), - false => OpNotes::default(), - }); + return Some(OpNotes::everywhere( + [Some(PrecisionNote::NativeDivision), native_nan(true)] + .into_iter() + .flatten() + .chain(device_float_notes(scalar_float(fmt), true, false)) + .collect(), + )); } - // A `float` remainder is Metal's: with every flag its `fast::fmod`, with that function's notes; - // otherwise exact, its NaN Metal's canonical one. - if op == AirBin::FRem && fmt == FloatFmt::F32 { - if !every_flag(fmf) { - return Some(OpNotes::everywhere(native_nan(true).into_iter().collect())); - } + // A `float` remainder with every flag is Metal's `fast::fmod`, with that function's notes. + if op == AirBin::FRem && fmt == FloatFmt::F32 && every_flag(fmf) { let f = Form { held: Held::Float(FloatFmt::F32), lanes: 1, }; return float_call(FloatFn::Fmod, true, fmf, f, FloatFacts::on(p)).map(|l| l.notes); } + // A fast `float` division is the device's `OpFDiv`, its `f32` denormals the device's: no + // device is measured to read a quotient's as Metal does. if op == AirBin::FDiv && fmt == FloatFmt::F32 { - let mut notes = BTreeSet::from([PrecisionNote::DeviceArithmetic]); - if native { - notes.insert(PrecisionNote::NativeDivision); - notes.extend(native_nan(true)); - } + let mut notes = BTreeSet::from([ + PrecisionNote::DeviceArithmetic, + PrecisionNote::NativeDivision, + PrecisionNote::DeviceDenormals, + ]); + notes.extend(native_nan(true)); return Some(OpNotes::unless_own( notes, p.fields().float_functions == FloatFunctions::Metal, )); } - // A `float` `+ - *` answers Metal's NaN: the device's, where the profile states it is, else - // selected ([`nan`]), and reads its denormals as Metal does: the device's, where the profile - // states it does, else flushed ([`with_denormals`]). Metal's `half` and `bfloat` remainders are - // not measured. - let answer = nan::binary_answer(op, fmt); + // A `float` `+ - *` and remainder answer Metal's NaN: the device's, where the profile states + // it is, else selected ([`nan`]), and leave their denormals to the device: `+ - *` but where it + // is measured to read them as Metal does ([`leave_denormals`]), a remainder on every device. + // Metal's `half` and `bfloat` remainders are not measured. + let answer = binop_answer(op, fmt); let nans = answer.is_none(); - let denormals = op == AirBin::FRem; + let denormals = op == AirBin::FRem || !denormal::device_flushes(p); let mut notes: BTreeSet<_> = device_float_notes(scalar_float(fmt), denormals, nans).collect(); if matches!(op, AirBin::FDiv | AirBin::FRem) { notes.insert(PrecisionNote::DeviceArithmetic); @@ -1739,6 +1383,15 @@ pub fn float_binop_notes( Some(OpNotes::everywhere(notes)) } +/// The NaN Metal answers for the float binary operator `op` on format `fmt` that its lowering +/// selects ([`with_nan`]): `float` `frem`'s canonical NaN beside [`nan::binary_answer`]'s. +fn binop_answer(op: AirBin, fmt: FloatFmt) -> Option { + match (op, fmt) { + (AirBin::FRem, FloatFmt::F32) => Some(nan::NanAnswer::Canonical), + _ => nan::binary_answer(op, fmt), + } +} + /// Strategy `s` of instruction `at`, a result of form `form`, with Metal's NaN `answer` selected /// ([`nan`]): where Metal answers one the lowering does not, the profile does not leave it to the /// device, and the result's NaN bits may be observed. Under native device maths @@ -1773,276 +1426,20 @@ fn note_native_nan(cx: &mut SelectCx<'_>, answer: Option) { } } -/// `s`, an operation on `float` lanes of form `form` whose result has form `out` and whose -/// operands are `operands`, with Metal's reading of its `f32` denormals, `reading` -/// ([`denormal`]). Where the device is measured to read them so (on the deviation, where the -/// profile takes it: [`denormal::device_flushes`]) `s` is left to it, and the module requires -/// the property; else `s` flushes them itself ([`ArithStrategy::Denormals`]), but for an operand -/// no denormal can reach ([`flushed`]). Another format is `s` itself: a `half` is held widened, -/// never an `f32` denormal, and Metal's `bfloat` and `double` environments are not measured. -fn with_denormals( - cx: &mut SelectCx<'_>, - s: ArithStrategy, - (form, out): (Form, Form), - operands: &[Value], - reading: denormal::Reading, -) -> ArithStrategy { - if form.float_fmt() != Some(FloatFmt::F32) { - return s; - } - if reading.covered == denormal::Covered::Deviation && denormal::device_flushes(cx.profile) { - cx.families.arith.device_denormals = true; - return s; - } - let flush = denormal_flush(cx, operands, reading.operands, reading.result); - if !flush.any() { - return s; - } - ArithStrategy::Denormals { - of: Box::new(s), - form, - out, - flush, - } -} - -/// `s`, a `float` operation `op` on lanes of form `f`, with Metal's flush of a product whose exact -/// value lies below `2^-126` where the device's rounding may reach `±2^-126` -/// ([`ArithStrategy::TinyProduct`]): an `f32` multiply whose result can be that small (`result`, -/// [`denormal_result`]) on a profile that computes Metal's products -/// ([`denormal::checks_tiny_products`]). A sum or difference that small is exact, so a rounding -/// never reaches `2^-126` from below it. -fn tiny_product( - cx: &mut SelectCx<'_>, - s: ArithStrategy, - op: AirBin, - f: Form, - result: bool, -) -> ArithStrategy { - let check = denormal::tiny_check(cx.profile) - .filter(|_| op == AirBin::FMul && result && f.float_fmt() == Some(FloatFmt::F32)); - let Some(check) = cx.families.arith.take_tiny_check(check, f) else { - return s; - }; - ArithStrategy::TinyProduct { - of: Box::new(s), - form: f, - check, - } -} - -/// The flushes of a fused addition by `OpFmaKHR` on `float` lanes of form `f` of `operands` -/// (`a`, `b` and `c`, or a chain link's `a` and `b`, [`ArithStrategy::Fused`]): none where the -/// device reads its denormals as Metal does ([`denormal::device_flushes`]; the module then -/// requires the property), else each operand a denormal may reach and the result, as -/// [`with_denormals`]. -fn fused_flush(cx: &mut SelectCx<'_>, f: Form, operands: &[Value]) -> denormal::Flush { +/// Leave an operation's `f32` denormals (on `float` lanes of form `f`) to the device: where the +/// device is measured to read them as Metal does and the operation is one the measured deviation +/// covers (`covered`, [`denormal::device_flushes`]), the module requires the property; elsewhere +/// they are the device's own, noted `DeviceDenormals` (as the operation's notes record it). +/// Another format leaves nothing: a `half` is held widened, never an `f32` denormal, and Metal's +/// `bfloat` and `double` environments are not measured. +pub(super) fn leave_denormals(cx: &mut SelectCx<'_>, f: Form, covered: denormal::Covered) { if f.float_fmt() != Some(FloatFmt::F32) { - return denormal::Flush::NONE; + return; } - if denormal::device_flushes(cx.profile) { + if covered == denormal::Covered::Deviation && denormal::device_flushes(cx.profile) { cx.families.arith.device_denormals = true; - return denormal::Flush::NONE; - } - let reads = u8::try_from((1u32 << operands.len().min(8)) - 1).unwrap_or(u8::MAX); - denormal_flush(cx, operands, reads, true) -} - -/// The flushes of an operation on `operands` that reads those bit `reads` names as Metal does, -/// and flushes its result where `result`: each such operand a denormal may reach -/// ([`flushed`]). -fn denormal_flush( - cx: &SelectCx<'_>, - operands: &[Value], - reads: u8, - result: bool, -) -> denormal::Flush { - let mut read = 0u8; - for (i, v) in operands.iter().enumerate().take(8) { - if reads & (1 << i) != 0 && !flushed(cx, *v) { - read |= 1 << i; - } - } - denormal::Flush { - operands: read, - result, - } -} - -/// Whether the result of `float` `op` (`+ - *`) on operands `a` and `b`, each read as Metal -/// reads it (no denormal), can be a denormal: not where an operand is a constant whose every -/// lane is a zero, a denormal (read as one), an infinity, a NaN, or, for a sum or difference, of -/// magnitude at least `2^-102`, or, for a product, at least 1. A sum of `x` and such a `c` is a -/// zero or a multiple of `2^-126` (a sum that cancels to below `2^-126` needs `|x|` above -/// `2^-103`, whose unit in the last place is at least `2^-126`, as `c`'s is); a product of `x` -/// and such a `c` is a zero or at least `|x|`, which is normal. -fn denormal_result(cx: &SelectCx<'_>, op: AirBin, a: Value, b: Value) -> bool { - let least = match op { - AirBin::FAdd | AirBin::FSub => 2f32.powi(-102), - AirBin::FMul => 1.0, - _ => return true, - }; - let bounds = |v: Value| { - f32_lanes(cx, v).is_some_and(|lanes| { - lanes.iter().all(|&bits| { - let x = f32::from_bits(bits); - bits & 0x7F80_0000 == 0 || !x.is_finite() || x.abs() >= least - }) - }) - }; - !(bounds(a) || bounds(b)) -} - -/// The `f32` lanes of constant `v`, or `None` for another value. -fn f32_lanes(cx: &SelectCx<'_>, v: Value) -> Option> { - use crate::spirv::ids::ScalarTy; - match cx.constant(v)? { - LoweredConst::Scalar { - ty: ScalarTy::Float { bits: 32 }, - bits, - } => u32::try_from(bits).ok().map(|b| vec![b]), - LoweredConst::Vector { - elem: ScalarTy::Float { bits: 32 }, - lanes, - } => lanes.iter().map(|&b| u32::try_from(b).ok()).collect(), - _ => None, - } -} - -/// How many definitions [`flushed`] reads for one operand: constant work per operand, so the -/// walk needs no meter. An operand whose walk runs out is flushed, which is exact, only larger. -const FLUSHED_BUDGET: u32 = 48; - -/// Whether no `f32` lane of `v` can be a denormal, by its definition's structure: a constant -/// without one; the result of a `float` `+ - * /` or of a function whose denormal result is -/// flushed (`ldexp` on its operand's bits; `fma`, `llvm.fmuladd`: by the device where it is -/// measured to, else by [`with_denormals`]; the divisions' and fused multiply-add routines' by -/// Metal's own rule); an integer or a `half` converted to `float`; an integral or square-root -/// function's (never a denormal); Metal's `fract`, `sign` and `saturate`; and a sign move, lane -/// move, `select` or `phi` of such values, a `phi` on a cycle taken as one while its other incoming -/// values are checked (every value on the cycle is then such a value). A load, an argument or any -/// other value may be one, as may a value past the walk's budget ([`FLUSHED_BUDGET`]). -fn flushed(cx: &SelectCx<'_>, v: Value) -> bool { - let mut walk = FlushedWalk { - budget: FLUSHED_BUDGET, - phis: Vec::new(), - }; - walk.flushed(cx, v) -} - -/// The state of one [`flushed`] walk: its remaining budget and the `phi`s it is inside. -struct FlushedWalk { - budget: u32, - phis: Vec, -} - -impl FlushedWalk { - fn all(&mut self, cx: &SelectCx<'_>, vs: &[Value]) -> bool { - vs.iter().all(|x| self.flushed(cx, *x)) - } - - fn flushed(&mut self, cx: &SelectCx<'_>, v: Value) -> bool { - let Value::Inst(id) = v else { - return cx.constant(v).is_some_and(|k| !denormal_constant(&k)); - }; - let Some(left) = self.budget.checked_sub(1) else { - return false; - }; - self.budget = left; - let Some(inst) = cx.body.insts.get(id) else { - return false; - }; - match &inst.kind { - InstKind::BinOp { - op: AirBin::FAdd | AirBin::FSub | AirBin::FMul | AirBin::FDiv, - .. - } => true, - InstKind::FNeg { v, .. } | InstKind::Freeze(v) => self.flushed(cx, *v), - InstKind::Cast { - op: CastOp::SIToFP | CastOp::UIToFP, - .. - } => true, - InstKind::Cast { - op: CastOp::FPExt, - v, - } => form(cx, *v).is_ok_and(|f| f.float_fmt() == Some(FloatFmt::Half)), - InstKind::Select { t, f, .. } => self.all(cx, &[*t, *f]), - InstKind::ExtractElement { vec, .. } => self.flushed(cx, *vec), - InstKind::InsertElement { vec, elt, .. } => self.all(cx, &[*vec, *elt]), - InstKind::ShuffleVector { a, b, .. } => self.all(cx, &[*a, *b]), - InstKind::Phi { incoming, .. } => { - if self.phis.contains(&id) { - return true; - } - self.phis.push(id); - let all = incoming.iter().all(|(x, _)| self.flushed(cx, *x)); - self.phis.pop(); - all - } - InstKind::Call(call) => { - let fun = match &call.callee { - crate::air::ir::Callee::Air { - op: AirIntrinsic::Math(m), - .. - } => air_math(m.f), - crate::air::ir::Callee::Air { - op: AirIntrinsic::Convert(c), - .. - } => { - return c.dst_kind == NumKind::Float - && (c.src_kind != NumKind::Float || c.src.elem == Elem::F16) - } - crate::air::ir::Callee::Llvm { op, .. } => llvm_math(op), - _ => return false, - }; - use FloatFn as F; - match fun { - Ok(Fun::Float( - F::Floor - | F::Ceil - | F::Trunc - | F::Round - | F::Rint - | F::Sqrt - | F::Rsqrt - | F::FastSqrt - | F::FastRsqrt - | F::Ldexp - | F::Fma - | F::MulAdd - | F::Fract - | F::Sign - | F::Saturate, - )) => true, - Ok(Fun::Float(F::Abs | F::CopySign)) => { - call.args.first().is_some_and(|x| self.flushed(cx, *x)) - } - Ok(Fun::Float(F::Min | F::Max | F::Clamp | F::Min3 | F::Max3 | F::Median3)) => { - self.all(cx, &call.args) - } - _ => false, - } - } - _ => false, - } - } -} - -/// Whether constant `k` has an `f32` denormal lane. -fn denormal_constant(k: &LoweredConst) -> bool { - use crate::spirv::ids::ScalarTy; - let den = |b: u64| b & 0x7F80_0000 == 0 && b & 0x007F_FFFF != 0; - match k { - LoweredConst::Scalar { - ty: ScalarTy::Float { bits: 32 }, - bits, - } => den(*bits), - LoweredConst::Vector { - elem: ScalarTy::Float { bits: 32 }, - lanes, - } => lanes.iter().any(|b| den(*b)), - LoweredConst::Composite { parts, .. } => parts.iter().any(denormal_constant), - _ => false, + } else { + cx.precision.insert(PrecisionNote::DeviceDenormals); } } @@ -2147,56 +1544,27 @@ fn select_in( match f.held { Held::Bool if !op.is_float() => S::Bool { op: *op, form: f }, Held::Int { .. } if !op.is_float() => S::Int { op: *op, form: f }, + // LLVM's `frem` on `float` is Metal's (measured on the M3 Max): with every + // fast-math flag its `fast::fmod`, as `air.fast_fmod` is lowered; otherwise + // `x - y * trunc(x / y)` of its precise quotient, which the device's `OpFRem` is at + // the device's precision, below. + Held::Float(FloatFmt::F32) if *op == AirBin::FRem && every_flag(*fmf) => { + return select_float_fn(cx, at, (FloatFn::Fmod, true), *fmf, f); + } // Metal divides `float` without `arcp` correctly rounded, a denormal operand // read as a zero and a denormal quotient flushed (a probe cases 914cc4d2, 711cc190, // and c10cba13, every lane), and `half` under every flag set rounded once from the - // exact quotient (4c363561, 54f0fe8e, every lane): a shared routine computes that - // quotient on every profile, apart from the device's division and its environment - // (a `half` one is its `float` quotient rounded once). LLVM's `frem` on `float` is - // Metal's (measured on the M3 Max): with every fast-math flag its `fast::fmod`, as - // `air.fast_fmod` is lowered; otherwise `x - y * trunc(x / y)` of its precise - // quotient, each step rounded and read as Metal reads `f32` denormals, a NaN the - // canonical one. - Held::Float(FloatFmt::F32) if *op == AirBin::FRem => { - if every_flag(*fmf) { - return select_float_fn(cx, at, (FloatFn::Fmod, true), *fmf, f, &[*a, *b]); - } - fp_env(cx, *fmf, f); - let routine = divide::Routine::on(cx.profile, f); - cx.families.arith.precise.insert(routine); - let flush = !denormal::device_flushes(cx.profile); - cx.families.arith.device_denormals |= !flush; - let s = S::Remainder { - form: f, - routine, - flush, - }; - let s = - with_denormals(cx, s, (f, f), &[*a, *b], denormal::Reading::binary(true)); - with_nan(cx, at, s, Some(nan::NanAnswer::Canonical), f) - } + // exact quotient (4c363561, 54f0fe8e, every lane): the device's quotient, its + // divisor kept in Vulkan's range ([`divide::native`]), its NaN Metal's canonical + // one. No device is measured to read a quotient's denormals as Metal does. Held::Float(fmt) if divide::precise(*op, fmt, *fmf) => { let notes = float_binop_notes(*op, fmt, *fmf, cx.profile); record(cx, notes.unwrap_or_default()); note_rewrites(cx, Some(at), (*op, *fmf), *a, *b); - // Native device maths: the device's quotient. Its operands and result read as - // Metal reads `f32` denormals, and its NaN Metal's canonical one, as the - // routine answers them. - if cx.profile.fields().float_functions == FloatFunctions::Native { - fp_env(cx, *fmf, f); - let s = S::NativeDivide { form: f }; - // No device is measured to read a quotient's denormals so. - let reading = denormal::Reading { - covered: denormal::Covered::Never, - operands: 0b11, - result: true, - }; - let s = with_denormals(cx, s, (f, f), &[*a, *b], reading); - return Ok(with_nan(cx, at, s, Some(nan::NanAnswer::Canonical), f)); - } - let routine = divide::Routine::on(cx.profile, f); - cx.families.arith.precise.insert(routine); - S::PreciseDivide { form: f, routine } + fp_env(cx, *fmf, f); + leave_denormals(cx, f, denormal::Covered::Never); + let s = S::NativeDivide { form: f }; + with_nan(cx, at, s, Some(nan::NanAnswer::Canonical), f) } Held::Float(fmt) if op.is_float() => { let notes = float_binop_notes(*op, fmt, *fmf, cx.profile); @@ -2216,31 +1584,17 @@ fn select_in( }; // Metal divides `float` under `arcp` as `x` times its fast reciprocal of `y` // (a probe cases 914cc4d2 and 711cc190, every flag set measured, every lane), - // its reciprocal flushing past `2^126` and at a denormal `y`. That reciprocal - // is the profile's (`divide::Reciprocal::on`): the device's own where its float - // functions and division are Metal's, `RN(1 / y)` where it has `OpFmaKHR`, and - // the device's elsewhere. Where the first's module is compiled with fast math, - // the quotient is the device's `OpFDiv(x, y)` itself - // (`ArithPlan::device_quotient`, known once the entry's modes are, so the - // routine waits in `arcp`). Only that form is Metal's on every lane, and only - // in that mode, so the note stays. The routine answers the canonical NaN - // itself. + // its reciprocal flushing past `2^126` and at a denormal `y`: the device's + // `OpFDiv(x, y)`, Metal's own where the device's functions are Metal's in an + // entry Metal compiles with fast math. Its NaN is the device's where the + // profile leaves NaNs to it, else Metal's canonical one, selected; its `f32` + // denormals the device's ([`float_binop_notes`]). if *op == AirBin::FDiv && fmf.contains(FastMath::ARCP) && f.float_fmt() == Some(FloatFmt::F32) { - let reciprocal = divide::Reciprocal::on(cx.profile); - let routine = math::FastDivision::new(f, reciprocal, contract); - cx.families.arith.arcp.insert(routine); - let s = S::FastDivide { form: f, routine }; - // Native device maths' quotient is the device's `OpFDiv`: its NaN is the - // device's where the profile leaves NaNs to it, else Metal's canonical one, - // selected as the routine would answer it. - if cx.profile.fields().float_functions == FloatFunctions::Native { - with_nan(cx, at, s, Some(nan::NanAnswer::Canonical), f) - } else { - s - } + let s = S::FastDivide { form: f, contract }; + with_nan(cx, at, s, Some(nan::NanAnswer::Canonical), f) } else if let Some(basis) = f16_arithmetic(cx.profile, *op, f) { // The device's own `half` arithmetic, Metal's in the forms that keep it // apart, which the AIR's flags allow whatever they are. Only the measured @@ -2255,24 +1609,13 @@ fn select_in( form: f, contract, }; - // Metal reads an `f32` denormal operand of `+ - *` as a zero and flushes - // a denormal result, a product's before rounding; its remainder is not - // measured. - let s = match op { - AirBin::FAdd | AirBin::FSub | AirBin::FMul => { - let result = denormal_result(cx, *op, *a, *b); - let s = tiny_product(cx, s, *op, f, result); - with_denormals( - cx, - s, - (f, f), - &[*a, *b], - denormal::Reading::binary(result), - ) - } - _ => s, - }; - with_nan(cx, at, s, nan::binary_answer(*op, fmt), f) + // Metal reads an `f32` denormal operand of `+ - *` as a zero and flushes a + // denormal result: the device's reading, on the deviation. A remainder's + // are the device's on every device ([`float_binop_notes`]). + if matches!(op, AirBin::FAdd | AirBin::FSub | AirBin::FMul) { + leave_denormals(cx, f, denormal::Covered::Deviation); + } + with_nan(cx, at, s, binop_answer(*op, fmt), f) } } _ => return Err(cx.invariant("a binary operator on mismatched operands")), @@ -2301,15 +1644,15 @@ fn select_in( } } } - InstKind::FCmp { pred, a, b, fmf } => { + InstKind::FCmp { pred, a, fmf, .. } => { let f = form_in(cx, *a, chunk)?; // Metal compares an `f32` denormal as a zero; the result is a `bool`, never a NaN. fp_env(cx, *fmf, f); - let s = S::FloatCompare { + leave_denormals(cx, f, denormal::Covered::Deviation); + S::FloatCompare { pred: *pred, form: f, - }; - with_denormals(cx, s, (f, f), &[*a, *b], denormal::Reading::binary(false)) + } } InstKind::Cast { op, v } => select_cast(cx, at, *op, *v, inst, chunk)?, InstKind::Select { .. } => S::Select, @@ -2573,14 +1916,13 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result { /// call keeps the precise function: /// /// - `air.fast_tanh` is the MSL fast-math formula ([`FloatFn::FastTanh`]), divided by the -/// profile's fast reciprocal (`reciprocal`); +/// device's division; /// - `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 profile's fast reciprocal (`reciprocal`), where the device's instruction is not Metal's -/// fast function; +/// the device's division, where the device's instruction is not Metal's fast function; /// - `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`]); @@ -2591,7 +1933,7 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result { /// - `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 -/// profile's fast reciprocal (`reciprocal`) where the device's `Tan` is not it; +/// 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 @@ -2604,8 +1946,8 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result { /// ([`FloatFn::FastSqrt`], [`FloatFn::FastExp`], [`FloatFn::FastExp10`], [`FloatFn::FastLog`], /// [`FloatFn::FastLog10`], [`FloatFn::FastPowr`]); `air.fast_pow`'s magnitude is the last of /// `|x|`; -/// - `air.fast_log2` is Metal's `log2`, the precise one's routine with its table -/// ([`FloatFn::FastLog2`]), which the fast formulas' `log2` is too; +/// - `air.fast_log2` is Metal's `log2`, the precise one ([`FloatFn::FastLog2`]), which the fast +/// formulas' `log2` is too; /// - `air.fast_sinpi`, `air.fast_cospi`, and `air.fast_tanpi` are Metal's precise functions, /// which a device whose functions are Metal's answers by its `Sin` and `Cos` within Apple's /// fast bound ([`FloatFn::FastSinPi`], [`FloatFn::FastCosPi`], [`FloatFn::FastTanPi`]). @@ -2628,13 +1970,7 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result { /// at infinities, which only a call with every flag answers as a NaN (A1 case aed3faaa without /// flags, our probe with them), and `half` `fract`'s NaN and infinities. The other flag /// combinations are not measured; they take the answer of a call without flags. -fn refine_float( - op: FloatFn, - fast: bool, - fmf: FastMath, - f: Form, - reciprocal: divide::Reciprocal, -) -> FloatFn { +fn refine_float(op: FloatFn, fast: bool, fmf: FastMath, f: Form) -> FloatFn { if f.float_fmt() == Some(FloatFmt::Half) && op == FloatFn::Fract && !fast && every_flag(fmf) { return FloatFn::FlaggedFract; } @@ -2655,12 +1991,12 @@ fn refine_float( return op; } match op { - FloatFn::Tanh => FloatFn::FastTanh { reciprocal }, + FloatFn::Tanh => FloatFn::FastTanh, FloatFn::Asinh if every_flag(fmf) => FloatFn::FastAsinh, FloatFn::Sinh => FloatFn::FastSinh, FloatFn::Cosh => FloatFn::FastCosh, FloatFn::Acosh => FloatFn::FastAcosh, - FloatFn::Atanh => FloatFn::FastAtanh { reciprocal }, + FloatFn::Atanh => FloatFn::FastAtanh, FloatFn::Exp10 => FloatFn::FastExp10, FloatFn::Log10 => FloatFn::FastLog10, FloatFn::Fract => FloatFn::FastFract { @@ -2670,7 +2006,7 @@ fn refine_float( FloatFn::Pow => FloatFn::FastPow, FloatFn::Sin => FloatFn::FastSin, FloatFn::Cos => FloatFn::FastCos, - FloatFn::Tan => FloatFn::FastTan { reciprocal }, + FloatFn::Tan => FloatFn::FastTan, FloatFn::Asin => FloatFn::FastAsin, FloatFn::Acos => FloatFn::FastAcos, FloatFn::Atan => FloatFn::FastAtan, @@ -2761,43 +2097,38 @@ fn select_call( } ArithStrategy::IntFn { f: op, form: f } } - Fun::Float(op) => select_float_fn(cx, at, (op, fast), call.fmf, f, args)?, + Fun::Float(op) => select_float_fn(cx, at, (op, fast), call.fmf, f)?, }) } /// The strategy of float function `op` (`fast` its `fast_` variant) with fast-math flags `fmf` -/// on operands `args` of form `f`, the result of instruction `at`: a math call's, or LLVM's -/// `frem`'s, which is `fmod`. +/// on operands of form `f`, the result of instruction `at`: a math call's, or LLVM's `frem`'s, +/// which is `fmod`. fn select_float_fn( cx: &mut SelectCx<'_>, at: InstId, (op, fast): (FloatFn, bool), fmf: FastMath, f: Form, - args: &[Value], ) -> Result { let facts = FloatFacts::on(cx.profile); let lowered = float_call(op, fast, fmf, f, facts).ok_or_else(not_lowered)?; record(cx, lowered.notes); fp_env(cx, fmf, f); if let FloatLowering::Fn(op) = lowered.how { - let uses = libm::uses(op, f); + let fmod = libm::uses(op, f).contains(&libm::Fun::Fmod); let arith = &mut cx.families.arith; - arith.libm_uses.extend(uses.iter().copied()); + arith.fmod_uses |= fmod; arith.device_min_max |= device_min_max(cx.profile, op, f); arith.native_min_max |= native_min_max(cx.profile, op, f); } if let FloatLowering::Fma(fma) - | FloatLowering::FastFmod { fma, .. } + | FloatLowering::FastFmod(fma) | FloatLowering::Mix(fma) | FloatLowering::Dot(fma) = lowered.how { cx.families.arith.take_fma(fma); } - // `fast::fmod`, `fast::tanh`, and `fast::tan` divide by the fast division's routine. - if let Some(r) = fast_division_of(lowered.how, f) { - cx.families.arith.fast.insert(r); - } // `dot`'s result is a scalar. let result = match lowered.how { FloatLowering::Fn(FloatFn::Dot) | FloatLowering::Dot(_) => f.scalar_form(), @@ -2805,94 +2136,55 @@ fn select_float_fn( }; let s = match lowered.how { FloatLowering::Fma(fma) => ArithStrategy::Fma(fma), - FloatLowering::FastFmod { fma, reciprocal } => ArithStrategy::FastFmod { fma, reciprocal }, - // As `dot`'s chain: the inner fused multiply-add's result is flushed where `OpFmaKHR` may - // keep a denormal ([`with_denormals`] flushes the operands and the result); the routines, - // and `OpFmaKHR` checked ([`fma::Fma::checked`]), read and answer them as Metal does. - FloatLowering::Mix(fma) => ArithStrategy::Mix { - fma, - flush: fma.route.device_float() - && !fma.checked() - && f.float_fmt() == Some(FloatFmt::F32) - && !denormal::device_flushes(cx.profile), - }, - // The chain's values are flushed where `OpFmaKHR` and the multiply may keep a - // denormal ([`with_denormals`] flushes the operands and the result); the - // routines read and answer them as Metal does. - FloatLowering::Dot(fma) => { - // The first product is a multiply: Metal's flush before its rounding. - let tiny = - denormal::tiny_check(cx.profile).filter(|_| f.float_fmt() == Some(FloatFmt::F32)); - ArithStrategy::Dot { - fma, - form: f, - flush: fma.route.device_float() - && f.float_fmt() == Some(FloatFmt::F32) - && !denormal::device_flushes(cx.profile), - tiny: cx.families.arith.take_tiny_check(tiny, f), - } - } + FloatLowering::FastFmod(fma) => ArithStrategy::FastFmod { fma }, + FloatLowering::Mix(fma) => ArithStrategy::Mix { fma }, + FloatLowering::Dot(fma) => ArithStrategy::Dot { fma, form: f }, FloatLowering::Fn(op) => ArithStrategy::FloatFn { f: op, form: f, contract: contraction(fmf), }, }; - // The device's instruction reads `f32` denormals as Metal does only where the table - // says so; `OpFmaKHR` is the device's, the routines are Metal's. - // Native device maths answers `fast::atan2` by the device's instructions, its denormals the - // device's (`PrecisionNote::DeviceDenormals`, [`function_notes`]); nothing is flushed there. - let native_atan2 = |op: FloatFn| { - matches!(op, FloatFn::FastAtan2 { .. }) - && facts.native - && libm::uses(op, f).iter().any(|r| r.native()) - }; - // Where the profile's functions are Metal's, Metal's fast `sinpi`, `cospi` and `tanpi` are the - // device's form ([`FloatFn::FastSinPi`], `math::pi_scaled`), whose first multiply and - // difference read the operand: as Metal does on the deviation, else flushed. For a normal - // operand no step of it is a denormal, and it answers none. - let device_pi = |op: FloatFn| { - facts.metal_functions - && matches!( - op, - FloatFn::FastSinPi | FloatFn::FastCosPi | FloatFn::FastTanPi - ) - }; - // `OpFmaKHR` checked ([`fma::Fma::checked`]) answers no denormal: only its operands are read. - let checked = |fma: fma::Fma| { - denormal::coverage(FloatFn::Fma).map(|r| denormal::Reading { - result: r.result && !fma.checked(), - ..r - }) - }; - let reading = match lowered.how { - FloatLowering::Fma(fma) if fma.route.device_float() => checked(fma), - FloatLowering::Fn(op) if native_atan2(op) => None, - FloatLowering::Fn(op) if device_pi(op) => Some(denormal::Reading { - covered: denormal::Covered::Deviation, - operands: 0b1, - result: false, - }), + // The device reads the call's `f32` denormals as Metal does where the table says so, on the + // deviation; elsewhere they are its own, as the call's notes say. + if let Some(covered) = call_coverage(lowered.how, facts) { + leave_denormals(cx, f, covered); + } + Ok(with_nan(cx, at, s, lowered.nan, result)) +} + +/// Where the device reads the `f32` denormals of a float function call lowered as `how` on a +/// profile with float facts `facts` as Metal does ([`denormal::coverage`]): a fused multiply-add, +/// `mix` and `fast::fmod` by the device's own `float` instruction as `fma` (`OpFmaKHR`, or the +/// device's `Fma`), `dot`'s chain as `dot`, and the function's own row. Where the profile's +/// functions are Metal's, Metal's fast `sinpi`, `cospi` and `tanpi` are the device's form +/// ([`FloatFn::FastSinPi`], `math::pi_scaled`), whose first multiply and difference read the +/// operand, on the deviation. `None` for a lowering the table does not list. +fn call_coverage(how: FloatLowering, facts: FloatFacts) -> Option { + match how { + FloatLowering::Fma(fma) | FloatLowering::Mix(fma) | FloatLowering::FastFmod(fma) + if fma.route.device_float() => + { + denormal::coverage(FloatFn::Fma) + } + FloatLowering::Fn(FloatFn::FastSinPi | FloatFn::FastCosPi | FloatFn::FastTanPi) + if facts.metal_functions => + { + Some(denormal::Covered::Deviation) + } FloatLowering::Fn(op) => denormal::coverage(op), FloatLowering::Dot(_) => denormal::coverage(FloatFn::Dot), - // `mix` by `OpFmaKHR` reads its operands and result as its fused multiply-adds do. - FloatLowering::Mix(fma) if fma.route.device_float() => checked(fma), - // `fast::fmod` by `OpFmaKHR` reads its two operands and its result as `fma` does, but under - // native device maths, which leaves them to the device; its quotient's division reads them - // as Metal's. - FloatLowering::FastFmod { fma, .. } if fma.route.device_float() && !facts.native => { - checked(fma).map(|r| denormal::Reading { - operands: 0b11, - ..r - }) - } - _ => None, - }; - let s = match reading { - Some(reading) => with_denormals(cx, s, (f, result), args, reading), - None => s, - }; - Ok(with_nan(cx, at, s, lowered.nan, result)) + FloatLowering::Fma(_) | FloatLowering::Mix(_) | FloatLowering::FastFmod(_) => None, + } +} + +/// Whether the device leaves a call lowered as `how` (on lanes of form `f`) its `f32` denormals +/// on a profile with float facts `facts`, as [`leave_denormals`] notes them: where its reading is +/// covered ([`call_coverage`]) but not by the profile's deviation (`facts.device_denormals`). +fn coverage_left(how: FloatLowering, f: Form, facts: FloatFacts) -> bool { + f.float_fmt() == Some(FloatFmt::F32) + && call_coverage(how, facts) + .is_some_and(|c| !(c == denormal::Covered::Deviation && facts.device_denormals)) } /// Whether Metal's minimum and maximum function `op` on lanes of form `f` takes the device's @@ -2949,10 +2241,11 @@ enum F16Basis { /// one to four lanes (a chunk's own form), where profile `p` has `shaderFloat16` and takes /// `DriverDeviation::MetalHalfArithmetic` ([`F16Basis::Measured`]) or rounds to `half` under the /// 16-bit float controls ([`F16Basis::Controlled`]). Under those controls the instruction is Metal's -/// by the Vulkan spec ([`ops::f16_binary`]). A `half` `fdiv` keeps the shared precise routine: -/// Metal's fast and relaxed compiles answer the device's 16-bit quotient of widened operands as a -/// `float` one, it has no form that keeps it apart, and Vulkan's precision table -/// does not make a 16-bit quotient correctly rounded. A `half` `frem` is not measured. +/// by the Vulkan spec ([`ops::f16_binary`]). A `half` `fdiv` is the device's `float` quotient of +/// the widened operands, rounded to `half`: Metal's fast and relaxed compiles answer the device's +/// 16-bit quotient of widened operands as a `float` one, it has no form that keeps it apart, and +/// Vulkan's precision table does not make a 16-bit quotient correctly rounded. A `half` `frem` is +/// not measured. fn f16_arithmetic(p: &DeviceProfile, op: AirBin, f: Form) -> Option { use crate::error::DriverDeviation; let applies = matches!(op, AirBin::FAdd | AirBin::FSub | AirBin::FMul) @@ -2970,41 +2263,14 @@ fn f16_arithmetic(p: &DeviceProfile, op: AirBin, f: Form) -> Option { } } -/// The fast division routine a float function call of form `f` lowered as `how` calls: -/// `fast::fmod`'s and `fast::tanh`'s quotients, `fast::tan`'s, and `fast::atanh`'s, their device -/// division `NoContraction`. A `fast::tan` or `fast::atanh` that the device's own instruction -/// answers calls none, and its unused routine leaves the module with the dead functions. -fn fast_division_of(how: FloatLowering, f: Form) -> Option { - let reciprocal = match how { - FloatLowering::FastFmod { reciprocal, .. } => reciprocal, - FloatLowering::Fn( - FloatFn::FastTanh { reciprocal } - | FloatFn::FastTan { reciprocal } - | FloatFn::FastAtanh { reciprocal }, - ) => reciprocal, - FloatLowering::Fma(_) - | FloatLowering::Mix(_) - | FloatLowering::Dot(_) - | FloatLowering::Fn(_) => return None, - }; - Some(math::FastDivision::new( - f, - reciprocal, - Contraction::Forbidden, - )) -} - /// How [`select_call`] lowers a float function call. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum FloatLowering { /// A fused multiply-add. Fma(fma::Fma), - /// `air.fast_fmod` on `float`, its quotient by `reciprocal`. - FastFmod { - fma: fma::Fma, - reciprocal: divide::Reciprocal, - }, - /// `air.mix` on `float` or `half`. + /// `air.fast_fmod` on `float`, its quotient the device's. + FastFmod(fma::Fma), + /// `air.mix` on `float` or `half` as Metal's two fused multiply-adds. Mix(fma::Fma), /// `air.dot` on `float` or `half`, Metal's fused chain by the fused multiply-add on one lane. Dot(fma::Fma), @@ -3025,20 +2291,15 @@ struct FloatCall { struct FloatFacts { /// The fused multiply-add routes ([`fma::routes`]). routes: fma::Routes, - /// The fast reciprocal ([`divide::Reciprocal::on`]). - reciprocal: divide::Reciprocal, /// Whether the profile's `float` functions are Metal's (`FloatFunctions::Metal`). metal_functions: bool, - /// Whether the profile takes native device maths (`FloatFunctions::Native`). - native: bool, + /// Whether the device reads `f32` denormals as Metal does ([`denormal::device_flushes`]). + device_denormals: bool, /// Whether the profile leaves Metal's NaN to the device ([`NanEncoding::Native`]). nan_native: bool, /// Whether Metal's minimum and maximum functions are the device's as they are /// (`MinMaxRoute::Native`, [`native_min_max`]). native_min_max: bool, - /// Whether `dot`, `mix` and `fast::sqrt` round in the device's order - /// (`RoundingOrderRoute::Native`, [`native_chain`]). - native_order: bool, } impl FloatFacts { @@ -3046,12 +2307,10 @@ impl FloatFacts { fn on(p: &DeviceProfile) -> FloatFacts { FloatFacts { routes: fma::routes(p), - reciprocal: divide::Reciprocal::on(p), metal_functions: p.fields().float_functions == FloatFunctions::Metal, - native: p.fields().float_functions == FloatFunctions::Native, + device_denormals: denormal::device_flushes(p), nan_native: nan::encoding(p) == NanEncoding::Native, native_min_max: p.fields().min_max == MinMaxRoute::Native, - native_order: p.fields().rounding_order == RoundingOrderRoute::Native, } } } @@ -3061,19 +2320,18 @@ impl FloatFacts { /// are Metal's. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum MetalOwn { - /// None of it: the lowering takes a routine of the translation's (a model of Metal's - /// function the device does not answer in a fast-math module), the device answers a routine - /// by a near-equivalent ([`libm::Fun::device_near_equivalent`]), or no `float` or `half` - /// function is called. + /// None of it: the device's instruction is not Metal's function in a fast-math module, the + /// device answers it by a near-equivalent ([`libm::Fun::device_near_equivalent`]), or no + /// `float` or `half` function is called. No, - /// Its function and its division: a `fast_` call that takes no routine (`fast::rsqrt`, + /// Its function and its division: a `fast_` call of no listed function (`fast::rsqrt`, /// `fast::sqrt`), whose device instruction the module compiles as Metal's fast function, and - /// whose reciprocal is Metal's fast one ([`divide::Reciprocal::Device`]). + /// whose division is Metal's fast one. Function, - /// Wholly: every routine the call takes the device answers in a fast-math module as Metal's + /// Wholly: every function the call takes the device answers in a fast-math module as Metal's /// own function ([`libm::Fun::device_answers`]), whose every word, denormals and NaNs among - /// them, is Metal's (`DriverDeviation::MetalFloatFunctions`); its division is by Metal's - /// fast reciprocal. + /// them, is Metal's (`DriverDeviation::MetalFloatFunctions`); its division is Metal's fast + /// one. Wholly, } @@ -3099,15 +2357,16 @@ impl MetalOwn { /// The notes of a call of float function `op` (with the `fast_` prefix where `fast`) on form `f` /// lowered as the function itself, on a profile whose `float` functions are Metal's where -/// `metal_functions`, the device's (native device maths) where `native`, and whose `fast::sqrt` -/// rounds in the device's order where `native_order`: the function's precision -/// ([`FloatFn::precision`]) and its division's (`DeviceArithmetic` for [`FloatFn::divides`]), and -/// its `f32` denormals' and NaNs' where they are left to the device (`denormals`, `nans`, -/// [`device_float_notes`]). +/// `metal_functions`: where they are not, the device's precision where the call takes the device's +/// instruction for one of Metal's functions, `fast::sqrt`'s `Sqrt` included +/// (`NativeTranscendentals`), else the function's precision ([`FloatFn::precision`]), +/// and its division's (`DeviceArithmetic` for [`FloatFn::divides`], and `NativeDivision` where the +/// functions are not Metal's), and its `f32` denormals' and NaNs' where they are left to the +/// device (`denormals`, `nans`, [`device_float_notes`]). /// -/// A function whose answer is the one right value, Metal's on every device -/// ([`libm::Fun::correctly_rounded`]: `sqrt`, `rsqrt`, and `fmod`, precise, and their `half` -/// calls), records no precision note. Where the profile's `float` functions are Metal's, a call +/// A call of precise `fmod` by its routine, whose answer is the one right value, Metal's on every +/// device ([`libm::Fun::correctly_rounded`]), records no precision note. Where the profile's +/// `float` functions are Metal's, a call /// that is Metal's own in a fast-math entry ([`MetalOwn`]) records its function's and its /// division's notes only outside one, and, where it is wholly Metal's own, its denormals' and /// NaNs' too ([`OpNotes`]). Of its fast functions, `fast::atan2` is Apple's formula @@ -3116,20 +2375,19 @@ impl MetalOwn { /// divisors are past `2^126`, where Table 8.2 states no accuracy for the quotient: within Apple's /// bound, which the user's fast-math sign-off accepts ("fast-math within Apple's bound", /// 2026-10-03), so it is Metal's own too. Its fast `sinpi`, `cospi`, and `tanpi`, the device's -/// near-equivalents, keep their notes, as does every call in an entry that keeps NaNs, and every -/// routine of the translation's. +/// near-equivalents, keep their notes, as does every call in an entry that keeps NaNs. fn function_notes( op: FloatFn, fast: bool, f: Form, - (metal_functions, native, native_order): (bool, bool, bool), + metal_functions: bool, (denormals, nans): (bool, bool), ) -> OpNotes { let uses = libm::uses(op, f); - // Native device maths answers by the device's instruction what a routine would, and the - // device's order `fast::sqrt`: its precision is Vulkan's, and its `f32` denormals the device's. - let native_uses = - (native && uses.iter().any(|r| r.native())) || (native_order && op.native_instruction()); + // Off Metal's own functions, the device's instruction for one of Metal's functions, and the + // device's `fast::sqrt`: its precision is Vulkan's, and its `f32` denormals the device's. + let native = !metal_functions; + let native_uses = native && (uses.iter().any(|r| r.native()) || op.native_instruction()); let exact = !native_uses && !uses.is_empty() && uses.iter().all(|r| r.correctly_rounded()); let mut function = BTreeSet::new(); if native_uses { @@ -3155,12 +2413,13 @@ fn function_notes( } /// Whether the device's instruction (`OpDot`, `FMix`) answers Metal's fused chain of `dot` or -/// `mix` with fused multiply-add `fma` on lanes of form `f`: on a profile that rounds in the -/// device's order (`RoundingOrderRoute::Native`), a `float` chain, and a `half` one whose fused -/// multiply-add is not the measured 16-bit route ([`fma::Route::F16`], Metal's own `half` `fma`, -/// which the chain keeps). +/// `mix` with fused multiply-add `fma` on lanes of form `f`: on a profile whose `float` functions +/// are not Metal's own, a `float` chain, and a `half` one whose fused multiply-add is not the +/// measured 16-bit route ([`fma::Route::F16`], Metal's own `half` `fma`, which the chain keeps). +/// Where they are (MoltenVK), Metal's own forms of its own fused multiply-add are Metal's answer +/// and stay. fn native_chain(facts: FloatFacts, fma: fma::Fma, f: Form) -> bool { - facts.native_order + !facts.metal_functions && match f.float_fmt() { Some(FloatFmt::F32) => true, Some(FloatFmt::Half) => fma.route != fma::Route::F16, @@ -3168,7 +2427,7 @@ fn native_chain(facts: FloatFacts, fma: fma::Fma, f: Form) -> bool { } } -/// The note of fused multiply-add `fma`: `NativeFma` where it takes native device maths' `Fma` +/// The note of fused multiply-add `fma`: `NativeFma` where it takes the device's `Fma` /// ([`fma::Route::Native`]), which [`finish`] records for every such route a family takes. fn native_fma(fma: fma::Fma) -> OpNotes { match fma.route { @@ -3183,7 +2442,9 @@ fn native_fma(fma: fma::Fma) -> OpNotes { /// the function does not take). Where the profile leaves NaNs to the device a Metal NaN the call /// answers is the device's, noted `NativeNanEncoding` (as [`with_nan`] records it), and where its /// picks are the device's Metal's minimum and maximum functions are the device's -/// ([`native_min_max`]), noted `NativeMinMax`. +/// ([`native_min_max`]), noted `NativeMinMax`; the `f32` denormals the device reads where the +/// table covers the call but the profile lacks the deviation are noted `DeviceDenormals` +/// ([`coverage_left`]). fn float_call( op: FloatFn, fast: bool, @@ -3202,11 +2463,16 @@ fn float_call( native.insert(PrecisionNote::NativeMinMax); } } + // The `f32` denormals the device reads where it is not measured to read them as Metal does + // ([`leave_denormals`]). + if coverage_left(call.how, f, facts) { + native.insert(PrecisionNote::DeviceDenormals); + } call.notes = call.notes.with(OpNotes::everywhere(native)); Some(call) } -/// [`float_call`] before native device maths' NaN and minimum and maximum notes. +/// [`float_call`] before the device's NaN and minimum and maximum notes. fn float_call_of( op: FloatFn, fast: bool, @@ -3219,22 +2485,20 @@ fn float_call_of( } let FloatFacts { routes, - reciprocal, metal_functions, .. } = facts; - let op = refine_float(op, fast, fmf, f, reciprocal); - // `float` and `half` fused multiply-adds round once on every profile; a `bfloat` one corrects - // its tie, and a `double` one is `GLSL.std.450 Fma` at the device's precision. `llvm.fmuladd` - // on `float` and `half` is the fused one too: LLVM lets the implementation choose, and Metal - // fuses it (a probe case f7850ba7, every lane), so its value is exact and needs no + let op = refine_float(op, fast, fmf, f); + // `float` and `half` fused multiply-adds take the profile's route ([`fma`]); a `bfloat` one + // corrects its tie, and a `double` one is `GLSL.std.450 Fma` at the device's precision. + // `llvm.fmuladd` on `float` and `half` is the fused one too: LLVM lets the implementation + // choose, and Metal fuses it (a probe case f7850ba7, every lane), so it needs no // `FastMathRewrites`. if matches!(op, FloatFn::Fma | FloatFn::MulAdd) { if let Some(fma) = fma::Fma::by(routes, f) { - // `OpFmaKHR` is the device's at denormals and answers the device's NaN, so Metal's - // reading of its denormals ([`with_denormals`]) and Metal's NaN are selected; the - // `float` routines are Metal's at both. A `half` result's rounding answers the device's - // `half` NaN on every route, so Metal's is selected where it is measured. + // The device's `float` instruction answers the device's NaN, so Metal's is selected; a + // `half` result's rounding answers the device's `half` NaN on every route, so Metal's + // is selected where it is measured. let khr = fma.route.device_float(); let nan = match f.float_fmt() { Some(FloatFmt::Half) => { @@ -3250,16 +2514,14 @@ fn float_call_of( } } // Metal's `mix(x, y, t)` on `float` and `half` is `fma(t, y, fma(-t, x, x))`, with and without - // fast-math flags, so both fused multiply-adds take the profile's route. The routines answer - // Metal's `float` NaN; `OpFmaKHR` answers the device's, which is selected, and a `half` - // result's as the `half` `fma`'s. Each reads an `f32` denormal as Metal's `fma` does: the - // routines themselves, `OpFmaKHR` on the deviation or flushed ([`ArithStrategy::Mix`]'s - // `flush`, [`with_denormals`]). + // fast-math flags. Where the device's functions are Metal's, and on `half` by the measured + // 16-bit fused multiply-add, Metal's own form of its own fused multiply-adds answers it, whose + // NaN is the device's `float` instruction's, which is selected, and a `half` result's as the + // `half` `fma`'s. if op == FloatFn::Mix { if let Some(fma) = fma::Fma::by(routes, f) { - // The device's order takes its `FMix` where Metal's fused form would be emulated: - // on `float`, and on `half` where its fused multiply-add is not the measured 16-bit - // one, rounded once (`NativeMix`). + // The device's order takes its `FMix`: on `float`, and on `half` where its fused + // multiply-add is not the measured 16-bit one, rounded once (`NativeMix`). if native_chain(facts, fma, f) { return Some(FloatCall { how: FloatLowering::Fn(op), @@ -3291,20 +2553,19 @@ fn float_call_of( } } // Metal's `dot` on `float` and `half` is the products' fused chain, with and without - // fast-math flags, so each lane after the first takes the profile's route on one lane: the - // device's `OpDot` may sum otherwise (a tree, an unfused sum, or, under fast-math flags, `b * - // (a + c)` for `dot(float2(a, b), float2(b, c))`). Where the profile's `float` functions are - // Metal's, a `float` `OpDot` reaches Metal's own `dot`, the same chain; a `half` there would be - // summed in its `float` container, so it takes the chain. Either is Metal's answer at denormals - // and records no note; Metal's NaN is selected as for any function. + // fast-math flags; the device's `OpDot` may sum otherwise (a tree, an unfused sum, or, under + // fast-math flags, `b * (a + c)` for `dot(float2(a, b), float2(b, c))`, `NativeDot`). Where the + // profile's `float` functions are Metal's, a `float` `OpDot` reaches Metal's own `dot`, the + // same chain; a `half` there would be summed in its `float` container, so it takes the chain, + // as a `half` one by the measured 16-bit fused multiply-add does. Metal's NaN is selected as + // for any function. if op == FloatFn::Dot { if let Some(fma) = fma::Fma::by(routes, f.scalar_form()) { let nan = f .float_fmt() .and_then(|fmt| nan::function_answer(op, fast, every_flag(fmf), fmt)); - // The device's order takes its `OpDot` where Metal's chain would be emulated: on - // `float`, and on `half` where its fused multiply-add is not the measured 16-bit one, - // rounded once (`NativeDot`). + // The device's order takes its `OpDot`: on `float`, and on `half` where its fused + // multiply-add is not the measured 16-bit one, rounded once (`NativeDot`). if native_chain(facts, fma, f.scalar_form()) { return Some(FloatCall { how: FloatLowering::Fn(op), @@ -3324,23 +2585,18 @@ fn float_call_of( }); } } - // `air.fast_fmod` on `float` is Metal's composition around a fused multiply-add; the fast-math - // table is single precision, so a narrow call keeps `fmod`. Where the profile's `float` - // functions are Metal's, its `fma` is Metal's own and its quotient's reciprocal Metal's fast - // one in a fast-math entry ([`divide::Reciprocal::Device`]), so its notes hold only outside - // one. Metal reads a denormal operand as the zero of its sign and answers no denormal, in both - // modes: the routines read them so, and the device's fused multiply-add on the - // deviation or flushed ([`with_denormals`]) where the profile asks Metal's functions; native - // device maths leaves them to the device's (`DeviceDenormals`), unflushed. + // `air.fast_fmod` on `float` is Metal's composition around a fused multiply-add, of the + // device's quotient; the fast-math table is single precision, so a narrow call keeps `fmod`. + // Where the profile's `float` functions are Metal's, its `fma` is Metal's own and its quotient + // Metal's fast one in a fast-math entry, so its notes hold only outside one. Metal reads a + // denormal operand as the zero of its sign and answers no denormal, in both modes; the + // device's reading is noted where the profile lacks the deviation ([`coverage_left`]). if fast && op == FloatFn::Fmod && f.float_fmt() == Some(FloatFmt::F32) { if let Some(fma) = fma::Fma::by(routes, f) { let khr = fma.route.device_float(); - let mut notes = BTreeSet::from([PrecisionNote::DeviceArithmetic]); - if khr && facts.native { - notes.extend(device_float_notes(f, true, false)); - } + let notes = BTreeSet::from([PrecisionNote::DeviceArithmetic]); return Some(FloatCall { - how: FloatLowering::FastFmod { fma, reciprocal }, + how: FloatLowering::FastFmod(fma), notes: OpNotes::unless_own(notes, metal_functions && khr).with(native_fma(fma)), nan: khr.then_some(nan::NanAnswer::Canonical), }); @@ -3350,16 +2606,12 @@ fn float_call_of( let answer = f .float_fmt() .and_then(|fmt| nan::function_answer(op, fast, every_flag(fmf), fmt)); - // Native device maths' fast quotient is the device's, NaN included. - let native_quotient = facts.native && matches!(op, FloatFn::FastTanh { .. }); - let metal_nans = f.float_fmt().is_some_and(|fmt| op.metal_nans(fmt)) && !native_quotient; + let metal_nans = f.float_fmt().is_some_and(|fmt| op.metal_nans(fmt)); let nan = answer.filter(|_| !metal_nans); - // A function whose denormals Metal's table reads ([`denormal::coverage`]) reads them as - // Metal does: the device's, where the profile states it does, else flushed - // ([`with_denormals`]). So do Metal's fast `sinpi`, `cospi` and `tanpi` (a - // denormal operand read as a zero, no denormal answer): the routines read the operand by - // `denormal::operand`, and the device's form where the profile's functions are Metal's reads - // it as `select_float_fn` says. Native device maths records the note ([`function_notes`]). + // A function whose denormals Metal's table reads ([`denormal::coverage`]), and Metal's fast + // `sinpi`, `cospi` and `tanpi` where the device's functions are Metal's, are noted where the + // device's reading is left ([`call_coverage`], [`float_call`]); the device's instruction for + // one of Metal's functions records its denormals itself ([`function_notes`]). let fast_pi = matches!( op, FloatFn::FastSinPi | FloatFn::FastCosPi | FloatFn::FastTanPi @@ -3368,7 +2620,7 @@ fn float_call_of( op, fast, f, - (metal_functions, facts.native, facts.native_order), + metal_functions, ( !op.metal_denormals() && denormal::coverage(op).is_none() && !fast_pi, !metal_nans && answer.is_none(), @@ -3506,23 +2758,17 @@ pub(super) fn select_sincos( .float_fmt() .and_then(|fmt| nan::function_answer(op, symbol_fast, every_flag(call.fmf), fmt)); let metal_nans = f.float_fmt().is_some_and(|fmt| op.metal_nans(fmt)); - let native = cx.profile.fields().float_functions == FloatFunctions::Native; - let native_order = cx.profile.fields().rounding_order == RoundingOrderRoute::Native; let notes = function_notes( op, fast, f, - (metal_functions, native, native_order), + metal_functions, (!op.metal_denormals(), !metal_nans && answer.is_none()), ); record(cx, notes); let observed = stored || cx.nan_payload_observed(at); note_native_nan(cx, answer.filter(|_| !metal_nans)); *slot = answer.filter(|a| !metal_nans && !a.left_to(nan::encoding(cx.profile)) && observed); - cx.families - .arith - .libm_uses - .extend(libm::uses(op, f).iter().copied()); } fp_env(cx, call.fmf, f); let align = cx @@ -3776,25 +3022,11 @@ pub fn emit( Ok(()) } -/// The math-library routines of the entry being emitted. -pub(crate) fn lib<'a>(cx: &EmitCx<'a>) -> libm::Lib<'a> { +/// 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; - let funcs = &cx.decl.families.arith.libm; - let lib = if arith.native { - libm::Lib::native(funcs) - } else { - libm::Lib::new(arith.metal_functions, funcs) - }; - lib.with_min_max(arith.device_min_max || arith.native_min_max) - .with_native_order(arith.native_order) -} - -/// The function of the plan's fast division routine `r`. -fn fast_division(cx: &mut EmitCx<'_>, r: math::FastDivision) -> BResult { - match cx.decl.families.arith.fast.get(&r) { - Some(id) => Ok(*id), - None => Err(cx.fail("a fast division whose routine is not declared")), - } + libm::Lib::new(arith.metal_functions, cx.decl.families.arith.fmod) + .with_min_max(arith.device_min_max || arith.native_min_max) } /// The operands strategy `s` reads (a prefix of the instruction's; all when `None`). @@ -3830,7 +3062,7 @@ fn arity(s: &ArithStrategy) -> Option { | S::Member { .. } => Some(0), S::Chunked { parts, .. } => parts.first().and_then(|(_, p)| arity(p)), S::Wide(w) => w.arity(), - S::Nan { of, .. } | S::Denormals { of, .. } | S::TinyProduct { of, .. } => arity(of), + S::Nan { of, .. } => arity(of), _ => None, } } @@ -3866,33 +3098,6 @@ fn value( let test = nan::NanTest::for_modes(&cx.plan.families.arith.modes); nan::select(fb, *form, *answer, test, r, xs.first().copied())? } - S::Denormals { - of, - form, - out, - flush, - } => { - let mut ys = xs.to_vec(); - for (i, y) in ys.iter_mut().enumerate() { - if flush.operand(i) { - *y = denormal::flush(fb, *form, *y)?; - } - } - let r = value(cx, fb, of, &ys)?; - if flush.result { - denormal::flush(fb, *out, r)? - } else { - r - } - } - S::TinyProduct { of, form, check } => { - let r = value(cx, fb, of, xs)?; - let ab = match xs { - [a, b, ..] => [*a, *b], - _ => return Err(cx.fail("a product without its operands")), - }; - denormal::tiny_product(fb, *form, ab, r, *check)? - } S::ChunkedDot { lanes, elem, @@ -3902,21 +3107,10 @@ fn value( lanes, elem, fma: f, - flush, - reads, - tiny, } => { - let routine = match f.routine() { - Some(r) => match cx.decl.families.arith.fmas.get(&r) { - Some(id) => Some(*id), - None => return Err(cx.fail("a dot whose fused multiply-add is not declared")), - }, - None => None, - }; - let fma = - |fb: &mut FunctionBuilder<'_>, args: &[SValue]| fma::emit(fb, *f, args, routine); + let fma = |fb: &mut FunctionBuilder<'_>, args: &[SValue]| fma::emit(fb, *f, args); let xy = [a(cx, 0)?, a(cx, 1)?]; - chunk::dot_chain(fb, *lanes, *elem, xy, &fma, (*flush, *tiny), *reads)? + chunk::dot_chain(fb, *lanes, *elem, xy, &fma)? } S::LaneExtract { src, at, index } => chunk::extract(fb, *src, *at, *index, xs)?, S::LaneInsert { dst, at, index } => chunk::insert(fb, *dst, *at, *index, xs)?, @@ -3954,40 +3148,14 @@ fn value( let (p, q) = (a(cx, 0)?, a(cx, 1)?); ops::f16_binary(fb, *op, form.lanes, p, q)? } - S::FastDivide { routine, .. } => { + S::FastDivide { contract, .. } => { let (p, q) = (a(cx, 0)?, a(cx, 1)?); - if cx.plan.families.arith.device_quotient() { - math::device_fast_division(fb, *routine, p, q)? - } else { - let id = fast_division(cx, *routine)?; - math::call_fast_division(fb, id, p, q)? - } + fb.binary_with(crate::spirv::ir::BinOp::FDiv, p, q, *contract)? } S::NativeDivide { form } => { let (p, q) = (a(cx, 0)?, a(cx, 1)?); divide::native(fb, *form, p, q)? } - S::PreciseDivide { form, routine } => { - let (p, q) = (a(cx, 0)?, a(cx, 1)?); - let Some(id) = cx.decl.families.arith.precise.get(routine).copied() else { - return Err(cx.fail("a precise division whose routine is not declared")); - }; - divide::emit(fb, *form, p, q, id)? - } - S::Remainder { - form, - routine, - flush, - } => { - let (x, y) = (a(cx, 0)?, a(cx, 1)?); - let Some(id) = cx.decl.families.arith.precise.get(routine).copied() else { - return Err(cx.fail("a remainder whose division routine is not declared")); - }; - let divide = |fb: &mut FunctionBuilder<'_>, p: SValue, q: SValue| { - divide::emit(fb, *form, p, q, id) - }; - math::metal_frem(fb, *form, (x, y), ÷, *flush)? - } S::FNeg { form, bits } => { let p = a(cx, 0)?; if *bits { @@ -4089,94 +3257,23 @@ fn value( }; wide::emit(fb, w, xs, routine)? } - S::FloatFn { - f: op @ FloatFn::FastTanh { reciprocal }, - form, - .. - } => { - let routine = math::FastDivision::new(*form, *reciprocal, Contraction::Forbidden); - let id = fast_division(cx, routine)?; - let x = a(cx, 0)?; - let divide = |fb: &mut FunctionBuilder<'_>, p: SValue, q: SValue| { - math::call_fast_division(fb, id, p, q) - }; - let lib = lib(cx); - math::fast_tanh(fb, *op, *form, x, &lib, ÷)? - } - // Metal's formula divides by the fast division's routine. - S::FloatFn { - f: op @ FloatFn::FastAtanh { reciprocal }, - form, - .. - } => { - let routine = math::FastDivision::new(*form, *reciprocal, Contraction::Forbidden); - let id = fast_division(cx, routine)?; - let x = a(cx, 0)?; - let divide = |fb: &mut FunctionBuilder<'_>, p: SValue, q: SValue| { - math::call_fast_division(fb, id, p, q) - }; - let lib = lib(cx); - math::fast_atanh(fb, *op, *form, x, &lib, ÷)? - } - // Apple's formula divides by the fast division's routine. - S::FloatFn { - f: FloatFn::FastTan { reciprocal }, - form, - .. - } => { - let routine = math::FastDivision::new(*form, *reciprocal, Contraction::Forbidden); - let id = fast_division(cx, routine)?; - let x = a(cx, 0)?; - let divide = |fb: &mut FunctionBuilder<'_>, p: SValue, q: SValue| { - math::call_fast_division(fb, id, p, q) - }; - let lib = lib(cx); - math::fast_tan(fb, *form, x, &lib, ÷)? - } S::FloatFn { f, form, contract } => { let test = nan::NanTest::for_modes(&cx.plan.families.arith.modes); let lib = lib(cx); math::float_fn(fb, *f, *form, *contract, test, xs, &lib)? } - S::Fma(f) => { - let routine = match f.routine() { - Some(r) => match cx.decl.families.arith.fmas.get(&r) { - Some(id) => Some(*id), - None => { - return Err(cx.fail("a fused multiply-add whose routine is not declared")) - } - }, - None => None, - }; - fma::emit(fb, *f, xs, routine)? - } + S::Fma(f) => fma::emit(fb, *f, xs)?, S::Fused { fma, a, b, c, negate, - flush, inner, } => { - let routine = match fma.routine() { - Some(r) => match cx.decl.families.arith.fmas.get(&r) { - Some(id) => Some(*id), - None => return Err(cx.fail("a fused addition whose routine is not declared")), - }, - None => None, - }; - let mut xyz = [ - cx.operand(fb, *a)?, - cx.operand(fb, *b)?, - cx.operand(fb, *c)?, - ]; - for (i, v) in xyz.iter_mut().enumerate() { - if flush.operand(i) { - *v = denormal::flush(fb, fma.form, *v)?; - } - } - let [mut x, y, mut z] = xyz; + let mut x = cx.operand(fb, *a)?; + let y = cx.operand(fb, *b)?; + let mut z = cx.operand(fb, *c)?; match negate { contract::Negate::Neither => {} contract::Negate::Product => x = fb.unary(UnOp::FNegate, x)?, @@ -4184,87 +3281,41 @@ fn value( } // A chain's links, innermost first, each one's value the next one's addend. for link in inner.iter().rev() { - let mut ab = [cx.operand(fb, link.a)?, cx.operand(fb, link.b)?]; - for (i, v) in ab.iter_mut().enumerate() { - if link.flush.operand(i) { - *v = denormal::flush(fb, fma.form, *v)?; - } - } - let [mut p, q] = ab; + let mut p = cx.operand(fb, link.a)?; + let q = cx.operand(fb, link.b)?; if link.negate { p = fb.unary(UnOp::FNegate, p)?; } - z = fma::emit(fb, *fma, &[p, q, z], routine)?; - if link.flush.result { - z = denormal::flush(fb, fma.form, z)?; - } - } - let r = fma::emit(fb, *fma, &[x, y, z], routine)?; - if flush.result { - denormal::flush(fb, fma.form, r)? - } else { - r + z = fma::emit(fb, *fma, &[p, q, z])?; } + fma::emit(fb, *fma, &[x, y, z])? } - S::FastFmod { fma: f, reciprocal } => { - let routine = match f.routine() { - Some(r) => match cx.decl.families.arith.fmas.get(&r) { - Some(id) => Some(*id), - None => { - return Err(cx.fail("a fast fmod whose fused multiply-add is not declared")) - } - }, - None => None, - }; + S::FastFmod { fma: f } => { let (x, y) = match xs { [x, y, ..] => (*x, *y), _ => return Err(cx.fail("a fast fmod without its operands")), }; - let fma = - |fb: &mut FunctionBuilder<'_>, args: &[SValue]| fma::emit(fb, *f, args, routine); - let division = math::FastDivision::new(f.form, *reciprocal, Contraction::Forbidden); - let id = fast_division(cx, division)?; + let fma = |fb: &mut FunctionBuilder<'_>, args: &[SValue]| fma::emit(fb, *f, args); let divide = |fb: &mut FunctionBuilder<'_>, p: SValue, q: SValue| { - math::call_fast_division(fb, id, p, q) + fb.binary_with(crate::spirv::ir::BinOp::FDiv, p, q, Contraction::Forbidden) }; math::fast_fmod(fb, x, y, ÷, &fma)? } - S::Mix { fma: f, flush } => { - let routine = match f.routine() { - Some(r) => match cx.decl.families.arith.fmas.get(&r) { - Some(id) => Some(*id), - None => return Err(cx.fail("a mix whose fused multiply-add is not declared")), - }, - None => None, - }; + S::Mix { fma: f } => { let xyt = match xs { [x, y, t, ..] => [*x, *y, *t], _ => return Err(cx.fail("a mix without its operands")), }; - let fma = - |fb: &mut FunctionBuilder<'_>, args: &[SValue]| fma::emit(fb, *f, args, routine); - math::metal_mix(fb, f.form, xyt, &fma, *flush)? + let fma = |fb: &mut FunctionBuilder<'_>, args: &[SValue]| fma::emit(fb, *f, args); + math::metal_mix(fb, f.form, xyt, &fma)? } - S::Dot { - fma: f, - form, - flush, - tiny, - } => { - let routine = match f.routine() { - Some(r) => match cx.decl.families.arith.fmas.get(&r) { - Some(id) => Some(*id), - None => return Err(cx.fail("a dot whose fused multiply-add is not declared")), - }, - None => None, - }; + S::Dot { fma: f, form } => { let xy = match xs { [x, y, ..] => [*x, *y], _ => return Err(cx.fail("a dot without its operands")), }; - let fma = - |fb: &mut FunctionBuilder<'_>, args: &[SValue]| fma::emit(fb, *f, args, routine); - math::metal_dot(fb, *form, xy, &fma, (*flush, *tiny))? + let fma = |fb: &mut FunctionBuilder<'_>, args: &[SValue]| fma::emit(fb, *f, args); + math::metal_dot(fb, *form, xy, &fma)? } S::Convert { kind, from, to } => { let p = a(cx, 0)?; diff --git a/crates/metal2vulkan/src/lower/arith/nan.rs b/crates/metal2vulkan/src/lower/arith/nan.rs index aa7978c43..73142354f 100644 --- a/crates/metal2vulkan/src/lower/arith/nan.rs +++ b/crates/metal2vulkan/src/lower/arith/nan.rs @@ -45,7 +45,6 @@ use crate::budget::Meter; use crate::device::profile::NanEncoding; use crate::device::DeviceProfile; use crate::error::Error; -use crate::lower::arith::divide::Reciprocal; use crate::lower::arith::legal::{FloatFmt, Form, Held}; use crate::lower::arith::math::FloatFn; use crate::lower::arith::narrow::u32_form; @@ -165,7 +164,7 @@ pub fn function_answer(op: FloatFn, fast: bool, flagged: bool, fmt: FloatFmt) -> precise_of(op) } else { // The reciprocal a refinement divides by does not decide its NaN. - super::refine_float(op, true, FastMath::NONE, f32_scalar(), Reciprocal::Device) + super::refine_float(op, true, FastMath::NONE, f32_scalar()) }; (measured(other, !fast) == Some(here)).then_some(here) } @@ -183,12 +182,12 @@ fn f32_scalar() -> Form { fn precise_of(op: FloatFn) -> FloatFn { use FloatFn as F; match op { - F::FastTanh { .. } => F::Tanh, + F::FastTanh => F::Tanh, F::FastAsinh => F::Asinh, F::FastSinh => F::Sinh, F::FastCosh => F::Cosh, F::FastAcosh => F::Acosh, - F::FastAtanh { .. } => F::Atanh, + F::FastAtanh => F::Atanh, F::FastExp10 => F::Exp10, F::FastLog10 => F::Log10, F::FastFract { .. } => F::Fract, @@ -202,7 +201,7 @@ fn precise_of(op: FloatFn) -> FloatFn { F::FastLog2 => F::Log2, F::FastPowr => F::Powr, F::FastAtan2 { .. } => F::Atan2, - F::FastTan { .. } => F::Tan, + F::FastTan => F::Tan, F::FastAsin => F::Asin, F::FastAcos => F::Acos, F::FastAtan => F::Atan, @@ -251,9 +250,9 @@ fn measured(op: FloatFn, fast: bool) -> Option { | F::Cosh | F::FastCosh | F::Tanh - | F::FastTanh { .. } + | F::FastTanh | F::FastAsinh - | F::FastAtanh { .. } + | F::FastAtanh | F::Acosh | F::FastAcosh | F::Powr @@ -280,7 +279,7 @@ fn measured(op: FloatFn, fast: bool) -> Option { | F::FastTanPi => A::Canonical, F::Sin | F::Cos if !fast => A::Canonical, F::Tan if fast => A::Operand, - F::FastTan { .. } => A::Operand, + F::FastTan => A::Operand, F::Tan => A::Canonical, F::Asin if fast => A::DomainSign, F::FastAsin => A::DomainSign, @@ -603,7 +602,7 @@ pub fn drops_payload(e: &Entry, func: FuncId, inst: &Inst) -> bool { return true; } // The reciprocal a refinement divides by does not decide its NaN. - let op = super::refine_float(op, fast, call.fmf, f, Reciprocal::Device); + let op = super::refine_float(op, fast, call.fmf, f); matches!( function_answer(op, fast, super::every_flag(call.fmf), fmt), Some(NanAnswer::Canonical | NanAnswer::CanonicalExact) diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index b3de47f1d..07b9d10f0 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -8,7 +8,6 @@ //! behavior are skipped, so an interpreter trap is a real failure). References are written from //! the LLVM and Metal definitions in plain Rust. -use super::divide::Reciprocal; use super::legal::{f16_to_f64, f64_to_f16, FloatFmt, Form, Held}; use super::libm::Lib; use super::math::{self, ConvertKind, FloatFn, IntFn, Sign}; @@ -2514,21 +2513,17 @@ fn half_nan_answers_follow_the_measured_states() { } } -/// The float facts of a profile whose `float` fused multiply-add is `OpFmaKHR`, checked by the -/// integer routine, whose `half` one is the device's `float` `Fma`, and whose `float` functions are -/// the device's. +/// The float facts of a profile whose `float` fused multiply-add is `OpFmaKHR`, whose `half` one +/// is the device's `float` `Fma`, and whose `float` functions are the device's. const KHR_FACTS: super::FloatFacts = super::FloatFacts { routes: super::fma::Routes { float: super::fma::Route::Khr, half: super::fma::Route::Native, - tiny: Some(super::fma::Route::Soft), }, - reciprocal: super::divide::Reciprocal::Rounded, metal_functions: false, - native: false, + device_denormals: false, nan_native: false, native_min_max: false, - native_order: false, }; /// Class E: Metal's `float` `fneg` and `fabs` flip or clear the sign bit alone, a NaN's payload and @@ -2670,7 +2665,7 @@ fn nan_answers_follow_the_measured_flag_states() { .iter() .fold(FastMath::NONE, |every, (flag, _)| every.union(*flag)); let fmf = if flagged { all } else { FastMath::NONE }; - let selected = super::refine_float(op, fast, fmf, float(32), Reciprocal::Device); + let selected = super::refine_float(op, fast, fmf, float(32)); assert_eq!( function_answer(selected, fast, flagged, f32_), want, @@ -3158,27 +3153,15 @@ fn pi_scaled_functions_reduce_exactly_to_metal_answers() { } } -/// [`FloatFn::words`] bounds what `sinpi`, `cospi`, and `tanpi` emit on every form: on `float` and -/// `half` the calls of Metal's routines (the routines are charged on their own), a fast call's on -/// `float` also where the device's functions are Metal's, which is the exact reduction around the -/// device's `Sin` and `Cos`, as on a `bfloat`, which no routine answers, the axis arms and -/// `tanpi`'s quarter turns included. The module's growth over an identity kernel (with the same -/// routines) is charged in full, its constants and the `GLSL.std.450` import included. +/// [`FloatFn::words`] bounds what `sinpi`, `cospi`, and `tanpi` emit on every form: the exact +/// reduction around the device's `Sin` and `Cos`, the axis arms and `tanpi`'s quarter turns +/// included, whether or not the device's functions are Metal's. The module's growth over an +/// 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::{self, Fun, Mode}; - use std::collections::BTreeMap; - let routines = [Mode::Precise, Mode::Fast] - .map(|m| [Fun::SinPi(m), Fun::CosPi(m), Fun::TanPi(m)]) - .concat(); - let defs = |b: &mut ModuleBuilder| -> BResult> { - routines - .iter() - .map(|fun| libm::define_alone(b, *fun, false)) - .collect() - }; - let module_words = |f: Form, body: BodyCalling<'_>| { - let m = kernel_defs(&[f], f, &defs, body, false, false).expect("kernel"); + use super::libm::Mode; + let module_words = |f: Form, body: Body<'_>| { + let m = kernel(&[f], f, body).expect("kernel"); crate::spirv::serialize::serialize(m) .expect("words") .words @@ -3186,9 +3169,16 @@ fn pi_scaled_functions_stay_within_their_word_estimate() { }; let precise = [FloatFn::SinPi, FloatFn::CosPi, FloatFn::TanPi]; let fast = [FloatFn::FastSinPi, FloatFn::FastCosPi, FloatFn::FastTanPi]; - for f in [float(32), vec(float(32), 4), float(16), vec(float(16), 4)] { - let bare = module_words(f, &|_, x, _| Ok(x[0])); - // `refine_float` gives a `half` call no fast function. + for f in [ + float(32), + vec(float(32), 4), + float(16), + vec(float(16), 4), + bfloat(), + vec(bfloat(), 4), + ] { + let bare = module_words(f, &|_, x| Ok(x[0])); + // `refine_float` gives a narrow call no fast function. let calls = if f.float_fmt() == Some(FloatFmt::F32) { [precise, fast].concat() } else { @@ -3196,12 +3186,7 @@ fn pi_scaled_functions_stay_within_their_word_estimate() { }; for g in calls { for metal in [None, Some(Mode::Fast), Some(Mode::Precise)] { - let used = module_words(f, &|fb, x, funcs| { - let map: BTreeMap = routines - .iter() - .copied() - .zip(funcs.iter().copied()) - .collect(); + let used = module_words(f, &|fb, x| { math::float_fn( fb, g, @@ -3209,7 +3194,7 @@ fn pi_scaled_functions_stay_within_their_word_estimate() { Contraction::Allowed, NanTest::IsNan, x, - &Lib::new(metal, &map), + &Lib::new(metal, None), ) }); let (emitted, bound) = (used - bare, g.words(f) as usize); @@ -3220,69 +3205,31 @@ fn pi_scaled_functions_stay_within_their_word_estimate() { } } } - let module_words = |f: Form, body: Body<'_>| { - let m = kernel(&[f], f, body).expect("kernel"); - crate::spirv::serialize::serialize(m) - .expect("words") - .words - .len() - }; - for f in [bfloat(), vec(bfloat(), 4)] { - let bare = module_words(f, &|_, x| Ok(x[0])); - for g in [FloatFn::SinPi, FloatFn::CosPi, FloatFn::TanPi] { - let used = module_words(f, &|fb, x| { - math::float_fn( - fb, - g, - f, - Contraction::Allowed, - NanTest::IsNan, - 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)`, -/// divided as Metal's fast division (`(t - 1) · (1 / (t + 1))`, the reciprocal flushed past -/// `2^126`). 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` (where `t + 1` is above `2^126` and the reciprocal flushes) is 0, `x = 44.4` -/// (where `t` overflows) is NaN, and `x = -100` (where `t` is 0) is -1. +/// 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); 5] = [ + let metal: [(f32, u32); 4] = [ (0.0, 0x0000_0000), (43.0, 0x3F80_0000), - (44.0, 0x0000_0000), (44.4, 0x7FC0_0000), (-100.0, 0xBF80_0000), ]; - // Metal's fast quotient: the numerator times the reciprocal, flushed past 2^126. - let quotient = |t: f32| { - let den = t + 1.0; - let r = if den.abs() > 2f32.powi(126) { - 0.0 - } else { - 1.0 / den - }; - (t - 1.0) * r - }; + let quotient = |t: f32| (t - 1.0) / (t + 1.0); let mut xs: Vec = metal.iter().map(|m| m.0).collect(); - xs.extend([0.5, -3.75, 5.0, 1e-3, -1e-3, 20.0, -44.4, 43.7]); + 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())]]) @@ -3293,24 +3240,7 @@ fn fast_tanh_is_the_fast_math_formula() { f, &|fb, t| { let divide = |fb: &mut FunctionBuilder<'_>, x: Value, y: Value| { - math::fast_divide(fb, f, x, y, Contraction::Forbidden, Reciprocal::Device) - }; - 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, - ); - check( - "fast tanh quotient f32, the reciprocal rounded", - &[f], - f, - &|fb, t| { - let divide = |fb: &mut FunctionBuilder<'_>, x: Value, y: Value| { - math::fast_divide(fb, f, x, y, Contraction::Forbidden, Reciprocal::Rounded) + fb.binary_with(BinOp::FDiv, x, y, Contraction::Forbidden) }; math::tanh_of_exp(fb, f, ÷, t[0]) }, @@ -3329,8 +3259,9 @@ fn fast_tanh_is_the_fast_math_formula() { got.to_bits() ); } - // x = 44: t + 1 > 2^126, where the reciprocal flushes. + // 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 @@ -3347,9 +3278,8 @@ fn fast_tanh_is_the_fast_math_formula() { #[test] fn fast_variants_refine_float_functions() { use crate::air::ir::FastMath; - let refine = |op: FloatFn, fast: bool, fmf: FastMath, f: Form| { - super::refine_float(op, fast, fmf, f, Reciprocal::Rounded) - }; + let refine = + |op: FloatFn, fast: bool, fmf: FastMath, f: Form| super::refine_float(op, fast, fmf, f); let every = FastMath::ALL .iter() .fold(FastMath::NONE, |all, (flag, _)| all.union(*flag)); @@ -3357,12 +3287,7 @@ fn fast_variants_refine_float_functions() { let f32_ = float(32); for fmf in [FastMath::NONE, some, every] { for (op, fast) in [ - ( - FloatFn::Tanh, - FloatFn::FastTanh { - reciprocal: Reciprocal::Rounded, - }, - ), + (FloatFn::Tanh, FloatFn::FastTanh), ( FloatFn::Asinh, if fmf == every { @@ -3381,12 +3306,7 @@ fn fast_variants_refine_float_functions() { (FloatFn::Pow, FloatFn::FastPow), (FloatFn::Sin, FloatFn::FastSin), (FloatFn::Cos, FloatFn::FastCos), - ( - FloatFn::Tan, - FloatFn::FastTan { - reciprocal: Reciprocal::Rounded, - }, - ), + (FloatFn::Tan, FloatFn::FastTan), (FloatFn::Asin, FloatFn::FastAsin), (FloatFn::Acos, FloatFn::FastAcos), (FloatFn::Atan, FloatFn::FastAtan), @@ -3433,27 +3353,8 @@ fn fast_variants_refine_float_functions() { assert_eq!(refine(op, false, fmf, bfloat()), op); } } - // The fast division's reciprocal is the profile's. - let device = super::refine_float( - FloatFn::Tanh, - true, - FastMath::NONE, - f32_, - Reciprocal::Device, - ); - assert_eq!( - device, - FloatFn::FastTanh { - reciprocal: Reciprocal::Device - } - ); - assert!(device.divides() && !FloatFn::Tanh.divides()); - assert_eq!( - super::refine_float(FloatFn::Tan, true, FastMath::NONE, f32_, Reciprocal::Device), - FloatFn::FastTan { - reciprocal: Reciprocal::Device - } - ); + assert!(FloatFn::FastTanh.divides() && !FloatFn::Tanh.divides()); + assert!(FloatFn::FastTan.divides()); for reciprocal_flushed in [false, true] { assert!(FloatFn::FastAtan2 { reciprocal_flushed }.divides()); } @@ -3461,7 +3362,7 @@ fn fast_variants_refine_float_functions() { } /// The transcendental and device-precision functions build and pass L3 (the interpreter does not -/// model them), `fast::tanh` with its division routine; `ldexp` and `dot` run: part `part` of `of` +/// model them), `fast::tanh` among them; `ldexp` and `dot` run: part `part` of `of` /// of the checks. fn device_precision_float_functions(part: usize, of: usize) { let device = [ @@ -3481,9 +3382,7 @@ fn device_precision_float_functions(part: usize, of: usize) { FloatFn::FastSin, FloatFn::FastCos, FloatFn::Tan, - FloatFn::FastTan { - reciprocal: Reciprocal::Device, - }, + FloatFn::FastTan, FloatFn::Asin, FloatFn::FastAsin, FloatFn::Acos, @@ -3493,6 +3392,7 @@ fn device_precision_float_functions(part: usize, of: usize) { FloatFn::Sinh, FloatFn::Cosh, FloatFn::Tanh, + FloatFn::FastTanh, FloatFn::Asinh, FloatFn::FastAsinh, FloatFn::Acosh, @@ -3537,36 +3437,6 @@ fn device_precision_float_functions(part: usize, of: usize) { })); } } - for lanes in [1u8, 3] { - let f = vec(float(32), lanes); - for reciprocal in [Reciprocal::Device, Reciprocal::Rounded] { - checks.push(Box::new(move || { - let routine = math::FastDivision::new(f, reciprocal, Contraction::Forbidden); - let m = kernel_defs( - &[f], - f, - &|b| Ok(vec![math::define_fast_division(b, routine)?]), - &|fb, x, funcs| { - let divide = |fb: &mut FunctionBuilder<'_>, p: Value, q: Value| { - math::call_fast_division(fb, funcs[0], p, q) - }; - math::fast_tanh( - fb, - FloatFn::FastTanh { reciprocal }, - f, - x[0], - &Lib::instructions(), - ÷, - ) - }, - false, - false, - ) - .unwrap_or_else(|e| panic!("fast tanh {reciprocal:?}: {e:?}")); - assert_valid(m, &wide_profile()); - })); - } - } checks.push(Box::new(|| { let f = float(32); let cases: Vec = [(1.5f32, 3u32), (-0.75, 0xFFFF_FFFE), (1.0, 127), (3.0, 0)] @@ -4109,7 +3979,6 @@ mod float_texel; mod fused; mod half_texel; mod libm; -mod libm_exp; mod narrow; mod round_texel; mod snapshot_codes; diff --git a/crates/metal2vulkan/src/lower/arith/tests/atan2.rs b/crates/metal2vulkan/src/lower/arith/tests/atan2.rs index 5cfe06043..4c44df5db 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/atan2.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/atan2.rs @@ -579,98 +579,6 @@ fn fast_atan2_answers_as_metal_at_every_special_operand() { } } -/// Metal's `fast::atan2(y, x)` with the translation's routines (Metal's fast `atan` and its -/// reciprocal) at pairs of our probe (the M4) where Metal's word is not the correctly rounded -/// one: `atan(y · rcp(x))`, turned by `±RN(π)` toward a negative `x`, bit for bit, in both of its -/// compiles. -#[test] -fn fast_atan2_answers_metals_words_through_its_reciprocal() { - use crate::lower::arith::libm as routines; - use std::collections::BTreeMap; - let words: [(u64, u64, u64); 32] = [ - (0xC19756F4, 0xBCB32371, 0xBFC935BC), - (0x3EF2780E, 0xB5B2A829, 0x3FC90FF3), - (0x3E6BF7B9, 0xBD0F72FB, 0x3FDC5E1B), - (0xBD4181FA, 0x3D17DFBB, 0xBF67C5E7), - (0x3C548FED, 0x3B64B74E, 0x3FA76D21), - (0xC0DD1B6B, 0xBD1D9C98, 0xBFC9C657), - (0x3C0A99D9, 0x3F1F346A, 0x3C5EDB04), - (0xBC409105, 0x421B1F31, 0xB99EE5D1), - (0xBEBB68F2, 0x41595AE5, 0xBCDCAD66), - (0x3D20648F, 0x42BFB421, 0x39D6300B), - (0x415087E1, 0x75D05A1E, 0x0B001C1C), - (0x3E53970E, 0x52C98B34, 0x2B066160), - (0xC0BEA79E, 0x4D39DF1E, 0xB3034B3F), - (0x4020F92A, 0x6CAD5F44, 0x12EDB124), - (0xBEB14461, 0x535AFD42, 0xAACF39F9), - (0xC2D8CD64, 0x3F5CDE07, 0xBFC80B10), - (0xBFD8F5D4, 0xC187265C, 0xC042A97B), - (0x4165ED74, 0xC03D4866, 0x3FE30AE0), - (0xBF95112C, 0x4139BD55, 0xBDCCC52A), - (0x40E2F5D5, 0x410FA6B3, 0x3F2B2910), - (0x41070303, 0xBF802825, 0x3FD82DCC), - (0x409EF0B0, 0x41187E78, 0x3EF5F8B0), - (0x41420F9D, 0xC0E8502E, 0x40070CC5), - (0x3DFE923E, 0xC14B9710, 0x40486FCF), - (0x40596E18, 0x42226465, 0x3DAAFBBB), - (0x4855E587, 0x3F7F47CE, 0x3FC90FB5), - (0xC180A967, 0x3F828DF3, 0xBFC0F482), - (0xC8F92619, 0x3F7FFC82, 0xBFC90FCB), - (0xC9A00AEE, 0x3F4FAF31, 0xBFC90FD6), - (0xC50006E2, 0x3F80009A, 0xBFC8FFDC), - (0xC06A090F, 0x3F80000D, 0xBFA6E4DD), - (0x20E9F44C, 0x2E7C8B9B, 0x31ED2795), - ]; - let f = float(32); - for reciprocal_flushed in [false, true] { - let op = FloatFn::FastAtan2 { reciprocal_flushed }; - let funs = routines::uses(op, f); - let m = kernel_defs( - &[f, f], - f, - &|b| { - funs.iter() - .map(|fun| routines::define_alone(b, *fun, false)) - .collect() - }, - &|fb, x, ids| { - let map: BTreeMap = - funs.iter().copied().zip(ids.iter().copied()).collect(); - math::float_fn( - fb, - op, - f, - Contraction::Forbidden, - NanTest::IsNan, - x, - &routines::Lib::new(None, &map), - ) - }, - false, - false, - ) - .expect("build"); - let cases: Vec = words - .iter() - .map(|(y, x, _)| vec![vec![*y], vec![*x]]) - .collect(); - check_module( - &format!("fast atan2 (reciprocal flushed {reciprocal_flushed}) through the routines"), - m, - &[f, f], - f, - &cases, - &|c| { - words - .iter() - .find(|(y, x, _)| (*y, *x) == (c[0][0], c[1][0])) - .map(|(_, _, w)| vec![*w]) - }, - &|g, w| g == 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. /// The module's growth over an identity kernel is charged in full, its constants and the diff --git a/crates/metal2vulkan/src/lower/arith/tests/divide.rs b/crates/metal2vulkan/src/lower/arith/tests/divide.rs index a0445c207..46deabb8b 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/divide.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/divide.rs @@ -1,616 +1,67 @@ -//! Metal's precise division: both routine paths against Metal's quotient, on the interpreter, with -//! the device's estimate exact and perturbed to the edge of Vulkan's 2.5 ulp; and the reciprocal -//! step the fused path's proof rests on, over every significand. -//! -//! The reference is Metal's, as the probe read it: an `f32` denormal operand is a zero of its sign, -//! the quotient is rounded once to nearest even to 24 bits with an unbounded exponent (the host's -//! `f64` quotient of two `f32` values is never within an `f64` ulp of an `f32` rounding midpoint -//! without being one, so rounding it to 24 bits rounds once), a result below the smallest normal -//! after that rounding is a zero of its sign (probe case c10cba13), and a NaN is `0x7FC00000`. +//! Metal's precise division by the device's `OpFDiv` ([`divide::native`]), on the interpreter, +//! whose division is correctly rounded. use super::*; -use crate::lower::arith::divide::{self, Path, Rough, Routine}; -use crate::lower::arith::legal::{f16_to_f64, f64_to_f16}; -use crate::lower::arith::narrow; +use crate::lower::arith::divide; -/// `float` lanes of `lanes` lanes. -fn floats(lanes: u8) -> Form { - vec(float(32), lanes) -} - -/// An `f32` denormal as a zero of its sign. -fn ftz(x: u64) -> u64 { - if x & 0x7F80_0000 == 0 { - x & 0x8000_0000 - } else { - x - } -} - -/// Metal's precise quotient of `f32` bits `x` and `y`. -fn metal_div32(x: u64, y: u64) -> u64 { - let (x, y) = (ftz(x), ftz(y)); - let q = f64::from(f32v(x)) / f64::from(f32v(y)); - if q.is_nan() { - return 0x7FC0_0000; - } - let smallest = 2f64.powi(-126); - if q != 0.0 && q.abs() < smallest { - // Rounded to 24 bits in `f32`'s normal range (the scaling is exact both ways), then - // flushed unless the rounding reached the smallest normal. - let scale = 2f64.powi(200); - let rounded = f64::from((q * scale) as f32) / scale; - if rounded.abs() < smallest { - return u64::from(q.is_sign_negative()) << 31; - } - return u64::from((rounded as f32).to_bits()); - } - u64::from((q as f32).to_bits()) -} - -/// `f32` bits of sign `s`, biased exponent `e`, and significand field `m`. -pub(super) fn bits(s: u64, e: u64, m: u64) -> u64 { - (s << 31) | (e << 23) | m -} - -/// Operand pairs: specials, every class against every other, the flush boundary (the quotient -/// `2^-126 - 2^-150`, which has 24 bits and is flushed although the denormal grid would round it -/// up to the smallest normal, and its neighbors), overflow, all-ones significands, divisors past -/// `2^126`, the edges of the range the fused path once kept to (`[2^-31, 2^33)`), divisors near -/// `2^40` (the probe's timing), quotients near rounding midpoints at moderate exponents and -/// at every exponent (where the fused path's exponent arithmetic decides the overflow and the -/// flush), and random bits. -fn pairs32() -> Vec<[u64; 2]> { - let mut rng = Rng(0x2790_D1F1_0000_0001); - let specials: Vec = [ - 0, - bits(1, 0, 0), - bits(0, 0, 1), - bits(1, 0, 0x7F_FFFF), - bits(0, 1, 0), - bits(0, 127, 0), - bits(1, 127, 0x40_0000), - bits(0, 127, 0x7F_FFFF), - bits(0, 254, 0x7F_FFFF), - bits(0, 253, 0), - bits(0, 254, 0), - bits(0, 95, 0x7F_FFFF), - bits(0, 96, 0), - bits(0, 159, 0x7F_FFFF), - bits(0, 160, 0), - bits(0, 255, 0), - bits(1, 255, 0), - bits(0, 255, 1), - 0x7FC0_0000, - ] - .to_vec(); - let mut out = Vec::new(); - for &x in &specials { - for &y in &specials { - out.push([x, y]); - } - } - // (2 - 2^-23) * 2^a over 2^(a + 127): exactly 2^-126 - 2^-150, either sign. - for a in [0u64, 1, 60, 126] { - for s in 0..4u64 { - out.push([bits(s & 1, 127 - a, 0x7F_FFFF), bits(s >> 1, 254 - a, 0)]); - // Just below and above: a numerator one ulp off. - out.push([bits(s & 1, 127 - a, 0x7F_FFFE), bits(s >> 1, 254 - a, 0)]); - out.push([bits(s & 1, 128 - a, 0), bits(s >> 1, 254 - a, 0)]); - } - } - // Overflow and the largest finite quotient. - out.push([bits(0, 254, 0x7F_FFFF), bits(0, 126, 0x7F_FFFF)]); - out.push([bits(0, 254, 0x7F_FFFF), bits(0, 127, 0)]); - out.push([bits(1, 254, 0x40_0000), bits(0, 126, 0)]); - // Quotients near a rounding midpoint: X * 2^t / Y within 2^-10 of a half. - let mut near = 0; - while near < 96 { - let (mx, my) = (rng.next() & 0x7F_FFFF, rng.next() & 0x7F_FFFF); - let (big_x, big_y) = (mx | 0x80_0000, my | 0x80_0000); - let t = if big_x >= big_y { 23 } else { 24 }; - let r = (big_x << (t + 1)) % (2 * big_y); - if r.abs_diff(big_y) * 1024 >= 2 * big_y { - continue; - } - near += 1; - let (ex, ey) = (64 + rng.next() % 128, 64 + rng.next() % 128); - out.push([bits(rng.next() & 1, ex, mx), bits(rng.next() & 1, ey, my)]); - } - // All-ones divisors and random operands, at moderate exponents. - for _ in 0..96 { - let ex = 96 + rng.next() % 64; - let ey = 96 + rng.next() % 64; - out.push([ - bits(rng.next() & 1, ex, rng.next() & 0x7F_FFFF), - bits(rng.next() & 1, ey, 0x7F_FFFF), - ]); - out.push([ - bits(rng.next() & 1, ex, rng.next() & 0x7F_FFFF), - bits(rng.next() & 1, ey, rng.next() & 0x7F_FFFF), - ]); - } - // Random bit patterns over the whole range. - for _ in 0..256 { - out.push([rng.next() & 0xFFFF_FFFF, rng.next() & 0xFFFF_FFFF]); - } - // Divisors near 2^40 (all-ones and random significands) over random numerators. - for _ in 0..32 { - let y = bits(rng.next() & 1, 166 + rng.next() % 2, rng.next() & 0x7F_FFFF); - out.push([rng.next() & 0xFFFF_FFFF, y]); - out.push([rng.next() & 0xFFFF_FFFF, bits(0, 166, 0x7F_FFFF)]); - } - // Quotients near a rounding midpoint at every exponent: past the largest finite, below the - // smallest normal, and across both. - let mut near = 0; - while near < 192 { - let (mx, my) = (rng.next() & 0x7F_FFFF, rng.next() & 0x7F_FFFF); - let (big_x, big_y) = (mx | 0x80_0000, my | 0x80_0000); - let t = if big_x >= big_y { 23 } else { 24 }; - let r = (big_x << (t + 1)) % (2 * big_y); - if r.abs_diff(big_y) * 1024 >= 2 * big_y { - continue; - } - near += 1; - let (ex, ey) = (1 + rng.next() % 254, 1 + rng.next() % 254); - out.push([bits(rng.next() & 1, ex, mx), bits(rng.next() & 1, ey, my)]); - } - out -} - -/// The cases of `pairs` in lanes of `lanes`. -fn lane_cases(pairs: &[[u64; 2]], lanes: u8) -> Vec { - let n = usize::from(lanes); - (0..pairs.len()) - .step_by(n) - .map(|i| { - (0..2) - .map(|k| (0..n).map(|l| pairs[(i + l) % pairs.len()][k]).collect()) - .collect() - }) - .collect() -} - -/// The device's quotient of `float` lanes (form `f`) moved by 0, +1, -2, or -1 ulp (by the -/// divisor's low bits): within 2.5 ulp of the exact one, as Vulkan allows, also where the move -/// crosses a power of two. -pub(super) fn perturbed( - fb: &mut FunctionBuilder<'_>, - f: Form, - x: Value, - y: Value, -) -> BResult { - let u = super::super::narrow::u32_form(f); - let ut = ops::ty(fb, u)?; - let ft = ops::ty(fb, f)?; - let q = fb.binary(BinOp::FDiv, x, y)?; - let qb = fb.convert(ConvOp::Bitcast, q, ut)?; - let yb = fb.convert(ConvOp::Bitcast, y, ut)?; - let three = ops::splat(fb, u, 3)?; - let sel = fb.binary(BinOp::BitwiseAnd, yb, three)?; - let mut out = qb; - for (k, delta) in [(1u64, 1u64), (2, 0xFFFF_FFFE), (3, 0xFFFF_FFFF)] { - let kv = ops::splat(fb, u, k)?; - let dv = ops::splat(fb, u, delta)?; - let hit = fb.binary(BinOp::IEqual, sel, kv)?; - let moved = fb.binary(BinOp::IAdd, qb, dv)?; - out = fb.select(hit, moved, out)?; - } - fb.convert(ConvOp::Bitcast, out, ft) -} - -/// Define a precise division routine of `lanes` lanes by `path` with estimate `rough`. -fn define_with(b: &mut ModuleBuilder, lanes: u8, path: Path, rough: Rough<'_>) -> BResult { - divide::define_with(b, Routine { lanes, path }, rough) -} - -fn check_divide(what: &str, lanes: u8, path: Path, rough: Rough<'_>, pairs: &[[u64; 2]]) { - let f = floats(lanes); - let m = kernel_defs( - &[f, f], - f, - &|b| Ok(vec![define_with(b, lanes, path, rough)?]), - &|fb, x, funcs| divide::emit(fb, f, x[0], x[1], funcs[0]), - true, - false, - ) - .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); - check_module( - what, - m, - &[f, f], - f, - &lane_cases(pairs, lanes), - &|c| { - Some( - (0..c[0].len()) - .map(|l| metal_div32(c[0][l], c[1][l])) - .collect(), - ) - }, - &|g, w| g == w, - ); -} - -/// Both paths answer Metal's precise quotient bit for bit, on scalars and vectors, with the -/// device's estimate exact and moved to the edge of 2.5 ulp; the vectors mix lanes of every -/// exponent with zeros, denormals, infinities, and NaNs. +/// A precise `float` division is the device's `OpFDiv` of its operands, a divisor past `2^126` and +/// its dividend first scaled by `2^-2` into Vulkan's range: exactly, so on the interpreter the +/// quotient is IEEE's on scalars and vectors, at the largest divisors, the infinities, the zeros +/// and NaN among them (a dividend the scale makes a denormal has a quotient far below `2^-149` +/// there). #[test] -fn precise_division_answers_metal_on_both_paths() { - let pairs = pairs32(); - let exact: Rough<'_> = &|fb, x, y| fb.binary(BinOp::FDiv, x, y); - for path in [Path::Integer, Path::Fused] { - for lanes in [1u8, 3] { - let moved = move |fb: &mut FunctionBuilder<'_>, x: Value, y: Value| { - perturbed(fb, floats(lanes), x, y) - }; - for (name, rough) in [("exact", exact), ("moved", &moved as Rough<'_>)] { - check_divide( - &format!("{path:?} x{lanes} {name}"), - lanes, - path, - rough, - &pairs, - ); - } - } - } -} - -/// The reciprocal step of [`Path::Fused`]: from every estimate within 2.5 ulp of `1 / y`, two -/// fused Newton steps give `RN(1 / y)` for every significand of `y` but the all-ones one, where -/// they give the even neighbor below and one ulp up is `RN(1 / y)` (the operation the routine -/// applies there). The path runs it on the divisor's significand in `[1, 2)`, which this covers. -#[test] -fn markstein_reciprocal_is_correctly_rounded() { - for m in 0u32..(1 << 23) { - let big_y = u64::from(m | 0x80_0000); - let y = f32::from_bits(0x3F80_0000 | m); - // RN(1 / y) = 2^23 / Y: in units of 2^-24, 2^47 / Y, rounded to nearest even. - let rn = if m == 0 { - 0x3F80_0000 - } else { - let mut q = (1u64 << 47) / big_y; - let r = (1u64 << 47) - q * big_y; - if 2 * r > big_y || (2 * r == big_y && q & 1 == 1) { - q += 1; - } - if q == 1 << 24 { - 0x3F80_0000 - } else { - 0x3F00_0000 | (q - (1 << 23)) as u32 - } - }; - for d in -5i32..=5 { - let rb = rn.wrapping_add_signed(d); - // Within 2.5 ulp of 1 / y (2^-24 in (1/2, 1); at y = 1, the ulp above one, 2^-23): - // |r * Y - 2^23| <= 2.5 ulp * Y, every term exact in f64 (r and Y have 24 bits). - let ulp = if m == 0 { - 2f64.powi(-23) - } else { - 2f64.powi(-24) - }; - let yf = big_y as f64; - if (f64::from(f32::from_bits(rb)) * yf - 2f64.powi(23)).abs() > 2.5 * ulp * yf { - continue; - } - let mut r = f32::from_bits(rb); - for _ in 0..2 { - let t = (-y).mul_add(r, 1.0); - r = t.mul_add(r, r); - } - let got = r.to_bits() | u32::from(m == 0x7F_FFFF); - assert_eq!(got, rn, "y = {y:e} (significand {m:#x}), estimate {rb:#x}"); - } - } -} - -/// [`Path::Halves`]'s quotient of two `half` values rounds to their exact quotient's `half`, at -/// every scale: for every pair of 11-bit significands `X / 2^10` and `Y / 2^10` (in `[1, 2)`) and -/// every estimate of `1 / y` within 2.5 ulp of it, `q = x · r` and one fused step `q + r · (x - -/// y · q)` give a quotient on the same point of the 12-bit grid as `X / Y` or strictly between -/// the same two neighboring points. Every `half` value and every `half` rounding midpoint (the -/// denormal ones and the overflow threshold 65520 included) is such a point at its scale, so the -/// quotient and the exact one round to the same `half`. The routine's steps stay normal for every -/// `half` operand (the divisor in `[2^-24, 65504]`, the quotient in `[2^-40, 2^40]`), where -/// scaling an operand by a power of two scales every step and the set of estimates exactly, and -/// negating one negates them, so these pairs cover every pair of finite nonzero `half` values. -#[test] -fn one_fused_correction_rounds_every_half_quotient() { - for my in 0u32..1024 { - let big_y = 1024 + my; - let y = big_y as f32 / 1024.0; - // RN(1 / y), and every float within 2.5 ulp of 1 / y around it (2^-24 in (1/2, 1); at - // y = 1, the ulp above one, 2^-23): `f64` holds each product `r · y` exactly (r has 24 - // bits and y 11). - let rn = 1.0 / y; - let yf = f64::from(y); - let ulp = if my == 0 { - 2f64.powi(-23) - } else { - 2f64.powi(-24) - }; - let estimates: Vec = (-5i32..=5) - .map(|d| f32::from_bits(rn.to_bits().wrapping_add_signed(d))) - .filter(|r| (f64::from(*r) * yf - 1.0).abs() <= 2.5 * ulp * yf) - .collect(); - assert!(estimates.len() >= 4, "y = {y}: {estimates:?}"); - for mx in 0u32..1024 { - let big_x = 1024 + mx; - let x = big_x as f32 / 1024.0; - // The 12-bit grid of X / Y's binade: spacing 2^-11 in [1, 2), 2^-12 in (1/2, 1). - let t = if big_x >= big_y { 11 } else { 12 }; - let scaled = u64::from(big_x) << t; - let (lo, rem) = (scaled / u64::from(big_y), scaled % u64::from(big_y)); - let point = |k: u64| k as f64 / f64::from(1u32 << t); - for &r in &estimates { - let q = x * r; - let e = (-y).mul_add(q, x); - let q = f64::from(e.mul_add(r, q)); - if rem == 0 { - assert_eq!(q, point(lo), "{big_x} / {big_y}, estimate {r:e}"); - } else { - assert!( - point(lo) < q && q < point(lo + 1), - "{big_x} / {big_y}, estimate {r:e}: {q:e} is not in ({:e}, {:e})", - point(lo), - point(lo + 1) - ); - } - } - } - } -} - -/// Metal's `half` quotient of half bits `x` and `y`: the exact quotient rounded once to `half` -/// (the host's `f64` quotient of two `half` values rounds to `half` once), `half` denormals kept. -fn metal_div16(x: u64, y: u64) -> u64 { - u64::from(f64_to_f16(f16_to_f64(x as u16) / f16_to_f64(y as u16))) -} - -/// `half` operand pairs: every pair of the edges (zeros, denormals, the smallest normal, one and -/// its neighbors, the largest finite, infinities, a NaN, three), and random bits. -fn pairs16() -> Vec<[u64; 2]> { +fn a_precise_division_is_the_device_s_quotient() { let edges: [u64; 16] = [ - 0, 0x8000, 0x0001, 0x8001, 0x03FF, 0x0400, 0x3C00, 0xBC00, 0x3C01, 0x3BFF, 0x7BFF, 0xFBFF, - 0x7C00, 0xFC00, 0x7E00, 0x4200, + 0, + 0x8000_0000, + 0x0080_0000, + 0x0000_0003, + 0x3DCC_CCCD, + 0x3F80_0000, + 0xBF80_0000, + 0x4040_0000, + 0x4B00_0001, + 0x7E80_0000, + 0x7F00_0001, + 0x7F7F_FFFF, + 0xFF7F_FFFF, + 0x7F80_0000, + 0xFF80_0000, + 0x7FC0_0000, ]; - let mut out = Vec::new(); - for a in edges { - for b in edges { - out.push([a, b]); + let mut pairs: Vec<[u64; 2]> = Vec::new(); + for x in edges { + for y in edges { + pairs.push([x, y]); } } - let mut rng = Rng(0x2790_D1F1_0000_0016); - for _ in 0..1500 { + let mut rng = Rng(0xD1F1_D1DE); + for _ in 0..512 { let r = rng.next(); - out.push([r & 0xFFFF, (r >> 16) & 0xFFFF]); + pairs.push([r & 0xFFFF_FFFF, r >> 32]); } - out -} - -/// A `half` quotient through every path is Metal's, the exact quotient rounded once to `half`, -/// with the device's `float` estimate exact and moved to the edge of 2.5 ulp (where the estimate -/// rounded to `half` alone would cross a rounding midpoint), on scalars and vectors. -#[test] -fn precise_half_division_rounds_once() { - let pairs = pairs16(); - let exact: Rough<'_> = &|fb, x, y| fb.binary(BinOp::FDiv, x, y); - for path in [Path::Integer, Path::Fused, Path::Halves] { - for lanes in [1u8, 2] { - let moved = move |fb: &mut FunctionBuilder<'_>, x: Value, y: Value| { - perturbed(fb, floats(lanes), x, y) - }; - for (name, rough) in [("exact", exact), ("moved", &moved as Rough<'_>)] { - let what = format!("half {path:?} x{lanes} {name}"); - let f = vec(float(16), lanes); - let m = kernel_defs( - &[f, f], - f, - &|b| Ok(vec![define_with(b, lanes, path, rough)?]), - &|fb, x, funcs| divide::emit(fb, f, x[0], x[1], funcs[0]), - true, - false, + for lanes in [1u8, 3] { + let f = vec(float(32), lanes); + let n = usize::from(lanes); + let cases: Vec = pairs + .chunks(n) + .filter(|c| c.len() == n) + .map(|c| (0..2).map(|k| c.iter().map(|p| p[k]).collect()).collect()) + .collect(); + check( + &format!("precise division x{lanes}"), + &[f, f], + f, + &|fb, x| divide::native(fb, f, x[0], x[1]), + &cases, + &|c| { + Some( + (0..c[0].len()) + .map(|l| u64::from((f32v(c[0][l]) / f32v(c[1][l])).to_bits())) + .collect(), ) - .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); - check_module( - &what, - m, - &[f, f], - f, - &lane_cases(&pairs, lanes), - &|c| { - Some( - (0..c[0].len()) - .map(|l| metal_div16(c[0][l], c[1][l])) - .collect(), - ) - }, - &|g, w| g == w || (is_nan(f, g) && is_nan(f, w)), - ); - } - } - } -} - -/// The routines' words stay within their estimates. -#[test] -fn precise_division_routines_fit_their_word_estimates() { - for path in [Path::Integer, Path::Fused, Path::Halves] { - for lanes in [1u8, 4] { - let r = Routine { lanes, path }; - let mut b = ModuleBuilder::new(); - divide::define(&mut b, r).expect("define"); - let void = b.ty(Type::Void).expect("void"); - let id = { - let mut fb = b.function(void).expect("entry"); - fb.ret(None).expect("ret"); - fb.finish().expect("finish") - }; - b.entry( - ExecModel::GLCompute, - id, - vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }], - ) - .expect("entry"); - let m = b.finalize().expect("finalize"); - let words = crate::spirv::serialize::serialize(m) - .expect("serialize") - .words - .len(); - assert!( - words <= r.words() as usize && words * 3 >= r.words() as usize * 2, - "{path:?} x{lanes}: {words} words against the estimate {} (within its last third)", - r.words() - ); - } - } -} - -/// The path follows the profile: fused where the `float` fused multiply-add is `OpFmaKHR`, -/// integer elsewhere; a `half` division on the fused path takes the halves' path where the -/// profile's `half` rounding is not the device's own. Every path is some committed profile's. -#[test] -fn the_precise_division_path_follows_the_profile() { - let mut seen = std::collections::BTreeSet::new(); - for (stem, p) in committed_profiles().expect("profiles") { - let want = if p.fields().leaf.fma32 { - Path::Fused - } else { - Path::Integer - }; - assert_eq!( - Routine::on(&p, floats(2)), - Routine { - lanes: 2, - path: want }, - "{stem}" - ); - let native = narrow::native_rounding(&p, narrow::quantize_form(&p)).is_some(); - let want_half = if want == Path::Fused && !native { - Path::Halves - } else { - want - }; - assert_eq!( - Routine::on(&p, vec(float(16), 2)), - Routine { - lanes: 2, - path: want_half - }, - "{stem}: half" - ); - seen.insert(want); - seen.insert(want_half); - } - assert_eq!( - seen.len(), - 3, - "every path is some committed profile's: {seen:?}" - ); -} - -/// Metal's `frem` without every fast-math flag: `x - y * trunc(x / y)` on operands read as zeros -/// where denormal, of Metal's precise quotient, the product and the difference rounded to `f32` and -/// flushed where denormal, a NaN the canonical one. -fn metal_frem32(x: u64, y: u64) -> u64 { - let (x, y) = (ftz(x), ftz(y)); - let t = f32v(metal_div32(x, y)).trunc(); - let p = ftz(u64::from((f32v(y) * t).to_bits())); - let r = f32v(x) - f32v(p); - if r.is_nan() { - return 0x7FC0_0000; - } - ftz(u64::from(r.to_bits())) -} - -/// Metal's `frem` on the M3 Max without fast math (our own probe): the -/// operands' bits and the answer's, sampled from the 49,753 measured pairs, which -/// [`metal_frem32`] answers all of bit for bit. Not the exact remainder: `frem(1, 0.1)` is `+0` -/// where `fmod` gives `0x3DCCCCCB`. -const FREM: [(u32, u32, u32); 24] = [ - (0x3F80_0000, 0x3DCC_CCCD, 0x0000_0000), - (0xBF80_0000, 0x3DCC_CCCD, 0x0000_0000), - (0x8000_0001, 0x3F80_0000, 0x0000_0000), - (0x526F_4968, 0xBE9B_F0CA, 0x4680_0000), - (0x5865_577A, 0xD43B_FA15, 0x537A_C000), - (0x4072_A1A8, 0xBF1A_5671, 0x3E31_FFE0), - (0x1DE5_2695, 0x9AD9_E1A5, 0x1A07_2E00), - (0x5174_BA86, 0xCB28_C38D, 0x4AEF_8000), - (0x79C5_B1DB, 0xF20B_EC8C, 0x720B_8000), - (0x61ED_4285, 0x5230_FE72, 0xD600_0000), - (0xF1A1_BD5E, 0xE9A9_D63A, 0xE930_0000), - (0xB31B_12F4, 0x3059_3991, 0xB015_9E80), - (0xA33A_821C, 0x9D89_EB99, 0x9D07_2000), - (0xBE99_999A, 0xF149_F2CA, 0xBE99_999A), - (0x3F80_0000, 0xBE99_999A, 0x3DCC_CCC8), - (0x4669_071D, 0x4602_9548, 0x45CC_E3AA), - (0x8A6A_493E, 0x008F_24EF, 0x8000_0000), - (0x997D_1870, 0x118E_32E4, 0x9164_0000), - (0x7F80_0000, 0xFF7F_FFFF, 0x7FC0_0000), - (0xBF80_0000, 0x7F80_0000, 0x7FC0_0000), - (0x0040_0000, 0xFFC0_0001, 0x7FC0_0000), - (0x0000_0000, 0x007F_FFFF, 0x7FC0_0000), - (0x811E_B274, 0x8053_3F6A, 0x7FC0_0000), - (0x0029_DF79, 0x07EC_0A0E, 0x0000_0000), -]; - -/// `math::metal_frem` with its operands, product and result flushed and its NaN canonicalized (as -/// selection wraps it) answers [`metal_frem32`] on both division paths, scalar and vector, at -/// [`pairs32`] and at every measured pair, which the reference answers as Metal did. -#[test] -fn frem_answers_metal_on_both_paths() { - for &(x, y, want) in &FREM { - assert_eq!( - metal_frem32(u64::from(x), u64::from(y)), - u64::from(want), - "the reference at ({x:#010x}, {y:#010x})" + false, ); } - let mut pairs = pairs32(); - pairs.extend(FREM.iter().map(|&(x, y, _)| [u64::from(x), u64::from(y)])); - let exact: Rough<'_> = &|fb, x, y| fb.binary(BinOp::FDiv, x, y); - for path in [Path::Integer, Path::Fused] { - for lanes in [1u8, 3] { - let f = floats(lanes); - let what = format!("frem {path:?} x{lanes}"); - let m = kernel_defs( - &[f, f], - f, - &|b| Ok(vec![define_with(b, lanes, path, exact)?]), - &|fb, x, funcs| { - let flush = - |fb: &mut FunctionBuilder<'_>, v| super::super::denormal::flush(fb, f, v); - let (p, q) = (flush(fb, x[0])?, flush(fb, x[1])?); - let divide = |fb: &mut FunctionBuilder<'_>, p: Value, q: Value| { - divide::emit(fb, f, p, q, funcs[0]) - }; - let r = math::metal_frem(fb, f, (p, q), ÷, true)?; - let r = flush(fb, r)?; - let nan = super::super::nan::is_nan(fb, f, NanTest::Bits, r)?; - let canonical = ops::fsplat(fb, f, f64::NAN)?; - fb.select(nan, canonical, r) - }, - true, - false, - ) - .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); - check_module( - &what, - m, - &[f, f], - f, - &lane_cases(&pairs, lanes), - &|c| { - Some( - (0..c[0].len()) - .map(|l| metal_frem32(c[0][l], c[1][l])) - .collect(), - ) - }, - &|g, w| g == w, - ); - } - } } diff --git a/crates/metal2vulkan/src/lower/arith/tests/fast.rs b/crates/metal2vulkan/src/lower/arith/tests/fast.rs index 0272b57da..cd78cb678 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/fast.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/fast.rs @@ -1,47 +1,15 @@ -//! Metal's fast division and the fast functions composed with it, on the interpreter against -//! Metal's recorded answers (Apple M3 Max, probe case 08bc6611, compiled with the default fast -//! math): the fast reciprocal's flushes, and `fast::fmod` as `fma(-trunc(x / y), y, x)` of the fast -//! quotient on every fused multiply-add route. +//! The fast functions Metal composes, on the interpreter against Metal's recorded answers (Apple +//! M3 Max, probe case 08bc6611, compiled with the default fast math): `fast::fmod` as +//! `fma(-trunc(x / y), y, x)` of the device's quotient on every `float` fused multiply-add route, +//! and `fast::sqrt` of Metal's own `rsqrt`. use super::*; -use crate::lower::arith::divide::{Reciprocal, Rough}; use crate::lower::arith::fma::{self, Fma, Route}; - -/// `(y, 1 / y)`: every divisor of case 08bc6611 that is an `f32` denormal, a zero, at least -/// `2^126`, an infinity, or a NaN, with Metal's fast reciprocal of it. -const RECIPROCALS: [(u32, u32); 27] = [ - (0x00000000, 0x7F800000), - (0x00000001, 0x7F800000), - (0x00032804, 0x7F800000), - (0x00088345, 0x7F800000), - (0x00130911, 0x7F800000), - (0x00137376, 0x7F800000), - (0x001A8C56, 0x7F800000), - (0x00221974, 0x7F800000), - (0x00314B0F, 0x7F800000), - (0x003EE65F, 0x7F800000), - (0x0053C4EF, 0x7F800000), - (0x007F47D9, 0x7F800000), - (0x7F7FFFFF, 0x00000000), - (0x7F800000, 0x00000000), - (0x7FC00000, 0x7FC00000), - (0x80000000, 0xFF800000), - (0x8004B787, 0xFF800000), - (0x8010F4B2, 0xFF800000), - (0x801ED4BD, 0xFF800000), - (0x802822A3, 0xFF800000), - (0x802B599C, 0xFF800000), - (0x803255FF, 0xFF800000), - (0x80400000, 0xFF800000), - (0x804188FC, 0xFF800000), - (0x804230F6, 0xFF800000), - (0x8056D96A, 0xFF800000), - (0xFF800000, 0x80000000), -]; +use crate::lower::arith::libm::{Lib, Mode}; /// `(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 -/// random), so the quotient the interpreter divides is Metal's. +/// random). const FMOD: [(u32, u32, u32); 108] = [ (0xBFFE18C9, 0xC15FD2B5, 0xBFFE18C9), (0x3E57C427, 0x400109AA, 0x3E57C427), @@ -153,596 +121,14 @@ const FMOD: [(u32, u32, u32); 108] = [ (0x80400000, 0x7FC00000, 0x7FC00000), ]; -/// Metal's fast reciprocal (`math::fast_reciprocal`) at every flushing divisor of the case: the -/// infinity of `y`'s sign for a zero or an `f32` denormal, the zero of its sign at or past -/// `2^126` (where the quotient is an `f32` denormal) and for an infinity, and NaN for a NaN. -#[test] -fn fast_reciprocal_flushes_as_metal() { - let f = float(32); - let cases: Vec = RECIPROCALS - .iter() - .map(|(y, _)| vec![vec![u64::from(*y)]]) - .collect(); - for reciprocal in [Reciprocal::Device, Reciprocal::Rounded] { - check_accept( - &format!("fast reciprocal f32 against Metal, {reciprocal:?}"), - &[f], - f, - &|fb, a| math::fast_reciprocal(fb, f, a[0], Contraction::Allowed, reciprocal), - &cases, - &|c| { - let y = arg(c, 0) as u32; - RECIPROCALS - .iter() - .find(|(k, _)| *k == y) - .map(|(_, r)| vec![u64::from(*r)]) - }, - &|g, w| g == w || (is_nan(f, g) && is_nan(f, w)), - ); - // 2^126 itself has a normal reciprocal, kept. - let edge = vec![vec![vec![u64::from(2f32.powi(126).to_bits())]]]; - check_accept( - &format!("fast reciprocal of 2^126, {reciprocal:?}"), - &[f], - f, - &|fb, a| math::fast_reciprocal(fb, f, a[0], Contraction::Allowed, reciprocal), - &edge, - &|_| Some(vec![u64::from(2f32.powi(-126).to_bits())]), - &|g, w| g == w, - ); - } -} - -/// Divisors for [`a_rounded_fast_reciprocal_is_correctly_rounded`]: the normal range's ends, the -/// range `(2^125, 2^126]` whose estimate is halved, all-ones significands, `3` (RADV's -/// `v_rcp_f32` answered `0x3eaaaaaa`, and `6 / 3` was `0x3fffffff`, RC3 case f8494e2f), -/// reciprocals near a rounding midpoint, the flushes, and random normal divisors. -fn reciprocal_divisors() -> Vec { - use super::divide::bits; - let mut rng = Rng(0x2790_8220_0000_0001); - let mut out: Vec = [ - bits(0, 127, 0), - bits(0, 128, 0x40_0000), - bits(1, 128, 0x40_0000), - bits(0, 127, 0x7F_FFFF), - bits(1, 127, 0x7F_FFFF), - bits(0, 127, 1), - bits(0, 1, 0), - bits(1, 1, 0x7F_FFFF), - bits(0, 2, 0), - bits(0, 252, 0), - bits(0, 252, 1), - bits(1, 252, 0x40_0000), - bits(0, 252, 0x7F_FFFF), - bits(1, 252, 0x7F_FFFF), - bits(0, 253, 0), - bits(1, 253, 0), - bits(0, 253, 1), - bits(0, 254, 0x7F_FFFF), - bits(0, 255, 0), - bits(1, 255, 0), - bits(0, 255, 0x40_0000), - bits(0, 0, 0), - bits(1, 0, 0), - bits(0, 0, 0x40_0000), - bits(1, 0, 0x7F_FFFF), - ] - .to_vec(); - // `1 / y` within 2^-10 of a rounding midpoint: 2^47 mod Y near Y / 2. - let mut near = 0; - while near < 64 { - let m = rng.next() & 0x7F_FFFF; - let big_y = m | 0x80_0000; - let r = (1u64 << 48) % (2 * big_y); - if r.abs_diff(big_y) * 1024 >= 2 * big_y { - continue; - } - near += 1; - out.push(bits(rng.next() & 1, 1 + rng.next() % 253, m)); - } - for _ in 0..256 { - let m = if rng.next() & 7 == 0 { - 0x7F_FFFF - } else { - rng.next() & 0x7F_FFFF - }; - out.push(bits(rng.next() & 1, 1 + rng.next() % 253, m)); - } - out -} - -/// Metal's fast reciprocal of `f32` bits `y` where it is `RN(1 / y)`, with its flushes: the -/// infinity of `y`'s sign for a zero or an `f32` denormal, the zero of its sign past `2^126`. -fn rounded_reciprocal_of(y: u64) -> u64 { - let v = f32v(y); - if y & 0x7F80_0000 == 0 { - return (y & 0x8000_0000) | 0x7F80_0000; - } - if v.is_nan() { - return 0x7FC0_0000; - } - if v.abs() > 2f32.powi(126) { - return y & 0x8000_0000; - } - // The host's `f64` reciprocal of an `f32` is never within an `f64` ulp of an `f32` rounding - // midpoint without being one, which it is not, so rounding it to `f32` rounds once. - u64::from(((1.0 / f64::from(v)) as f32).to_bits()) -} - -/// The device's quotient one ulp low everywhere, as RADV's `v_rcp_f32` answered `1 / 3`. -fn one_ulp_low(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, y: Value) -> BResult { - let u = super::super::narrow::u32_form(f); - let (ut, ft) = (ops::ty(fb, u)?, ops::ty(fb, f)?); - let q = fb.binary(BinOp::FDiv, x, y)?; - let qb = fb.convert(ConvOp::Bitcast, q, ut)?; - let one = ops::splat(fb, u, 1)?; - let low = fb.binary(BinOp::ISub, qb, one)?; - fb.convert(ConvOp::Bitcast, low, ft) -} - -/// On profiles whose `float` fused multiply-add is `OpFmaKHR`, the fast reciprocal is `RN(1 / y)` -/// from any device estimate within 2.5 ulp: [`reciprocal_divisors`] on one and three lanes, with -/// the estimate exact, moved by up to two ulp either way, and one ulp low everywhere. The flushes -/// are the device reciprocal's. With the estimate one ulp low, the fast `6 / 3` is `2` (Metal's -/// answer), where the device's reciprocal gives `0x3fffffff`. -#[test] -fn a_rounded_fast_reciprocal_is_correctly_rounded() { - let ys = reciprocal_divisors(); - let exact: Rough<'_> = &|fb, x, y| fb.binary(BinOp::FDiv, x, y); - for lanes in [1u8, 3] { - let f = vec(float(32), lanes); - let n = usize::from(lanes); - let cases: Vec = (0..ys.len()) - .step_by(n) - .map(|i| vec![(0..n).map(|l| ys[(i + l) % ys.len()]).collect()]) - .collect(); - let moved = move |fb: &mut FunctionBuilder<'_>, x: Value, y: Value| { - super::divide::perturbed(fb, f, x, y) - }; - let low = move |fb: &mut FunctionBuilder<'_>, x: Value, y: Value| one_ulp_low(fb, f, x, y); - for (name, rough) in [ - ("exact", exact), - ("moved", &moved as Rough<'_>), - ("low", &low as Rough<'_>), - ] { - check_accept( - &format!("rounded fast reciprocal x{lanes} {name}"), - &[f], - f, - &|fb, a| math::fast_reciprocal_with(fb, f, a[0], Reciprocal::Rounded, rough), - &cases, - &|c| Some(c[0].iter().map(|y| rounded_reciprocal_of(*y)).collect()), - &|g, w| g == w || (is_nan(f, g) && is_nan(f, w)), - ); - } - } - let f = float(32); - let low = move |fb: &mut FunctionBuilder<'_>, x: Value, y: Value| one_ulp_low(fb, f, x, y); - let six_by_three = vec![vec![ - vec![u64::from(6f32.to_bits())], - vec![u64::from(3f32.to_bits())], - ]]; - for (reciprocal, want) in [ - (Reciprocal::Rounded, 0x4000_0000u64), - (Reciprocal::Device, 0x3FFF_FFFF), - ] { - check_accept( - &format!("6 / 3 from a low estimate, {reciprocal:?}"), - &[f, f], - f, - &|fb, a| { - let r = math::fast_reciprocal_with(fb, f, a[1], reciprocal, &low)?; - fb.binary(BinOp::FMul, a[0], r) - }, - &six_by_three, - &|_| Some(vec![want]), - &|g, w| g == w, - ); - } -} - -/// Metal's fast quotient of `f32` bits `x` and `y` where its reciprocal is `RN(1 / y)` -/// ([`rounded_reciprocal_of`]): a denormal `x` read as a zero of its sign, a product whose -/// 24-bit rounding (with an unbounded exponent) is below `2^-126` a zero of its sign, and a NaN -/// `0x7FC00000`. -fn metal_fast_quotient(x: u64, y: u64) -> u64 { - let r = f64::from(f32v(rounded_reciprocal_of(y))); - let x = if x & 0x7F80_0000 == 0 { - f64::from(f32v(x & 0x8000_0000)) - } else { - f64::from(f32v(x)) - }; - // Exact: the two significands' product has 48 bits, and its exponent is an `f64`'s. - let p = x * r; - if p.is_nan() { - return 0x7FC0_0000; - } - // Below `2^-126` the 24-bit rounding is decided `2^64` higher, where it is a normal `f32`. - let scaled = (p * 2f64.powi(64)) as f32; - if p.abs() < 2f64.powi(-126) && scaled.abs() < 2f32.powi(-62) { - return u64::from(f32v(0).copysign(p as f32).to_bits()); - } - u64::from((p as f32).to_bits()) -} - -/// `(x, y)`: fast divisions at Metal's NaNs and denormals. A NaN divisor (either sign), a NaN -/// numerator, `0 / 0`, `inf / inf`, and `inf · 0` (`inf / 2^127`) answer `0x7FC00000`; a denormal -/// numerator is a zero of its sign (`0 · inf = NaN` over a denormal divisor, A1 case f9a12252's -/// lanes); a quotient below `2^-126` is a zero of its sign, including `(2^24 - 1) · 2^-150`, which -/// the denormal grid rounds up to `2^-126`; a zero quotient of a numerator too large to scale by -/// `2^24` (`2^127 / 2^127`, whose reciprocal flushes) keeps its sign; and quotients at `2^-126` and -/// of normals are the product's. -const SPECIAL_DIVISIONS: [(u32, u32); 34] = [ - (0x3F80_0000, 0x7FC0_0000), - (0x7F80_0000, 0x7FC0_0000), - (0x3F80_0000, 0xFFC0_0000), - (0x7FC0_0001, 0x4000_0000), - (0xFFC0_0000, 0x4000_0000), - (0x0000_0000, 0x0000_0000), - (0x8000_0000, 0x0000_0000), - (0x7F80_0000, 0x7F80_0000), - (0x7F80_0000, 0x7F00_0000), - (0xFF80_0000, 0x7F7F_FFFF), - (0x0040_0000, 0x3F80_0000), - (0x8040_0000, 0x4000_0000), - (0x0000_0001, 0xBF80_0000), - (0x807F_FFFF, 0x3F00_0000), - (0x0040_0000, 0x0040_0000), - (0x0000_0001, 0x0000_0001), - (0x8000_0001, 0x0040_0000), - (0x0D80_0000, 0x4E80_0000), - (0x8D80_0000, 0x4E80_0000), - (0x0D80_0000, 0xCE80_0000), - (0x00C0_0000, 0x4000_0000), - (0x80C0_0000, 0x4000_0000), - (0x00FF_FFFF, 0x4000_0000), - (0x80FF_FFFF, 0x4000_0000), - (0x0100_0000, 0x4000_0000), - (0x8100_0000, 0x4000_0000), - (0x00FF_FFFF, 0x3F00_0000), - (0x40C0_0000, 0x4040_0000), - (0x3F80_0000, 0x4040_0000), - (0x42AA_3A21, 0x44C8_0075), - (0x7F7F_FFFF, 0x3F00_0000), - (0x3F80_0000, 0x0080_0000), - (0x7F00_0000, 0x7F00_0000), - (0xFF00_0000, 0x7F00_0000), -]; - -/// The fast division's test vectors in lanes of `lanes`: [`SPECIAL_DIVISIONS`] and random normal -/// operands whose quotients reach the denormals. -fn fast_division_cases(lanes: u8) -> Vec { - let mut rng = Rng(0x0864_0000_D279_0001); - let mut pairs: Vec<(u64, u64)> = SPECIAL_DIVISIONS - .iter() - .map(|(x, y)| (u64::from(*x), u64::from(*y))) - .collect(); - for _ in 0..96 { - let x = super::divide::bits(rng.next() & 1, 1 + rng.next() % 40, rng.next() & 0x7F_FFFF); - let y = super::divide::bits( - rng.next() & 1, - 100 + rng.next() % 54, - rng.next() & 0x7F_FFFF, - ); - pairs.push((x, y)); - } - let n = usize::from(lanes); - (0..pairs.len()) - .step_by(n) - .map(|i| { - let lane = |l: usize| pairs[(i + l) % pairs.len()]; - vec![ - (0..n).map(|l| lane(l).0).collect(), - (0..n).map(|l| lane(l).1).collect(), - ] - }) - .collect() -} - -/// Metal's fast division (`math::fast_divide`) answers its NaNs and denormals on every device, by -/// either reciprocal, on one and four lanes: [`SPECIAL_DIVISIONS`] and random normal operands whose -/// quotients reach the denormals, against [`metal_fast_quotient`], bit for bit. The interpreter's -/// division is correctly rounded, its arithmetic keeps denormals, and its NaNs keep their payloads, -/// so no answer here comes from a device that happens to flush. -#[test] -fn a_fast_division_answers_metal_at_nans_and_denormals() { - for lanes in [1u8, 4] { - let f = vec(float(32), lanes); - let cases = fast_division_cases(lanes); - for reciprocal in [Reciprocal::Device, Reciprocal::Rounded] { - check_accept( - &format!("fast division at NaNs and denormals x{lanes}, {reciprocal:?}"), - &[f, f], - f, - &|fb, a| math::fast_divide(fb, f, a[0], a[1], Contraction::Allowed, reciprocal), - &cases, - &|c| { - Some( - c[0].iter() - .zip(&c[1]) - .map(|(x, y)| metal_fast_quotient(*x, *y)) - .collect(), - ) - }, - &|g, w| g == w, - ); - } - } -} - -/// An `arcp` division's word estimate ([`ArithStrategy::FastDivide`], a call) with its routine's -/// ([`math::FastDivision`], charged once per module), and `fast::tanh`'s and `fast::fmod`'s with -/// the same routine, bound what they emit by either reciprocal, on scalars and vectors, and the -/// routine with one call is within the last third of its estimate. The module's growth over an -/// identity kernel is charged in full, its constants, types, and the `GLSL.std.450` import -/// included. -#[test] -fn a_fast_division_fits_its_word_estimate() { - use crate::lower::strategy::FamilyStrategy; - let module_words = |ins: &[Form], f: Form, defs: Defs<'_>, body: BodyCalling<'_>| { - let m = kernel_defs(ins, f, defs, body, false, false).expect("kernel"); - crate::spirv::serialize::serialize(m) - .expect("words") - .words - .len() - }; - let mut over = Vec::new(); - for f in [float(32), vec(float(32), 2), vec(float(32), 4)] { - let none: Defs<'_> = &|_| Ok(Vec::new()); - let bare = module_words(&[f, f], f, none, &|_, x, _| Ok(x[0])); - for reciprocal in [Reciprocal::Device, Reciprocal::Rounded] { - for contract in [Contraction::Allowed, Contraction::Forbidden] { - let routine = math::FastDivision::new(f, reciprocal, contract); - let defs: Defs<'_> = &|b| Ok(vec![math::define_fast_division(b, routine)?]); - let used = module_words(&[f, f], f, defs, &|fb, x, funcs| { - math::call_fast_division(fb, funcs[0], x[0], x[1]) - }); - let bound = super::super::ArithStrategy::FastDivide { form: f, routine }.words() - as usize - + routine.words() as usize; - if used - bare > bound || (used - bare) * 3 < bound * 2 { - over.push(format!( - "{reciprocal:?} {contract:?} x{}: {} against {bound}", - f.lanes, - used - bare - )); - } - } - let routine = math::FastDivision::new(f, reciprocal, Contraction::Forbidden); - let defs: Defs<'_> = &|b| Ok(vec![math::define_fast_division(b, routine)?]); - let tanh = FloatFn::FastTanh { reciprocal }; - let used = module_words(&[f, f], f, defs, &|fb, x, funcs| { - let divide = |fb: &mut FunctionBuilder<'_>, p: Value, q: Value| { - math::call_fast_division(fb, funcs[0], p, q) - }; - math::fast_tanh(fb, tanh, f, x[0], &Lib::instructions(), ÷) - }); - let bound = (tanh.words(f) + routine.words()) as usize; - if used - bare > bound { - over.push(format!( - "{tanh:?} x{}: {} over {bound}", - f.lanes, - used - bare - )); - } - } - for route in [Route::Khr, Route::Wide, Route::Soft] { - let fma = Fma { - form: f, - route, - tiny: None, - }; - let reciprocal = Reciprocal::of(route); - let routine = math::FastDivision::new(f, reciprocal, Contraction::Forbidden); - let defs: Defs<'_> = &|b| { - let mut funcs = vec![math::define_fast_division(b, routine)?]; - if let Some(r) = fma.routine() { - funcs.push(fma::define(b, r)?); - } - Ok(funcs) - }; - let used = module_words(&[f, f], f, defs, &|fb, x, funcs| { - let divide = |fb: &mut FunctionBuilder<'_>, p: Value, q: Value| { - math::call_fast_division(fb, funcs[0], p, q) - }; - let call = |fb: &mut FunctionBuilder<'_>, args: &[Value]| { - fma::emit(fb, fma, args, funcs.get(1).copied()) - }; - math::fast_fmod(fb, x[0], x[1], ÷, &call) - }); - let bound = (super::super::ArithStrategy::FastFmod { fma, reciprocal }.words() - + routine.words() - + fma.routine().map_or(0, |r| r.words())) as usize; - if used - bare > bound { - over.push(format!( - "fast fmod {route:?} x{}: {} over {bound}", - f.lanes, - used - bare - )); - } - } - } - assert!(over.is_empty(), "{over:?}"); -} - -/// The fast division's routine answers as the division expanded in place, bit for bit: an `arcp` -/// division by a call of [`math::define_fast_division`] against `math::fast_divide` inline, on the -/// fast division's test vectors, by either reciprocal and either contraction, on one and four -/// lanes; and `fast::tanh`'s quotient and `fast::fmod` (every `float` route of its fused -/// multiply-add) with the routine against the same with the division inline, on their test vectors. -#[test] -fn a_fast_division_routine_answers_as_the_division_inline() { - let compare = |what: &str, - ins: &[Form], - f: Form, - inline: TypedModule, - called: TypedModule, - cases: &[Case]| { - let a = run_module(&format!("{what}, inline"), inline, ins, f, cases); - let b = run_module(&format!("{what}, called"), called, ins, f, cases); - let differ: Vec = cases - .iter() - .zip(a.iter().zip(&b)) - .filter(|(_, (a, b))| a != b) - .take(12) - .map(|(c, (a, b))| format!("{c:x?}: inline {a:x?}, called {b:x?}")) - .collect(); - assert!(differ.is_empty(), "{what}: {}", differ.join("\n")); - }; - for lanes in [1u8, 4] { - let f = vec(float(32), lanes); - let cases = fast_division_cases(lanes); - for reciprocal in [Reciprocal::Device, Reciprocal::Rounded] { - for contract in [Contraction::Allowed, Contraction::Forbidden] { - let routine = math::FastDivision::new(f, reciprocal, contract); - let inline = kernel(&[f, f], f, &|fb, x| { - math::fast_divide(fb, f, x[0], x[1], contract, reciprocal) - }) - .expect("inline"); - let called = kernel_defs( - &[f, f], - f, - &|b| Ok(vec![math::define_fast_division(b, routine)?]), - &|fb, x, funcs| math::call_fast_division(fb, funcs[0], x[0], x[1]), - false, - false, - ) - .expect("called"); - let what = format!("fast division x{lanes} {reciprocal:?} {contract:?}"); - compare(&what, &[f, f], f, inline, called, &cases); - } - } - } - // `fast::tanh`'s quotient, `(t - 1) / (t + 1)` of `t = exp(2x)` (the interpreter does not - // model `Exp2`): zeros, small and large `t`, the reciprocal's flush past `2^126`, infinities, - // and NaNs. - let f = float(32); - let tanh_cases: Vec = [ - 0.0f32, - -0.0, - 1e-40, - 3.9e-22, - 0.25, - 1.0, - 1.5, - 7.0, - 1e20, - 8.5e37, - 1.7e38, - f32::MAX, - f32::INFINITY, - f32::NAN, - ] - .iter() - .map(|t| vec![vec![u64::from(t.to_bits())]]) - .collect(); - for reciprocal in [Reciprocal::Device, Reciprocal::Rounded] { - let routine = math::FastDivision::new(f, reciprocal, Contraction::Forbidden); - let inline = kernel(&[f], f, &|fb, t| { - let divide = |fb: &mut FunctionBuilder<'_>, p: Value, q: Value| { - math::fast_divide(fb, f, p, q, Contraction::Forbidden, reciprocal) - }; - math::tanh_of_exp(fb, f, ÷, t[0]) - }) - .expect("inline"); - let called = kernel_defs( - &[f], - f, - &|b| Ok(vec![math::define_fast_division(b, routine)?]), - &|fb, t, funcs| { - let divide = |fb: &mut FunctionBuilder<'_>, p: Value, q: Value| { - math::call_fast_division(fb, funcs[0], p, q) - }; - math::tanh_of_exp(fb, f, ÷, t[0]) - }, - false, - false, - ) - .expect("called"); - compare( - &format!("fast tanh's quotient {reciprocal:?}"), - &[f], - f, - inline, - called, - &tanh_cases, - ); - } - let fmod_cases: Vec = FMOD - .iter() - .map(|(x, y, _)| vec![vec![u64::from(*x)], vec![u64::from(*y)]]) - .collect(); - for route in [Route::Khr, Route::Wide, Route::Soft] { - let fma = Fma { - form: f, - route, - tiny: None, - }; - let reciprocal = Reciprocal::of(route); - let routine = math::FastDivision::new(f, reciprocal, Contraction::Forbidden); - let fmas = |b: &mut ModuleBuilder| -> BResult> { - Ok(fma - .routine() - .map(|r| fma::define(b, r)) - .transpose()? - .into_iter() - .collect()) - }; - let inline = kernel_defs( - &[f, f], - f, - &fmas, - &|fb, x, funcs| { - let divide = |fb: &mut FunctionBuilder<'_>, p: Value, q: Value| { - math::fast_divide(fb, f, p, q, Contraction::Forbidden, reciprocal) - }; - let call = |fb: &mut FunctionBuilder<'_>, args: &[Value]| { - fma::emit(fb, fma, args, funcs.first().copied()) - }; - math::fast_fmod(fb, x[0], x[1], ÷, &call) - }, - false, - false, - ) - .expect("inline"); - let called = kernel_defs( - &[f, f], - f, - &|b| { - let mut funcs = fmas(b)?; - funcs.push(math::define_fast_division(b, routine)?); - Ok(funcs) - }, - &|fb, x, funcs| { - let division = funcs.last().copied().expect("the division routine"); - let divide = |fb: &mut FunctionBuilder<'_>, p: Value, q: Value| { - math::call_fast_division(fb, division, p, q) - }; - let fma_id = fma.routine().and(funcs.first().copied()); - let call = - |fb: &mut FunctionBuilder<'_>, args: &[Value]| fma::emit(fb, fma, args, fma_id); - math::fast_fmod(fb, x[0], x[1], ÷, &call) - }, - false, - false, - ) - .expect("called"); - compare( - &format!("fast fmod {route:?}"), - &[f, f], - f, - inline, - called, - &fmod_cases, - ); - } -} - /// `fast::fmod` (`math::fast_fmod`) on every `float` route of its fused multiply-add, at the -/// lanes of [`FMOD`], bit for bit: Metal's answer is the expression on its own quotient, and the -/// interpreter's quotient there is Metal's. `OpFmaKHR` is the device's (the interpreter's IEEE -/// `fma`, which keeps denormals), so on that route a lane with an `f32` denormal operand or a -/// zero or denormal answer is not asserted. +/// lanes of [`FMOD`], bit for bit: Metal's answer is the expression on its own quotient, its fast +/// division's, where the module takes the device's division (`PrecisionNote::NativeDivision`), +/// here the interpreter's correctly rounded one. A lane whose finite answer depends on the +/// quotient's last bits (a quotient of `2^22` or more in magnitude, whose `trunc` they decide) is +/// the device's division's and not asserted. The device's division, `OpFmaKHR` and `Fma` keep +/// denormals (here the interpreter's IEEE ones), so a lane with an `f32` denormal operand or a +/// zero or denormal answer is the device's and not asserted either. #[test] fn fast_fmod_answers_as_metal_on_every_route() { let f = float(32); @@ -750,42 +136,19 @@ fn fast_fmod_answers_as_metal_on_every_route() { .iter() .map(|(x, y, _)| vec![vec![u64::from(*x)], vec![u64::from(*y)]]) .collect(); - for route in [Route::Khr, Route::Wide, Route::Soft] { - let fma = Fma { - form: f, - route, - tiny: None, - }; - let routine = fma.routine(); - let division = math::FastDivision::new(f, Reciprocal::of(route), Contraction::Forbidden); - let m = kernel_defs( + for route in [Route::Khr, Route::Native] { + let fma = Fma { form: f, route }; + check_accept( + &format!("fast fmod {route:?} against Metal"), &[f, f], f, - &|b| { - let mut funcs = vec![math::define_fast_division(b, division)?]; - if let Some(r) = routine { - funcs.push(fma::define(b, r)?); - } - Ok(funcs) - }, - &|fb, x, funcs| { + &|fb, x| { let divide = |fb: &mut FunctionBuilder<'_>, p: Value, q: Value| { - math::call_fast_division(fb, funcs[0], p, q) - }; - let call = |fb: &mut FunctionBuilder<'_>, args: &[Value]| { - fma::emit(fb, fma, args, funcs.get(1).copied()) + fb.binary_with(BinOp::FDiv, p, q, Contraction::Forbidden) }; + let call = |fb: &mut FunctionBuilder<'_>, args: &[Value]| fma::emit(fb, fma, args); math::fast_fmod(fb, x[0], x[1], ÷, &call) }, - true, - false, - ) - .unwrap_or_else(|e| panic!("fast fmod {route:?}: build: {e:?}")); - check_module( - &format!("fast fmod {route:?} against Metal"), - m, - &[f, f], - f, &cases, &|c| { let (x, y) = (arg(c, 0) as u32, arg(c, 1) as u32); @@ -793,11 +156,12 @@ fn fast_fmod_answers_as_metal_on_every_route() { .iter() .find(|(a, b, _)| *a == x && *b == y) .map(|(_, _, w)| *w)?; - // `OpFmaKHR` keeps denormal operands and results (the device's denormal mode), - // so on that route a lane with an `f32` denormal operand or a zero or denormal - // answer is the device's. let denormal = |b: u32| b & 0x7F80_0000 == 0 && b & 0x007F_FFFF != 0; - if route == Route::Khr && (denormal(x) || denormal(y) || want & 0x7F80_0000 == 0) { + if denormal(x) || denormal(y) || want & 0x7F80_0000 == 0 { + return None; + } + let q = f32::from_bits(x) / f32::from_bits(y); + if q.is_finite() && q.abs() >= 4_194_304.0 && !f32::from_bits(want).is_nan() { return None; } Some(vec![u64::from(want)]) @@ -892,8 +256,9 @@ fn fast_sqrt_answers_as_metal_from_its_rsqrt() { /// The fast functions Metal composes are emitted as its compositions, read from the module: /// `fast::exp` is one `Exp2` of a product with `float(log2 e)`, `fast::log` one `Log2` times -/// `float(ln 2)`, `fast::powr` and `fast::pow` one `Exp2` of a product with one `Log2`, and -/// `fast::sqrt` one `InverseSqrt`; none reads `Exp`, `Log`, `Pow`, or `Sqrt`. +/// `float(ln 2)`, `fast::powr` and `fast::pow` one `Exp2` of a product with one `Log2`; none reads +/// `Exp`, `Log`, or `Pow`. `fast::sqrt` is the device's `Sqrt` where its functions are not Metal's, +/// and Metal's `x · rsqrt(x)` of one `InverseSqrt` where they are. #[test] fn fast_functions_are_metals_compositions() { const OP_CONSTANT: u32 = 43; @@ -902,17 +267,9 @@ fn fast_functions_are_metals_compositions() { // GLSL.std.450: Pow, Exp, Log, Exp2, Log2, Sqrt, InverseSqrt. const GLSL: [u32; 7] = [26, 27, 28, 29, 30, 31, 32]; let f = float(32); - let read = |op: FloatFn| { + let read_in = |op: FloatFn, lib: Lib| { let m = kernel(&vec![f; op.arity()], f, &|fb, a| { - math::float_fn( - fb, - op, - f, - Contraction::Forbidden, - NanTest::IsNan, - a, - &Lib::instructions(), - ) + math::float_fn(fb, op, f, Contraction::Forbidden, NanTest::IsNan, a, &lib) }) .expect("kernel"); let words = crate::spirv::serialize::serialize(m).expect("words").words; @@ -935,6 +292,7 @@ fn fast_functions_are_metals_compositions() { } (ext, fmul, consts) }; + let read = |op: FloatFn| read_in(op, Lib::instructions()); let log2e = (std::f64::consts::LOG2_E as f32).to_bits(); let ln2 = (std::f64::consts::LN_2 as f32).to_bits(); assert_eq!((log2e, ln2), (0x3FB8_AA3B, 0x3F31_7218)); @@ -951,5 +309,7 @@ fn fast_functions_are_metals_compositions() { let (ext, _, _) = read(FloatFn::Pow); assert_eq!(ext, [1, 0, 0, 0, 0, 0, 0]); let (ext, _, _) = read(FloatFn::FastSqrt); + assert_eq!(ext, [0, 0, 0, 0, 0, 1, 0]); + let (ext, _, _) = read_in(FloatFn::FastSqrt, Lib::new(Some(Mode::Fast), None)); assert_eq!(ext, [0, 0, 0, 0, 0, 0, 1]); } diff --git a/crates/metal2vulkan/src/lower/arith/tests/fused.rs b/crates/metal2vulkan/src/lower/arith/tests/fused.rs index 0f4c17569..a6ef4ba4c 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/fused.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/fused.rs @@ -1,5 +1,5 @@ -//! Correctly rounded fused multiply-add: every route against one rounding of the exact `a * b + c`, -//! on the interpreter. +//! Fused multiply-add: every route against one rounding of the exact `a * b + c`, on the +//! interpreter, and Metal's `mix` and `dot` chains over them. //! //! The `float` reference is the host's `f32::mul_add` (one rounding, denormals kept); the `half` //! reference rounds the exact sum, formed as an integer multiple of `2^-48`, once to nearest @@ -9,8 +9,8 @@ //! product dominant, and the `half` triples whose `float` sum lands on a `half` midpoint. use super::*; -use crate::lower::arith::fma::{self, Fma, Route, Routine}; -use std::collections::{BTreeMap, BTreeSet}; +use crate::lower::arith::fma::{self, Fma, Route}; +use std::collections::BTreeSet; fn floats(lanes: u8) -> Form { vec(float(32), lanes) @@ -30,50 +30,6 @@ fn fma32(a: u64, b: u64, c: u64) -> u64 { u64::from(f32v(a).mul_add(f32v(b), f32v(c)).to_bits()) } -/// An `f32` denormal as a zero of its sign. -fn ftz(x: u64) -> u64 { - if x & 0x7F80_0000 == 0 { - x & 0x8000_0000 - } else { - x - } -} - -/// Whether the exact `a * b + c` of finite `f32`s is nonzero and below `2^-126` in magnitude: the -/// product is exact in `f64`, and the sum's rounding error is exact (TwoSum), so the sum rounded -/// to `f64` and its error place the exact value against `2^-126`, a `f64`. -fn exact_below_normal(a: u64, b: u64, c: u64) -> bool { - let (a, b, c) = (f32v(a), f32v(b), f32v(c)); - if !(a.is_finite() && b.is_finite() && c.is_finite()) { - return false; - } - let p = f64::from(a) * f64::from(b); - let c = f64::from(c); - let s = p + c; - let v = s - p; - let e = (p - (s - v)) + (c - v); - let normal = f64::from(f32::MIN_POSITIVE); - (s != 0.0 && s.abs() < normal) || (s.abs() == normal && e != 0.0 && (e < 0.0) == (s > 0.0)) -} - -/// Metal's `fma` (probe cases e98b103f and f7850ba7): denormal operands read as zeros, the one -/// rounding, a result whose exact value is below `2^-126` a zero of its sign before rounding, and -/// every NaN `0x7FC00000`. -fn metal_fma32(a: u64, b: u64, c: u64) -> u64 { - let (a, b, c) = (ftz(a), ftz(b), ftz(c)); - let r = fma32(a, b, c); - let r = if exact_below_normal(a, b, c) { - r & 0x8000_0000 - } else { - r - }; - if f32v(r).is_nan() { - 0x7FC0_0000 - } else { - r - } -} - /// Whether a `double` sum rounded to `float` differs from the fused result (the hazard the /// `double` route's round-to-odd removes). fn double_rounds_wrong(a: u64, b: u64, c: u64) -> bool { @@ -280,67 +236,21 @@ fn same(f: Form) -> impl Fn(u64, u64) -> bool { move |g, w| g == w || (is_nan(f, g) && is_nan(f, w)) } -/// Run `fma` over `cases` (through a defined routine when its route has one; on vectors, per -/// lane through its route's routine on one lane when `per_lane`; checked, on operands read as -/// Metal reads them, as a module flushes them) and compare with `reference` per lane: bit for bit -/// when `exact`, else any NaN for a NaN. +/// Run `fma` over `cases` and compare with `reference` per lane: bit for bit when `exact`, else +/// any NaN for a NaN. fn check_fma( what: &str, fma: Fma, - per_lane: bool, cases: &[Case], reference: &dyn Fn(u64, u64, u64) -> u64, exact: bool, ) { let f = fma.form; - let routine = fma.routine(); - // The module's routines: the use's and, per lane, its route's on one lane. - let mut fmas: BTreeSet = routine.into_iter().collect(); - if per_lane { - fmas.extend(routine.map(|r| Routine { - route: r.route, - lanes: 1, - })); - } - // The routine of `OpFmaKHR`'s small results is never defined per lane. - assert_eq!( - routine.is_some_and(|r| fma::per_lane(r, &fmas)), - per_lane && routine.is_some_and(|r| r.route != Route::Khr) && f.lanes > 1, - "{what}" - ); - let m = kernel_defs( - &[f, f, f], - f, - &|b| { - let mut defined = BTreeMap::new(); - for r in &fmas { - let id = fma::define_among(b, *r, &fmas, &defined)?; - defined.insert(*r, id); - } - Ok(routine - .and_then(|r| defined.get(&r).copied()) - .into_iter() - .collect()) - }, - &|fb, x, funcs| { - let x = match fma.checked() { - true => x - .iter() - .map(|v| crate::lower::arith::denormal::flush(fb, f, *v)) - .collect::>>()?, - false => x.to_vec(), - }; - fma::emit(fb, fma, &x, funcs.first().copied()) - }, - true, - false, - ) - .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); - check_module( + check_accept( what, - m, &[f, f, f], f, + &|fb, x| fma::emit(fb, fma, x), cases, &|c| { Some( @@ -353,122 +263,29 @@ fn check_fma( ); } -/// The three `float` routes round the exact `a * b + c` once, on scalars and vectors (a vector -/// routine's sequence on its lanes, and per lane), specials, signed zeros, denormals, overflow, and -/// the double-rounding hazards included. The routes the translation computes answer Metal's `fma` -/// bit for bit (its denormal flush and NaN); `OpFmaKHR` is the device's (here the interpreter's -/// IEEE `fma`), and checked by either routine, on operands read as Metal reads them, Metal's -/// but for the NaN's encoding. +/// `OpFmaKHR` and the device's `Fma` round the exact `a * b + c` once on the interpreter (whose +/// `Fma` is IEEE's), on scalars and vectors, specials, signed zeros, denormals, overflow, and the +/// double-rounding hazards included: the module adds nothing to the device's instruction. #[test] -fn float_fused_multiply_add_rounds_once_on_every_route() { +fn float_fused_multiply_add_is_the_device_s_instruction() { let triples = float_triples(); - for (route, tiny, reference, exact) in [ - (Route::Khr, None, fma32 as fn(u64, u64, u64) -> u64, false), - (Route::Khr, Some(Route::Wide), metal_fma32, false), - (Route::Khr, Some(Route::Soft), metal_fma32, false), - (Route::Wide, None, metal_fma32, true), - (Route::Soft, None, metal_fma32, true), - ] { - for (lanes, per_lane) in [(1u8, false), (3, false), (3, true)] { + for route in [Route::Khr, Route::Native] { + for lanes in [1u8, 3] { let fma = Fma { form: floats(lanes), route, - tiny, }; check_fma( - &format!("fma {route:?} checked by {tiny:?} x{lanes}, per lane {per_lane}"), + &format!("fma {route:?} x{lanes}"), fma, - per_lane, &lane_cases(&triples, lanes), - &reference, - exact, + &fma32, + false, ); } } } -/// `OpFmaKHR` checked (`fma::checked`) is Metal's `fma` on every device Vulkan allows, on operands -/// read as Metal reads them: whether the device keeps a denormal result, flushes it to a zero of -/// its sign or to `+0`, or flushes an exact value below `2^-126` before rounding, a result above -/// `2^-126` in magnitude is Metal's, and the routine answers the rest. The triples reach the -/// results the device rounds up to `2^-126` (`2^-126 * (1 - 2^-24)` among the edges), and the -/// test counts them. -#[test] -fn a_checked_fused_multiply_add_is_metals_in_every_denormal_mode() { - let devices: [(&str, fn(u64, u64, u64) -> u64); 4] = [ - ("kept", fma32), - ("flushed", |a, b, c| ftz(fma32(a, b, c))), - ("flushed to +0", |a, b, c| { - let r = fma32(a, b, c); - if r & 0x7F80_0000 == 0 { - 0 - } else { - r - } - }), - ("flushed before rounding", |a, b, c| { - let r = fma32(a, b, c); - if exact_below_normal(a, b, c) { - r & 0x8000_0000 - } else { - r - } - }), - ]; - let triples: Vec<[u64; 3]> = float_triples().into_iter().map(|t| t.map(ftz)).collect(); - let rounded_up = triples - .iter() - .filter(|[a, b, c]| { - exact_below_normal(*a, *b, *c) && fma32(*a, *b, *c) & 0x7FFF_FFFF == 0x0080_0000 - }) - .count(); - assert!(rounded_up >= 1, "{rounded_up} results rounded up to 2^-126"); - for (what, device) in devices { - for [a, b, c] in &triples { - let r = device(*a, *b, *c); - let small = r & 0x7FFF_FFFF <= 0x0080_0000; - let want = metal_fma32(*a, *b, *c); - // By the whole routine (the integer route), and by the routine of small results. - for (routine, answer) in [ - ("Metal's fma", metal_fma32(*a, *b, *c)), - ("small", small_results(*a, *b, *c, r)), - ] { - let checked = if small { answer } else { r }; - assert!( - same(float(32))(checked, want), - "{what}, {routine}: fma({a:#010x}, {b:#010x}, {c:#010x}): {checked:#010x}, \ - Metal {want:#010x}" - ); - } - } - } -} - -/// `fma::small` on one lane, in Rust's IEEE `double`: Metal's `fma` of `a`, `b`, `c` from `r`, -/// their `OpFmaKHR` on some device, where `r` is at most `2^-126` in magnitude, else `r`. -fn small_results(a: u64, b: u64, c: u64, r: u64) -> u64 { - let read = |x: u64| match x & 0x7F80_0000 { - 0 => 0.0, - _ => f64::from(f32v(x)), - }; - let (x, y, z) = (read(a), read(b), read(c)); - let p = x * y; - let s = p + z; - let sp = s - z; - let sz = s - sp; - let e = (p - sp) + (z - sz); - let normal = f64::from(f32::MIN_POSITIVE); - let size = s.abs(); - let tiny = size < normal || (size == normal && e * s < 0.0); - match r & 0x7FFF_FFFF <= 0x0080_0000 && tiny { - // An exact zero sum: IEEE's sign, on the operands' bits. - true if s == 0.0 => (a ^ b) & c & 0x8000_0000, - true if s < 0.0 => 0x8000_0000, - true => 0, - false => r, - } -} - /// The blends' exact `float` multiply-add (`fma::float_fma_exact`, of a `float` output's blend into /// an extended-range or 16-bit float attachment) rounds the exact `a * b + c` once on operands below /// 2 in magnitude whose parts do not underflow, on one lane and four, and its zero is IEEE's: `-0` @@ -540,9 +357,9 @@ fn the_blends_float_multiply_add_rounds_once_and_signs_its_zeros() { } } -/// The `double` and integer routes never take the unfused shortcut where it differs: the -/// hazard families hold triples a `double` sum rounded to `float` gets wrong, and the -/// cancellations triples where the unfused result differs from the fused one. +/// The triples reach the hazards a shortcut gets wrong: the hazard families hold triples a +/// `double` sum rounded to `float` gets wrong, and the cancellations triples where the unfused +/// result differs from the fused one. #[test] fn the_float_triples_reach_the_hazards() { let t = float_triples(); @@ -663,30 +480,54 @@ fn half_triples() -> Vec<[u64; 3]> { out } -/// A `half` fused multiply-add on 16 bits, by the device's 16-bit `Fma` ([`Route::F16`]) or by -/// `OpFmaKHR` on 16 bits ([`Route::F16Khr`]), is the exact sum rounded once to `half` where the -/// device rounds it once, as the interpreter does: its operands narrow and its result widens -/// exactly. +/// A `half` fused multiply-add on 16-bit floats, by the device's `Fma` ([`Route::F16`]) or by +/// `OpFmaKHR` ([`Route::F16Khr`]), rounds once on the interpreter: the operands convert to 16 bits +/// exactly and the result widens exactly. The device's `float` `Fma` rounded to `half` +/// ([`Route::Native`]) rounds the sum twice, so it is within one `half` unit in the last place. #[test] -fn half_fused_multiply_add_on_16_bits_rounds_once() { +fn half_fused_multiply_add_rounds_on_its_route() { let triples = half_triples(); for route in [Route::F16, Route::F16Khr] { for lanes in [1u8, 2] { let fma = Fma { form: vec(float(16), lanes), route, - tiny: None, }; check_fma( &format!("fma half {route:?} x{lanes}"), fma, - false, &lane_cases(&triples, lanes), &fma16, false, ); } } + // Within one unit in the last place: the `float` sum's rounding may move a `half` tie. + let near = |g: u64, w: u64| { + same(float(16))(g, w) || ((g ^ w) & 0x8000 == 0 && (g & 0x7FFF).abs_diff(w & 0x7FFF) <= 1) + }; + for lanes in [1u8, 2] { + let f = vec(float(16), lanes); + let fma = Fma { + form: f, + route: Route::Native, + }; + check_accept( + &format!("fma half native x{lanes}"), + &[f, f, f], + f, + &|fb, x| fma::emit(fb, fma, x), + &lane_cases(&triples, lanes), + &|c| { + Some( + (0..c[0].len()) + .map(|l| fma16(c[0][l], c[1][l], c[2][l])) + .collect(), + ) + }, + &near, + ); + } } /// The `half` reference itself: exact sums of a few hand-checked triples, signed zeros, the @@ -708,288 +549,51 @@ fn the_half_reference_rounds_the_exact_sum() { assert_eq!(fma16(0x0003, 0x3800, 0), 0x0002); } -/// The route follows the profile: `OpFmaKHR` where `shaderFmaFloat32` is enabled, else `double` -/// where 64-bit floats and integers are, else the integer routine; `half` has its own, the device's -/// 16-bit `Fma` where the driver is measured to compute it as Metal's `half` `fma` and -/// `shaderFloat16` is enabled (the MoltenVK captures alone), else `OpFmaKHR` on 16 bits where -/// `shaderFmaFloat16` is enabled and the profile rounds under the 16-bit float controls, else the -/// device's `float` `Fma` ([`Route::Native`]), under either policy, with no routine; and `bfloat` -/// and `double` keep their own lowering. -/// -/// Under native device maths (the default policy) a profile whose functions are not Metal's takes -/// the device's `Fma` ([`Route::Native`]) where it would take a routine. Under -/// `FloatMathsPolicy::Exact`, `OpFmaKHR` on a profile whose functions are not Metal's own (not -/// MoltenVK, whose `fma` is Metal's) is checked by the `double` routine where it is offered, else -/// the integer one ([`fma::tiny_route`]), whether or not the device reads its denormals as Metal -/// does (`DriverDeviation::MetalFloatDenormals`): it rounds before it flushes. +/// The route follows the profile: `float` by `OpFmaKHR` where `shaderFmaFloat32` is enabled, else +/// the device's `Fma`; `half` by the device's 16-bit `Fma` where the driver is measured to compute +/// it as Metal's `half` `fma` and `shaderFloat16` is enabled (the MoltenVK captures alone), else +/// `OpFmaKHR` on 16 bits where `shaderFmaFloat16` is enabled and the profile rounds under the +/// 16-bit float controls, else the device's `float` `Fma` rounded to `half`; `bfloat` and `double` +/// keep their own lowering. #[test] fn the_fused_multiply_add_route_follows_the_profile() { - use crate::device::profile::FloatFunctions; use crate::error::DriverDeviation; - use crate::pipeline::testing::exact_maths; - use crate::spirv::testing::{committed_profiles_with, is_moltenvk_capture}; - // The `half` route a profile offers whatever its policy: Metal's measured `Fma`, or `OpFmaKHR` - // on 16 bits under the float controls, else the device's `float` `Fma`. - let half_route = |p: &crate::device::DeviceProfile| { + use crate::spirv::testing::is_moltenvk_capture; + let mut seen = BTreeSet::new(); + let mut f16 = 0; + let mut khr16 = 0; + for (stem, p) in committed_profiles().expect("profiles") { let l = &p.fields().leaf; - if p.takes_driver_deviation(DriverDeviation::MetalHalfFma) && l.float16 { + let want = if l.fma32 { Route::Khr } else { Route::Native }; + assert_eq!(Fma::on(&p, float(32)).expect("float").route, want, "{stem}"); + let half = if p.takes_driver_deviation(DriverDeviation::MetalHalfFma) && l.float16 { Route::F16 } else if l.fma16 - && crate::lower::arith::narrow::quantize_form(p) - == crate::spirv::builder::QuantizeForm::Controlled + && crate::lower::arith::narrow::quantize_form(&p) == QuantizeForm::Controlled { Route::F16Khr } else { Route::Native - } - }; - let mut native = 0; - let mut khr16 = 0; - for (stem, p) in committed_profiles().expect("profiles") { - let l = &p.fields().leaf; - if p.fields().float_functions != FloatFunctions::Native { - continue; - } - native += 1; - let want = if l.fma32 { Route::Khr } else { Route::Native }; - let f = Fma::on(&p, float(32)).expect("float"); - assert_eq!((f.route, f.routine()), (want, None), "{stem}"); - let h = Fma::on(&p, float(16)).expect("half"); - let half = half_route(&p); - assert_eq!((h.route, h.routine()), (half, None), "{stem}"); - khr16 += usize::from(half == Route::F16Khr); - } - assert!(native >= 10, "{native} profiles take native device maths"); - assert!(khr16 >= 2, "{khr16} profiles take OpFmaKHR on 16 bits"); - let mut seen = std::collections::BTreeSet::new(); - let mut f16 = Vec::new(); - let mut checked = 0; - let mut flushing = 0; - let mut metals = 0; - for (stem, p) in committed_profiles_with(exact_maths()).expect("profiles") { - let l = &p.fields().leaf; - let want = if l.fma32 { - Route::Khr - } else if l.float64 && l.int64 { - Route::Wide - } else { - Route::Soft }; - let f = Fma::on(&p, float(32)).expect("float"); - assert_eq!(f.route, want, "{stem}"); - // Metal's own functions (MoltenVK) take its `fma`, unchecked. - let device = p.fields().float_functions == FloatFunctions::Device; - let tiny = (want == Route::Khr && device).then_some(if l.float64 && l.int64 { - Route::Wide - } else { - Route::Soft - }); - assert_eq!(f.tiny, tiny, "{stem}"); - // `OpFmaKHR` checked through `double` calls the routine of its small results alone. - assert_eq!( - f.routine(), - match want { - Route::Khr => tiny.map(|t| if t == Route::Wide { Route::Khr } else { t }), - _ => Some(want), - } - .map(|route| Routine { route, lanes: 1 }), - "{stem}" - ); - checked += usize::from(tiny.is_some()); - metals += usize::from(want == Route::Khr && !device); - flushing += usize::from( - tiny.is_some() && p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals), - ); - let half = half_route(&p); - let h = Fma::on(&p, float(16)).expect("half"); - assert_eq!((h.route, h.routine()), (half, None), "{stem}"); - if half == Route::F16 { - f16.push(stem.clone()); - } + assert_eq!(Fma::on(&p, float(16)).expect("half").route, half, "{stem}"); assert_eq!(half == Route::F16, is_moltenvk_capture(&stem), "{stem}"); + f16 += usize::from(half == Route::F16); + khr16 += usize::from(half == Route::F16Khr); assert_eq!(Fma::on(&p, bfloat()), None, "{stem}"); assert_eq!(Fma::on(&p, float(64)), None, "{stem}"); seen.insert(want); } assert_eq!( seen, - fma::FLOAT_ROUTES.into_iter().collect(), + BTreeSet::from([Route::Khr, Route::Native]), "every float route is some committed profile's" ); - assert!(!f16.is_empty(), "{f16:?}"); - assert!(checked >= 1, "{checked} profiles check OpFmaKHR"); - assert!( - flushing >= 1, - "{flushing} profiles check OpFmaKHR on a device that flushes its denormals" - ); - assert!( - metals >= 1, - "{metals} profiles take Metal's own OpFmaKHR unchecked" - ); + assert!(f16 >= 1, "{f16} profiles take Metal's 16-bit Fma"); + assert!(khr16 >= 2, "{khr16} profiles take OpFmaKHR on 16 bits"); } -/// The words of a module of the functions `defs` defines and an empty entry point. -fn defined_words(defs: &dyn Fn(&mut ModuleBuilder) -> BResult<()>) -> usize { - let mut b = ModuleBuilder::new(); - defs(&mut b).expect("define"); - let void = b.ty(Type::Void).expect("void"); - let fb = b.function(void).expect("entry"); - let id = { - let mut fb = fb; - fb.ret(None).expect("ret"); - fb.finish().expect("finish") - }; - b.entry( - ExecModel::GLCompute, - id, - vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }], - ) - .expect("entry"); - let m = b.finalize().expect("finalize"); - crate::spirv::serialize::serialize(m) - .expect("serialize") - .words - .len() -} - -/// The routines' words stay within their estimates: each routine's function, defined alone, and -/// each use; and a routine defined per lane, beside its route's routine on one lane, its type -/// included. A use of `OpFmaKHR` checked ([`Fma::checked`]) stays within its own estimate, on one -/// lane and four, by the integer routine and by the routine of its small results. -#[test] -fn fused_multiply_add_routines_fit_their_word_estimates() { - let lanes_and_routes = [1u8, 4] - .into_iter() - .flat_map(|lanes| [(lanes, Route::Soft), (lanes, Route::Wide)]); - for (lanes, tiny) in lanes_and_routes { - let fma = Fma { - form: floats(lanes), - route: Route::Khr, - tiny: Some(tiny), - }; - let r = fma.routine().expect("a checked use's routine"); - // The routine and a function of three floats that answers their `fma`, or its first. - let module = |uses: bool| { - defined_words(&|b| { - let id = fma::define(b, r)?; - let e = b.ty(Type::Float { width: 32 })?; - let t = match lanes { - 1 => e, - len => b.ty(Type::Vector { elem: e, len })?, - }; - let mut fb = b.routine(t)?; - let xyz = [fb.param(t)?, fb.param(t)?, fb.param(t)?]; - let v = match uses { - true => fma::emit(&mut fb, fma, &xyz, Some(id))?, - false => xyz[0], - }; - fb.ret(Some(v))?; - fb.finish().map(drop) - }) - }; - let words = module(true) - module(false); - assert!( - words <= fma.words() as usize, - "checked by {tiny:?} x{lanes}: {words} words against the estimate {}", - fma.words() - ); - } - let within = |what: &str, words: usize, estimate: u32| { - let estimate = estimate as usize; - assert!( - words <= estimate && words * 3 >= estimate * 2, - "{what}: {words} words against the estimate {estimate} (within its last third)" - ); - }; - for route in [Route::Wide, Route::Soft] { - let one = Routine { route, lanes: 1 }; - let alone = defined_words(&|b| fma::define(b, one).map(drop)); - for lanes in [1u8, 4] { - let r = Routine { route, lanes }; - let words = defined_words(&|b| fma::define(b, r).map(drop)); - within(&format!("{route:?} x{lanes}"), words, r.words()); - } - for lanes in [2u8, 4] { - let r = Routine { route, lanes }; - let both = defined_words(&|b| { - let id = fma::define(b, one)?; - fma::define_per_lane(b, r, id).map(drop) - }); - within( - &format!("{route:?} x{lanes} per lane"), - both - alone, - r.per_lane_words(), - ); - } - } - // The routine of `OpFmaKHR`'s small results, never defined per lane. - for lanes in [1u8, 4] { - let r = Routine { - route: Route::Khr, - lanes, - }; - let words = defined_words(&|b| fma::define(b, r).map(drop)); - within(&format!("Khr x{lanes}"), words, r.words()); - } -} - -/// A route a module calls on one lane and on more is defined per lane on more; one called only on -/// `k` (two or more) vector lane counts gets its routine on one lane where the `k - 1` sequences -/// that saves outweigh the per-lane routines twice (the integer and `double` routes on two lane -/// counts and on three); a route called on one lane count keeps its one routine, on any lanes. Each -/// routine is charged its per-lane words where it is defined per lane. -#[test] -fn a_route_on_several_lane_counts_holds_its_sequence_once() { - let r = |route, lanes| Routine { route, lanes }; - let mut fmas = BTreeSet::from([ - r(Route::Soft, 2), - r(Route::Soft, 4), - r(Route::Wide, 1), - r(Route::Wide, 3), - ]); - fma::complete(&mut fmas); - assert_eq!( - fmas, - BTreeSet::from([ - r(Route::Soft, 1), - r(Route::Soft, 2), - r(Route::Soft, 4), - r(Route::Wide, 1), - r(Route::Wide, 3), - ]) - ); - let per_lane: Vec = fmas - .iter() - .copied() - .filter(|x| fma::per_lane(*x, &fmas)) - .collect(); - assert_eq!( - per_lane, - [r(Route::Wide, 3), r(Route::Soft, 2), r(Route::Soft, 4)] - ); - // A double route on two vector lane counts gets its one-lane routine too, and so does one on - // three, which saves two sequences. - for lanes in [&[2u8, 4][..], &[2, 3, 4]] { - let mut double: BTreeSet = lanes.iter().map(|&n| r(Route::Wide, n)).collect(); - fma::complete(&mut double); - assert!(double.contains(&r(Route::Wide, 1)), "{double:?}"); - } - for x in &fmas { - let want = if per_lane.contains(x) { - x.per_lane_words() - } else { - x.words() - }; - assert_eq!(x.words_among(&fmas), want, "{x:?}"); - } - // Completing again adds nothing. - let again = fmas.clone(); - fma::complete(&mut fmas); - assert_eq!(fmas, again); -} - -/// Run Metal's `mix` ([`math::metal_mix`]) through `fma`'s route (its routine defined when it -/// has one) over `cases` and compare with `reference` per lane, as [`check_fma`] does. +/// Run Metal's `mix` ([`math::metal_mix`]) through `fma`'s route over `cases` and compare with +/// `reference` per lane, as [`check_fma`] does. fn check_mix( what: &str, fma: Fma, @@ -998,31 +602,14 @@ fn check_mix( exact: bool, ) { let f = fma.form; - let routine = fma.routine(); - let m = kernel_defs( - &[f, f, f], - f, - &|b| { - Ok(routine - .map(|r| fma::define(b, r)) - .transpose()? - .into_iter() - .collect()) - }, - &|fb, x, funcs| { - let id = funcs.first().copied(); - let fused = |fb: &mut FunctionBuilder<'_>, args: &[Value]| fma::emit(fb, fma, args, id); - math::metal_mix(fb, f, [x[0], x[1], x[2]], &fused, false) - }, - true, - false, - ) - .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); - check_module( + check_accept( what, - m, &[f, f, f], f, + &|fb, x| { + let fused = |fb: &mut FunctionBuilder<'_>, args: &[Value]| fma::emit(fb, fma, args); + math::metal_mix(fb, f, [x[0], x[1], x[2]], &fused) + }, cases, &|c| { Some( @@ -1073,58 +660,45 @@ fn metal_float_mixes() -> Vec<[u64; 4]> { .collect() } -/// Metal's `mix(x, y, t)` on `float` and `half` is `fma(t, y, fma(-t, x, x))`, each fused -/// multiply-add rounding once on the profile's route, on scalars and vectors. Against the -/// composition of each route's reference over the fused multiply-add triples (as `(x, y, t)`): -/// bit for bit on the routines, which answer Metal's `fma` ([`metal_fma32`]); `OpFmaKHR` and -/// `half`'s `OpFmaKHR` on 16 bits ([`Route::F16Khr`]) by value, a NaN for a NaN. And Metal's -/// recorded words: [`metal_float_mixes`] on -/// every `float` route (bit for bit on the routines), and `nan_half`'s `mix(-0.3, 0.7, 0.2)` -/// (`0xB4CD`, `0x399A`, `0x3266`), `0xAE68` where the blend gives `0xAE66`, and `mix(inf, 0, 0)` -/// and `mix(inf, 1, 0.5)`, NaN. +/// Metal's `mix(x, y, t)` on `float` and `half` is `fma(t, y, fma(-t, x, x))` (MoltenVK's order, +/// and a `half` one's on the 16-bit `Fma`), each fused multiply-add rounding once on its route, on +/// scalars and vectors. Against the composition of each route's reference over the fused +/// multiply-add triples (as `(x, y, t)`), by value, a NaN for a NaN. And Metal's recorded words: +/// [`metal_float_mixes`] on `OpFmaKHR`, and `nan_half`'s `mix(-0.3, 0.7, 0.2)` (`0xB4CD`, `0x399A`, +/// `0x3266`), `0xAE68` where the blend gives `0xAE66`, and `mix(inf, 0, 0)` and `mix(inf, 1, 0.5)`, +/// NaN. #[test] fn mix_is_metals_two_fused_multiply_adds() { let flip32 = |t: u64| t ^ 0x8000_0000; let triples = float_triples(); let pinned = metal_float_mixes(); - for (route, exact) in [ - (Route::Khr, false), - (Route::Wide, true), - (Route::Soft, true), - ] { - let fused = move |a: u64, b: u64, c: u64| match route { - Route::Khr => fma32(a, b, c), - _ => metal_fma32(a, b, c), + let reference = move |x: u64, y: u64, t: u64| fma32(t, y, fma32(flip32(t), x, x)); + for lanes in [1u8, 3] { + let fma = Fma { + form: floats(lanes), + route: Route::Khr, }; - let reference = move |x: u64, y: u64, t: u64| fused(t, y, fused(flip32(t), x, x)); - for lanes in [1u8, 3] { - let fma = Fma { - form: floats(lanes), - route, - tiny: None, - }; - check_mix( - &format!("mix {route:?} x{lanes}"), - fma, - &lane_cases(&triples, lanes), - &reference, - exact, - ); - let rows: Vec<[u64; 3]> = pinned.iter().map(|r| [r[0], r[1], r[2]]).collect(); - let want = |x: u64, y: u64, t: u64| { - pinned - .iter() - .find(|r| [r[0], r[1], r[2]] == [x, y, t]) - .map_or(0, |r| r[3]) - }; - check_mix( - &format!("mix {route:?} x{lanes}, Metal's words"), - fma, - &lane_cases(&rows, lanes), - &want, - exact, - ); - } + check_mix( + &format!("mix x{lanes}"), + fma, + &lane_cases(&triples, lanes), + &reference, + false, + ); + let rows: Vec<[u64; 3]> = pinned.iter().map(|r| [r[0], r[1], r[2]]).collect(); + let want = |x: u64, y: u64, t: u64| { + pinned + .iter() + .find(|r| [r[0], r[1], r[2]] == [x, y, t]) + .map_or(0, |r| r[3]) + }; + check_mix( + &format!("mix x{lanes}, Metal's words"), + fma, + &lane_cases(&rows, lanes), + &want, + false, + ); } let half_triples = half_triples(); let reference = |x: u64, y: u64, t: u64| fma16(t, y, fma16(t ^ 0x8000, x, x)); @@ -1136,8 +710,7 @@ fn mix_is_metals_two_fused_multiply_adds() { for lanes in [1u8, 2] { let fma = Fma { form: vec(float(16), lanes), - route: Route::F16Khr, - tiny: None, + route: Route::F16, }; check_mix( &format!("mix half x{lanes}"), @@ -1240,45 +813,26 @@ const METAL_HALF_DOTS: [([u16; 4], [u16; 4], [u16; 3]); 6] = [ ]; /// Run Metal's `dot` ([`math::metal_dot`]) of two vectors of `lanes` lanes through `fma`'s route -/// on one lane (its routine defined when it has one), flushing the chain's values where `flush`, -/// over `cases` and compare with `reference(x, y)`: bit for bit when `exact`, else any NaN for a -/// NaN. +/// on one lane over `cases` and compare with `reference(x, y)`: bit for bit when `exact`, else any +/// NaN for a NaN. fn check_dot( what: &str, fma: Fma, lanes: u8, - flush: bool, cases: &[Case], reference: &dyn Fn(&[u64], &[u64]) -> u64, exact: bool, ) { let s = fma.form; let v = vec(s, lanes); - let routine = fma.routine(); - let m = kernel_defs( - &[v, v], - s, - &|b| { - Ok(routine - .map(|r| fma::define(b, r)) - .transpose()? - .into_iter() - .collect()) - }, - &|fb, x, funcs| { - let id = funcs.first().copied(); - let fused = |fb: &mut FunctionBuilder<'_>, args: &[Value]| fma::emit(fb, fma, args, id); - math::metal_dot(fb, v, [x[0], x[1]], &fused, (flush, None)) - }, - true, - false, - ) - .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); - check_module( + check_accept( what, - m, &[v, v], s, + &|fb, x| { + let fused = |fb: &mut FunctionBuilder<'_>, args: &[Value]| fma::emit(fb, fma, args); + math::metal_dot(fb, v, [x[0], x[1]], &fused) + }, cases, &|c| Some(vec![reference(&c[0], &c[1])]), &|g, w| if exact { g == w } else { same(s)(g, w) }, @@ -1304,67 +858,51 @@ fn dot_cases(triples: &[[u64; 3]], lanes: u8) -> Vec { } /// Metal's `dot` on `float` and `half` is the products' fused chain, `fma(x[n-1], y[n-1], ... -/// fma(x[1], y[1], x[0] * y[0]))`, on two, three and four lanes. On every `float` route against the -/// chain of each route's fused multiply-add over the fused multiply-add triples (bit for bit on the -/// routines, which answer Metal's `fma`; with the chain's values flushed on `OpFmaKHR` where the -/// device may keep a denormal), and against Metal's recorded words ([`METAL_FLOAT_DOTS`], bit for -/// bit on every route); on `half`'s `OpFmaKHR` on 16 bits ([`Route::F16Khr`]) the same against the -/// `half` chain and [`METAL_HALF_DOTS`]. +/// fma(x[1], y[1], x[0] * y[0]))` (MoltenVK's order, and a `half` one's on the 16-bit `Fma`), on +/// two, three and four lanes: on `OpFmaKHR` against the chain of its fused multiply-add over the +/// fused multiply-add triples and against Metal's recorded words ([`METAL_FLOAT_DOTS`], bit for +/// bit); on the 16-bit `Fma` the same against the `half` chain and [`METAL_HALF_DOTS`]. #[test] fn dot_is_metals_fused_chain() { let triples = float_triples(); - for (route, flush, exact) in [ - (Route::Khr, false, false), - (Route::Khr, true, false), - (Route::Wide, false, true), - (Route::Soft, false, true), - ] { - let step = move |a: u64, b: u64, c: u64| match (route, flush) { - (Route::Khr, false) => fma32(a, b, c), - (Route::Khr, true) => fma32(a, b, ftz(c)), - _ => metal_fma32(a, b, c), - }; - let reference = move |x: &[u64], y: &[u64]| { - let mut sum = u64::from((f32v(x[0]) * f32v(y[0])).to_bits()); - for l in 1..x.len() { - sum = step(x[l], y[l], sum); - } - sum - }; - let fma = Fma { - form: floats(1), - route, - tiny: None, - }; - for lanes in [2u8, 3, 4] { - let what = format!("dot {route:?} x{lanes}, flush {flush}"); - let cases = dot_cases(&triples, lanes); - check_dot(&what, fma, lanes, flush, &cases, &reference, exact); - let n = usize::from(lanes); - let pinned: Vec = METAL_FLOAT_DOTS - .iter() - .map(|(x, y, _)| { - [x, y] - .map(|v| v[..n].iter().map(|b| u64::from(*b)).collect()) - .to_vec() - }) - .collect(); - let want = |x: &[u64], _: &[u64]| { - METAL_FLOAT_DOTS - .iter() - .find(|(mx, ..)| mx[..n].iter().map(|b| u64::from(*b)).eq(x.iter().copied())) - .map_or(0, |(.., w)| u64::from(w[n - 2])) - }; - check_dot( - &format!("{what}, Metal's words"), - fma, - lanes, - flush, - &pinned, - &want, - true, - ); + let reference = |x: &[u64], y: &[u64]| { + let mut sum = u64::from((f32v(x[0]) * f32v(y[0])).to_bits()); + for l in 1..x.len() { + sum = fma32(x[l], y[l], sum); } + sum + }; + let fma = Fma { + form: floats(1), + route: Route::Khr, + }; + for lanes in [2u8, 3, 4] { + let what = format!("dot x{lanes}"); + let cases = dot_cases(&triples, lanes); + check_dot(&what, fma, lanes, &cases, &reference, false); + let n = usize::from(lanes); + let pinned: Vec = METAL_FLOAT_DOTS + .iter() + .map(|(x, y, _)| { + [x, y] + .map(|v| v[..n].iter().map(|b| u64::from(*b)).collect()) + .to_vec() + }) + .collect(); + let want = |x: &[u64], _: &[u64]| { + METAL_FLOAT_DOTS + .iter() + .find(|(mx, ..)| mx[..n].iter().map(|b| u64::from(*b)).eq(x.iter().copied())) + .map_or(0, |(.., w)| u64::from(w[n - 2])) + }; + check_dot( + &format!("{what}, Metal's words"), + fma, + lanes, + &pinned, + &want, + true, + ); } let half_triples = half_triples(); let reference = |x: &[u64], y: &[u64]| { @@ -1376,8 +914,7 @@ fn dot_is_metals_fused_chain() { }; let fma = Fma { form: float(16), - route: Route::F16Khr, - tiny: None, + route: Route::F16, }; for lanes in [2u8, 3, 4] { let what = format!("dot half x{lanes}"); @@ -1385,7 +922,6 @@ fn dot_is_metals_fused_chain() { &what, fma, lanes, - false, &dot_cases(&half_triples, lanes), &reference, false, @@ -1409,7 +945,6 @@ fn dot_is_metals_fused_chain() { &format!("{what}, Metal's words"), fma, lanes, - false, &pinned, &want, true, diff --git a/crates/metal2vulkan/src/lower/arith/tests/libm.rs b/crates/metal2vulkan/src/lower/arith/tests/libm.rs index 213df02e0..0df3d442c 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/libm.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/libm.rs @@ -1,35 +1,12 @@ -//! The math-library routines on the interpreter: each within its bound of the exact value over -//! operands across the whole range, and Metal's answers at the special operands, bit for bit. A -//! routine divides and takes square roots only through the module's correctly rounded routines, so -//! its answers are every device's; those of `sqrt` and `rsqrt` correct the device's own, which -//! their tests also move to the edge of what they correct. -//! -//! The reference is the host's `f64` function of the exact operand, rounded nowhere: the error is -//! measured in ulps of the `float` grid at the exact value (the result's exponent, `2^-149` below -//! the normal range). +//! The maths routines left on the interpreter: precise `fmod`'s routine, exact against C's `fmod` +//! on `float` and on `half`, and the infinite product of Metal's fast `pow` and `powr`. use super::*; -use crate::lower::arith::libm::{self, Fun, Mode}; -use crate::spirv::serialize::serialize; -use std::cell::Cell; - -/// `float` scalars. -pub(super) fn f32s() -> Form { - float(32) -} - -/// The ulp of the `float` grid at `v`. -fn ulp32(v: f64) -> f64 { - let a = v.abs(); - if a < 2f64.powi(-126) { - return 2f64.powi(-149); - } - 2f64.powi(a.log2().floor() as i32 - 23) -} +use crate::lower::arith::libm::{self, Lib}; /// Operands: every 2^k from `2^-126` to `2^127` and their neighbours, both signs, pseudo-random /// bit patterns of every exponent, and the interval edges each routine reduces by. -pub(super) fn operands(seed: u64, random: usize) -> Vec { +fn operands(seed: u64, random: usize) -> Vec { let mut v = Vec::new(); for e in 1u64..255 { for m in [0u64, 1, 0x7F_FFFF, 0x40_0000] { @@ -73,2440 +50,28 @@ pub(super) fn operands(seed: u64, random: usize) -> Vec { v } -/// The routine of `fun` built rough (its division and square root moved) or exact, on a profile -/// whose `float` fused multiply-add is `OpFmaKHR` where `fma`. -pub(super) fn routine_module(fun: Fun, rough: bool, fma: bool) -> TypedModule { - let f = f32s(); - let ins = vec![f; fun.arity()]; +/// A module of precise `fmod` on lanes of form `f`, by its routine (`libm::define_fmod`): a +/// `half` call takes the `float` routine before its rounding. +fn fmod_module(f: Form) -> TypedModule { kernel_defs( - &ins, + &[f, f], f, - &|b| { - Ok(vec![if rough { - libm::define_rough(b, fun, fma)? - } else { - libm::define_alone(b, fun, fma)? - }]) - }, + &|b| Ok(vec![libm::define_fmod(b)?]), &|fb, x, funcs| { - fb.call(funcs[0], x)? - .ok_or(crate::spirv::error::BuildError::Type( - crate::spirv::error::TypeRule::FunctionSignature, - )) - }, - true, - false, - ) - .unwrap_or_else(|e| panic!("{fun:?}: build: {e:?}")) -} - -/// A module of the helpers `fun`'s routine calls ([`Fun::needs`]) alone, each called from the -/// entry so that none leaves as dead: taken from [`routine_module`]'s words, it leaves the -/// routine's own (each helper is charged to its own census name, [`Fun::Recip`]'s routine with its -/// table; Metal's `exp2`, `log2`, and reciprocal tables are charged to the routines that read -/// them, [`Fun::words`]). -pub(super) fn helpers_module(fun: Fun, fma: bool) -> TypedModule { - let f = f32s(); - let ins = vec![f; fun.arity()]; - let needs = libm::Needs { - exp2: false, - log2: false, - rcp: false, - rsqrt: false, - quarter: false, - sinc: false, - ..fun.needs() - }; - // The helpers `define_helpers` defines (the ones `fun` calls and the ones they call), for the - // entry to call each by its own signature. - let defined = Cell::new(libm::Helpers::default()); - kernel_defs( - &ins, - f, - &|b| { - let h = libm::define_helpers(b, needs, false, fma)?; - defined.set(h); - Ok(h.fused - .into_iter() - .chain(h.division) - .chain(h.recip) - .chain(h.inverse_root) - .chain(h.fast_inverse_root) - .collect()) - }, - &|fb, x, _| { - let call = |fb: &mut FunctionBuilder<'_>, id: FuncId, args: &[Value]| { - fb.call(id, args)? - .ok_or(crate::spirv::error::BuildError::Type( - crate::spirv::error::TypeRule::FunctionSignature, - )) - }; - let h = defined.get(); - let mut v = x[0]; - if let Some(id) = h.fused { - v = call(fb, id, &[v, x[0], v])?; - } - if let Some(id) = h.division { - v = call(fb, id, &[v, x[0]])?; - } - if let Some(id) = h.recip { - v = call(fb, id, &[v])?; - } - if let Some(id) = h.inverse_root { - v = call(fb, id, &[v])?; - } - if let Some(id) = h.fast_inverse_root { - v = call(fb, id, &[v])?; - } - Ok(v) - }, - true, - false, - ) - .unwrap_or_else(|e| panic!("{fun:?}: helpers: {e:?}")) -} - -/// Run the routine of `fun` over `cases` (one operand list each), against `exact(operands)` (an -/// `f64`, or `None` where the lane is not measured), accepting `limit` ulps; returns the worst. -pub(super) fn worst_error( - fun: Fun, - rough: bool, - cases: &[Vec], - exact: &dyn Fn(&[f32]) -> Option, - limit: f64, -) -> f64 { - let worst = Cell::new(0f64); - let f = f32s(); - let ins = vec![f; fun.arity()]; - let cases: Vec = cases - .iter() - .map(|c| c.iter().map(|b| vec![*b]).collect()) - .collect(); - check_module( - &format!("{fun:?} rough={rough}"), - routine_module(fun, rough, false), - &ins, - f, - &cases, - &|c| { - let xs: Vec = c.iter().map(|l| f32v(l[0])).collect(); - exact(&xs).map(|r| vec![r.to_bits()]) - }, - &|got, want| { - let (g, w) = (f64::from(f32v(got)), f64v(want)); - if w.is_nan() { - return g.is_nan(); - } - let e = (g - w).abs() / ulp32(w); - if e > worst.get() { - worst.set(e); - } - e <= limit - }, - ); - worst.get() -} - -/// The one-operand cases of `xs`. -pub(super) fn unary(xs: &[u64]) -> Vec> { - xs.iter().map(|x| vec![*x]).collect() -} - -/// Metal's precise `asin` or `acos` of a normal or zero `x` as the model computes it -/// (`libm::atan`'s list): Metal's polynomials by fused Horner steps and its root `z rsqrt(z)` of -/// Metal's inverse root's model ([`rsqrt_model`], 0 at `z = 0`); Metal's NaN past 1. -pub(super) fn precise_arc_model(asin: bool, x: f32) -> f32 { - use crate::lower::arith::libm::atan::{ - ACOS_FAR, ACOS_MID, ACOS_NEAR_END, ASIN_FAR, ASIN_FAR_START, ASIN_HIGH, ASIN_LOW, ASIN_MID, - ASIN_NEAR, ASIN_TINY, - }; - let poly = |c: &[u32], v: f32| { - c.iter() - .rev() - .skip(1) - .fold(f32::from_bits(c[c.len() - 1]), |acc, k| { - acc.mul_add(v, f32::from_bits(*k)) - }) - }; - let root = |z: f32| if z == 0.0 { 0.0 } else { z * rsqrt_model(z) }; - let (half_pi, pi) = (f32::from_bits(0x3FC9_0FDB), f32::from_bits(0x4049_0FDB)); - let a = x.abs(); - if x.is_nan() { - return x; - } - if asin && a.to_bits() < ASIN_TINY { - return x; - } - if a > 1.0 { - return f32::from_bits(0x7FC0_0000); - } - if asin { - let r = if a < 0.1 { - poly(&ASIN_NEAR, a) - } else if a < 0.36 { - poly(&ASIN_LOW, a) - } else if a < 0.62 { - poly(&ASIN_MID, a * a) * a - } else if a.to_bits() < ASIN_FAR_START { - poly(&ASIN_HIGH, a * a) * a - } else { - let z = if a < 0.99 { - (-a).mul_add(a, 1.0) - } else { - (1.0 - a) * (a + 1.0) - }; - root(z).mul_add(poly(&ASIN_FAR, a), half_pi) - }; - r.copysign(x) - } else { - let r = if a.to_bits() <= ACOS_NEAR_END { - (a * (a * a)).mul_add(f32::from_bits(0xBE2A_AAAB), half_pi - a) - } else if a <= 0.5 { - poly(&ACOS_MID, a) - } else { - let u = 1.0 - a; - poly(&ACOS_FAR, u) * root(u) - }; - if x < 0.0 { - pi - r - } else { - r - } - } -} - -/// The precise `asin` and `acos` routines answer [`precise_arc_model`] bit for bit, with and -/// without `OpFmaKHR`, over the normal and zero operands in `[-1, 1]` of [`operands`], every -/// region's edges, and every 65,537th `float` of `[0, 1]` of both signs, and lie within Apple's -/// bound (4 ulp, MSL Table 8.1) of the exact value there. Part `part` of `of` checks every -/// `of`-th operand. -fn precise_asin_and_acos_are_metals(part: usize, of: usize) { - use crate::lower::arith::libm::atan::{ACOS_NEAR_END, ASIN_FAR_START, ASIN_TINY}; - let mut xs: Vec = operands(0x07A4_E297, 4000) - .into_iter() - .filter(|b| { - let v = f32v(*b); - v.abs() <= 1.0 && (v == 0.0 || v.is_normal()) - }) - .collect(); - for edge in [ - ASIN_TINY, - 0.1f32.to_bits(), - 0.36f32.to_bits(), - 0.62f32.to_bits(), - ASIN_FAR_START, - 0.99f32.to_bits(), - ACOS_NEAR_END, - 0.5f32.to_bits(), - 1.0f32.to_bits(), - ] { - for d in 0..=64u32 { - let b = (edge + d).wrapping_sub(32); - if f32::from_bits(b) <= 1.0 { - xs.push(u64::from(b)); - } - } - } - xs.extend((0..=0x3F80_0000u32).step_by(65_537).map(u64::from)); - let signed: Vec = xs - .iter() - .flat_map(|b| [*b & 0x7FFF_FFFF, *b | 0x8000_0000]) - .collect(); - let signed = part_of(signed, part, of); - let f = f32s(); - for asin in [true, false] { - let fun = if asin { - Fun::Asin(Mode::Precise) - } else { - Fun::Acos(Mode::Precise) - }; - for fma in [false, true] { - check_module( - &format!("{fun:?} fma={fma}"), - routine_module(fun, false, fma), - &[f], - f, - &signed.iter().map(|x| vec![vec![*x]]).collect::>(), - &|c| { - Some(vec![u64::from( - precise_arc_model(asin, f32v(c[0][0])).to_bits(), - )]) - }, - &|g, w| g == w, - ); - } - let worst = signed - .iter() - .map(|b| { - let x = f32v(*b); - let e = if asin { - f64::from(x).asin() - } else { - f64::from(x).acos() - }; - let w = f64::from(precise_arc_model(asin, x)); - let r = e.abs() as f32; - let ulp = f64::from(f32::from_bits(r.to_bits() + 1)) - f64::from(r); - if e == 0.0 { - 0.0 - } else { - (w - e).abs() / ulp - } - }) - .fold(0f64, f64::max); - assert!(worst <= 4.0, "{fun:?}: {worst:.3} ulp"); - } -} - -mod precise_asin_and_acos_routines_are_metals { - parts!(super::precise_asin_and_acos_are_metals, 4; part_1_of_4 = 0, part_2_of_4 = 1, - part_3_of_4 = 2, part_4_of_4 = 3); -} - -/// Metal's reduction of a finite `x` to quarter turns as the model computes it -/// (`libm::quarter::turns`): `(r, k)`, `k` modulo `2^32`, with the rounding error of the large -/// operands' difference where `compensated` (`tan`). -pub(super) fn metal_quarter_turns(x: f32, compensated: bool) -> (f32, u32) { - use crate::lower::arith::libm::quarter::{QUARTER, QUARTER_TABLE}; - let a = x.to_bits() & 0x7FFF_FFFF; - let rounded = |c: f32, v: f32, like: f32| { - let b = 8_388_608f32.copysign(like); - c.mul_add(v, b) - b - }; - // An integer-valued `float` below `2^32` in magnitude, modulo `2^32`. - let int = |k: f32| (k as i64) as u32; - if a < 0x4A00_0000 { - let [c0, c1, c2] = QUARTER.map(f32::from_bits); - let k = rounded(c0, x, x); - let r = c2.mul_add(x, c1.mul_add(x, c0.mul_add(x, -k))); - return (r, int(k)); - } - let [h, m, l] = QUARTER_TABLE[((a - 0x4A00_0000) >> 24) as usize].map(f32::from_bits); - let xs = x * f32::from_bits(0x0080_0000); - let p = xs * h; - let k0 = if p.abs() >= 8_388_608.0 { - p - } else { - rounded(h, xs, p) - }; - let r0 = h.mul_add(xs, -k0); - let r1 = m.mul_add(xs, r0); - let k1 = (r1 + 0.5f32.copysign(r1)).trunc(); - let d = r0 - k1; - let r = l.mul_add(xs, m.mul_add(xs, d)); - let r = if compensated { - let e1 = d - r0; - r + ((-k1 - e1) + (r0 - (d - e1))) - } else { - r - }; - (r, int(k0).wrapping_add(int(k1))) -} - -/// Metal's precise `tan(x)` as the model computes it: the routine's form (`libm::tan`) in `f32` -/// arithmetic, each of Metal's fused steps one `mul_add`, and the quotient correctly rounded. -pub(super) fn metal_tan_model(x: f32) -> f32 { - use crate::lower::arith::libm::tan::{TAN_P, TAN_Q}; - let a = x.to_bits() & 0x7FFF_FFFF; - if a >= 0x7F80_0000 { - return f32::from_bits(0x7FC0_0000); - } - if a < 0x3A00_0000 { - return x; - } - let poly = |c: &[u32], v: f32| { - let (last, rest) = c.split_last().expect("coefficients"); - rest.iter().rev().fold(f32::from_bits(*last), |acc, k| { - acc.mul_add(v, f32::from_bits(*k)) - }) - }; - let (r, k) = metal_quarter_turns(x, true); - let s = r * r; - let n = r * poly(&TAN_P, s); - let d = poly(&TAN_Q, s); - if k & 1 == 0 { - n / d - } else { - -d / n - } -} - -/// The model of Metal's hardware `sinc` of `|t| <= 1` (`libm::sincos::SINC`), in 64-bit integers. -pub(super) fn metal_sinc_model(at: f32) -> f32 { - use crate::lower::arith::libm::sincos::SINC; - let m = (at * 8_388_608.0) as u32; - if m == 0 { - return std::f32::consts::FRAC_PI_2; - } - if m >= 1 << 23 { - return 1.0; - } - let row = SINC[(m >> 18) as usize]; - let d = i64::from(m & 0x3_FFFF); - let c = |i: usize| i64::from(row[i] as i32); - let t2 = c(3) + ((c(4) * d) >> 18); - let t1 = c(2) + ((t2 * d) >> 18); - let w = c(1) + ((t1 * d) >> 18); - f32::from_bits(row[0].wrapping_add(((w + 2048) >> 12) as u32)) -} - -/// Metal's precise `sin(x)` (or `cos(x)` where `cos`) as the model computes it: the routine's form -/// (`libm::sincos`) in `f32` arithmetic, the reduction's fused steps each one `mul_add`, and the -/// `sinc` [`metal_sinc_model`]. -pub(super) fn metal_sin_cos_model(x: f32, cos: bool) -> f32 { - let a = x.to_bits() & 0x7FFF_FFFF; - if a >= 0x7F80_0000 { - return f32::from_bits(0x7FC0_0000); - } - if a <= 0x3980_0000 { - return if cos { 1.0 } else { x }; - } - let (r, k) = metal_quarter_turns(x, false); - let odd = k & 1 != 0; - let t = match (cos, odd) { - (false, false) => r, - (true, true) => -r, - _ => 1.0 - r.abs(), - }; - let t = if k & 2 != 0 { -t } else { t }; - t * metal_sinc_model(t.abs()) -} - -/// The precise `tan` routine answers [`metal_tan_model`] bit for bit, with and without `OpFmaKHR`, -/// over [`trig_operands`] (every binade, and the floats nearest multiples of `π/2` to `2^40 π/2`), -/// every reduction's and region's edges, and every 65,537th finite `float`, both signs; and the -/// model lies within 5 ulp of the exact value there (Apple's bound: 6; Metal's worst over every -/// 251st `float` from `2^-11` and the floats nearest the first `2^22` multiples of `π/2`, by the -/// model, is 4.77). Part `part` of `of` checks every `of`-th operand. -fn precise_tan_is_metals(part: usize, of: usize) { - let mut xs = trig_operands(); - for edge in [0x3A00_0000u32, 0x4A00_0000, 0x4B00_0000, 0x7F00_0000] { - for d in 0..=64u32 { - xs.push(u64::from((edge + d).wrapping_sub(32))); - } - } - xs.extend((0..0x7F80_0000u32).step_by(65_537).map(u64::from)); - let signed: Vec = xs - .iter() - .flat_map(|b| [*b & 0x7FFF_FFFF, *b | 0x8000_0000]) - .filter(|b| f32v(*b).is_finite()) - .collect(); - let signed = part_of(signed, part, of); - let f = f32s(); - for fma in [false, true] { - check_module( - &format!("Tan fma={fma}"), - routine_module(Fun::Tan, false, fma), - &[f], - f, - &signed.iter().map(|x| vec![vec![*x]]).collect::>(), - &|c| Some(vec![u64::from(metal_tan_model(f32v(c[0][0])).to_bits())]), - &|g, w| g == w, - ); - } - let worst = signed - .iter() - .map(|b| { - let x = f32v(*b); - let e = f64::from(x).tan(); - let r = e.abs() as f32; - let ulp = f64::from(f32::from_bits(r.to_bits() + 1)) - f64::from(r); - (f64::from(metal_tan_model(x)) - e).abs() / ulp - }) - .fold(0f64, f64::max); - assert!(worst <= 5.0, "Tan: {worst:.3} ulp"); -} - -mod precise_tan_routine_is_metals { - parts!(super::precise_tan_is_metals, 4; part_1_of_4 = 0, part_2_of_4 = 1, - part_3_of_4 = 2, part_4_of_4 = 3); -} - -/// [`metal_tan_model`] is Metal's precise `tan` at words measured on the M3 Max -/// in each of its ranges (below 1/4, `[1/4, 1)`, `[1, 4)`, `[4, 2^21)` and from `2^21`), where -/// Metal's word is not the correctly rounded value, and the routine answers them bit for bit, with -/// and without `OpFmaKHR`. -#[test] -fn precise_tan_answers_metals_measured_words() { - let words: [(u32, u32); 40] = [ - (0x3A00_1A10, 0x3A00_1A10), - (0x3A00_3BC0, 0x3A00_3BC0), - (0x3A00_4240, 0x3A00_4240), - (0x3A00_52C0, 0x3A00_52C0), - (0x3A00_7C70, 0x3A00_7C70), - (0x3A00_9700, 0x3A00_9700), - (0x3A00_B390, 0x3A00_B390), - (0x3A00_CEC0, 0x3A00_CEC0), - (0x3E80_0420, 0x3E82_C093), - (0x3E80_08EF, 0x3E82_C5B2), - (0x3E80_09E4, 0x3E82_C6B7), - (0x3E80_0C6D, 0x3E82_C969), - (0x3E80_139A, 0x3E82_D10E), - (0x3E80_17FA, 0x3E82_D5B7), - (0x3E80_1C05, 0x3E82_DA07), - (0x3E80_200E, 0x3E82_DE52), - (0x3F80_02AB, 0x3FC7_6246), - (0x3F80_05D6, 0x3FC7_6D21), - (0x3F80_0687, 0x3FC7_6F80), - (0x3F80_0812, 0x3FC7_74CC), - (0x3F80_0C21, 0x3FC7_82B6), - (0x3F80_0EB8, 0x3FC7_8B98), - (0x3F80_1172, 0x3FC7_94F3), - (0x3F80_140A, 0x3FC7_9DD7), - (0x4081_FA00, 0x3FA8_28A7), - (0x4085_2000, 0x3FCF_BB23), - (0x4085_D400, 0x3FDA_54AF), - (0x4087_6100, 0x3FF4_CA15), - (0x408B_FA00, 0x4036_0324), - (0x408E_9700, 0x4074_0F56), - (0x4092_5E00, 0x40E5_B628), - (0x4095_4A00, 0x41A9_B476), - (0x4A29_E000, 0x3F89_4A74), - (0x4A5F_E000, 0x4159_4F3A), - (0x4A6B_5000, 0x3F3D_7462), - (0x4A85_A000, 0x3FB8_AE5D), - (0x4AC6_C000, 0xBFB3_8744), - (0x4AF1_C000, 0xBDDA_1E74), - (0x4B1E_9000, 0xBF8D_35D3), - (0x4B4B_4000, 0xBF3A_A6CC), - ]; - let f = f32s(); - for (x, want) in words { - assert_eq!( - metal_tan_model(f32::from_bits(x)).to_bits(), - want, - "model at {x:#010x}" - ); - } - for fma in [false, true] { - check_module( - &format!("Tan fma={fma}"), - routine_module(Fun::Tan, false, fma), - &[f], - f, - &words - .iter() - .map(|(x, _)| vec![vec![u64::from(*x)]]) - .collect::>(), - &|c| { - let x = c[0][0] as u32; - words - .iter() - .find(|(b, _)| *b == x) - .map(|(_, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - } -} - -/// [`precise_arc_model`] is Metal's precise `asin` and `acos` at words measured on the M4 in every -/// region, where Metal's word is not the correctly rounded value, and the -/// routines answer them bit for bit. -#[test] -fn precise_asin_and_acos_answer_metals_measured_words() { - let asin: [(u32, u32); 24] = [ - (0x39E8_9770, 0x39E8_9770), - (0x3A9E_4650, 0x3A9E_4652), - (0x3C3A_A7B0, 0x3C3A_A8B8), - (0x3DCC_CCC0, 0x3DCD_2486), - (0x3DCC_CD50, 0x3DCD_2517), - (0x3E7F_FFC0, 0x3E81_5F2E), - (0x3E80_0002, 0x3E81_5F50), - (0x3EB8_51E0, 0x3EBC_8D8F), - (0x3EB8_51FA, 0x3EBC_8DAB), - (0x3ED7_DE29, 0x3EDE_D627), - (0x3EF3_2927, 0x3EFD_6083), - (0x3F1E_B851, 0x3F2B_32B7), - (0x3F1E_B852, 0x3F2B_32BA), - (0x3F31_6BFF, 0x3F44_0609), - (0x3F41_7C9F, 0x3F5B_5CF2), - (0x3F50_A3D5, 0x3F73_E60B), - (0x3F50_A3D7, 0x3F73_E610), - (0x3F5C_1ABE, 0x3F84_75CB), - (0x3F6C_7255, 0x3F96_B5A7), - (0x3F7D_70A3, 0x3FB6_F1E1), - (0x3F7D_70A8, 0x3FB6_F1F3), - (0x3F7E_4A48, 0x3FBA_4282), - (0x3F7F_2591, 0x3FBE_9BBD), - (0x3F7F_FFFF, 0x3FC9_048B), - ]; - let acos: [(u32, u32); 20] = [ - (0x3980_0230, 0x3FC9_07DB), - (0x3B6A_12A0, 0x3FC8_9AD2), - (0x3D12_1140, 0x3FC4_7F12), - (0x3E7F_FF80, 0x3FA8_B817), - (0x3E80_0000, 0x3FA8_B806), - (0x3EAB_11F4, 0x3F9D_74AF), - (0x3ED5_92EB, 0x3F91_FC08), - (0x3EFF_FFFD, 0x3F86_0A92), - (0x3F00_0001, 0x3F86_0A92), - (0x3F28_BA28, 0x3F59_E76C), - (0x3F53_1DA8, 0x3F19_E6A3), - (0x3F7F_FFFE, 0x39FF_FFFF), - (0xBE80_0000, 0x3FE9_67B0), - (0xBEA4_A4AE, 0x3FF2_F7A4), - (0xBEC9_50F0, 0x3FFC_C98F), - (0xBEFF_FFFE, 0x4006_0A92), - (0xBF00_0004, 0x4006_0A94), - (0xBF28_E452, 0x4012_A406), - (0xBF53_6D36, 0x4022_B96A), - (0xBF7F_FFFF, 0x4049_0A33), - ]; - let f = f32s(); - for (is_asin, words) in [(true, &asin[..]), (false, &acos[..])] { - for (x, w) in words { - assert_eq!( - precise_arc_model(is_asin, f32::from_bits(*x)).to_bits(), - *w, - "{x:#010x}: the model against Metal's word" - ); - } - let fun = if is_asin { - Fun::Asin(Mode::Precise) - } else { - Fun::Acos(Mode::Precise) - }; - for fma in [false, true] { - check_module( - &format!("{fun:?} fma={fma} at Metal's measured words"), - routine_module(fun, false, fma), - &[f], - f, - &words - .iter() - .map(|(x, _)| vec![vec![u64::from(*x)]]) - .collect::>(), - &|c| { - words - .iter() - .find(|(x, _)| u64::from(*x) == c[0][0]) - .map(|(_, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - } - } -} - -/// Metal's fast `atan` (the M3; the M4's words are the same) at lanes where its -/// word is not the correctly rounded one: below `2^-12` (where it is `x` less an ulp), on `[2^-12, -/// 1]`, on `(1, 4)` through Metal's reciprocal, and up to `2^126`; each word bit for bit, both -/// signs. -#[test] -fn fast_atan_answers_metals_words() { - let words: [(u64, u64); 44] = [ - (0x07EE2100, 0x07EE20FF), - (0x0B769C00, 0x0B769BFF), - (0x12360D00, 0x12360CFF), - (0x19984C00, 0x19984BFF), - (0x2A2D3200, 0x2A2D31FF), - (0x30B09300, 0x30B092FF), - (0x39F45200, 0x39F451FE), - (0x3A1BB100, 0x3A1BB0FE), - (0x3A7D9600, 0x3A7D95FA), - (0x3B694700, 0x3B6946BE), - (0x3C4EDA00, 0x3C4ED72F), - (0x3D627900, 0x3D623E06), - (0x3E8B0DCA, 0x3E87C75B), - (0x3EADBE05, 0x3EA77FD2), - (0x3EAF7020, 0x3EA904B5), - (0x3EC46393, 0x3EBB870D), - (0x3ECE5D03, 0x3EC42A60), - (0x3ED0FC2C, 0x3EC66AB7), - (0x3EEBD321, 0x3EDCFE97), - (0x3EED7E44, 0x3EDE5E89), - (0x3EEF6840, 0x3EDFF12F), - (0x3F2509B8, 0x3F12979C), - (0x3F499ABD, 0x3F2AC5F6), - (0x3F766465, 0x3F442AB1), - (0x3F8C35F1, 0x3F54B56F), - (0x3F8D30B0, 0x3F559887), - (0x3F995055, 0x3F600937), - (0x3FB092A0, 0x3F718C27), - (0x3FC0F063, 0x3F7C2BCE), - (0x3FCDE59B, 0x3F81DE40), - (0x4019B6D5, 0x3F968FFC), - (0x4023C994, 0x3F99618A), - (0x4033533E, 0x3F9D2EE5), - (0x403A05CE, 0x3F9EA5E2), - (0x403EDAE4, 0x3F9FA5CC), - (0x40531E61, 0x3FA362E0), - (0x4186A600, 0x3FC17744), - (0x4311E800, 0x3FC82F47), - (0x44C38B00, 0x3FC8FAE9), - (0x45B78D00, 0x3FC90A47), - (0x45C5CD00, 0x3FC90AAE), - (0x49783F00, 0x3FC90FD3), - (0x498D9600, 0x3FC90FD4), - (0x4A15D200, 0x3FC90FD8), - ]; - let cases: Vec = words - .iter() - .flat_map(|(x, _)| [vec![vec![*x]], vec![vec![*x | 0x8000_0000]]]) - .collect(); - for fma in [false, true] { - let f = f32s(); - check_module( - &format!("fast atan fma={fma}"), - routine_module(Fun::Atan(Mode::Fast), false, fma), - &[f], - f, - &cases, - &|c| { - let x = c[0][0]; - words - .iter() - .find(|(w, _)| *w == x & 0x7FFF_FFFF) - .map(|(_, r)| vec![*r | (x & 0x8000_0000)]) - }, - &|g, w| g == w, - ); - } -} - -/// Metal's precise `atan` (the M3) at lanes where its word is not the correctly -/// rounded one: below `RN(tan(π/8))` (from `2^-12`), at it (where the next reduction starts), up to -/// `RN(tan(3π/8))` and above it through Metal's reciprocal, and up to `2^126`; each word bit for -/// bit, both signs. These lanes are among those where the reciprocal model is Metal's. -#[test] -fn precise_atan_answers_metals_words() { - let words: [(u64, u64); 48] = [ - (0x39916500, 0x39916500), - (0x3B832900, 0x3B8328D2), - (0x3BEA3D00, 0x3BEA3BFB), - (0x3D125400, 0x3D124414), - (0x3D87D700, 0x3D87A423), - (0x3DC2AD00, 0x3DC217B4), - (0x3E87E074, 0x3E84D0B4), - (0x3E8BAC29, 0x3E885ACC), - (0x3E90A7ED, 0x3E8CFB3D), - (0x3EA771A5, 0x3EA1D493), - (0x3EB040CD, 0x3EA9BF5F), - (0x3EB5733E, 0x3EAE611E), - (0x3EB7AB9A, 0x3EB0595E), - (0x3EC2EF62, 0x3EBA424A), - (0x3EC65C06, 0x3EBD3E3C), - (0x3ECBB20A, 0x3EC1DDCA), - (0x3ECC3332, 0x3EC24D42), - (0x3ECD713C, 0x3EC35F6C), - (0x3ED413CD, 0x3EC90FDA), - (0x3EDD796F, 0x3ED107CB), - (0x3EDE548B, 0x3ED1C041), - (0x3EE479D4, 0x3ED6E61D), - (0x3EEA4427, 0x3EDBB510), - (0x3EF344C7, 0x3EE31A02), - (0x3F3B7B7B, 0x3F21D207), - (0x3F61E992, 0x3F391980), - (0x3F75FB18, 0x3F43F3FB), - (0x3F791339, 0x3F458D5F), - (0x3F87D7E8, 0x3F50AB80), - (0x3F889C03, 0x3F516368), - (0x3FB84D51, 0x3F76B92C), - (0x4023481D, 0x3F993F26), - (0x40236D99, 0x3F994920), - (0x4045AC53, 0x3FA0FBAB), - (0x40507C74, 0x3FA2F020), - (0x40538662, 0x3FA3745A), - (0x4053C455, 0x3FA37EBB), - (0x405F2247, 0x3FA54EF2), - (0x4063ECE0, 0x3FA605CB), - (0x406B61E9, 0x3FA7149C), - (0x4071498B, 0x3FA7DFFA), - (0x4076441B, 0x3FA8845C), - (0x407F35F1, 0x3FA99C8E), - (0x43005500, 0x3FC81086), - (0x43F34700, 0x3FC8CC82), - (0x45A40200, 0x3FC9099D), - (0x498DC600, 0x3FC90FD4), - (0x4C158B00, 0x3FC90FDB), - ]; - let cases: Vec = words - .iter() - .flat_map(|(x, _)| [vec![vec![*x]], vec![vec![*x | 0x8000_0000]]]) - .collect(); - for fma in [false, true] { - let f = f32s(); - check_module( - &format!("precise atan fma={fma}"), - routine_module(Fun::Atan(Mode::Precise), false, fma), - &[f], - f, - &cases, - &|c| { - let x = c[0][0]; - words - .iter() - .find(|(w, _)| *w == x & 0x7FFF_FFFF) - .map(|(_, r)| vec![*r | (x & 0x8000_0000)]) - }, - &|g, w| g == w, - ); - } -} - -/// Metal's fast `atan`, `asin`, and `acos` and its precise `atan` are within Apple's bound for them -/// (5 ulp, MSL Tables 8.1 and 8.2) over their ranges; Metal's own words are within 3 ulp (both -/// `atan`s, on every `float` of `[0.25, 4)`) and 4 ulp (`asin` and `acos`, on every `float` of -/// `[0.25, 1)`, both signs for `acos`) of the exact value. -#[test] -fn metal_arc_forms_stay_within_apples_bound() { - let xs: Vec = operands(0x07A4_E297, 4000) - .into_iter() - .filter(|b| { - f32v(*b).is_finite() && (f32v(*b) == 0.0 || f32v(*b).abs() >= f32::MIN_POSITIVE) - }) - .collect(); - let in_domain: Vec = xs - .iter() - .copied() - .filter(|b| f32v(*b).abs() <= 1.0) - .collect(); - for (fun, set, exact) in [ - ( - Fun::Atan(Mode::Fast), - &xs, - (|x: &[f32]| (x[0].abs() > f32::MIN_POSITIVE).then(|| f64::from(x[0]).atan())) - as fn(&[f32]) -> Option, - ), - (Fun::Asin(Mode::Fast), &in_domain, |x: &[f32]| { - (x[0] != 0.0).then(|| f64::from(x[0]).asin()) - }), - (Fun::Acos(Mode::Fast), &in_domain, |x: &[f32]| { - Some(f64::from(x[0]).acos()) - }), - (Fun::Atan(Mode::Precise), &xs, |x: &[f32]| { - Some(f64::from(x[0]).atan()) - }), - ] { - let w = worst_error(fun, false, &unary(set), &|x| exact(x), 5.0); - eprintln!("{fun:?}: {w:.3} ulp"); - } -} - -/// Metal's fast `asin` and `acos` (the M4; the M3's are the same at every `half` operand) at lanes -/// where its word is not the correctly rounded one: below 0.25 (stepping 16 `float`s from `2^-12`), -/// on `[0.25, 0.7)`, and from 0.7 to 1, for `acos` both signs. Each word bit for bit (`asin` both -/// signs). The last 8 of `asin` and 12 of `acos` are from 0.7 on where the form with the correctly -/// rounded inverse root is not Metal's word either, and the hardware's inverse root's model is. -#[test] -fn fast_asin_and_acos_answer_metals_words() { - let asin: [(u64, u64); 32] = [ - (0x3CF62CB0, 0x3CF6362F), - (0x3999ECE0, 0x3999ECE1), - (0x399EE730, 0x399EE731), - (0x3AD716F0, 0x3AD716F8), - (0x3B4C04D0, 0x3B4C04E8), - (0x39D2A8D0, 0x39D2A8D2), - (0x3CFA3980, 0x3CFA4379), - (0x3A9EADF0, 0x3A9EADF4), - (0x3E99830C, 0x3E9BE90A), - (0x3EA5706C, 0x3EA8765D), - (0x3F10A18C, 0x3F19B338), - (0x3ED863CF, 0x3EDF6994), - (0x3EBE29E1, 0x3EC2D4ED), - (0x3ED80DF2, 0x3EDF0ADB), - (0x3E81842B, 0x3E82F05E), - (0x3EE6624D, 0x3EEEF746), - (0x3F73B78D, 0x3FA14019), - (0x3F38AD57, 0x3F4E49DE), - (0x3F478662, 0x3F64C96B), - (0x3F6689CD, 0x3F8F7D45), - (0x3F7AAB17, 0x3FAEE47E), - (0x3F745A1C, 0x3FA24D1F), - (0x3F48A433, 0x3F669399), - (0x3F430BCE, 0x3F5DC1E4), - (0x3F33_3352, 0x3F46_809E), - (0x3F38_689B, 0x3F4D_E6B0), - (0x3F3F_2320, 0x3F57_CDA0), - (0x3F45_2DAF, 0x3F61_1330), - (0x3F4C_A8BC, 0x3F6D_2725), - (0x3F54_2347, 0x3F7A_0A05), - (0x3F63_DE37, 0x3F8C_7DAD), - (0x3F7F_ED13, 0x3FC5_FC55), - ]; - let acos: [(u64, u64); 44] = [ - (0x3E5C38E0, 0x3FAD5143), - (0x3B091CE0, 0x3FC8CB4D), - (0x3E5736D0, 0x3FADF545), - (0x3C547030, 0x3FC766F8), - (0x3AB4C110, 0x3FC8E2AB), - (0x39A395D0, 0x3FC905A2), - (0x3F1FE3CF, 0x3F656E66), - (0x3F1AF5B2, 0x3F6BAF03), - (0x3EDAECD9, 0x3F908232), - (0x3F224F40, 0x3F625156), - (0x3EE8C12D, 0x3F8CA7ED), - (0x3F270BD8, 0x3F5C2171), - (0x3F438211, 0x3F33A6EE), - (0x3F6D44BD, 0x3EC513A9), - (0x3F3473B6, 0x3F49DCEE), - (0x3F4BF531, 0x3F26228A), - (0x3F765AEE, 0x3E8CFD24), - (0x3F60CDDB, 0x3EFF6723), - (0x3F531A80, 0x3F19EC3A), - (0x3F568C06, 0x3F13B9BF), - (0xBEAFE43F, 0x3FF5F300), - (0xBECC61AA, 0x3FFD9F39), - (0xBEA71227, 0x3FF39BDD), - (0xBECB9768, 0x3FFD6818), - (0xBEBF2072, 0x3FFA0781), - (0xBEA0682E, 0x3FF1D9BA), - (0xBF45B1F7, 0x401D00AE), - (0xBF7F80FA, 0x4045139B), - (0xBF641A15, 0x402AE7AC), - (0xBF5BF761, 0x4026B187), - (0xBF65828E, 0x402BB09D), - (0xBF679D26, 0x402CE683), - (0x3F33_3640, 0x3F4B_9AFD), - (0x3F4E_A39D, 0x3F21_A56C), - (0x3F58_5EB5, 0x3F10_598A), - (0x3F63_D477, 0x3EF2_737B), - (0x3F73_7C51, 0x3EA0_C062), - (0x3F7F_FE3A, 0x3BF1_109C), - (0xBF33_368F, 0x4016_2938), - (0xBF4C_3C82, 0x401F_A4C1), - (0xBF54_7157, 0x4023_2D5A), - (0xBF5B_8C97, 0x4026_7D7A), - (0xBF66_1E0A, 0x402C_08D7), - (0xBF7F_8B3F, 0x4045_3DBB), - ]; - for fma in [false, true] { - let f = f32s(); - let cases: Vec = asin - .iter() - .flat_map(|(x, _)| [vec![vec![*x]], vec![vec![*x | 0x8000_0000]]]) - .collect(); - check_module( - &format!("fast asin fma={fma}"), - routine_module(Fun::Asin(Mode::Fast), false, fma), - &[f], - f, - &cases, - &|c| { - let x = c[0][0]; - asin.iter() - .find(|(w, _)| *w == x & 0x7FFF_FFFF) - .map(|(_, r)| vec![*r | (x & 0x8000_0000)]) - }, - &|g, w| g == w, - ); - let cases: Vec = acos.iter().map(|(x, _)| vec![vec![*x]]).collect(); - check_module( - &format!("fast acos fma={fma}"), - routine_module(Fun::Acos(Mode::Fast), false, fma), - &[f], - f, - &cases, - &|c| { - acos.iter() - .find(|(w, _)| *w == c[0][0]) - .map(|(_, r)| vec![*r]) - }, - &|g, w| g == w, - ); - } -} - -/// The generic part of precise `atan2`, Metal's own form, is within Apple's bound (6 ulp, MSL Table -/// 8.1) for finite nonzero normal operands, quotients from `2^-200` to `2^200` included; Metal's -/// own words are within 3.3 ulp of the exact value (every finite normal pair of our probe -/// whose answer is normal). Its quotients are the module's correctly rounded division routine's, -/// whatever the device's. -#[test] -fn atan2_routine_stays_within_its_bound() { - let xs = operands(0x051A_BE11, 600); - let normal: Vec = xs - .iter() - .copied() - .filter(|b| { - let v = f32v(*b); - v.is_normal() - }) - .collect(); - let mut rng = Rng(0x2BAD_F00D); - let mut pairs = Vec::new(); - for _ in 0..6000 { - let y = normal[(rng.next() as usize) % normal.len()]; - let x = normal[(rng.next() as usize) % normal.len()]; - pairs.push(vec![y, x]); - } - // Quotients near one and near the reduction's edges. - for k in [0.4375f32, 0.6875, 1.0, 1.1875, 2.4375, 0.999_999_9] { - for s in [1.0f32, -1.0] { - pairs.push(vec![ - u64::from((k * s).to_bits()), - u64::from(1.0f32.to_bits()), - ]); - pairs.push(vec![ - u64::from(1.0f32.to_bits()), - u64::from((k * s).to_bits()), - ]); - } - } - let w = worst_error( - Fun::Atan2, - false, - &pairs, - &|x| { - let r = f64::from(x[0]).atan2(f64::from(x[1])); - // A result `atan2_special` flushes (below 2^-126) is its, not the routine's. - (r.abs() >= 2f64.powi(-126)).then_some(r) - }, - 6.0, - ); - eprintln!("Atan2: {w:.3}"); -} - -/// Metal's precise `atan2(y, x)` (the M4) at pairs where its word is not the -/// correctly rounded one, five in each quadrant's quotients below `2^-12`, below `RN(tan(π/8))`, -/// below `RN(tan(3π/8))`, and above, toward a positive and a negative `x`; each word bit for bit. -/// These pairs are among those where the reciprocal model is Metal's. -#[test] -fn precise_atan2_answers_metals_words() { - let words: [(u64, u64, u64); 40] = [ - (0xC7CB9EAA, 0x3F8001D8, 0xBFC90F8B), - (0xC29D223D, 0x3FF4603E, 0xBFC5F3BF), - (0xC1334FA1, 0x40946D3E, 0xBF96D535), - (0x3F59E032, 0xC1842DFF, 0x4045C4A8), - (0x41E2023E, 0x3D7F73A3, 0x3FC8C785), - (0xC176DECC, 0xC257C9F3, 0xC0373BBB), - (0x3C023B14, 0x41844686, 0x39FC0AF2), - (0xB7327783, 0xB7A34141, 0xC0290C3C), - (0x474B21BF, 0x3F581529, 0x3FC90F53), - (0x3F764DFF, 0x4287BD5D, 0x3C683EC1), - (0xBBFCA34D, 0xBF033F5B, 0xC048197D), - (0x3FC7FDF7, 0xC2AEB69E, 0x4047EAD9), - (0x3E7BA212, 0x3FD7E2F6, 0x3E1426DE), - (0x0868E679, 0x82516CA0, 0x3FC9170D), - (0x40D4D09C, 0xC1854DCC, 0x4030C221), - (0x3F6B30D1, 0xBEA6EA53, 0x3FF4B56A), - (0xC09627FA, 0xC0E202E3, 0xC023880C), - (0xC1123F6F, 0xC18DFA94, 0xC02A9F97), - (0xBF8CE01F, 0x4092549B, 0xBE71DB4D), - (0xC10E031C, 0x417EEAFD, 0xBF021DFD), - (0x400AADC7, 0x3FB582E0, 0x3F7DC6B1), - (0xBDB60C6F, 0x408F06BF, 0xBCA2E6AD), - (0xC18A40F2, 0x412B56FD, 0xBF820DDF), - (0x3FD72868, 0x3F800000, 0x3F845E41), - (0x3DB7A5FD, 0xB9A8757B, 0x3FC98545), - (0x40A8B4DB, 0x40FC10E4, 0x3F16FE71), - (0xC188098E, 0xB8EC1249, 0xBFC91013), - (0xBEF9A9A0, 0xB820258A, 0xBFC9126C), - (0xC147F77F, 0xC0ADD2A8, 0xBFFD8AB0), - (0x1BCA6E57, 0xA57C6253, 0x40490FD5), - (0x416E7672, 0xC162697D, 0x40152347), - (0x1D34B8B5, 0xA75EAF2B, 0x40490FD8), - (0xBBABB6BE, 0x42222524, 0xB9078DC2), - (0xCF3CE185, 0xDA1A7835, 0xC0490FDA), - (0xCA02C1C0, 0xD5C95DBB, 0xC0490FDB), - (0x40B93FD1, 0x47417508, 0x38F5237C), - (0xC1ABF335, 0xCE0DB5EC, 0xC0490FDB), - (0x3BD48266, 0x41E76EAD, 0x396B117B), - (0x3BB0A5ED, 0x41EBC17C, 0x393FD11B), - (0x3BA6C4AF, 0x41DEBF99, 0x393FA9CA), - ]; - let cases: Vec = words - .iter() - .map(|(y, x, _)| vec![vec![*y], vec![*x]]) - .collect(); - for fma in [false, true] { - let f = f32s(); - check_module( - &format!("precise atan2 fma={fma}"), - routine_module(Fun::Atan2, false, fma), - &[f, f], - f, - &cases, - &|c| { - words - .iter() - .find(|(y, x, _)| *y == c[0][0] && *x == c[1][0]) - .map(|(_, _, r)| vec![*r]) - }, - &|g, w| g == w, - ); - } -} - -/// Metal's answers at the special operands (cases 087758cb and cc234732), bit for bit: zeros and -/// denormals as each function and mode reads them, infinities, `±1`, and the smallest normal. -#[test] -fn arc_tangent_family_routines_answer_metals_special_values() { - const HALF_PI: u64 = 0x3FC9_0FDB; - let specials: [(Fun, u64, u64); 28] = [ - (Fun::Atan(Mode::Precise), 0x0000_0000, 0x0000_0000), - (Fun::Atan(Mode::Precise), 0x8000_0000, 0x0000_0000), - (Fun::Atan(Mode::Precise), 0x8000_0001, 0x0000_0000), - (Fun::Atan(Mode::Precise), 0x807F_FFFF, 0x0000_0000), - (Fun::Atan(Mode::Precise), 0x8080_0000, 0x8080_0000), - (Fun::Atan(Mode::Precise), 0x7F80_0000, HALF_PI), - (Fun::Atan(Mode::Precise), 0xFF80_0000, HALF_PI | 0x8000_0000), - (Fun::Atan(Mode::Precise), 0x7F7F_FFFF, HALF_PI), - (Fun::Atan(Mode::Precise), 0x3F80_0000, 0x3F49_0FDB), - (Fun::Atan(Mode::Fast), 0x8000_0000, 0x8000_0000), - (Fun::Atan(Mode::Fast), 0x8000_0001, 0x8000_0000), - (Fun::Atan(Mode::Fast), 0x0000_0001, 0x0000_0000), - (Fun::Atan(Mode::Fast), 0xFF80_0000, HALF_PI | 0x8000_0000), - (Fun::Asin(Mode::Precise), 0x8000_0000, 0x8000_0000), - (Fun::Asin(Mode::Precise), 0x0000_0001, 0x0000_0001), - (Fun::Asin(Mode::Precise), 0x807F_FFFF, 0x807F_FFFF), - (Fun::Asin(Mode::Precise), 0x3F80_0000, HALF_PI), - (Fun::Asin(Mode::Precise), 0xBF80_0000, HALF_PI | 0x8000_0000), - (Fun::Asin(Mode::Fast), 0x8000_0000, 0x0000_0000), - (Fun::Asin(Mode::Fast), 0x8000_0001, 0x0000_0000), - (Fun::Asin(Mode::Fast), 0x007F_FFFF, 0x0000_0000), - (Fun::Acos(Mode::Precise), 0x8000_0001, HALF_PI), - (Fun::Acos(Mode::Precise), 0x3F80_0000, 0x0000_0000), - (Fun::Acos(Mode::Precise), 0xBF80_0000, 0x4049_0FDB), - (Fun::Acos(Mode::Fast), 0x0000_0000, HALF_PI), - (Fun::Acos(Mode::Fast), 0xBF80_0000, 0x4049_0FDB), - (Fun::Acos(Mode::Fast), 0x3F80_0000, 0x0000_0000), - (Fun::Asin(Mode::Fast), 0x3F80_0000, HALF_PI), - ]; - for rough in [false, true] { - for (fun, x, want) in specials { - let f = f32s(); - check_module( - &format!("{fun:?}({x:#010x}) rough={rough}"), - routine_module(fun, rough, false), - &[f], - f, - &[vec![vec![x]]], - &|_| Some(vec![want]), - &|g, w| g == w, - ); - } - // A domain error is a NaN. - for fun in [ - Fun::Asin(Mode::Precise), - Fun::Asin(Mode::Fast), - Fun::Acos(Mode::Precise), - Fun::Acos(Mode::Fast), - ] { - for x in [ - 0x3F80_0001u64, - 0xBF80_0001, - 0x7F80_0000, - 0xFF80_0000, - 0x7FC0_0000, - ] { - let f = f32s(); - check_module( - &format!("{fun:?}({x:#010x}) rough={rough}"), - routine_module(fun, rough, false), - &[f], - f, - &[vec![vec![x]]], - &|_| Some(vec![0x7FC0_0000]), - &|g, _| f32v(g).is_nan(), - ); - } - } - } -} - -/// Each routine's words, with its constants and types, stay within [`Fun::words`], with and without -/// `OpFmaKHR`, and the estimate is at most twice the larger. -#[test] -fn libm_routines_fit_their_word_estimates() { - let module_words = |m: TypedModule| serialize(m).expect("serialize").words.len(); - let mut off = Vec::new(); - for fun in [ - Fun::Atan(Mode::Precise), - Fun::Atan(Mode::Fast), - Fun::Asin(Mode::Precise), - Fun::Asin(Mode::Fast), - Fun::Acos(Mode::Precise), - Fun::Acos(Mode::Fast), - Fun::Atan2, - Fun::Sin, - Fun::Cos, - Fun::Tan, - Fun::FastSin, - Fun::FastCos, - Fun::SinPi(Mode::Precise), - Fun::CosPi(Mode::Precise), - Fun::TanPi(Mode::Precise), - Fun::SinPi(Mode::Fast), - Fun::CosPi(Mode::Fast), - Fun::TanPi(Mode::Fast), - Fun::Sqrt, - Fun::Rsqrt, - Fun::Fmod, - Fun::Fused, - Fun::HalfAtan, - Fun::HalfAtan2, - Fun::HalfTan, - Fun::HalfSin, - Fun::HalfCos, - Fun::HalfAsinh, - ] { - // The estimate covers the larger emission (without `OpFmaKHR` a fused step is - // emulated) and is not loose by more than half of it. - let bound = fun.words() as usize; - let mut largest = 0; - for fma in [false, true] { - let bare = module_words(helpers_module(fun, fma)); - let used = module_words(routine_module(fun, false, fma)); - let emitted = used - bare; - eprintln!("{fun:?} fma={fma}: {emitted} words against {bound}"); - if emitted > bound { - off.push(format!("{fun:?} fma={fma}: {emitted} words over {bound}")); - } - largest = largest.max(emitted); - } - if 2 * largest < bound { - off.push(format!("{fun:?}: {bound} words for at most {largest}")); - } - } - assert!(off.is_empty(), "{off:#?}"); -} - -/// A `half` call of the arc tangent family takes a routine before its rounding (the `float` routine -/// of `asin` and `acos`, precise: Metal's `half` functions are the same in both modes; `atan`'s own -/// `half` form, `half_forms_follow_their_model`), so it is within a `half` ulp of the exact value -/// over every pattern, and it answers Metal's `half` zeros (the half probe, cases dc0fee8f and -/// 3ef7c1c5): `asin(±0)` is `+0` and `atan(±0)` the zero itself, where the `float` routines answer -/// `asin(-0) = -0` and `atan(-0) = +0`. Part `part` of `of` checks every `of`-th pattern. -fn half_arc_functions(part: usize, of: usize) { - use std::collections::BTreeMap; - let h = float(16); - let functions: [(FloatFn, Fun, fn(f64) -> f64); 3] = [ - (FloatFn::Atan, Fun::HalfAtan, f64::atan), - (FloatFn::Asin, Fun::Asin(Mode::Precise), f64::asin), - (FloatFn::Acos, Fun::Acos(Mode::Precise), f64::acos), - ]; - let cases: Vec = (0..=0xFFFFu64) - .filter(|b| b & 0x7C00 != 0x7C00 || b & 0x03FF == 0) - .map(|b| vec![vec![b]]) - .collect(); - let cases = part_of(cases, part, of); - for (op, fun, exact) in functions { - let m = kernel_defs( - &[h], - h, - &|b| Ok(vec![libm::define_alone(b, fun, false)?]), - &|fb, x, funcs| { - let map: BTreeMap = funcs.iter().map(|id| (fun, *id)).collect(); - math::float_fn( - fb, - op, - h, - Contraction::Forbidden, - NanTest::IsNan, - x, - &Lib::new(None, &map), - ) - }, - true, - false, - ) - .unwrap_or_else(|e| panic!("{op:?}: build: {e:?}")); - check_module( - &format!("half {op:?}"), - m, - &[h], - h, - &cases, - &|c| { - let b = c[0][0]; - let x = f16_to_f64(b as u16); - let r = match (op, x == 0.0) { - (FloatFn::Asin, true) => 0.0, - (FloatFn::Atan, true) => x, - _ => exact(x), - }; - Some(vec![u64::from(f64_to_f16(r))]) - }, - &|g, w| { - let nan = |b: u64| b & 0x7C00 == 0x7C00 && b & 0x03FF != 0; - if nan(w) || nan(g) { - return nan(w) && nan(g); - } - // A zero answer is exact; another is within one `half` ulp of the same sign. - if w & 0x7FFF == 0 || g & 0x7FFF == 0 { - return g == w; - } - (g ^ w) & 0x8000 == 0 && (g as i64 - w as i64).abs() <= 1 - }, - ); - } -} - -mod half_arc_functions_take_the_routines_and_answer_metals_zeros { - parts!(super::half_arc_functions, 6; part_1_of_6 = 0, part_2_of_6 = 1, - part_3_of_6 = 2, part_4_of_6 = 3, part_5_of_6 = 4, part_6_of_6 = 5); -} - -/// Metal's `half` `atan` of a `half` held as `float`, before its rounding: the test's model of -/// `Fun::HalfAtan`'s routine (`libm::atan::half_atan`). -fn half_atan_form(x: f32) -> f32 { - let p = libm::atan::HALF_ATAN_P.map(f32::from_bits); - let a = x.abs(); - let above = a > 1.0; - let t = match (above, a.is_infinite()) { - (true, true) => 0.0, - (true, false) => 1.0 / a, - (false, _) => a, - }; - let s = t * t; - let q = ((p[3] * s + p[2]) * s + p[1]) * s + p[0]; - let core = t * q; - let r = if above { - std::f32::consts::FRAC_PI_2 - core - } else { - core - }; - r.copysign(x) -} - -/// Metal's `half` `atan2(y, x)` of finite nonzero `half` operands held as `float`, before its -/// rounding: the model of `Fun::HalfAtan2`'s routine. -fn half_atan2_form(y: f32, x: f32) -> f32 { - let t = half_atan_form(y / x); - match (x < 0.0, y < 0.0) { - (true, true) => t - std::f32::consts::PI, - (true, false) => t + std::f32::consts::PI, - _ => t, - } -} - -/// Metal's `half` `tan` of a `half` held as `float`, before its rounding: the model of -/// `Fun::HalfTan`'s routine (`libm::trig::half_tan`), each fused step one `mul_add` and Metal's -/// reciprocal its model. -fn half_tan_form(x: f32) -> f32 { - let (r, k) = half_quarter_turns(x, 12_582_912.0); - let p = libm::trig::HALF_TAN_P.map(f32::from_bits); - let s = r * r; - let t = r * p[3].mul_add(s, p[2]).mul_add(s, p[1]).mul_add(s, p[0]); - if k & 1 != 0 { - libm::rcp::model(-t) - } else { - t - } -} - -/// The reduction of Metal's `half` `sin`, `cos`, and `tan`: `(r, k)` of `s = fma(x, c0, magic)`, -/// `k` its bits and `r = fma(x, c1, fma(x, c0, magic - s))` of `2/π`'s first two parts. -fn half_quarter_turns(x: f32, magic: f32) -> (f32, u32) { - let [c0, c1, _] = libm::quarter::QUARTER.map(f32::from_bits); - let s = x.mul_add(c0, magic); - let r = x.mul_add(c0, magic - s); - (x.mul_add(c1, r), s.to_bits()) -} - -/// Metal's `half` `sin` (`cos` where `cos`) of a `half` held as `float`, before its rounding: the -/// model of `Fun::HalfSin`'s and `Fun::HalfCos`'s routine (`libm::sincos::half_sin_cos`), the -/// `sinc` [`metal_sinc_model`]. -fn half_sin_cos_form(x: f32, cos: bool) -> f32 { - if !x.is_finite() { - return f32::NAN; - } - if !cos && x.abs() < 1.0 / 64.0 { - return x; - } - let (r, k) = half_quarter_turns(x, if cos { 12_582_913.0 } else { 12_582_912.0 }); - let t = if k & 1 != 0 { 1.0 - r.abs() } else { r }; - let t = if k & 2 != 0 { -t } else { t }; - t * metal_sinc_model(t.abs()) -} - -/// A module of `half` function `op` (operands of form `h`) lowered as a call takes it, with the -/// routine `fun` (and its helpers) defined. -pub(super) fn half_module(op: FloatFn, fun: Fun) -> TypedModule { - use std::collections::BTreeMap; - let h = float(16); - kernel_defs( - &vec![h; fun.arity()], - h, - &|b| Ok(vec![libm::define_alone(b, fun, false)?]), - &|fb, x, funcs| { - let map: BTreeMap = funcs.iter().map(|id| (fun, *id)).collect(); math::float_fn( fb, - op, - h, + FloatFn::Fmod, + f, Contraction::Forbidden, NanTest::IsNan, x, - &Lib::new(None, &map), + &Lib::new(None, funcs.first().copied()), ) }, true, false, ) - .unwrap_or_else(|e| panic!("{op:?}: build: {e:?}")) -} - -/// A `half` `atan`, `tan`, `sin`, `cos`, or `atan2` call answers its model of Metal's own `half` -/// form rounded to `half` ([`half_atan_form`], [`half_tan_form`], [`half_sin_cos_form`], -/// [`half_atan2_form`]) at every `half` (`atan2`: at the 65,536 pairs of our probe, `y` every -/// pattern and `x` its hash, and at those of finite nonzero operands), a zero `sin` or `tan` -/// operand giving `+0` and a NaN or an infinite operand a NaN. Rounded so, each model is Metal's -/// word at every `half` of our probes (`atan`, `atan2`, `tan`, `sin`, `cos`; the M3 -/// and the M4); Metal's words where they are not the correctly rounded ones are -/// `half_forms_answer_metals_words`'. Part `part` of `of` checks every `of`-th -/// run. -fn half_forms(part: usize, of: usize) { - let h = float(16); - let nan = |b: u64| b & 0x7C00 == 0x7C00 && b & 0x03FF != 0; - let half_of = |x: f32| u64::from(f64_to_f16(f64::from(x))); - let all: Vec = (0..=0xFFFFu64).map(|b| vec![vec![b]]).collect(); - let finite = |b: u64| b & 0x7C00 != 0x7C00 && b & 0x7FFF != 0; - let pairs: Vec = (0..=0xFFFFu32) - .map(|i| (u64::from(i), u64::from(i.wrapping_mul(2_654_435_761) >> 16))) - .filter(|(y, x)| finite(*y) && finite(*x)) - .map(|(y, x)| vec![vec![y], vec![x]]) - .collect(); - let mut runs = Vec::new(); - for (op, fun) in [ - (FloatFn::Atan, Fun::HalfAtan), - (FloatFn::Tan, Fun::HalfTan), - (FloatFn::Sin, Fun::HalfSin), - (FloatFn::Cos, Fun::HalfCos), - (FloatFn::Atan2, Fun::HalfAtan2), - ] { - let cases = if op == FloatFn::Atan2 { &pairs } else { &all }; - for run in cases.chunks(4096) { - runs.push((op, fun, run)); - } - } - for (op, fun, run) in part_of(runs, part, of) { - check_module( - &format!("half {op:?}"), - half_module(op, fun), - &vec![h; fun.arity()], - h, - run, - &|c| { - let x = f16_to_f64(c[0][0] as u16) as f32; - let r = match op { - FloatFn::Atan2 => half_atan2_form(x, f16_to_f64(c[1][0] as u16) as f32), - FloatFn::Tan | FloatFn::Sin if x == 0.0 => 0.0, - FloatFn::Tan if !x.is_finite() => f32::NAN, - FloatFn::Tan => half_tan_form(x), - FloatFn::Sin => half_sin_cos_form(x, false), - FloatFn::Cos => half_sin_cos_form(x, true), - _ => half_atan_form(x), - }; - Some(vec![half_of(r)]) - }, - &|g, w| g == w || (nan(g) && nan(w)), - ); - } -} - -mod half_forms_follow_their_model { - parts!(super::half_forms, 12; - part_1_of_12 = 0, part_2_of_12 = 1, part_3_of_12 = 2, part_4_of_12 = 3, - part_5_of_12 = 4, part_6_of_12 = 5, part_7_of_12 = 6, part_8_of_12 = 7, - part_9_of_12 = 8, part_10_of_12 = 9, part_11_of_12 = 10, part_12_of_12 = 11); -} - -/// Metal's `half` `atan`, `tan`, `sin`, `cos`, and `atan2` words (the M3; the M4's are the same) -/// where they are not the correctly rounded ones, bit for bit: `atan` and `tan` at 24 operands -/// each, spread over the magnitudes where they differ (3,728 and 2,280 `half` values), `sin` and -/// `cos` at every nonzero one (6 and 2), and `atan2` at six pairs per quadrant (of the 3,210 probe -/// pairs where it differs). -#[test] -fn half_forms_answer_metals_words() { - let h = float(16); - let atan: [(u64, u64); 24] = [ - (0x237F, 0x237E), - (0x23D0, 0x23CF), - (0x25BF, 0x25BE), - (0x2610, 0x260F), - (0x2661, 0x2660), - (0x26B2, 0x26B1), - (0x2703, 0x2702), - (0x280F, 0x280E), - (0x2860, 0x285F), - (0x2A49, 0x2A47), - (0x2A9A, 0x2A98), - (0x2BCC, 0x2BC9), - (0x2CEF, 0x2CEC), - (0x2EC3, 0x2EBC), - (0x30AF, 0x30A6), - (0x345E, 0x3444), - (0x35BE, 0x3584), - (0x36E0, 0x367F), - (0x38FA, 0x3873), - (0x3A5C, 0x395F), - (0x3C05, 0x3A4E), - (0x3D86, 0x3B8E), - (0x40BD, 0x3CAF), - (0xDC01, 0xBE45), - ]; - let tan: [(u64, u64); 24] = [ - (0x2745, 0x2745), - (0xA776, 0xA776), - (0x27A8, 0x27A8), - (0xA8B8, 0xA8B8), - (0x2BE1, 0x2BE3), - (0xAF68, 0xAF70), - (0x34CF, 0x34F6), - (0xB9AD, 0xBADF), - (0x3E2D, 0x50A8), - (0xC2C1, 0xB3AD), - (0x4660, 0x2DE4), - (0xCA2C, 0x333F), - (0xCDFB, 0x4150), - (0x525F, 0x3AC9), - (0xD635, 0x4170), - (0x5B2E, 0x3707), - (0xDF5E, 0xB447), - (0x63E8, 0x36E7), - (0xE872, 0xC9F3), - (0x6C71, 0xBE9B), - (0xF0B3, 0xC340), - (0x749D, 0xBA78), - (0xF8C0, 0xB39C), - (0xFBE5, 0x3C57), - ]; - let sin: [(u64, u64); 6] = [ - (0x32B3, 0x32A6), - (0x51F5, 0xB810), - (0x5CB0, 0xBC00), - (0xB2B3, 0xB2A6), - (0xD1F5, 0x3810), - (0xDCB0, 0x3C00), - ]; - let cos: [(u64, u64); 2] = [(0x4578, 0x397E), (0xC578, 0x397E)]; - let atan2: [(u64, u64, u64); 24] = [ - (0x001A, 0x11A2, 0x189D), - (0x1253, 0x328A, 0x1BBC), - (0x255B, 0x424E, 0x1ECB), - (0x370C, 0x55BE, 0x1CE8), - (0x4B12, 0x608D, 0x2636), - (0x7BF4, 0x7458, 0x3D37), - (0x07B2, 0x86E6, 0x409B), - (0x2957, 0xA757, 0x4058), - (0x3EC1, 0xB74B, 0x3F57), - (0x4F99, 0xADB5, 0x3E4B), - (0x5F75, 0xE583, 0x41A1), - (0x7935, 0xFA00, 0x40DA), - (0x800F, 0x0218, 0xA729), - (0x9370, 0x1325, 0xBA71), - (0xA558, 0x2480, 0xBAF7), - (0xB89C, 0x4945, 0xAAFD), - (0xCD22, 0x6FD0, 0x9941), - (0xFBE1, 0x7312, 0xBD66), - (0x81A6, 0x8C4B, 0xC218), - (0xA128, 0x9C33, 0xBFD5), - (0xB6B4, 0xAF85, 0xBF61), - (0xC95B, 0xCC44, 0xC12A), - (0xE502, 0xDC4A, 0xBF21), - (0xFBAE, 0xEE05, 0xBEAC), - ]; - for (op, fun, words) in [ - (FloatFn::Atan, Fun::HalfAtan, &atan[..]), - (FloatFn::Tan, Fun::HalfTan, &tan[..]), - (FloatFn::Sin, Fun::HalfSin, &sin[..]), - (FloatFn::Cos, Fun::HalfCos, &cos[..]), - ] { - let cases: Vec = words.iter().map(|(x, _)| vec![vec![*x]]).collect(); - check_module( - &format!("half {op:?} words"), - half_module(op, fun), - &[h], - h, - &cases, - &|c| { - words - .iter() - .find(|(x, _)| *x == c[0][0]) - .map(|(_, r)| vec![*r]) - }, - &|g, w| g == w, - ); - } - let cases: Vec = atan2 - .iter() - .map(|(y, x, _)| vec![vec![*y], vec![*x]]) - .collect(); - check_module( - "half Atan2 words", - half_module(FloatFn::Atan2, Fun::HalfAtan2), - &[h, h], - h, - &cases, - &|c| { - atan2 - .iter() - .find(|(y, x, _)| *y == c[0][0] && *x == c[1][0]) - .map(|(_, _, r)| vec![*r]) - }, - &|g, w| g == w, - ); -} - -/// At a domain error of its function every routine answers Metal's NaN bit for bit, a constant, so -/// no device's NaN encoding reaches it (Metal's rows of cases 087758cb and cc234732, every such -/// lane): `0x7fc00000` for an infinite operand of `sin`, `cos`, and `tan`, `|x| > 1` of precise -/// `asin` and of `acos`, a negative normal or infinite operand of `sqrt` and `rsqrt`, and an -/// infinite dividend or a zero or denormal divisor of `fmod`; and `fast::asin`'s carries the -/// operand's sign. Metal's `half` `asin` of `|x| > 1` carries the operand's sign in both modes -/// (cases 48500c31 and 32931370), its `half` `acos`'s does not. -#[test] -fn routines_answer_metals_nan_at_their_domain_errors() { - use std::collections::BTreeMap; - const NAN: u64 = 0x7FC0_0000; - const NEG_NAN: u64 = 0xFFC0_0000; - let f = f32s(); - let unary: Vec<(Fun, u64, u64)> = [ - (Fun::Sin, 0x7F80_0000u64, NAN), - (Fun::Sin, 0xFF80_0000, NAN), - (Fun::Cos, 0x7F80_0000, NAN), - (Fun::Cos, 0xFF80_0000, NAN), - (Fun::Tan, 0x7F80_0000, NAN), - (Fun::Tan, 0xFF80_0000, NAN), - (Fun::Asin(Mode::Precise), 0x3F80_0001, NAN), - (Fun::Asin(Mode::Precise), 0xBF80_0001, NAN), - (Fun::Asin(Mode::Precise), 0xC020_0000, NAN), - (Fun::Asin(Mode::Precise), 0xFF80_0000, NAN), - (Fun::Asin(Mode::Fast), 0x4020_0000, NAN), - (Fun::Asin(Mode::Fast), 0x7F80_0000, NAN), - (Fun::Asin(Mode::Fast), 0xC020_0000, NEG_NAN), - (Fun::Asin(Mode::Fast), 0xFF80_0000, NEG_NAN), - (Fun::Acos(Mode::Precise), 0xC020_0000, NAN), - (Fun::Acos(Mode::Precise), 0x7F80_0000, NAN), - (Fun::Acos(Mode::Fast), 0xC020_0000, NAN), - (Fun::Acos(Mode::Fast), 0xFF80_0000, NAN), - (Fun::Sqrt, 0xBF80_0000, NAN), - (Fun::Sqrt, 0x8080_0000, NAN), - (Fun::Sqrt, 0xFF80_0000, NAN), - (Fun::Rsqrt, 0xBF80_0000, NAN), - (Fun::Rsqrt, 0x8080_0000, NAN), - (Fun::Rsqrt, 0xFF80_0000, NAN), - ] - .to_vec(); - for rough in [false, true] { - for (fun, x, want) in &unary { - check_module( - &format!("{fun:?}({x:#010x}) rough={rough}"), - routine_module(*fun, rough, false), - &[f], - f, - &[vec![vec![*x]]], - &|_| Some(vec![*want]), - &|g, w| g == w, - ); - } - for (x, y) in [ - (0x7F80_0000u64, 0x3F80_0000u64), - (0xFF80_0000, 0x4000_0000), - (0x3F80_0000, 0x0000_0000), - (0xC000_0000, 0x8000_0000), - (0x4000_0000, 0x0000_0001), - (0x0000_0001, 0x0000_0000), - ] { - check_module( - &format!("Fmod({x:#010x}, {y:#010x}) rough={rough}"), - routine_module(Fun::Fmod, rough, false), - &[f, f], - f, - &[vec![vec![x], vec![y]]], - &|_| Some(vec![NAN]), - &|g, w| g == w, - ); - } - } - // `half` `asin` and `acos` through the precise routines. - let h = float(16); - for (op, fun, cases) in [ - ( - FloatFn::Asin, - Fun::Asin(Mode::Precise), - [ - (0x4100u64, 0x7E00u64), - (0xC100, 0xFE00), - (0x7C00, 0x7E00), - (0xFC00, 0xFE00), - ], - ), - ( - FloatFn::Acos, - Fun::Acos(Mode::Precise), - [ - (0x4100, 0x7E00), - (0xC100, 0x7E00), - (0x7C00, 0x7E00), - (0xFC00, 0x7E00), - ], - ), - ] { - let m = kernel_defs( - &[h], - h, - &|b| Ok(vec![libm::define_alone(b, fun, false)?]), - &|fb, x, funcs| { - let map: BTreeMap = funcs.iter().map(|id| (fun, *id)).collect(); - math::float_fn( - fb, - op, - h, - Contraction::Forbidden, - NanTest::IsNan, - x, - &Lib::new(None, &map), - ) - }, - true, - false, - ) - .unwrap_or_else(|e| panic!("{op:?}: build: {e:?}")); - let inputs: Vec = cases.iter().map(|(x, _)| vec![vec![*x]]).collect(); - check_module( - &format!("half {op:?}"), - m, - &[h], - h, - &inputs, - &|c| { - let x = c[0][0]; - cases.iter().find(|(b, _)| *b == x).map(|(_, w)| vec![*w]) - }, - &|g, w| g == w, - ); - } -} - -/// Operands for the trigonometric routines: [`operands`], and the floats nearest the first 4,096 -/// and some larger multiples of `π/2` with their neighbours, where the reduction cancels most. -fn trig_operands() -> Vec { - let mut v = operands(0x0B5E_55ED, 3000); - let mut rng = Rng(0x7A11_C0DE); - let ks = (1u64..4096).chain((0..2000).map(|_| rng.next() % (1 << 40))); - for k in ks { - let x = (k as f64 * std::f64::consts::FRAC_PI_2) as f32; - if !x.is_finite() { - continue; - } - for d in [-1i64, 0, 1] { - let b = (i64::from(x.to_bits()) + d) as u64; - v.push(b); - v.push(b | 0x8000_0000); - } - } - v.retain(|b| f32v(*b).is_finite()); - v -} - -/// The `OpFmaKHR` instructions of `m`. -fn fma_count(m: TypedModule) -> usize { - let words = serialize(m).expect("serialize").words; - let mut at = 5; - let mut n = 0; - while at < words.len() { - let w = words[at]; - if w & 0xFFFF == crate::spv::Op::FmaKHR as u32 { - n += 1; - } - at += (w >> 16).max(1) as usize; - } - n -} - -/// On a profile whose `float` fused multiply-add is `OpFmaKHR`, the trigonometric routines take it -/// for a product's exact error, Metal's precise `atan` and `atan2` for their own fused steps, its -/// `tanpi` for its denominator, and its `half` `tan` for its reduction and polynomial, and no other -/// first-stage routine does (`sinpi`, `cospi`, and the `half` `atan` and `atan2` among them); on -/// any other profile no routine does. -#[test] -fn trig_routines_take_fma_where_the_profile_has_it() { - for fun in [ - Fun::Sin, - Fun::Cos, - Fun::Tan, - Fun::FastSin, - Fun::FastCos, - Fun::SinPi(Mode::Precise), - Fun::CosPi(Mode::Precise), - Fun::TanPi(Mode::Precise), - Fun::SinPi(Mode::Fast), - Fun::CosPi(Mode::Fast), - Fun::TanPi(Mode::Fast), - Fun::Atan(Mode::Precise), - Fun::Atan2, - Fun::Sqrt, - Fun::Rsqrt, - Fun::Fmod, - Fun::HalfAtan, - Fun::HalfAtan2, - Fun::HalfTan, - Fun::HalfSin, - Fun::HalfCos, - Fun::HalfAsinh, - ] { - let fuses = matches!( - fun, - Fun::Sin - | Fun::Cos - | Fun::Tan - | Fun::FastSin - | Fun::FastCos - | Fun::TanPi(_) - | Fun::Atan(Mode::Precise) - | Fun::Atan2 - | Fun::HalfTan - | Fun::HalfSin - | Fun::HalfCos - | Fun::HalfAsinh - ); - // The routine's own: a helper takes `OpFmaKHR` on its own account (the precise - // division's fused path). - let own = - |fma| fma_count(routine_module(fun, false, fma)) - fma_count(helpers_module(fun, fma)); - assert_eq!(own(false), 0, "{fun:?}"); - let fused = own(true); - assert_eq!(fused > 0, fuses, "{fun:?}: {fused} OpFmaKHR"); - } -} - -/// The precise `sin` and `cos` routines answer [`metal_sin_cos_model`] bit for bit, with and -/// without `OpFmaKHR`, over [`trig_operands`] (every binade, and the floats nearest multiples of -/// `π/2` to `2^40 π/2`), the edges of the reduction, the tiny operands' bound and the `sinc`'s -/// segments, and every 65,537th finite `float`, both signs; and the model lies within Apple's -/// bound of the exact value there (4 ulp). Part `part` of `of` checks every `of`-th operand. -fn precise_sin_cos_is_metals(part: usize, of: usize) { - let mut xs = trig_operands(); - for edge in [0x3980_0000u32, 0x4A00_0000, 0x4B00_0000, 0x7F00_0000] { - for d in 0..=64u32 { - xs.push(u64::from((edge + d).wrapping_sub(32))); - } - } - // Operands whose folded value starts a segment of the `sinc` (`t = j / 32`, `x = t π/2`). - for j in 1..32u32 { - let x = (f64::from(j) / 32.0 * std::f64::consts::FRAC_PI_2) as f32; - for d in 0..=8u32 { - xs.push(u64::from((x.to_bits() + d).wrapping_sub(4))); - } - } - xs.extend((0..0x7F80_0000u32).step_by(65_537).map(u64::from)); - let signed: Vec = xs - .iter() - .flat_map(|b| [*b & 0x7FFF_FFFF, *b | 0x8000_0000]) - .filter(|b| f32v(*b).is_finite()) - .collect(); - let signed = part_of(signed, part, of); - let f = f32s(); - for (fun, cos) in [(Fun::Sin, false), (Fun::Cos, true)] { - for fma in [false, true] { - check_module( - &format!("{fun:?} fma={fma}"), - routine_module(fun, false, fma), - &[f], - f, - &signed.iter().map(|x| vec![vec![*x]]).collect::>(), - &|c| { - Some(vec![u64::from( - metal_sin_cos_model(f32v(c[0][0]), cos).to_bits(), - )]) - }, - &|g, w| g == w, - ); - } - let exact = if cos { f64::cos } else { f64::sin }; - let worst = signed - .iter() - .map(|b| { - let x = f32v(*b); - let e = exact(f64::from(x)); - let r = e.abs() as f32; - let ulp = f64::from(f32::from_bits(r.to_bits() + 1)) - f64::from(r); - (f64::from(metal_sin_cos_model(x, cos)) - e).abs() / ulp - }) - .fold(0f64, f64::max); - eprintln!("{fun:?}: {worst:.3} ulp"); - assert!(worst <= 4.0, "{fun:?}: {worst:.3} ulp"); - } -} - -mod precise_sin_and_cos_routines_are_metals { - parts!(super::precise_sin_cos_is_metals, 8; part_1_of_8 = 0, part_2_of_8 = 1, - part_3_of_8 = 2, part_4_of_8 = 3, part_5_of_8 = 4, part_6_of_8 = 5, part_7_of_8 = 6, - part_8_of_8 = 7); -} - -/// [`metal_sin_cos_model`] is Metal's precise `sin` and `cos` at words measured on the M3 Max, 8 of -/// each in `[2^-12, 1/4)` and in `[1/4, 1)`, where Metal's word is not the -/// correctly rounded value, and the routines answer them bit for bit, with and without `OpFmaKHR`. -#[test] -fn precise_sin_and_cos_answer_metals_measured_words() { - let words: [(u32, u32); 32] = [ - (0x3E80_3039, 0x3E7D_B4E7), - (0x3EA0_3039, 0x3E9D_9678), - (0x3EC0_3039, 0x3EBB_B4F2), - (0x3EE0_303A, 0x3ED9_17C5), - (0x3F00_3039, 0x3EF5_CBE2), - (0x3F20_3039, 0x3F15_F009), - (0x3F40_303C, 0x3F2E_A328), - (0x3F60_3039, 0x3F44_9CA0), - (0x3983_0390, 0x3983_038F), - (0x3A43_03D0, 0x3A43_03CE), - (0x3B04_92B0, 0x3B04_92A9), - (0x3BC3_0FF0, 0x3BC3_0FA5), - (0x3C83_0390, 0x3C83_0221), - (0x3D43_0390, 0x3D42_F0B5), - (0x3E03_0390, 0x3E02_A821), - (0x3EC3_03A0, 0x3EBE_553E), - (0x3E80_3039, 0x3F78_04AC), - (0x3EA0_303C, 0x3F73_9289), - (0x3EC0_303B, 0x3F6E_2CE8), - (0x3EE0_303A, 0x3F67_D930), - (0x3F00_303A, 0x3F60_921E), - (0x3F20_3039, 0x3F4F_7F0C), - (0x3F40_3039, 0x3F3B_2F13), - (0x3F60_3039, 0x3F23_F358), - (0x3983_0390, 0x3F80_0000), - (0x3A43_0390, 0x3F7F_FFFA), - (0x3B03_0390, 0x3F7F_FFDF), - (0x3BC3_0390, 0x3F7F_FED8), - (0x3C83_0390, 0x3F7F_F79F), - (0x3D43_03A0, 0x3F7F_B5BB), - (0x3E03_03B0, 0x3F7D_E854), - (0x3EC3_03C0, 0x3F6D_A75C), - ]; - let f = f32s(); - for (i, (x, want)) in words.into_iter().enumerate() { - let (fun, cos) = if i < 16 { - (Fun::Sin, false) - } else { - (Fun::Cos, true) - }; - let got = metal_sin_cos_model(f32::from_bits(x), cos).to_bits(); - assert_eq!(got, want, "{fun:?} model at {x:#010x}"); - for fma in [false, true] { - check_module( - &format!("{fun:?}({x:#010x}) fma={fma}"), - routine_module(fun, false, fma), - &[f], - f, - &[vec![vec![u64::from(x)]]], - &|_| Some(vec![u64::from(want)]), - &|g, w| g == w, - ); - } - } -} - -/// Metal's precise `sin`, `cos`, and `tan` at their special operands (cases 087758cb and cc234732): -/// a zero or a denormal is its own `sin` and `tan` and has `cos` 1, signs kept, and an infinity or -/// NaN answers a NaN. -#[test] -fn trig_routines_answer_metals_special_values() { - let f = f32s(); - for rough in [false, true] { - for x in [ - 0x0000_0000u64, - 0x8000_0000, - 0x0000_0001, - 0x8000_0001, - 0x007F_FFFF, - 0x807F_FFFF, - 0x0080_0000, - 0x8080_0000, - 0x3900_0000, - 0xB880_0000, - ] { - for (fun, want) in [(Fun::Sin, x), (Fun::Cos, 0x3F80_0000), (Fun::Tan, x)] { - check_module( - &format!("{fun:?}({x:#010x}) rough={rough}"), - routine_module(fun, rough, false), - &[f], - f, - &[vec![vec![x]]], - &|_| Some(vec![want]), - &|g, w| g == w, - ); - } - } - for x in [0x7F80_0000u64, 0xFF80_0000, 0x7FC0_0000] { - for fun in [Fun::Sin, Fun::Cos, Fun::Tan] { - check_module( - &format!("{fun:?}({x:#010x}) rough={rough}"), - routine_module(fun, rough, false), - &[f], - f, - &[vec![vec![x]]], - &|_| Some(vec![0x7FC0_0000]), - &|g, _| f32v(g).is_nan(), - ); - } - } - } -} - -/// Metal's `sinpi`, `cospi`, or `tanpi` (`op`) of `x` as the model computes it: the routine's form -/// (`libm::pi`) in `f32` arithmetic, its fused step one `mul_add`, the `sinc` [`metal_sinc_model`], -/// and Metal's reciprocal through its model (`+inf` of the `+0` at a half-integer). -pub(super) fn metal_pi_model(op: FloatFn, x: f32) -> f32 { - use crate::lower::arith::libm::rcp; - let a = x.to_bits() & 0x7FFF_FFFF; - if a >= 0x7F80_0000 { - return f32::from_bits(0x7FC0_0000); - } - // Metal reads a denormal as the zero of its sign. - let x = if a < 0x0080_0000 { 0f32.copysign(x) } else { x }; - let (large, whole) = (a >= 0x4B00_0000, a >= 0x4B80_0000); - let b = if large && op != FloatFn::SinPi { - 0.0 - } else { - 16_777_216f32.copysign(x) - }; - let x2 = x * 2.0; - let s = x2 + b; - let t = x2 + (b - s); - let odd = s.to_bits() & 1 != 0; - let at = t.abs(); - let rest = 1.0 - at; - let signed = |v: f32| if odd { -v } else { v }; - match op { - FloatFn::SinPi if large => 0.0, - FloatFn::SinPi => signed(t) * metal_sinc_model(at), - FloatFn::CosPi if whole => 1.0, - FloatFn::CosPi => signed(rest) * metal_sinc_model(rest), - _ if whole => 0.0, - _ => { - let a = t * metal_sinc_model(at); - let c = metal_sinc_model(rest); - let den = c.mul_add(-at, c); - let q = if den == 0.0 { - f32::INFINITY - } else { - rcp::model(den) - }; - a * q - } - } -} - -/// `sin(π x)`, `cos(π x)`, or `tan(π x)` (`op`) of the exact `x` in `f64`, by the exact quarter -/// turn `q` and residue `u` in `[-1/4, 1/4]` of `x = q/2 + u` (mod 2), so that the zeros and -/// poles are exact; `None` at a pole. -fn exact_pi(op: FloatFn, x: f32) -> Option { - let x = f64::from(x); - let r = x - 2.0 * (x / 2.0).round_ties_even(); - let q = (2.0 * r).round_ties_even(); - let u = r - q / 2.0; - let (su, cu) = ( - (std::f64::consts::PI * u).sin(), - (std::f64::consts::PI * u).cos(), - ); - let (s, c) = match q as i64 { - 0 => (su, cu), - 1 => (cu, -su), - -1 => (-cu, su), - _ => (-su, -cu), - }; - match op { - FloatFn::SinPi => Some(s), - FloatFn::CosPi => Some(c), - _ if c == 0.0 => None, - _ => Some(s / c), - } -} - -/// The operands of the `π`-scaled routines' checks: [`operands`], every 131,071st finite `float`, -/// the floats about `2^23` and `2^24` (where the half turns change form) and about the first 256 -/// quarter turns, the tiny ones, Metal's measured operands, [`DENORMALS`], the infinities, and a -/// NaN, both signs. -fn pi_operands() -> Vec { - let mut xs = operands(0x5150_0C05, 3000); - xs.extend((0..0x7F80_0000u32).step_by(131_071).map(u64::from)); - for edge in [0x4B00_0000u32, 0x4B80_0000, 0x0080_0000, 0x3380_0000] { - xs.extend((0..=64u32).map(|d| u64::from(edge + d - 32))); - } - for k in 1..=256u32 { - let b = (k as f32 / 4.0).to_bits(); - xs.extend((0..=4u32).map(|d| u64::from(b + d - 2))); - } - xs.extend( - PI_WORDS - .iter() - .flat_map(|(_, words)| words.iter().map(|w| u64::from(w.0))), - ); - xs.extend(DENORMALS); - xs.extend([0x7F80_0000, 0x7FC0_0000]); - xs.iter() - .flat_map(|b| [*b & 0x7FFF_FFFF, *b | 0x8000_0000]) - .collect() -} - -/// The `sinpi`, `cospi`, and `tanpi` routines answer [`metal_pi_model`] bit for bit, with and -/// without `OpFmaKHR`, over [`pi_operands`]. Part `part` of `of` checks every `of`-th operand. -fn precise_pi_is_metals(part: usize, of: usize) { - let f = f32s(); - let xs = part_of(pi_operands(), part, of); - let cases: Vec = xs.iter().map(|x| vec![vec![*x]]).collect(); - for (fun, op) in [ - (Fun::SinPi(Mode::Precise), FloatFn::SinPi), - (Fun::CosPi(Mode::Precise), FloatFn::CosPi), - (Fun::TanPi(Mode::Precise), FloatFn::TanPi), - ] { - for fma in [false, true] { - check_module( - &format!("{fun:?} fma={fma}"), - routine_module(fun, false, fma), - &[f], - f, - &cases, - &|c| Some(vec![u64::from(metal_pi_model(op, f32v(c[0][0])).to_bits())]), - &|g, w| g == w, - ); - } - } -} - -mod pi_routines_are_metals { - parts!(super::precise_pi_is_metals, 6; part_1_of_6 = 0, part_2_of_6 = 1, - part_3_of_6 = 2, part_4_of_6 = 3, part_5_of_6 = 4, part_6_of_6 = 5); -} - -/// [`metal_pi_model`] lies within 3 ulp of the exact value for `sinpi` and `cospi`, and within 5 -/// for `tanpi`, over [`pi_operands`] and every 4,099th finite normal `float`, both signs (the worst -/// over every `float` from `2^-11` by the model, our probe's analysis: 2.26 and 4.25); and it -/// answers a denormal operand as its zero. -#[test] -fn pi_model_stays_near_the_exact_value() { - let mut xs = pi_operands(); - xs.extend( - (0x0080_0000..0x7F80_0000u32) - .step_by(4_099) - .flat_map(|b| [b, b | 0x8000_0000]) - .map(u64::from), - ); - for (op, limit) in [ - (FloatFn::SinPi, 3.0), - (FloatFn::CosPi, 3.0), - (FloatFn::TanPi, 5.0), - ] { - let mut worst = (0f64, 0u64); - for b in &xs { - let x = f32v(*b); - let got = metal_pi_model(op, x); - if !x.is_finite() { - assert_eq!(got.to_bits(), 0x7FC0_0000, "{op:?}({b:#010x})"); - continue; - } - if x != 0.0 && x.is_subnormal() { - let zero = metal_pi_model(op, 0.0); - assert_eq!(got.to_bits(), zero.to_bits(), "{op:?}({b:#010x})"); - continue; - } - let Some(w) = exact_pi(op, x) else { - assert!(got.is_infinite(), "{op:?}({b:#010x}) = {got:e} at a pole"); - continue; - }; - if w.abs() > f64::from(f32::MAX) { - continue; - } - let e = (f64::from(got) - w).abs() / ulp32(w); - if e > worst.0 { - worst = (e, *b); - } - } - eprintln!("{op:?}: worst {:.4} ulp at {:#010x}", worst.0, worst.1); - assert!( - worst.0 <= limit, - "{op:?}: {:.4} ulp at {:#010x}", - worst.0, - worst.1 - ); - } -} - -/// Metal's `sinpi`, `cospi`, and `tanpi` (precise and fast answer alike) at operands measured on -/// the M3 Max (the M4's, are the same), two in each of five ranges where Metal's word is not the -/// correctly rounded value: about `1/4`, about 1, the tiny operands, from 4, and the small negative -/// ones. -const PI_WORDS: [(FloatFn, [(u32, u32); 10]); 3] = [ - ( - FloatFn::SinPi, - [ - (0x3E80_3003, 0x3F35_3A40), - (0x3E80_4004, 0x3F35_4BFF), - (0x3F80_5005, 0xBBFB_62E4), - (0x3F80_A00A, 0xBC7B_60FF), - (0x3380_0000, 0x3449_0FDA), - (0x3380_B010, 0x344A_2469), - (0x4080_B100, 0x3D8A_E8A3), - (0x4084_2600, 0x3ECA_CE62), - (0xBA00_6840, 0xBAC9_B396), - (0xBA01_38C0, 0xBACA_FB19), - ], - ), - ( - FloatFn::CosPi, - [ - (0x3E80_2002, 0x3F34_E163), - (0x3E80_4004, 0x3F34_BDCA), - (0x3F80_2002, 0xBF7F_FFB0), - (0x3F80_7007, 0xBF7F_FC39), - (0x38A3_A790, 0x3F80_0000), - (0x38A4_57A0, 0x3F80_0000), - (0x4080_B100, 0x3F7F_6913), - (0x4081_6200, 0x3F7D_A502), - (0xBA02_D9C0, 0x3F7F_FFEC), - (0xBA03_4200, 0x3F7F_FFEC), - ], - ), - ( - FloatFn::TanPi, - [ - (0x3E80_3003, 0x3F80_4B82), - (0x3E80_5005, 0x3F80_7DEF), - (0x3F80_2002, 0x3B49_1C96), - (0x3F80_5005, 0x3BFB_64C9), - (0x3380_0000, 0x3449_0FDA), - (0x3380_B010, 0x344A_2469), - (0x4082_1300, 0x3E53_7445), - (0x4084_2600, 0x3EDC_DF5A), - (0xBA01_A100, 0xBACB_9EEC), - (0xBA02_0940, 0xBACC_42AC), - ], - ), -]; - -/// [`metal_pi_model`] is Metal's word at [`PI_WORDS`] and at the exact answers of -/// [`METAL_SINPI_COSPI`] and [`METAL_TANPI`] (the zeros, poles, units, quarter turns, large and -/// non-finite operands), and the routines of a precise and a fast call (Metal's fast functions -/// are its precise ones) answer them bit for bit, with and without `OpFmaKHR`. -#[test] -fn pi_routines_answer_metals_measured_words() { - let f = f32s(); - for (op, of) in [ - (FloatFn::SinPi, Fun::SinPi as fn(Mode) -> Fun), - (FloatFn::CosPi, Fun::CosPi), - (FloatFn::TanPi, Fun::TanPi), - ] { - let mut words: Vec<(u32, u32)> = PI_WORDS - .iter() - .filter(|(o, _)| *o == op) - .flat_map(|(_, w)| w.iter().copied()) - .collect(); - words.extend(match op { - FloatFn::SinPi => METAL_SINPI_COSPI.iter().map(|r| (r.0, r.1)).collect(), - FloatFn::CosPi => METAL_SINPI_COSPI.iter().map(|r| (r.0, r.2)).collect(), - _ => METAL_TANPI.to_vec(), - }); - for (x, want) in &words { - let got = metal_pi_model(op, f32::from_bits(*x)).to_bits(); - assert_eq!(got, *want, "{op:?} model at {x:#010x}: {got:#010x}"); - } - let cases: Vec = words - .iter() - .map(|(x, _)| vec![vec![u64::from(*x)]]) - .collect(); - for (fun, fma) in [Mode::Precise, Mode::Fast] - .into_iter() - .flat_map(|m| [(of(m), false), (of(m), true)]) - { - check_module( - &format!("{fun:?} fma={fma} at Metal's measured operands"), - routine_module(fun, false, fma), - &[f], - f, - &cases, - &|c| { - let x = c[0][0] as u32; - words - .iter() - .find(|(m, _)| *m == x) - .map(|(_, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - } - } -} - -/// `a 2^k` against one, for `a` below `2^127`. -fn against_one(a: u128, k: i32) -> std::cmp::Ordering { - use std::cmp::Ordering; - match (a, k) { - (0, _) => Ordering::Less, - (_, 0..) => { - if a == 1 && k == 0 { - Ordering::Equal - } else { - Ordering::Greater - } - } - _ if -k >= 127 => Ordering::Less, - _ => a.cmp(&(1u128 << -k)), - } -} - -/// A positive finite `float` as `(M, e)`, `M 2^e`, `M` its integer significand. -fn significand(x: f32) -> (u128, i32) { - let b = x.to_bits(); - let e = ((b >> 23) & 0xFF) as i32; - let f = u128::from(b & 0x007F_FFFF); - if e == 0 { - (f, -149) - } else { - (f | (1 << 23), e - 150) - } -} - -/// The correctly rounded `rsqrt` of a positive finite `float` (a positive normal answer): the -/// `f64` estimate or a neighbour, whichever lies between the midpoints `m` around the exact -/// value `t`, decided exactly (`m < t` exactly when `m^2 x < 1`). -pub(super) fn rsqrt_exact(x: f32) -> f32 { - use std::cmp::Ordering; - let (mx, ex) = significand(x); - let estimate = (1.0 / f64::from(x).sqrt()) as f32; - let candidates = [ - estimate, - f32::from_bits(estimate.to_bits() + 1), - f32::from_bits(estimate.to_bits() - 1), - ]; - for r in candidates { - let (mr, er) = significand(r); - let up = (2 * mr + 1) * (2 * mr + 1) * mx; - let below_upper = against_one(up, 2 * er - 2 + ex) == Ordering::Greater; - let (low, k) = if mr == 1 << 23 { - ((4 * mr - 1) * (4 * mr - 1) * mx, 2 * er - 4 + ex) - } else { - ((2 * mr - 1) * (2 * mr - 1) * mx, 2 * er - 2 + ex) - }; - let above_lower = against_one(low, k) == Ordering::Less; - if below_upper && above_lower { - return r; - } - } - panic!("rsqrt({x:e}): no candidate is correctly rounded"); -} - -/// Metal's fast `rsqrt` of `y` as the model computes it and the routine forms it (`libm::rsqrt`): -/// `y = m 4^k` with `m` in `[1, 4)`, `RN(hi + RN(lo + eps(m) 2^-24))` of `hi = RN(1 / sqrt(m))`, -/// `lo = RN(RN(hi d) / 2)` of `d = 1 - m hi^2` from exact products, and `eps` by Horner's rule in -/// plain `float`, scaled by `2^-k`; `+inf` of a zero or denormal, `+0` of `+inf`, and a NaN of a -/// NaN. For operands at or above `+0`, as its callers pass. -pub(super) fn rsqrt_model(y: f32) -> f32 { - let b = y.to_bits(); - let n = (b >> 23) & 0xFF; - if y.is_nan() { - return y; - } - if n == 0 { - return f32::INFINITY; - } - if b == 0x7F80_0000 { - return 0.0; - } - let k = b & 0x007F_FFFF; - let binade = (n & 1) ^ 1; - let m = f32::from_bits((0x3F80_0000 + (binade << 23)) | k); - let hi = rsqrt_exact(m); - let p = hi * hi; - let pe = (f64::from(hi) * f64::from(hi) - f64::from(p)) as f32; - let q = m * p; - let qe = (f64::from(m) * f64::from(p) - f64::from(q)) as f32; - let w = m * pe; - let d = (1.0 - q) - (qe + w); - let lo = (hi * d) * 0.5; - let row = libm::rsqrt::TABLE[((k >> 18) + 32 * binade) as usize].map(f32::from_bits); - let t = (k & 0x3_FFFF) as f32 / 262_144.0; - let eps = row.iter().rev().fold(0.0f32, |acc, c| acc * t + c); - let r = hi + (lo + eps / 16_777_216.0); - let shift = ((127 + binade as i32 - n as i32) / 2) << 23; - f32::from_bits(r.to_bits().wrapping_add(shift as u32)) -} - -/// Operands for the roots: the positive normal [`operands`] and the magnitudes of the negative -/// ones, the edges of the reduction's `[1, 4)`, and perfect squares. -fn root_operands() -> Vec { - let mut v: Vec = operands(0x0C0F_FEE5, 4000) - .into_iter() - .map(|b| b & 0x7FFF_FFFF) - .filter(|b| f32v(*b).is_normal()) - .collect(); - for x in [1.0f32, 2.0, 4.0, 0.5, 0.25] { - for d in [-2i64, -1, 0, 1, 2] { - v.push((i64::from(x.to_bits()) + d) as u64); - } - } - for k in 1u32..4096 { - let s = (k * k) as f32; - v.push(u64::from(s.to_bits())); - v.push(u64::from((s * 2f32.powi(-100)).to_bits())); - } - v.extend([0x0080_0000u64, 0x7F7F_FFFF, 0x0080_0001, 0x7F7F_FFFE]); - v -} - -/// Precise `sqrt` and `rsqrt` are correctly rounded (MSL Table 8.1) at every positive normal -/// operand checked, with the device's division and square root correctly rounded or moved 2 and 3 -/// ulp. -#[test] -fn root_routines_are_correctly_rounded() { - let xs: Vec = root_operands().iter().map(|b| vec![vec![*b]]).collect(); - let f = f32s(); - for rough in [false, true] { - for (fun, exact) in [ - (Fun::Sqrt, f32::sqrt as fn(f32) -> f32), - (Fun::Rsqrt, rsqrt_exact), - ] { - check_module( - &format!("{fun:?} rough={rough}"), - routine_module(fun, rough, false), - &[f], - f, - &xs, - &|c| Some(vec![u64::from(exact(f32v(c[0][0])).to_bits())]), - &|g, w| g == w, - ); - } - } -} - -/// Every other operand of the roots takes the device's `Sqrt` (and `rsqrt` its reciprocal): Metal's -/// answers at the zeros, infinities, and negative operands (case 087758cb), and a denormal as the -/// device reads it (the interpreter keeps it; how Metal reads one is the denormal model's). -#[test] -fn root_routines_answer_the_special_operands() { - let f = f32s(); - let nan = 0x7FC0_0000u64; - let denormal = |x: u32, rsqrt: bool| { - let s = f32::from_bits(x).sqrt(); - u64::from(if rsqrt { 1.0 / s } else { s }.to_bits()) - }; - let cases: [(Fun, u64, u64); 18] = [ - (Fun::Sqrt, 0x0000_0000, 0x0000_0000), - (Fun::Sqrt, 0x8000_0000, 0x8000_0000), - (Fun::Sqrt, 0x7F80_0000, 0x7F80_0000), - (Fun::Sqrt, 0xFF80_0000, nan), - (Fun::Sqrt, 0xBF80_0000, nan), - (Fun::Sqrt, 0x8080_0000, nan), - (Fun::Sqrt, 0x7FC0_0000, nan), - (Fun::Sqrt, 0x0000_0001, denormal(1, false)), - (Fun::Sqrt, 0x007F_FFFF, denormal(0x007F_FFFF, false)), - (Fun::Rsqrt, 0x0000_0000, 0x7F80_0000), - (Fun::Rsqrt, 0x8000_0000, 0xFF80_0000), - (Fun::Rsqrt, 0x7F80_0000, 0x0000_0000), - (Fun::Rsqrt, 0xFF80_0000, nan), - (Fun::Rsqrt, 0xBF80_0000, nan), - (Fun::Rsqrt, 0x8080_0000, nan), - (Fun::Rsqrt, 0x7FC0_0000, nan), - (Fun::Rsqrt, 0x0000_0001, denormal(1, true)), - (Fun::Rsqrt, 0x007F_FFFF, denormal(0x007F_FFFF, true)), - ]; - for rough in [false, true] { - for (fun, x, want) in cases { - check_module( - &format!("{fun:?}({x:#010x}) rough={rough}"), - routine_module(fun, rough, false), - &[f], - f, - &[vec![vec![x]]], - &|_| Some(vec![want]), - &|g, w| g == w || (f32v(g).is_nan() && f32v(w).is_nan()), - ); - } - } + .unwrap_or_else(|e| panic!("fmod {f:?}: build: {e:?}")) } /// Precise `fmod` is exact (MSL Table 8.1: 0 ulp), bit for bit against C's `fmod` (Rust's `%`) of @@ -2585,10 +150,10 @@ fn fmod_routine_is_exact() { pairs.push(vec![x, y]); } } - let f = f32s(); + let f = float(32); check_module( "Fmod", - routine_module(Fun::Fmod, false, false), + fmod_module(f), &[f, f], f, &pairs @@ -2614,7 +179,7 @@ fn fmod_routine_is_exact() { /// routine decides on the operands' bits. #[test] fn fmod_routine_reads_metals_denormal_operands() { - let f = f32s(); + let f = float(32); let nan = 0x7FC0_0000u64; for (x, y, want) in [ (0x4000_0000u64, 0x0000_0001u64, nan), @@ -2629,7 +194,7 @@ fn fmod_routine_reads_metals_denormal_operands() { ] { check_module( &format!("Fmod({x:#010x}, {y:#010x})"), - routine_module(Fun::Fmod, false, false), + fmod_module(f), &[f, f], f, &[vec![vec![x], vec![y]]], @@ -2639,45 +204,15 @@ fn fmod_routine_reads_metals_denormal_operands() { } } -/// A `half` call of `sqrt`, `rsqrt`, and `fmod` takes the `float` routine before its rounding -/// (Metal's `half` functions are the same in both modes), so it is Metal's `half` function (MSL -/// Table 8.3: correctly rounded, correctly rounded, and exact) over every pattern of the roots and -/// a grid of `fmod`'s pairs: the `float` roots' rounding to `half` is exact (24 bits hold twice -/// `half`'s 11 and two more for `sqrt`; checked exhaustively for `rsqrt`), and the remainder of two -/// `half` values is one. The half reading: `fmod(x, ±inf) = x` (where lavapipe, RADV, and NVIDIA -/// answer a NaN) and `fmod(1.5, -0.75) = 0` (RADV: 0.75). A zero remainder is Metal's `half` one: -/// `+0` for a nonzero dividend, the dividend itself for a zero one. Part `part` of `of` of the runs -/// of 4,096 operands. -fn half_roots_and_fmod(part: usize, of: usize) { - use std::collections::BTreeMap; +/// A `half` call of `fmod` takes the `float` routine before its rounding (Metal's `half` functions +/// are the same in both modes), so it is Metal's `half` `fmod` (MSL Table 8.3: exact) over a grid +/// of pairs: the remainder of two `half` values is one. The half reading: `fmod(x, ±inf) = x` +/// (where lavapipe, RADV, and NVIDIA answer a NaN) and `fmod(1.5, -0.75) = 0` (RADV: 0.75). A zero +/// remainder is Metal's `half` one: `+0` for a nonzero dividend, the dividend itself for a zero +/// one. Part `part` of `of` of the runs of 4,096 pairs. +fn half_fmod(part: usize, of: usize) { let h = float(16); let nan = |b: u64| b & 0x7C00 == 0x7C00 && b & 0x03FF != 0; - let module = |op: FloatFn, fun: Fun| { - kernel_defs( - &vec![h; fun.arity()], - h, - &|b| Ok(vec![libm::define_alone(b, fun, false)?]), - &|fb, x, funcs| { - let map: BTreeMap = funcs.iter().map(|id| (fun, *id)).collect(); - math::float_fn( - fb, - op, - h, - Contraction::Forbidden, - NanTest::IsNan, - x, - &Lib::new(None, &map), - ) - }, - true, - false, - ) - .unwrap_or_else(|e| panic!("{op:?}: build: {e:?}")) - }; - let all: Vec = (0..=0xFFFFu64) - .filter(|b| !nan(*b)) - .map(|b| vec![vec![b]]) - .collect(); let half_of = |x: f32| u64::from(f64_to_f16(f64::from(x))); let mut pairs: Vec = Vec::new(); for x in (0..=0xFFFFu64).step_by(251) { @@ -2694,40 +229,19 @@ fn half_roots_and_fmod(part: usize, of: usize) { ] { pairs.push(vec![vec![x], vec![y]]); } - let mut runs = Vec::new(); - for (op, fun) in [ - (FloatFn::Sqrt, Fun::Sqrt), - (FloatFn::Rsqrt, Fun::Rsqrt), - (FloatFn::Fmod, Fun::Fmod), - ] { - let cases = if op == FloatFn::Fmod { &pairs } else { &all }; - for run in cases.chunks(4096) { - runs.push((op, fun, run)); - } - } - for (op, fun, run) in part_of(runs, part, of) { + let runs: Vec<&[Case]> = pairs.chunks(4096).collect(); + for run in part_of(runs, part, of) { check_module( - &format!("half {op:?}"), - module(op, fun), - &vec![h; fun.arity()], + "half Fmod", + fmod_module(h), + &[h, h], h, run, &|c| { let x = f16_to_f64(c[0][0] as u16); - let r = match op { - FloatFn::Fmod => { - let y = f16_to_f64(c[1][0] as u16); - let r = (x as f32) % (y as f32); - if r == 0.0 && x != 0.0 { - 0.0 - } else { - r - } - } - FloatFn::Sqrt => (x as f32).sqrt(), - _ if x > 0.0 && x.is_finite() => rsqrt_exact(x as f32), - _ => 1.0 / (x as f32).sqrt(), - }; + let y = f16_to_f64(c[1][0] as u16); + let r = (x as f32) % (y as f32); + let r = if r == 0.0 && x != 0.0 { 0.0 } else { r }; Some(vec![half_of(r)]) }, &|g, w| g == w || (nan(g) && nan(w)), @@ -2735,399 +249,79 @@ fn half_roots_and_fmod(part: usize, of: usize) { } } -mod half_roots_and_fmod_take_the_routines { - parts!(super::half_roots_and_fmod, 8; - part_1_of_8 = 0, part_2_of_8 = 1, part_3_of_8 = 2, part_4_of_8 = 3, - part_5_of_8 = 4, part_6_of_8 = 5, part_7_of_8 = 6, part_8_of_8 = 7); +mod half_fmod_takes_the_routine { + parts!(super::half_fmod, 4; + part_1_of_4 = 0, part_2_of_4 = 1, part_3_of_4 = 2, part_4_of_4 = 3); } -/// The [`trig_operands`] from `float(π)` up in magnitude, past `π`, where Metal's fast `sin` and -/// `cos` take the precise routine (inside, the device's instruction answers, which the -/// interpreter does not model). -fn past_pi_operands() -> Vec { - let mut v = trig_operands(); - assert!(v.contains(&u64::from(std::f32::consts::PI.to_bits()))); - v.retain(|b| f32v(*b).abs() >= std::f32::consts::PI); - v -} - -/// Metal's fast `sin` and `cos` past `π` (where Apple states no bound and RADV, ANV, and NVIDIA are -/// up to 1.8 off) are its precise functions, which the routines compute under the branch: -/// [`metal_sin_cos_model`] bit for bit. Part `part` of `of` checks every `of`-th operand. -fn fast_trig_past_pi(part: usize, of: usize) { - let xs = part_of(past_pi_operands(), part, of); - let f = f32s(); - for (fun, cos) in [(Fun::FastSin, false), (Fun::FastCos, true)] { - check_module( - &format!("{fun:?} past π"), - routine_module(fun, false, false), - &[f], - f, - &xs.iter().map(|x| vec![vec![*x]]).collect::>(), - &|c| { - Some(vec![u64::from( - metal_sin_cos_model(f32v(c[0][0]), cos).to_bits(), - )]) +/// Metal's fast `pow` and `powr` (and its `half` ones, the same compositions) where `y · log2(x)` +/// is infinite answer IEEE's value whatever the composition gave there (`math::infinite_product` +/// 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. +#[test] +fn an_infinite_product_answers_ieee_whatever_the_composition_gave() { + let (f, h) = (float(32), float(16)); + let one = u64::from(1.0f32.to_bits()); + let one_h = 0x3C00; + // (x, y, answer); `None`: the composition's value kept. + 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)), + (0x7F80_0000, 0xC000_0000, Some(0)), + (0x7F80_0000, 0x4100_0000, Some(0x7F80_0000)), + (0x3F00_0000, 0x7F80_0000, Some(0)), + (0x4000_0000, 0x7F80_0000, Some(0x7F80_0000)), + (0x3F00_0000, 0xFF80_0000, Some(0x7F80_0000)), + (0x4000_0000, 0xFF80_0000, Some(0)), + (0x3F80_0000, 0x7F80_0000, None), + (0x0000_0000, 0x0000_0000, None), + (0x7FC0_0000, 0x4000_0000, None), + (0x4000_0000, 0x4040_0000, None), + ]; + let half_words: [(u64, u64, Option); 8] = [ + (0x0000, 0x3C00, Some(0)), + (0x8000, 0x4000, Some(0)), + (0x7C00, 0xC000, Some(0)), + (0x7C00, 0x4800, Some(0x7C00)), + (0x3800, 0x7C00, Some(0)), + (0x4000, 0xFC00, Some(0)), + (0x0001, 0x3C00, None), + (0x3C00, 0x7C00, None), + ]; + for (form, words, kept) in [(f, &words[..], one), (h, &half_words[..], one_h)] { + let module = kernel_defs( + &[form, form], + form, + &|_| Ok(Vec::new()), + &|fb, x, _| { + let r = crate::lower::arith::ops::fsplat(fb, form, 1.0)?; + math::infinite_product(fb, form, x[1], x[0], r) }, - &|g, w| g == w, - ); - } -} - -mod fast_trig_routines_take_the_precise_routine_past_pi { - parts!(super::fast_trig_past_pi, 6; part_1_of_6 = 0, part_2_of_6 = 1, - part_3_of_6 = 2, part_4_of_6 = 3, part_5_of_6 = 4, part_6_of_6 = 5); -} - -/// `fast::tan` off a device whose functions are Metal's in a fast-math module is Apple's formula -/// `sin(x) · (1 / cos(x))` (MSL Table 8.2) of Metal's fast functions divided by its fast division's -/// routine, by either reciprocal: past `π` the formula of Metal's functions -/// ([`metal_sin_cos_model`]) bit for bit, the reciprocal and the product each rounded once, and -/// past Metal's flush point, where both flush to `+0`, the canonical NaN `0 · (1 / 0)` that Metal -/// answers at 148 of the 160 such lanes of case cc234732. Part `part` of `of` checks every `of`-th -/// operand past `π`. -fn fast_tan_formula(part: usize, of: usize) { - use std::collections::BTreeMap; - let f = f32s(); - let module = |reciprocal: Reciprocal| { - let division = math::FastDivision::new(f, reciprocal, Contraction::Forbidden); - kernel_defs( - &[f], - f, - &|b| { - Ok(vec![ - libm::define_alone(b, Fun::FastSin, false)?, - libm::define_alone(b, Fun::FastCos, false)?, - math::define_fast_division(b, division)?, - ]) - }, - &|fb, x, funcs| { - let map: BTreeMap = [Fun::FastSin, Fun::FastCos] - .into_iter() - .zip(funcs.iter().copied()) - .collect(); - let divide = |fb: &mut FunctionBuilder<'_>, p: Value, q: Value| { - math::call_fast_division(fb, funcs[2], p, q) - }; - math::fast_tan(fb, f, x[0], &Lib::new(None, &map), ÷) - }, - true, + false, false, ) - .unwrap_or_else(|e| panic!("FastTan {reciprocal:?}: build: {e:?}")) - }; - let limit = f64::from(math::FAST_TRIG_LIMIT); - let (below, past): (Vec, Vec) = part_of(past_pi_operands(), part, of) - .into_iter() - .partition(|b| f64::from(f32v(*b)).abs() <= limit); - for reciprocal in [Reciprocal::Device, Reciprocal::Rounded] { + .expect("build"); + let cases: Vec = words + .iter() + .map(|(x, y, _)| vec![vec![*x], vec![*y]]) + .collect(); check_module( - "FastTan past π", - module(reciprocal), - &[f], - f, - &below.iter().map(|b| vec![vec![*b]]).collect::>(), + &format!("infinite product {form:?}"), + module, + &[form, form], + form, + &cases, &|c| { - let x = f32v(c[0][0]); - let (s, c) = (metal_sin_cos_model(x, false), metal_sin_cos_model(x, true)); - Some(vec![u64::from((s * (1.0 / c)).to_bits())]) + words + .iter() + .find(|(x, y, _)| (*x, *y) == (c[0][0], c[1][0])) + .map(|(_, _, w)| vec![w.unwrap_or(kept)]) }, &|g, w| g == w, ); - check_module( - "FastTan of a denormal", - module(reciprocal), - &[f], - f, - &DENORMALS - .iter() - .map(|b| vec![vec![*b]]) - .collect::>(), - &|c| Some(vec![c[0][0]]), - &|g, w| g == w, - ); - check_module( - "FastTan past the flush point", - module(reciprocal), - &[f], - f, - &past.iter().map(|b| vec![vec![*b]]).collect::>(), - &|_| Some(vec![0x7FC0_0000]), - &|g, w| g == w, - ); } } - -mod fast_tan_is_apples_formula_of_the_fast_functions { - parts!(super::fast_tan_formula, 8; part_1_of_8 = 0, part_2_of_8 = 1, part_3_of_8 = 2, - part_4_of_8 = 3, part_5_of_8 = 4, part_6_of_8 = 5, part_7_of_8 = 6, part_8_of_8 = 7); -} - -/// `f32` denormals of both signs: the smallest, the largest, and between. -pub(super) const DENORMALS: [u64; 8] = [ - 0x0000_0001, - 0x8000_0001, - 0x007F_FFFF, - 0x807F_FFFF, - 0x0040_0000, - 0x8040_0000, - 0x0000_1234, - 0x8012_3456, -]; - -/// Metal keeps a denormal operand of `fast::sin` and `fast::cos` (case cc234732, every such lane: -/// `fast::sin(x) = x`, `fast::cos(x) = 1`), where RADV, ANV, and NVIDIA flush it: the routines send -/// a denormal lane, told by its bits, to the precise routine, whose selects answer it (the device's -/// instruction, which the interpreter does not model, is not reached). -#[test] -fn fast_trig_routines_keep_a_denormal() { - let f = f32s(); - for rough in [false, true] { - for (fun, cos) in [(Fun::FastSin, false), (Fun::FastCos, true)] { - check_module( - &format!("{fun:?} of a denormal rough={rough}"), - routine_module(fun, rough, false), - &[f], - f, - &DENORMALS - .iter() - .map(|b| vec![vec![*b]]) - .collect::>(), - &|c| Some(vec![if cos { 0x3F80_0000 } else { c[0][0] }]), - &|g, w| g == w, - ); - } - } -} - -/// The device's divisions and square roots in `m`: `OpFDiv`, and `GLSL.std.450`'s `Sqrt` (31) -/// and `InverseSqrt` (32), the only extended instruction set the routines import. -fn device_divisions_and_roots(m: TypedModule) -> usize { - let words = serialize(m).expect("serialize").words; - let mut at = 5; - let mut n = 0; - while at < words.len() { - let w = words[at]; - let op = w & 0xFFFF; - let root = - op == crate::spv::Op::ExtInst as u32 && matches!(words.get(at + 4), Some(31 | 32)); - n += usize::from(op == crate::spv::Op::FDiv as u32 || root); - at += (w >> 16).max(1) as usize; - } - n -} - -/// No routine's answer depends on the device's division or square root, which Vulkan bounds at 2.5 -/// and 3 ulp: no routine divides or takes a square root but through the module's correctly rounded -/// routines ([`Fun::needs`]), with and without `OpFmaKHR`. Only those of `sqrt` and `rsqrt` take -/// the device's, which they correct exactly (`root_routines_are_correctly_rounded`, with the -/// device's moved), as the precise division routine does its quotient -/// (`precise_division_answers_metal_on_both_paths`). So a routine's answers on the interpreter, -/// whose division and square root are correctly rounded, are its answers on every device. -#[test] -fn routines_divide_and_take_roots_only_through_their_helpers() { - let mut wrong = Vec::new(); - for fun in [ - Fun::Atan(Mode::Precise), - Fun::Atan(Mode::Fast), - Fun::Asin(Mode::Precise), - Fun::Asin(Mode::Fast), - Fun::Acos(Mode::Precise), - Fun::Acos(Mode::Fast), - Fun::Atan2, - Fun::Sin, - Fun::Cos, - Fun::Tan, - Fun::FastSin, - Fun::FastCos, - Fun::SinPi(Mode::Precise), - Fun::CosPi(Mode::Precise), - Fun::TanPi(Mode::Precise), - Fun::SinPi(Mode::Fast), - Fun::CosPi(Mode::Fast), - Fun::TanPi(Mode::Fast), - Fun::Fmod, - Fun::Exp2, - Fun::Exp, - Fun::Exp10, - Fun::Log2, - Fun::Log, - Fun::Log10, - Fun::Powr, - Fun::Sinh, - Fun::Cosh, - Fun::Tanh, - Fun::Asinh, - Fun::Acosh, - Fun::Atanh, - Fun::FastAsinh, - Fun::FastAcosh, - Fun::Recip, - Fun::FastRsqrt, - Fun::Fused, - Fun::HalfAtan, - Fun::HalfAtan2, - Fun::HalfTan, - ] { - for fma in [false, true] { - let own = device_divisions_and_roots(routine_module(fun, false, fma)) - - device_divisions_and_roots(helpers_module(fun, fma)); - if own != 0 { - wrong.push(format!("{fun:?} fma={fma}: {own}")); - } - } - } - assert!(wrong.is_empty(), "{wrong:#?}"); -} - -/// Each routine calls exactly the helpers [`Fun::needs`] lists: it is defined with them, and not -/// without any of them. -#[test] -fn each_routine_needs_what_it_calls() { - let mut wrong = Vec::new(); - for fun in [ - Fun::Atan(Mode::Precise), - Fun::Atan(Mode::Fast), - Fun::Asin(Mode::Precise), - Fun::Asin(Mode::Fast), - Fun::Acos(Mode::Precise), - Fun::Acos(Mode::Fast), - Fun::Atan2, - Fun::Sin, - Fun::Cos, - Fun::Tan, - Fun::FastSin, - Fun::FastCos, - Fun::SinPi(Mode::Precise), - Fun::CosPi(Mode::Precise), - Fun::TanPi(Mode::Precise), - Fun::SinPi(Mode::Fast), - Fun::CosPi(Mode::Fast), - Fun::TanPi(Mode::Fast), - Fun::Sqrt, - Fun::Rsqrt, - Fun::Fmod, - Fun::Exp2, - Fun::Exp, - Fun::Exp10, - Fun::Log2, - Fun::Log, - Fun::Log10, - Fun::Powr, - Fun::Sinh, - Fun::Cosh, - Fun::Tanh, - Fun::Asinh, - Fun::Acosh, - Fun::Atanh, - Fun::FastAsinh, - Fun::FastAcosh, - Fun::Recip, - Fun::FastRsqrt, - Fun::Fused, - Fun::HalfAtan, - Fun::HalfAtan2, - Fun::HalfTan, - Fun::HalfSin, - Fun::HalfCos, - Fun::HalfAsinh, - ] { - let needs = fun.needs(); - let mut b = ModuleBuilder::new(); - let helpers = libm::define_helpers(&mut b, needs, false, false).expect("helpers"); - if let Err(e) = libm::define(&mut b, fun, false, helpers) { - wrong.push(format!("{fun:?} with its helpers: {e:?}")); - } - for (missing, without) in [ - ( - needs.division, - libm::Helpers { - division: None, - ..helpers - }, - ), - ( - needs.exp2, - libm::Helpers { - exp2: None, - ..helpers - }, - ), - ( - needs.log2, - libm::Helpers { - log2: None, - ..helpers - }, - ), - ( - needs.rcp, - libm::Helpers { - rcp: None, - ..helpers - }, - ), - ( - needs.recip, - libm::Helpers { - recip: None, - ..helpers - }, - ), - ( - needs.inverse_root, - libm::Helpers { - inverse_root: None, - ..helpers - }, - ), - ( - needs.rsqrt, - libm::Helpers { - rsqrt: None, - ..helpers - }, - ), - ( - needs.fast_inverse_root, - libm::Helpers { - fast_inverse_root: None, - ..helpers - }, - ), - ( - needs.fused, - libm::Helpers { - fused: None, - ..helpers - }, - ), - ( - needs.quarter, - libm::Helpers { - quarter: None, - ..helpers - }, - ), - ( - needs.sinc, - libm::Helpers { - sinc: None, - ..helpers - }, - ), - ( - needs.powr, - libm::Helpers { - powr: None, - ..helpers - }, - ), - ] { - if missing && libm::define(&mut b, fun, false, without).is_ok() { - wrong.push(format!("{fun:?} is defined without a helper it lists")); - } - } - } - assert!(wrong.is_empty(), "{}", wrong.join("\n")); -} diff --git a/crates/metal2vulkan/src/lower/arith/tests/libm_exp.rs b/crates/metal2vulkan/src/lower/arith/tests/libm_exp.rs deleted file mode 100644 index 98f7ae74b..000000000 --- a/crates/metal2vulkan/src/lower/arith/tests/libm_exp.rs +++ /dev/null @@ -1,2704 +0,0 @@ -//! The second stage's routines on the interpreter: the exponentials, the logarithms, `powr`, and -//! the hyperbolic functions and their inverses, each Metal's measured form where it is identified -//! (bit for bit against its model) and otherwise within an ulp of the exact value over its range -//! with the device's division and square root exact and moved to the edge of what the routine -//! corrects; Metal's answers at the special operands, bit for bit; and the fast functions' formulas -//! at theirs. - -use super::libm::{ - f32s, helpers_module, operands, routine_module, rsqrt_model, unary, worst_error, DENORMALS, -}; -use super::*; -use crate::lower::arith::libm::rcp::model as rcp_model; -use crate::lower::arith::libm::{self, Fun}; -use crate::spirv::serialize::serialize; -use std::collections::BTreeMap; - -/// A float uniformly in `[lo, hi]`. -fn uniform(rng: &mut Rng, lo: f64, hi: f64) -> u64 { - let t = (rng.next() >> 11) as f64 / (1u64 << 53) as f64; - u64::from(((lo + (hi - lo) * t) as f32).to_bits()) -} - -/// `n` floats of magnitude log-uniform in `[2^lo, 2^hi]`, both signs. -fn magnitudes(rng: &mut Rng, lo: f64, hi: f64, n: usize) -> Vec { - (0..n) - .map(|_| { - let b = uniform(rng, lo, hi); - let x = f64::from(f32v(b)).exp2() as f32; - u64::from(x.to_bits()) | (rng.next() & 0x8000_0000) - }) - .collect() -} - -/// `x` and its neighbours `d` ulps away, `d` in `-k..=k`. -fn around(x: f32, k: i64) -> Vec { - (-k..=k) - .map(|d| (i64::from(x.to_bits()) + d) as u64) - .collect() -} - -/// Operands of the exponentials and the hyperbolic functions: [`operands`], uniform ones across -/// the range where the results are finite and normal, small magnitudes, and the neighbours of the -/// reduction's edges (the integers and half-integers). -fn exp_operands(seed: u64) -> Vec { - let mut rng = Rng(seed); - let mut v = operands(seed, 1500); - for (lo, hi, n) in [ - (-150.0, 130.0, 2500), - (-40.0, 40.0, 1500), - (-1.0, 1.0, 1000), - ] { - v.extend((0..n).map(|_| uniform(&mut rng, lo, hi))); - } - v.extend(magnitudes(&mut rng, -30.0, 3.0, 1500)); - for k in -30..=30 { - for x in [k as f32, k as f32 + 0.5, k as f32 * std::f32::consts::LN_2] { - v.extend(around(x, 2)); - } - } - v.retain(|b| f32v(*b).is_finite() && !is_denormal(*b)); - v -} - -/// Positive normal operands of the logarithms: [`operands`], the floats near 1 (where the -/// result cancels most), random ones, and the neighbours of `√2` and `√2 / 2`, where the reduction -/// changes exponent. -fn log_operands(seed: u64) -> Vec { - let mut rng = Rng(seed); - let mut v = operands(seed, 2000); - v.extend(around(1.0, 1500)); - v.extend((0..1500).map(|_| uniform(&mut rng, 0.5, 2.0))); - v.extend(magnitudes(&mut rng, -126.0, 127.9, 2000)); - v.extend(around(f32::from_bits(0x3FB5_04F3), 4)); - v.extend(around(f32::from_bits(0x3F35_04F3), 4)); - v.retain(|b| { - let x = f32v(*b); - x.is_normal() && x > 0.0 - }); - v -} - -/// Whether float bits `b` are an `f32` denormal. -fn is_denormal(b: u64) -> bool { - b & 0x7F80_0000 == 0 && b & 0x007F_FFFF != 0 -} - -/// `r` where it is a finite normal `float` value away from the edges of the range, where the -/// result's rounding to infinity or its flush below `2^-126` is checked by the special operands. -fn in_range(r: f64) -> Option { - let a = r.abs(); - let normal = a == 0.0 || a >= 1.001 * f64::from(f32::MIN_POSITIVE); - (r.is_finite() && a <= 0.999 * f64::from(f32::MAX) && normal).then_some(r) -} - -/// Metal's `log2` of positive normal float bits `x` as the model computes it: `RZ(log2(x) + eps)`, -/// `eps` the table's ([`libm::log::TABLE`]) quintic at the fraction's 32nd by Horner's rule in -/// `float`, 0 in `[PLAIN_LOW, PLAIN_END)`. `None` where the sum lies within `2^-38` of its -/// magnitude of a `float` (the routine's exact value is a pair accurate to about `2^-41`, the -/// model's a double). -fn log2_model(x: u32) -> Option { - use libm::log::{PLAIN_END, PLAIN_LOW, TABLE}; - let v = f32::from_bits(x); - if !(v.is_normal() && v > 0.0) { - return None; - } - let k = x & 0x7F_FFFF; - let eps = if (PLAIN_LOW..PLAIN_END).contains(&x) { - 0.0 - } else { - let c = TABLE[(k >> 18) as usize].map(f32::from_bits); - let t = (k & 0x3_FFFF) as f32 / 262_144.0; - let mut e = c[5]; - for j in (0..5).rev() { - e = e * t + c[j]; - } - f64::from(e) - }; - let w = f64::from(v).log2() + eps; - let r = w as f32; - let r = if f64::from(r).abs() > w.abs() { - f32::from_bits(r.to_bits() - 1) - } else { - r - }; - let away = f64::from(f32::from_bits(r.to_bits() + 1)); - let tol = w.abs() * 2f64.powi(-38); - let near = (w - f64::from(r)).abs() < tol || (away - w).abs() < tol; - (!near).then_some(r.to_bits()) -} - -/// Metal's precise `log` or `log10` of positive normal float bits `x` as the model computes it: -/// inside the [`libm::log::Near`] range `RN(f fma(p(f), f, lead))`, elsewhere [`log2_model`]'s -/// fitted word times `RN(ln 2)` or `RN(log10(2))`; `log2`'s routines' [`log2_model`]. -fn log_model(fun: Fun, x: u32) -> Option { - use libm::log::{LOG10_NEAR, LOG_NEAR}; - let (near, c) = match fun { - Fun::Log => (&LOG_NEAR, std::f32::consts::LN_2), - Fun::Log10 => (&LOG10_NEAR, std::f32::consts::LOG10_2), - _ => return log2_model(x), - }; - if near.low < x && x < near.end { - let f = f32::from_bits(x) - 1.0; - let (last, rest) = near.p.split_last()?; - let mut p = f32::from_bits(*last); - for c in rest.iter().rev() { - p = p.mul_add(f, f32::from_bits(*c)); - } - let q = p.mul_add(f, f32::from_bits(near.lead)); - return Some((f * q).to_bits()); - } - log2_model(x).map(|l| (f32::from_bits(l) * c).to_bits()) -} - -/// The `log2`, `log`, and `log10` routines answer [`log_model`] bit for bit over the logarithms' -/// operands, the edges of the plain and near ranges and of the table's 32nds, and uniform operands -/// next to 1 and in `[1/2, 4)`, and stay within 3 ulp of the exact value: part `part` of `of` of -/// the runs of 2,048 operands. -fn logarithms_are_metals(part: usize, of: usize) { - use libm::log::{LOG10_NEAR, LOG_NEAR, PLAIN_END, PLAIN_LOW}; - let mut rng = Rng(0x1065_1066); - let mut xs = log_operands(0x1065_1065); - for edge in [ - PLAIN_LOW, - PLAIN_END, - LOG_NEAR.low, - LOG_NEAR.end, - LOG10_NEAR.low, - LOG10_NEAR.end, - ] { - xs.extend(around(f32::from_bits(edge), 3)); - } - for s in 0..32u32 { - for e in [0x3F00_0000u32, 0x3F80_0000, 0x4000_0000, 0x7F00_0000] { - xs.extend(around(f32::from_bits(e | (s << 18)), 2)); - } - } - for (lo, hi) in [(0.95, 1.07), (0.5, 4.0)] { - xs.extend((0..2000).map(|_| uniform(&mut rng, lo, hi))); - } - xs.retain(|b| { - let x = f32v(*b); - x.is_normal() && x > 0.0 - }); - let mut runs = Vec::new(); - for fun in [Fun::Log2, Fun::Log, Fun::Log10] { - let modelled: Vec = xs - .iter() - .copied() - .filter(|b| log_model(fun, *b as u32).is_some()) - .collect(); - for run in modelled.chunks(2048) { - runs.push((fun, run.to_vec())); - } - } - let f = f32s(); - for (fun, run) in part_of(runs, part, of) { - check_module( - &format!("{fun:?}"), - routine_module(fun, false, false), - &[f], - f, - &run.iter().map(|x| vec![vec![*x]]).collect::>(), - &|c| log_model(fun, c[0][0] as u32).map(|w| vec![u64::from(w)]), - &|g, w| g == w, - ); - let exact: fn(f64) -> f64 = match fun { - Fun::Log2 => f64::log2, - Fun::Log => f64::ln, - _ => f64::log10, - }; - let w = worst_error( - fun, - false, - &unary(&run), - &|x| in_range(exact(f64::from(x[0]))), - 3.0, - ); - eprintln!("{fun:?}, {} operands: {w:.3}", run.len()); - } -} - -mod logarithm_routines_are_metals { - parts!(super::logarithms_are_metals, 6; - part_1_of_6 = 0, part_2_of_6 = 1, part_3_of_6 = 2, part_4_of_6 = 3, part_5_of_6 = 4, - part_6_of_6 = 5); -} - -/// The routines answer Metal's precise `log2`, `log`, and `log10` at measured words of the M4: the -/// far forms, the near polynomials and their edges, and the plain range's -/// first operand. -#[test] -fn logarithm_routines_answer_metals_measured_words() { - let words: [(Fun, u64, u64); 43] = [ - (Fun::Log2, 0x3F7F_0000, 0xBBB9_06CE), - (Fun::Log2, 0x4000_0001, 0x3F80_0001), - (Fun::Log2, 0x3FB5_04F3, 0x3EFF_FFFF), - (Fun::Log2, 0x3F35_04F3, 0xBF00_0000), - (Fun::Log2, 0x0080_0001, 0xC2FB_FFFF), - (Fun::Log2, 0x7F7F_FFFF, 0x42FF_FFFF), - (Fun::Log2, 0x3F00_0001, 0xBF7F_FFFD), - (Fun::Log2, 0x4B00_0001, 0x41B8_0000), - (Fun::Log2, 0x3FC9_0FDB, 0x3F26_C874), - (Fun::Log2, 0x4049_0FDB, 0x3FD3_643A), - (Fun::Log2, 0x3E4C_CCCD, 0xC014_9A78), - (Fun::Log2, 0x42C8_0000, 0x40D4_9A78), - (Fun::Log2, 0x3F9D_70A4, 0x3E98_E9BE), - (Fun::Log2, 0x3F60_0000, 0xBE45_44BF), - (Fun::Log, 0x3F74_0001, 0xBD44_A540), - (Fun::Log, 0x3F87_FFFF, 0x3D78_5168), - (Fun::Log, 0x3F80_0001, 0x33FF_FFFF), - (Fun::Log, 0x3F7F_FFFF, 0xB380_0000), - (Fun::Log, 0x3F74_0000, 0xBD44_A54F), - (Fun::Log, 0x3F7A_0000, 0xBCC2_492A), - (Fun::Log, 0x3F85_0000, 0x3D1C_F43E), - (Fun::Log, 0x4000_0001, 0x3F31_7219), - (Fun::Log, 0x3FB5_04F3, 0x3EB1_7217), - (Fun::Log, 0x4049_0FDB, 0x3F92_8683), - (Fun::Log, 0x3E4C_CCCD, 0xBFCE_020F), - (Fun::Log, 0x42C8_0000, 0x4093_5D8E), - (Fun::Log, 0x3F9D_70A4, 0x3E53_FB86), - (Fun::Log, 0x3F60_0000, 0xBE08_BC73), - (Fun::Log10, 0x3F77_8001, 0xBC70_445A), - (Fun::Log10, 0x3F87_BFFF, 0x3CD1_23E8), - (Fun::Log10, 0x3F80_0001, 0x335E_5BD7), - (Fun::Log10, 0x3F7F_FFFF, 0xB2DE_5BD8), - (Fun::Log10, 0x3F77_8000, 0xBC70_4479), - (Fun::Log10, 0x3F87_C000, 0x3CD1_2402), - (Fun::Log10, 0x3F7A_0000, 0xBC28_C128), - (Fun::Log10, 0x3F85_0000, 0x3C88_541E), - (Fun::Log10, 0x4000_0001, 0x3E9A_209C), - (Fun::Log10, 0x3FB5_04F3, 0x3E1A_209A), - (Fun::Log10, 0x4049_0FDB, 0x3EFE_8A6F), - (Fun::Log10, 0x3E4C_CCCD, 0xBF32_EFB3), - (Fun::Log10, 0x42C8_0000, 0x4000_0000), - (Fun::Log10, 0x3F9D_70A4, 0x3DB8_202C), - (Fun::Log10, 0x3F60_0000, 0xBD6D_88F6), - ]; - let f = f32s(); - for fun in [Fun::Log2, Fun::Log, Fun::Log10] { - let cases: Vec<(u64, u64)> = words - .iter() - .filter(|(g, _, _)| *g == fun) - .map(|(_, x, w)| (*x, *w)) - .collect(); - check_module( - &format!("{fun:?} at Metal's words"), - routine_module(fun, false, false), - &[f], - f, - &cases - .iter() - .map(|(x, _)| vec![vec![*x]]) - .collect::>(), - &|c| { - let x = c[0][0]; - cases.iter().find(|(b, _)| *b == x).map(|(_, w)| vec![*w]) - }, - &|g, w| g == w, - ); - } -} - -/// Metal's `exp2` of float bits `x` as the model computes it ([`libm::exp::TABLE`]): an operand -/// below `2^-23` in magnitude reads as 0, a NaN gives `0x7fc00000`, and otherwise `2^n (1 + T(f) -/// 2^-23)` of `k = floor(x 2^23)`, `n = k >> 23`, `f = k mod 2^23`, `+0` where the exponent field -/// is 0 or below and `+inf` from 255. -fn exp2_model(x: u32) -> u32 { - let v = f32::from_bits(x); - if v.is_nan() { - return 0x7FC0_0000; - } - let v = if v.abs() < f32::EPSILON { - 0.0 - } else { - v.clamp(-200.0, 200.0) - }; - let k = (f64::from(v) * 8_388_608.0).floor() as i64; - let (n, f) = (k >> 23, (k & 0x7F_FFFF) as u64); - let [c0, c1, c2, c3] = libm::exp::TABLE[(f >> 18) as usize].map(u64::from); - let t = f & 0x3_FFFF; - let u2 = c2 + ((c3 * t) >> 18); - let u1 = c1 + ((u2 * t) >> 18); - let y = c0 + ((u1 * t) >> 18); - assert!(y < 1 << 32, "{x:#010x}: Y {y:#x}"); - match n + 127 { - e if e <= 0 => 0, - e if e >= 255 => 0x7F80_0000, - e => ((e as u32) << 23) | (y >> 9) as u32, - } -} - -/// Metal's precise `exp` (`c` is `log2(e)`) or `exp10` (`log2(10)`) of float bits `x`, as it -/// composes its `exp2` of the model's ([`exp2_model`]): `fma(E, RN(d ln 2), E)` of `E = exp2(p)`, -/// `p = RN(x c_hi)`, and `d = fma(x, c_lo, fma(x, c_hi, -p))`, `E` itself where it is `+inf`, `+0`, -/// or a NaN; a denormal result is `+0`. -fn exp_model(x: u32, c: f64) -> u32 { - exp_composed(x, c, false) -} - -/// [`exp_model`], and with `halved` its composition of `E = exp2(p - 1)`: `e^x / 2` as Metal's -/// `sinh` and `cosh` form it from 1.5 on. -fn exp_composed(x: u32, c: f64, halved: bool) -> u32 { - let x = f32::from_bits(x); - let (hi, lo) = libm::split(c); - let p = x * hi; - let d = x.mul_add(lo, x.mul_add(hi, -p)); - let p = if halved { p - 1.0 } else { p }; - let big = f32::from_bits(exp2_model(p.to_bits())); - if big.is_infinite() || big == 0.0 || big.is_nan() { - return big.to_bits(); - } - let r = big.mul_add(d * (std::f64::consts::LN_2 as f32), big); - if r.is_subnormal() { - 0 - } else { - r.to_bits() - } -} - -/// The `exp2` routine answers its model ([`exp2_model`]) and the `exp` and `exp10` routines Metal's -/// compositions of it ([`exp_model`]) bit for bit, over the exponentials' operands and fractions of -/// `[1, 2)` of both signs, and the models are within Apple's 4 ulp of the exact value: part `part` -/// of `of` of the runs of 2,048 operands. -fn exponentials_are_metals(part: usize, of: usize) { - let mut xs = exp_operands(0x0E59_0E59); - let mut rng = Rng(0x0E5A_0E5A); - xs.extend((0..4096).map(|_| 0x3F80_0000 | (rng.next() & 0x807F_FFFF))); - let mut runs = Vec::new(); - for (fun, exact) in [ - (Fun::Exp2, f64::exp2 as fn(f64) -> f64), - (Fun::Exp, f64::exp), - (Fun::Exp10, |x: f64| 10f64.powf(x)), - ] { - for run in xs.chunks(2048) { - runs.push((fun, exact, run.to_vec())); - } - } - let f = f32s(); - for (fun, exact, run) in part_of(runs, part, of) { - let model = |x: u64| -> u64 { - let x = x as u32; - u64::from(match fun { - Fun::Exp2 => exp2_model(x), - Fun::Exp => exp_model(x, std::f64::consts::LOG2_E), - _ => exp_model(x, std::f64::consts::LOG2_10), - }) - }; - let mut worst = 0f64; - for x in &run { - let r = f64::from(f32v(model(*x))); - if let Some(v) = in_range(exact(f64::from(f32v(*x)))) { - let ulp = 2f64.powi((v.abs().log2().floor() as i32).max(-126) - 23); - worst = worst.max((r - v).abs() / ulp); - } - } - assert!(worst <= 4.0, "{fun:?}: the model is {worst:.3} ulp off"); - eprintln!("{fun:?}: the model within {worst:.3} ulp"); - check_module( - &format!("{fun:?}"), - routine_module(fun, false, false), - &[f], - f, - &run.iter().map(|x| vec![vec![*x]]).collect::>(), - &|c| Some(vec![model(c[0][0])]), - &|g, w| g == w, - ); - } -} - -mod exponential_routines_are_metals { - parts!(super::exponentials_are_metals, 6; - part_1_of_6 = 0, part_2_of_6 = 1, part_3_of_6 = 2, part_4_of_6 = 3, - part_5_of_6 = 4, part_6_of_6 = 5); -} - -/// The `exp2` routine answers Metal's words where the model does, measured on the Apple M4: -/// `exp2(0.5)` is `0x3fb504f4`, an ulp above `√2`'s rounding, as Metal answers, -/// and the other binades' and signs' reductions and flushes alike. -#[test] -fn exp2_routine_answers_metals_measured_words() { - let measured: [(u32, u32); 20] = [ - (0x3F80_0000, 0x4000_0000), - (0x3F00_0000, 0x3FB5_04F4), - (0x3DCC_CCCD, 0x3F89_2FDF), - (0x3E99_999A, 0x3F9D_9624), - (0x3F33_3333, 0x3FCF_EFC6), - (0xBE99_999A, 0x3F4F_EFC6), - (0xBFD9_999A, 0x3E9D_9624), - (0x4049_0FD0, 0x410D_330C), - (0xC0B0_0000, 0x3CB5_04F4), - (0x4124_0000, 0x4498_37F1), - (0x42C9_8000, 0x71D7_44FD), - (0xC2C8_999A, 0x0D4F_EFA9), - (0x42FF_CCCD, 0x7F6E_DB51), - (0xC2FB_CCCD, 0x0089_2FD6), - (0x3580_0000, 0x3F80_0006), - (0xB480_0000, 0x3F7F_FFFE), - (0xB400_0000, 0x3F7F_FFFF), - (0xB3FF_FFFF, 0x3F80_0000), - (0x3F7F_BE77, 0x3FFF_D297), - (0xBF40_0000, 0x3F18_37F1), - ]; - let f = f32s(); - check_module( - "Exp2 at Metal's measured words", - routine_module(Fun::Exp2, false, false), - &[f], - f, - &measured - .iter() - .map(|(x, _)| vec![vec![u64::from(*x)]]) - .collect::>(), - &|c| { - measured - .iter() - .find(|(x, _)| u64::from(*x) == c[0][0]) - .map(|(_, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - for (x, w) in measured { - assert_eq!(exp2_model(x), w, "the model at {x:#010x}"); - } -} - -/// Metal's precise `powr` magnitude of a positive normal `x` and a finite `y` as the model -/// computes it (`libm::log::powr`): `log2(x)` as a pair through [`libm::log::POWR_TABLE`] and -/// [`libm::log::POWR_P`], its product with `y` as a pair, one unit of the last place down from 128 -/// with a negative low part, and [`exp2_model`] of the high part grown as `fma(E, RN(z_l RN(ln 2)), -/// E)`, `E` itself where it is `+inf` or `+0`; a denormal result is `+0`. -fn powr_model(x: f32, y: f32) -> u32 { - use libm::log::{POWR_P, POWR_TABLE}; - if y == 1.0 { - return x.to_bits(); - } - let b = x.to_bits(); - let (mut mb, mut n) = ( - (b & 0x7F_FFFF) | 0x3F80_0000, - ((b >> 23) & 0xFF) as i32 - 127, - ); - if mb > 0x3FB5_04F3 { - mb -= 0x0080_0000; - n += 1; - } - let m = f32::from_bits(mb); - let row = POWR_TABLE[((mb >> 20) & 15) as usize - 3].map(f32::from_bits); - let p = m * row[0]; - let p_l = m.mul_add(row[1], m.mul_add(row[0], -p)); - let s = p + p_l; - let s_l = p_l - (s - p); - let u = s - 1.0; - let uh = u + s_l; - let ul = s_l - (uh - u); - let t = horner_model(&POWR_P, uh) * uh; - let (l2e, l2e_lo) = libm::split(std::f64::consts::LOG2_E); - let q0 = t + l2e; - let q0_l = (t + (l2e - q0)) + l2e_lo; - let qh = q0 + q0_l; - let ql = q0_l - (qh - q0); - let lp = uh * qh; - let l_err = ql.mul_add(uh, qh.mul_add(ul, qh.mul_add(uh, -lp))); - let lh = lp + l_err; - let ll = l_err - (lh - lp); - let ef = n as f32; - let a = ef + lh; - let r = ll + (lh - (a - ef)); - let g = a + r; - let gl = r - (g - a); - let (log_hi, log_lo) = (row[2], row[3]); - let s2 = log_hi + g; - let rest = if log_hi.abs() < g.abs() { - gl + (log_lo + (log_hi + (g - s2))) - } else { - log_lo + (gl + (g + (log_hi - s2))) - }; - let gh = s2 + rest; - let gl = rest - (gh - s2); - let y = y.clamp(-2_147_483_648.0, 2_147_483_648.0); - let zp = gh * y; - let z_err = gl.mul_add(y, gh.mul_add(y, -zp)); - let mut zh = zp + z_err; - let mut zl = z_err - (zh - zp); - if zh >= 128.0 && zl < 0.0 { - let lower = f32::from_bits(zh.to_bits() - 1); - zl += zh - lower; - zh = lower; - } - let big = f32::from_bits(exp2_model(zh.to_bits())); - if big.is_infinite() || big == 0.0 { - return big.to_bits(); - } - let r = big.mul_add(zl * f32::from_bits(libm::log::LN_2_BITS), big); - if r.is_subnormal() { - 0 - } else { - r.to_bits() - } -} - -/// Positive normal bases and exponents for `powr`: `y log2(x)` across the exponential's range, -/// small integral exponents, and bases near 1 to large powers. -fn powr_pairs(seed: u64) -> Vec> { - let mut rng = Rng(seed); - let bases = log_operands(seed ^ 0x0B45_0B45); - let mut pairs = Vec::new(); - for _ in 0..6000 { - let x = bases[(rng.next() as usize) % bases.len()]; - let l = f64::from(f32v(x)).log2(); - if l == 0.0 { - continue; - } - let t = f64::from(f32v(uniform(&mut rng, -140.0, 130.0))); - pairs.push(vec![x, u64::from(((t / l) as f32).to_bits())]); - } - for _ in 0..2000 { - let x = bases[(rng.next() as usize) % bases.len()]; - let y = (rng.next() % 41) as f32 - 20.0; - pairs.push(vec![x, u64::from(y.to_bits())]); - } - for k in 1..400i64 { - for x in [ - 1.0f32 + k as f32 * f32::EPSILON, - 1.0 - k as f32 * f32::EPSILON / 2.0, - ] { - let l = f64::from(x).log2(); - for t in [-100.0, -10.0, 1.0, 50.0, 120.0, 127.99] { - pairs.push(vec![ - u64::from(x.to_bits()), - u64::from(((t / l) as f32).to_bits()), - ]); - } - } - } - pairs -} - -/// The `powr` routine answers its model (Metal's form, [`powr_model`]) bit for bit, with and -/// without `OpFmaKHR`, and the model is within Apple's 16 ulp of `x^y` wherever the result is -/// finite and normal: part `part` of `of` of the runs of 2,048 pairs. -fn powr_is_metals_form(part: usize, of: usize) { - let pairs = powr_pairs(0x0907_0907); - let mut worst = 0f64; - for c in &pairs { - let (x, y) = (f32v(c[0]), f32v(c[1])); - let r = f64::from(f32::from_bits(powr_model(x, y))); - if let Some(v) = in_range(f64::from(x).powf(f64::from(y))) { - let ulp = 2f64.powi((v.abs().log2().floor() as i32).max(-126) - 23); - worst = worst.max((r - v).abs() / ulp); - } - } - assert!(worst <= 16.0, "the model is {worst:.3} ulp off"); - eprintln!("powr: the model within {worst:.3} ulp"); - let f = f32s(); - let runs: Vec<(bool, Vec>)> = [false, true] - .into_iter() - .flat_map(|fma| pairs.chunks(2048).map(move |r| (fma, r.to_vec()))) - .collect(); - for (fma, run) in part_of(runs, part, of) { - check_module( - &format!("Powr fma={fma}"), - routine_module(Fun::Powr, false, fma), - &[f, f], - f, - &run.iter() - .map(|c| vec![vec![c[0]], vec![c[1]]]) - .collect::>(), - &|c| Some(vec![u64::from(powr_model(f32v(c[0][0]), f32v(c[1][0])))]), - &|g, w| g == w, - ); - } -} - -mod powr_routine_is_metals_form { - parts!(super::powr_is_metals_form, 4; - part_1_of_4 = 0, part_2_of_4 = 1, part_3_of_4 = 2, part_4_of_4 = 3); -} - -/// Metal's precise `powr` words on the M3 Max (case 7b283404's `powr` lanes, the M4's the same) -/// where Metal's word is not the correctly rounded `x^y`, each one unit of the last place off it: -/// the model and the routine answer them. -const POWR_WORDS: [(u32, u32, u32); 24] = [ - (0x3966_6C74, 0xC09E_DDCB, 0x5DA0_C338), - (0x3D67_2CF1, 0xC044_0FB6, 0x45D0_9B37), - (0x3E00_0000, 0xC07B_F941, 0x4560_9B9F), - (0x3E00_C07E, 0x3F5D_6038, 0x3E2A_6ECB), - (0x3E10_3271, 0xC1EA_DB2D, 0x6902_34C8), - (0x3E6B_C386, 0xC076_78BC, 0x438E_FD21), - (0x3E7D_8B6D, 0x414E_7502, 0x3281_330A), - (0x3E8E_F404, 0x401F_D291, 0x3D29_51B6), - (0x3E9A_CA4E, 0xBF2D_D5DE, 0x4010_32E3), - (0x3F10_D34F, 0xC0C0_0000, 0x41F4_0A3B), - (0x3F5C_4D74, 0x3FC9_A051, 0x3F4A_1239), - (0x3F80_0004, 0xC2AD_D0D0, 0x3F7F_FD48), - (0x3F80_000D, 0x42A4_38BE, 0x3F80_042B), - (0x3F80_0400, 0x4604_6C53, 0x4034_134F), - (0x3F81_1AFD, 0x3FC0_0000, 0x3F81_A965), - (0x3FAA_7AE9, 0x4080_0000, 0x4049_6381), - (0x406C_AFCD, 0xC110_0000, 0x3701_A690), - (0x40C9_0FDA, 0x40F9_3B26, 0x49C9_01AA), - (0x4120_0000, 0xC214_0000, 0x0208_1CEB), - (0x41A3_5CE2, 0x4071_9F39, 0x47AC_73BB), - (0x4242_C75D, 0x3C98_4C8C, 0x3F89_96AB), - (0x4252_1A85, 0xC175_EB28, 0x138F_2C5B), - (0x427C_BBA6, 0xBD85_02D6, 0x3F43_9146), - (0x4DAE_4DB4, 0x3FFE_BE9D, 0x5BC3_9F39), -]; - -/// Metal's precise `powr(x, 1)` is `x` itself (every one of case 7b283404's nine lanes with `y = -/// 1`, the M3's and the M4's): these three are where the form alone is a unit above. -const POWR_AT_ONE: [(u32, u32, u32); 3] = [ - (0x3FC9_C1AA, 0x3F80_0000, 0x3FC9_C1AA), - (0x3FDF_B484, 0x3F80_0000, 0x3FDF_B484), - (0x3FFD_BEE5, 0x3F80_0000, 0x3FFD_BEE5), -]; - -/// The `powr` routine and its model answer Metal's measured words ([`POWR_WORDS`], -/// [`POWR_AT_ONE`]). -#[test] -fn powr_answers_metals_measured_words() { - let words: Vec<(u32, u32, u32)> = POWR_WORDS.iter().chain(&POWR_AT_ONE).copied().collect(); - for &(x, y, w) in &words { - let got = powr_model(f32::from_bits(x), f32::from_bits(y)); - assert_eq!(got, w, "the model at ({x:#010x}, {y:#010x}): {got:#010x}"); - } - let f = f32s(); - for fma in [false, true] { - check_module( - &format!("Powr fma={fma} at Metal's measured words"), - routine_module(Fun::Powr, false, fma), - &[f, f], - f, - &words - .iter() - .map(|(x, y, _)| vec![vec![u64::from(*x)], vec![u64::from(*y)]]) - .collect::>(), - &|c| { - words - .iter() - .find(|(x, y, _)| [u64::from(*x), u64::from(*y)] == [c[0][0], c[1][0]]) - .map(|(_, _, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - } -} - -/// The centres `c` of `powr`'s reduction, one per row of [`libm::log::POWR_TABLE`]: the left end -/// of the row's sixteenth (below 1) or eighth (from 1) of a binade, or 1 next to 1. -const POWR_CENTRES: [f64; 9] = [0.6875, 0.75, 0.8125, 0.875, 1.0, 1.0, 1.125, 1.25, 1.375]; - -/// [`libm::log::POWR_TABLE`] is `1 / c` and `log2(c)` of each centre of [`POWR_CENTRES`] split into -/// a `float` pair, and each centre is the left end of its row's range of significands (or 1 next to -/// 1). -#[test] -fn powr_table_is_the_centres_split() { - use libm::log::POWR_TABLE; - for (k, (c, row)) in POWR_CENTRES.iter().zip(POWR_TABLE).enumerate() { - let (ih, il) = libm::split(1.0 / c); - let (lh, ll) = libm::split(c.log2()); - let want = [ih, il, lh, ll].map(f32::to_bits); - assert_eq!(row, want, "row {k}: centre {c}"); - // Row `k` holds the significands whose bits 20 to 23 (with the exponent's last bit) are - // `k + 3`. - let left = f32::from_bits(0x3F00_0000 | ((k as u32 + 3) << 20)); - assert!( - *c == f64::from(left) || *c == 1.0, - "row {k}: centre {c}, left end {left}" - ); - } -} - -/// Every table of the math library is declared a whole number of 16-byte rows -/// (`libm::declare_words`), the quarter-turn table's 165 words followed by three zeros, so each -/// table starts on a 16-byte boundary of the tables declared before it. Behind the unpadded 165, -/// NVIDIA's driver read every word of the `powr` table one index low (case 7b283404 on the RTX -/// 5080). -#[test] -fn math_tables_are_whole_16_byte_rows() { - let f = f32s(); - let needs = libm::Needs { - exp2: true, - log2: true, - rcp: true, - rsqrt: true, - quarter: true, - sinc: true, - powr: true, - ..libm::Needs::default() - }; - let module = kernel_defs( - &[f], - f, - &|b| { - libm::define_helpers(b, needs, false, true)?; - Ok(Vec::new()) - }, - &|_, x, _| Ok(x[0]), - false, - false, - ) - .expect("build"); - let words = serialize(module).expect("words").words; - const OP_TYPE_ARRAY: u32 = 28; - const OP_CONSTANT: u32 = 43; - let mut constants = BTreeMap::new(); - let mut lengths = Vec::new(); - let mut i = 5; - while i < words.len() { - let (n, op) = ((words[i] >> 16) as usize, words[i] & 0xFFFF); - match op { - OP_CONSTANT if n == 4 => { - constants.insert(words[i + 2], words[i + 3]); - } - OP_TYPE_ARRAY => lengths.push(constants[&words[i + 3]]), - _ => {} - } - i += n.max(1); - } - lengths.sort_unstable(); - assert_eq!(lengths, [36, 128, 160, 168, 192, 256, 320]); -} - -/// `P(v)` of the coefficients `c` (bits, lowest first) by Horner's rule from the highest in fused -/// steps, as the routines evaluate Metal's polynomials. -fn horner_model(c: &[u32], v: f32) -> f32 { - let mut acc = f32::from_bits(c[c.len() - 1]); - for k in c[..c.len() - 1].iter().rev() { - acc = acc.mul_add(v, f32::from_bits(*k)); - } - acc -} - -/// Metal's precise `asinh`, `acosh`, or `atanh` of `xb` as the model computes it, of -/// [`log2_model`]'s fitted word, [`rcp_model`], and Metal's fast inverse root's model -/// [`rsqrt_model`] (libm::hyper's list); `None` where [`log2_model`] is. -fn arc_model(fun: Fun, xb: u32) -> Option { - use libm::hyper::*; - let x = f32::from_bits(xb); - if x.is_nan() { - return Some(xb); - } - let ln2 = f32::from_bits(libm::log::LN_2_BITS); - let l2 = |v: f32| log2_model(v.to_bits()).map(f32::from_bits); - let a = x.abs(); - let ab = a.to_bits(); - let r = match fun { - Fun::Asinh => { - let r = if ab < ASINH_TINY { - a - } else if ab < ASINH_NEAR_END { - horner_model(&ASINH_NEAR, a * a) * a - } else if ab < ASINH_ROOT { - horner_model(&ASINH_MIDDLE, a) - } else if a.is_infinite() { - a - } else if a >= ASINH_LARGE { - l2(a)? * ln2 + ln2 - } else { - let z = a.mul_add(a, 1.0); - l2(a + z * rsqrt_model(z))? * ln2 - }; - r.copysign(x) - } - Fun::Acosh => { - if x < 1.0 { - return Some(0x7FC0_0000); - } - if x.is_infinite() { - x - } else if xb >= ACOSH_LARGE { - l2(x)? * ln2 + ln2 - } else { - let z = (x - 1.0) * (x + 1.0); - let q = if z == 0.0 { 0.0 } else { z * rsqrt_model(z) }; - let w = q + x; - let err = q - (w - x); - let off = w.to_bits().wrapping_sub(ACOSH_LOG1P_START); - let l = if off < ACOSH_LOG1P_END - ACOSH_LOG1P_START { - let t = w - 1.0; - t * horner_model(&ACOSH_LOG1P, t) - } else { - l2(w)? * ln2 - }; - l + err * rcp_model(w) - } - } - _ => { - if a > 1.0 { - return Some(0x7FC0_0000); - } - let r = if ab <= ATANH_TINY { - a - } else if a == 1.0 { - f32::INFINITY - } else if a <= ATANH_FORM { - horner_model(&ATANH_NEAR, a) - } else { - let q = (1.0 + a) * rcp_model(1.0 - a); - l2(q)? * ln2 * 0.5 - }; - r.copysign(x) - } - }; - Some(r.to_bits()) -} - -/// The ulp error of `w` against the exact `e` (in units of the `float` nearest `e`'s magnitude). -fn ulps(w: u32, e: f64) -> f64 { - let ulp = f64::from(f32::from_bits((e.abs() as f32).to_bits() + 1)) - f64::from(e.abs() as f32); - (f64::from(f32::from_bits(w)) - e).abs() / ulp -} - -/// The inverse hyperbolic routines answer [`arc_model`] bit for bit over the exponentials' -/// operands, each region's edges, uniform operands in each region, and every 262,147th positive -/// `float` (both signs for the odd functions), and lie within Apple's bounds of the exact value -/// there (4, 4, and 5 ulp): part `part` of `of` of the runs of 2,048 operands. -fn inverse_hyperbolics_are_metals(part: usize, of: usize) { - use libm::hyper::*; - let mut rng = Rng(0x4790_4790); - let mut xs = exp_operands(0x51A4_51A4); - xs.extend(magnitudes(&mut rng, -30.0, 127.9, 2000)); - xs.extend((0..0x7F80_0000u32).step_by(262_147).map(u64::from)); - for edge in [ - ASINH_TINY, - ASINH_NEAR_END, - ASINH_ROOT, - ASINH_LARGE.to_bits(), - ACOSH_LARGE, - ATANH_TINY, - ATANH_FORM.to_bits(), - 0x3F80_0000, - 0x3FC5_83AB, - ] { - xs.extend(around(f32::from_bits(edge), 32)); - } - for (lo, hi) in [ - (1.0, 1.6), - (0.0, 0.35), - (0.35, 1.5), - (1.5, 500.0), - (0.25, 1.0), - ] { - xs.extend((0..1500).map(|_| uniform(&mut rng, lo, hi))); - } - xs.retain(|b| !f32v(*b).is_nan()); - let signed: Vec = xs - .iter() - .flat_map(|b| [*b & 0x7FFF_FFFF, *b | 0x8000_0000]) - .collect(); - let mut runs = Vec::new(); - for (fun, set, exact, bound) in [ - (Fun::Asinh, &signed, f64::asinh as fn(f64) -> f64, 4.0), - (Fun::Acosh, &xs, f64::acosh, 4.0), - (Fun::Atanh, &signed, f64::atanh, 5.0), - ] { - let cases: Vec<(u32, u32)> = set - .iter() - .filter_map(|b| arc_model(fun, *b as u32).map(|w| (*b as u32, w))) - .collect(); - for run in cases.chunks(2048) { - runs.push((fun, exact, bound, run.to_vec())); - } - } - let f = f32s(); - for (fun, exact, bound, run) in part_of(runs, part, of) { - check_module( - &format!("{fun:?}"), - routine_module(fun, false, false), - &[f], - f, - &run.iter() - .map(|(x, _)| vec![vec![u64::from(*x)]]) - .collect::>(), - &|c| { - run.iter() - .find(|(x, _)| u64::from(*x) == c[0][0]) - .map(|(_, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - let worst = run - .iter() - .filter_map(|(x, w)| { - let e = exact(f64::from(f32::from_bits(*x))); - (e.is_finite() && e.abs() >= f64::from(f32::MIN_POSITIVE)).then(|| ulps(*w, e)) - }) - .fold(0f64, f64::max); - assert!(worst <= bound, "{fun:?}: {worst:.3} ulp"); - } -} - -mod inverse_hyperbolic_routines_are_metals { - parts!(super::inverse_hyperbolics_are_metals, 6; - part_1_of_6 = 0, part_2_of_6 = 1, part_3_of_6 = 2, part_4_of_6 = 3, - part_5_of_6 = 4, part_6_of_6 = 5); -} - -/// [`arc_model`] is Metal's word at operands measured on the M3 in every region, most where Metal's -/// word is not the correctly rounded one (the last 16 where the forms with the correctly rounded -/// inverse root are not Metal's word either), and the routines answer them bit for bit. -#[test] -fn inverse_hyperbolics_answer_metals_measured_words() { - let measured: [(Fun, u32, u32); 135] = [ - (Fun::Asinh, 0x3FC0_0000, 0x3F98_EE00), - (Fun::Asinh, 0x3FC0_0004, 0x3F98_EE02), - (Fun::Asinh, 0x3FD8_0001, 0x3FA5_B10A), - (Fun::Asinh, 0x3FF0_0002, 0x3FB1_7218), - (Fun::Asinh, 0x4008_0000, 0x3FBF_C455), - (Fun::Asinh, 0x4020_0000, 0x3FD2_D877), - (Fun::Asinh, 0x4038_0001, 0x3FE3_9AB6), - (Fun::Asinh, 0x4050_0000, 0x3FF2_849D), - (Fun::Asinh, 0x4068_0002, 0x3FFF_EFCB), - (Fun::Asinh, 0x4084_D400, 0x4008_5CE9), - (Fun::Asinh, 0x4284_D300, 0x409C_735E), - (Fun::Asinh, 0x43F9_FFFF, 0x40DD_0C56), - (Fun::Asinh, 0x43FA_0000, 0x40DD_0C55), - (Fun::Asinh, 0x4484_D200, 0x40F5_2BB5), - (Fun::Asinh, 0x4C84_D900, 0x4196_0466), - (Fun::Asinh, 0x5484_D200, 0x41EE_BD05), - (Fun::Asinh, 0x5C84_D200, 0x4223_BB08), - (Fun::Asinh, 0x6484_D200, 0x4250_178E), - (Fun::Asinh, 0x6C84_D200, 0x427C_7414), - (Fun::Asinh, 0x7484_D300, 0x4294_6850), - (Fun::Asinh, 0x7C84_D300, 0x42AA_9693), - (Fun::Asinh, 0x7E84_D300, 0x42B0_2224), - (Fun::Asinh, 0x7F7F_FF00, 0x42B2_D4FA), - (Fun::Acosh, 0x3FC5_83AB, 0x3F80_0000), - (Fun::Acosh, 0x3FC5_83AD, 0x3F80_0001), - (Fun::Acosh, 0x3FFC_D337, 0x3FA6_B8E2), - (Fun::Acosh, 0x4034_22C3, 0x3FD8_EF85), - (Fun::Acosh, 0x406B_724A, 0x3FFD_05DD), - (Fun::Acosh, 0x40A2_C1D7, 0x4013_D4CD), - (Fun::Acosh, 0x40DA_1160, 0x4026_D5A6), - (Fun::Acosh, 0x4111_60EA, 0x4039_661C), - (Fun::Acosh, 0x4148_B076, 0x404E_2055), - (Fun::Acosh, 0x4184_D300, 0x4060_1DE2), - (Fun::Acosh, 0x4384_D200, 0x40C8_CF28), - (Fun::Acosh, 0x44DA_C8D8, 0x4102_9220), - (Fun::Acosh, 0x44DA_C8E1, 0x4102_9222), - (Fun::Acosh, 0x4584_D300, 0x4110_C43C), - (Fun::Acosh, 0x4D84_D500, 0x41A1_1B4A), - (Fun::Acosh, 0x5584_D200, 0x41F9_D426), - (Fun::Acosh, 0x5D84_D200, 0x4229_4699), - (Fun::Acosh, 0x6584_D300, 0x4255_A326), - (Fun::Acosh, 0x6D84_D300, 0x4280_FFD6), - (Fun::Acosh, 0x7584_D200, 0x4297_2E15), - (Fun::Acosh, 0x7984_D300, 0x42A2_453A), - (Fun::Acosh, 0x7D84_D200, 0x42AD_5C58), - (Fun::Acosh, 0x7F7F_FF00, 0x42B2_D4FA), - (Fun::Asinh, 0x39E8_9800, 0x39E8_9800), - (Fun::Asinh, 0x3E80_0000, 0x3E7D_67D8), - (Fun::Asinh, 0x3EA8_0011, 0x3EA5_1F79), - (Fun::Asinh, 0x3ECF_FFFF, 0x3ECA_AA7C), - (Fun::Asinh, 0x3EF7_FFFF, 0x3EEF_33EA), - (Fun::Asinh, 0x3F1F_FFFF, 0x3F17_13A6), - (Fun::Asinh, 0x3F47_FFFF, 0x3F37_CC39), - (Fun::Asinh, 0x3F70_0000, 0x3F56_23AC), - (Fun::Asinh, 0x3F98_0000, 0x3F81_0462), - (Fun::Acosh, 0x3F80_0008, 0x3AB5_04F3), - (Fun::Acosh, 0x3F89_9999, 0x3EC5_13E7), - (Fun::Acosh, 0x3F93_3333, 0x3F0A_855A), - (Fun::Acosh, 0x3F9C_CCCD, 0x3F28_A9B7), - (Fun::Acosh, 0x3FA6_6666, 0x3F41_A594), - (Fun::Acosh, 0x3FB0_0000, 0x3F57_4D0A), - (Fun::Acosh, 0x3FB9_9999, 0x3F6A_9205), - (Fun::Acosh, 0x3FC3_3334, 0x3F7C_055E), - (Fun::Acosh, 0x4180_0100, 0x405D_BF17), - (Fun::Acosh, 0x493F_FA00, 0x4164_4AE6), - (Fun::Acosh, 0x50FF_F300, 0x41C7_9FF2), - (Fun::Acosh, 0x58BF_EB00, 0x420F_05AC), - (Fun::Acosh, 0x607F_E400, 0x4239_C300), - (Fun::Acosh, 0x683F_DD00, 0x4264_F8A5), - (Fun::Acosh, 0x6FFF_DD00, 0x4287_DB13), - (Fun::Acosh, 0x77BF_CF00, 0x429D_75CF), - (Fun::Atanh, 0x3E80_0002, 0x3E82_C579), - (Fun::Atanh, 0x3E85_57FC, 0x3E88_7CCA), - (Fun::Atanh, 0x3E8A_AFD1, 0x3E8E_3C7D), - (Fun::Atanh, 0x3E90_0679, 0x3E94_03EE), - (Fun::Atanh, 0x3E95_5DF7, 0x3E99_D5C2), - (Fun::Atanh, 0x3E9A_B87F, 0x3E9F_B4DB), - (Fun::Atanh, 0x3EA0_0C10, 0x3EA5_96B9), - (Fun::Atanh, 0x3EA5_589A, 0x3EAB_7BA5), - (Fun::Atanh, 0x3EAA_B0FD, 0x3EB1_7933), - (Fun::Atanh, 0x3EB0_0941, 0x3EB7_82AE), - (Fun::Atanh, 0x3EB5_6275, 0x3EBD_99DC), - (Fun::Atanh, 0x3EBA_B6D6, 0x3EC3_B8BC), - (Fun::Atanh, 0x3EC0_0122, 0x3EC9_D9A8), - (Fun::Atanh, 0x3EC5_454E, 0x3ED0_0199), - (Fun::Atanh, 0x3ECA_8C3D, 0x3ED6_3B8E), - (Fun::Atanh, 0x3ECF_D8E5, 0x3EDC_8BD9), - (Fun::Atanh, 0x3ED5_21ED, 0x3EE2_E81A), - (Fun::Atanh, 0x3EDA_66C4, 0x3EE9_5040), - (Fun::Atanh, 0x3EDF_A03E, 0x3EEF_BC0F), - (Fun::Atanh, 0x3EE4_DFBA, 0x3EF6_4194), - (Fun::Atanh, 0x3EEA_1651, 0x3EFC_CF15), - (Fun::Atanh, 0x3EF0_8232, 0x3F02_7E61), - (Fun::Atanh, 0x3EF7_FAF1, 0x3F07_5492), - (Fun::Atanh, 0x3EFF_700B, 0x3F0C_3F6E), - (Fun::Atanh, 0x3F08_C4B1, 0x3F18_986B), - (Fun::Atanh, 0x3F12_3AAF, 0x3F26_3971), - (Fun::Atanh, 0x3F1B_03E1, 0x3F33_AB1D), - (Fun::Atanh, 0x3F21_96C7, 0x3F3E_50C3), - (Fun::Atanh, 0x3F28_2932, 0x3F49_8CB3), - (Fun::Atanh, 0x3F2E_C051, 0x3F55_8184), - (Fun::Atanh, 0x3F35_23A9, 0x3F61_DF28), - (Fun::Atanh, 0x3F3B_61C8, 0x3F6E_D506), - (Fun::Atanh, 0x3F41_9F3D, 0x3F7C_D330), - (Fun::Atanh, 0x3F4C_5103, 0x3F8B_F41D), - (Fun::Atanh, 0x3F58_A4E3, 0x3F9F_15A6), - (Fun::Atanh, 0x3F63_5748, 0x3FB4_D0F0), - (Fun::Atanh, 0x3F69_A218, 0x3FC5_824C), - (Fun::Atanh, 0x3F6F_DF48, 0x3FDB_3FDD), - (Fun::Atanh, 0x3F76_38FC, 0x3FFC_1812), - (Fun::Atanh, 0x3F7F_FFFE, 0x4105_1591), - (Fun::Atanh, 0x39B8_9C00, 0x39B8_9C00), - (Fun::Atanh, 0x3A20_0000, 0x3A20_0000), - (Fun::Atanh, 0x3AC0_0000, 0x3AC0_0008), - (Fun::Atanh, 0x3B60_7000, 0x3B60_7039), - (Fun::Atanh, 0x3C00_3500, 0x3C00_35AB), - (Fun::Atanh, 0x3CA0_0900, 0x3CA0_0E36), - (Fun::Atanh, 0x3D40_0100, 0x3D40_250C), - (Fun::Atanh, 0x3DE0_0000, 0x3DE0_E651), - (Fun::Asinh, 0x3FC0_002A, 0x3F98_EE17), - (Fun::Asinh, 0x3FD2_D856, 0x3FA3_0A46), - (Fun::Asinh, 0x3FE4_4F82, 0x3FAB_D693), - (Fun::Asinh, 0x400D_8489, 0x3FC4_63A8), - (Fun::Asinh, 0x4029_D277, 0x3FD9_F44D), - (Fun::Asinh, 0x4044_E4A1, 0x3FEB_D221), - (Fun::Asinh, 0x4062_DB4B, 0x3FFD_2C2E), - (Fun::Asinh, 0x407F_FFC9, 0x4006_0FB8), - (Fun::Acosh, 0x3F80_0002, 0x3A35_04F3), - (Fun::Acosh, 0x3F9D_1641, 0x3F29_78C7), - (Fun::Acosh, 0x3FC4_1B34, 0x3F7D_96BF), - (Fun::Acosh, 0x3FFC_E8BB, 0x3FA6_C583), - (Fun::Acosh, 0x4044_F0B8, 0x3FE5_134E), - (Fun::Acosh, 0x409A_42F7, 0x4010_53F9), - (Fun::Acosh, 0x40FB_21B7, 0x402F_F49C), - (Fun::Acosh, 0x417F_FF39, 0x405D_BE66), - ]; - for (fun, x, w) in measured { - assert_eq!(arc_model(fun, x), Some(w), "{fun:?}'s model at {x:#010x}"); - } - let f = f32s(); - for fun in [Fun::Asinh, Fun::Acosh, Fun::Atanh] { - let mine: Vec<(u32, u32)> = measured - .iter() - .filter(|(g, _, _)| *g == fun) - .map(|(_, x, w)| (*x, *w)) - .collect(); - check_module( - &format!("{fun:?} at Metal's measured words"), - routine_module(fun, false, false), - &[f], - f, - &mine - .iter() - .map(|(x, _)| vec![vec![u64::from(*x)]]) - .collect::>(), - &|c| { - mine.iter() - .find(|(x, _)| u64::from(*x) == c[0][0]) - .map(|(_, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - } -} - -/// Metal's fast `asinh` or `acosh` of `xb` as the model computes it (`libm::hyper::fast_arc`): -/// `RN(log2(v) RN(ln 2))` of `v = fma(s, rsqrt(s), x)` and `s = RN(RN(x x) ± 1)` with Metal's -/// inverse root's model [`rsqrt_model`] and [`log2_model`], `v = RN(x + s)` where `s` is 0 or -/// `+inf`, and Metal's NaN where `s` is below zero; an `f32` denormal operand is a zero. `None` -/// where [`log2_model`] is, and for a NaN `v`. -fn fast_arc_model(fun: Fun, xb: u32) -> Option { - let x = f32::from_bits(xb); - let x = if x.is_subnormal() { - 0f32.copysign(x) - } else { - x - }; - let s = if fun == Fun::FastAsinh { - x * x + 1.0 - } else { - x * x - 1.0 - }; - if s < 0.0 { - return Some(0x7FC0_0000); - } - let v = if s == 0.0 || s.is_infinite() { - x + s - } else { - s.mul_add(rsqrt_model(s), x) - }; - let l2 = if v.is_nan() { - return None; - } else if v.to_bits() & 0x7F80_0000 == 0 { - f32::NEG_INFINITY - } else if v < 0.0 { - return Some(0x7FC0_0000); - } else if v.is_infinite() { - v - } else { - f32::from_bits(log2_model(v.to_bits())?) - }; - Some((l2 * f32::from_bits(libm::log::LN_2_BITS)).to_bits()) -} - -/// The fast `asinh` and `acosh` routines answer [`fast_arc_model`] bit for bit, with and without -/// `OpFmaKHR`, over the exponentials' operands, magnitudes of either sign from `2^-30` to `2^127` -/// (where the fused sum keeps the root's error for a negative `x`), and the neighbours of 1 and -1: -/// part `part` of `of` of the runs of 2,048 operands. -fn fast_arcs_are_metals_form(part: usize, of: usize) { - let mut rng = Rng(0x4820_4820); - let mut xs = exp_operands(0x4821_4821); - xs.extend(magnitudes(&mut rng, -30.0, 127.9, 1500)); - xs.extend(around(1.0, 32)); - xs.extend(around(-1.0, 32)); - xs.retain(|b| f32v(*b).is_finite()); - let mut runs = Vec::new(); - for fun in [Fun::FastAsinh, Fun::FastAcosh] { - let cases: Vec<(u32, u32)> = xs - .iter() - .filter_map(|b| fast_arc_model(fun, *b as u32).map(|w| (*b as u32, w))) - .collect(); - for fma in [false, true] { - for run in cases.chunks(2048) { - runs.push((fun, fma, run.to_vec())); - } - } - } - let f = f32s(); - for (fun, fma, run) in part_of(runs, part, of) { - check_module( - &format!("{fun:?} fma={fma}"), - routine_module(fun, false, fma), - &[f], - f, - &run.iter() - .map(|(x, _)| vec![vec![u64::from(*x)]]) - .collect::>(), - &|c| { - run.iter() - .find(|(x, _)| u64::from(*x) == c[0][0]) - .map(|(_, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - } -} - -mod fast_inverse_hyperbolic_routines_are_metals_form { - parts!(super::fast_arcs_are_metals_form, 8; - part_1_of_8 = 0, part_2_of_8 = 1, part_3_of_8 = 2, part_4_of_8 = 3, - part_5_of_8 = 4, part_6_of_8 = 5, part_7_of_8 = 6, part_8_of_8 = 7); -} - -/// Metal's fast `asinh` and `acosh` words on the M3 Max (case f6524207, the M4's the same), most -/// where they are not the correctly rounded function: below `-1e7` the fused sum leaves the root's -/// error (`asinh` and `acosh` alike there), and from `-1e4` on a negative `acosh` is a number. The -/// model and the routines answer them. -#[test] -fn fast_arcs_answer_metals_measured_words() { - let measured: [(Fun, u32, u32); 32] = [ - (Fun::FastAsinh, 0xFF7F_FFFF, 0x7F80_0000), - (Fun::FastAsinh, 0xD96D_F87F, 0x7FC0_0000), - (Fun::FastAsinh, 0xD678_EF4C, 0x4166_3E90), - (Fun::FastAsinh, 0xD438_A2DF, 0x40D8_9E8D), - (Fun::FastAsinh, 0xD200_1B7B, 0x4101_F0DF), - (Fun::FastAsinh, 0xCE52_18BC, 0x4050_D6AA), - (Fun::FastAsinh, 0xCC35_418C, 0x3F81_6E95), - (Fun::FastAsinh, 0xCB28_390F, 0xBF1B_C5E5), - (Fun::FastAsinh, 0xCAC9_0FDC, 0xC002_7053), - (Fun::FastAsinh, 0xC589_ADD5, 0xC130_0AB4), - (Fun::FastAsinh, 0xC5A8_A26C, 0xC112_840A), - (Fun::FastAsinh, 0xC4C1_8A29, 0xC100_AEB2), - (Fun::FastAsinh, 0xC291_D119, 0xC09F_7158), - (Fun::FastAsinh, 0xC11B_5C07, 0xC03E_033D), - (Fun::FastAsinh, 0xBF29_5707, 0xBF1E_EE94), - (Fun::FastAsinh, 0xBDD7_1180, 0xBDD6_ACCF), - (Fun::FastAsinh, 0x3E02_D2E7, 0x3E02_7873), - (Fun::FastAsinh, 0x3F66_8CEF, 0x3F4F_2E8A), - (Fun::FastAsinh, 0x3FFE_A25D, 0x3FB8_2C59), - (Fun::FastAsinh, 0x41B7_F547, 0x4075_0C78), - (Fun::FastAsinh, 0x42B0_0000, 0x40A5_74DE), - (Fun::FastAsinh, 0x4AC9_0FDC, 0x4183_26D8), - (Fun::FastAsinh, 0x6892_3E06, 0x7F80_0000), - (Fun::FastAcosh, 0xFF7F_FFFF, 0x7F80_0000), - (Fun::FastAcosh, 0xD678_EF4C, 0x4166_3E90), - (Fun::FastAcosh, 0xCB28_390F, 0xBF1B_C5E5), - (Fun::FastAcosh, 0xC589_ADD5, 0xC130_0AB4), - (Fun::FastAcosh, 0xC0D7_A67F, 0x7FC0_0000), - (Fun::FastAcosh, 0x3F7F_FFFB, 0x7FC0_0000), - (Fun::FastAcosh, 0x4128_2940, 0x4042_C3F3), - (Fun::FastAcosh, 0x497F_FFFF, 0x4168_E5BE), - (Fun::FastAcosh, 0x3F80_0000, 0x0000_0000), - ]; - for (fun, x, w) in measured { - assert_eq!( - fast_arc_model(fun, x), - Some(w), - "{fun:?}'s model at {x:#010x}" - ); - } - let f = f32s(); - for fun in [Fun::FastAsinh, Fun::FastAcosh] { - let mine: Vec<(u32, u32)> = measured - .iter() - .filter(|(g, _, _)| *g == fun) - .map(|(_, x, w)| (*x, *w)) - .collect(); - for fma in [false, true] { - check_module( - &format!("{fun:?} fma={fma} at Metal's measured words"), - routine_module(fun, false, fma), - &[f], - f, - &mine - .iter() - .map(|(x, _)| vec![vec![u64::from(*x)]]) - .collect::>(), - &|c| { - mine.iter() - .find(|(x, _)| u64::from(*x) == c[0][0]) - .map(|(_, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - } - } -} - -/// Metal's `half` `asinh` of `half` bits `b`, rounded to `half`, as the model computes it -/// (`libm::hyper::half_asinh`): `x` below `2^-11` in magnitude and at an infinity, else `RN(log2(v) -/// RN(ln 2))` with `x`'s sign of `v = fma(z, rsqrt(z), |x|)` and `z = fma(x, x, 1)`, with -/// [`rsqrt_model`] and [`log2_model`]; `None` for a NaN and where [`log2_model`] is. -fn half_asinh_model(b: u16) -> Option { - let x = f16_to_f64(b) as f32; - if x.is_nan() { - return None; - } - let r = if x.abs() < 1.0 / 2048.0 || x.is_infinite() { - x - } else { - let z = x.mul_add(x, 1.0); - let v = z.mul_add(rsqrt_model(z), x.abs()); - let l = f32::from_bits(log2_model(v.to_bits())?) * f32::from_bits(libm::log::LN_2_BITS); - if x < 0.0 { - -l - } else { - l - } - }; - Some(u64::from(f64_to_f16(f64::from(r)))) -} - -/// A `half` `asinh` call answers [`half_asinh_model`] at every `half` it gives a value for (the -/// model is Metal's word at every `half` of our probe, the M3; the M4's are the same): part -/// `part` of `of` of the runs of 2,048 operands. -fn half_asinh_is_metals_form(part: usize, of: usize) { - let h = float(16); - let cases: Vec<(u64, u64)> = (0..=0xFFFFu16) - .filter_map(|b| half_asinh_model(b).map(|w| (u64::from(b), w))) - .collect(); - let runs: Vec<&[(u64, u64)]> = cases.chunks(2048).collect(); - for run in part_of(runs, part, of) { - check_module( - "half Asinh", - super::libm::half_module(FloatFn::Asinh, Fun::HalfAsinh), - &[h], - h, - &run.iter() - .map(|(b, _)| vec![vec![*b]]) - .collect::>(), - &|c| { - run.iter() - .find(|(b, _)| *b == c[0][0]) - .map(|(_, w)| vec![*w]) - }, - &|g, w| g == w, - ); - } -} - -mod half_asinh_routine_is_metals_form { - parts!(super::half_asinh_is_metals_form, 8; - part_1_of_8 = 0, part_2_of_8 = 1, part_3_of_8 = 2, part_4_of_8 = 3, - part_5_of_8 = 4, part_6_of_8 = 5, part_7_of_8 = 6, part_8_of_8 = 7); -} - -/// Metal's `half` `asinh` words where they are not the correctly rounded ones (all four of our -/// probe, the M3; the M4's are the same): the model and the routine answer them. -#[test] -fn half_asinh_answers_metals_words() { - let h = float(16); - let measured: [(u64, u64); 4] = [ - (0x29C5, 0x29C4), - (0x32BD, 0x32B0), - (0xA9C5, 0xA9C4), - (0xB2BD, 0xB2B0), - ]; - for (b, w) in measured { - assert_eq!(half_asinh_model(b as u16), Some(w), "the model at {b:#06x}"); - } - check_module( - "half Asinh at Metal's words", - super::libm::half_module(FloatFn::Asinh, Fun::HalfAsinh), - &[h], - h, - &measured - .iter() - .map(|(b, _)| vec![vec![*b]]) - .collect::>(), - &|c| { - measured - .iter() - .find(|(b, _)| *b == c[0][0]) - .map(|(_, w)| vec![*w]) - }, - &|g, w| g == w, - ); -} - -/// [`rcp_model`] answers Metal's reciprocal at words measured on the Apple M4 (a -/// library compiled with `mathMode` fast): where Metal's word is `RN(1 / y)`, one unit above it, -/// and one below, in `[1, 2)`, the same significands in the lowest and highest binades whose -/// reciprocal is normal, and negated. -#[test] -fn metal_reciprocal_model_answers_measured_words() { - let measured: [(u32, u32); 23] = [ - (0x3F80_0000, 0x3F80_0000), - (0x3F80_05D1, 0x3F7F_F45E), - (0x3F86_446F, 0x3F74_0CEA), - (0x3F8E_EDE9, 0x3F65_4299), - (0x3FBB_D1E9, 0x3F2E_7707), - (0x3FC0_0000, 0x3F2A_AAAB), - (0x3FC9_66D0, 0x3F22_B326), - (0x3FD0_E1BE, 0x3F1C_DF98), - (0x3FD6_6159, 0x3F18_D993), - (0x3FDB_C21E, 0x3F15_1BFA), - (0x3FDB_D94E, 0x3F15_0C40), - (0x3FE4_BF14, 0x3F0F_4017), - (0x3FE8_959C, 0x3F0C_E2F1), - (0x3FF4_6C2C, 0x3F06_101C), - (0x3FF8_E791, 0x3F03_A61C), - (0x3FFF_FFFF, 0x3F00_0001), - (0x00C9_66D0, 0x7E22_B326), - (0x0080_05D1, 0x7E7F_F45E), - (0x7E49_66D0, 0x00A2_B326), - (0x7E5B_C21E, 0x0095_1BFA), - (0xBFC9_66D0, 0xBF22_B326), - (0xBF80_05D1, 0xBF7F_F45E), - (0xBFDB_C21E, 0xBF15_1BFA), - ]; - for (y, w) in measured { - assert_eq!( - rcp_model(f32::from_bits(y)).to_bits(), - w, - "{y:#010x}: the model against Metal's word" - ); - } -} - -/// [`Fun::Recip`]'s routine answers [`rcp_model`] bit for bit, with and without `OpFmaKHR`, over -/// magnitudes from `2^-126` to `2^128` of both signs and around the ends of the binades it scales -/// between, and Metal's flushes: the infinity of a zero's or a denormal's sign, and the zero of the -/// sign past `2^126`, an infinity included; a NaN gives a NaN. -#[test] -fn metal_reciprocal_routine_answers_the_model() { - const ANY_NAN: u64 = 0x7FC0_0000; - let mut rng = Rng(0x7EC1_7EC1); - let mut xs = magnitudes(&mut rng, -126.0, 128.0, 3000); - for e in [-126, -125, -1, 0, 1, 125, 126, 127] { - let p = 2f32.powi(e); - xs.extend(around(p, 2)); - xs.extend(around(-p, 2)); - } - xs.extend(DENORMALS); - xs.extend([ - 0, - 0x8000_0000, - 0x7F80_0000, - 0xFF80_0000, - 0x7FC0_0000, - 0xFF80_0001, - ]); - let expect = |b: u64| -> u64 { - let b = b as u32; - let y = f32::from_bits(b); - let sign = b & 0x8000_0000; - u64::from(if y.is_nan() { - return ANY_NAN; - } else if b & 0x7F80_0000 == 0 { - sign | 0x7F80_0000 - } else if b & 0x7FFF_FFFF > 0x7E80_0000 { - sign - } else { - rcp_model(y).to_bits() - }) - }; - let f = f32s(); - for fma in [false, true] { - check_module( - &format!("Recip fma={fma}"), - routine_module(Fun::Recip, false, fma), - &[f], - f, - &xs.iter().map(|x| vec![vec![*x]]).collect::>(), - &|c| Some(vec![expect(c[0][0])]), - &|g, w| g == w || (w == ANY_NAN && f32v(g).is_nan()), - ); - } -} - -/// [`rsqrt_model`] is Metal's fast `rsqrt` at words measured on the M3 Max and the M4 (the same -/// words): in `[1, 4)`, in the binades below and above (every 256th `float`), all where Metal's -/// word is not the correctly rounded root, and its specials (`+inf` of a zero and a denormal, `+0` -/// of `+inf`); and [`Fun::FastRsqrt`]'s routine answers them bit for bit. -#[test] -fn metal_fast_rsqrt_answers_metals_measured_words() { - let measured: [(u32, u32); 43] = [ - (0x3F80_0927, 0x3F7F_F6DA), - (0x3F8C_3CE2, 0x3F74_933E), - (0x3F94_EDE1, 0x3F6D_54D0), - (0x3FA6_C81A, 0x3F60_4513), - (0x3FAF_0148, 0x3F5A_EFF2), - (0x3FB8_4D43, 0x3F55_5807), - (0x3FC3_D76E, 0x3F4E_F682), - (0x3FCB_095A, 0x3F4B_4346), - (0x3FD2_09C2, 0x3F47_D8A1), - (0x3FDE_75ED, 0x3F42_2FAB), - (0x3FEB_2FCC, 0x3F3C_DC01), - (0x3FF7_BBDE, 0x3F38_03BD), - (0x4001_45CE, 0x3F34_2047), - (0x4009_F8EC, 0x3F2E_5AD5), - (0x4014_732B, 0x3F28_16DC), - (0x4020_4D77, 0x3F21_C177), - (0x402D_AC35, 0x3F1B_679C), - (0x403C_70A5, 0x3F15_30F7), - (0x404B_8318, 0x3F0F_8F7A), - (0x4057_1727, 0x3F0B_A4A1), - (0x4060_8753, 0x3F08_AD35), - (0x406A_671A, 0x3F05_C453), - (0x4073_B7E4, 0x3F03_2F7E), - (0x407F_EE87, 0x3F00_045F), - (0x07EE_C200, 0x5B3B_7111), - (0x112E_0100, 0x569B_41BA), - (0x1A78_9300, 0x5201_E5D9), - (0x23BD_B700, 0x4D52_473A), - (0x2CF7_8500, 0x48B8_1821), - (0x3637_C200, 0x4417_147D), - (0x3F7F_E600, 0x3F80_0681), - (0x4080_1000, 0x3EFF_F002), - (0x497F_E600, 0x3A80_0681), - (0x527F_E600, 0x3600_0681), - (0x5B7F_D300, 0x3180_0B42), - (0x647F_D300, 0x2D00_0B42), - (0x6D7F_BB00, 0x2880_1144), - (0x767F_BB00, 0x2400_1144), - (0x7F7F_BB00, 0x1F80_1144), - (0x0000_0000, 0x7F80_0000), - (0x0000_0100, 0x7F80_0000), - (0x006C_E400, 0x7F80_0000), - (0x7F80_0000, 0x0000_0000), - ]; - for (y, w) in measured { - assert_eq!( - rsqrt_model(f32::from_bits(y)).to_bits(), - w, - "{y:#010x}: the model against Metal's word" - ); - } - let f = f32s(); - for fma in [false, true] { - check_module( - &format!("FastRsqrt fma={fma} at Metal's measured words"), - routine_module(Fun::FastRsqrt, false, fma), - &[f], - f, - &measured - .iter() - .map(|(y, _)| vec![vec![u64::from(*y)]]) - .collect::>(), - &|c| { - measured - .iter() - .find(|(y, _)| u64::from(*y) == c[0][0]) - .map(|(_, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - } -} - -/// [`Fun::FastRsqrt`]'s routine answers [`rsqrt_model`] bit for bit, with and without `OpFmaKHR`, -/// over positive magnitudes from `2^-126` to `2^128`, around the powers of 2 it reduces by, every -/// 65,537th `float` of `[1, 4)`, and its specials: `+inf` of a zero and a denormal, `+0` of `+inf`, -/// and a NaN of a NaN. -#[test] -fn metal_fast_rsqrt_routine_answers_the_model() { - const ANY_NAN: u64 = 0x7FC0_0000; - let mut rng = Rng(0x2591_2591); - let mut xs = magnitudes(&mut rng, -126.0, 128.0, 3000); - for e in [-126, -125, -2, -1, 0, 1, 2, 3, 125, 126, 127] { - xs.extend(around(2f32.powi(e), 2)); - } - xs.extend((0x3F80_0000u32..0x4080_0000).step_by(65_537).map(u64::from)); - xs.retain(|b| f32v(*b) > 0.0); - xs.extend(DENORMALS.iter().map(|b| b & 0x7FFF_FFFF)); - xs.extend([0, 0x7F7F_FFFF, 0x7F80_0000, 0x7FC0_0000]); - let f = f32s(); - for fma in [false, true] { - check_module( - &format!("FastRsqrt fma={fma}"), - routine_module(Fun::FastRsqrt, false, fma), - &[f], - f, - &xs.iter().map(|x| vec![vec![*x]]).collect::>(), - &|c| { - let y = f32v(c[0][0]); - Some(vec![if y.is_nan() { - ANY_NAN - } else { - u64::from(rsqrt_model(y).to_bits()) - }]) - }, - &|g, w| g == w || (w == ANY_NAN && f32v(g).is_nan()), - ); - } -} - -/// `1 + s q(s)` of Metal's coefficients `q` (`libm::hyper`), each step one fused multiply-add. -fn near_zero_model(q: &[u32], s: f32) -> f32 { - horner_model(q, s).mul_add(s, 1.0) -} - -/// Metal's precise `sinh`, `cosh`, or `tanh` of `x` with its reciprocals the -/// model's ([`rcp_model`]): the polynomials near zero, `(E -+ 1/E) / 2` of its precise -/// `exp` ([`exp_model`]) and `e^a / 2` ([`exp_composed`]) past `12 ln 2`, `tanh`'s `(t - 1) (1 / -/// (t + 1))` of `t = e^(2a)`, and its polynomial from 0.35 to 1.25. -fn hyper_model(fun: Fun, xb: u32) -> u32 { - use libm::hyper::*; - let x = f32::from_bits(xb); - if x.is_nan() { - return xb; - } - let a = x.abs(); - let ab = a.to_bits(); - let s = a * a; - let r = match fun { - Fun::Sinh | Fun::Cosh => { - let sinh = fun == Fun::Sinh; - if ab <= if sinh { SINH_TINY } else { COSH_TINY } { - if sinh { - a - } else { - 1.0 - } - } else if ab < POLY_END { - let p = near_zero_model(if sinh { &SINH_Q } else { &COSH_Q }, s); - if sinh { - a * p - } else { - p - } - } else { - let h = f32::from_bits(exp_composed(ab, std::f64::consts::LOG2_E, true)); - if ab > HALF_EXP { - h - } else { - let big = h + h; - let inv = rcp_model(big); - 0.5 * if sinh { big - inv } else { big + inv } - } - } - } - _ => { - if ab <= TANH_TINY { - a - } else if ab < TANH_POLY_END { - a * near_zero_model(&TANH_Q, s) - } else if ab <= TANH_QUOTIENT { - horner_model(&TANH_MIDDLE, a) - } else if ab >= HALF_EXP { - 1.0 - } else { - let t = f32::from_bits(exp_model((a + a).to_bits(), std::f64::consts::LOG2_E)); - (t - 1.0) * rcp_model(t + 1.0) - } - } - }; - if fun == Fun::Cosh { r } else { r.copysign(x) }.to_bits() -} - -/// The `sinh`, `cosh`, and `tanh` routines answer [`hyper_model`] bit for bit over the -/// exponentials' operands, every region's edges, and uniform operands in each region: part `part` -/// of `of` of the runs of 2,048 operands. -fn hyperbolics_are_metals(part: usize, of: usize) { - use libm::hyper::*; - let mut rng = Rng(0x4791_4791); - let mut xs = exp_operands(0x51A5_51A5); - for edge in [ - SINH_TINY, - COSH_TINY, - TANH_TINY, - POLY_END, - TANH_POLY_END, - TANH_QUOTIENT, - HALF_EXP, - 0x42B1_7218, - 0x42B2_D4FC, - ] { - xs.extend(around(f32::from_bits(edge), 3)); - xs.extend(around(-f32::from_bits(edge), 3)); - } - for (lo, hi) in [ - (-0.35, 0.35), - (-1.5, 1.5), - (0.35, 1.25), - (1.25, 8.4), - (-90.0, 90.0), - ] { - xs.extend((0..1500).map(|_| uniform(&mut rng, lo, hi))); - } - xs.extend(magnitudes(&mut rng, -12.0, -1.0, 1500)); - xs.retain(|b| !f32v(*b).is_nan()); - let mut runs = Vec::new(); - for fun in [Fun::Sinh, Fun::Cosh, Fun::Tanh] { - for run in xs.chunks(2048) { - runs.push((fun, run.to_vec())); - } - } - let f = f32s(); - for (fun, run) in part_of(runs, part, of) { - check_module( - &format!("{fun:?}"), - routine_module(fun, false, false), - &[f], - f, - &run.iter().map(|x| vec![vec![*x]]).collect::>(), - &|c| Some(vec![u64::from(hyper_model(fun, c[0][0] as u32))]), - &|g, w| g == w, - ); - } -} - -mod hyperbolic_routines_are_metals { - parts!(super::hyperbolics_are_metals, 6; - part_1_of_6 = 0, part_2_of_6 = 1, part_3_of_6 = 2, part_4_of_6 = 3, - part_5_of_6 = 4, part_6_of_6 = 5); -} - -/// The `sinh`, `cosh`, and `tanh` routines answer Metal's words, measured on the Apple M4, at each -/// region's edges and inside it, both signs: the operand itself to the tiny bound and the -/// polynomials' first word past it, the polynomials, the compositions of the precise `exp`, among -/// them words where the correctly rounded reciprocal is one unit off and Metal's is not, and -/// `e^a / 2` and `tanh`'s 1 from `12 ln 2`; and `tanh`'s polynomial from 0.35 to 1.25 at words -/// measured on the M3 where Metal's word is not the correctly rounded one. -#[test] -fn hyperbolic_routines_answer_metals_measured_words() { - let measured: [(Fun, u32, u32); 54] = [ - (Fun::Sinh, 0x3A85_2018, 0x3A85_2018), - (Fun::Sinh, 0x3A85_2019, 0x3A85_201A), - (Fun::Sinh, 0x3D00_0000, 0x3D00_0555), - (Fun::Sinh, 0x3F00_0000, 0x3F05_6680), - (Fun::Sinh, 0x3FBF_FFFF, 0x4008_461C), - (Fun::Sinh, 0x3FC0_0000, 0x4008_461E), - (Fun::Sinh, 0x4000_0000, 0x4068_1E7B), - (Fun::Sinh, 0x4080_0000, 0x41DA_51C1), - (Fun::Sinh, 0x4105_1592, 0x44FF_FFFF), - (Fun::Sinh, 0x4105_1593, 0x4500_0009), - (Fun::Sinh, 0x4180_0000, 0x4A87_975F), - (Fun::Sinh, 0x42B0_0000, 0x7E78_82B7), - (Fun::Sinh, 0xBF00_0000, 0xBF05_6680), - (Fun::Sinh, 0xC000_0000, 0xC068_1E7B), - (Fun::Sinh, 0x3FD6_533D, 0x4024_BE84), - (Fun::Sinh, 0x400C_E2F5, 0x408E_D33F), - (Fun::Sinh, 0x4085_0099, 0x41FF_4864), - (Fun::Cosh, 0x3A35_04F2, 0x3F80_0000), - (Fun::Cosh, 0x3A35_04F3, 0x3F80_0002), - (Fun::Cosh, 0x3E80_0000, 0x3F84_0558), - (Fun::Cosh, 0x3F80_0000, 0x3FC5_83AA), - (Fun::Cosh, 0x3FBF_FFFF, 0x4016_8DE0), - (Fun::Cosh, 0x3FC0_0000, 0x4016_8DE2), - (Fun::Cosh, 0x4040_0000, 0x4121_1525), - (Fun::Cosh, 0x4105_1592, 0x4500_0000), - (Fun::Cosh, 0x4105_1593, 0x4500_0009), - (Fun::Cosh, 0x4280_0000, 0x6D21_2CC2), - (Fun::Cosh, 0xC040_0000, 0x4121_1525), - (Fun::Cosh, 0x3FD6_533D, 0x4030_BD2C), - (Fun::Cosh, 0x400F_0487, 0x4097_343D), - (Fun::Cosh, 0x4085_0099, 0x41FF_687A), - (Fun::Tanh, 0x3A38_9BA2, 0x3A38_9BA2), - (Fun::Tanh, 0x3A38_9BA3, 0x3A38_9BA1), - (Fun::Tanh, 0x3E00_0000, 0x3DFE_ACC9), - (Fun::Tanh, 0x3EB3_3333, 0x3EAC_396A), - (Fun::Tanh, 0x3FA0_0001, 0x3F59_291E), - (Fun::Tanh, 0x3FC0_0000, 0x3F67_B7CC), - (Fun::Tanh, 0x4040_0000, 0x3F7E_BBE8), - (Fun::Tanh, 0x4080_0000, 0x3F7F_D40C), - (Fun::Tanh, 0x4105_1591, 0x3F7F_FFFE), - (Fun::Tanh, 0x4105_1592, 0x3F80_0000), - (Fun::Tanh, 0xC000_0000, 0xBF76_CA84), - (Fun::Tanh, 0x3FC1_2FA0, 0x3F68_249E), - (Fun::Tanh, 0x402A_AB55, 0x3F7D_8A49), - (Fun::Tanh, 0x40AA_DFAA, 0x3F7F_FCFD), - (Fun::Tanh, 0x4101_CA7D, 0x3F7F_FFFE), - (Fun::Tanh, 0x3EB3_3336, 0x3EAC_396C), - (Fun::Tanh, 0x3ED0_CCCC, 0x3EC5_F23A), - (Fun::Tanh, 0x3EEE_6666, 0x3EDE_8B71), - (Fun::Tanh, 0x3F0C_0005, 0x3EFF_10C0), - (Fun::Tanh, 0x3F29_999A, 0x3F14_7C80), - (Fun::Tanh, 0x3F47_3333, 0x3F26_D12B), - (Fun::Tanh, 0x3F64_CCCC, 0x3F36_96F5), - (Fun::Tanh, 0x3F82_6666, 0x3F44_F492), - ]; - let f = f32s(); - for fun in [Fun::Sinh, Fun::Cosh, Fun::Tanh] { - let mine: Vec<(u32, u32)> = measured - .iter() - .filter(|(g, _, _)| *g == fun) - .map(|(_, x, w)| (*x, *w)) - .collect(); - for (x, w) in &mine { - assert_eq!(hyper_model(fun, *x), *w, "{fun:?}'s model at {x:#010x}"); - } - check_module( - &format!("{fun:?} at Metal's measured words"), - routine_module(fun, false, false), - &[f], - f, - &mine - .iter() - .map(|(x, _)| vec![vec![u64::from(*x)]]) - .collect::>(), - &|c| { - mine.iter() - .find(|(x, _)| u64::from(*x) == c[0][0]) - .map(|(_, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - } -} - -/// Every second-stage routine answers bit for bit the same with `OpFmaKHR` for a product's exact -/// error as with Dekker's product, over the accuracy tests' operands: each product whose error an -/// answer depends on lies above `2^-100`, where both are the same exact `float`. Part `part` of -/// `of` of the runs of 1,024 operands. -fn same_with_fma(part: usize, of: usize) { - let xs = exp_operands(0x0F3A_0F3A); - let ls = log_operands(0x0F3B_0F3B); - let mut rng = Rng(0x0F3C_0F3C); - let pairs: Vec> = (0..4000) - .map(|_| { - let x = ls[(rng.next() as usize) % ls.len()]; - let l = f64::from(f32v(x)).log2(); - let t = f64::from(f32v(uniform(&mut rng, -140.0, 130.0))); - let y = if l == 0.0 { t } else { t / l }; - vec![x, u64::from((y as f32).to_bits())] - }) - .collect(); - let mut runs = Vec::new(); - for fun in [ - Fun::Exp2, - Fun::Exp, - Fun::Exp10, - Fun::Log2, - Fun::Log, - Fun::Log10, - Fun::Powr, - Fun::Sinh, - Fun::Cosh, - Fun::Tanh, - Fun::Asinh, - Fun::Acosh, - Fun::Atanh, - ] { - let operands = match fun { - Fun::Powr => pairs.clone(), - Fun::Log2 | Fun::Log | Fun::Log10 => unary(&ls), - _ => unary(&xs), - }; - let cases: Vec = operands - .iter() - .map(|c| c.iter().map(|b| vec![*b]).collect()) - .collect(); - for run in cases.chunks(1024) { - runs.push((fun, run.to_vec())); - } - } - let f = f32s(); - let mut differ = Vec::new(); - for (fun, run) in part_of(runs, part, of) { - let ins = vec![f; fun.arity()]; - let plain = run_module("plain", routine_module(fun, false, false), &ins, f, &run); - let fused = run_module("fused", routine_module(fun, false, true), &ins, f, &run); - for ((c, p), q) in run.iter().zip(&plain).zip(&fused) { - if p != q { - differ.push(format!("{fun:?} {c:x?}: {p:x?} without, {q:x?} with")); - } - } - } - assert!( - differ.is_empty(), - "{} differ:\n{}", - differ.len(), - differ - .iter() - .take(12) - .cloned() - .collect::>() - .join("\n") - ); -} - -mod second_stage_routines_answer_the_same_with_fma { - parts!(super::same_with_fma, 16; - part_1_of_16 = 0, part_2_of_16 = 1, part_3_of_16 = 2, part_4_of_16 = 3, - part_5_of_16 = 4, part_6_of_16 = 5, part_7_of_16 = 6, part_8_of_16 = 7, - part_9_of_16 = 8, part_10_of_16 = 9, part_11_of_16 = 10, part_12_of_16 = 11, - part_13_of_16 = 12, part_14_of_16 = 13, part_15_of_16 = 14, part_16_of_16 = 15); -} - -/// Signed zeros, denormals, infinities, the largest finite floats, and the smallest normals. -const ZERO: u64 = 0x0000_0000; -const NEG_ZERO: u64 = 0x8000_0000; -const INF: u64 = 0x7F80_0000; -const NEG_INF: u64 = 0xFF80_0000; -const MAX: u64 = 0x7F7F_FFFF; -const NEG_MAX: u64 = 0xFF7F_FFFF; -const MIN: u64 = 0x0080_0000; -const NEG_MIN: u64 = 0x8080_0000; -const ONE: u64 = 0x3F80_0000; -const NEG_ONE: u64 = 0xBF80_0000; -const NAN: u64 = 0x7FC0_0000; - -/// The operands whose answer is the operand itself to Metal's odd functions below `2^-12`. -const TINY: [u64; 6] = [ZERO, NEG_ZERO, MIN, NEG_MIN, DENORMALS[0], DENORMALS[3]]; - -/// Metal's precise answers at the special operands (case 7b283404, every such lane), bit for bit: -/// zeros, denormals, and the smallest normals; infinities; the largest finite floats where the -/// answer is infinite or `±1`; `±1` where Metal's answer is exact; and its NaN `0x7fc00000` at a -/// domain error. A NaN operand gives a NaN. (Metal's `asinh(±FLT_MAX)` and `acosh(FLT_MAX)`, -/// `±0x42b2d4fb`, are 1.15 ulp below the exact value, and are its forms' words.) Part `part` of -/// `of` of the routines, each over all of its special operands in one run. -fn metals_special_values(part: usize, of: usize) { - let mut specials: Vec<(Fun, u64, u64)> = Vec::new(); - for fun in [Fun::Exp2, Fun::Exp, Fun::Exp10] { - for x in [ZERO, NEG_ZERO, MIN, NEG_MIN].into_iter().chain(DENORMALS) { - specials.push((fun, x, ONE)); - } - specials.extend([ - (fun, INF, INF), - (fun, NEG_INF, ZERO), - (fun, MAX, INF), - (fun, NEG_MAX, ZERO), - ]); - } - specials.extend([ - (Fun::Exp2, ONE, 0x4000_0000), - (Fun::Exp2, NEG_ONE, 0x3F00_0000), - (Fun::Exp2, u64::from((-126f32).to_bits()), MIN), - (Fun::Exp2, u64::from((-127f32).to_bits()), ZERO), - (Fun::Exp2, u64::from(128f32.to_bits()), INF), - (Fun::Exp10, NEG_ONE, 0x3DCC_CCCD), - // A denormal result is flushed (case 7b283404: `exp(-87.34)` is `+0`). - (Fun::Exp, u64::from((-87.34f32).to_bits()), ZERO), - ]); - for fun in [Fun::Log2, Fun::Log, Fun::Log10] { - for x in [ZERO, NEG_ZERO].into_iter().chain(DENORMALS) { - specials.push((fun, x, NEG_INF)); - } - specials.extend([ - (fun, INF, INF), - (fun, ONE, ZERO), - (fun, NEG_ONE, NAN), - (fun, NEG_MIN, NAN), - (fun, NEG_MAX, NAN), - (fun, NEG_INF, NAN), - ]); - } - specials.push((Fun::Log2, MIN, 0xC2FC_0000)); - for x in TINY.into_iter().chain(DENORMALS) { - specials.push((Fun::Sinh, x, x)); - specials.push((Fun::Tanh, x, x)); - specials.push((Fun::Asinh, x, x)); - specials.push((Fun::Atanh, x, x)); - specials.push((Fun::Cosh, x, ONE)); - specials.push((Fun::Acosh, x, NAN)); - } - specials.extend([ - (Fun::Sinh, INF, INF), - (Fun::Sinh, NEG_INF, NEG_INF), - (Fun::Sinh, MAX, INF), - (Fun::Sinh, NEG_MAX, NEG_INF), - (Fun::Cosh, INF, INF), - (Fun::Cosh, NEG_INF, INF), - (Fun::Cosh, NEG_MAX, INF), - (Fun::Tanh, INF, ONE), - (Fun::Tanh, NEG_INF, NEG_ONE), - (Fun::Tanh, MAX, ONE), - (Fun::Tanh, NEG_MAX, NEG_ONE), - (Fun::Asinh, INF, INF), - (Fun::Asinh, NEG_INF, NEG_INF), - (Fun::Asinh, MAX, 0x42B2_D4FB), - (Fun::Asinh, NEG_MAX, 0xC2B2_D4FB), - (Fun::Acosh, INF, INF), - (Fun::Acosh, MAX, 0x42B2_D4FB), - (Fun::Acosh, ONE, ZERO), - (Fun::Acosh, NEG_ONE, NAN), - (Fun::Acosh, NEG_INF, NAN), - (Fun::Acosh, NEG_MAX, NAN), - (Fun::Atanh, ONE, INF), - (Fun::Atanh, NEG_ONE, NEG_INF), - // To `0x3a400000` Metal's `atanh` is its operand. - (Fun::Atanh, 0x39C0_0000, 0x39C0_0000), - (Fun::Atanh, 0xB9FF_FF00, 0xB9FF_FF00), - (Fun::Atanh, INF, NAN), - (Fun::Atanh, NEG_INF, NAN), - (Fun::Atanh, MAX, NAN), - (Fun::Atanh, NEG_MAX, NAN), - ]); - // `powr`'s own answers at a zero, denormal, and infinite base (`math::powr_nan` answers the - // NaNs around them), and exact powers. - let two = u64::from(2f32.to_bits()); - let minus_two = u64::from((-2f32).to_bits()); - let powr = [ - (ZERO, two, ZERO), - (ZERO, minus_two, INF), - (DENORMALS[0], two, ZERO), - (DENORMALS[0], minus_two, INF), - (INF, two, INF), - (INF, minus_two, ZERO), - (two, u64::from(3f32.to_bits()), u64::from(8f32.to_bits())), - (u64::from(4f32.to_bits()), u64::from(0.5f32.to_bits()), two), - (two, NEG_ONE, u64::from(0.5f32.to_bits())), - (two, u64::from(128f32.to_bits()), INF), - (two, u64::from((-127f32).to_bits()), ZERO), - (MAX, two, INF), - ]; - let checks = vec![ - Fun::Exp2, - Fun::Exp, - Fun::Exp10, - Fun::Log2, - Fun::Log, - Fun::Log10, - Fun::Powr, - Fun::Sinh, - Fun::Cosh, - Fun::Tanh, - Fun::Asinh, - Fun::Acosh, - Fun::Atanh, - ]; - let f = f32s(); - for fun in part_of(checks, part, of) { - if fun == Fun::Powr { - check_module( - "Powr at its special operands", - routine_module(Fun::Powr, false, false), - &[f, f], - f, - &powr - .iter() - .map(|(x, y, _)| vec![vec![*x], vec![*y]]) - .collect::>(), - &|c| { - powr.iter() - .find(|(x, y, _)| [*x, *y] == [c[0][0], c[1][0]]) - .map(|(_, _, w)| vec![*w]) - }, - &|g, w| g == w, - ); - continue; - } - let mut want: BTreeMap = BTreeMap::new(); - for (_, x, w) in specials.iter().filter(|(g, _, _)| *g == fun) { - let other = want.insert(*x, *w); - assert!( - other.is_none_or(|o| o == *w), - "{fun:?}({x:#010x}) has two answers" - ); - } - check_module( - &format!("{fun:?} at its special operands"), - routine_module(fun, false, false), - &[f], - f, - &want.keys().map(|x| vec![vec![*x]]).collect::>(), - &|c| want.get(&c[0][0]).map(|w| vec![*w]), - &|g, w| g == w, - ); - // A NaN operand gives a NaN. - check_module( - &format!("{fun:?}(NaN)"), - routine_module(fun, false, false), - &[f], - f, - &[vec![vec![NAN]], vec![vec![0xFFC0_1234]]], - &|_| Some(vec![NAN]), - &|g, _| f32v(g).is_nan(), - ); - } -} - -mod exponential_and_hyperbolic_routines_answer_metals_special_values { - parts!(super::metals_special_values, 4; - part_1_of_4 = 0, part_2_of_4 = 1, part_3_of_4 = 2, part_4_of_4 = 3); -} - -/// The module of float function `op` on form `f` whose routines `funs` are defined, for -/// [`math::float_fn`]. -fn function_module(op: FloatFn, f: Form, funs: &[Fun]) -> TypedModule { - kernel_defs( - &vec![f; op.arity()], - f, - &|b| { - funs.iter() - .map(|fun| libm::define_alone(b, *fun, false)) - .collect() - }, - &|fb, x, ids| { - let map: BTreeMap = - funs.iter().copied().zip(ids.iter().copied()).collect(); - math::float_fn( - fb, - op, - f, - Contraction::Forbidden, - NanTest::IsNan, - x, - &Lib::new(None, &map), - ) - }, - true, - false, - ) - .unwrap_or_else(|e| panic!("{op:?} {f:?}: build: {e:?}")) -} - -/// Metal's fast functions off a device whose instructions are Metal's are MSL Table 8.2's formulas -/// of the `exp2` and `log2` routines, which answer Metal's fast functions at the special operands -/// bit for bit (case f6524207, every such lane): a zero, a denormal, and the smallest normal give -/// `exp`'s 1 and the others' `+0`, whatever the sign; `fast::asinh(-inf)` is NaN (`-inf + inf`), -/// and `fast::asinh(-FLT_MAX)` and `fast::acosh(-FLT_MAX)` are `+inf`. -#[test] -fn fast_formulas_answer_metals_special_values() { - let f = f32s(); - let small = [ZERO, NEG_ZERO, MIN, NEG_MIN, DENORMALS[0], DENORMALS[3]]; - let mut specials: Vec<(FloatFn, u64, u64)> = Vec::new(); - for x in small { - for op in [FloatFn::FastExp, FloatFn::FastExp10, FloatFn::FastCosh] { - specials.push((op, x, ONE)); - } - for op in [FloatFn::FastSinh, FloatFn::FastAsinh] { - specials.push((op, x, ZERO)); - } - specials.push((FloatFn::FastAcosh, x, NAN)); - } - for x in [ZERO, NEG_ZERO].into_iter().chain(DENORMALS) { - specials.push((FloatFn::FastLog, x, NEG_INF)); - specials.push((FloatFn::FastLog10, x, NEG_INF)); - } - specials.extend([ - (FloatFn::FastExp, INF, INF), - (FloatFn::FastExp, NEG_INF, ZERO), - (FloatFn::FastExp, MAX, INF), - (FloatFn::FastExp, NEG_MAX, ZERO), - (FloatFn::FastExp10, INF, INF), - (FloatFn::FastExp10, NEG_INF, ZERO), - (FloatFn::FastLog, INF, INF), - (FloatFn::FastLog, ONE, ZERO), - (FloatFn::FastLog, NEG_ONE, NAN), - (FloatFn::FastLog, NEG_INF, NAN), - (FloatFn::FastLog, MIN, 0xC2AE_AC50), - (FloatFn::FastLog10, INF, INF), - (FloatFn::FastLog10, ONE, ZERO), - (FloatFn::FastLog10, NEG_MAX, NAN), - (FloatFn::FastSinh, INF, INF), - (FloatFn::FastSinh, NEG_INF, NEG_INF), - (FloatFn::FastSinh, MAX, INF), - (FloatFn::FastSinh, NEG_MAX, NEG_INF), - (FloatFn::FastCosh, INF, INF), - (FloatFn::FastCosh, NEG_INF, INF), - (FloatFn::FastCosh, MAX, INF), - (FloatFn::FastAsinh, INF, INF), - (FloatFn::FastAsinh, NEG_INF, NAN), - (FloatFn::FastAsinh, MAX, INF), - (FloatFn::FastAsinh, NEG_MAX, INF), - (FloatFn::FastAcosh, INF, INF), - (FloatFn::FastAcosh, NEG_INF, NAN), - (FloatFn::FastAcosh, MAX, INF), - (FloatFn::FastAcosh, NEG_MAX, INF), - (FloatFn::FastAcosh, ONE, ZERO), - (FloatFn::FastAcosh, NEG_ONE, NAN), - ]); - let ops: Vec = { - let mut ops: Vec = specials.iter().map(|(op, _, _)| *op).collect(); - ops.dedup(); - ops.sort_by_key(|op| format!("{op:?}")); - ops.dedup(); - ops - }; - for op in ops { - let funs = libm::uses(op, f); - let cases: Vec<(u64, u64)> = specials - .iter() - .filter(|(o, _, _)| *o == op) - .map(|(_, x, w)| (*x, *w)) - .collect(); - check_module( - &format!("{op:?} at its special operands"), - function_module(op, f, funs), - &[f], - f, - &cases - .iter() - .map(|(x, _)| vec![vec![*x]]) - .collect::>(), - &|c| { - let x = c[0][0]; - cases.iter().find(|(b, _)| *b == x).map(|(_, w)| vec![*w]) - }, - &|g, w| g == w || (w == NAN && f32v(g).is_nan()), - ); - } -} - -/// `fast::atanh` off a device whose instructions are Metal's is `0.5 · log((1 + x) · rcp(1 - x))` -/// of the `log2` routine and Metal's fast division, by either reciprocal, which answers Metal's -/// fast `atanh` at the special operands bit for bit (case f6524207, every such lane): `+0` for a -/// zero, a denormal, and the smallest normal, `±inf` at `±1`, NaN for an infinity, and `-inf` for -/// `±FLT_MAX`, whose divisor's reciprocal Metal flushes. -#[test] -fn fast_atanh_is_the_formula_with_the_fast_division() { - let f = f32s(); - let mut cases: Vec<(u64, u64)> = [ZERO, NEG_ZERO, MIN, NEG_MIN, DENORMALS[0], DENORMALS[3]] - .into_iter() - .map(|x| (x, ZERO)) - .collect(); - cases.extend([ - (ONE, INF), - (NEG_ONE, NEG_INF), - (INF, NAN), - (NEG_INF, NAN), - (MAX, NEG_INF), - (NEG_MAX, NEG_INF), - ]); - for reciprocal in [Reciprocal::Device, Reciprocal::Rounded] { - let op = FloatFn::FastAtanh { reciprocal }; - let division = math::FastDivision::new(f, reciprocal, Contraction::Forbidden); - let m = kernel_defs( - &[f], - f, - &|b| { - Ok(vec![ - libm::define_alone(b, Fun::Log2, false)?, - math::define_fast_division(b, division)?, - ]) - }, - &|fb, x, ids| { - let map: BTreeMap = [(Fun::Log2, ids[0])].into_iter().collect(); - let divide = |fb: &mut FunctionBuilder<'_>, p: Value, q: Value| { - math::call_fast_division(fb, ids[1], p, q) - }; - math::fast_atanh(fb, op, f, x[0], &Lib::new(None, &map), ÷) - }, - true, - false, - ) - .unwrap_or_else(|e| panic!("{op:?}: build: {e:?}")); - check_module( - &format!("{op:?} at its special operands"), - m, - &[f], - f, - &cases - .iter() - .map(|(x, _)| vec![vec![*x]]) - .collect::>(), - &|c| { - let x = c[0][0]; - cases.iter().find(|(b, _)| *b == x).map(|(_, w)| vec![*w]) - }, - &|g, w| g == w || (w == NAN && f32v(g).is_nan()), - ); - } -} - -/// A `half` call of a second-stage function takes the `float` routine before its rounding, so it is -/// within a `half` ulp of the exact value over every fifth finite pattern (in runs within the -/// interpreter's step budget) whose result is a finite `half`: part `part` of `of` of the runs. -fn half_takes_the_routines(part: usize, of: usize) { - let h = float(16); - let cases: Vec = (0..=0xFFFFu64) - .step_by(5) - .filter(|b| b & 0x7C00 != 0x7C00) - .map(|b| vec![vec![b]]) - .collect(); - let functions: [(FloatFn, fn(f64) -> f64); 12] = [ - (FloatFn::Exp2, f64::exp2), - (FloatFn::Exp, f64::exp), - (FloatFn::Exp10, |x| 10f64.powf(x)), - (FloatFn::Log2, f64::log2), - (FloatFn::Log, f64::ln), - (FloatFn::Log10, f64::log10), - (FloatFn::Sinh, f64::sinh), - (FloatFn::Cosh, f64::cosh), - (FloatFn::Tanh, f64::tanh), - (FloatFn::Asinh, f64::asinh), - (FloatFn::Acosh, f64::acosh), - (FloatFn::Atanh, f64::atanh), - ]; - let reference = |exact: fn(f64) -> f64, c: &Case| { - let r = exact(f16_to_f64(c[0][0] as u16)); - // Finite `half` results; the infinities and NaNs are the `float` routine's. - (r.is_finite() && r.abs() <= 65504.0).then(|| vec![u64::from(f64_to_f16(r))]) - }; - let mut runs = Vec::new(); - for (op, exact) in functions { - let defined: Vec = cases - .iter() - .filter(|c| reference(exact, c).is_some()) - .cloned() - .collect(); - for run in defined.chunks(2048) { - runs.push((op, exact, run.to_vec())); - } - } - for (op, exact, run) in part_of(runs, part, of) { - check_module( - &format!("half {op:?}"), - function_module(op, h, libm::uses(op, h)), - &[h], - h, - &run, - &|c| reference(exact, c), - &|g, w| { - let nan = |b: u64| b & 0x7C00 == 0x7C00 && b & 0x03FF != 0; - if nan(g) { - return false; - } - // A zero answer is exact up to its sign; another is within one `half` ulp of the - // same sign. - if w & 0x7FFF == 0 || g & 0x7FFF == 0 { - return g & 0x7FFF == w & 0x7FFF; - } - (g ^ w) & 0x8000 == 0 && (g as i64 - w as i64).abs() <= 1 - }, - ); - } -} - -mod half_exponentials_and_hyperbolics_take_the_routines { - parts!(super::half_takes_the_routines, 4; - part_1_of_4 = 0, part_2_of_4 = 1, part_3_of_4 = 2, part_4_of_4 = 3); -} - -/// Metal's `half` functions that are not its precise `float` functions rounded -/// (`math::metal_half`, `half_tanh`, `half_small`, `half_cospi_zero`, and `sinpi(-0)`): Metal's -/// words at measured operands of our probe (the M4's, are the same), those where the precise -/// routines rounded were not Metal's among them, the edges of the operand ranges each answers by, -/// and others; and `tanpi`, its `float` form rounded. The binary functions' second operand is the -/// probe's, `(i * 2654435761) >> 16` of the first's bits `i` (32-bit arithmetic). -#[test] -fn half_functions_answer_metals_measured_words() { - let h = float(16); - let unary: [(FloatFn, &[(u16, u16)]); 11] = [ - ( - FloatFn::Tanh, - &[ - (0x2744, 0x2743), - (0x2745, 0x2745), - (0x2748, 0x2748), - (0x2894, 0x2893), - (0x2895, 0x2895), - (0x2D86, 0x2D83), - (0xA746, 0xA746), - (0x0A68, 0x0A68), - (0x0C01, 0x0C01), - (0x4C00, 0x3C00), - (0x5A00, 0x3C00), - (0xFC00, 0xBC00), - (0x3C00, 0x3A18), - (0xC400, 0xBBFF), - ], - ), - ( - FloatFn::Sinh, - &[ - (0x321B, 0x3224), - (0x4758, 0x620A), - (0xB21B, 0xB224), - (0xC758, 0xE20A), - (0x0A68, 0x0A68), - (0x0A71, 0x0A71), - (0x0C00, 0x0C00), - (0x3C00, 0x3CB3), - ], - ), - ( - FloatFn::Cosh, - &[ - (0x3DEF, 0x40A3), - (0xBDEF, 0x40A3), - (0x3C00, 0x3E2C), - (0x4900, 0x7161), - ], - ), - ( - FloatFn::CosPi, - &[ - (0x3800, 0x8000), - (0x3E00, 0x0000), - (0x4100, 0x8000), - (0x4300, 0x0000), - (0xB800, 0x0000), - (0xBE00, 0x8000), - (0xC100, 0x0000), - (0x6200, 0x3C00), - (0x3400, 0x39A8), - ], - ), - ( - FloatFn::SinPi, - &[ - (0x8000, 0x8000), - (0x0000, 0x0000), - (0x3C00, 0x8000), - (0x4000, 0x0000), - (0x4200, 0x8000), - (0xBC00, 0x8000), - (0xC000, 0x0000), - (0x3800, 0x3C00), - ], - ), - // Metal's `float` `tanpi` of the widened operand, rounded. - ( - FloatFn::TanPi, - &[ - (0x0000, 0x0000), - (0x8000, 0x0000), - (0x0001, 0x0003), - (0x3400, 0x3C00), - (0x3800, 0x7C00), - (0xB800, 0xFC00), - (0x3C00, 0x0000), - (0x3E00, 0xFC00), - (0x3555, 0x3EED), - (0x3BFF, 0x9648), - (0x37FF, 0x6518), - (0x7C00, 0x7E00), - ], - ), - ( - FloatFn::Exp, - &[ - (0x3C00, 0x4170), - (0x4A00, 0x7C00), - (0xC880, 0x080B), - (0x2E66, 0x3C6C), - (0x0441, 0x3C00), - ], - ), - ( - FloatFn::Exp10, - &[ - (0x3C00, 0x4900), - (0x4000, 0x5640), - (0xBC00, 0x2E66), - (0x3555, 0x404F), - ], - ), - ( - FloatFn::Log, - &[ - (0x3C01, 0x13FF), - (0x4A00, 0x40F8), - (0x0400, 0xC8DA), - (0x3BFF, 0x9000), - ], - ), - ( - FloatFn::Log2, - &[ - (0x3C01, 0x15C5), - (0x4A00, 0x432C), - (0x0001, 0xCE00), - (0x3BFF, 0x91C6), - ], - ), - ( - FloatFn::Log10, - &[ - (0x3C01, 0x0EF2), - (0x4A00, 0x3C51), - (0x0400, 0xC437), - (0x7BFF, 0x44D1), - ], - ), - ]; - for (op, words) in unary { - let cases: Vec = words - .iter() - .map(|(x, _)| vec![vec![u64::from(*x)]]) - .collect(); - check_module( - &format!("half {op:?}"), - function_module(op, h, libm::uses(op, h)), - &[h], - h, - &cases, - &|c| { - words - .iter() - .find(|(x, _)| u64::from(*x) == c[0][0]) - .map(|(_, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - } - let pairs: [(u16, u16, u16); 7] = [ - (0x07D1, 0xAF9E, 0x41DC), - (0x41D1, 0x4130, 0x4BF8), - (0x4F23, 0xC023, 0x13FF), - (0x3C00, 0x0085, 0x3C00), - (0x4000, 0xDE6C, 0x0000), - (0x4100, 0x15E5, 0x3C01), - (0x3555, 0x049D, 0x3C00), - ]; - let cases: Vec = pairs - .iter() - .map(|(x, y, _)| vec![vec![u64::from(*x)], vec![u64::from(*y)]]) - .collect(); - for op in [FloatFn::Pow, FloatFn::Powr] { - check_module( - &format!("half {op:?}"), - function_module(op, h, libm::uses(op, h)), - &[h, h], - h, - &cases, - &|c| { - pairs - .iter() - .find(|(x, y, _)| (u64::from(*x), u64::from(*y)) == (c[0][0], c[1][0])) - .map(|(_, _, w)| vec![u64::from(*w)]) - }, - &|g, w| g == w, - ); - } -} - -/// Metal's fast `pow` and `powr` (and its `half` ones, the same compositions) where `y · log2(x)` -/// is infinite answer IEEE's value whatever the composition gave there (`math::infinite_product` -/// 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. -#[test] -fn an_infinite_product_answers_ieee_whatever_the_composition_gave() { - let (f, h) = (f32s(), float(16)); - let one = u64::from(1.0f32.to_bits()); - let one_h = 0x3C00; - // (x, y, answer); `None`: the composition's value kept. - 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)), - (0x7F80_0000, 0xC000_0000, Some(0)), - (0x7F80_0000, 0x4100_0000, Some(0x7F80_0000)), - (0x3F00_0000, 0x7F80_0000, Some(0)), - (0x4000_0000, 0x7F80_0000, Some(0x7F80_0000)), - (0x3F00_0000, 0xFF80_0000, Some(0x7F80_0000)), - (0x4000_0000, 0xFF80_0000, Some(0)), - (0x3F80_0000, 0x7F80_0000, None), - (0x0000_0000, 0x0000_0000, None), - (0x7FC0_0000, 0x4000_0000, None), - (0x4000_0000, 0x4040_0000, None), - ]; - let half_words: [(u64, u64, Option); 8] = [ - (0x0000, 0x3C00, Some(0)), - (0x8000, 0x4000, Some(0)), - (0x7C00, 0xC000, Some(0)), - (0x7C00, 0x4800, Some(0x7C00)), - (0x3800, 0x7C00, Some(0)), - (0x4000, 0xFC00, Some(0)), - (0x0001, 0x3C00, None), - (0x3C00, 0x7C00, None), - ]; - for (form, words, kept) in [(f, &words[..], one), (h, &half_words[..], one_h)] { - let module = kernel_defs( - &[form, form], - form, - &|_| Ok(Vec::new()), - &|fb, x, _| { - let r = crate::lower::arith::ops::fsplat(fb, form, 1.0)?; - math::infinite_product(fb, form, x[1], x[0], r) - }, - false, - false, - ) - .expect("build"); - let cases: Vec = words - .iter() - .map(|(x, y, _)| vec![vec![*x], vec![*y]]) - .collect(); - check_module( - &format!("infinite product {form:?}"), - module, - &[form, form], - form, - &cases, - &|c| { - words - .iter() - .find(|(x, y, _)| (*x, *y) == (c[0][0], c[1][0])) - .map(|(_, _, w)| vec![w.unwrap_or(kept)]) - }, - &|g, w| g == w, - ); - } -} - -/// Each second-stage routine's words, with its constants and types, stay within [`Fun::words`] with -/// and without `OpFmaKHR` (the estimate at most twice the larger), and each function's call site -/// within [`FloatFn::words`] on `float` and `float4` (and on `half` and `half4` the ones Metal -/// answers by its own `half` functions, `math::metal_half`), on a device whose functions are its -/// own and on one whose functions are Metal's, precise or fast (`exp10`'s, `log10`'s, and the fast -/// module's `exp`'s compositions): the module's growth over one that defines the same routines and -/// returns its operand. -#[test] -fn second_stage_fits_its_word_estimates() { - let module_words = |m: TypedModule| serialize(m).expect("serialize").words.len(); - let f = f32s(); - let mut off = Vec::new(); - for fun in [ - Fun::Exp2, - Fun::Exp, - Fun::Exp10, - Fun::Log2, - Fun::Log, - Fun::Log10, - Fun::Powr, - Fun::Sinh, - Fun::Cosh, - Fun::Tanh, - Fun::Asinh, - Fun::Acosh, - Fun::Atanh, - Fun::FastAsinh, - Fun::FastAcosh, - Fun::Recip, - Fun::FastRsqrt, - ] { - let bound = fun.words() as usize; - let mut largest = 0; - for fma in [false, true] { - let bare = module_words(helpers_module(fun, fma)); - let emitted = module_words(routine_module(fun, false, fma)) - bare; - eprintln!("{fun:?} fma={fma}: {emitted} words against {bound}"); - if emitted > bound { - off.push(format!("{fun:?} fma={fma}: {emitted} words over {bound}")); - } - largest = largest.max(emitted); - } - // The estimate covers the larger emission (without `OpFmaKHR`, each fused step is - // emulated) and is not loose by more than half. - if 2 * largest < bound { - off.push(format!("{fun:?}: {bound} words for at most {largest}")); - } - } - let h = float(16); - let half_ops = [ - FloatFn::Exp, - FloatFn::Exp10, - FloatFn::Log2, - FloatFn::Log, - FloatFn::Log10, - FloatFn::Powr, - FloatFn::Pow, - FloatFn::Sinh, - FloatFn::Cosh, - FloatFn::Tanh, - ]; - for form in [f, vec(f, 4), h, vec(h, 4)] { - for op in [ - FloatFn::Exp2, - FloatFn::Exp, - FloatFn::Exp10, - FloatFn::FastExp, - FloatFn::FastExp10, - FloatFn::Log2, - FloatFn::FastLog2, - FloatFn::Log, - FloatFn::Log10, - FloatFn::FastLog, - FloatFn::FastLog10, - FloatFn::Powr, - FloatFn::FastPowr, - FloatFn::Pow, - FloatFn::FastPow, - FloatFn::Sinh, - FloatFn::FastSinh, - FloatFn::Cosh, - FloatFn::FastCosh, - FloatFn::Tanh, - FloatFn::Asinh, - FloatFn::FastAsinh, - FloatFn::Acosh, - FloatFn::FastAcosh, - FloatFn::Atanh, - ] { - if form.float_fmt() == Some(FloatFmt::Half) && !half_ops.contains(&op) { - continue; - } - let funs = libm::uses(op, form); - let defined = |body: BodyCalling<'_>| { - kernel_defs( - &vec![form; op.arity()], - form, - &|b| { - funs.iter() - .map(|fun| libm::define_alone(b, *fun, false)) - .collect() - }, - body, - false, - false, - ) - .unwrap_or_else(|e| panic!("{op:?} {form:?}: build: {e:?}")) - }; - let bare = module_words(defined(&|_, x, _| Ok(x[0]))); - for metal in [None, Some(libm::Mode::Precise), Some(libm::Mode::Fast)] { - let used = module_words(defined(&|fb, x, ids| { - let map: BTreeMap = - funs.iter().copied().zip(ids.iter().copied()).collect(); - math::float_fn( - fb, - op, - form, - Contraction::Forbidden, - NanTest::IsNan, - x, - &Lib::new(metal, &map), - ) - })); - let (emitted, bound) = (used - bare, op.words(form) as usize); - eprintln!( - "{op:?} x{} {metal:?}: {emitted} words against {bound}", - form.lanes - ); - if emitted > bound { - off.push(format!( - "{op:?} x{} {metal:?}: {emitted} words over {bound}", - form.lanes - )); - } - } - } - } - assert!(off.is_empty(), "{}", off.join("\n")); -} diff --git a/crates/metal2vulkan/src/lower/sampler/face.rs b/crates/metal2vulkan/src/lower/sampler/face.rs index 0f635641c..3417b2fba 100644 --- a/crates/metal2vulkan/src/lower/sampler/face.rs +++ b/crates/metal2vulkan/src/lower/sampler/face.rs @@ -67,9 +67,7 @@ //! majors, and lies above it on 204 and below on 4, by one ulp or two (the lanes tell those apart //! from `RN(1 / |m_a|)`, not from each other), each a major whose reciprocal lies within about 0.2 //! ulp of a rounding midpoint; the shader's own `1.0f / m_a` and `precise::divide` are `RN(1 / -//! |m_a|)` on all of them. It is Metal's fast reciprocal, whose model (`libm::Fun::Recip`) reads -//! Metal's texel on 1,992 of those 2,001 lanes, on the M3 Max and the M4 alike; no exact form of it -//! is known. +//! |m_a|)` on all of them. It is Metal's fast reciprocal; no exact form of it is known. //! //! **A repeating face axis** ([`FaceWrap`]). Metal reads every other address mode of a cube's //! sampler as clamping, but `repeat` on a face axis whose size is not a power of two wraps that @@ -87,12 +85,12 @@ //! So a nearest sample through a constexpr normalized sampler that reads the base level, on a //! device without `VkProperty::MetalSampler`, hands the device the direction whose major component //! is `±1` and whose minor components are the centres of the texels Metal's position names with -//! `r` Metal's reciprocal's model (`libm::Fun::Recip`, or the device's `1 / |m_a|` where that is -//! Metal's) and the fused multiply-add, wrapped on a repeating face axis ([`FaceWrap`]): each -//! `(2i + 1) / n - 1`, oriented as Vulkan's face table orients it, which every device reads at the -//! face coordinate `(i + 1/2) / n`, half a texel from either edge. Where the model misses Apple's -//! reciprocal (by one ulp, on about 0.3 % of significands) and `X` lies within about `n * 2^-23` of -//! a texel edge, Metal reads the next texel, which the module records +//! `r` the device's `1 / |m_a|` (Metal's own where the device's functions are Metal's in a +//! fast-math entry, else `PrecisionNote::NativeDivision`) and the fused multiply-add, wrapped on a +//! repeating face axis ([`FaceWrap`]): each `(2i + 1) / n - 1`, oriented as Vulkan's face table +//! orients it, which every device reads at the face coordinate `(i + 1/2) / n`, half a texel from +//! either edge. Where that reciprocal misses Apple's and `X` lies within about `n * 2^-23` of a +//! texel edge, Metal reads the next texel, which the module records //! (`PrecisionNote::CubeFaceReciprocal`). A linear sample that Metal's filter answers takes the //! same position (`position`) and reads its taps by fetches, across a face's edges through //! `define_fold` (`linear::cube`), under the same note, and so does a cube gather (a depth cube's @@ -113,13 +111,11 @@ use crate::error::Error; use crate::lower::arith::fma::{self, Fma}; use crate::lower::arith::legal::{FloatFmt, Form, Held}; -use crate::lower::arith::libm; -use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; use crate::metal::sampler::SamplerWord; use crate::pipeline::artifact::PrecisionNote; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::{BResult, BuildError, TypeRule}; +use crate::spirv::error::BResult; use crate::spirv::ids::{FuncId, Value as SValue}; use crate::spirv::ir::{BinOp, ConstBits, Constant, ConvOp, GlslOp, Type as SType, UnOp}; @@ -287,15 +283,11 @@ pub(super) fn metal_ties(fb: &mut FunctionBuilder<'_>, p: SValue) -> BResult, pub fma: Fma, - pub fma_routine: Option, } /// The `float` scalar form the routines take. @@ -304,44 +296,23 @@ pub(super) const SCALAR: Form = Form { lanes: 1, }; -/// The routines Metal's face position takes on a profile ([`SnapRoutines`] before the module -/// declares them): Metal's reciprocal, which the arith family plans and declares with the math -/// library's routines (`libm::Fun::Recip`), and the fused multiply-add `fma`. +/// What Metal's face position takes on a profile ([`SnapRoutines`] as emission takes it): the +/// fused multiply-add `fma`. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct FaceRoutines { pub fma: Fma, } impl FaceRoutines { - /// The census words a position adds beside its own: the reciprocal's use (its routine's - /// call) and the two fused multiply-adds'. + /// The census words a position adds beside its own: the reciprocal's division and the two + /// fused multiply-adds'. pub(super) fn use_words(self) -> u32 { - libm::use_words(1, 1) + 2 * self.fma.words() + 16 + 2 * self.fma.words() } - /// The declared routines, as emission calls them. - pub(super) fn declared(self, cx: &mut EmitCx<'_>) -> BResult { - let recip = match crate::lower::arith::lib(cx).device(libm::Fun::Recip) { - true => None, - false => match cx.decl.families.arith.libm.get(&libm::Fun::Recip) { - Some(id) => Some(*id), - None => return Err(cx.fail("a cube position whose reciprocal is not declared")), - }, - }; - let fma_routine = match self.fma.routine() { - Some(r) => match cx.decl.families.arith.fmas.get(&r) { - Some(id) => Some(*id), - None => { - return Err(cx.fail("a cube position whose fused multiply-add is not declared")) - } - }, - None => None, - }; - Ok(SnapRoutines { - recip, - fma: self.fma, - fma_routine, - }) + /// The routines as emission takes them. + pub(super) fn declared(self) -> SnapRoutines { + SnapRoutines { fma: self.fma } } } @@ -431,44 +402,35 @@ fn wrapping( } } -/// The routines of a sample that takes Metal's face position ([`snapped`], [`position`]): Metal's -/// reciprocal (`libm::Fun::Recip`) and the profile's correctly rounded fused multiply-add, whose -/// module-scope routines the arith family declares. The reciprocal's model is Apple's texture -/// unit's on most majors, not all (module docs), which the module records -/// (`PrecisionNote::CubeFaceReciprocal`). +/// What a sample that takes Metal's face position takes ([`snapped`], [`position`]): the +/// device's reciprocal and the profile's fused multiply-add. The device's reciprocal is Apple's +/// texture unit's on most majors at best, not all (module docs), which the module records +/// (`PrecisionNote::CubeFaceReciprocal`), and the device's division within Vulkan's bound, but +/// where the device's functions are Metal's in an entry Metal compiles with fast math +/// (`PrecisionNote::NativeDivision`). pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result { // The sum `1 + sc * r` ([`texel_x`]) is computed between the sample's image and its use, which - // stay in one block, so it takes no branch: `OpFmaKHR` unchecked ([`Fma::unchecked`]), which is - // Metal's here. Its exact value is zero or at least `2^-48` in magnitude: a product near `-1` - // is an integer below `2^48` times a power of two of at least `2^-48`, so the sum is a - // multiple of that power (or, for a power above 1, at least 1). - let Some(fma) = Fma::on(cx.profile, SCALAR).map(Fma::unchecked) else { + // stay in one block, so it takes no branch. + let Some(fma) = Fma::on(cx.profile, SCALAR) else { return Err(cx.invariant("a cube position without a float fused multiply-add")); }; - cx.families.arith.libm_uses.insert(libm::Fun::Recip); cx.families.arith.take_fma(fma); cx.precision.insert(PrecisionNote::CubeFaceReciprocal); - // Native device maths: the reciprocal is the device's `1 / |m_a|`. - if cx.profile.fields().float_functions == crate::device::profile::FloatFunctions::Native { + if cx.profile.fields().float_functions == crate::device::profile::FloatFunctions::Metal { + cx.families + .arith + .unless_metal_fast + .insert(PrecisionNote::NativeDivision); + } else { cx.precision.insert(PrecisionNote::NativeDivision); } Ok(FaceRoutines { fma }) } -/// Metal's reciprocal of the major magnitude `ma` (a `float`): the call of its routine, or the -/// device's `1 / ma` (`one` is `1.0`) where that is Metal's ([`SnapRoutines::recip`]). -fn reciprocal( - fb: &mut FunctionBuilder<'_>, - one: SValue, - ma: SValue, - routines: SnapRoutines, -) -> BResult { - match routines.recip { - Some(f) => fb - .call(f, &[ma])? - .ok_or(BuildError::Type(TypeRule::FunctionSignature)), - None => fb.binary(BinOp::FDiv, one, ma), - } +/// The reciprocal of the major magnitude `ma` (a `float`): the device's `1 / ma` (`one` is +/// `1.0`). +fn reciprocal(fb: &mut FunctionBuilder<'_>, one: SValue, ma: SValue) -> BResult { + fb.binary(BinOp::FDiv, one, ma) } /// A cube direction `p` (three floats, `metal_ties`'s) handed to the device so that a nearest @@ -493,7 +455,7 @@ pub(super) fn snapped( let fr = frame(fb, p)?; let (wrap_s, wrap_t) = wrapping(fb, n, Wraps::Axes(wrap))?; // Metal's reciprocal of `|ma|`, its texture unit's on most majors (module docs). - let r = reciprocal(fb, one, fr.ma, routines)?; + let r = reciprocal(fb, one, fr.ma)?; // The centre of Metal's texel on one face axis, as the minor component handed on. let centre = |fb: &mut FunctionBuilder<'_>, (flip, c): (SValue, SValue), @@ -552,7 +514,7 @@ pub(super) fn position( let nf = fb.convert(ConvOp::ConvertUToF, n, f32_)?; let fr = frame(fb, p)?; let (wrap_s, wrap_t) = wrapping(fb, n, wrap)?; - let r = reciprocal(fb, one, fr.ma, routines)?; + let r = reciprocal(fb, one, fr.ma)?; let sc = oriented(fb, fr.flip_s, fr.c_s)?; let s = texel_x(fb, sc, (r, nf), (routines, wrap_s))?; let tc = oriented(fb, fr.flip_t, fr.c_t)?; @@ -664,7 +626,7 @@ fn texel_x( ) -> BResult { let one = f32_value(fb, 1.0)?; let half = f32_value(fb, 0.5)?; - let sum = fma::emit(fb, routines.fma, &[sc, r, one], routines.fma_routine)?; + let sum = fma::emit(fb, routines.fma, &[sc, r, one])?; let s = fb.binary_no_contraction(BinOp::FMul, sum, half)?; let s = match wrap { Some(w) => { diff --git a/crates/metal2vulkan/src/lower/sampler/face/tests/snap.rs b/crates/metal2vulkan/src/lower/sampler/face/tests/snap.rs index f3c8106c2..7dd58af6b 100644 --- a/crates/metal2vulkan/src/lower/sampler/face/tests/snap.rs +++ b/crates/metal2vulkan/src/lower/sampler/face/tests/snap.rs @@ -2,64 +2,29 @@ //! and M4), and its wrap of a repeating face axis (the cube probes, Apple M4). Each kernel //! invocation reads a direction's bits and a face size, hands the direction through `metal_ties` //! and then `snapped`, and writes the handed direction's bits; a device reading it in exact -//! arithmetic, or rounding each operation to `f32`, must read the texel Metal's position names. +//! arithmetic, or rounding each operation to `f32`, must read the texel Metal's position names with +//! the device's reciprocal (here the interpreter's correctly rounded one). -use super::super::{snapped, FaceWrap, SnapRoutines, SCALAR, SNAP_WORDS}; +use super::super::{snapped, FaceRoutines, FaceWrap, SnapRoutines, SCALAR, SNAP_WORDS}; use super::{ - kernel_on, lanes, metal_axis, metal_ties, read_as_zero, run_records, selecting, MOST_READ, - SIZES, + kernel_on, lanes, metal_axis, metal_ties, read_as_zero, run_records, selecting, SIZES, }; -use crate::lower::arith::divide::{self, Path}; -use crate::lower::arith::fma::{self, Fma, Route, FLOAT_ROUTES}; -use crate::lower::arith::libm::{self, rcp, Fun, Helpers}; +use crate::lower::arith::fma::{self, Fma, Route}; use crate::spirv::builder::ModuleBuilder; use crate::spirv::error::BResult; use crate::spirv::ir::TypedModule; -/// The routines of `fma`'s route on module `b`: Metal's reciprocal (`libm::Fun::Recip`), with its -/// table and the precise division by the path a profile pairs with the route -/// (`divide::Path::on`: fused where the fused multiply-add is `OpFmaKHR`), and the fused -/// multiply-add's own routine where it has one. -fn routines(b: &mut ModuleBuilder, fma: Fma) -> BResult { - let (path, khr) = match fma.route { - Route::Khr => (Path::Fused, true), - Route::Wide | Route::Soft | Route::F16 | Route::F16Khr | Route::Native => { - (Path::Integer, false) - } - }; - let helpers = Helpers { - division: Some(divide::define(b, divide::Routine { lanes: 1, path })?), - rcp: Some(rcp::declare(b)?), - ..Helpers::default() - }; - let recip = Some(libm::define(b, Fun::Recip, khr, helpers)?); - let fma_routine = match fma.routine() { - Some(r) => Some(fma::define(b, r)?), - None => None, - }; - Ok(SnapRoutines { - recip, - fma, - fma_routine, - }) -} - -/// Metal's reciprocal of a major magnitude `top` that it reads (`2^-125` up to `2^126`; past -/// `2^126` it reads every minor component as zero, and the reciprocal is its flushed zero): the -/// model of `libm::Fun::Recip`'s routine. -fn metal_recip(top: f32) -> f32 { - match top > MOST_READ { - true => 0.0, - false => rcp::model(top), - } +/// The device's reciprocal of a major magnitude `top`, as the interpreter divides: `RN(1 / top)`. +fn device_recip(top: f32) -> f32 { + 1.0 / top } /// A kernel whose invocation reads a direction and a face size and writes the direction that -/// `metal_ties` and then (`snap`) `snapped` hand the device, with the routines of `fma`'s route, -/// wrapping the face axes `wrap` names. +/// `metal_ties` and then (`snap`) `snapped` hand the device, by `fma`'s route, wrapping the face +/// axes `wrap` names. fn kernel(fma: Fma, snap: bool, wrap: FaceWrap) -> BResult { - let mut b = ModuleBuilder::new(); - let r = routines(&mut b, fma)?; + let b = ModuleBuilder::new(); + let r = SnapRoutines { fma }; kernel_on(b, 4, &|f, p, n| { let p = metal_ties(f, p)?; match snap { @@ -74,7 +39,6 @@ fn by(route: Route) -> Fma { let routes = fma::Routes { float: route, half: Route::Native, - tiny: None, }; Fma::by(routes, SCALAR).expect("float") } @@ -128,9 +92,9 @@ fn metal_x(c: f32, r: f32, n: u32, wraps: bool) -> f32 { } /// Metal's nearest texel along a finite direction `d` on faces of size `n`, its reciprocal of the -/// major magnitude [`metal_recip`]'s: the face `metal_reading` reads, and on each face -/// axis `floor(X)` of [`metal_x`] (wrapped on the axes `wrap` names), at most `n - 1`, with each -/// component Metal reads as zero `0`; a direction left zero at face `+x`'s texel `(0, 0)`. +/// major magnitude the device's ([`device_recip`]): the face `metal_reading` reads, and on each +/// face axis `floor(X)` of [`metal_x`] (wrapped on the axes `wrap` names), at most `n - 1`, with +/// each component Metal reads as zero `0`; a direction left zero at face `+x`'s texel `(0, 0)`. fn metal_texel(d: [f32; 3], n: u32, wrap: FaceWrap) -> Texel { let m = selecting(d); let major = metal_axis(m); @@ -143,7 +107,7 @@ fn metal_texel(d: [f32; 3], n: u32, wrap: FaceWrap) -> Texel { false => d[k], }); let positive = d[major] > 0.0; - let r = metal_recip(top); + let r = device_recip(top); let [s, t] = face_minors(read, major, positive); let texels = [(s, wrap.s), (t, wrap.t)].map(|(c, w)| clamped(metal_x(c, r, n, w).into(), n)); (major, positive, texels) @@ -237,57 +201,10 @@ fn check(lanes: &[([f32; 3], u32)], got: &[[f32; 3]], wrap: FaceWrap, what: &str } } -/// Lanes of WRG's cube rounding probe 2 (Apple M3 Max on macOS 26.7 and -/// M4 on macOS 27.0.1, byte-identical) on faces of 1,024 texels along which Metal's texture -/// unit's reciprocal is not `RN(1 / |m_a|)`: each direction's bits (face `+x`) and the texel -/// Metal read on the face's `s` and `t` axes. Every 25th of the 202 such lanes that Metal's -/// reciprocal's model reads. -const PINNED: [([u32; 3], [u32; 2]); 9] = [ - ([0x3FFC_C375, 0x3FFC_4513, 0x3FFC_4515], [0, 0]), - ([0x3F80_AEB9, 0x3F78_D1D8, 0x3F80_6E62], [0, 16]), - ([0x3F95_653D, 0x3F82_6DE3, 0x3F95_1A8B], [0, 64]), - ([0x3FEE_D65E, 0x3FEE_5EF2, 0x3FEE_5EF4], [0, 0]), - ([0x3FA7_0203, 0x3FA6_AE82, 0x3FA6_AE83], [0, 0]), - ([0x3FB4_BA15, 0x3FB4_5FB8, 0x3FB4_5FB9], [0, 0]), - ([0x3FC8_66C7, 0x3FC8_0293, 0x3FC8_0295], [0, 0]), - ([0x3E2A_E95C, 0x3E2A_93E7, 0x3E2A_93E8], [0, 0]), - ([0x4060_9D9A, 0x4060_2D4B, 0x4060_2D4C], [0, 0]), -]; - -/// Along [`PINNED`]'s lanes, where the correctly rounded reciprocal names another texel than Metal -/// read, Metal's reciprocal's model names Metal's, and the device reads it along the handed -/// direction through every `float` route. -#[test] -fn metals_reciprocal_reads_the_pinned_texels() { - let lanes: Vec<([f32; 3], u32)> = PINNED - .iter() - .map(|(d, _)| (d.map(f32::from_bits), 1024)) - .collect(); - let none = FaceWrap::default(); - for ((d, n), (_, texel)) in lanes.iter().zip(PINNED) { - assert_eq!(metal_texel(*d, *n, none), (0, true, texel), "{d:?}"); - let r = 1.0 / d[0]; - let rounded = - face_minors(*d, 0, true).map(|c| clamped(metal_x(c, r, *n, false).into(), *n)); - assert_ne!( - rounded, texel, - "{d:?}: the correctly rounded reciprocal's texel" - ); - } - for route in FLOAT_ROUTES { - check( - &lanes, - &run(by(route), &lanes, none), - none, - &format!("{route:?}"), - ); - } -} - /// On every lane of `metal_ties`'s tests, at every size, through `OpFmaKHR`, and on the texel-step -/// lanes and the through every `float` route, the device reads the face and texel Metal's position -/// names (Metal's reciprocal) along the handed direction; a direction with an infinite or NaN -/// component passes unchanged. +/// lanes through the device's `Fma` too, the device reads the face and texel Metal's position +/// names with the device's reciprocal along the handed direction; a direction with an infinite or +/// NaN component passes unchanged. #[test] fn the_device_reads_metals_nearest_texel() { let mut all: Vec<([f32; 3], u32)> = lanes() @@ -303,14 +220,7 @@ fn the_device_reads_metals_nearest_texel() { check(&all, &run(by(Route::Khr), &all, none), none, "Khr"); let mut few: Vec<([f32; 3], u32)> = steps.iter().step_by(5).copied().collect(); few.push(TODO_1_14); - for route in FLOAT_ROUTES.into_iter().filter(|r| *r != Route::Khr) { - check( - &few, - &run(by(route), &few, none), - none, - &format!("{route:?}"), - ); - } + check(&few, &run(by(Route::Native), &few, none), none, "Native"); } /// The step lanes reach the hazards Metal's position decides: on many of them the texel differs @@ -322,7 +232,7 @@ fn the_step_lanes_reach_the_rounding_hazards() { let steps = steps(); let (mut unfused, mut quotient, mut residue) = (0, 0, 0); for ([ma, c, _], n) in &steps { - let r = metal_recip(*ma); + let r = device_recip(*ma); let texel = |x: f32| clamped(x.into(), *n); let want = texel(metal_x(*c, r, *n, false)); unfused += usize::from(texel((c * r + 1.0) * 0.5 * *n as f32) != want); @@ -342,9 +252,9 @@ fn the_step_lanes_reach_the_rounding_hazards() { assert!(residue > 1000, "{residue} of {} lanes", steps.len()); } -/// `SNAP_WORDS`, a reciprocal's use, two fused multiply-adds', and the wrap's bound the words -/// `snapped` adds beside its routines, in a module valid on every committed profile, without a wrap -/// and wrapping either face axis or both. +/// `SNAP_WORDS`, the reciprocal's division, two fused multiply-adds', and the wrap's bound the +/// words `snapped` adds beside its routines, in a module valid on every committed profile, without +/// a wrap and wrapping either face axis or both. #[test] fn the_estimate_bounds_the_emitted_words() { let profiles = crate::spirv::testing::committed_profiles().expect("profiles"); @@ -362,7 +272,7 @@ fn the_estimate_bounds_the_emitted_words() { profile, ); let added = with.len() - without.len(); - let estimate = SNAP_WORDS + libm::use_words(1, 1) + 2 * fma.words() + wrap.words(); + let estimate = SNAP_WORDS + FaceRoutines { fma }.use_words() + wrap.words(); assert!( added <= estimate as usize, "{stem} {wrap:?}: snapped adds {added} words, estimated {estimate}" diff --git a/crates/metal2vulkan/src/lower/sampler/linear/cube.rs b/crates/metal2vulkan/src/lower/sampler/linear/cube.rs index 8782f4c03..ec86e33de 100644 --- a/crates/metal2vulkan/src/lower/sampler/linear/cube.rs +++ b/crates/metal2vulkan/src/lower/sampler/linear/cube.rs @@ -320,7 +320,7 @@ fn fetch_taps( let Some(cube) = cx.decl.families.sampler.linear_cube else { return Err(cx.fail("a cube footprint without its fold")); }; - let routines = site.routines.declared(cx)?; + let routines = site.routines.declared(); let i32_ = fb.module().ty(SType::Int { width: 32, signed: true, diff --git a/crates/metal2vulkan/src/lower/sampler/position.rs b/crates/metal2vulkan/src/lower/sampler/position.rs index feb74bde8..3afae328d 100644 --- a/crates/metal2vulkan/src/lower/sampler/position.rs +++ b/crates/metal2vulkan/src/lower/sampler/position.rs @@ -1020,7 +1020,7 @@ pub fn snapped_on( let kind = match snap.kind { SnapKind::Axes(kind) => kind, SnapKind::Cube(routines) => { - let routines = routines.declared(cx)?; + let routines = routines.declared(); let n = lane(fb, size, size_lanes, 0)?; return super::face::snapped(fb, coord, n, (routines, snap.face_wrap())); } diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index ad2765973..1d4e9f4ee 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -607,38 +607,32 @@ pub enum PrecisionNote { /// Metal's own sample. GradFromBias, /// Transcendentals answer within Apple's stated bound, not Metal's bits: the device's own - /// functions, or the translation's routines where a device's instruction may leave the bound - /// (and, for the functions no routine covers yet, the device's precision). Not recorded by - /// `sqrt`, `rsqrt`, and `fmod`, precise, whose answer is the one right value on every device, - /// nor, on a device whose `float` functions are Metal's own (MoltenVK), in an entry Metal + /// functions where they are Metal's (MoltenVK), and the device's precision for a call no + /// other note bounds. Not recorded by precise `fmod`, whose answer is the one right value on + /// every device, nor, on a device whose `float` functions are Metal's own, in an entry Metal /// compiles with fast math ([`EntryMath::Fast`]) by a call the device answers as Metal's own - /// function; there its fast `sinpi`, `cospi`, and `tanpi`, near-equivalents, and the - /// translation's own routines still record it. + /// function; there its fast `sinpi`, `cospi`, and `tanpi`, near-equivalents, still record it. DeviceTranscendentals, /// Float reductions use the device's association order. ReductionOrder, /// `float` denormals follow the device: Metal reads an `f32` denormal operand of its float /// arithmetic, comparisons, and functions as the zero of its sign and flushes a denormal result /// to one, where a Vulkan device keeps or flushes them by its own float controls (this - /// translation declares no `DenormFlushToZero`). Recorded only where the module leaves an - /// operation's denormals to the device: the instructions of native device maths - /// (`FloatMathsPolicy::Native`, `fast::fmod`'s fused multiply-add among them) and of the - /// device's order (`RoundingOrderPolicy::Native`: `mix` by `FMix`, `fast::sqrt` by `Sqrt`, - /// and `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, under every - /// policy, a conversion to or from `double`, whose reading Metal's is not measured. Every other - /// `float` operation reads its denormals as Metal does on every device (the device's where the - /// profile takes the measured `DriverDeviation::MetalFloatDenormals`, an exponent-field select - /// elsewhere): `+ - *`, the comparisons, the divisions, `fma`, `mix`, `dot`, `sqrt`, `rsqrt`, - /// `floor` and `ceil`, `ldexp` (on its operand's bits), the minimum and maximum functions - /// (`llvm.minnum` and `llvm.maxnum` among them, with any flags), and the functions the - /// translation computes itself or the device answers as Metal's own; `mix`, `atan2`, `sinpi`, - /// `cospi`, `tanpi` and `fast::fmod` in both modes, and two chained `fma`s, answer Metal's - /// words on an Apple M3 Max under macOS 27.0.1 at and around denormal operands, - /// but where the device's fused multiply-add under native device maths rounds a result whose - /// exact value is below `2^-126` up to `2^-126`, which Metal flushes (docs/FAST-PATHS.md, - /// known gaps). Validation derives no tolerance and no explanation from it: every `float` - /// computation is exposed to it. + /// translation declares no `DenormFlushToZero`). Recorded where the module leaves an + /// operation's denormals to a device not measured to read them as Metal does: `+ - *`, the + /// comparisons, `fma`, `dot`, `sqrt`, `rsqrt`, `trunc` and `rint` but on a device that takes + /// the measured `DriverDeviation::MetalFloatDenormals`; and on every device the divisions and + /// the remainder, `floor` and `ceil`, the device's maths functions (`fast::fmod`'s fused + /// multiply-add among them), `mix` by `FMix`, `fast::sqrt` by `Sqrt`, `dot` of vectors of other + /// than two to four lanes, whose chunks' products the device sums where Metal flushes each one + /// below `2^-126`, beside their own notes, and a conversion to or from `double`, whose reading + /// Metal's is not measured. The operations that read a denormal on its bits answer Metal on + /// every device: `ldexp`, `sign`, `fract`, `copysign`, `fabs` and `atan2`; and so do the + /// functions the device answers as Metal's own. Where the minimum and maximum functions + /// (`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 + /// it: every `float` computation is exposed to it. DeviceDenormals, /// Pixel-coordinate samplers scale coordinates in the shader, rounding differently. /// Recorded for an access through a runtime sampler slot whose word may state pixel @@ -655,21 +649,16 @@ pub enum PrecisionNote { PixelSamplerScaling, /// Float division, remainder, square root, fused multiply-add, and dot products use Vulkan's /// precision bounds (e.g. 2.5 ULP division, a possibly unfused `Fma`) rather than correct - /// rounding. A fast (`arcp`) division's reciprocal, which Metal rounds within about 0.64 - /// ulp but not correctly, is the device's or, where the profile has `OpFmaKHR`, `RN(1 / y)`, - /// which differs from Metal's by an ulp near rounding midpoints. Not recorded by `sqrt` and - /// `fmod`, precise, whose answer is the one right value on every device, nor, on a device whose - /// `float` functions are Metal's own (MoltenVK), in an entry Metal compiles with fast math + /// rounding. A fast (`arcp`) division is the device's `OpFDiv`, where Metal's is `x` times a + /// reciprocal it rounds within about 0.64 ulp but not correctly. Not recorded by precise + /// `fmod`, whose answer is the one right value on every device, nor, on a device whose `float` + /// functions are Metal's own (MoltenVK), in an entry Metal compiles with fast math /// ([`EntryMath::Fast`]), by a fast division, which is Metal's own there, or by a call the /// device answers as Metal's own function. DeviceArithmetic, /// Float operations LLVM requires to keep signed zeros, infinities, and NaNs run without - /// `SignedZeroInfNanPreserve`, which the device does not support at their width. Under - /// `FloatMathsPolicy::Exact` so does an operation that answers Metal's zero of its sign: a - /// fused multiply-add the translation computes itself (in `double` or in integers without - /// `OpFmaKHR`), one by `OpFmaKHR` whose result is at most `2^-126` in magnitude, and a `float` - /// product flushed below `2^-126`. Without the mode the device may answer such a zero with - /// either sign. + /// `SignedZeroInfNanPreserve`, which the device does not support at their width. Without the + /// mode the device may answer such a zero with either sign. DeviceSignedZeroInfNan, /// A ray intersection traversed by the device's ray query. The hit distance and the /// barycentrics are the device's arithmetic. The conventions no Metal reading has settled yet @@ -1671,9 +1660,8 @@ pub enum PrecisionNote { DeviceSampling, /// Native device maths: the module computes a `float` or `half` math-library function by the /// device's own `GLSL.std.450` instruction (or Metal's composition of the device's `Exp2` and - /// `Log2`), not by the translation's routine of Metal's answer, on a device whose functions - /// are not Metal's own, under `FloatMathsPolicy::Native` (the default; the owner's ruling of - /// 2026-10-11); and `fast::sqrt` the device's `Sqrt`, under `RoundingOrderPolicy::Native`. + /// `Log2`) where Metal's function is not the device's own; and `fast::sqrt` the device's + /// `Sqrt` on a device whose functions are not Metal's own. /// **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 @@ -1685,9 +1673,8 @@ pub enum PrecisionNote { /// `DeviceNanEncoding` where recorded). Validation derives no tolerance from it. NativeTranscendentals, /// Native device maths: a precise `float` or `half` division, or Metal's fast division or - /// reciprocal, is the device's `OpFDiv`, not the translation's correctly rounded routine or - /// its `RN(1 / y)`, on a device whose division is not Metal's own, under - /// `FloatMathsPolicy::Native` (the default). **Recorded bound:** Vulkan's 2.5 ulp of the + /// reciprocal, is the device's `OpFDiv` where the device's division is not Metal's own. + /// **Recorded bound:** Vulkan's 2.5 ulp of the /// quotient for a divisor in `[2^-126, 2^126]`, where Metal's precise division is correctly /// rounded and its fast one `x` times a reciprocal within about 0.64 ulp; beyond that range /// a precise division's operands are scaled by `2^-2` into it, exactly, and a fast one is the @@ -1695,12 +1682,11 @@ pub enum PrecisionNote { /// once more: within one unit in the last place of the `half` result. Validation derives no /// tolerance from it. NativeDivision, - /// Native device maths: a `float` fused multiply-add on a device without `OpFmaKHR`, under - /// `FloatMathsPolicy::Native` (the default), not the translation's correctly rounded routine, - /// or a `half` one, under every policy, where the device's 16-bit `Fma` is not measured to be - /// Metal's and the device has no 16-bit `OpFmaKHR` under the 16-bit float controls, is the - /// device's `GLSL.std.450 Fma` (on the `half` operands held in `float`, its result rounded to - /// `half`). **Recorded bound:** a `half` result within one unit in its last place of + /// Native device maths: a `float` fused multiply-add on a device without `OpFmaKHR`, or a + /// `half` one where the device's 16-bit `Fma` is not measured to be Metal's and the device has + /// no 16-bit `OpFmaKHR` under the 16-bit float controls, is the device's `GLSL.std.450 Fma` + /// (on the `half` operands held in `float`, its result rounded to `half`), where Metal's rounds + /// once. **Recorded bound:** a `half` result within one unit in its last place of /// Metal's (the product of two `half` values is exact in `float`, so only the two roundings /// differ); a `float` one within half a unit in the last place of the product plus half a /// unit in the last place of the result (Vulkan lets `Fma` round the product and then the @@ -1805,8 +1791,8 @@ pub enum PrecisionNote { NativeMinMax, /// Native device maths: Metal's `dot` on `float`, or on `half` where its fused multiply-add is /// not the measured 16-bit one, is the device's `OpDot` (a `half` one summed in `float` and - /// rounded once to `half`), not Metal's fused chain of its products, under - /// `RoundingOrderPolicy::Native` (the default). **Recorded bound:** a `float` `dot` of `n` + /// rounded once to `half`), not Metal's fused chain of its products, on a device whose + /// functions are not Metal's own. **Recorded bound:** a `float` `dot` of `n` /// lanes within `(3n - 1) * 2^-24 * sum |a_i * b_i|` of Metal's chain, plus `n * 2^-126` where /// a product is an `f32` denormal the device keeps (Vulkan's `OpDot` inherits `OpFMul`'s and /// `OpFAdd`'s rounding, `2n - 1` roundings, where Metal's chain rounds `n` times); a `half` @@ -1815,8 +1801,8 @@ pub enum PrecisionNote { NativeDot, /// Native device maths: Metal's `mix(x, y, t)` on `float`, or on `half` where its fused /// multiply-add is not the measured 16-bit one, is the device's `FMix` (a `half` one computed - /// in `float` and rounded once to `half`), not Metal's `fma(t, y, fma(-t, x, x))`, under - /// `RoundingOrderPolicy::Native` (the default). **Recorded bound:** a `float` result within + /// in `float` and rounded once to `half`), not Metal's `fma(t, y, fma(-t, x, x))`, on a device + /// whose functions are not Metal's own. **Recorded bound:** a `float` result within /// `2^-21 * (|x * (1 - t)| + |y * t|)` of Metal's (Vulkan's `FMix` inherits /// `x * (1 - t) + y * t`'s rounding, four roundings, where Metal's rounds twice); a `half` /// one within `3 * 2^-10 * (|x * (1 - t)| + |y * t|) + 2^-23`. Validation derives no diff --git a/crates/metal2vulkan/src/pipeline/compile/fit.rs b/crates/metal2vulkan/src/pipeline/compile/fit.rs index 75eb343ab..eafcce4e8 100644 --- a/crates/metal2vulkan/src/pipeline/compile/fit.rs +++ b/crates/metal2vulkan/src/pipeline/compile/fit.rs @@ -13,8 +13,7 @@ use crate::budget::{Budget, Meter}; use crate::cache::VariantKey; use crate::device::policy::{ - DevicePolicy, FloatMathsPolicy, NanMinMaxPolicy, RoundingOrderPolicy, SamplingPolicy, - TexelConversionPolicy, YCbCrFilterPolicy, + DevicePolicy, NanMinMaxPolicy, SamplingPolicy, TexelConversionPolicy, YCbCrFilterPolicy, }; use crate::device::{mechanism, Device, DeviceProfile}; use crate::error::Error; @@ -298,10 +297,8 @@ impl ReducedForms { match self { ReducedForms::NativeSampling => sampled, ReducedForms::AllNative => DevicePolicy { - float_maths: FloatMathsPolicy::Native, texel_conversion: TexelConversionPolicy::Device, nan_and_min_max: NanMinMaxPolicy::Native, - rounding_order: RoundingOrderPolicy::Native, ..sampled }, } @@ -318,10 +315,8 @@ fn dropped_forms( ) -> RuntimeDependency { let fact = RuntimeFact::ExactFormsOverCompilerLimit { sampling: base.sampling != policy.sampling || base.ycbcr_filter != policy.ycbcr_filter, - float_maths: base.float_maths != policy.float_maths, texel_conversion: base.texel_conversion != policy.texel_conversion, nan_and_min_max: base.nan_and_min_max != policy.nan_and_min_max, - rounding_order: base.rounding_order != policy.rounding_order, }; RuntimeDependency { fact, diff --git a/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs b/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs index fe95aa9c1..520296c3b 100644 --- a/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs @@ -65,21 +65,13 @@ fn device(stem: &str, policy: DevicePolicy) -> Device { /// The forms a fitted pipeline's `dependencies` record it dropped, in the fact's field order; /// `None` where it records none. -fn dropped(dependencies: &[RuntimeDependency]) -> Option<[bool; 5]> { +fn dropped(dependencies: &[RuntimeDependency]) -> Option<[bool; 3]> { dependencies.iter().find_map(|d| match d.fact { RuntimeFact::ExactFormsOverCompilerLimit { sampling, - float_maths, texel_conversion, nan_and_min_max, - rounding_order, - } => Some([ - sampling, - float_maths, - texel_conversion, - nan_and_min_max, - rounding_order, - ]), + } => Some([sampling, texel_conversion, nan_and_min_max]), _ => None, }) } @@ -90,10 +82,8 @@ fn dropped(dependencies: &[RuntimeDependency]) -> Option<[bool; 5]> { fn fitted_as(reduced: P, compiled: &P) -> P { let fact = RuntimeFact::ExactFormsOverCompilerLimit { sampling: true, - float_maths: true, texel_conversion: true, nan_and_min_max: true, - rounding_order: true, }; let mut reduced = reduced; reduced @@ -173,7 +163,7 @@ fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() { assert_eq!(largest(&pipe), w_fast, "reduced to the fast default"); assert_eq!( dropped(&pipe.dependencies), - Some([true; 5]), + Some([true; 3]), "every exact form dropped" ); @@ -184,7 +174,7 @@ fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() { assert_eq!(largest(&pipe), w_sampling_native); assert_eq!( dropped(&pipe.dependencies), - Some([true, false, false, false, false]), + Some([true, false, false]), "only sampling dropped" ); } @@ -236,7 +226,7 @@ fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() { .expect("fitted from the functions"); assert_eq!(fitted.key, keys.pipeline); assert_eq!(largest(&fitted), w_fast); - assert_eq!(dropped(&fitted.dependencies), Some([true; 5])); + assert_eq!(dropped(&fitted.dependencies), Some([true; 3])); } /// A mesh render pipeline is fitted as a vertex and fragment pipeline is: past the bound, its @@ -310,8 +300,12 @@ fn a_mesh_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() { w_fast, "{stem}: the fast forms" ); + // The fixture's maths are the device's under every policy, so no exact form need grow it. let w_exact = compiled.largest_stage_words(); - assert!(w_fast < w_exact, "{stem}: fast {w_fast} < exact {w_exact}"); + assert!( + w_fast <= w_exact, + "{stem}: fast {w_fast} <= exact {w_exact}" + ); let fit = |d: &MeshPipelineDescriptor, bound| { dev.fit_mesh_within(d, &v, &b, compiled.clone(), bound) .expect(stem) @@ -512,7 +506,7 @@ fn a_compute_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() { assert_eq!(pipe.stage, sampled.stage, "{stem}: native sampling"); assert_eq!( dropped(&pipe.dependencies), - Some([true, false, false, false, false]), + Some([true, false, false]), "{stem}: only sampling dropped" ); assert_eq!( diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 1016643ea..9ee1e1a30 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -767,10 +767,8 @@ pub enum RuntimeFact { /// dropped. Nothing binds it. ExactFormsOverCompilerLimit { sampling: bool, - float_maths: bool, texel_conversion: bool, nan_and_min_max: bool, - rounding_order: bool, }, /// The render pipeline was compiled under `VariantKey::quad_primitive_ids`, and its fragment /// function reads `[[primitive_id]]` from Vulkan's `PrimitiveId` shifted right by one diff --git a/crates/metal2vulkan/src/pipeline/testing.rs b/crates/metal2vulkan/src/pipeline/testing.rs index 5d6cfd889..d002efd67 100644 --- a/crates/metal2vulkan/src/pipeline/testing.rs +++ b/crates/metal2vulkan/src/pipeline/testing.rs @@ -160,11 +160,9 @@ pub fn storage_buffers(a: &FunctionArtifact) -> u32 { .sum() } -/// The default policy with the translation's routines of Metal's maths -/// (`FloatMathsPolicy::Exact`), and Metal's NaN, minimum and maximum and rounding order (`NanMinMaxPolicy::Exact`, -/// `RoundingOrderPolicy::Exact`): the policy of the tests of those routines, which the device's -/// forms, the defaults, leave off a device whose functions are not Metal's. The texel conversions -/// are the default's. +/// The default policy with Metal's NaN and minimum and maximum (`NanMinMaxPolicy::Exact`): the +/// policy of the tests of those forms, which the device's forms, the defaults, leave off a device +/// whose functions are not Metal's. The texel conversions are the default's. pub fn exact_maths() -> DevicePolicy { let native = DevicePolicy::default(); DevicePolicy { @@ -461,98 +459,6 @@ pub fn zero_relocations(a: &FunctionArtifact, words: &[u32]) -> Vec { out } -/// The result ids of each product check's scaling multiply in module `words` -/// (`denormal::tiny_product` under `TinyCheck::Fused`, `|a| · 2^48`): an `OpFMul` of a 32-bit -/// `float` constant `2^48`, or of a vector of them. So a test counts the check's own instructions -/// apart from the caller's. -pub fn tiny_check_scales(words: &[u32]) -> Vec { - use crate::spv::Op; - const SCALE: u32 = 0x5780_0000; - let (mut floats, mut scales, mut results) = (Vec::new(), Vec::new(), Vec::new()); - let mut i = 5; - while i < words.len() { - let (len, op) = ((words[i] >> 16) as usize, words[i] & 0xFFFF); - assert!(len > 0 && i + len <= words.len(), "malformed module"); - let at = &words[i..i + len]; - if op == Op::TypeFloat as u32 && at[2] == 32 { - floats.push(at[1]); - } - if op == Op::Constant as u32 && len == 4 && floats.contains(&at[1]) && at[3] == SCALE { - scales.push(at[2]); - } - if op == Op::ConstantComposite as u32 - && len > 3 - && at[3..].iter().all(|c| scales.contains(c)) - { - scales.push(at[2]); - } - if op == Op::FMul as u32 && (scales.contains(&at[3]) || scales.contains(&at[4])) { - results.push(at[2]); - } - i += len; - } - results -} - -/// The module `words` without the math library's routines: the functions of exactly one -/// parameter, which answer Metal's function of one operand where the device's instruction does -/// not, and the functions only they call, which they divide and take roots through (the precise -/// division's routine). So a test reads an entry's own instructions around their calls. The entry -/// (no parameter), and what it calls itself (the fast division's routine of two), stay. -pub fn without_math_routines(words: &[u32]) -> Vec { - // Each function: its words, its result id, its parameters, and the functions it calls. - let mut functions: Vec<(std::ops::Range, u32, usize, Vec)> = Vec::new(); - let mut entries = Vec::new(); - let mut i = 5; - while i < words.len() { - let (len, op) = ((words[i] >> 16) as usize, words[i] & 0xFFFF); - assert!(len > 0 && i + len <= words.len(), "malformed module"); - if op == crate::spv::Op::EntryPoint as u32 { - entries.push(words[i + 2]); - } - if op == crate::spv::Op::Function as u32 { - functions.push((i..i, words[i + 2], 0, Vec::new())); - } - if let Some((range, _, params, calls)) = functions.last_mut().filter(|f| f.0.is_empty()) { - if op == crate::spv::Op::FunctionParameter as u32 { - *params += 1; - } - if op == crate::spv::Op::FunctionCall as u32 { - calls.push(words[i + 3]); - } - if op == crate::spv::Op::FunctionEnd as u32 { - range.end = i + len; - } - } - i += len; - } - let mut dropped: Vec = functions.iter().filter(|f| f.2 == 1).map(|f| f.1).collect(); - loop { - let only_theirs = functions.iter().map(|f| f.1).find(|&id| { - let mut callers = functions.iter().filter(|f| f.3.contains(&id)); - !dropped.contains(&id) - && !entries.contains(&id) - && callers.clone().next().is_some() - && callers.all(|f| dropped.contains(&f.1)) - }); - match only_theirs { - Some(id) => dropped.push(id), - None => break, - } - } - let mut keep = vec![true; words.len()]; - for (range, id, _, _) in &functions { - if dropped.contains(id) { - keep[range.clone()].fill(false); - } - } - words - .iter() - .zip(keep) - .filter_map(|(w, k)| k.then_some(*w)) - .collect() -} - /// The instructions of the module `words` after its header: each opcode with its whole /// instruction (the first word included). fn instructions(words: &[u32]) -> Result, String> { diff --git a/crates/metal2vulkan/src/spirv/testing.rs b/crates/metal2vulkan/src/spirv/testing.rs index b82ca211d..9aa045e67 100644 --- a/crates/metal2vulkan/src/spirv/testing.rs +++ b/crates/metal2vulkan/src/spirv/testing.rs @@ -248,8 +248,8 @@ pub fn committed_exact_profiles() -> Result, String committed_profiles_under(crate::pipeline::testing::EXACT_SAMPLING) } -/// [`committed_profiles`] under `policy` (the tests of the exact maths routines take -/// `FloatMathsPolicy::Exact`, [`crate::pipeline::testing::exact_maths`]). +/// [`committed_profiles`] under `policy` (the tests of Metal's NaN and `half` rounding take +/// [`crate::pipeline::testing::exact_maths`]). pub fn committed_profiles_with( policy: DevicePolicy, ) -> Result, String> { diff --git a/crates/metal2vulkan/src/tests/engine_arith.rs b/crates/metal2vulkan/src/tests/engine_arith.rs index d7fcd1623..6fb680aa2 100644 --- a/crates/metal2vulkan/src/tests/engine_arith.rs +++ b/crates/metal2vulkan/src/tests/engine_arith.rs @@ -11,9 +11,9 @@ //! an integer where it needs one. `llvm-as` assembles the generated module; without it the test //! skips visibly. //! -//! Every profile here takes the translation's routines of Metal's maths -//! (`FloatMathsPolicy::Exact`, `exact_maths`), whose answers these tests check; native device -//! maths, the default, is `engine_native_maths`'. +//! Every profile here takes Metal's `half` rounding and NaN (`exact_maths`), whose answers these +//! tests check; the maths functions are the device's on every device but MoltenVK +//! (`engine_native_maths`). use crate::air::{self, SpecRequest}; use crate::device::profile::{DeviceProfile, DriverWorkaround, FloatFunctions}; @@ -29,8 +29,7 @@ use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::compile::{plan_bitcode, EntryRef}; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; use crate::pipeline::testing::{ - compile, exact_maths, link_and_validate, llvm_assemble, meter, profile, tiny_check_scales, - without_math_routines, AssembleError, Scratch, + compile, exact_maths, link_and_validate, llvm_assemble, meter, profile, AssembleError, Scratch, }; use crate::spirv::interp::{run, Buffer, Config, Resources}; @@ -402,8 +401,7 @@ fn kernels() -> Vec { ), 0x9522_6620, )); - // Metal's fast division reads the device's reciprocal; its precise division is a routine, exact - // on every profile. + // A fast division is the device's quotient, noted. v.push(Kernel { name: "arcp_fdiv_notes_device_precision", body: format!("{} %r = fdiv arcp float %a, 2.0\n", of("a", 7.0)), @@ -607,9 +605,10 @@ fn kernels() -> Vec { needs: &[], note: None, }); - // `dot` of chunked vectors, under the exact maths these kernels compile with, is Metal's fused - // chain over every lane (`wide_dot_is_metals_fused_chain_in_metals_order`), with no note; - // `sincos` of one computes per chunk and stores its cosine as one chunked leaf. + // `dot` of chunked vectors is Metal's fused chain over every lane where the profile's `float` + // functions are Metal's, and each chunk's `OpDot` elsewhere + // (`wide_dot_is_metals_fused_chain_in_metals_order`), exact on these lanes; `sincos` of one + // computes per chunk and stores its cosine as one chunked leaf. v.push(Kernel { name: "chunked_dot_sums_every_chunk", body: format!( @@ -1064,6 +1063,16 @@ fn arith_kernels_validate_and_compute_on_every_profile() { plan.estimate.words ); if let Some(n) = kk.note { + // A maths function off Metal's own functions records the device's + // precision. + let n = match n { + PrecisionNote::DeviceTranscendentals + if p.fields().float_functions != FloatFunctions::Metal => + { + PrecisionNote::NativeTranscendentals + } + n => n, + }; assert!(a.precision.contains(&n), "{what}: {:?}", a.precision); } // Only an 8-bit float to integer conversion reads the unverified value. @@ -1209,19 +1218,17 @@ fn wide_divisions_share_one_routine_per_form() { } } -/// `float` and `half` fused multiply-adds (`air.fma`, `llvm.fma`, `llvm.fmuladd`) round once on -/// every profile, by the profile's route: `OpFmaKHR` where `shaderFmaFloat32` is enabled -/// (moltenvk-m3), else one shared `double` routine (lavapipe) or integer routine (vk12-floor) per -/// lane count, which every use on that many lanes calls; called on one and two lanes, the two-lane -/// routine calls the one-lane routine on each lane. A1 case 52343cc4's lane (`a = 1 + 2^-23`, `b = -/// 1 - 2^-24`, `c = -RN(a * b)`), on one lane and on a vector's first, gives the product's rounding -/// error, which an unfused `Fma` loses; a `half` triple whose `float` sum is a `half` midpoint -/// gives the once-rounded `half` inline as the device's 16-bit `Fma`, which the driver computes as -/// Metal's `half` `fma` (moltenvk-m3), and elsewhere (lavapipe, vk12-floor) is the device's -/// `float` `Fma` rounded to `half`, inline too, noted `NativeFma`, within one unit in the last place -/// of the `half`. No module notes `DeviceArithmetic` or `F16FmaDoubleRounding`. +/// `float` and `half` fused multiply-adds (`air.fma`, `llvm.fma`, `llvm.fmuladd`) take the +/// profile's route, inline: `OpFmaKHR` where `shaderFmaFloat32` is enabled (moltenvk-m3), else the +/// device's `Fma` (lavapipe, vk12-floor), noted `NativeFma`. A1 case 52343cc4's lane (`a = 1 + +/// 2^-23`, `b = 1 - 2^-24`, `c = -RN(a * b)`), on one lane and on a vector's first, gives the +/// product's rounding error, which an unfused `Fma` loses (the interpreter's `Fma` rounds once); a +/// `half` triple whose `float` sum is a `half` midpoint gives the once-rounded `half` as the +/// device's 16-bit `Fma`, which the driver computes as Metal's `half` `fma` (moltenvk-m3), and +/// rounds twice as the device's `Fma` on the operands held in `float`, its result rounded to +/// `half` (lavapipe, vk12-floor). No module notes `DeviceArithmetic`. #[test] -fn fused_multiply_adds_round_once_on_every_route() { +fn fused_multiply_adds_take_the_profiles_route() { let (a, b) = (1.0f32 + f32::EPSILON, 1.0f32 - f32::EPSILON / 2.0); let c = -(a * b); let fused = a.mul_add(b, c); @@ -1266,14 +1273,11 @@ fn fused_multiply_adds_round_once_on_every_route() { let Some(bitcode) = assemble("fma-routes", &text) else { return; }; - // (profile, OpFmaKHR, functions, calls) of the float kernel: the entry and one routine per - // lane count (scalar, two lanes), one call per use, and the two-lane routine's call per lane. - // And whether the half kernel's is the device's `float` `Fma` rounded to `half`, the entry - // alone either way. - for (stem, khr, functions, calls, native_half) in [ - ("moltenvk-m3", 3, 1, 0, false), - ("lavapipe", 0, 3, 5, true), - ("vk12-floor", 0, 3, 5, true), + // (profile, OpFmaKHR of the float kernel, whether the routes are the device's `Fma`). + for (stem, khr, native) in [ + ("moltenvk-m3", 3, false), + ("lavapipe", 0, true), + ("vk12-floor", 0, true), ] { let p = profile(stem, exact_maths()).expect("profile"); for kk in &ks { @@ -1283,48 +1287,35 @@ fn fused_multiply_adds_round_once_on_every_route() { link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); for n in [ PrecisionNote::DeviceArithmetic, - PrecisionNote::F16FmaDoubleRounding, PrecisionNote::FastMathRewrites, ] { assert!(!a.precision.contains(&n), "{what}: {:?}", a.precision); } - if kk.name == "fma_float_rounds_once" { - assert_eq!( - ( - count_op(&words, crate::spv::Op::FmaKHR), - count_op(&words, crate::spv::Op::Function), - count_op(&words, crate::spv::Op::FunctionCall) - ), - (khr, functions, calls), - "{what}: OpFmaKHR, functions, calls" - ); - } else { - assert_eq!( - ( - count_op(&words, crate::spv::Op::Function), - count_op(&words, crate::spv::Op::FunctionCall) - ), - (1, 0), - "{what}: functions, calls" - ); - assert_eq!( - a.precision.contains(&PrecisionNote::NativeFma), - native_half, - "{what}: {:?}", - a.precision - ); - } + assert_eq!( + a.precision.contains(&PrecisionNote::NativeFma), + native, + "{what}: {:?}", + a.precision + ); + let float = kk.name == "fma_float_rounds_once"; + assert_eq!( + ( + count_op(&words, crate::spv::Op::FmaKHR), + count_op(&words, crate::spv::Op::Function), + count_op(&words, crate::spv::Op::FunctionCall) + ), + (if float { khr } else { 0 }, 1, 0), + "{what}: OpFmaKHR, functions, calls" + ); let got = interpret(&bitcode, kk.name, &p); - if kk.name == "fma_half_rounds_once" && native_half { - let want = f32::from_bits(kk.want.expect("want")); - let ulp = 2f32.powi(-10); - assert!( - (f32::from_bits(got) - want).abs() <= ulp, - "{what}: {got:#x} beyond one ulp of {want}" - ); + // The device's `Fma` in `float` rounds the `half` midpoint to even, away from the + // once-rounded `half`. + let want = if native && !float { + Some((-1182.0f32 / 1024.0).to_bits()) } else { - assert_eq!(Some(got), kk.want, "{what}: {got:#x}"); - } + kk.want + }; + assert_eq!(Some(got), want, "{what}: {got:#x}"); } } } @@ -1358,18 +1349,17 @@ fn opaque_vector(name: &str, half: bool, vals: &[f32]) -> String { } /// Metal's `dot` on `float` and `half` is the products' fused chain, `fma(x[n-1], y[n-1], ... -/// fma(x[1], y[1], x[0] * y[0]))`, with and without fast math, on every profile: the multiply and -/// `OpFmaKHR` (amd-rdna3-radv), or the shared routine of the profile's route (lavapipe's `double` -/// one, vk12-floor's and lunarg-desktop-baseline-2023's integer one), and on moltenvk-m3, whose -/// `float` functions are Metal's, the device's `OpDot` on `float`, which reaches Metal's own `dot`. -/// A `half` is summed in `half` by the chain on every profile. The words are Metal's (a probe, the -/// M3 Max and the M4 alike, at lanes where no other order, tree, unfused or exact sum gives them), -/// and fast math's zero signs where a device that regroups `dot(float2(a, b), float2(b, c))` as -/// `b * (a + c)` misses them (`nan_denormals_fast` with zeros for its denormals; -/// `nan_functions_fast`'s `dot((-0, +0), (+0, -0))`). No `dot` notes `DeviceArithmetic` or -/// `DeviceDenormals`. +/// fma(x[1], y[1], x[0] * y[0]))`, with and without fast math. On moltenvk-m3, whose `float` +/// functions are Metal's, `dot` on `float` is the device's `OpDot`, which reaches Metal's own +/// `dot`, and on `half` the chain of the device's 16-bit fused multiply-add, Metal's own: the words +/// are Metal's (a probe, the M3 Max and the M4 alike, at lanes where no other order, tree, unfused +/// or exact sum gives them), and fast math's zero signs where a device that regroups +/// `dot(float2(a, b), float2(b, c))` as `b * (a + c)` misses them (`nan_denormals_fast` with zeros +/// for its denormals; `nan_functions_fast`'s `dot((-0, +0), (+0, -0))`), with no +/// `DeviceArithmetic` or `DeviceDenormals`. Every other profile takes the device's `OpDot`, noted +/// `NativeDot`. #[test] -fn dot_is_metals_fused_chain_on_every_profile() { +fn dot_is_metals_fused_chain_on_moltenvk_and_the_devices_op_dot_elsewhere() { let f = |b: u32| f32::from_bits(b); let x = [0x3F2121E3, 0xC1504426, 0x40D96C9D, 0x3EC6C559].map(f); let y = [0xBFD689B8, 0xC0608ADE, 0xC0D7159F, 0x402DE9ED].map(f); @@ -1475,13 +1465,22 @@ fn dot_is_metals_fused_chain_on_every_profile() { let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + if !metal { + assert!( + count_op(&words, crate::spv::Op::Dot) > 0 + && a.precision.contains(&PrecisionNote::NativeDot), + "{what}: OpDot, {:?}", + a.precision + ); + continue; + } for n in [ PrecisionNote::DeviceArithmetic, PrecisionNote::DeviceDenormals, ] { assert!(!a.precision.contains(&n), "{what}: {:?}", a.precision); } - let device_dot = metal && !kk.name.ends_with("_half"); + let device_dot = !kk.name.ends_with("_half"); assert_eq!( count_op(&words, crate::spv::Op::Dot) > 0, device_dot, @@ -1501,9 +1500,8 @@ fn dot_is_metals_fused_chain_on_every_profile() { /// 27.0.1, 16,384 rows of seeded random lanes each on 5, 8 and 16 `float` lanes and 8 and 16 `half` /// lanes, every answer the chain's. Each row here is one where the chain backwards, the chunks' /// sums added and the exact sum rounded once all miss Metal's word. Where Metal's order is the -/// profile's (`RoundingOrderPolicy::Exact`; moltenvk-m3 under every policy) every profile answers it -/// by the chain ([`ArithStrategy::ChunkedChain`]): no `OpDot`, no `DeviceArithmetic` and no -/// `DeviceDenormals`. Under the default, a profile of the device's order keeps each chunk's +/// profile's (moltenvk-m3) it answers it by the chain ([`ArithStrategy::ChunkedChain`]): no +/// `OpDot`, no `DeviceArithmetic` and no `DeviceDenormals`. Every other profile keeps each chunk's /// `OpDot`, noted `DeviceArithmetic`. /// /// [`ArithStrategy::ChunkedChain`]: crate::lower::arith::ArithStrategy::ChunkedChain @@ -1605,9 +1603,9 @@ fn wide_dot_is_metals_fused_chain_in_metals_order() { ] { for (policy, exact) in [(exact_maths(), true), (DevicePolicy::default(), false)] { let p = profile(stem, policy).expect("profile"); - let chain = exact || p.fields().float_functions == FloatFunctions::Metal; + let chain = p.fields().float_functions == FloatFunctions::Metal; for kk in &ks { - let what = format!("{} on {stem} (exact: {exact})", kk.name); + let what = format!("{} on {stem} (exact forms: {exact})", kk.name); let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); @@ -1632,16 +1630,12 @@ fn wide_dot_is_metals_fused_chain_in_metals_order() { } } -/// `air.fast_fmod` on `float` is Metal's `fma(-trunc(x / y), y, x)` of its fast quotient (`x` times -/// the reciprocal of `y`), on every profile's fused multiply-add: `OpFmaKHR` (moltenvk-m3) or the -/// shared routine (lavapipe, vk12-floor). A1 case dd3b3b99's `fmod(1e10, 3)` is Metal's `-512` (the -/// quotient one ulp above the correctly rounded one), where `OpFRem`'s expression on the correctly -/// rounded quotient gives `0`. The module notes `DeviceArithmetic` (the reciprocal's rounding). On -/// moltenvk-m3, whose float functions and division are Metal's, the reciprocal is the device's -/// `OpFDiv(1, y)`; a profile with `OpFmaKHR` and without that fact refines it to `RN(1 / y)` by -/// four more `OpFmaKHR` (`fast_division_follows_the_metal_float_functions_fact`). The quotient is a -/// call of the fast division's routine, one function beside the entry (and the fused multiply-add's -/// routine where it has one). +/// `air.fast_fmod` on `float` is Metal's `fma(-trunc(x / y), y, x)` (MSL Table 8.2), of the +/// device's quotient `OpFDiv(x, y)`, on every profile's fused multiply-add: `OpFmaKHR` +/// (moltenvk-m3) or the device's `Fma` (lavapipe, vk12-floor), inline, the entry the module's one +/// function. A1 case dd3b3b99's `fmod(1e10, 3)` is Metal's `-512` (its fast quotient one ulp above +/// the correctly rounded one); on the interpreter's correctly rounded quotient, `3333333248`, the +/// fused expression gives `256`. The module notes `DeviceArithmetic` (the quotient's rounding). #[test] fn fast_fmod_is_metals_composition() { let kernel = Kernel { @@ -1652,7 +1646,7 @@ fn fast_fmod_is_metals_composition() { of("y", 3.0) ), float: true, - want: Some((-512.0f32).to_bits()), + want: Some(256.0f32.to_bits()), needs: &[], note: None, }; @@ -1665,9 +1659,9 @@ fn fast_fmod_is_metals_composition() { return; }; for (stem, khr, functions) in [ - ("moltenvk-m3", 1, 2), - ("lavapipe", 0, 3), - ("vk12-floor", 0, 3), + ("moltenvk-m3", 1, 1), + ("lavapipe", 0, 1), + ("vk12-floor", 0, 1), ] { let p = profile(stem, exact_maths()).expect("profile"); let kk = &ks[0]; @@ -1943,7 +1937,7 @@ fn a_fused_subtraction_negates_a_factor_that_is_not_a_sum() { let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); // On moltenvk-m3 both pairs are `OpFmaKHR` and the negation is the module's only - // one; the routes that call routines negate the same operand. + // one; the device's `Fma` negates the same operand. if stem == "moltenvk-m3" { let negated = negated_operands(&words); assert_eq!(negated.len(), 1, "{what}: one OpFNegate"); @@ -2097,30 +2091,18 @@ fn negated_operands(words: &[u32]) -> Vec { } /// Metal divides `float` under `arcp` as `x` times its fast reciprocal of `y` (a probe cases -/// 9496749c and 3921d3e2, every flag set with `arcp`, every lane). The probe's lane 0, `0x42aa3a21 -/// / 0x44c80075`, is `0x3d59e381` under `arcp` (`x` times `1 / y` rounded; without a flag it is -/// `0x3d59e382`, [`a_division_without_arcp_is_metals_precise_division`]). The reciprocal flushes: a -/// divisor past `2^126` gives a zero and a denormal divisor the infinity. On moltenvk-m3, whose -/// float functions and division are Metal's, the reciprocal is the device's `OpFDiv(1, y)`, Metal's -/// own under its fast-math compile, with no `OpFmaKHR`. A profile with `OpFmaKHR` and without that -/// fact takes `RN(1 / y)`, the device's estimate refined by four `OpFmaKHR` -/// (`fast_division_follows_the_metal_float_functions_fact`), so `6 / 3` is `2` whatever the -/// device's estimate (RC3 case f8494e2f read `0x3fffffff` from RADV's). The others take the -/// device's. Metal's own reciprocal is not on every lane of any of them in every math mode, and the -/// note stays. +/// 9496749c and 3921d3e2, every flag set with `arcp`, every lane): the probe's lane 0, `0x42aa3a21 +/// / 0x44c80075`, is `0x3d59e381` under `arcp` (`x` times `1 / y` rounded). The module takes the +/// device's `OpFDiv(x, y)` on every profile, with no `OpFmaKHR` and its note: here the +/// interpreter's correctly rounded quotient, `0x3d59e382`, as without a flag +/// ([`a_division_without_arcp_is_the_devices_quotient`]), and `6 / 3` is `2`. #[test] -fn an_arcp_division_is_metals_fast_division() { +fn an_arcp_division_is_the_devices_quotient() { let xy = format!( "{}{}", of("x", f32::from_bits(0x42AA_3A21)), of("y", f32::from_bits(0x44C8_0075)) ); - let one = of("one", 1.0); - let far = format!("{one}{}", of("far", 2f32.powi(127))); - let tiny = format!( - "{one}{} %tiny = bitcast i32 %tb to float\n", - oi("tb", 0x0040_0000) - ); let kernel = |name: &'static str, body: String, want: u32| Kernel { name, body, @@ -2133,22 +2115,12 @@ fn an_arcp_division_is_metals_fast_division() { kernel( "arcp_divide", format!("{xy} %r = fdiv arcp float %x, %y\n"), - 0x3D59_E381, + 0x3D59_E382, ), kernel( "fast_divide", format!("{xy} %r = fdiv fast float %x, %y\n"), - 0x3D59_E381, - ), - kernel( - "arcp_divide_past_2_126", - format!("{far} %r = fdiv arcp float %one, %far\n"), - 0, - ), - kernel( - "arcp_divide_by_a_denormal", - format!("{tiny} %r = fdiv arcp float %one, %tiny\n"), - 0x7F80_0000, + 0x3D59_E382, ), kernel( "arcp_six_by_three", @@ -2171,9 +2143,12 @@ fn an_arcp_division_is_metals_fast_division() { let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); assert_eq!( - count_op(&words, crate::spv::Op::FmaKHR), - 0, - "{what}: OpFmaKHR" + ( + count_op(&words, crate::spv::Op::FmaKHR), + count_op(&words, crate::spv::Op::FDiv) + ), + (0, 1), + "{what}: OpFmaKHR, OpFDiv" ); assert!( a.precision.contains(&PrecisionNote::DeviceArithmetic), @@ -2200,19 +2175,17 @@ fn every_profile() -> Vec { out } -/// Metal's fast division answers its NaNs and denormals on every committed profile, whatever the -/// device's NaN encoding and denormal mode: `0x7FC00000` for a NaN divisor of either sign (RADV -/// answered `0xffc00000`, a probe cases 9496749c and 3921d3e2), a NaN numerator, `0 / 0`, `inf / -/// inf`, and `inf · 0` (`inf / 2^127`, A1 case a919193f's `tanh` past `x = 44.4`); a denormal -/// numerator as a zero of its sign, so a denormal over a denormal is `0 · inf = NaN` (A1 case -/// f9a12252, where lavapipe kept the numerator and answered `+inf`); and a quotient whose 24-bit -/// rounding is below `2^-126` as a zero of its sign, `(2^24 - 1) · 2^-150` included, which the -/// denormal grid rounds up to `2^-126`. The operands are integer bits, so the division is the -/// kernel's only float operation, and it records the device's arithmetic (its reciprocal) and no -/// denormal or NaN note. The interpreter keeps denormals and NaN payloads, so each answer is the -/// lowering's. +/// Metal's fast division answers `0x7FC00000` for a NaN divisor of either sign (RADV answered +/// `0xffc00000`, a probe cases 9496749c and 3921d3e2), a NaN numerator, `0 / 0` and `inf / inf`, +/// which the module selects after the device's `OpFDiv` where the profile does not leave NaNs to +/// the device (where it does, the device's `OpFDiv` answers it; `inf / 2^127`, Metal's `inf · 0` +/// of its flushed reciprocal, is the device's infinity); its `f32` +/// denormals are the device's on every committed profile. The operands are integer bits, so the +/// division is the kernel's only float operation, and it records the device's arithmetic, its +/// division and its denormals, and no NaN note. The interpreter keeps NaN payloads, so each NaN +/// answer is the lowering's. #[test] -fn a_fast_division_answers_metal_at_nans_and_denormals_on_every_profile() { +fn a_fast_division_answers_metals_nans_on_every_profile() { let bits = |name: &str, b: u32| { format!(" %{name}.i = call i32 @llvm.umin.i32(i32 {b}, i32 -1)\n %{name} = bitcast i32 %{name}.i to float\n") }; @@ -2236,52 +2209,6 @@ fn a_fast_division_answers_metal_at_nans_and_denormals_on_every_profile() { kernel("fast_nan_by_two", 0x7FC0_0001, 0x4000_0000, nan), kernel("fast_zero_by_zero", 0, 0, nan), kernel("fast_inf_by_inf", 0x7F80_0000, 0x7F80_0000, nan), - kernel("fast_inf_by_2_127", 0x7F80_0000, 0x7F00_0000, nan), - kernel("fast_denormal_by_one", 0x0040_0000, 0x3F80_0000, 0), - kernel( - "fast_negative_denormal_by_two", - 0x8040_0000, - 0x4000_0000, - 0x8000_0000, - ), - kernel( - "fast_denormal_by_minus_one", - 0x0000_0001, - 0xBF80_0000, - 0x8000_0000, - ), - kernel("fast_denormal_by_denormal", 0x0040_0000, 0x0040_0000, nan), - kernel("fast_tiny_quotient", 0x0D80_0000, 0x4E80_0000, 0), - kernel( - "fast_negative_tiny_quotient", - 0x8D80_0000, - 0x4E80_0000, - 0x8000_0000, - ), - kernel( - "fast_tiny_quotient_negative_divisor", - 0x0D80_0000, - 0xCE80_0000, - 0x8000_0000, - ), - kernel( - "fast_quotient_below_the_grid_rounding", - 0x00FF_FFFF, - 0x4000_0000, - 0, - ), - kernel( - "fast_negative_quotient_below_the_grid_rounding", - 0x80FF_FFFF, - 0x4000_0000, - 0x8000_0000, - ), - kernel( - "fast_least_normal_quotient", - 0x0100_0000, - 0x4000_0000, - 0x0080_0000, - ), kernel("fast_six_by_three", 0x40C0_0000, 0x4040_0000, 0x4000_0000), ]; let Some(bitcode) = assemble("fast-divide-specials", &module(&ks)) else { @@ -2289,48 +2216,57 @@ fn a_fast_division_answers_metal_at_nans_and_denormals_on_every_profile() { }; for stem in every_profile() { let p = profile(&stem, exact_maths()).expect("profile"); + let metal_functions = + p.takes_driver_deviation(crate::error::DriverDeviation::MetalFloatFunctions); + let device_nans = + p.takes_driver_deviation(crate::error::DriverDeviation::MetalCanonicalNans); for kk in &ks { let what = format!("{} on {stem}", kk.name); let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - assert!( - a.precision.contains(&PrecisionNote::DeviceArithmetic), - "{what}: {:?}", - a.precision - ); for n in [ + PrecisionNote::DeviceArithmetic, + PrecisionNote::NativeDivision, PrecisionNote::DeviceDenormals, - PrecisionNote::DeviceNanEncoding, ] { assert!( - !a.precision.contains(&n), - "{what}: {n:?} in {:?}", + a.precision.contains(&n), + "{what}: {n:?} not in {:?}", a.precision ); } + assert!( + !a.precision.contains(&PrecisionNote::DeviceNanEncoding), + "{what}: {:?}", + a.precision + ); + // Where the device answers Metal's canonical NaN itself (the measured + // `MetalCanonicalNans`), the interpreter's NaN is no Metal's. + if device_nans && kk.want == Some(nan) { + continue; + } let got = interpret(&bitcode, kk.name, &p); - assert_eq!(Some(got), kk.want, "{what}: {got:#x}"); + assert_eq!( + Some(got), + kk.want, + "{what} (Metal's functions: {metal_functions}): {got:#x}" + ); } } } -/// An `fdiv` without `arcp` on `float` is Metal's precise division on every profile (a probe cases -/// 9496749c, 3921d3e2, and c10cba13): the correctly rounded quotient (lane 0x42aa3a21 / 0x44c80075 -/// gives 0x3D59E382, where `arcp` gives 0x3D59E381), a denormal operand read as a zero, a denormal -/// quotient flushed, also `(2 - 2^-23) / 2^127`, whose 24-bit quotient `2^-126 - 2^-150` the -/// denormal grid would round up to the smallest normal (c10cba13: Metal answers 0), and -/// `0x7FC00000` for `0 / 0`. The interpreter's `OpFDiv` keeps denormals (it answers `2^-127` for `1 -/// / 2^127`), so these lanes fail on the device's division. A `half` division is the routine's -/// under every flag set, `arcp` included, rounded once to `half` (4c363561, 54f0fe8e). The routine -/// is exact: no `DeviceArithmetic` note. +/// An `fdiv` without `arcp` on `float`, Metal's precise division, is the device's `OpFDiv` on +/// every profile (`arith.fdiv.native`), noted `NativeDivision`: here the interpreter's correctly +/// rounded quotient (lane 0x42aa3a21 / 0x44c80075 gives 0x3D59E382, Metal's word, where `arcp` +/// gives 0x3D59E381), and `0x7FC00000` for `0 / 0`. A `half` division under every flag set, +/// `arcp` included, is the `float` quotient rounded once to `half`. #[test] -fn a_division_without_arcp_is_metals_precise_division() { +fn a_division_without_arcp_is_the_devices_quotient() { let xy = format!( "{}{}", of("x", f32::from_bits(0x42AA_3A21)), of("y", f32::from_bits(0x44C8_0075)) ); - let one = of("one", 1.0); // 1 / 3 in `half`: 0x3555, whose `float` value is the stored word. let hxy = format!( "{}{} %hx = bitcast i16 %hxb to half\n %hy = bitcast i16 %hyb to half\n", @@ -2357,31 +2293,6 @@ fn a_division_without_arcp_is_metals_precise_division() { format!("{xy} %r = fdiv nnan ninf nsz contract float %x, %y\n"), 0x3D59_E382, ), - kernel( - "divide_to_a_denormal", - format!( - "{one}{} %r = fdiv float %one, %far\n", - of("far", 2f32.powi(127)) - ), - 0, - ), - kernel( - "divide_a_denormal", - format!( - "{one}{} %tiny = bitcast i32 %tb to float\n %r = fdiv float %tiny, %one\n", - oi("tb", 0x0040_0000) - ), - 0, - ), - kernel( - "divide_to_just_below_the_smallest_normal", - format!( - "{}{} %r = fdiv float %x, %y\n", - of("x", f32::from_bits(0x3FFF_FFFF)), - of("y", -(2f32.powi(127))) - ), - 0x8000_0000, - ), kernel( "divide_zero_by_zero", format!("{} %r = fdiv float %z, %z\n", of("z", 0.0)), @@ -2408,12 +2319,12 @@ fn a_division_without_arcp_is_metals_precise_division() { let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); assert!( - !a.precision.contains(&PrecisionNote::DeviceArithmetic), + a.precision.contains(&PrecisionNote::NativeDivision), "{what}: {:?}", a.precision ); assert!( - a.strategies.entries.contains_key("arith.fdiv.precise"), + a.strategies.entries.contains_key("arith.fdiv.native"), "{what}: {:?}", a.strategies.entries ); @@ -2493,14 +2404,14 @@ fn fast_sincos_flushes_past_the_last_quadrant() { } } -/// `float` `+ - *`, a comparison and `OpFmaKHR` record neither `DeviceDenormals` nor -/// `DeviceNanEncoding`: their denormals are read as Metal reads them, the device's where the -/// profile states it reads them so and flushed elsewhere, and their NaN is Metal's, the device's -/// where the profile states it and selected elsewhere; so does a remainder, Metal's composition of -/// those; the functions that answer Metal at denormals and NaNs themselves (`sign`), `half` -/// arithmetic, and the fused multiply-add routines record neither; nor does `fast::atan2`, whose -/// device quotient reads its operands as Metal does, flushed off the deviation. -/// The operands come from bits (`llvm.umin` of constants, bitcast), not from `float` arithmetic. +/// `float` `+ - *`, a comparison and `OpFmaKHR` record `DeviceDenormals` exactly where the +/// profile does not take `DriverDeviation::MetalFloatDenormals` (lavapipe), whose device keeps or +/// flushes them by its own controls; a remainder, the device's `OpFRem`, records it on every +/// profile; `sign`, which answers Metal at denormals itself, and `half` arithmetic record it on +/// none; `fast::atan2`, whose quotient is the device's division, records it off the deviation. +/// None records `DeviceNanEncoding`: the NaN is Metal's, the device's where the profile states it +/// and selected elsewhere. The operands come from bits (`llvm.umin` of constants, bitcast), not +/// from `float` arithmetic. #[test] fn device_float_environment_notes_follow_the_operations() { // 0x3fc03c00: a float near 1.5 whose low half is half 1.0. @@ -2509,32 +2420,29 @@ fn device_float_environment_notes_follow_the_operations() { let none = &[][..]; let ks = [ k("env_fadd", format!("{w} %s = fadd float %x, %x\n %r = bitcast float %s to i32\n"), (x + x).to_bits()), - // Metal's remainder: `x - x * trunc(x / x)`. + // The device's remainder of `x` by itself. k("env_frem", format!("{w} %s = frem float %x, %x\n %r = bitcast float %s to i32\n"), 0), k("env_sign", format!("{w} %s = call float @air.sign.f32(float %x)\n %r = bitcast float %s to i32\n"), 1.0f32.to_bits()), k("env_fcmp", format!("{w} %c = fcmp olt float %x, 0.0\n %r = zext i1 %c to i32\n"), 0), k("env_half", format!("{w} %t = trunc i32 %w to i16\n %h = bitcast i16 %t to half\n %s = fadd half %h, %h\n %u = bitcast half %s to i16\n %r = zext i16 %u to i32\n"), 0x4000), k("env_fma", format!("{w} %s = call float @air.fma.f32(float %x, float %x, float %x)\n %r = bitcast float %s to i32\n"), x.mul_add(x, x).to_bits()), - // `fast::atan2` selects Metal's NaN but returns the `atan` of the device's quotient: - // the device's `Atan` only in a fast-math entry on a device whose functions are - // Metal's, and the translation's routine here, an entry that keeps NaNs. The value is not - // checked here. + // `fast::atan2` selects Metal's NaN but returns the device's `Atan` of the device's + // quotient. The value is not checked here. Kernel { want: None, ..k("env_fast_atan2", format!("{w} %s = call float @air.fast_atan2.f32(float %x, float %x)\n %r = bitcast float %s to i32\n"), 0) }, ]; - // The notes each kernel records on moltenvk-m3 and on lavapipe. A `float` sum answers - // Metal's NaN and denormals on both: the device's on moltenvk-m3, selected and flushed on - // lavapipe. + // The notes each kernel records on moltenvk-m3 and on lavapipe. + let dd = &[PrecisionNote::DeviceDenormals][..]; let notes: [(&[PrecisionNote], &[PrecisionNote]); 7] = [ + (none, dd), + (dd, dd), (none, none), + (none, dd), (none, none), - (none, none), - (none, none), - (none, none), - (none, none), - (none, none), + (none, dd), + (none, dd), ]; let text = module(&ks).replace( DECLS, @@ -2568,20 +2476,20 @@ fn device_float_environment_notes_follow_the_operations() { } } -/// An `frem` on `float` is Metal's. Without every fast-math flag it is `x - y * trunc(x / y)` of -/// Metal's precise quotient, each step rounded (`arith.frem`): `frem(1, 0.1)` is `+0`, as on the M3 -/// Max, where the exact remainder is `0x3DCCCCCB`; with every flag it is Metal's `fast::fmod` -/// (`arith.fmod.fast`). Neither leaves the remainder to the device's `OpFRem`, and the one without -/// flags records no note. +/// An `frem` on `float` without every fast-math flag is the device's `OpFRem`, noted +/// `DeviceArithmetic` and `DeviceDenormals`, where Metal computes `x - y * trunc(x / y)` of its +/// precise quotient, each step rounded: `frem(1, 0.1)` is `+0` on the M3 Max, and here the +/// interpreter's exact remainder, `0x3DCCCCCB`. With every flag it is Metal's `fast::fmod` +/// (`arith.fmod.fast`), with no `OpFRem`. #[test] -fn a_float_remainder_is_metals() { +fn a_float_remainder_is_the_devices_without_every_flag() { let one = " %w = call i32 @llvm.umin.i32(i32 1065353216, i32 2147483647)\n %x = bitcast i32 %w to float\n"; let tenth = " %v = call i32 @llvm.umin.i32(i32 1036831949, i32 2147483647)\n %y = bitcast i32 %v to float\n"; let ks = [ k( "frem_precise", format!("{one}{tenth} %s = frem float %x, %y\n %r = bitcast float %s to i32\n"), - 0, + 0x3DCC_CCCB, ), Kernel { want: None, @@ -2604,27 +2512,27 @@ fn a_float_remainder_is_metals() { let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - assert_eq!(count_op(&words, crate::spv::Op::FRem), 0, "{what}: OpFRem"); - let census = if kk.name == "frem_precise" { - "arith.frem" - } else { - "arith.fmod.fast" - }; - assert!( - a.strategies.entries.contains_key(census), - "{what}: {:?}", - a.strategies.entries + let precise = kk.name == "frem_precise"; + assert_eq!( + count_op(&words, crate::spv::Op::FRem), + usize::from(precise), + "{what}: OpFRem" ); - if kk.name == "frem_precise" { + if precise { for n in [ PrecisionNote::DeviceArithmetic, PrecisionNote::DeviceDenormals, - PrecisionNote::DeviceNanEncoding, ] { - assert!(!a.precision.contains(&n), "{what}: {n:?}"); + assert!(a.precision.contains(&n), "{what}: {n:?}"); } let got = interpret(&bitcode, kk.name, &p); - assert_eq!(got, 0, "{what}: {got:#x}"); + assert_eq!(got, 0x3DCC_CCCB, "{what}: {got:#x}"); + } else { + assert!( + a.strategies.entries.contains_key("arith.fmod.fast"), + "{what}: {:?}", + a.strategies.entries + ); } } } @@ -2720,9 +2628,7 @@ fn glsl_fma_results(words: &[u32]) -> Vec { /// left undecorated; every other addition is decorated `NoContraction`, and every other multiply is /// the product rounded on its own, decorated `NoContraction`: an `OpFMul` where the profile's /// `float` functions are the device's, and `GLSL.std.450 Fma(a, b, -0.0)` where they are Metal's, -/// whose SPIR-V reaches Metal through SPIRV-Cross. Under `FloatMathsPolicy::Exact` the product's -/// check of a profile whose check is fused (`TinyCheck::Fused`) scales an operand by its own -/// multiply, `NoContraction` too, counted apart. The decoration matters where the addition may be +/// whose SPIR-V reaches Metal through SPIRV-Cross. The decoration matters where the addition may be /// fused: Mesa splits a contractable `Fma` into a multiply and an add and folds the `-0.0` away, /// and the multiply may then be fused with the `reassoc contract` add of `mul_strict_add_fast` /// (NIR's `fuse` option on older Mesa, or a backend such as ACO) unless the multiply is @@ -2731,7 +2637,6 @@ fn glsl_fma_results(words: &[u32]) -> Vec { /// one fused multiply-add, the multiply no operation of its own, 2^-24 on every profile. #[test] fn float_ops_without_contract_and_reassoc_are_no_contraction() { - use crate::lower::arith::denormal::{tiny_check, TinyCheck}; let inputs = format!( "{}{}", of("a", 1.0 + 2f32.powi(-12)), @@ -2781,19 +2686,6 @@ fn float_ops_without_contract_and_reassoc_are_no_contraction() { let (muls, decorated) = results_and_no_contraction(&words, crate::spv::Op::FMul); let (adds, _) = results_and_no_contraction(&words, crate::spv::Op::FAdd); let fmas = glsl_fma_results(&words); - // The product's check, where it is fused, scales an operand by its own multiply. - let scales = tiny_check_scales(&words); - let fused = tiny_check(&p) == Some(TinyCheck::Fused); - assert_eq!( - scales.len(), - usize::from(fused), - "{what}: the check's scaling" - ); - assert!( - scales.iter().all(|s| decorated.contains(s)), - "{what}: the check's scaling NoContraction: {scales:?}" - ); - let muls: Vec = muls.into_iter().filter(|m| !scales.contains(m)).collect(); let add_rewritable = kk.name == "mul_strict_add_fast"; // No unfused multiply here carries both flags: each is the profile's product with // `NoContraction`. @@ -2892,16 +2784,11 @@ fn arithmetic_the_air_lets_a_compiler_rewrite_notes_fast_math_rewrites() { } /// Growth report: the same chain of 16 float operations on `float`, `half`, and `bfloat`. Each -/// widened `half` operation adds its rounding; each `bfloat` operation adds its integer rounding. -/// The narrow chains grow over the `float` chain without the check of a product at `2^-126` -/// (native float maths, `FloatMathsPolicy::Native`); under exact float maths each of its eight -/// products adds at most that check (`denormal::tiny_product_words`). The measured words are -/// printed (`--nocapture`) and bounded so a growth regression fails. +/// widened `half` operation adds its rounding; each `bfloat` operation adds its integer rounding, +/// over the `float` chain. The measured words are printed (`--nocapture`) and bounded so a growth +/// regression fails. #[test] fn narrow_float_module_growth_is_bounded() { - use crate::device::FloatMathsPolicy; - use crate::lower::arith::denormal::{tiny_product_words, TinyCheck}; - use crate::lower::arith::legal::{FloatFmt, Form, Held}; let chain = |ty: &str| -> String { let (enter, leave) = match ty { "float" => ( @@ -2937,15 +2824,6 @@ fn narrow_float_module_growth_is_bounded() { let Some(bitcode) = assemble("growth", &module(&ks)) else { return; }; - let plain = DevicePolicy { - float_maths: FloatMathsPolicy::Native, - ..exact_maths() - }; - let float = Form { - held: Held::Float(FloatFmt::F32), - lanes: 1, - }; - let checks = 8 * tiny_product_words(float, TinyCheck::Bits) as usize; for stem in PROFILES { let words_on = |policy: DevicePolicy, kk: &Kernel| { let p = profile(stem, policy).expect("profile"); @@ -2955,26 +2833,15 @@ fn narrow_float_module_growth_is_bounded() { a.module.words.len() }; let p = profile(stem, exact_maths()).expect("profile"); - let checked = words_on(exact_maths(), &ks[0]); - let words = [ - words_on(plain, &ks[0]), - words_on(exact_maths(), &ks[1]), - words_on(exact_maths(), &ks[2]), - ]; + let words = ks.each_ref().map(|kk| words_on(exact_maths(), kk)); eprintln!( - "half and bfloat growth on {stem}: float {} words ({checked} with its products' \ - checks), half {} ({:+}), bfloat {} ({:+})", + "half and bfloat growth on {stem}: float {} words, half {} ({:+}), bfloat {} ({:+})", words[0], words[1], words[1] as i64 - words[0] as i64, words[2], words[2] as i64 - words[0] as i64 ); - assert!( - words[0] <= checked && checked <= words[0] + checks, - "{stem}: float {} words, {checked} with its products' checks", - words[0] - ); // Half: through the device's measured quantize, per multiply and per narrowing // conversion a six-instruction rounding with the denormal arithmetic (at most 32 words), // and per sum a three-instruction one without it (at most 16 words), plus the conversions' @@ -3013,15 +2880,15 @@ fn narrow_float_module_growth_is_bounded() { /// /// The chain: one `fptrunc`, eight `fadd`, and eight `fmul` on `half`, strict and `fast`. The /// `fast` chain's seven multiplies whose one use is the next addition are fused into it: each pair -/// is the device's `float` `Fma` rounded to `half` (`fma::Route::Native`), whose rounding carries -/// the denormal arithmetic as a product's does, so the chain keeps the first addition's, the last -/// multiply's, the conversion's, and each pair's roundings. On a profile whose driver computes a -/// 16-bit `Fma` as Metal's `half` `fma` (moltenvk-m3) each pair is that `Fma` instead, inline, on -/// its operands converted to 16 bits and its result widened, all exactly (four `OpFConvert`, the -/// module's one 16-bit float type), so the chain keeps the other three roundings. On a profile -/// whose driver's 16-bit `+ - *`, kept apart, is Metal's (moltenvk-m3), each `fadd` and `fmul` that -/// rounds is that instruction, between two narrowings and a widening (three `OpFConvert`), and -/// rounds nothing itself: the conversion's rounding alone is left to the module. +/// is the device's `Fma` on the operands held in `float`, its result rounded to `half` with the +/// denormal arithmetic a product's rounding carries, so the chain keeps the first addition's, the +/// last multiply's, the conversion's, and the seven pairs' roundings. On a profile whose driver +/// computes a 16-bit `Fma` as Metal's `half` `fma` (moltenvk-m3) each pair is that `Fma` instead, +/// inline, on its operands converted to 16 bits and its result widened, all exactly (four +/// `OpFConvert`, the module's one 16-bit float type), so the chain keeps the other three roundings. +/// On a profile whose driver's 16-bit `+ - *`, kept apart, is Metal's (moltenvk-m3), each `fadd` +/// and `fmul` that rounds is that instruction, between two narrowings and a widening (three +/// `OpFConvert`), and rounds nothing itself: the conversion's rounding alone is left to the module. #[test] fn half_rounding_follows_the_operation() { let chain = |fast: bool| -> String { @@ -3073,7 +2940,7 @@ fn half_rounding_follows_the_operation() { ); let (q, c, r) = match (kk.name == "fast_chain", f16) { (true, true) => (3, 7 * 4, 2), - (true, false) => (10, 0, 9), + (true, false) => (3 + 7, 0, 2 + 7), (false, _) => (17, 0, 9), }; // With `shaderFloat16` each rounding is the device's conversion and its widening, with @@ -3244,9 +3111,8 @@ fn no_rounding_requires_the_conversion_fact() { /// Only a `half` result that is a value of the format wherever it lies below the smallest normal /// half skips the denormal arithmetic. A square root and `fract`'s difference round through /// `OpQuantizeToF16` alone, and an integer converted to `half` rounds by integer arithmetic with -/// neither; a transcendental, -/// `ldexp`, a quotient, and the rounding of each fused sum (`fmuladd`'s, and `mix`'s two fused -/// multiply-adds', each the device's `float` `Fma` rounded to `half`) keep one `RoundEven` each, since +/// neither; a transcendental, `ldexp`, a quotient, and the one rounding of a fused sum (`fmuladd` +/// and `mix`, the device's `Fma` and `FMix` in `float`) keep one `RoundEven` each, since /// their `f32` result below `2^-14` is off the `2^-24` grid (half `exp(-10)` is about `4.54e-5`). /// The counts pin which steps may take `round_exact_below_normal`. On a profile whose driver /// computes a 16-bit `Fma` as Metal's `half` `fma` (moltenvk-m3), a fused sum rounds nothing @@ -3277,8 +3143,8 @@ fn only_an_exact_half_result_skips_the_denormal_rounding() { ( "half_mix", "call half @air.mix.f16(half %h, half %g, half %u)", - 2, - 2, + 1, + 1, ), ( "half_fmuladd", @@ -3502,11 +3368,10 @@ fn float_ops_without_fast_flags_preserve_signed_zero_inf_nan() { let note = a.precision.contains(&PrecisionNote::DeviceSignedZeroInfNan); let mode = declares_signed_zero_inf_nan(&words, 32); if kk.name == "fast_mul" { - let checked = crate::lower::arith::denormal::checks_tiny_products(&p); assert_eq!( (mode, note), - (checked && supported, checked && !supported), - "{what}: fast needs preservation only for its product's check" + (false, false), + "{what}: fast needs no preservation" ); } else { assert_eq!((mode, note), (supported, !supported), "{what}"); @@ -3521,18 +3386,11 @@ fn float_ops_without_fast_flags_preserve_signed_zero_inf_nan() { ); } -/// Under `FloatMathsPolicy::Exact` a fused multiply-add the translation computes by a routine (in -/// `double` or in integers without `OpFmaKHR`, and a checked `OpFmaKHR`'s small results) answers -/// Metal's zero of its sign through float instructions, so a `fast` entry that calls one declares -/// `SignedZeroInfNanPreserve` at 32 bits, and at 64 for a routine in `double`, where the profile -/// supports it, else notes `DeviceSignedZeroInfNan`: without the mode Vulkan lets a device answer a -/// zero of either sign (Metal's `fma(+0, 100, +0)` is `+0`). A `half` one calls no routine, so its -/// kernel never declares it. Nothing else in the kernels needs the mode: their operands are bits, -/// their calls `fast`. Where the profile's functions are Metal's own (MoltenVK), and under the -/// default policy, neither kernel declares it. +/// A `fast` entry's fused multiply-add is the device's instruction on every profile (`OpFmaKHR`, +/// the device's `Fma`, or a `half` one's 16-bit form), so no kernel declares +/// `SignedZeroInfNanPreserve`, at 32 bits or 64: their operands are bits, their calls `fast`. #[test] -fn fused_multiply_add_routines_keep_zero_signs() { - use crate::lower::arith::fma::{self, Route}; +fn fused_multiply_adds_keep_no_zero_signs() { use crate::spirv::testing::committed_profiles_with; let ks = [ Kernel { @@ -3571,51 +3429,9 @@ fn fused_multiply_add_routines_keep_zero_signs() { let Some(bitcode) = assemble("fma-zero-signs", &text) else { return; }; - // The routes and widths some profile keeps zero signs at (by the mode or the note). - let mut kept = std::collections::BTreeSet::new(); - for (stem, p) in committed_profiles_with(exact_maths()).expect("profiles") { - let exact = p.fields().float_functions == FloatFunctions::Device; - let r = fma::routes(&p); - let fc = p.fields().float_controls; - let supported = [ - fc.f32.signed_zero_inf_nan_preserve, - fc.f64.signed_zero_inf_nan_preserve, - ]; - for kk in &ks { - let what = format!("{} on {stem}", kk.name); - // The kernel's route, whether it calls a routine, and whether that one is in `double`. - let (route, routine) = if kk.float { - let routine = matches!(r.float, Route::Wide | Route::Soft) || r.tiny.is_some(); - let double = r.float == Route::Wide || r.tiny == Some(Route::Wide); - (r.float, [routine, double]) - } else { - (r.half, [false, false]) - }; - let wanted = routine.map(|w| w && exact); - let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let (_, words) = - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - for (i, width) in [32, 64].into_iter().enumerate() { - let mode = declares_signed_zero_inf_nan(&words, width); - assert_eq!(mode, wanted[i] && supported[i], "{what}: mode {width}"); - if wanted[i] { - kept.insert((route, width)); - } - } - let unsupported = (0..2).any(|i| wanted[i] && !supported[i]); - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceSignedZeroInfNan), - unsupported, - "{what}: note" - ); - } - } - for want in [(Route::Wide, 32), (Route::Wide, 64), (Route::Soft, 32)] { - assert!(kept.contains(&want), "no profile keeps {want:?}: {kept:?}"); - } for (stem, p) in committed_profiles_with(DevicePolicy::default()).expect("profiles") { for kk in &ks { - let what = format!("{} on {stem} by default", kk.name); + let what = format!("{} on {stem}", kk.name); let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); @@ -3632,9 +3448,8 @@ fn fused_multiply_add_routines_keep_zero_signs() { /// A float to integer `air.convert` converts NaN to 0, telling it by `OpIsNan` only where the entry /// declares `SignedZeroInfNanPreserve` for `float`, and by its bits where it does not (a device may /// assume there that no operand is a NaN, in `OpIsNan` and `NClamp` alike): a `fast` entry has no -/// `OpIsNan`. The NaN is a sum's: a product's check at `±2^-126` would keep zero signs under -/// `FloatMathsPolicy::Exact`. (AIR has no `double` conversion; `math::convert`'s unit tests read a -/// 64-bit container's NaN by its two words.) +/// `OpIsNan`. The NaN is a sum's. (AIR has no `double` conversion; `math::convert`'s unit tests +/// read a 64-bit container's NaN by its two words.) #[test] fn a_convert_tells_a_nan_by_its_bits_where_the_entry_may_assume_none() { let float = |name: &'static str, flags: &str| { @@ -3692,198 +3507,16 @@ fn with_float_functions(stem: &str, metal: bool) -> DeviceProfile { .clone() } -/// A precise `sinpi`, `cospi`, or `tanpi` call (and a `half` one) is Metal's own form, a routine -/// the entry calls, with no `GLSL.std.450 Sin` or `Cos`, whatever the profile's typed fact says of -/// the device's `float` functions (its driver's deviation `MetalFloatFunctions`): Metal's are none -/// of the instructions SPIRV-Cross emits, so no device answers them. A fast call (`air.fast_sinpi`) -/// is the routine too without the fact; with it, the exact reduction around the device's `Sin` and -/// `Cos`, within Apple's fast bound (the orchestrator's ruling of 2026-10-07). On two profiles that -/// differ only in the fact; the routines' values are within their few ulp on the interpreter (which -/// leaves a device's `Sin` and `Cos` unmodelled). +/// An `arcp` division is the device's `OpFDiv(x, y)` itself on every profile, which MoltenVK hands +/// Metal's compiler as the AIR's own fast `x / y` (Metal's compiler does not treat `x * (1.0 / y)` +/// the same way: case 24c263bb's `(a * 255) / a` was 255 on Metal and 254 as `x` times the +/// device's `OpFDiv(1, y)`). Where the device's `float` division is Metal's (its driver's +/// deviation `MetalFloatFunctions`) and Metal compiles the entry with fast math (it declares no +/// `SignedZeroInfNanPreserve`), the quotient is Metal's own and records no note; elsewhere it +/// records `DeviceArithmetic`. The interpreter's `OpFDiv` is correctly rounded: `RN(1e10 / 3)` is +/// `0x4f46aea1`. #[test] -fn pi_scaled_functions_call_metals_routines_but_a_fast_call_on_metals_device() { - let fast_inputs = |s: String| s.replace("fadd float", "fadd fast float"); - let kernel = |name: &'static str, body: String| Kernel { - name, - body, - float: true, - want: None, - needs: &[], - note: None, - }; - let x = of("x", 0.3); - let ks = [ - kernel( - "pi_sinpi_precise_entry", - format!("{x} %r = call float @air.sinpi.f32(float %x)\n"), - ), - kernel( - "pi_cospi_precise_entry", - format!("{x} %r = call float @air.cospi.f32(float %x)\n"), - ), - kernel( - "pi_tanpi_precise_entry", - format!("{x} %r = call float @air.tanpi.f32(float %x)\n"), - ), - kernel( - "pi_sinpi_fast_entry", - fast_inputs(format!( - "{x} %r = call fast float @air.fast_sinpi.f32(float %x)\n" - )), - ), - kernel( - "pi_half_sinpi_fast_entry", - fast_inputs(format!( - "{x} %h = fptrunc float %x to half\n %s = call fast half @air.sinpi.f16(half %h)\n %r = fpext half %s to float\n" - )), - ), - ]; - // The `half` call's operand is 0.3 rounded to `half`, so its answer is within a `half` ulp - // (2^13 `float` ulps) of the `float` one. - let pi03 = std::f64::consts::PI * f64::from(0.3f32); - let exact = [ - (pi03.sin(), 3.0), - (pi03.cos(), 3.0), - (pi03.tan(), 5.0), - (pi03.sin(), 3.0), - (pi03.sin(), 8192.0), - ]; - let text = module(&ks).replace( - DECLS, - &format!( - "{DECLS}declare float @air.sinpi.f32(float)\ndeclare float @air.cospi.f32(float)\ndeclare float @air.tanpi.f32(float)\ndeclare float @air.fast_sinpi.f32(float)\ndeclare half @air.sinpi.f16(half)\n" - ), - ); - let Some(bitcode) = assemble("pi_scaled", &text) else { - return; - }; - // `GLSL.std.450 Sin` and `Cos` are instructions 13 and 14 of the set. - let sin_cos = |words: &[u32]| { - count_ops(words, |w| { - w[0] & 0xFFFF == crate::spv::Op::ExtInst as u32 - && w.len() > 4 - && (w[4] == 13 || w[4] == 14) - }) - }; - for metal in [true, false] { - let p = with_float_functions("moltenvk-m3", metal); - for (kk, (v, tolerance)) in ks.iter().zip(exact) { - let what = format!("{} with the fact {metal}", kk.name); - let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let (_, words) = - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let calls = count_op(&words, crate::spv::Op::FunctionCall); - if metal && kk.name == "pi_sinpi_fast_entry" { - assert_eq!(calls, 0, "{what}: calls a routine"); - assert!(sin_cos(&words) >= 2, "{what}: no device Sin and Cos"); - // The device's `Sin` and `Cos` are not the interpreter's to model. - continue; - } - assert!(calls >= 1, "{what}: does not call the routine"); - assert_eq!(sin_cos(&words), 0, "{what}: a device Sin or Cos"); - let got = f64::from(f32::from_bits(interpret(&bitcode, kk.name, &p))); - let ulp = f64::from(f32::EPSILON) * 2f64.powi(v.abs().log2().floor() as i32); - assert!( - (got - v).abs() <= tolerance * ulp, - "{what}: {got} against {v} ({} ulp)", - (got - v).abs() / ulp - ); - } - } -} - -/// The fast reciprocal that an `arcp` division, `air.fast_tanh`, and `air.fast_fmod` divide by is -/// chosen by the profile's typed fact alone. Where the device's `float` functions and division are -/// Metal's own (its driver's deviation `MetalFloatFunctions`), it is the device's `OpFDiv(1, y)`: -/// Metal's fast reciprocal where Metal compiles the module with fast math, and `RN(1 / y)` where -/// the module turns it off. Elsewhere, on a profile with `OpFmaKHR`, it is `RN(1 / y)` refined from -/// that estimate by four more `OpFmaKHR`, counted outside the math library's routines of one -/// operand (`fast::tanh`'s `exp2` is a routine without the fact, whose exact products are -/// `OpFmaKHR` too). The test uses two `moltenvk-m3` profiles that differ only in the fact. The -/// division's and `fmod`'s values are the interpreter's on both: at these operands the device's -/// reciprocal and `RN(1 / y)` agree. -#[test] -fn fast_division_follows_the_metal_float_functions_fact() { - let kernel = |name: &'static str, body: String, want: Option| Kernel { - name, - body, - float: true, - want: want.map(f32::to_bits), - needs: &[], - note: None, - }; - let (x, y) = (of("x", 1e10), of("y", 3.0)); - let ks = [ - kernel( - "fast_division_arcp", - format!("{x}{y} %r = fdiv arcp float %x, %y\n"), - Some(1e10f32 * (1.0f32 / 3.0)), - ), - kernel( - "fast_division_tanh", - format!( - "{} %r = call fast float @air.fast_tanh.f32(float %x)\n", - of("x", 0.5) - ), - None, - ), - kernel( - "fast_division_fmod", - format!("{x}{y} %r = call fast float @air.fast_fmod.f32(float %x, float %y)\n"), - Some(-512.0), - ), - ]; - let text = module(&ks).replace( - DECLS, - &format!( - "{DECLS}declare float @air.fast_tanh.f32(float)\ndeclare float @air.fast_fmod.f32(float, float)\n" - ), - ); - let Some(bitcode) = assemble("fast-division-fact", &text) else { - return; - }; - for kk in &ks { - let mut khr = [0usize; 2]; - for (i, metal) in [true, false].into_iter().enumerate() { - let p = with_float_functions("moltenvk-m3", metal); - let what = format!("{} with the fact {metal}", kk.name); - let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let (_, words) = - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - assert!( - a.precision.contains(&PrecisionNote::DeviceArithmetic), - "{what}: {:?}", - a.precision - ); - khr[i] = count_op(&without_math_routines(&words), crate::spv::Op::FmaKHR); - // `fast::tanh`'s `exp2` is the device's, which the interpreter leaves unmodelled. - if kk.want.is_some() { - let got = interpret(&bitcode, kk.name, &p); - assert_eq!(Some(got), kk.want, "{what}: {got:#x}"); - } - } - // The refinement's four `OpFmaKHR`, and nothing else, tell the two apart. - assert_eq!( - khr[1], - khr[0] + 4, - "{}: OpFmaKHR with the fact and without", - kk.name - ); - } -} - -/// Where the device's `float` division is Metal's (its driver's deviation `MetalFloatFunctions`) -/// and Metal compiles the entry with fast math (it declares no `SignedZeroInfNanPreserve`), an -/// `arcp` division is the device's `OpFDiv(x, y)` itself, which MoltenVK hands Metal's compiler as -/// the AIR's own fast `x / y`. Metal's compiler does not treat `x * (1.0 / y)` the same way: case -/// 24c263bb's `(a * 255) / a` was 255 on Metal and 254 as `x` times the device's `OpFDiv(1, y)`. In -/// an entry that declares the mode, and on a profile without the fact, the -/// quotient stays `x` times the profile's reciprocal, a call of the fast division's routine. The -/// interpreter's `OpFDiv` is correctly rounded, so `1e10 / 3` tells the forms apart: `RN(1e10 / 3)` -/// is `0x4f46aea1` and `1e10 · RN(1 / 3)` is `0x4f46aea2`. The device's quotient, Metal's own, -/// records no note; the routine's records `DeviceArithmetic`. -#[test] -fn a_fast_division_is_the_devices_in_a_fast_math_entry_where_division_is_metals() { +fn a_fast_division_is_the_device_s_quotient() { // The fast-math entries' opaque inputs are `fast` too, so nothing there needs preservation. let fast_inputs = |s: String| s.replace("fadd float", "fadd fast float"); let (x, y) = (of("x", 1e10), of("y", 3.0)); @@ -3929,7 +3562,7 @@ fn a_fast_division_is_the_devices_in_a_fast_math_entry_where_division_is_metals( !fast_math, "{what}: SignedZeroInfNanPreserve" ); - // Metal's own quotient in a fast entry records no note; the routine's does. + // Metal's own quotient in a fast entry records no note; the device's elsewhere does. let device = metal && fast_math; assert_eq!( a.precision.contains(&PrecisionNote::DeviceArithmetic), @@ -3937,340 +3570,19 @@ fn a_fast_division_is_the_devices_in_a_fast_math_entry_where_division_is_metals( "{what}: {:?}", a.precision ); - // The device's form is the entry's one `OpFDiv`, and the module defines no routine; - // the other is one call of the routine, which holds the reciprocal's `OpFDiv`. + // The entry's one `OpFDiv`, and the module defines no routine. let form = ( count_op(&words, crate::spv::Op::Function), count_op(&words, crate::spv::Op::FunctionCall), count_op(&words, crate::spv::Op::FDiv), ); - assert_eq!(form, if device { (1, 0, 1) } else { (2, 1, 1) }, "{what}"); + assert_eq!(form, (1, 0, 1), "{what}"); let got = interpret(&bitcode, kk.name, &p); - let want: u32 = if device { 0x4F46_AEA1 } else { 0x4F46_AEA2 }; - assert_eq!(got, want, "{what}: {got:#x}"); + assert_eq!(got, 0x4F46_AEA1, "{what}: {got:#x}"); } } } -/// On a profile whose `float` functions are Metal's own (`moltenvk-m3` states it), a call in the -/// math mode Metal compiles the entry in is the device's instruction, and a call in the other mode -/// (`precise::atan` in a fast-math entry, `fast::atan` or `fast::acos` in an entry that keeps NaNs) -/// calls the translation's routine; `atan2` is the device's in either, since MoltenVK's is always -/// `precise::atan2`. The same description without the fact takes the routine for every call, as -/// `lavapipe` does: the fact flips the emission. `exp10`, which no instruction is, is Metal's -/// composition of the device's `exp2` with the fact and its routine without, and `fast::rsqrt`, the -/// device's everywhere, is the same word for word with and without the fact. Precise `sin`, `sqrt`, -/// `rsqrt`, and `fmod`, whose fast calls are their own functions, are the device's only in an entry -/// that keeps NaNs; `fast::rsqrt` is the device's everywhere; `fast::sin` and `fast::cos` are the -/// device's in either mode where its functions are Metal's (and elsewhere call the routine that -/// answers past `π`), and so is `fast::tan`'s formula of them in an entry that keeps NaNs, whose -/// quotient calls the fast division's routine on every profile. A `half` `atan` calls its own -/// form's routine on every profile, and so does a precise `sinpi` -/// (`pi_scaled_functions_call_metals_routines_but_a_fast_call_on_metals_device`). A routine's value -/// is within an ulp of the exact one on the interpreter (a correctly rounded root within half of -/// one, `fmod` exact, `fast::atan` Metal's own word), and the plan's estimate bounds the module's -/// words. -#[test] -fn math_library_routines_follow_the_device_fact_and_the_entry_mode() { - let fast_inputs = |s: String| s.replace("fadd float", "fadd fast float"); - let kernel = |name: &'static str, body: String| Kernel { - name, - body, - float: true, - want: None, - needs: &[], - note: None, - }; - let x = of("x", 0.5); - let yx = format!("{}{}", of("y", 0.5), of("x", 0.75)); - let ks = [ - kernel( - "libm_atan_precise_entry", - format!("{x} %r = call float @air.atan.f32(float %x)\n"), - ), - kernel( - "libm_fast_atan_fast_entry", - fast_inputs(format!( - "{x} %r = call fast float @air.fast_atan.f32(float %x)\n" - )), - ), - kernel( - "libm_fast_atan_precise_entry", - format!("{x} %r = call fast float @air.fast_atan.f32(float %x)\n"), - ), - kernel( - "libm_atan_fast_entry", - fast_inputs(format!( - "{x} %r = call fast float @air.atan.f32(float %x)\n" - )), - ), - kernel( - "libm_asin_precise_entry", - format!("{x} %r = call float @air.asin.f32(float %x)\n"), - ), - kernel( - "libm_fast_acos_precise_entry", - format!("{x} %r = call fast float @air.fast_acos.f32(float %x)\n"), - ), - kernel( - "libm_atan2_fast_entry", - fast_inputs(format!( - "{yx} %r = call fast float @air.atan2.f32(float %y, float %x)\n" - )), - ), - kernel( - "libm_exp10_precise_entry", - format!("{x} %r = call float @air.exp10.f32(float %x)\n"), - ), - // A `half` function is precise in both modes: the device's only in an entry that keeps - // NaNs (the widenings carry no flags and need nothing preserved). - kernel( - "libm_half_atan_fast_entry", - fast_inputs(format!( - "{x} %h = fptrunc float %x to half\n %s = call fast half @air.atan.f16(half %h)\n %r = fpext half %s to float\n" - )), - ), - kernel( - "libm_half_atan_precise_entry", - format!( - "{x} %h = fptrunc float %x to half\n %s = call half @air.atan.f16(half %h)\n %r = fpext half %s to float\n" - ), - ), - kernel( - "libm_sin_precise_entry", - format!("{x} %r = call float @air.sin.f32(float %x)\n"), - ), - kernel( - "libm_sin_fast_entry", - fast_inputs(format!("{x} %r = call fast float @air.sin.f32(float %x)\n")), - ), - kernel( - "libm_sincos_precise_entry", - format!( - " %c = alloca float, align 4\n{x} %s = call float @air.sincos.f32(float %x, ptr %c)\n %cv = load float, ptr %c, align 4\n %r = fadd float %s, %cv\n" - ), - ), - // `fast::sincos`: Metal's fast functions, the device's where its functions are Metal's in - // either mode, and elsewhere the device's inside `[-π, π]` and the routine past it. - kernel( - "libm_fast_sincos_fast_entry", - fast_inputs(format!( - " %c = alloca float, align 4\n{x} %s = call fast float @air.fast_sincos.f32(float %x, ptr %c)\n %cv = load float, ptr %c, align 4\n %r = fadd fast float %s, %cv\n" - )), - ), - // `fast::tan`, not the precise routine: Apple's formula of the fast functions, or the - // device's `Tan` where it is Metal's fast one. - kernel( - "libm_fast_tan_fast_entry", - fast_inputs(format!( - "{x} %r = call fast float @air.fast_tan.f32(float %x)\n" - )), - ), - kernel( - "libm_sinpi_precise_entry", - format!( - "{} %r = call float @air.sinpi.f32(float %x)\n", - of("x", 0.3) - ), - ), - kernel( - "libm_sqrt_precise_entry", - format!( - "{} %r = call float @air.sqrt.f32(float %x)\n", - of("x", 2.0) - ), - ), - kernel( - "libm_sqrt_fast_entry", - fast_inputs(format!( - "{} %r = call fast float @air.sqrt.f32(float %x)\n", - of("x", 2.0) - )), - ), - kernel( - "libm_rsqrt_fast_entry", - fast_inputs(format!( - "{} %r = call fast float @air.rsqrt.f32(float %x)\n", - of("x", 2.0) - )), - ), - // `fast::rsqrt`: Metal's fast function, the device's within its bound. - kernel( - "libm_fast_rsqrt_fast_entry", - fast_inputs(format!( - "{} %r = call fast float @air.fast_rsqrt.f32(float %x)\n", - of("x", 2.0) - )), - ), - kernel( - "libm_fast_sin_precise_entry", - format!("{x} %r = call fast float @air.fast_sin.f32(float %x)\n"), - ), - kernel( - "libm_fast_sin_past_pi_fast_entry", - fast_inputs(format!( - "{} %r = call fast float @air.fast_sin.f32(float %x)\n", - of("x", 4.0) - )), - ), - kernel( - "libm_fast_tan_precise_entry", - format!("{x} %r = call fast float @air.fast_tan.f32(float %x)\n"), - ), - kernel( - "libm_fmod_fast_entry", - fast_inputs(format!( - "{}{} %r = call fast float @air.fmod.f32(float %x, float %y)\n", - of("x", 7.5), - of("y", 2.0) - )), - ), - ]; - // Per kernel: the exact value (`None`: not measured here), its tolerance in `float` ulps (a - // `half` ulp is 2^13 of them), and its routine (`Mode(m)`: a device function, whose routine - // `moltenvk-m3` calls when `m`, `sinpi`'s on every profile; `Never`: no routine, the same - // module on both sides of the fact; `Divides`: `fast::tan`'s formula in an entry that keeps - // NaNs, which calls the fast division's routine on every profile, and the fast sine's and - // cosine's routines only without the fact). - #[derive(Clone, Copy)] - enum Routine { - Mode(bool), - Never, - Divides, - } - let sin_pi_03 = (std::f64::consts::PI * f64::from(0.3f32)).sin(); - // Metal's fast `atan` of 0.5, its own word: 1.83 ulp above the exact value. - let fast_atan_half = f64::from(f32::from_bits(0x3EED_633A)); - let expect: [(Option, f64, Routine); 24] = [ - (Some(0.5f64.atan()), 1.0, Routine::Mode(false)), - (Some(fast_atan_half), 0.0, Routine::Mode(false)), - (Some(fast_atan_half), 0.0, Routine::Mode(true)), - (Some(0.5f64.atan()), 1.0, Routine::Mode(true)), - (Some(0.5f64.asin()), 1.0, Routine::Mode(false)), - (Some(0.5f64.acos()), 1.0, Routine::Mode(true)), - // Metal's precise `atan2` is its own form, 1.31 ulp from the exact value here. - (Some(0.5f64.atan2(0.75)), 2.0, Routine::Mode(false)), - (Some(10f64.powf(0.5)), 1.0, Routine::Mode(false)), - // A `half` `atan` is Metal's own `half` form's routine on every profile. - (Some(0.5f64.atan()), 4096.0, Routine::Mode(true)), - (Some(0.5f64.atan()), 4096.0, Routine::Mode(true)), - (Some(0.5f64.sin()), 1.0, Routine::Mode(false)), - (Some(0.5f64.sin()), 1.0, Routine::Mode(true)), - (Some(0.5f64.sin() + 0.5f64.cos()), 2.0, Routine::Mode(false)), - (None, 0.0, Routine::Mode(false)), - (None, 0.0, Routine::Mode(false)), - // Metal's own form's routine on every profile. - (Some(sin_pi_03), 3.0, Routine::Mode(true)), - (Some(2f64.sqrt()), 0.5, Routine::Mode(false)), - (Some(2f64.sqrt()), 0.5, Routine::Mode(true)), - (Some(1.0 / 2f64.sqrt()), 0.5, Routine::Mode(true)), - (None, 0.0, Routine::Never), - (None, 0.0, Routine::Mode(false)), - (Some(4f64.sin()), 1.0, Routine::Mode(false)), - (None, 0.0, Routine::Divides), - (Some(1.5), 0.0, Routine::Mode(true)), - ]; - let text = module(&ks).replace( - DECLS, - &format!( - "{DECLS}declare float @air.atan.f32(float)\ndeclare float @air.fast_atan.f32(float)\ndeclare float @air.asin.f32(float)\ndeclare float @air.fast_acos.f32(float)\ndeclare float @air.atan2.f32(float, float)\ndeclare float @air.exp10.f32(float)\ndeclare half @air.atan.f16(half)\ndeclare float @air.fast_sincos.f32(float, ptr)\ndeclare float @air.fast_tan.f32(float)\ndeclare float @air.fast_sin.f32(float)\ndeclare float @air.sinpi.f32(float)\ndeclare float @air.sqrt.f32(float)\ndeclare float @air.rsqrt.f32(float)\ndeclare float @air.fast_rsqrt.f32(float)\ndeclare float @air.fmod.f32(float, float)\n" - ), - ); - let Some(bitcode) = assemble("libm", &text) else { - return; - }; - let stated = profile("moltenvk-m3", exact_maths()).expect("profile"); - assert_eq!( - stated.fields().float_functions, - with_float_functions("moltenvk-m3", true) - .fields() - .float_functions - ); - let profiles = [ - ("moltenvk-m3", stated), - ( - "moltenvk-m3 without the fact", - with_float_functions("moltenvk-m3", false), - ), - ( - "lavapipe", - profile("lavapipe", exact_maths()).expect("profile"), - ), - ]; - let mut composition: Vec<(&str, usize, Vec)> = Vec::new(); - for (column, (label, p)) in profiles.iter().enumerate() { - for (kk, (exact, tolerance, routine)) in ks.iter().zip(expect) { - let what = format!("{} on {label}", kk.name); - let a = compile(&bitcode, kk.name, p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let (_, words) = link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let plan = plan_bitcode( - &bitcode, - EntryRef::Name(kk.name), - &FunctionConstantValues::defaults(), - p, - &LowerInputs::new(), - &mut meter(), - ) - .unwrap_or_else(|e| panic!("{what}: plan: {e}")); - assert!( - plan.estimate.words >= a.module.words.len() as u64, - "{what}: estimate {} < emitted {}", - plan.estimate.words, - a.module.words.len() - ); - // The fact is the device's: with it, Metal's mode rule; without it, every routine. - let metal = column == 0; - let calls = match routine { - Routine::Mode(on_metal) => !metal || on_metal, - Routine::Divides => true, - Routine::Never => false, - }; - assert_eq!( - count_op(&words, crate::spv::Op::FunctionCall) > 0, - calls, - "{what}: calls a routine" - ); - if matches!(routine, Routine::Divides) { - // The division's call; and the sine's and cosine's where they are routines, with - // the fused step's from inside them where the profile has no `OpFmaKHR`. - let n = count_op(&words, crate::spv::Op::FunctionCall); - if metal { - assert_eq!(n, 1, "{what}: calls"); - } else { - assert!(n >= 3, "{what}: {n} calls"); - } - } - if matches!(routine, Routine::Never) { - composition.push((kk.name, column, a.module.words.clone())); - } - match exact { - Some(v) if calls => { - let got = f64::from(f32::from_bits(interpret(&bitcode, kk.name, p))); - let ulp = f64::from(f32::EPSILON) * 2f64.powi(v.abs().log2().floor() as i32); - assert!( - (got - v).abs() <= tolerance * ulp, - "{what}: {got} against {v} ({} ulp)", - (got - v).abs() / ulp - ); - } - _ => {} - } - } - } - // A composition's module is the same on both sides of the fact. - for (name, column, words) in &composition { - if *column == 0 { - let without = composition - .iter() - .find(|(n, c, _)| n == name && *c == 1) - .expect("the module without the fact"); - assert!(words == &without.2, "{name} changes with the fact"); - } - } -} - -// ---- Metal's NaN ---- - /// `%x` = an opaque `float` with bits `b` (any pattern, NaNs included): `llvm.umin` of a constant /// and `-1`, bitcast. fn ob(name: &str, b: u32) -> String { @@ -4427,17 +3739,20 @@ fn the_canonical_nan_follows_the_device_fact() { // ---- Metal's float denormals ---- -/// Metal reads an `f32` denormal operand of `+ - *`, a comparison, `sqrt` and `ldexp` as the zero -/// of its sign and flushes a denormal result, and `floor` and `ceil` read their operand so. Where -/// the profile takes its driver's measured deviation `MetalFloatDenormals` the device's own reading -/// is left to it and the module requires the fact; elsewhere the module flushes them itself, so the -/// interpreter, which keeps denormals as lavapipe does, gives Metal's answer. `floor` and `ceil` -/// are flushed whatever the fact: no device measured reads their operand as Metal does; and `ldexp` -/// is Metal's whatever the fact, computed on the operand's bits for every exponent. Flipping the -/// fact flips that and nothing else; neither side notes `DeviceDenormals`. The operands are bits -/// (`llvm.umin` of constants), so each kernel's float operation is its only one. +/// Metal reads an `f32` denormal operand of `+ - *`, a comparison, `sqrt`, `floor`, `ceil` and +/// `ldexp` as the zero of its sign and flushes a denormal result. The module leaves the reading to +/// the device: where the profile takes its driver's measured deviation `MetalFloatDenormals` it +/// requires the fact for `+ - *`, the comparison and `sqrt`, which then read them as Metal does; +/// elsewhere they are the device's, noted `DeviceDenormals` (`sqrt`, the device's maths function, +/// off Metal's own functions notes them beside its precision on either). `floor` and `ceil` are +/// the device's +/// whatever the fact, noted: no device measured reads their operand as Metal does. `ldexp` is +/// Metal's whatever the fact, computed on the operand's bits for every exponent. Flipping the fact +/// changes the requirement and the note, never the module. The interpreter keeps denormals as +/// lavapipe does. The operands are bits (`llvm.umin` of constants), so each kernel's float +/// operation is its only one. #[test] -fn float_denormals_follow_the_device_fact() { +fn float_denormals_are_the_devices_and_noted_off_the_device_fact() { // The kernel's float `%r` from `body`, Metal's word, and the word of a device that keeps // denormals (the interpreter, where the module leaves them to the device). let float = |name: &'static str, body: String, metal: u32| Kernel { @@ -4507,7 +3822,7 @@ fn float_denormals_follow_the_device_fact() { ), 0x8000_0000, ), - 0x8000_0000, + (-1.0f32).to_bits(), ), ( float( @@ -4515,7 +3830,7 @@ fn float_denormals_follow_the_device_fact() { format!("{} %r = call float @air.ceil.f32(float %x)\n", ob("x", 1)), 0, ), - 0, + 1.0f32.to_bits(), ), ( float( @@ -4571,28 +3886,30 @@ fn float_denormals_follow_the_device_fact() { let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let own = matches!( - kk.name, - "den_floor" | "den_ceil" | "den_ldexp" | "den_ldexp_tiny" - ); - let left = fact && !own; + let bits = matches!(kk.name, "den_ldexp" | "den_ldexp_tiny"); + let never = matches!(kk.name, "den_floor" | "den_ceil"); + // The device's `Sqrt`, a maths function off Metal's own functions, records its + // denormals with its precision. + let function = kk.name == "den_sqrt" + && p.fields().float_functions != crate::device::profile::FloatFunctions::Metal; assert_eq!( a.requirements .properties .contains(&crate::device::requirements::VkProperty::MetalFloatDenormals), - left, + fact && !bits && !never, "{what}" ); - assert!( - !a.precision.contains(&PrecisionNote::DeviceDenormals), + assert_eq!( + a.precision.contains(&PrecisionNote::DeviceDenormals), + never || function || (!fact && !bits), "{what}: {:?}", a.precision ); let got = interpret(&bitcode, kk.name, &p); - let want = if left { - *device - } else { + let want = if bits { kk.want.expect("Metal's word") + } else { + *device }; assert_eq!(got, want, "{what}: {got:#x} != {want:#x}"); per.push(words); @@ -4600,13 +3917,8 @@ fn float_denormals_follow_the_device_fact() { emitted.push(per); } for (i, kk) in ks.iter().enumerate() { - let own = matches!( - kk.name, - "den_floor" | "den_ceil" | "den_ldexp" | "den_ldexp_tiny" - ); assert_eq!( - emitted[0][i] == emitted[1][i], - own, + emitted[0][i], emitted[1][i], "{} on {stem}: the module with and without the fact", kk.name ); @@ -4627,10 +3939,8 @@ fn float_denormals_follow_the_device_fact() { /// `sincos` is its `sin` and `cos` word for word (cases 7b283404 and f6524207, every pair): precise /// `sin` and `cos` without fast-math flags answer the canonical NaN, so each result selects it /// where the device fact does not leave it to the device, and the call notes no -/// `DeviceNanEncoding`. The cosine is stored, so it is selected even where the sine is not read. On -/// `lavapipe`, whose sine and cosine are the translation's routines, the interpreter runs both -/// results: each is `0x7FC00000` for an operand NaN with a payload and the sign bit, which the -/// routines alone pass on (NVIDIA answered `0x7FFFFFFF`). +/// `DeviceNanEncoding`. The cosine is stored, so it is selected even where the sine is not read. +/// (The interpreter does not model `Sin`; the shape is the module's.) #[test] fn sincos_answers_the_nan_of_sin_and_cos() { let kernel = |name: &'static str, read: &str| { @@ -4673,10 +3983,6 @@ fn sincos_answers_the_nan_of_sin_and_cos() { ); let (is_nan, bits) = nan_tests(&words); tests.push(is_nan + bits); - if stem == "lavapipe" && !fact { - let got = interpret(&bitcode, kk.name, &p); - assert_eq!(got, 0x7FC0_0000, "{what}: {got:#x}"); - } } assert_eq!(tests[1], tests[0] + selects, "{} on {stem}", kk.name); } @@ -4685,9 +3991,7 @@ fn sincos_answers_the_nan_of_sin_and_cos() { /// A result whose every use drops its NaN's bits (a float comparison, or arithmetic that answers /// the canonical NaN itself) needs no select, so a chain of `float` arithmetic tests once, at its -/// end, and a result only compared tests never. The chain has no division: the precise division -/// routine answers the canonical NaN through bit comparisons of its own, which the count would read -/// as the model's tests. +/// end, and a result only compared tests never. #[test] fn a_nan_is_selected_only_where_its_bits_are_observed() { let xyz = format!( @@ -5430,13 +4734,16 @@ fn half_fmod_answers_metals_zero_remainder_on_every_profile() { } /// Class I: Metal's `mix(x, y, t)` on `float` and `half` is `fma(t, y, fma(-t, x, x))`, with and -/// without fast-math flags, on every profile: no `FMix` is emitted, and the interpreter answers -/// Metal's recorded words (`nan_functions`: `mix(inf, 1, 0)` is the canonical NaN, `mix(-0, -0, 0)` -/// is `+0`; `nan_half`: `mix(-0.3, 0.7, 0.2)` is `0xAE68`, where the blend gives `0xAE66`). The -/// driver's deviation `MetalCanonicalNans` is not taken, so a device that leaves the NaN to -/// `OpFmaKHR` (MoltenVK's, whose arithmetic answers Metal's) shows the select here too. +/// without fast-math flags. On a profile whose `float` functions are Metal's (moltenvk-m3), and on +/// `half` where its fused multiply-add is the measured 16-bit one, the module keeps that form: no +/// `FMix` is emitted, and the interpreter answers Metal's recorded words (`nan_functions`: +/// `mix(inf, 1, 0)` is the canonical NaN, `mix(-0, -0, 0)` is `+0`; `nan_half`: +/// `mix(-0.3, 0.7, 0.2)` is `0xAE68`, where the blend gives `0xAE66`). The driver's deviation +/// `MetalCanonicalNans` is not taken, so a device that leaves the NaN to `OpFmaKHR` (MoltenVK's, +/// whose arithmetic answers Metal's) shows the select here too. Every other profile takes the +/// device's `FMix`, noted `NativeMix`. #[test] -fn mix_is_metals_fused_form_on_every_profile() { +fn mix_is_metals_fused_form_on_moltenvk_and_the_devices_fmix_elsewhere() { let three = |a: u32, b: u32, c: u32| format!("{}{}{}", ob("x", a), ob("y", b), ob("z", c)); let halves = |a: u16, b: u16, c: u16| format!("{}{}{}", oh("hx", a), oh("hy", b), oh("hz", c)); let ks = [ @@ -5498,11 +4805,22 @@ fn mix_is_metals_fused_form_on_every_profile() { }; for stem in PROFILES.iter().copied().chain(["lavapipe"]) { let p = profile_with_canonical_nans(stem, false); + let metal = p.fields().float_functions == FloatFunctions::Metal; + let f16 = crate::lower::arith::fma::half_route(&p) == crate::lower::arith::fma::Route::F16; for kk in &ks { let what = format!("{} on {stem}", kk.name); let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + let chain = metal || (kk.name.starts_with("half_") && f16); + if !chain { + assert!( + blend(&words) > 0 && a.precision.contains(&PrecisionNote::NativeMix), + "{what}: FMix, {:?}", + a.precision + ); + continue; + } assert_eq!(blend(&words), 0, "{what}"); let got = interpret(&bitcode, kk.name, &p); assert_eq!(Some(got), kk.want, "{what}: {got:#x}"); diff --git a/crates/metal2vulkan/src/tests/engine_float_call_notes.rs b/crates/metal2vulkan/src/tests/engine_float_call_notes.rs index bb22925f7..670366eea 100644 --- a/crates/metal2vulkan/src/tests/engine_float_call_notes.rs +++ b/crates/metal2vulkan/src/tests/engine_float_call_notes.rs @@ -19,6 +19,7 @@ use crate::air::ir::{BinOp, FastMath}; use crate::device::profile::FloatFunctions; use crate::device::requirements::VkProperty; use crate::device::DeviceProfile; +use crate::error::DriverDeviation; use crate::lower::arith::fma::{self, Route}; use crate::lower::arith::libm::Mode; use crate::lower::arith::{denormal, float_binop_notes, float_call_notes, FloatFmt}; @@ -301,7 +302,7 @@ fn one_profile_per_class() -> BTreeMap { let routes: BTreeSet = out.keys().map(|(route, _, _)| *route).collect(); assert_eq!( routes, - BTreeSet::from(fma::FLOAT_ROUTES), + BTreeSet::from([Route::Khr, Route::Native]), "every float route is some committed profile's" ); assert!( @@ -364,19 +365,21 @@ fn exported_float_notes_are_the_ones_a_compile_records() { assert!(compared > 0); } -/// The binary operators' notes beside the functions': a `half` or `bfloat` remainder, and a -/// division other than Metal's precise one, is the device's arithmetic, and no operator leaves -/// the device its denormals or its NaN: `+ - *` answer Metal's, and so does the `float` remainder, -/// Metal's composition measured on the M3 Max, or with every flag its `fast::fmod`, whose notes it -/// records. Metal's precise division (an `fdiv` on `float` without `arcp`, or on `half` under every -/// flag set) records nothing: the shared routine computes Metal's quotient. Metal's fast division -/// (an `fdiv` on `float` with `arcp`) answers Metal's denormals and NaNs itself, so it records the -/// device's arithmetic (its reciprocal) alone, and where the profile's `float` functions are -/// Metal's, not in an entry Metal compiles with fast math, whose quotient is Metal's own. +/// The binary operators' notes beside the functions': a remainder and a division are the device's +/// arithmetic, and a `float` operator leaves the device its denormals where the profile does not +/// take `DriverDeviation::MetalFloatDenormals`, and a remainder and a division on every profile. +/// Metal's precise division (an `fdiv` on `float` without `arcp`, or on `half` under every flag +/// set) is the device's `OpFDiv`, noted `NativeDivision`. A `float` remainder without every flag is +/// the device's `OpFRem`, and with every flag Metal's `fast::fmod`, whose notes it records. Metal's +/// fast division (an `fdiv` on `float` with `arcp`) is the device's `OpFDiv` too, and records the +/// device's arithmetic, its division and its denormals, but where the profile's `float` functions +/// are Metal's, in an entry Metal compiles with fast math, whose quotient is Metal's own. No +/// operator leaves the device its NaN here (the policy keeps Metal's). #[test] fn a_float_division_is_the_devices_arithmetic_unless_it_is_metals_precise_one() { for (class, (stem, p)) in one_profile_per_class() { let (_, metal_functions, _) = class; + let flushes = p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals); for (_, _, _, fmt) in ELEMS { for op in BinOp::ALL { for fmf in [FastMath::NONE, FastMath::ARCP, every_flag()] { @@ -386,37 +389,40 @@ fn a_float_division_is_the_devices_arithmetic_unless_it_is_metals_precise_one() for mode in [Mode::Fast, Mode::Precise] { let metal = metal_functions.then_some(mode); let notes = notes.clone().in_entry(metal); + let single = fmt == FloatFmt::F32; let precise = op == BinOp::FDiv - && (fmt == FloatFmt::Half - || (fmt == FloatFmt::F32 && !fmf.contains(FastMath::ARCP))); + && (fmt == FloatFmt::Half || (single && !fmf.contains(FastMath::ARCP))); let what = format!("{op:?} on {fmt:?} under {fmf:?} on {stem}, {metal:?}"); + assert!(!notes.contains(&PrecisionNote::DeviceNanEncoding), "{what}"); if precise { - assert!(notes.is_empty(), "{what}: {notes:?}"); - continue; - } - // A `float` remainder is Metal's, measured on the M3 Max: exact without - // every flag, `fast::fmod` with them, whose notes it records. - if op == BinOp::FRem && fmt == FloatFmt::F32 { - let want = if fmf == every_flag() { - let Some(AirIntrinsic::Math(fmod)) = - AirIntrinsic::parse("air.fast_fmod.f32") - else { - panic!("air.fast_fmod.f32 does not parse"); - }; - float_call_notes(fmod, fmf, &p) - .expect("fast fmod is a float function") - .in_entry(metal) - } else { - BTreeSet::new() - }; + let want: BTreeSet<_> = [PrecisionNote::NativeDivision] + .into_iter() + .chain(single.then_some(PrecisionNote::DeviceDenormals)) + .collect(); assert_eq!(notes, want, "{what}"); continue; } - if op == BinOp::FDiv && fmt == FloatFmt::F32 { + if op == BinOp::FRem && single && fmf == every_flag() { + let Some(AirIntrinsic::Math(fmod)) = + AirIntrinsic::parse("air.fast_fmod.f32") + else { + panic!("air.fast_fmod.f32 does not parse"); + }; + let want = float_call_notes(fmod, fmf, &p) + .expect("fast fmod is a float function") + .in_entry(metal); + assert_eq!(notes, want, "{what}"); + continue; + } + if op == BinOp::FDiv && single { let want = if metal == Some(Mode::Fast) { BTreeSet::new() } else { - BTreeSet::from([PrecisionNote::DeviceArithmetic]) + BTreeSet::from([ + PrecisionNote::DeviceArithmetic, + PrecisionNote::NativeDivision, + PrecisionNote::DeviceDenormals, + ]) }; assert_eq!(notes, want, "{what}"); continue; @@ -426,8 +432,11 @@ fn a_float_division_is_the_devices_arithmetic_unless_it_is_metals_precise_one() matches!(op, BinOp::FDiv | BinOp::FRem), "{what}" ); - assert!(!notes.contains(&PrecisionNote::DeviceDenormals), "{what}"); - assert!(!notes.contains(&PrecisionNote::DeviceNanEncoding), "{what}"); + assert_eq!( + notes.contains(&PrecisionNote::DeviceDenormals), + single && (op == BinOp::FRem || !flushes), + "{what}" + ); } } } @@ -435,31 +444,25 @@ fn a_float_division_is_the_devices_arithmetic_unless_it_is_metals_precise_one() } } -/// Metal's precise `sqrt`, `rsqrt`, and `fmod`, on `float` and `half`, answer the one right value -/// (`libm::Fun::correctly_rounded`: correctly rounded and exact by MSL Tables 8.1 and 8.3, and at -/// every `half` operand), which the product computes on every device: they record neither precision -/// note on any profile class, in either mode, with or without flags. A function Apple bounds by -/// ulps keeps its note where the translation's routine computes it: precise `exp` on a profile -/// whose functions are the device's. +/// Metal's precise `fmod`, on `float` and `half`, answers the one right value +/// (`libm::Fun::correctly_rounded`: exact by MSL Tables 8.1 and 8.3), which its routine computes +/// on every device: it records neither precision note on any profile class, in either mode, with +/// or without flags. Precise `sqrt` and `rsqrt`, which Metal documents correctly rounded, are the +/// device's `Sqrt` and `InverseSqrt`: off Metal's own functions they record the device's precision +/// (`NativeTranscendentals`), as precise `exp`, which Apple bounds by ulps, does. #[test] -fn metals_correctly_rounded_functions_record_no_precision_note() { +fn precise_fmod_records_no_precision_note_and_the_roots_the_devices() { let function_notes = [ PrecisionNote::DeviceArithmetic, PrecisionNote::DeviceTranscendentals, + PrecisionNote::NativeTranscendentals, ]; let parse = |name: &str| match AirIntrinsic::parse(name) { Some(AirIntrinsic::Math(call)) => call, _ => panic!("{name} is a math call"), }; for ((_, metal_functions, _), (stem, p)) in one_profile_per_class() { - for name in [ - "air.sqrt.f32", - "air.rsqrt.f32", - "air.fmod.f32", - "air.sqrt.f16", - "air.rsqrt.f16", - "air.fmod.f16", - ] { + for name in ["air.fmod.f32", "air.fmod.f16"] { for fmf in [FastMath::NONE, every_flag()] { for math in [EntryMath::Fast, EntryMath::Precise] { let notes = PrecisionNote::of_math_call(parse(name), fmf, &p, math) @@ -472,17 +475,25 @@ fn metals_correctly_rounded_functions_record_no_precision_note() { } } if !metal_functions { - let notes = PrecisionNote::of_math_call( - parse("air.exp.f32"), - FastMath::NONE, - &p, - EntryMath::Precise, - ) - .expect("exp is a float function"); - assert!( - notes.contains(&PrecisionNote::DeviceTranscendentals), - "exp on {stem}: {notes:?}" - ); + for name in [ + "air.sqrt.f32", + "air.rsqrt.f32", + "air.sqrt.f16", + "air.rsqrt.f16", + "air.exp.f32", + ] { + let notes = PrecisionNote::of_math_call( + parse(name), + FastMath::NONE, + &p, + EntryMath::Precise, + ) + .unwrap_or_else(|| panic!("{name} is a float function")); + assert!( + notes.contains(&PrecisionNote::NativeTranscendentals), + "{name} on {stem}: {notes:?}" + ); + } } } } @@ -534,9 +545,9 @@ fn call_kernel(name: &str, symbol: &str, arity: usize, fmf: FastMath) -> Kernel /// function, `fast::atan2` among them; an entry Metal compiles without fast math (a division /// without `nnan` and `ninf`, a call without flags) still records them, and `fast::sinpi`, the /// device's near-equivalent, records its note in either. `mix` and `fast::sinpi` record no -/// `DeviceDenormals` there and require the measured fact. Off MoltenVK, Metal's fused `mix` reads -/// its denormals as Metal's does on every route, and requires the fact exactly -/// where `OpFmaKHR` reads them so. +/// `DeviceDenormals` there and require the measured fact. Off MoltenVK `mix` is the device's +/// `FMix`, with or without Metal's denormals: noted `NativeMix` and `DeviceDenormals`, requiring +/// no fact. #[test] fn a_fast_math_entry_on_moltenvk_records_no_note_for_metals_own_operations() { let every = every_flag(); @@ -654,9 +665,8 @@ fn a_fast_math_entry_on_moltenvk_records_no_note_for_metals_own_operations() { "mix_fast on {stem}: {mix:?}, requires the fact: {requires}" ); } - // Without Metal's functions, with or without Metal's denormals, `mix` reads its denormals as - // Metal's does, the fact required where `OpFmaKHR` reads them so, and the fast division keeps - // its reciprocal's note. + // Without Metal's functions, with or without Metal's denormals, `mix` is the device's `FMix`, + // and the fast division keeps its note. for denormals in [true, false] { let Some((stem, p)) = profiles.iter().find(|(_, p)| { let (_, metal, flushes) = note_class(p); @@ -665,9 +675,10 @@ fn a_fast_math_entry_on_moltenvk_records_no_note_for_metals_own_operations() { panic!("no committed profile of the device's functions, Metal's denormals {denormals}"); }; let (mix, requires) = notes_of(p, "mix_fast"); - let khr = note_class(p).0 == Route::Khr; assert!( - !mix.contains(&PrecisionNote::DeviceDenormals) && requires == (khr && denormals), + mix.contains(&PrecisionNote::NativeMix) + && mix.contains(&PrecisionNote::DeviceDenormals) + && !requires, "mix_fast on {stem}: {mix:?}, requires the fact: {requires}" ); let (fast, _) = notes_of(p, "fdiv_fast"); diff --git a/crates/metal2vulkan/src/tests/engine_linear_cube.rs b/crates/metal2vulkan/src/tests/engine_linear_cube.rs index b72a2a1fa..811ad05e6 100644 --- a/crates/metal2vulkan/src/tests/engine_linear_cube.rs +++ b/crates/metal2vulkan/src/tests/engine_linear_cube.rs @@ -333,12 +333,12 @@ fn select(d: [f32; 3]) -> (usize, f32, f32, f32) { } /// Metal's base texel and 1/256 steps on a face axis of `n` texels of minor component `c` beside -/// major magnitude `ma`: `X = RN(RN(1 + c r) / 2 n)` with `r` Metal's reciprocal of `ma` (its -/// model, `libm::rcp::model`), the sum fused, then `q = floor(256 X + 1/2) - 128`; on a repeating +/// major magnitude `ma`: `X = RN(RN(1 + c r) / 2 n)` with `r` the device's reciprocal of `ma` (the +/// interpreter's `RN(1 / ma)`), the sum fused, then `q = floor(256 X + 1/2) - 128`; on a repeating /// axis (`wraps`) of a size that is not a power of two, a face coordinate `RN(1 + c r) / 2` of 1 or /// more less 1 first. fn axis(c: f32, ma: f32, n: u32, wraps: bool) -> (i64, i64) { - let r = crate::lower::arith::libm::rcp::model(ma); + let r = 1.0 / ma; let f = c.mul_add(r, 1.0); let u = f * 0.5; let u = match wraps && !n.is_power_of_two() && u >= 1.0 { diff --git a/crates/metal2vulkan/src/tests/engine_metal_denormals.rs b/crates/metal2vulkan/src/tests/engine_metal_denormals.rs index 1793fdd46..80086784a 100644 --- a/crates/metal2vulkan/src/tests/engine_metal_denormals.rs +++ b/crates/metal2vulkan/src/tests/engine_metal_denormals.rs @@ -7,12 +7,10 @@ //! Each kernel loops over its rows (three operand words a row in `[[buffer(0)]]`) and stores one //! answer word a row in `[[buffer(1)]]`. The CPU SPIR-V interpreter keeps denormals, as a device //! without `DriverDeviation::MetalFloatDenormals` may, so on each such committed profile (one per -//! fused multiply-add route and routine of its small results) an entry that records no -//! `PrecisionNote::DeviceDenormals` must answer every row as Metal did, but, where the device's -//! fused multiply-add is unchecked (`fma::tiny_route`), for its rounding before the flush -//! ([`device_fma_gap`]). `llvm-as` assembles the module; without it the tests skip visibly. +//! fused multiply-add route) an entry that records no `PrecisionNote::DeviceDenormals` must answer +//! every row as Metal did. `llvm-as` assembles the module; without it the tests skip visibly. -use crate::device::{DevicePolicy, DeviceProfile, FloatMathsPolicy, RoundingOrderPolicy}; +use crate::device::{DevicePolicy, DeviceProfile}; use crate::error::DriverDeviation; use crate::lower::arith::fma; use crate::pipeline::artifact::PrecisionNote; @@ -260,65 +258,28 @@ fn interpret(bc: &[u8], name: &str, p: &DeviceProfile, rows: &[([u32; 3], [u32; } /// The committed profiles under `policy` whose device may keep denormals (no -/// `DriverDeviation::MetalFloatDenormals`), one per fused multiply-add route and routine of its -/// small results ([`fma::tiny_route`]). +/// `DriverDeviation::MetalFloatDenormals`), one per fused multiply-add route. fn profiles(policy: DevicePolicy) -> Vec<(String, DeviceProfile)> { let mut seen = BTreeSet::new(); committed_profiles_with(policy) .expect("profiles") .into_iter() .filter(|(_, p)| !p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals)) - .filter(|(_, p)| seen.insert((fma::float_route(p), fma::tiny_route(p)))) + .filter(|(_, p)| seen.insert(fma::float_route(p))) .collect() } -/// An `f32` denormal as the zero of its sign. -fn ftz(x: u32) -> u32 { - if x & 0x7F80_0000 == 0 { - x & 0x8000_0000 - } else { - x - } -} - -/// The device's fused multiply-add (`OpFmaKHR`, or native device maths' `Fma`) on a device that -/// keeps denormals, read as Metal reads them around it: the operands and the rounded result -/// flushed, a NaN Metal's. -fn device_fma(a: u32, b: u32, c: u32) -> u32 { - let f = |x: u32| f32::from_bits(ftz(x)); - let r = ftz(f(a).mul_add(f(b), f(c)).to_bits()); - if f32::from_bits(r).is_nan() { - 0x7FC0_0000 - } else { - r - } -} - -/// The device's fused multiply-add unchecked (native device maths, which the runtime announces as -/// `float-tininess-after-rounding`; docs/FAST-PATHS.md): Metal flushes a result whose exact value -/// is below `2^-126` before rounding it, where the device has rounded it up to `2^-126`, which the -/// flush after it keeps. `fun`'s answer with each `fma` so, where it is a composition of them. -fn device_fma_gap(fun: Fun, [a, b, c]: [u32; 3]) -> Option { - match fun { - Fun::Mix | Fun::FmaFma => Some(device_fma(c, b, device_fma(c ^ 0x8000_0000, a, a))), - _ => None, - } -} - /// What every kernel on one profile answered. #[derive(Default)] struct Report { /// The kernels that record `DeviceDenormals`. noted: Vec, - /// The rows of [`device_fma_gap`]'s known gap, per kernel. - gaps: Vec<(String, usize)>, - /// Every other answer that is not Metal's word. + /// Every answer of the others that is not Metal's word. wrong: Vec, } /// Every kernel on `p` against Metal's words. fn check(bc: &[u8], stem: &str, p: &DeviceProfile) -> Report { - let device = fma::float_route(p).device_float() && fma::tiny_route(p).is_none(); let mut report = Report::default(); for (fun, fast) in kernels() { let name = fun.name(fast); @@ -339,50 +300,22 @@ fn check(bc: &[u8], stem: &str, p: &DeviceProfile) -> Report { .any(|n| a.precision.contains(n)); let rows = rows(fun); let got = interpret(bc, &name, p, &rows); - let mut gaps = 0; for ((ops, metal), g) in rows.iter().zip(&got) { let want = metal[usize::from(fast)]; if *g == want || (device_nan && nan(*g) && nan(want)) { continue; } - if device && device_fma_gap(fun, *ops) == Some(*g) { - gaps += 1; - continue; - } report.wrong.push(format!( "{what}: {:08x?}: {g:08x}, Metal {want:08x}", &ops[..fun.arity()] )); } - if gaps > 0 { - report.gaps.push((name, gaps)); - } } report } -fn exact_answers() -> DevicePolicy { - DevicePolicy::default().exact_answers() -} - -fn exact_float_maths() -> DevicePolicy { - DevicePolicy { - float_maths: FloatMathsPolicy::Exact, - ..DevicePolicy::default() - } -} - -fn exact_rounding_order() -> DevicePolicy { - DevicePolicy { - rounding_order: RoundingOrderPolicy::Exact, - ..DevicePolicy::default() - } -} - -/// Each policy's kernels on each route, against Metal's words: no answer off Metal's but -/// [`device_fma_gap`]'s on the device's fused multiply-add unchecked, and `DeviceDenormals` -/// recorded by exactly the kernels `noted` names (`mix`: the device's `FMix` under the device's -/// order; the others: native device maths). +/// The kernels on each route against Metal's words: no answer off Metal's, and `DeviceDenormals` +/// recorded by exactly the kernels `noted` names. fn run_policy(bc: &[u8], policy: DevicePolicy, what: &str, noted: &[Fun]) -> Vec { let want: Vec = kernels() .into_iter() @@ -393,12 +326,9 @@ fn run_policy(bc: &[u8], policy: DevicePolicy, what: &str, noted: &[Fun]) -> Vec for (stem, p) in profiles(policy) { let report = check(bc, &stem, &p); eprintln!( - "{what} on {stem} ({:?}, checked by {:?}): DeviceDenormals on {:?}; the device fma's \ - gap on {:?}; {} other answers off Metal's", + "{what} on {stem} ({:?}): DeviceDenormals on {:?}; {} other answers off Metal's", fma::float_route(&p), - fma::tiny_route(&p), report.noted, - report.gaps, report.wrong.len() ); assert_eq!(report.noted, want, "{what} on {stem}: DeviceDenormals"); @@ -407,57 +337,15 @@ fn run_policy(bc: &[u8], policy: DevicePolicy, what: &str, noted: &[Fun]) -> Vec wrong } -/// The accurate forms read every probed function's denormals as Metal does: under -/// `exact_answers()` no kernel records `DeviceDenormals`, under `FloatMathsPolicy::Exact` only -/// `mix` by the device's `FMix` (the device's order), under `RoundingOrderPolicy::Exact` only the -/// functions native device maths answers; on every route of a device that may keep a denormal, -/// every other kernel answers every row with Metal's word. Under `FloatMathsPolicy::Exact` -/// (`exact_answers()` too) the device's fused multiply-add is checked and has no gap; under -/// `RoundingOrderPolicy::Exact` alone, `mix` by it rounds before its flush. -#[test] -fn the_accurate_forms_read_denormals_as_metal() { - let Some(bc) = assemble() else { - return; - }; - let native = [Fun::Atan2, Fun::SinPi, Fun::CosPi, Fun::TanPi, Fun::Fmod]; - let mut wrong = run_policy(&bc, exact_answers(), "exact_answers", &[]); - wrong.extend(run_policy( - &bc, - exact_float_maths(), - "FloatMathsPolicy::Exact", - &[Fun::Mix], - )); - wrong.extend(run_policy( - &bc, - exact_rounding_order(), - "RoundingOrderPolicy::Exact", - &native, - )); - assert!( - wrong.is_empty(), - "{} answers off Metal's, the first: {:#?}", - wrong.len(), - &wrong[..wrong.len().min(40)] - ); -} - -/// The default forms answer as Metal does at denormals wherever they record no `DeviceDenormals` -/// (but the unchecked device `fma`'s rounding before its flush); native device maths and the -/// device's `FMix` record it. +/// The forms answer as Metal does at denormals wherever they record no `DeviceDenormals`; on a +/// device that may keep a denormal every kernel here records it: the device's maths functions, its +/// `FMix` and its fused multiply-adds read them as the device does. #[test] fn the_default_forms_note_what_they_leave_to_the_device() { let Some(bc) = assemble() else { return; }; - let noted = [ - Fun::Mix, - Fun::Atan2, - Fun::SinPi, - Fun::CosPi, - Fun::TanPi, - Fun::Fmod, - ]; - let wrong = run_policy(&bc, DevicePolicy::default(), "default", ¬ed); + let wrong = run_policy(&bc, DevicePolicy::default(), "default", &FUNS); assert!( wrong.is_empty(), "{} answers off Metal's, the first: {:#?}", diff --git a/crates/metal2vulkan/src/tests/engine_metal_math.rs b/crates/metal2vulkan/src/tests/engine_metal_math.rs index 415114c09..9441fa375 100644 --- a/crates/metal2vulkan/src/tests/engine_metal_math.rs +++ b/crates/metal2vulkan/src/tests/engine_metal_math.rs @@ -4,20 +4,14 @@ //! computes: //! //! - `air.fast_tanh` on `float` is the MSL fast-math formula `(t - 1) / (t + 1)`, -//! `t = exp2(x * 2 log2 e)` of Metal's `exp2` (no `Tanh`), every step of it `NoContraction`; the -//! precise `air.tanh` is Metal's `tanh`, and a `half` `fast_tanh` Metal's `half` `tanh`, `(t - 1) -//! rcp(t + 1)` of the same `t` with Metal's reciprocal (no `Tanh`). Metal's `exp2` and `tanh` are -//! the device's `Exp2` and `Tanh` where the profile's `float` functions are Metal's -//! (`FloatFunctions::Metal`) and the translation's routines elsewhere, and so is its reciprocal -//! in a fast-math entry, the device's `1 / y` (`OpFDiv`); the checks below leave the routines out -//! of the kernel's own instructions, with the precise division they divide through -//! (`without_math_routines`); +//! `t = exp2(x * 2 log2 e)` of the device's `Exp2` (no `Tanh`), every step of it +//! `NoContraction`, its quotient the device's division (`OpFDiv`); the precise `air.tanh` is the +//! device's `Tanh`, and a `half` `fast_tanh` Metal's `half` `tanh`, `(t - 1) · (1 / (t + 1))` of +//! the same `t` (no `Tanh`); //! - `air.sign` is Metal's `sign` with and without fast math (no `FSign`, which keeps the sign //! of a zero where Metal answers `+0`), and both answer `-1` for `-3` on the interpreter; -//! - the precise `air.sinpi` calls Metal's routine on every profile, so the entry's own -//! instructions hold no `Sin` and no `RoundEven`; the fast `air.fast_sinpi` reduces its argument -//! (`RoundEven`) and takes the sine of the residue from the device's `Sin` where the profile's -//! `float` functions are Metal's (`FloatFunctions::Metal`), and calls the routine elsewhere. +//! - `air.sinpi` and `air.fast_sinpi` reduce their argument (`RoundEven`) and take the sine of the +//! residue from the device's `Sin` on every profile. //! //! The values of these functions are the unit tests' (`lower::arith::tests`); no GPU is used. //! @@ -39,7 +33,7 @@ use crate::pipeline::interface::PushLoc; use crate::pipeline::sym::{Axis, PushField, ResourceKind, ResourceSlot, SpecKey, Stage}; use crate::pipeline::testing::{ compile, engine_dir, exact_maths, link_and_validate, llvm_assemble, meter, profile, - tiny_check_scales, typed_module, without_math_routines, AssembleError, Scratch, + typed_module, AssembleError, Scratch, }; use crate::spirv::interp::{run, Buffer, Config, Resources}; use crate::spirv::ir::StorageClass; @@ -61,14 +55,8 @@ struct Kernel { /// `GLSL.std.450` instructions the module must and must not contain. has: &'static [u32], lacks: &'static [u32], - /// `GLSL.std.450` instructions the module contains exactly where the profile's `float` - /// functions are Metal's. - metal_functions_only: &'static [u32], - /// Whether the module divides (`OpFDiv`) by the fast division's routine. + /// Whether the module divides (`OpFDiv`): `fast::tanh`'s quotient. divides: bool, - /// Whether the module divides (`OpFDiv`) exactly where the profile's `float` functions are - /// Metal's: the device's reciprocal in a fast-math entry. - metal_divides: bool, /// The stored word on the interpreter, when it models the kernel. want: Option, } @@ -77,42 +65,34 @@ const KERNELS: [Kernel; 8] = [ 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: &[], + has: &[EXP2], lacks: &[TANH], - metal_functions_only: &[EXP2], divides: true, - metal_divides: 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: &[], + has: &[EXP2], lacks: &[TANH], - metal_functions_only: &[EXP2], divides: true, - metal_divides: false, want: None, }, Kernel { name: "precise_tanh_float", body: " %a = fadd fast float 0x4046000000000000, -0.0\n %r = call fast float @air.tanh.f32(float %a)\n", - has: &[], + has: &[TANH], lacks: &[EXP2], - metal_functions_only: &[TANH], divides: false, - metal_divides: false, want: None, }, Kernel { name: "fast_tanh_half", body: " %a = fadd fast float 0x4000000000000000, -0.0\n %h = fptrunc float %a to half\n %t = call fast half @air.fast_tanh.f16(half %h)\n %r = fpext half %t to float\n", - has: &[], + has: &[EXP2], lacks: &[TANH], - metal_functions_only: &[EXP2], - divides: false, - metal_divides: true, + divides: true, want: None, }, Kernel { @@ -120,9 +100,7 @@ const KERNELS: [Kernel; 8] = [ body: " %a = fadd fast float 0xC008000000000000, -0.0\n %r = call fast float @air.sign.f32(float %a)\n", has: &[], lacks: &[FSIGN], - metal_functions_only: &[], divides: false, - metal_divides: false, want: Some(0xBF80_0000), }, Kernel { @@ -130,29 +108,23 @@ const KERNELS: [Kernel; 8] = [ body: " %a = fadd float 0xC008000000000000, -0.0\n %r = call float @air.sign.f32(float %a)\n", has: &[], lacks: &[FSIGN], - metal_functions_only: &[], divides: false, - metal_divides: false, want: Some(0xBF80_0000), }, Kernel { name: "precise_sinpi", body: " %a = fadd fast float 0x3FF0000000000000, -0.0\n %r = call fast float @air.sinpi.f32(float %a)\n", - has: &[], - lacks: &[SIN, ROUND_EVEN], - metal_functions_only: &[], + has: &[SIN, ROUND_EVEN], + lacks: &[], divides: false, - metal_divides: false, want: None, }, Kernel { name: "fast_sinpi", body: " %a = fadd fast float 0x3FF0000000000000, -0.0\n %r = call fast float @air.fast_sinpi.f32(float %a)\n", - has: &[], + has: &[SIN, ROUND_EVEN], lacks: &[], - metal_functions_only: &[SIN, ROUND_EVEN], divides: false, - metal_divides: false, want: None, }, ]; @@ -264,7 +236,7 @@ fn metal_math_variants_select_metals_functions() { let a = compile(&bitcode, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let (ext, div) = ext_insts(&without_math_routines(&words)); + let (ext, div) = ext_insts(&words); for i in k.has { assert!( ext.contains(i), @@ -278,25 +250,16 @@ fn metal_math_variants_select_metals_functions() { ); } let metal = p.fields().float_functions == FloatFunctions::Metal; - for i in k.metal_functions_only { - assert_eq!( - ext.contains(i), - metal, - "{what}: GLSL.std.450 {i} with float functions Metal's = {metal} ({ext:?})" - ); - } - assert_eq!( - div, - k.divides || (k.metal_divides && metal), - "{what}: OpFDiv" - ); - // The fast-math entry's `fast_tanh` notes the routines it calls, except where every - // step is Metal's own function on the device (`FloatFunctions::Metal`), which notes - // nothing in such an entry. + 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. + // A `half` one's division is its reciprocal, a function of its own. if k.divides { + let half = k.name.ends_with("_half"); assert_eq!( - a.precision.contains(&PrecisionNote::DeviceArithmetic) - && a.precision.contains(&PrecisionNote::DeviceTranscendentals), + (half || a.precision.contains(&PrecisionNote::DeviceArithmetic)) + && a.precision.contains(&PrecisionNote::NativeTranscendentals), !metal, "{what}: {:?}", a.precision @@ -311,9 +274,8 @@ fn metal_math_variants_select_metals_functions() { } /// Each float arithmetic result of `words` (`OpFAdd`, `OpFSub`, `OpFMul`, `OpFDiv`, and -/// `GLSL.std.450 Fma`) but those of `apart`, as its opcode and whether it is decorated -/// `NoContraction`. -fn float_arithmetic(words: &[u32], apart: &[u32]) -> Vec<(u32, bool)> { +/// `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, @@ -338,24 +300,19 @@ fn float_arithmetic(words: &[u32], apart: &[u32]) -> Vec<(u32, bool)> { } results .into_iter() - .filter(|(_, id)| !apart.contains(id)) .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`, the quotient's product and the same product `2^24` larger that decides its flush -/// (each 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 reciprocal's estimate. The caller's +/// 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)`). Under `FloatMathsPolicy::Exact` each of the caller's two products is checked; a -/// fused check (`TinyCheck::Fused`) scales an operand by its own multiply, `NoContraction`, -/// counted apart. +/// `gelu(-8)`). #[test] fn fast_tanh_is_one_operation() { - use crate::lower::arith::denormal::{tiny_check, TinyCheck}; let Some(bitcode) = assemble() else { return; }; @@ -365,24 +322,7 @@ fn fast_tanh_is_one_operation() { 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 own = without_math_routines(&words); - let scales = tiny_check_scales(&own); - let fused = tiny_check(&p) == Some(TinyCheck::Fused); - assert_eq!( - scales.len(), - 2 * usize::from(fused), - "{what}: the checks' scaling" - ); - let ops = float_arithmetic(&own, &scales); - let exact_muls = |ops: &[(u32, bool)]| { - let mul = (crate::spv::Op::FMul as u32, true); - ops.iter().filter(|&&o| o == mul).count() - }; - assert_eq!( - exact_muls(&float_arithmetic(&own, &[])), - exact_muls(&ops) + scales.len(), - "{what}: the checks' scaling, NoContraction" - ); + let ops = float_arithmetic(&words); let count = |op: crate::spv::Op, exact: bool| { ops.iter() .filter(|(o, e)| *o == op as u32 && *e == exact) @@ -393,21 +333,17 @@ fn fast_tanh_is_one_operation() { .filter(|(o, e)| *o == crate::spv::Op::ExtInst as u32 && *e == exact) .count() }; - // The tanh's products are in the profile's form, and none in the other. - let metal = p.fields().float_functions == FloatFunctions::Metal; - let (products, other) = if metal { - (fma(true), count(crate::spv::Op::FMul, true)) - } else { - (count(crate::spv::Op::FMul, true), fma(true)) - }; + // The tanh's product is in the profile's form. + let metal = usize::from(p.fields().float_functions == FloatFunctions::Metal); assert_eq!( ( - products, + count(crate::spv::Op::FMul, true), count(crate::spv::Op::FSub, true), count(crate::spv::Op::FAdd, true), - count(crate::spv::Op::FDiv, true) + count(crate::spv::Op::FDiv, true), + fma(true) ), - (4, 1, 1, 1), + (1 - metal, 1, 1, 1, metal), "{what}: the tanh's steps, NoContraction: {ops:?}" ); assert_eq!( @@ -416,9 +352,8 @@ fn fast_tanh_is_one_operation() { count(crate::spv::Op::FSub, false), count(crate::spv::Op::FDiv, false), count(crate::spv::Op::FMul, false), - other ), - (0, 0, 0, 2, 0), + (0, 0, 0, 2), "{what}: only the caller's multiplies are left free: {ops:?}" ); assert!( diff --git a/crates/metal2vulkan/src/tests/engine_native_maths.rs b/crates/metal2vulkan/src/tests/engine_native_maths.rs index 341fe637c..755b4c35c 100644 --- a/crates/metal2vulkan/src/tests/engine_native_maths.rs +++ b/crates/metal2vulkan/src/tests/engine_native_maths.rs @@ -1,25 +1,22 @@ //! The device's forms of Metal's maths: on a device whose `float` functions are not Metal's own, -//! three of the policy's choices each take the device's instructions where Metal's answer would be -//! computed, each recording its kinds, and each set on or off alone: the maths functions, divisions -//! and fused multiply-adds (`FloatMathsPolicy`: `NativeTranscendentals`, `NativeDivision`, -//! `NativeFma`), the NaN and minimum and maximum (`NanMinMaxPolicy`: `NativeNanEncoding`, -//! `NativeMinMax`), and the rounding order of `dot`, `mix` and `fast::sqrt` (`RoundingOrderPolicy`: -//! `NativeDot`, `NativeMix`, `NativeTranscendentals`). Off, each takes Metal's answer: the -//! translation's routines, its selects of Metal's NaN and operand, and Metal's fused forms. +//! the maths functions, divisions and fused multiply-adds (`NativeTranscendentals`, +//! `NativeDivision`, `NativeFma`) and `dot`, `mix` and `fast::sqrt` (`NativeDot`, `NativeMix`, +//! `NativeTranscendentals`) are the device's instructions, each recording its kinds; and one of the +//! policy's choices takes the device's NaN and minimum and maximum (`NanMinMaxPolicy`: +//! `NativeNanEncoding`, `NativeMinMax`) where it is on, and Metal's selects of its NaN and operand +//! where it is off. //! //! The kernels read three `float`s from buffer 0 and store one result after them: a precise //! `sin`, `exp`, `atan2` and `pow`, a precise and an `arcp` division, a `half` `fma`, an addition, //! an `fmin`, a `saturate`, a `fast::sqrt`, a `dot` and a `float` and a `half` `mix`. On lavapipe -//! each records its kind exactly where its own choice is on, whatever the others are, and is -//! smaller there than with it off; the interpreter's answers stay within the bound the kind's -//! docs state when on, and are Metal's when off. `llvm-as` assembles the module; without it the +//! each records its kind, a choice's exactly where it is on, and a choice's is smaller there than +//! with it off; the interpreter's answers stay within the bound the kind's docs state, and are +//! Metal's on MoltenVK and with the choice off. `llvm-as` assembles the module; without it the //! tests skip visibly. use crate::air::{self, SpecRequest}; -use crate::device::profile::{ - DeviceProfile, FloatFunctions, MinMaxRoute, NanEncoding, RoundingOrderRoute, -}; -use crate::device::{DevicePolicy, FloatMathsPolicy, NanMinMaxPolicy, RoundingOrderPolicy}; +use crate::device::profile::{DeviceProfile, FloatFunctions, MinMaxRoute, NanEncoding}; +use crate::device::{DevicePolicy, NanMinMaxPolicy}; use crate::lower::emit::emit_module; use crate::lower::select::{select, LowerInputs}; use crate::memory::static_root::analyze_memory; @@ -33,31 +30,19 @@ use crate::spirv::testing::{committed_profiles_with, is_moltenvk_capture}; const OP_FUNCTION: u32 = 54; -/// One of the policy's choices between the device's form and Metal's that native device maths -/// was split into. +/// One of the policy's choices between the device's form and Metal's. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Choice { - /// The maths functions, divisions and fused multiply-adds (`FloatMathsPolicy`). - Maths, /// The NaN and minimum and maximum (`NanMinMaxPolicy`). NanMinMax, - /// The rounding order of `dot`, `mix` and `fast::sqrt` (`RoundingOrderPolicy`). - RoundingOrder, } impl Choice { - const ALL: [Choice; 3] = [Choice::Maths, Choice::NanMinMax, Choice::RoundingOrder]; + const ALL: [Choice; 1] = [Choice::NanMinMax]; /// `policy` with this choice on (the device's form) or off (Metal's). fn set(self, policy: DevicePolicy, on: bool) -> DevicePolicy { match self { - Choice::Maths => DevicePolicy { - float_maths: match on { - true => FloatMathsPolicy::Native, - false => FloatMathsPolicy::Exact, - }, - ..policy - }, Choice::NanMinMax => DevicePolicy { nan_and_min_max: match on { true => NanMinMaxPolicy::Native, @@ -65,13 +50,6 @@ impl Choice { }, ..policy }, - Choice::RoundingOrder => DevicePolicy { - rounding_order: match on { - true => RoundingOrderPolicy::Native, - false => RoundingOrderPolicy::Exact, - }, - ..policy - }, } } @@ -86,33 +64,20 @@ impl Choice { fn taken(self, p: &DeviceProfile) -> bool { let f = p.fields(); match self { - Choice::Maths => f.float_functions == FloatFunctions::Native, Choice::NanMinMax => { f.nan_encoding == NanEncoding::Native && f.min_max == MinMaxRoute::Native } - Choice::RoundingOrder => f.rounding_order == RoundingOrderRoute::Native, } } } -/// The kinds of the device's forms of Metal's maths. -const NATIVES: [PrecisionNote; 7] = [ - PrecisionNote::NativeTranscendentals, - PrecisionNote::NativeDivision, - PrecisionNote::NativeFma, - PrecisionNote::NativeNanEncoding, - PrecisionNote::NativeMinMax, - PrecisionNote::NativeDot, - PrecisionNote::NativeMix, -]; - /// A kernel: its name, the body defining `%r` from `%a`, `%b` and `%c`, the note its device form -/// records, and the choice that takes it. +/// records, and the choice that takes it (`None`: every device but MoltenVK). struct Kernel { name: &'static str, body: &'static str, note: PrecisionNote, - choice: Choice, + choice: Option, } const KERNELS: [Kernel; 14] = [ @@ -120,85 +85,85 @@ const KERNELS: [Kernel; 14] = [ name: "native_sin", body: " %r = tail call float @air.sin.f32(float %a)\n", note: PrecisionNote::NativeTranscendentals, - choice: Choice::Maths, + choice: None, }, Kernel { name: "native_exp", body: " %r = tail call float @air.exp.f32(float %a)\n", note: PrecisionNote::NativeTranscendentals, - choice: Choice::Maths, + choice: None, }, Kernel { name: "native_atan2", body: " %r = tail call float @air.atan2.f32(float %a, float %b)\n", note: PrecisionNote::NativeTranscendentals, - choice: Choice::Maths, + choice: None, }, Kernel { name: "native_pow", body: " %r = tail call float @air.pow.f32(float %a, float %b)\n", note: PrecisionNote::NativeTranscendentals, - choice: Choice::Maths, + choice: None, }, Kernel { name: "native_fdiv", body: " %r = fdiv float %a, %b\n", note: PrecisionNote::NativeDivision, - choice: Choice::Maths, + choice: None, }, Kernel { name: "native_fdiv_arcp", body: " %r = fdiv arcp float %a, %b\n", note: PrecisionNote::NativeDivision, - choice: Choice::Maths, + choice: None, }, Kernel { name: "native_half_fma", body: " %ha = fptrunc float %a to half\n %hb = fptrunc float %b to half\n %hc = fptrunc float %c to half\n %hr = tail call half @air.fma.f16(half %ha, half %hb, half %hc)\n %r = fpext half %hr to float\n", note: PrecisionNote::NativeFma, - choice: Choice::Maths, + choice: None, }, Kernel { name: "native_fadd", body: " %r = fadd float %a, %b\n", note: PrecisionNote::NativeNanEncoding, - choice: Choice::NanMinMax, + choice: Some(Choice::NanMinMax), }, Kernel { name: "native_fmin", body: " %r = tail call float @air.fmin.f32(float %a, float %b)\n", note: PrecisionNote::NativeMinMax, - choice: Choice::NanMinMax, + choice: Some(Choice::NanMinMax), }, Kernel { name: "native_fast_sqrt", body: " %r = tail call fast float @air.fast_sqrt.f32(float %a)\n", note: PrecisionNote::NativeTranscendentals, - choice: Choice::RoundingOrder, + choice: None, }, Kernel { name: "native_dot", body: " %u0 = insertelement <2 x float> undef, float %a, i32 0\n %u = insertelement <2 x float> %u0, float %b, i32 1\n %v0 = insertelement <2 x float> undef, float %c, i32 0\n %v = insertelement <2 x float> %v0, float %a, i32 1\n %r = tail call float @air.dot.v2f32(<2 x float> %u, <2 x float> %v)\n", note: PrecisionNote::NativeDot, - choice: Choice::RoundingOrder, + choice: None, }, Kernel { name: "native_mix", body: " %r = tail call float @air.mix.f32(float %a, float %b, float %c)\n", note: PrecisionNote::NativeMix, - choice: Choice::RoundingOrder, + choice: None, }, Kernel { name: "native_saturate", body: " %r = tail call float @air.saturate.f32(float %a)\n", note: PrecisionNote::NativeMinMax, - choice: Choice::NanMinMax, + choice: Some(Choice::NanMinMax), }, Kernel { name: "native_half_mix", body: " %ha = fptrunc float %a to half\n %hb = fptrunc float %b to half\n %hc = fptrunc float %c to half\n %hr = tail call half @air.mix.f16(half %ha, half %hb, half %hc)\n %r = fpext half %hr to float\n", note: PrecisionNote::NativeMix, - choice: Choice::RoundingOrder, + choice: None, }, ]; @@ -298,35 +263,38 @@ fn ulps(got: f32, want: f64) -> f64 { } /// On every committed profile but the MoltenVK captures, whose functions, NaN and minimum and -/// maximum are Metal's own, each choice takes its device forms exactly where it is on, and moves -/// the fingerprint; on the MoltenVK captures neither setting takes them, and only the NaN choice -/// moves the fingerprint: a texel's NaN, the image's decode, follows it on every device -/// (`TexelNanRoute`). +/// maximum are Metal's own, the maths functions are the device's, and each choice takes its device +/// forms exactly where it is on, and moves the fingerprint; on the MoltenVK captures neither +/// setting takes them, and the NaN choice moves the fingerprint all the same: a texel's NaN, the +/// image's decode, follows it on every device (`TexelNanRoute`). #[test] fn each_choice_takes_the_device_s_forms_where_it_is_on() { + let profiles = committed_profiles_with(DevicePolicy::default()).expect("profiles"); + assert!(profiles.len() >= 10, "{} profiles", profiles.len()); + for (stem, p) in &profiles { + assert_eq!( + p.fields().float_functions == FloatFunctions::Native, + !is_moltenvk_capture(stem), + "{stem}" + ); + } for choice in Choice::ALL { let base = Choice::every(true); let on = committed_profiles_with(choice.set(base, true)).expect("profiles"); let off = committed_profiles_with(choice.set(base, false)).expect("profiles"); - assert!(on.len() >= 10, "{} profiles", on.len()); for ((stem, p), (_, q)) in on.iter().zip(&off) { let metal = is_moltenvk_capture(stem); assert_eq!(choice.taken(p), !metal, "{stem} {choice:?} on"); assert!(!choice.taken(q), "{stem} {choice:?} off"); - let moved = p.fingerprint() != q.fingerprint(); - assert_eq!( - moved, - !metal || choice == Choice::NanMinMax, - "{stem} {choice:?}" - ); + assert_ne!(p.fingerprint(), q.fingerprint(), "{stem} {choice:?}"); } } } -/// On lavapipe each kernel records its kind exactly where its own choice is on, under every setting -/// of the others (all of them on and all of them off); where it is on the module is smaller than -/// where it is off, passes L3 either way, and records no kind of a choice that is off. With every -/// choice on, each module is its entry alone (no routine). +/// On lavapipe each kernel of a choice records its kind exactly where its choice is on, and each +/// other kernel records its kind under every setting (all of them on and all of them off); where +/// a choice is on its kernel's module is smaller than where it is off, passes L3 either way, and +/// records no kind of a choice that is off. Each module is its entry alone (no routine). #[test] fn each_choice_records_its_kinds_only_when_on() { let Some(bc) = bitcode() else { @@ -336,22 +304,22 @@ fn each_choice_records_its_kinds_only_when_on() { let base = Choice::every(others); for k in &KERNELS { let words = |on: bool| { - let policy = k.choice.set(base, on); + let policy = k.choice.map_or(base, |c| c.set(base, on)); let p = profile("lavapipe", policy).expect("profile"); let what = format!("{} {:?} on {on}, others {others}", k.name, k.choice); let a = compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); assert_eq!( a.precision.contains(&k.note), - on, + on || k.choice.is_none(), "{what}: {:?}", a.precision ); for c in Choice::ALL { - if c != k.choice && !others { + if Some(c) != k.choice && !others { let theirs: Vec<_> = KERNELS .iter() - .filter(|o| o.choice == c && o.note != k.note) + .filter(|o| o.choice == Some(c) && o.note != k.note) .map(|o| o.note) .collect(); assert!( @@ -361,18 +329,13 @@ fn each_choice_records_its_kinds_only_when_on() { ); } } - if on && others { - assert_eq!(functions(&a.module.words), 1, "{what}: no routine"); - } - if !on && !others { - assert!( - NATIVES.iter().all(|n| !a.precision.contains(n)), - "{what}: {:?}", - a.precision - ); - } + assert_eq!(functions(&a.module.words), 1, "{what}: no routine"); a.module.words.len() }; + if k.choice.is_none() { + words(true); + continue; + } let (on, off) = (words(true), words(false)); assert!( on < off, @@ -385,38 +348,30 @@ fn each_choice_records_its_kinds_only_when_on() { /// On lavapipe the maths functions' device forms compute within the bounds their notes state on the /// interpreter (which models the divisions and the `half` `fma`, not the transcendental -/// instructions), and Metal's off: the correctly rounded quotient, `x` times `RN(1 / y)` for an -/// `arcp` one, the correctly rounded `half` `fma`. +/// instructions). #[test] -fn the_maths_functions_are_within_their_bounds_on_and_metal_s_off() { +fn the_maths_functions_are_within_their_bounds() { let Some(bc) = bitcode() else { return; }; - let on = profile("lavapipe", Choice::Maths.set(Choice::every(false), true)).expect("on"); - let off = profile("lavapipe", Choice::every(false)).expect("off"); + let p = profile("lavapipe", DevicePolicy::default()).expect("lavapipe"); for (a, b) in [(1.0f32, 3.0f32), (-3.0, 0.7), (0.75, -4.1), (1e-30, 3e7)] { for div in ["native_fdiv", "native_fdiv_arcp"] { - let q = interpret(&bc, div, &on, [a, b, 0.0]); + let q = interpret(&bc, div, &p, [a, b, 0.0]); assert!( ulps(q, f64::from(a) / f64::from(b)) <= 2.5, "{div}({a}, {b})" ); } - let exact = interpret(&bc, "native_fdiv", &off, [a, b, 0.0]); - assert_eq!(exact, (f64::from(a) / f64::from(b)) as f32, "{a} / {b}"); - let fast = interpret(&bc, "native_fdiv_arcp", &off, [a, b, 0.0]); - assert_eq!(fast, a * (1.0 / b), "{a} / {b} arcp"); } // A precise division's divisor past `2^126` is scaled into Vulkan's range. let big = 2f32.powi(127); - assert_eq!(interpret(&bc, "native_fdiv", &on, [big, big, 0.0]), 1.0); + assert_eq!(interpret(&bc, "native_fdiv", &p, [big, big, 0.0]), 1.0); // `half` `fma(1.5, 2.25, 0.125)` is exact: 3.5. - for p in [&on, &off] { - assert_eq!( - interpret(&bc, "native_half_fma", p, [1.5, 2.25, 0.125]), - 3.5 - ); - } + assert_eq!( + interpret(&bc, "native_half_fma", &p, [1.5, 2.25, 0.125]), + 3.5 + ); } /// On lavapipe with the NaN and minimum and maximum on, an addition answers the device's NaN (a @@ -465,18 +420,17 @@ fn the_nan_and_min_max_are_the_device_s_on_and_metal_s_off() { ); } -/// On lavapipe with the rounding order on, `dot` is the device's `OpDot` and `mix` its `FMix` (a -/// `half` one rounded once), each within the bound its note states, and `fast::sqrt` the device's -/// `Sqrt`, within Vulkan's `1 / InverseSqrt` (4.5 ulp); off, `dot` is Metal's fused chain and `mix` -/// its `fma(t, y, fma(-t, x, x))`, word for word. +/// On lavapipe `dot` is the device's `OpDot` and `mix` its `FMix` (a `half` one rounded once), each +/// within the bound its note states, and `fast::sqrt` the device's `Sqrt`, within Vulkan's +/// `1 / InverseSqrt` (4.5 ulp); on MoltenVK, whose functions are Metal's, `dot` is Metal's fused +/// chain and `mix` its `fma(t, y, fma(-t, x, x))`, word for word. #[test] -fn the_rounding_order_is_the_device_s_on_and_metal_s_off() { +fn dot_mix_and_fast_sqrt_are_the_device_s_and_metal_s_on_moltenvk() { let Some(bc) = bitcode() else { return; }; - let base = Choice::every(true); - let on = profile("lavapipe", Choice::RoundingOrder.set(base, true)).expect("on"); - let off = profile("lavapipe", Choice::RoundingOrder.set(base, false)).expect("off"); + let on = profile("lavapipe", DevicePolicy::default()).expect("lavapipe"); + let metal = profile("moltenvk-m3", DevicePolicy::default()).expect("moltenvk-m3"); for [a, b, c] in [ [1.0f32, 3.0, 0.5], [-3.0, 0.7, 1.9], @@ -492,7 +446,7 @@ fn the_rounding_order_is_the_device_s_on_and_metal_s_off() { "dot({a}, {b}, {c}) = {dot}" ); assert_eq!( - interpret(&bc, "native_dot", &off, [a, b, c]), + interpret(&bc, "native_dot", &metal, [a, b, c]), b.mul_add(a, a * c), "Metal's dot({a}, {b}, {c})" ); @@ -504,16 +458,16 @@ fn the_rounding_order_is_the_device_s_on_and_metal_s_off() { "mix({a}, {b}, {c}) = {mix}" ); assert_eq!( - interpret(&bc, "native_mix", &off, [a, b, c]), + interpret(&bc, "native_mix", &metal, [a, b, c]), c.mul_add(b, (-c).mul_add(a, a)), "Metal's mix({a}, {b}, {c})" ); } // `half` `mix(0.5, 1.5, 0.25)` is exact: 0.75. - for p in [&on, &off] { + for p in [&on, &metal] { assert_eq!(interpret(&bc, "native_half_mix", p, [0.5, 1.5, 0.25]), 0.75); } - // On, `fast::sqrt`'s zero and `+inf` are IEEE's, as Metal's (the interpreter leaves off's + // `fast::sqrt`'s zero and `+inf` are IEEE's, as Metal's (the interpreter leaves MoltenVK's // `InverseSqrt` unmodelled). let sqrt = |x: f32| interpret(&bc, "native_fast_sqrt", &on, [x, 0.0, 0.0]); for x in [2.0f32, 0.75, 1e-30, 3e30] { diff --git a/crates/metal2vulkan/src/tests/engine_roll.rs b/crates/metal2vulkan/src/tests/engine_roll.rs index 08b794ba6..1d9b5462e 100644 --- a/crates/metal2vulkan/src/tests/engine_roll.rs +++ b/crates/metal2vulkan/src/tests/engine_roll.rs @@ -22,7 +22,7 @@ use crate::spirv::ir::TypedModule; use crate::spirv::roll::{entry_weight, ROLL_ABOVE}; /// The `float` operations of the body: two inlined copies are above `ROLL_ABOVE`. -const OPS: usize = 8_000; +const OPS: usize = 13_000; /// The operations before the body's first selection; each later stretch is one longer than the /// one before, and [`halves`] picks each operation, so no stretch of the body repeats another diff --git a/crates/metal2vulkan/src/tests/engine_spirv_cross_forms.rs b/crates/metal2vulkan/src/tests/engine_spirv_cross_forms.rs index c0f8bd473..5faea4129 100644 --- a/crates/metal2vulkan/src/tests/engine_spirv_cross_forms.rs +++ b/crates/metal2vulkan/src/tests/engine_spirv_cross_forms.rs @@ -289,11 +289,10 @@ fn only_the_entry_reads_the_coverage_of_a_looped_body() { /// requires `VkProperty::MetalHalfFma`; on macOS it compiles as MoltenVK's MSL. A profile that /// rounds a `half` under the 16-bit float controls (`QuantizeForm::Controlled`: ANV and RADV) with /// `shaderFmaFloat16` takes `OpFmaKHR` on 16 bits (`fma::Route::F16Khr`), inline and under no note. -/// Every other committed profile takes native device maths (the default): the device's `float` +/// Every other committed profile takes the device's `float` /// `Fma` rounded to `half`, inline too, under `PrecisionNote::NativeFma`; it holds a 16-bit float /// only where it rounds a `half` through the device's conversion, measured -/// (`QuantizeForm::Converted`) or under the float controls. Under `FloatMathsPolicy::Exact` it -/// calls the `half` routine where it takes neither 16-bit form. +/// (`QuantizeForm::Converted`) or under the float controls. #[test] fn a_half_fused_multiply_add_is_inline_on_moltenvk() { let Some(lib) = library("fmx_fma_precise") else { diff --git a/crates/metal2vulkan/src/tests/engine_texture.rs b/crates/metal2vulkan/src/tests/engine_texture.rs index 0199efc7f..4a5473ed9 100644 --- a/crates/metal2vulkan/src/tests/engine_texture.rs +++ b/crates/metal2vulkan/src/tests/engine_texture.rs @@ -1032,11 +1032,9 @@ fn nil_census(bc: &[u8], name: &str, p: &DeviceProfile, stem: &str) -> NilCensus all.clone().count(), all.map(|s| u64::from(s.words())).sum::(), ); - // The arm's `fast::sin` calls the math library's routines where the device's functions are - // not Metal's and the maths are exact (`FloatMathsPolicy::Exact`; the test takes it, as native - // device maths calls no routine): shared routines, whose words the census counts once under - // their own names, with no uses. So the census words are the strategies' words and those - // routines', partitioned: the arm's leave their names, and none is counted twice or dropped. + // A shared routine's words the census counts once under its own name, with no uses. So the + // census words are the strategies' words and the shared routines', partitioned: the arm's + // leave their names, and none is counted twice or dropped. let mut routines: BTreeMap = BTreeMap::new(); for (n, w) in crate::lower::arith::routine_words(&plan.families.arith) { *routines.entry(n.to_owned()).or_default() += w; diff --git a/crates/metal2vulkan/src/tests/engine_tiny_products.rs b/crates/metal2vulkan/src/tests/engine_tiny_products.rs index 2676851d1..d07eb019b 100644 --- a/crates/metal2vulkan/src/tests/engine_tiny_products.rs +++ b/crates/metal2vulkan/src/tests/engine_tiny_products.rs @@ -5,24 +5,20 @@ //! macOS 27.0.1 are `tiny_products_m3.txt` (the authored cases of the fixtures, //! `float-products-flushed-before-rounding` and its fast-math twin). //! A Vulkan device rounds first, so an exact product within half a unit below `2^-126` answers -//! `2^-126` there. +//! `2^-126` there, and the module takes the device's multiply (announced once per device, +//! `float-tininess-after-rounding`). //! //! The CPU SPIR-V interpreter rounds first and keeps denormals, as a device without //! `DriverDeviation::MetalFloatDenormals` may, so on each such committed profile (one per fused -//! multiply-add route and routine of its small results) it shows what each policy answers: under -//! `FloatMathsPolicy::Exact` every word is Metal's; under the default a product is the device's, -//! rounded first (announced once per device, `float-tininess-after-rounding`). On every committed -//! profile the check of a product (`arith.float.tiny`) is compiled exactly where the profile's -//! functions are to answer as Metal's (`denormal::checks_tiny_products`), inline and branchless. -//! `llvm-as` assembles the fixtures; without it the tests skip visibly. +//! multiply-add route) it shows what the device answers. `llvm-as` assembles the fixtures; without +//! it the tests skip visibly. -use crate::device::profile::FloatFunctions; use crate::device::{DevicePolicy, DeviceProfile}; use crate::error::DriverDeviation; use crate::lower::arith::fma; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; use crate::pipeline::testing::{ - compile, exact_maths, link_and_validate, llvm_assemble, typed_module, AssembleError, + compile, link_and_validate, llvm_assemble, typed_module, AssembleError, }; use crate::spirv::interp::{run, Buffer, Config, Resources}; use crate::spirv::testing::committed_profiles_with; @@ -34,14 +30,10 @@ const WORDS: &str = include_str!("tiny_products_m3.txt"); /// The fixtures' entries: without and with fast math. const ENTRIES: [&str; 2] = ["tiny_products_flush", "tiny_products_flush_fast"]; -/// The census name of a product's check. -const TINY: &str = "arith.float.tiny"; - /// A thread past the authored cases', its words measured on the same M3 Max under macOS 27.0.1 by /// the fixtures' own source: `(2 - 2^-23) · 2^-126`, a normal `float`, times `±0.5` on each lane, /// whose exact product `±(2^-126 - 2^-150)` a device that rounds first ties to `±2^-126`, where -/// Metal answers the zero of its sign. A product by a constant of magnitude at least 1 is never -/// checked (its product is a zero or at least the other operand's magnitude), but one by `0.5` is. +/// Metal answers the zero of its sign. const HALF_A_NORMAL: &str = concat!( "00ffffff 80ffffff 3f000000 00ffffff 3f000000 3f000000 00ffffff bf000000 ", "00000000 80000000 00000000 80000000 00000000 80000000 ", @@ -145,107 +137,44 @@ fn interpret(bc: &[u8], entry: &str, p: &DeviceProfile, threads: &[Thread]) -> V .collect() } -/// The committed profiles under `policy` whose device may keep denormals (no +/// The committed profiles whose device may keep denormals (no /// `DriverDeviation::MetalFloatDenormals`), as the interpreter does, one per fused multiply-add -/// route and routine of its small results ([`fma::tiny_route`]). -fn keeping(policy: DevicePolicy) -> Vec<(String, DeviceProfile)> { +/// route. +fn keeping() -> Vec<(String, DeviceProfile)> { let mut seen = BTreeSet::new(); - committed_profiles_with(policy) + committed_profiles_with(DevicePolicy::default()) .expect("profiles") .into_iter() .filter(|(_, p)| !p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals)) - .filter(|(_, p)| seen.insert((fma::float_route(p), fma::tiny_route(p)))) + .filter(|(_, p)| seen.insert(fma::float_route(p))) .collect() } -/// An `f32` denormal as the zero of its sign. -fn ftz(x: u32) -> u32 { - if x & 0x7F80_0000 == 0 { - x & 0x8000_0000 - } else { - x - } +/// Whether `x` is an `f32` denormal. +fn denormal(x: u32) -> bool { + x & 0x7F80_0000 == 0 && x & 0x007F_FFFF != 0 } -/// The product of `a` and `b` on a device that rounds first and keeps denormals, its operands and -/// result read as Metal reads a denormal (the module flushes them there). -fn device_mul(a: u32, b: u32) -> u32 { - let f = |x: u32| f32::from_bits(ftz(x)); - ftz((f(a) * f(b)).to_bits()) -} - -/// Whether every committed profile under `policy` compiles a product's check exactly where its -/// functions are to answer as Metal's, and how many do. -fn checks_where_device_functions(bc: &[u8], entry: &str, policy: DevicePolicy) -> usize { - let mut checking = 0; - for (stem, p) in committed_profiles_with(policy).expect("profiles") { - let what = format!("{entry} on {stem}"); - let a = compile(bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let device = p.fields().float_functions == FloatFunctions::Device; - assert_eq!(a.strategies.entries.contains_key(TINY), device, "{what}"); - checking += usize::from(device); - } - checking -} - -/// Under `FloatMathsPolicy::Exact` every committed profile whose functions are not Metal's own -/// checks its products (MoltenVK's multiply is Metal's), and on each one that may keep a denormal -/// every word, multiplies and `dot`s alike, is Metal's. +/// On a device that may keep a denormal each product is the device's (here the interpreter's IEEE +/// product, rounded first, denormals kept), which differs from Metal's word only where Metal +/// flushes: a product that rounds up to `2^-126` of its sign where Metal answers the zero of its +/// sign (`float-tininess-after-rounding`; some lanes do), or a denormal operand or result +/// (`PrecisionNote::DeviceDenormals`). Every committed profile compiles the fixtures and passes L3. #[test] -fn exact_float_maths_flushes_a_tiny_product_as_metal() { +fn a_tiny_product_is_the_device_s() { let threads = threads(); for (i, entry) in ENTRIES.into_iter().enumerate() { let Some(bc) = assemble(entry) else { return; }; - let checking = checks_where_device_functions(&bc, entry, exact_maths()); - assert!(checking > 0, "{entry}: no profile checks a product"); - let profiles = keeping(exact_maths()); + for (stem, p) in committed_profiles_with(DevicePolicy::default()).expect("profiles") { + let what = format!("{entry} on {stem}"); + let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + } + let profiles = keeping(); assert!(!profiles.is_empty(), "no profile keeps denormals"); for (stem, p) in profiles { - let got = interpret(&bc, entry, &p, &threads); - let wrong: Vec = threads - .iter() - .zip(&got) - .enumerate() - .flat_map(|(t, (thread, words))| { - (0..12) - .filter(|&w| words[w] != thread.metal[i][w]) - .map(move |w| { - format!( - "thread {t} word {w}: {:08x}, Metal {:08x}", - words[w], thread.metal[i][w] - ) - }) - }) - .collect(); - assert!( - wrong.is_empty(), - "{entry} on {stem}: {} words off Metal's: {:#?}", - wrong.len(), - &wrong[..wrong.len().min(20)] - ); - } - } -} - -/// Under the default policy no profile checks a product: on a device that may keep a denormal -/// each product is the device's, rounded first, which answers `2^-126` of its sign on lanes where -/// Metal answers the zero of its sign (some do), and Metal's word on every other lane. -#[test] -fn the_default_leaves_a_tiny_product_to_the_device() { - let threads = threads(); - for (i, entry) in ENTRIES.into_iter().enumerate() { - let Some(bc) = assemble(entry) else { - return; - }; - let checking = checks_where_device_functions(&bc, entry, DevicePolicy::default()); - assert_eq!( - checking, 0, - "{entry}: a profile checks a product by default" - ); - for (stem, p) in keeping(DevicePolicy::default()) { let got = interpret(&bc, entry, &p, &threads); let mut rounded_first = 0; for (t, (thread, words)) in threads.iter().zip(&got).enumerate() { @@ -253,19 +182,21 @@ fn the_default_leaves_a_tiny_product_to_the_device() { let products = words.iter().zip(&thread.metal[i]).take(8); for (w, (&got, &metal)) in products.enumerate() { let l = w % 4; - let device = device_mul(thread.input[l], thread.input[4 + l]); + let (a, b) = (thread.input[l], thread.input[4 + l]); + let device = (f32::from_bits(a) * f32::from_bits(b)).to_bits(); assert_eq!( got, device, "{entry} on {stem}: thread {t} word {w}, Metal {metal:08x}" ); - if device != metal { - assert_eq!( - (device & 0x7FFF_FFFF, device & 0x8000_0000), - (0x0080_0000, metal), - "{entry} on {stem}: thread {t} word {w}: only a tiny product differs" - ); - rounded_first += 1; + if device == metal || denormal(a) || denormal(b) || denormal(device) { + continue; } + assert_eq!( + (device & 0x7FFF_FFFF, device & 0x8000_0000), + (0x0080_0000, metal), + "{entry} on {stem}: thread {t} word {w}: only a tiny product differs" + ); + rounded_first += 1; } } assert!( @@ -276,171 +207,17 @@ fn the_default_leaves_a_tiny_product_to_the_device() { } } -/// The `UMulExtended` instructions inside the entry point's own function of module `words`. -fn entry_umul_extended(words: &[u32]) -> usize { - use crate::spv::Op; - let instructions = || { - let mut i = 5; - std::iter::from_fn(move || { - let len = (*words.get(i)? >> 16) as usize; - assert!(len > 0 && i + len <= words.len(), "malformed module"); - let at = &words[i..i + len]; - i += len; - Some(at) - }) - }; - let entry = instructions() - .find(|at| at[0] & 0xFFFF == Op::EntryPoint as u32) - .map(|at| at[2]) - .expect("an entry point"); - let (mut inside, mut n) = (false, 0); - for at in instructions() { - let op = at[0] & 0xFFFF; - if op == Op::Function as u32 { - inside = at[2] == entry; - } else if op == Op::FunctionEnd as u32 { - inside = false; - } else if op == Op::UMulExtended as u32 && inside { - n += 1; - } - } - n -} - -/// Under `FloatMathsPolicy::Exact` each product's check is inline and branchless, in the form the -/// profile takes (`denormal::tiny_check`): where its `float` fused multiply-add is `OpFmaKHR`, one -/// `OpFmaKHR` on the operands' magnitudes and no integer product; elsewhere the operands' bits, -/// one `UMulExtended` a check (nine in each fixture: the vector product, the four scalar ones and -/// each `dot`'s first). The plan's size estimate bounds the module. +/// The fast entry declares no `SignedZeroInfNanPreserve`, at 32 bits or 64, on any committed +/// profile: nothing in it answers a zero's sign. #[test] -fn a_product_s_check_is_inline_in_the_profile_s_form() { - use crate::lower::arith::denormal::{tiny_check, TinyCheck}; - for entry in ENTRIES { - let Some(bc) = assemble(entry) else { - return; - }; - let mut forms = BTreeSet::new(); - for (stem, p) in committed_profiles_with(exact_maths()).expect("profiles") { - let Some(check) = tiny_check(&p) else { - continue; - }; - let what = format!("{entry} on {stem}"); - let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let products = entry_umul_extended(&a.module.words); - let want = match check { - TinyCheck::Fused => 0, - TinyCheck::Bits => 9, - }; - assert_eq!(products, want, "{what}: {check:?}"); - let (plan, _) = typed_module(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - let words = a.module.words.len() as u64; - assert!( - plan.estimate.words >= words, - "{what}: estimate {} < emitted {words}", - plan.estimate.words - ); - forms.insert(format!("{check:?}")); - } - assert!( - forms.contains("Fused"), - "{entry}: no profile checks by OpFmaKHR: {forms:?}" - ); - } -} - -/// The functions of module `words` declared `DontInline` (`OpFunction`'s control `0x2`). -fn dont_inline_functions(words: &[u32]) -> usize { - use crate::spv::Op; - let mut i = 5; - let mut found = 0; - 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 == Op::Function as u32 && words[i + 3] & 0x2 != 0 { - found += 1; - } - i += len; - } - found -} - -/// Under `FloatMathsPolicy::Exact` a checked `OpFmaKHR` (`dot`'s chain in the fixtures) answers -/// its small results by a plain routine, which a driver may inline: NVIDIA keeps a call declared -/// `DontInline`, and on the RTX 5080 (615.71.09) the call cost more than the inlined routine, in -/// pipeline creation and in GPU time. No function of the fixture is declared so, on any profile. -#[test] -fn the_routine_of_small_fma_results_is_not_declared_dont_inline() { - use crate::lower::arith::fma::tiny_route; - let entry = ENTRIES[0]; - let Some(bc) = assemble(entry) else { - return; - }; - let mut checked = 0; - for (stem, p) in committed_profiles_with(exact_maths()).expect("profiles") { - if tiny_route(&p).is_none() { - continue; - } - let what = format!("{entry} on {stem}"); - let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(dont_inline_functions(&a.module.words), 0, "{what}"); - checked += 1; - } - assert!(checked > 0, "no profile checks OpFmaKHR"); -} - -/// A check that answers Metal's zero of its sign keeps zero signs, in a fast-math entry too: a -/// product's at `±2^-126` and `dot`'s chain, a checked `OpFmaKHR` or a fused multiply-add routine, -/// make the entry declare `SignedZeroInfNanPreserve 32`, and the chain whose routine computes in -/// `double` (`fma::small`, the `double` route) `64`, each where the profile supports it, else note -/// `DeviceSignedZeroInfNan`. Without the mode Vulkan -/// lets a device answer a zero of either sign from any float operation: NVIDIA's 615.71.09 on the -/// RTX 3090 answered `-0` for a checked `fma(+0, 100, +0)`, where Metal answers `+0`. Under the -/// default policy nothing is checked, and the fast entry declares neither. -#[test] -fn checks_that_answer_a_zero_s_sign_keep_zero_signs() { +fn the_fast_entry_keeps_no_zero_signs() { use super::engine_arith::declares_signed_zero_inf_nan; - use crate::pipeline::artifact::PrecisionNote; let entry = ENTRIES[1]; let Some(bc) = assemble(entry) else { return; }; - let mut declared = [0; 2]; - for (stem, p) in committed_profiles_with(exact_maths()).expect("profiles") { - let what = format!("{entry} on {stem}"); - let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - // The fixture's products are checked where the profile checks one, and `dot`'s chain is - // then a checked `OpFmaKHR` or a routine, in `double` on the `double` route. - let tiny = fma::tiny_route(&p); - let exact = p.fields().float_functions == FloatFunctions::Device; - let wide = fma::float_route(&p) == fma::Route::Wide || tiny == Some(fma::Route::Wide); - let wanted = [ - a.strategies.entries.contains_key(TINY) || tiny.is_some(), - exact && wide, - ]; - let fc = p.fields().float_controls; - let supported = [ - fc.f32.signed_zero_inf_nan_preserve, - fc.f64.signed_zero_inf_nan_preserve, - ]; - for (i, width) in [32, 64].into_iter().enumerate() { - let mode = declares_signed_zero_inf_nan(&words, width); - assert_eq!(mode, wanted[i] && supported[i], "{what}: mode {width}"); - declared[i] += usize::from(mode); - } - let unsupported = (0..2).any(|i| wanted[i] && !supported[i]); - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceSignedZeroInfNan), - unsupported, - "{what}: note" - ); - } - assert!( - declared.iter().all(|&n| n > 0), - "no profile declares a width: {declared:?}" - ); for (stem, p) in committed_profiles_with(DevicePolicy::default()).expect("profiles") { - let what = format!("{entry} on {stem} by default"); + let what = format!("{entry} on {stem}"); let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); for width in [32, 64] { diff --git a/crates/metal2vulkan/src/tests/fast_paths.rs b/crates/metal2vulkan/src/tests/fast_paths.rs index be1c22824..bc3e7433f 100644 --- a/crates/metal2vulkan/src/tests/fast_paths.rs +++ b/crates/metal2vulkan/src/tests/fast_paths.rs @@ -7,10 +7,9 @@ //! classed, and so reaches the ledger. use crate::device::{ - BatchOrderPolicy, CompletionPolicy, DecodedTexelsPolicy, DevicePolicy, FloatMathsPolicy, - HeapCompressionPolicy, HostPageTexturePolicy, NanMinMaxPolicy, RenderLoweringPolicy, - RoundingOrderPolicy, SamplingPolicy, TexelConversionPolicy, Unorm8LinearFilterPolicy, - VertexNormalizedPolicy, YCbCrFilterPolicy, + BatchOrderPolicy, CompletionPolicy, DecodedTexelsPolicy, DevicePolicy, HeapCompressionPolicy, + HostPageTexturePolicy, NanMinMaxPolicy, RenderLoweringPolicy, SamplingPolicy, + TexelConversionPolicy, Unorm8LinearFilterPolicy, VertexNormalizedPolicy, YCbCrFilterPolicy, }; use crate::pipeline::PrecisionNote; use std::collections::BTreeSet; @@ -63,11 +62,9 @@ fn choices() -> Vec { unorm8_linear_filter: _, sampling: _, ycbcr_filter: _, - float_maths: _, texel_conversion: _, vertex_normalized: _, nan_and_min_max: _, - rounding_order: _, // The runtime's: the texels of a carried texture's decoded twin, a heap's compressed // texture's image, when the host sees a command buffer complete, how a batch begins after // the earlier ones of its queue, where a render encoder's calls are lowered, and what holds @@ -83,11 +80,9 @@ fn choices() -> Vec { choice!(p.unorm8_linear_filter: Unorm8LinearFilterPolicy { Exact, DeviceWithinOneCode }), choice!(p.sampling: SamplingPolicy { NativeDevice, Exact }), choice!(p.ycbcr_filter: YCbCrFilterPolicy { Device, Exact }), - choice!(p.float_maths: FloatMathsPolicy { Native, Exact }), choice!(p.texel_conversion: TexelConversionPolicy { Device, Exact }), choice!(p.vertex_normalized: VertexNormalizedPolicy { Device, Exact }), choice!(p.nan_and_min_max: NanMinMaxPolicy { Native, Exact }), - choice!(p.rounding_order: RoundingOrderPolicy { Native, Exact }), choice!(p.decoded_texels: DecodedTexelsPolicy { Compact, Exact }), choice!(p.heap_compression: HeapCompressionPolicy { Compressed, Uncompressed }), choice!(p.completion: CompletionPolicy { Grouped, Exact }), @@ -131,13 +126,8 @@ fn notes() -> Vec<(&'static str, Ledger)> { DeviceSampling, DeviceTexelConversion, HalfTexelConversion, - NativeTranscendentals, - NativeDivision, - NativeFma, NativeNanEncoding, NativeMinMax, - NativeDot, - NativeMix, ], NotBuilt: [ ExtendedRangeBlendSource, @@ -146,6 +136,11 @@ fn notes() -> Vec<(&'static str, Ledger)> { ], OptIn: [DeviceUnorm8LinearFilter], DeviceGap: [ + NativeTranscendentals, + NativeDivision, + NativeFma, + NativeDot, + NativeMix, DeviceDenormals, DeviceTexelDenormals, RestrictedDepthRange, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 39a4cca80..4a0661d11 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1455,7 +1455,6 @@ enum metal2vulkan::device::DriverFact #[derive(Clone, Copy, Debug, PartialEq, Eq enum metal2vulkan::device::DriverWorkaround #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum DriverWorkaround enum metal2vulkan::device::Exposure #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum Exposure enum metal2vulkan::device::FloatControl #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum FloatControl -enum metal2vulkan::device::FloatMathsPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum FloatMathsPolicy enum metal2vulkan::device::FloatWidth #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum FloatWidth enum metal2vulkan::device::FormatUsage #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum FormatUsage enum metal2vulkan::device::FunctionStorage #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum FunctionStorage @@ -1469,7 +1468,6 @@ enum metal2vulkan::device::PointerDomain #[cfg_attr(feature = "serde", derive(se enum metal2vulkan::device::RenderLoweringPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum RenderLoweringPolicy enum metal2vulkan::device::ResolveMode #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ResolveMode enum metal2vulkan::device::Robustness #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Robustness -enum metal2vulkan::device::RoundingOrderPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum RoundingOrderPolicy enum metal2vulkan::device::SamplingPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum SamplingPolicy enum metal2vulkan::device::SimdClass #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum SimdClass enum metal2vulkan::device::SpirvExtension #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum SpirvExtension @@ -3712,7 +3710,6 @@ field metal2vulkan::device::DevicePolicy.batch_order pub batch_order: BatchOrder field metal2vulkan::device::DevicePolicy.completion pub completion: CompletionPolicy field metal2vulkan::device::DevicePolicy.containment pub containment: ContainmentPolicy field metal2vulkan::device::DevicePolicy.decoded_texels pub decoded_texels: DecodedTexelsPolicy -field metal2vulkan::device::DevicePolicy.float_maths pub float_maths: FloatMathsPolicy field metal2vulkan::device::DevicePolicy.handle_domain pub handle_domain: HandleDomain field metal2vulkan::device::DevicePolicy.heap_compression pub heap_compression: HeapCompressionPolicy field metal2vulkan::device::DevicePolicy.host_page_textures pub host_page_textures: HostPageTexturePolicy @@ -3720,7 +3717,6 @@ field metal2vulkan::device::DevicePolicy.isolation pub isolation: GuestIsolation field metal2vulkan::device::DevicePolicy.nan_and_min_max pub nan_and_min_max: NanMinMaxPolicy field metal2vulkan::device::DevicePolicy.pointer_domain pub pointer_domain: PointerDomain field metal2vulkan::device::DevicePolicy.render_lowering pub render_lowering: RenderLoweringPolicy -field metal2vulkan::device::DevicePolicy.rounding_order pub rounding_order: RoundingOrderPolicy field metal2vulkan::device::DevicePolicy.sampling pub sampling: SamplingPolicy field metal2vulkan::device::DevicePolicy.texel_conversion pub texel_conversion: TexelConversionPolicy field metal2vulkan::device::DevicePolicy.unorm8_linear_filter pub unorm8_linear_filter: Unorm8LinearFilterPolicy @@ -12472,8 +12468,6 @@ variant metal2vulkan::device::FloatControl::DenormPreserve DenormPreserve variant metal2vulkan::device::FloatControl::RoundingModeRte RoundingModeRte variant metal2vulkan::device::FloatControl::RoundingModeRtz RoundingModeRtz variant metal2vulkan::device::FloatControl::SignedZeroInfNanPreserve SignedZeroInfNanPreserve -variant metal2vulkan::device::FloatMathsPolicy::Exact Exact -variant metal2vulkan::device::FloatMathsPolicy::Native Native variant metal2vulkan::device::FloatWidth::F16 F16 variant metal2vulkan::device::FloatWidth::F32 F32 variant metal2vulkan::device::FloatWidth::F64 F64 @@ -12517,8 +12511,6 @@ variant metal2vulkan::device::ResolveMode::SampleZero SampleZero variant metal2vulkan::device::Robustness::None None variant metal2vulkan::device::Robustness::Rba Rba variant metal2vulkan::device::Robustness::Rba2 Rba2 -variant metal2vulkan::device::RoundingOrderPolicy::Exact Exact -variant metal2vulkan::device::RoundingOrderPolicy::Native Native variant metal2vulkan::device::SamplingPolicy::Exact Exact variant metal2vulkan::device::SamplingPolicy::NativeDevice NativeDevice variant metal2vulkan::device::SimdClass::CrossLane CrossLane(OpBits) @@ -13720,7 +13712,7 @@ variant metal2vulkan::pipeline::RuntimeFact::DeviceAddresses DeviceAddresses { s variant metal2vulkan::pipeline::RuntimeFact::DispatchGrid DispatchGrid variant metal2vulkan::pipeline::RuntimeFact::DroppedColor DroppedColor { color: u32 } variant metal2vulkan::pipeline::RuntimeFact::EmulatedSimdgroups EmulatedSimdgroups -variant metal2vulkan::pipeline::RuntimeFact::ExactFormsOverCompilerLimit ExactFormsOverCompilerLimit { sampling: bool, float_maths: bool, texel_conversion: bool, nan_and_min_max: bool, rounding_order: bool } +variant metal2vulkan::pipeline::RuntimeFact::ExactFormsOverCompilerLimit ExactFormsOverCompilerLimit { sampling: bool, texel_conversion: bool, nan_and_min_max: bool } variant metal2vulkan::pipeline::RuntimeFact::ExecutionStatus ExecutionStatus variant metal2vulkan::pipeline::RuntimeFact::ExtendedRangeInputBlend ExtendedRangeInputBlend { color: u32, blend: crate::pipeline::lower_inputs::BlendEquation, kept: crate::vk::ColorComponentFlags } variant metal2vulkan::pipeline::RuntimeFact::FlatGrid FlatGrid diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 374e251e4..9df7cb625 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -227,11 +227,9 @@ surface! { enum Unorm8LinearFilterPolicy N; enum SamplingPolicy N; enum YCbCrFilterPolicy N; - enum FloatMathsPolicy N; enum TexelConversionPolicy N; enum VertexNormalizedPolicy N; enum NanMinMaxPolicy N; - enum RoundingOrderPolicy N; enum DecodedTexelsPolicy N; enum HeapCompressionPolicy N; enum CompletionPolicy N; @@ -1048,9 +1046,7 @@ surface! { use metal2vulkan::bind::{BindState, BoundBuffer, Dispatch, DrawCall, StageTable}; use metal2vulkan::cache::{Hash256, PipelineArtifact, PipelineKey}; -use metal2vulkan::device::{ - Device, DeviceDescription, DevicePolicy, FloatMathsPolicy, FloatWidth, NanMinMaxPolicy, -}; +use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy, FloatWidth, NanMinMaxPolicy}; use metal2vulkan::library::{CompiledFunction, Library}; use metal2vulkan::metal::{PixelFormat, VertexFormat}; use metal2vulkan::pipeline::{ @@ -1338,13 +1334,13 @@ 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 and NaN where the policy takes both -/// (`NativeDivision`, `NativeNanEncoding`, native device maths), the division alone under -/// `NanMinMaxPolicy::Exact` and nothing under `FloatMathsPolicy::Exact`, 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. +/// Metal's precise division records the device's division, its denormals and its NaN where the +/// policy takes the device's NaN (`NativeDivision`, `DeviceDenormals`, `NativeNanEncoding`), the +/// division and its denormals under `NanMinMaxPolicy::Exact`, an integer operator has no notes, and +/// 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. #[test] fn the_precision_contract_names_each_float_operations_notes() { use metal2vulkan_air::intrinsics::AirIntrinsic; @@ -1366,26 +1362,26 @@ fn the_precision_contract_names_each_float_operations_notes() { .expect("a float operator") .contains(&PrecisionNote::DeviceArithmetic)); let mut policy = DevicePolicy::default(); - policy.float_maths = FloatMathsPolicy::Native; policy.nan_and_min_max = NanMinMaxPolicy::Native; let native = device_under("lavapipe", policy); policy.nan_and_min_max = NanMinMaxPolicy::Exact; let metal_nans = device_under("lavapipe", policy); - policy.float_maths = FloatMathsPolicy::Exact; - let exact = device_under("lavapipe", policy); for (p, notes) in [ ( native.profile(), BTreeSet::from([ + PrecisionNote::DeviceDenormals, PrecisionNote::NativeDivision, PrecisionNote::NativeNanEncoding, ]), ), ( metal_nans.profile(), - BTreeSet::from([PrecisionNote::NativeDivision]), + BTreeSet::from([ + PrecisionNote::DeviceDenormals, + PrecisionNote::NativeDivision, + ]), ), - (exact.profile(), BTreeSet::new()), ] { assert_eq!( PrecisionNote::of_float_operator( diff --git a/docs/API.md b/docs/API.md index 079aa215c..fc8c94cad 100644 --- a/docs/API.md +++ b/docs/API.md @@ -84,11 +84,14 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: and guest shaders cannot reach each other's resources. Where the device enables `robustBufferAccess`, buffer accesses and vertex input are left to it. (MoltenVK advertises the feature without implementing it; there such accesses are not contained, as on native Metal.) +- **The device's arithmetic.** The device's own maths library, divisions, fused multiply-adds, + `float` denormals, and rounding order of `dot`/`mix`/`fast::sqrt`, on every device and with no + exact form. Each records a precision note with its bound; on MoltenVK on an Apple GPU, whose + `float` functions are Metal's own, they are Metal's answers. - **Fast native forms off Apple's GPUs.** The device's own sampler (its filter of a two-plane - YCbCr texture among them), maths library, divisions, fused multiply-adds, texel conversions, - NaN bits, min/max and rounding order of `dot`/`mix`/`fast::sqrt`. Each records a precision note - with its bound, and each has an exact switch. The device's own `half` rounding and its blend of - a `half` color have none: each records its note. + YCbCr texture among them), texel conversions, NaN bits and min/max. Each records a precision + note with its bound, and each has an exact switch. The device's own `half` rounding and its + blend of a `half` color have none: each records its note. `DevicePolicy::exact_answers()` turns on every exact form but sampling's, Metal's filter of a two-plane YCbCr texture (`YCbCrFilterPolicy::Exact`) included; `sampling = SamplingPolicy::Exact` emulates Metal's sampler too. @@ -2539,14 +2542,12 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. attachment, on ANV (`RuntimeDriverDefect::OcclusionCountPerColorOutput`). Cost: the result is Metal's count multiplied by the colors the draw writes; a `Boolean` result is Metal's. - `metal2vulkan-degrade-float-tininess-after-rounding` (precision). `FloatTininessAfterRounding`: A - device whose policy takes native device maths (`FloatMathsPolicy::Native`, the default) where its - float functions are not Metal's own (not MoltenVK): Metal flushes a `float` product or fused + device whose float functions are not Metal's own (not MoltenVK): Metal flushes a `float` product or fused multiply-add whose exact value lies below `2^-126` to the zero of its sign, deciding tininess before rounding, and the device rounds before it decides (measured on RADV, ANV, NVIDIA and lavapipe, whether they flush denormals or keep them). Announced once, as the device is made. Cost: a `float` product or fused multiply-add 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; `FloatMathsPolicy::Exact` - computes Metal's. + answers `2^-126` of its sign where Metal answers the zero of its sign. - `metal2vulkan-degrade-shader-cache-entry-not-written` (performance). `ShaderCacheEntryNotWritten`: an entry of the device's shader cache directory was not written -- the directory, a temporary file in it or the rename over the entry failed, on the device's cache @@ -2570,25 +2571,28 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. `maintenance8`, a fragment's implicit-level sample with a dynamic texel offset samples with its derivatives too, taken before the switch over the offset's values (`docs/FAST-PATHS.md`). - `metal2vulkan-degrade-device-transcendentals` (precision). `PrecisionNote::DeviceTranscendentals`: - Transcendentals answer within Apple's stated bound, not Metal's bits: the device's own functions, - or the translation's routines where a device's instruction may leave the bound (and, for the - functions no routine covers yet, the device's precision). + Transcendentals answer within Apple's stated bound, not Metal's bits: the device's own functions + where they are Metal's (MoltenVK), and the device's precision for a call no other note bounds. - `metal2vulkan-degrade-reduction-order` (precision). `PrecisionNote::ReductionOrder`: Float reductions use the device's association order. - `metal2vulkan-degrade-device-denormals` (precision). `PrecisionNote::DeviceDenormals`: `float` denormals follow the device: Metal reads an `f32` denormal operand of its float arithmetic, comparisons, and functions as the zero of its sign and flushes a denormal result to one, where a Vulkan device keeps or flushes them by its own float controls (this translation declares no - `DenormFlushToZero`). Recorded only by the instructions of native device maths - (`FloatMathsPolicy::Native`, `fast::fmod`'s fused multiply-add among them) and of the device's - order (`RoundingOrderPolicy::Native`: `mix` by `FMix`, `fast::sqrt` by `Sqrt`, and `dot` of - vectors of other than two to four lanes, whose chunks' products the device sums where Metal - flushes each one below `2^-126`), the fast defaults off Apple's GPUs; and, under every policy, by - a conversion to or from `double`, where Metal's reading is not measured. Under - `DevicePolicy::exact_answers()` every other `float` operation reads its denormals as Metal does, - `mix`, `atan2`, `sinpi`, `cospi`, `tanpi`, `fast::fmod` and `fma` among them. Under - `FloatMathsPolicy::Native` the device's fused multiply-add rounds a result whose exact value is - below `2^-126` up to `2^-126`, which Metal flushes (docs/FAST-PATHS.md, known gaps). + `DenormFlushToZero`). Recorded where the module leaves an operation's denormals to a device not + measured to read them as Metal does: `+ - *`, the comparisons, `fma`, `dot`, `sqrt`, `rsqrt`, + `trunc` and `rint` but on a device that takes the measured + `DriverDeviation::MetalFloatDenormals`; and on every device the divisions and the remainder, + `floor` and `ceil`, the device's maths functions (`fast::fmod`'s fused multiply-add among them), + `mix` by `FMix`, `fast::sqrt` by `Sqrt`, `dot` of vectors of other than two to four lanes, whose + chunks' products the device sums where Metal flushes each one below `2^-126`, and a conversion + to or from `double`, where Metal's reading is not measured. The operations that read a denormal + on its bits answer Metal on every device: `ldexp`, `sign`, `fract`, `copysign`, `fabs` and + `atan2`; and so do the functions the device answers as Metal's own. Where the minimum and maximum + functions and `saturate` are the device's `NMin`, `NMax` and `NClamp`, their pick of a denormal + is `NativeMinMax`'s. Off MoltenVK the device's multiply and fused multiply-add round a result whose + exact value is below `2^-126` up to `2^-126`, which Metal flushes + (`float-tininess-after-rounding`). - `metal2vulkan-degrade-pixel-sampler-scaling` (precision). `PrecisionNote::PixelSamplerScaling`: Pixel-coordinate samplers scale coordinates in the shader, rounding differently. - `metal2vulkan-degrade-device-arithmetic` (precision). `PrecisionNote::DeviceArithmetic`: Float @@ -2597,11 +2601,7 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. - `metal2vulkan-degrade-device-signed-zero-inf-nan` (precision). `PrecisionNote::DeviceSignedZeroInfNan`: Float operations LLVM requires to keep signed zeros, infinities, and NaNs run without `SignedZeroInfNanPreserve`, which the device does not support at - their width. Under `FloatMathsPolicy::Exact` so does an operation that answers Metal's zero of - its sign: a fused multiply-add the translation computes itself (in `double` or in integers - without `OpFmaKHR`), one by `OpFmaKHR` whose result is at most `2^-126` in magnitude, and a - `float` product flushed below `2^-126`. Without the mode the device may answer such a zero with - either sign. + their width. Without the mode the device may answer such a zero with either sign. - `metal2vulkan-degrade-device-ray-intersection` (precision). `PrecisionNote::DeviceRayIntersection`: A ray intersection traversed by the device's ray query. - `metal2vulkan-degrade-fast-math-rewrites` (precision). `PrecisionNote::FastMathRewrites`: Float @@ -2985,20 +2985,18 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. sum on the format's grid, so a draw binding such a texture makes no pipeline of its own. - `metal2vulkan-degrade-native-transcendentals` (precision). `PrecisionNote::NativeTranscendentals`: Native device maths: the module computes a `float` or `half` math-library function by the device's - own `GLSL.std.450` instruction (or Metal's composition of the device's `Exp2` and `Log2`), not by - the translation's routine of Metal's answer, on a device whose functions are not Metal's own, - under `FloatMathsPolicy::Native`; and `fast::sqrt` the device's `Sqrt`, under - `RoundingOrderPolicy::Native`. + own `GLSL.std.450` instruction (or Metal's composition of the device's `Exp2` and `Log2`) where + Metal's function is not the device's own; and `fast::sqrt` the device's `Sqrt` on a device whose + functions are not Metal's own. - `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`, not the translation's correctly rounded routine or its `RN(1 / y)`, on a device - whose division is not Metal's own, under `FloatMathsPolicy::Native` (the default). + device's `OpFDiv` where the device's division is not Metal's own: within Vulkan's 2.5 ulp, where + Metal's precise division is correctly rounded. - `metal2vulkan-degrade-native-fma` (precision). `PrecisionNote::NativeFma`: Native device maths: a - `float` fused multiply-add on a device without `OpFmaKHR`, under `FloatMathsPolicy::Native` (the - default), not the translation's correctly rounded routine, or a `half` one, under every policy, - where the device's 16-bit `Fma` is not measured to be Metal's and the device has no 16-bit - `OpFmaKHR` under the 16-bit float controls, is the device's `GLSL.std.450 Fma` (on the `half` - operands held in `float`, its result rounded to `half`). + `float` fused multiply-add on a device without `OpFmaKHR`, or a `half` one where the device's + 16-bit `Fma` is not measured to be Metal's and the device has no 16-bit `OpFmaKHR` under the + 16-bit float controls, is the device's `GLSL.std.450 Fma` (on the `half` operands held in + `float`, its result rounded to `half`), where Metal's rounds once. - `metal2vulkan-degrade-device-texel-conversion` (precision). `PrecisionNote::DeviceTexelConversion`: Native device sampling (a texel conversion): the module hands a read, sample or gather with a `float` result the device's own conversion of the texel's @@ -3032,11 +3030,11 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. - `metal2vulkan-degrade-native-dot` (precision). `PrecisionNote::NativeDot`: Native device maths: Metal's `dot` on `float`, or on `half` where its fused multiply-add is not the measured 16-bit one, is the device's `OpDot` (a `half` one summed in `float` and rounded once to `half`), not - Metal's fused chain of its products, under `RoundingOrderPolicy::Native`. + Metal's fused chain of its products, on a device whose functions are not Metal's own. - `metal2vulkan-degrade-native-mix` (precision). `PrecisionNote::NativeMix`: Native device maths: Metal's `mix(x, y, t)` on `float`, or on `half` where its fused multiply-add is not the measured 16-bit one, is the device's `FMix` (a `half` one computed in `float` and rounded once to `half`), - not Metal's `fma(t, y, fma(-t, x, x))`, under `RoundingOrderPolicy::Native`. + not Metal's `fma(t, y, fma(-t, x, x))`, on a device whose functions are not Metal's own. - `metal2vulkan-degrade-color-attachment-groups` (precision). `PrecisionNote::ColorAttachmentGroups`: A render pipeline whose color attachments the device draws in more than one group (more than the lesser of its `maxColorAttachments` and diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 27127fe4c..c46d206d4 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -93,9 +93,9 @@ needs an internal item is one of the crate's own tests (`src/tests/`). policy. Every device-dependent choice (subgroup tier, buffer views, storage widths, robustness, push-constant room, limits, measured driver deviations) reads it, and its fingerprint is part of every cache key. -- **The policy's accuracy choices.** Off Apple's GPUs the default policy takes the device's own - sampler, maths, texel conversions, `half` rounding, NaNs and blends where they are faster; each - has an exact switch ([FAST-PATHS.md](FAST-PATHS.md)). +- **The policy's accuracy choices.** The maths are the device's own on every device. Off Apple's + GPUs the default policy takes the device's own sampler, texel conversions, `half` rounding, NaNs + and blends where they are faster; each has an exact switch ([FAST-PATHS.md](FAST-PATHS.md)). - **Structure, not names.** Families decide from IR types, address spaces, the metadata ABI and the `air.*` and `llvm.*` intrinsic contract. No branch keys on a function, type or variable name. - **Typed refusals.** An input the device cannot run exactly is `Error::Unsupported`, naming the diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 87c398269..323e8810e 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -31,9 +31,7 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X | A two-plane YCbCr texture's linear sample (`YCBCR8_420_2P` and its kin, over a surface's planes) is the device's filter of its texels, which hold Metal's reads exactly, as any other texture's is under native sampling: a draw binding one takes the pipeline a draw binding any other texture takes. Metal sums the texels' steps on the format's grid (`1/2048`, `1/8192`), each term truncated. Under native sampling, MoltenVK's included (Metal's own sampler filters the texels as an `RGBA16Float` or `RGBA32Float` texture's); with `sampling = SamplingPolicy::Exact` every module answers Metal's filter, MoltenVK's through the slot's variant. On a device whose memory is the host's, a sample that reads the planes in place is Metal's filter exactly under either value (the two-plane YCbCr bullet under **Costs of matching Metal**), so the row applies there only to the samples that form does not read. | `ycbcr_filter = YCbCrFilterPolicy::Device` | `ycbcr_filter = YCbCrFilterPolicy::Exact`: Metal's filter emulated in the slot's YCbCr variant, a pipeline the first draw binding such a texture makes | Linear filter within 1.183 codes (1/255) of Metal's filter of the format on NVIDIA (RTX 3090), 0.877 on RADV, 1.058 on ANV, 0.872 on lavapipe; within 0.498 at coordinates on the 1/256 grid. `DeviceSampling` (`device-sampling`). On MoltenVK within one step of the grid (0.125 codes on `1/2048`, 0.016 on `1/8192`), a `half` result within one `half` ulp; a `half` sample of one texel on the grid `8192` through a runtime sampler rounds to nearest even where Metal rounds ties away. `ycbcr-filter-not-exact`, `HalfTexelConversion` (`half-texel-conversion`), announced where a draw binds such a texture | One pipeline more, made at the first draw binding such a texture. A2X (`a2x-s96` with a `YCBCR8_420_2P` texture at fragment slot 3, on ANV, Iris Xe): 2 pipelines, 13.9 s at the state's creation and 37.8 s at the draw (52.3 s wall), against the creation's one drawn as made (14.3 s) | | A texel's `float` value is the device's conversion of its codes; a `half` result is the device's `float` texel rounded to nearest even. | `texel_conversion = TexelConversionPolicy::Device` | `texel_conversion = TexelConversionPolicy::Exact`: Metal's conversion by the bound format's class of every read; a sample's or gather's also with `sampling = SamplingPolicy::Exact` (under native sampling the device's sampler decodes it) | One `f32` ulp for 8- and 16-bit codes, 0.18 of a code for 5- and 6-bit packed channels; `half` within one ulp; NaN bits the device's. `DeviceTexelConversion` (`device-texel-conversion`), `HalfTexelConversion` (`half-texel-conversion`, also recorded for heap textures and unmeasured formats) | Exact reads (the same reads): Xgc14 0.88-0.89 → 0.90-0.93 s, GPU 0.039 → 0.046 ms; Xgc15 0.65-0.66 → 0.68 s, 0.090 → 0.094 ms; A2X unchanged (no affected read). Samples: with the sampling row | | A normalized vertex attribute (`UCharNormalized` through `Short4Normalized` of either sign, `UChar4Normalized_BGRA`, `Int1010102Normalized`, `UInt1010102Normalized`) is converted by fixed-function vertex input, through the attribute's own Vulkan `UNORM` or `SNORM` format, not pulled from its vertex buffer and divided in the shader. Vulkan states that conversion as Metal states it (`c / (2^b - 1)` unsigned, `max(c / (2^(b-1) - 1), -1)` signed, correctly rounded), so it is the driver's implementation of it that can differ, and nothing in the attribute's Vulkan format asks for a correction after the load. The whole format is then `VertexAttribute` state that no instruction of the module names, so every format the device fetches shares one module (`pipeline::link::vertex`, item 9). | `vertex_normalized = VertexNormalizedPolicy::Device` | `vertex_normalized = VertexNormalizedPolicy::Exact`: every such attribute is pulled and its codes divided by `lower::stage_io::fetch`'s integer sequence, one module per format | One `f32` ulp at some codes on a driver that multiplies by the reciprocal: measured on llvmpipe (Mesa 26.2.4), which reads 127/255 as `0x3EFEFF00` where Metal reads `0x3EFEFEFF`, over the five 8-bit unsigned sites of `vertex-format-float4` and four of `-instance-step` (`known-gaps.tsv`); the 16-bit and packed normalized formats are exact there, and the unsigned ones are exact on RADV. Every normalized format of `vertex-format-float4`, `-half4` and `-instance-step` is Metal's on MoltenVK (Apple M3 Max, macOS 27.0.1) under both values of this switch, each case `exact` at every site. The signed formats are **unaudited** off MoltenVK under the default: they were pulled on every device until this row existed, so llvmpipe's 8-bit sites are expected to read one ulp as their unsigned twins do, and no run has taken them. Not announced: no note names the device's normalized vertex conversion. `tests::engine_vertex_variants` tests both values | Not timed. The variant count is the cost, measured on an Apple M3 Max over `cases::vertex_formats`' 45-format sweep (`tests::engine_vertex_variants`): the `float4` entry compiles 2 modules under the default and 21 under the switch, the `half4` entry 1 against 20. Each extra module is a translation of ours and a shader the driver converts once more | -| The maths library (`sin`, `exp`, `log`, `pow`, `atan2`...), divisions and Metal's fast reciprocal, and a fused multiply-add without `OpFmaKHR` are the device's instructions, not routines of Metal's answers. Off MoltenVK a `float` multiply, and a fused multiply-add by `OpFmaKHR`, keep the device's rounding before Metal's flush: Metal flushes a result whose exact value lies below `2^-126` before rounding it. | `float_maths = FloatMathsPolicy::Native` | `float_maths = FloatMathsPolicy::Exact`; there off MoltenVK a `float` product of `±2^-126` is Metal's zero where the exact product lies below `2^-126`, decided inline without a branch by one `OpFmaKHR` on the operands' magnitudes, or by their bits without `OpFmaKHR` (`arith.float.tiny`, `dot`'s first product too), and `OpFmaKHR` is checked: a result at most `2^-126` in magnitude, zero included, is answered by a routine called only then, with `double` one that decides only the exact sum's sign and whether it lies below `2^-126`, else the integer `fma`; a module with either check, or with a fused multiply-add the translation computes itself (the `double` and integer routines without `OpFmaKHR`), declares `SignedZeroInfNanPreserve` at 32 bits, and at 64 for a `double` routine, where the device supports it, so the device keeps the zero signs they answer (without it Vulkan lets the device answer a zero of either sign; else `DeviceSignedZeroInfNan`) | Vulkan's precision table (`Sin` 2^-11 absolute in [-π, π], `Exp` 3 + 2·\|x\| ulp, `Atan` 4096 ulp) against Metal's 4-6 ulp; division 2.5 ulp; `fma` one `half` ulp (a `float` one may round twice); an `f32` denormal in a maths function, `fast::fmod` among them, read as the device reads it (`DeviceDenormals`); a product or fused multiply-add 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, announced once per device as it is made. `NativeTranscendentals` (`native-transcendentals`), `NativeDivision` (`native-division`), `NativeFma` (`native-fma`), `FloatTininessAfterRounding` (`float-tininess-after-rounding`) | A2X 0.99-1.02 → 9.66-9.83 s, GPU 0.097-0.098 → 0.222-0.225 ms; Xgc14 0.87-0.90 → 12.6-13.6 s, 0.038 → 0.124-0.135 ms; Xgc15 0.63-0.65 → 9.40-9.54 s, 0.089 → 0.208 ms (measured before these modules declared `SignedZeroInfNanPreserve`, whose cost is not measured). Off MoltenVK a product's check is 12 instructions inline (23 without `OpFmaKHR`), and a checked `OpFmaKHR` adds its test, a branch and a call of a routine of about 40 instructions (with `double`), which the device's compiler copies into each use | | A NaN result's bits are the device's (no select of Metal's NaN), and `fmin`, `fmax`, `min3`, `max3`, `clamp` and `saturate` are the device's `NMin`, `NMax` and `NClamp`. | `nan_and_min_max = NanMinMaxPolicy::Native` | `nan_and_min_max = NanMinMaxPolicy::Exact` | A NaN where Metal answers one, its bits the device's; the operand Metal picks but at two NaNs, `+0` against `-0`, and `f32` denormals. `NativeNanEncoding` (`native-nan-encoding`), `NativeMinMax` (`native-min-max`) | A2X 1.00-1.02 → 1.85-1.88 s, GPU 0.098 → 0.116 ms; Xgc14 0.88-0.89 → 1.59-1.63 s, 0.039 → 0.048 ms; Xgc15 0.65-0.66 → 1.25-1.28 s, 0.090 → 0.102 ms | -| `dot`, `mix` and `fast::sqrt` are the device's `OpDot`, `FMix` and `Sqrt`, not Metal's fused chain, its two fused multiply-adds and `x · rsqrt(x)`; a `dot` of other than two to four lanes sums the `OpDot` of each chunk of up to four lanes. | `rounding_order = RoundingOrderPolicy::Native` | `rounding_order = RoundingOrderPolicy::Exact` (MoltenVK takes Metal's order under every policy): Metal's chain over every lane of a `dot` of any width (test `wide_dot_is_metals_fused_chain_in_metals_order`) | `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; `FMix` and `Sqrt` read an `f32` denormal as the device does (`DeviceDenormals`). `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, an `f32` denormal read as the device reads it, `DeviceArithmetic` (`device-arithmetic`) and `DeviceDenormals` | A2X 1.00-1.02 → 1.03-1.06 s, GPU 0.098 → 0.101 ms; Xgc14 0.88-0.89 → 0.97-1.02 s, 0.039 → 0.041 ms; Xgc15 0.65-0.66 → 0.73 s, 0.090 → 0.088 ms | | A `half` texel's NaN is the rounding's own NaN, not the texel's bits (the keep's four instructions a texel are left out). | `nan_and_min_max = NanMinMaxPolicy::Native` | `nan_and_min_max = NanMinMaxPolicy::Exact` (the keep under native half rounding). The same switch also gives Metal's full rule: `0x7e00` for every NaN but a one-texel read, nearest sample or gather of a 16-bit float texture, by the slot's format class read as data, a heap handle's class index and a runtime sampler's filter. A gather with a `half` result fetches its four texels where the class is a half-float one, since NVIDIA's gather hands back every NaN as `0x7fffffff`. **Not yet exact:** a cube gather, bicubic and emulated linear, fetched or compared samples; and on ANV (Iris Xe, Mesa 26.2.4) every 16-bit float texel's NaN, which its image decode answers as `0xFFC00000` (`0xFE00` as a `half`) before any keep, and on RADV (the Radeon 780M and the RX 7900 XTX, Mesa 26.2.4) a 16-bit float texel's NaN through a **sampler**, which answers `0xFFC00000` the same way where its image loads keep the texel's bits (`half-texel-nans-r16f`'s `nearest-sample` site differs, its `read` sites are exact): reading the texel's bits through an unsigned integer view would answer Metal's. Possible, not built: the runtime sampler's filter read as push data rather than specialized, which would spare the remake below. Measured on the RTX 5080: under the switch no `half` lane of the runtime lane's texel reads, samples and gathers differs from Metal's (1,469 differ by default). Under the switch `DeviceNanEncoding` is still announced; the consumer logs notes, so no device fact is built to drop it | NaN bits the device's (`0x7FFF` on the RTX 5080), where Metal hands back a 16-bit float texel's own bits on a read, nearest sample or gather, and `0x7e00` for a 32-bit or small float texel's NaN and a linear sample's. `NativeHalfConversion` (`native-half-conversion`); the read also records `DeviceNanEncoding` (`device-nan-encoding`) | Measured on top of the NaN switch's own row (a probe with the keep against one without): A2X 341,299 → 347,519 words, 1.82-1.86 → 1.81-1.87 s, GPU 0.115-0.117 → 0.115-0.116 ms, within noise; Xgc14 and Xgc15 read no `half` texel (words unchanged). The full rule (a probe with it against the same tree without it): A2X 347,519 → 372,429 words (+7.2%), creation 1.85-1.88 → 1.99-2.04 s; where a linear runtime sampler is bound at the draw the sampler word's filter is now specialized, so the first draw remakes (1.94-1.96 s) and its GPU time rises 0.115-0.117 → 0.124-0.125 ms; with a nearest sampler GPU 0.115-0.116 → 0.115-0.117 ms; Xgc14 and Xgc15 words unchanged. On the RTX 3090 the same pair: A2X creation 2.91-3.06 → 3.17-3.23 s, the first draw's remake 3.0 s and its GPU time 0.17-0.18 → 0.79-1.15 ms, with a nearest sampler 0.17-0.18 ms both | | On ANV and RADV, which round a `half` through the device's conversion under the float controls, a `half` read from its bits (a load, a reinterpretation, a texel's bits) is the device's widening of them as a 16-bit float, loops included, and a `half` texel takes that conversion's NaN (no keep): every value but a NaN is exact by the Vulkan spec. | `nan_and_min_max = NanMinMaxPolicy::Native` | `nan_and_min_max = NanMinMaxPolicy::Exact`: the integer decode and the texel's keep; a `half` widened to `float` then answers Metal's `0x7fc00000` for every NaN, read from memory, a texel or a select alike | A `half` NaN widened to `float` has the device's bits (ANV quiets a signalling NaN, RADV keeps it), where Metal answers `0x7fc00000`; a `half` stored back unchanged keeps its bits. `NativeNanEncoding` (`native-nan-encoding`); a texel's, `DeviceNanEncoding` (`device-nan-encoding`) | ANV (Iris Xe, Mesa 26.2.4), A2X: making 4.06-4.36 → 5.76-5.87 s, 269,828 → 280,070 words, peak RSS 0.35 → 0.51 GB, GPU 4.48 → 4.62 ms (warm); RADV (Radeon 780M, Mesa 26.2.4): 379-467 → 535-665 ms, GPU within its clock states' spread | | A computed `half` or `float` color blended into an extended-range attachment (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`) rounds the blend's source as a loaded one; Metal's compiler rounds it by how it computed it. Every device. | The in-shader blend's loaded rounding (no switch) | **Not built yet:** Metal's rounding per shape is probed, not modelled | One code. `ExtendedRangeBlendSource` (`extended-range-blend-source`), `ExtendedRangeFloatBlendSource` (`extended-range-float-blend-source`) | Not measured | @@ -61,7 +59,10 @@ 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 | |---|---|---| -| `f32` denormals in the operations left to the device under every policy: a conversion to or from `double`. Metal reads them as zero. | Vulkan lets each device keep or flush them; Metal runs no `double`, so its reading of a conversion is not measured. Native device maths and the device's order record the note too (their rows above). Every other `float` operation reads them as Metal on every device (test `the_accurate_forms_read_denormals_as_metal`). | `DeviceDenormals` (`device-denormals`) | +| The maths library (`sin`, `exp`, `log`, `pow`, `atan2`...), 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). | The device's arithmetic is the contract: no routine computes Metal's answer where the device has an instruction. | Vulkan's precision table (`Sin` 2^-11 absolute in [-π, π], `Exp` 3 + 2·\|x\| ulp, `Atan` 4096 ulp) against Metal's 4-6 ulp; division 2.5 ulp; `fma` one `half` ulp (a `float` one may round twice). `NativeTranscendentals` (`native-transcendentals`), `NativeDivision` (`native-division`), `NativeFma` (`native-fma`) | +| `dot`, `mix` and `fast::sqrt` are the device's `OpDot`, `FMix` and `Sqrt`, not Metal's fused chain, its two fused multiply-adds and `x · rsqrt(x)`, on every device but MoltenVK, which takes Metal's order; a `dot` of other than two to four lanes sums the `OpDot` of each chunk of up to four lanes. | The device's order is the contract. | `float` `dot` of n lanes within (3n − 1)·2^-24·Σ\|aᵢbᵢ\|, `mix` within 2^-21 of its two terms, `fast::sqrt` 4.5 ulp. `NativeDot` (`native-dot`), `NativeMix` (`native-mix`), `NativeTranscendentals` (`native-transcendentals`); a `dot` of other than two to four lanes within Vulkan's precision of its chunks' `OpDot` and sum, `DeviceArithmetic` (`device-arithmetic`) | +| Off MoltenVK a `float` multiply, and a fused multiply-add by `OpFmaKHR`, round before Metal's flush: Metal flushes a result whose exact value lies below `2^-126` before rounding it, so a result whose exact value lies within half a unit below `2^-126` answers `2^-126` of its sign where Metal answers the zero of its sign. | Every device measured off MoltenVK (RADV, ANV, NVIDIA, lavapipe) rounds first; its multiply is the contract. | Announced once per device as it is made: `float-tininess-after-rounding` | +| `f32` denormals in a `float` operation on a device not measured to read them as Metal does (`DriverDeviation::MetalFloatDenormals`: lavapipe, and every unmeasured device), in `floor` and `ceil` on every device, in the maths functions and the device's order of the rows above, and in a conversion to or from `double`. Metal reads them as zero and flushes a denormal result. | The device's reading is the contract: Vulkan lets each device keep or flush them, and Metal runs no `double`, so its reading of a conversion is not measured. | `DeviceDenormals` (`device-denormals`) | | A denormal 32-bit float texel the device's sample or gather reads as zero (RADV's gathers and nearest samples, NVIDIA's gathers, ANV's nearest samples), where the module cannot fetch the texels itself. | The device's filter decides; no fetch form reaches filtered, cube, heap or runtime-sampler samples. | `DeviceTexelDenormals` (`device-texel-denormals`) | | Depth values outside [0, 1] stored clamped (RADV, ANV) on a device without `VK_EXT_depth_range_unrestricted`. | Vulkan leaves them undefined without the extension: enable it. | `RestrictedDepthRange` (`restricted-depth-range`) | | A multisampled 32-bit float depth written by a blit copy from a buffer or a colour texture, or a separate depth texture's copies to and from its pass's scratch image, on a device whose depth/colour copies are missing or wrong (lavapipe, MoltenVK, NVIDIA's GA10x, a device without `VK_KHR_maintenance8`): the values its driver's fragment depth changes (MoltenVK's, NVIDIA's), or on a driver not measured may change (outside [0, 1], denormals, -0), land changed. | Vulkan writes a multisampled depth image's samples by no other means there but a clear; a driver measured to store every fragment depth unchanged (lavapipe's measured releases) is exact. | `DrawnDepthCopy` (`drawn-depth-copy`) |