Answer Metal's maths special values and fast functions by the device's instructions

The fast transcendental functions and the special values take the device's instructions, with
the precision contract's and c3's near-equivalent checks held at the device's notes.

One work packet, landed as 3 commits on archive/development-linear-2026-10-29, in order:

* Answer Metal's maths special values and fast functions by the device's instructions (d49cbcd398)

The fast sin, cos, tan, sinh, cosh, tanh and atanh are the device's Sin, Cos,
Tan, Sinh, Cosh, Tanh and Atanh on every device: no flush past Metal's last
evaluated quadrant, no kept denormal, no MSL Table 8.2 formula. The half zero and
NaN-sign tables are gone: a half function is its float instruction rounded. pow,
powr, fast::powr, atan2 and fast::atan2 keep only the C99/MSL special values
GLSL.std.450 leaves undefined (a negative base, 0^y with y <= 0, atan2(0,0),
infinities, pow's odd-integer sign), by the device's comparisons: no bit-level
denormal-as-zero reading, no canonical NaN over a NaN operand (the device's sum
instead), no pow(x, 1) = x, no flush of a denormal atan2 result. The fast
functions take libm::Fun entries of their own, so MoltenVK records
DeviceTranscendentals where its instruction is not Metal's fast function;
elsewhere NativeTranscendentals and DeviceDenormals as before; the NaNs no longer
claimed record NativeNanEncoding or DeviceNanEncoding. half fmod's zero stays on
the exact remainder routine (capability; no note path there yet). Dead code goes:
Lib's Metal mode and denormal::flush. FAST-PATHS rows, the libm module doc, and
API.md's fneg/fabs paragraph (now the device's OpFNegate and FAbs) and
native-transcendentals entry say so; known-gaps.tsv gains the M3's
fast-float-tanh row. SEMANTICS_VERSION 1918.

Verified: arith unit tests 192/192, engine tests of the path 42/42 (metal
denormals, arith, metal math, float call notes), fast_paths/profile/
api_signatures 47/47, runtime degradation and catalogue 17/17; clippy plain and
m2v_gpu, rustdoc; restoring pow(x,1) = x and a fast::sin flush fails the new
tests; conformance replay of pass-bytes-half-tanh-regimes on the Apple M3 Max
matches the ledger (exit 0; MoltenVK's Tanh is MSL's precise tanh, 2623 of 4096
words differ from Metal's fast::tanh, DeviceTranscendentals declared).
golden_hashes.tsv moves 1224 cells (65 rows over 59 fixtures), re-blessed on
development. Not run: lavapipe and other venues, the validation crate.

* Hold the precision contract's fast tanh at the device's Tanh notes (685db3e29f)

d49cbcd398 made a fast float tanh the device's Tanh instead of the MSL formula
the crate computed with a division of its own, so on lavapipe it records
NativeTranscendentals, not DeviceArithmetic, and on MoltenVK, whose Tanh is
Metal's precise tanh rather than its fast one, DeviceTranscendentals instead of
nothing. api_surface's the_precision_contract_names_each_float_operations_notes
still held the formula's notes and failed in development's gate at
b7f6dec939; it and its doc now hold the device's.

Verified: the api_surface binary passes (with fast_paths, golden_hashes and the
conformance ledger tests, 41/41) at 11eaace858.

* Hold c3's near-equivalent checks at the device's tanh and NaN notes (43a9c268e4)

d49cbcd398 made a fast float tanh the device's Tanh instead of the MSL formula
the crate computed with a division of its own, and left the NaN of pow and of
fast sin and cos to the device, so three c3 tests held the old notes and failed
on development:

- the_products_own_approximations_are_its_near_equivalents: tanh (fast or
  precise, float or half, lavapipe or MoltenVK) is now no near-equivalent;
  fast atan2 keeps DeviceArithmetic. Fast tanh(44) stays Apple's unstated word
  even where the row records DeviceArithmetic for another operation.
- a_nan_encoding_the_product_answers_is_not_a_near_equivalent: on lavapipe F32
  exactly precise pow and fast sin and cos record DeviceNanEncoding; the test
  asserts that set over msl::Prim::ALL. A differing NaN of fast sin(inf) and of
  precise pow(-1, 0.5) is now the note's (near_equivalent, open); precise
  sin(inf), mul and div keep the old answer.
- an_unstated_word_the_product_approximates_keeps_its_reading_open: fast fmod
  keeps its open reading and refusal (now the named-lowering check); fast
  tanh(44) is the device's answer, unstated, and the sign-off stands with
  DeviceArithmetic recorded.

Doc comments say what is true now. No product code changes.

Verified: cargo nextest run -p metal2vulkan-validation --all-features -E
'test(/^c3::/)' 72/72 passed (3 failed before); clippy -p
metal2vulkan-validation --all-targets --all-features -D warnings clean. The
lavapipe/MoltenVK note sets were read from lowering_notes for every prim.
This commit is contained in:
Anees Iqbal committed 2026-10-29 15:43:50 +02:00
1 parent ced4a0ecda
commit ed114bcf43
19 files changed
+557 -1168

No files matched your search

@@ -755,6 +755,7 @@ norm-storage-codes-rgba8unorm llvmpipe divergent case/hsw_read_write/texels 128
norm-storage-codes-rgba8unorm llvmpipe divergent case/hsw_write/texels 128 elements differ (U32), the largest difference 16843009 A `float` the function writes to a normalized storage texture at a tie between two codes: Metal stores the exact product rounded with a tie away from zero, and this device rounds the tie to even, so each tie channel is a code apart (the report compares whole words, so its difference adds a word's channels together: Metal 0x01010101 against our 0x00000000 is four channels a code apart). Under the native-arithmetic contract the device's conversion is the answer: `device-color-conversion` records exactly this for a storage write the device converts, and validation derives no tolerance from it. Open: nothing.
pass-bytes-half-tanh-regimes llvmpipe divergent case/output/half-tanh 1257 elements differ (U32), the largest difference 2180022768 Each word holds two `half` results of `tanh` over its regimes, which the device computes by its own `Tanh` (a `half` held as `float`, on every device) and rounds to `half` by its own conversion (`native-transcendentals`, `native-half-conversion`; a NaN's bits and a denormal are the device's, `native-nan-encoding`, `device-denormals`). The first differing element is one `half` ulp toward zero in each half (Metal 0x0C00 against our 0x0BFF), and the site's largest difference, 0x81F081F0, sets a sign bit in each half, so some lanes differ in sign too. `native-transcendentals` bounds `Tanh` as Vulkan does, inherited from `sinh / cosh` and so from `Exp`, and `native-half-conversion` the rounding at one `half` ulp; whether every differing word is within them is not established by this run, which reads the first and the largest. Validation derives no tolerance from them. Open: an element-by-element read of the site against the notes' recorded bounds.
pass-bytes-half-tanh-regimes llvmpipe divergent case/output/fast-float-tanh 1428 elements differ (U32), the largest difference 2151546880 Each word holds `fast::tanh` of a `float` over its regimes, which the device computes by its own `Tanh` (`native-transcendentals`, on every device; a NaN's bits and a denormal are the device's, `native-nan-encoding`, `device-denormals`). The first differing element is Metal 0x38F218D9 against our 0x38F1F8DA, a result near 1.15e-4, 8,191 ulp apart, and the site's largest difference, 0x803E0000, is past the sign bit, so some lanes differ in sign too. `native-transcendentals` bounds `Tanh` as Vulkan does, inherited from `sinh / cosh` and so from `Exp`; whether every differing word is within it is not established by this run, which reads the first and the largest. Validation derives no tolerance from it. Open: an element-by-element read of the site against the note's recorded bound.
pass-bytes-half-tanh-regimes Apple M3 Max divergent case/output/fast-float-tanh 2623 elements differ (U32), the largest difference 2147483648 Each word holds `fast::tanh` of a `float` over its regimes, which the device computes by its own `Tanh` on every device; on MoltenVK that instruction is MSL's precise `tanh` in either math mode (SPIRV-Cross emits `precise::tanh`), where Metal's `fast::tanh` is MSL Table 8.2's formula `(t - 1) / (t + 1)` of `t = exp(2x)`, which is a NaN once `t` overflows where `Tanh` answers 1 (`device-transcendentals`, announced because the instruction is not Metal's fast function there; a NaN's bits and a denormal are the device's). The first differing element is Metal 0x357FFFF0 against our 0x35800000, one ulp, and the site's largest difference, 0x80000000, is a zero's sign. Measured: this case's replay on this M3 Max (macOS 27.0.1), 2026-10-29. Every other venue: expected, unaudited. Open: an element-by-element read of the site against the note's recorded bound.
pass-bytes-srgb-decode-all-bytes llvmpipe divergent case/output/words 1153 elements differ (U32), the largest difference 16318464 Each thread holds four `float` and two words of two `half` results of an sRGB decode of a byte. Metal decodes through its twelve-bit table, answering the step `k / 4095` nearest the transfer; the module decodes by the MSL transfer function through the device's `Pow` (`device-pack-conversion`, on every device), and rounds a `half` result by the device's conversion (`native-half-conversion`). The first differing element is a `float` decode of byte 90, Metal's step 419/4095 (0x3DD18D19) against the transfer's 0.1022417 (0x3DD1641D); the site's largest difference, 0x00F90000, is a small `half` 249 of its ulps off. Read element by element on the validation crate's copy of the case (`srgb-decode-of-every-byte` on lavapipe), every `float` is within 1.221e-4 of Metal's, half a twelve-bit step, and every `half` within that and one `half` ulp, the alpha channels exact: within `device-pack-conversion`'s recorded bound. Validation derives no tolerance from it. Open: nothing.
pass-bytes-srgb-decode-all-bytes Apple M3 Max divergent case/output/words 1136 elements differ (U32), the largest difference 16318465 Each thread holds four `float` and two words of two `half` results of an sRGB decode of a byte. Metal decodes through its twelve-bit table, answering the step `k / 4095` nearest the transfer; the module decodes by the MSL transfer function through the device's `Pow` (`device-pack-conversion`, on every device), and rounds a `half` result by the device's conversion. The first differing element is a `float` decode of byte 90, Metal's step 419/4095 (0x3DD18D19) against the transfer's 0x3DD1641F; the site's largest difference, 0x00F90001, is a word whose small `half` is 249 of its ulps off and whose other `half` is one. Read element by element off this replay's bytes against the committed recording, every `float` is within 1.2205e-4 of Metal's, under half a twelve-bit step (1/8190), and every `half` within that and one `half` ulp (at most 0.97 of it), the alpha channels exact: within `device-pack-conversion`'s recorded bound. Validation derives no tolerance from it. Open: nothing.
pass-bytes-srgb-encode-sweep llvmpipe divergent case/output/words 772 elements differ (U32), the largest difference 65793 Each word holds an sRGB encode of a `float` or a `half` colour packed to four bytes. Metal encodes through its twelve-bit table; the module encodes by the MSL transfer function through the device's `Pow` and rounds it to a byte by `PackUnorm4x8` (`device-pack-conversion`, on every device), so a colour near a byte boundary lands a code from Metal's. The first differing element is one code in one channel (Metal 0x00020201 against our 0x00020101), and the site's largest difference, 0x00010101, is one code in each colour channel. Read element by element on the validation crate's copy of the case (`srgb-encode-of-every-half-and-a-2-14-float-grid` on lavapipe), every differing channel is one code from Metal's and no alpha differs: within `device-pack-conversion`'s recorded bound. Validation derives no tolerance from it. Open: nothing.
Can't render this file because it is too large.
@@ -299,11 +299,12 @@ fn every_operation_is_metals_air_and_the_product_lowers_it() {
/// The near-equivalents are the product's own, as its lowering records them: its fast `float`
/// division (Metal's precise division and every `half` division are a shared routine's correctly
/// rounded quotient, which records nothing), fast `fmod`, and a function it computes with a
/// division of its own (fast `float` `tanh` and `atan2`). Its transcendentals are the device's,
/// fast `float` `sqrt` is Metal's `x * rsqrt(x)` on the device's `rsqrt`, a narrow or precise
/// `tanh` is the device's `tanh`, and precise `sqrt` and `fmod`, `float` and `half`, are the one
/// right value, which records nothing. On a device whose `float` functions are Metal's own, a fast
/// division and those functions are Metal's own under fast math and record nothing there either.
/// division of its own (fast `float` `atan2`). Its transcendentals are the device's: `tanh`, fast
/// or precise, `float` or `half`, is the device's `Tanh`, a transcendental, not a near-equivalent;
/// fast `float` `sqrt` is Metal's `x * rsqrt(x)` on the device's `rsqrt`, and precise `sqrt` and
/// `fmod`, `float` and `half`, are the one right value, which records nothing. On a device whose
/// `float` functions are Metal's own, a fast division and those functions are Metal's own under
/// fast math and record nothing there either.
#[test]
fn the_products_own_approximations_are_its_near_equivalents() {
use msl::Prim;
@@ -340,11 +341,20 @@ fn the_products_own_approximations_are_its_near_equivalents() {
assert_eq!(note(Prim::Sqrt, format, math), None, "{format:?} {math:?}");
}
}
for prim in [Prim::Tanh, Prim::Atan2] {
assert_eq!(note(prim, F32, Math::Fast), arithmetic, "{prim:?}");
assert_eq!(note(prim, F32, Math::Precise), None, "{prim:?}");
assert_eq!(note(prim, F16, Math::Fast), None, "{prim:?}");
assert_eq!(note_on(prim, F32, Math::Fast, moltenvk()), None, "{prim:?}");
assert_eq!(note(Prim::Atan2, F32, Math::Fast), arithmetic);
assert_eq!(note(Prim::Atan2, F32, Math::Precise), None);
assert_eq!(note(Prim::Atan2, F16, Math::Fast), None);
assert_eq!(note_on(Prim::Atan2, F32, Math::Fast, moltenvk()), None);
for format in [F32, F16] {
for math in [Math::Precise, Math::Fast] {
for profile in [lavapipe(), moltenvk()] {
assert_eq!(
note_on(Prim::Tanh, format, math, profile),
None,
"{format:?} {math:?}"
);
}
}
}
for prim in [
Prim::Sin,
@@ -359,7 +369,9 @@ fn the_products_own_approximations_are_its_near_equivalents() {
}
// Fast tanh(44): t + 1 is past 2^126, where Table 8.2 states no accuracy for the division.
// Metal answers 0, the device 1. With the product's division recorded, the word stays open.
// Metal answers 0, the device 1. The product's fast tanh is the device's `Tanh`, which records
// no division of its own, so the word stays Apple's unstated one even where the row records
// the device's arithmetic for another operation.
let lanes = vec![BoundedLane {
words: words(0, 1, 1),
result: Part::F32,
@@ -388,12 +400,12 @@ fn the_products_own_approximations_are_its_near_equivalents() {
panic!("tanh(44) is stated");
};
assert!(why.contains("div"), "{why}");
let open = judge(&[
let device = judge(&[
PrecisionNote::DeviceArithmetic,
PrecisionNote::DeviceTranscendentals,
]);
assert_eq!(open.label(), "near_equivalent");
assert!(open.keeps_open(UnstatedWords::WithinPromise));
assert_eq!(device.label(), "unstated", "{device:?}");
assert!(!device.keeps_open(UnstatedWords::WithinPromise));
}
/// Fast `atan2` with a divisor past `2^126` (case f6524207's lanes 351 and 26): Table 8.2's formula
@@ -544,12 +556,15 @@ const EVERY_ARITHMETIC_NOTE: [PrecisionNote; 4] = [
/// Metal answers the canonical NaN reproducibly, so where both answers are NaNs of an operation
/// whose lowering leaves the encoding to the device, and the row records `DeviceNanEncoding`, the
/// value stays open with the exact path. The product answers Metal's NaN for every operation this
/// check reads on `float`, in either math mode (its calls carry no flags, or every flag, the
/// measured states): none records the note, so a differing NaN of `div` or `mul` is not the note's
/// even where the row records it (another operation of the module may), and the verdict is Apple's
/// bound's; Metal's precise and fast divisions answer `0x7fc00000` themselves. Fast `sin` answers
/// Metal's NaN itself. Two different answers, not both NaNs, are not the encoding's.
/// value stays open with the exact path. On lavapipe, which is not measured to answer Metal's NaN,
/// the product's `float` lowerings that leave a NaN's encoding to the device record the note:
/// precise `pow`, and fast `sin` and `cos` (the device's instructions, whose NaN over an infinity
/// is the device's). Every other operation this check reads answers a NaN whose encoding the
/// product states (`NativeNanEncoding`) or none, so a differing NaN of `div` or `mul` is not the
/// note's even where the row records it (another operation of the module may), and the verdict is
/// Apple's bound's; Metal's precise and fast divisions answer `0x7fc00000` themselves. A differing
/// NaN of fast `sin` is the note's; of precise `sin`, which does not record it, it is not. Two
/// different answers, not both NaNs, are not the encoding's.
#[test]
fn a_nan_encoding_the_product_answers_is_not_a_near_equivalent() {
let (metal, device) = (0x7fc0_0000, 0xffc0_0000);
@@ -557,10 +572,15 @@ fn a_nan_encoding_the_product_answers_is_not_a_near_equivalent() {
let infinity = f32::INFINITY.to_bits();
let nan = [PrecisionNote::DeviceNanEncoding];
for math in [Math::Precise, Math::Fast] {
let device_nans: &[msl::Prim] = match math {
Math::Precise => &[msl::Prim::Pow],
Math::Fast => &[msl::Prim::Sin, msl::Prim::Cos],
};
for prim in msl::Prim::ALL {
let (op, notes) = lowering_notes(prim, F32, math, lavapipe()).unwrap();
assert!(
!notes.contains(&PrecisionNote::DeviceNanEncoding),
assert_eq!(
notes.contains(&PrecisionNote::DeviceNanEncoding),
device_nans.contains(&prim),
"{op} under {math:?}: {notes:?}"
);
}
@@ -585,12 +605,23 @@ fn a_nan_encoding_the_product_answers_is_not_a_near_equivalent() {
&nan,
);
assert_ne!(mul.label(), "near_equivalent", "{mul:?}");
// Fast `sin` answers Metal's NaN itself: a row recording the note for another operation does
// not make this value the note's.
let (_, sin) = lowering_notes(msl::Prim::Sin, F32, Math::Fast, lavapipe()).unwrap();
assert!(!sin.contains(&PrecisionNote::DeviceNanEncoding), "{sin:?}");
// Fast `sin` is the device's `Sin`, whose NaN of an infinity is the device's: the note's, open.
let sin = verdict_of("sin(a)", Math::Fast, &[infinity], (metal, device), &nan);
assert_eq!(sin.label(), "unstated", "{sin:?}");
assert_eq!(sin.label(), "near_equivalent", "{sin:?}");
assert!(sin.keeps_open(UnstatedWords::WithinPromise), "{sin:?}");
// Precise `sin` records no `DeviceNanEncoding`: a row recording the note for another
// operation does not make this value the note's.
let sin = verdict_of("sin(a)", Math::Precise, &[infinity], (metal, device), &nan);
assert_ne!(sin.label(), "near_equivalent", "{sin:?}");
// Precise `pow` of a negative base and a non-integer exponent: a NaN the device encodes.
let pow = verdict_of(
"pow(a, b)",
Math::Precise,
&[(-1.0f32).to_bits(), 0.5f32.to_bits()],
(metal, device),
&nan,
);
assert_eq!(pow.label(), "near_equivalent", "{pow:?}");
let one = 1.0f32.to_bits();
let finite = verdict_of("div(a, b)", Math::Fast, &[one, one], (one, one + 1), &nan);
assert_ne!(finite.label(), "near_equivalent", "{finite:?}");
+30 -26
View File
@@ -1817,10 +1817,11 @@ fn a_signed_off_apple_reading_holds_only_while_every_differing_word_is_within_ap
/// Where Apple states no accuracy, the device's answer is within Apple's promise, but not the
/// product's approximation. A row whose modules record the product's lowering as a near-equivalent
/// of Metal's (`DeviceArithmetic`) keeps the word open, so the report refuses the sign-off,
/// whatever the unstated-words flag says: fast `fmod` ("Undefined"), and fast `float` `tanh`,
/// which the product computes as `(t - 1) / (t + 1)` with its own division (its lowering of
/// `air.fast_tanh.f32` records `DeviceArithmetic`), whose divisor at `tanh(44)` is past the
/// `2^126` where Table 8.2 bounds the fast division.
/// whatever the unstated-words flag says: fast `fmod` ("Undefined"). Fast `float` `tanh` at
/// `tanh(44)`, whose formula's divisor is past the `2^126` where Table 8.2 bounds the fast
/// division, is unstated too, but the product's fast `tanh` is the device's `Tanh` (its lowering
/// of `air.fast_tanh.f32` records no `DeviceArithmetic`): the device's own answer, within the
/// promise, so the sign-off stands even where the row records the note for another operation.
#[test]
fn an_unstated_word_the_product_approximates_keeps_its_reading_open() {
/// A one-word fast-math reading: the case's AIR tag, what the word computes of which bit
@@ -1885,33 +1886,36 @@ fn an_unstated_word_the_product_approximates_keeps_its_reading_open() {
let check = report.readings[0].bound.as_ref().unwrap();
assert_eq!(check.count("unstated"), 1, "{}", word.computes);
assert!(report.refused.is_empty());
// The product's remainder or division, recorded as a near-equivalent: open, and the
// sign-off refused.
let report = report_of(
word,
&[
PrecisionNote::DeviceArithmetic,
PrecisionNote::DeviceTranscendentals,
],
);
let check = report.readings[0].bound.as_ref().unwrap();
assert_eq!(check.count("near_equivalent"), 1, "{}", word.computes);
assert_eq!(report.refused.len(), 1);
assert!(
report.refused[0].words[0].contains("near_equivalent")
&& report.refused[0].words[0].contains("DeviceArithmetic"),
"{:?}",
report.refused
);
assert!(!report.holds());
}
let report = report_of(&tanh, &[PrecisionNote::DeviceArithmetic]);
let recorded = [
PrecisionNote::DeviceArithmetic,
PrecisionNote::DeviceTranscendentals,
];
// The product's remainder, recorded as a near-equivalent: open, and the sign-off refused.
let report = report_of(&fmod, &recorded);
let check = report.readings[0].bound.as_ref().unwrap();
assert_eq!(check.count("near_equivalent"), 1);
assert_eq!(report.refused.len(), 1);
assert!(
report.refused[0].words[0].contains("its lowering of air.fast_tanh.f32 (Metal's tanh)"),
report.refused[0].words[0].contains("near_equivalent")
&& report.refused[0].words[0].contains("DeviceArithmetic"),
"{:?}",
report.refused
);
assert!(!report.holds());
let report = report_of(&fmod, &[PrecisionNote::DeviceArithmetic]);
assert!(
report.refused[0].words[0].contains("its lowering of air.fast_fmod.f32 (Metal's fmod)"),
"{:?}",
report.refused
);
// The device's `Tanh`: no near-equivalent of the product's, so the word stays unstated and
// the sign-off stands, whatever arithmetic notes the row records.
let report = report_of(&tanh, &recorded);
let check = report.readings[0].bound.as_ref().unwrap();
assert_eq!(check.count("unstated"), 1);
assert_eq!(check.count("near_equivalent"), 0);
assert!(report.refused.is_empty(), "{:?}", report.refused);
}
/// A word within Apple's bound that shows a recorded near-equivalent's difference keeps its reading
+1 -1
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 = 1918;
pub const SEMANTICS_VERSION: u32 = 1919;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -7,14 +7,7 @@
use crate::device::DeviceProfile;
use crate::error::DriverDeviation;
use crate::lower::arith::legal::Form;
use crate::lower::arith::math::FloatFn;
use crate::lower::arith::narrow::u32_form;
use crate::lower::arith::ops::{splat, ty};
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::Value;
use crate::spirv::ir::{BinOp, ConvOp};
/// Whether profile `p`'s device reads the denormals of the operations [`Covered::Deviation`]
/// names as Metal does: an `f32` denormal operand as the zero of its sign, a denormal result
@@ -75,25 +68,3 @@ pub fn coverage(op: FloatFn) -> Option<Covered> {
_ => return None,
})
}
/// An upper estimate of the SPIR-V words of one [`flush`] on form `f`: six instructions of at most
/// six words, and the three masks' share (a vector's constants carry their lanes).
pub fn flush_words(f: Form) -> u32 {
36 + 4 * u32::from(f.lanes)
}
/// `x` (`float` lanes of form `f`) with each denormal lane replaced by the zero of its sign,
/// decided on the exponent field, so the same on every device and in every float mode.
pub fn flush(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value> {
let u = u32_form(f);
let (ut, ft) = (ty(fb, u)?, ty(fb, f)?);
let bits = fb.convert(ConvOp::Bitcast, x, ut)?;
let exponent = splat(fb, u, 0x7F80_0000)?;
let sign = splat(fb, u, 0x8000_0000)?;
let zero = splat(fb, u, 0)?;
let e = fb.binary(BinOp::BitwiseAnd, bits, exponent)?;
let denormal = fb.binary(BinOp::IEqual, e, zero)?;
let signed_zero = fb.binary(BinOp::BitwiseAnd, bits, sign)?;
let r = fb.select(denormal, signed_zero, bits)?;
fb.convert(ConvOp::Bitcast, r, ft)
}
+51 -43
View File
@@ -6,11 +6,16 @@
//! `2^-11` absolute, about what Metal's fast-math table allows, while Metal's precise functions are
//! bounded at 4 to 6 ulp (MSL Table 8.1). Every call, on `float` and on a `half` held as `float`,
//! takes the device's instruction where one is the function (`exp`, `log`, `pow`, `sinh`, `cosh`
//! and `tanh` among them), and a composition of the device's instructions only where none is
//! (`exp10`, `log10`, `sinpi`, `cospi`, `tanpi`, and the fast functions' formulas of MSL Table
//! 8.2), and records the device's precision where its functions are not Metal's own
//! and `tanh` among them, and the fast `sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh` and `atanh`,
//! whatever formula MSL Table 8.2 gives them), and a composition of the device's instructions only
//! where none is (`exp10`, `log10`, `sinpi`, `cospi`, `tanpi`, and the fast `exp`, `log`, `powr`
//! and `atan2`, which MSL Table 8.2 defines as compositions of `exp2`, `log2`, `atan` and a
//! division), and records the device's precision where its functions are not Metal's own
//! (`PrecisionNote::NativeTranscendentals`). No routine computes Metal's answer where the device
//! has an instruction. Where the device is Metal's own
//! has an instruction, and no select reads a special operand as Metal does where the device's
//! instruction answers it: the selects around `pow`, `powr` and `atan2` give only the C99 and MSL
//! values `GLSL.std.450` leaves undefined, by the device's comparisons. Where the device is
//! Metal's own
//! (`FloatFunctions::Metal`: MoltenVK on an Apple GPU), its instruction is Metal's function in the
//! math mode Metal compiles the module with ([`module_mode`]), so a call in that mode is Metal's
//! own answer there ([`Fun::device_answers`]), which the notes read.
@@ -73,11 +78,21 @@ pub enum Fun {
Cos,
/// Metal's precise `tan` (within 6 ulp).
Tan,
/// Metal's fast `sin` below its flush point, which is its precise `sin` inside `[-π, π]`
/// (Apple's `2^-13` bound, MSL Table 8.2).
/// Metal's fast `sin`, which is its precise `sin` inside `[-π, π]` (Apple's `2^-13` bound, MSL
/// Table 8.2) and `+0` past its flush point and for an infinity or NaN.
FastSin,
/// Metal's fast `cos` below its flush point; as [`Fun::FastSin`].
/// Metal's fast `cos`; as [`Fun::FastSin`].
FastCos,
/// Metal's fast `tan`, MSL Table 8.2's `sin(x) · (1 / cos(x))` of its fast `sin` and `cos`.
FastTan,
/// Metal's fast `sinh`, MSL Table 8.2's `(exp(x) - exp(-x)) · 0.5`.
FastSinh,
/// Metal's fast `cosh`, MSL Table 8.2's `(exp(x) + exp(-x)) · 0.5`.
FastCosh,
/// Metal's fast `tanh`, MSL Table 8.2's `(t - 1) / (t + 1)` of `t = exp(2x)`.
FastTanh,
/// Metal's fast `atanh`, MSL Table 8.2's `0.5 · log((1 + x) / (1 - x))`.
FastAtanh,
/// Metal's `sinpi`, for a precise call (`air.sinpi`) or a fast one (`air.fast_sinpi`): Metal's
/// fast function is its precise one, and only a device whose functions are Metal's tells them
/// apart ([`Fun::device_answers`]).
@@ -164,9 +179,11 @@ impl Fun {
/// `module`: the instruction is Metal's function in that mode, and `atan2` is always the
/// precise one (SPIRV-Cross emits `precise::atan2` whatever the flags). The precise-only
/// functions (`sin`, `cos`, `tan`, `sqrt`, `rsqrt`, and `fmod`, whose fast calls are their own
/// functions) are Metal's only in a precise module. Metal's fast `sin` and `cos` are the
/// device's in either: its fast functions in a fast-math module, and in a precise one its
/// precise functions, which are the fast ones below the flush point. Metal's `sinpi`, `cospi`,
/// functions) are Metal's only in a precise module. Metal's fast `sin`, `cos`, `tan`, `sinh`,
/// `cosh` and `atanh` are the device's `Sin`, `Cos`, `Tan`, `Sinh`, `Cosh` and `Atanh` in a
/// fast-math module only (in a precise one those are Metal's precise functions, which differ:
/// `fast::sin` is `+0` past its flush point), and its fast `tanh` in none (SPIRV-Cross emits
/// `precise::tanh`, below). Metal's `sinpi`, `cospi`,
/// and `tanpi` are none of the instructions SPIRV-Cross emits (it emits no `sinpi`), so the
/// device's `Sin` and `Cos` of `float(π) r` answer a precise call otherwise than Metal (849,
/// 922 and 637 of case 087758cb's 1,024 lanes matched); a fast call is that composition, in
@@ -184,7 +201,13 @@ impl Fun {
/// function, never Metal's `half` form.
pub fn device_answers(self, module: Mode) -> bool {
match self {
Fun::FastSin | Fun::FastCos => true,
Fun::FastSin
| Fun::FastCos
| Fun::FastTan
| Fun::FastSinh
| Fun::FastCosh
| Fun::FastAtanh => module == Mode::Fast,
Fun::FastTanh => false,
Fun::SinPi(m) | Fun::CosPi(m) | Fun::TanPi(m) => m == Mode::Fast,
Fun::Atan(m) | Fun::Asin(m) | Fun::Acos(m) => m == module,
Fun::Sin
@@ -303,8 +326,7 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] {
FloatFn::Tan => &[Fun::Tan],
FloatFn::FastSin => &[Fun::FastSin],
FloatFn::FastCos => &[Fun::FastCos],
// Apple's formula `sin(x) · (1 / cos(x))` of Metal's fast functions.
FloatFn::FastTan => &[Fun::FastSin, Fun::FastCos],
FloatFn::FastTan => &[Fun::FastTan],
FloatFn::SinPi => &[Fun::SinPi(Mode::Precise)],
FloatFn::CosPi => &[Fun::CosPi(Mode::Precise)],
FloatFn::TanPi => &[Fun::TanPi(Mode::Precise)],
@@ -314,8 +336,8 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] {
FloatFn::Sqrt => &[Fun::Sqrt],
FloatFn::Rsqrt => &[Fun::Rsqrt],
FloatFn::Fmod => &[Fun::Fmod],
// The precise functions, and the fast ones' formulas of Metal's `exp2` and `log2` (MSL
// Table 8.2).
// The precise functions, the fast ones the device's instructions, and the fast ones'
// compositions of Metal's `exp2` and `log2` (MSL Table 8.2).
FloatFn::Exp2 => &[Fun::Exp2],
FloatFn::Exp => &[Fun::Exp],
FloatFn::Exp10 => &[Fun::Exp10],
@@ -329,12 +351,12 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] {
FloatFn::Asinh => &[Fun::Asinh],
FloatFn::Acosh => &[Fun::Acosh],
FloatFn::Atanh => &[Fun::Atanh],
FloatFn::FastExp
| FloatFn::FastExp10
| FloatFn::FastSinh
| FloatFn::FastCosh
| FloatFn::FastTanh => &[Fun::Exp2],
FloatFn::FastLog | FloatFn::FastLog10 | FloatFn::FastAtanh => &[Fun::Log2],
FloatFn::FastSinh => &[Fun::FastSinh],
FloatFn::FastCosh => &[Fun::FastCosh],
FloatFn::FastTanh => &[Fun::FastTanh],
FloatFn::FastAtanh => &[Fun::FastAtanh],
FloatFn::FastExp | FloatFn::FastExp10 => &[Fun::Exp2],
FloatFn::FastLog | FloatFn::FastLog10 => &[Fun::Log2],
FloatFn::FastAsinh => &[Fun::FastAsinh],
FloatFn::FastAcosh => &[Fun::FastAcosh],
FloatFn::FastPow | FloatFn::FastPowr => &[Fun::Exp2, Fun::Log2],
@@ -360,40 +382,26 @@ pub fn use_words(lanes: u8, arity: usize) -> u32 {
.saturating_add(8)
}
/// What an entry's calls take, as emission reads them: the mode Metal compiles the entry's
/// functions in where the device's are Metal's, and the routine of precise `fmod` where the module
/// defines one.
/// What an entry's calls take, as emission reads them: the routine of precise `fmod` where the
/// module defines one. Every other function is the device's instruction, whichever mode Metal
/// compiles the entry in.
#[derive(Clone, Copy, Debug)]
pub struct Lib {
metal: Option<Mode>,
fmod: Option<FuncId>,
}
impl Lib {
/// The library of an entry whose `float` functions are Metal's in mode `metal` (`None`: the
/// device's), whose module defines precise `fmod`'s routine as `fmod` where it takes one.
pub fn new(metal: Option<Mode>, fmod: Option<FuncId>) -> Lib {
Lib { metal, fmod }
/// The library of an entry whose module defines precise `fmod`'s routine as `fmod` where it
/// takes one.
pub fn new(fmod: Option<FuncId>) -> Lib {
Lib { fmod }
}
/// A library that leaves every function to its instruction (a unit test's view of the
/// sequences around one).
#[cfg(test)]
pub fn instructions() -> Lib {
Lib::new(None, None)
}
/// Whether the device's instructions are Metal's own functions in mode `mode`: MoltenVK in a
/// module Metal compiles in that mode ([`module_mode`]).
pub fn metal_in(&self, mode: Mode) -> bool {
self.metal == Some(mode)
}
/// Whether the device's instructions are Metal's own functions in its fast mode: MoltenVK in a
/// module Metal compiles with fast math ([`module_mode`]), whose `Sin` and `Cos` are Metal's
/// `fast::sin` and `fast::cos` themselves, past their flush point too.
pub fn metal_fast(&self) -> bool {
self.metal_in(Mode::Fast)
Lib::new(None)
}
/// Metal's precise `fmod` of `x` and `y` (`float` lanes of form `f`) by its routine, one call
File diff suppressed because it is too large. Load diff
+10 -14
View File
@@ -1766,25 +1766,22 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result<Fun, Error> {
/// are their own functions; the fast-math accuracy table is single precision, so a narrow `fast_`
/// call keeps the precise function:
///
/// - `air.fast_tanh` is the MSL fast-math formula ([`FloatFn::FastTanh`]), divided by the
/// device's division;
/// - `air.fast_tanh`, `air.fast_sinh`, `air.fast_cosh`, `air.fast_atanh`, `air.fast_sin`,
/// `air.fast_cos` and `air.fast_tan` are the device's instructions, which a device whose
/// functions are Metal's answers as Metal's fast functions only in a fast-math module (and its
/// `Tanh` as Metal's precise `tanh` in every module): their own variants for their notes
/// ([`FloatFn::FastTanh`], [`FloatFn::FastSinh`], [`FloatFn::FastCosh`],
/// [`FloatFn::FastAtanh`], [`FloatFn::FastSin`], [`FloatFn::FastCos`], [`FloatFn::FastTan`]);
/// - `air.fast_asinh` with every flag is MSL Table 8.2's formula, the canonical NaN at `-inf`
/// ([`FloatFn::FastAsinh`]);
/// - `air.fast_sinh`, `air.fast_cosh`, `air.fast_acosh`, and `air.fast_atanh` are MSL Table
/// 8.2's formulas of Metal's fast `exp`, `log`, `sqrt`, and division ([`FloatFn::FastSinh`],
/// [`FloatFn::FastCosh`], [`FloatFn::FastAcosh`], [`FloatFn::FastAtanh`]), the last divided by
/// the device's division, where the device's instruction is not Metal's fast function;
/// - `air.fast_acosh` is MSL Table 8.2's formula of Metal's fast `log` and `sqrt`
/// ([`FloatFn::FastAcosh`]), the device's `Acosh`;
/// - `air.fast_fract` is not bounded below one, and with every flag is the canonical NaN at an
/// infinity ([`FloatFn::FastFract`]);
/// - `air.fast_fmedian3` answers `b` for two NaN first operands ([`FloatFn::FastMedian3`]);
/// - `air.fast_pow` answers the canonical NaN for a NaN base to the exponent one
/// ([`FloatFn::FastPow`]);
/// - `air.fast_pow`'s magnitude is `exp2(y · log2|x|)` ([`FloatFn::FastPow`]);
/// - `air.fast_atan2` is `atan(y / x)` turned by `±π`, NaN at `0 / 0` and `inf / inf`
/// ([`FloatFn::FastAtan2`]);
/// - `air.fast_sin` and `air.fast_cos` answer `+0` past `float(π/2) · 2^22` and for an infinity
/// or NaN ([`FloatFn::FastSin`], [`FloatFn::FastCos`]);
/// - `air.fast_tan` is Metal's fast `tan` ([`FloatFn::FastTan`]), Apple's formula divided by the
/// device's division where the device's `Tan` is not it;
/// - `air.fast_asin`, `air.fast_acos`, and `air.fast_atan` are Metal's fast functions, which a
/// device that is Metal's own answers only in a fast-math module and which answer `fast::asin`
/// of a zero and of a denormal as `+0` and `fast::atan` of one as its signed zero
@@ -2792,8 +2789,7 @@ pub fn emit(
/// What the entry being emitted's float function calls take ([`libm::Lib`]).
pub(crate) fn lib(cx: &EmitCx<'_>) -> libm::Lib {
let arith = &cx.plan.families.arith;
libm::Lib::new(arith.metal_functions, cx.decl.families.arith.fmod)
libm::Lib::new(cx.decl.families.arith.fmod)
}
/// The operands strategy `s` reads (a prefix of the instruction's; all when `None`).
+74 -119
View File
@@ -2057,14 +2057,15 @@ fn exact_float_functions_answer_their_instructions() {
}
/// The functions the device has an instruction for are that instruction, on `float` and on a
/// `half` held in `float`, in every math mode of every library: `exp`, `log`, `pow` and `powr`'s
/// magnitude, `sinh`, `cosh`, `tanh` (`Exp`, `Log`, `Pow`, `Sinh`, `Cosh`, `Tanh`, with no `Exp2`
/// or `Log2` composition of Metal's), `fabs`, `sign`, `fract` and `fast::fract` (`FAbs`, `FSign`,
/// `Fract`, with no bit operation), `median3` (`NMin` and `NMax` alone), `mix` (`FMix`) and
/// `fast::sqrt` (`Sqrt`). `round` is C99's from the device's `Trunc`.
/// `half` held in `float`: `exp`, `log`, `pow` and `powr`'s magnitude, `sinh`, `cosh`, `tanh`
/// (`Exp`, `Log`, `Pow`, `Sinh`, `Cosh`, `Tanh`, with no `Exp2` or `Log2` composition of Metal's),
/// the fast `sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh` and `atanh` (the instruction alone, with no
/// flush past Metal's last evaluated quadrant and no MSL Table 8.2 formula), `fabs`, `sign`,
/// `fract` and `fast::fract` (`FAbs`, `FSign`, `Fract`, with no bit operation), `median3` (`NMin`
/// and `NMax` alone), `mix` (`FMix`) and `fast::sqrt` (`Sqrt`). `round` is C99's from the device's
/// `Trunc`.
#[test]
fn functions_with_an_instruction_are_that_instruction() {
use super::libm::Mode;
use crate::spv::GlslStd450Op as G;
const OP_EXT_INST: u32 = 12;
const OP_BITCAST: u32 = 124;
@@ -2086,7 +2087,14 @@ fn functions_with_an_instruction_are_that_instruction() {
}
(ext, bitcasts)
};
let cases: [(FloatFn, &[G]); 15] = [
let cases: [(FloatFn, &[G]); 22] = [
(FloatFn::FastSin, &[G::Sin]),
(FloatFn::FastCos, &[G::Cos]),
(FloatFn::FastTan, &[G::Tan]),
(FloatFn::FastSinh, &[G::Sinh]),
(FloatFn::FastCosh, &[G::Cosh]),
(FloatFn::FastTanh, &[G::Tanh]),
(FloatFn::FastAtanh, &[G::Atanh]),
(FloatFn::Exp, &[G::Exp]),
(FloatFn::Log, &[G::Log]),
(FloatFn::Sinh, &[G::Sinh]),
@@ -2103,16 +2111,25 @@ fn functions_with_an_instruction_are_that_instruction() {
(FloatFn::FastSqrt, &[G::Sqrt]),
(FloatFn::Round, &[G::Trunc]),
];
for lib in [
Lib::instructions(),
Lib::new(Some(Mode::Fast), None),
Lib::new(Some(Mode::Precise), None),
] {
{
let lib = Lib::instructions();
for lane in [float(32), float(16)] {
for lanes in [1u8, 3] {
let f = vec(lane, lanes);
for (op, want) in cases {
if op == FloatFn::FastSqrt && lane.float_fmt() == Some(FloatFmt::Half) {
// `refine_float` gives a narrow call no fast function.
let fast = matches!(
op,
FloatFn::FastSqrt
| FloatFn::FastSin
| FloatFn::FastCos
| FloatFn::FastTan
| FloatFn::FastSinh
| FloatFn::FastCosh
| FloatFn::FastTanh
| FloatFn::FastAtanh
);
if fast && lane.float_fmt() == Some(FloatFmt::Half) {
continue;
}
let what = format!("{op:?} on {f:?} ({lib:?})");
@@ -2130,6 +2147,13 @@ fn functions_with_an_instruction_are_that_instruction() {
| FloatFn::Sinh
| FloatFn::Cosh
| FloatFn::Tanh
| FloatFn::FastSin
| FloatFn::FastCos
| FloatFn::FastTan
| FloatFn::FastSinh
| FloatFn::FastCosh
| FloatFn::FastTanh
| FloatFn::FastAtanh
| FloatFn::Abs
| FloatFn::Sign
| FloatFn::FastFract
@@ -2622,16 +2646,15 @@ fn nan_answers_follow_the_measured_flag_states() {
}
}
/// `powr(x, y)` is Metal's canonical NaN where Metal's `exp2(y * log2(x))` is a NaN for operands
/// that are not: `x < 0` (`-0` is not), `y = ±0` with `x = ±0` or `+inf`,
/// and `y = ±inf` with `x = 1`, an `f32` denormal read as a zero by the zero tests and, in
/// `fast::powr` only, by the sign test; every other lane keeps the device's result, which the
/// kernel's third input stands for, except that `fast::powr` answers IEEE's value where `y ·
/// log2(x)` is infinite (`math::infinite_product`'s rule, on the same classification of the
/// operands). `half`'s NaN lanes are the same rule's (`nan_half`, `nan_half_fast`, every lane,
/// class K).
/// `powr(x, y)` is a NaN where MSL's `exp2(y * log2(x))` is a NaN for operands that are not: `x <
/// 0` (`-0` is not), `y = ±0` with `x = ±0` or `+inf`, and `y = ±inf` with `x = 1`, each by the
/// device's comparisons (the interpreter reads an `f32` denormal as a value, where Metal reads a
/// zero); every other lane keeps the device's result, which the kernel's third input stands for,
/// except that `fast::powr` answers IEEE's value where `y · log2(x)` is infinite
/// (`math::infinite_product`'s rule, on the same classification of the operands). `half`'s NaN
/// lanes are the same rule's (`nan_half`, `nan_half_fast`, every lane, class K).
#[test]
fn powr_answers_metals_nan_at_its_special_operands() {
fn powr_answers_c99_nan_at_its_special_operands() {
// The answer where `y · log2(x)` is infinite (`log2(x)` read as `-inf` at a zero), for
// operands that are not NaNs nor in the NaN rule's lanes; `None` where it is finite.
fn infinite(x: f64, y: f64, y_negative: bool) -> Option<f64> {
@@ -2709,7 +2732,7 @@ fn powr_answers_metals_nan_at_its_special_operands() {
-f32::NAN,
f32::MIN_POSITIVE,
-f32::MIN_POSITIVE,
// Denormals, which Metal reads as zeros.
// Denormals, which Metal reads as zeros and the device's comparisons as it reads them.
f32::from_bits(1),
-f32::from_bits(0x007F_FFFF),
]
@@ -2738,17 +2761,8 @@ fn powr_answers_metals_nan_at_its_special_operands() {
},
&cases,
&|c| {
// A denormal is a zero to Metal's zero tests, and to `fast::powr`'s sign test;
// the precise sign is the bit's, a NaN's included.
let read = |v: f32| if v.is_subnormal() { 0.0 } else { v };
let raw = f32v(arg(c, 0));
let (x, y) = (read(raw), read(f32v(arg(c, 1))));
let below = if fast {
x < 0.0
} else {
raw.is_sign_negative() && raw != 0.0
};
let nan = below
let (x, y) = (f32v(arg(c, 0)), f32v(arg(c, 1)));
let nan = x < 0.0
|| (y == 0.0 && (x == 0.0 || x == f32::INFINITY))
|| (y.is_infinite() && x == 1.0);
if nan {
@@ -2763,7 +2777,7 @@ fn powr_answers_metals_nan_at_its_special_operands() {
_ => device,
}])
},
&|g, w| g == w,
&|g, w| g == w || (is_nan(f, g) && is_nan(f, w)),
);
}
}
@@ -2795,20 +2809,18 @@ fn pow_special_cases_match_c99() {
);
}
}
for precise in [true, false] {
check(
&format!("pow special cases f32 (precise {precise})"),
&[f, f, f],
f,
&|fb, a| math::pow_special(fb, f, a[0], a[1], a[2], precise),
&cases,
&|c| {
let r = f32v(arg(c, 0)).powf(f32v(arg(c, 1)));
Some(vec![u64::from(r.to_bits())])
},
false,
);
}
check(
"pow special cases f32",
&[f, f, f],
f,
&|fb, a| math::pow_special(fb, f, a[0], a[1], a[2]),
&cases,
&|c| {
let r = f32v(arg(c, 0)).powf(f32v(arg(c, 1)));
Some(vec![u64::from(r.to_bits())])
},
false,
);
}
/// The inputs of the authored case `pi-scaled-sine-and-cosine-are-exact-at-every-half-integer`
@@ -3009,7 +3021,6 @@ fn pi_scaled_functions_reduce_exactly_to_metal_answers() {
/// identity kernel is charged in full, its constants and the `GLSL.std.450` import included.
#[test]
fn pi_scaled_functions_stay_within_their_word_estimate() {
use super::libm::Mode;
let module_words = |f: Form, body: Body<'_>| {
let m = kernel(&[f], f, body).expect("kernel");
crate::spirv::serialize::serialize(m)
@@ -3035,77 +3046,18 @@ fn pi_scaled_functions_stay_within_their_word_estimate() {
precise.to_vec()
};
for g in calls {
for metal in [None, Some(Mode::Fast), Some(Mode::Precise)] {
let used = module_words(f, &|fb, x| {
math::float_fn(fb, g, f, Contraction::Allowed, x, &Lib::new(metal, None))
});
let (emitted, bound) = (used - bare, g.words(f) as usize);
assert!(
emitted <= bound,
"{g:?} {f:?} with Metal's functions {metal:?}: {emitted} words over {bound}"
);
}
let used = module_words(f, &|fb, x| {
math::float_fn(fb, g, f, Contraction::Allowed, x, &Lib::instructions())
});
let (emitted, bound) = (used - bare, g.words(f) as usize);
assert!(
emitted <= bound,
"{g:?} {f:?}: {emitted} words over {bound}"
);
}
}
}
/// `air.fast_tanh` on `float` is the MSL fast-math formula `(t - 1) / (t + 1)` of `t = exp(2x)`,
/// its quotient the device's division. The interpreter does not model `Exp2`, so the kernel takes
/// `t` as an input (`exp2(x * 2 log2 e)` in `f32` on the host) and runs the quotient. Where the
/// quotient does not depend on the last place of `t` it gives the Metal observation of the
/// authored case `fast-tanh-through-all-three-of-its-regimes` (M3 Max, ORACLE_ABI v32): `x = 0` is
/// 0, `x = 43` is 1, `x = 44.4` (where `t` overflows) is NaN, and `x = -100` (where `t` is 0) is
/// -1. At `x = 44`, where `t + 1` is above `2^126`, Metal's fast reciprocal flushes and answers 0;
/// the device's quotient answers 1 (`PrecisionNote::NativeDivision`).
#[test]
fn fast_tanh_is_the_fast_math_formula() {
let f = float(32);
let two_log2e = (2.0 * std::f64::consts::LOG2_E) as f32;
let t_of = |x: f32| (x * two_log2e).exp2();
// (x, Metal's fast::tanh(x)).
let metal: [(f32, u32); 4] = [
(0.0, 0x0000_0000),
(43.0, 0x3F80_0000),
(44.4, 0x7FC0_0000),
(-100.0, 0xBF80_0000),
];
let quotient = |t: f32| (t - 1.0) / (t + 1.0);
let mut xs: Vec<f32> = metal.iter().map(|m| m.0).collect();
xs.extend([44.0, 0.5, -3.75, 5.0, 1e-3, -1e-3, 20.0, -44.4, 43.7]);
let cases: Vec<Case> = xs
.iter()
.map(|x| vec![vec![u64::from(t_of(*x).to_bits())]])
.collect();
check(
"fast tanh quotient f32",
&[f],
f,
&|fb, t| {
let divide = |fb: &mut FunctionBuilder<'_>, x: Value, y: Value| {
fb.binary_with(BinOp::FDiv, x, y, Contraction::Forbidden)
};
math::tanh_of_exp(fb, f, &divide, t[0])
},
&cases,
&|c| {
let t = f32v(arg(c, 0));
Some(vec![u64::from(quotient(t).to_bits())])
},
false,
);
for (x, want) in metal {
let got = quotient(t_of(x));
assert!(
got.to_bits() == want || (got.is_nan() && f32::from_bits(want).is_nan()),
"fast::tanh({x}) = {got} ({:#010x}), Metal {want:#010x}",
got.to_bits()
);
}
// x = 44: t + 1 > 2^126, where Metal's reciprocal flushes and the device's quotient is 1.
assert!(t_of(44.0) + 1.0 > 2f32.powi(126));
assert_eq!(quotient(t_of(44.0)), 1.0);
}
/// The function a call computes follows its `air` symbol's `fast_` variant, never a name: on
/// `float`, `fast_tanh` is the fast-math formula, `fast_fract` is unbounded, `fast_fmedian3`
/// records the device's pick of two NaNs, `fast_pow` the canonical NaN for a NaN base to the
@@ -3184,8 +3136,11 @@ fn fast_variants_refine_float_functions() {
assert_eq!(refine(op, false, fmf, bfloat()), op);
}
}
assert!(FloatFn::FastTanh.divides() && !FloatFn::Tanh.divides());
assert!(FloatFn::FastTan.divides());
// The fast `tanh`, `tan` and `atanh` are the device's instructions, which divide by nothing.
for op in [FloatFn::FastTanh, FloatFn::FastTan, FloatFn::FastAtanh] {
assert!(!op.divides(), "{op:?}");
}
assert!(!FloatFn::Tanh.divides());
for reciprocal_flushed in [false, true] {
assert!(FloatFn::FastAtan2 { reciprocal_flushed }.divides());
}
@@ -3,8 +3,10 @@
//! of both signs, denormals, the smallest normal, ordinary values, the largest finite values,
//! infinities, and NaNs. The interpreter does not model `GLSL.std.450 Atan2` or `Atan`, so `atan2`
//! takes its generic value as an input and `fast::atan2` a stand-in `atan`; every lane a special
//! value decides must equal Metal's answer bit for bit, and every other lane must be the generic
//! value (or the stand-in's), so the special values read neither.
//! value decides must equal Metal's answer bit for bit (a NaN any NaN, its bits the device's), and
//! every other lane must be the generic value (or the stand-in's), so the special values read
//! neither. An `f32` denormal operand is a value, as the interpreter reads it, where Metal reads a
//! zero (`PrecisionNote::DeviceDenormals` off a device measured to read it as Metal does).
use super::*;
@@ -356,9 +358,14 @@ const ATAN2_HALF: [[u16; 16]; 16] = [
const MARKER_F32: u32 = 0x3E00_0000;
const MARKER_HALF: u16 = 0x3000;
/// Whether an `f32` operand is a zero to Metal (its exponent field is zero), infinite, or NaN.
/// Whether an `f32` operand is a zero, infinite, or NaN (its denormals are values).
fn f32_special(b: u32) -> bool {
b & 0x7F80_0000 == 0 || b & 0x7F80_0000 == 0x7F80_0000
b & 0x7FFF_FFFF == 0 || b & 0x7F80_0000 == 0x7F80_0000
}
/// Whether an `f32` operand is a denormal, which Metal reads as a zero.
fn f32_denormal(b: u32) -> bool {
b & 0x7F80_0000 == 0 && b & 0x007F_FFFF != 0
}
/// Whether a `half` operand is a zero, infinite, or NaN (its denormals are values).
@@ -368,19 +375,22 @@ fn half_special(b: u16) -> bool {
/// `atan2` (`math::atan2_special` around its generic input, then the format's rounding): a lane
/// with a zero, infinite, or NaN operand is Metal's answer whatever the generic value; any other
/// lane is the generic value, `+0` when it is an `f32` denormal. The generic input is the host's
/// correctly rounded `atan2` there and [`MARKER_F32`] elsewhere. Metal's own generic answers are
/// within one ulp of it (five `float` lanes differ by one, the device's precision); its `+0` for
/// a denormal `float` result is asserted on the lanes that have one.
/// lane is the generic value, a denormal one included (the device's `Atan2`, where Metal answers
/// `+0`). The generic input is the host's correctly rounded `atan2` there and [`MARKER_F32`]
/// elsewhere. Metal's own generic answers are within one ulp of it (five `float` lanes differ by
/// one, the device's precision). The `float` lanes with a denormal operand, which Metal reads as a
/// zero, are the device's reading and left out.
#[test]
fn atan2_answers_as_metal_at_every_special_operand() {
fn atan2_answers_as_c99_at_every_special_operand() {
for bits in [32u8, 16] {
let f = float(bits);
let mut cases: Vec<Case> = Vec::new();
let mut want = Vec::new();
let mut flushed = 0;
for j in 0..16 {
for k in 0..16 {
if bits == 32 && (f32_denormal(F32_OPERANDS[j]) || f32_denormal(F32_OPERANDS[k])) {
continue;
}
let (y, x, metal, special) = if bits == 32 {
let (y, x) = (F32_OPERANDS[j], F32_OPERANDS[k]);
let special = f32_special(y) || f32_special(x);
@@ -415,20 +425,12 @@ fn atan2_answers_as_metal_at_every_special_operand() {
let r = f16_to_f64(y as u16).atan2(f16_to_f64(x as u16));
u64::from(f64_to_f16(r))
};
let tiny = bits == 32 && g & 0x7F80_0000 == 0;
if tiny {
flushed += 1;
assert_eq!(metal, 0, "Metal's tiny atan2({y:#x}, {x:#x})");
}
(g, if tiny { 0 } else { g })
(g, g)
};
cases.push(vec![vec![y], vec![x], vec![generic]]);
want.push(((y, x), expect));
}
}
if bits == 32 {
assert_eq!(flushed, 6, "the float lanes with a denormal answer");
}
check_accept(
&format!("atan2 f{bits} against Metal"),
&[f, f, f],
@@ -442,7 +444,7 @@ fn atan2_answers_as_metal_at_every_special_operand() {
let key = (arg(c, 0), arg(c, 1));
want.iter().find(|(k, _)| *k == key).map(|(_, w)| vec![*w])
},
&|g, w| g == w,
&|g, w| g == w || (is_nan(f, g) && is_nan(f, w)),
);
}
}
@@ -456,9 +458,9 @@ fn metal_read(b: u32) -> f32 {
}
}
/// `fast::atan2(y, x)` with the stand-in `atan(q) = q + 1/8`, where Metal's special values do not
/// decide it (`None` where they do): the quotient (divided over the whole range, or `y` times the
/// flushed reciprocal), the stand-in, and the turn.
/// `fast::atan2(y, x)` with the stand-in `atan(q) = q + 1/8`, where the formula's special values do
/// not decide it (`None` where they do): the quotient (divided over the whole range, or `y` times
/// the flushed reciprocal), the stand-in, and the turn. A denormal operand or quotient is a value.
fn fast_generic(y: u32, x: u32, reciprocal_flushed: bool) -> Option<u32> {
if f32_special(y) || f32_special(x) {
return None;
@@ -468,7 +470,7 @@ fn fast_generic(y: u32, x: u32, reciprocal_flushed: bool) -> Option<u32> {
return None;
}
let q = (f64::from(yv) / f64::from(xv)) as f32;
if f32_special(q.to_bits()) {
if !q.is_finite() {
return None;
}
let a = q + 0.125;
@@ -482,11 +484,12 @@ fn fast_generic(y: u32, x: u32, reciprocal_flushed: bool) -> Option<u32> {
}
/// `fast::atan2` (`math::fast_atan2`) with a stand-in `atan(q) = q + 1/8` the interpreter runs:
/// every lane of the grid that Metal's special values decide is Metal's answer for the call's
/// flags (the quotient's sign, the flushed operands and quotient, `0 / 0` and `inf / inf`, the
/// turn's comparisons, and the flushed reciprocal beyond `2^126` of a call without every flag),
/// and every other lane is the stand-in of the correctly rounded quotient, turned; operands
/// beyond the grid check the scaled division near `2^126` and `FLT_MAX`.
/// every lane of the grid that the formula's special values decide is Metal's answer for the
/// call's flags (the quotient's sign, `0 / 0` and `inf / inf`, the turn's comparisons, and the
/// flushed reciprocal beyond `2^126` of a call without every flag), a NaN any NaN, and every other
/// lane is the stand-in of the correctly rounded quotient, turned, a denormal quotient's included;
/// operands beyond the grid check the scaled division near `2^126` and `FLT_MAX`. The lanes with
/// a denormal operand, which Metal reads as a zero, are the device's reading and left out.
#[test]
fn fast_atan2_answers_as_metal_at_every_special_operand() {
let f = float(32);
@@ -511,6 +514,9 @@ fn fast_atan2_answers_as_metal_at_every_special_operand() {
for j in 0..16 {
for k in 0..16 {
let (y, x) = (F32_OPERANDS[j], F32_OPERANDS[k]);
if f32_denormal(y) || f32_denormal(x) {
continue;
}
let w = match fast_generic(y, x, reciprocal_flushed) {
Some(g) => g,
None => {
@@ -521,15 +527,16 @@ fn fast_atan2_answers_as_metal_at_every_special_operand() {
want.push(((u64::from(y), u64::from(x)), u64::from(w)));
}
}
// The lanes with a finite normal quotient of finite normal operands, less the lanes a
// flushed reciprocal decides.
// The 196 lanes of operands that are not denormals, less those with a finite quotient of
// finite nonzero operands (and, with a flushed reciprocal, less beyond `2^126`).
assert_eq!(
decided,
if reciprocal_flushed {
256 - 30
196 - 31
} else {
256 - 34
}
196 - 45
},
"reciprocal flushed {reciprocal_flushed}"
);
if !reciprocal_flushed {
for (y, x) in extra {
@@ -574,13 +581,13 @@ fn fast_atan2_answers_as_metal_at_every_special_operand() {
let key = (arg(c, 0), arg(c, 1));
want.iter().find(|(k, _)| *k == key).map(|(_, w)| vec![*w])
},
&|g, w| g == w,
&|g, w| g == w || (is_nan(f, g) && is_nan(f, w)),
);
}
}
/// [`FloatFn::words`] bounds what `atan2`, `fast::atan2`, `fast::sin`, and `fast::cos` emit on
/// every form they take (`fast::sin` and `fast::cos` on `float`), and is not more than twice it.
/// [`FloatFn::words`] bounds what `atan2` and `fast::atan2` emit on every form they take, and is
/// not more than twice it.
/// The module's growth over an identity kernel is charged in full, its constants and the
/// `GLSL.std.450` import included.
#[test]
@@ -600,17 +607,11 @@ fn special_value_functions_stay_within_their_word_estimate() {
FloatFn::FastAtan2 {
reciprocal_flushed: true,
},
FloatFn::FastSin,
FloatFn::FastCos,
];
let mut out = Vec::new();
for f in [float(32), vec(float(32), 4), float(16), vec(float(16), 4)] {
let bare = module_words(f, &|_, x| Ok(x[0]));
for g in fns {
// `fast::sin` and `fast::cos` are refined from `float` calls only.
if matches!(g, FloatFn::FastSin | FloatFn::FastCos) && f.is_narrow() {
continue;
}
let used = module_words(f, &|fb, x| {
math::float_fn(fb, g, f, Contraction::Allowed, x, &Lib::instructions())
});
@@ -5,7 +5,7 @@
use super::*;
use crate::lower::arith::fma::{self, Fma, Route};
use crate::lower::arith::libm::{Lib, Mode};
use crate::lower::arith::libm::Lib;
/// `(x, y, fast::fmod(x, y))`: the lanes of case 08bc6611 whose fast reciprocal of `y` is the
/// correctly rounded `1 / y` (917 of 1,024; these are its special lanes and 44 others drawn at
@@ -226,18 +226,12 @@ fn fast_functions_are_metals_compositions() {
assert_eq!(ext, [0, 0, 0, 1, 1, 0, 0]);
let (ext, _, _) = read(FloatFn::Pow);
assert_eq!(ext, [1, 0, 0, 0, 0, 0, 0]);
for lib in [
Lib::instructions(),
Lib::new(Some(Mode::Fast), None),
Lib::new(Some(Mode::Precise), None),
let (ext, _, _) = read(FloatFn::FastSqrt);
assert_eq!(ext, [0, 0, 0, 0, 0, 1, 0]);
for (op, want) in [
(FloatFn::Exp, [0, 1, 0, 0, 0, 0, 0]),
(FloatFn::Log, [0, 0, 1, 0, 0, 0, 0]),
] {
let (ext, _, _) = read_in(FloatFn::FastSqrt, lib);
assert_eq!(ext, [0, 0, 0, 0, 0, 1, 0]);
for (op, want) in [
(FloatFn::Exp, [0, 1, 0, 0, 0, 0, 0]),
(FloatFn::Log, [0, 0, 1, 0, 0, 0, 0]),
] {
assert_eq!(read_in(op, lib).0, want, "{op:?}");
}
assert_eq!(read(op).0, want, "{op:?}");
}
}
@@ -64,7 +64,7 @@ fn fmod_module(f: Form) -> TypedModule {
f,
Contraction::Forbidden,
x,
&Lib::new(None, funcs.first().copied()),
&Lib::new(funcs.first().copied()),
)
},
true,
@@ -258,6 +258,8 @@ mod half_fmod_takes_the_routine {
/// over a composition that answered `1`, as the RTX 5080 did without `SignedZeroInfNanPreserve`):
/// Metal's word at case f6524207's special pairs and case 32931370's `half`
/// ones, and the composition's own value where the product is finite, a NaN, or an operand is one.
/// An `f32` denormal base is a zero only where the device's comparison reads it so (the
/// interpreter does not, where Metal does): there the product is finite, the composition's.
#[test]
fn an_infinite_product_answers_ieee_whatever_the_composition_gave() {
let (f, h) = (float(32), float(16));
@@ -267,9 +269,9 @@ fn an_infinite_product_answers_ieee_whatever_the_composition_gave() {
let words: [(u64, u64, Option<u64>); 15] = [
(0x0000_0000, 0x3F80_0000, Some(0)),
(0x8000_0000, 0x4000_0000, Some(0)),
(0x0000_0001, 0xBF80_0000, Some(0x7F80_0000)),
(0x8000_0001, 0x3F00_0000, Some(0)),
(0x0040_0000, 0x4100_0000, Some(0)),
(0x0000_0001, 0xBF80_0000, None),
(0x8000_0001, 0x3F00_0000, None),
(0x0040_0000, 0x4100_0000, None),
(0x7F80_0000, 0xC000_0000, Some(0)),
(0x7F80_0000, 0x4100_0000, Some(0x7F80_0000)),
(0x3F00_0000, 0x7F80_0000, Some(0)),
@@ -2,11 +2,10 @@
//! Metal's recorded answers (Apple M3 Max, ORACLE_ABI v34), bit for bit: every distinct lane of the
//! A1 case `fract-saturate-and-median3-at-nan-infinity-and-signed-zero` (aed3faaa) but those whose
//! answer is the device's instruction's (`median3`'s ties), and the lanes of
//! `pow-at-every-c99-special-operand`
//! (116e052a) with a NaN operand, the exponent one, a denormal exponent, or a negative denormal
//! base to a non-integral exponent. The operands are signed zeros, `f32` and `half` denormals, the
//! smallest normals, values beside the integers, the largest finite values, infinities, and NaNs
//! (quiet and signalling, both signs, with payloads).
//! `pow-at-every-c99-special-operand` (116e052a) that one of C99's special cases decides (a NaN
//! answer as any NaN, its bits the device's). The operands are signed zeros, `f32` and `half`
//! denormals, the smallest normals, values beside the integers, the largest finite values,
//! infinities, and NaNs (quiet and signalling, both signs, with payloads).
use super::*;
@@ -559,14 +558,31 @@ fn median3_answers_as_metal_but_at_its_recorded_ties() {
metal_answers(FloatFn::Median3, float(16), &half);
}
/// `pow`'s special cases (`math::pow_special`) at the lanes of [`POW`], each decided by a special
/// case: the magnitude operand (`GLSL.std.450 Pow(|x|, y)`, which the interpreter does not
/// model) is a constant no answer equals, so a lane that read it would fail.
/// `pow`'s C99 special cases (`math::pow_special`) at the lanes of [`POW`] one of them decides,
/// against Metal's answers: the magnitude operand (`GLSL.std.450 Pow(|x|, y)`, which the
/// interpreter does not model) is a constant no answer equals, so a lane that read it would fail.
/// Left out are the lanes the device answers: `pow(x, 1)` of a nonzero number `x` other than `±1`
/// (the device's `Pow`, which Metal answers `x` exactly), and an `f32` denormal operand, which
/// Metal reads as a zero and the device as it reads it (`PrecisionNote::DeviceDenormals`). A NaN
/// answer is any NaN: its bits are the device's (`PrecisionNote::NativeNanEncoding`).
#[test]
fn pow_special_operands_answer_as_metal() {
fn pow_special_operands_answer_as_c99() {
for (bits, precise) in [(32u8, true), (32, false), (16, true)] {
let f = float(bits);
let pi = if bits == 32 { 0x4049_0FDB } else { 0x4248 };
let (one, nan_from, magnitude) = if bits == 32 {
(0x3F80_0000, 0x7F80_0000, 0x7FFF_FFFF)
} else {
(0x3C00, 0x7C00, 0x7FFF)
};
// Decided by the device: `pow(x, 1)` of a number that is not a zero or `±1`, and an `f32`
// denormal operand.
let device = |x: u64, y: u64| {
let ax = x & magnitude;
let to_one = y == one && ax != 0 && ax != one && ax <= nan_from;
let denormal = |v: u64| bits == 32 && v & 0x7F80_0000 == 0 && v & 0x007F_FFFF != 0;
to_one || denormal(x) || denormal(y)
};
let rows: Vec<Row> = POW
.iter()
.map(|r| match (bits, precise) {
@@ -574,6 +590,7 @@ fn pow_special_operands_answer_as_metal() {
(32, false) => (vec![u64::from(r.0), u64::from(r.1), pi], u64::from(r.3)),
_ => (vec![u64::from(r.4), u64::from(r.5), pi], u64::from(r.6)),
})
.filter(|(ops, _)| !device(ops[0], ops[1]))
.collect();
let cases: Vec<Case> = rows
.iter()
@@ -584,7 +601,7 @@ fn pow_special_operands_answer_as_metal() {
&[f, f, f],
f,
&|fb, a| {
let r = math::pow_special(fb, f, a[0], a[1], a[2], precise)?;
let r = math::pow_special(fb, f, a[0], a[1], a[2])?;
crate::lower::arith::narrow::round(fb, f, r)
},
&cases,
@@ -594,96 +611,37 @@ fn pow_special_operands_answer_as_metal() {
.find(|(o, _)| *o == ops)
.map(|(_, want)| vec![*want])
},
&|g, w| g == w,
&|g, w| g == w || (is_nan(f, g) && is_nan(f, w)),
);
}
}
/// `pow(x, 1)` of an `f32` denormal `x` (`math::pow_special`): Metal's precise `pow` answers `x`
/// itself and `fast::pow` the zero of its sign, at each denormal base of the denormal probes
/// (cases 638c7906 and c9b6bacb, the `pow` word at `y = 1`; the M3 Max and the M4 answer the
/// same). The magnitude operand is a constant no answer equals, so a lane that read it fails.
/// `pow(x, 1)` (`math::pow_special`) is the device's `Pow(|x|, 1)`, negated for a negative `x`
/// (one is odd), where Metal answers `x` itself: the magnitude operand is a constant no `x`
/// equals, so a lane that kept `x` fails. A zero and `±1` are C99's cases, a NaN its NaN.
#[test]
fn pow_of_a_denormal_base_to_one_answers_as_metal() {
fn pow_of_a_number_to_one_is_the_device_pow() {
let f = float(32);
let magnitude = 0x4049_0FDBu64;
let one = 0x3F80_0000u64;
let bases = [
0x0000_0001u32,
0x8000_0001,
0x0000_0003,
0x0040_0000,
0x807F_FFFF,
0x007F_FFFF,
0x3F00_0000u32,
0xBF00_0000,
0x4040_0000,
0xC040_0000,
0x7F7F_FFFF,
];
for precise in [true, false] {
let cases: Vec<Case> = bases
.iter()
.map(|x| vec![vec![u64::from(*x)], vec![one], vec![magnitude]])
.collect();
check_accept(
&format!("pow f32 of a denormal base to 1 (precise {precise}) against Metal"),
&[f, f, f],
f,
&|fb, a| math::pow_special(fb, f, a[0], a[1], a[2], precise),
&cases,
&|c| {
let x = c[0][0] as u32;
let want = if precise { x } else { x & 0x8000_0000 };
Some(vec![u64::from(want)])
},
&|g, w| g == w,
);
}
}
/// Metal's `fast::sin` and `fast::cos` past the last evaluated quadrant (`math::fast_trig_flush`),
/// against Metal's answers: `+0` from the float after `float(π/2) · 2^22` on, for the infinities,
/// and for NaNs, whatever the sign; the device's `Sin`/`Cos` (here an input no answer equals) up to
/// and at the limit. The arguments are the bisected boundary, the two A1 cases' (`9424775`, `1e7`,
/// a NaN, 179b6aa6's `6588397.5`), and probe case 08bc6611's lanes.
#[test]
fn fast_sine_and_cosine_flush_past_the_last_quadrant_as_metal() {
let f = float(32);
let device = 0x3F12_3456u64;
let limit = math::FAST_TRIG_LIMIT;
assert_eq!(limit, std::f32::consts::FRAC_PI_2 * (1u32 << 22) as f32);
assert_eq!(limit.to_bits(), 0x4AC9_0FDB);
// (x, flushed): Metal answers +0 when flushed and its evaluated function otherwise.
let rows: [(u32, bool); 16] = [
(limit.to_bits(), false),
((-limit).to_bits(), false),
(0x4AC9_0FDC, true),
(0xCAC9_0FDC, true),
(9_424_775f32.to_bits(), true),
(1e7f32.to_bits(), true),
((-1e7f32).to_bits(), true),
(f32::MAX.to_bits(), true),
(0x7F80_0000, true),
(0xFF80_0000, true),
(0x7FC0_0000, true),
(0xFFC0_0000, true),
(0x7F80_0001, true),
(0x3F80_0000, false),
(0x8000_0000, false),
(1e6f32.to_bits(), false),
];
let cases: Vec<Case> = rows
let cases: Vec<Case> = bases
.iter()
.map(|(x, _)| vec![vec![u64::from(*x)], vec![device]])
.map(|x| vec![vec![u64::from(*x)], vec![one], vec![magnitude]])
.collect();
check_accept(
"fast sin/cos flush f32 against Metal",
&[f, f],
"pow f32 of a number to 1",
&[f, f, f],
f,
&|fb, a| math::fast_trig_flush(fb, f, a[0], a[1]),
&|fb, a| math::pow_special(fb, f, a[0], a[1], a[2]),
&cases,
&|c| {
let x = arg(c, 0) as u32;
rows.iter()
.find(|(r, _)| *r == x)
.map(|(_, flushed)| vec![if *flushed { 0 } else { device }])
},
&|c| Some(vec![magnitude | (c[0][0] & 0x8000_0000)]),
&|g, w| g == w,
);
}
+15 -7
View File
@@ -620,8 +620,8 @@ pub enum PrecisionNote {
/// by `Sqrt`, `dot` of vectors of other than two to four lanes, whose chunks' products the
/// device sums where Metal flushes each one below `2^-126`, beside their own notes, and a
/// conversion to or from `double`, whose reading Metal's is not measured. The operations that
/// read a denormal on its bits answer Metal on every device: `ldexp`, `copysign` and `atan2`;
/// and so do the functions the device answers as Metal's own. Where the minimum and maximum functions
/// read a denormal on its bits answer Metal on every device: `ldexp` and `copysign`; and so do
/// the functions the device answers as Metal's own. Where the minimum and maximum functions
/// (`llvm.minnum` and `llvm.maxnum` among them, with any flags) and `saturate` are the device's
/// `NMin`, `NMax` and `NClamp`, their pick of a denormal is
/// [`PrecisionNote::NativeMinMax`]'s. Validation derives no tolerance and no explanation from
@@ -1575,11 +1575,19 @@ pub enum PrecisionNote {
/// device's own `GLSL.std.450` instruction (`Exp`, `Log`, `Pow`, `Sinh`, `Cosh` and `Tanh`
/// among them; a composition of the device's `Exp2` and `Log2` only for `exp10` and `log10`,
/// which no instruction is) where Metal's function is not the device's own; `fast::sqrt` the
/// device's `Sqrt`; `fabs`, `sign` and `fract` the device's `FAbs`, `FSign` and `Fract`, their
/// special operands the instruction's (Metal's `sign` of a NaN, a zero and an `f32` denormal is
/// `+0`, its `fract` of an infinity `+0`, where `FSign` keeps a zero's sign and leaves a NaN's
/// answer undefined and `Fract` of an infinity is a NaN); and `round` C99's, from the
/// device's `Trunc`, on every device (`round(-0.3)` is `-0`, where Metal answers `+0`).
/// device's `Sqrt`; the fast `sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh` and `atanh` the
/// device's instructions, where MSL Table 8.2 defines Metal's by formulas (`fast::sin` and
/// `fast::cos` are `+0` past `float(π/2) · 2^22` and at an infinity or NaN, `fast::tanh` a NaN
/// once `exp(2x)` overflows); `fabs`, `sign` and `fract` the device's `FAbs`, `FSign` and
/// `Fract`, their special operands the instruction's (Metal's `sign` of a NaN, a zero and an
/// `f32` denormal is `+0`, its `fract` of an infinity `+0`, where `FSign` keeps a zero's sign
/// and leaves a NaN's answer undefined and `Fract` of an infinity is a NaN); a `half`
/// function's zeros' and NaNs' signs its `float` instruction's (Metal's `half` `sin`, `tan`
/// and `asin` of `-0` are `+0`, its `half` `asin` NaN takes the operand's sign); `pow`,
/// `powr` and `atan2` C99's special values around the device's instruction, decided by the
/// device's comparisons, so `pow(x, 1)` is the device's `Pow` (Metal answers `x`) and an
/// `f32` denormal operand reads as the device reads it; and `round` C99's, from the device's
/// `Trunc`, on every device (`round(-0.3)` is `-0`, where Metal answers `+0`).
/// **Recorded bound:** Vulkan's precision table for the instruction, where Metal promises 4 to
/// 6 ulp precise and its fast-math table fast (MSL Tables 8.1, 8.2): `Exp2` and `Exp` 3 + 2·|x|
/// ulp; `Log2` and `Log` 3 ulp outside `[0.5, 2]` and `2^-21` absolute inside; `Pow` inherited
+8 -15
View File
@@ -1840,15 +1840,13 @@ fn a_division_without_arcp_is_the_devices_quotient() {
}
}
/// `air.fast_sincos` on `float` answers as `air.fast_sin` and `air.fast_cos` do (a probe cases
/// 9496749c and 3921d3e2, every lane): `+0` for both past `float(π/2) · 2^22` (`0x4AC90FDB`), which
/// the module compares against, while `air.sincos` keeps the device's functions there. On
/// MoltenVK a module Metal compiles with fast math (no `SignedZeroInfNanPreserve`) takes the
/// device's `Sin` and `Cos`, which are Metal's `fast::sin` and `fast::cos` and answer the flush
/// themselves, so it compares against no limit; elsewhere the flush stays. (The interpreter does
/// not model `Sin`; the shape is the module's.)
/// `air.fast_sincos` on `float`, like `air.sincos`, is the device's `Sin` and `Cos` on every
/// profile, in a fast-math module and out of one: the module compares against no limit (Metal's
/// `fast::sincos` answers `+0` for both past `float(π/2) · 2^22`, `0x4AC90FDB`, where the device
/// answers its functions, `PrecisionNote::NativeTranscendentals` off Metal's own). (The
/// interpreter does not model `Sin`; the shape is the module's.)
#[test]
fn fast_sincos_flushes_past_the_last_quadrant() {
fn fast_sincos_is_the_devices_sine_and_cosine() {
let body = |call: &str| {
format!(
" %c = alloca float, align 4\n{} %s = call float @{call}(float %a, ptr %c)\n %cv = load float, ptr %c, align 4\n %r = fadd float %s, %cv\n",
@@ -1877,7 +1875,7 @@ fn fast_sincos_flushes_past_the_last_quadrant() {
note: None,
};
let ks = [
kernel("fast_sincos_flushes", "air.fast_sincos.f32"),
kernel("fast_sincos_out_of_a_fast_module", "air.fast_sincos.f32"),
kernel("sincos_keeps_the_device", "air.sincos.f32"),
fast,
];
@@ -1900,12 +1898,7 @@ fn fast_sincos_flushes_past_the_last_quadrant() {
&& w.len() == 4
&& w[3] == 0x4AC9_0FDB
});
let flushes = match kk.name {
"fast_sincos_flushes" => true,
"fast_sincos_in_a_fast_module" => stem != "moltenvk-m3",
_ => false,
};
assert_eq!(limits > 0, flushes, "{what}: the flush limit");
assert_eq!(limits, 0, "{what}: a flush limit");
}
}
}
@@ -3,14 +3,11 @@
//! device's instructions where none is. On every committed M1 profile each kernel compiles, links,
//! and passes L3, and its module holds the instructions of the form it takes:
//!
//! - `air.fast_tanh` on `float` is the MSL fast-math formula `(t - 1) / (t + 1)`,
//! `t = exp2(x * 2 log2 e)` of the device's `Exp2` (no `Tanh`), every step of it
//! `NoContraction`, its quotient the device's division (`OpFDiv`); the precise `air.tanh` is the
//! device's `Tanh`. A `half` `fast_tanh` is Metal's `half` `tanh` (Metal's `half` functions are
//! the same in both math modes, and MSL's fast-math formulas are its `float` ones), so it is the
//! device's `Tanh` too (no `Exp2`, no division), noted `NativeTranscendentals` wherever the
//! device's functions are not Metal's own, and on MoltenVK MSL's `float` `tanh` rounded to
//! `half` (`DeviceTranscendentals`);
//! - `air.fast_tanh` is the device's `Tanh` (no `Exp2`, no division) on `float` and `half`, as
//! the precise `air.tanh` is, where MSL Table 8.2 defines Metal's `float` one as the formula
//! `(t - 1) / (t + 1)` of `t = exp(2x)`: noted `NativeTranscendentals` wherever the device's
//! functions are not Metal's own, and on MoltenVK, whose `Tanh` is MSL's precise `tanh` (and a
//! `half` one that rounded to `half`), `DeviceTranscendentals`;
//! - `air.sign` is the device's `FSign` with and without fast math (it keeps the sign of a zero
//! where Metal answers `+0`), noted `NativeTranscendentals` wherever the device's functions are
//! not Metal's own (on MoltenVK it is MSL's own `sign`), and both answer `-1` for `-3` on the
@@ -63,33 +60,25 @@ struct Kernel {
/// `GLSL.std.450` instructions the module must and must not contain.
has: &'static [u32],
lacks: &'static [u32],
/// Whether the module divides (`OpFDiv`): `fast::tanh`'s quotient.
divides: bool,
/// Whether the module takes the device's instruction for a function Metal defines otherwise,
/// recording `NativeTranscendentals` wherever the device's functions are not Metal's own.
native: bool,
/// Whether the instruction on MoltenVK is not Metal's own function for the call
/// (`DeviceTranscendentals` there): MSL's precise `tanh` for `fast::tanh`, its `float` one
/// rounded for a `half` one.
off_metal: bool,
/// The stored word on the interpreter, when it models the kernel.
want: Option<u32>,
}
const KERNELS: [Kernel; 8] = [
const KERNELS: [Kernel; 7] = [
Kernel {
name: "fast_tanh_float",
body: " %a = fadd fast float 0x4046000000000000, -0.0\n %r = call fast float @air.fast_tanh.f32(float %a)\n",
has: &[EXP2],
lacks: &[TANH],
divides: true,
native: false,
want: None,
},
// RC3 cases e72f550f and 2d5f3949's GELU tail at x = -8: 0.5 * x * (1 + tanh(...)).
Kernel {
name: FAST_TANH_IN_GELU,
body: " %a = fadd fast float 0xC038A66660000000, -0.0\n %x = fadd fast float 0xC020000000000000, -0.0\n %t = call fast float @air.fast_tanh.f32(float %a)\n %s = fadd fast float %t, 1.000000e+00\n %h = fmul fast float %x, 5.000000e-01\n %r = fmul fast float %h, %s\n",
has: &[EXP2],
lacks: &[TANH],
divides: true,
native: false,
has: &[TANH],
lacks: &[EXP2],
native: true,
off_metal: true,
want: None,
},
Kernel {
@@ -97,8 +86,8 @@ const KERNELS: [Kernel; 8] = [
body: " %a = fadd fast float 0x4046000000000000, -0.0\n %r = call fast float @air.tanh.f32(float %a)\n",
has: &[TANH],
lacks: &[EXP2],
divides: false,
native: false,
off_metal: false,
want: None,
},
Kernel {
@@ -106,8 +95,8 @@ const KERNELS: [Kernel; 8] = [
body: " %a = fadd fast float 0x4000000000000000, -0.0\n %h = fptrunc float %a to half\n %t = call fast half @air.fast_tanh.f16(half %h)\n %r = fpext half %t to float\n",
has: &[TANH],
lacks: &[EXP2],
divides: false,
native: true,
off_metal: true,
want: None,
},
Kernel {
@@ -115,8 +104,8 @@ const KERNELS: [Kernel; 8] = [
body: " %a = fadd fast float 0xC008000000000000, -0.0\n %r = call fast float @air.sign.f32(float %a)\n",
has: &[FSIGN],
lacks: &[],
divides: false,
native: true,
off_metal: false,
want: Some(0xBF80_0000),
},
Kernel {
@@ -124,8 +113,8 @@ const KERNELS: [Kernel; 8] = [
body: " %a = fadd float 0xC008000000000000, -0.0\n %r = call float @air.sign.f32(float %a)\n",
has: &[FSIGN],
lacks: &[],
divides: false,
native: true,
off_metal: false,
want: Some(0xBF80_0000),
},
Kernel {
@@ -133,8 +122,8 @@ const KERNELS: [Kernel; 8] = [
body: " %a = fadd fast float 0x3FF0000000000000, -0.0\n %r = call fast float @air.sinpi.f32(float %a)\n",
has: &[SIN, ROUND_EVEN],
lacks: &[],
divides: false,
native: false,
off_metal: false,
want: None,
},
Kernel {
@@ -142,18 +131,12 @@ const KERNELS: [Kernel; 8] = [
body: " %a = fadd fast float 0x3FF0000000000000, -0.0\n %r = call fast float @air.fast_sinpi.f32(float %a)\n",
has: &[SIN, ROUND_EVEN],
lacks: &[],
divides: false,
native: false,
off_metal: false,
want: None,
},
];
/// The kernel whose `fast::tanh` feeds the caller's `1 + tanh` ([`fast_tanh_is_one_operation`]).
const FAST_TANH_IN_GELU: &str = "fast_tanh_in_gelu";
/// The `GLSL.std.450 Fma` instruction number.
const FMA: u32 = 50;
fn module() -> String {
let mut s = String::from(
"target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n",
@@ -269,22 +252,10 @@ fn metal_math_variants_select_their_forms() {
);
}
let metal = p.fields().float_functions == FloatFunctions::Metal;
assert_eq!(div, k.divides, "{what}: OpFDiv");
// The fast-math entry's `fast_tanh` notes its steps' precision (the device's
// `Exp2` and division), except where every step is Metal's own function on the device
// (`FloatFunctions::Metal`), which notes nothing in such an entry.
if k.divides {
assert_eq!(
a.precision.contains(&PrecisionNote::DeviceArithmetic)
&& a.precision.contains(&PrecisionNote::NativeTranscendentals),
!metal,
"{what}: {:?}",
a.precision
);
}
assert!(!div, "{what}: OpFDiv");
// The device's instruction: noted `NativeTranscendentals` wherever the device's
// functions are not Metal's own. On MoltenVK `sign` is MSL's own; a `half` `tanh` is
// MSL's `float` one rounded to `half`, within Apple's bound.
// functions are not Metal's own. On MoltenVK `sign` is MSL's own; `fast::tanh` is
// MSL's precise `tanh`, and a `half` `tanh` MSL's `float` one rounded to `half`.
if k.native {
assert_eq!(
a.precision.contains(&PrecisionNote::NativeTranscendentals),
@@ -292,10 +263,9 @@ fn metal_math_variants_select_their_forms() {
"{what}: {:?}",
a.precision
);
let half = k.name.ends_with("_half");
assert_eq!(
a.precision.contains(&PrecisionNote::DeviceTranscendentals),
metal && half,
metal && k.off_metal,
"{what}: {:?}",
a.precision
);
@@ -308,96 +278,6 @@ fn metal_math_variants_select_their_forms() {
}
}
/// Each float arithmetic result of `words` (`OpFAdd`, `OpFSub`, `OpFMul`, `OpFDiv`, and
/// `GLSL.std.450 Fma`), as its opcode and whether it is decorated `NoContraction`.
fn float_arithmetic(words: &[u32]) -> Vec<(u32, bool)> {
let (mut results, mut exact) = (Vec::new(), Vec::new());
let arith = [
crate::spv::Op::FAdd,
crate::spv::Op::FSub,
crate::spv::Op::FMul,
crate::spv::Op::FDiv,
]
.map(|op| op as u32);
let mut i = 5;
while i < words.len() {
let (len, op) = ((words[i] >> 16) as usize, words[i] & 0xFFFF);
assert!(len > 0 && i + len <= words.len(), "malformed module");
if op == crate::spv::Op::Decorate as u32
&& words[i + 2] == crate::spv::Decoration::NoContraction as u32
{
exact.push(words[i + 1]);
}
if arith.contains(&op) || (op == crate::spv::Op::ExtInst as u32 && words[i + 4] == FMA) {
results.push((op, words[i + 2]));
}
i += len;
}
results
.into_iter()
.map(|(op, id)| (op, exact.contains(&id)))
.collect()
}
/// `air.fast_tanh` is one operation to Metal, so the device may not fuse or regroup any of its
/// steps with the caller's arithmetic. Every step is `NoContraction` whatever the call's flags:
/// `x · 2 log2 e` (in the profile's form: `GLSL.std.450 Fma(a, b, -0.0)` where its `float`
/// functions are Metal's, an `OpFMul` elsewhere), `t - 1`, `t + 1`, and the quotient. The caller's
/// `fast` arithmetic stays undecorated. Without the decorations, Mesa's `lower_flrp` rule turned
/// GELU's `1 + tanh` into `t` on RADV and x86 lavapipe (RC3 cases e72f550f and 2d5f3949,
/// `gelu(-8)`).
#[test]
fn fast_tanh_is_one_operation() {
let Some(bitcode) = assemble() else {
return;
};
for stem in PROFILES.into_iter().chain(["amd-rdna3-radv", "lavapipe"]) {
let p = profile(stem, exact_maths()).expect("profile");
let what = format!("{FAST_TANH_IN_GELU} on {stem}");
let a =
compile(&bitcode, FAST_TANH_IN_GELU, &p).unwrap_or_else(|e| panic!("{what}: {e:?}"));
let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let ops = float_arithmetic(&words);
let count = |op: crate::spv::Op, exact: bool| {
ops.iter()
.filter(|(o, e)| *o == op as u32 && *e == exact)
.count()
};
let fma = |exact: bool| {
ops.iter()
.filter(|(o, e)| *o == crate::spv::Op::ExtInst as u32 && *e == exact)
.count()
};
// The tanh's product is in the profile's form.
let metal = usize::from(p.fields().float_functions == FloatFunctions::Metal);
assert_eq!(
(
count(crate::spv::Op::FMul, true),
count(crate::spv::Op::FSub, true),
count(crate::spv::Op::FAdd, true),
count(crate::spv::Op::FDiv, true),
fma(true)
),
(1 - metal, 1, 1, 1, metal),
"{what}: the tanh's steps, NoContraction: {ops:?}"
);
assert_eq!(
(
fma(false),
count(crate::spv::Op::FSub, false),
count(crate::spv::Op::FDiv, false),
count(crate::spv::Op::FMul, false),
),
(0, 0, 0, 2),
"{what}: only the caller's multiplies are left free: {ops:?}"
);
assert!(
count(crate::spv::Op::FAdd, false) >= 1,
"{what}: the caller's 1 + tanh stays free: {ops:?}"
);
}
}
/// End to end: the sRGB fixtures through select, emit, and link on every profile above: L3 passes,
/// and each module takes the MSL transfer functions by the device's `Pow` around the 8-bit
/// instruction (`a1_srgb_decode_all_bytes`: `UnpackUnorm4x8`, its `float` and `half` results;
+13 -6
View File
@@ -1318,10 +1318,11 @@ fn content_digests_name_what_a_pipeline_says_not_its_build() {
/// The precision contract is public: a fast `float` division records the device's arithmetic,
/// Metal's precise division records the device's division, its denormals and its NaN
/// (`NativeDivision`, `DeviceDenormals`, `NativeNanEncoding`), an integer operator has no notes, and
/// a fast `float` `tanh`, which the crate computes with a division of its own, records the device's
/// arithmetic, on a profile whose `float` functions are the device's (lavapipe's); on one whose
/// functions are Metal's own (MoltenVK's), both are Metal's own in a fast-math entry and record
/// nothing there, and the division records its note in an entry that keeps NaNs.
/// a fast `float` `tanh`, the device's `Tanh`, records the device's transcendental, on a profile
/// whose `float` functions are the device's (lavapipe's); on one whose functions are Metal's own
/// (MoltenVK's), a fast-math division is Metal's own and records nothing, the division records its
/// note in an entry that keeps NaNs, and a fast `tanh` records that its `Tanh` is Metal's precise
/// function, not the fast one (`DeviceTranscendentals`).
#[test]
fn the_precision_contract_names_each_float_operations_notes() {
use metal2vulkan_air::intrinsics::AirIntrinsic;
@@ -1372,10 +1373,16 @@ fn the_precision_contract_names_each_float_operations_notes() {
};
let notes = PrecisionNote::of_math_call(tanh, fast, lavapipe, EntryMath::Fast)
.expect("a float function");
assert!(notes.contains(&PrecisionNote::DeviceArithmetic));
assert!(
notes.contains(&PrecisionNote::NativeTranscendentals),
"{notes:?}"
);
let notes = PrecisionNote::of_math_call(tanh, fast, moltenvk, EntryMath::Fast)
.expect("a float function");
assert!(notes.is_empty(), "{notes:?}");
assert!(
notes.contains(&PrecisionNote::DeviceTranscendentals),
"{notes:?}"
);
}
/// A render pipeline with a signed-integer color attachment compiles its fragment function with the
+14 -7
View File
@@ -242,8 +242,9 @@ measured takes the route each deviation's docs name for it: the device's own ans
precision note, or, where the answer decides a capability, its emulation or a refusal.
Metal semantics the translation keeps on every device, beyond Vulkan's: Metal's 32-lane
simdgroups (including lockstep races on threadgroup memory within a barrier interval), and the
bit-exact `fneg` and `fabs` of a `float`, its NaNs and denormals included. A NaN's bits, the
simdgroups (including lockstep races on threadgroup memory within a barrier interval). `fneg` and
`fabs` are the device's `OpFNegate` and `FAbs`, so a NaN's payload and a denormal are the
device's (`native-nan-encoding`, `device-denormals`). A NaN's bits, the
operand `fmin`, `fmax`, `min3`, `max3`, `clamp` and `saturate` pick beside a NaN or between two
zeros, a `half` read from its bits, which is the device's widening on every device (a NaN's
bits, and a denormal on a device that may flush 16-bit ones), and a `half` rounded from a value
@@ -3170,11 +3171,17 @@ bound.
Native device maths: the module computes a `float` or `half` math-library function by the device's
own `GLSL.std.450` instruction (`exp`, `log`, `pow`, `sinh`, `cosh` and `tanh` among them; a
composition of the device's `Exp2` and `Log2` only for `exp10` and `log10`, which no instruction
is) where Metal's function is not the device's own; `fast::sqrt` the device's `Sqrt`; `fabs`,
`sign` and `fract` the device's `FAbs`, `FSign` and `Fract`, their special operands the
instruction's (Metal's `sign` of a NaN, a zero and an `f32` denormal is `+0`, its `fract` of an
infinity `+0`); and `round` C99's from the device's `Trunc` on every device (`round(-0.3)` is
`-0`, where Metal answers `+0`).
is) where Metal's function is not the device's own; `fast::sqrt` the device's `Sqrt`; the fast
`sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh` and `atanh` the device's instructions, not MSL's
fast-math formulas (`fast::sin` of `1e7` is the device's sine, where Metal answers `+0`;
`fast::tanh(45)` is `1`, where Metal answers NaN); `fabs`, `sign` and `fract` the device's
`FAbs`, `FSign` and `Fract`, their special operands the instruction's (Metal's `sign` of a NaN,
a zero and an `f32` denormal is `+0`, its `fract` of an infinity `+0`); a `half` function's
signed zeros and NaN signs its `float` instruction's (`half` `sin(-0)` is `-0`, where Metal
answers `+0`); `pow`, `powr` and `atan2` C99's special values by the device's comparisons
around its instruction (`pow(x, 1)` the device's `Pow`, where Metal answers `x`; an `f32`
denormal operand as the device reads it); and `round` C99's from the device's `Trunc` on every
device (`round(-0.3)` is `-0`, where Metal answers `+0`).
- `metal2vulkan-degrade-native-division` (precision). `PrecisionNote::NativeDivision`: Native device
maths: a precise `float` or `half` division, or Metal's fast division or reciprocal, is the
device's `OpFDiv` where the device's division is not Metal's own: within Vulkan's 2.5 ulp, where
+2 -2
View File
@@ -55,12 +55,12 @@ known. The rest of the differences are docs/API.md section 9's precision notes.
| What it is | Why there is no switch | Note, code |
|---|---|---|
| The maths library (`sin`, `exp`, `log`, `pow`, `sinh`, `cosh`, `tanh`, `atan2`...) on `float` and `half`, fast divisions and Metal's fast reciprocal, a `half` fused multiply-add, and a `float` one without `OpFmaKHR` are the device's instructions on every device whose `float` functions are not Metal's own (every device but MoltenVK, whose functions are Metal's in a fast-math entry; a `half` function is the `float` instruction rounded on every device); Metal's precise division (an `fdiv` without `arcp`, or on `half`) is the device's `OpFDiv` on every device. `fabs`, `sign` and `fract` are `FAbs`, `FSign` and `Fract`, their special operands (a NaN, an infinity, a signed zero, an `f32` denormal) the instruction's; `round` is C99's from `Trunc` on every device (`round(-0.3)` is `-0`, Metal's `+0`). | The device's arithmetic is the contract: no routine computes Metal's answer where the device has an instruction. | Vulkan's precision table (`Sin` 2^-11 absolute in [-π, π], `Exp` 3 + 2·\|x\| ulp, `Log` 3 ulp or 2^-21 absolute in [0.5, 2], `Pow` from `Exp2(y · Log2 x)`, `FAbs`, `FSign` and `Fract` correct or correctly rounded, `Atan` 4096 ulp) against Metal's 4-6 ulp; division 2.5 ulp; `fma` one `half` ulp (a `float` one may round twice). `NativeTranscendentals` (`native-transcendentals`), `NativeDivision` (`native-division`), `NativeFma` (`native-fma`) |
| The maths library (`sin`, `exp`, `log`, `pow`, `sinh`, `cosh`, `tanh`, `atan2`...) on `float` and `half`, fast divisions and Metal's fast reciprocal, a `half` fused multiply-add, and a `float` one without `OpFmaKHR` are the device's instructions on every device whose `float` functions are not Metal's own (every device but MoltenVK, whose functions are Metal's in a fast-math entry; a `half` function is the `float` instruction rounded on every device); Metal's precise division (an `fdiv` without `arcp`, or on `half`) is the device's `OpFDiv` on every device. `fabs`, `sign` and `fract` are `FAbs`, `FSign` and `Fract`, their special operands (a NaN, an infinity, a signed zero, an `f32` denormal) the instruction's; the fast `sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh` and `atanh` are `Sin`, `Cos`, `Tan`, `Sinh`, `Cosh`, `Tanh` and `Atanh`, not MSL Table 8.2's formulas (`fast::sin(1e7)` is the device's sine, Metal's `+0`; `fast::tanh(45)` is `1`, Metal's NaN); a `half` function's signed zeros and NaN signs are its `float` instruction's (`half` `sin(-0)` is `-0`, Metal's `+0`); `pow`, `powr` and `atan2` add only C99's special values that `GLSL.std.450` leaves undefined, by the device's comparisons (`pow(x, 1)` is the device's `Pow`, Metal's `x`; a NaN operand's NaN is the device's sum of the operands); `round` is C99's from `Trunc` on every device (`round(-0.3)` is `-0`, Metal's `+0`). | The device's arithmetic is the contract: no routine computes Metal's answer, and no select reads a special operand as Metal does, where the device has an instruction. | Vulkan's precision table (`Sin` 2^-11 absolute in [-π, π], `Exp` 3 + 2·\|x\| ulp, `Log` 3 ulp or 2^-21 absolute in [0.5, 2], `Pow` from `Exp2(y · Log2 x)`, `FAbs`, `FSign` and `Fract` correct or correctly rounded, `Atan` 4096 ulp) against Metal's 4-6 ulp; division 2.5 ulp; `fma` one `half` ulp (a `float` one may round twice). `NativeTranscendentals` (`native-transcendentals`), `NativeDivision` (`native-division`), `NativeFma` (`native-fma`) |
| `dot`, `mix` and `fast::sqrt` are the device's `OpDot`, `FMix` and `Sqrt` on every device, not Metal's fused chain, its two fused multiply-adds and `x · rsqrt(x)`: a `float` one on MoltenVK reaches Metal's own `dot`, `mix` and `fast::sqrt`, a `half` one is the instruction on its `float` container, rounded once; a `dot` of other than two to four lanes sums the `OpDot` of each chunk of up to four lanes. | The device's order is the contract. | `float` `dot` of n lanes within (3n − 1)·2^-24·Σ\|aᵢbᵢ\|, `mix` within 2^-21 of its two terms, `fast::sqrt` 4.5 ulp. `NativeDot` (`native-dot`), `NativeMix` (`native-mix`), `NativeTranscendentals` (`native-transcendentals`); a `dot` of other than two to four lanes within Vulkan's precision of its chunks' `OpDot` and sum, `DeviceArithmetic` (`device-arithmetic`) |
| Fast-math sums, differences and products group, and a multiply contracts into an addition, as the device's compiler groups and fuses them, on every device, MoltenVK included: each operation is emitted in the AIR's order, one carrying both `contract` and `reassoc` undecorated and any other `NoContraction`. Metal's compiler takes its own grouping (its rank order of a sum's leaves, its pairing of a product's lane-uniform factors) and its own fusion pairs. | The device's grouping is the contract: what the AIR's flags allow, the device's compiler chooses; nothing reproduces Metal's choice. | Unbounded relative to the result where a sum of mixed signs is grouped otherwise, or a multiply-add is fused on one side alone; each operation kept apart is exact as written. `FastMathRewrites` (`fast-math-rewrites`) |
| `air.pack` and `air.unpack` of a normalized format are the device's conversion: `GLSL.std.450`'s `Pack`/`Unpack` `Unorm4x8`, `Snorm4x8`, `Unorm2x16` and `Snorm2x16`, and for `rgb10a2` and `rgb565` their definition by the device's `NClamp`, multiply, `RoundEven` (a pack) and multiply by the reciprocal (an unpack); `unorm4x8_srgb`'s colour is the MSL transfer functions by the device's `Pow` around the 8-bit instruction, as is an 8-bit sRGB storage texture's write through its UNORM alias. A `float` one of the four named formats on MoltenVK reaches Metal's own. The same conversions serve an implicit imageblock access of a normalized attachment (a `half` load rounding the unpacked `float` once more), the interlocked storage form's 8-bit sRGB attachment and sRGB word, and a snapshot's normalized codes (`c` times the `f32` nearest `1/D`). | The device's conversion is the contract. | A packed code within one of Metal's, apart only where `clamp(c)·scale` lies within its rounding of a half-integer (`Round`'s tie is the device's); an unpacked value within 2.5 ulp of the correctly rounded quotient; a decoded sRGB colour within half a twelve-bit step (`1/8190`) of Metal's table step `k/4095`, beyond its `Pow`'s bound; a NaN channel's code the device's (Metal's: 0). `DevicePackConversion` (`device-pack-conversion`) |
| Off MoltenVK a `float` multiply, and a fused multiply-add by `OpFmaKHR`, round before Metal's flush: Metal flushes a result whose exact value lies below `2^-126` before rounding it, so a result whose exact value lies within half a unit below `2^-126` answers `2^-126` of its sign where Metal answers the zero of its sign. | Every device measured off MoltenVK (RADV, ANV, NVIDIA, lavapipe) rounds first; its multiply is the contract. | Announced once per device as it is made: `float-tininess-after-rounding` |
| `f32` denormals in a `float` operation on a device not measured to read them as Metal does (`DriverDeviation::MetalFloatDenormals`: lavapipe, and every unmeasured device), in `floor`, `ceil` and `fneg` on every device, in the maths functions (`fabs`, `sign` and `fract` among them) and the device's order of the rows above, and in a conversion to or from `double`. Metal reads them as zero and flushes a denormal result. | The device's reading is the contract: Vulkan lets each device keep or flush them, and Metal runs no `double`, so its reading of a conversion is not measured. | `DeviceDenormals` (`device-denormals`) |
| `f32` denormals in a `float` operation on a device not measured to read them as Metal does (`DriverDeviation::MetalFloatDenormals`: lavapipe, and every unmeasured device), in `floor`, `ceil` and `fneg` on every device, in the maths functions (`fabs`, `sign` and `fract` among them, and the zero and sign tests of `pow`, `powr` and `atan2`) and the device's order of the rows above, and in a conversion to or from `double`. Metal reads them as zero and flushes a denormal result. | The device's reading is the contract: Vulkan lets each device keep or flush them, and Metal runs no `double`, so its reading of a conversion is not measured. | `DeviceDenormals` (`device-denormals`) |
| Samples, gathers, depth comparisons and level queries are the device's own sampler's on every device whose sampler is not Metal's (every device but MoltenVK): its filter, footprint, level, anisotropy, sRGB decode and comparison, its level clamp (the descriptor's as given, which Metal holds on a `1/64` grid) and its reading of a subnormal coordinate (which Metal reads as the zero of its sign before addressing). A sample's or gather's residency on a device with `shaderResourceResidency` is the device's `OpImageSparse*` word and non-resident value (`SparseResidency`); Metal's footprint rule answers it only where the device has no residency and the slot's tile map does. A two-plane YCbCr texture's linear sample is the device's filter of its texels (the device's own Y′CbCr conversion's where it converts the format, next row; Metal's reads exactly elsewhere); where the device's memory is the host's, a sample that reads the planes in place is Metal's filter exactly. An 8-bit sRGB format the device cannot sample (`R8_SRGB` on lavapipe, `R8G8_SRGB` on lavapipe, ANV and NVIDIA) is held as its UNORM twin, the device lacking its decode: a read, a sample, a fetch, a gather and a bicubic tap decode what the twin's view reads (one texel's codes, or the device's filter of them) by the MSL transfer through the device's `Pow`. | The device's sampler is the contract. | Linear filter within one code (1/255) on the measured devices, sRGB within 1.83, a two-plane YCbCr texture's within 1.183; levels, anisotropy, cubes, 3D, gathers and comparisons unmeasured. A twin's texel: the transfer within the device's `Pow` (MoltenVK's within 1.83e-7 through a storage alias, `runtime_lane::srgb_storage`) where Metal's table rounds it to a twelve-bit step (up to 1/8190 apart); a filtered sample decodes the filtered codes, up to 0.286 off for a blend of codes 0 and 255 (`SrgbTexelDecode`). `DeviceSampling` (`device-sampling`) |
| A pixel-coordinate sampler's sample, gather, comparison and level query is the device's sampler's at the coordinate divided by the texture's level-0 size in the shader, on every device, MoltenVK included: the device reads its texels from that coordinate in its own arithmetic, where Metal reads the coordinate as given (its nearest texel `floor(x)`, its filter's footprint from `x`). A constexpr pixel sampler that filters nearest and clamps to the edge fetches its texel (`sampler.pixel_fetch`), as does an argument buffer's sample without a comparison through a state that does. | The device's sampler is the contract. Vulkan's unnormalized samplers take no gather, offset, comparison, array, 3D image or level of detail, so the shader scales the coordinate; nothing reproduces Metal's position at a texel edge. | The device answers as its normalized sampler at a coordinate within one `f32` ulp of the quotient on MoltenVK (10 of 800 cells of each mirror-clamp configuration move by it; a nearest sample at a texel edge then reads the neighbouring texel) and at the quotient itself on lavapipe (`runtime_lane::pixel_samplers`: 800 coordinates at and around each texel edge of a 5x3 texture, every filter and address mode); a linear downscale by 8 of textures 1000 to 1920 texels wide within 1/255 of Metal's on MoltenVK and 2/255 on lavapipe (`runtime_lane::pixel_downscales`); other devices unmeasured. `PixelSamplerScaling` (`pixel-sampler-scaling`), `ArgumentPixelSamplerScaling` (`argument-pixel-sampler-scaling`) |
| A two-plane YCbCr texture's texels are the device's own sampler Y′CbCr conversion of its planes where the device converts their format (`ycbcr_device.rs`): unpacked 8- or 10-bit codes of a 4:2:0, 4:2:2 or 4:4:4 layout over plane 0 that form one image (no chroma codes 0, no rows past the buffer; a 4:4:4 layout read as codes aside, whose identity conversion converts nothing), on a device that enables `samplerYcbcrConversion` (a 4:4:4 layout also needs Vulkan 1.3 or `VK_EXT_ycbcr_2plane_444_formats`), reports the multi-planar format's conversion and, for a 4:2:0 or 4:2:2 layout, Metal's reconstruction (midpoint chroma through a linear chroma filter), and has no defect in the format; the planes are copied into an image of it and sampled once per texel into the texture's image (`bind::ycbcr_sample_module`), through the refresh's indirect arguments. The conversion takes the surface's matrix and range (the identity model for the code-reading formats), and Metal's reconstruction of a subsampled layout; a device's cosited or nearest reconstruction would move what the codes mean to Metal (cosited, up to 1340/2048 of random planes on lavapipe), a capability it lacks, so such a layout converts through Metal's arithmetic. A render pass's load stays Metal's arithmetic, which our store inverts, so a loaded texel no draw changes keeps its codes, as `MTLLoadActionLoad` keeps the attachment's contents. lavapipe (Mesa 26.0.8) converts the 8-bit 4:4:4 layout (its 4:2:0 and 4:2:2 ones are cosited only, and it reads 10-bit codes as 16-bit words, `RuntimeDriverDefect::TenBitCodesReadAsWords`); MoltenVK 1.4.2 converts none (its 4:2:0 and 4:2:2 reconstruction is misplaced, `RuntimeDriverDefect::TwoPlaneChromaMisplaced`, and it reports no 4:4:4 two-plane format). RADV (Mesa 26.2.4) reads 10-bit codes as 16-bit words too (measured on a linear image of the 4:2:0 format on the Radeon 780M), so its 10-bit layouts convert through Metal's arithmetic. Elsewhere, and for packed codes, chroma codes 0 and plane 1, Metal's fixed-point conversion stays as capability (`WorkCounts::ycbcr_device_conversions`). | The device's conversion is the contract: Vulkan states the reconstruction's weights and the model's matrices, the precision of each step at least the format's, and the clamp of the result into `[0, 1]` the implementation's. | Each channel within 0.04/2048 of Vulkan's conversion past the `half` its image stores on lavapipe's 8-bit 4:4:4 layout; of Metal's read within 6/2048 where the result lies in `[0, 1]`, and unclamped outside it (random planes, every texel, `tests/ycbcr_device.rs`). `YCbCrFilterNotExact` (`ycbcr-filter-not-exact`) |