Take the device's float maths, rounding order and denormals on every device

One work packet, landed as 3 commits (9fd799bdbb..43bdc4ac17 on archive/development-linear-2026-10-28), in order:

* Take the device's float maths, rounding order and denormals on every device

The owner's ruling: promise the GPU's native arithmetic, no exact emulation.
The translation's own Metal-answer forms for float maths go, and the
device's native form is the only form.

What goes:
- DevicePolicy::float_maths (FloatMathsPolicy) and
  DevicePolicy::rounding_order (RoundingOrderPolicy), their exact_answers()
  lines, serde, docs, and the profile state that carried them
  (FloatFunctions::Device, ProfileFields::rounding_order and
  RoundingOrderRoute); RuntimeFact::ExactFormsOverCompilerLimit loses its
  float_maths and rounding_order fields.
- The maths routines of Metal's answers in lower/arith/libm (atan, exp,
  hyper, log, pair, pi, quarter, rcp, root, rsqrt, sincos, tan, trig) and
  their paths in math.rs: off MoltenVK every call takes the device's
  GLSL.std.450 instruction (or Metal's composition of the device's
  instructions), noted NativeTranscendentals; on MoltenVK the device's
  instruction, Metal's own in the module's mode, with its old notes.
- Metal's precise division routine and its fast reciprocal: a precise and a
  fast division are the device's OpFDiv (NativeDivision), and an frem
  without every flag the device's OpFRem.
- The checked OpFmaKHR, the double, integer and half fused multiply-add
  routines, and the tiny-product check (arith.float.tiny): a fused
  multiply-add is OpFmaKHR, the measured 16-bit Fma, OpFmaKHR under the
  16-bit float controls, or the device's Fma (NativeFma).
- Metal's fused chain for dot, mix and fast::sqrt off MoltenVK: OpDot, FMix
  and Sqrt (NativeDot, NativeMix, NativeTranscendentals). MoltenVK, whose
  float functions are Metal's, keeps Metal's chains.
- The f32 denormal flush taken where the device is not measured to read
  denormals as Metal does (no DriverDeviation::MetalFloatDenormals), and the
  floor and ceil flush: those denormals are the device's, noted
  DeviceDenormals.
- FloatTininessAfterRounding is announced on every device off MoltenVK.

What stays: precise fmod's routine (OpFRem is not the exact remainder past a
quotient of 2^24), ldexp on the bits (GLSL Ldexp is undefined past the
exponent range), double support, and every precision note that describes the
native answer. FloatFn::words charges each function a call takes as before
(the device's instruction where a routine's call was counted).

Tests of the deleted forms are deleted; the tests of the native forms now
check the device's instruction, its note and the interpreter's IEEE answer
(the division, remainder, fmod, fused multiply-add, dot, mix, denormal and
tanh tests), and the roll fixture grows to 13,000 operations so two bodies
stay above the roll size without the flushes. The c3 bound and sign-off
tests expect a subnormal product or quotient on lavapipe to stay open
(its multiply and divisions now record DeviceDenormals) and a product on
MoltenVK, measured to flush as Metal does, to keep Apple's verdict.

Docs: FAST-PATHS.md's two rows become device gaps (the maths library and
divisions; dot, mix and fast::sqrt; the tininess; the denormals), API.md's
policy bullet and catalogue entries, ARCHITECTURE.md's decisions bullet.

Versions: SEMANTICS_VERSION 1878, ARTIFACT_FORMAT_VERSION 461,
RUNTIME_VERSION 1660. REFUSALS.md regenerated unchanged; api_signatures.tsv
is re-blessed in a later commit, after the rebase onto development.

Verified on b1ae235a12, before the rebase onto development 4df472aea2
(whose conflicts the commits after this one check): cargo clippy
--workspace --all-targets --all-features -D warnings with --cfg m2v_gpu;
cargo nextest (--test-threads 4) on the touched modules' tests
(lower::arith, lower::sampler face, position and linear, device::tests,
compile::fit, cache, the engine_* suites touched, engine_roll, fast_paths,
api_surface, api_signatures), the runtime's degradation, catalogue, device
and fitted_variant_notice tests, and the whole metal2vulkan-validation
suite but the runtime-sources pin (left to the landing) and
c3::tests::each_moltenvk_device_compares_with_its_own_gpus_metal (a venue
identity check outside the arithmetic). No device tests ran: the device
lanes compile under --cfg m2v_gpu and were adapted, not run.

* Re-bless the public signatures after the float maths switches' removal

The commit before this one was rebased onto development 4df472aea2. This
commit holds what the rebase left to do:

- api_signatures.tsv re-blessed: against development it drops
  FloatMathsPolicy and RoundingOrderPolicy (their records, fields and
  variants) and ExactFormsOverCompilerLimit's float_maths and
  rounding_order fields. docs/REFUSALS.md regenerated, unchanged.
- corpus-draw-ab's --policy error message: the conflict resolution lost the
  string's line continuation and left a run of spaces in it.
- The DeviceDenormals docs (PrecisionNote and the API.md catalogue entry)
  no longer say the minimum and maximum functions and saturate answer
  Metal at a denormal on every device: under the default policy, and on
  every device once Metal's picks go, they are the device's NMin, NMax and
  NClamp, whose pick of a denormal NativeMinMax records.
- Doc comments this lane wrote past 100 columns refilled.

Verified on this tree: cargo clippy --workspace --all-targets
--all-features -- -D warnings, plain and with --cfg m2v_gpu, clean;
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps,
clean; cargo nextest (--test-threads 4) of metal2vulkan filtered to the
touched modules (lower::arith, lower::sampler, device::tests, compile::fit,
cache, the touched engine_* suites) and fast_paths, catalogue,
degradation, profile, mechanism, api_surface and api_signatures: 818 run,
817 passed; of the runtime's degradation, catalogue, device and
fitted_variant_notice tests and the whole metal2vulkan-validation suite:
1402 run, 1400 passed. The three failures fail identically on development
4df472aea2 (run there): engine_float_call_notes::
exported_float_notes_are_the_ones_a_compile_records (fabs_f16 on
moltenvk-m3 records NativeHalfConversion, the half decode's note) and
c3::tests::each_moltenvk_device_compares_with_its_own_gpus_metal (a venue
identity check); and the runtime-sources pin, left to the landing. No
device tests ran.

* Re-pin the runtime sources at the landing tip

The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
This commit is contained in:
Anees Iqbal committed 2026-10-28 17:24:20 +02:00
1 parent 70068f7cc0
commit 4817f3bdfe
77 files changed
+2332 -19696

No files matched your search

+21 -35
View File
@@ -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))
@@ -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(),
)
});
}
+16 -27
View File
@@ -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,
@@ -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<RuntimeDependency>) {
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:?}"
);
@@ -1 +1 @@
8dfdbe852e2042225ae5ecaa4677869e32417533984dbe01f946d00bbdc2bce9
3d4df3af6a75270a98fba273007ec0aa849a57a434bd7b5a61058b6ba89b9c39
@@ -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<String, String>) -> Result<DevicePolicy, String> {
"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"
))
}
}
@@ -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<PrecisionNote>,
expr: &Expr,
@@ -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(
@@ -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.
@@ -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<Degradation> {
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);
}
@@ -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,
@@ -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::<usize, usize>::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<usize> = (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::<Vec<_>>());
let all = differing_of(&run.output, &metal, 8, &(0..8).collect::<Vec<_>>());
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!(
@@ -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<String> {
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();
+1 -3
View File
@@ -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,
+3 -3
View File
@@ -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
+4 -16
View File
@@ -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
+3 -3
View File
@@ -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};
+4 -69
View File
@@ -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
+8 -30
View File
@@ -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]
@@ -267,10 +267,8 @@ fn every_fact() -> Vec<RuntimeFact> {
},
RuntimeFact::ExactFormsOverCompilerLimit {
sampling: true,
float_maths: true,
texel_conversion: false,
nan_and_min_max: true,
rounding_order: false,
},
]
}
@@ -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}");
}
}
+21 -65
View File
@@ -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<denormal::TinyCheck>),
reads: denormal::Flush,
) -> BResult<SValue> {
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<denormal::TinyCheck>),
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<NanAnswer>; 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)> {
+12 -26
View File
@@ -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)))
+42 -317
View File
@@ -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<Operand> {
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<Value> {
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<Reading> {
/// states no sign for a flushed denormal, so only the deviation covers them.
pub fn coverage(op: FloatFn) -> Option<Covered> {
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<TinyCheck> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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 {
+22 -610
View File
@@ -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<FuncId> {
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<FuncId> {
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<Value> {
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<Value> {
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<Value>;
/// 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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Parts> {
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<Value> {
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<Value> {
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)
}
File diff suppressed because it is too large. Load diff
@@ -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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<FastArcs> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
let q = e.div(y, x)?;
let t = half_atan(e, q)?;
turned(e, t, y, x)
}
@@ -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<GlobalId> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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)
}
@@ -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<Value> {
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)
}
@@ -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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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)
}
@@ -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<GlobalId> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<GlobalId> {
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<Value> {
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<Value> {
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)
}
File diff suppressed because it is too large. Load diff
@@ -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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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))
}
}
@@ -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<Value> {
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<Value> {
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)
}
@@ -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<GlobalId> {
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<Value> {
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<Value> {
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<Value> {
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))
}
@@ -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<GlobalId> {
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<Value> {
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<Value> {
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))
}
@@ -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<Value> {
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<Value>,
down: &dyn Fn(&mut E<'_, '_>, Value) -> BResult<Value>,
) -> BResult<Value> {
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<Value> {
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<Value> {
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)
}
@@ -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<GlobalId> {
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<Value> {
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<Value> {
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)
}
@@ -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<GlobalId> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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)
}
@@ -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<Value> {
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)
}
@@ -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<Value> {
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<Value> {
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)
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+8 -9
View File
@@ -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<NanAnswer> {
| 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<NanAnswer> {
| 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)
+45 -176
View File
@@ -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<Vec<FuncId>> {
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<Fun, FuncId> = 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<f32> = 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<Case> = 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, &divide, 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, &divide, 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(),
&divide,
)
},
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<Case> = [(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;
@@ -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<routines::Fun, FuncId> =
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<Case> = 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
@@ -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<u64> = [
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<Case> {
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<Value> {
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<FuncId> {
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<f32> = (-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<Case> = 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), &divide, 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,
);
}
}
}
+33 -673
View File
@@ -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<Case> = 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<u64> {
use super::divide::bits;
let mut rng = Rng(0x2790_8220_0000_0001);
let mut out: Vec<u64> = [
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<Value> {
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<Case> = (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<Case> {
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(), &divide)
});
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], &divide, &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<String> = 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<Case> = [
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, &divide, 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, &divide, t[0])
},
false,
false,
)
.expect("called");
compare(
&format!("fast tanh's quotient {reciprocal:?}"),
&[f],
f,
inline,
called,
&tanh_cases,
);
}
let fmod_cases: Vec<Case> = 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<Vec<FuncId>> {
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], &divide, &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], &divide, &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], &divide, &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]);
}
+162 -627
View File
@@ -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> = 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::<BResult<Vec<_>>>()?,
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<Routine> = 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<Routine> = 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<Case> {
}
/// 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<Case> = 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<Case> = 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,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+39 -77
View File
@@ -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<SVa
/// (`Snap::words` adds those): its 70 instructions and 6 constants, at most 6 words each.
pub const SNAP_WORDS: u32 = 480;
/// The routines `snapped` computes Metal's face position with: Metal's reciprocal
/// (`libm::Fun::Recip`) by its function `recip`, or by the device's `1 / y` where that is Metal's
/// (`None`), and the correctly rounded fused multiply-add of `fma`, by its function `fma_routine`
/// where its route has one.
/// What `snapped` computes Metal's face position with: the device's reciprocal `1 / y`, and the
/// fused multiply-add `fma`.
#[derive(Clone, Copy, Debug)]
pub struct SnapRoutines {
pub recip: Option<FuncId>,
pub fma: Fma,
pub fma_routine: Option<FuncId>,
}
/// 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<SnapRoutines> {
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<FaceRoutines, Error> {
// 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<SValue> {
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<SValue> {
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<SValue> {
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) => {
@@ -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<SnapRoutines> {
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<TypedModule> {
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}"
@@ -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,
@@ -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()));
}
+38 -52
View File
@@ -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
@@ -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,
@@ -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<P: Fitted>(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!(
@@ -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
+3 -97
View File
@@ -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<u32> {
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<u32> {
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<u32> {
// Each function: its words, its result id, its parameters, and the functions it calls.
let mut functions: Vec<(std::ops::Range<usize>, u32, usize, Vec<u32>)> = 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<u32> = 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<Vec<(crate::spv::Op, &[u32])>, String> {
+2 -2
View File
@@ -248,8 +248,8 @@ pub fn committed_exact_profiles() -> Result<Vec<(String, DeviceProfile)>, 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<Vec<(String, DeviceProfile)>, String> {
File diff suppressed because it is too large. Load diff
@@ -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<NoteClass, (String, DeviceProfile)> {
let routes: BTreeSet<Route> = 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");
@@ -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 {
@@ -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<u32> {
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<String>,
/// 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<String>,
}
/// 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<String> {
let want: Vec<String> = 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", &noted);
let wrong = run_policy(&bc, DevicePolicy::default(), "default", &FUNS);
assert!(
wrong.is_empty(),
"{} answers off Metal's, the first: {:#?}",
@@ -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<u32>,
}
@@ -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!(
@@ -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<Choice>,
}
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] {
+1 -1
View File
@@ -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
@@ -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 {
@@ -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::<u64>(),
);
// 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<String, u64> = BTreeMap::new();
for (n, w) in crate::lower::arith::routine_words(&plan.families.arith) {
*routines.entry(n.to_owned()).or_default() += w;
@@ -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<String> = 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] {
+8 -13
View File
@@ -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<Choice> {
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> {
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,
+1 -9
View File
@@ -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
Can't render this file because it is too large.
+13 -17
View File
@@ -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(
+37 -39
View File
@@ -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
+3 -3
View File
@@ -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
+4 -3
View File
@@ -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`) |